getcap.c revision 90039
1178354Ssam/*-
2178354Ssam * Copyright (c) 1992, 1993
3178354Ssam *	The Regents of the University of California.  All rights reserved.
4206358Srpaulo *
5178354Ssam * This code is derived from software contributed to Berkeley by
6178354Ssam * Casey Leedom of Lawrence Livermore National Laboratory.
7178354Ssam *
8178354Ssam * Redistribution and use in source and binary forms, with or without
9178354Ssam * modification, are permitted provided that the following conditions
10178354Ssam * are met:
11178354Ssam * 1. Redistributions of source code must retain the above copyright
12178354Ssam *    notice, this list of conditions and the following disclaimer.
13178354Ssam * 2. Redistributions in binary form must reproduce the above copyright
14178354Ssam *    notice, this list of conditions and the following disclaimer in the
15178354Ssam *    documentation and/or other materials provided with the distribution.
16178354Ssam * 3. All advertising materials mentioning features or use of this software
17178354Ssam *    must display the following acknowledgement:
18178354Ssam *	This product includes software developed by the University of
19178354Ssam *	California, Berkeley and its contributors.
20178354Ssam * 4. Neither the name of the University nor the names of its contributors
21178354Ssam *    may be used to endorse or promote products derived from this software
22178354Ssam *    without specific prior written permission.
23178354Ssam *
24178354Ssam * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25178354Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26178354Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27178354Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28178354Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29178354Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30178354Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31178354Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32178354Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33178354Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34178354Ssam * SUCH DAMAGE.
35178354Ssam */
36178354Ssam
37178354Ssam#if defined(LIBC_SCCS) && !defined(lint)
38178354Ssamstatic char sccsid[] = "@(#)getcap.c	8.3 (Berkeley) 3/25/94";
39178354Ssam#endif /* LIBC_SCCS and not lint */
40178354Ssam#include <sys/cdefs.h>
41178354Ssam__FBSDID("$FreeBSD: head/lib/libc/gen/getcap.c 90039 2002-02-01 00:57:29Z obrien $");
42178354Ssam
43178354Ssam#include "namespace.h"
44178354Ssam#include <sys/types.h>
45178354Ssam
46206358Srpaulo#include <ctype.h>
47178354Ssam#include <errno.h>
48178354Ssam#include <fcntl.h>
49178354Ssam#include <limits.h>
50178354Ssam#include <stdio.h>
51178354Ssam#include <stdlib.h>
52178354Ssam#include <string.h>
53178354Ssam#include <unistd.h>
54178354Ssam#include "un-namespace.h"
55178354Ssam
56178354Ssam#include <db.h>
57178354Ssam
58178354Ssam#define	BFRAG		1024
59178354Ssam#define	BSIZE		1024
60178354Ssam#define	ESC		('[' & 037)	/* ASCII ESC */
61209092Sed#define	MAX_RECURSION	32		/* maximum getent recursion */
62209092Sed#define	SFRAG		100		/* cgetstr mallocs in SFRAG chunks */
63209092Sed
64209092Sed#define RECOK	(char)0
65209092Sed#define TCERR	(char)1
66209092Sed#define	SHADOW	(char)2
67178354Ssam
68178354Ssamstatic size_t	 topreclen;	/* toprec length */
69178354Ssamstatic char	*toprec;	/* Additional record specified by cgetset() */
70178354Ssamstatic int	 gottoprec;	/* Flag indicating retrieval of toprecord */
71178354Ssam
72178354Ssamstatic int	cdbget(DB *, char **, char *);
73178354Ssamstatic int 	getent(char **, u_int *, char **, int, char *, int, char *);
74178354Ssamstatic int	nfcmp(char *, char *);
75178354Ssam
76206358Srpaulo/*
77206358Srpaulo * Cgetset() allows the addition of a user specified buffer to be added
78206358Srpaulo * to the database array, in effect "pushing" the buffer on top of the
79206358Srpaulo * virtual database. 0 is returned on success, -1 on failure.
80206358Srpaulo */
81206358Srpauloint
82206358Srpaulocgetset(ent)
83206358Srpaulo	char *ent;
84206358Srpaulo{
85206358Srpaulo	if (ent == NULL) {
86206358Srpaulo		if (toprec)
87206358Srpaulo			free(toprec);
88206358Srpaulo                toprec = NULL;
89206358Srpaulo                topreclen = 0;
90206358Srpaulo                return (0);
91178354Ssam        }
92178354Ssam        topreclen = strlen(ent);
93178354Ssam        if ((toprec = malloc (topreclen + 1)) == NULL) {
94178354Ssam		errno = ENOMEM;
95206358Srpaulo                return (-1);
96206358Srpaulo	}
97206358Srpaulo	gottoprec = 0;
98206358Srpaulo        (void)strcpy(toprec, ent);
99206358Srpaulo        return (0);
100206358Srpaulo}
101206358Srpaulo
102206358Srpaulo/*
103206358Srpaulo * Cgetcap searches the capability record buf for the capability cap with
104206358Srpaulo * type `type'.  A pointer to the value of cap is returned on success, NULL
105206358Srpaulo * if the requested capability couldn't be found.
106206358Srpaulo *
107206358Srpaulo * Specifying a type of ':' means that nothing should follow cap (:cap:).
108206358Srpaulo * In this case a pointer to the terminating ':' or NUL will be returned if
109206358Srpaulo * cap is found.
110206358Srpaulo *
111206358Srpaulo * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
112206358Srpaulo * return NULL.
113178354Ssam */
114206358Srpaulochar *
115178354Ssamcgetcap(buf, cap, type)
116178354Ssam	char *buf, *cap;
117178354Ssam	int type;
118178354Ssam{
119178354Ssam	char *bp, *cp;
120178354Ssam
121178354Ssam	bp = buf;
122178354Ssam	for (;;) {
123206358Srpaulo		/*
124206358Srpaulo		 * Skip past the current capability field - it's either the
125178354Ssam		 * name field if this is the first time through the loop, or
126206358Srpaulo		 * the remainder of a field whose name failed to match cap.
127206358Srpaulo		 */
128206358Srpaulo		for (;;)
129206358Srpaulo			if (*bp == '\0')
130206358Srpaulo				return (NULL);
131206419Srpaulo			else
132206419Srpaulo				if (*bp++ == ':')
133206419Srpaulo					break;
134206419Srpaulo
135206419Srpaulo		/*
136206419Srpaulo		 * Try to match (cap, type) in buf.
137178354Ssam		 */
138206358Srpaulo		for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
139206358Srpaulo			continue;
140178354Ssam		if (*cp != '\0')
141178354Ssam			continue;
142206358Srpaulo		if (*bp == '@')
143206358Srpaulo			return (NULL);
144178354Ssam		if (type == ':') {
145206358Srpaulo			if (*bp != '\0' && *bp != ':')
146178354Ssam				continue;
147178354Ssam			return(bp);
148178354Ssam		}
149178354Ssam		if (*bp != type)
150178354Ssam			continue;
151178354Ssam		bp++;
152178354Ssam		return (*bp == '@' ? NULL : bp);
153178354Ssam	}
154178354Ssam	/* NOTREACHED */
155178354Ssam}
156178354Ssam
157178354Ssam/*
158178354Ssam * Cgetent extracts the capability record name from the NULL terminated file
159178354Ssam * array db_array and returns a pointer to a malloc'd copy of it in buf.
160178354Ssam * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
161178354Ssam * cgetflag, and cgetstr, but may then be free'd.  0 is returned on success,
162178354Ssam * -1 if the requested record couldn't be found, -2 if a system error was
163178354Ssam * encountered (couldn't open/read a file, etc.), and -3 if a potential
164206358Srpaulo * reference loop is detected.
165206358Srpaulo */
166178354Ssamint
167206358Srpaulocgetent(buf, db_array, name)
168206419Srpaulo	char **buf, **db_array, *name;
169206419Srpaulo{
170178354Ssam	u_int dummy;
171178354Ssam
172207323Srpaulo	return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
173207323Srpaulo}
174207323Srpaulo
175207323Srpaulo/*
176207323Srpaulo * Getent implements the functions of cgetent.  If fd is non-negative,
177207323Srpaulo * *db_array has already been opened and fd is the open file descriptor.  We
178207323Srpaulo * do this to save time and avoid using up file descriptors for tc=
179207323Srpaulo * recursions.
180207323Srpaulo *
181207323Srpaulo * Getent returns the same success/failure codes as cgetent.  On success, a
182207323Srpaulo * pointer to a malloc'ed capability record with all tc= capabilities fully
183178354Ssam * expanded and its length (not including trailing ASCII NUL) are left in
184178354Ssam * *cap and *len.
185178354Ssam *
186178354Ssam * Basic algorithm:
187178354Ssam *	+ Allocate memory incrementally as needed in chunks of size BFRAG
188178354Ssam *	  for capability buffer.
189178354Ssam *	+ Recurse for each tc=name and interpolate result.  Stop when all
190178354Ssam *	  names interpolated, a name can't be found, or depth exceeds
191178354Ssam *	  MAX_RECURSION.
192178354Ssam */
193178354Ssamstatic int
194178354Ssamgetent(cap, len, db_array, fd, name, depth, nfield)
195178354Ssam	char **cap, **db_array, *name, *nfield;
196178354Ssam	u_int *len;
197178354Ssam	int fd, depth;
198178354Ssam{
199206358Srpaulo	DB *capdbp;
200206358Srpaulo	char *r_end, *rp, **db_p;
201206358Srpaulo	int myfd, eof, foundit, retval, clen;
202206358Srpaulo	char *record, *cbuf;
203206358Srpaulo	int tc_not_resolved;
204206358Srpaulo	char pbuf[_POSIX_PATH_MAX];
205206358Srpaulo
206178354Ssam	/*
207178354Ssam	 * Return with ``loop detected'' error if we've recursed more than
208178354Ssam	 * MAX_RECURSION times.
209178354Ssam	 */
210178354Ssam	if (depth > MAX_RECURSION)
211178354Ssam		return (-3);
212178354Ssam
213178354Ssam	/*
214178354Ssam	 * Check if we have a top record from cgetset().
215178354Ssam         */
216178354Ssam	if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
217178354Ssam		if ((record = malloc (topreclen + BFRAG)) == NULL) {
218178354Ssam			errno = ENOMEM;
219178354Ssam			return (-2);
220178354Ssam		}
221206358Srpaulo		(void)strcpy(record, toprec);
222206358Srpaulo		myfd = 0;
223178354Ssam		db_p = db_array;
224206358Srpaulo		rp = record + topreclen + 1;
225206358Srpaulo		r_end = rp + BFRAG;
226178354Ssam		goto tc_exp;
227178354Ssam	}
228178354Ssam	/*
229178354Ssam	 * Allocate first chunk of memory.
230178354Ssam	 */
231178354Ssam	if ((record = malloc(BFRAG)) == NULL) {
232178354Ssam		errno = ENOMEM;
233178354Ssam		return (-2);
234178354Ssam	}
235178354Ssam	r_end = record + BFRAG;
236178354Ssam	foundit = 0;
237178354Ssam	/*
238178354Ssam	 * Loop through database array until finding the record.
239178354Ssam	 */
240178354Ssam
241178354Ssam	for (db_p = db_array; *db_p != NULL; db_p++) {
242178354Ssam		eof = 0;
243178354Ssam
244178354Ssam		/*
245178354Ssam		 * Open database if not already open.
246178354Ssam		 */
247178354Ssam
248178354Ssam		if (fd >= 0) {
249178354Ssam			(void)lseek(fd, (off_t)0, SEEK_SET);
250178354Ssam			myfd = 0;
251178354Ssam		} else {
252178354Ssam			(void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p);
253178354Ssam			if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0))
254178354Ssam			     != NULL) {
255178354Ssam				free(record);
256178354Ssam				retval = cdbget(capdbp, &record, name);
257178354Ssam				if (retval < 0) {
258178354Ssam					/* no record available */
259178354Ssam					(void)capdbp->close(capdbp);
260206358Srpaulo					return (retval);
261206358Srpaulo				}
262178354Ssam				/* save the data; close frees it */
263178354Ssam				clen = strlen(record);
264178354Ssam				cbuf = malloc(clen + 1);
265178354Ssam				memcpy(cbuf, record, clen + 1);
266178354Ssam				if (capdbp->close(capdbp) < 0) {
267178354Ssam					free(cbuf);
268178354Ssam					return (-2);
269178354Ssam				}
270178354Ssam				*len = clen;
271178354Ssam				*cap = cbuf;
272178354Ssam				return (retval);
273178354Ssam			} else {
274178354Ssam				fd = _open(*db_p, O_RDONLY, 0);
275178354Ssam				if (fd < 0)
276178354Ssam					continue;
277178354Ssam				myfd = 1;
278178354Ssam			}
279178354Ssam		}
280206358Srpaulo		/*
281206358Srpaulo		 * Find the requested capability record ...
282178354Ssam		 */
283178354Ssam		{
284178354Ssam		char buf[BUFSIZ];
285178354Ssam		char *b_end, *bp;
286178354Ssam		int c;
287178354Ssam
288178354Ssam		/*
289178354Ssam		 * Loop invariants:
290178354Ssam		 *	There is always room for one more character in record.
291178354Ssam		 *	R_end always points just past end of record.
292178354Ssam		 *	Rp always points just past last character in record.
293178354Ssam		 *	B_end always points just past last character in buf.
294178354Ssam		 *	Bp always points at next character in buf.
295178354Ssam		 */
296178354Ssam		b_end = buf;
297178354Ssam		bp = buf;
298178354Ssam		for (;;) {
299178354Ssam
300178354Ssam			/*
301178354Ssam			 * Read in a line implementing (\, newline)
302178354Ssam			 * line continuation.
303178354Ssam			 */
304178354Ssam			rp = record;
305178354Ssam			for (;;) {
306178354Ssam				if (bp >= b_end) {
307178354Ssam					int n;
308206358Srpaulo
309206358Srpaulo					n = _read(fd, buf, sizeof(buf));
310206358Srpaulo					if (n <= 0) {
311206358Srpaulo						if (myfd)
312206358Srpaulo							(void)_close(fd);
313206358Srpaulo						if (n < 0) {
314206358Srpaulo							free(record);
315206358Srpaulo							return (-2);
316206358Srpaulo						} else {
317206358Srpaulo							fd = -1;
318206358Srpaulo							eof = 1;
319206358Srpaulo							break;
320206358Srpaulo						}
321206358Srpaulo					}
322206358Srpaulo					b_end = buf+n;
323206358Srpaulo					bp = buf;
324206358Srpaulo				}
325206358Srpaulo
326178354Ssam				c = *bp++;
327178354Ssam				if (c == '\n') {
328178354Ssam					if (rp > record && *(rp-1) == '\\') {
329206358Srpaulo						rp--;
330206358Srpaulo						continue;
331178354Ssam					} else
332178354Ssam						break;
333178354Ssam				}
334178354Ssam				*rp++ = c;
335178354Ssam
336178354Ssam				/*
337206358Srpaulo				 * Enforce loop invariant: if no room
338178354Ssam				 * left in record buffer, try to get
339178354Ssam				 * some more.
340178354Ssam				 */
341178354Ssam				if (rp >= r_end) {
342206358Srpaulo					u_int pos;
343178354Ssam					size_t newsize;
344178354Ssam
345178354Ssam					pos = rp - record;
346178354Ssam					newsize = r_end - record + BFRAG;
347206358Srpaulo					record = reallocf(record, newsize);
348178354Ssam					if (record == NULL) {
349178354Ssam						errno = ENOMEM;
350						if (myfd)
351							(void)_close(fd);
352						return (-2);
353					}
354					r_end = record + newsize;
355					rp = record + pos;
356				}
357			}
358				/* loop invariant let's us do this */
359			*rp++ = '\0';
360
361			/*
362			 * If encountered eof check next file.
363			 */
364			if (eof)
365				break;
366
367			/*
368			 * Toss blank lines and comments.
369			 */
370			if (*record == '\0' || *record == '#')
371				continue;
372
373			/*
374			 * See if this is the record we want ...
375			 */
376			if (cgetmatch(record, name) == 0) {
377				if (nfield == NULL || !nfcmp(nfield, record)) {
378					foundit = 1;
379					break;	/* found it! */
380				}
381			}
382		}
383	}
384		if (foundit)
385			break;
386	}
387
388	if (!foundit) {
389		free(record);
390		return (-1);
391	}
392
393	/*
394	 * Got the capability record, but now we have to expand all tc=name
395	 * references in it ...
396	 */
397tc_exp:	{
398		char *newicap, *s;
399		int newilen;
400		u_int ilen;
401		int diff, iret, tclen;
402		char *icap, *scan, *tc, *tcstart, *tcend;
403
404		/*
405		 * Loop invariants:
406		 *	There is room for one more character in record.
407		 *	R_end points just past end of record.
408		 *	Rp points just past last character in record.
409		 *	Scan points at remainder of record that needs to be
410		 *	scanned for tc=name constructs.
411		 */
412		scan = record;
413		tc_not_resolved = 0;
414		for (;;) {
415			if ((tc = cgetcap(scan, "tc", '=')) == NULL)
416				break;
417
418			/*
419			 * Find end of tc=name and stomp on the trailing `:'
420			 * (if present) so we can use it to call ourselves.
421			 */
422			s = tc;
423			for (;;)
424				if (*s == '\0')
425					break;
426				else
427					if (*s++ == ':') {
428						*(s - 1) = '\0';
429						break;
430					}
431			tcstart = tc - 3;
432			tclen = s - tcstart;
433			tcend = s;
434
435			iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
436				      NULL);
437			newicap = icap;		/* Put into a register. */
438			newilen = ilen;
439			if (iret != 0) {
440				/* an error */
441				if (iret < -1) {
442					if (myfd)
443						(void)_close(fd);
444					free(record);
445					return (iret);
446				}
447				if (iret == 1)
448					tc_not_resolved = 1;
449				/* couldn't resolve tc */
450				if (iret == -1) {
451					*(s - 1) = ':';
452					scan = s - 1;
453					tc_not_resolved = 1;
454					continue;
455
456				}
457			}
458			/* not interested in name field of tc'ed record */
459			s = newicap;
460			for (;;)
461				if (*s == '\0')
462					break;
463				else
464					if (*s++ == ':')
465						break;
466			newilen -= s - newicap;
467			newicap = s;
468
469			/* make sure interpolated record is `:'-terminated */
470			s += newilen;
471			if (*(s-1) != ':') {
472				*s = ':';	/* overwrite NUL with : */
473				newilen++;
474			}
475
476			/*
477			 * Make sure there's enough room to insert the
478			 * new record.
479			 */
480			diff = newilen - tclen;
481			if (diff >= r_end - rp) {
482				u_int pos, tcpos, tcposend;
483				size_t newsize;
484
485				pos = rp - record;
486				newsize = r_end - record + diff + BFRAG;
487				tcpos = tcstart - record;
488				tcposend = tcend - record;
489				record = reallocf(record, newsize);
490				if (record == NULL) {
491					errno = ENOMEM;
492					if (myfd)
493						(void)_close(fd);
494					free(icap);
495					return (-2);
496				}
497				r_end = record + newsize;
498				rp = record + pos;
499				tcstart = record + tcpos;
500				tcend = record + tcposend;
501			}
502
503			/*
504			 * Insert tc'ed record into our record.
505			 */
506			s = tcstart + newilen;
507			bcopy(tcend, s, rp - tcend);
508			bcopy(newicap, tcstart, newilen);
509			rp += diff;
510			free(icap);
511
512			/*
513			 * Start scan on `:' so next cgetcap works properly
514			 * (cgetcap always skips first field).
515			 */
516			scan = s-1;
517		}
518
519	}
520	/*
521	 * Close file (if we opened it), give back any extra memory, and
522	 * return capability, length and success.
523	 */
524	if (myfd)
525		(void)_close(fd);
526	*len = rp - record - 1;	/* don't count NUL */
527	if (r_end > rp)
528		if ((record =
529		     reallocf(record, (size_t)(rp - record))) == NULL) {
530			errno = ENOMEM;
531			return (-2);
532		}
533
534	*cap = record;
535	if (tc_not_resolved)
536		return (1);
537	return (0);
538}
539
540static int
541cdbget(capdbp, bp, name)
542	DB *capdbp;
543	char **bp, *name;
544{
545	DBT key, data;
546
547	key.data = name;
548	key.size = strlen(name);
549
550	for (;;) {
551		/* Get the reference. */
552		switch(capdbp->get(capdbp, &key, &data, 0)) {
553		case -1:
554			return (-2);
555		case 1:
556			return (-1);
557		}
558
559		/* If not an index to another record, leave. */
560		if (((char *)data.data)[0] != SHADOW)
561			break;
562
563		key.data = (char *)data.data + 1;
564		key.size = data.size - 1;
565	}
566
567	*bp = (char *)data.data + 1;
568	return (((char *)(data.data))[0] == TCERR ? 1 : 0);
569}
570
571/*
572 * Cgetmatch will return 0 if name is one of the names of the capability
573 * record buf, -1 if not.
574 */
575int
576cgetmatch(buf, name)
577	char *buf, *name;
578{
579	char *np, *bp;
580
581	/*
582	 * Start search at beginning of record.
583	 */
584	bp = buf;
585	for (;;) {
586		/*
587		 * Try to match a record name.
588		 */
589		np = name;
590		for (;;)
591			if (*np == '\0')
592				if (*bp == '|' || *bp == ':' || *bp == '\0')
593					return (0);
594				else
595					break;
596			else
597				if (*bp++ != *np++)
598					break;
599
600		/*
601		 * Match failed, skip to next name in record.
602		 */
603		bp--;	/* a '|' or ':' may have stopped the match */
604		for (;;)
605			if (*bp == '\0' || *bp == ':')
606				return (-1);	/* match failed totally */
607			else
608				if (*bp++ == '|')
609					break;	/* found next name */
610	}
611}
612
613
614
615
616
617int
618cgetfirst(buf, db_array)
619	char **buf, **db_array;
620{
621	(void)cgetclose();
622	return (cgetnext(buf, db_array));
623}
624
625static FILE *pfp;
626static int slash;
627static char **dbp;
628
629int
630cgetclose()
631{
632	if (pfp != NULL) {
633		(void)fclose(pfp);
634		pfp = NULL;
635	}
636	dbp = NULL;
637	gottoprec = 0;
638	slash = 0;
639	return(0);
640}
641
642/*
643 * Cgetnext() gets either the first or next entry in the logical database
644 * specified by db_array.  It returns 0 upon completion of the database, 1
645 * upon returning an entry with more remaining, and -1 if an error occurs.
646 */
647int
648cgetnext(bp, db_array)
649	char **bp;
650	char **db_array;
651{
652	size_t len;
653	int done, hadreaderr, i, savederrno, status;
654	char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
655	u_int dummy;
656
657	if (dbp == NULL)
658		dbp = db_array;
659
660	if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
661		(void)cgetclose();
662		return (-1);
663	}
664	for(;;) {
665		if (toprec && !gottoprec) {
666			gottoprec = 1;
667			line = toprec;
668		} else {
669			line = fgetln(pfp, &len);
670			if (line == NULL && pfp) {
671				hadreaderr = ferror(pfp);
672				if (hadreaderr)
673					savederrno = errno;
674				fclose(pfp);
675				pfp = NULL;
676				if (hadreaderr) {
677					cgetclose();
678					errno = savederrno;
679					return (-1);
680				} else {
681					if (*++dbp == NULL) {
682						(void)cgetclose();
683						return (0);
684					} else if ((pfp =
685					    fopen(*dbp, "r")) == NULL) {
686						(void)cgetclose();
687						return (-1);
688					} else
689						continue;
690				}
691			} else
692				line[len - 1] = '\0';
693			if (len == 1) {
694				slash = 0;
695				continue;
696			}
697			if (isspace((unsigned char)*line) ||
698			    *line == ':' || *line == '#' || slash) {
699				if (line[len - 2] == '\\')
700					slash = 1;
701				else
702					slash = 0;
703				continue;
704			}
705			if (line[len - 2] == '\\')
706				slash = 1;
707			else
708				slash = 0;
709		}
710
711
712		/*
713		 * Line points to a name line.
714		 */
715		i = 0;
716		done = 0;
717		np = nbuf;
718		for (;;) {
719			for (cp = line; *cp != '\0'; cp++) {
720				if (*cp == ':') {
721					*np++ = ':';
722					done = 1;
723					break;
724				}
725				if (*cp == '\\')
726					break;
727				*np++ = *cp;
728			}
729			if (done) {
730				*np = '\0';
731				break;
732			} else { /* name field extends beyond the line */
733				line = fgetln(pfp, &len);
734				if (line == NULL && pfp) {
735					/* Name extends beyond the EOF! */
736					hadreaderr = ferror(pfp);
737					if (hadreaderr)
738						savederrno = errno;
739					fclose(pfp);
740					pfp = NULL;
741					if (hadreaderr) {
742						cgetclose();
743						errno = savederrno;
744						return (-1);
745					} else {
746						cgetclose();
747						return (-1);
748					}
749				} else
750					line[len - 1] = '\0';
751			}
752		}
753		rp = buf;
754		for(cp = nbuf; *cp != '\0'; cp++)
755			if (*cp == '|' || *cp == ':')
756				break;
757			else
758				*rp++ = *cp;
759
760		*rp = '\0';
761		/*
762		 * XXX
763		 * Last argument of getent here should be nbuf if we want true
764		 * sequential access in the case of duplicates.
765		 * With NULL, getent will return the first entry found
766		 * rather than the duplicate entry record.  This is a
767		 * matter of semantics that should be resolved.
768		 */
769		status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
770		if (status == -2 || status == -3)
771			(void)cgetclose();
772
773		return (status + 1);
774	}
775	/* NOTREACHED */
776}
777
778/*
779 * Cgetstr retrieves the value of the string capability cap from the
780 * capability record pointed to by buf.  A pointer to a decoded, NUL
781 * terminated, malloc'd copy of the string is returned in the char *
782 * pointed to by str.  The length of the string not including the trailing
783 * NUL is returned on success, -1 if the requested string capability
784 * couldn't be found, -2 if a system error was encountered (storage
785 * allocation failure).
786 */
787int
788cgetstr(buf, cap, str)
789	char *buf, *cap;
790	char **str;
791{
792	u_int m_room;
793	char *bp, *mp;
794	int len;
795	char *mem;
796
797	/*
798	 * Find string capability cap
799	 */
800	bp = cgetcap(buf, cap, '=');
801	if (bp == NULL)
802		return (-1);
803
804	/*
805	 * Conversion / storage allocation loop ...  Allocate memory in
806	 * chunks SFRAG in size.
807	 */
808	if ((mem = malloc(SFRAG)) == NULL) {
809		errno = ENOMEM;
810		return (-2);	/* couldn't even allocate the first fragment */
811	}
812	m_room = SFRAG;
813	mp = mem;
814
815	while (*bp != ':' && *bp != '\0') {
816		/*
817		 * Loop invariants:
818		 *	There is always room for one more character in mem.
819		 *	Mp always points just past last character in mem.
820		 *	Bp always points at next character in buf.
821		 */
822		if (*bp == '^') {
823			bp++;
824			if (*bp == ':' || *bp == '\0')
825				break;	/* drop unfinished escape */
826			if (*bp == '?') {
827				*mp++ = '\177';
828				bp++;
829			} else
830				*mp++ = *bp++ & 037;
831		} else if (*bp == '\\') {
832			bp++;
833			if (*bp == ':' || *bp == '\0')
834				break;	/* drop unfinished escape */
835			if ('0' <= *bp && *bp <= '7') {
836				int n, i;
837
838				n = 0;
839				i = 3;	/* maximum of three octal digits */
840				do {
841					n = n * 8 + (*bp++ - '0');
842				} while (--i && '0' <= *bp && *bp <= '7');
843				*mp++ = n;
844			}
845			else switch (*bp++) {
846				case 'b': case 'B':
847					*mp++ = '\b';
848					break;
849				case 't': case 'T':
850					*mp++ = '\t';
851					break;
852				case 'n': case 'N':
853					*mp++ = '\n';
854					break;
855				case 'f': case 'F':
856					*mp++ = '\f';
857					break;
858				case 'r': case 'R':
859					*mp++ = '\r';
860					break;
861				case 'e': case 'E':
862					*mp++ = ESC;
863					break;
864				case 'c': case 'C':
865					*mp++ = ':';
866					break;
867				default:
868					/*
869					 * Catches '\', '^', and
870					 *  everything else.
871					 */
872					*mp++ = *(bp-1);
873					break;
874			}
875		} else
876			*mp++ = *bp++;
877		m_room--;
878
879		/*
880		 * Enforce loop invariant: if no room left in current
881		 * buffer, try to get some more.
882		 */
883		if (m_room == 0) {
884			size_t size = mp - mem;
885
886			if ((mem = reallocf(mem, size + SFRAG)) == NULL)
887				return (-2);
888			m_room = SFRAG;
889			mp = mem + size;
890		}
891	}
892	*mp++ = '\0';	/* loop invariant let's us do this */
893	m_room--;
894	len = mp - mem - 1;
895
896	/*
897	 * Give back any extra memory and return value and success.
898	 */
899	if (m_room != 0)
900		if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
901			return (-2);
902	*str = mem;
903	return (len);
904}
905
906/*
907 * Cgetustr retrieves the value of the string capability cap from the
908 * capability record pointed to by buf.  The difference between cgetustr()
909 * and cgetstr() is that cgetustr does not decode escapes but rather treats
910 * all characters literally.  A pointer to a  NUL terminated malloc'd
911 * copy of the string is returned in the char pointed to by str.  The
912 * length of the string not including the trailing NUL is returned on success,
913 * -1 if the requested string capability couldn't be found, -2 if a system
914 * error was encountered (storage allocation failure).
915 */
916int
917cgetustr(buf, cap, str)
918	char *buf, *cap, **str;
919{
920	u_int m_room;
921	char *bp, *mp;
922	int len;
923	char *mem;
924
925	/*
926	 * Find string capability cap
927	 */
928	if ((bp = cgetcap(buf, cap, '=')) == NULL)
929		return (-1);
930
931	/*
932	 * Conversion / storage allocation loop ...  Allocate memory in
933	 * chunks SFRAG in size.
934	 */
935	if ((mem = malloc(SFRAG)) == NULL) {
936		errno = ENOMEM;
937		return (-2);	/* couldn't even allocate the first fragment */
938	}
939	m_room = SFRAG;
940	mp = mem;
941
942	while (*bp != ':' && *bp != '\0') {
943		/*
944		 * Loop invariants:
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.
948		 */
949		*mp++ = *bp++;
950		m_room--;
951
952		/*
953		 * Enforce loop invariant: if no room left in current
954		 * buffer, try to get some more.
955		 */
956		if (m_room == 0) {
957			size_t size = mp - mem;
958
959			if ((mem = reallocf(mem, size + SFRAG)) == NULL)
960				return (-2);
961			m_room = SFRAG;
962			mp = mem + size;
963		}
964	}
965	*mp++ = '\0';	/* loop invariant let's us do this */
966	m_room--;
967	len = mp - mem - 1;
968
969	/*
970	 * Give back any extra memory and return value and success.
971	 */
972	if (m_room != 0)
973		if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
974			return (-2);
975	*str = mem;
976	return (len);
977}
978
979/*
980 * Cgetnum retrieves the value of the numeric capability cap from the
981 * capability record pointed to by buf.  The numeric value is returned in
982 * the long pointed to by num.  0 is returned on success, -1 if the requested
983 * numeric capability couldn't be found.
984 */
985int
986cgetnum(buf, cap, num)
987	char *buf, *cap;
988	long *num;
989{
990	long n;
991	int base, digit;
992	char *bp;
993
994	/*
995	 * Find numeric capability cap
996	 */
997	bp = cgetcap(buf, cap, '#');
998	if (bp == NULL)
999		return (-1);
1000
1001	/*
1002	 * Look at value and determine numeric base:
1003	 *	0x... or 0X...	hexadecimal,
1004	 * else	0...		octal,
1005	 * else			decimal.
1006	 */
1007	if (*bp == '0') {
1008		bp++;
1009		if (*bp == 'x' || *bp == 'X') {
1010			bp++;
1011			base = 16;
1012		} else
1013			base = 8;
1014	} else
1015		base = 10;
1016
1017	/*
1018	 * Conversion loop ...
1019	 */
1020	n = 0;
1021	for (;;) {
1022		if ('0' <= *bp && *bp <= '9')
1023			digit = *bp - '0';
1024		else if ('a' <= *bp && *bp <= 'f')
1025			digit = 10 + *bp - 'a';
1026		else if ('A' <= *bp && *bp <= 'F')
1027			digit = 10 + *bp - 'A';
1028		else
1029			break;
1030
1031		if (digit >= base)
1032			break;
1033
1034		n = n * base + digit;
1035		bp++;
1036	}
1037
1038	/*
1039	 * Return value and success.
1040	 */
1041	*num = n;
1042	return (0);
1043}
1044
1045
1046/*
1047 * Compare name field of record.
1048 */
1049static int
1050nfcmp(nf, rec)
1051	char *nf, *rec;
1052{
1053	char *cp, tmp;
1054	int ret;
1055
1056	for (cp = rec; *cp != ':'; cp++)
1057		;
1058
1059	tmp = *(cp + 1);
1060	*(cp + 1) = '\0';
1061	ret = strcmp(nf, rec);
1062	*(cp + 1) = tmp;
1063
1064	return (ret);
1065}
1066