2 * Copyright (c) 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Casey Leedom of Lawrence Livermore National Laboratory.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * $FreeBSD: src/lib/libc/gen/getcap.c,v 1.11.2.2 2001/01/15 06:48:09 gad Exp $
37 * $DragonFly: src/lib/libc/gen/getcap.c,v 1.3 2003/11/12 20:21:23 eirikn Exp $
39 * @(#)getcap.c 8.3 (Berkeley) 3/25/94
42 #include <sys/types.h>
56 #define ESC ('[' & 037) /* ASCII ESC */
57 #define MAX_RECURSION 32 /* maximum getent recursion */
58 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
62 #define SHADOW (char)2
64 static size_t topreclen; /* toprec length */
65 static char *toprec; /* Additional record specified by cgetset() */
66 static int gottoprec; /* Flag indicating retrieval of toprecord */
68 static int cdbget (DB *, char **, char *);
69 static int getent (char **, u_int *, char **, int, char *, int, char *);
70 static int nfcmp (char *, char *);
73 * Cgetset() allows the addition of a user specified buffer to be added
74 * to the database array, in effect "pushing" the buffer on top of the
75 * virtual database. 0 is returned on success, -1 on failure.
88 topreclen = strlen(ent);
89 if ((toprec = malloc (topreclen + 1)) == NULL) {
94 (void)strcpy(toprec, ent);
99 * Cgetcap searches the capability record buf for the capability cap with
100 * type `type'. A pointer to the value of cap is returned on success, NULL
101 * if the requested capability couldn't be found.
103 * Specifying a type of ':' means that nothing should follow cap (:cap:).
104 * In this case a pointer to the terminating ':' or NUL will be returned if
107 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
111 cgetcap(buf, cap, type)
115 register char *bp, *cp;
120 * Skip past the current capability field - it's either the
121 * name field if this is the first time through the loop, or
122 * the remainder of a field whose name failed to match cap.
132 * Try to match (cap, type) in buf.
134 for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
141 if (*bp != '\0' && *bp != ':')
148 return (*bp == '@' ? NULL : bp);
154 * Cgetent extracts the capability record name from the NULL terminated file
155 * array db_array and returns a pointer to a malloc'd copy of it in buf.
156 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
157 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
158 * -1 if the requested record couldn't be found, -2 if a system error was
159 * encountered (couldn't open/read a file, etc.), and -3 if a potential
160 * reference loop is detected.
163 cgetent(buf, db_array, name)
164 char **buf, **db_array, *name;
168 return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
172 * Getent implements the functions of cgetent. If fd is non-negative,
173 * *db_array has already been opened and fd is the open file descriptor. We
174 * do this to save time and avoid using up file descriptors for tc=
177 * Getent returns the same success/failure codes as cgetent. On success, a
178 * pointer to a malloc'ed capability record with all tc= capabilities fully
179 * expanded and its length (not including trailing ASCII NUL) are left in
183 * + Allocate memory incrementally as needed in chunks of size BFRAG
184 * for capability buffer.
185 * + Recurse for each tc=name and interpolate result. Stop when all
186 * names interpolated, a name can't be found, or depth exceeds
190 getent(cap, len, db_array, fd, name, depth, nfield)
191 char **cap, **db_array, *name, *nfield;
196 register char *r_end, *rp, **db_p;
197 int myfd, eof, foundit, retval, clen;
200 char pbuf[_POSIX_PATH_MAX];
203 * Return with ``loop detected'' error if we've recursed more than
204 * MAX_RECURSION times.
206 if (depth > MAX_RECURSION)
210 * Check if we have a top record from cgetset().
212 if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
213 if ((record = malloc (topreclen + BFRAG)) == NULL) {
217 (void)strcpy(record, toprec);
220 rp = record + topreclen + 1;
225 * Allocate first chunk of memory.
227 if ((record = malloc(BFRAG)) == NULL) {
231 r_end = record + BFRAG;
234 * Loop through database array until finding the record.
237 for (db_p = db_array; *db_p != NULL; db_p++) {
241 * Open database if not already open.
245 (void)lseek(fd, (off_t)0, SEEK_SET);
248 (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
249 if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
252 retval = cdbget(capdbp, &record, name);
254 /* no record available */
255 (void)capdbp->close(capdbp);
258 /* save the data; close frees it */
259 clen = strlen(record);
260 cbuf = malloc(clen + 1);
261 memcpy(cbuf, record, clen + 1);
262 if (capdbp->close(capdbp) < 0) {
270 fd = _open(*db_p, O_RDONLY, 0);
277 * Find the requested capability record ...
281 register char *b_end, *bp;
286 * There is always room for one more character in record.
287 * R_end always points just past end of record.
288 * Rp always points just past last character in record.
289 * B_end always points just past last character in buf.
290 * Bp always points at next character in buf.
297 * Read in a line implementing (\, newline)
305 n = _read(fd, buf, sizeof(buf));
324 if (rp > record && *(rp-1) == '\\') {
333 * Enforce loop invariant: if no room
334 * left in record buffer, try to get
342 newsize = r_end - record + BFRAG;
343 record = reallocf(record, newsize);
344 if (record == NULL) {
350 r_end = record + newsize;
354 /* loop invariant let's us do this */
358 * If encountered eof check next file.
364 * Toss blank lines and comments.
366 if (*record == '\0' || *record == '#')
370 * See if this is the record we want ...
372 if (cgetmatch(record, name) == 0) {
373 if (nfield == NULL || !nfcmp(nfield, record)) {
375 break; /* found it! */
390 * Got the capability record, but now we have to expand all tc=name
391 * references in it ...
394 register char *newicap, *s;
395 register int newilen;
397 int diff, iret, tclen;
398 char *icap, *scan, *tc, *tcstart, *tcend;
402 * There is room for one more character in record.
403 * R_end points just past end of record.
404 * Rp points just past last character in record.
405 * Scan points at remainder of record that needs to be
406 * scanned for tc=name constructs.
411 if ((tc = cgetcap(scan, "tc", '=')) == NULL)
415 * Find end of tc=name and stomp on the trailing `:'
416 * (if present) so we can use it to call ourselves.
431 iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
433 newicap = icap; /* Put into a register. */
445 /* couldn't resolve tc */
454 /* not interested in name field of tc'ed record */
462 newilen -= s - newicap;
465 /* make sure interpolated record is `:'-terminated */
468 *s = ':'; /* overwrite NUL with : */
473 * Make sure there's enough room to insert the
476 diff = newilen - tclen;
477 if (diff >= r_end - rp) {
478 u_int pos, tcpos, tcposend;
482 newsize = r_end - record + diff + BFRAG;
483 tcpos = tcstart - record;
484 tcposend = tcend - record;
485 record = reallocf(record, newsize);
486 if (record == NULL) {
493 r_end = record + newsize;
495 tcstart = record + tcpos;
496 tcend = record + tcposend;
500 * Insert tc'ed record into our record.
502 s = tcstart + newilen;
503 bcopy(tcend, s, rp - tcend);
504 bcopy(newicap, tcstart, newilen);
509 * Start scan on `:' so next cgetcap works properly
510 * (cgetcap always skips first field).
517 * Close file (if we opened it), give back any extra memory, and
518 * return capability, length and success.
522 *len = rp - record - 1; /* don't count NUL */
525 reallocf(record, (size_t)(rp - record))) == NULL) {
537 cdbget(capdbp, bp, name)
544 key.size = strlen(name);
547 /* Get the reference. */
548 switch(capdbp->get(capdbp, &key, &data, 0)) {
555 /* If not an index to another record, leave. */
556 if (((char *)data.data)[0] != SHADOW)
559 key.data = (char *)data.data + 1;
560 key.size = data.size - 1;
563 *bp = (char *)data.data + 1;
564 return (((char *)(data.data))[0] == TCERR ? 1 : 0);
568 * Cgetmatch will return 0 if name is one of the names of the capability
569 * record buf, -1 if not.
575 register char *np, *bp;
578 * Start search at beginning of record.
583 * Try to match a record name.
588 if (*bp == '|' || *bp == ':' || *bp == '\0')
597 * Match failed, skip to next name in record.
599 bp--; /* a '|' or ':' may have stopped the match */
601 if (*bp == '\0' || *bp == ':')
602 return (-1); /* match failed totally */
605 break; /* found next name */
614 cgetfirst(buf, db_array)
615 char **buf, **db_array;
618 return (cgetnext(buf, db_array));
639 * Cgetnext() gets either the first or next entry in the logical database
640 * specified by db_array. It returns 0 upon completion of the database, 1
641 * upon returning an entry with more remaining, and -1 if an error occurs.
644 cgetnext(bp, db_array)
649 int done, hadreaderr, i, savederrno, status;
650 char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
656 if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
661 if (toprec && !gottoprec) {
665 line = fgetln(pfp, &len);
666 if (line == NULL && pfp) {
667 hadreaderr = ferror(pfp);
677 if (*++dbp == NULL) {
681 fopen(*dbp, "r")) == NULL) {
688 line[len - 1] = '\0';
693 if (isspace((unsigned char)*line) ||
694 *line == ':' || *line == '#' || slash) {
695 if (line[len - 2] == '\\')
701 if (line[len - 2] == '\\')
709 * Line points to a name line.
715 for (cp = line; *cp != '\0'; cp++) {
728 } else { /* name field extends beyond the line */
729 line = fgetln(pfp, &len);
730 if (line == NULL && pfp) {
731 /* Name extends beyond the EOF! */
732 hadreaderr = ferror(pfp);
746 line[len - 1] = '\0';
750 for(cp = nbuf; *cp != '\0'; cp++)
751 if (*cp == '|' || *cp == ':')
759 * Last argument of getent here should be nbuf if we want true
760 * sequential access in the case of duplicates.
761 * With NULL, getent will return the first entry found
762 * rather than the duplicate entry record. This is a
763 * matter of semantics that should be resolved.
765 status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
766 if (status == -2 || status == -3)
775 * Cgetstr retrieves the value of the string capability cap from the
776 * capability record pointed to by buf. A pointer to a decoded, NUL
777 * terminated, malloc'd copy of the string is returned in the char *
778 * pointed to by str. The length of the string not including the trailing
779 * NUL is returned on success, -1 if the requested string capability
780 * couldn't be found, -2 if a system error was encountered (storage
781 * allocation failure).
784 cgetstr(buf, cap, str)
788 register u_int m_room;
789 register char *bp, *mp;
794 * Find string capability cap
796 bp = cgetcap(buf, cap, '=');
801 * Conversion / storage allocation loop ... Allocate memory in
802 * chunks SFRAG in size.
804 if ((mem = malloc(SFRAG)) == NULL) {
806 return (-2); /* couldn't even allocate the first fragment */
811 while (*bp != ':' && *bp != '\0') {
814 * There is always room for one more character in mem.
815 * Mp always points just past last character in mem.
816 * Bp always points at next character in buf.
820 if (*bp == ':' || *bp == '\0')
821 break; /* drop unfinished escape */
827 } else if (*bp == '\\') {
829 if (*bp == ':' || *bp == '\0')
830 break; /* drop unfinished escape */
831 if ('0' <= *bp && *bp <= '7') {
835 i = 3; /* maximum of three octal digits */
837 n = n * 8 + (*bp++ - '0');
838 } while (--i && '0' <= *bp && *bp <= '7');
841 else switch (*bp++) {
865 * Catches '\', '^', and
876 * Enforce loop invariant: if no room left in current
877 * buffer, try to get some more.
880 size_t size = mp - mem;
882 if ((mem = reallocf(mem, size + SFRAG)) == NULL)
888 *mp++ = '\0'; /* loop invariant let's us do this */
893 * Give back any extra memory and return value and success.
896 if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
903 * Cgetustr retrieves the value of the string capability cap from the
904 * capability record pointed to by buf. The difference between cgetustr()
905 * and cgetstr() is that cgetustr does not decode escapes but rather treats
906 * all characters literally. A pointer to a NUL terminated malloc'd
907 * copy of the string is returned in the char pointed to by str. The
908 * length of the string not including the trailing NUL is returned on success,
909 * -1 if the requested string capability couldn't be found, -2 if a system
910 * error was encountered (storage allocation failure).
913 cgetustr(buf, cap, str)
914 char *buf, *cap, **str;
916 register u_int m_room;
917 register char *bp, *mp;
922 * Find string capability cap
924 if ((bp = cgetcap(buf, cap, '=')) == NULL)
928 * Conversion / storage allocation loop ... Allocate memory in
929 * chunks SFRAG in size.
931 if ((mem = malloc(SFRAG)) == NULL) {
933 return (-2); /* couldn't even allocate the first fragment */
938 while (*bp != ':' && *bp != '\0') {
941 * There is always room for one more character in mem.
942 * Mp always points just past last character in mem.
943 * Bp always points at next character in buf.
949 * Enforce loop invariant: if no room left in current
950 * buffer, try to get some more.
953 size_t size = mp - mem;
955 if ((mem = reallocf(mem, size + SFRAG)) == NULL)
961 *mp++ = '\0'; /* loop invariant let's us do this */
966 * Give back any extra memory and return value and success.
969 if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
976 * Cgetnum retrieves the value of the numeric capability cap from the
977 * capability record pointed to by buf. The numeric value is returned in
978 * the long pointed to by num. 0 is returned on success, -1 if the requested
979 * numeric capability couldn't be found.
982 cgetnum(buf, cap, num)
987 register int base, digit;
991 * Find numeric capability cap
993 bp = cgetcap(buf, cap, '#');
998 * Look at value and determine numeric base:
999 * 0x... or 0X... hexadecimal,
1005 if (*bp == 'x' || *bp == 'X') {
1014 * Conversion loop ...
1018 if ('0' <= *bp && *bp <= '9')
1020 else if ('a' <= *bp && *bp <= 'f')
1021 digit = 10 + *bp - 'a';
1022 else if ('A' <= *bp && *bp <= 'F')
1023 digit = 10 + *bp - 'A';
1030 n = n * base + digit;
1035 * Return value and success.
1043 * Compare name field of record.
1052 for (cp = rec; *cp != ':'; cp++)
1057 ret = strcmp(nf, rec);