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