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