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