read_entry.c revision 1.16
1/* $OpenBSD: read_entry.c,v 1.16 2010/01/12 23:22:06 nicm Exp $ */
2
3/****************************************************************************
4 * Copyright (c) 1998-2007,2008 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 *     and: Thomas E. Dickey                        1996-on                 *
35 ****************************************************************************/
36
37/*
38 *	read_entry.c -- Routine for reading in a compiled terminfo file
39 */
40
41#include <curses.priv.h>
42#include <hashed_db.h>
43
44#include <tic.h>
45#include <term_entry.h>
46
47MODULE_ID("$Id: read_entry.c,v 1.16 2010/01/12 23:22:06 nicm Exp $")
48
49#define TYPE_CALLOC(type,elts) typeCalloc(type, (unsigned)(elts))
50
51#if USE_DATABASE
52static void
53convert_shorts(char *buf, short *Numbers, int count)
54{
55    int i;
56    for (i = 0; i < count; i++) {
57	if (IS_NEG1(buf + 2 * i))
58	    Numbers[i] = ABSENT_NUMERIC;
59	else if (IS_NEG2(buf + 2 * i))
60	    Numbers[i] = CANCELLED_NUMERIC;
61	else
62	    Numbers[i] = LOW_MSB(buf + 2 * i);
63	TR(TRACE_DATABASE, ("get Numbers[%d]=%d", i, Numbers[i]));
64    }
65}
66
67static void
68convert_strings(char *buf, char **Strings, int count, int size, char *table)
69{
70    int i;
71    char *p;
72
73    for (i = 0; i < count; i++) {
74	if (IS_NEG1(buf + 2 * i)) {
75	    Strings[i] = ABSENT_STRING;
76	} else if (IS_NEG2(buf + 2 * i)) {
77	    Strings[i] = CANCELLED_STRING;
78	} else if ((int) LOW_MSB(buf + 2 * i) > size) {
79	    Strings[i] = ABSENT_STRING;
80	} else {
81	    Strings[i] = (LOW_MSB(buf + 2 * i) + table);
82	    TR(TRACE_DATABASE, ("Strings[%d] = %s", i, _nc_visbuf(Strings[i])));
83	}
84
85	/* make sure all strings are NUL terminated */
86	if (VALID_STRING(Strings[i])) {
87	    for (p = Strings[i]; p <= table + size; p++)
88		if (*p == '\0')
89		    break;
90	    /* if there is no NUL, ignore the string */
91	    if (p > table + size)
92		Strings[i] = ABSENT_STRING;
93	}
94    }
95}
96
97static int
98fake_read(char *src, int *offset, int limit, char *dst, unsigned want)
99{
100    int have = (limit - *offset);
101
102    if (have > 0) {
103	if ((int) want > have)
104	    want = have;
105	memcpy(dst, src + *offset, want);
106	*offset += want;
107    } else {
108	want = 0;
109    }
110    return (int) want;
111}
112
113#define Read(buf, count) fake_read(buffer, &offset, limit, buf, count)
114
115#define read_shorts(buf, count) \
116	(Read(buf, (unsigned) (count)*2) == (int) (count)*2)
117
118#define even_boundary(value) \
119    if ((value) % 2 != 0) Read(buf, 1)
120
121NCURSES_EXPORT(int)
122_nc_read_termtype(TERMTYPE *ptr, char *buffer, int limit)
123/* return 1 if read, 0 if not found or garbled */
124{
125    int offset = 0;
126    int name_size, bool_count, num_count, str_count, str_size;
127    int i;
128    char buf[MAX_ENTRY_SIZE + 1];
129    char *string_table;
130    unsigned want, have;
131
132    TR(TRACE_DATABASE, ("READ termtype header @%d", offset));
133
134    memset(ptr, 0, sizeof(*ptr));
135
136    /* grab the header */
137    if (!read_shorts(buf, 6)
138	|| !IS_TIC_MAGIC(buf)) {
139	return (TGETENT_NO);
140    }
141
142    name_size = LOW_MSB(buf + 2);
143    bool_count = LOW_MSB(buf + 4);
144    num_count = LOW_MSB(buf + 6);
145    str_count = LOW_MSB(buf + 8);
146    str_size = LOW_MSB(buf + 10);
147
148    TR(TRACE_DATABASE,
149       ("TERMTYPE name_size=%d, bool=%d/%d, num=%d/%d str=%d/%d(%d)",
150	name_size, bool_count, BOOLCOUNT, num_count, NUMCOUNT,
151	str_count, STRCOUNT, str_size));
152    if (name_size < 0
153	|| bool_count < 0
154	|| num_count < 0
155	|| str_count < 0
156	|| str_size < 0) {
157	return (TGETENT_NO);
158    }
159
160    want = str_size + name_size + 1;
161    if (str_size) {
162	/* try to allocate space for the string table */
163	if (str_count * 2 >= (int) sizeof(buf)
164	    || (string_table = typeMalloc(char, want)) == 0) {
165	    return (TGETENT_NO);
166	}
167    } else {
168	str_count = 0;
169	if ((string_table = typeMalloc(char, want)) == 0) {
170	    return (TGETENT_NO);
171	}
172    }
173
174    /* grab the name (a null-terminated string) */
175    want = min(MAX_NAME_SIZE, (unsigned) name_size);
176    ptr->str_table = string_table;
177    ptr->term_names = string_table;
178    if ((have = Read(ptr->term_names, want)) != want) {
179	memset(ptr->term_names + have, 0, want - have);
180    }
181    ptr->term_names[want] = '\0';
182    string_table += (want + 1);
183
184    if (have > MAX_NAME_SIZE)
185	offset = (have - MAX_NAME_SIZE);
186
187    /* grab the booleans */
188    if ((ptr->Booleans = TYPE_CALLOC(NCURSES_SBOOL,
189				     max(BOOLCOUNT, bool_count))) == 0
190	|| Read(ptr->Booleans, (unsigned) bool_count) < bool_count) {
191	return (TGETENT_NO);
192    }
193
194    /*
195     * If booleans end on an odd byte, skip it.  The machine they
196     * originally wrote terminfo on must have been a 16-bit
197     * word-oriented machine that would trap out if you tried a
198     * word access off a 2-byte boundary.
199     */
200    even_boundary(name_size + bool_count);
201
202    /* grab the numbers */
203    if ((ptr->Numbers = TYPE_CALLOC(short, max(NUMCOUNT, num_count))) == 0
204	|| !read_shorts(buf, num_count)) {
205	return (TGETENT_NO);
206    }
207    convert_shorts(buf, ptr->Numbers, num_count);
208
209    if ((ptr->Strings = TYPE_CALLOC(char *, max(STRCOUNT, str_count))) == 0)
210	  return (TGETENT_NO);
211
212    if (str_count) {
213	/* grab the string offsets */
214	if (!read_shorts(buf, str_count)) {
215	    return (TGETENT_NO);
216	}
217	/* finally, grab the string table itself */
218	if (Read(string_table, (unsigned) str_size) != str_size)
219	    return (TGETENT_NO);
220	convert_strings(buf, ptr->Strings, str_count, str_size, string_table);
221    }
222#if NCURSES_XNAMES
223
224    ptr->num_Booleans = BOOLCOUNT;
225    ptr->num_Numbers = NUMCOUNT;
226    ptr->num_Strings = STRCOUNT;
227
228    /*
229     * Read extended entries, if any, after the normal end of terminfo data.
230     */
231    even_boundary(str_size);
232    TR(TRACE_DATABASE, ("READ extended_header @%d", offset));
233    if (_nc_user_definable && read_shorts(buf, 5)) {
234	int ext_bool_count = LOW_MSB(buf + 0);
235	int ext_num_count = LOW_MSB(buf + 2);
236	int ext_str_count = LOW_MSB(buf + 4);
237	int ext_str_size = LOW_MSB(buf + 6);
238	int ext_str_limit = LOW_MSB(buf + 8);
239	unsigned need = (ext_bool_count + ext_num_count + ext_str_count);
240	int base = 0;
241
242	if (need >= sizeof(buf)
243	    || ext_str_size >= (int) sizeof(buf)
244	    || ext_str_limit >= (int) sizeof(buf)
245	    || ext_bool_count < 0
246	    || ext_num_count < 0
247	    || ext_str_count < 0
248	    || ext_str_size < 0
249	    || ext_str_limit < 0)
250	    return (TGETENT_NO);
251
252	ptr->num_Booleans = BOOLCOUNT + ext_bool_count;
253	ptr->num_Numbers = NUMCOUNT + ext_num_count;
254	ptr->num_Strings = STRCOUNT + ext_str_count;
255
256	ptr->Booleans = typeRealloc(NCURSES_SBOOL, ptr->num_Booleans, ptr->Booleans);
257	ptr->Numbers = typeRealloc(short, ptr->num_Numbers, ptr->Numbers);
258	ptr->Strings = typeRealloc(char *, ptr->num_Strings, ptr->Strings);
259
260	TR(TRACE_DATABASE, ("extended header is %d/%d/%d(%d:%d)",
261			    ext_bool_count, ext_num_count, ext_str_count,
262			    ext_str_size, ext_str_limit));
263
264	TR(TRACE_DATABASE, ("READ %d extended-booleans @%d",
265			    ext_bool_count, offset));
266	if ((ptr->ext_Booleans = ext_bool_count) != 0) {
267	    if (Read(ptr->Booleans + BOOLCOUNT, (unsigned)
268		     ext_bool_count) != ext_bool_count)
269		return (TGETENT_NO);
270	}
271	even_boundary(ext_bool_count);
272
273	TR(TRACE_DATABASE, ("READ %d extended-numbers @%d",
274			    ext_num_count, offset));
275	if ((ptr->ext_Numbers = ext_num_count) != 0) {
276	    if (!read_shorts(buf, ext_num_count))
277		return (TGETENT_NO);
278	    TR(TRACE_DATABASE, ("Before converting extended-numbers"));
279	    convert_shorts(buf, ptr->Numbers + NUMCOUNT, ext_num_count);
280	}
281
282	TR(TRACE_DATABASE, ("READ extended-offsets @%d", offset));
283	if ((ext_str_count || need)
284	    && !read_shorts(buf, ext_str_count + need))
285	    return (TGETENT_NO);
286
287	TR(TRACE_DATABASE, ("READ %d bytes of extended-strings @%d",
288			    ext_str_limit, offset));
289
290	if (ext_str_limit) {
291	    if ((ptr->ext_str_table = typeMalloc(char, ext_str_limit)) == 0)
292		  return (TGETENT_NO);
293	    if (Read(ptr->ext_str_table, (unsigned) ext_str_limit) != ext_str_limit)
294		return (TGETENT_NO);
295	    TR(TRACE_DATABASE, ("first extended-string is %s", _nc_visbuf(ptr->ext_str_table)));
296	}
297
298	if ((ptr->ext_Strings = ext_str_count) != 0) {
299	    TR(TRACE_DATABASE,
300	       ("Before computing extended-string capabilities str_count=%d, ext_str_count=%d",
301		str_count, ext_str_count));
302	    convert_strings(buf, ptr->Strings + str_count, ext_str_count,
303			    ext_str_limit, ptr->ext_str_table);
304	    for (i = ext_str_count - 1; i >= 0; i--) {
305		TR(TRACE_DATABASE, ("MOVE from [%d:%d] %s",
306				    i, i + str_count,
307				    _nc_visbuf(ptr->Strings[i + str_count])));
308		ptr->Strings[i + STRCOUNT] = ptr->Strings[i + str_count];
309		if (VALID_STRING(ptr->Strings[i + STRCOUNT]))
310		    base += (strlen(ptr->Strings[i + STRCOUNT]) + 1);
311		TR(TRACE_DATABASE, ("... to    [%d] %s",
312				    i + STRCOUNT,
313				    _nc_visbuf(ptr->Strings[i + STRCOUNT])));
314	    }
315	}
316
317	if (need) {
318	    if (ext_str_count >= (MAX_ENTRY_SIZE * 2))
319		  return (TGETENT_NO);
320	    if ((ptr->ext_Names = TYPE_CALLOC(char *, need)) == 0)
321		  return (TGETENT_NO);
322	    TR(TRACE_DATABASE,
323	       ("ext_NAMES starting @%d in extended_strings, first = %s",
324		base, _nc_visbuf(ptr->ext_str_table + base)));
325	    convert_strings(buf + (2 * ext_str_count),
326			    ptr->ext_Names,
327			    (int) need,
328			    ext_str_limit, ptr->ext_str_table + base);
329	}
330
331	T(("...done reading terminfo bool %d(%d) num %d(%d) str %d(%d)",
332	   ptr->num_Booleans, ptr->ext_Booleans,
333	   ptr->num_Numbers, ptr->ext_Numbers,
334	   ptr->num_Strings, ptr->ext_Strings));
335
336	TR(TRACE_DATABASE, ("extend: num_Booleans:%d", ptr->num_Booleans));
337    } else
338#endif /* NCURSES_XNAMES */
339    {
340	T(("...done reading terminfo bool %d num %d str %d",
341	   bool_count, num_count, str_count));
342#if NCURSES_XNAMES
343	TR(TRACE_DATABASE, ("normal: num_Booleans:%d", ptr->num_Booleans));
344#endif
345    }
346
347    for (i = bool_count; i < BOOLCOUNT; i++)
348	ptr->Booleans[i] = FALSE;
349    for (i = num_count; i < NUMCOUNT; i++)
350	ptr->Numbers[i] = ABSENT_NUMERIC;
351    for (i = str_count; i < STRCOUNT; i++)
352	ptr->Strings[i] = ABSENT_STRING;
353
354    return (TGETENT_YES);
355}
356
357/*
358 *	int
359 *	_nc_read_file_entry(filename, ptr)
360 *
361 *	Read the compiled terminfo entry in the given file into the
362 *	structure pointed to by ptr, allocating space for the string
363 *	table.
364 */
365NCURSES_EXPORT(int)
366_nc_read_file_entry(const char *const filename, TERMTYPE *ptr)
367/* return 1 if read, 0 if not found or garbled */
368{
369    int code, fd = -1;
370    int limit;
371    char buffer[MAX_ENTRY_SIZE + 1];
372
373#ifdef __OpenBSD__
374    if (_nc_read_bsd_terminfo_file(filename, ptr) == 1)
375	return (1);
376#endif /* __OpenBSD__ */
377
378    if (_nc_access(filename, R_OK) < 0
379	|| (fd = open(filename, O_RDONLY | O_BINARY)) < 0) {
380	T(("cannot open terminfo %s (errno=%d)", filename, errno));
381	code = TGETENT_NO;
382    } else {
383	if ((limit = read(fd, buffer, sizeof(buffer))) > 0) {
384
385	    T(("read terminfo %s", filename));
386	    if ((code = _nc_read_termtype(ptr, buffer, limit)) == TGETENT_NO) {
387		_nc_free_termtype(ptr);
388	    }
389	} else {
390	    code = TGETENT_NO;
391	}
392	close(fd);
393    }
394
395    return (code);
396}
397
398/*
399 * Build a terminfo pathname and try to read the data.  Returns TGETENT_YES on
400 * success, TGETENT_NO on failure.
401 */
402static int
403_nc_read_tic_entry(char *filename,
404		   unsigned limit,
405		   const char *const path,
406		   const char *name,
407		   TERMTYPE *const tp)
408{
409    int result = TGETENT_NO;
410
411    /*
412     * If we are looking in a directory, assume the entry is a file under that,
413     * according to the normal rules.
414     *
415     * FIXME - add caseless-filename fixup.
416     */
417    unsigned need = 4 + strlen(path) + strlen(name);
418    if (need <= limit) {
419	    (void) snprintf(filename, limit, "%s/" LEAF_FMT "/%s", path, *name, name);
420	    if (_nc_is_dir_path(path))
421		    result = _nc_read_file_entry(filename, tp);
422    }
423
424#if USE_HASHED_DB
425    else {
426	static const char suffix[] = DBM_SUFFIX;
427	DB *capdbp;
428	unsigned lens = sizeof(suffix) - 1;
429	unsigned size = strlen(path);
430	unsigned need = lens + size;
431
432	if (need <= limit) {
433	    if (size >= lens
434		&& !strcmp(path + size - lens, suffix))
435		(void) strlcpy(filename, path, limit);
436	    else
437		(void) snprintf(filename, limit, "%s%s", path, suffix);
438
439	    /*
440	     * It would be nice to optimize the dbopen/close activity, as
441	     * done in the cgetent implementation for tc= clauses.  However,
442	     * since we support multiple database locations, we cannot do
443	     * that.
444	     */
445	    if ((capdbp = _nc_db_open(filename, FALSE)) != 0) {
446		DBT key, data;
447		int reccnt = 0;
448		char *save = strdup(name);
449
450		memset(&key, 0, sizeof(key));
451		key.data = save;
452		key.size = strlen(save);
453
454		/*
455		 * This lookup could return termcap data, which we do not want.
456		 * We are looking for compiled (binary) terminfo data.
457		 *
458		 * cgetent uses a two-level lookup.  On the first it uses the
459		 * given name to return a record containing only the aliases
460		 * for an entry.  On the second (using that list of aliases as
461		 * a key), it returns the content of the terminal description.
462		 * We expect second lookup to return data beginning with the
463		 * same set of aliases.
464		 *
465		 * For compiled terminfo, the list of aliases in the second
466		 * case will be null-terminated.  A termcap entry will not be,
467		 * and will run on into the description.  So we can easily
468		 * distinguish between the two (source/binary) by checking the
469		 * lengths.
470		 */
471		while (_nc_db_get(capdbp, &key, &data) == 0) {
472		    int used = data.size - 1;
473		    char *have = (char *) data.data;
474
475		    if (*have++ == 0) {
476			if (data.size > key.size
477			    && IS_TIC_MAGIC(have)) {
478			    result = _nc_read_termtype(tp, have, used);
479			    if (result == TGETENT_NO) {
480				_nc_free_termtype(tp);
481			    }
482			}
483			break;
484		    }
485
486		    /*
487		     * Just in case we have a corrupt database, do not waste
488		     * time with it.
489		     */
490		    if (++reccnt >= 3)
491			break;
492
493		    /*
494		     * Prepare for the second level.
495		     */
496		    key.data = have;
497		    key.size = used;
498		}
499
500		_nc_db_close(capdbp);
501		free(save);
502	    }
503	}
504    }
505#endif
506    return result;
507}
508#endif /* USE_DATABASE */
509
510/*
511 *	_nc_read_entry(char *name, char *filename, TERMTYPE *tp)
512 *
513 *	Find and read the compiled entry for a given terminal type,
514 *	if it exists.  We take pains here to make sure no combination
515 *	of environment variables and terminal type name can be used to
516 *	overrun the file buffer.
517 */
518
519NCURSES_EXPORT(int)
520_nc_read_entry(const char *const name, char *const filename, TERMTYPE *const tp)
521{
522    int code = TGETENT_NO;
523
524#ifdef __OpenBSD__
525    /* First check the BSD terminfo.db file */
526    if (_nc_read_bsd_terminfo_entry(name, filename, tp) == 1)
527	return (1);
528#endif /* __OpenBSD__ */
529
530    snprintf(filename, PATH_MAX, "%s", name);
531    if (strlen(name) == 0
532	|| strcmp(name, ".") == 0
533	|| strcmp(name, "..") == 0
534	|| _nc_pathlast(name) != 0
535	|| strchr(name, NCURSES_PATHSEP) != 0) {
536	T(("illegal or missing entry name '%s'", name));
537    } else {
538#if USE_DATABASE
539	DBDIRS state = dbdTIC;
540	int offset = 0;
541	const char *path;
542
543	while ((path = _nc_next_db(&state, &offset)) != 0) {
544	    code = _nc_read_tic_entry(filename, PATH_MAX, path, name, tp);
545	    if (code == TGETENT_YES) {
546		_nc_last_db();
547		break;
548	    }
549	}
550#endif
551#if USE_TERMCAP
552	if (code != TGETENT_YES) {
553	    code = _nc_read_termcap_entry(name, tp);
554	    snprintf(filename, PATH_MAX, "%s", _nc_get_source());
555	}
556#endif
557    }
558    return code;
559}
560