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, "time") == 0) {
633				if (value == NULL) {
634					error = ENOATTR;
635					break;
636				}
637				p = strchr(value, '.');
638				if (p != NULL)
639					*p++ = '\0';
640				error = read_number(value, 10, &num, 0,
641				    INTMAX_MAX);
642				if (error)
643					break;
644				st->st_atime = num;
645				st->st_ctime = num;
646				st->st_mtime = num;
647#if HAVE_STRUCT_STAT_ST_MTIMENSEC
648				if (p == NULL)
649					break;
650				error = read_number(p, 10, &num, 0,
651				    INTMAX_MAX);
652				if (error)
653					break;
654				st->st_atimensec = num;
655				st->st_ctimensec = num;
656				st->st_mtimensec = num;
657#endif
658			} else if (strcmp(keyword, "type") == 0) {
659				if (value == NULL) {
660					error = ENOATTR;
661					break;
662				}
663				if (strcmp(value, "dir") == 0)
664					node->type = S_IFDIR;
665				else if (strcmp(value, "file") == 0)
666					node->type = S_IFREG;
667				else if (strcmp(value, "link") == 0)
668					node->type = S_IFLNK;
669				else
670					error = EINVAL;
671			} else
672				error = ENOSYS;
673			break;
674		case 'u':
675			if (strcmp(keyword, "uid") == 0) {
676				if (value == NULL) {
677					error = ENOATTR;
678					break;
679				}
680				error = read_number(value, 10, &num,
681				    0, UINT_MAX);
682				if (!error)
683					st->st_uid = num;
684			} else if (strcmp(keyword, "uname") == 0) {
685				if (value == NULL) {
686					error = ENOATTR;
687					break;
688				}
689				if (uid_from_user(value, &uid) == 0)
690					st->st_uid = uid;
691				else
692					error = EINVAL;
693			} else
694				error = ENOSYS;
695			break;
696		default:
697			error = ENOSYS;
698			break;
699		}
700
701		switch (error) {
702		case EINVAL:
703			mtree_error("%s: invalid value '%s'", keyword, value);
704			break;
705		case ENOATTR:
706			mtree_error("%s: keyword needs a value", keyword);
707			break;
708		case ENOSYS:
709			mtree_warning("%s: unsupported keyword", keyword);
710			break;
711		case ENXIO:
712			mtree_error("%s: keyword does not take a value",
713			    keyword);
714			break;
715		}
716	} while (1);
717
718	if (error)
719		return (error);
720
721	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
722
723	/* Nothing more to do for the global defaults. */
724	if (node->name == NULL)
725		return (0);
726
727	/*
728	 * Be intelligent about the file type.
729	 */
730	if (node->contents != NULL) {
731		if (node->symlink != NULL) {
732			mtree_error("%s: both link and contents keywords "
733			    "defined", node->name);
734			return (0);
735		}
736		type = S_IFREG;
737	} else if (node->type != 0) {
738		type = node->type;
739		if (type == S_IFREG) {
740			/* the named path is the default contents */
741			node->contents = mtree_file_path(node);
742		}
743	} else
744		type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
745
746	if (node->type == 0)
747		node->type = type;
748
749	if (node->type != type) {
750		mtree_error("%s: file type and defined keywords to not match",
751		    node->name);
752		return (0);
753	}
754
755	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
756
757	if (node->contents == NULL)
758		return (0);
759
760	name = mtree_resolve(node->contents, &istemp);
761	if (name == NULL)
762		return (errno);
763
764	if (stat(name, &sb) != 0) {
765		mtree_error("%s: contents file '%s' not found", node->name,
766		    name);
767		free(name);
768		return (0);
769	}
770
771	/*
772         * Check for hardlinks. If the contents key is used, then the check
773         * will only trigger if the contents file is a link even if it is used
774         * by more than one file
775	 */
776	if (sb.st_nlink > 1) {
777		fsinode *curino;
778
779		st->st_ino = sb.st_ino;
780		st->st_dev = sb.st_dev;
781		curino = link_check(node->inode);
782		if (curino != NULL) {
783			free(node->inode);
784			node->inode = curino;
785			node->inode->nlink++;
786		}
787	}
788
789	free(node->contents);
790	node->contents = name;
791	st->st_size = sb.st_size;
792	return (0);
793}
794
795static int
796read_mtree_command(FILE *fp)
797{
798	char cmd[10];
799	int error;
800
801	error = read_word(fp, cmd, sizeof(cmd));
802	if (error)
803		goto out;
804
805	error = read_mtree_keywords(fp, &mtree_global);
806
807 out:
808	skip_to(fp, "\n");
809	(void)getc(fp);
810	return (error);
811}
812
813static int
814read_mtree_spec1(FILE *fp, bool def, const char *name)
815{
816	fsnode *last, *node, *parent;
817	u_int type;
818	int error;
819
820	assert(name[0] != '\0');
821
822	/*
823	 * Treat '..' specially, because it only changes our current
824	 * directory. We don't create a node for it. We simply ignore
825	 * any keywords that may appear on the line as well.
826	 * Going up a directory is a little non-obvious. A directory
827	 * node has a corresponding '.' child. The parent of '.' is
828	 * not the '.' node of the parent directory, but the directory
829	 * node within the parent to which the child relates. However,
830	 * going up a directory means we need to find the '.' node to
831	 * which the directoy node is linked.  This we can do via the
832	 * first * pointer, because '.' is always the first entry in a
833	 * directory.
834	 */
835	if (IS_DOTDOT(name)) {
836		/* This deals with NULL pointers as well. */
837		if (mtree_current == mtree_root) {
838			mtree_warning("ignoring .. in root directory");
839			return (0);
840		}
841
842		node = mtree_current;
843
844		assert(node != NULL);
845		assert(IS_DOT(node->name));
846		assert(node->first == node);
847
848		/* Get the corresponding directory node in the parent. */
849		node = mtree_current->parent;
850
851		assert(node != NULL);
852		assert(!IS_DOT(node->name));
853
854		node = node->first;
855
856		assert(node != NULL);
857		assert(IS_DOT(node->name));
858		assert(node->first == node);
859
860		mtree_current = node;
861		return (0);
862	}
863
864	/*
865	 * If we don't have a current directory and the first specification
866	 * (either implicit or defined) is not '.', then we need to create
867	 * a '.' node first (using a recursive call).
868	 */
869	if (!IS_DOT(name) && mtree_current == NULL) {
870		error = read_mtree_spec1(fp, false, ".");
871		if (error)
872			return (error);
873	}
874
875	/*
876	 * Lookup the name in the current directory (if we have a current
877	 * directory) to make sure we do not create multiple nodes for the
878	 * same component. For non-definitions, if we find a node with the
879	 * same name, simply change the current directory. For definitions
880	 * more happens.
881	 */
882	last = NULL;
883	node = mtree_current;
884	while (node != NULL) {
885		assert(node->first == mtree_current);
886
887		if (strcmp(name, node->name) == 0) {
888			if (def == true) {
889				if (!dupsok)
890					mtree_error(
891					    "duplicate definition of %s",
892					    name);
893				else
894					mtree_warning(
895					    "duplicate definition of %s",
896					    name);
897				return (0);
898			}
899
900			if (node->type != S_IFDIR) {
901				mtree_error("%s is not a directory", name);
902				return (0);
903			}
904
905			assert(!IS_DOT(name));
906
907			node = node->child;
908
909			assert(node != NULL);
910			assert(IS_DOT(node->name));
911
912			mtree_current = node;
913			return (0);
914		}
915
916		last = node;
917		node = last->next;
918	}
919
920	parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
921	type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
922	node = create_node(name, type, parent, &mtree_global);
923	if (node == NULL)
924		return (ENOMEM);
925
926	if (def == true) {
927		error = read_mtree_keywords(fp, node);
928		if (error) {
929			destroy_node(node);
930			return (error);
931		}
932	}
933
934	node->first = (mtree_current != NULL) ? mtree_current : node;
935
936	if (last != NULL)
937		last->next = node;
938
939	if (node->type != S_IFDIR)
940		return (0);
941
942	if (!IS_DOT(node->name)) {
943		parent = node;
944		node = create_node(".", S_IFDIR, parent, parent);
945		if (node == NULL) {
946			last->next = NULL;
947			destroy_node(parent);
948			return (ENOMEM);
949		}
950		parent->child = node;
951		node->first = node;
952	}
953
954	assert(node != NULL);
955	assert(IS_DOT(node->name));
956	assert(node->first == node);
957
958	mtree_current = node;
959	if (mtree_root == NULL)
960		mtree_root = node;
961
962	return (0);
963}
964
965static int
966read_mtree_spec(FILE *fp)
967{
968	char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
969	char *cp;
970	int error;
971
972	error = read_word(fp, pathtmp, sizeof(pathtmp));
973	if (error)
974		goto out;
975	if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
976		error = errno;
977		goto out;
978	}
979	error = 0;
980
981	cp = strchr(pathspec, '/');
982	if (cp != NULL) {
983		/* Absolute pathname */
984		mtree_current = mtree_root;
985
986		do {
987			*cp++ = '\0';
988
989			/* Disallow '..' as a component. */
990			if (IS_DOTDOT(pathspec)) {
991				mtree_error("absolute path cannot contain "
992				    ".. component");
993				goto out;
994			}
995
996			/* Ignore multiple adjacent slashes and '.'. */
997			if (pathspec[0] != '\0' && !IS_DOT(pathspec))
998				error = read_mtree_spec1(fp, false, pathspec);
999			memmove(pathspec, cp, strlen(cp) + 1);
1000			cp = strchr(pathspec, '/');
1001		} while (!error && cp != NULL);
1002
1003		/* Disallow '.' and '..' as the last component. */
1004		if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1005			mtree_error("absolute path cannot contain . or .. "
1006			    "components");
1007			goto out;
1008		}
1009	}
1010
1011	/* Ignore absolute specfications that end with a slash. */
1012	if (!error && pathspec[0] != '\0')
1013		error = read_mtree_spec1(fp, true, pathspec);
1014
1015 out:
1016	skip_to(fp, "\n");
1017	(void)getc(fp);
1018	return (error);
1019}
1020
1021fsnode *
1022read_mtree(const char *fname, fsnode *node)
1023{
1024	struct mtree_fileinfo *fi;
1025	FILE *fp;
1026	int c, error;
1027
1028	/* We do not yet support nesting... */
1029	assert(node == NULL);
1030
1031	if (strcmp(fname, "-") == 0)
1032		fp = stdin;
1033	else {
1034		fp = fopen(fname, "r");
1035		if (fp == NULL)
1036			err(1, "Can't open `%s'", fname);
1037	}
1038
1039	error = mtree_file_push(fname, fp);
1040	if (error)
1041		goto out;
1042
1043	memset(&mtree_global, 0, sizeof(mtree_global));
1044	memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1045	mtree_global.inode = &mtree_global_inode;
1046	mtree_global_inode.nlink = 1;
1047	mtree_global_inode.st.st_nlink = 1;
1048	mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1049	    mtree_global_inode.st.st_mtime = time(NULL);
1050	errors = warnings = 0;
1051
1052	setgroupent(1);
1053	setpassent(1);
1054
1055	mtree_root = node;
1056	mtree_current = node;
1057	do {
1058		/* Start of a new line... */
1059		fi = SLIST_FIRST(&mtree_fileinfo);
1060		fi->line++;
1061
1062		error = skip_over(fp, " \t");
1063		if (error)
1064			break;
1065
1066		c = getc(fp);
1067		if (c == EOF) {
1068			error = ferror(fp) ? errno : -1;
1069			break;
1070		}
1071
1072		switch (c) {
1073		case '\n':		/* empty line */
1074			error = 0;
1075			break;
1076		case '#':		/* comment -- skip to end of line. */
1077			error = skip_to(fp, "\n");
1078			if (!error)
1079				(void)getc(fp);
1080			break;
1081		case '/':		/* special commands */
1082			error = read_mtree_command(fp);
1083			break;
1084		default:		/* specification */
1085			ungetc(c, fp);
1086			error = read_mtree_spec(fp);
1087			break;
1088		}
1089	} while (!error);
1090
1091	endpwent();
1092	endgrent();
1093
1094	if (error <= 0 && (errors || warnings)) {
1095		warnx("%u error(s) and %u warning(s) in mtree manifest",
1096		    errors, warnings);
1097		if (errors)
1098			exit(1);
1099	}
1100
1101 out:
1102	if (error > 0)
1103		errc(1, error, "Error reading mtree file");
1104
1105	if (fp != stdin)
1106		fclose(fp);
1107
1108	if (mtree_root != NULL)
1109		return (mtree_root);
1110
1111	/* Handle empty specifications. */
1112	node = create_node(".", S_IFDIR, NULL, &mtree_global);
1113	node->first = node;
1114	return (node);
1115}
1116