]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/read_entry.c
ncurses 6.4 - patch 20230408
[ncurses.git] / ncurses / tinfo / read_entry.c
1 /****************************************************************************
2  * Copyright 2018-2022,2023 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.165 2023/04/08 20:14:49 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)"), (void *) 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         || bool_count > BOOLCOUNT
327         || num_count > NUMCOUNT
328         || str_count > STRCOUNT
329         || str_size < 0) {
330         returnDB(TGETENT_NO);
331     }
332
333     want = (unsigned) (str_size + name_size + 1);
334     /* try to allocate space for the string table */
335     if (str_count * SIZEOF_SHORT >= max_entry_size
336         || (string_table = typeMalloc(char, want)) == 0) {
337         returnDB(TGETENT_NO);
338     }
339
340     /* grab the name (a null-terminated string) */
341     want = min(MAX_NAME_SIZE, (unsigned) name_size);
342     ptr->str_table = string_table;
343     ptr->term_names = string_table;
344     if ((have = (unsigned) Read(ptr->term_names, want)) != want) {
345         memset(ptr->term_names + have, 0, (size_t) (want - have));
346     }
347     ptr->term_names[want] = '\0';
348     string_table += (want + 1);
349
350     if (have > MAX_NAME_SIZE)
351         offset = (int) (have - MAX_NAME_SIZE);
352
353     /* grab the booleans */
354     TYPE_CALLOC(NCURSES_SBOOL, max(BOOLCOUNT, bool_count), ptr->Booleans);
355     if (Read(ptr->Booleans, (unsigned) bool_count) < bool_count) {
356         returnDB(TGETENT_NO);
357     }
358
359     /*
360      * If booleans end on an odd byte, skip it.  The machine they
361      * originally wrote terminfo on must have been a 16-bit
362      * word-oriented machine that would trap out if you tried a
363      * word access off a 2-byte boundary.
364      */
365     even_boundary(name_size + bool_count);
366
367     /* grab the numbers */
368     TYPE_CALLOC(NCURSES_INT2, max(NUMCOUNT, num_count), ptr->Numbers);
369     if (!read_numbers(buf, num_count)) {
370         returnDB(TGETENT_NO);
371     }
372     convert_numbers(buf, ptr->Numbers, num_count);
373
374     TYPE_CALLOC(char *, max(STRCOUNT, str_count), ptr->Strings);
375
376     if (str_count) {
377         /* grab the string offsets */
378         if (!read_shorts(buf, str_count)) {
379             returnDB(TGETENT_NO);
380         }
381         /* finally, grab the string table itself */
382         if (Read(string_table, (unsigned) str_size) != str_size) {
383             returnDB(TGETENT_NO);
384         }
385         convert_strings(buf, ptr->Strings, str_count, str_size, string_table);
386     }
387 #if NCURSES_XNAMES
388
389     ptr->num_Booleans = BOOLCOUNT;
390     ptr->num_Numbers = NUMCOUNT;
391     ptr->num_Strings = STRCOUNT;
392
393     /*
394      * Read extended entries, if any, after the normal end of terminfo data.
395      */
396     even_boundary(str_size);
397     TR(TRACE_DATABASE, ("READ extended_header @%d", offset));
398     if (_nc_user_definable && read_shorts(buf, 5) && valid_shorts(buf, 5)) {
399         int ext_bool_count = MyNumber(buf + 0);
400         int ext_num_count = MyNumber(buf + 2);
401         int ext_str_count = MyNumber(buf + 4);
402         int ext_str_usage = MyNumber(buf + 6);
403         int ext_str_limit = MyNumber(buf + 8);
404         unsigned need = (unsigned) (ext_bool_count + ext_num_count + ext_str_count);
405         int base = 0;
406
407         if ((int) need >= (max_entry_size / 2)
408             || ext_str_usage >= max_entry_size
409             || ext_str_limit >= max_entry_size
410             || ext_bool_count < 0
411             || ext_num_count < 0
412             || ext_str_count < 0
413             || ext_str_usage < 0
414             || ext_str_limit < 0) {
415             returnDB(TGETENT_NO);
416         }
417
418         ptr->num_Booleans = UShort(BOOLCOUNT + ext_bool_count);
419         ptr->num_Numbers = UShort(NUMCOUNT + ext_num_count);
420         ptr->num_Strings = UShort(STRCOUNT + ext_str_count);
421
422         TYPE_REALLOC(NCURSES_SBOOL, ptr->num_Booleans, ptr->Booleans);
423         TYPE_REALLOC(NCURSES_INT2, ptr->num_Numbers, ptr->Numbers);
424         TYPE_REALLOC(char *, ptr->num_Strings, ptr->Strings);
425
426         TR(TRACE_DATABASE, ("extended header: "
427                             "bool %d, "
428                             "number %d, "
429                             "string %d(%d:%d)",
430                             ext_bool_count,
431                             ext_num_count,
432                             ext_str_count,
433                             ext_str_usage,
434                             ext_str_limit));
435
436         TR(TRACE_DATABASE, ("READ %d extended-booleans @%d",
437                             ext_bool_count, offset));
438         if ((ptr->ext_Booleans = UShort(ext_bool_count)) != 0) {
439             if (Read(ptr->Booleans + BOOLCOUNT, (unsigned)
440                      ext_bool_count) != ext_bool_count) {
441                 returnDB(TGETENT_NO);
442             }
443         }
444         even_boundary(ext_bool_count);
445
446         TR(TRACE_DATABASE, ("READ %d extended-numbers @%d",
447                             ext_num_count, offset));
448         if ((ptr->ext_Numbers = UShort(ext_num_count)) != 0) {
449             if (!read_numbers(buf, ext_num_count)) {
450                 returnDB(TGETENT_NO);
451             }
452             TR(TRACE_DATABASE, ("Before converting extended-numbers"));
453             convert_numbers(buf, ptr->Numbers + NUMCOUNT, ext_num_count);
454         }
455
456         TR(TRACE_DATABASE, ("READ extended-offsets @%d", offset));
457         if ((ext_str_count + (int) need) >= (max_entry_size / 2)) {
458             returnDB(TGETENT_NO);
459         }
460         if ((ext_str_count || need)
461             && !read_shorts(buf, ext_str_count + (int) need)) {
462             returnDB(TGETENT_NO);
463         }
464
465         TR(TRACE_DATABASE, ("READ %d bytes of extended-strings @%d",
466                             ext_str_limit, offset));
467
468         if (ext_str_limit) {
469             ptr->ext_str_table = typeMalloc(char, (size_t) ext_str_limit);
470             if (ptr->ext_str_table == 0) {
471                 returnDB(TGETENT_NO);
472             }
473             if (Read(ptr->ext_str_table, (unsigned) ext_str_limit) != ext_str_limit) {
474                 returnDB(TGETENT_NO);
475             }
476             TR(TRACE_DATABASE, ("first extended-string is %s", _nc_visbuf(ptr->ext_str_table)));
477         }
478
479         if ((ptr->ext_Strings = UShort(ext_str_count)) != 0) {
480             int check = (ext_bool_count + ext_num_count + ext_str_count);
481
482             TR(TRACE_DATABASE,
483                ("Before computing extended-string capabilities "
484                 "str_count=%d, ext_str_count=%d",
485                 str_count, ext_str_count));
486             convert_strings(buf, ptr->Strings + str_count, ext_str_count,
487                             ext_str_limit, ptr->ext_str_table);
488             for (i = ext_str_count - 1; i >= 0; i--) {
489                 TR(TRACE_DATABASE, ("MOVE from [%d:%d] %s",
490                                     i, i + str_count,
491                                     _nc_visbuf(ptr->Strings[i + str_count])));
492                 ptr->Strings[i + STRCOUNT] = ptr->Strings[i + str_count];
493                 if (VALID_STRING(ptr->Strings[i + STRCOUNT])) {
494                     base += (int) (strlen(ptr->Strings[i + STRCOUNT]) + 1);
495                     ++check;
496                 }
497                 TR(TRACE_DATABASE, ("... to    [%d] %s",
498                                     i + STRCOUNT,
499                                     _nc_visbuf(ptr->Strings[i + STRCOUNT])));
500             }
501             TR(TRACE_DATABASE, ("Check table-size: %d/%d", check, ext_str_usage));
502 #if 0
503             /*
504              * Phasing in a proper check will be done "later".
505              */
506             if (check != ext_str_usage)
507                 returnDB(TGETENT_NO);
508 #endif
509         }
510
511         if (need) {
512             if (ext_str_count >= (max_entry_size / 2)) {
513                 returnDB(TGETENT_NO);
514             }
515             TYPE_CALLOC(char *, need, ptr->ext_Names);
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