1 /* $NetBSD: getcap.c,v 1.52 2012/06/04 20:56:40 joerg 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.52 2012/06/04 20:56:40 joerg Exp $");
46 #endif /* LIBC_SCCS and not lint */
49 #include "namespace.h"
51 #include <sys/types.h>
52 #include <sys/param.h>
68 #if defined(__weak_alias) && !defined(SMALL)
69 __weak_alias(cgetcap
,_cgetcap
)
70 __weak_alias(cgetclose
,_cgetclose
)
71 __weak_alias(cgetent
,_cgetent
)
72 __weak_alias(cgetfirst
,_cgetfirst
)
73 __weak_alias(cgetmatch
,_cgetmatch
)
74 __weak_alias(cgetnext
,_cgetnext
)
75 __weak_alias(cgetnum
,_cgetnum
)
76 __weak_alias(cgetset
,_cgetset
)
77 __weak_alias(cgetstr
,_cgetstr
)
78 __weak_alias(cgetustr
,_cgetustr
)
79 __weak_alias(csetexpandtc
,_csetexpandtc
)
84 #define ESC ('[' & 037) /* ASCII ESC */
85 #define MAX_RECURSION 32 /* maximum getent recursion */
86 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
90 #define SHADOW (char)2
92 static size_t topreclen
; /* toprec length */
93 static char *toprec
; /* Additional record specified by cgetset() */
94 static int gottoprec
; /* Flag indicating retrieval of toprecord */
95 static int expandtc
= 1; /* flag to expand tc= or not */
98 static int cdbget(DB
*, char **, const char *);
100 static int getent(char **, size_t *, const char * const *, int,
101 const char *, int, char *);
102 static int nfcmp(char *, char *);
105 * Cgetset() allows the addition of a user specified buffer to be added
106 * to the database array, in effect "pushing" the buffer on top of the
107 * virtual database. 0 is returned on success, -1 on failure.
110 cgetset(const char *ent
)
112 const char *source
, *check
;
122 topreclen
= strlen(ent
);
123 if ((toprec
= malloc(topreclen
+ 1)) == NULL
) {
131 while (*source
!= '\0') { /* Strip whitespace */
132 *dest
++ = *source
++; /* Do not check first field */
133 while (*source
== ':') {
135 while (*check
&& (isspace((unsigned char)*check
) ||
136 (*check
=='\\' && isspace((unsigned char)check
[1]))))
151 * Cgetcap searches the capability record buf for the capability cap with
152 * type `type'. A pointer to the value of cap is returned on success, NULL
153 * if the requested capability couldn't be found.
155 * Specifying a type of ':' means that nothing should follow cap (:cap:).
156 * In this case a pointer to the terminating ':' or NUL will be returned if
159 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
163 cgetcap(char *buf
, const char *cap
, int type
)
168 _DIAGASSERT(buf
!= NULL
);
169 _DIAGASSERT(cap
!= NULL
);
174 * Skip past the current capability field - it's either the
175 * name field if this is the first time through the loop, or
176 * the remainder of a field whose name failed to match cap.
181 else if (*bp
++ == ':')
185 * Try to match (cap, type) in buf.
187 for (cp
= cap
; *cp
== *bp
&& *bp
!= '\0'; cp
++, bp
++)
194 if (*bp
!= '\0' && *bp
!= ':')
201 return *bp
== '@' ? NULL
: bp
;
207 * Cgetent extracts the capability record name from the NULL terminated file
208 * array db_array and returns a pointer to a malloc'd copy of it in buf.
209 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
210 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
211 * -1 if the requested record couldn't be found, -2 if a system error was
212 * encountered (couldn't open/read a file, etc.), and -3 if a potential
213 * reference loop is detected.
215 /* coverity[+alloc : arg-*0] */
217 cgetent(char **buf
, const char * const *db_array
, const char *name
)
221 _DIAGASSERT(buf
!= NULL
);
222 _DIAGASSERT(db_array
!= NULL
);
223 _DIAGASSERT(name
!= NULL
);
225 return getent(buf
, &dummy
, db_array
, -1, name
, 0, NULL
);
229 csetexpandtc(int etc
)
235 * Getent implements the functions of cgetent. If fd is non-negative,
236 * *db_array has already been opened and fd is the open file descriptor. We
237 * do this to save time and avoid using up file descriptors for tc=
240 * Getent returns the same success/failure codes as cgetent. On success, a
241 * pointer to a malloc'ed capability record with all tc= capabilities fully
242 * expanded and its length (not including trailing ASCII NUL) are left in
246 * + Allocate memory incrementally as needed in chunks of size BFRAG
247 * for capability buffer.
248 * + Recurse for each tc=name and interpolate result. Stop when all
249 * names interpolated, a name can't be found, or depth exceeds
252 /* coverity[+alloc : arg-*0] */
254 getent(char **cap
, size_t *len
, const char * const *db_array
, int fd
,
255 const char *name
, int depth
, char *nfield
)
259 char pbuf
[MAXPATHLEN
];
264 char *record
, *newrecord
;
265 char *r_end
, *rp
; /* pacify gcc */
266 const char * const *db_p
;
267 int myfd
, eof
, foundit
;
270 _DIAGASSERT(cap
!= NULL
);
271 _DIAGASSERT(len
!= NULL
);
272 _DIAGASSERT(db_array
!= NULL
);
274 _DIAGASSERT(name
!= NULL
);
275 /* nfield may be NULL */
281 * Return with ``loop detected'' error if we've recursed more than
282 * MAX_RECURSION times.
284 if (depth
> MAX_RECURSION
)
288 * Check if we have a top record from cgetset().
290 if (depth
== 0 && toprec
!= NULL
&& cgetmatch(toprec
, name
) == 0) {
291 if ((record
= malloc(topreclen
+ BFRAG
)) == NULL
) {
295 (void)strcpy(record
, toprec
); /* XXX: strcpy is safe */
297 rp
= record
+ topreclen
+ 1;
302 * Allocate first chunk of memory.
304 if ((record
= malloc(BFRAG
)) == NULL
) {
308 r_end
= record
+ BFRAG
;
311 * Loop through database array until finding the record.
314 for (db_p
= db_array
; *db_p
!= NULL
; db_p
++) {
318 * Open database if not already open.
322 (void)lseek(fd
, (off_t
)0, SEEK_SET
);
325 (void)snprintf(pbuf
, sizeof(pbuf
), "%s.db", *db_p
);
327 (capdbp
= dbopen(pbuf
, O_RDONLY
, 0, DB_HASH
, 0))
330 retval
= cdbget(capdbp
, &record
, name
);
332 /* no record available */
333 (void)capdbp
->close(capdbp
);
336 /* save the data; close frees it */
337 clen
= strlen(record
);
338 if ((cbuf
= malloc(clen
+ 1)) == NULL
) {
339 (void)capdbp
->close(capdbp
);
343 memmove(cbuf
, record
, clen
+ 1);
344 if (capdbp
->close(capdbp
) < 0) {
357 fd
= open(*db_p
, O_RDONLY
, 0);
359 /* No error on unfound file. */
366 * Find the requested capability record ...
370 char *b_end
, *bp
, *cp
;
375 * There is always room for one more character in record.
376 * R_end always points just past end of record.
377 * Rp always points just past last character in record.
378 * B_end always points just past last character in buf.
379 * Bp always points at next character in buf.
380 * Cp remembers where the last colon was.
388 * Read in a line implementing (\, newline)
396 n
= read(fd
, buf
, sizeof(buf
));
431 * If the field was `empty' (i.e.
432 * contained only white space), back up
433 * to the colon (eliminating the
440 } else if (c
== '\\') {
442 } else if (c
!= ' ' && c
!= '\t') {
444 * Forget where the colon was, as this
445 * is not an empty field.
452 * Enforce loop invariant: if no room
453 * left in record buffer, try to get
461 newsize
= r_end
- record
+ BFRAG
;
462 newrecord
= realloc(record
, newsize
);
463 if (newrecord
== NULL
) {
471 r_end
= record
+ newsize
;
475 /* Eliminate any white space after the last colon. */
478 /* Loop invariant lets us do this. */
482 * If encountered eof check next file.
488 * Toss blank lines and comments.
490 if (*record
== '\0' || *record
== '#')
494 * See if this is the record we want ...
496 if (cgetmatch(record
, name
) == 0)
497 if (nfield
== NULL
|| !nfcmp(nfield
, record
)) {
499 break; /* found it! */
511 * Got the capability record, but now we have to expand all tc=name
512 * references in it ...
518 size_t ilen
, newilen
;
520 ptrdiff_t diff
, tclen
;
521 char *icap
, *scan
, *tc
, *tcstart
, *tcend
;
525 * There is room for one more character in record.
526 * R_end points just past end of record.
527 * Rp points just past last character in record.
528 * Scan points at remainder of record that needs to be
529 * scanned for tc=name constructs.
533 if ((tc
= cgetcap(scan
, "tc", '=')) == NULL
)
537 * Find end of tc=name and stomp on the trailing `:'
538 * (if present) so we can use it to call ourselves.
553 iret
= getent(&icap
, &ilen
, db_p
, fd
, tc
, depth
+1,
555 newicap
= icap
; /* Put into a register. */
567 /* couldn't resolve tc */
576 /* not interested in name field of tc'ed record */
581 else if (*s
++ == ':')
583 newilen
-= s
- newicap
;
586 /* make sure interpolated record is `:'-terminated */
588 if (*(s
- 1) != ':') {
589 *s
= ':'; /* overwrite NUL with : */
594 * Make sure there's enough room to insert the
597 diff
= newilen
- tclen
;
598 if (diff
>= r_end
- rp
) {
599 ptrdiff_t pos
, tcpos
, tcposend
;
603 newsize
= r_end
- record
+ diff
+ BFRAG
;
604 tcpos
= tcstart
- record
;
605 tcposend
= tcend
- record
;
606 newrecord
= realloc(record
, newsize
);
607 if (newrecord
== NULL
) {
616 r_end
= record
+ newsize
;
618 tcstart
= record
+ tcpos
;
619 tcend
= record
+ tcposend
;
623 * Insert tc'ed record into our record.
625 s
= tcstart
+ newilen
;
626 memmove(s
, tcend
, (size_t)(rp
- tcend
));
627 memmove(tcstart
, newicap
, newilen
);
632 * Start scan on `:' so next cgetcap works properly
633 * (cgetcap always skips first field).
640 * Close file (if we opened it), give back any extra memory, and
641 * return capability, length and success.
645 *len
= rp
- record
- 1; /* don't count NUL */
648 realloc(record
, (size_t)(rp
- record
))) == NULL
) {
664 cdbget(DB
*capdbp
, char **bp
, const char *name
)
669 _DIAGASSERT(capdbp
!= NULL
);
670 _DIAGASSERT(bp
!= NULL
);
671 _DIAGASSERT(name
!= NULL
);
673 key
.data
= __UNCONST(name
);
674 key
.size
= strlen(name
);
677 /* Get the reference. */
678 switch(capdbp
->get(capdbp
, &key
, &data
, 0)) {
685 /* If not an index to another record, leave. */
686 if (((char *)data
.data
)[0] != SHADOW
)
689 key
.data
= (char *)data
.data
+ 1;
690 key
.size
= data
.size
- 1;
693 *bp
= (char *)data
.data
+ 1;
694 return ((char *)(data
.data
))[0] == TCERR
? 1 : 0;
699 * Cgetmatch will return 0 if name is one of the names of the capability
700 * record buf, -1 if not.
703 cgetmatch(const char *buf
, const char *name
)
707 _DIAGASSERT(buf
!= NULL
);
708 _DIAGASSERT(name
!= NULL
);
711 * Start search at beginning of record.
716 * Try to match a record name.
721 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
725 } else if (*bp
++ != *np
++)
729 * Match failed, skip to next name in record.
732 bp
--; /* a '|' or ':' may have stopped the match */
736 if (*bp
== '\0' || *bp
== ':')
737 return -1; /* match failed totally */
738 else if (*bp
++ == '|')
739 break; /* found next name */
744 cgetfirst(char **buf
, const char * const *db_array
)
747 _DIAGASSERT(buf
!= NULL
);
748 _DIAGASSERT(db_array
!= NULL
);
751 return cgetnext(buf
, db_array
);
756 static const char * const *dbp
;
772 * Cgetnext() gets either the first or next entry in the logical database
773 * specified by db_array. It returns 0 upon completion of the database, 1
774 * upon returning an entry with more remaining, and -1 if an error occurs.
776 /* coverity[+alloc : arg-*0] */
778 cgetnext(char **bp
, const char * const *db_array
)
782 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
785 _DIAGASSERT(bp
!= NULL
);
786 _DIAGASSERT(db_array
!= NULL
);
791 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "re")) == NULL
) {
796 if (toprec
!= NULL
&& !gottoprec
) {
800 line
= fgetln(pfp
, &len
);
810 if (*++dbp
== NULL
) {
814 fopen(*dbp
, "re")) == NULL
) {
821 line
[len
- 1] = '\0';
826 if (isspace((unsigned char)*line
) ||
827 *line
== ':' || *line
== '#' || slash
) {
828 if (line
[len
- 2] == '\\')
834 if (line
[len
- 2] == '\\')
842 * Line points to a name line.
844 if (len
> sizeof(nbuf
))
849 for (cp
= line
; *cp
!= '\0'; cp
++) {
862 } else { /* name field extends beyond the line */
863 line
= fgetln(pfp
, &len
);
864 if (line
== NULL
&& pfp
) {
874 line
[len
- 1] = '\0';
877 if (len
> sizeof(buf
))
880 for (cp
= nbuf
; *cp
!= '\0'; cp
++)
881 if (*cp
== '|' || *cp
== ':')
889 * Last argument of getent here should be nbuf if we want true
890 * sequential access in the case of duplicates.
891 * With NULL, getent will return the first entry found
892 * rather than the duplicate entry record. This is a
893 * matter of semantics that should be resolved.
895 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
896 if (status
== -2 || status
== -3)
905 * Cgetstr retrieves the value of the string capability cap from the
906 * capability record pointed to by buf. A pointer to a decoded, NUL
907 * terminated, malloc'd copy of the string is returned in the char *
908 * pointed to by str. The length of the string not including the trailing
909 * NUL is returned on success, -1 if the requested string capability
910 * couldn't be found, -2 if a system error was encountered (storage
911 * allocation failure).
914 cgetstr(char *buf
, const char *cap
, char **str
)
922 _DIAGASSERT(buf
!= NULL
);
923 _DIAGASSERT(cap
!= NULL
);
924 _DIAGASSERT(str
!= NULL
);
927 * Find string capability cap
929 bp
= cgetcap(buf
, cap
, '=');
934 * Conversion / storage allocation loop ... Allocate memory in
935 * chunks SFRAG in size.
937 if ((mem
= malloc(SFRAG
)) == NULL
) {
939 return -2; /* couldn't even allocate the first fragment */
944 while (*bp
!= ':' && *bp
!= '\0') {
947 * There is always room for one more character in mem.
948 * Mp always points just past last character in mem.
949 * Bp always points at next character in buf.
953 if (*bp
== ':' || *bp
== '\0')
954 break; /* drop unfinished escape */
956 } else if (*bp
== '\\') {
958 if (*bp
== ':' || *bp
== '\0')
959 break; /* drop unfinished escape */
960 if ('0' <= *bp
&& *bp
<= '7') {
964 i
= 3; /* maximum of three octal digits */
966 n
= n
* 8 + (*bp
++ - '0');
967 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
970 else switch (*bp
++) {
994 * Catches '\', '^', and
1005 * Enforce loop invariant: if no room left in current
1006 * buffer, try to get some more.
1009 size_t size
= mp
- mem
;
1011 if ((newmem
= realloc(mem
, size
+ SFRAG
)) == NULL
) {
1020 *mp
++ = '\0'; /* loop invariant let's us do this */
1025 * Give back any extra memory and return value and success.
1028 if ((newmem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
) {
1035 _DIAGASSERT(__type_fit(int, len
));
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
) {
1120 _DIAGASSERT(__type_fit(int, len
));
1125 * Cgetnum retrieves the value of the numeric capability cap from the
1126 * capability record pointed to by buf. The numeric value is returned in
1127 * the long pointed to by num. 0 is returned on success, -1 if the requested
1128 * numeric capability couldn't be found.
1131 cgetnum(char *buf
, const char *cap
, long *num
)
1137 _DIAGASSERT(buf
!= NULL
);
1138 _DIAGASSERT(cap
!= NULL
);
1139 _DIAGASSERT(num
!= NULL
);
1142 * Find numeric capability cap
1144 bp
= cgetcap(buf
, cap
, '#');
1149 * Look at value and determine numeric base:
1150 * 0x... or 0X... hexadecimal,
1156 if (*bp
== 'x' || *bp
== 'X') {
1165 * Conversion loop ...
1169 if ('0' <= *bp
&& *bp
<= '9')
1171 else if ('a' <= *bp
&& *bp
<= 'f')
1172 digit
= 10 + *bp
- 'a';
1173 else if ('A' <= *bp
&& *bp
<= 'F')
1174 digit
= 10 + *bp
- 'A';
1181 n
= n
* base
+ digit
;
1186 * Return value and success.
1194 * Compare name field of record.
1197 nfcmp(char *nf
, char *rec
)
1202 _DIAGASSERT(nf
!= NULL
);
1203 _DIAGASSERT(rec
!= NULL
);
1205 for (cp
= rec
; *cp
!= ':'; cp
++)
1210 ret
= strcmp(nf
, rec
);