1 /* $NetBSD: getcap.c,v 1.48 2008/02/02 20:56:46 christos 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
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
39 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
42 static char sccsid
[] = "@(#)getcap.c 8.3 (Berkeley) 3/25/94";
44 __RCSID("$NetBSD: getcap.c,v 1.48 2008/02/02 20:56:46 christos Exp $");
46 #endif /* LIBC_SCCS and not lint */
49 #include "namespace.h"
51 #include <sys/types.h>
52 #include <sys/param.h>
68 __weak_alias(cgetcap
,_cgetcap
)
69 __weak_alias(cgetclose
,_cgetclose
)
70 __weak_alias(cgetent
,_cgetent
)
71 __weak_alias(cgetfirst
,_cgetfirst
)
72 __weak_alias(cgetmatch
,_cgetmatch
)
73 __weak_alias(cgetnext
,_cgetnext
)
74 __weak_alias(cgetnum
,_cgetnum
)
75 __weak_alias(cgetset
,_cgetset
)
76 __weak_alias(cgetstr
,_cgetstr
)
77 __weak_alias(cgetustr
,_cgetustr
)
78 __weak_alias(csetexpandtc
,_csetexpandtc
)
83 #define ESC ('[' & 037) /* ASCII ESC */
84 #define MAX_RECURSION 32 /* maximum getent recursion */
85 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
89 #define SHADOW (char)2
91 static size_t topreclen
; /* toprec length */
92 static char *toprec
; /* Additional record specified by cgetset() */
93 static int gottoprec
; /* Flag indicating retrieval of toprecord */
94 static int expandtc
= 1; /* flag to expand tc= or not */
97 static int cdbget(DB
*, char **, const char *);
99 static int getent(char **, size_t *, const char * const *, int,
100 const char *, int, char *);
101 static int nfcmp(char *, char *);
104 * Cgetset() allows the addition of a user specified buffer to be added
105 * to the database array, in effect "pushing" the buffer on top of the
106 * virtual database. 0 is returned on success, -1 on failure.
109 cgetset(const char *ent
)
111 const char *source
, *check
;
121 topreclen
= strlen(ent
);
122 if ((toprec
= malloc(topreclen
+ 1)) == NULL
) {
130 while (*source
!= '\0') { /* Strip whitespace */
131 *dest
++ = *source
++; /* Do not check first field */
132 while (*source
== ':') {
134 while (*check
&& (isspace((unsigned char)*check
) ||
135 (*check
=='\\' && isspace((unsigned char)check
[1]))))
150 * Cgetcap searches the capability record buf for the capability cap with
151 * type `type'. A pointer to the value of cap is returned on success, NULL
152 * if the requested capability couldn't be found.
154 * Specifying a type of ':' means that nothing should follow cap (:cap:).
155 * In this case a pointer to the terminating ':' or NUL will be returned if
158 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
162 cgetcap(buf
, cap
, type
)
170 _DIAGASSERT(buf
!= NULL
);
171 _DIAGASSERT(cap
!= NULL
);
176 * Skip past the current capability field - it's either the
177 * name field if this is the first time through the loop, or
178 * the remainder of a field whose name failed to match cap.
183 else if (*bp
++ == ':')
187 * Try to match (cap, type) in buf.
189 for (cp
= cap
; *cp
== *bp
&& *bp
!= '\0'; cp
++, bp
++)
196 if (*bp
!= '\0' && *bp
!= ':')
203 return *bp
== '@' ? NULL
: bp
;
209 * Cgetent extracts the capability record name from the NULL terminated file
210 * array db_array and returns a pointer to a malloc'd copy of it in buf.
211 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
212 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
213 * -1 if the requested record couldn't be found, -2 if a system error was
214 * encountered (couldn't open/read a file, etc.), and -3 if a potential
215 * reference loop is detected.
217 /* coverity[+alloc : arg-*0] */
219 cgetent(char **buf
, const char * const *db_array
, const char *name
)
223 _DIAGASSERT(buf
!= NULL
);
224 _DIAGASSERT(db_array
!= NULL
);
225 _DIAGASSERT(name
!= NULL
);
227 return getent(buf
, &dummy
, db_array
, -1, name
, 0, NULL
);
231 csetexpandtc(int etc
)
237 * Getent implements the functions of cgetent. If fd is non-negative,
238 * *db_array has already been opened and fd is the open file descriptor. We
239 * do this to save time and avoid using up file descriptors for tc=
242 * Getent returns the same success/failure codes as cgetent. On success, a
243 * pointer to a malloc'ed capability record with all tc= capabilities fully
244 * expanded and its length (not including trailing ASCII NUL) are left in
248 * + Allocate memory incrementally as needed in chunks of size BFRAG
249 * for capability buffer.
250 * + Recurse for each tc=name and interpolate result. Stop when all
251 * names interpolated, a name can't be found, or depth exceeds
254 /* coverity[+alloc : arg-*0] */
256 getent(char **cap
, size_t *len
, const char * const *db_array
, int fd
,
257 const char *name
, int depth
, char *nfield
)
261 char pbuf
[MAXPATHLEN
];
266 char *record
, *newrecord
;
267 char *r_end
, *rp
; /* pacify gcc */
268 const char * const *db_p
;
269 int myfd
, eof
, foundit
;
272 _DIAGASSERT(cap
!= NULL
);
273 _DIAGASSERT(len
!= NULL
);
274 _DIAGASSERT(db_array
!= NULL
);
276 _DIAGASSERT(name
!= NULL
);
277 /* nfield may be NULL */
283 * Return with ``loop detected'' error if we've recursed more than
284 * MAX_RECURSION times.
286 if (depth
> MAX_RECURSION
)
290 * Check if we have a top record from cgetset().
292 if (depth
== 0 && toprec
!= NULL
&& cgetmatch(toprec
, name
) == 0) {
293 if ((record
= malloc(topreclen
+ BFRAG
)) == NULL
) {
297 (void)strcpy(record
, toprec
); /* XXX: strcpy is safe */
299 rp
= record
+ topreclen
+ 1;
304 * Allocate first chunk of memory.
306 if ((record
= malloc(BFRAG
)) == NULL
) {
310 r_end
= record
+ BFRAG
;
313 * Loop through database array until finding the record.
316 for (db_p
= db_array
; *db_p
!= NULL
; db_p
++) {
320 * Open database if not already open.
324 (void)lseek(fd
, (off_t
)0, SEEK_SET
);
327 (void)snprintf(pbuf
, sizeof(pbuf
), "%s.db", *db_p
);
329 (capdbp
= dbopen(pbuf
, O_RDONLY
, 0, DB_HASH
, 0))
332 retval
= cdbget(capdbp
, &record
, name
);
334 /* no record available */
335 (void)capdbp
->close(capdbp
);
338 /* save the data; close frees it */
339 clen
= strlen(record
);
340 if ((cbuf
= malloc(clen
+ 1)) == NULL
) {
341 (void)capdbp
->close(capdbp
);
345 memmove(cbuf
, record
, clen
+ 1);
346 if (capdbp
->close(capdbp
) < 0) {
359 fd
= open(*db_p
, O_RDONLY
, 0);
361 /* No error on unfound file. */
368 * Find the requested capability record ...
372 char *b_end
, *bp
, *cp
;
377 * There is always room for one more character in record.
378 * R_end always points just past end of record.
379 * Rp always points just past last character in record.
380 * B_end always points just past last character in buf.
381 * Bp always points at next character in buf.
382 * Cp remembers where the last colon was.
390 * Read in a line implementing (\, newline)
398 n
= read(fd
, buf
, sizeof(buf
));
433 * If the field was `empty' (i.e.
434 * contained only white space), back up
435 * to the colon (eliminating the
442 } else if (c
== '\\') {
444 } else if (c
!= ' ' && c
!= '\t') {
446 * Forget where the colon was, as this
447 * is not an empty field.
454 * Enforce loop invariant: if no room
455 * left in record buffer, try to get
463 newsize
= r_end
- record
+ BFRAG
;
464 newrecord
= realloc(record
, newsize
);
465 if (newrecord
== NULL
) {
473 r_end
= record
+ newsize
;
477 /* Eliminate any white space after the last colon. */
480 /* Loop invariant lets us do this. */
484 * If encountered eof check next file.
490 * Toss blank lines and comments.
492 if (*record
== '\0' || *record
== '#')
496 * See if this is the record we want ...
498 if (cgetmatch(record
, name
) == 0)
499 if (nfield
== NULL
|| !nfcmp(nfield
, record
)) {
501 break; /* found it! */
513 * Got the capability record, but now we have to expand all tc=name
514 * references in it ...
520 size_t ilen
, newilen
;
521 int diff
, iret
, tclen
;
522 char *icap
, *scan
, *tc
, *tcstart
, *tcend
;
526 * There is room for one more character in record.
527 * R_end points just past end of record.
528 * Rp points just past last character in record.
529 * Scan points at remainder of record that needs to be
530 * scanned for tc=name constructs.
534 if ((tc
= cgetcap(scan
, "tc", '=')) == NULL
)
538 * Find end of tc=name and stomp on the trailing `:'
539 * (if present) so we can use it to call ourselves.
554 iret
= getent(&icap
, &ilen
, db_p
, fd
, tc
, depth
+1,
556 newicap
= icap
; /* Put into a register. */
568 /* couldn't resolve tc */
577 /* not interested in name field of tc'ed record */
582 else if (*s
++ == ':')
584 newilen
-= s
- newicap
;
587 /* make sure interpolated record is `:'-terminated */
589 if (*(s
- 1) != ':') {
590 *s
= ':'; /* overwrite NUL with : */
595 * Make sure there's enough room to insert the
598 diff
= newilen
- tclen
;
599 if (diff
>= r_end
- rp
) {
600 u_int pos
, tcpos
, tcposend
;
604 newsize
= r_end
- record
+ diff
+ BFRAG
;
605 tcpos
= tcstart
- record
;
606 tcposend
= tcend
- record
;
607 newrecord
= realloc(record
, newsize
);
608 if (newrecord
== NULL
) {
617 r_end
= record
+ newsize
;
619 tcstart
= record
+ tcpos
;
620 tcend
= record
+ tcposend
;
624 * Insert tc'ed record into our record.
626 s
= tcstart
+ newilen
;
627 memmove(s
, tcend
, (size_t)(rp
- tcend
));
628 memmove(tcstart
, newicap
, newilen
);
633 * Start scan on `:' so next cgetcap works properly
634 * (cgetcap always skips first field).
641 * Close file (if we opened it), give back any extra memory, and
642 * return capability, length and success.
646 *len
= rp
- record
- 1; /* don't count NUL */
649 realloc(record
, (size_t)(rp
- record
))) == NULL
) {
665 cdbget(DB
*capdbp
, char **bp
, const char *name
)
670 _DIAGASSERT(capdbp
!= NULL
);
671 _DIAGASSERT(bp
!= NULL
);
672 _DIAGASSERT(name
!= NULL
);
674 key
.data
= __UNCONST(name
);
675 key
.size
= strlen(name
);
678 /* Get the reference. */
679 switch(capdbp
->get(capdbp
, &key
, &data
, 0)) {
686 /* If not an index to another record, leave. */
687 if (((char *)data
.data
)[0] != SHADOW
)
690 key
.data
= (char *)data
.data
+ 1;
691 key
.size
= data
.size
- 1;
694 *bp
= (char *)data
.data
+ 1;
695 return ((char *)(data
.data
))[0] == TCERR
? 1 : 0;
700 * Cgetmatch will return 0 if name is one of the names of the capability
701 * record buf, -1 if not.
704 cgetmatch(const char *buf
, const char *name
)
708 _DIAGASSERT(buf
!= NULL
);
709 _DIAGASSERT(name
!= NULL
);
712 * Start search at beginning of record.
717 * Try to match a record name.
722 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
726 } else if (*bp
++ != *np
++)
730 * Match failed, skip to next name in record.
733 bp
--; /* a '|' or ':' may have stopped the match */
737 if (*bp
== '\0' || *bp
== ':')
738 return -1; /* match failed totally */
739 else if (*bp
++ == '|')
740 break; /* found next name */
745 cgetfirst(char **buf
, const char * const *db_array
)
748 _DIAGASSERT(buf
!= NULL
);
749 _DIAGASSERT(db_array
!= NULL
);
752 return cgetnext(buf
, db_array
);
757 static const char * const *dbp
;
773 * Cgetnext() gets either the first or next entry in the logical database
774 * specified by db_array. It returns 0 upon completion of the database, 1
775 * upon returning an entry with more remaining, and -1 if an error occurs.
777 /* coverity[+alloc : arg-*0] */
779 cgetnext(char **bp
, const char * const *db_array
)
783 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
786 _DIAGASSERT(bp
!= NULL
);
787 _DIAGASSERT(db_array
!= NULL
);
792 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "r")) == NULL
) {
797 if (toprec
!= NULL
&& !gottoprec
) {
801 line
= fgetln(pfp
, &len
);
811 if (*++dbp
== NULL
) {
815 fopen(*dbp
, "r")) == NULL
) {
822 line
[len
- 1] = '\0';
827 if (isspace((unsigned char)*line
) ||
828 *line
== ':' || *line
== '#' || slash
) {
829 if (line
[len
- 2] == '\\')
835 if (line
[len
- 2] == '\\')
843 * Line points to a name line.
845 if (len
> sizeof(nbuf
))
850 for (cp
= line
; *cp
!= '\0'; cp
++) {
863 } else { /* name field extends beyond the line */
864 line
= fgetln(pfp
, &len
);
865 if (line
== NULL
&& pfp
) {
875 line
[len
- 1] = '\0';
878 if (len
> sizeof(buf
))
881 for (cp
= nbuf
; *cp
!= '\0'; cp
++)
882 if (*cp
== '|' || *cp
== ':')
890 * Last argument of getent here should be nbuf if we want true
891 * sequential access in the case of duplicates.
892 * With NULL, getent will return the first entry found
893 * rather than the duplicate entry record. This is a
894 * matter of semantics that should be resolved.
896 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
897 if (status
== -2 || status
== -3)
906 * Cgetstr retrieves the value of the string capability cap from the
907 * capability record pointed to by buf. A pointer to a decoded, NUL
908 * terminated, malloc'd copy of the string is returned in the char *
909 * pointed to by str. The length of the string not including the trailing
910 * NUL is returned on success, -1 if the requested string capability
911 * couldn't be found, -2 if a system error was encountered (storage
912 * allocation failure).
915 cgetstr(char *buf
, const char *cap
, char **str
)
923 _DIAGASSERT(buf
!= NULL
);
924 _DIAGASSERT(cap
!= NULL
);
925 _DIAGASSERT(str
!= NULL
);
928 * Find string capability cap
930 bp
= cgetcap(buf
, cap
, '=');
935 * Conversion / storage allocation loop ... Allocate memory in
936 * chunks SFRAG in size.
938 if ((mem
= malloc(SFRAG
)) == NULL
) {
940 return -2; /* couldn't even allocate the first fragment */
945 while (*bp
!= ':' && *bp
!= '\0') {
948 * There is always room for one more character in mem.
949 * Mp always points just past last character in mem.
950 * Bp always points at next character in buf.
954 if (*bp
== ':' || *bp
== '\0')
955 break; /* drop unfinished escape */
957 } else if (*bp
== '\\') {
959 if (*bp
== ':' || *bp
== '\0')
960 break; /* drop unfinished escape */
961 if ('0' <= *bp
&& *bp
<= '7') {
965 i
= 3; /* maximum of three octal digits */
967 n
= n
* 8 + (*bp
++ - '0');
968 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
971 else switch (*bp
++) {
995 * Catches '\', '^', and
1006 * Enforce loop invariant: if no room left in current
1007 * buffer, try to get some more.
1010 size_t size
= mp
- mem
;
1012 if ((newmem
= realloc(mem
, size
+ SFRAG
)) == NULL
) {
1021 *mp
++ = '\0'; /* loop invariant let's us do this */
1026 * Give back any extra memory and return value and success.
1029 if ((newmem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
) {
1040 * Cgetustr retrieves the value of the string capability cap from the
1041 * capability record pointed to by buf. The difference between cgetustr()
1042 * and cgetstr() is that cgetustr does not decode escapes but rather treats
1043 * all characters literally. A pointer to a NUL terminated malloc'd
1044 * copy of the string is returned in the char pointed to by str. The
1045 * length of the string not including the trailing NUL is returned on success,
1046 * -1 if the requested string capability couldn't be found, -2 if a system
1047 * error was encountered (storage allocation failure).
1050 cgetustr(char *buf
, const char *cap
, char **str
)
1058 _DIAGASSERT(buf
!= NULL
);
1059 _DIAGASSERT(cap
!= NULL
);
1060 _DIAGASSERT(str
!= NULL
);
1063 * Find string capability cap
1065 if ((bp
= cgetcap(buf
, cap
, '=')) == NULL
)
1069 * Conversion / storage allocation loop ... Allocate memory in
1070 * chunks SFRAG in size.
1072 if ((mem
= malloc(SFRAG
)) == NULL
) {
1074 return -2; /* couldn't even allocate the first fragment */
1079 while (*bp
!= ':' && *bp
!= '\0') {
1082 * There is always room for one more character in mem.
1083 * Mp always points just past last character in mem.
1084 * Bp always points at next character in buf.
1090 * Enforce loop invariant: if no room left in current
1091 * buffer, try to get some more.
1094 size_t size
= mp
- mem
;
1096 if ((newmem
= realloc(mem
, size
+ SFRAG
)) == NULL
) {
1105 *mp
++ = '\0'; /* loop invariant let's us do this */
1110 * Give back any extra memory and return value and success.
1113 if ((newmem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
) {
1124 * Cgetnum retrieves the value of the numeric capability cap from the
1125 * capability record pointed to by buf. The numeric value is returned in
1126 * the long pointed to by num. 0 is returned on success, -1 if the requested
1127 * numeric capability couldn't be found.
1130 cgetnum(char *buf
, const char *cap
, long *num
)
1136 _DIAGASSERT(buf
!= NULL
);
1137 _DIAGASSERT(cap
!= NULL
);
1138 _DIAGASSERT(num
!= NULL
);
1141 * Find numeric capability cap
1143 bp
= cgetcap(buf
, cap
, '#');
1148 * Look at value and determine numeric base:
1149 * 0x... or 0X... hexadecimal,
1155 if (*bp
== 'x' || *bp
== 'X') {
1164 * Conversion loop ...
1168 if ('0' <= *bp
&& *bp
<= '9')
1170 else if ('a' <= *bp
&& *bp
<= 'f')
1171 digit
= 10 + *bp
- 'a';
1172 else if ('A' <= *bp
&& *bp
<= 'F')
1173 digit
= 10 + *bp
- 'A';
1180 n
= n
* base
+ digit
;
1185 * Return value and success.
1193 * Compare name field of record.
1196 nfcmp(char *nf
, char *rec
)
1201 _DIAGASSERT(nf
!= NULL
);
1202 _DIAGASSERT(rec
!= NULL
);
1204 for (cp
= rec
; *cp
!= ':'; cp
++)
1209 ret
= strcmp(nf
, rec
);