1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2011 Marcel Moolenaar
5 * 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 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#if HAVE_NBTOOL_CONFIG_H
29#include "nbtool_config.h"
30#endif
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD$");
34
35#include <sys/param.h>
36#include <sys/queue.h>
37#include <sys/sbuf.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <assert.h>
41#include <errno.h>
42#include <fcntl.h>
43#include <grp.h>
44#include <inttypes.h>
45#include <pwd.h>
46#include <stdarg.h>
47#include <stdbool.h>
48#include <stddef.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52#include <strings.h>
53#include <time.h>
54#include <unistd.h>
55#include <util.h>
56#include <vis.h>
57
58#include "makefs.h"
59
60#ifndef ENOATTR
61#define	ENOATTR	ENODATA
62#endif
63
64#define	IS_DOT(nm)	((nm)[0] == '.' && (nm)[1] == '\0')
65#define	IS_DOTDOT(nm)	((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
66
67struct mtree_fileinfo {
68	SLIST_ENTRY(mtree_fileinfo) next;
69	FILE *fp;
70	const char *name;
71	u_int line;
72};
73
74/* Global state used while parsing. */
75static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
76    SLIST_HEAD_INITIALIZER(mtree_fileinfo);
77static fsnode *mtree_root;
78static fsnode *mtree_current;
79static fsnode mtree_global;
80static fsinode mtree_global_inode;
81static u_int errors, warnings;
82
83static void mtree_error(const char *, ...) __printflike(1, 2);
84static void mtree_warning(const char *, ...) __printflike(1, 2);
85
86static int
87mtree_file_push(const char *name, FILE *fp)
88{
89	struct mtree_fileinfo *fi;
90
91	fi = emalloc(sizeof(*fi));
92	if (strcmp(name, "-") == 0)
93		fi->name = estrdup("(stdin)");
94	else
95		fi->name = estrdup(name);
96	if (fi->name == NULL) {
97		free(fi);
98		return (ENOMEM);
99	}
100
101	fi->fp = fp;
102	fi->line = 0;
103
104	SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
105	return (0);
106}
107
108static void
109mtree_print(const char *msgtype, const char *fmt, va_list ap)
110{
111	struct mtree_fileinfo *fi;
112
113	if (msgtype != NULL) {
114		fi = SLIST_FIRST(&mtree_fileinfo);
115		if (fi != NULL)
116			fprintf(stderr, "%s:%u: ", fi->name, fi->line);
117		fprintf(stderr, "%s: ", msgtype);
118	}
119	vfprintf(stderr, fmt, ap);
120}
121
122static void
123mtree_error(const char *fmt, ...)
124{
125	va_list ap;
126
127	va_start(ap, fmt);
128	mtree_print("error", fmt, ap);
129	va_end(ap);
130
131	errors++;
132	fputc('\n', stderr);
133}
134
135static void
136mtree_warning(const char *fmt, ...)
137{
138	va_list ap;
139
140	va_start(ap, fmt);
141	mtree_print("warning", fmt, ap);
142	va_end(ap);
143
144	warnings++;
145	fputc('\n', stderr);
146}
147
148#ifndef MAKEFS_MAX_TREE_DEPTH
149# define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
150#endif
151
152/* construct path to node->name */
153static char *
154mtree_file_path(fsnode *node)
155{
156	fsnode *pnode;
157	struct sbuf *sb;
158	char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
159	int depth;
160
161	depth = 0;
162	rp[depth] = node->name;
163	for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
164	     pnode = pnode->parent) {
165		if (strcmp(pnode->name, ".") == 0)
166			break;
167		rp[++depth] = pnode->name;
168	}
169
170	sb = sbuf_new_auto();
171	if (sb == NULL) {
172		errno = ENOMEM;
173		return (NULL);
174	}
175	while (depth > 0) {
176		sbuf_cat(sb, rp[depth--]);
177		sbuf_putc(sb, '/');
178	}
179	sbuf_cat(sb, rp[depth]);
180	sbuf_finish(sb);
181	res = estrdup(sbuf_data(sb));
182	sbuf_delete(sb);
183	if (res == NULL)
184		errno = ENOMEM;
185	return res;
186
187}
188
189/* mtree_resolve() sets errno to indicate why NULL was returned. */
190static char *
191mtree_resolve(const char *spec, int *istemp)
192{
193	struct sbuf *sb;
194	char *res, *var = NULL;
195	const char *base, *p, *v;
196	size_t len;
197	int c, error, quoted, subst;
198
199	len = strlen(spec);
200	if (len == 0) {
201		errno = EINVAL;
202		return (NULL);
203	}
204
205	c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
206	*istemp = (c == '`') ? 1 : 0;
207	subst = (c == '`' || c == '"') ? 1 : 0;
208	quoted = (subst || c == '\'') ? 1 : 0;
209
210	if (!subst) {
211		res = estrdup(spec + quoted);
212		if (quoted)
213			res[len - 2] = '\0';
214		return (res);
215	}
216
217	sb = sbuf_new_auto();
218	if (sb == NULL) {
219		errno = ENOMEM;
220		return (NULL);
221	}
222
223	base = spec + 1;
224	len -= 2;
225	error = 0;
226	while (len > 0) {
227		p = strchr(base, '$');
228		if (p == NULL) {
229			sbuf_bcat(sb, base, len);
230			base += len;
231			len = 0;
232			continue;
233		}
234		/* The following is safe. spec always starts with a quote. */
235		if (p[-1] == '\\')
236			p--;
237		if (base != p) {
238			sbuf_bcat(sb, base, p - base);
239			len -= p - base;
240			base = p;
241		}
242		if (*p == '\\') {
243			sbuf_putc(sb, '$');
244			base += 2;
245			len -= 2;
246			continue;
247		}
248		/* Skip the '$'. */
249		base++;
250		len--;
251		/* Handle ${X} vs $X. */
252		v = base;
253		if (*base == '{') {
254			p = strchr(v, '}');
255			if (p == NULL)
256				p = v;
257		} else
258			p = v;
259		len -= (p + 1) - base;
260		base = p + 1;
261
262		if (v == p) {
263			sbuf_putc(sb, *v);
264			continue;
265		}
266
267		error = ENOMEM;
268		var = ecalloc(p - v, 1);
269		memcpy(var, v + 1, p - v - 1);
270		if (strcmp(var, ".CURDIR") == 0) {
271			res = getcwd(NULL, 0);
272			if (res == NULL)
273				break;
274		} else if (strcmp(var, ".PROG") == 0) {
275			res = estrdup(getprogname());
276		} else {
277			v = getenv(var);
278			if (v != NULL) {
279				res = estrdup(v);
280			} else
281				res = NULL;
282		}
283		error = 0;
284
285		if (res != NULL) {
286			sbuf_cat(sb, res);
287			free(res);
288		}
289		free(var);
290		var = NULL;
291	}
292
293	free(var);
294	sbuf_finish(sb);
295	res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
296	sbuf_delete(sb);
297	if (res == NULL)
298		errno = ENOMEM;
299	return (res);
300}
301
302static int
303skip_over(FILE *fp, const char *cs)
304{
305	int c;
306
307	c = getc(fp);
308	while (c != EOF && strchr(cs, c) != NULL)
309		c = getc(fp);
310	if (c != EOF) {
311		ungetc(c, fp);
312		return (0);
313	}
314	return (ferror(fp) ? errno : -1);
315}
316
317static int
318skip_to(FILE *fp, const char *cs)
319{
320	int c;
321
322	c = getc(fp);
323	while (c != EOF && strchr(cs, c) == NULL)
324		c = getc(fp);
325	if (c != EOF) {
326		ungetc(c, fp);
327		return (0);
328	}
329	return (ferror(fp) ? errno : -1);
330}
331
332static int
333read_word(FILE *fp, char *buf, size_t bufsz)
334{
335	struct mtree_fileinfo *fi;
336	size_t idx, qidx;
337	int c, done, error, esc, qlvl;
338
339	if (bufsz == 0)
340		return (EINVAL);
341
342	done = 0;
343	esc = 0;
344	idx = 0;
345	qidx = -1;
346	qlvl = 0;
347	do {
348		c = getc(fp);
349		switch (c) {
350		case EOF:
351			buf[idx] = '\0';
352			error = ferror(fp) ? errno : -1;
353			if (error == -1)
354				mtree_error("unexpected end of file");
355			return (error);
356		case '#':		/* comment -- skip to end of line. */
357			if (!esc) {
358				error = skip_to(fp, "\n");
359				if (!error)
360					continue;
361			}
362			break;
363		case '\\':
364			esc++;
365			break;
366		case '`':
367		case '\'':
368		case '"':
369			if (esc)
370				break;
371			if (qlvl == 0) {
372				qlvl++;
373				qidx = idx;
374			} else if (c == buf[qidx]) {
375				qlvl--;
376				if (qlvl > 0) {
377					do {
378						qidx--;
379					} while (buf[qidx] != '`' &&
380					    buf[qidx] != '\'' &&
381					    buf[qidx] != '"');
382				} else
383					qidx = -1;
384			} else {
385				qlvl++;
386				qidx = idx;
387			}
388			break;
389		case ' ':
390		case '\t':
391		case '\n':
392			if (!esc && qlvl == 0) {
393				ungetc(c, fp);
394				c = '\0';
395				done = 1;
396				break;
397			}
398			if (c == '\n') {
399				/*
400				 * We going to eat the newline ourselves.
401				 */
402				if (qlvl > 0)
403					mtree_warning("quoted word straddles "
404					    "onto next line.");
405				fi = SLIST_FIRST(&mtree_fileinfo);
406				fi->line++;
407			}
408			break;
409		default:
410			if (esc)
411				buf[idx++] = '\\';
412			break;
413		}
414		buf[idx++] = c;
415		esc = 0;
416	} while (idx < bufsz && !done);
417
418	if (idx >= bufsz) {
419		mtree_error("word too long to fit buffer (max %zu characters)",
420		    bufsz);
421		skip_to(fp, " \t\n");
422	}
423	return (0);
424}
425
426static fsnode *
427create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
428{
429	fsnode *n;
430
431	n = ecalloc(1, sizeof(*n));
432	n->name = estrdup(name);
433	n->type = (type == 0) ? global->type : type;
434	n->parent = parent;
435
436	n->inode = ecalloc(1, sizeof(*n->inode));
437
438	/* Assign global options/defaults. */
439	memcpy(n->inode, global->inode, sizeof(*n->inode));
440	n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
441
442	if (n->type == S_IFLNK)
443		n->symlink = global->symlink;
444	else if (n->type == S_IFREG)
445		n->contents = global->contents;
446
447	return (n);
448}
449
450static void
451destroy_node(fsnode *n)
452{
453
454	assert(n != NULL);
455	assert(n->name != NULL);
456	assert(n->inode != NULL);
457
458	free(n->inode);
459	free(n->name);
460	free(n);
461}
462
463static int
464read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
465    intmax_t max)
466{
467	char *end;
468	intmax_t val;
469
470	val = strtoimax(tok, &end, base);
471	if (end == tok || end[0] != '\0')
472		return (EINVAL);
473	if (val < min || val > max)
474		return (EDOM);
475	*res = val;
476	return (0);
477}
478
479static int
480read_mtree_keywords(FILE *fp, fsnode *node)
481{
482	char keyword[PATH_MAX];
483	char *name, *p, *value;
484	gid_t gid;
485	uid_t uid;
486	struct stat *st, sb;
487	intmax_t num;
488	u_long flset, flclr;
489	int error, istemp;
490	uint32_t type;
491
492	st = &node->inode->st;
493	do {
494		error = skip_over(fp, " \t");
495		if (error)
496			break;
497
498		error = read_word(fp, keyword, sizeof(keyword));
499		if (error)
500			break;
501
502		if (keyword[0] == '\0')
503			break;
504
505		value = strchr(keyword, '=');
506		if (value != NULL)
507			*value++ = '\0';
508
509		/*
510		 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
511		 * certain conditions:
512		 *   EINVAL -	Value provided for a keyword that does
513		 *		not take a value. The value is ignored.
514		 *   ENOATTR -	Value missing for a keyword that needs
515		 *		a value. The keyword is ignored.
516		 *   ENOSYS -	Unsupported keyword encountered. The
517		 *		keyword is ignored.
518		 *   ENXIO -	Value provided for a keyword that does
519		 *		not take a value. The value is ignored.
520		 */
521		switch (keyword[0]) {
522		case 'c':
523			if (strcmp(keyword, "contents") == 0) {
524				if (value == NULL) {
525					error = ENOATTR;
526					break;
527				}
528				node->contents = estrdup(value);
529			} else
530				error = ENOSYS;
531			break;
532		case 'f':
533			if (strcmp(keyword, "flags") == 0) {
534				if (value == NULL) {
535					error = ENOATTR;
536					break;
537				}
538				flset = flclr = 0;
539#if HAVE_STRUCT_STAT_ST_FLAGS
540				if (!strtofflags(&value, &flset, &flclr)) {
541					st->st_flags &= ~flclr;
542					st->st_flags |= flset;
543				} else
544					error = errno;
545#endif
546			} else
547				error = ENOSYS;
548			break;
549		case 'g':
550			if (strcmp(keyword, "gid") == 0) {
551				if (value == NULL) {
552					error = ENOATTR;
553					break;
554				}
555				error = read_number(value, 10, &num,
556				    0, UINT_MAX);
557				if (!error)
558					st->st_gid = num;
559			} else if (strcmp(keyword, "gname") == 0) {
560				if (value == NULL) {
561					error = ENOATTR;
562					break;
563				}
564				if (gid_from_group(value, &gid) == 0)
565					st->st_gid = gid;
566				else
567					error = EINVAL;
568			} else
569				error = ENOSYS;
570			break;
571		case 'l':
572			if (strcmp(keyword, "link") == 0) {
573				if (value == NULL) {
574					error = ENOATTR;
575					break;
576				}
577				node->symlink = emalloc(strlen(value) + 1);
578				if (node->symlink == NULL) {
579					error = errno;
580					break;
581				}
582				if (strunvis(node->symlink, value) < 0) {
583					error = errno;
584					break;
585				}
586			} else
587				error = ENOSYS;
588			break;
589		case 'm':
590			if (strcmp(keyword, "mode") == 0) {
591				if (value == NULL) {
592					error = ENOATTR;
593					break;
594				}
595				if (value[0] >= '0' && value[0] <= '9') {
596					error = read_number(value, 8, &num,
597					    0, 07777);
598					if (!error) {
599						st->st_mode &= S_IFMT;
600						st->st_mode |= num;
601					}
602				} else {
603					/* Symbolic mode not supported. */
604					error = EINVAL;
605					break;
606				}
607			} else
608				error = ENOSYS;
609			break;
610		case 'o':
611			if (strcmp(keyword, "optional") == 0) {
612				if (value != NULL)
613					error = ENXIO;
614				node->flags |= FSNODE_F_OPTIONAL;
615			} else
616				error = ENOSYS;
617			break;
618		case 's':
619			if (strcmp(keyword, "size") == 0) {
620				if (value == NULL) {
621					error = ENOATTR;
622					break;
623				}
624				error = read_number(value, 10, &num,
625				    0, INTMAX_MAX);
626				if (!error)
627					st->st_size = num;
628			} else
629				error = ENOSYS;
630			break;
631		case 't':
632			if (strcmp(keyword, "tags") == 0) {
633				if (value == NULL) {
634					error = ENOATTR;
635					break;
636				}
637				/* Ignore. */
638			} else if (strcmp(keyword, "time") == 0) {
639				if (value == NULL) {
640					error = ENOATTR;
641					break;
642				}
643				p = strchr(value, '.');
644				if (p != NULL)
645					*p++ = '\0';
646				error = read_number(value, 10, &num, 0,
647				    INTMAX_MAX);
648				if (error)
649					break;
650				st->st_atime = num;
651				st->st_ctime = num;
652				st->st_mtime = num;
653#if HAVE_STRUCT_STAT_ST_MTIMENSEC
654				if (p == NULL)
655					break;
656				error = read_number(p, 10, &num, 0,
657				    INTMAX_MAX);
658				if (error)
659					break;
660				st->st_atimensec = num;
661				st->st_ctimensec = num;
662				st->st_mtimensec = num;
663#endif
664			} else if (strcmp(keyword, "type") == 0) {
665				if (value == NULL) {
666					error = ENOATTR;
667					break;
668				}
669				if (strcmp(value, "dir") == 0)
670					node->type = S_IFDIR;
671				else if (strcmp(value, "file") == 0)
672					node->type = S_IFREG;
673				else if (strcmp(value, "link") == 0)
674					node->type = S_IFLNK;
675				else
676					error = EINVAL;
677			} else
678				error = ENOSYS;
679			break;
680		case 'u':
681			if (strcmp(keyword, "uid") == 0) {
682				if (value == NULL) {
683					error = ENOATTR;
684					break;
685				}
686				error = read_number(value, 10, &num,
687				    0, UINT_MAX);
688				if (!error)
689					st->st_uid = num;
690			} else if (strcmp(keyword, "uname") == 0) {
691				if (value == NULL) {
692					error = ENOATTR;
693					break;
694				}
695				if (uid_from_user(value, &uid) == 0)
696					st->st_uid = uid;
697				else
698					error = EINVAL;
699			} else
700				error = ENOSYS;
701			break;
702		default:
703			error = ENOSYS;
704			break;
705		}
706
707		switch (error) {
708		case EINVAL:
709			mtree_error("%s: invalid value '%s'", keyword, value);
710			break;
711		case ENOATTR:
712			mtree_error("%s: keyword needs a value", keyword);
713			break;
714		case ENOSYS:
715			mtree_warning("%s: unsupported keyword", keyword);
716			break;
717		case ENXIO:
718			mtree_error("%s: keyword does not take a value",
719			    keyword);
720			break;
721		}
722	} while (1);
723
724	if (error)
725		return (error);
726
727	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
728
729	/* Nothing more to do for the global defaults. */
730	if (node->name == NULL)
731		return (0);
732
733	/*
734	 * Be intelligent about the file type.
735	 */
736	if (node->contents != NULL) {
737		if (node->symlink != NULL) {
738			mtree_error("%s: both link and contents keywords "
739			    "defined", node->name);
740			return (0);
741		}
742		type = S_IFREG;
743	} else if (node->type != 0) {
744		type = node->type;
745		if (type == S_IFREG) {
746			/* the named path is the default contents */
747			node->contents = mtree_file_path(node);
748		}
749	} else
750		type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
751
752	if (node->type == 0)
753		node->type = type;
754
755	if (node->type != type) {
756		mtree_error("%s: file type and defined keywords to not match",
757		    node->name);
758		return (0);
759	}
760
761	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
762
763	if (node->contents == NULL)
764		return (0);
765
766	name = mtree_resolve(node->contents, &istemp);
767	if (name == NULL)
768		return (errno);
769
770	if (stat(name, &sb) != 0) {
771		mtree_error("%s: contents file '%s' not found", node->name,
772		    name);
773		free(name);
774		return (0);
775	}
776
777	/*
778         * Check for hardlinks. If the contents key is used, then the check
779         * will only trigger if the contents file is a link even if it is used
780         * by more than one file
781	 */
782	if (sb.st_nlink > 1) {
783		fsinode *curino;
784
785		st->st_ino = sb.st_ino;
786		st->st_dev = sb.st_dev;
787		curino = link_check(node->inode);
788		if (curino != NULL) {
789			free(node->inode);
790			node->inode = curino;
791			node->inode->nlink++;
792			/* Reset st since node->inode has been updated. */
793			st = &node->inode->st;
794		}
795	}
796
797	free(node->contents);
798	node->contents = name;
799	st->st_size = sb.st_size;
800	return (0);
801}
802
803static int
804read_mtree_command(FILE *fp)
805{
806	char cmd[10];
807	int error;
808
809	error = read_word(fp, cmd, sizeof(cmd));
810	if (error)
811		goto out;
812
813	error = read_mtree_keywords(fp, &mtree_global);
814
815 out:
816	skip_to(fp, "\n");
817	(void)getc(fp);
818	return (error);
819}
820
821static int
822read_mtree_spec1(FILE *fp, bool def, const char *name)
823{
824	fsnode *last, *node, *parent;
825	u_int type;
826	int error;
827
828	assert(name[0] != '\0');
829
830	/*
831	 * Treat '..' specially, because it only changes our current
832	 * directory. We don't create a node for it. We simply ignore
833	 * any keywords that may appear on the line as well.
834	 * Going up a directory is a little non-obvious. A directory
835	 * node has a corresponding '.' child. The parent of '.' is
836	 * not the '.' node of the parent directory, but the directory
837	 * node within the parent to which the child relates. However,
838	 * going up a directory means we need to find the '.' node to
839	 * which the directoy node is linked.  This we can do via the
840	 * first * pointer, because '.' is always the first entry in a
841	 * directory.
842	 */
843	if (IS_DOTDOT(name)) {
844		/* This deals with NULL pointers as well. */
845		if (mtree_current == mtree_root) {
846			mtree_warning("ignoring .. in root directory");
847			return (0);
848		}
849
850		node = mtree_current;
851
852		assert(node != NULL);
853		assert(IS_DOT(node->name));
854		assert(node->first == node);
855
856		/* Get the corresponding directory node in the parent. */
857		node = mtree_current->parent;
858
859		assert(node != NULL);
860		assert(!IS_DOT(node->name));
861
862		node = node->first;
863
864		assert(node != NULL);
865		assert(IS_DOT(node->name));
866		assert(node->first == node);
867
868		mtree_current = node;
869		return (0);
870	}
871
872	/*
873	 * If we don't have a current directory and the first specification
874	 * (either implicit or defined) is not '.', then we need to create
875	 * a '.' node first (using a recursive call).
876	 */
877	if (!IS_DOT(name) && mtree_current == NULL) {
878		error = read_mtree_spec1(fp, false, ".");
879		if (error)
880			return (error);
881	}
882
883	/*
884	 * Lookup the name in the current directory (if we have a current
885	 * directory) to make sure we do not create multiple nodes for the
886	 * same component. For non-definitions, if we find a node with the
887	 * same name, simply change the current directory. For definitions
888	 * more happens.
889	 */
890	last = NULL;
891	node = mtree_current;
892	while (node != NULL) {
893		assert(node->first == mtree_current);
894
895		if (strcmp(name, node->name) == 0) {
896			if (def == true) {
897				if (!dupsok)
898					mtree_error(
899					    "duplicate definition of %s",
900					    name);
901				else
902					mtree_warning(
903					    "duplicate definition of %s",
904					    name);
905				return (0);
906			}
907
908			if (node->type != S_IFDIR) {
909				mtree_error("%s is not a directory", name);
910				return (0);
911			}
912
913			assert(!IS_DOT(name));
914
915			node = node->child;
916
917			assert(node != NULL);
918			assert(IS_DOT(node->name));
919
920			mtree_current = node;
921			return (0);
922		}
923
924		last = node;
925		node = last->next;
926	}
927
928	parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
929	type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
930	node = create_node(name, type, parent, &mtree_global);
931	if (node == NULL)
932		return (ENOMEM);
933
934	if (def == true) {
935		error = read_mtree_keywords(fp, node);
936		if (error) {
937			destroy_node(node);
938			return (error);
939		}
940	}
941
942	node->first = (mtree_current != NULL) ? mtree_current : node;
943
944	if (last != NULL)
945		last->next = node;
946
947	if (node->type != S_IFDIR)
948		return (0);
949
950	if (!IS_DOT(node->name)) {
951		parent = node;
952		node = create_node(".", S_IFDIR, parent, parent);
953		if (node == NULL) {
954			last->next = NULL;
955			destroy_node(parent);
956			return (ENOMEM);
957		}
958		parent->child = node;
959		node->first = node;
960	}
961
962	assert(node != NULL);
963	assert(IS_DOT(node->name));
964	assert(node->first == node);
965
966	mtree_current = node;
967	if (mtree_root == NULL)
968		mtree_root = node;
969
970	return (0);
971}
972
973static int
974read_mtree_spec(FILE *fp)
975{
976	char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
977	char *cp;
978	int error;
979
980	error = read_word(fp, pathtmp, sizeof(pathtmp));
981	if (error)
982		goto out;
983	if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
984		error = errno;
985		goto out;
986	}
987	error = 0;
988
989	cp = strchr(pathspec, '/');
990	if (cp != NULL) {
991		/* Absolute pathname */
992		mtree_current = mtree_root;
993
994		do {
995			*cp++ = '\0';
996
997			/* Disallow '..' as a component. */
998			if (IS_DOTDOT(pathspec)) {
999				mtree_error("absolute path cannot contain "
1000				    ".. component");
1001				goto out;
1002			}
1003
1004			/* Ignore multiple adjacent slashes and '.'. */
1005			if (pathspec[0] != '\0' && !IS_DOT(pathspec))
1006				error = read_mtree_spec1(fp, false, pathspec);
1007			memmove(pathspec, cp, strlen(cp) + 1);
1008			cp = strchr(pathspec, '/');
1009		} while (!error && cp != NULL);
1010
1011		/* Disallow '.' and '..' as the last component. */
1012		if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1013			mtree_error("absolute path cannot contain . or .. "
1014			    "components");
1015			goto out;
1016		}
1017	}
1018
1019	/* Ignore absolute specfications that end with a slash. */
1020	if (!error && pathspec[0] != '\0')
1021		error = read_mtree_spec1(fp, true, pathspec);
1022
1023 out:
1024	skip_to(fp, "\n");
1025	(void)getc(fp);
1026	return (error);
1027}
1028
1029fsnode *
1030read_mtree(const char *fname, fsnode *node)
1031{
1032	struct mtree_fileinfo *fi;
1033	FILE *fp;
1034	int c, error;
1035
1036	/* We do not yet support nesting... */
1037	assert(node == NULL);
1038
1039	if (strcmp(fname, "-") == 0)
1040		fp = stdin;
1041	else {
1042		fp = fopen(fname, "r");
1043		if (fp == NULL)
1044			err(1, "Can't open `%s'", fname);
1045	}
1046
1047	error = mtree_file_push(fname, fp);
1048	if (error)
1049		goto out;
1050
1051	memset(&mtree_global, 0, sizeof(mtree_global));
1052	memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1053	mtree_global.inode = &mtree_global_inode;
1054	mtree_global_inode.nlink = 1;
1055	mtree_global_inode.st.st_nlink = 1;
1056	mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1057	    mtree_global_inode.st.st_mtime = time(NULL);
1058	errors = warnings = 0;
1059
1060	setgroupent(1);
1061	setpassent(1);
1062
1063	mtree_root = node;
1064	mtree_current = node;
1065	do {
1066		/* Start of a new line... */
1067		fi = SLIST_FIRST(&mtree_fileinfo);
1068		fi->line++;
1069
1070		error = skip_over(fp, " \t");
1071		if (error)
1072			break;
1073
1074		c = getc(fp);
1075		if (c == EOF) {
1076			error = ferror(fp) ? errno : -1;
1077			break;
1078		}
1079
1080		switch (c) {
1081		case '\n':		/* empty line */
1082			error = 0;
1083			break;
1084		case '#':		/* comment -- skip to end of line. */
1085			error = skip_to(fp, "\n");
1086			if (!error)
1087				(void)getc(fp);
1088			break;
1089		case '/':		/* special commands */
1090			error = read_mtree_command(fp);
1091			break;
1092		default:		/* specification */
1093			ungetc(c, fp);
1094			error = read_mtree_spec(fp);
1095			break;
1096		}
1097	} while (!error);
1098
1099	endpwent();
1100	endgrent();
1101
1102	if (error <= 0 && (errors || warnings)) {
1103		warnx("%u error(s) and %u warning(s) in mtree manifest",
1104		    errors, warnings);
1105		if (errors)
1106			exit(1);
1107	}
1108
1109 out:
1110	if (error > 0)
1111		errc(1, error, "Error reading mtree file");
1112
1113	if (fp != stdin)
1114		fclose(fp);
1115
1116	if (mtree_root != NULL)
1117		return (mtree_root);
1118
1119	/* Handle empty specifications. */
1120	node = create_node(".", S_IFDIR, NULL, &mtree_global);
1121	node->first = node;
1122	return (node);
1123}
1124