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