xref: /freebsd/lib/libc/gen/getcap.c (revision 6e8394b8baa7d5d9153ab90de6824bcd19b3b4e1)
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 
41 #include <sys/types.h>
42 
43 #include <ctype.h>
44 #include <db.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <limits.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 
53 #define	BFRAG		1024
54 #define	BSIZE		1024
55 #define	ESC		('[' & 037)	/* ASCII ESC */
56 #define	MAX_RECURSION	32		/* maximum getent recursion */
57 #define	SFRAG		100		/* cgetstr mallocs in SFRAG chunks */
58 
59 #define RECOK	(char)0
60 #define TCERR	(char)1
61 #define	SHADOW	(char)2
62 
63 static size_t	 topreclen;	/* toprec length */
64 static char	*toprec;	/* Additional record specified by cgetset() */
65 static int	 gottoprec;	/* Flag indicating retrieval of toprecord */
66 
67 static int	cdbget __P((DB *, char **, char *));
68 static int 	getent __P((char **, u_int *, char **, int, char *, int, char *));
69 static int	nfcmp __P((char *, char *));
70 
71 /*
72  * Cgetset() allows the addition of a user specified buffer to be added
73  * to the database array, in effect "pushing" the buffer on top of the
74  * virtual database. 0 is returned on success, -1 on failure.
75  */
76 int
77 cgetset(ent)
78 	char *ent;
79 {
80 	if (ent == NULL) {
81 		if (toprec)
82 			free(toprec);
83                 toprec = NULL;
84                 topreclen = 0;
85                 return (0);
86         }
87         topreclen = strlen(ent);
88         if ((toprec = malloc (topreclen + 1)) == NULL) {
89 		errno = ENOMEM;
90                 return (-1);
91 	}
92 	gottoprec = 0;
93         (void)strcpy(toprec, ent);
94         return (0);
95 }
96 
97 /*
98  * Cgetcap searches the capability record buf for the capability cap with
99  * type `type'.  A pointer to the value of cap is returned on success, NULL
100  * if the requested capability couldn't be found.
101  *
102  * Specifying a type of ':' means that nothing should follow cap (:cap:).
103  * In this case a pointer to the terminating ':' or NUL will be returned if
104  * cap is found.
105  *
106  * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator)
107  * return NULL.
108  */
109 char *
110 cgetcap(buf, cap, type)
111 	char *buf, *cap;
112 	int type;
113 {
114 	register char *bp, *cp;
115 
116 	bp = buf;
117 	for (;;) {
118 		/*
119 		 * Skip past the current capability field - it's either the
120 		 * name field if this is the first time through the loop, or
121 		 * the remainder of a field whose name failed to match cap.
122 		 */
123 		for (;;)
124 			if (*bp == '\0')
125 				return (NULL);
126 			else
127 				if (*bp++ == ':')
128 					break;
129 
130 		/*
131 		 * Try to match (cap, type) in buf.
132 		 */
133 		for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++)
134 			continue;
135 		if (*cp != '\0')
136 			continue;
137 		if (*bp == '@')
138 			return (NULL);
139 		if (type == ':') {
140 			if (*bp != '\0' && *bp != ':')
141 				continue;
142 			return(bp);
143 		}
144 		if (*bp != type)
145 			continue;
146 		bp++;
147 		return (*bp == '@' ? NULL : bp);
148 	}
149 	/* NOTREACHED */
150 }
151 
152 /*
153  * Cgetent extracts the capability record name from the NULL terminated file
154  * array db_array and returns a pointer to a malloc'd copy of it in buf.
155  * Buf must be retained through all subsequent calls to cgetcap, cgetnum,
156  * cgetflag, and cgetstr, but may then be free'd.  0 is returned on success,
157  * -1 if the requested record couldn't be found, -2 if a system error was
158  * encountered (couldn't open/read a file, etc.), and -3 if a potential
159  * reference loop is detected.
160  */
161 int
162 cgetent(buf, db_array, name)
163 	char **buf, **db_array, *name;
164 {
165 	u_int dummy;
166 
167 	return (getent(buf, &dummy, db_array, -1, name, 0, NULL));
168 }
169 
170 /*
171  * Getent implements the functions of cgetent.  If fd is non-negative,
172  * *db_array has already been opened and fd is the open file descriptor.  We
173  * do this to save time and avoid using up file descriptors for tc=
174  * recursions.
175  *
176  * Getent returns the same success/failure codes as cgetent.  On success, a
177  * pointer to a malloc'ed capability record with all tc= capabilities fully
178  * expanded and its length (not including trailing ASCII NUL) are left in
179  * *cap and *len.
180  *
181  * Basic algorithm:
182  *	+ Allocate memory incrementally as needed in chunks of size BFRAG
183  *	  for capability buffer.
184  *	+ Recurse for each tc=name and interpolate result.  Stop when all
185  *	  names interpolated, a name can't be found, or depth exceeds
186  *	  MAX_RECURSION.
187  */
188 static int
189 getent(cap, len, db_array, fd, name, depth, nfield)
190 	char **cap, **db_array, *name, *nfield;
191 	u_int *len;
192 	int fd, depth;
193 {
194 	DB *capdbp;
195 	register 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 		register char *b_end, *bp;
281 		register 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 		return (-1);
385 
386 	/*
387 	 * Got the capability record, but now we have to expand all tc=name
388 	 * references in it ...
389 	 */
390 tc_exp:	{
391 		register char *newicap, *s;
392 		register int newilen;
393 		u_int ilen;
394 		int diff, iret, tclen;
395 		char *icap, *scan, *tc, *tcstart, *tcend;
396 
397 		/*
398 		 * Loop invariants:
399 		 *	There is room for one more character in record.
400 		 *	R_end points just past end of record.
401 		 *	Rp points just past last character in record.
402 		 *	Scan points at remainder of record that needs to be
403 		 *	scanned for tc=name constructs.
404 		 */
405 		scan = record;
406 		tc_not_resolved = 0;
407 		for (;;) {
408 			if ((tc = cgetcap(scan, "tc", '=')) == NULL)
409 				break;
410 
411 			/*
412 			 * Find end of tc=name and stomp on the trailing `:'
413 			 * (if present) so we can use it to call ourselves.
414 			 */
415 			s = tc;
416 			for (;;)
417 				if (*s == '\0')
418 					break;
419 				else
420 					if (*s++ == ':') {
421 						*(s - 1) = '\0';
422 						break;
423 					}
424 			tcstart = tc - 3;
425 			tclen = s - tcstart;
426 			tcend = s;
427 
428 			iret = getent(&icap, &ilen, db_p, fd, tc, depth+1,
429 				      NULL);
430 			newicap = icap;		/* Put into a register. */
431 			newilen = ilen;
432 			if (iret != 0) {
433 				/* an error */
434 				if (iret < -1) {
435 					if (myfd)
436 						(void)close(fd);
437 					free(record);
438 					return (iret);
439 				}
440 				if (iret == 1)
441 					tc_not_resolved = 1;
442 				/* couldn't resolve tc */
443 				if (iret == -1) {
444 					*(s - 1) = ':';
445 					scan = s - 1;
446 					tc_not_resolved = 1;
447 					continue;
448 
449 				}
450 			}
451 			/* not interested in name field of tc'ed record */
452 			s = newicap;
453 			for (;;)
454 				if (*s == '\0')
455 					break;
456 				else
457 					if (*s++ == ':')
458 						break;
459 			newilen -= s - newicap;
460 			newicap = s;
461 
462 			/* make sure interpolated record is `:'-terminated */
463 			s += newilen;
464 			if (*(s-1) != ':') {
465 				*s = ':';	/* overwrite NUL with : */
466 				newilen++;
467 			}
468 
469 			/*
470 			 * Make sure there's enough room to insert the
471 			 * new record.
472 			 */
473 			diff = newilen - tclen;
474 			if (diff >= r_end - rp) {
475 				u_int pos, tcpos, tcposend;
476 				size_t newsize;
477 
478 				pos = rp - record;
479 				newsize = r_end - record + diff + BFRAG;
480 				tcpos = tcstart - record;
481 				tcposend = tcend - record;
482 				record = reallocf(record, newsize);
483 				if (record == NULL) {
484 					errno = ENOMEM;
485 					if (myfd)
486 						(void)close(fd);
487 					free(icap);
488 					return (-2);
489 				}
490 				r_end = record + newsize;
491 				rp = record + pos;
492 				tcstart = record + tcpos;
493 				tcend = record + tcposend;
494 			}
495 
496 			/*
497 			 * Insert tc'ed record into our record.
498 			 */
499 			s = tcstart + newilen;
500 			bcopy(tcend, s, rp - tcend);
501 			bcopy(newicap, tcstart, newilen);
502 			rp += diff;
503 			free(icap);
504 
505 			/*
506 			 * Start scan on `:' so next cgetcap works properly
507 			 * (cgetcap always skips first field).
508 			 */
509 			scan = s-1;
510 		}
511 
512 	}
513 	/*
514 	 * Close file (if we opened it), give back any extra memory, and
515 	 * return capability, length and success.
516 	 */
517 	if (myfd)
518 		(void)close(fd);
519 	*len = rp - record - 1;	/* don't count NUL */
520 	if (r_end > rp)
521 		if ((record =
522 		     reallocf(record, (size_t)(rp - record))) == NULL) {
523 			errno = ENOMEM;
524 			return (-2);
525 		}
526 
527 	*cap = record;
528 	if (tc_not_resolved)
529 		return (1);
530 	return (0);
531 }
532 
533 static int
534 cdbget(capdbp, bp, name)
535 	DB *capdbp;
536 	char **bp, *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(buf, name)
570 	char *buf, *name;
571 {
572 	register char *np, *bp;
573 
574 	/*
575 	 * Start search at beginning of record.
576 	 */
577 	bp = buf;
578 	for (;;) {
579 		/*
580 		 * Try to match a record name.
581 		 */
582 		np = name;
583 		for (;;)
584 			if (*np == '\0')
585 				if (*bp == '|' || *bp == ':' || *bp == '\0')
586 					return (0);
587 				else
588 					break;
589 			else
590 				if (*bp++ != *np++)
591 					break;
592 
593 		/*
594 		 * Match failed, skip to next name in record.
595 		 */
596 		bp--;	/* a '|' or ':' may have stopped the match */
597 		for (;;)
598 			if (*bp == '\0' || *bp == ':')
599 				return (-1);	/* match failed totally */
600 			else
601 				if (*bp++ == '|')
602 					break;	/* found next name */
603 	}
604 }
605 
606 
607 
608 
609 
610 int
611 cgetfirst(buf, db_array)
612 	char **buf, **db_array;
613 {
614 	(void)cgetclose();
615 	return (cgetnext(buf, db_array));
616 }
617 
618 static FILE *pfp;
619 static int slash;
620 static char **dbp;
621 
622 int
623 cgetclose()
624 {
625 	if (pfp != NULL) {
626 		(void)fclose(pfp);
627 		pfp = NULL;
628 	}
629 	dbp = NULL;
630 	gottoprec = 0;
631 	slash = 0;
632 	return(0);
633 }
634 
635 /*
636  * Cgetnext() gets either the first or next entry in the logical database
637  * specified by db_array.  It returns 0 upon completion of the database, 1
638  * upon returning an entry with more remaining, and -1 if an error occurs.
639  */
640 int
641 cgetnext(bp, db_array)
642         register char **bp;
643 	char **db_array;
644 {
645 	size_t len;
646 	int status, i, done;
647 	char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE];
648 	u_int dummy;
649 
650 	if (dbp == NULL)
651 		dbp = db_array;
652 
653 	if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) {
654 		(void)cgetclose();
655 		return (-1);
656 	}
657 	for(;;) {
658 		if (toprec && !gottoprec) {
659 			gottoprec = 1;
660 			line = toprec;
661 		} else {
662 			line = fgetln(pfp, &len);
663 			if (line == NULL && pfp) {
664 				(void)fclose(pfp);
665 				if (ferror(pfp)) {
666 					(void)cgetclose();
667 					return (-1);
668 				} else {
669 					if (*++dbp == NULL) {
670 						(void)cgetclose();
671 						return (0);
672 					} else if ((pfp =
673 					    fopen(*dbp, "r")) == NULL) {
674 						(void)cgetclose();
675 						return (-1);
676 					} else
677 						continue;
678 				}
679 			} else
680 				line[len - 1] = '\0';
681 			if (len == 1) {
682 				slash = 0;
683 				continue;
684 			}
685 			if (isspace(*line) ||
686 			    *line == ':' || *line == '#' || slash) {
687 				if (line[len - 2] == '\\')
688 					slash = 1;
689 				else
690 					slash = 0;
691 				continue;
692 			}
693 			if (line[len - 2] == '\\')
694 				slash = 1;
695 			else
696 				slash = 0;
697 		}
698 
699 
700 		/*
701 		 * Line points to a name line.
702 		 */
703 		i = 0;
704 		done = 0;
705 		np = nbuf;
706 		for (;;) {
707 			for (cp = line; *cp != '\0'; cp++) {
708 				if (*cp == ':') {
709 					*np++ = ':';
710 					done = 1;
711 					break;
712 				}
713 				if (*cp == '\\')
714 					break;
715 				*np++ = *cp;
716 			}
717 			if (done) {
718 				*np = '\0';
719 				break;
720 			} else { /* name field extends beyond the line */
721 				line = fgetln(pfp, &len);
722 				if (line == NULL && pfp) {
723 					(void)fclose(pfp);
724 					if (ferror(pfp)) {
725 						(void)cgetclose();
726 						return (-1);
727 					}
728 				} else
729 					line[len - 1] = '\0';
730 			}
731 		}
732 		rp = buf;
733 		for(cp = nbuf; *cp != '\0'; cp++)
734 			if (*cp == '|' || *cp == ':')
735 				break;
736 			else
737 				*rp++ = *cp;
738 
739 		*rp = '\0';
740 		/*
741 		 * XXX
742 		 * Last argument of getent here should be nbuf if we want true
743 		 * sequential access in the case of duplicates.
744 		 * With NULL, getent will return the first entry found
745 		 * rather than the duplicate entry record.  This is a
746 		 * matter of semantics that should be resolved.
747 		 */
748 		status = getent(bp, &dummy, db_array, -1, buf, 0, NULL);
749 		if (status == -2 || status == -3)
750 			(void)cgetclose();
751 
752 		return (status + 1);
753 	}
754 	/* NOTREACHED */
755 }
756 
757 /*
758  * Cgetstr retrieves the value of the string capability cap from the
759  * capability record pointed to by buf.  A pointer to a decoded, NUL
760  * terminated, malloc'd copy of the string is returned in the char *
761  * pointed to by str.  The length of the string not including the trailing
762  * NUL is returned on success, -1 if the requested string capability
763  * couldn't be found, -2 if a system error was encountered (storage
764  * allocation failure).
765  */
766 int
767 cgetstr(buf, cap, str)
768 	char *buf, *cap;
769 	char **str;
770 {
771 	register u_int m_room;
772 	register char *bp, *mp;
773 	int len;
774 	char *mem;
775 
776 	/*
777 	 * Find string capability cap
778 	 */
779 	bp = cgetcap(buf, cap, '=');
780 	if (bp == NULL)
781 		return (-1);
782 
783 	/*
784 	 * Conversion / storage allocation loop ...  Allocate memory in
785 	 * chunks SFRAG in size.
786 	 */
787 	if ((mem = malloc(SFRAG)) == NULL) {
788 		errno = ENOMEM;
789 		return (-2);	/* couldn't even allocate the first fragment */
790 	}
791 	m_room = SFRAG;
792 	mp = mem;
793 
794 	while (*bp != ':' && *bp != '\0') {
795 		/*
796 		 * Loop invariants:
797 		 *	There is always room for one more character in mem.
798 		 *	Mp always points just past last character in mem.
799 		 *	Bp always points at next character in buf.
800 		 */
801 		if (*bp == '^') {
802 			bp++;
803 			if (*bp == ':' || *bp == '\0')
804 				break;	/* drop unfinished escape */
805 			if (*bp == '?') {
806 				*mp++ = '\177';
807 				bp++;
808 			} else
809 				*mp++ = *bp++ & 037;
810 		} else if (*bp == '\\') {
811 			bp++;
812 			if (*bp == ':' || *bp == '\0')
813 				break;	/* drop unfinished escape */
814 			if ('0' <= *bp && *bp <= '7') {
815 				register int n, i;
816 
817 				n = 0;
818 				i = 3;	/* maximum of three octal digits */
819 				do {
820 					n = n * 8 + (*bp++ - '0');
821 				} while (--i && '0' <= *bp && *bp <= '7');
822 				*mp++ = n;
823 			}
824 			else switch (*bp++) {
825 				case 'b': case 'B':
826 					*mp++ = '\b';
827 					break;
828 				case 't': case 'T':
829 					*mp++ = '\t';
830 					break;
831 				case 'n': case 'N':
832 					*mp++ = '\n';
833 					break;
834 				case 'f': case 'F':
835 					*mp++ = '\f';
836 					break;
837 				case 'r': case 'R':
838 					*mp++ = '\r';
839 					break;
840 				case 'e': case 'E':
841 					*mp++ = ESC;
842 					break;
843 				case 'c': case 'C':
844 					*mp++ = ':';
845 					break;
846 				default:
847 					/*
848 					 * Catches '\', '^', and
849 					 *  everything else.
850 					 */
851 					*mp++ = *(bp-1);
852 					break;
853 			}
854 		} else
855 			*mp++ = *bp++;
856 		m_room--;
857 
858 		/*
859 		 * Enforce loop invariant: if no room left in current
860 		 * buffer, try to get some more.
861 		 */
862 		if (m_room == 0) {
863 			size_t size = mp - mem;
864 
865 			if ((mem = reallocf(mem, size + SFRAG)) == NULL)
866 				return (-2);
867 			m_room = SFRAG;
868 			mp = mem + size;
869 		}
870 	}
871 	*mp++ = '\0';	/* loop invariant let's us do this */
872 	m_room--;
873 	len = mp - mem - 1;
874 
875 	/*
876 	 * Give back any extra memory and return value and success.
877 	 */
878 	if (m_room != 0)
879 		if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
880 			return (-2);
881 	*str = mem;
882 	return (len);
883 }
884 
885 /*
886  * Cgetustr retrieves the value of the string capability cap from the
887  * capability record pointed to by buf.  The difference between cgetustr()
888  * and cgetstr() is that cgetustr does not decode escapes but rather treats
889  * all characters literally.  A pointer to a  NUL terminated malloc'd
890  * copy of the string is returned in the char pointed to by str.  The
891  * length of the string not including the trailing NUL is returned on success,
892  * -1 if the requested string capability couldn't be found, -2 if a system
893  * error was encountered (storage allocation failure).
894  */
895 int
896 cgetustr(buf, cap, str)
897 	char *buf, *cap, **str;
898 {
899 	register u_int m_room;
900 	register char *bp, *mp;
901 	int len;
902 	char *mem;
903 
904 	/*
905 	 * Find string capability cap
906 	 */
907 	if ((bp = cgetcap(buf, cap, '=')) == NULL)
908 		return (-1);
909 
910 	/*
911 	 * Conversion / storage allocation loop ...  Allocate memory in
912 	 * chunks SFRAG in size.
913 	 */
914 	if ((mem = malloc(SFRAG)) == NULL) {
915 		errno = ENOMEM;
916 		return (-2);	/* couldn't even allocate the first fragment */
917 	}
918 	m_room = SFRAG;
919 	mp = mem;
920 
921 	while (*bp != ':' && *bp != '\0') {
922 		/*
923 		 * Loop invariants:
924 		 *	There is always room for one more character in mem.
925 		 *	Mp always points just past last character in mem.
926 		 *	Bp always points at next character in buf.
927 		 */
928 		*mp++ = *bp++;
929 		m_room--;
930 
931 		/*
932 		 * Enforce loop invariant: if no room left in current
933 		 * buffer, try to get some more.
934 		 */
935 		if (m_room == 0) {
936 			size_t size = mp - mem;
937 
938 			if ((mem = reallocf(mem, size + SFRAG)) == NULL)
939 				return (-2);
940 			m_room = SFRAG;
941 			mp = mem + size;
942 		}
943 	}
944 	*mp++ = '\0';	/* loop invariant let's us do this */
945 	m_room--;
946 	len = mp - mem - 1;
947 
948 	/*
949 	 * Give back any extra memory and return value and success.
950 	 */
951 	if (m_room != 0)
952 		if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL)
953 			return (-2);
954 	*str = mem;
955 	return (len);
956 }
957 
958 /*
959  * Cgetnum retrieves the value of the numeric capability cap from the
960  * capability record pointed to by buf.  The numeric value is returned in
961  * the long pointed to by num.  0 is returned on success, -1 if the requested
962  * numeric capability couldn't be found.
963  */
964 int
965 cgetnum(buf, cap, num)
966 	char *buf, *cap;
967 	long *num;
968 {
969 	register long n;
970 	register int base, digit;
971 	register char *bp;
972 
973 	/*
974 	 * Find numeric capability cap
975 	 */
976 	bp = cgetcap(buf, cap, '#');
977 	if (bp == NULL)
978 		return (-1);
979 
980 	/*
981 	 * Look at value and determine numeric base:
982 	 *	0x... or 0X...	hexadecimal,
983 	 * else	0...		octal,
984 	 * else			decimal.
985 	 */
986 	if (*bp == '0') {
987 		bp++;
988 		if (*bp == 'x' || *bp == 'X') {
989 			bp++;
990 			base = 16;
991 		} else
992 			base = 8;
993 	} else
994 		base = 10;
995 
996 	/*
997 	 * Conversion loop ...
998 	 */
999 	n = 0;
1000 	for (;;) {
1001 		if ('0' <= *bp && *bp <= '9')
1002 			digit = *bp - '0';
1003 		else if ('a' <= *bp && *bp <= 'f')
1004 			digit = 10 + *bp - 'a';
1005 		else if ('A' <= *bp && *bp <= 'F')
1006 			digit = 10 + *bp - 'A';
1007 		else
1008 			break;
1009 
1010 		if (digit >= base)
1011 			break;
1012 
1013 		n = n * base + digit;
1014 		bp++;
1015 	}
1016 
1017 	/*
1018 	 * Return value and success.
1019 	 */
1020 	*num = n;
1021 	return (0);
1022 }
1023 
1024 
1025 /*
1026  * Compare name field of record.
1027  */
1028 static int
1029 nfcmp(nf, rec)
1030 	char *nf, *rec;
1031 {
1032 	char *cp, tmp;
1033 	int ret;
1034 
1035 	for (cp = rec; *cp != ':'; cp++)
1036 		;
1037 
1038 	tmp = *(cp + 1);
1039 	*(cp + 1) = '\0';
1040 	ret = strcmp(nf, rec);
1041 	*(cp + 1) = tmp;
1042 
1043 	return (ret);
1044 }
1045