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