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