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