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