xref: /openbsd/lib/libcurses/tinfo/read_termcap.c (revision db3296cf)
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  * Termcap compatibility support
36  *
37  * If your OS integrator didn't install a terminfo database, you can call
38  * _nc_read_termcap_entry() to support reading and translating capabilities
39  * from the system termcap file.  This is a kludge; it will bulk up and slow
40  * down every program that uses ncurses, and translated termcap entries cannot
41  * use full terminfo capabilities.  Don't use it unless you absolutely have to;
42  * instead, get your system people to run tic(1) from root on the terminfo
43  * master included with ncurses to translate it into a terminfo database.
44  *
45  * If USE_GETCAP is enabled, we use what is effectively a copy of the 4.4BSD
46  * getcap code to fetch entries.  There are disadvantages to this; mainly that
47  * getcap(3) does its own resolution, meaning that entries read in in this way
48  * can't reference the terminfo tree.  The only thing it buys is faster startup
49  * time, getcap(3) is much faster than our tic parser.
50  */
51 
52 #include <curses.priv.h>
53 
54 #include <ctype.h>
55 #include <tic.h>
56 #include <term_entry.h>
57 
58 MODULE_ID("$From: read_termcap.c,v 1.55 2000/12/10 02:55:08 tom Exp $")
59 
60 #if !PURE_TERMINFO
61 
62 #ifdef __EMX__
63 #define is_pathname(s) ((((s) != 0) && ((s)[0] == '/')) \
64 		  || (((s)[0] != 0) && ((s)[1] == ':')))
65 #else
66 #define is_pathname(s) ((s) != 0 && (s)[0] == '/')
67 #endif
68 
69 #define TC_SUCCESS     0
70 #define TC_UNRESOLVED -1
71 #define TC_NOT_FOUND  -2
72 #define TC_SYS_ERR    -3
73 #define TC_REF_LOOP   -4
74 
75 #if USE_GETCAP
76 
77 #if HAVE_BSD_CGETENT
78 #define _nc_cgetcap   cgetcap
79 #define _nc_cgetent(buf, oline, db_array, name) cgetent(buf, db_array, name)
80 #define _nc_cgetmatch cgetmatch
81 #define _nc_cgetset   cgetset
82 #else
83 static int _nc_cgetmatch(char *, const char *);
84 static int _nc_getent(char **, unsigned *, int *, int, char **, int, const char
85 		      *, int, char *);
86 static int _nc_nfcmp(const char *, char *);
87 
88 /*-
89  * Copyright (c) 1992, 1993
90  *	The Regents of the University of California.  All rights reserved.
91  *
92  * This code is derived from software contributed to Berkeley by
93  * Casey Leedom of Lawrence Livermore National Laboratory.
94  *
95  * Redistribution and use in source and binary forms, with or without
96  * modification, are permitted provided that the following conditions
97  * are met:
98  * 1. Redistributions of source code must retain the above copyright
99  *    notice, this list of conditions and the following disclaimer.
100  * 2. Redistributions in binary form must reproduce the above copyright
101  *    notice, this list of conditions and the following disclaimer in the
102  *    documentation and/or other materials provided with the distribution.
103  * 3. Neither the name of the University nor the names of its contributors
104  *    may be used to endorse or promote products derived from this software
105  *    without specific prior written permission.
106  *
107  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
108  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
109  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
110  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
111  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
112  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
113  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
114  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
115  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
116  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
117  * SUCH DAMAGE.
118  */
119 
120 /* static char sccsid[] = "@(#)getcap.c	8.3 (Berkeley) 3/25/94"; */
121 
122 #define	BFRAG		1024
123 #define	BSIZE		1024
124 #define	ESC		('[' & 037)	/* ASCII ESC */
125 #define	MAX_RECURSION	32	/* maximum getent recursion */
126 #define	SFRAG		100	/* cgetstr mallocs in SFRAG chunks */
127 
128 #define RECOK	(char)0
129 #define TCERR	(char)1
130 #define	SHADOW	(char)2
131 
132 static size_t topreclen;	/* toprec length */
133 static char *toprec;		/* Additional record specified by cgetset() */
134 static int gottoprec;		/* Flag indicating retrieval of toprecord */
135 
136 /*
137  * Cgetset() allows the addition of a user specified buffer to be added to the
138  * database array, in effect "pushing" the buffer on top of the virtual
139  * database.  0 is returned on success, -1 on failure.
140  */
141 static int
142 _nc_cgetset(const char *ent)
143 {
144     if (ent == 0) {
145 	FreeIfNeeded(toprec);
146 	toprec = 0;
147 	topreclen = 0;
148 	return (0);
149     }
150     topreclen = strlen(ent);
151     if ((toprec = typeMalloc(char, topreclen + 1)) == 0) {
152 	errno = ENOMEM;
153 	return (-1);
154     }
155     gottoprec = 0;
156     (void) strlcpy(toprec, ent, topreclen + 1);
157     return (0);
158 }
159 
160 /*
161  * Cgetcap searches the capability record buf for the capability cap with type
162  * `type'.  A pointer to the value of cap is returned on success, 0 if the
163  * requested capability couldn't be found.
164  *
165  * Specifying a type of ':' means that nothing should follow cap (:cap:).  In
166  * this case a pointer to the terminating ':' or NUL will be returned if cap is
167  * found.
168  *
169  * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
170  * return 0.
171  */
172 static char *
173 _nc_cgetcap(char *buf, const char *cap, int type)
174 {
175     register const char *cp;
176     register char *bp;
177 
178     bp = buf;
179     for (;;) {
180 	/*
181 	 * Skip past the current capability field - it's either the
182 	 * name field if this is the first time through the loop, or
183 	 * the remainder of a field whose name failed to match cap.
184 	 */
185 	for (;;) {
186 	    if (*bp == '\0')
187 		return (0);
188 	    else if (*bp++ == ':')
189 		break;
190 	}
191 
192 	/*
193 	 * Try to match (cap, type) in buf.
194 	 */
195 	for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
196 	    continue;
197 	if (*cp != '\0')
198 	    continue;
199 	if (*bp == '@')
200 	    return (0);
201 	if (type == ':') {
202 	    if (*bp != '\0' && *bp != ':')
203 		continue;
204 	    return (bp);
205 	}
206 	if (*bp != type)
207 	    continue;
208 	bp++;
209 	return (*bp == '@' ? 0 : bp);
210     }
211     /* NOTREACHED */
212 }
213 
214 /*
215  * Cgetent extracts the capability record name from the NULL terminated file
216  * array db_array and returns a pointer to a malloc'd copy of it in buf.  Buf
217  * must be retained through all subsequent calls to cgetcap, cgetnum, cgetflag,
218  * and cgetstr, but may then be freed.
219  *
220  * Returns:
221  *
222  * positive #    on success (i.e., the index in db_array)
223  * TC_UNRESOLVED if we had too many recurrences to resolve
224  * TC_NOT_FOUND  if the requested record couldn't be found
225  * TC_SYS_ERR    if a system error was encountered (e.g.,couldn't open a file)
226  * TC_REF_LOOP   if a potential reference loop is detected
227  */
228 static int
229 _nc_cgetent(char **buf, int *oline, char **db_array, const char *name)
230 {
231     unsigned dummy;
232 
233     return (_nc_getent(buf, &dummy, oline, 0, db_array, -1, name, 0, 0));
234 }
235 
236 /*
237  * Getent implements the functions of cgetent.  If fd is non-negative,
238  * *db_array has already been opened and fd is the open file descriptor.  We
239  * do this to save time and avoid using up file descriptors for tc=
240  * recursions.
241  *
242  * Getent returns the same success/failure codes as cgetent.  On success, a
243  * pointer to a malloc'd capability record with all tc= capabilities fully
244  * expanded and its length (not including trailing ASCII NUL) are left in
245  * *cap and *len.
246  *
247  * Basic algorithm:
248  *	+ Allocate memory incrementally as needed in chunks of size BFRAG
249  *	  for capability buffer.
250  *	+ Recurse for each tc=name and interpolate result.  Stop when all
251  *	  names interpolated, a name can't be found, or depth exceeds
252  *	  MAX_RECURSION.
253  */
254 #define DOALLOC(size) typeRealloc(char, size, record)
255 static int
256 _nc_getent(
257 	      char **cap,	/* termcap-content */
258 	      unsigned *len,	/* length, needed for recursion */
259 	      int *beginning,	/* line-number at match */
260 	      int in_array,	/* index in 'db_array[] */
261 	      char **db_array,	/* list of files to search */
262 	      int fd,
263 	      const char *name,
264 	      int depth,
265 	      char *nfield)
266 {
267     register char *r_end, *rp;
268     int myfd = FALSE;
269     char *record = 0;
270     int tc_not_resolved;
271     int current;
272     int lineno;
273 
274     /*
275      * Return with ``loop detected'' error if we've recurred more than
276      * MAX_RECURSION times.
277      */
278     if (depth > MAX_RECURSION)
279 	return (TC_REF_LOOP);
280 
281     /*
282      * Check if we have a top record from cgetset().
283      */
284     if (depth == 0 && toprec != 0 && _nc_cgetmatch(toprec, name) == 0) {
285 	if ((record = DOALLOC(topreclen + BFRAG)) == 0) {
286 	    errno = ENOMEM;
287 	    return (TC_SYS_ERR);
288 	}
289 	(void) strlcpy(record, toprec, topreclen + BFRAG);
290 	rp = record + topreclen + 1;
291 	r_end = rp + BFRAG;
292 	current = in_array;
293     } else {
294 	int foundit;
295 
296 	/*
297 	 * Allocate first chunk of memory.
298 	 */
299 	if ((record = DOALLOC(BFRAG)) == 0) {
300 	    errno = ENOMEM;
301 	    return (TC_SYS_ERR);
302 	}
303 	rp = r_end = record + BFRAG;
304 	foundit = FALSE;
305 
306 	/*
307 	 * Loop through database array until finding the record.
308 	 */
309 	for (current = in_array; db_array[current] != 0; current++) {
310 	    int eof = FALSE;
311 
312 	    /*
313 	     * Open database if not already open.
314 	     */
315 	    if (fd >= 0) {
316 		(void) lseek(fd, (off_t) 0, SEEK_SET);
317 	    } else if ((_nc_access(db_array[current], R_OK) < 0)
318 		       || (fd = open(db_array[current], O_RDONLY, 0)) < 0) {
319 		/* No error on unfound file. */
320 		if (errno == ENOENT)
321 		    continue;
322 		free(record);
323 		return (TC_SYS_ERR);
324 	    } else {
325 		myfd = TRUE;
326 	    }
327 	    lineno = 0;
328 
329 	    /*
330 	     * Find the requested capability record ...
331 	     */
332 	    {
333 		char buf[2048];
334 		register char *b_end = buf;
335 		register char *bp = buf;
336 		register int c;
337 
338 		/*
339 		 * Loop invariants:
340 		 *      There is always room for one more character in record.
341 		 *      R_end always points just past end of record.
342 		 *      Rp always points just past last character in record.
343 		 *      B_end always points just past last character in buf.
344 		 *      Bp always points at next character in buf.
345 		 */
346 
347 		for (;;) {
348 		    int first = lineno + 1;
349 
350 		    /*
351 		     * Read in a line implementing (\, newline)
352 		     * line continuation.
353 		     */
354 		    rp = record;
355 		    for (;;) {
356 			if (bp >= b_end) {
357 			    int n;
358 
359 			    n = read(fd, buf, sizeof(buf));
360 			    if (n <= 0) {
361 				if (myfd)
362 				    (void) close(fd);
363 				if (n < 0) {
364 				    free(record);
365 				    return (TC_SYS_ERR);
366 				}
367 				fd = -1;
368 				eof = TRUE;
369 				break;
370 			    }
371 			    b_end = buf + n;
372 			    bp = buf;
373 			}
374 
375 			c = *bp++;
376 			if (c == '\n') {
377 			    lineno++;
378 			    if (rp == record || *(rp - 1) != '\\')
379 				break;
380 			}
381 			*rp++ = c;
382 
383 			/*
384 			 * Enforce loop invariant: if no room
385 			 * left in record buffer, try to get
386 			 * some more.
387 			 */
388 			if (rp >= r_end) {
389 			    unsigned pos;
390 			    size_t newsize;
391 
392 			    pos = rp - record;
393 			    newsize = r_end - record + BFRAG;
394 			    record = DOALLOC(newsize);
395 			    if (record == 0) {
396 				if (myfd)
397 				    (void) close(fd);
398 				errno = ENOMEM;
399 				return (TC_SYS_ERR);
400 			    }
401 			    r_end = record + newsize;
402 			    rp = record + pos;
403 			}
404 		    }
405 		    /* loop invariant lets us do this */
406 		    *rp++ = '\0';
407 
408 		    /*
409 		     * If encountered eof check next file.
410 		     */
411 		    if (eof)
412 			break;
413 
414 		    /*
415 		     * Toss blank lines and comments.
416 		     */
417 		    if (*record == '\0' || *record == '#')
418 			continue;
419 
420 		    /*
421 		     * See if this is the record we want ...
422 		     */
423 		    if (_nc_cgetmatch(record, name) == 0
424 			&& (nfield == 0
425 			    || !_nc_nfcmp(nfield, record))) {
426 			foundit = TRUE;
427 			*beginning = first;
428 			break;	/* found it! */
429 		    }
430 		}
431 	    }
432 	    if (foundit)
433 		break;
434 	}
435 
436 	if (!foundit)
437 	    return (TC_NOT_FOUND);
438     }
439 
440     /*
441      * Got the capability record, but now we have to expand all tc=name
442      * references in it ...
443      */
444     {
445 	register char *newicap, *s;
446 	register int newilen;
447 	unsigned ilen;
448 	int diff, iret, tclen, oline;
449 	char *icap, *scan, *tc, *tcstart, *tcend;
450 
451 	/*
452 	 * Loop invariants:
453 	 *      There is room for one more character in record.
454 	 *      R_end points just past end of record.
455 	 *      Rp points just past last character in record.
456 	 *      Scan points at remainder of record that needs to be
457 	 *      scanned for tc=name constructs.
458 	 */
459 	scan = record;
460 	tc_not_resolved = FALSE;
461 	for (;;) {
462 	    if ((tc = _nc_cgetcap(scan, "tc", '=')) == 0)
463 		break;
464 
465 	    /*
466 	     * Find end of tc=name and stomp on the trailing `:'
467 	     * (if present) so we can use it to call ourselves.
468 	     */
469 	    s = tc;
470 	    while (*s != '\0') {
471 		if (*s++ == ':') {
472 		    *(s - 1) = '\0';
473 		    break;
474 		}
475 	    }
476 	    tcstart = tc - 3;
477 	    tclen = s - tcstart;
478 	    tcend = s;
479 
480 	    iret = _nc_getent(&icap, &ilen, &oline, current, db_array, fd,
481 			      tc, depth + 1, 0);
482 	    newicap = icap;	/* Put into a register. */
483 	    newilen = ilen;
484 	    if (iret != TC_SUCCESS) {
485 		/* an error */
486 		if (iret < TC_NOT_FOUND) {
487 		    if (myfd)
488 			(void) close(fd);
489 		    free(record);
490 		    return (iret);
491 		}
492 		if (iret == TC_UNRESOLVED)
493 		    tc_not_resolved = TRUE;
494 		/* couldn't resolve tc */
495 		if (iret == TC_NOT_FOUND) {
496 		    *(s - 1) = ':';
497 		    scan = s - 1;
498 		    tc_not_resolved = TRUE;
499 		    continue;
500 		}
501 	    }
502 
503 	    /* not interested in name field of tc'ed record */
504 	    s = newicap;
505 	    while (*s != '\0' && *s++ != ':') ;
506 	    newilen -= s - newicap;
507 	    newicap = s;
508 
509 	    /* make sure interpolated record is `:'-terminated */
510 	    s += newilen;
511 	    if (*(s - 1) != ':') {
512 		*s = ':';	/* overwrite NUL with : */
513 		newilen++;
514 	    }
515 
516 	    /*
517 	     * Make sure there's enough room to insert the
518 	     * new record.
519 	     */
520 	    diff = newilen - tclen;
521 	    if (diff >= r_end - rp) {
522 		unsigned pos, tcpos, tcposend;
523 		size_t newsize;
524 
525 		pos = rp - record;
526 		newsize = r_end - record + diff + BFRAG;
527 		tcpos = tcstart - record;
528 		tcposend = tcend - record;
529 		record = DOALLOC(newsize);
530 		if (record == 0) {
531 		    if (myfd)
532 			(void) close(fd);
533 		    free(icap);
534 		    errno = ENOMEM;
535 		    return (TC_SYS_ERR);
536 		}
537 		r_end = record + newsize;
538 		rp = record + pos;
539 		tcstart = record + tcpos;
540 		tcend = record + tcposend;
541 	    }
542 
543 	    /*
544 	     * Insert tc'ed record into our record.
545 	     */
546 	    s = tcstart + newilen;
547 	    memmove(s, tcend, (size_t) (rp - tcend));
548 	    memmove(tcstart, newicap, (size_t) newilen);
549 	    rp += diff;
550 	    free(icap);
551 
552 	    /*
553 	     * Start scan on `:' so next cgetcap works properly
554 	     * (cgetcap always skips first field).
555 	     */
556 	    scan = s - 1;
557 	}
558     }
559 
560     /*
561      * Close file (if we opened it), give back any extra memory, and
562      * return capability, length and success.
563      */
564     if (myfd)
565 	(void) close(fd);
566     *len = rp - record - 1;	/* don't count NUL */
567     if (r_end > rp) {
568 	if ((record = DOALLOC((size_t) (rp - record))) == 0) {
569 	    errno = ENOMEM;
570 	    return (TC_SYS_ERR);
571 	}
572     }
573 
574     *cap = record;
575     if (tc_not_resolved)
576 	return (TC_UNRESOLVED);
577     return (current);
578 }
579 
580 /*
581  * Cgetmatch will return 0 if name is one of the names of the capability
582  * record buf, -1 if not.
583  */
584 static int
585 _nc_cgetmatch(char *buf, const char *name)
586 {
587     register const char *np;
588     register char *bp;
589 
590     /*
591      * Start search at beginning of record.
592      */
593     bp = buf;
594     for (;;) {
595 	/*
596 	 * Try to match a record name.
597 	 */
598 	np = name;
599 	for (;;) {
600 	    if (*np == '\0') {
601 		if (*bp == '|' || *bp == ':' || *bp == '\0')
602 		    return (0);
603 		else
604 		    break;
605 	    } else if (*bp++ != *np++) {
606 		break;
607 	    }
608 	}
609 
610 	/*
611 	 * Match failed, skip to next name in record.
612 	 */
613 	bp--;			/* a '|' or ':' may have stopped the match */
614 	for (;;) {
615 	    if (*bp == '\0' || *bp == ':')
616 		return (-1);	/* match failed totally */
617 	    else if (*bp++ == '|')
618 		break;		/* found next name */
619 	}
620     }
621 }
622 
623 /*
624  * Compare name field of record.
625  */
626 static int
627 _nc_nfcmp(const char *nf, char *rec)
628 {
629     char *cp, tmp;
630     int ret;
631 
632     for (cp = rec; *cp != ':'; cp++) ;
633 
634     tmp = *(cp + 1);
635     *(cp + 1) = '\0';
636     ret = strcmp(nf, rec);
637     *(cp + 1) = tmp;
638 
639     return (ret);
640 }
641 #endif /* HAVE_BSD_CGETENT */
642 
643 /*
644  * Since ncurses provides its own 'tgetent()', we cannot use the native one.
645  * So we reproduce the logic to get down to cgetent() -- or our cut-down
646  * version of that -- to circumvent the problem of configuring against the
647  * termcap library.
648  */
649 #define USE_BSD_TGETENT 1
650 
651 #if USE_BSD_TGETENT
652 /*
653  * Copyright (c) 1980, 1993
654  *	The Regents of the University of California.  All rights reserved.
655  *
656  * Redistribution and use in source and binary forms, with or without
657  * modification, are permitted provided that the following conditions
658  * are met:
659  * 1. Redistributions of source code must retain the above copyright
660  *    notice, this list of conditions and the following disclaimer.
661  * 2. Redistributions in binary form must reproduce the above copyright
662  *    notice, this list of conditions and the following disclaimer in the
663  *    documentation and/or other materials provided with the distribution.
664  * 3. Neither the name of the University nor the names of its contributors
665  *    may be used to endorse or promote products derived from this software
666  *    without specific prior written permission.
667  *
668  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
669  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
670  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
671  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
672  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
673  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
674  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
675  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
676  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
677  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
678  * SUCH DAMAGE.
679  */
680 
681 /* static char sccsid[] = "@(#)termcap.c	8.1 (Berkeley) 6/4/93" */
682 
683 #define	PBUFSIZ		512	/* max length of filename path */
684 #define	PVECSIZ		32	/* max number of names in path */
685 #define TBUFSIZ (2048*2)
686 
687 static char *tbuf;
688 
689 /*
690  * On entry, srcp points to a non ':' character which is the beginning of the
691  * token, if any.  We'll try to return a string that doesn't end with a ':'.
692  */
693 static char *
694 get_tc_token(char **srcp, int *endp)
695 {
696     int ch;
697     bool found = FALSE;
698     char *s, *base;
699     char *tok = 0;
700 
701     *endp = TRUE;
702     for (s = base = *srcp; *s != '\0';) {
703 	ch = *s++;
704 	if (ch == '\\') {
705 	    if (*s == '\0') {
706 		break;
707 	    } else if (*s++ == '\n') {
708 		while (isspace(*s))
709 		    s++;
710 	    } else {
711 		found = TRUE;
712 	    }
713 	} else if (ch == ':') {
714 	    if (found) {
715 		tok = base;
716 		s[-1] = '\0';
717 		*srcp = s;
718 		*endp = FALSE;
719 		break;
720 	    }
721 	    base = s;
722 	} else if (isgraph(ch)) {
723 	    found = TRUE;
724 	}
725     }
726 
727     /* malformed entry may end without a ':' */
728     if (tok == 0 && found) {
729 	tok = base;
730     }
731 
732     return tok;
733 }
734 
735 static char *
736 copy_tc_token(char *dst, const char *src, size_t len)
737 {
738     int ch;
739 
740     while ((ch = *src++) != '\0') {
741 	if (ch == '\\' && *src == '\n') {
742 	    while (isspace(*src))
743 		src++;
744 	    continue;
745 	}
746 	if (--len == 0) {
747 	    dst = 0;
748 	    break;
749 	}
750 	*dst++ = ch;
751     }
752     return dst;
753 }
754 
755 /*
756  * Get an entry for terminal name in buffer bp from the termcap file.
757  */
758 static int
759 _nc_tgetent(char *bp, char **sourcename, int *lineno, const char *name)
760 {
761     static char *the_source;
762 
763     register char *p;
764     register char *cp;
765     char *dummy = NULL;
766     char **fname;
767     char *home;
768     int i;
769     char pathbuf[PBUFSIZ];	/* holds raw path of filenames */
770     char *pathvec[PVECSIZ];	/* to point to names in pathbuf */
771     char **pvec;		/* holds usable tail of path vector */
772     char *termpath;
773     string_desc desc;
774 
775     fname = pathvec;
776     pvec = pathvec;
777     tbuf = bp;
778     p = pathbuf;
779     cp = use_terminfo_vars()? getenv("TERMCAP") : NULL;
780 
781     /*
782      * TERMCAP can have one of two things in it.  It can be the name of a file
783      * to use instead of /etc/termcap.  In this case it better start with a
784      * "/".  Or it can be an entry to use so we don't have to read the file.
785      * In this case it has to already have the newlines crunched out.  If
786      * TERMCAP does not hold a file name then a path of names is searched
787      * instead.  The path is found in the TERMPATH variable, or becomes
788      * "$HOME/.termcap /etc/termcap" if no TERMPATH exists.
789      */
790     _nc_str_init(&desc, pathbuf, sizeof(pathbuf));
791     if (cp == NULL) {
792 	_nc_safe_strcpy(&desc, "/usr/share/misc/termcap /etc/termcap");
793     } else if (!is_pathname(cp)) {	/* TERMCAP holds an entry */
794 	if ((termpath = getenv("TERMPATH")) != 0) {
795 	    _nc_safe_strcat(&desc, termpath);
796 	} else {
797 	    char temp[PBUFSIZ];
798 	    size_t len;
799 	    temp[0] = 0;
800 	    if ((home = getenv("HOME")) != 0 && *home != '\0'
801 	     && strchr(home, ' ') == 0) { /* setup path */
802 		len = snprintf(temp, sizeof(temp), "%s/.termcap", home);
803 		if (len < sizeof(temp)) {
804 		    _nc_safe_strcat(&desc, temp);
805 		}
806 	    }
807 	    _nc_safe_strcat(&desc, " /usr/share/misc/termcap");
808 	    _nc_safe_strcat(&desc, " /etc/termcap");
809 	}
810     } else {			/* user-defined name in TERMCAP */
811 	_nc_safe_strcat(&desc, cp);	/* still can be tokenized */
812     }
813 
814     *fname++ = pathbuf;		/* tokenize path into vector of names */
815     while (*++p) {
816 	if (*p == ' ' || *p == NCURSES_PATHSEP) {
817 	    *p = '\0';
818 	    while (*++p)
819 		if (*p != ' ' && *p != NCURSES_PATHSEP)
820 		    break;
821 	    if (*p == '\0')
822 		break;
823 	    *fname++ = p;
824 	    if (fname >= pathvec + PVECSIZ) {
825 		fname--;
826 		break;
827 	    }
828 	}
829     }
830     *fname = 0;			/* mark end of vector */
831     if (is_pathname(cp)) {
832 	if (_nc_cgetset(cp) < 0) {
833 	    return (TC_SYS_ERR);
834 	}
835     }
836 
837     i = _nc_cgetent(&dummy, lineno, pathvec, name);
838 
839     /* ncurses' termcap-parsing routines cannot handle multiple adjacent
840      * empty fields, and mistakenly use the last valid cap entry instead of
841      * the first (breaks tc= includes)
842      */
843     if (i >= 0) {
844 	char *pd, *ps, *tok;
845 	int endflag = FALSE;
846 	char *list[1023];
847 	size_t n, count = 0;
848 
849 	pd = bp;
850 	ps = dummy;
851 	while (!endflag && (tok = get_tc_token(&ps, &endflag)) != 0) {
852 	    bool ignore = FALSE;
853 
854 	    for (n = 1; n < count; n++) {
855 		char *s = list[n];
856 		if (s[0] == tok[0]
857 		    && s[1] == tok[1]) {
858 		    ignore = TRUE;
859 		    break;
860 		}
861 	    }
862 	    if (ignore != TRUE) {
863 		list[count++] = tok;
864 		pd = copy_tc_token(pd, tok, TBUFSIZ - (2 + pd - bp));
865 		if (pd == 0) {
866 		    i = -1;
867 		    break;
868 		}
869 		*pd++ = ':';
870 		*pd = '\0';
871 	    }
872 	}
873     }
874 
875     FreeIfNeeded(dummy);
876     FreeIfNeeded(the_source);
877     the_source = 0;
878 
879     /* This is not related to the BSD cgetent(), but to fake up a suitable
880      * filename for ncurses' error reporting.  (If we are not using BSD
881      * cgetent, then it is the actual filename).
882      */
883     if (i >= 0) {
884 	if ((the_source = strdup(pathvec[i])) != 0)
885 	    *sourcename = the_source;
886     }
887 
888     return (i);
889 }
890 #endif /* USE_BSD_TGETENT */
891 #endif /* USE_GETCAP */
892 
893 #define MAXPATHS	32
894 
895 /*
896  * Add a filename to the list in 'termpaths[]', checking that we really have
897  * a right to open the file.
898  */
899 #if !USE_GETCAP
900 static int
901 add_tc(char *termpaths[], char *path, int count)
902 {
903     if (count < MAXPATHS
904 	&& _nc_access(path, R_OK) == 0)
905 	termpaths[count++] = path;
906     termpaths[count] = 0;
907     return count;
908 }
909 #define ADD_TC(path, count) filecount = add_tc(termpaths, path, count)
910 #endif /* !USE_GETCAP */
911 
912 NCURSES_EXPORT(int)
913 _nc_read_termcap_entry
914 (const char *const tn, TERMTYPE * const tp)
915 {
916     int found = FALSE;
917     ENTRY *ep;
918 #if USE_GETCAP_CACHE
919     char cwd_buf[PATH_MAX];
920 #endif
921 #if USE_GETCAP
922     char *p, tc[TBUFSIZ];
923     static char *source;
924     static int lineno;
925 
926     if (use_terminfo_vars() && (p = getenv("TERMCAP")) != 0
927 	&& !is_pathname(p) && _nc_name_match(p, tn, "|:")) {
928 	/* TERMCAP holds a termcap entry */
929 	strlcpy(tc, p, sizeof(tc));
930 	_nc_set_source("TERMCAP");
931     } else {
932 	/* we're using getcap(3) */
933 	if (_nc_tgetent(tc, &source, &lineno, tn) < 0)
934 	    return (ERR);
935 
936 	_nc_curr_line = lineno;
937 	_nc_set_source(source);
938     }
939     _nc_read_entry_source((FILE *) 0, tc, FALSE, TRUE, NULLHOOK);
940 #else
941     /*
942      * Here is what the 4.4BSD termcap(3) page prescribes:
943      *
944      * It will look in the environment for a TERMCAP variable.  If found, and
945      * the value does not begin with a slash, and the terminal type name is the
946      * same as the environment string TERM, the TERMCAP string is used instead
947      * of reading a termcap file.  If it does begin with a slash, the string is
948      * used as a path name of the termcap file to search.  If TERMCAP does not
949      * begin with a slash and name is different from TERM, tgetent() searches
950      * the files $HOME/.termcap and /usr/share/misc/termcap, in that order,
951      * unless the environment variable TERMPATH exists, in which case it
952      * specifies a list of file pathnames (separated by spaces or colons) to be
953      * searched instead.
954      *
955      * It goes on to state:
956      *
957      * Whenever multiple files are searched and a tc field occurs in the
958      * requested entry, the entry it names must be found in the same file or
959      * one of the succeeding files.
960      *
961      * However, this restriction is relaxed in ncurses; tc references to
962      * previous files are permitted.
963      *
964      * This routine returns 1 if an entry is found, 0 if not found, and -1 if
965      * the database is not accessible.
966      */
967     FILE *fp;
968     char *tc, *termpaths[MAXPATHS];
969     int filecount = 0;
970     bool use_buffer = FALSE;
971     char tc_buf[1024];
972     char pathbuf[PATH_MAX];
973 
974     termpaths[filecount] = 0;
975     if (use_terminfo_vars() && (tc = getenv("TERMCAP")) != 0) {
976 	if (is_pathname(tc)) {	/* interpret as a filename */
977 	    ADD_TC(tc, 0);
978 	} else if (_nc_name_match(tc, tn, "|:")) {	/* treat as a capability file */
979 	    use_buffer = TRUE;
980 	    (void) snprintf(tc_buf, sizeof(tc_buf), "%.*s\n",
981 		(int) sizeof(tc_buf) - 2, tc);
982 	} else if ((tc = getenv("TERMPATH")) != 0) {
983 	    char *cp;
984 
985 	    for (cp = tc; *cp; cp++) {
986 		if (*cp == NCURSES_PATHSEP)
987 		    *cp = '\0';
988 		else if (cp == tc || cp[-1] == '\0') {
989 		    ADD_TC(cp, filecount);
990 		}
991 	    }
992 	}
993     } else {			/* normal case */
994 	char envhome[PATH_MAX], *h;
995 
996 	filecount = 0;
997 
998 	/*
999 	 * Probably /etc/termcap is a symlink to /usr/share/misc/termcap.
1000 	 * Avoid reading the same file twice.
1001 	 */
1002 	if (_nc_access("/etc/termcap", F_OK) == 0)
1003 	    ADD_TC("/etc/termcap", filecount);
1004 	else
1005 	    ADD_TC("/usr/share/misc/termcap", filecount);
1006 
1007 #define PRIVATE_CAP "%s/.termcap"
1008 
1009 	if (use_terminfo_vars() && (h = getenv("HOME")) != NULL && *h != '\0'
1010 	    && (strlen(h) + sizeof(PRIVATE_CAP)) < PATH_MAX) {
1011 	    /* user's .termcap, if any, should override it */
1012 	    (void) strlcpy(envhome, h, sizeof(envhome));
1013 	    (void) snprintf(pathbuf, sizeof(pathbuf), PRIVATE_CAP, envhome);
1014 	    ADD_TC(pathbuf, filecount);
1015 	}
1016     }
1017 
1018     /* parse the sources */
1019     if (use_buffer) {
1020 	_nc_set_source("TERMCAP");
1021 	_nc_read_entry_source((FILE *) 0, tc_buf, FALSE, TRUE, NULLHOOK);
1022     } else {
1023 	int i;
1024 
1025 	for (i = 0; i < filecount; i++) {
1026 
1027 	    T(("Looking for %s in %s", tn, termpaths[i]));
1028 	    if ((fp = fopen(termpaths[i], "r")) != (FILE *) 0) {
1029 		_nc_set_source(termpaths[i]);
1030 
1031 		/*
1032 		 * Suppress warning messages.  Otherwise you get 400 lines of
1033 		 * crap from archaic termcap files as ncurses complains about
1034 		 * all the obsolete capabilities.
1035 		 */
1036 		_nc_read_entry_source(fp, (char *) 0, FALSE, TRUE, NULLHOOK);
1037 
1038 		(void) fclose(fp);
1039 	    }
1040 	}
1041     }
1042 #endif /* USE_GETCAP */
1043 
1044     if (_nc_head == 0)
1045 	return (ERR);
1046 
1047     /* resolve all use references */
1048     _nc_resolve_uses(TRUE);
1049 
1050     /* find a terminal matching tn, if we can */
1051 #if USE_GETCAP_CACHE
1052     if (getcwd(cwd_buf, sizeof(cwd_buf)) != 0) {
1053 	_nc_set_writedir((char *) 0);	/* note: this does a chdir */
1054 #endif
1055 	for_entry_list(ep) {
1056 	    if (_nc_name_match(ep->tterm.term_names, tn, "|:")) {
1057 		/*
1058 		 * Make a local copy of the terminal capabilities.  Free all
1059 		 * entry storage except the string table for the loaded type
1060 		 * (which we disconnected from the list by NULLing out
1061 		 * ep->tterm.str_table above).
1062 		 */
1063 		*tp = ep->tterm;
1064 		ep->tterm.str_table = (char *) 0;
1065 
1066 		/*
1067 		 * OK, now try to write the type to user's terminfo directory.
1068 		 * Next time he loads this, it will come through terminfo.
1069 		 *
1070 		 * Advantage:  Second and subsequent fetches of this entry will
1071 		 * be very fast.
1072 		 *
1073 		 * Disadvantage:  After the first time a termcap type is loaded
1074 		 * by its user, editing it in the /etc/termcap file, or in
1075 		 * TERMCAP, or in a local ~/.termcap, will be ineffective
1076 		 * unless the terminfo entry is explicitly removed.
1077 		 */
1078 #if USE_GETCAP_CACHE
1079 		(void) _nc_write_entry(tp);
1080 #endif
1081 		found = TRUE;
1082 		break;
1083 	    }
1084 	}
1085 #if USE_GETCAP_CACHE
1086 	chdir(cwd_buf);
1087     }
1088 #endif
1089 
1090     _nc_free_entries(_nc_head);
1091     return (found);
1092 }
1093 #else
1094 extern
1095 NCURSES_EXPORT(void)
1096 _nc_read_termcap(void);
1097 NCURSES_EXPORT(void)
1098 _nc_read_termcap(void)
1099 {
1100 }
1101 #endif /* PURE_TERMINFO */
1102