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.7 2005/11/19 23:32:53 swildner Exp $
39 * @(#)getcap.c 8.3 (Berkeley) 3/25/94
42 #include "namespace.h"
43 #include <sys/types.h>
53 #include "un-namespace.h"
59 #define ESC ('[' & 037) /* ASCII ESC */
60 #define MAX_RECURSION 32 /* maximum getent recursion */
61 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
65 #define SHADOW (char)2
67 static size_t topreclen
; /* toprec length */
68 static char *toprec
; /* Additional record specified by cgetset() */
69 static int gottoprec
; /* Flag indicating retrieval of toprecord */
71 static int cdbget (DB
*, char **, char *);
72 static int getent (char **, u_int
*, char **, int, char *, int, char *);
73 static int nfcmp (char *, char *);
76 * Cgetset() allows the addition of a user specified buffer to be added
77 * to the database array, in effect "pushing" the buffer on top of the
78 * virtual database. 0 is returned on success, -1 on failure.
90 topreclen
= strlen(ent
);
91 if ((toprec
= malloc (topreclen
+ 1)) == NULL
) {
101 * Cgetcap searches the capability record buf for the capability cap with
102 * type `type'. A pointer to the value of cap is returned on success, NULL
103 * if the requested capability couldn't be found.
105 * Specifying a type of ':' means that nothing should follow cap (:cap:).
106 * In this case a pointer to the terminating ':' or NUL will be returned if
109 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
113 cgetcap(char *buf
, char *cap
, int type
)
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(char **buf
, char **db_array
, char *name
)
167 return (getent(buf
, &dummy
, db_array
, -1, name
, 0, NULL
));
171 * Getent implements the functions of cgetent. If fd is non-negative,
172 * *db_array has already been opened and fd is the open file descriptor. We
173 * do this to save time and avoid using up file descriptors for tc=
176 * Getent returns the same success/failure codes as cgetent. On success, a
177 * pointer to a malloc'ed capability record with all tc= capabilities fully
178 * expanded and its length (not including trailing ASCII NUL) are left in
182 * + Allocate memory incrementally as needed in chunks of size BFRAG
183 * for capability buffer.
184 * + Recurse for each tc=name and interpolate result. Stop when all
185 * names interpolated, a name can't be found, or depth exceeds
189 getent(char **cap
, u_int
*len
, char **db_array
, int fd
, char *name
, int depth
,
193 char *r_end
, *rp
, **db_p
;
194 int myfd
, eof
, foundit
, retval
, clen
;
197 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 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 lseek(fd
, (off_t
)0, SEEK_SET
);
248 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 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 ...
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 ...
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(DB
*capdbp
, char **bp
, char *name
)
542 key
.size
= strlen(name
);
545 /* Get the reference. */
546 switch(capdbp
->get(capdbp
, &key
, &data
, 0)) {
553 /* If not an index to another record, leave. */
554 if (((char *)data
.data
)[0] != SHADOW
)
557 key
.data
= (char *)data
.data
+ 1;
558 key
.size
= data
.size
- 1;
561 *bp
= (char *)data
.data
+ 1;
562 return (((char *)(data
.data
))[0] == TCERR
? 1 : 0);
566 * Cgetmatch will return 0 if name is one of the names of the capability
567 * record buf, -1 if not.
570 cgetmatch(char *buf
, char *name
)
575 * Start search at beginning of record.
580 * Try to match a record name.
585 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
594 * Match failed, skip to next name in record.
596 bp
--; /* a '|' or ':' may have stopped the match */
598 if (*bp
== '\0' || *bp
== ':')
599 return (-1); /* match failed totally */
602 break; /* found next name */
611 cgetfirst(char **buf
, char **db_array
)
614 return (cgetnext(buf
, db_array
));
635 * Cgetnext() gets either the first or next entry in the logical database
636 * specified by db_array. It returns 0 upon completion of the database, 1
637 * upon returning an entry with more remaining, and -1 if an error occurs.
640 cgetnext(char **bp
, char **db_array
)
643 int done
, hadreaderr
, i
, savederrno
, status
;
644 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
652 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "r")) == NULL
) {
657 if (toprec
&& !gottoprec
) {
661 line
= fgetln(pfp
, &len
);
662 if (line
== NULL
&& pfp
) {
663 hadreaderr
= ferror(pfp
);
673 if (*++dbp
== NULL
) {
677 fopen(*dbp
, "r")) == NULL
) {
684 line
[len
- 1] = '\0';
689 if (isspace((unsigned char)*line
) ||
690 *line
== ':' || *line
== '#' || slash
) {
691 if (line
[len
- 2] == '\\')
697 if (line
[len
- 2] == '\\')
705 * Line points to a name line.
711 for (cp
= line
; *cp
!= '\0'; cp
++) {
724 } else { /* name field extends beyond the line */
725 line
= fgetln(pfp
, &len
);
726 if (line
== NULL
&& pfp
) {
727 /* Name extends beyond the EOF! */
728 hadreaderr
= ferror(pfp
);
742 line
[len
- 1] = '\0';
746 for(cp
= nbuf
; *cp
!= '\0'; cp
++)
747 if (*cp
== '|' || *cp
== ':')
755 * Last argument of getent here should be nbuf if we want true
756 * sequential access in the case of duplicates.
757 * With NULL, getent will return the first entry found
758 * rather than the duplicate entry record. This is a
759 * matter of semantics that should be resolved.
761 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
762 if (status
== -2 || status
== -3)
771 * Cgetstr retrieves the value of the string capability cap from the
772 * capability record pointed to by buf. A pointer to a decoded, NUL
773 * terminated, malloc'd copy of the string is returned in the char *
774 * pointed to by str. The length of the string not including the trailing
775 * NUL is returned on success, -1 if the requested string capability
776 * couldn't be found, -2 if a system error was encountered (storage
777 * allocation failure).
780 cgetstr(char *buf
, char *cap
, char **str
)
788 * Find string capability cap
790 bp
= cgetcap(buf
, cap
, '=');
795 * Conversion / storage allocation loop ... Allocate memory in
796 * chunks SFRAG in size.
798 if ((mem
= malloc(SFRAG
)) == NULL
) {
800 return (-2); /* couldn't even allocate the first fragment */
805 while (*bp
!= ':' && *bp
!= '\0') {
808 * There is always room for one more character in mem.
809 * Mp always points just past last character in mem.
810 * Bp always points at next character in buf.
814 if (*bp
== ':' || *bp
== '\0')
815 break; /* drop unfinished escape */
821 } else if (*bp
== '\\') {
823 if (*bp
== ':' || *bp
== '\0')
824 break; /* drop unfinished escape */
825 if ('0' <= *bp
&& *bp
<= '7') {
829 i
= 3; /* maximum of three octal digits */
831 n
= n
* 8 + (*bp
++ - '0');
832 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
835 else switch (*bp
++) {
859 * Catches '\', '^', and
870 * Enforce loop invariant: if no room left in current
871 * buffer, try to get some more.
874 size_t size
= mp
- mem
;
876 if ((mem
= reallocf(mem
, size
+ SFRAG
)) == NULL
)
882 *mp
++ = '\0'; /* loop invariant let's us do this */
887 * Give back any extra memory and return value and success.
890 if ((mem
= reallocf(mem
, (size_t)(mp
- mem
))) == NULL
)
897 * Cgetustr retrieves the value of the string capability cap from the
898 * capability record pointed to by buf. The difference between cgetustr()
899 * and cgetstr() is that cgetustr does not decode escapes but rather treats
900 * all characters literally. A pointer to a NUL terminated malloc'd
901 * copy of the string is returned in the char pointed to by str. The
902 * length of the string not including the trailing NUL is returned on success,
903 * -1 if the requested string capability couldn't be found, -2 if a system
904 * error was encountered (storage allocation failure).
907 cgetustr(char *buf
, char *cap
, char **str
)
915 * Find string capability cap
917 if ((bp
= cgetcap(buf
, cap
, '=')) == NULL
)
921 * Conversion / storage allocation loop ... Allocate memory in
922 * chunks SFRAG in size.
924 if ((mem
= malloc(SFRAG
)) == NULL
) {
926 return (-2); /* couldn't even allocate the first fragment */
931 while (*bp
!= ':' && *bp
!= '\0') {
934 * There is always room for one more character in mem.
935 * Mp always points just past last character in mem.
936 * Bp always points at next character in buf.
942 * Enforce loop invariant: if no room left in current
943 * buffer, try to get some more.
946 size_t size
= mp
- mem
;
948 if ((mem
= reallocf(mem
, size
+ SFRAG
)) == NULL
)
954 *mp
++ = '\0'; /* loop invariant let's us do this */
959 * Give back any extra memory and return value and success.
962 if ((mem
= reallocf(mem
, (size_t)(mp
- mem
))) == NULL
)
969 * Cgetnum retrieves the value of the numeric capability cap from the
970 * capability record pointed to by buf. The numeric value is returned in
971 * the long pointed to by num. 0 is returned on success, -1 if the requested
972 * numeric capability couldn't be found.
975 cgetnum(char *buf
, char *cap
, long *num
)
982 * Find numeric capability cap
984 bp
= cgetcap(buf
, cap
, '#');
989 * Look at value and determine numeric base:
990 * 0x... or 0X... hexadecimal,
996 if (*bp
== 'x' || *bp
== 'X') {
1005 * Conversion loop ...
1009 if ('0' <= *bp
&& *bp
<= '9')
1011 else if ('a' <= *bp
&& *bp
<= 'f')
1012 digit
= 10 + *bp
- 'a';
1013 else if ('A' <= *bp
&& *bp
<= 'F')
1014 digit
= 10 + *bp
- 'A';
1021 n
= n
* base
+ digit
;
1026 * Return value and success.
1034 * Compare name field of record.
1037 nfcmp(char *nf
, char *rec
)
1042 for (cp
= rec
; *cp
!= ':'; cp
++)
1047 ret
= strcmp(nf
, rec
);