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