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