2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2011 Marcel Moolenaar
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
28 #if HAVE_NBTOOL_CONFIG_H
29 #include "nbtool_config.h"
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/queue.h>
39 #include <sys/types.h>
61 #define ENOATTR ENODATA
64 #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0')
65 #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
67 struct mtree_fileinfo {
68 SLIST_ENTRY(mtree_fileinfo) next;
74 /* Global state used while parsing. */
75 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
76 SLIST_HEAD_INITIALIZER(mtree_fileinfo);
77 static fsnode *mtree_root;
78 static fsnode *mtree_current;
79 static fsnode mtree_global;
80 static fsinode mtree_global_inode;
81 static u_int errors, warnings;
83 static void mtree_error(const char *, ...) __printflike(1, 2);
84 static void mtree_warning(const char *, ...) __printflike(1, 2);
87 mtree_file_push(const char *name, FILE *fp)
89 struct mtree_fileinfo *fi;
91 fi = emalloc(sizeof(*fi));
92 if (strcmp(name, "-") == 0)
93 fi->name = estrdup("(stdin)");
95 fi->name = estrdup(name);
96 if (fi->name == NULL) {
104 SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
109 mtree_print(const char *msgtype, const char *fmt, va_list ap)
111 struct mtree_fileinfo *fi;
113 if (msgtype != NULL) {
114 fi = SLIST_FIRST(&mtree_fileinfo);
116 fprintf(stderr, "%s:%u: ", fi->name, fi->line);
117 fprintf(stderr, "%s: ", msgtype);
119 vfprintf(stderr, fmt, ap);
123 mtree_error(const char *fmt, ...)
128 mtree_print("error", fmt, ap);
136 mtree_warning(const char *fmt, ...)
141 mtree_print("warning", fmt, ap);
148 #ifndef MAKEFS_MAX_TREE_DEPTH
149 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
152 /* construct path to node->name */
154 mtree_file_path(fsnode *node)
158 char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
162 rp[depth] = node->name;
163 for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
164 pnode = pnode->parent) {
165 if (strcmp(pnode->name, ".") == 0)
167 rp[++depth] = pnode->name;
170 sb = sbuf_new_auto();
176 sbuf_cat(sb, rp[depth--]);
179 sbuf_cat(sb, rp[depth]);
181 res = estrdup(sbuf_data(sb));
189 /* mtree_resolve() sets errno to indicate why NULL was returned. */
191 mtree_resolve(const char *spec, int *istemp)
194 char *res, *var = NULL;
195 const char *base, *p, *v;
197 int c, error, quoted, subst;
205 c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
206 *istemp = (c == '`') ? 1 : 0;
207 subst = (c == '`' || c == '"') ? 1 : 0;
208 quoted = (subst || c == '\'') ? 1 : 0;
211 res = estrdup(spec + quoted);
217 sb = sbuf_new_auto();
227 p = strchr(base, '$');
229 sbuf_bcat(sb, base, len);
234 /* The following is safe. spec always starts with a quote. */
238 sbuf_bcat(sb, base, p - base);
251 /* Handle ${X} vs $X. */
259 len -= (p + 1) - base;
268 var = ecalloc(p - v, 1);
269 memcpy(var, v + 1, p - v - 1);
270 if (strcmp(var, ".CURDIR") == 0) {
271 res = getcwd(NULL, 0);
274 } else if (strcmp(var, ".PROG") == 0) {
275 res = estrdup(getprogname());
295 res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
303 skip_over(FILE *fp, const char *cs)
308 while (c != EOF && strchr(cs, c) != NULL)
314 return (ferror(fp) ? errno : -1);
318 skip_to(FILE *fp, const char *cs)
323 while (c != EOF && strchr(cs, c) == NULL)
329 return (ferror(fp) ? errno : -1);
333 read_word(FILE *fp, char *buf, size_t bufsz)
335 struct mtree_fileinfo *fi;
337 int c, done, error, esc, qlvl;
352 error = ferror(fp) ? errno : -1;
354 mtree_error("unexpected end of file");
356 case '#': /* comment -- skip to end of line. */
358 error = skip_to(fp, "\n");
374 } else if (c == buf[qidx]) {
379 } while (buf[qidx] != '`' &&
392 if (!esc && qlvl == 0) {
400 * We going to eat the newline ourselves.
403 mtree_warning("quoted word straddles "
405 fi = SLIST_FIRST(&mtree_fileinfo);
416 } while (idx < bufsz && !done);
419 mtree_error("word too long to fit buffer (max %zu characters)",
421 skip_to(fp, " \t\n");
427 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
431 n = ecalloc(1, sizeof(*n));
432 n->name = estrdup(name);
433 n->type = (type == 0) ? global->type : type;
436 n->inode = ecalloc(1, sizeof(*n->inode));
438 /* Assign global options/defaults. */
439 memcpy(n->inode, global->inode, sizeof(*n->inode));
440 n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
442 if (n->type == S_IFLNK)
443 n->symlink = global->symlink;
444 else if (n->type == S_IFREG)
445 n->contents = global->contents;
451 destroy_node(fsnode *n)
455 assert(n->name != NULL);
456 assert(n->inode != NULL);
464 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
470 val = strtoimax(tok, &end, base);
471 if (end == tok || end[0] != '\0')
473 if (val < min || val > max)
480 read_mtree_keywords(FILE *fp, fsnode *node)
482 char keyword[PATH_MAX];
483 char *name, *p, *value;
492 st = &node->inode->st;
494 error = skip_over(fp, " \t");
498 error = read_word(fp, keyword, sizeof(keyword));
502 if (keyword[0] == '\0')
505 value = strchr(keyword, '=');
510 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
511 * certain conditions:
512 * EINVAL - Value provided for a keyword that does
513 * not take a value. The value is ignored.
514 * ENOATTR - Value missing for a keyword that needs
515 * a value. The keyword is ignored.
516 * ENOSYS - Unsupported keyword encountered. The
517 * keyword is ignored.
518 * ENXIO - Value provided for a keyword that does
519 * not take a value. The value is ignored.
521 switch (keyword[0]) {
523 if (strcmp(keyword, "contents") == 0) {
528 node->contents = estrdup(value);
533 if (strcmp(keyword, "flags") == 0) {
539 #if HAVE_STRUCT_STAT_ST_FLAGS
540 if (!strtofflags(&value, &flset, &flclr)) {
541 st->st_flags &= ~flclr;
542 st->st_flags |= flset;
550 if (strcmp(keyword, "gid") == 0) {
555 error = read_number(value, 10, &num,
559 } else if (strcmp(keyword, "gname") == 0) {
564 if (gid_from_group(value, &gid) == 0)
572 if (strcmp(keyword, "link") == 0) {
577 node->symlink = emalloc(strlen(value) + 1);
578 if (node->symlink == NULL) {
582 if (strunvis(node->symlink, value) < 0) {
590 if (strcmp(keyword, "mode") == 0) {
595 if (value[0] >= '0' && value[0] <= '9') {
596 error = read_number(value, 8, &num,
599 st->st_mode &= S_IFMT;
603 /* Symbolic mode not supported. */
611 if (strcmp(keyword, "optional") == 0) {
614 node->flags |= FSNODE_F_OPTIONAL;
619 if (strcmp(keyword, "size") == 0) {
624 error = read_number(value, 10, &num,
632 if (strcmp(keyword, "time") == 0) {
637 p = strchr(value, '.');
640 error = read_number(value, 10, &num, 0,
647 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
650 error = read_number(p, 10, &num, 0,
654 st->st_atimensec = num;
655 st->st_ctimensec = num;
656 st->st_mtimensec = num;
658 } else if (strcmp(keyword, "type") == 0) {
663 if (strcmp(value, "dir") == 0)
664 node->type = S_IFDIR;
665 else if (strcmp(value, "file") == 0)
666 node->type = S_IFREG;
667 else if (strcmp(value, "link") == 0)
668 node->type = S_IFLNK;
675 if (strcmp(keyword, "uid") == 0) {
680 error = read_number(value, 10, &num,
684 } else if (strcmp(keyword, "uname") == 0) {
689 if (uid_from_user(value, &uid) == 0)
703 mtree_error("%s: invalid value '%s'", keyword, value);
706 mtree_error("%s: keyword needs a value", keyword);
709 mtree_warning("%s: unsupported keyword", keyword);
712 mtree_error("%s: keyword does not take a value",
721 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
723 /* Nothing more to do for the global defaults. */
724 if (node->name == NULL)
728 * Be intelligent about the file type.
730 if (node->contents != NULL) {
731 if (node->symlink != NULL) {
732 mtree_error("%s: both link and contents keywords "
733 "defined", node->name);
737 } else if (node->type != 0) {
739 if (type == S_IFREG) {
740 /* the named path is the default contents */
741 node->contents = mtree_file_path(node);
744 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
749 if (node->type != type) {
750 mtree_error("%s: file type and defined keywords to not match",
755 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
757 if (node->contents == NULL)
760 name = mtree_resolve(node->contents, &istemp);
764 if (stat(name, &sb) != 0) {
765 mtree_error("%s: contents file '%s' not found", node->name,
772 * Check for hardlinks. If the contents key is used, then the check
773 * will only trigger if the contents file is a link even if it is used
774 * by more than one file
776 if (sb.st_nlink > 1) {
779 st->st_ino = sb.st_ino;
780 st->st_dev = sb.st_dev;
781 curino = link_check(node->inode);
782 if (curino != NULL) {
784 node->inode = curino;
785 node->inode->nlink++;
789 free(node->contents);
790 node->contents = name;
791 st->st_size = sb.st_size;
796 read_mtree_command(FILE *fp)
801 error = read_word(fp, cmd, sizeof(cmd));
805 error = read_mtree_keywords(fp, &mtree_global);
814 read_mtree_spec1(FILE *fp, bool def, const char *name)
816 fsnode *last, *node, *parent;
820 assert(name[0] != '\0');
823 * Treat '..' specially, because it only changes our current
824 * directory. We don't create a node for it. We simply ignore
825 * any keywords that may appear on the line as well.
826 * Going up a directory is a little non-obvious. A directory
827 * node has a corresponding '.' child. The parent of '.' is
828 * not the '.' node of the parent directory, but the directory
829 * node within the parent to which the child relates. However,
830 * going up a directory means we need to find the '.' node to
831 * which the directoy node is linked. This we can do via the
832 * first * pointer, because '.' is always the first entry in a
835 if (IS_DOTDOT(name)) {
836 /* This deals with NULL pointers as well. */
837 if (mtree_current == mtree_root) {
838 mtree_warning("ignoring .. in root directory");
842 node = mtree_current;
844 assert(node != NULL);
845 assert(IS_DOT(node->name));
846 assert(node->first == node);
848 /* Get the corresponding directory node in the parent. */
849 node = mtree_current->parent;
851 assert(node != NULL);
852 assert(!IS_DOT(node->name));
856 assert(node != NULL);
857 assert(IS_DOT(node->name));
858 assert(node->first == node);
860 mtree_current = node;
865 * If we don't have a current directory and the first specification
866 * (either implicit or defined) is not '.', then we need to create
867 * a '.' node first (using a recursive call).
869 if (!IS_DOT(name) && mtree_current == NULL) {
870 error = read_mtree_spec1(fp, false, ".");
876 * Lookup the name in the current directory (if we have a current
877 * directory) to make sure we do not create multiple nodes for the
878 * same component. For non-definitions, if we find a node with the
879 * same name, simply change the current directory. For definitions
883 node = mtree_current;
884 while (node != NULL) {
885 assert(node->first == mtree_current);
887 if (strcmp(name, node->name) == 0) {
891 "duplicate definition of %s",
895 "duplicate definition of %s",
900 if (node->type != S_IFDIR) {
901 mtree_error("%s is not a directory", name);
905 assert(!IS_DOT(name));
909 assert(node != NULL);
910 assert(IS_DOT(node->name));
912 mtree_current = node;
920 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
921 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
922 node = create_node(name, type, parent, &mtree_global);
927 error = read_mtree_keywords(fp, node);
934 node->first = (mtree_current != NULL) ? mtree_current : node;
939 if (node->type != S_IFDIR)
942 if (!IS_DOT(node->name)) {
944 node = create_node(".", S_IFDIR, parent, parent);
947 destroy_node(parent);
950 parent->child = node;
954 assert(node != NULL);
955 assert(IS_DOT(node->name));
956 assert(node->first == node);
958 mtree_current = node;
959 if (mtree_root == NULL)
966 read_mtree_spec(FILE *fp)
968 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
972 error = read_word(fp, pathtmp, sizeof(pathtmp));
975 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
981 cp = strchr(pathspec, '/');
983 /* Absolute pathname */
984 mtree_current = mtree_root;
989 /* Disallow '..' as a component. */
990 if (IS_DOTDOT(pathspec)) {
991 mtree_error("absolute path cannot contain "
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);
1003 /* Disallow '.' and '..' as the last component. */
1004 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1005 mtree_error("absolute path cannot contain . or .. "
1011 /* Ignore absolute specfications that end with a slash. */
1012 if (!error && pathspec[0] != '\0')
1013 error = read_mtree_spec1(fp, true, pathspec);
1022 read_mtree(const char *fname, fsnode *node)
1024 struct mtree_fileinfo *fi;
1028 /* We do not yet support nesting... */
1029 assert(node == NULL);
1031 if (strcmp(fname, "-") == 0)
1034 fp = fopen(fname, "r");
1036 err(1, "Can't open `%s'", fname);
1039 error = mtree_file_push(fname, fp);
1043 memset(&mtree_global, 0, sizeof(mtree_global));
1044 memset(&mtree_global_inode, 0, 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;
1056 mtree_current = node;
1058 /* Start of a new line... */
1059 fi = SLIST_FIRST(&mtree_fileinfo);
1062 error = skip_over(fp, " \t");
1068 error = ferror(fp) ? errno : -1;
1073 case '\n': /* empty line */
1076 case '#': /* comment -- skip to end of line. */
1077 error = skip_to(fp, "\n");
1081 case '/': /* special commands */
1082 error = read_mtree_command(fp);
1084 default: /* specification */
1086 error = read_mtree_spec(fp);
1094 if (error <= 0 && (errors || warnings)) {
1095 warnx("%u error(s) and %u warning(s) in mtree manifest",
1103 errc(1, error, "Error reading mtree file");
1108 if (mtree_root != NULL)
1109 return (mtree_root);
1111 /* Handle empty specifications. */
1112 node = create_node(".", S_IFDIR, NULL, &mtree_global);