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