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