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