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