Home | History | Annotate | Line # | Download | only in gen
getcap.c revision 1.54
      1 /*	$NetBSD: getcap.c,v 1.54 2014/09/18 13:58:20 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Casey Leedom of Lawrence Livermore National Laboratory.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     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.
     21  *
     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
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #if HAVE_NBTOOL_CONFIG_H
     36 #include "nbtool_config.h"
     37 #endif
     38 
     39 #include <sys/cdefs.h>
     40 #if defined(LIBC_SCCS) && !defined(lint)
     41 #if 0
     42 static char sccsid[] = "@(#)getcap.c	8.3 (Berkeley) 3/25/94";
     43 #else
     44 __RCSID("$NetBSD: getcap.c,v 1.54 2014/09/18 13:58:20 christos Exp $");
     45 #endif
     46 #endif /* LIBC_SCCS and not lint */
     47 
     48 #ifndef SMALL
     49 #include "namespace.h"
     50 #endif
     51 #include <sys/types.h>
     52 #include <sys/param.h>
     53 
     54 #include <assert.h>
     55 #include <stddef.h>
     56 #include <ctype.h>
     57 #ifndef SMALL
     58 #include <db.h>
     59 #endif
     60 #include <errno.h>
     61 #include <fcntl.h>
     62 #include <limits.h>
     63 #include <stdio.h>
     64 #include <stdlib.h>
     65 #include <string.h>
     66 #include <unistd.h>
     67 
     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)
     80 #endif
     81 
     82 #define	BFRAG		1024
     83 #define	BSIZE		1024
     84 #define	ESC		('[' & 037)	/* ASCII ESC */
     85 #define	MAX_RECURSION	32		/* maximum getent recursion */
     86 #define	SFRAG		100		/* cgetstr mallocs in SFRAG chunks */
     87 
     88 #define RECOK	(char)0
     89 #define TCERR	(char)1
     90 #define	SHADOW	(char)2
     91 
     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 */
     96 
     97 #ifndef SMALL
     98 static int	cdbget(DB *, char **, const char *);
     99 #endif
    100 static int 	getent(char **, size_t *, const char * const *, int,
    101     const char *, int, char *);
    102 static int	nfcmp(char *, char *);
    103 
    104 /*
    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.
    108  */
    109 int
    110 cgetset(const char *ent)
    111 {
    112 	const char *source, *check;
    113 	char *dest;
    114 
    115 	if (ent == NULL) {
    116 		if (toprec != NULL)
    117 			free(toprec);
    118                 toprec = NULL;
    119                 topreclen = 0;
    120                 return 0;
    121         }
    122         topreclen = strlen(ent);
    123         if ((toprec = malloc(topreclen + 1)) == NULL) {
    124 		errno = ENOMEM;
    125                 return -1;
    126 	}
    127 	gottoprec = 0;
    128 
    129 	source = ent;
    130 	dest = toprec;
    131 	while (*source != '\0') { /* Strip whitespace */
    132 		*dest++ = *source++; /* Do not check first field */
    133 		while (*source == ':') {
    134 			check = source + 1;
    135 			while (*check && (isspace((unsigned char)*check) ||
    136 			    (*check=='\\' && isspace((unsigned char)check[1]))))
    137 				++check;
    138 			if (*check == ':')
    139 				source = check;
    140 			else
    141 				break;
    142 
    143 		}
    144 	}
    145 	*dest = 0;
    146 
    147         return 0;
    148 }
    149 
    150 /*
    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.
    154  *
    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
    157  * cap is found.
    158  *
    159  * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
    160  * return NULL.
    161  */
    162 char *
    163 cgetcap(char *buf, const char *cap, int type)
    164 {
    165 	char *bp;
    166 	const char *cp;
    167 
    168 	_DIAGASSERT(buf != NULL);
    169 	_DIAGASSERT(cap != NULL);
    170 
    171 	bp = buf;
    172 	for (;;) {
    173 		/*
    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.
    177 		 */
    178 		for (;;)
    179 			if (*bp == '\0')
    180 				return NULL;
    181 			else if (*bp++ == ':')
    182 				break;
    183 
    184 		/*
    185 		 * Try to match (cap, type) in buf.
    186 		 */
    187 		for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
    188 			continue;
    189 		if (*cp != '\0')
    190 			continue;
    191 		if (*bp == '@')
    192 			return NULL;
    193 		if (type == ':') {
    194 			if (*bp != '\0' && *bp != ':')
    195 				continue;
    196 			return bp;
    197 		}
    198 		if (*bp != type)
    199 			continue;
    200 		bp++;
    201 		return *bp == '@' ? NULL : bp;
    202 	}
    203 	/* NOTREACHED */
    204 }
    205 
    206 /*
    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.
    214  */
    215 /* coverity[+alloc : arg-*0] */
    216 int
    217 cgetent(char **buf, const char * const *db_array, const char *name)
    218 {
    219 	size_t dummy;
    220 
    221 	_DIAGASSERT(buf != NULL);
    222 	_DIAGASSERT(db_array != NULL);
    223 	_DIAGASSERT(name != NULL);
    224 
    225 	return getent(buf, &dummy, db_array, -1, name, 0, NULL);
    226 }
    227 
    228 void
    229 csetexpandtc(int etc)
    230 {
    231 	expandtc = etc;
    232 }
    233 
    234 /*
    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=
    238  * recursions.
    239  *
    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
    243  * *cap and *len.
    244  *
    245  * Basic algorithm:
    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
    250  *	  MAX_RECURSION.
    251  */
    252 /* coverity[+alloc : arg-*0] */
    253 static int
    254 getent(char **cap, size_t *len, const char * const *db_array, int fd,
    255     const char *name, int depth, char *nfield)
    256 {
    257 	char *record, *newrecord;
    258 	char *r_end, *rp;	/* pacify gcc */
    259 	const char * const *db_p;
    260 	int myfd, eof, foundit;
    261 	int tc_not_resolved;
    262 
    263 	_DIAGASSERT(cap != NULL);
    264 	_DIAGASSERT(len != NULL);
    265 	_DIAGASSERT(db_array != NULL);
    266 	/* fd may be -1 */
    267 	_DIAGASSERT(name != NULL);
    268 	/* nfield may be NULL */
    269 
    270 	myfd = 0;
    271 	rp = NULL;
    272 
    273 	/*
    274 	 * Return with ``loop detected'' error if we've recursed more than
    275 	 * MAX_RECURSION times.
    276 	 */
    277 	if (depth > MAX_RECURSION)
    278 		return -3;
    279 
    280 	/*
    281 	 * Check if we have a top record from cgetset().
    282          */
    283 	if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) {
    284 		if ((record = malloc(topreclen + BFRAG)) == NULL) {
    285 			errno = ENOMEM;
    286 			return -2;
    287 		}
    288 		(void)strcpy(record, toprec);	/* XXX: strcpy is safe */
    289 		db_p = db_array;
    290 		rp = record + topreclen + 1;
    291 		r_end = rp + BFRAG;
    292 		goto tc_exp;
    293 	}
    294 	/*
    295 	 * Allocate first chunk of memory.
    296 	 */
    297 	if ((record = malloc(BFRAG)) == NULL) {
    298 		errno = ENOMEM;
    299 		return -2;
    300 	}
    301 	r_end = record + BFRAG;
    302 	foundit = 0;
    303 	/*
    304 	 * Loop through database array until finding the record.
    305 	 */
    306 
    307 	for (db_p = db_array; *db_p != NULL; db_p++) {
    308 		eof = 0;
    309 
    310 		/*
    311 		 * Open database if not already open.
    312 		 */
    313 
    314 		if (fd >= 0) {
    315 			(void)lseek(fd, (off_t)0, SEEK_SET);
    316 		} else {
    317 #ifndef SMALL
    318 			DB *capdbp;
    319 			char pbuf[MAXPATHLEN];
    320 			char *cbuf;
    321 			int retval;
    322 			size_t clen;
    323 
    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) {
    327 				free(record);
    328 				retval = cdbget(capdbp, &record, name);
    329 				if (retval < 0) {
    330 					/* no record available */
    331 					(void)capdbp->close(capdbp);
    332 					return retval;
    333 				}
    334 				/* save the data; close frees it */
    335 				clen = strlen(record);
    336 				if ((cbuf = malloc(clen + 1)) == NULL) {
    337 					(void)capdbp->close(capdbp);
    338 					errno = ENOMEM;
    339 					return -2;
    340 				}
    341 				memmove(cbuf, record, clen + 1);
    342 				if (capdbp->close(capdbp) < 0) {
    343 					int serrno = errno;
    344 
    345 					free(cbuf);
    346 					errno = serrno;
    347 					return -2;
    348 				}
    349 				*len = clen;
    350 				*cap = cbuf;
    351 				return retval;
    352 			} else
    353 #endif
    354 			{
    355 				fd = open(*db_p, O_RDONLY | O_CLOEXEC, 0);
    356 				if (fd < 0) {
    357 					/* No error on unfound file. */
    358 					continue;
    359 				}
    360 				myfd = 1;
    361 			}
    362 		}
    363 		/*
    364 		 * Find the requested capability record ...
    365 		 */
    366 		{
    367 		char buf[BUFSIZ];
    368 		char *b_end, *bp, *cp;
    369 		int c, slash;
    370 
    371 		/*
    372 		 * Loop invariants:
    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.
    379 		 */
    380 		b_end = buf;
    381 		bp = buf;
    382 		cp = NULL;
    383 		slash = 0;
    384 		for (;;) {
    385 			/*
    386 			 * Read in a line implementing (\, newline)
    387 			 * line continuation.
    388 			 */
    389 			rp = record;
    390 			for (;;) {
    391 				if (bp >= b_end) {
    392 					ssize_t n;
    393 
    394 					n = read(fd, buf, sizeof(buf));
    395 					if (n <= 0) {
    396 						if (myfd)
    397 							(void)close(fd);
    398 						if (n < 0) {
    399 							int serrno = errno;
    400 
    401 							free(record);
    402 							errno = serrno;
    403 							return -2;
    404 						} else {
    405 							fd = -1;
    406 							eof = 1;
    407 							break;
    408 						}
    409 					}
    410 					b_end = buf+n;
    411 					bp = buf;
    412 				}
    413 
    414 				c = *bp++;
    415 				if (c == '\n') {
    416 					if (slash) {
    417 						slash = 0;
    418 						rp--;
    419 						continue;
    420 					} else
    421 						break;
    422 				}
    423 				if (slash) {
    424 					slash = 0;
    425 					cp = 0;
    426 				}
    427 				if (c == ':') {
    428 					/*
    429 					 * If the field was `empty' (i.e.
    430 					 * contained only white space), back up
    431 					 * to the colon (eliminating the
    432 					 * field).
    433 					 */
    434 					if (cp != NULL)
    435 						rp = cp;
    436 					else
    437 						cp = rp;
    438 				} else if (c == '\\') {
    439 					slash = 1;
    440 				} else if (c != ' ' && c != '\t') {
    441 					/*
    442 					 * Forget where the colon was, as this
    443 					 * is not an empty field.
    444 					 */
    445 					cp = 0;
    446 				}
    447 				*rp++ = c;
    448 
    449 				/*
    450 				 * Enforce loop invariant: if no room
    451 				 * left in record buffer, try to get
    452 				 * some more.
    453 				 */
    454 				if (rp >= r_end) {
    455 					ptrdiff_t pos;
    456 					size_t newsize;
    457 
    458 					pos = rp - record;
    459 					newsize = r_end - record + BFRAG;
    460 					newrecord = realloc(record, newsize);
    461 					if (newrecord == NULL) {
    462 						free(record);
    463 						if (myfd)
    464 							(void)close(fd);
    465 						errno = ENOMEM;
    466 						return -2;
    467 					}
    468 					record = newrecord;
    469 					r_end = record + newsize;
    470 					rp = record + pos;
    471 				}
    472 			}
    473 			/* Eliminate any white space after the last colon. */
    474 			if (cp)
    475 				rp = cp + 1;
    476 			/* Loop invariant lets us do this. */
    477 			*rp++ = '\0';
    478 
    479 			/*
    480 			 * If encountered eof check next file.
    481 			 */
    482 			if (eof)
    483 				break;
    484 
    485 			/*
    486 			 * Toss blank lines and comments.
    487 			 */
    488 			if (*record == '\0' || *record == '#')
    489 				continue;
    490 
    491 			/*
    492 			 * See if this is the record we want ...
    493 			 */
    494 			if (cgetmatch(record, name) == 0)
    495 				if (nfield == NULL || !nfcmp(nfield, record)) {
    496 					foundit = 1;
    497 					break;	/* found it! */
    498 				}
    499 		}
    500 		}
    501 		if (foundit)
    502 			break;
    503 	}
    504 
    505 	if (!foundit)
    506 		return -1;
    507 
    508 	/*
    509 	 * Got the capability record, but now we have to expand all tc=name
    510 	 * references in it ...
    511 	 */
    512 tc_exp:
    513 	tc_not_resolved = 0;
    514 	if (expandtc) {
    515 		char *newicap, *s;
    516 		size_t ilen, newilen;
    517 		int iret;
    518 		ptrdiff_t diff, tclen;
    519 		char *icap, *scan, *tc, *tcstart, *tcend;
    520 
    521 		/*
    522 		 * Loop invariants:
    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.
    528 		 */
    529 		scan = record;
    530 		for (;;) {
    531 			if ((tc = cgetcap(scan, "tc", '=')) == NULL)
    532 				break;
    533 
    534 			/*
    535 			 * Find end of tc=name and stomp on the trailing `:'
    536 			 * (if present) so we can use it to call ourselves.
    537 			 */
    538 			s = tc;
    539 			for (;;)
    540 				if (*s == '\0')
    541 					break;
    542 				else
    543 					if (*s++ == ':') {
    544 						*(s - 1) = '\0';
    545 						break;
    546 					}
    547 			tcstart = tc - 3;
    548 			tclen = s - tcstart;
    549 			tcend = s;
    550 
    551 			iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
    552 				      NULL);
    553 			newicap = icap;		/* Put into a register. */
    554 			newilen = ilen;
    555 			if (iret != 0) {
    556 				/* an error */
    557 				if (iret < -1) {
    558 					if (myfd)
    559 						(void)close(fd);
    560 					free(record);
    561 					return iret;
    562 				}
    563 				if (iret == 1)
    564 					tc_not_resolved = 1;
    565 				/* couldn't resolve tc */
    566 				if (iret == -1) {
    567 					*(s - 1) = ':';
    568 					scan = s - 1;
    569 					tc_not_resolved = 1;
    570 					continue;
    571 
    572 				}
    573 			}
    574 			/* not interested in name field of tc'ed record */
    575 			s = newicap;
    576 			for (;;)
    577 				if (*s == '\0')
    578 					break;
    579 				else if (*s++ == ':')
    580 					break;
    581 			newilen -= s - newicap;
    582 			newicap = s;
    583 
    584 			/* make sure interpolated record is `:'-terminated */
    585 			s += newilen;
    586 			if (*(s - 1) != ':') {
    587 				*s = ':';	/* overwrite NUL with : */
    588 				newilen++;
    589 			}
    590 
    591 			/*
    592 			 * Make sure there's enough room to insert the
    593 			 * new record.
    594 			 */
    595 			diff = newilen - tclen;
    596 			if (diff >= r_end - rp) {
    597 				ptrdiff_t pos, tcpos, tcposend;
    598 				size_t newsize;
    599 
    600 				pos = rp - record;
    601 				newsize = r_end - record + diff + BFRAG;
    602 				tcpos = tcstart - record;
    603 				tcposend = tcend - record;
    604 				newrecord = realloc(record, newsize);
    605 				if (newrecord == NULL) {
    606 					free(record);
    607 					if (myfd)
    608 						(void)close(fd);
    609 					free(icap);
    610 					errno = ENOMEM;
    611 					return -2;
    612 				}
    613 				record = newrecord;
    614 				r_end = record + newsize;
    615 				rp = record + pos;
    616 				tcstart = record + tcpos;
    617 				tcend = record + tcposend;
    618 			}
    619 
    620 			/*
    621 			 * Insert tc'ed record into our record.
    622 			 */
    623 			s = tcstart + newilen;
    624 			memmove(s, tcend,  (size_t)(rp - tcend));
    625 			memmove(tcstart, newicap, newilen);
    626 			rp += diff;
    627 			free(icap);
    628 
    629 			/*
    630 			 * Start scan on `:' so next cgetcap works properly
    631 			 * (cgetcap always skips first field).
    632 			 */
    633 			scan = s - 1;
    634 		}
    635 
    636 	}
    637 	/*
    638 	 * Close file (if we opened it), give back any extra memory, and
    639 	 * return capability, length and success.
    640 	 */
    641 	if (myfd)
    642 		(void)close(fd);
    643 	*len = rp - record - 1;	/* don't count NUL */
    644 	if (r_end > rp) {
    645 		if ((newrecord =
    646 		     realloc(record, (size_t)(rp - record))) == NULL) {
    647 			free(record);
    648 			errno = ENOMEM;
    649 			return -2;
    650 		}
    651 		record = newrecord;
    652 	}
    653 
    654 	*cap = record;
    655 	if (tc_not_resolved)
    656 		return 1;
    657 	return 0;
    658 }
    659 
    660 #ifndef SMALL
    661 static int
    662 cdbget(DB *capdbp, char **bp, const char *name)
    663 {
    664 	DBT key;
    665 	DBT data;
    666 
    667 	_DIAGASSERT(capdbp != NULL);
    668 	_DIAGASSERT(bp != NULL);
    669 	_DIAGASSERT(name != NULL);
    670 
    671 	key.data = __UNCONST(name);
    672 	key.size = strlen(name);
    673 
    674 	for (;;) {
    675 		/* Get the reference. */
    676 		switch(capdbp->get(capdbp, &key, &data, 0)) {
    677 		case -1:
    678 			return -2;
    679 		case 1:
    680 			return -1;
    681 		}
    682 
    683 		/* If not an index to another record, leave. */
    684 		if (((char *)data.data)[0] != SHADOW)
    685 			break;
    686 
    687 		key.data = (char *)data.data + 1;
    688 		key.size = data.size - 1;
    689 	}
    690 
    691 	*bp = (char *)data.data + 1;
    692 	return ((char *)(data.data))[0] == TCERR ? 1 : 0;
    693 }
    694 #endif
    695 
    696 /*
    697  * Cgetmatch will return 0 if name is one of the names of the capability
    698  * record buf, -1 if not.
    699  */
    700 int
    701 cgetmatch(const char *buf, const char *name)
    702 {
    703 	const char *np, *bp;
    704 
    705 	_DIAGASSERT(buf != NULL);
    706 	_DIAGASSERT(name != NULL);
    707 
    708 	/*
    709 	 * Start search at beginning of record.
    710 	 */
    711 	bp = buf;
    712 	for (;;) {
    713 		/*
    714 		 * Try to match a record name.
    715 		 */
    716 		np = name;
    717 		for (;;)
    718 			if (*np == '\0') {
    719 				if (*bp == '|' || *bp == ':' || *bp == '\0')
    720 					return 0;
    721 				else
    722 					break;
    723 			} else if (*bp++ != *np++)
    724 				break;
    725 
    726 		/*
    727 		 * Match failed, skip to next name in record.
    728 		 */
    729 		if (bp > buf)
    730 			bp--;	/* a '|' or ':' may have stopped the match */
    731 		else
    732 			return -1;
    733 		for (;;)
    734 			if (*bp == '\0' || *bp == ':')
    735 				return -1;	/* match failed totally */
    736 			else if (*bp++ == '|')
    737 				break;		/* found next name */
    738 	}
    739 }
    740 
    741 int
    742 cgetfirst(char **buf, const char * const *db_array)
    743 {
    744 
    745 	_DIAGASSERT(buf != NULL);
    746 	_DIAGASSERT(db_array != NULL);
    747 
    748 	(void)cgetclose();
    749 	return cgetnext(buf, db_array);
    750 }
    751 
    752 static FILE *pfp;
    753 static int slash;
    754 static const char * const *dbp;
    755 
    756 int
    757 cgetclose(void)
    758 {
    759 	if (pfp != NULL) {
    760 		(void)fclose(pfp);
    761 		pfp = NULL;
    762 	}
    763 	dbp = NULL;
    764 	gottoprec = 0;
    765 	slash = 0;
    766 	return 0;
    767 }
    768 
    769 /*
    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.
    773  */
    774 /* coverity[+alloc : arg-*0] */
    775 int
    776 cgetnext(char **bp, const char * const *db_array)
    777 {
    778 	size_t len = 0;
    779 	int status, done;
    780 	char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
    781 	size_t dummy;
    782 
    783 	_DIAGASSERT(bp != NULL);
    784 	_DIAGASSERT(db_array != NULL);
    785 
    786 	if (dbp == NULL)
    787 		dbp = db_array;
    788 
    789 	if (pfp == NULL && (pfp = fopen(*dbp, "re")) == NULL) {
    790 		(void)cgetclose();
    791 		return -1;
    792 	}
    793 	for (;;) {
    794 		if (toprec != NULL && !gottoprec) {
    795 			gottoprec = 1;
    796 			line = toprec;
    797 		} else {
    798 			line = fgetln(pfp, &len);
    799 			if (line == NULL) {
    800 				if (pfp == NULL)
    801 					return -1;
    802 				if (ferror(pfp)) {
    803 					(void)cgetclose();
    804 					return -1;
    805 				} else {
    806 					(void)fclose(pfp);
    807 					pfp = NULL;
    808 					if (*++dbp == NULL) {
    809 						(void)cgetclose();
    810 						return 0;
    811 					} else if ((pfp =
    812 					    fopen(*dbp, "re")) == NULL) {
    813 						(void)cgetclose();
    814 						return -1;
    815 					} else
    816 						continue;
    817 				}
    818 			} else
    819 				line[len - 1] = '\0';
    820 			if (len == 1) {
    821 				slash = 0;
    822 				continue;
    823 			}
    824 			if (isspace((unsigned char)*line) ||
    825 			    *line == ':' || *line == '#' || slash) {
    826 				if (line[len - 2] == '\\')
    827 					slash = 1;
    828 				else
    829 					slash = 0;
    830 				continue;
    831 			}
    832 			if (line[len - 2] == '\\')
    833 				slash = 1;
    834 			else
    835 				slash = 0;
    836 		}
    837 
    838 
    839 		/*
    840 		 * Line points to a name line.
    841 		 */
    842 		if (len > sizeof(nbuf))
    843 			return -1;
    844 		done = 0;
    845 		np = nbuf;
    846 		for (;;) {
    847 			for (cp = line; *cp != '\0'; cp++) {
    848 				if (*cp == ':') {
    849 					*np++ = ':';
    850 					done = 1;
    851 					break;
    852 				}
    853 				if (*cp == '\\')
    854 					break;
    855 				*np++ = *cp;
    856 			}
    857 			if (done) {
    858 				*np = '\0';
    859 				break;
    860 			} else { /* name field extends beyond the line */
    861 				line = fgetln(pfp, &len);
    862 				if (line == NULL && pfp) {
    863 					if (ferror(pfp)) {
    864 						(void)cgetclose();
    865 						return -1;
    866 					}
    867 					(void)fclose(pfp);
    868 					pfp = NULL;
    869 					*np = '\0';
    870 					break;
    871 				} else
    872 					line[len - 1] = '\0';
    873 			}
    874 		}
    875 		if (len > sizeof(buf))
    876 			return -1;
    877 		rp = buf;
    878 		for (cp = nbuf; *cp != '\0'; cp++)
    879 			if (*cp == '|' || *cp == ':')
    880 				break;
    881 			else
    882 				*rp++ = *cp;
    883 
    884 		*rp = '\0';
    885 		/*
    886 		 * XXX
    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.
    892 		 */
    893 		status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
    894 		if (status == -2 || status == -3)
    895 			(void)cgetclose();
    896 
    897 		return status + 1;
    898 	}
    899 	/* NOTREACHED */
    900 }
    901 
    902 /*
    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).
    910  */
    911 int
    912 cgetstr(char *buf, const char *cap, char **str)
    913 {
    914 	u_int m_room;
    915 	const char *bp;
    916 	char *mp;
    917 	ptrdiff_t len;
    918 	char *mem, *newmem;
    919 
    920 	_DIAGASSERT(buf != NULL);
    921 	_DIAGASSERT(cap != NULL);
    922 	_DIAGASSERT(str != NULL);
    923 
    924 	/*
    925 	 * Find string capability cap
    926 	 */
    927 	bp = cgetcap(buf, cap, '=');
    928 	if (bp == 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 		if (*bp == '^') {
    950 			bp++;
    951 			if (*bp == ':' || *bp == '\0')
    952 				break;	/* drop unfinished escape */
    953 			*mp++ = *bp++ & 037;
    954 		} else if (*bp == '\\') {
    955 			bp++;
    956 			if (*bp == ':' || *bp == '\0')
    957 				break;	/* drop unfinished escape */
    958 			if ('0' <= *bp && *bp <= '7') {
    959 				int n, i;
    960 
    961 				n = 0;
    962 				i = 3;	/* maximum of three octal digits */
    963 				do {
    964 					n = n * 8 + (*bp++ - '0');
    965 				} while (--i && '0' <= *bp && *bp <= '7');
    966 				*mp++ = n;
    967 			}
    968 			else switch (*bp++) {
    969 				case 'b': case 'B':
    970 					*mp++ = '\b';
    971 					break;
    972 				case 't': case 'T':
    973 					*mp++ = '\t';
    974 					break;
    975 				case 'n': case 'N':
    976 					*mp++ = '\n';
    977 					break;
    978 				case 'f': case 'F':
    979 					*mp++ = '\f';
    980 					break;
    981 				case 'r': case 'R':
    982 					*mp++ = '\r';
    983 					break;
    984 				case 'e': case 'E':
    985 					*mp++ = ESC;
    986 					break;
    987 				case 'c': case 'C':
    988 					*mp++ = ':';
    989 					break;
    990 				default:
    991 					/*
    992 					 * Catches '\', '^', and
    993 					 *  everything else.
    994 					 */
    995 					*mp++ = *(bp-1);
    996 					break;
    997 			}
    998 		} else
    999 			*mp++ = *bp++;
   1000 		m_room--;
   1001 
   1002 		/*
   1003 		 * Enforce loop invariant: if no room left in current
   1004 		 * buffer, try to get some more.
   1005 		 */
   1006 		if (m_room == 0) {
   1007 			size_t size = mp - mem;
   1008 
   1009 			if ((newmem = realloc(mem, size + SFRAG)) == NULL) {
   1010 				free(mem);
   1011 				return -2;
   1012 			}
   1013 			mem = newmem;
   1014 			m_room = SFRAG;
   1015 			mp = mem + size;
   1016 		}
   1017 	}
   1018 	*mp++ = '\0';	/* loop invariant let's us do this */
   1019 	m_room--;
   1020 	len = mp - mem - 1;
   1021 
   1022 	/*
   1023 	 * Give back any extra memory and return value and success.
   1024 	 */
   1025 	if (m_room != 0) {
   1026 		if ((newmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
   1027 			free(mem);
   1028 			return -2;
   1029 		}
   1030 		mem = newmem;
   1031 	}
   1032 	*str = mem;
   1033 	_DIAGASSERT(__type_fit(int, len));
   1034 	return (int)len;
   1035 }
   1036 
   1037 /*
   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).
   1046  */
   1047 int
   1048 cgetustr(char *buf, const char *cap, char **str)
   1049 {
   1050 	u_int m_room;
   1051 	const char *bp;
   1052 	char *mp;
   1053 	size_t len;
   1054 	char *mem, *newmem;
   1055 
   1056 	_DIAGASSERT(buf != NULL);
   1057 	_DIAGASSERT(cap != NULL);
   1058 	_DIAGASSERT(str != NULL);
   1059 
   1060 	/*
   1061 	 * Find string capability cap
   1062 	 */
   1063 	if ((bp = cgetcap(buf, cap, '=')) == NULL)
   1064 		return -1;
   1065 
   1066 	/*
   1067 	 * Conversion / storage allocation loop ...  Allocate memory in
   1068 	 * chunks SFRAG in size.
   1069 	 */
   1070 	if ((mem = malloc(SFRAG)) == NULL) {
   1071 		errno = ENOMEM;
   1072 		return -2;	/* couldn't even allocate the first fragment */
   1073 	}
   1074 	m_room = SFRAG;
   1075 	mp = mem;
   1076 
   1077 	while (*bp != ':' && *bp != '\0') {
   1078 		/*
   1079 		 * Loop invariants:
   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.
   1083 		 */
   1084 		*mp++ = *bp++;
   1085 		m_room--;
   1086 
   1087 		/*
   1088 		 * Enforce loop invariant: if no room left in current
   1089 		 * buffer, try to get some more.
   1090 		 */
   1091 		if (m_room == 0) {
   1092 			size_t size = mp - mem;
   1093 
   1094 			if ((newmem = realloc(mem, size + SFRAG)) == NULL) {
   1095 				free(mem);
   1096 				return -2;
   1097 			}
   1098 			mem = newmem;
   1099 			m_room = SFRAG;
   1100 			mp = mem + size;
   1101 		}
   1102 	}
   1103 	*mp++ = '\0';	/* loop invariant let's us do this */
   1104 	m_room--;
   1105 	len = mp - mem - 1;
   1106 
   1107 	/*
   1108 	 * Give back any extra memory and return value and success.
   1109 	 */
   1110 	if (m_room != 0) {
   1111 		if ((newmem = realloc(mem, (size_t)(mp - mem))) == NULL) {
   1112 			free(mem);
   1113 			return -2;
   1114 		}
   1115 		mem = newmem;
   1116 	}
   1117 	*str = mem;
   1118 	_DIAGASSERT(__type_fit(int, len));
   1119 	return (int)len;
   1120 }
   1121 
   1122 /*
   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.
   1127  */
   1128 int
   1129 cgetnum(char *buf, const char *cap, long *num)
   1130 {
   1131 	long n;
   1132 	int base, digit;
   1133 	const char *bp;
   1134 
   1135 	_DIAGASSERT(buf != NULL);
   1136 	_DIAGASSERT(cap != NULL);
   1137 	_DIAGASSERT(num != NULL);
   1138 
   1139 	/*
   1140 	 * Find numeric capability cap
   1141 	 */
   1142 	bp = cgetcap(buf, cap, '#');
   1143 	if (bp == NULL)
   1144 		return -1;
   1145 
   1146 	/*
   1147 	 * Look at value and determine numeric base:
   1148 	 *	0x... or 0X...	hexadecimal,
   1149 	 * else	0...		octal,
   1150 	 * else			decimal.
   1151 	 */
   1152 	if (*bp == '0') {
   1153 		bp++;
   1154 		if (*bp == 'x' || *bp == 'X') {
   1155 			bp++;
   1156 			base = 16;
   1157 		} else
   1158 			base = 8;
   1159 	} else
   1160 		base = 10;
   1161 
   1162 	/*
   1163 	 * Conversion loop ...
   1164 	 */
   1165 	n = 0;
   1166 	for (;;) {
   1167 		if ('0' <= *bp && *bp <= '9')
   1168 			digit = *bp - '0';
   1169 		else if ('a' <= *bp && *bp <= 'f')
   1170 			digit = 10 + *bp - 'a';
   1171 		else if ('A' <= *bp && *bp <= 'F')
   1172 			digit = 10 + *bp - 'A';
   1173 		else
   1174 			break;
   1175 
   1176 		if (digit >= base)
   1177 			break;
   1178 
   1179 		n = n * base + digit;
   1180 		bp++;
   1181 	}
   1182 
   1183 	/*
   1184 	 * Return value and success.
   1185 	 */
   1186 	*num = n;
   1187 	return 0;
   1188 }
   1189 
   1190 
   1191 /*
   1192  * Compare name field of record.
   1193  */
   1194 static int
   1195 nfcmp(char *nf, char *rec)
   1196 {
   1197 	char *cp, tmp;
   1198 	int ret;
   1199 
   1200 	_DIAGASSERT(nf != NULL);
   1201 	_DIAGASSERT(rec != NULL);
   1202 
   1203 	for (cp = rec; *cp != ':'; cp++)
   1204 		continue;
   1205 
   1206 	tmp = *(cp + 1);
   1207 	*(cp + 1) = '\0';
   1208 	ret = strcmp(nf, rec);
   1209 	*(cp + 1) = tmp;
   1210 
   1211 	return ret;
   1212 }
   1213