1 /* $NetBSD: getcap.c,v 1.29 1999/03/29 09:27:29 abs 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
41 #include <sys/types.h>
43 #if defined(HAVE_DB_185_H)
45 #elif defined(HAVE_DB_H)
60 #define ESC ('[' & 037) /* ASCII ESC */
61 #define MAX_RECURSION 32 /* maximum getent recursion */
62 #define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */
66 #define SHADOW (char)2
68 static size_t topreclen
; /* toprec length */
69 static char *toprec
; /* Additional record specified by cgetset() */
70 static int gottoprec
; /* Flag indicating retrieval of toprecord */
73 * Don't use db support unless its build into libc but we dont
74 * check for that now, so just disable the code.
76 #if defined(HAVE_DBOPEN) && defined(HAVE_DB_H)
82 static int cdbget (DB
*, char **, const char *);
84 static int getent (char **, size_t *, char **, int, const char *, int, char *);
85 static int nfcmp (char *, char *);
88 int ROKEN_LIB_FUNCTION
cgetset(const char *ent
);
89 char *ROKEN_LIB_FUNCTION
cgetcap(char *buf
, const char *cap
, int type
);
90 int ROKEN_LIB_FUNCTION
cgetent(char **buf
, char **db_array
, const char *name
);
91 int ROKEN_LIB_FUNCTION
cgetmatch(const char *buf
, const char *name
);
92 int ROKEN_LIB_FUNCTION
cgetclose(void);
94 int cgetfirst(char **buf
, char **db_array
);
95 int cgetnext(char **bp
, char **db_array
);
97 int ROKEN_LIB_FUNCTION
cgetstr(char *buf
, const char *cap
, char **str
);
98 int ROKEN_LIB_FUNCTION
cgetustr(char *buf
, const char *cap
, char **str
);
99 int ROKEN_LIB_FUNCTION
cgetnum(char *buf
, const char *cap
, long *num
);
101 * Cgetset() allows the addition of a user specified buffer to be added
102 * to the database array, in effect "pushing" the buffer on top of the
103 * virtual database. 0 is returned on success, -1 on failure.
105 int ROKEN_LIB_FUNCTION
106 cgetset(const char *ent
)
108 const char *source
, *check
;
118 topreclen
= strlen(ent
);
119 if ((toprec
= malloc (topreclen
+ 1)) == NULL
) {
127 while (*source
) { /* Strip whitespace */
128 *dest
++ = *source
++; /* Do not check first field */
129 while (*source
== ':') {
131 while (*check
&& (isspace((unsigned char)*check
) ||
132 (*check
=='\\' && isspace((unsigned char)check
[1]))))
147 * Cgetcap searches the capability record buf for the capability cap with
148 * type `type'. A pointer to the value of cap is returned on success, NULL
149 * if the requested capability couldn't be found.
151 * Specifying a type of ':' means that nothing should follow cap (:cap:).
152 * In this case a pointer to the terminating ':' or NUL will be returned if
155 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
158 char * ROKEN_LIB_FUNCTION
159 cgetcap(char *buf
, const char *cap
, int type
)
167 * Skip past the current capability field - it's either the
168 * name field if this is the first time through the loop, or
169 * the remainder of a field whose name failed to match cap.
179 * Try to match (cap, type) in buf.
181 for (cp
= cap
; *cp
== *bp
&& *bp
!= '\0'; cp
++, bp
++)
188 if (*bp
!= '\0' && *bp
!= ':')
195 return (*bp
== '@' ? NULL
: bp
);
201 * Cgetent extracts the capability record name from the NULL terminated file
202 * array db_array and returns a pointer to a malloc'd copy of it in buf.
203 * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
204 * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success,
205 * -1 if the requested record couldn't be found, -2 if a system error was
206 * encountered (couldn't open/read a file, etc.), and -3 if a potential
207 * reference loop is detected.
209 int ROKEN_LIB_FUNCTION
210 cgetent(char **buf
, char **db_array
, const char *name
)
214 return (getent(buf
, &dummy
, db_array
, -1, name
, 0, NULL
));
218 * Getent implements the functions of cgetent. If fd is non-negative,
219 * *db_array has already been opened and fd is the open file descriptor. We
220 * do this to save time and avoid using up file descriptors for tc=
223 * Getent returns the same success/failure codes as cgetent. On success, a
224 * pointer to a malloc'ed capability record with all tc= capabilities fully
225 * expanded and its length (not including trailing ASCII NUL) are left in
229 * + Allocate memory incrementally as needed in chunks of size BFRAG
230 * for capability buffer.
231 * + Recurse for each tc=name and interpolate result. Stop when all
232 * names interpolated, a name can't be found, or depth exceeds
236 getent(char **cap
, size_t *len
, char **db_array
, int fd
,
237 const char *name
, int depth
, char *nfield
)
239 char *r_end
, *rp
= NULL
, **db_p
; /* pacify gcc */
240 int myfd
= 0, eof
, foundit
;
245 * Return with ``loop detected'' error if we've recursed more than
246 * MAX_RECURSION times.
248 if (depth
> MAX_RECURSION
)
252 * Check if we have a top record from cgetset().
254 if (depth
== 0 && toprec
!= NULL
&& cgetmatch(toprec
, name
) == 0) {
255 size_t len
= topreclen
+ BFRAG
;
256 if ((record
= malloc (len
)) == NULL
) {
260 (void)strlcpy(record
, toprec
, len
);
262 rp
= record
+ topreclen
+ 1;
267 * Allocate first chunk of memory.
269 if ((record
= malloc(BFRAG
)) == NULL
) {
273 r_end
= record
+ BFRAG
;
276 * Loop through database array until finding the record.
279 for (db_p
= db_array
; *db_p
!= NULL
; db_p
++) {
283 * Open database if not already open.
287 (void)lseek(fd
, (off_t
)0, SEEK_SET
);
290 char pbuf
[_POSIX_PATH_MAX
];
296 (void)snprintf(pbuf
, sizeof(pbuf
), "%s.db", *db_p
);
297 if ((capdbp
= dbopen(pbuf
, O_RDONLY
, 0, DB_HASH
, 0))
300 retval
= cdbget(capdbp
, &record
, name
);
302 /* no record available */
303 (void)capdbp
->close(capdbp
);
306 /* save the data; close frees it */
307 clen
= strlen(record
);
308 cbuf
= malloc(clen
+ 1);
309 memmove(cbuf
, record
, clen
+ 1);
310 if (capdbp
->close(capdbp
) < 0) {
320 fd
= open(*db_p
, O_RDONLY
, 0);
322 /* No error on unfound file. */
329 * Find the requested capability record ...
333 char *b_end
, *bp
, *cp
;
338 * There is always room for one more character in record.
339 * R_end always points just past end of record.
340 * Rp always points just past last character in record.
341 * B_end always points just past last character in buf.
342 * Bp always points at next character in buf.
343 * Cp remembers where the last colon was.
352 * Read in a line implementing (\, newline)
360 n
= read(fd
, buf
, sizeof(buf
));
392 * If the field was `empty' (i.e.
393 * contained only white space), back up
394 * to the colon (eliminating the
401 } else if (c
== '\\') {
403 } else if (c
!= ' ' && c
!= '\t') {
405 * Forget where the colon was, as this
406 * is not an empty field.
413 * Enforce loop invariant: if no room
414 * left in record buffer, try to get
422 newsize
= r_end
- record
+ BFRAG
;
423 record
= realloc(record
, newsize
);
424 if (record
== NULL
) {
430 r_end
= record
+ newsize
;
434 /* Eliminate any white space after the last colon. */
437 /* Loop invariant lets us do this. */
441 * If encountered eof check next file.
447 * Toss blank lines and comments.
449 if (*record
== '\0' || *record
== '#')
453 * See if this is the record we want ...
455 if (cgetmatch(record
, name
) == 0) {
456 if (nfield
== NULL
|| !nfcmp(nfield
, record
)) {
458 break; /* found it! */
471 * Got the capability record, but now we have to expand all tc=name
472 * references in it ...
476 size_t ilen
, newilen
;
477 int diff
, iret
, tclen
;
478 char *icap
, *scan
, *tc
, *tcstart
, *tcend
;
482 * There is room for one more character in record.
483 * R_end points just past end of record.
484 * Rp points just past last character in record.
485 * Scan points at remainder of record that needs to be
486 * scanned for tc=name constructs.
491 if ((tc
= cgetcap(scan
, "tc", '=')) == NULL
)
495 * Find end of tc=name and stomp on the trailing `:'
496 * (if present) so we can use it to call ourselves.
511 iret
= getent(&icap
, &ilen
, db_p
, fd
, tc
, depth
+1,
513 newicap
= icap
; /* Put into a register. */
525 /* couldn't resolve tc */
534 /* not interested in name field of tc'ed record */
542 newilen
-= s
- newicap
;
545 /* make sure interpolated record is `:'-terminated */
548 *s
= ':'; /* overwrite NUL with : */
553 * Make sure there's enough room to insert the
556 diff
= newilen
- tclen
;
557 if (diff
>= r_end
- rp
) {
558 u_int pos
, tcpos
, tcposend
;
562 newsize
= r_end
- record
+ diff
+ BFRAG
;
563 tcpos
= tcstart
- record
;
564 tcposend
= tcend
- record
;
565 record
= realloc(record
, newsize
);
566 if (record
== NULL
) {
573 r_end
= record
+ newsize
;
575 tcstart
= record
+ tcpos
;
576 tcend
= record
+ tcposend
;
580 * Insert tc'ed record into our record.
582 s
= tcstart
+ newilen
;
583 memmove(s
, tcend
, (size_t)(rp
- tcend
));
584 memmove(tcstart
, newicap
, newilen
);
589 * Start scan on `:' so next cgetcap works properly
590 * (cgetcap always skips first field).
597 * Close file (if we opened it), give back any extra memory, and
598 * return capability, length and success.
602 *len
= rp
- record
- 1; /* don't count NUL */
605 realloc(record
, (size_t)(rp
- record
))) == NULL
) {
618 cdbget(DB
*capdbp
, char **bp
, const char *name
)
623 /* LINTED key is not modified */
624 key
.data
= (char *)name
;
625 key
.size
= strlen(name
);
628 /* Get the reference. */
629 switch(capdbp
->get(capdbp
, &key
, &data
, 0)) {
636 /* If not an index to another record, leave. */
637 if (((char *)data
.data
)[0] != SHADOW
)
640 key
.data
= (char *)data
.data
+ 1;
641 key
.size
= data
.size
- 1;
644 *bp
= (char *)data
.data
+ 1;
645 return (((char *)(data
.data
))[0] == TCERR
? 1 : 0);
650 * Cgetmatch will return 0 if name is one of the names of the capability
651 * record buf, -1 if not.
654 cgetmatch(const char *buf
, const char *name
)
659 * Start search at beginning of record.
664 * Try to match a record name.
669 if (*bp
== '|' || *bp
== ':' || *bp
== '\0')
678 * Match failed, skip to next name in record.
680 bp
--; /* a '|' or ':' may have stopped the match */
682 if (*bp
== '\0' || *bp
== ':')
683 return (-1); /* match failed totally */
686 break; /* found next name */
692 cgetfirst(char **buf
, char **db_array
)
695 return (cgetnext(buf
, db_array
));
703 int ROKEN_LIB_FUNCTION
718 * Cgetnext() gets either the first or next entry in the logical database
719 * specified by db_array. It returns 0 upon completion of the database, 1
720 * upon returning an entry with more remaining, and -1 if an error occurs.
723 cgetnext(char **bp
, char **db_array
)
727 char *cp
, *line
, *rp
, *np
, buf
[BSIZE
], nbuf
[BSIZE
];
733 if (pfp
== NULL
&& (pfp
= fopen(*dbp
, "r")) == NULL
) {
738 if (toprec
&& !gottoprec
) {
742 line
= fgetln(pfp
, &len
);
743 if (line
== NULL
&& pfp
) {
750 if (*++dbp
== NULL
) {
754 fopen(*dbp
, "r")) == NULL
) {
761 line
[len
- 1] = '\0';
766 if (isspace((unsigned char)*line
) ||
767 *line
== ':' || *line
== '#' || slash
) {
768 if (line
[len
- 2] == '\\')
774 if (line
[len
- 2] == '\\')
782 * Line points to a name line.
787 for (cp
= line
; *cp
!= '\0'; cp
++) {
800 } else { /* name field extends beyond the line */
801 line
= fgetln(pfp
, &len
);
802 if (line
== NULL
&& pfp
) {
812 line
[len
- 1] = '\0';
816 for(cp
= nbuf
; *cp
!= '\0'; cp
++)
817 if (*cp
== '|' || *cp
== ':')
825 * Last argument of getent here should be nbuf if we want true
826 * sequential access in the case of duplicates.
827 * With NULL, getent will return the first entry found
828 * rather than the duplicate entry record. This is a
829 * matter of semantics that should be resolved.
831 status
= getent(bp
, &dummy
, db_array
, -1, buf
, 0, NULL
);
832 if (status
== -2 || status
== -3)
842 * Cgetstr retrieves the value of the string capability cap from the
843 * capability record pointed to by buf. A pointer to a decoded, NUL
844 * terminated, malloc'd copy of the string is returned in the char *
845 * pointed to by str. The length of the string not including the trailing
846 * NUL is returned on success, -1 if the requested string capability
847 * couldn't be found, -2 if a system error was encountered (storage
848 * allocation failure).
850 int ROKEN_LIB_FUNCTION
851 cgetstr(char *buf
, const char *cap
, char **str
)
860 * Find string capability cap
862 bp
= cgetcap(buf
, cap
, '=');
867 * Conversion / storage allocation loop ... Allocate memory in
868 * chunks SFRAG in size.
870 if ((mem
= malloc(SFRAG
)) == NULL
) {
872 return (-2); /* couldn't even allocate the first fragment */
877 while (*bp
!= ':' && *bp
!= '\0') {
880 * There is always room for one more character in mem.
881 * Mp always points just past last character in mem.
882 * Bp always points at next character in buf.
886 if (*bp
== ':' || *bp
== '\0')
887 break; /* drop unfinished escape */
889 } else if (*bp
== '\\') {
891 if (*bp
== ':' || *bp
== '\0')
892 break; /* drop unfinished escape */
893 if ('0' <= *bp
&& *bp
<= '7') {
897 i
= 3; /* maximum of three octal digits */
899 n
= n
* 8 + (*bp
++ - '0');
900 } while (--i
&& '0' <= *bp
&& *bp
<= '7');
903 else switch (*bp
++) {
927 * Catches '\', '^', and
938 * Enforce loop invariant: if no room left in current
939 * buffer, try to get some more.
942 size_t size
= mp
- mem
;
944 if ((mem
= realloc(mem
, size
+ SFRAG
)) == NULL
)
950 *mp
++ = '\0'; /* loop invariant let's us do this */
955 * Give back any extra memory and return value and success.
958 if ((mem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
)
965 * Cgetustr retrieves the value of the string capability cap from the
966 * capability record pointed to by buf. The difference between cgetustr()
967 * and cgetstr() is that cgetustr does not decode escapes but rather treats
968 * all characters literally. A pointer to a NUL terminated malloc'd
969 * copy of the string is returned in the char pointed to by str. The
970 * length of the string not including the trailing NUL is returned on success,
971 * -1 if the requested string capability couldn't be found, -2 if a system
972 * error was encountered (storage allocation failure).
974 int ROKEN_LIB_FUNCTION
975 cgetustr(char *buf
, const char *cap
, char **str
)
984 * Find string capability cap
986 if ((bp
= cgetcap(buf
, cap
, '=')) == NULL
)
990 * Conversion / storage allocation loop ... Allocate memory in
991 * chunks SFRAG in size.
993 if ((mem
= malloc(SFRAG
)) == NULL
) {
995 return (-2); /* couldn't even allocate the first fragment */
1000 while (*bp
!= ':' && *bp
!= '\0') {
1003 * There is always room for one more character in mem.
1004 * Mp always points just past last character in mem.
1005 * Bp always points at next character in buf.
1011 * Enforce loop invariant: if no room left in current
1012 * buffer, try to get some more.
1015 size_t size
= mp
- mem
;
1017 if ((mem
= realloc(mem
, size
+ SFRAG
)) == NULL
)
1023 *mp
++ = '\0'; /* loop invariant let's us do this */
1028 * Give back any extra memory and return value and success.
1031 if ((mem
= realloc(mem
, (size_t)(mp
- mem
))) == NULL
)
1038 * Cgetnum retrieves the value of the numeric capability cap from the
1039 * capability record pointed to by buf. The numeric value is returned in
1040 * the long pointed to by num. 0 is returned on success, -1 if the requested
1041 * numeric capability couldn't be found.
1043 int ROKEN_LIB_FUNCTION
1044 cgetnum(char *buf
, const char *cap
, long *num
)
1051 * Find numeric capability cap
1053 bp
= cgetcap(buf
, cap
, '#');
1058 * Look at value and determine numeric base:
1059 * 0x... or 0X... hexadecimal,
1065 if (*bp
== 'x' || *bp
== 'X') {
1074 * Conversion loop ...
1078 if ('0' <= *bp
&& *bp
<= '9')
1080 else if ('a' <= *bp
&& *bp
<= 'f')
1081 digit
= 10 + *bp
- 'a';
1082 else if ('A' <= *bp
&& *bp
<= 'F')
1083 digit
= 10 + *bp
- 'A';
1090 n
= n
* base
+ digit
;
1095 * Return value and success.
1103 * Compare name field of record.
1106 nfcmp(char *nf
, char *rec
)
1111 for (cp
= rec
; *cp
!= ':'; cp
++)
1116 ret
= strcmp(nf
, rec
);