1/*	$NetBSD$	*/
2
3/*	NetBSD: getcap.c,v 1.29 1999/03/29 09:27:29 abs Exp	*/
4
5/*-
6 * Copyright (c) 1992, 1993
7 *	The Regents of the University of California.  All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * Casey Leedom of Lawrence Livermore National Laboratory.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. 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.
23 *
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
34 * SUCH DAMAGE.
35 */
36
37#include <config.h>
38
39#include <krb5/roken.h>
40
41#include <sys/types.h>
42#include <ctype.h>
43#if defined(HAVE_DB_185_H)
44#include <db_185.h>
45#elif defined(HAVE_DB_H)
46#include <db.h>
47#endif
48#include <errno.h>
49#include <fcntl.h>
50#include <limits.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55
56#define	BFRAG		1024
57#if 0
58#define	BSIZE		1024
59#endif
60#define	ESC		('[' & 037)	/* ASCII ESC */
61#define	MAX_RECURSION	32		/* maximum getent recursion */
62#define	SFRAG		100		/* cgetstr mallocs in SFRAG chunks */
63
64#define RECOK	(char)0
65#define TCERR	(char)1
66#define	SHADOW	(char)2
67
68static size_t	 topreclen;	/* toprec length */
69static char	*toprec;	/* Additional record specified by cgetset() */
70static int	 gottoprec;	/* Flag indicating retrieval of toprecord */
71
72#if 0 /*
73       * Don't use db support unless it's build into libc but we don't
74       * check for that now, so just disable the code.
75       */
76#if defined(HAVE_DBOPEN) && defined(HAVE_DB_H)
77#define USE_DB
78#endif
79#endif
80
81#ifdef USE_DB
82static int	cdbget (DB *, char **, const char *);
83#endif
84static int 	getent (char **, size_t *, char **, int, const char *, int, char *);
85static int	nfcmp (char *, char *);
86
87
88ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetset(const char *ent);
89ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL cgetcap(char *buf, const char *cap, int type);
90ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetent(char **buf, char **db_array, const char *name);
91ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetmatch(const char *buf, const char *name);
92ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetclose(void);
93#if 0
94int cgetfirst(char **buf, char **db_array);
95int cgetnext(char **bp, char **db_array);
96#endif
97ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetstr(char *buf, const char *cap, char **str);
98ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetustr(char *buf, const char *cap, char **str);
99ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetnum(char *buf, const char *cap, long *num);
100/*
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.
104 */
105ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
106cgetset(const char *ent)
107{
108    const char *source, *check;
109    char *dest;
110
111    if (ent == NULL) {
112	if (toprec)
113	    free(toprec);
114	toprec = NULL;
115	topreclen = 0;
116	return (0);
117    }
118    topreclen = strlen(ent);
119    if ((toprec = malloc (topreclen + 1)) == NULL) {
120	errno = ENOMEM;
121	return (-1);
122    }
123    gottoprec = 0;
124
125    source=ent;
126    dest=toprec;
127    while (*source) { /* Strip whitespace */
128	*dest++ = *source++; /* Do not check first field */
129	while (*source == ':') {
130	    check=source+1;
131	    while (*check && (isspace((unsigned char)*check) ||
132			      (*check=='\\' && isspace((unsigned char)check[1]))))
133		++check;
134	    if( *check == ':' )
135		source=check;
136	    else
137		break;
138
139	}
140    }
141    *dest=0;
142
143    return (0);
144}
145
146/*
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.
150 *
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
153 * cap is found.
154 *
155 * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
156 * return NULL.
157 */
158ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
159cgetcap(char *buf, const char *cap, int type)
160{
161    char *bp;
162    const char *cp;
163
164    bp = buf;
165    for (;;) {
166	/*
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.
170	 */
171	for (;;)
172	    if (*bp == '\0')
173		return (NULL);
174	    else
175		if (*bp++ == ':')
176		    break;
177
178	/*
179	 * Try to match (cap, type) in buf.
180	 */
181	for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
182	    continue;
183	if (*cp != '\0')
184	    continue;
185	if (*bp == '@')
186	    return (NULL);
187	if (type == ':') {
188	    if (*bp != '\0' && *bp != ':')
189		continue;
190	    return(bp);
191	}
192	if (*bp != type)
193	    continue;
194	bp++;
195	return (*bp == '@' ? NULL : bp);
196    }
197    /* NOTREACHED */
198}
199
200/*
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.
208 */
209ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
210cgetent(char **buf, char **db_array, const char *name)
211{
212    size_t dummy;
213
214    return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
215}
216
217/*
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=
221 * recursions.
222 *
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
226 * *cap and *len.
227 *
228 * Basic algorithm:
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
233 *	  MAX_RECURSION.
234 */
235static int
236getent(char **cap, size_t *len, char **db_array, int fd,
237       const char *name, int depth, char *nfield)
238{
239    char *r_end, *rp = NULL, **db_p;	/* pacify gcc */
240    int myfd = 0, eof, foundit;
241    char *record;
242    int tc_not_resolved;
243
244    /*
245     * Return with ``loop detected'' error if we've recursed more than
246     * MAX_RECURSION times.
247     */
248    if (depth > MAX_RECURSION)
249	return (-3);
250
251    /*
252     * Check if we have a top record from cgetset().
253     */
254    if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
255	size_t len = topreclen + BFRAG;
256	if ((record = malloc (len)) == NULL) {
257	    errno = ENOMEM;
258	    return (-2);
259	}
260	(void)strlcpy(record, toprec, len);
261	db_p = db_array;
262	rp = record + topreclen + 1;
263	r_end = rp + BFRAG;
264	goto tc_exp;
265    }
266    /*
267     * Allocate first chunk of memory.
268     */
269    if ((record = malloc(BFRAG)) == NULL) {
270	errno = ENOMEM;
271	return (-2);
272    }
273    r_end = record + BFRAG;
274    foundit = 0;
275    /*
276     * Loop through database array until finding the record.
277     */
278
279    for (db_p = db_array; *db_p != NULL; db_p++) {
280	eof = 0;
281
282	/*
283	 * Open database if not already open.
284	 */
285
286	if (fd >= 0) {
287	    (void)lseek(fd, (off_t)0, SEEK_SET);
288	} else {
289#ifdef USE_DB
290	    char pbuf[_POSIX_PATH_MAX];
291	    char *cbuf;
292	    size_t clen;
293	    int retval;
294	    DB *capdbp;
295
296	    (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
297	    if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
298		!= NULL) {
299		free(record);
300		retval = cdbget(capdbp, &record, name);
301		if (retval < 0) {
302		    /* no record available */
303		    (void)capdbp->close(capdbp);
304		    return (retval);
305		}
306				/* save the data; close frees it */
307		clen = strlen(record);
308		cbuf = malloc(clen + 1);
309		if (cbuf == NULL)
310		    return (-2);
311		memmove(cbuf, record, clen + 1);
312		if (capdbp->close(capdbp) < 0) {
313		    free(cbuf);
314		    return (-2);
315		}
316		*len = clen;
317		*cap = cbuf;
318		return (retval);
319	    } else
320#endif
321	    {
322		fd = open(*db_p, O_RDONLY, 0);
323		if (fd < 0) {
324		    /* No error on unfound file. */
325		    continue;
326		}
327		myfd = 1;
328	    }
329	}
330	/*
331	 * Find the requested capability record ...
332	 */
333	{
334	    char buf[BUFSIZ];
335	    char *b_end, *bp, *cp;
336	    int c, slash;
337
338	    /*
339	     * Loop invariants:
340	     *	There is always room for one more character in record.
341	     *	R_end always points just past end of record.
342	     *	Rp always points just past last character in record.
343	     *	B_end always points just past last character in buf.
344	     *	Bp always points at next character in buf.
345	     *	Cp remembers where the last colon was.
346	     */
347	    b_end = buf;
348	    bp = buf;
349	    cp = 0;
350	    slash = 0;
351	    for (;;) {
352
353		/*
354		 * Read in a line implementing (\, newline)
355		 * line continuation.
356		 */
357		rp = record;
358		for (;;) {
359		    if (bp >= b_end) {
360			int n;
361
362			n = read(fd, buf, sizeof(buf));
363			if (n <= 0) {
364			    if (myfd)
365				(void)close(fd);
366			    if (n < 0) {
367				free(record);
368				return (-2);
369			    } else {
370				fd = -1;
371				eof = 1;
372				break;
373			    }
374			}
375			b_end = buf+n;
376			bp = buf;
377		    }
378
379		    c = *bp++;
380		    if (c == '\n') {
381			if (slash) {
382			    slash = 0;
383			    rp--;
384			    continue;
385			} else
386			    break;
387		    }
388		    if (slash) {
389			slash = 0;
390			cp = 0;
391		    }
392		    if (c == ':') {
393			/*
394			 * If the field was `empty' (i.e.
395			 * contained only white space), back up
396			 * to the colon (eliminating the
397			 * field).
398			 */
399			if (cp)
400			    rp = cp;
401			else
402			    cp = rp;
403		    } else if (c == '\\') {
404			slash = 1;
405		    } else if (c != ' ' && c != '\t') {
406			/*
407			 * Forget where the colon was, as this
408			 * is not an empty field.
409			 */
410			cp = 0;
411		    }
412		    *rp++ = c;
413
414				/*
415				 * Enforce loop invariant: if no room
416				 * left in record buffer, try to get
417				 * some more.
418				 */
419		    if (rp >= r_end) {
420			u_int pos;
421			size_t newsize;
422
423			pos = rp - record;
424			newsize = r_end - record + BFRAG;
425			record = realloc(record, newsize);
426			if (record == NULL) {
427			    errno = ENOMEM;
428			    if (myfd)
429				(void)close(fd);
430			    return (-2);
431			}
432			r_end = record + newsize;
433			rp = record + pos;
434		    }
435		}
436		/* Eliminate any white space after the last colon. */
437		if (cp)
438		    rp = cp + 1;
439		/* Loop invariant lets us do this. */
440		*rp++ = '\0';
441
442		/*
443		 * If encountered eof check next file.
444		 */
445		if (eof)
446		    break;
447
448		/*
449		 * Toss blank lines and comments.
450		 */
451		if (*record == '\0' || *record == '#')
452		    continue;
453
454		/*
455		 * See if this is the record we want ...
456		 */
457		if (cgetmatch(record, name) == 0) {
458		    if (nfield == NULL || !nfcmp(nfield, record)) {
459			foundit = 1;
460			break;	/* found it! */
461		    }
462		}
463	    }
464	}
465	if (foundit)
466	    break;
467    }
468
469    if (!foundit)
470	return (-1);
471
472    /*
473     * Got the capability record, but now we have to expand all tc=name
474     * references in it ...
475     */
476 tc_exp:	{
477	char *newicap, *s;
478	size_t ilen, newilen;
479	int diff, iret, tclen;
480	char *icap, *scan, *tc, *tcstart, *tcend;
481
482	/*
483	 * Loop invariants:
484	 *	There is room for one more character in record.
485	 *	R_end points just past end of record.
486	 *	Rp points just past last character in record.
487	 *	Scan points at remainder of record that needs to be
488	 *	scanned for tc=name constructs.
489	 */
490	scan = record;
491	tc_not_resolved = 0;
492	for (;;) {
493	    if ((tc = cgetcap(scan, "tc", '=')) == NULL)
494		break;
495
496	    /*
497	     * Find end of tc=name and stomp on the trailing `:'
498	     * (if present) so we can use it to call ourselves.
499	     */
500	    s = tc;
501	    for (;;)
502		if (*s == '\0')
503		    break;
504		else
505		    if (*s++ == ':') {
506			*(s - 1) = '\0';
507			break;
508		    }
509	    tcstart = tc - 3;
510	    tclen = s - tcstart;
511	    tcend = s;
512
513	    iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
514			  NULL);
515	    newicap = icap;		/* Put into a register. */
516	    newilen = ilen;
517	    if (iret != 0) {
518				/* an error */
519		if (iret < -1) {
520		    if (myfd)
521			(void)close(fd);
522		    free(record);
523		    return (iret);
524		}
525		if (iret == 1)
526		    tc_not_resolved = 1;
527				/* couldn't resolve tc */
528		if (iret == -1) {
529		    *(s - 1) = ':';
530		    scan = s - 1;
531		    tc_not_resolved = 1;
532		    continue;
533
534		}
535	    }
536	    /* not interested in name field of tc'ed record */
537	    s = newicap;
538	    for (;;)
539		if (*s == '\0')
540		    break;
541		else
542		    if (*s++ == ':')
543			break;
544	    newilen -= s - newicap;
545	    newicap = s;
546
547	    /* make sure interpolated record is `:'-terminated */
548	    s += newilen;
549	    if (*(s-1) != ':') {
550		*s = ':';	/* overwrite NUL with : */
551		newilen++;
552	    }
553
554	    /*
555	     * Make sure there's enough room to insert the
556	     * new record.
557	     */
558	    diff = newilen - tclen;
559	    if (diff >= r_end - rp) {
560		u_int pos, tcpos, tcposend;
561		size_t newsize;
562
563		pos = rp - record;
564		newsize = r_end - record + diff + BFRAG;
565		tcpos = tcstart - record;
566		tcposend = tcend - record;
567		record = realloc(record, newsize);
568		if (record == NULL) {
569		    errno = ENOMEM;
570		    if (myfd)
571			(void)close(fd);
572		    free(icap);
573		    return (-2);
574		}
575		r_end = record + newsize;
576		rp = record + pos;
577		tcstart = record + tcpos;
578		tcend = record + tcposend;
579	    }
580
581	    /*
582	     * Insert tc'ed record into our record.
583	     */
584	    s = tcstart + newilen;
585	    memmove(s, tcend,  (size_t)(rp - tcend));
586	    memmove(tcstart, newicap, newilen);
587	    rp += diff;
588	    free(icap);
589
590	    /*
591	     * Start scan on `:' so next cgetcap works properly
592	     * (cgetcap always skips first field).
593	     */
594	    scan = s-1;
595	}
596
597    }
598    /*
599     * Close file (if we opened it), give back any extra memory, and
600     * return capability, length and success.
601     */
602    if (myfd)
603	(void)close(fd);
604    *len = rp - record - 1;	/* don't count NUL */
605    if (r_end > rp)
606	if ((record =
607	     realloc(record, (size_t)(rp - record))) == NULL) {
608	    errno = ENOMEM;
609	    return (-2);
610	}
611
612    *cap = record;
613    if (tc_not_resolved)
614	return (1);
615    return (0);
616}
617
618#ifdef USE_DB
619static int
620cdbget(DB *capdbp, char **bp, const char *name)
621{
622	DBT key;
623	DBT data;
624
625	/* LINTED key is not modified */
626	key.data = (char *)name;
627	key.size = strlen(name);
628
629	for (;;) {
630		/* Get the reference. */
631		switch(capdbp->get(capdbp, &key, &data, 0)) {
632		case -1:
633			return (-2);
634		case 1:
635			return (-1);
636		}
637
638		/* If not an index to another record, leave. */
639		if (((char *)data.data)[0] != SHADOW)
640			break;
641
642		key.data = (char *)data.data + 1;
643		key.size = data.size - 1;
644	}
645
646	*bp = (char *)data.data + 1;
647	return (((char *)(data.data))[0] == TCERR ? 1 : 0);
648}
649#endif /* USE_DB */
650
651/*
652 * Cgetmatch will return 0 if name is one of the names of the capability
653 * record buf, -1 if not.
654 */
655int
656cgetmatch(const char *buf, const char *name)
657{
658    const char *np, *bp;
659
660    /*
661     * Start search at beginning of record.
662     */
663    bp = buf;
664    for (;;) {
665	/*
666	 * Try to match a record name.
667	 */
668	np = name;
669	for (;;)
670	    if (*np == '\0') {
671		if (*bp == '|' || *bp == ':' || *bp == '\0')
672		    return (0);
673		else
674		    break;
675	    } else
676		if (*bp++ != *np++)
677		    break;
678
679	/*
680	 * Match failed, skip to next name in record.
681	 */
682	bp--;	/* a '|' or ':' may have stopped the match */
683	for (;;)
684	    if (*bp == '\0' || *bp == ':')
685		return (-1);	/* match failed totally */
686	    else
687		if (*bp++ == '|')
688		    break;	/* found next name */
689    }
690}
691
692#if 0
693int
694cgetfirst(char **buf, char **db_array)
695{
696    (void)cgetclose();
697    return (cgetnext(buf, db_array));
698}
699#endif
700
701static FILE *pfp;
702static int slash;
703static char **dbp;
704
705ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
706cgetclose(void)
707{
708    if (pfp != NULL) {
709	(void)fclose(pfp);
710	pfp = NULL;
711    }
712    dbp = NULL;
713    gottoprec = 0;
714    slash = 0;
715    return(0);
716}
717
718#if 0
719/*
720 * Cgetnext() gets either the first or next entry in the logical database
721 * specified by db_array.  It returns 0 upon completion of the database, 1
722 * upon returning an entry with more remaining, and -1 if an error occurs.
723 */
724int
725cgetnext(char **bp, char **db_array)
726{
727    size_t len;
728    int status, done;
729    char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
730    size_t dummy;
731
732    if (dbp == NULL)
733	dbp = db_array;
734
735    if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
736	(void)cgetclose();
737	return (-1);
738    }
739    for(;;) {
740	if (toprec && !gottoprec) {
741	    gottoprec = 1;
742	    line = toprec;
743	} else {
744	    line = fgetln(pfp, &len);
745	    if (line == NULL && pfp) {
746		if (ferror(pfp)) {
747		    (void)cgetclose();
748		    return (-1);
749		} else {
750		    (void)fclose(pfp);
751		    pfp = NULL;
752		    if (*++dbp == NULL) {
753			(void)cgetclose();
754			return (0);
755		    } else if ((pfp =
756				fopen(*dbp, "r")) == NULL) {
757			(void)cgetclose();
758			return (-1);
759		    } else
760			continue;
761		}
762	    } else
763		line[len - 1] = '\0';
764	    if (len == 1) {
765		slash = 0;
766		continue;
767	    }
768	    if (isspace((unsigned char)*line) ||
769		*line == ':' || *line == '#' || slash) {
770		if (line[len - 2] == '\\')
771		    slash = 1;
772		else
773		    slash = 0;
774		continue;
775	    }
776	    if (line[len - 2] == '\\')
777		slash = 1;
778	    else
779		slash = 0;
780	}
781
782
783	/*
784	 * Line points to a name line.
785	 */
786	done = 0;
787	np = nbuf;
788	for (;;) {
789	    for (cp = line; *cp != '\0'; cp++) {
790		if (*cp == ':') {
791		    *np++ = ':';
792		    done = 1;
793		    break;
794		}
795		if (*cp == '\\')
796		    break;
797		*np++ = *cp;
798	    }
799	    if (done) {
800		*np = '\0';
801		break;
802	    } else { /* name field extends beyond the line */
803		line = fgetln(pfp, &len);
804		if (line == NULL && pfp) {
805		    if (ferror(pfp)) {
806			(void)cgetclose();
807			return (-1);
808		    }
809		    (void)fclose(pfp);
810		    pfp = NULL;
811		    *np = '\0';
812		    break;
813		} else
814		    line[len - 1] = '\0';
815	    }
816	}
817	rp = buf;
818	for(cp = nbuf; *cp != '\0'; cp++)
819	    if (*cp == '|' || *cp == ':')
820		break;
821	    else
822		*rp++ = *cp;
823
824	*rp = '\0';
825	/*
826	 * XXX
827	 * Last argument of getent here should be nbuf if we want true
828	 * sequential access in the case of duplicates.
829	 * With NULL, getent will return the first entry found
830	 * rather than the duplicate entry record.  This is a
831	 * matter of semantics that should be resolved.
832	 */
833	status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
834	if (status == -2 || status == -3)
835	    (void)cgetclose();
836
837	return (status + 1);
838    }
839    /* NOTREACHED */
840}
841#endif
842
843/*
844 * Cgetstr retrieves the value of the string capability cap from the
845 * capability record pointed to by buf.  A pointer to a decoded, NUL
846 * terminated, malloc'd copy of the string is returned in the char *
847 * pointed to by str.  The length of the string not including the trailing
848 * NUL is returned on success, -1 if the requested string capability
849 * couldn't be found, -2 if a system error was encountered (storage
850 * allocation failure).
851 */
852ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
853cgetstr(char *buf, const char *cap, char **str)
854{
855    u_int m_room;
856    const char *bp;
857    char *mp;
858    int len;
859    char *mem, *nmem;
860
861    *str = NULL;
862
863    /*
864     * Find string capability cap
865     */
866    bp = cgetcap(buf, cap, '=');
867    if (bp == NULL)
868	return (-1);
869
870    /*
871     * Conversion / storage allocation loop ...  Allocate memory in
872     * chunks SFRAG in size.
873     */
874    if ((mem = malloc(SFRAG)) == NULL) {
875	errno = ENOMEM;
876	return (-2);	/* couldn't even allocate the first fragment */
877    }
878    m_room = SFRAG;
879    mp = mem;
880
881    while (*bp != ':' && *bp != '\0') {
882	/*
883	 * Loop invariants:
884	 *	There is always room for one more character in mem.
885	 *	Mp always points just past last character in mem.
886	 *	Bp always points at next character in buf.
887	 */
888	if (*bp == '^') {
889	    bp++;
890	    if (*bp == ':' || *bp == '\0')
891		break;	/* drop unfinished escape */
892	    *mp++ = *bp++ & 037;
893	} else if (*bp == '\\') {
894	    bp++;
895	    if (*bp == ':' || *bp == '\0')
896		break;	/* drop unfinished escape */
897	    if ('0' <= *bp && *bp <= '7') {
898		int n, i;
899
900		n = 0;
901		i = 3;	/* maximum of three octal digits */
902		do {
903		    n = n * 8 + (*bp++ - '0');
904		} while (--i && '0' <= *bp && *bp <= '7');
905		*mp++ = n;
906	    }
907	    else switch (*bp++) {
908	    case 'b': case 'B':
909		*mp++ = '\b';
910		break;
911	    case 't': case 'T':
912		*mp++ = '\t';
913		break;
914	    case 'n': case 'N':
915		*mp++ = '\n';
916		break;
917	    case 'f': case 'F':
918		*mp++ = '\f';
919		break;
920	    case 'r': case 'R':
921		*mp++ = '\r';
922		break;
923	    case 'e': case 'E':
924		*mp++ = ESC;
925		break;
926	    case 'c': case 'C':
927		*mp++ = ':';
928		break;
929	    default:
930		/*
931		 * Catches '\', '^', and
932		 *  everything else.
933		 */
934		*mp++ = *(bp-1);
935		break;
936	    }
937	} else
938	    *mp++ = *bp++;
939	m_room--;
940
941	/*
942	 * Enforce loop invariant: if no room left in current
943	 * buffer, try to get some more.
944	 */
945	if (m_room == 0) {
946	    size_t size = mp - mem;
947
948	    if ((nmem = realloc(mem, size + SFRAG)) == NULL) {
949		free(mem);
950		return (-2);
951	    }
952	    mem = nmem;
953	    m_room = SFRAG;
954	    mp = mem + size;
955	}
956    }
957    *mp++ = '\0';	/* loop invariant let's us do this */
958    m_room--;
959    len = mp - mem - 1;
960
961    /*
962     * Give back any extra memory and return value and success.
963     */
964    if (m_room != 0) {
965	if ((nmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
966	    free(mem);
967	    return (-2);
968	}
969	mem = nmem;
970    }
971    *str = mem;
972    return (len);
973}
974
975/*
976 * Cgetustr retrieves the value of the string capability cap from the
977 * capability record pointed to by buf.  The difference between cgetustr()
978 * and cgetstr() is that cgetustr does not decode escapes but rather treats
979 * all characters literally.  A pointer to a  NUL terminated malloc'd
980 * copy of the string is returned in the char pointed to by str.  The
981 * length of the string not including the trailing NUL is returned on success,
982 * -1 if the requested string capability couldn't be found, -2 if a system
983 * error was encountered (storage allocation failure).
984 */
985ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
986cgetustr(char *buf, const char *cap, char **str)
987{
988    u_int m_room;
989    const char *bp;
990    char *mp;
991    int len;
992    char *mem;
993
994    /*
995     * Find string capability cap
996     */
997    if ((bp = cgetcap(buf, cap, '=')) == NULL)
998	return (-1);
999
1000    /*
1001     * Conversion / storage allocation loop ...  Allocate memory in
1002     * chunks SFRAG in size.
1003     */
1004    if ((mem = malloc(SFRAG)) == NULL) {
1005	errno = ENOMEM;
1006	return (-2);	/* couldn't even allocate the first fragment */
1007    }
1008    m_room = SFRAG;
1009    mp = mem;
1010
1011    while (*bp != ':' && *bp != '\0') {
1012	/*
1013	 * Loop invariants:
1014	 *	There is always room for one more character in mem.
1015	 *	Mp always points just past last character in mem.
1016	 *	Bp always points at next character in buf.
1017	 */
1018	*mp++ = *bp++;
1019	m_room--;
1020
1021	/*
1022	 * Enforce loop invariant: if no room left in current
1023	 * buffer, try to get some more.
1024	 */
1025	if (m_room == 0) {
1026	    size_t size = mp - mem;
1027
1028	    if ((mem = realloc(mem, size + SFRAG)) == NULL)
1029		return (-2);
1030	    m_room = SFRAG;
1031	    mp = mem + size;
1032	}
1033    }
1034    *mp++ = '\0';	/* loop invariant let's us do this */
1035    m_room--;
1036    len = mp - mem - 1;
1037
1038    /*
1039     * Give back any extra memory and return value and success.
1040     */
1041    if (m_room != 0)
1042	if ((mem = realloc(mem, (size_t)(mp - mem))) == NULL)
1043	    return (-2);
1044    *str = mem;
1045    return (len);
1046}
1047
1048/*
1049 * Cgetnum retrieves the value of the numeric capability cap from the
1050 * capability record pointed to by buf.  The numeric value is returned in
1051 * the long pointed to by num.  0 is returned on success, -1 if the requested
1052 * numeric capability couldn't be found.
1053 */
1054ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
1055cgetnum(char *buf, const char *cap, long *num)
1056{
1057    long n;
1058    int base, digit;
1059    const char *bp;
1060
1061    /*
1062     * Find numeric capability cap
1063     */
1064    bp = cgetcap(buf, cap, '#');
1065    if (bp == NULL)
1066	return (-1);
1067
1068    /*
1069     * Look at value and determine numeric base:
1070     *	0x... or 0X...	hexadecimal,
1071     * else	0...		octal,
1072     * else			decimal.
1073     */
1074    if (*bp == '0') {
1075	bp++;
1076	if (*bp == 'x' || *bp == 'X') {
1077	    bp++;
1078	    base = 16;
1079	} else
1080	    base = 8;
1081    } else
1082	base = 10;
1083
1084    /*
1085     * Conversion loop ...
1086     */
1087    n = 0;
1088    for (;;) {
1089	if ('0' <= *bp && *bp <= '9')
1090	    digit = *bp - '0';
1091	else if ('a' <= *bp && *bp <= 'f')
1092	    digit = 10 + *bp - 'a';
1093	else if ('A' <= *bp && *bp <= 'F')
1094	    digit = 10 + *bp - 'A';
1095	else
1096	    break;
1097
1098	if (digit >= base)
1099	    break;
1100
1101	n = n * base + digit;
1102	bp++;
1103    }
1104
1105    /*
1106     * Return value and success.
1107     */
1108    *num = n;
1109    return (0);
1110}
1111
1112
1113/*
1114 * Compare name field of record.
1115 */
1116static int
1117nfcmp(char *nf, char *rec)
1118{
1119    char *cp, tmp;
1120    int ret;
1121
1122    for (cp = rec; *cp != ':'; cp++)
1123	;
1124
1125    tmp = *(cp + 1);
1126    *(cp + 1) = '\0';
1127    ret = strcmp(nf, rec);
1128    *(cp + 1) = tmp;
1129
1130    return (ret);
1131}
1132