1 /* $NetBSD: getcap.c,v 1.56 2014/09/24 13:18:52 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.56 2014/09/24 13:18:52 christos 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
)
257 char *record
, *newrecord
;
258 char *r_end
, *rp
; /* pacify gcc */
259 const char * const *db_p
;
260 int myfd
, eof
, foundit
;
263 _DIAGASSERT(cap
!= NULL
);
264 _DIAGASSERT(len
!= NULL
);
265 _DIAGASSERT(db_array
!= NULL
);
267 _DIAGASSERT(name
!= NULL
);
268 /* nfield may be NULL */
274 * Return with ``loop detected'' error if we've recursed more than
275 * MAX_RECURSION times.
277 if (depth
> MAX_RECURSION
)
281 * Check if we have a top record from cgetset().
283 if (depth
== 0 && toprec
!= NULL
&& cgetmatch(toprec
, name
) == 0) {
284 if ((record
= malloc(topreclen
+ BFRAG
)) == NULL
) {
288 (void)strcpy(record
, toprec
); /* XXX: strcpy is safe */
290 rp
= record
+ topreclen
+ 1;
295 * Allocate first chunk of memory.
297 if ((record
= malloc(BFRAG
)) == NULL
) {
301 r_end
= record
+ BFRAG
;
304 * Loop through database array until finding the record.
307 for (db_p
= db_array
; *db_p
!= NULL
; db_p
++) {
311 * Open database if not already open.
315 (void)lseek(fd
, (off_t
)0, SEEK_SET
);
319 char pbuf
[MAXPATHLEN
];
324 (void)snprintf(pbuf
, sizeof(pbuf
), "%s.db", *db_p
);
325 if ((capdbp
= dbopen(pbuf
, O_RDONLY
| O_CLOEXEC
, 0,
326 DB_HASH
, 0)) != NULL
) {
328 retval
= cdbget(capdbp
, &record
, name
);
330 /* no record available */
331 (void)capdbp
->close(capdbp
);
334 /* save the data; close frees it */
335 clen
= strlen(record
);
336 if ((cbuf
= malloc(clen
+ 1)) == NULL
) {
337 (void)capdbp
->close(capdbp
);
341 memmove(cbuf
, record
, clen
+ 1);
342 if (capdbp
->close(capdbp
) < 0) {
355 fd
= open(*db_p
, O_RDONLY
| O_CLOEXEC
, 0);
357 /* No error on unfound file. */
364 * Find the requested capability record ...
368 char *b_end
, *bp
, *cp
;
373 * There is always room for one more character in record.
374 * R_end always points just past end of record.
375 * Rp always points just past last character in record.
376 * B_end always points just past last character in buf.
377 * Bp always points at next character in buf.
378 * Cp remembers where the last colon was.
386 * Read in a line implementing (\, newline)
394 n
= read(fd
, buf
, sizeof(buf
));
429 * If the field was `empty' (i.e.
430 * contained only white space), back up
431 * to the colon (eliminating the
438 } else if (c
== '\\') {
440 } else if (c
!= ' ' && c
!= '\t') {
442 * Forget where the colon was, as this
443 * is not an empty field.
450 * Enforce loop invariant: if no room
451 * left in record buffer, try to get
459 newsize
= r_end
- record
+ BFRAG
;
460 newrecord
= realloc(record
, newsize
);
461 if (newrecord
== NULL
) {
469 r_end
= record
+ newsize
;
473 /* Eliminate any white space after the last colon. */
476 /* Loop invariant lets us do this. */
480 * If encountered eof check next file.
486 * Toss blank lines and comments.
488 if (*record
== '\0' || *record
== '#')
492 * See if this is the record we want ...
494 if (cgetmatch(record
, name
) == 0)
495 if (nfield
== NULL
|| !nfcmp(nfield
, record
)) {
497 break; /* found it! */
509 * Got the capability record, but now we have to expand all tc=name
510 * references in it ...
516 size_t ilen
, newilen
;
518 ptrdiff_t diff
, tclen
;
519 char *icap
, *scan
, *tc
, *tcstart
, *tcend
;
523 * There is room for one more character in record.
524 * R_end points just past end of record.
525 * Rp points just past last character in record.
526 * Scan points at remainder of record that needs to be
527 * scanned for tc=name constructs.
531 if ((tc
= cgetcap(scan
, "tc", '=')) == NULL
)
535 * Find end of tc=name and stomp on the trailing `:'
536 * (if present) so we can use it to call ourselves.
551 iret
= getent(&icap
, &ilen
, db_p
, fd
, tc
, depth
+1,
553 newicap
= icap
; /* Put into a register. */
565 /* couldn't resolve tc */
574 /* not interested in name field of tc'ed record */
579 else if (*s
++ == ':')
581 newilen
-= s
- newicap
;
584 /* make sure interpolated record is `:'-terminated */
586 if (*(s
- 1) != ':') {
587 *s
= ':'; /* overwrite NUL with : */
592 * Make sure there's enough room to insert the
595 diff
= newilen
- tclen
;
596 if (diff
>= r_end
- rp
) {
597 ptrdiff_t pos
, tcpos
, tcposend
;
601 newsize
= r_end
- record
+ diff
+ BFRAG
;
602 tcpos
= tcstart
- record
;
603 tcposend
= tcend
- record
;
604 newrecord
= realloc(record
, newsize
);
605 if (newrecord
== NULL
) {
614 r_end
= record
+ newsize
;
616 tcstart
= record
+ tcpos
;
617 tcend
= record
+ tcposend
;
621 * Insert tc'ed record into our record.
623 s
= tcstart
+ newilen
;
624 memmove(s
, tcend
, (size_t)(rp
- tcend
));
625 memmove(tcstart
, newicap
, newilen
);
630 * Start scan on `:' so next cgetcap works properly
631 * (cgetcap always skips first field).
638 * Close file (if we opened it), give back any extra memory, and
639 * return capability, length and success.
643 *len
= rp
- record
- 1; /* don't count NUL */
646 realloc(record
, (size_t)(rp
- record
))) == NULL
) {
662 cdbget(DB
*capdbp
, char **bp
, const char *name
)
667 _DIAGASSERT(capdbp
!= NULL
);
668 _DIAGASSERT(bp
!= NULL
);
669 _DIAGASSERT(name
!= NULL
);
671 key
.data
= __UNCONST(name
);
672 key
.size
= strlen(name
);
675 /* Get the reference. */
676 switch(capdbp
->get(capdbp
, &key
, &data
, 0)) {
683 /* If not an index to another record, leave. */
684 if (((char *)data
.data
)[0] != SHADOW
)
687 key
.data
= (char *)data
.data
+ 1;
688 key
.size
= data
.size
- 1;
691 *bp
= (char *)data
.data
+ 1;
692 return ((char *)(data
.data
))[0] == TCERR
? 1 : 0;
697 * Cgetmatch will return 0 if name is one of the names of the capability
698 * record buf, -1 if not.
701 cgetmatch(const char *buf
, const char *name
)
705 _DIAGASSERT(buf
!= NULL
);
706 _DIAGASSERT(name
!= NULL
);
709 * Start search at beginning of record.
714 * Try to match a record name.
719 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
723 } else if (*bp
++ != *np
++)
727 * Match failed, skip to next name in record.
730 bp
--; /* a '|' or ':' may have stopped the match */
734 if (*bp
== '\0' || *bp
== ':')
735 return -1; /* match failed totally */
736 else if (*bp
++ == '|')
737 break; /* found next name */
742 cgetfirst(char **buf
, const char * const *db_array
)
745 _DIAGASSERT(buf
!= NULL
);
746 _DIAGASSERT(db_array
!= NULL
);
749 return cgetnext(buf
, db_array
);
754 static const char * const *dbp
;
770 * Cgetnext() gets either the first or next entry in the logical database
771 * specified by db_array. It returns 0 upon completion of the database, 1
772 * upon returning an entry with more remaining, and -1 if an error occurs.
774 /* coverity[+alloc : arg-*0] */
776 cgetnext(char **bp
, const char * const *db_array
)
780 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
783 _DIAGASSERT(bp
!= NULL
);
784 _DIAGASSERT(db_array
!= NULL
);
789 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "re")) == NULL
) {
794 if (toprec
!= NULL
&& !gottoprec
) {
798 line
= fgetln(pfp
, &len
);
808 if (*++dbp
== NULL
) {
812 fopen(*dbp
, "re")) == NULL
) {
819 line
[len
- 1] = '\0';
824 if (isspace((unsigned char)*line
) ||
825 *line
== ':' || *line
== '#' || slash
) {
826 if (line
[len
- 2] == '\\')
832 if (line
[len
- 2] == '\\')
840 * Line points to a name line.
842 if (len
> sizeof(nbuf
))
847 for (cp
= line
; *cp
!= '\0'; cp
++) {
860 } else { /* name field extends beyond the line */
861 line
= fgetln(pfp
, &len
);
862 if (line
== NULL
&& pfp
) {
872 line
[len
- 1] = '\0';
875 if (len
> sizeof(buf
))
878 for (cp
= nbuf
; *cp
!= '\0'; cp
++)
879 if (*cp
== '|' || *cp
== ':')
887 * Last argument of getent here should be nbuf if we want true
888 * sequential access in the case of duplicates.
889 * With NULL, getent will return the first entry found
890 * rather than the duplicate entry record. This is a
891 * matter of semantics that should be resolved.
893 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
894 if (status
== -2 || status
== -3)
903 * Cgetstr retrieves the value of the string capability cap from the
904 * capability record pointed to by buf. A pointer to a decoded, NUL
905 * terminated, malloc'd copy of the string is returned in the char *
906 * pointed to by str. The length of the string not including the trailing
907 * NUL is returned on success, -1 if the requested string capability
908 * couldn't be found, -2 if a system error was encountered (storage
909 * allocation failure).
912 cgetstr(char *buf
, const char *cap
, char **str
)
920 _DIAGASSERT(buf
!= NULL
);
921 _DIAGASSERT(cap
!= NULL
);
922 _DIAGASSERT(str
!= NULL
);
925 * Find string capability cap
927 bp
= cgetcap(buf
, cap
, '=');
932 * Conversion / storage allocation loop ... Allocate memory in
933 * chunks SFRAG in size.
935 if ((mem
= malloc(SFRAG
)) == NULL
) {
937 return -2; /* couldn't even allocate the first fragment */
942 while (*bp
!= ':' && *bp
!= '\0') {
945 * There is always room for one more character in mem.
946 * Mp always points just past last character in mem.
947 * Bp always points at next character in buf.
951 if (*bp
== ':' || *bp
== '\0')
952 break; /* drop unfinished escape */
954 } else if (*bp
== '\\') {
956 if (*bp
== ':' || *bp
== '\0')
957 break; /* drop unfinished escape */
958 if ('0' <= *bp
&& *bp
<= '7') {
962 i
= 3; /* maximum of three octal digits */
964 n
= n
* 8 + (*bp
++ - '0');
965 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
968 else switch (*bp
++) {
992 * Catches '\', '^', and
1003 * Enforce loop invariant: if no room left in current
1004 * buffer, try to get some more.
1007 size_t size
= mp
- mem
;
1009 if ((newmem
= realloc(mem
, size
+ SFRAG
)) == NULL
) {
1018 *mp
++ = '\0'; /* loop invariant let's us do this */
1023 * Give back any extra memory and return value and success.
1026 if ((newmem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
) {
1033 _DIAGASSERT(__type_fit(int, len
));
1038 * Cgetustr retrieves the value of the string capability cap from the
1039 * capability record pointed to by buf. The difference between cgetustr()
1040 * and cgetstr() is that cgetustr does not decode escapes but rather treats
1041 * all characters literally. A pointer to a NUL terminated malloc'd
1042 * copy of the string is returned in the char pointed to by str. The
1043 * length of the string not including the trailing NUL is returned on success,
1044 * -1 if the requested string capability couldn't be found, -2 if a system
1045 * error was encountered (storage allocation failure).
1048 cgetustr(char *buf
, const char *cap
, char **str
)
1056 _DIAGASSERT(buf
!= NULL
);
1057 _DIAGASSERT(cap
!= NULL
);
1058 _DIAGASSERT(str
!= NULL
);
1061 * Find string capability cap
1063 if ((bp
= cgetcap(buf
, cap
, '=')) == NULL
)
1067 * Conversion / storage allocation loop ... Allocate memory in
1068 * chunks SFRAG in size.
1070 if ((mem
= malloc(SFRAG
)) == NULL
) {
1072 return -2; /* couldn't even allocate the first fragment */
1077 while (*bp
!= ':' && *bp
!= '\0') {
1080 * There is always room for one more character in mem.
1081 * Mp always points just past last character in mem.
1082 * Bp always points at next character in buf.
1088 * Enforce loop invariant: if no room left in current
1089 * buffer, try to get some more.
1092 size_t size
= mp
- mem
;
1094 if ((newmem
= realloc(mem
, size
+ SFRAG
)) == NULL
) {
1103 *mp
++ = '\0'; /* loop invariant let's us do this */
1108 * Give back any extra memory and return value and success.
1111 if ((newmem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
) {
1118 _DIAGASSERT(__type_fit(int, len
));
1123 * Cgetnum retrieves the value of the numeric capability cap from the
1124 * capability record pointed to by buf. The numeric value is returned in
1125 * the long pointed to by num. 0 is returned on success, -1 if the requested
1126 * numeric capability couldn't be found.
1129 cgetnum(char *buf
, const char *cap
, long *num
)
1135 _DIAGASSERT(buf
!= NULL
);
1136 _DIAGASSERT(cap
!= NULL
);
1137 _DIAGASSERT(num
!= NULL
);
1140 * Find numeric capability cap
1142 bp
= cgetcap(buf
, cap
, '#');
1147 * Look at value and determine numeric base:
1148 * 0x... or 0X... hexadecimal,
1154 if (*bp
== 'x' || *bp
== 'X') {
1163 * Conversion loop ...
1167 if ('0' <= *bp
&& *bp
<= '9')
1169 else if ('a' <= *bp
&& *bp
<= 'f')
1170 digit
= 10 + *bp
- 'a';
1171 else if ('A' <= *bp
&& *bp
<= 'F')
1172 digit
= 10 + *bp
- 'A';
1179 n
= n
* base
+ digit
;
1184 * Return value and success.
1192 * Compare name field of record.
1195 nfcmp(char *nf
, char *rec
)
1200 _DIAGASSERT(nf
!= NULL
);
1201 _DIAGASSERT(rec
!= NULL
);
1203 for (cp
= rec
; *cp
!= ':'; cp
++)
1208 ret
= strcmp(nf
, rec
);