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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 #include <sys/types.h>
41 #if defined(HAVE_DB_185_H)
43 #elif defined(HAVE_DB_H)
55 #define ESC ('[' & 037) /* ASCII ESC */
56 #define MAX_RECURSION 32 /* maximum getent recursion */
57 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
61 #define SHADOW (char)2
63 static size_t topreclen; /* toprec length */
64 static char *toprec; /* Additional record specified by cgetset() */
65 static int gottoprec; /* Flag indicating retrieval of toprecord */
68 static int cdbget (DB *, char **, const char *);
70 static int getent (char **, size_t *, char **, int, const char *, int, char *);
71 static int nfcmp (char *, char *);
74 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetset(const char *ent);
75 ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL cgetcap(char *buf, const char *cap, int type);
76 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetent(char **buf, char **db_array, const char *name);
77 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetmatch(const char *buf, const char *name);
78 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetclose(void);
79 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetstr(char *buf, const char *cap, char **str);
80 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetustr(char *buf, const char *cap, char **str);
81 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetnum(char *buf, const char *cap, long *num);
83 * Cgetset() allows the addition of a user specified buffer to be added
84 * to the database array, in effect "pushing" the buffer on top of the
85 * virtual database. 0 is returned on success, -1 on failure.
87 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
88 cgetset(const char *ent)
90 const char *source, *check;
100 topreclen = strlen(ent);
101 if ((toprec = malloc (topreclen + 1)) == NULL) {
109 while (*source) { /* Strip whitespace */
110 *dest++ = *source++; /* Do not check first field */
111 while (*source == ':') {
113 while (*check && (isspace((unsigned char)*check) ||
114 (*check=='\\' && isspace((unsigned char)check[1]))))
129 * Cgetcap searches the capability record buf for the capability cap with
130 * type `type'. A pointer to the value of cap is returned on success, NULL
131 * if the requested capability couldn't be found.
133 * Specifying a type of ':' means that nothing should follow cap (:cap:).
134 * In this case a pointer to the terminating ':' or NUL will be returned if
137 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
140 ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
141 cgetcap(char *buf, const char *cap, int type)
149 * Skip past the current capability field - it's either the
150 * name field if this is the first time through the loop, or
151 * the remainder of a field whose name failed to match cap.
161 * Try to match (cap, type) in buf.
163 for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
170 if (*bp != '\0' && *bp != ':')
177 return (*bp == '@' ? NULL : bp);
183 * Cgetent extracts the capability record name from the NULL terminated file
184 * array db_array and returns a pointer to a malloc'd copy of it in buf.
185 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
186 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
187 * -1 if the requested record couldn't be found, -2 if a system error was
188 * encountered (couldn't open/read a file, etc.), and -3 if a potential
189 * reference loop is detected.
191 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
192 cgetent(char **buf, char **db_array, const char *name)
196 return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
200 * Getent implements the functions of cgetent. If fd is non-negative,
201 * *db_array has already been opened and fd is the open file descriptor. We
202 * do this to save time and avoid using up file descriptors for tc=
205 * Getent returns the same success/failure codes as cgetent. On success, a
206 * pointer to a malloc'ed capability record with all tc= capabilities fully
207 * expanded and its length (not including trailing ASCII NUL) are left in
211 * + Allocate memory incrementally as needed in chunks of size BFRAG
212 * for capability buffer.
213 * + Recurse for each tc=name and interpolate result. Stop when all
214 * names interpolated, a name can't be found, or depth exceeds
218 getent(char **cap, size_t *len, char **db_array, int fd,
219 const char *name, int depth, char *nfield)
221 char *r_end, *rp = NULL, **db_p; /* pacify gcc */
222 int myfd = 0, eof, foundit;
227 * Return with ``loop detected'' error if we've recursed more than
228 * MAX_RECURSION times.
230 if (depth > MAX_RECURSION)
234 * Check if we have a top record from cgetset().
236 if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
237 size_t tmplen = topreclen + BFRAG;
238 if ((record = malloc (tmplen)) == NULL) {
242 (void)strlcpy(record, toprec, tmplen);
244 rp = record + topreclen + 1;
249 * Allocate first chunk of memory.
251 if ((record = malloc(BFRAG)) == NULL) {
255 r_end = record + BFRAG;
258 * Loop through database array until finding the record.
261 for (db_p = db_array; *db_p != NULL; db_p++) {
265 * Open database if not already open.
269 (void)lseek(fd, (off_t)0, SEEK_SET);
272 char pbuf[_POSIX_PATH_MAX];
278 (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
279 if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
282 retval = cdbget(capdbp, &record, name);
283 /* record is no longer for us to free here */
285 /* no record available */
286 (void)capdbp->close(capdbp);
289 /* save the data; close frees it */
290 clen = strlen(record);
291 cbuf = malloc(clen + 1);
294 memmove(cbuf, record, clen + 1);
295 if (capdbp->close(capdbp) < 0) {
305 fd = open(*db_p, O_RDONLY, 0);
307 /* No error on unfound file. */
314 * Find the requested capability record ...
318 char *b_end, *bp, *cp;
323 * There is always room for one more character in record.
324 * R_end always points just past end of record.
325 * Rp always points just past last character in record.
326 * B_end always points just past last character in buf.
327 * Bp always points at next character in buf.
328 * Cp remembers where the last colon was.
337 * Read in a line implementing (\, newline)
345 n = read(fd, buf, sizeof(buf));
377 * If the field was `empty' (i.e.
378 * contained only white space), back up
379 * to the colon (eliminating the
386 } else if (c == '\\') {
388 } else if (c != ' ' && c != '\t') {
390 * Forget where the colon was, as this
391 * is not an empty field.
398 * Enforce loop invariant: if no room
399 * left in record buffer, try to get
408 newsize = r_end - record + BFRAG;
409 tmp = realloc(record, newsize);
418 r_end = record + newsize;
422 /* Eliminate any white space after the last colon. */
425 /* Loop invariant lets us do this. */
429 * If encountered eof check next file.
435 * Toss blank lines and comments.
437 if (*record == '\0' || *record == '#')
441 * See if this is the record we want ...
443 if (cgetmatch(record, name) == 0) {
444 if (nfield == NULL || !nfcmp(nfield, record)) {
446 break; /* found it! */
461 * Got the capability record, but now we have to expand all tc=name
462 * references in it ...
466 size_t ilen, newilen;
467 int diff, iret, tclen;
468 char *icap, *scan, *tc, *tcstart, *tcend;
472 * There is room for one more character in record.
473 * R_end points just past end of record.
474 * Rp points just past last character in record.
475 * Scan points at remainder of record that needs to be
476 * scanned for tc=name constructs.
481 if ((tc = cgetcap(scan, "tc", '=')) == NULL)
485 * Find end of tc=name and stomp on the trailing `:'
486 * (if present) so we can use it to call ourselves.
501 iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
503 newicap = icap; /* Put into a register. */
515 /* couldn't resolve tc */
524 /* not interested in name field of tc'ed record */
532 newilen -= s - newicap;
535 /* make sure interpolated record is `:'-terminated */
538 *s = ':'; /* overwrite NUL with : */
543 * Make sure there's enough room to insert the
546 diff = newilen - tclen;
547 if (diff >= r_end - rp) {
548 u_int pos, tcpos, tcposend;
553 newsize = r_end - record + diff + BFRAG;
554 tcpos = tcstart - record;
555 tcposend = tcend - record;
556 tmp = realloc(record, newsize);
566 r_end = record + newsize;
568 tcstart = record + tcpos;
569 tcend = record + tcposend;
573 * Insert tc'ed record into our record.
575 s = tcstart + newilen;
576 memmove(s, tcend, (size_t)(rp - tcend));
577 memmove(tcstart, newicap, newilen);
582 * Start scan on `:' so next cgetcap works properly
583 * (cgetcap always skips first field).
590 * Close file (if we opened it), give back any extra memory, and
591 * return capability, length and success.
595 *len = rp - record - 1; /* don't count NUL */
597 char *tmp = realloc(record, (size_t)(rp - record));
614 cdbget(DB *capdbp, char **bp, const char *name)
619 /* LINTED key is not modified */
620 key.data = (char *)name;
621 key.size = strlen(name);
624 /* Get the reference. */
625 switch(capdbp->get(capdbp, &key, &data, 0)) {
632 /* If not an index to another record, leave. */
633 if (((char *)data.data)[0] != SHADOW)
636 key.data = (char *)data.data + 1;
637 key.size = data.size - 1;
640 *bp = (char *)data.data + 1;
641 return (((char *)(data.data))[0] == TCERR ? 1 : 0);
646 * Cgetmatch will return 0 if name is one of the names of the capability
647 * record buf, -1 if not.
650 cgetmatch(const char *buf, const char *name)
655 * Start search at beginning of record.
660 * Try to match a record name.
665 if (*bp == '|' || *bp == ':' || *bp == '\0')
674 * Match failed, skip to next name in record.
676 bp--; /* a '|' or ':' may have stopped the match */
678 if (*bp == '\0' || *bp == ':')
679 return (-1); /* match failed totally */
682 break; /* found next name */
690 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
704 * Cgetstr retrieves the value of the string capability cap from the
705 * capability record pointed to by buf. A pointer to a decoded, NUL
706 * terminated, malloc'd copy of the string is returned in the char *
707 * pointed to by str. The length of the string not including the trailing
708 * NUL is returned on success, -1 if the requested string capability
709 * couldn't be found, -2 if a system error was encountered (storage
710 * allocation failure).
712 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
713 cgetstr(char *buf, const char *cap, char **str)
724 * Find string capability cap
726 bp = cgetcap(buf, cap, '=');
731 * Conversion / storage allocation loop ... Allocate memory in
732 * chunks SFRAG in size.
734 if ((mem = malloc(SFRAG)) == NULL) {
736 return (-2); /* couldn't even allocate the first fragment */
741 while (*bp != ':' && *bp != '\0') {
744 * There is always room for one more character in mem.
745 * Mp always points just past last character in mem.
746 * Bp always points at next character in buf.
750 if (*bp == ':' || *bp == '\0')
751 break; /* drop unfinished escape */
753 } else if (*bp == '\\') {
755 if (*bp == ':' || *bp == '\0')
756 break; /* drop unfinished escape */
757 if ('0' <= *bp && *bp <= '7') {
761 i = 3; /* maximum of three octal digits */
763 n = n * 8 + (*bp++ - '0');
764 } while (--i && '0' <= *bp && *bp <= '7');
767 else switch (*bp++) {
791 * Catches '\', '^', and
802 * Enforce loop invariant: if no room left in current
803 * buffer, try to get some more.
806 size_t size = mp - mem;
808 if ((nmem = realloc(mem, size + SFRAG)) == NULL) {
817 *mp++ = '\0'; /* loop invariant let's us do this */
822 * Give back any extra memory and return value and success.
825 if ((nmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
836 * Cgetustr retrieves the value of the string capability cap from the
837 * capability record pointed to by buf. The difference between cgetustr()
838 * and cgetstr() is that cgetustr does not decode escapes but rather treats
839 * all characters literally. A pointer to a NUL terminated malloc'd
840 * copy of the string is returned in the char pointed to by str. The
841 * length of the string not including the trailing NUL is returned on success,
842 * -1 if the requested string capability couldn't be found, -2 if a system
843 * error was encountered (storage allocation failure).
845 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
846 cgetustr(char *buf, const char *cap, char **str)
855 * Find string capability cap
857 if ((bp = cgetcap(buf, cap, '=')) == NULL)
861 * Conversion / storage allocation loop ... Allocate memory in
862 * chunks SFRAG in size.
864 if ((mem = malloc(SFRAG)) == NULL) {
866 return (-2); /* couldn't even allocate the first fragment */
871 while (*bp != ':' && *bp != '\0') {
874 * There is always room for one more character in mem.
875 * Mp always points just past last character in mem.
876 * Bp always points at next character in buf.
882 * Enforce loop invariant: if no room left in current
883 * buffer, try to get some more.
886 size_t size = mp - mem;
888 if ((mem = realloc(mem, size + SFRAG)) == NULL)
894 *mp++ = '\0'; /* loop invariant let's us do this */
899 * Give back any extra memory and return value and success.
902 char *tmp = realloc(mem, (size_t)(mp - mem));
914 * Cgetnum retrieves the value of the numeric capability cap from the
915 * capability record pointed to by buf. The numeric value is returned in
916 * the long pointed to by num. 0 is returned on success, -1 if the requested
917 * numeric capability couldn't be found.
919 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
920 cgetnum(char *buf, const char *cap, long *num)
927 * Find numeric capability cap
929 bp = cgetcap(buf, cap, '#');
934 * Look at value and determine numeric base:
935 * 0x... or 0X... hexadecimal,
941 if (*bp == 'x' || *bp == 'X') {
950 * Conversion loop ...
954 if ('0' <= *bp && *bp <= '9')
956 else if ('a' <= *bp && *bp <= 'f')
957 digit = 10 + *bp - 'a';
958 else if ('A' <= *bp && *bp <= 'F')
959 digit = 10 + *bp - 'A';
966 n = n * base + digit;
971 * Return value and success.
979 * Compare name field of record.
982 nfcmp(char *nf, char *rec)
987 for (cp = rec; *cp != ':'; cp++)
992 ret = strcmp(nf, rec);