]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/read_entry.c
ncurses 6.3 - patch 20220416
[ncurses.git] / ncurses / tinfo / read_entry.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2016,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  *      read_entry.c -- Routine for reading in a compiled terminfo file
38  */
39
40 #include <curses.priv.h>
41 #include <hashed_db.h>
42
43 #include <tic.h>
44
45 MODULE_ID("$Id: read_entry.c,v 1.162 2022/04/16 21:00:00 tom Exp $")
46
47 #define TYPE_CALLOC(type,elts) typeCalloc(type, (unsigned)(elts))
48
49 #define MyNumber(n) (short) LOW_MSB(n)
50
51 #define SIZEOF_32BITS 4
52
53 #if NCURSES_USE_DATABASE
54 #if NCURSES_EXT_NUMBERS
55 static size_t
56 convert_16bits(char *buf, NCURSES_INT2 *Numbers, int count)
57 {
58     int i;
59     size_t j;
60     size_t size = SIZEOF_SHORT;
61     for (i = 0; i < count; i++) {
62         unsigned mask = 0xff;
63         unsigned char ch = 0;
64         Numbers[i] = 0;
65         for (j = 0; j < size; ++j) {
66             ch = UChar(*buf++);
67             Numbers[i] |= (ch << (8 * j));
68             mask <<= 8;
69         }
70         if (ch & 0x80) {
71             while (mask != 0) {
72                 Numbers[i] |= (int) mask;
73                 mask <<= 8;
74             }
75         }
76         TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
77     }
78     return size;
79 }
80
81 static size_t
82 convert_32bits(char *buf, NCURSES_INT2 *Numbers, int count)
83 {
84     int i;
85     size_t j;
86     size_t size = SIZEOF_INT2;
87     unsigned char ch;
88
89     assert(sizeof(NCURSES_INT2) == size);
90     for (i = 0; i < count; i++) {
91         Numbers[i] = 0;
92         for (j = 0; j < size; ++j) {
93             ch = UChar(*buf++);
94             Numbers[i] |= (ch << (8 * j));
95         }
96         /* "unsigned" and NCURSES_INT2 are the same size - no sign-extension */
97         TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
98     }
99     return size;
100 }
101 #else
102 static size_t
103 convert_32bits(char *buf, NCURSES_INT2 *Numbers, int count)
104 {
105     int i, j;
106     unsigned char ch;
107     for (i = 0; i < count; i++) {
108         int value = 0;
109         for (j = 0; j < SIZEOF_32BITS; ++j) {
110             ch = UChar(*buf++);
111             value |= (ch << (8 * j));
112         }
113         if (value == -1)
114             Numbers[i] = ABSENT_NUMERIC;
115         else if (value == -2)
116             Numbers[i] = CANCELLED_NUMERIC;
117         else if (value > MAX_OF_TYPE(NCURSES_INT2))
118             Numbers[i] = MAX_OF_TYPE(NCURSES_INT2);
119         else
120             Numbers[i] = (short) value;
121         TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
122     }
123     return SIZEOF_SHORT;
124 }
125
126 static size_t
127 convert_16bits(char *buf, NCURSES_INT2 *Numbers, int count)
128 {
129     int i;
130     for (i = 0; i < count; i++) {
131         if (IS_NEG1(buf + 2 * i))
132             Numbers[i] = ABSENT_NUMERIC;
133         else if (IS_NEG2(buf + 2 * i))
134             Numbers[i] = CANCELLED_NUMERIC;
135         else
136             Numbers[i] = MyNumber(buf + 2 * i);
137         TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
138     }
139     return SIZEOF_SHORT;
140 }
141 #endif
142
143 static void
144 convert_strings(char *buf, char **Strings, int count, int size, char *table)
145 {
146     int i;
147     char *p;
148     bool corrupt = FALSE;
149
150     for (i = 0; i < count; i++) {
151         if (IS_NEG1(buf + 2 * i)) {
152             Strings[i] = ABSENT_STRING;
153         } else if (IS_NEG2(buf + 2 * i)) {
154             Strings[i] = CANCELLED_STRING;
155         } else if (MyNumber(buf + 2 * i) > size) {
156             Strings[i] = ABSENT_STRING;
157         } else {
158             int nn = MyNumber(buf + 2 * i);
159             if (nn >= 0 && nn < size) {
160                 Strings[i] = (nn + table);
161                 TR(TRACE_DATABASE, ("Strings[%d] = %s", i,
162                                     _nc_visbuf(Strings[i])));
163             } else {
164                 if (!corrupt) {
165                     corrupt = TRUE;
166                     TR(TRACE_DATABASE,
167                        ("ignore out-of-range index %d to Strings[]", nn));
168                     _nc_warning("corrupt data found in convert_strings");
169                 }
170                 Strings[i] = ABSENT_STRING;
171             }
172         }
173
174         /* make sure all strings are NUL terminated */
175         if (VALID_STRING(Strings[i])) {
176             for (p = Strings[i]; p < table + size; p++)
177                 if (*p == '\0')
178                     break;
179             /* if there is no NUL, ignore the string */
180             if (p >= table + size)
181                 Strings[i] = ABSENT_STRING;
182         }
183     }
184 }
185
186 static int
187 fake_read(char *src, int *offset, int limit, char *dst, unsigned want)
188 {
189     int have = (limit - *offset);
190
191     if (have > 0) {
192         if ((int) want > have)
193             want = (unsigned) have;
194         memcpy(dst, src + *offset, (size_t) want);
195         *offset += (int) want;
196     } else {
197         want = 0;
198     }
199     return (int) want;
200 }
201
202 #define Read(buf, count) fake_read(buffer, &offset, limit, (char *) buf, (unsigned) count)
203
204 #define read_shorts(buf, count) \
205         (Read(buf, (count)*SIZEOF_SHORT) == (int) (count)*SIZEOF_SHORT)
206
207 #define read_numbers(buf, count) \
208         (Read(buf, (count)*(unsigned)size_of_numbers) == (int) (count)*size_of_numbers)
209
210 #define even_boundary(value) \
211     if ((value) % 2 != 0) Read(buf, 1)
212 #endif
213
214 NCURSES_EXPORT(void)
215 _nc_init_termtype(TERMTYPE2 *const tp)
216 {
217     unsigned i;
218
219 #if NCURSES_XNAMES
220     tp->num_Booleans = BOOLCOUNT;
221     tp->num_Numbers = NUMCOUNT;
222     tp->num_Strings = STRCOUNT;
223     tp->ext_Booleans = 0;
224     tp->ext_Numbers = 0;
225     tp->ext_Strings = 0;
226 #endif
227     if (tp->Booleans == 0)
228         TYPE_MALLOC(NCURSES_SBOOL, BOOLCOUNT, tp->Booleans);
229     if (tp->Numbers == 0)
230         TYPE_MALLOC(NCURSES_INT2, NUMCOUNT, tp->Numbers);
231     if (tp->Strings == 0)
232         TYPE_MALLOC(char *, STRCOUNT, tp->Strings);
233
234     for_each_boolean(i, tp)
235         tp->Booleans[i] = FALSE;
236
237     for_each_number(i, tp)
238         tp->Numbers[i] = ABSENT_NUMERIC;
239
240     for_each_string(i, tp)
241         tp->Strings[i] = ABSENT_STRING;
242 }
243
244 #if NCURSES_USE_DATABASE
245 #if NCURSES_XNAMES
246 static bool
247 valid_shorts(char *buffer, int limit)
248 {
249     bool result = FALSE;
250     int n;
251     for (n = 0; n < limit; ++n) {
252         if (MyNumber(buffer + (n * 2)) > 0) {
253             result = TRUE;
254             break;
255         }
256     }
257     return result;
258 }
259 #endif
260
261 /*
262  * Return TGETENT_YES if read, TGETENT_NO if not found or garbled.
263  */
264 NCURSES_EXPORT(int)
265 _nc_read_termtype(TERMTYPE2 *ptr, char *buffer, int limit)
266 {
267     int offset = 0;
268     int name_size, bool_count, num_count, str_count, str_size;
269     int i;
270     char buf[MAX_ENTRY_SIZE + 2];
271     char *string_table;
272     unsigned want, have;
273     size_t (*convert_numbers) (char *, NCURSES_INT2 *, int);
274     int size_of_numbers;
275     int max_entry_size = MAX_ENTRY_SIZE;
276
277     TR(TRACE_DATABASE,
278        (T_CALLED("_nc_read_termtype(ptr=%p, buffer=%p, limit=%d)"),
279         (void *) ptr, buffer, limit));
280
281     TR(TRACE_DATABASE, ("READ termtype header @%d", offset));
282
283     memset(ptr, 0, sizeof(*ptr));
284
285     /* grab the header */
286     if (!read_shorts(buf, 6)
287         || !IS_TIC_MAGIC(buf)) {
288         returnDB(TGETENT_NO);
289     }
290 #if NCURSES_EXT_NUMBERS
291     if (LOW_MSB(buf) == MAGIC2) {
292         convert_numbers = convert_32bits;
293         size_of_numbers = SIZEOF_INT2;
294     } else {
295         max_entry_size = MAX_ENTRY_SIZE1;
296         convert_numbers = convert_16bits;
297         size_of_numbers = SIZEOF_SHORT;
298     }
299 #else
300     if (LOW_MSB(buf) == MAGIC2) {
301         convert_numbers = convert_32bits;
302         size_of_numbers = SIZEOF_32BITS;
303     } else {
304         convert_numbers = convert_16bits;
305         size_of_numbers = SIZEOF_INT2;
306     }
307 #endif
308
309     /* *INDENT-EQLS* */
310     name_size  = MyNumber(buf + 2);
311     bool_count = MyNumber(buf + 4);
312     num_count  = MyNumber(buf + 6);
313     str_count  = MyNumber(buf + 8);
314     str_size   = MyNumber(buf + 10);
315
316     TR(TRACE_DATABASE,
317        ("TERMTYPE name_size=%d, bool=%d/%d, num=%d/%d str=%d/%d(%d)",
318         name_size, bool_count, BOOLCOUNT, num_count, NUMCOUNT,
319         str_count, STRCOUNT, str_size));
320     if (name_size < 0
321         || bool_count < 0
322         || num_count < 0
323         || str_count < 0
324         || str_size < 0) {
325         returnDB(TGETENT_NO);
326     }
327
328     want = (unsigned) (str_size + name_size + 1);
329     /* try to allocate space for the string table */
330     if (str_count * SIZEOF_SHORT >= max_entry_size
331         || (string_table = typeMalloc(char, want)) == 0) {
332         returnDB(TGETENT_NO);
333     }
334
335     /* grab the name (a null-terminated string) */
336     want = min(MAX_NAME_SIZE, (unsigned) name_size);
337     ptr->str_table = string_table;
338     ptr->term_names = string_table;
339     if ((have = (unsigned) Read(ptr->term_names, want)) != want) {
340         memset(ptr->term_names + have, 0, (size_t) (want - have));
341     }
342     ptr->term_names[want] = '\0';
343     string_table += (want + 1);
344
345     if (have > MAX_NAME_SIZE)
346         offset = (int) (have - MAX_NAME_SIZE);
347
348     /* grab the booleans */
349     if ((ptr->Booleans = TYPE_CALLOC(NCURSES_SBOOL,
350                                      max(BOOLCOUNT, bool_count))) == 0
351         || Read(ptr->Booleans, (unsigned) bool_count) < bool_count) {
352         returnDB(TGETENT_NO);
353     }
354
355     /*
356      * If booleans end on an odd byte, skip it.  The machine they
357      * originally wrote terminfo on must have been a 16-bit
358      * word-oriented machine that would trap out if you tried a
359      * word access off a 2-byte boundary.
360      */
361     even_boundary(name_size + bool_count);
362
363     /* grab the numbers */
364     if (!(ptr->Numbers = TYPE_CALLOC(NCURSES_INT2, max(NUMCOUNT, num_count)))
365         || !read_numbers(buf, num_count)) {
366         returnDB(TGETENT_NO);
367     }
368     convert_numbers(buf, ptr->Numbers, num_count);
369
370     if ((ptr->Strings = TYPE_CALLOC(char *, max(STRCOUNT, str_count))) == 0) {
371         returnDB(TGETENT_NO);
372     }
373
374     if (str_count) {
375         /* grab the string offsets */
376         if (!read_shorts(buf, str_count)) {
377             returnDB(TGETENT_NO);
378         }
379         /* finally, grab the string table itself */
380         if (Read(string_table, (unsigned) str_size) != str_size) {
381             returnDB(TGETENT_NO);
382         }
383         convert_strings(buf, ptr->Strings, str_count, str_size, string_table);
384     }
385 #if NCURSES_XNAMES
386
387     ptr->num_Booleans = BOOLCOUNT;
388     ptr->num_Numbers = NUMCOUNT;
389     ptr->num_Strings = STRCOUNT;
390
391     /*
392      * Read extended entries, if any, after the normal end of terminfo data.
393      */
394     even_boundary(str_size);
395     TR(TRACE_DATABASE, ("READ extended_header @%d", offset));
396     if (_nc_user_definable && read_shorts(buf, 5) && valid_shorts(buf, 5)) {
397         int ext_bool_count = MyNumber(buf + 0);
398         int ext_num_count = MyNumber(buf + 2);
399         int ext_str_count = MyNumber(buf + 4);
400         int ext_str_usage = MyNumber(buf + 6);
401         int ext_str_limit = MyNumber(buf + 8);
402         unsigned need = (unsigned) (ext_bool_count + ext_num_count + ext_str_count);
403         int base = 0;
404
405         if ((int) need >= (max_entry_size / 2)
406             || ext_str_usage >= max_entry_size
407             || ext_str_limit >= max_entry_size
408             || ext_bool_count < 0
409             || ext_num_count < 0
410             || ext_str_count < 0
411             || ext_str_usage < 0
412             || ext_str_limit < 0) {
413             returnDB(TGETENT_NO);
414         }
415
416         ptr->num_Booleans = UShort(BOOLCOUNT + ext_bool_count);
417         ptr->num_Numbers = UShort(NUMCOUNT + ext_num_count);
418         ptr->num_Strings = UShort(STRCOUNT + ext_str_count);
419
420         TYPE_REALLOC(NCURSES_SBOOL, ptr->num_Booleans, ptr->Booleans);
421         TYPE_REALLOC(NCURSES_INT2, ptr->num_Numbers, ptr->Numbers);
422         TYPE_REALLOC(char *, ptr->num_Strings, ptr->Strings);
423
424         TR(TRACE_DATABASE, ("extended header: "
425                             "bool %d, "
426                             "number %d, "
427                             "string %d(%d:%d)",
428                             ext_bool_count,
429                             ext_num_count,
430                             ext_str_count,
431                             ext_str_usage,
432                             ext_str_limit));
433
434         TR(TRACE_DATABASE, ("READ %d extended-booleans @%d",
435                             ext_bool_count, offset));
436         if ((ptr->ext_Booleans = UShort(ext_bool_count)) != 0) {
437             if (Read(ptr->Booleans + BOOLCOUNT, (unsigned)
438                      ext_bool_count) != ext_bool_count) {
439                 returnDB(TGETENT_NO);
440             }
441         }
442         even_boundary(ext_bool_count);
443
444         TR(TRACE_DATABASE, ("READ %d extended-numbers @%d",
445                             ext_num_count, offset));
446         if ((ptr->ext_Numbers = UShort(ext_num_count)) != 0) {
447             if (!read_numbers(buf, ext_num_count)) {
448                 returnDB(TGETENT_NO);
449             }
450             TR(TRACE_DATABASE, ("Before converting extended-numbers"));
451             convert_numbers(buf, ptr->Numbers + NUMCOUNT, ext_num_count);
452         }
453
454         TR(TRACE_DATABASE, ("READ extended-offsets @%d", offset));
455         if ((ext_str_count + (int) need) >= (max_entry_size / 2)) {
456             returnDB(TGETENT_NO);
457         }
458         if ((ext_str_count || need)
459             && !read_shorts(buf, ext_str_count + (int) need)) {
460             returnDB(TGETENT_NO);
461         }
462
463         TR(TRACE_DATABASE, ("READ %d bytes of extended-strings @%d",
464                             ext_str_limit, offset));
465
466         if (ext_str_limit) {
467             ptr->ext_str_table = typeMalloc(char, (size_t) ext_str_limit);
468             if (ptr->ext_str_table == 0) {
469                 returnDB(TGETENT_NO);
470             }
471             if (Read(ptr->ext_str_table, (unsigned) ext_str_limit) != ext_str_limit) {
472                 returnDB(TGETENT_NO);
473             }
474             TR(TRACE_DATABASE, ("first extended-string is %s", _nc_visbuf(ptr->ext_str_table)));
475         }
476
477         if ((ptr->ext_Strings = UShort(ext_str_count)) != 0) {
478             int check = (ext_bool_count + ext_num_count + ext_str_count);
479
480             TR(TRACE_DATABASE,
481                ("Before computing extended-string capabilities "
482                 "str_count=%d, ext_str_count=%d",
483                 str_count, ext_str_count));
484             convert_strings(buf, ptr->Strings + str_count, ext_str_count,
485                             ext_str_limit, ptr->ext_str_table);
486             for (i = ext_str_count - 1; i >= 0; i--) {
487                 TR(TRACE_DATABASE, ("MOVE from [%d:%d] %s",
488                                     i, i + str_count,
489                                     _nc_visbuf(ptr->Strings[i + str_count])));
490                 ptr->Strings[i + STRCOUNT] = ptr->Strings[i + str_count];
491                 if (VALID_STRING(ptr->Strings[i + STRCOUNT])) {
492                     base += (int) (strlen(ptr->Strings[i + STRCOUNT]) + 1);
493                     ++check;
494                 }
495                 TR(TRACE_DATABASE, ("... to    [%d] %s",
496                                     i + STRCOUNT,
497                                     _nc_visbuf(ptr->Strings[i + STRCOUNT])));
498             }
499             TR(TRACE_DATABASE, ("Check table-size: %d/%d", check, ext_str_usage));
500 #if 0
501             /*
502              * Phasing in a proper check will be done "later".
503              */
504             if (check != ext_str_usage)
505                 returnDB(TGETENT_NO);
506 #endif
507         }
508
509         if (need) {
510             if (ext_str_count >= (max_entry_size / 2)) {
511                 returnDB(TGETENT_NO);
512             }
513             if ((ptr->ext_Names = TYPE_CALLOC(char *, need)) == 0) {
514                 returnDB(TGETENT_NO);
515             }
516             TR(TRACE_DATABASE,
517                ("ext_NAMES starting @%d in extended_strings, first = %s",
518                 base, _nc_visbuf(ptr->ext_str_table + base)));
519             convert_strings(buf + (2 * ext_str_count),
520                             ptr->ext_Names,
521                             (int) need,
522                             ext_str_limit, ptr->ext_str_table + base);
523         }
524
525         TR(TRACE_DATABASE,
526            ("...done reading terminfo bool %d(%d) num %d(%d) str %d(%d)",
527             ptr->num_Booleans, ptr->ext_Booleans,
528             ptr->num_Numbers, ptr->ext_Numbers,
529             ptr->num_Strings, ptr->ext_Strings));
530
531         TR(TRACE_DATABASE, ("extend: num_Booleans:%d", ptr->num_Booleans));
532     } else
533 #endif /* NCURSES_XNAMES */
534     {
535         TR(TRACE_DATABASE, ("...done reading terminfo bool %d num %d str %d",
536                             bool_count, num_count, str_count));
537 #if NCURSES_XNAMES
538         TR(TRACE_DATABASE, ("normal: num_Booleans:%d", ptr->num_Booleans));
539 #endif
540     }
541
542     for (i = bool_count; i < BOOLCOUNT; i++)
543         ptr->Booleans[i] = FALSE;
544     for (i = num_count; i < NUMCOUNT; i++)
545         ptr->Numbers[i] = ABSENT_NUMERIC;
546     for (i = str_count; i < STRCOUNT; i++)
547         ptr->Strings[i] = ABSENT_STRING;
548
549     returnDB(TGETENT_YES);
550 }
551
552 /*
553  *      int
554  *      _nc_read_file_entry(filename, ptr)
555  *
556  *      Read the compiled terminfo entry in the given file into the
557  *      structure pointed to by ptr, allocating space for the string
558  *      table.
559  */
560 NCURSES_EXPORT(int)
561 _nc_read_file_entry(const char *const filename, TERMTYPE2 *ptr)
562 /* return 1 if read, 0 if not found or garbled */
563 {
564     FILE *fp = 0;
565     int code;
566
567     if (_nc_access(filename, R_OK) < 0
568         || (fp = safe_fopen(filename, BIN_R)) == 0) {
569         TR(TRACE_DATABASE, ("cannot open terminfo %s (errno=%d)", filename, errno));
570         code = TGETENT_NO;
571     } else {
572         int limit;
573         char buffer[MAX_ENTRY_SIZE + 1];
574
575         if ((limit = (int) fread(buffer, sizeof(char), sizeof(buffer), fp))
576             > 0) {
577
578             TR(TRACE_DATABASE, ("read terminfo %s", filename));
579             if ((code = _nc_read_termtype(ptr, buffer, limit)) == TGETENT_NO) {
580                 _nc_free_termtype2(ptr);
581             }
582         } else {
583             code = TGETENT_NO;
584         }
585         fclose(fp);
586     }
587
588     return (code);
589 }
590
591 #if USE_HASHED_DB
592 /*
593  * Return if if we can build the filename of a ".db" file.
594  */
595 static bool
596 make_db_filename(char *filename, unsigned limit, const char *const path)
597 {
598     static const char suffix[] = DBM_SUFFIX;
599
600     size_t lens = sizeof(suffix) - 1;
601     size_t size = strlen(path);
602     size_t test = lens + size;
603     bool result = FALSE;
604
605     if (test < limit) {
606         if (size >= lens
607             && !strcmp(path + size - lens, suffix))
608             _nc_STRCPY(filename, path, limit);
609         else
610             _nc_SPRINTF(filename, _nc_SLIMIT(limit) "%s%s", path, suffix);
611         result = TRUE;
612     }
613     return result;
614 }
615 #endif
616
617 /*
618  * Return true if we can build the name of a filesystem entry.
619  */
620 static bool
621 make_dir_filename(char *filename,
622                   unsigned limit,
623                   const char *const path,
624                   const char *name)
625 {
626     bool result = FALSE;
627
628 #if NCURSES_USE_TERMCAP
629     if (_nc_is_dir_path(path))
630 #endif
631     {
632         unsigned need = (unsigned) (LEAF_LEN + 3 + strlen(path) + strlen(name));
633
634         if (need <= limit) {
635             _nc_SPRINTF(filename, _nc_SLIMIT(limit)
636                         "%s/" LEAF_FMT "/%s", path, *name, name);
637             result = TRUE;
638         }
639     }
640     return result;
641 }
642
643 static int
644 lookup_b64(int *target, const char **source)
645 {
646     int result = 3;
647     int j;
648     /*
649      * ncurses' quickdump writes only RFC 4648 "url/filename-safe" encoding,
650      * but accepts RFC-3548
651      */
652     for (j = 0; j < 4; ++j) {
653         int ch = UChar(**source);
654         *source += 1;
655         if (ch >= 'A' && ch <= 'Z') {
656             target[j] = (ch - 'A');
657         } else if (ch >= 'a' && ch <= 'z') {
658             target[j] = 26 + (ch - 'a');
659         } else if (ch >= '0' && ch <= '9') {
660             target[j] = 52 + (ch - '0');
661         } else if (ch == '-' || ch == '+') {
662             target[j] = 62;
663         } else if (ch == '_' || ch == '/') {
664             target[j] = 63;
665         } else if (ch == '=') {
666             target[j] = 64;
667             result--;
668         } else {
669             result = -1;
670             break;
671         }
672     }
673     return result;
674 }
675
676 static int
677 decode_hex(const char **source)
678 {
679     int result = 0;
680     int nibble;
681
682     for (nibble = 0; nibble < 2; ++nibble) {
683         int ch = UChar(**source);
684         result <<= 4;
685         *source += 1;
686         if (ch >= '0' && ch <= '9') {
687             ch -= '0';
688         } else if (ch >= 'A' && ch <= 'F') {
689             ch -= 'A';
690             ch += 10;
691         } else if (ch >= 'a' && ch <= 'f') {
692             ch -= 'a';
693             ch += 10;
694         } else {
695             result = -1;
696             break;
697         }
698         result |= ch;
699     }
700     return result;
701 }
702
703 static int
704 decode_quickdump(char *target, const char *source)
705 {
706     char *base = target;
707     int result = 0;
708
709     if (!strncmp(source, "b64:", (size_t) 4)) {
710         source += 4;
711         while (*source != '\0') {
712             int bits[4];
713             int ch = lookup_b64(bits, &source);
714             if (ch < 0 || (ch + target - base) >= MAX_ENTRY_SIZE) {
715                 result = 0;
716                 break;
717             }
718             result += ch;
719             *target++ = (char) ((bits[0] << 2) | (bits[1] >> 4));
720             if (bits[2] < 64) {
721                 *target++ = (char) ((bits[1] << 4) | (bits[2] >> 2));
722                 if (bits[3] < 64) {
723                     *target++ = (char) ((bits[2] << 6) | bits[3]);
724                 }
725             }
726         }
727     } else if (!strncmp(source, "hex:", (size_t) 4)) {
728         source += 4;
729         while (*source != '\0') {
730             int ch = decode_hex(&source);
731             if (ch < 0 || (target - base) >= MAX_ENTRY_SIZE) {
732                 result = 0;
733                 break;
734             }
735             *target++ = (char) ch;
736             ++result;
737         }
738     }
739     return result;
740 }
741
742 /*
743  * Build a terminfo pathname and try to read the data.  Returns TGETENT_YES on
744  * success, TGETENT_NO on failure.
745  */
746 static int
747 _nc_read_tic_entry(char *filename,
748                    unsigned limit,
749                    const char *const path,
750                    const char *name,
751                    TERMTYPE2 *const tp)
752 {
753     int code = TGETENT_NO;
754 #if USE_HASHED_DB
755     DB *capdbp;
756 #endif
757     char buffer[MAX_ENTRY_SIZE + 1];
758     int used;
759
760     TR(TRACE_DATABASE,
761        (T_CALLED("_nc_read_tic_entry(file=%p, path=%s, name=%s)"),
762         filename, path, name));
763
764     assert(TGETENT_YES == TRUE);        /* simplify call for _nc_name_match */
765
766     if ((used = decode_quickdump(buffer, path)) != 0
767         && (code = _nc_read_termtype(tp, buffer, used)) == TGETENT_YES
768         && (code = _nc_name_match(tp->term_names, name, "|")) == TGETENT_YES) {
769         TR(TRACE_DATABASE, ("loaded quick-dump for %s", name));
770         /* shorten name shown by infocmp */
771         _nc_STRCPY(filename, "$TERMINFO", limit);
772     } else
773 #if USE_HASHED_DB
774         if (make_db_filename(filename, limit, path)
775             && (capdbp = _nc_db_open(filename, FALSE)) != 0) {
776
777         DBT key, data;
778         int reccnt = 0;
779         char *save = strdup(name);
780
781         memset(&key, 0, sizeof(key));
782         key.data = save;
783         key.size = strlen(save);
784
785         /*
786          * This lookup could return termcap data, which we do not want.  We are
787          * looking for compiled (binary) terminfo data.
788          *
789          * cgetent uses a two-level lookup.  On the first it uses the given
790          * name to return a record containing only the aliases for an entry.
791          * On the second (using that list of aliases as a key), it returns the
792          * content of the terminal description.  We expect second lookup to
793          * return data beginning with the same set of aliases.
794          *
795          * For compiled terminfo, the list of aliases in the second case will
796          * be null-terminated.  A termcap entry will not be, and will run on
797          * into the description.  So we can easily distinguish between the two
798          * (source/binary) by checking the lengths.
799          */
800         while (_nc_db_get(capdbp, &key, &data) == 0) {
801             char *have = (char *) data.data;
802             used = (int) data.size - 1;
803
804             if (*have++ == 0) {
805                 if (data.size > key.size
806                     && IS_TIC_MAGIC(have)) {
807                     code = _nc_read_termtype(tp, have, used);
808                     if (code == TGETENT_NO) {
809                         _nc_free_termtype2(tp);
810                     }
811                 }
812                 break;
813             }
814
815             /*
816              * Just in case we have a corrupt database, do not waste time with
817              * it.
818              */
819             if (++reccnt >= 3)
820                 break;
821
822             /*
823              * Prepare for the second level.
824              */
825             key.data = have;
826             key.size = used;
827         }
828
829         free(save);
830     } else                      /* may be either filesystem or flat file */
831 #endif
832     if (make_dir_filename(filename, limit, path, name)) {
833         code = _nc_read_file_entry(filename, tp);
834     }
835 #if NCURSES_USE_TERMCAP
836     if (code != TGETENT_YES) {
837         code = _nc_read_termcap_entry(name, tp);
838         _nc_SPRINTF(filename, _nc_SLIMIT(PATH_MAX)
839                     "%.*s", PATH_MAX - 1, _nc_get_source());
840     }
841 #endif
842     returnDB(code);
843 }
844 #endif /* NCURSES_USE_DATABASE */
845
846 /*
847  * Find and read the compiled entry for a given terminal type, if it exists.
848  * We take pains here to make sure no combination of environment variables and
849  * terminal type name can be used to overrun the file buffer.
850  */
851 NCURSES_EXPORT(int)
852 _nc_read_entry2(const char *const name, char *const filename, TERMTYPE2 *const tp)
853 {
854     int code = TGETENT_NO;
855
856     if (name == 0)
857         return _nc_read_entry2("", filename, tp);
858
859     _nc_SPRINTF(filename, _nc_SLIMIT(PATH_MAX)
860                 "%.*s", PATH_MAX - 1, name);
861
862     if (strlen(name) == 0
863         || strcmp(name, ".") == 0
864         || strcmp(name, "..") == 0
865         || _nc_pathlast(name) != 0
866         || strchr(name, NCURSES_PATHSEP) != 0) {
867         TR(TRACE_DATABASE, ("illegal or missing entry name '%s'", name));
868     } else {
869 #if NCURSES_USE_DATABASE
870         DBDIRS state;
871         int offset;
872         const char *path;
873
874         _nc_first_db(&state, &offset);
875         code = TGETENT_ERR;
876         while ((path = _nc_next_db(&state, &offset)) != 0) {
877             code = _nc_read_tic_entry(filename, PATH_MAX, path, name, tp);
878             if (code == TGETENT_YES) {
879                 _nc_last_db();
880                 break;
881             }
882         }
883 #elif NCURSES_USE_TERMCAP
884         if (code != TGETENT_YES) {
885             code = _nc_read_termcap_entry(name, tp);
886             _nc_SPRINTF(filename, _nc_SLIMIT(PATH_MAX)
887                         "%.*s", PATH_MAX - 1, _nc_get_source());
888         }
889 #endif
890     }
891     return code;
892 }
893
894 #if NCURSES_EXT_NUMBERS
895 /*
896  * This entrypoint is used by tack 1.07
897  */
898 NCURSES_EXPORT(int)
899 _nc_read_entry(const char *const name, char *const filename, TERMTYPE *const tp)
900 {
901     TERMTYPE2 dummy;
902     int rc;
903     rc = _nc_read_entry2(name, filename, &dummy);
904     if (rc == TGETENT_YES)
905         _nc_export_termtype2(tp, &dummy);
906     return rc;
907 }
908 #endif