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