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