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.8 2003/04/16 16:23:36 lha 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 size_t len = topreclen + BFRAG;
255 if ((record = malloc (len)) == NULL) {
259 (void)strlcpy(record, toprec, len);
261 rp = record + topreclen + 1;
266 * Allocate first chunk of memory.
268 if ((record = malloc(BFRAG)) == NULL) {
272 r_end = record + BFRAG;
275 * Loop through database array until finding the record.
278 for (db_p = db_array; *db_p != NULL; db_p++) {
282 * Open database if not already open.
286 (void)lseek(fd, (off_t)0, SEEK_SET);
289 char pbuf[_POSIX_PATH_MAX];
295 (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
296 if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
299 retval = cdbget(capdbp, &record, name);
301 /* no record available */
302 (void)capdbp->close(capdbp);
305 /* save the data; close frees it */
306 clen = strlen(record);
307 cbuf = malloc(clen + 1);
308 memmove(cbuf, record, clen + 1);
309 if (capdbp->close(capdbp) < 0) {
319 fd = open(*db_p, O_RDONLY, 0);
321 /* No error on unfound file. */
328 * Find the requested capability record ...
332 char *b_end, *bp, *cp;
337 * There is always room for one more character in record.
338 * R_end always points just past end of record.
339 * Rp always points just past last character in record.
340 * B_end always points just past last character in buf.
341 * Bp always points at next character in buf.
342 * Cp remembers where the last colon was.
351 * Read in a line implementing (\, newline)
359 n = read(fd, buf, sizeof(buf));
391 * If the field was `empty' (i.e.
392 * contained only white space), back up
393 * to the colon (eliminating the
400 } else if (c == '\\') {
402 } else if (c != ' ' && c != '\t') {
404 * Forget where the colon was, as this
405 * is not an empty field.
412 * Enforce loop invariant: if no room
413 * left in record buffer, try to get
421 newsize = r_end - record + BFRAG;
422 record = realloc(record, newsize);
423 if (record == NULL) {
429 r_end = record + newsize;
433 /* Eliminate any white space after the last colon. */
436 /* Loop invariant lets us do this. */
440 * If encountered eof check next file.
446 * Toss blank lines and comments.
448 if (*record == '\0' || *record == '#')
452 * See if this is the record we want ...
454 if (cgetmatch(record, name) == 0) {
455 if (nfield == NULL || !nfcmp(nfield, record)) {
457 break; /* found it! */
470 * Got the capability record, but now we have to expand all tc=name
471 * references in it ...
475 size_t ilen, newilen;
476 int diff, iret, tclen;
477 char *icap, *scan, *tc, *tcstart, *tcend;
481 * There is room for one more character in record.
482 * R_end points just past end of record.
483 * Rp points just past last character in record.
484 * Scan points at remainder of record that needs to be
485 * scanned for tc=name constructs.
490 if ((tc = cgetcap(scan, "tc", '=')) == NULL)
494 * Find end of tc=name and stomp on the trailing `:'
495 * (if present) so we can use it to call ourselves.
510 iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
512 newicap = icap; /* Put into a register. */
524 /* couldn't resolve tc */
533 /* not interested in name field of tc'ed record */
541 newilen -= s - newicap;
544 /* make sure interpolated record is `:'-terminated */
547 *s = ':'; /* overwrite NUL with : */
552 * Make sure there's enough room to insert the
555 diff = newilen - tclen;
556 if (diff >= r_end - rp) {
557 u_int pos, tcpos, tcposend;
561 newsize = r_end - record + diff + BFRAG;
562 tcpos = tcstart - record;
563 tcposend = tcend - record;
564 record = realloc(record, newsize);
565 if (record == NULL) {
572 r_end = record + newsize;
574 tcstart = record + tcpos;
575 tcend = record + tcposend;
579 * Insert tc'ed record into our record.
581 s = tcstart + newilen;
582 memmove(s, tcend, (size_t)(rp - tcend));
583 memmove(tcstart, newicap, newilen);
588 * Start scan on `:' so next cgetcap works properly
589 * (cgetcap always skips first field).
596 * Close file (if we opened it), give back any extra memory, and
597 * return capability, length and success.
601 *len = rp - record - 1; /* don't count NUL */
604 realloc(record, (size_t)(rp - record))) == NULL) {
617 cdbget(DB *capdbp, char **bp, const char *name)
622 /* LINTED key is not modified */
623 key.data = (char *)name;
624 key.size = strlen(name);
627 /* Get the reference. */
628 switch(capdbp->get(capdbp, &key, &data, 0)) {
635 /* If not an index to another record, leave. */
636 if (((char *)data.data)[0] != SHADOW)
639 key.data = (char *)data.data + 1;
640 key.size = data.size - 1;
643 *bp = (char *)data.data + 1;
644 return (((char *)(data.data))[0] == TCERR ? 1 : 0);
649 * Cgetmatch will return 0 if name is one of the names of the capability
650 * record buf, -1 if not.
653 cgetmatch(const char *buf, const char *name)
658 * Start search at beginning of record.
663 * Try to match a record name.
668 if (*bp == '|' || *bp == ':' || *bp == '\0')
677 * Match failed, skip to next name in record.
679 bp--; /* a '|' or ':' may have stopped the match */
681 if (*bp == '\0' || *bp == ':')
682 return (-1); /* match failed totally */
685 break; /* found next name */
691 cgetfirst(char **buf, char **db_array)
694 return (cgetnext(buf, db_array));
717 * Cgetnext() gets either the first or next entry in the logical database
718 * specified by db_array. It returns 0 upon completion of the database, 1
719 * upon returning an entry with more remaining, and -1 if an error occurs.
722 cgetnext(char **bp, char **db_array)
726 char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
732 if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
737 if (toprec && !gottoprec) {
741 line = fgetln(pfp, &len);
742 if (line == NULL && pfp) {
749 if (*++dbp == NULL) {
753 fopen(*dbp, "r")) == NULL) {
760 line[len - 1] = '\0';
765 if (isspace((unsigned char)*line) ||
766 *line == ':' || *line == '#' || slash) {
767 if (line[len - 2] == '\\')
773 if (line[len - 2] == '\\')
781 * Line points to a name line.
786 for (cp = line; *cp != '\0'; cp++) {
799 } else { /* name field extends beyond the line */
800 line = fgetln(pfp, &len);
801 if (line == NULL && pfp) {
811 line[len - 1] = '\0';
815 for(cp = nbuf; *cp != '\0'; cp++)
816 if (*cp == '|' || *cp == ':')
824 * Last argument of getent here should be nbuf if we want true
825 * sequential access in the case of duplicates.
826 * With NULL, getent will return the first entry found
827 * rather than the duplicate entry record. This is a
828 * matter of semantics that should be resolved.
830 status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
831 if (status == -2 || status == -3)
841 * Cgetstr retrieves the value of the string capability cap from the
842 * capability record pointed to by buf. A pointer to a decoded, NUL
843 * terminated, malloc'd copy of the string is returned in the char *
844 * pointed to by str. The length of the string not including the trailing
845 * NUL is returned on success, -1 if the requested string capability
846 * couldn't be found, -2 if a system error was encountered (storage
847 * allocation failure).
850 cgetstr(char *buf, const char *cap, char **str)
859 * Find string capability cap
861 bp = cgetcap(buf, cap, '=');
866 * Conversion / storage allocation loop ... Allocate memory in
867 * chunks SFRAG in size.
869 if ((mem = malloc(SFRAG)) == NULL) {
871 return (-2); /* couldn't even allocate the first fragment */
876 while (*bp != ':' && *bp != '\0') {
879 * There is always room for one more character in mem.
880 * Mp always points just past last character in mem.
881 * Bp always points at next character in buf.
885 if (*bp == ':' || *bp == '\0')
886 break; /* drop unfinished escape */
888 } else if (*bp == '\\') {
890 if (*bp == ':' || *bp == '\0')
891 break; /* drop unfinished escape */
892 if ('0' <= *bp && *bp <= '7') {
896 i = 3; /* maximum of three octal digits */
898 n = n * 8 + (*bp++ - '0');
899 } while (--i && '0' <= *bp && *bp <= '7');
902 else switch (*bp++) {
926 * Catches '\', '^', and
937 * Enforce loop invariant: if no room left in current
938 * buffer, try to get some more.
941 size_t size = mp - mem;
943 if ((mem = realloc(mem, size + SFRAG)) == NULL)
949 *mp++ = '\0'; /* loop invariant let's us do this */
954 * Give back any extra memory and return value and success.
957 if ((mem = realloc(mem, (size_t)(mp - mem))) == NULL)
964 * Cgetustr retrieves the value of the string capability cap from the
965 * capability record pointed to by buf. The difference between cgetustr()
966 * and cgetstr() is that cgetustr does not decode escapes but rather treats
967 * all characters literally. A pointer to a NUL terminated malloc'd
968 * copy of the string is returned in the char pointed to by str. The
969 * length of the string not including the trailing NUL is returned on success,
970 * -1 if the requested string capability couldn't be found, -2 if a system
971 * error was encountered (storage allocation failure).
974 cgetustr(char *buf, const char *cap, char **str)
983 * Find string capability cap
985 if ((bp = cgetcap(buf, cap, '=')) == NULL)
989 * Conversion / storage allocation loop ... Allocate memory in
990 * chunks SFRAG in size.
992 if ((mem = malloc(SFRAG)) == NULL) {
994 return (-2); /* couldn't even allocate the first fragment */
999 while (*bp != ':' && *bp != '\0') {
1002 * There is always room for one more character in mem.
1003 * Mp always points just past last character in mem.
1004 * Bp always points at next character in buf.
1010 * Enforce loop invariant: if no room left in current
1011 * buffer, try to get some more.
1014 size_t size = mp - mem;
1016 if ((mem = realloc(mem, size + SFRAG)) == NULL)
1022 *mp++ = '\0'; /* loop invariant let's us do this */
1027 * Give back any extra memory and return value and success.
1030 if ((mem = realloc(mem, (size_t)(mp - mem))) == NULL)
1037 * Cgetnum retrieves the value of the numeric capability cap from the
1038 * capability record pointed to by buf. The numeric value is returned in
1039 * the long pointed to by num. 0 is returned on success, -1 if the requested
1040 * numeric capability couldn't be found.
1043 cgetnum(char *buf, const char *cap, long *num)
1050 * Find numeric capability cap
1052 bp = cgetcap(buf, cap, '#');
1057 * Look at value and determine numeric base:
1058 * 0x... or 0X... hexadecimal,
1064 if (*bp == 'x' || *bp == 'X') {
1073 * Conversion loop ...
1077 if ('0' <= *bp && *bp <= '9')
1079 else if ('a' <= *bp && *bp <= 'f')
1080 digit = 10 + *bp - 'a';
1081 else if ('A' <= *bp && *bp <= 'F')
1082 digit = 10 + *bp - 'A';
1089 n = n * base + digit;
1094 * Return value and success.
1102 * Compare name field of record.
1105 nfcmp(char *nf, char *rec)
1110 for (cp = rec; *cp != ':'; cp++)
1115 ret = strcmp(nf, rec);