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