]> ncurses.scripts.mit.edu Git - ncurses.git/blob - progs/toe.c
ncurses 6.2 - patch 20210925
[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.83 2021/09/21 20:07:51 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 static void
334 show_termcap(int db_index, int db_limit, char *buffer, DescHook hook)
335 {
336     TERMTYPE2 data;
337     char *next = strchr(buffer, ':');
338     char *last;
339     char *list = buffer;
340
341     if (next)
342         *next = '\0';
343
344     last = strrchr(buffer, '|');
345     if (last)
346         ++last;
347
348     memset(&data, 0, sizeof(data));
349     data.term_names = strmalloc(buffer);
350     while ((next = strtok(list, "|")) != 0) {
351         if (next != last)
352             hook(db_index, db_limit, next, &data);
353         list = 0;
354     }
355     free(data.term_names);
356 }
357 #endif
358
359 #if NCURSES_USE_DATABASE
360 static char *
361 copy_entryname(DIRENT * src)
362 {
363     size_t len = NAMLEN(src);
364     char *result = malloc(len + 1);
365     if (result == 0)
366         failed("copy entryname");
367     memcpy(result, src->d_name, len);
368     result[len] = '\0';
369
370     return result;
371 }
372 #endif
373
374 static int
375 typelist(int eargc, char *eargv[],
376          int verbosity,
377          DescHook hook)
378 /* apply a function to each entry in given terminfo directories */
379 {
380     int i;
381
382     for (i = 0; i < eargc; i++) {
383 #if NCURSES_USE_DATABASE
384         if (_nc_is_dir_path(eargv[i])) {
385             char *cwd_buf = 0;
386             DIR *termdir;
387             DIRENT *subdir;
388
389             if ((termdir = opendir(eargv[i])) == 0) {
390                 (void) fflush(stdout);
391                 (void) fprintf(stderr,
392                                "%s: can't open terminfo directory %s\n",
393                                _nc_progname, eargv[i]);
394                 continue;
395             }
396
397             if (verbosity)
398                 (void) printf("#\n#%s:\n#\n", eargv[i]);
399
400             while ((subdir = readdir(termdir)) != 0) {
401                 size_t cwd_len;
402                 char *name_1;
403                 DIR *entrydir;
404                 DIRENT *entry;
405
406                 name_1 = copy_entryname(subdir);
407                 if (isDotname(name_1)) {
408                     free(name_1);
409                     continue;
410                 }
411
412                 cwd_len = NAMLEN(subdir) + strlen(eargv[i]) + 3;
413                 cwd_buf = typeRealloc(char, cwd_len, cwd_buf);
414                 if (cwd_buf == 0)
415                     failed("realloc cwd_buf");
416
417                 assert(cwd_buf != 0);
418
419                 _nc_SPRINTF(cwd_buf, _nc_SLIMIT(cwd_len)
420                             "%s/%s/", eargv[i], name_1);
421                 free(name_1);
422
423                 if (chdir(cwd_buf) != 0)
424                     continue;
425
426                 entrydir = opendir(".");
427                 if (entrydir == 0) {
428                     perror(cwd_buf);
429                     continue;
430                 }
431                 while ((entry = readdir(entrydir)) != 0) {
432                     char *name_2;
433                     TERMTYPE2 lterm;
434                     char *cn;
435                     int status;
436
437                     name_2 = copy_entryname(entry);
438                     if (isDotname(name_2) || !_nc_is_file_path(name_2)) {
439                         free(name_2);
440                         continue;
441                     }
442
443                     status = _nc_read_file_entry(name_2, &lterm);
444                     if (status <= 0) {
445                         (void) fflush(stdout);
446                         (void) fprintf(stderr,
447                                        "%s: couldn't open terminfo file %s.\n",
448                                        _nc_progname, name_2);
449                         free(name_2);
450                         continue;
451                     }
452
453                     /* only visit things once, by primary name */
454                     cn = _nc_first_name(lterm.term_names);
455                     if (!strcmp(cn, name_2)) {
456                         /* apply the selected hook function */
457                         hook(i, eargc, cn, &lterm);
458                     }
459                     _nc_free_termtype2(&lterm);
460                     free(name_2);
461                 }
462                 closedir(entrydir);
463             }
464             closedir(termdir);
465             if (cwd_buf != 0)
466                 free(cwd_buf);
467             continue;
468         }
469 #if USE_HASHED_DB
470         else {
471             DB *capdbp;
472             char filename[PATH_MAX];
473
474             if (verbosity)
475                 (void) printf("#\n#%s:\n#\n", eargv[i]);
476
477             if (make_db_name(filename, eargv[i], sizeof(filename))) {
478                 if ((capdbp = _nc_db_open(filename, FALSE)) != 0) {
479                     DBT key, data;
480                     int code;
481
482                     code = _nc_db_first(capdbp, &key, &data);
483                     while (code == 0) {
484                         TERMTYPE2 lterm;
485                         int used;
486                         char *have;
487                         char *cn;
488
489                         if (_nc_db_have_data(&key, &data, &have, &used)) {
490                             if (_nc_read_termtype(&lterm, have, used) > 0) {
491                                 /* only visit things once, by primary name */
492                                 cn = _nc_first_name(lterm.term_names);
493                                 /* apply the selected hook function */
494                                 hook(i, eargc, cn, &lterm);
495                                 _nc_free_termtype2(&lterm);
496                             }
497                         }
498                         code = _nc_db_next(capdbp, &key, &data);
499                     }
500
501                     _nc_db_close(capdbp);
502                     continue;
503                 }
504             }
505         }
506 #endif /* USE_HASHED_DB */
507 #endif /* NCURSES_USE_DATABASE */
508 #if NCURSES_USE_TERMCAP
509 #if HAVE_BSD_CGETENT
510         {
511             CGETENT_CONST char *db_array[2];
512             char *buffer = 0;
513
514             if (verbosity)
515                 (void) printf("#\n#%s:\n#\n", eargv[i]);
516
517             db_array[0] = eargv[i];
518             db_array[1] = 0;
519
520             if (cgetfirst(&buffer, db_array) > 0) {
521                 show_termcap(i, eargc, buffer, hook);
522                 free(buffer);
523                 while (cgetnext(&buffer, db_array) > 0) {
524                     show_termcap(i, eargc, buffer, hook);
525                     free(buffer);
526                 }
527                 cgetclose();
528                 continue;
529             }
530         }
531 #else
532         /* scan termcap text-file only */
533         if (_nc_is_file_path(eargv[i])) {
534             char buffer[2048];
535             FILE *fp;
536
537             if (verbosity)
538                 (void) printf("#\n#%s:\n#\n", eargv[i]);
539
540             if ((fp = safe_fopen(eargv[i], "r")) != 0) {
541                 while (fgets(buffer, sizeof(buffer), fp) != 0) {
542                     if (*buffer == '#')
543                         continue;
544                     if (isspace(*buffer))
545                         continue;
546                     show_termcap(i, eargc, buffer, hook);
547                 }
548                 fclose(fp);
549             }
550         }
551 #endif
552 #endif
553     }
554
555     if (hook == sorthook) {
556         show_termdata(eargc, eargv);
557         free_termdata();
558     }
559
560     return (EXIT_SUCCESS);
561 }
562
563 static void
564 usage(void)
565 {
566     (void) fprintf(stderr, "usage: %s [-ahsuUV] [-v n] [file...]\n", _nc_progname);
567     ExitProgram(EXIT_FAILURE);
568 }
569
570 int
571 main(int argc, char *argv[])
572 {
573     bool all_dirs = FALSE;
574     bool direct_dependencies = FALSE;
575     bool invert_dependencies = FALSE;
576     bool header = FALSE;
577     char *report_file = 0;
578     int code;
579     int this_opt, last_opt = '?';
580     unsigned v_opt = 0;
581     DescHook *hook = deschook;
582
583     _nc_progname = _nc_rootname(argv[0]);
584
585     while ((this_opt = getopt(argc, argv, "0123456789ahsu:vU:V")) != -1) {
586         /* handle optional parameter */
587         if (isdigit(this_opt)) {
588             switch (last_opt) {
589             case 'v':
590                 v_opt = (unsigned) (this_opt - '0');
591                 break;
592             default:
593                 if (isdigit(last_opt))
594                     v_opt *= 10;
595                 else
596                     v_opt = 0;
597                 v_opt += (unsigned) (this_opt - '0');
598                 last_opt = this_opt;
599             }
600             continue;
601         }
602         switch (this_opt) {
603         case 'a':
604             all_dirs = TRUE;
605             break;
606         case 'h':
607             header = TRUE;
608             break;
609         case 's':
610             hook = sorthook;
611             break;
612         case 'u':
613             direct_dependencies = TRUE;
614             report_file = optarg;
615             break;
616         case 'v':
617             v_opt = 1;
618             break;
619         case 'U':
620             invert_dependencies = TRUE;
621             report_file = optarg;
622             break;
623         case 'V':
624             puts(curses_version());
625             ExitProgram(EXIT_SUCCESS);
626         default:
627             usage();
628         }
629     }
630     set_trace_level(v_opt);
631
632     if (report_file != 0) {
633         if (freopen(report_file, "r", stdin) == 0) {
634             (void) fflush(stdout);
635             fprintf(stderr, "%s: can't open %s\n", _nc_progname, report_file);
636             ExitProgram(EXIT_FAILURE);
637         }
638
639         /* parse entries out of the source file */
640         _nc_set_source(report_file);
641         _nc_read_entry_source(stdin, 0, FALSE, FALSE, NULLHOOK);
642     }
643
644     /* maybe we want a direct-dependency listing? */
645     if (direct_dependencies) {
646         ENTRY *qp;
647
648         for_entry_list(qp) {
649             if (qp->nuses) {
650                 unsigned j;
651
652                 (void) printf("%s:", _nc_first_name(qp->tterm.term_names));
653                 for (j = 0; j < qp->nuses; j++)
654                     (void) printf(" %s", qp->uses[j].name);
655                 putchar('\n');
656             }
657         }
658
659         ExitProgram(EXIT_SUCCESS);
660     }
661
662     /* maybe we want a reverse-dependency listing? */
663     if (invert_dependencies) {
664         ENTRY *qp, *rp;
665
666         for_entry_list(qp) {
667             int matchcount = 0;
668
669             for_entry_list(rp) {
670                 unsigned i;
671
672                 if (rp->nuses == 0)
673                     continue;
674
675                 for (i = 0; i < rp->nuses; i++)
676                     if (_nc_name_match(qp->tterm.term_names,
677                                        rp->uses[i].name, "|")) {
678                         if (matchcount++ == 0)
679                             (void) printf("%s:",
680                                           _nc_first_name(qp->tterm.term_names));
681                         (void) printf(" %s",
682                                       _nc_first_name(rp->tterm.term_names));
683                     }
684             }
685             if (matchcount)
686                 putchar('\n');
687         }
688
689         ExitProgram(EXIT_SUCCESS);
690     }
691
692     /*
693      * If we get this far, user wants a simple terminal type listing.
694      */
695     if (optind < argc) {
696         code = typelist(argc - optind, argv + optind, header, hook);
697     } else if (all_dirs) {
698         DBDIRS state;
699         int offset;
700         int pass;
701         char **eargv = 0;
702
703         code = EXIT_FAILURE;
704         for (pass = 0; pass < 2; ++pass) {
705             size_t count = 0;
706             const char *path;
707
708             _nc_first_db(&state, &offset);
709             while ((path = _nc_next_db(&state, &offset)) != 0) {
710                 if (quick_prefix(path))
711                     continue;
712                 if (pass) {
713                     eargv[count] = strmalloc(path);
714                 }
715                 ++count;
716             }
717             if (!pass) {
718                 eargv = allocArgv(count);
719                 if (eargv == 0)
720                     failed("eargv");
721             } else {
722                 code = typelist((int) count, eargv, header, hook);
723                 freeArgv(eargv);
724             }
725         }
726     } else {
727         DBDIRS state;
728         int offset;
729         const char *path;
730         char **eargv = allocArgv((size_t) 2);
731         size_t count = 0;
732
733         if (eargv == 0)
734             failed("eargv");
735         _nc_first_db(&state, &offset);
736         if ((path = _nc_next_db(&state, &offset)) != 0) {
737             if (!quick_prefix(path))
738                 eargv[count++] = strmalloc(path);
739         }
740
741         code = typelist((int) count, eargv, header, hook);
742
743         freeArgv(eargv);
744     }
745     _nc_last_db();
746
747     ExitProgram(code);
748 }