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