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