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