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