xref: /freebsd/usr.sbin/makefs/mtree.c (revision 6574b8ed19b093f0af09501d2c9676c28993cb97)
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;
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;
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 	}
288 
289 	sbuf_finish(sb);
290 	res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
291 	sbuf_delete(sb);
292 	if (res == NULL)
293 		errno = ENOMEM;
294 	return (res);
295 }
296 
297 static int
298 skip_over(FILE *fp, const char *cs)
299 {
300 	int c;
301 
302 	c = getc(fp);
303 	while (c != EOF && strchr(cs, c) != NULL)
304 		c = getc(fp);
305 	if (c != EOF) {
306 		ungetc(c, fp);
307 		return (0);
308 	}
309 	return (ferror(fp) ? errno : -1);
310 }
311 
312 static int
313 skip_to(FILE *fp, const char *cs)
314 {
315 	int c;
316 
317 	c = getc(fp);
318 	while (c != EOF && strchr(cs, c) == NULL)
319 		c = getc(fp);
320 	if (c != EOF) {
321 		ungetc(c, fp);
322 		return (0);
323 	}
324 	return (ferror(fp) ? errno : -1);
325 }
326 
327 static int
328 read_word(FILE *fp, char *buf, size_t bufsz)
329 {
330 	struct mtree_fileinfo *fi;
331 	size_t idx, qidx;
332 	int c, done, error, esc, qlvl;
333 
334 	if (bufsz == 0)
335 		return (EINVAL);
336 
337 	done = 0;
338 	esc = 0;
339 	idx = 0;
340 	qidx = -1;
341 	qlvl = 0;
342 	do {
343 		c = getc(fp);
344 		switch (c) {
345 		case EOF:
346 			buf[idx] = '\0';
347 			error = ferror(fp) ? errno : -1;
348 			if (error == -1)
349 				mtree_error("unexpected end of file");
350 			return (error);
351 		case '#':		/* comment -- skip to end of line. */
352 			if (!esc) {
353 				error = skip_to(fp, "\n");
354 				if (!error)
355 					continue;
356 			}
357 			break;
358 		case '\\':
359 			esc++;
360 			if (esc == 1)
361 				continue;
362 			break;
363 		case '`':
364 		case '\'':
365 		case '"':
366 			if (esc)
367 				break;
368 			if (qlvl == 0) {
369 				qlvl++;
370 				qidx = idx;
371 			} else if (c == buf[qidx]) {
372 				qlvl--;
373 				if (qlvl > 0) {
374 					do {
375 						qidx--;
376 					} while (buf[qidx] != '`' &&
377 					    buf[qidx] != '\'' &&
378 					    buf[qidx] != '"');
379 				} else
380 					qidx = -1;
381 			} else {
382 				qlvl++;
383 				qidx = idx;
384 			}
385 			break;
386 		case ' ':
387 		case '\t':
388 		case '\n':
389 			if (!esc && qlvl == 0) {
390 				ungetc(c, fp);
391 				c = '\0';
392 				done = 1;
393 				break;
394 			}
395 			if (c == '\n') {
396 				/*
397 				 * We going to eat the newline ourselves.
398 				 */
399 				if (qlvl > 0)
400 					mtree_warning("quoted word straddles "
401 					    "onto next line.");
402 				fi = SLIST_FIRST(&mtree_fileinfo);
403 				fi->line++;
404 			}
405 			break;
406 		case 'a':
407 			if (esc)
408 				c = '\a';
409 			break;
410 		case 'b':
411 			if (esc)
412 				c = '\b';
413 			break;
414 		case 'f':
415 			if (esc)
416 				c = '\f';
417 			break;
418 		case 'n':
419 			if (esc)
420 				c = '\n';
421 			break;
422 		case 'r':
423 			if (esc)
424 				c = '\r';
425 			break;
426 		case 't':
427 			if (esc)
428 				c = '\t';
429 			break;
430 		case 'v':
431 			if (esc)
432 				c = '\v';
433 			break;
434 		}
435 		buf[idx++] = c;
436 		esc = 0;
437 	} while (idx < bufsz && !done);
438 
439 	if (idx >= bufsz) {
440 		mtree_error("word too long to fit buffer (max %zu characters)",
441 		    bufsz);
442 		skip_to(fp, " \t\n");
443 	}
444 	return (0);
445 }
446 
447 static fsnode *
448 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
449 {
450 	fsnode *n;
451 
452 	n = calloc(1, sizeof(*n));
453 	if (n == NULL)
454 		return (NULL);
455 
456 	n->name = strdup(name);
457 	if (n->name == NULL) {
458 		free(n);
459 		return (NULL);
460 	}
461 
462 	n->type = (type == 0) ? global->type : type;
463 	n->parent = parent;
464 
465 	n->inode = calloc(1, sizeof(*n->inode));
466 	if (n->inode == NULL) {
467 		free(n->name);
468 		free(n);
469 		return (NULL);
470 	}
471 
472 	/* Assign global options/defaults. */
473 	bcopy(global->inode, n->inode, sizeof(*n->inode));
474 	n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
475 
476 	if (n->type == S_IFLNK)
477 		n->symlink = global->symlink;
478 	else if (n->type == S_IFREG)
479 		n->contents = global->contents;
480 
481 	return (n);
482 }
483 
484 static void
485 destroy_node(fsnode *n)
486 {
487 
488 	assert(n != NULL);
489 	assert(n->name != NULL);
490 	assert(n->inode != NULL);
491 
492 	free(n->inode);
493 	free(n->name);
494 	free(n);
495 }
496 
497 static int
498 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
499     intmax_t max)
500 {
501 	char *end;
502 	intmax_t val;
503 
504 	val = strtoimax(tok, &end, base);
505 	if (end == tok || end[0] != '\0')
506 		return (EINVAL);
507 	if (val < min || val > max)
508 		return (EDOM);
509 	*res = val;
510 	return (0);
511 }
512 
513 static int
514 read_mtree_keywords(FILE *fp, fsnode *node)
515 {
516 	char keyword[PATH_MAX];
517 	char *name, *p, *value;
518 	gid_t gid;
519 	uid_t uid;
520 	struct stat *st, sb;
521 	intmax_t num;
522 	u_long flset, flclr;
523 	int error, istemp, type;
524 
525 	st = &node->inode->st;
526 	do {
527 		error = skip_over(fp, " \t");
528 		if (error)
529 			break;
530 
531 		error = read_word(fp, keyword, sizeof(keyword));
532 		if (error)
533 			break;
534 
535 		if (keyword[0] == '\0')
536 			break;
537 
538 		value = strchr(keyword, '=');
539 		if (value != NULL)
540 			*value++ = '\0';
541 
542 		/*
543 		 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
544 		 * certain conditions:
545 		 *   EINVAL -	Value provided for a keyword that does
546 		 *		not take a value. The value is ignored.
547 		 *   ENOATTR -	Value missing for a keyword that needs
548 		 *		a value. The keyword is ignored.
549 		 *   ENOSYS -	Unsupported keyword encountered. The
550 		 *		keyword is ignored.
551 		 *   ENXIO -	Value provided for a keyword that does
552 		 *		not take a value. The value is ignored.
553 		 */
554 		switch (keyword[0]) {
555 		case 'c':
556 			if (strcmp(keyword, "contents") == 0) {
557 				if (value == NULL) {
558 					error = ENOATTR;
559 					break;
560 				}
561 				node->contents = strdup(value);
562 			} else
563 				error = ENOSYS;
564 			break;
565 		case 'f':
566 			if (strcmp(keyword, "flags") == 0) {
567 				if (value == NULL) {
568 					error = ENOATTR;
569 					break;
570 				}
571 				flset = flclr = 0;
572 				if (!strtofflags(&value, &flset, &flclr)) {
573 					st->st_flags &= ~flclr;
574 					st->st_flags |= flset;
575 				} else
576 					error = errno;
577 			} else
578 				error = ENOSYS;
579 			break;
580 		case 'g':
581 			if (strcmp(keyword, "gid") == 0) {
582 				if (value == NULL) {
583 					error = ENOATTR;
584 					break;
585 				}
586 				error = read_number(value, 10, &num,
587 				    0, UINT_MAX);
588 				if (!error)
589 					st->st_gid = num;
590 			} else if (strcmp(keyword, "gname") == 0) {
591 				if (value == NULL) {
592 					error = ENOATTR;
593 					break;
594 				}
595 				if (gid_from_group(value, &gid) == 0)
596 					st->st_gid = gid;
597 				else
598 					error = EINVAL;
599 			} else
600 				error = ENOSYS;
601 			break;
602 		case 'l':
603 			if (strcmp(keyword, "link") == 0) {
604 				if (value == NULL) {
605 					error = ENOATTR;
606 					break;
607 				}
608 				node->symlink = strdup(value);
609 			} else
610 				error = ENOSYS;
611 			break;
612 		case 'm':
613 			if (strcmp(keyword, "mode") == 0) {
614 				if (value == NULL) {
615 					error = ENOATTR;
616 					break;
617 				}
618 				if (value[0] >= '0' && value[0] <= '9') {
619 					error = read_number(value, 8, &num,
620 					    0, 07777);
621 					if (!error) {
622 						st->st_mode &= S_IFMT;
623 						st->st_mode |= num;
624 					}
625 				} else {
626 					/* Symbolic mode not supported. */
627 					error = EINVAL;
628 					break;
629 				}
630 			} else
631 				error = ENOSYS;
632 			break;
633 		case 'o':
634 			if (strcmp(keyword, "optional") == 0) {
635 				if (value != NULL)
636 					error = ENXIO;
637 				node->flags |= FSNODE_F_OPTIONAL;
638 			} else
639 				error = ENOSYS;
640 			break;
641 		case 's':
642 			if (strcmp(keyword, "size") == 0) {
643 				if (value == NULL) {
644 					error = ENOATTR;
645 					break;
646 				}
647 				error = read_number(value, 10, &num,
648 				    0, INTMAX_MAX);
649 				if (!error)
650 					st->st_size = num;
651 			} else
652 				error = ENOSYS;
653 			break;
654 		case 't':
655 			if (strcmp(keyword, "time") == 0) {
656 				if (value == NULL) {
657 					error = ENOATTR;
658 					break;
659 				}
660 				p = strchr(value, '.');
661 				if (p != NULL)
662 					*p++ = '\0';
663 				error = read_number(value, 10, &num, 0,
664 				    INTMAX_MAX);
665 				if (error)
666 					break;
667 				st->st_atime = num;
668 				st->st_ctime = num;
669 				st->st_mtime = num;
670 				if (p == NULL)
671 					break;
672 				error = read_number(p, 10, &num, 0,
673 				    INTMAX_MAX);
674 				if (error)
675 					break;
676 				if (num != 0)
677 					error = EINVAL;
678 			} else if (strcmp(keyword, "type") == 0) {
679 				if (value == NULL) {
680 					error = ENOATTR;
681 					break;
682 				}
683 				if (strcmp(value, "dir") == 0)
684 					node->type = S_IFDIR;
685 				else if (strcmp(value, "file") == 0)
686 					node->type = S_IFREG;
687 				else if (strcmp(value, "link") == 0)
688 					node->type = S_IFLNK;
689 				else
690 					error = EINVAL;
691 			} else
692 				error = ENOSYS;
693 			break;
694 		case 'u':
695 			if (strcmp(keyword, "uid") == 0) {
696 				if (value == NULL) {
697 					error = ENOATTR;
698 					break;
699 				}
700 				error = read_number(value, 10, &num,
701 				    0, UINT_MAX);
702 				if (!error)
703 					st->st_uid = num;
704 			} else if (strcmp(keyword, "uname") == 0) {
705 				if (value == NULL) {
706 					error = ENOATTR;
707 					break;
708 				}
709 				if (uid_from_user(value, &uid) == 0)
710 					st->st_uid = uid;
711 				else
712 					error = EINVAL;
713 			} else
714 				error = ENOSYS;
715 			break;
716 		default:
717 			error = ENOSYS;
718 			break;
719 		}
720 
721 		switch (error) {
722 		case EINVAL:
723 			mtree_error("%s: invalid value '%s'", keyword, value);
724 			break;
725 		case ENOATTR:
726 			mtree_error("%s: keyword needs a value", keyword);
727 			break;
728 		case ENOSYS:
729 			mtree_warning("%s: unsupported keyword", keyword);
730 			break;
731 		case ENXIO:
732 			mtree_error("%s: keyword does not take a value",
733 			    keyword);
734 			break;
735 		}
736 	} while (1);
737 
738 	if (error)
739 		return (error);
740 
741 	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
742 
743 	/* Nothing more to do for the global defaults. */
744 	if (node->name == NULL)
745 		return (0);
746 
747 	/*
748 	 * Be intelligent about the file type.
749 	 */
750 	if (node->contents != NULL) {
751 		if (node->symlink != NULL) {
752 			mtree_error("%s: both link and contents keywords "
753 			    "defined", node->name);
754 			return (0);
755 		}
756 		type = S_IFREG;
757 	} else if (node->type != 0) {
758 		type = node->type;
759 		if (type == S_IFREG) {
760 			/* the named path is the default contents */
761 			node->contents = mtree_file_path(node);
762 		}
763 	} else
764 		type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
765 
766 	if (node->type == 0)
767 		node->type = type;
768 
769 	if (node->type != type) {
770 		mtree_error("%s: file type and defined keywords to not match",
771 		    node->name);
772 		return (0);
773 	}
774 
775 	st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
776 
777 	if (node->contents == NULL)
778 		return (0);
779 
780 	name = mtree_resolve(node->contents, &istemp);
781 	if (name == NULL)
782 		return (errno);
783 
784 	if (stat(name, &sb) != 0) {
785 		mtree_error("%s: contents file '%s' not found", node->name,
786 		    name);
787 		free(name);
788 		return (0);
789 	}
790 
791 	/*
792          * Check for hardlinks. If the contents key is used, then the check
793          * will only trigger if the contents file is a link even if it is used
794          * by more than one file
795 	 */
796 	if (sb.st_nlink > 1) {
797 		fsinode *curino;
798 
799 		st->st_ino = sb.st_ino;
800 		st->st_dev = sb.st_dev;
801 		curino = link_check(node->inode);
802 		if (curino != NULL) {
803 			free(node->inode);
804 			node->inode = curino;
805 			node->inode->nlink++;
806 		}
807 	}
808 
809 	free(node->contents);
810 	node->contents = name;
811 	st->st_size = sb.st_size;
812 	return (0);
813 }
814 
815 static int
816 read_mtree_command(FILE *fp)
817 {
818 	char cmd[10];
819 	int error;
820 
821 	error = read_word(fp, cmd, sizeof(cmd));
822 	if (error)
823 		goto out;
824 
825 	error = read_mtree_keywords(fp, &mtree_global);
826 
827  out:
828 	skip_to(fp, "\n");
829 	(void)getc(fp);
830 	return (error);
831 }
832 
833 static int
834 read_mtree_spec1(FILE *fp, bool def, const char *name)
835 {
836 	fsnode *last, *node, *parent;
837 	u_int type;
838 	int error;
839 
840 	assert(name[0] != '\0');
841 
842 	/*
843 	 * Treat '..' specially, because it only changes our current
844 	 * directory. We don't create a node for it. We simply ignore
845 	 * any keywords that may appear on the line as well.
846 	 * Going up a directory is a little non-obvious. A directory
847 	 * node has a corresponding '.' child. The parent of '.' is
848 	 * not the '.' node of the parent directory, but the directory
849 	 * node within the parent to which the child relates. However,
850 	 * going up a directory means we need to find the '.' node to
851 	 * which the directoy node is linked.  This we can do via the
852 	 * first * pointer, because '.' is always the first entry in a
853 	 * directory.
854 	 */
855 	if (IS_DOTDOT(name)) {
856 		/* This deals with NULL pointers as well. */
857 		if (mtree_current == mtree_root) {
858 			mtree_warning("ignoring .. in root directory");
859 			return (0);
860 		}
861 
862 		node = mtree_current;
863 
864 		assert(node != NULL);
865 		assert(IS_DOT(node->name));
866 		assert(node->first == node);
867 
868 		/* Get the corresponding directory node in the parent. */
869 		node = mtree_current->parent;
870 
871 		assert(node != NULL);
872 		assert(!IS_DOT(node->name));
873 
874 		node = node->first;
875 
876 		assert(node != NULL);
877 		assert(IS_DOT(node->name));
878 		assert(node->first == node);
879 
880 		mtree_current = node;
881 		return (0);
882 	}
883 
884 	/*
885 	 * If we don't have a current directory and the first specification
886 	 * (either implicit or defined) is not '.', then we need to create
887 	 * a '.' node first (using a recursive call).
888 	 */
889 	if (!IS_DOT(name) && mtree_current == NULL) {
890 		error = read_mtree_spec1(fp, false, ".");
891 		if (error)
892 			return (error);
893 	}
894 
895 	/*
896 	 * Lookup the name in the current directory (if we have a current
897 	 * directory) to make sure we do not create multiple nodes for the
898 	 * same component. For non-definitions, if we find a node with the
899 	 * same name, simply change the current directory. For definitions
900 	 * more happens.
901 	 */
902 	last = NULL;
903 	node = mtree_current;
904 	while (node != NULL) {
905 		assert(node->first == mtree_current);
906 
907 		if (strcmp(name, node->name) == 0) {
908 			if (def == true) {
909 				if (!dupsok)
910 					mtree_error(
911 					    "duplicate definition of %s",
912 					    name);
913 				else
914 					mtree_warning(
915 					    "duplicate definition of %s",
916 					    name);
917 				return (0);
918 			}
919 
920 			if (node->type != S_IFDIR) {
921 				mtree_error("%s is not a directory", name);
922 				return (0);
923 			}
924 
925 			assert(!IS_DOT(name));
926 
927 			node = node->child;
928 
929 			assert(node != NULL);
930 			assert(IS_DOT(node->name));
931 
932 			mtree_current = node;
933 			return (0);
934 		}
935 
936 		last = node;
937 		node = last->next;
938 	}
939 
940 	parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
941 	type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
942 	node = create_node(name, type, parent, &mtree_global);
943 	if (node == NULL)
944 		return (ENOMEM);
945 
946 	if (def == true) {
947 		error = read_mtree_keywords(fp, node);
948 		if (error) {
949 			destroy_node(node);
950 			return (error);
951 		}
952 	}
953 
954 	node->first = (mtree_current != NULL) ? mtree_current : node;
955 
956 	if (last != NULL)
957 		last->next = node;
958 
959 	if (node->type != S_IFDIR)
960 		return (0);
961 
962 	if (!IS_DOT(node->name)) {
963 		parent = node;
964 		node = create_node(".", S_IFDIR, parent, parent);
965 		if (node == NULL) {
966 			last->next = NULL;
967 			destroy_node(parent);
968 			return (ENOMEM);
969 		}
970 		parent->child = node;
971 		node->first = node;
972 	}
973 
974 	assert(node != NULL);
975 	assert(IS_DOT(node->name));
976 	assert(node->first == node);
977 
978 	mtree_current = node;
979 	if (mtree_root == NULL)
980 		mtree_root = node;
981 
982 	return (0);
983 }
984 
985 static int
986 read_mtree_spec(FILE *fp)
987 {
988 	char pathspec[PATH_MAX];
989 	char *cp;
990 	int error;
991 
992 	error = read_word(fp, pathspec, sizeof(pathspec));
993 	if (error)
994 		goto out;
995 
996 	cp = strchr(pathspec, '/');
997 	if (cp != NULL) {
998 		/* Absolute pathname */
999 		mtree_current = mtree_root;
1000 
1001 		do {
1002 			*cp++ = '\0';
1003 
1004 			/* Disallow '..' as a component. */
1005 			if (IS_DOTDOT(pathspec)) {
1006 				mtree_error("absolute path cannot contain "
1007 				    ".. component");
1008 				goto out;
1009 			}
1010 
1011 			/* Ignore multiple adjacent slashes and '.'. */
1012 			if (pathspec[0] != '\0' && !IS_DOT(pathspec))
1013 				error = read_mtree_spec1(fp, false, pathspec);
1014 			memmove(pathspec, cp, strlen(cp) + 1);
1015 			cp = strchr(pathspec, '/');
1016 		} while (!error && cp != NULL);
1017 
1018 		/* Disallow '.' and '..' as the last component. */
1019 		if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1020 			mtree_error("absolute path cannot contain . or .. "
1021 			    "components");
1022 			goto out;
1023 		}
1024 	}
1025 
1026 	/* Ignore absolute specfications that end with a slash. */
1027 	if (!error && pathspec[0] != '\0')
1028 		error = read_mtree_spec1(fp, true, pathspec);
1029 
1030  out:
1031 	skip_to(fp, "\n");
1032 	(void)getc(fp);
1033 	return (error);
1034 }
1035 
1036 fsnode *
1037 read_mtree(const char *fname, fsnode *node)
1038 {
1039 	struct mtree_fileinfo *fi;
1040 	FILE *fp;
1041 	int c, error;
1042 
1043 	/* We do not yet support nesting... */
1044 	assert(node == NULL);
1045 
1046 	if (strcmp(fname, "-") == 0)
1047 		fp = stdin;
1048 	else {
1049 		fp = fopen(fname, "r");
1050 		if (fp == NULL)
1051 			err(1, "Can't open `%s'", fname);
1052 	}
1053 
1054 	error = mtree_file_push(fname, fp);
1055 	if (error)
1056 		goto out;
1057 
1058 	bzero(&mtree_global, sizeof(mtree_global));
1059 	bzero(&mtree_global_inode, sizeof(mtree_global_inode));
1060 	mtree_global.inode = &mtree_global_inode;
1061 	mtree_global_inode.nlink = 1;
1062 	mtree_global_inode.st.st_nlink = 1;
1063 	mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1064 	    mtree_global_inode.st.st_mtime = time(NULL);
1065 	errors = warnings = 0;
1066 
1067 	setgroupent(1);
1068 	setpassent(1);
1069 
1070 	mtree_root = node;
1071 	mtree_current = node;
1072 	do {
1073 		/* Start of a new line... */
1074 		fi = SLIST_FIRST(&mtree_fileinfo);
1075 		fi->line++;
1076 
1077 		error = skip_over(fp, " \t");
1078 		if (error)
1079 			break;
1080 
1081 		c = getc(fp);
1082 		if (c == EOF) {
1083 			error = ferror(fp) ? errno : -1;
1084 			break;
1085 		}
1086 
1087 		switch (c) {
1088 		case '\n':		/* empty line */
1089 			error = 0;
1090 			break;
1091 		case '#':		/* comment -- skip to end of line. */
1092 			error = skip_to(fp, "\n");
1093 			if (!error)
1094 				(void)getc(fp);
1095 			break;
1096 		case '/':		/* special commands */
1097 			error = read_mtree_command(fp);
1098 			break;
1099 		default:		/* specification */
1100 			ungetc(c, fp);
1101 			error = read_mtree_spec(fp);
1102 			break;
1103 		}
1104 	} while (!error);
1105 
1106 	endpwent();
1107 	endgrent();
1108 
1109 	if (error <= 0 && (errors || warnings)) {
1110 		warnx("%u error(s) and %u warning(s) in mtree manifest",
1111 		    errors, warnings);
1112 		if (errors)
1113 			exit(1);
1114 	}
1115 
1116  out:
1117 	if (error > 0)
1118 		errc(1, error, "Error reading mtree file");
1119 
1120 	if (fp != stdin)
1121 		fclose(fp);
1122 
1123 	if (mtree_root != NULL)
1124 		return (mtree_root);
1125 
1126 	/* Handle empty specifications. */
1127 	node = create_node(".", S_IFDIR, NULL, &mtree_global);
1128 	node->first = node;
1129 	return (node);
1130 }
1131