xref: /netbsd-src/usr.sbin/mtree/spec.c (revision 975a152cfcdb39ae6e496af647af0c7275ca0b61)
1 /*	$NetBSD: spec.c,v 1.86 2013/09/09 23:27:43 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 2001-2004 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Luke Mewburn of Wasabi Systems.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
49  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
51  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
52  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
53  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
54  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
55  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
56  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
57  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
58  * POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 #if HAVE_NBTOOL_CONFIG_H
62 #include "nbtool_config.h"
63 #endif
64 
65 #include <sys/cdefs.h>
66 #if defined(__RCSID) && !defined(lint)
67 #if 0
68 static char sccsid[] = "@(#)spec.c	8.2 (Berkeley) 4/28/95";
69 #else
70 __RCSID("$NetBSD: spec.c,v 1.86 2013/09/09 23:27:43 christos Exp $");
71 #endif
72 #endif /* not lint */
73 
74 #include <sys/param.h>
75 #include <sys/stat.h>
76 
77 #include <assert.h>
78 #include <ctype.h>
79 #include <errno.h>
80 #include <grp.h>
81 #include <pwd.h>
82 #include <stdarg.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <unistd.h>
87 #include <vis.h>
88 #include <util.h>
89 
90 #include "extern.h"
91 #include "pack_dev.h"
92 
93 size_t	mtree_lineno;			/* Current spec line number */
94 int	mtree_Mflag;			/* Merge duplicate entries */
95 int	mtree_Wflag;			/* Don't "whack" permissions */
96 int	mtree_Sflag;			/* Sort entries */
97 
98 static	dev_t	parsedev(char *);
99 static	void	replacenode(NODE *, NODE *);
100 static	void	set(char *, NODE *);
101 static	void	unset(char *, NODE *);
102 static	void	addchild(NODE *, NODE *);
103 static	int	nodecmp(const NODE *, const NODE *);
104 static	int	appendfield(int, const char *, ...) __printflike(2, 3);
105 
106 #define REPLACEPTR(x,v)	do { if ((x)) free((x)); (x) = (v); } while (0)
107 
108 NODE *
109 spec(FILE *fp)
110 {
111 	NODE *centry, *last, *pathparent, *cur;
112 	char *p, *e, *next;
113 	NODE ginfo, *root;
114 	char *buf, *tname, *ntname;
115 	size_t tnamelen, plen;
116 
117 	root = NULL;
118 	centry = last = NULL;
119 	tname = NULL;
120 	tnamelen = 0;
121 	memset(&ginfo, 0, sizeof(ginfo));
122 	for (mtree_lineno = 0;
123 	    (buf = fparseln(fp, NULL, &mtree_lineno, NULL,
124 		FPARSELN_UNESCCOMM));
125 	    free(buf)) {
126 		/* Skip leading whitespace. */
127 		for (p = buf; *p && isspace((unsigned char)*p); ++p)
128 			continue;
129 
130 		/* If nothing but whitespace, continue. */
131 		if (!*p)
132 			continue;
133 
134 #ifdef DEBUG
135 		fprintf(stderr, "line %lu: {%s}\n",
136 		    (u_long)mtree_lineno, p);
137 #endif
138 		/* Grab file name, "$", "set", or "unset". */
139 		next = buf;
140 		while ((p = strsep(&next, " \t")) != NULL && *p == '\0')
141 			continue;
142 		if (p == NULL)
143 			mtree_err("missing field");
144 
145 		if (p[0] == '/') {
146 			if (strcmp(p + 1, "set") == 0)
147 				set(next, &ginfo);
148 			else if (strcmp(p + 1, "unset") == 0)
149 				unset(next, &ginfo);
150 			else
151 				mtree_err("invalid specification `%s'", p);
152 			continue;
153 		}
154 
155 		if (strcmp(p, "..") == 0) {
156 			/* Don't go up, if haven't gone down. */
157 			if (root == NULL)
158 				goto noparent;
159 			if (last->type != F_DIR || last->flags & F_DONE) {
160 				if (last == root)
161 					goto noparent;
162 				last = last->parent;
163 			}
164 			last->flags |= F_DONE;
165 			continue;
166 
167 noparent:		mtree_err("no parent node");
168 		}
169 
170 		plen = strlen(p) + 1;
171 		if (plen > tnamelen) {
172 			if ((ntname = realloc(tname, plen)) == NULL)
173 				mtree_err("realloc: %s", strerror(errno));
174 			tname = ntname;
175 			tnamelen = plen;
176 		}
177 		if (strunvis(tname, p) == -1)
178 			mtree_err("strunvis failed on `%s'", p);
179 		p = tname;
180 
181 		pathparent = NULL;
182 		if (strchr(p, '/') != NULL) {
183 			cur = root;
184 			for (; (e = strchr(p, '/')) != NULL; p = e+1) {
185 				if (p == e)
186 					continue;	/* handle // */
187 				*e = '\0';
188 				if (strcmp(p, ".") != 0) {
189 					while (cur &&
190 					    strcmp(cur->name, p) != 0) {
191 						cur = cur->next;
192 					}
193 				}
194 				if (cur == NULL || cur->type != F_DIR) {
195 					mtree_err("%s: %s", tname,
196 					"missing directory in specification");
197 				}
198 				*e = '/';
199 				pathparent = cur;
200 				cur = cur->child;
201 			}
202 			if (*p == '\0')
203 				mtree_err("%s: empty leaf element", tname);
204 		}
205 
206 		if ((centry = calloc(1, sizeof(NODE) + strlen(p))) == NULL)
207 			mtree_err("%s", strerror(errno));
208 		*centry = ginfo;
209 		centry->lineno = mtree_lineno;
210 		strcpy(centry->name, p);
211 #define	MAGIC	"?*["
212 		if (strpbrk(p, MAGIC))
213 			centry->flags |= F_MAGIC;
214 		set(next, centry);
215 
216 		if (root == NULL) {
217 				/*
218 				 * empty tree
219 				 */
220 			if (strcmp(centry->name, ".") != 0 ||
221 			    centry->type != F_DIR)
222 				mtree_err(
223 				    "root node must be the directory `.'");
224 			last = root = centry;
225 			root->parent = root;
226 		} else if (pathparent != NULL) {
227 				/*
228 				 * full path entry; add or replace
229 				 */
230 			centry->parent = pathparent;
231 			addchild(pathparent, centry);
232 			last = centry;
233 		} else if (strcmp(centry->name, ".") == 0) {
234 				/*
235 				 * duplicate "." entry; always replace
236 				 */
237 			replacenode(root, centry);
238 		} else if (last->type == F_DIR && !(last->flags & F_DONE)) {
239 				/*
240 				 * new relative child in current dir;
241 				 * add or replace
242 				 */
243 			centry->parent = last;
244 			addchild(last, centry);
245 			last = centry;
246 		} else {
247 				/*
248 				 * new relative child in parent dir
249 				 * (after encountering ".." entry);
250 				 * add or replace
251 				 */
252 			centry->parent = last->parent;
253 			addchild(last->parent, centry);
254 			last = centry;
255 		}
256 	}
257 	return (root);
258 }
259 
260 void
261 free_nodes(NODE *root)
262 {
263 	NODE	*cur, *next;
264 
265 	if (root == NULL)
266 		return;
267 
268 	next = NULL;
269 	for (cur = root; cur != NULL; cur = next) {
270 		next = cur->next;
271 		free_nodes(cur->child);
272 		REPLACEPTR(cur->slink, NULL);
273 		REPLACEPTR(cur->md5digest, NULL);
274 		REPLACEPTR(cur->rmd160digest, NULL);
275 		REPLACEPTR(cur->sha1digest, NULL);
276 		REPLACEPTR(cur->sha256digest, NULL);
277 		REPLACEPTR(cur->sha384digest, NULL);
278 		REPLACEPTR(cur->sha512digest, NULL);
279 		REPLACEPTR(cur->tags, NULL);
280 		REPLACEPTR(cur, NULL);
281 	}
282 }
283 
284 /*
285  * appendfield --
286  *	Like printf(), but output a space either before or after
287  *	the regular output, according to the pathlast flag.
288  */
289 static int
290 appendfield(int pathlast, const char *fmt, ...)
291 {
292 	va_list ap;
293 	int result;
294 
295 	va_start(ap, fmt);
296 	if (!pathlast)
297 		printf(" ");
298 	result = vprintf(fmt, ap);
299 	if (pathlast)
300 		printf(" ");
301 	va_end(ap);
302 	return result;
303 }
304 
305 /*
306  * dump_nodes --
307  *	dump the NODEs from `cur', based in the directory `dir'.
308  *	if pathlast is none zero, print the path last, otherwise print
309  *	it first.
310  */
311 void
312 dump_nodes(const char *dir, NODE *root, int pathlast)
313 {
314 	NODE	*cur;
315 	char	path[MAXPATHLEN];
316 	const char *name;
317 	char	*str;
318 	char	*p, *q;
319 
320 	for (cur = root; cur != NULL; cur = cur->next) {
321 		if (cur->type != F_DIR && !matchtags(cur))
322 			continue;
323 
324 		if (snprintf(path, sizeof(path), "%s%s%s",
325 		    dir, *dir ? "/" : "", cur->name)
326 		    >= (int)sizeof(path))
327 			mtree_err("Pathname too long.");
328 
329 		if (!pathlast)
330 			printf("%s", vispath(path));
331 
332 #define MATCHFLAG(f)	((keys & (f)) && (cur->flags & (f)))
333 		if (MATCHFLAG(F_TYPE))
334 			appendfield(pathlast, "type=%s", nodetype(cur->type));
335 		if (MATCHFLAG(F_UID | F_UNAME)) {
336 			if (keys & F_UNAME &&
337 			    (name = user_from_uid(cur->st_uid, 1)) != NULL)
338 				appendfield(pathlast, "uname=%s", name);
339 			else
340 				appendfield(pathlast, "uid=%u", cur->st_uid);
341 		}
342 		if (MATCHFLAG(F_GID | F_GNAME)) {
343 			if (keys & F_GNAME &&
344 			    (name = group_from_gid(cur->st_gid, 1)) != NULL)
345 				appendfield(pathlast, "gname=%s", name);
346 			else
347 				appendfield(pathlast, "gid=%u", cur->st_gid);
348 		}
349 		if (MATCHFLAG(F_MODE))
350 			appendfield(pathlast, "mode=%#o", cur->st_mode);
351 		if (MATCHFLAG(F_DEV) &&
352 		    (cur->type == F_BLOCK || cur->type == F_CHAR))
353 			appendfield(pathlast, "device=%#jx",
354 			    (uintmax_t)cur->st_rdev);
355 		if (MATCHFLAG(F_NLINK))
356 			appendfield(pathlast, "nlink=%d", cur->st_nlink);
357 		if (MATCHFLAG(F_SLINK))
358 			appendfield(pathlast, "link=%s", vispath(cur->slink));
359 		if (MATCHFLAG(F_SIZE))
360 			appendfield(pathlast, "size=%ju",
361 			    (uintmax_t)cur->st_size);
362 		if (MATCHFLAG(F_TIME))
363 			appendfield(pathlast, "time=%jd.%09ld",
364 			    (intmax_t)cur->st_mtimespec.tv_sec,
365 			    cur->st_mtimespec.tv_nsec);
366 		if (MATCHFLAG(F_CKSUM))
367 			appendfield(pathlast, "cksum=%lu", cur->cksum);
368 		if (MATCHFLAG(F_MD5))
369 			appendfield(pathlast, "%s=%s", MD5KEY, cur->md5digest);
370 		if (MATCHFLAG(F_RMD160))
371 			appendfield(pathlast, "%s=%s", RMD160KEY,
372 			    cur->rmd160digest);
373 		if (MATCHFLAG(F_SHA1))
374 			appendfield(pathlast, "%s=%s", SHA1KEY,
375 			    cur->sha1digest);
376 		if (MATCHFLAG(F_SHA256))
377 			appendfield(pathlast, "%s=%s", SHA256KEY,
378 			    cur->sha256digest);
379 		if (MATCHFLAG(F_SHA384))
380 			appendfield(pathlast, "%s=%s", SHA384KEY,
381 			    cur->sha384digest);
382 		if (MATCHFLAG(F_SHA512))
383 			appendfield(pathlast, "%s=%s", SHA512KEY,
384 			    cur->sha512digest);
385 		if (MATCHFLAG(F_FLAGS)) {
386 			str = flags_to_string(cur->st_flags, "none");
387 			appendfield(pathlast, "flags=%s", str);
388 			free(str);
389 		}
390 		if (MATCHFLAG(F_IGN))
391 			appendfield(pathlast, "ignore");
392 		if (MATCHFLAG(F_OPT))
393 			appendfield(pathlast, "optional");
394 		if (MATCHFLAG(F_TAGS)) {
395 			/* don't output leading or trailing commas */
396 			p = cur->tags;
397 			while (*p == ',')
398 				p++;
399 			q = p + strlen(p);
400 			while(q > p && q[-1] == ',')
401 				q--;
402 			appendfield(pathlast, "tags=%.*s", (int)(q - p), p);
403 		}
404 		puts(pathlast ? vispath(path) : "");
405 
406 		if (cur->child)
407 			dump_nodes(path, cur->child, pathlast);
408 	}
409 }
410 
411 /*
412  * vispath --
413  *	strsvis(3) encodes path, which must not be longer than MAXPATHLEN
414  *	characters long, and returns a pointer to a static buffer containing
415  *	the result.
416  */
417 char *
418 vispath(const char *path)
419 {
420 	static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
421 	static const char extra_glob[] = { ' ', '\t', '\n', '\\', '#', '*',
422 	    '?', '[', '\0' };
423 	static char pathbuf[4*MAXPATHLEN + 1];
424 
425 	if (flavor == F_NETBSD6)
426 		strsvis(pathbuf, path, VIS_CSTYLE, extra);
427 	else
428 		strsvis(pathbuf, path, VIS_OCTAL, extra_glob);
429 	return pathbuf;
430 }
431 
432 
433 static dev_t
434 parsedev(char *arg)
435 {
436 #define MAX_PACK_ARGS	3
437 	u_long	numbers[MAX_PACK_ARGS];
438 	char	*p, *ep, *dev;
439 	int	argc;
440 	pack_t	*pack;
441 	dev_t	result;
442 	const char *error = NULL;
443 
444 	if ((dev = strchr(arg, ',')) != NULL) {
445 		*dev++='\0';
446 		if ((pack = pack_find(arg)) == NULL)
447 			mtree_err("unknown format `%s'", arg);
448 		argc = 0;
449 		while ((p = strsep(&dev, ",")) != NULL) {
450 			if (*p == '\0')
451 				mtree_err("missing number");
452 			numbers[argc++] = strtoul(p, &ep, 0);
453 			if (*ep != '\0')
454 				mtree_err("invalid number `%s'",
455 				    p);
456 			if (argc > MAX_PACK_ARGS)
457 				mtree_err("too many arguments");
458 		}
459 		if (argc < 2)
460 			mtree_err("not enough arguments");
461 		result = (*pack)(argc, numbers, &error);
462 		if (error != NULL)
463 			mtree_err("%s", error);
464 	} else {
465 		result = (dev_t)strtoul(arg, &ep, 0);
466 		if (*ep != '\0')
467 			mtree_err("invalid device `%s'", arg);
468 	}
469 	return (result);
470 }
471 
472 static void
473 replacenode(NODE *cur, NODE *new)
474 {
475 
476 #define REPLACE(x)	cur->x = new->x
477 #define REPLACESTR(x)	REPLACEPTR(cur->x,new->x)
478 
479 	if (cur->type != new->type) {
480 		if (mtree_Mflag) {
481 				/*
482 				 * merge entries with different types; we
483 				 * don't want children retained in this case.
484 				 */
485 			REPLACE(type);
486 			free_nodes(cur->child);
487 			cur->child = NULL;
488 		} else {
489 			mtree_err(
490 			    "existing entry for `%s', type `%s'"
491 			    " does not match type `%s'",
492 			    cur->name, nodetype(cur->type),
493 			    nodetype(new->type));
494 		}
495 	}
496 
497 	REPLACE(st_size);
498 	REPLACE(st_mtimespec);
499 	REPLACESTR(slink);
500 	if (cur->slink != NULL) {
501 		if ((cur->slink = strdup(new->slink)) == NULL)
502 			mtree_err("memory allocation error");
503 		if (strunvis(cur->slink, new->slink) == -1)
504 			mtree_err("strunvis failed on `%s'", new->slink);
505 		free(new->slink);
506 	}
507 	REPLACE(st_uid);
508 	REPLACE(st_gid);
509 	REPLACE(st_mode);
510 	REPLACE(st_rdev);
511 	REPLACE(st_flags);
512 	REPLACE(st_nlink);
513 	REPLACE(cksum);
514 	REPLACESTR(md5digest);
515 	REPLACESTR(rmd160digest);
516 	REPLACESTR(sha1digest);
517 	REPLACESTR(sha256digest);
518 	REPLACESTR(sha384digest);
519 	REPLACESTR(sha512digest);
520 	REPLACESTR(tags);
521 	REPLACE(lineno);
522 	REPLACE(flags);
523 	free(new);
524 }
525 
526 static void
527 set(char *t, NODE *ip)
528 {
529 	int	type, value, len;
530 	gid_t	gid;
531 	uid_t	uid;
532 	char	*kw, *val, *md, *ep;
533 	void	*m;
534 
535 	while ((kw = strsep(&t, "= \t")) != NULL) {
536 		if (*kw == '\0')
537 			continue;
538 		if (strcmp(kw, "all") == 0)
539 			mtree_err("invalid keyword `all'");
540 		ip->flags |= type = parsekey(kw, &value);
541 		if (!value)
542 			/* Just set flag bit (F_IGN and F_OPT) */
543 			continue;
544 		while ((val = strsep(&t, " \t")) != NULL && *val == '\0')
545 			continue;
546 		if (val == NULL)
547 			mtree_err("missing value");
548 		switch (type) {
549 		case F_CKSUM:
550 			ip->cksum = strtoul(val, &ep, 10);
551 			if (*ep)
552 				mtree_err("invalid checksum `%s'", val);
553 			break;
554 		case F_DEV:
555 			ip->st_rdev = parsedev(val);
556 			break;
557 		case F_FLAGS:
558 			if (strcmp("none", val) == 0)
559 				ip->st_flags = 0;
560 			else if (string_to_flags(&val, &ip->st_flags, NULL)
561 			    != 0)
562 				mtree_err("invalid flag `%s'", val);
563 			break;
564 		case F_GID:
565 			ip->st_gid = (gid_t)strtoul(val, &ep, 10);
566 			if (*ep)
567 				mtree_err("invalid gid `%s'", val);
568 			break;
569 		case F_GNAME:
570 			if (mtree_Wflag)	/* don't parse if whacking */
571 				break;
572 			if (gid_from_group(val, &gid) == -1)
573 				mtree_err("unknown group `%s'", val);
574 			ip->st_gid = gid;
575 			break;
576 		case F_MD5:
577 			if (val[0]=='0' && val[1]=='x')
578 				md=&val[2];
579 			else
580 				md=val;
581 			if ((ip->md5digest = strdup(md)) == NULL)
582 				mtree_err("memory allocation error");
583 			break;
584 		case F_MODE:
585 			if ((m = setmode(val)) == NULL)
586 				mtree_err("cannot set file mode `%s' (%s)",
587 				    val, strerror(errno));
588 			ip->st_mode = getmode(m, 0);
589 			free(m);
590 			break;
591 		case F_NLINK:
592 			ip->st_nlink = (nlink_t)strtoul(val, &ep, 10);
593 			if (*ep)
594 				mtree_err("invalid link count `%s'", val);
595 			break;
596 		case F_RMD160:
597 			if (val[0]=='0' && val[1]=='x')
598 				md=&val[2];
599 			else
600 				md=val;
601 			if ((ip->rmd160digest = strdup(md)) == NULL)
602 				mtree_err("memory allocation error");
603 			break;
604 		case F_SHA1:
605 			if (val[0]=='0' && val[1]=='x')
606 				md=&val[2];
607 			else
608 				md=val;
609 			if ((ip->sha1digest = strdup(md)) == NULL)
610 				mtree_err("memory allocation error");
611 			break;
612 		case F_SIZE:
613 			ip->st_size = (off_t)strtoll(val, &ep, 10);
614 			if (*ep)
615 				mtree_err("invalid size `%s'", val);
616 			break;
617 		case F_SLINK:
618 			if ((ip->slink = strdup(val)) == NULL)
619 				mtree_err("memory allocation error");
620 			if (strunvis(ip->slink, val) == -1)
621 				mtree_err("strunvis failed on `%s'", val);
622 			break;
623 		case F_TAGS:
624 			len = strlen(val) + 3;	/* "," + str + ",\0" */
625 			if ((ip->tags = malloc(len)) == NULL)
626 				mtree_err("memory allocation error");
627 			snprintf(ip->tags, len, ",%s,", val);
628 			break;
629 		case F_TIME:
630 			ip->st_mtimespec.tv_sec =
631 			    (time_t)strtoll(val, &ep, 10);
632 			if (*ep != '.')
633 				mtree_err("invalid time `%s'", val);
634 			val = ep + 1;
635 			ip->st_mtimespec.tv_nsec = strtol(val, &ep, 10);
636 			if (*ep)
637 				mtree_err("invalid time `%s'", val);
638 			break;
639 		case F_TYPE:
640 			ip->type = parsetype(val);
641 			break;
642 		case F_UID:
643 			ip->st_uid = (uid_t)strtoul(val, &ep, 10);
644 			if (*ep)
645 				mtree_err("invalid uid `%s'", val);
646 			break;
647 		case F_UNAME:
648 			if (mtree_Wflag)	/* don't parse if whacking */
649 				break;
650 			if (uid_from_user(val, &uid) == -1)
651 				mtree_err("unknown user `%s'", val);
652 			ip->st_uid = uid;
653 			break;
654 		case F_SHA256:
655 			if (val[0]=='0' && val[1]=='x')
656 				md=&val[2];
657 			else
658 				md=val;
659 			if ((ip->sha256digest = strdup(md)) == NULL)
660 				mtree_err("memory allocation error");
661 			break;
662 		case F_SHA384:
663 			if (val[0]=='0' && val[1]=='x')
664 				md=&val[2];
665 			else
666 				md=val;
667 			if ((ip->sha384digest = strdup(md)) == NULL)
668 				mtree_err("memory allocation error");
669 			break;
670 		case F_SHA512:
671 			if (val[0]=='0' && val[1]=='x')
672 				md=&val[2];
673 			else
674 				md=val;
675 			if ((ip->sha512digest = strdup(md)) == NULL)
676 				mtree_err("memory allocation error");
677 			break;
678 		default:
679 			mtree_err(
680 			    "set(): unsupported key type 0x%x (INTERNAL ERROR)",
681 			    type);
682 			/* NOTREACHED */
683 		}
684 	}
685 }
686 
687 static void
688 unset(char *t, NODE *ip)
689 {
690 	char *p;
691 
692 	while ((p = strsep(&t, " \t")) != NULL) {
693 		if (*p == '\0')
694 			continue;
695 		ip->flags &= ~parsekey(p, NULL);
696 	}
697 }
698 
699 /*
700  * addchild --
701  *	Add the centry node as a child of the pathparent node.	If
702  *	centry is a duplicate, call replacenode().  If centry is not
703  *	a duplicate, insert it into the linked list referenced by
704  *	pathparent->child.  Keep the list sorted if Sflag is set.
705  */
706 static void
707 addchild(NODE *pathparent, NODE *centry)
708 {
709 	NODE *samename;      /* node with the same name as centry */
710 	NODE *replacepos;    /* if non-NULL, centry should replace this node */
711 	NODE *insertpos;     /* if non-NULL, centry should be inserted
712 			      * after this node */
713 	NODE *cur;           /* for stepping through the list */
714 	NODE *last;          /* the last node in the list */
715 	int cmp;
716 
717 	samename = NULL;
718 	replacepos = NULL;
719 	insertpos = NULL;
720 	last = NULL;
721 	cur = pathparent->child;
722 	if (cur == NULL) {
723 		/* centry is pathparent's first and only child node so far */
724 		pathparent->child = centry;
725 		return;
726 	}
727 
728 	/*
729 	 * pathparent already has at least one other child, so add the
730 	 * centry node to the list.
731 	 *
732 	 * We first scan through the list looking for an existing node
733 	 * with the same name (setting samename), and also looking
734 	 * for the correct position to replace or insert the new node
735 	 * (setting replacepos and/or insertpos).
736 	 */
737 	for (; cur != NULL; last = cur, cur = cur->next) {
738 		if (strcmp(centry->name, cur->name) == 0) {
739 			samename = cur;
740 		}
741 		if (mtree_Sflag) {
742 			cmp = nodecmp(centry, cur);
743 			if (cmp == 0) {
744 				replacepos = cur;
745 			} else if (cmp > 0) {
746 				insertpos = cur;
747 			}
748 		}
749 	}
750 	if (! mtree_Sflag) {
751 		if (samename != NULL) {
752 			/* replace node with same name */
753 			replacepos = samename;
754 		} else {
755 			/* add new node at end of list */
756 			insertpos = last;
757 		}
758 	}
759 
760 	if (samename != NULL) {
761 		/*
762 		 * We found a node with the same name above.  Call
763 		 * replacenode(), which will either exit with an error,
764 		 * or replace the information in the samename node and
765 		 * free the information in the centry node.
766 		 */
767 		replacenode(samename, centry);
768 		if (samename == replacepos) {
769 			/* The just-replaced node was in the correct position */
770 			return;
771 		}
772 		if (samename == insertpos || samename->prev == insertpos) {
773 			/*
774 			 * We thought the new node should be just before
775 			 * or just after the replaced node, but that would
776 			 * be equivalent to just retaining the replaced node.
777 			 */
778 			return;
779 		}
780 
781 		/*
782 		 * The just-replaced node is in the wrong position in
783 		 * the list.  This can happen if sort order depends on
784 		 * criteria other than the node name.
785 		 *
786 		 * Make centry point to the just-replaced node.	 Unlink
787 		 * the just-replaced node from the list, and allow it to
788 		 * be insterted in the correct position later.
789 		 */
790 		centry = samename;
791 		if (centry->prev)
792 			centry->prev->next = centry->next;
793 		else {
794 			/* centry->next is the new head of the list */
795 			pathparent->child = centry->next;
796 			assert(centry->next != NULL);
797 		}
798 		if (centry->next)
799 			centry->next->prev = centry->prev;
800 		centry->prev = NULL;
801 		centry->next = NULL;
802 	}
803 
804 	if (insertpos == NULL) {
805 		/* insert centry at the beginning of the list */
806 		pathparent->child->prev = centry;
807 		centry->next = pathparent->child;
808 		centry->prev = NULL;
809 		pathparent->child = centry;
810 	} else {
811 		/* insert centry into the list just after insertpos */
812 		centry->next = insertpos->next;
813 		insertpos->next = centry;
814 		centry->prev = insertpos;
815 		if (centry->next)
816 			centry->next->prev = centry;
817 	}
818 	return;
819 }
820 
821 /*
822  * nodecmp --
823  *	used as a comparison function by addchild() to control the order
824  *	in which entries appear within a list of sibling nodes.	 We make
825  *	directories sort after non-directories, but otherwise sort in
826  *	strcmp() order.
827  *
828  * Keep this in sync with dcmp() in create.c.
829  */
830 static int
831 nodecmp(const NODE *a, const NODE *b)
832 {
833 
834 	if ((a->type & F_DIR) != 0) {
835 		if ((b->type & F_DIR) == 0)
836 			return 1;
837 	} else if ((b->type & F_DIR) != 0)
838 		return -1;
839 	return strcmp(a->name, b->name);
840 }
841