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. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)getcap.c 8.3 (Berkeley) 3/25/94
33 * $FreeBSD: src/lib/libc/gen/getcap.c,v 1.20 2007/01/09 00:27:53 imp Exp $
34 * $DragonFly: src/lib/libc/gen/getcap.c,v 1.7 2005/11/19 22:32:53 swildner Exp $
37 #include "namespace.h"
38 #include <sys/types.h>
48 #include "un-namespace.h"
54 #define ESC ('[' & 037) /* ASCII ESC */
55 #define MAX_RECURSION 32 /* maximum getent recursion */
56 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
60 #define SHADOW (char)2
62 static size_t topreclen
; /* toprec length */
63 static char *toprec
; /* Additional record specified by cgetset() */
64 static int gottoprec
; /* Flag indicating retrieval of toprecord */
66 static int cdbget(DB
*, char **, const char *);
67 static int getent(char **, u_int
*, char **, int, const char *, int, char *);
68 static int nfcmp(char *, char *);
71 * Cgetset() allows the addition of a user specified buffer to be added
72 * to the database array, in effect "pushing" the buffer on top of the
73 * virtual database. 0 is returned on success, -1 on failure.
76 cgetset(const char *ent
)
85 topreclen
= strlen(ent
);
86 if ((toprec
= malloc (topreclen
+ 1)) == NULL
) {
96 * Cgetcap searches the capability record buf for the capability cap with
97 * type `type'. A pointer to the value of cap is returned on success, NULL
98 * if the requested capability couldn't be found.
100 * Specifying a type of ':' means that nothing should follow cap (:cap:).
101 * In this case a pointer to the terminating ':' or NUL will be returned if
104 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
108 cgetcap(char *buf
, const char *cap
, int type
)
116 * Skip past the current capability field - it's either the
117 * name field if this is the first time through the loop, or
118 * the remainder of a field whose name failed to match cap.
128 * Try to match (cap, type) in buf.
130 for (cp
= cap
; *cp
== *bp
&& *bp
!= '\0'; cp
++, bp
++)
137 if (*bp
!= '\0' && *bp
!= ':')
144 return (*bp
== '@' ? NULL
: bp
);
150 * Cgetent extracts the capability record name from the NULL terminated file
151 * array db_array and returns a pointer to a malloc'd copy of it in buf.
152 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
153 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
154 * -1 if the requested record couldn't be found, -2 if a system error was
155 * encountered (couldn't open/read a file, etc.), and -3 if a potential
156 * reference loop is detected.
159 cgetent(char **buf
, char **db_array
, const char *name
)
163 return (getent(buf
, &dummy
, db_array
, -1, name
, 0, NULL
));
167 * Getent implements the functions of cgetent. If fd is non-negative,
168 * *db_array has already been opened and fd is the open file descriptor. We
169 * do this to save time and avoid using up file descriptors for tc=
172 * Getent returns the same success/failure codes as cgetent. On success, a
173 * pointer to a malloc'ed capability record with all tc= capabilities fully
174 * expanded and its length (not including trailing ASCII NUL) are left in
178 * + Allocate memory incrementally as needed in chunks of size BFRAG
179 * for capability buffer.
180 * + Recurse for each tc=name and interpolate result. Stop when all
181 * names interpolated, a name can't be found, or depth exceeds
185 getent(char **cap
, u_int
*len
, char **db_array
, int fd
, const char *name
,
186 int depth
, char *nfield
)
189 char *r_end
, *rp
, **db_p
;
190 int myfd
, eof
, foundit
, retval
, clen
;
193 char pbuf
[_POSIX_PATH_MAX
];
199 * Return with ``loop detected'' error if we've recursed more than
200 * MAX_RECURSION times.
202 if (depth
> MAX_RECURSION
)
206 * Check if we have a top record from cgetset().
208 if (depth
== 0 && toprec
!= NULL
&& cgetmatch(toprec
, name
) == 0) {
209 if ((record
= malloc (topreclen
+ BFRAG
)) == NULL
) {
213 strcpy(record
, toprec
);
216 rp
= record
+ topreclen
+ 1;
221 * Allocate first chunk of memory.
223 if ((record
= malloc(BFRAG
)) == NULL
) {
227 r_end
= record
+ BFRAG
;
230 * Loop through database array until finding the record.
233 for (db_p
= db_array
; *db_p
!= NULL
; db_p
++) {
237 * Open database if not already open.
241 lseek(fd
, (off_t
)0, SEEK_SET
);
244 snprintf(pbuf
, sizeof(pbuf
), "%s.db", *db_p
);
245 if ((capdbp
= dbopen(pbuf
, O_RDONLY
, 0, DB_HASH
, 0))
248 retval
= cdbget(capdbp
, &record
, name
);
250 /* no record available */
251 capdbp
->close(capdbp
);
254 /* save the data; close frees it */
255 clen
= strlen(record
);
256 cbuf
= malloc(clen
+ 1);
257 memcpy(cbuf
, record
, clen
+ 1);
258 if (capdbp
->close(capdbp
) < 0) {
266 fd
= _open(*db_p
, O_RDONLY
| O_CLOEXEC
, 0);
273 * Find the requested capability record ...
282 * There is always room for one more character in record.
283 * R_end always points just past end of record.
284 * Rp always points just past last character in record.
285 * B_end always points just past last character in buf.
286 * Bp always points at next character in buf.
293 * Read in a line implementing (\, newline)
301 n
= _read(fd
, buf
, sizeof(buf
));
320 if (rp
> record
&& *(rp
-1) == '\\') {
329 * Enforce loop invariant: if no room
330 * left in record buffer, try to get
338 newsize
= r_end
- record
+ BFRAG
;
339 record
= reallocf(record
, newsize
);
340 if (record
== NULL
) {
346 r_end
= record
+ newsize
;
350 /* loop invariant let's us do this */
354 * If encountered eof check next file.
360 * Toss blank lines and comments.
362 if (*record
== '\0' || *record
== '#')
366 * See if this is the record we want ...
368 if (cgetmatch(record
, name
) == 0) {
369 if (nfield
== NULL
|| !nfcmp(nfield
, record
)) {
371 break; /* found it! */
386 * Got the capability record, but now we have to expand all tc=name
387 * references in it ...
393 int diff
, iret
, tclen
;
394 char *icap
, *scan
, *tc
, *tcstart
, *tcend
;
398 * There is room for one more character in record.
399 * R_end points just past end of record.
400 * Rp points just past last character in record.
401 * Scan points at remainder of record that needs to be
402 * scanned for tc=name constructs.
407 if ((tc
= cgetcap(scan
, "tc", '=')) == NULL
)
411 * Find end of tc=name and stomp on the trailing `:'
412 * (if present) so we can use it to call ourselves.
427 iret
= getent(&icap
, &ilen
, db_p
, fd
, tc
, depth
+1,
429 newicap
= icap
; /* Put into a register. */
441 /* couldn't resolve tc */
450 /* not interested in name field of tc'ed record */
458 newilen
-= s
- newicap
;
461 /* make sure interpolated record is `:'-terminated */
464 *s
= ':'; /* overwrite NUL with : */
469 * Make sure there's enough room to insert the
472 diff
= newilen
- tclen
;
473 if (diff
>= r_end
- rp
) {
474 u_int pos
, tcpos
, tcposend
;
478 newsize
= r_end
- record
+ diff
+ BFRAG
;
479 tcpos
= tcstart
- record
;
480 tcposend
= tcend
- record
;
481 record
= reallocf(record
, newsize
);
482 if (record
== NULL
) {
489 r_end
= record
+ newsize
;
491 tcstart
= record
+ tcpos
;
492 tcend
= record
+ tcposend
;
496 * Insert tc'ed record into our record.
498 s
= tcstart
+ newilen
;
499 bcopy(tcend
, s
, rp
- tcend
);
500 bcopy(newicap
, tcstart
, newilen
);
505 * Start scan on `:' so next cgetcap works properly
506 * (cgetcap always skips first field).
513 * Close file (if we opened it), give back any extra memory, and
514 * return capability, length and success.
518 *len
= rp
- record
- 1; /* don't count NUL */
521 reallocf(record
, (size_t)(rp
- record
))) == NULL
) {
533 cdbget(DB
*capdbp
, char **bp
, const char *name
)
538 namebuf
= strdup(name
);
542 key
.size
= strlen(namebuf
);
545 /* Get the reference. */
546 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;
565 return (((char *)(data
.data
))[0] == TCERR
? 1 : 0);
569 * Cgetmatch will return 0 if name is one of the names of the capability
570 * record buf, -1 if not.
573 cgetmatch(const char *buf
, const char *name
)
577 if (name
== NULL
|| *name
== '\0')
581 * Start search at beginning of record.
586 * Try to match a record name.
591 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
600 * Match failed, skip to next name in record.
602 bp
--; /* a '|' or ':' may have stopped the match */
604 if (*bp
== '\0' || *bp
== ':')
605 return (-1); /* match failed totally */
608 break; /* found next name */
617 cgetfirst(char **buf
, char **db_array
)
620 return (cgetnext(buf
, db_array
));
641 * Cgetnext() gets either the first or next entry in the logical database
642 * specified by db_array. It returns 0 upon completion of the database, 1
643 * upon returning an entry with more remaining, and -1 if an error occurs.
646 cgetnext(char **bp
, char **db_array
)
649 int done
, hadreaderr
, savederrno
, status
;
650 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
658 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "r")) == NULL
) {
663 if (toprec
&& !gottoprec
) {
667 line
= fgetln(pfp
, &len
);
668 if (line
== NULL
&& pfp
) {
669 hadreaderr
= ferror(pfp
);
679 if (*++dbp
== NULL
) {
683 fopen(*dbp
, "r")) == NULL
) {
690 line
[len
- 1] = '\0';
695 if (isspace((unsigned char)*line
) ||
696 *line
== ':' || *line
== '#' || slash
) {
697 if (line
[len
- 2] == '\\')
703 if (line
[len
- 2] == '\\')
711 * Line points to a name line.
716 for (cp
= line
; *cp
!= '\0'; cp
++) {
729 } else { /* name field extends beyond the line */
730 line
= fgetln(pfp
, &len
);
731 if (line
== NULL
&& pfp
) {
732 /* Name extends beyond the EOF! */
733 hadreaderr
= ferror(pfp
);
747 line
[len
- 1] = '\0';
751 for(cp
= nbuf
; *cp
!= '\0'; cp
++)
752 if (*cp
== '|' || *cp
== ':')
760 * Last argument of getent here should be nbuf if we want true
761 * sequential access in the case of duplicates.
762 * With NULL, getent will return the first entry found
763 * rather than the duplicate entry record. This is a
764 * matter of semantics that should be resolved.
766 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
767 if (status
== -2 || status
== -3)
776 * Cgetstr retrieves the value of the string capability cap from the
777 * capability record pointed to by buf. A pointer to a decoded, NUL
778 * terminated, malloc'd copy of the string is returned in the char *
779 * pointed to by str. The length of the string not including the trailing
780 * NUL is returned on success, -1 if the requested string capability
781 * couldn't be found, -2 if a system error was encountered (storage
782 * allocation failure).
785 cgetstr(char *buf
, const char *cap
, char **str
)
793 * Find string capability cap
795 bp
= cgetcap(buf
, cap
, '=');
800 * Conversion / storage allocation loop ... Allocate memory in
801 * chunks SFRAG in size.
803 if ((mem
= malloc(SFRAG
)) == NULL
) {
805 return (-2); /* couldn't even allocate the first fragment */
810 while (*bp
!= ':' && *bp
!= '\0') {
813 * There is always room for one more character in mem.
814 * Mp always points just past last character in mem.
815 * Bp always points at next character in buf.
819 if (*bp
== ':' || *bp
== '\0')
820 break; /* drop unfinished escape */
826 } else if (*bp
== '\\') {
828 if (*bp
== ':' || *bp
== '\0')
829 break; /* drop unfinished escape */
830 if ('0' <= *bp
&& *bp
<= '7') {
834 i
= 3; /* maximum of three octal digits */
836 n
= n
* 8 + (*bp
++ - '0');
837 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
840 else switch (*bp
++) {
864 * Catches '\', '^', and
875 * Enforce loop invariant: if no room left in current
876 * buffer, try to get some more.
879 size_t size
= mp
- mem
;
881 if ((mem
= reallocf(mem
, size
+ SFRAG
)) == NULL
)
887 *mp
++ = '\0'; /* loop invariant let's us do this */
892 * Give back any extra memory and return value and success.
895 if ((mem
= reallocf(mem
, (size_t)(mp
- mem
))) == NULL
)
902 * Cgetustr retrieves the value of the string capability cap from the
903 * capability record pointed to by buf. The difference between cgetustr()
904 * and cgetstr() is that cgetustr does not decode escapes but rather treats
905 * all characters literally. A pointer to a NUL terminated malloc'd
906 * copy of the string is returned in the char pointed to by str. The
907 * length of the string not including the trailing NUL is returned on success,
908 * -1 if the requested string capability couldn't be found, -2 if a system
909 * error was encountered (storage allocation failure).
912 cgetustr(char *buf
, const char *cap
, char **str
)
920 * Find string capability cap
922 if ((bp
= cgetcap(buf
, cap
, '=')) == NULL
)
926 * Conversion / storage allocation loop ... Allocate memory in
927 * chunks SFRAG in size.
929 if ((mem
= malloc(SFRAG
)) == NULL
) {
931 return (-2); /* couldn't even allocate the first fragment */
936 while (*bp
!= ':' && *bp
!= '\0') {
939 * There is always room for one more character in mem.
940 * Mp always points just past last character in mem.
941 * Bp always points at next character in buf.
947 * Enforce loop invariant: if no room left in current
948 * buffer, try to get some more.
951 size_t size
= mp
- mem
;
953 if ((mem
= reallocf(mem
, size
+ SFRAG
)) == NULL
)
959 *mp
++ = '\0'; /* loop invariant let's us do this */
964 * Give back any extra memory and return value and success.
967 if ((mem
= reallocf(mem
, (size_t)(mp
- mem
))) == NULL
)
974 * Cgetnum retrieves the value of the numeric capability cap from the
975 * capability record pointed to by buf. The numeric value is returned in
976 * the long pointed to by num. 0 is returned on success, -1 if the requested
977 * numeric capability couldn't be found.
980 cgetnum(char *buf
, const char *cap
, long *num
)
987 * Find numeric capability cap
989 bp
= cgetcap(buf
, cap
, '#');
994 * Look at value and determine numeric base:
995 * 0x... or 0X... hexadecimal,
1001 if (*bp
== 'x' || *bp
== 'X') {
1010 * Conversion loop ...
1014 if ('0' <= *bp
&& *bp
<= '9')
1016 else if ('a' <= *bp
&& *bp
<= 'f')
1017 digit
= 10 + *bp
- 'a';
1018 else if ('A' <= *bp
&& *bp
<= 'F')
1019 digit
= 10 + *bp
- 'A';
1026 n
= n
* base
+ digit
;
1031 * Return value and success.
1039 * Compare name field of record.
1042 nfcmp(char *nf
, char *rec
)
1047 for (cp
= rec
; *cp
!= ':'; cp
++)
1052 ret
= strcmp(nf
, rec
);