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