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