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