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