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