1 /* $NetBSD: getcap.c,v 1.29 1999/03/29 09:27:29 abs Exp $ */
4 * Copyright (c) 1992, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Casey Leedom of Lawrence Livermore National Laboratory.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 RCSID("$Id: getcap.c,v 1.7 1999/11/17 21:11:58 assar Exp $");
45 #include <sys/types.h>
47 #if defined(HAVE_DB_185_H)
49 #elif defined(HAVE_DB_H)
64 #define ESC ('[' & 037) /* ASCII ESC */
65 #define MAX_RECURSION 32 /* maximum getent recursion */
66 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
70 #define SHADOW (char)2
72 static size_t topreclen; /* toprec length */
73 static char *toprec; /* Additional record specified by cgetset() */
74 static int gottoprec; /* Flag indicating retrieval of toprecord */
76 #if defined(HAVE_DBOPEN) && defined(HAVE_DB_H)
81 static int cdbget (DB *, char **, const char *);
83 static int getent (char **, size_t *, char **, int, const char *, int, char *);
84 static int nfcmp (char *, char *);
87 int cgetset(const char *ent);
88 char *cgetcap(char *buf, const char *cap, int type);
89 int cgetent(char **buf, char **db_array, const char *name);
90 int cgetmatch(const char *buf, const char *name);
93 int cgetfirst(char **buf, char **db_array);
94 int cgetnext(char **bp, char **db_array);
96 int cgetstr(char *buf, const char *cap, char **str);
97 int cgetustr(char *buf, const char *cap, char **str);
98 int cgetnum(char *buf, const char *cap, long *num);
100 * Cgetset() allows the addition of a user specified buffer to be added
101 * to the database array, in effect "pushing" the buffer on top of the
102 * virtual database. 0 is returned on success, -1 on failure.
105 cgetset(const char *ent)
107 const char *source, *check;
117 topreclen = strlen(ent);
118 if ((toprec = malloc (topreclen + 1)) == NULL) {
126 while (*source) { /* Strip whitespace */
127 *dest++ = *source++; /* Do not check first field */
128 while (*source == ':') {
130 while (*check && (isspace((unsigned char)*check) ||
131 (*check=='\\' && isspace((unsigned char)check[1]))))
146 * Cgetcap searches the capability record buf for the capability cap with
147 * type `type'. A pointer to the value of cap is returned on success, NULL
148 * if the requested capability couldn't be found.
150 * Specifying a type of ':' means that nothing should follow cap (:cap:).
151 * In this case a pointer to the terminating ':' or NUL will be returned if
154 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
158 cgetcap(char *buf, const char *cap, int type)
166 * Skip past the current capability field - it's either the
167 * name field if this is the first time through the loop, or
168 * the remainder of a field whose name failed to match cap.
178 * Try to match (cap, type) in buf.
180 for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
187 if (*bp != '\0' && *bp != ':')
194 return (*bp == '@' ? NULL : bp);
200 * Cgetent extracts the capability record name from the NULL terminated file
201 * array db_array and returns a pointer to a malloc'd copy of it in buf.
202 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
203 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
204 * -1 if the requested record couldn't be found, -2 if a system error was
205 * encountered (couldn't open/read a file, etc.), and -3 if a potential
206 * reference loop is detected.
209 cgetent(char **buf, char **db_array, const char *name)
213 return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
217 * Getent implements the functions of cgetent. If fd is non-negative,
218 * *db_array has already been opened and fd is the open file descriptor. We
219 * do this to save time and avoid using up file descriptors for tc=
222 * Getent returns the same success/failure codes as cgetent. On success, a
223 * pointer to a malloc'ed capability record with all tc= capabilities fully
224 * expanded and its length (not including trailing ASCII NUL) are left in
228 * + Allocate memory incrementally as needed in chunks of size BFRAG
229 * for capability buffer.
230 * + Recurse for each tc=name and interpolate result. Stop when all
231 * names interpolated, a name can't be found, or depth exceeds
235 getent(char **cap, size_t *len, char **db_array, int fd,
236 const char *name, int depth, char *nfield)
238 char *r_end, *rp = NULL, **db_p; /* pacify gcc */
239 int myfd = 0, eof, foundit;
244 * Return with ``loop detected'' error if we've recursed more than
245 * MAX_RECURSION times.
247 if (depth > MAX_RECURSION)
251 * Check if we have a top record from cgetset().
253 if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
254 if ((record = malloc (topreclen + BFRAG)) == NULL) {
258 (void)strcpy(record, toprec); /* XXX: strcpy is safe */
260 rp = record + topreclen + 1;
265 * Allocate first chunk of memory.
267 if ((record = malloc(BFRAG)) == NULL) {
271 r_end = record + BFRAG;
274 * Loop through database array until finding the record.
277 for (db_p = db_array; *db_p != NULL; db_p++) {
281 * Open database if not already open.
285 (void)lseek(fd, (off_t)0, SEEK_SET);
288 char pbuf[_POSIX_PATH_MAX];
294 (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
295 if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
298 retval = cdbget(capdbp, &record, name);
300 /* no record available */
301 (void)capdbp->close(capdbp);
304 /* save the data; close frees it */
305 clen = strlen(record);
306 cbuf = malloc(clen + 1);
307 memmove(cbuf, record, clen + 1);
308 if (capdbp->close(capdbp) < 0) {
318 fd = open(*db_p, O_RDONLY, 0);
320 /* No error on unfound file. */
327 * Find the requested capability record ...
331 char *b_end, *bp, *cp;
336 * There is always room for one more character in record.
337 * R_end always points just past end of record.
338 * Rp always points just past last character in record.
339 * B_end always points just past last character in buf.
340 * Bp always points at next character in buf.
341 * Cp remembers where the last colon was.
350 * Read in a line implementing (\, newline)
358 n = read(fd, buf, sizeof(buf));
390 * If the field was `empty' (i.e.
391 * contained only white space), back up
392 * to the colon (eliminating the
399 } else if (c == '\\') {
401 } else if (c != ' ' && c != '\t') {
403 * Forget where the colon was, as this
404 * is not an empty field.
411 * Enforce loop invariant: if no room
412 * left in record buffer, try to get
420 newsize = r_end - record + BFRAG;
421 record = realloc(record, newsize);
422 if (record == NULL) {
428 r_end = record + newsize;
432 /* Eliminate any white space after the last colon. */
435 /* Loop invariant lets us do this. */
439 * If encountered eof check next file.
445 * Toss blank lines and comments.
447 if (*record == '\0' || *record == '#')
451 * See if this is the record we want ...
453 if (cgetmatch(record, name) == 0) {
454 if (nfield == NULL || !nfcmp(nfield, record)) {
456 break; /* found it! */
469 * Got the capability record, but now we have to expand all tc=name
470 * references in it ...
474 size_t ilen, newilen;
475 int diff, iret, tclen;
476 char *icap, *scan, *tc, *tcstart, *tcend;
480 * There is room for one more character in record.
481 * R_end points just past end of record.
482 * Rp points just past last character in record.
483 * Scan points at remainder of record that needs to be
484 * scanned for tc=name constructs.
489 if ((tc = cgetcap(scan, "tc", '=')) == NULL)
493 * Find end of tc=name and stomp on the trailing `:'
494 * (if present) so we can use it to call ourselves.
509 iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
511 newicap = icap; /* Put into a register. */
523 /* couldn't resolve tc */
532 /* not interested in name field of tc'ed record */
540 newilen -= s - newicap;
543 /* make sure interpolated record is `:'-terminated */
546 *s = ':'; /* overwrite NUL with : */
551 * Make sure there's enough room to insert the
554 diff = newilen - tclen;
555 if (diff >= r_end - rp) {
556 u_int pos, tcpos, tcposend;
560 newsize = r_end - record + diff + BFRAG;
561 tcpos = tcstart - record;
562 tcposend = tcend - record;
563 record = realloc(record, newsize);
564 if (record == NULL) {
571 r_end = record + newsize;
573 tcstart = record + tcpos;
574 tcend = record + tcposend;
578 * Insert tc'ed record into our record.
580 s = tcstart + newilen;
581 memmove(s, tcend, (size_t)(rp - tcend));
582 memmove(tcstart, newicap, newilen);
587 * Start scan on `:' so next cgetcap works properly
588 * (cgetcap always skips first field).
595 * Close file (if we opened it), give back any extra memory, and
596 * return capability, length and success.
600 *len = rp - record - 1; /* don't count NUL */
603 realloc(record, (size_t)(rp - record))) == NULL) {
616 cdbget(DB *capdbp, char **bp, const char *name)
621 /* LINTED key is not modified */
622 key.data = (char *)name;
623 key.size = strlen(name);
626 /* Get the reference. */
627 switch(capdbp->get(capdbp, &key, &data, 0)) {
634 /* If not an index to another record, leave. */
635 if (((char *)data.data)[0] != SHADOW)
638 key.data = (char *)data.data + 1;
639 key.size = data.size - 1;
642 *bp = (char *)data.data + 1;
643 return (((char *)(data.data))[0] == TCERR ? 1 : 0);
648 * Cgetmatch will return 0 if name is one of the names of the capability
649 * record buf, -1 if not.
652 cgetmatch(const char *buf, const char *name)
657 * Start search at beginning of record.
662 * Try to match a record name.
667 if (*bp == '|' || *bp == ':' || *bp == '\0')
676 * Match failed, skip to next name in record.
678 bp--; /* a '|' or ':' may have stopped the match */
680 if (*bp == '\0' || *bp == ':')
681 return (-1); /* match failed totally */
684 break; /* found next name */
690 cgetfirst(char **buf, char **db_array)
693 return (cgetnext(buf, db_array));
716 * Cgetnext() gets either the first or next entry in the logical database
717 * specified by db_array. It returns 0 upon completion of the database, 1
718 * upon returning an entry with more remaining, and -1 if an error occurs.
721 cgetnext(char **bp, char **db_array)
725 char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
731 if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
736 if (toprec && !gottoprec) {
740 line = fgetln(pfp, &len);
741 if (line == NULL && pfp) {
748 if (*++dbp == NULL) {
752 fopen(*dbp, "r")) == NULL) {
759 line[len - 1] = '\0';
764 if (isspace((unsigned char)*line) ||
765 *line == ':' || *line == '#' || slash) {
766 if (line[len - 2] == '\\')
772 if (line[len - 2] == '\\')
780 * Line points to a name line.
785 for (cp = line; *cp != '\0'; cp++) {
798 } else { /* name field extends beyond the line */
799 line = fgetln(pfp, &len);
800 if (line == NULL && pfp) {
810 line[len - 1] = '\0';
814 for(cp = nbuf; *cp != '\0'; cp++)
815 if (*cp == '|' || *cp == ':')
823 * Last argument of getent here should be nbuf if we want true
824 * sequential access in the case of duplicates.
825 * With NULL, getent will return the first entry found
826 * rather than the duplicate entry record. This is a
827 * matter of semantics that should be resolved.
829 status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
830 if (status == -2 || status == -3)
840 * Cgetstr retrieves the value of the string capability cap from the
841 * capability record pointed to by buf. A pointer to a decoded, NUL
842 * terminated, malloc'd copy of the string is returned in the char *
843 * pointed to by str. The length of the string not including the trailing
844 * NUL is returned on success, -1 if the requested string capability
845 * couldn't be found, -2 if a system error was encountered (storage
846 * allocation failure).
849 cgetstr(char *buf, const char *cap, char **str)
858 * Find string capability cap
860 bp = cgetcap(buf, cap, '=');
865 * Conversion / storage allocation loop ... Allocate memory in
866 * chunks SFRAG in size.
868 if ((mem = malloc(SFRAG)) == NULL) {
870 return (-2); /* couldn't even allocate the first fragment */
875 while (*bp != ':' && *bp != '\0') {
878 * There is always room for one more character in mem.
879 * Mp always points just past last character in mem.
880 * Bp always points at next character in buf.
884 if (*bp == ':' || *bp == '\0')
885 break; /* drop unfinished escape */
887 } else if (*bp == '\\') {
889 if (*bp == ':' || *bp == '\0')
890 break; /* drop unfinished escape */
891 if ('0' <= *bp && *bp <= '7') {
895 i = 3; /* maximum of three octal digits */
897 n = n * 8 + (*bp++ - '0');
898 } while (--i && '0' <= *bp && *bp <= '7');
901 else switch (*bp++) {
925 * Catches '\', '^', and
936 * Enforce loop invariant: if no room left in current
937 * buffer, try to get some more.
940 size_t size = mp - mem;
942 if ((mem = realloc(mem, size + SFRAG)) == NULL)
948 *mp++ = '\0'; /* loop invariant let's us do this */
953 * Give back any extra memory and return value and success.
956 if ((mem = realloc(mem, (size_t)(mp - mem))) == NULL)
963 * Cgetustr retrieves the value of the string capability cap from the
964 * capability record pointed to by buf. The difference between cgetustr()
965 * and cgetstr() is that cgetustr does not decode escapes but rather treats
966 * all characters literally. A pointer to a NUL terminated malloc'd
967 * copy of the string is returned in the char pointed to by str. The
968 * length of the string not including the trailing NUL is returned on success,
969 * -1 if the requested string capability couldn't be found, -2 if a system
970 * error was encountered (storage allocation failure).
973 cgetustr(char *buf, const char *cap, char **str)
982 * Find string capability cap
984 if ((bp = cgetcap(buf, cap, '=')) == NULL)
988 * Conversion / storage allocation loop ... Allocate memory in
989 * chunks SFRAG in size.
991 if ((mem = malloc(SFRAG)) == NULL) {
993 return (-2); /* couldn't even allocate the first fragment */
998 while (*bp != ':' && *bp != '\0') {
1001 * There is always room for one more character in mem.
1002 * Mp always points just past last character in mem.
1003 * Bp always points at next character in buf.
1009 * Enforce loop invariant: if no room left in current
1010 * buffer, try to get some more.
1013 size_t size = mp - mem;
1015 if ((mem = realloc(mem, size + SFRAG)) == NULL)
1021 *mp++ = '\0'; /* loop invariant let's us do this */
1026 * Give back any extra memory and return value and success.
1029 if ((mem = realloc(mem, (size_t)(mp - mem))) == NULL)
1036 * Cgetnum retrieves the value of the numeric capability cap from the
1037 * capability record pointed to by buf. The numeric value is returned in
1038 * the long pointed to by num. 0 is returned on success, -1 if the requested
1039 * numeric capability couldn't be found.
1042 cgetnum(char *buf, const char *cap, long *num)
1049 * Find numeric capability cap
1051 bp = cgetcap(buf, cap, '#');
1056 * Look at value and determine numeric base:
1057 * 0x... or 0X... hexadecimal,
1063 if (*bp == 'x' || *bp == 'X') {
1072 * Conversion loop ...
1076 if ('0' <= *bp && *bp <= '9')
1078 else if ('a' <= *bp && *bp <= 'f')
1079 digit = 10 + *bp - 'a';
1080 else if ('A' <= *bp && *bp <= 'F')
1081 digit = 10 + *bp - 'A';
1088 n = n * base + digit;
1093 * Return value and success.
1101 * Compare name field of record.
1104 nfcmp(char *nf, char *rec)
1109 for (cp = rec; *cp != ':'; cp++)
1114 ret = strcmp(nf, rec);