xref: /openbsd-src/lib/libcurses/tinfo/read_entry.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: read_entry.c,v 1.12 2001/01/22 18:01:55 millert Exp $	*/
2 
3 /****************************************************************************
4  * Copyright (c) 1998,1999,2000 Free Software Foundation, Inc.              *
5  *                                                                          *
6  * Permission is hereby granted, free of charge, to any person obtaining a  *
7  * copy of this software and associated documentation files (the            *
8  * "Software"), to deal in the Software without restriction, including      *
9  * without limitation the rights to use, copy, modify, merge, publish,      *
10  * distribute, distribute with modifications, sublicense, and/or sell       *
11  * copies of the Software, and to permit persons to whom the Software is    *
12  * furnished to do so, subject to the following conditions:                 *
13  *                                                                          *
14  * The above copyright notice and this permission notice shall be included  *
15  * in all copies or substantial portions of the Software.                   *
16  *                                                                          *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
20  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
23  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
24  *                                                                          *
25  * Except as contained in this notice, the name(s) of the above copyright   *
26  * holders shall not be used in advertising or otherwise to promote the     *
27  * sale, use or other dealings in this Software without prior written       *
28  * authorization.                                                           *
29  ****************************************************************************/
30 
31 /****************************************************************************
32  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
33  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
34  ****************************************************************************/
35 
36 /*
37  *	read_entry.c -- Routine for reading in a compiled terminfo file
38  *
39  */
40 
41 #include <curses.priv.h>
42 
43 #include <tic.h>
44 #include <term_entry.h>
45 
46 MODULE_ID("$From: read_entry.c,v 1.72 2000/12/10 02:55:08 tom Exp $")
47 
48 #if !HAVE_TELL
49 #define tell(fd) 0		/* lseek() is POSIX, but not tell() - odd... */
50 #endif
51 
52 /*
53  *	int
54  *	_nc_read_file_entry(filename, ptr)
55  *
56  *	Read the compiled terminfo entry in the given file into the
57  *	structure pointed to by ptr, allocating space for the string
58  *	table.
59  */
60 
61 #undef  BYTE
62 #define BYTE(p,n)	(unsigned char)((p)[n])
63 
64 #define IS_NEG1(p)	((BYTE(p,0) == 0377) && (BYTE(p,1) == 0377))
65 #define IS_NEG2(p)	((BYTE(p,0) == 0376) && (BYTE(p,1) == 0377))
66 #define LOW_MSB(p)	(BYTE(p,0) + 256*BYTE(p,1))
67 
68 static bool have_tic_directory = FALSE;
69 static bool keep_tic_directory = FALSE;
70 
71 /*
72  * Record the "official" location of the terminfo directory, according to
73  * the place where we're writing to, or the normal default, if not.
74  */
75 NCURSES_EXPORT(const char *)
76 _nc_tic_dir(const char *path)
77 {
78     static const char *result = TERMINFO;
79 
80     if (!keep_tic_directory) {
81 	if (path != 0) {
82 	    result = path;
83 	    have_tic_directory = TRUE;
84 	} else if (!have_tic_directory && use_terminfo_vars()) {
85 	    char *envp;
86 	    if ((envp = getenv("TERMINFO")) != 0)
87 		return _nc_tic_dir(envp);
88 	}
89     }
90     return result;
91 }
92 
93 /*
94  * Special fix to prevent the terminfo directory from being moved after tic
95  * has chdir'd to it.  If we let it be changed, then if $TERMINFO has a
96  * relative path, we'll lose track of the actual directory.
97  */
98 NCURSES_EXPORT(void)
99 _nc_keep_tic_dir(const char *path)
100 {
101     _nc_tic_dir(path);
102     keep_tic_directory = TRUE;
103 }
104 
105 static void
106 convert_shorts(char *buf, short *Numbers, int count)
107 {
108     int i;
109     for (i = 0; i < count; i++) {
110 	if (IS_NEG1(buf + 2 * i))
111 	    Numbers[i] = ABSENT_NUMERIC;
112 	else if (IS_NEG2(buf + 2 * i))
113 	    Numbers[i] = CANCELLED_NUMERIC;
114 	else
115 	    Numbers[i] = LOW_MSB(buf + 2 * i);
116 	TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
117     }
118 }
119 
120 static void
121 convert_strings(char *buf, char **Strings, int count, int size, char *table)
122 {
123     int i;
124     char *p;
125 
126     for (i = 0; i < count; i++) {
127 	if (IS_NEG1(buf + 2 * i)) {
128 	    Strings[i] = ABSENT_STRING;
129 	} else if (IS_NEG2(buf + 2 * i)) {
130 	    Strings[i] = CANCELLED_STRING;
131 	} else if (LOW_MSB(buf + 2 * i) > size) {
132 	    Strings[i] = ABSENT_STRING;
133 	} else {
134 	    Strings[i] = (LOW_MSB(buf + 2 * i) + table);
135 	    TR(TRACE_DATABASE, ("Strings[%d] = %s", i, _nc_visbuf(Strings[i])));
136 	}
137 
138 	/* make sure all strings are NUL terminated */
139 	if (VALID_STRING(Strings[i])) {
140 	    for (p = Strings[i]; p <= table + size; p++)
141 		if (*p == '\0')
142 		    break;
143 	    /* if there is no NUL, ignore the string */
144 	    if (p > table + size)
145 		Strings[i] = ABSENT_STRING;
146 	}
147     }
148 }
149 
150 #define read_shorts(fd, buf, count) (read(fd, buf, (count)*2) == (count)*2)
151 
152 #define even_boundary(value) \
153     if ((value) % 2 != 0) read(fd, buf, 1)
154 
155 static int
156 read_termtype(int fd, TERMTYPE * ptr)
157 /* return 1 if read, 0 if not found or garbled */
158 {
159     int name_size, bool_count, num_count, str_count, str_size;
160     int i;
161     char buf[MAX_ENTRY_SIZE];
162 
163     TR(TRACE_DATABASE, ("READ termtype header @%d", tell(fd)));
164 
165     memset(ptr, 0, sizeof(*ptr));
166 
167     /* grab the header */
168     if (!read_shorts(fd, buf, 6)
169 	|| LOW_MSB(buf) != MAGIC) {
170 	return (0);
171     }
172 
173     _nc_free_termtype(ptr);
174     name_size = LOW_MSB(buf + 2);
175     bool_count = LOW_MSB(buf + 4);
176     num_count = LOW_MSB(buf + 6);
177     str_count = LOW_MSB(buf + 8);
178     str_size = LOW_MSB(buf + 10);
179 
180     TR(TRACE_DATABASE,
181        ("TERMTYPE name_size=%d, bool=%d/%d, num=%d/%d str=%d/%d(%d)",
182 	name_size, bool_count, BOOLCOUNT, num_count, NUMCOUNT,
183 	str_count, STRCOUNT, str_size));
184     if (name_size < 0
185 	|| bool_count < 0
186 	|| num_count < 0
187 	|| str_count < 0
188 	|| str_size < 0) {
189 	return (0);
190     }
191 
192     if (str_size) {
193 	/* try to allocate space for the string table */
194 	if (str_count * 2 >= (int) sizeof(buf)
195 	    || (ptr->str_table = typeMalloc(char, (unsigned) str_size)) == 0) {
196 	    return (0);
197 	}
198     } else {
199 	str_count = 0;
200     }
201 
202     /* grab the name (a null-terminate string) */
203     read(fd, buf, min(MAX_NAME_SIZE, (unsigned) name_size));
204     buf[MAX_NAME_SIZE] = '\0';
205     ptr->term_names = typeCalloc(char, strlen(buf) + 1);
206     if (ptr->term_names == NULL) {
207 	return (0);
208     }
209     (void) strcpy(ptr->term_names, buf);
210     if (name_size > MAX_NAME_SIZE)
211 	lseek(fd, (off_t) (name_size - MAX_NAME_SIZE), 1);
212 
213     /* grab the booleans */
214     if ((ptr->Booleans = typeCalloc(char, max(BOOLCOUNT, bool_count))) == 0
215 	|| read(fd, ptr->Booleans, (unsigned) bool_count) < bool_count) {
216 	return (0);
217     }
218 
219     /*
220      * If booleans end on an odd byte, skip it.  The machine they
221      * originally wrote terminfo on must have been a 16-bit
222      * word-oriented machine that would trap out if you tried a
223      * word access off a 2-byte boundary.
224      */
225     even_boundary(name_size + bool_count);
226 
227     /* grab the numbers */
228     if ((ptr->Numbers = typeCalloc(short, max(NUMCOUNT, num_count))) == 0
229 	|| !read_shorts(fd, buf, num_count)) {
230 	return (0);
231     }
232     convert_shorts(buf, ptr->Numbers, num_count);
233 
234     if ((ptr->Strings = typeCalloc(char *, max(STRCOUNT, str_count))) == 0)
235 	  return (0);
236 
237     if (str_count) {
238 	/* grab the string offsets */
239 	if (!read_shorts(fd, buf, str_count)) {
240 	    return (0);
241 	}
242 	/* finally, grab the string table itself */
243 	if (read(fd, ptr->str_table, (unsigned) str_size) != str_size)
244 	    return (0);
245 	convert_strings(buf, ptr->Strings, str_count, str_size, ptr->str_table);
246     }
247 #if NCURSES_XNAMES
248 
249     ptr->num_Booleans = BOOLCOUNT;
250     ptr->num_Numbers = NUMCOUNT;
251     ptr->num_Strings = STRCOUNT;
252 
253     /*
254      * Read extended entries, if any, after the normal end of terminfo data.
255      */
256     even_boundary(str_size);
257     TR(TRACE_DATABASE, ("READ extended_header @%d", tell(fd)));
258     if (_nc_user_definable && read_shorts(fd, buf, 5)) {
259 	int ext_bool_count = LOW_MSB(buf + 0);
260 	int ext_num_count = LOW_MSB(buf + 2);
261 	int ext_str_count = LOW_MSB(buf + 4);
262 	int ext_str_size = LOW_MSB(buf + 6);
263 	int ext_str_limit = LOW_MSB(buf + 8);
264 	int need = (ext_bool_count + ext_num_count + ext_str_count);
265 	int base = 0;
266 
267 	if (need >= (int) sizeof(buf)
268 	    || ext_str_size >= (int) sizeof(buf)
269 	    || ext_str_limit >= (int) sizeof(buf)
270 	    || ext_bool_count < 0
271 	    || ext_num_count < 0
272 	    || ext_str_count < 0
273 	    || ext_str_size < 0
274 	    || ext_str_limit < 0)
275 	    return (0);
276 
277 	ptr->num_Booleans = BOOLCOUNT + ext_bool_count;
278 	ptr->num_Numbers = NUMCOUNT + ext_num_count;
279 	ptr->num_Strings = STRCOUNT + ext_str_count;
280 
281 	ptr->Booleans = typeRealloc(char, ptr->num_Booleans, ptr->Booleans);
282 	ptr->Numbers = typeRealloc(short, ptr->num_Numbers, ptr->Numbers);
283 	ptr->Strings = typeRealloc(char *, ptr->num_Strings, ptr->Strings);
284 
285 	TR(TRACE_DATABASE, ("extended header is %d/%d/%d(%d:%d)",
286 			    ext_bool_count, ext_num_count, ext_str_count,
287 			    ext_str_size, ext_str_limit));
288 
289 	TR(TRACE_DATABASE, ("READ %d extended-booleans @%d",
290 			    ext_bool_count, tell(fd)));
291 	if ((ptr->ext_Booleans = ext_bool_count) != 0) {
292 	    if (read(fd, ptr->Booleans + BOOLCOUNT, (unsigned)
293 		     ext_bool_count) != ext_bool_count)
294 		return (0);
295 	}
296 	even_boundary(ext_bool_count);
297 
298 	TR(TRACE_DATABASE, ("READ %d extended-numbers @%d",
299 			    ext_num_count, tell(fd)));
300 	if ((ptr->ext_Numbers = ext_num_count) != 0) {
301 	    if (!read_shorts(fd, buf, ext_num_count))
302 		return (0);
303 	    TR(TRACE_DATABASE, ("Before converting extended-numbers"));
304 	    convert_shorts(buf, ptr->Numbers + NUMCOUNT, ext_num_count);
305 	}
306 
307 	TR(TRACE_DATABASE, ("READ extended-offsets @%d", tell(fd)));
308 	if ((ext_str_count || need)
309 	    && !read_shorts(fd, buf, ext_str_count + need))
310 	    return (0);
311 
312 	TR(TRACE_DATABASE, ("READ %d bytes of extended-strings @%d",
313 			    ext_str_limit, tell(fd)));
314 
315 	if (ext_str_limit) {
316 	    if ((ptr->ext_str_table = typeMalloc(char, ext_str_limit)) == 0)
317 		  return (0);
318 	    if (read(fd, ptr->ext_str_table, ext_str_limit) != ext_str_limit)
319 		return (0);
320 	    TR(TRACE_DATABASE, ("first extended-string is %s", _nc_visbuf(ptr->ext_str_table)));
321 	}
322 
323 	if ((ptr->ext_Strings = ext_str_count) != 0) {
324 	    TR(TRACE_DATABASE,
325 	       ("Before computing extended-string capabilities str_count=%d, ext_str_count=%d",
326 		str_count, ext_str_count));
327 	    convert_strings(buf, ptr->Strings + str_count, ext_str_count,
328 			    ext_str_limit, ptr->ext_str_table);
329 	    for (i = ext_str_count - 1; i >= 0; i--) {
330 		TR(TRACE_DATABASE, ("MOVE from [%d:%d] %s",
331 				    i, i + str_count,
332 				    _nc_visbuf(ptr->Strings[i + str_count])));
333 		ptr->Strings[i + STRCOUNT] = ptr->Strings[i + str_count];
334 		if (VALID_STRING(ptr->Strings[i + STRCOUNT]))
335 		    base += (strlen(ptr->Strings[i + STRCOUNT]) + 1);
336 		TR(TRACE_DATABASE, ("... to    [%d] %s",
337 				    i + STRCOUNT,
338 				    _nc_visbuf(ptr->Strings[i + STRCOUNT])));
339 	    }
340 	}
341 
342 	if (need) {
343 	    if ((ptr->ext_Names = typeCalloc(char *, need)) == 0)
344 		  return (0);
345 	    TR(TRACE_DATABASE,
346 	       ("ext_NAMES starting @%d in extended_strings, first = %s",
347 		base, _nc_visbuf(ptr->ext_str_table + base)));
348 	    convert_strings(buf + (2 * ext_str_count), ptr->ext_Names, need,
349 			    ext_str_limit, ptr->ext_str_table + base);
350 	}
351 
352 	T(("...done reading terminfo bool %d(%d) num %d(%d) str %d(%d)",
353 	   ptr->num_Booleans, ptr->ext_Booleans,
354 	   ptr->num_Numbers, ptr->ext_Numbers,
355 	   ptr->num_Strings, ptr->ext_Strings));
356 
357 	TR(TRACE_DATABASE, ("extend: num_Booleans:%d", ptr->num_Booleans));
358     } else
359 #endif /* NCURSES_XNAMES */
360     {
361 	T(("...done reading terminfo bool %d num %d str %d",
362 	   bool_count, num_count, str_count));
363 #if NCURSES_XNAMES
364 	TR(TRACE_DATABASE, ("normal: num_Booleans:%d", ptr->num_Booleans));
365 #endif
366     }
367 
368     for (i = bool_count; i < BOOLCOUNT; i++)
369 	ptr->Booleans[i] = FALSE;
370     for (i = num_count; i < NUMCOUNT; i++)
371 	ptr->Numbers[i] = ABSENT_NUMERIC;
372     for (i = str_count; i < STRCOUNT; i++)
373 	ptr->Strings[i] = ABSENT_STRING;
374 
375     return (1);
376 }
377 
378 NCURSES_EXPORT(int)
379 _nc_read_file_entry
380 (const char *const filename, TERMTYPE * ptr)
381 /* return 1 if read, 0 if not found or garbled */
382 {
383     int code, fd = -1;
384 
385 #ifdef __OpenBSD__
386     if (_nc_read_bsd_terminfo_file(filename, ptr) == 1)
387 	return (1);
388 #endif /* __OpenBSD__ */
389 
390     if (_nc_access(filename, R_OK) < 0
391 	|| (fd = open(filename, O_RDONLY | O_BINARY)) < 0) {
392 	T(("cannot open terminfo %s (errno=%d)", filename, errno));
393 	return (0);
394     }
395 
396     T(("read terminfo %s", filename));
397     if ((code = read_termtype(fd, ptr)) == 0)
398 	_nc_free_termtype(ptr);
399     close(fd);
400 
401     return (code);
402 }
403 
404 /*
405  * Build a terminfo pathname and try to read the data.  Returns 1 on success,
406  * 0 on failure.
407  */
408 static int
409 _nc_read_tic_entry(char *const filename,
410 		   const char *const dir, const char *ttn, TERMTYPE * const tp)
411 {
412 /* maximum safe length of terminfo root directory name */
413 #define MAX_TPATH	(PATH_MAX - MAX_ALIAS - 6)
414 
415     if (strlen(dir) > MAX_TPATH)
416 	return 0;
417     (void) sprintf(filename, "%s/%s", dir, ttn);
418     return _nc_read_file_entry(filename, tp);
419 }
420 
421 /*
422  * Process the list of :-separated directories, looking for the terminal type.
423  * We don't use strtok because it does not show us empty tokens.
424  */
425 static int
426 _nc_read_terminfo_dirs(const char *dirs, char *const filename, const char *const
427 		       ttn, TERMTYPE * const tp)
428 {
429     char *list, *a;
430     const char *b;
431     int code = 0;
432 
433     /* we'll modify the argument, so we must copy */
434     if ((b = a = list = strdup(dirs)) == NULL)
435 	return (0);
436 
437     for (;;) {
438 	int c = *a;
439 	if (c == 0 || c == NCURSES_PATHSEP) {
440 	    *a = 0;
441 	    if ((b + 1) >= a)
442 		b = TERMINFO;
443 	    if (_nc_read_tic_entry(filename, b, ttn, tp) == 1) {
444 		code = 1;
445 		break;
446 	    }
447 	    b = a + 1;
448 	    if (c == 0)
449 		break;
450 	}
451 	a++;
452     }
453 
454     free(list);
455     return (code);
456 }
457 
458 /*
459  *	_nc_read_entry(char *tn, char *filename, TERMTYPE *tp)
460  *
461  *	Find and read the compiled entry for a given terminal type,
462  *	if it exists.  We take pains here to make sure no combination
463  *	of environment variables and terminal type name can be used to
464  *	overrun the file buffer.
465  */
466 
467 NCURSES_EXPORT(int)
468 _nc_read_entry
469 (const char *const tn, char *const filename, TERMTYPE * const tp)
470 {
471     char *envp;
472     char ttn[MAX_ALIAS + 3];
473 
474 #ifdef __OpenBSD__
475     /* First check the BSD terminfo.db file */
476     if (_nc_read_bsd_terminfo_entry(tn, filename, tp) == 1)
477 	return (1);
478 #endif /* __OpenBSD__ */
479 
480     /* truncate the terminal name to prevent dangerous buffer airline */
481     (void) sprintf(ttn, "%c/%.*s", *tn, MAX_ALIAS, tn);
482 
483     /* This is System V behavior, in conjunction with our requirements for
484      * writing terminfo entries.
485      */
486     if (have_tic_directory
487 	&& _nc_read_tic_entry(filename, _nc_tic_dir(0), ttn, tp) == 1)
488 	return 1;
489 
490     if (use_terminfo_vars()) {
491 	if ((envp = getenv("TERMINFO")) != 0
492 	    && _nc_read_tic_entry(filename, _nc_tic_dir(envp), ttn, tp) == 1)
493 	    return 1;
494 
495 	/* this is an ncurses extension */
496 	if ((envp = _nc_home_terminfo()) != 0) {
497 	    if (_nc_read_tic_entry(filename, envp, ttn, tp) == 1) {
498 		return (1);
499 	    }
500 	}
501 
502 	/* this is an ncurses extension */
503 	if ((envp = getenv("TERMINFO_DIRS")) != 0)
504 	    return _nc_read_terminfo_dirs(envp, filename, ttn, tp);
505     }
506 
507     /* Try the system directory.  Note that the TERMINFO_DIRS value, if
508      * defined by the configure script, begins with a ":", which will be
509      * interpreted as TERMINFO.
510      */
511 #ifdef TERMINFO_DIRS
512     return _nc_read_terminfo_dirs(TERMINFO_DIRS, filename, ttn, tp);
513 #else
514     return _nc_read_tic_entry(filename, TERMINFO, ttn, tp);
515 #endif
516 }
517