]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/toe.c
32f2ae4c48042690aeac79d3a40031c27585cc6a
[ncurses.git] / progs / toe.c
1 /****************************************************************************
2  * Copyright 2018-2020,2021 Thomas E. Dickey                                *
3  * Copyright 1998-2013,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  ****************************************************************************/
35
36 /*
37  *      toe.c --- table of entries report generator
38  */
39
40 #include <progs.priv.h>
41
42 #include <sys/stat.h>
43
44 #if USE_HASHED_DB
45 #include <hashed_db.h>
46 #endif
47
48 MODULE_ID("$Id: toe.c,v 1.84 2021/09/28 08:27:29 tom Exp $")
49
50 #define isDotname(name) (!strcmp(name, ".") || !strcmp(name, ".."))
51
52 typedef struct {
53     int db_index;
54     unsigned long checksum;
55     char *term_name;
56     char *description;
57 } TERMDATA;
58
59 const char *_nc_progname;
60
61 static TERMDATA *ptr_termdata;  /* array of terminal data */
62 static size_t use_termdata;     /* actual usage in ptr_termdata[] */
63 static size_t len_termdata;     /* allocated size of ptr_termdata[] */
64
65 #if NO_LEAKS
66 #undef ExitProgram
67 static GCC_NORETURN void ExitProgram(int code);
68 static void
69 ExitProgram(int code)
70 {
71     _nc_free_entries(_nc_head);
72     _nc_free_tic(code);
73 }
74 #endif
75
76 static GCC_NORETURN void failed(const char *);
77
78 static void
79 failed(const char *msg)
80 {
81     perror(msg);
82     ExitProgram(EXIT_FAILURE);
83 }
84
85 static char *
86 strmalloc(const char *value)
87 {
88     char *result = strdup(value);
89     if (result == 0) {
90         failed("strmalloc");
91     }
92     return result;
93 }
94
95 static TERMDATA *
96 new_termdata(void)
97 {
98     size_t want = use_termdata + 1;
99
100     if (want >= len_termdata) {
101         len_termdata = (2 * want) + 10;
102         ptr_termdata = typeRealloc(TERMDATA, len_termdata, ptr_termdata);
103         if (ptr_termdata == 0)
104             failed("ptr_termdata");
105     }
106
107     return ptr_termdata + use_termdata++;
108 }
109
110 static int
111 compare_termdata(const void *a, const void *b)
112 {
113     const TERMDATA *p = (const TERMDATA *) a;
114     const TERMDATA *q = (const TERMDATA *) b;
115     int result = strcmp(p->term_name, q->term_name);
116
117     if (result == 0) {
118         result = (p->db_index - q->db_index);
119     }
120     return result;
121 }
122
123 /*
124  * Sort the array of TERMDATA and print it.  If more than one database is being
125  * reported, add a column to show which database has a given entry.
126  */
127 static void
128 show_termdata(int eargc, char **eargv)
129 {
130     if (use_termdata) {
131         size_t n;
132
133         if (eargc > 1) {
134             int j;
135
136             for (j = 0; j < eargc; ++j) {
137                 int k;
138
139                 for (k = 0; k <= j; ++k) {
140                     printf("--");
141                 }
142                 printf("> ");
143                 printf("%s\n", eargv[j]);
144             }
145         }
146         if (use_termdata > 1)
147             qsort(ptr_termdata, use_termdata, sizeof(TERMDATA), compare_termdata);
148         for (n = 0; n < use_termdata; ++n) {
149
150             /*
151              * If there is more than one database, show how they differ.
152              */
153             if (eargc > 1) {
154                 unsigned long check = 0;
155                 int k = 0;
156                 for (;;) {
157                     for (; k < ptr_termdata[n].db_index; ++k) {
158                         printf("--");
159                     }
160
161                     /*
162                      * If this is the first entry, or its checksum differs
163                      * from the first entry's checksum, print "*". Otherwise
164                      * it looks enough like a duplicate to print "+".
165                      */
166                     printf("%c-", ((check == 0
167                                     || (check != ptr_termdata[n].checksum))
168                                    ? '*'
169                                    : '+'));
170                     check = ptr_termdata[n].checksum;
171
172                     ++k;
173                     if ((n + 1) >= use_termdata
174                         || strcmp(ptr_termdata[n].term_name,
175                                   ptr_termdata[n + 1].term_name)) {
176                         break;
177                     }
178                     ++n;
179                 }
180                 for (; k < eargc; ++k) {
181                     printf("--");
182                 }
183                 printf(":\t");
184             }
185
186             (void) printf("%-10s\t%s\n",
187                           ptr_termdata[n].term_name,
188                           ptr_termdata[n].description);
189         }
190     }
191 }
192
193 static void
194 free_termdata(void)
195 {
196     if (ptr_termdata != 0) {
197         while (use_termdata != 0) {
198             --use_termdata;
199             free(ptr_termdata[use_termdata].term_name);
200             free(ptr_termdata[use_termdata].description);
201         }
202         free(ptr_termdata);
203         ptr_termdata = 0;
204     }
205     use_termdata = 0;
206     len_termdata = 0;
207 }
208
209 static char **
210 allocArgv(size_t count)
211 {
212     char **result = typeCalloc(char *, count + 1);
213     if (result == 0)
214         failed("realloc eargv");
215
216     assert(result != 0);
217     return result;
218 }
219
220 static void
221 freeArgv(char **argv)
222 {
223     if (argv) {
224         int count = 0;
225         while (argv[count]) {
226             free(argv[count++]);
227         }
228         free(argv);
229     }
230 }
231
232 #if USE_HASHED_DB
233 static bool
234 make_db_name(char *dst, const char *src, unsigned limit)
235 {
236     static const char suffix[] = DBM_SUFFIX;
237
238     bool result = FALSE;
239     size_t lens = sizeof(suffix) - 1;
240     size_t size = strlen(src);
241     size_t need = lens + size;
242
243     if (need <= limit) {
244         if (size >= lens
245             && !strcmp(src + size - lens, suffix)) {
246             _nc_STRCPY(dst, src, PATH_MAX);
247         } else {
248             _nc_SPRINTF(dst, _nc_SLIMIT(PATH_MAX) "%.*s%s",
249                         (int) (PATH_MAX - sizeof(suffix)),
250                         src, suffix);
251         }
252         result = TRUE;
253     }
254     return result;
255 }
256 #endif
257
258 typedef void (DescHook) (int /* db_index */ ,
259                          int /* db_limit */ ,
260                          const char * /* term_name */ ,
261                          TERMTYPE2 * /* term */ );
262
263 static const char *
264 term_description(TERMTYPE2 *tp)
265 {
266     const char *desc;
267
268     if (tp->term_names == 0
269         || (desc = strrchr(tp->term_names, '|')) == 0
270         || (*++desc == '\0')) {
271         desc = "(No description)";
272     }
273
274     return desc;
275 }
276
277 /* display a description for the type */
278 static void
279 deschook(int db_index, int db_limit, const char *term_name, TERMTYPE2 *tp)
280 {
281     (void) db_index;
282     (void) db_limit;
283     (void) printf("%-10s\t%s\n", term_name, term_description(tp));
284 }
285
286 static unsigned long
287 string_sum(const char *value)
288 {
289     unsigned long result = 0;
290
291     if ((intptr_t) value == (intptr_t) (-1)) {
292         result = ~result;
293     } else if (value) {
294         while (*value) {
295             result += UChar(*value);
296             ++value;
297         }
298     }
299     return result;
300 }
301
302 static unsigned long
303 checksum_of(TERMTYPE2 *tp)
304 {
305     unsigned long result = string_sum(tp->term_names);
306     unsigned i;
307
308     for (i = 0; i < NUM_BOOLEANS(tp); i++) {
309         result += (unsigned long) (tp->Booleans[i]);
310     }
311     for (i = 0; i < NUM_NUMBERS(tp); i++) {
312         result += (unsigned long) (tp->Numbers[i]);
313     }
314     for (i = 0; i < NUM_STRINGS(tp); i++) {
315         result += string_sum(tp->Strings[i]);
316     }
317     return result;
318 }
319
320 /* collect data, to sort before display */
321 static void
322 sorthook(int db_index, int db_limit, const char *term_name, TERMTYPE2 *tp)
323 {
324     TERMDATA *data = new_termdata();
325
326     data->db_index = db_index;
327     data->checksum = ((db_limit > 1) ? checksum_of(tp) : 0);
328     data->term_name = strmalloc(term_name);
329     data->description = strmalloc(term_description(tp));
330 }
331
332 #if NCURSES_USE_TERMCAP
333 /*
334  * Check if the buffer contents are printable ASCII, ensuring that we do not
335  * accidentally pick up incompatible binary content from a hashed database.
336  */
337 static bool
338 is_termcap(char *buffer)
339 {
340     bool result = TRUE;
341     while (*buffer != '\0') {
342         int ch = UChar(*buffer++);
343         if (ch == '\t')
344             continue;
345         if (ch < ' ' || ch > '~') {
346             result = FALSE;
347             break;
348         }
349     }
350     return result;
351 }
352
353 static void
354 show_termcap(int db_index, int db_limit, char *buffer, DescHook hook)
355 {
356     TERMTYPE2 data;
357     char *next = strchr(buffer, ':');
358     char *last;
359     char *list = buffer;
360
361     if (next)
362         *next = '\0';
363
364     last = strrchr(buffer, '|');
365     if (last)
366         ++last;
367
368     memset(&data, 0, sizeof(data));
369     data.term_names = strmalloc(buffer);
370     while ((next = strtok(list, "|")) != 0) {
371         if (next != last)
372             hook(db_index, db_limit, next, &data);
373         list = 0;
374     }
375     free(data.term_names);
376 }
377 #endif
378
379 #if NCURSES_USE_DATABASE
380 static char *
381 copy_entryname(DIRENT * src)
382 {
383     size_t len = NAMLEN(src);
384     char *result = malloc(len + 1);
385     if (result == 0)
386         failed("copy entryname");
387     memcpy(result, src->d_name, len);
388     result[len] = '\0';
389
390     return result;
391 }
392 #endif
393
394 static int
395 typelist(int eargc, char *eargv[],
396          int verbosity,
397          DescHook hook)
398 /* apply a function to each entry in given terminfo directories */
399 {
400     int i;
401
402     for (i = 0; i < eargc; i++) {
403 #if NCURSES_USE_DATABASE
404         if (_nc_is_dir_path(eargv[i])) {
405             char *cwd_buf = 0;
406             DIR *termdir;
407             DIRENT *subdir;
408
409             if ((termdir = opendir(eargv[i])) == 0) {
410                 (void) fflush(stdout);
411                 (void) fprintf(stderr,
412                                "%s: can't open terminfo directory %s\n",
413                                _nc_progname, eargv[i]);
414                 continue;
415             }
416
417             if (verbosity)
418                 (void) printf("#\n#%s:\n#\n", eargv[i]);
419
420             while ((subdir = readdir(termdir)) != 0) {
421                 size_t cwd_len;
422                 char *name_1;
423                 DIR *entrydir;
424                 DIRENT *entry;
425
426                 name_1 = copy_entryname(subdir);
427                 if (isDotname(name_1)) {
428                     free(name_1);
429                     continue;
430                 }
431
432                 cwd_len = NAMLEN(subdir) + strlen(eargv[i]) + 3;
433                 cwd_buf = typeRealloc(char, cwd_len, cwd_buf);
434                 if (cwd_buf == 0)
435                     failed("realloc cwd_buf");
436
437                 assert(cwd_buf != 0);
438
439                 _nc_SPRINTF(cwd_buf, _nc_SLIMIT(cwd_len)
440                             "%s/%s/", eargv[i], name_1);
441                 free(name_1);
442
443                 if (chdir(cwd_buf) != 0)
444                     continue;
445
446                 entrydir = opendir(".");
447                 if (entrydir == 0) {
448                     perror(cwd_buf);
449                     continue;
450                 }
451                 while ((entry = readdir(entrydir)) != 0) {
452                     char *name_2;
453                     TERMTYPE2 lterm;
454                     char *cn;
455                     int status;
456
457                     name_2 = copy_entryname(entry);
458                     if (isDotname(name_2) || !_nc_is_file_path(name_2)) {
459                         free(name_2);
460                         continue;
461                     }
462
463                     status = _nc_read_file_entry(name_2, &lterm);
464                     if (status <= 0) {
465                         (void) fflush(stdout);
466                         (void) fprintf(stderr,
467                                        "%s: couldn't open terminfo file %s.\n",
468                                        _nc_progname, name_2);
469                         free(name_2);
470                         continue;
471                     }
472
473                     /* only visit things once, by primary name */
474                     cn = _nc_first_name(lterm.term_names);
475                     if (!strcmp(cn, name_2)) {
476                         /* apply the selected hook function */
477                         hook(i, eargc, cn, &lterm);
478                     }
479                     _nc_free_termtype2(&lterm);
480                     free(name_2);
481                 }
482                 closedir(entrydir);
483             }
484             closedir(termdir);
485             if (cwd_buf != 0)
486                 free(cwd_buf);
487             continue;
488         }
489 #if USE_HASHED_DB
490         else {
491             DB *capdbp;
492             char filename[PATH_MAX];
493
494             if (verbosity)
495                 (void) printf("#\n#%s:\n#\n", eargv[i]);
496
497             if (make_db_name(filename, eargv[i], sizeof(filename))) {
498                 if ((capdbp = _nc_db_open(filename, FALSE)) != 0) {
499                     DBT key, data;
500                     int code;
501
502                     code = _nc_db_first(capdbp, &key, &data);
503                     while (code == 0) {
504                         TERMTYPE2 lterm;
505                         int used;
506                         char *have;
507                         char *cn;
508
509                         if (_nc_db_have_data(&key, &data, &have, &used)) {
510                             if (_nc_read_termtype(&lterm, have, used) > 0) {
511                                 /* only visit things once, by primary name */
512                                 cn = _nc_first_name(lterm.term_names);
513                                 /* apply the selected hook function */
514                                 hook(i, eargc, cn, &lterm);
515                                 _nc_free_termtype2(&lterm);
516                             }
517                         }
518                         code = _nc_db_next(capdbp, &key, &data);
519                     }
520
521                     _nc_db_close(capdbp);
522                     continue;
523                 }
524             }
525         }
526 #endif /* USE_HASHED_DB */
527 #endif /* NCURSES_USE_DATABASE */
528 #if NCURSES_USE_TERMCAP
529 #if HAVE_BSD_CGETENT
530         {
531             CGETENT_CONST char *db_array[2];
532             char *buffer = 0;
533
534             if (verbosity)
535                 (void) printf("#\n#%s:\n#\n", eargv[i]);
536
537             db_array[0] = eargv[i];
538             db_array[1] = 0;
539
540             if (cgetfirst(&buffer, db_array) > 0) {
541                 if (is_termcap(buffer)) {
542                     show_termcap(i, eargc, buffer, hook);
543                     free(buffer);
544                     while (cgetnext(&buffer, db_array) > 0) {
545                         show_termcap(i, eargc, buffer, hook);
546                         free(buffer);
547                     }
548                 }
549                 cgetclose();
550                 continue;
551             }
552         }
553 #else
554         /* scan termcap text-file only */
555         if (_nc_is_file_path(eargv[i])) {
556             char buffer[2048];
557             FILE *fp;
558
559             if (verbosity)
560                 (void) printf("#\n#%s:\n#\n", eargv[i]);
561
562             if ((fp = safe_fopen(eargv[i], "r")) != 0) {
563                 while (fgets(buffer, sizeof(buffer), fp) != 0) {
564                     if (!is_termcap(buffer))
565                         break;
566                     if (*buffer == '#')
567                         continue;
568                     if (isspace(*buffer))
569                         continue;
570                     show_termcap(i, eargc, buffer, hook);
571                 }
572                 fclose(fp);
573             }
574         }
575 #endif
576 #endif
577     }
578
579     if (hook == sorthook) {
580         show_termdata(eargc, eargv);
581         free_termdata();
582     }
583
584     return (EXIT_SUCCESS);
585 }
586
587 static void
588 usage(void)
589 {
590     (void) fprintf(stderr, "usage: %s [-ahsuUV] [-v n] [file...]\n", _nc_progname);
591     ExitProgram(EXIT_FAILURE);
592 }
593
594 int
595 main(int argc, char *argv[])
596 {
597     bool all_dirs = FALSE;
598     bool direct_dependencies = FALSE;
599     bool invert_dependencies = FALSE;
600     bool header = FALSE;
601     char *report_file = 0;
602     int code;
603     int this_opt, last_opt = '?';
604     unsigned v_opt = 0;
605     DescHook *hook = deschook;
606
607     _nc_progname = _nc_rootname(argv[0]);
608
609     while ((this_opt = getopt(argc, argv, "0123456789ahsu:vU:V")) != -1) {
610         /* handle optional parameter */
611         if (isdigit(this_opt)) {
612             switch (last_opt) {
613             case 'v':
614                 v_opt = (unsigned) (this_opt - '0');
615                 break;
616             default:
617                 if (isdigit(last_opt))
618                     v_opt *= 10;
619                 else
620                     v_opt = 0;
621                 v_opt += (unsigned) (this_opt - '0');
622                 last_opt = this_opt;
623             }
624             continue;
625         }
626         switch (this_opt) {
627         case 'a':
628             all_dirs = TRUE;
629             break;
630         case 'h':
631             header = TRUE;
632             break;
633         case 's':
634             hook = sorthook;
635             break;
636         case 'u':
637             direct_dependencies = TRUE;
638             report_file = optarg;
639             break;
640         case 'v':
641             v_opt = 1;
642             break;
643         case 'U':
644             invert_dependencies = TRUE;
645             report_file = optarg;
646             break;
647         case 'V':
648             puts(curses_version());
649             ExitProgram(EXIT_SUCCESS);
650         default:
651             usage();
652         }
653     }
654     set_trace_level(v_opt);
655
656     if (report_file != 0) {
657         if (freopen(report_file, "r", stdin) == 0) {
658             (void) fflush(stdout);
659             fprintf(stderr, "%s: can't open %s\n", _nc_progname, report_file);
660             ExitProgram(EXIT_FAILURE);
661         }
662
663         /* parse entries out of the source file */
664         _nc_set_source(report_file);
665         _nc_read_entry_source(stdin, 0, FALSE, FALSE, NULLHOOK);
666     }
667
668     /* maybe we want a direct-dependency listing? */
669     if (direct_dependencies) {
670         ENTRY *qp;
671
672         for_entry_list(qp) {
673             if (qp->nuses) {
674                 unsigned j;
675
676                 (void) printf("%s:", _nc_first_name(qp->tterm.term_names));
677                 for (j = 0; j < qp->nuses; j++)
678                     (void) printf(" %s", qp->uses[j].name);
679                 putchar('\n');
680             }
681         }
682
683         ExitProgram(EXIT_SUCCESS);
684     }
685
686     /* maybe we want a reverse-dependency listing? */
687     if (invert_dependencies) {
688         ENTRY *qp, *rp;
689
690         for_entry_list(qp) {
691             int matchcount = 0;
692
693             for_entry_list(rp) {
694                 unsigned i;
695
696                 if (rp->nuses == 0)
697                     continue;
698
699                 for (i = 0; i < rp->nuses; i++)
700                     if (_nc_name_match(qp->tterm.term_names,
701                                        rp->uses[i].name, "|")) {
702                         if (matchcount++ == 0)
703                             (void) printf("%s:",
704                                           _nc_first_name(qp->tterm.term_names));
705                         (void) printf(" %s",
706                                       _nc_first_name(rp->tterm.term_names));
707                     }
708             }
709             if (matchcount)
710                 putchar('\n');
711         }
712
713         ExitProgram(EXIT_SUCCESS);
714     }
715
716     /*
717      * If we get this far, user wants a simple terminal type listing.
718      */
719     if (optind < argc) {
720         code = typelist(argc - optind, argv + optind, header, hook);
721     } else if (all_dirs) {
722         DBDIRS state;
723         int offset;
724         int pass;
725         char **eargv = 0;
726
727         code = EXIT_FAILURE;
728         for (pass = 0; pass < 2; ++pass) {
729             size_t count = 0;
730             const char *path;
731
732             _nc_first_db(&state, &offset);
733             while ((path = _nc_next_db(&state, &offset)) != 0) {
734                 if (quick_prefix(path))
735                     continue;
736                 if (pass) {
737                     eargv[count] = strmalloc(path);
738                 }
739                 ++count;
740             }
741             if (!pass) {
742                 eargv = allocArgv(count);
743                 if (eargv == 0)
744                     failed("eargv");
745             } else {
746                 code = typelist((int) count, eargv, header, hook);
747                 freeArgv(eargv);
748             }
749         }
750     } else {
751         DBDIRS state;
752         int offset;
753         const char *path;
754         char **eargv = allocArgv((size_t) 2);
755         size_t count = 0;
756
757         if (eargv == 0)
758             failed("eargv");
759         _nc_first_db(&state, &offset);
760         if ((path = _nc_next_db(&state, &offset)) != 0) {
761             if (!quick_prefix(path))
762                 eargv[count++] = strmalloc(path);
763         }
764
765         code = typelist((int) count, eargv, header, hook);
766
767         freeArgv(eargv);
768     }
769     _nc_last_db();
770
771     ExitProgram(code);
772 }