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