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,
649 error = read_number(p, 10, &num, 0,
655 } else if (strcmp(keyword, "type") == 0) {
660 if (strcmp(value, "dir") == 0)
661 node->type = S_IFDIR;
662 else if (strcmp(value, "file") == 0)
663 node->type = S_IFREG;
664 else if (strcmp(value, "link") == 0)
665 node->type = S_IFLNK;
672 if (strcmp(keyword, "uid") == 0) {
677 error = read_number(value, 10, &num,
681 } else if (strcmp(keyword, "uname") == 0) {
686 if (uid_from_user(value, &uid) == 0)
700 mtree_error("%s: invalid value '%s'", keyword, value);
703 mtree_error("%s: keyword needs a value", keyword);
706 mtree_warning("%s: unsupported keyword", keyword);
709 mtree_error("%s: keyword does not take a value",
718 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
720 /* Nothing more to do for the global defaults. */
721 if (node->name == NULL)
725 * Be intelligent about the file type.
727 if (node->contents != NULL) {
728 if (node->symlink != NULL) {
729 mtree_error("%s: both link and contents keywords "
730 "defined", node->name);
734 } else if (node->type != 0) {
736 if (type == S_IFREG) {
737 /* the named path is the default contents */
738 node->contents = mtree_file_path(node);
741 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
746 if (node->type != type) {
747 mtree_error("%s: file type and defined keywords to not match",
752 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
754 if (node->contents == NULL)
757 name = mtree_resolve(node->contents, &istemp);
761 if (stat(name, &sb) != 0) {
762 mtree_error("%s: contents file '%s' not found", node->name,
769 * Check for hardlinks. If the contents key is used, then the check
770 * will only trigger if the contents file is a link even if it is used
771 * by more than one file
773 if (sb.st_nlink > 1) {
776 st->st_ino = sb.st_ino;
777 st->st_dev = sb.st_dev;
778 curino = link_check(node->inode);
779 if (curino != NULL) {
781 node->inode = curino;
782 node->inode->nlink++;
786 free(node->contents);
787 node->contents = name;
788 st->st_size = sb.st_size;
793 read_mtree_command(FILE *fp)
798 error = read_word(fp, cmd, sizeof(cmd));
802 error = read_mtree_keywords(fp, &mtree_global);
811 read_mtree_spec1(FILE *fp, bool def, const char *name)
813 fsnode *last, *node, *parent;
817 assert(name[0] != '\0');
820 * Treat '..' specially, because it only changes our current
821 * directory. We don't create a node for it. We simply ignore
822 * any keywords that may appear on the line as well.
823 * Going up a directory is a little non-obvious. A directory
824 * node has a corresponding '.' child. The parent of '.' is
825 * not the '.' node of the parent directory, but the directory
826 * node within the parent to which the child relates. However,
827 * going up a directory means we need to find the '.' node to
828 * which the directoy node is linked. This we can do via the
829 * first * pointer, because '.' is always the first entry in a
832 if (IS_DOTDOT(name)) {
833 /* This deals with NULL pointers as well. */
834 if (mtree_current == mtree_root) {
835 mtree_warning("ignoring .. in root directory");
839 node = mtree_current;
841 assert(node != NULL);
842 assert(IS_DOT(node->name));
843 assert(node->first == node);
845 /* Get the corresponding directory node in the parent. */
846 node = mtree_current->parent;
848 assert(node != NULL);
849 assert(!IS_DOT(node->name));
853 assert(node != NULL);
854 assert(IS_DOT(node->name));
855 assert(node->first == node);
857 mtree_current = node;
862 * If we don't have a current directory and the first specification
863 * (either implicit or defined) is not '.', then we need to create
864 * a '.' node first (using a recursive call).
866 if (!IS_DOT(name) && mtree_current == NULL) {
867 error = read_mtree_spec1(fp, false, ".");
873 * Lookup the name in the current directory (if we have a current
874 * directory) to make sure we do not create multiple nodes for the
875 * same component. For non-definitions, if we find a node with the
876 * same name, simply change the current directory. For definitions
880 node = mtree_current;
881 while (node != NULL) {
882 assert(node->first == mtree_current);
884 if (strcmp(name, node->name) == 0) {
888 "duplicate definition of %s",
892 "duplicate definition of %s",
897 if (node->type != S_IFDIR) {
898 mtree_error("%s is not a directory", name);
902 assert(!IS_DOT(name));
906 assert(node != NULL);
907 assert(IS_DOT(node->name));
909 mtree_current = node;
917 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
918 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
919 node = create_node(name, type, parent, &mtree_global);
924 error = read_mtree_keywords(fp, node);
931 node->first = (mtree_current != NULL) ? mtree_current : node;
936 if (node->type != S_IFDIR)
939 if (!IS_DOT(node->name)) {
941 node = create_node(".", S_IFDIR, parent, parent);
944 destroy_node(parent);
947 parent->child = node;
951 assert(node != NULL);
952 assert(IS_DOT(node->name));
953 assert(node->first == node);
955 mtree_current = node;
956 if (mtree_root == NULL)
963 read_mtree_spec(FILE *fp)
965 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
969 error = read_word(fp, pathtmp, sizeof(pathtmp));
972 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
978 cp = strchr(pathspec, '/');
980 /* Absolute pathname */
981 mtree_current = mtree_root;
986 /* Disallow '..' as a component. */
987 if (IS_DOTDOT(pathspec)) {
988 mtree_error("absolute path cannot contain "
993 /* Ignore multiple adjacent slashes and '.'. */
994 if (pathspec[0] != '\0' && !IS_DOT(pathspec))
995 error = read_mtree_spec1(fp, false, pathspec);
996 memmove(pathspec, cp, strlen(cp) + 1);
997 cp = strchr(pathspec, '/');
998 } while (!error && cp != NULL);
1000 /* Disallow '.' and '..' as the last component. */
1001 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1002 mtree_error("absolute path cannot contain . or .. "
1008 /* Ignore absolute specfications that end with a slash. */
1009 if (!error && pathspec[0] != '\0')
1010 error = read_mtree_spec1(fp, true, pathspec);
1019 read_mtree(const char *fname, fsnode *node)
1021 struct mtree_fileinfo *fi;
1025 /* We do not yet support nesting... */
1026 assert(node == NULL);
1028 if (strcmp(fname, "-") == 0)
1031 fp = fopen(fname, "r");
1033 err(1, "Can't open `%s'", fname);
1036 error = mtree_file_push(fname, fp);
1040 memset(&mtree_global, 0, sizeof(mtree_global));
1041 memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1042 mtree_global.inode = &mtree_global_inode;
1043 mtree_global_inode.nlink = 1;
1044 mtree_global_inode.st.st_nlink = 1;
1045 mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1046 mtree_global_inode.st.st_mtime = time(NULL);
1047 errors = warnings = 0;
1053 mtree_current = node;
1055 /* Start of a new line... */
1056 fi = SLIST_FIRST(&mtree_fileinfo);
1059 error = skip_over(fp, " \t");
1065 error = ferror(fp) ? errno : -1;
1070 case '\n': /* empty line */
1073 case '#': /* comment -- skip to end of line. */
1074 error = skip_to(fp, "\n");
1078 case '/': /* special commands */
1079 error = read_mtree_command(fp);
1081 default: /* specification */
1083 error = read_mtree_spec(fp);
1091 if (error <= 0 && (errors || warnings)) {
1092 warnx("%u error(s) and %u warning(s) in mtree manifest",
1100 errc(1, error, "Error reading mtree file");
1105 if (mtree_root != NULL)
1106 return (mtree_root);
1108 /* Handle empty specifications. */
1109 node = create_node(".", S_IFDIR, NULL, &mtree_global);