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 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/queue.h>
35 #include <sys/types.h>
57 #define ENOATTR ENOMSG
60 #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0')
61 #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
63 struct mtree_fileinfo {
64 SLIST_ENTRY(mtree_fileinfo) next;
70 /* Global state used while parsing. */
71 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
72 SLIST_HEAD_INITIALIZER(mtree_fileinfo);
73 static fsnode *mtree_root;
74 static fsnode *mtree_current;
75 static fsnode mtree_global;
76 static fsinode mtree_global_inode;
77 static u_int errors, warnings;
79 static void mtree_error(const char *, ...) __printflike(1, 2);
80 static void mtree_warning(const char *, ...) __printflike(1, 2);
83 mtree_file_push(const char *name, FILE *fp)
85 struct mtree_fileinfo *fi;
87 fi = emalloc(sizeof(*fi));
88 if (strcmp(name, "-") == 0)
89 fi->name = estrdup("(stdin)");
91 fi->name = estrdup(name);
92 if (fi->name == NULL) {
100 SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
105 mtree_print(const char *msgtype, const char *fmt, va_list ap)
107 struct mtree_fileinfo *fi;
109 if (msgtype != NULL) {
110 fi = SLIST_FIRST(&mtree_fileinfo);
112 fprintf(stderr, "%s:%u: ", fi->name, fi->line);
113 fprintf(stderr, "%s: ", msgtype);
115 vfprintf(stderr, fmt, ap);
119 mtree_error(const char *fmt, ...)
124 mtree_print("error", fmt, ap);
132 mtree_warning(const char *fmt, ...)
137 mtree_print("warning", fmt, ap);
144 #ifndef MAKEFS_MAX_TREE_DEPTH
145 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
148 /* construct path to node->name */
150 mtree_file_path(fsnode *node)
154 char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
158 rp[depth] = node->name;
159 for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
160 pnode = pnode->parent) {
161 if (strcmp(pnode->name, ".") == 0)
163 rp[++depth] = pnode->name;
166 sb = sbuf_new_auto();
172 sbuf_cat(sb, rp[depth--]);
175 sbuf_cat(sb, rp[depth]);
177 res = estrdup(sbuf_data(sb));
185 /* mtree_resolve() sets errno to indicate why NULL was returned. */
187 mtree_resolve(const char *spec, int *istemp)
190 char *res, *var = NULL;
191 const char *base, *p, *v;
193 int c, error, quoted, subst;
201 c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
202 *istemp = (c == '`') ? 1 : 0;
203 subst = (c == '`' || c == '"') ? 1 : 0;
204 quoted = (subst || c == '\'') ? 1 : 0;
207 res = estrdup(spec + quoted);
213 sb = sbuf_new_auto();
223 p = strchr(base, '$');
225 sbuf_bcat(sb, base, len);
230 /* The following is safe. spec always starts with a quote. */
234 sbuf_bcat(sb, base, p - base);
247 /* Handle ${X} vs $X. */
255 len -= (p + 1) - base;
264 var = ecalloc(p - v, 1);
265 memcpy(var, v + 1, p - v - 1);
266 if (strcmp(var, ".CURDIR") == 0) {
267 res = getcwd(NULL, 0);
270 } else if (strcmp(var, ".PROG") == 0) {
271 res = estrdup(getprogname());
291 res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
299 skip_over(FILE *fp, const char *cs)
304 while (c != EOF && strchr(cs, c) != NULL)
310 return (ferror(fp) ? errno : -1);
314 skip_to(FILE *fp, const char *cs)
319 while (c != EOF && strchr(cs, c) == NULL)
325 return (ferror(fp) ? errno : -1);
329 read_word(FILE *fp, char *buf, size_t bufsz)
331 struct mtree_fileinfo *fi;
333 int c, done, error, esc, qlvl;
348 error = ferror(fp) ? errno : -1;
350 mtree_error("unexpected end of file");
352 case '#': /* comment -- skip to end of line. */
354 error = skip_to(fp, "\n");
370 } else if (c == buf[qidx]) {
375 } while (buf[qidx] != '`' &&
388 if (!esc && qlvl == 0) {
396 * We going to eat the newline ourselves.
399 mtree_warning("quoted word straddles "
401 fi = SLIST_FIRST(&mtree_fileinfo);
412 } while (idx < bufsz && !done);
415 mtree_error("word too long to fit buffer (max %zu characters)",
417 skip_to(fp, " \t\n");
423 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
427 n = ecalloc(1, sizeof(*n));
428 n->name = estrdup(name);
429 n->type = (type == 0) ? global->type : type;
432 n->inode = ecalloc(1, sizeof(*n->inode));
434 /* Assign global options/defaults. */
435 memcpy(n->inode, global->inode, sizeof(*n->inode));
436 n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
438 if (n->type == S_IFLNK)
439 n->symlink = global->symlink;
440 else if (n->type == S_IFREG)
441 n->contents = global->contents;
447 destroy_node(fsnode *n)
451 assert(n->name != NULL);
452 assert(n->inode != NULL);
460 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
466 val = strtoimax(tok, &end, base);
467 if (end == tok || end[0] != '\0')
469 if (val < min || val > max)
476 read_mtree_keywords(FILE *fp, fsnode *node)
478 char keyword[PATH_MAX];
479 char *name, *p, *value;
488 st = &node->inode->st;
490 error = skip_over(fp, " \t");
494 error = read_word(fp, keyword, sizeof(keyword));
498 if (keyword[0] == '\0')
501 value = strchr(keyword, '=');
506 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
507 * certain conditions:
508 * EINVAL - Value provided for a keyword that does
509 * not take a value. The value is ignored.
510 * ENOATTR - Value missing for a keyword that needs
511 * a value. The keyword is ignored.
512 * ENOSYS - Unsupported keyword encountered. The
513 * keyword is ignored.
514 * ENXIO - Value provided for a keyword that does
515 * not take a value. The value is ignored.
517 switch (keyword[0]) {
519 if (strcmp(keyword, "contents") == 0) {
524 node->contents = estrdup(value);
529 if (strcmp(keyword, "flags") == 0) {
535 if (!strtofflags(&value, &flset, &flclr)) {
536 st->st_flags &= ~flclr;
537 st->st_flags |= flset;
544 if (strcmp(keyword, "gid") == 0) {
549 error = read_number(value, 10, &num,
553 } else if (strcmp(keyword, "gname") == 0) {
558 if (gid_from_group(value, &gid) == 0)
566 if (strcmp(keyword, "link") == 0) {
571 node->symlink = emalloc(strlen(value) + 1);
572 if (node->symlink == NULL) {
576 if (strunvis(node->symlink, value) < 0) {
584 if (strcmp(keyword, "mode") == 0) {
589 if (value[0] >= '0' && value[0] <= '9') {
590 error = read_number(value, 8, &num,
593 st->st_mode &= S_IFMT;
597 /* Symbolic mode not supported. */
605 if (strcmp(keyword, "optional") == 0) {
608 node->flags |= FSNODE_F_OPTIONAL;
613 if (strcmp(keyword, "size") == 0) {
618 error = read_number(value, 10, &num,
626 if (strcmp(keyword, "time") == 0) {
631 p = strchr(value, '.');
634 error = read_number(value, 10, &num, 0,
643 error = read_number(p, 10, &num, 0,
649 } else if (strcmp(keyword, "type") == 0) {
654 if (strcmp(value, "dir") == 0)
655 node->type = S_IFDIR;
656 else if (strcmp(value, "file") == 0)
657 node->type = S_IFREG;
658 else if (strcmp(value, "link") == 0)
659 node->type = S_IFLNK;
666 if (strcmp(keyword, "uid") == 0) {
671 error = read_number(value, 10, &num,
675 } else if (strcmp(keyword, "uname") == 0) {
680 if (uid_from_user(value, &uid) == 0)
694 mtree_error("%s: invalid value '%s'", keyword, value);
697 mtree_error("%s: keyword needs a value", keyword);
700 mtree_warning("%s: unsupported keyword", keyword);
703 mtree_error("%s: keyword does not take a value",
712 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
714 /* Nothing more to do for the global defaults. */
715 if (node->name == NULL)
719 * Be intelligent about the file type.
721 if (node->contents != NULL) {
722 if (node->symlink != NULL) {
723 mtree_error("%s: both link and contents keywords "
724 "defined", node->name);
728 } else if (node->type != 0) {
730 if (type == S_IFREG) {
731 /* the named path is the default contents */
732 node->contents = mtree_file_path(node);
735 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
740 if (node->type != type) {
741 mtree_error("%s: file type and defined keywords to not match",
746 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
748 if (node->contents == NULL)
751 name = mtree_resolve(node->contents, &istemp);
755 if (stat(name, &sb) != 0) {
756 mtree_error("%s: contents file '%s' not found", node->name,
763 * Check for hardlinks. If the contents key is used, then the check
764 * will only trigger if the contents file is a link even if it is used
765 * by more than one file
767 if (sb.st_nlink > 1) {
770 st->st_ino = sb.st_ino;
771 st->st_dev = sb.st_dev;
772 curino = link_check(node->inode);
773 if (curino != NULL) {
775 node->inode = curino;
776 node->inode->nlink++;
780 free(node->contents);
781 node->contents = name;
782 st->st_size = sb.st_size;
787 read_mtree_command(FILE *fp)
792 error = read_word(fp, cmd, sizeof(cmd));
796 error = read_mtree_keywords(fp, &mtree_global);
805 read_mtree_spec1(FILE *fp, bool def, const char *name)
807 fsnode *last, *node, *parent;
811 assert(name[0] != '\0');
814 * Treat '..' specially, because it only changes our current
815 * directory. We don't create a node for it. We simply ignore
816 * any keywords that may appear on the line as well.
817 * Going up a directory is a little non-obvious. A directory
818 * node has a corresponding '.' child. The parent of '.' is
819 * not the '.' node of the parent directory, but the directory
820 * node within the parent to which the child relates. However,
821 * going up a directory means we need to find the '.' node to
822 * which the directoy node is linked. This we can do via the
823 * first * pointer, because '.' is always the first entry in a
826 if (IS_DOTDOT(name)) {
827 /* This deals with NULL pointers as well. */
828 if (mtree_current == mtree_root) {
829 mtree_warning("ignoring .. in root directory");
833 node = mtree_current;
835 assert(node != NULL);
836 assert(IS_DOT(node->name));
837 assert(node->first == node);
839 /* Get the corresponding directory node in the parent. */
840 node = mtree_current->parent;
842 assert(node != NULL);
843 assert(!IS_DOT(node->name));
847 assert(node != NULL);
848 assert(IS_DOT(node->name));
849 assert(node->first == node);
851 mtree_current = node;
856 * If we don't have a current directory and the first specification
857 * (either implicit or defined) is not '.', then we need to create
858 * a '.' node first (using a recursive call).
860 if (!IS_DOT(name) && mtree_current == NULL) {
861 error = read_mtree_spec1(fp, false, ".");
867 * Lookup the name in the current directory (if we have a current
868 * directory) to make sure we do not create multiple nodes for the
869 * same component. For non-definitions, if we find a node with the
870 * same name, simply change the current directory. For definitions
874 node = mtree_current;
875 while (node != NULL) {
876 assert(node->first == mtree_current);
878 if (strcmp(name, node->name) == 0) {
882 "duplicate definition of %s",
886 "duplicate definition of %s",
891 if (node->type != S_IFDIR) {
892 mtree_error("%s is not a directory", name);
896 assert(!IS_DOT(name));
900 assert(node != NULL);
901 assert(IS_DOT(node->name));
903 mtree_current = node;
911 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
912 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
913 node = create_node(name, type, parent, &mtree_global);
918 error = read_mtree_keywords(fp, node);
925 node->first = (mtree_current != NULL) ? mtree_current : node;
930 if (node->type != S_IFDIR)
933 if (!IS_DOT(node->name)) {
935 node = create_node(".", S_IFDIR, parent, parent);
938 destroy_node(parent);
941 parent->child = node;
945 assert(node != NULL);
946 assert(IS_DOT(node->name));
947 assert(node->first == node);
949 mtree_current = node;
950 if (mtree_root == NULL)
957 read_mtree_spec(FILE *fp)
959 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
963 error = read_word(fp, pathtmp, sizeof(pathtmp));
966 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
972 cp = strchr(pathspec, '/');
974 /* Absolute pathname */
975 mtree_current = mtree_root;
980 /* Disallow '..' as a component. */
981 if (IS_DOTDOT(pathspec)) {
982 mtree_error("absolute path cannot contain "
987 /* Ignore multiple adjacent slashes and '.'. */
988 if (pathspec[0] != '\0' && !IS_DOT(pathspec))
989 error = read_mtree_spec1(fp, false, pathspec);
990 memmove(pathspec, cp, strlen(cp) + 1);
991 cp = strchr(pathspec, '/');
992 } while (!error && cp != NULL);
994 /* Disallow '.' and '..' as the last component. */
995 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
996 mtree_error("absolute path cannot contain . or .. "
1002 /* Ignore absolute specfications that end with a slash. */
1003 if (!error && pathspec[0] != '\0')
1004 error = read_mtree_spec1(fp, true, pathspec);
1013 read_mtree(const char *fname, fsnode *node)
1015 struct mtree_fileinfo *fi;
1019 /* We do not yet support nesting... */
1020 assert(node == NULL);
1022 if (strcmp(fname, "-") == 0)
1025 fp = fopen(fname, "r");
1027 err(1, "Can't open `%s'", fname);
1030 error = mtree_file_push(fname, fp);
1034 memset(&mtree_global, 0, sizeof(mtree_global));
1035 memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1036 mtree_global.inode = &mtree_global_inode;
1037 mtree_global_inode.nlink = 1;
1038 mtree_global_inode.st.st_nlink = 1;
1039 mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1040 mtree_global_inode.st.st_mtime = time(NULL);
1041 errors = warnings = 0;
1047 mtree_current = node;
1049 /* Start of a new line... */
1050 fi = SLIST_FIRST(&mtree_fileinfo);
1053 error = skip_over(fp, " \t");
1059 error = ferror(fp) ? errno : -1;
1064 case '\n': /* empty line */
1067 case '#': /* comment -- skip to end of line. */
1068 error = skip_to(fp, "\n");
1072 case '/': /* special commands */
1073 error = read_mtree_command(fp);
1075 default: /* specification */
1077 error = read_mtree_spec(fp);
1085 if (error <= 0 && (errors || warnings)) {
1086 warnx("%u error(s) and %u warning(s) in mtree manifest",
1094 errc(1, error, "Error reading mtree file");
1099 if (mtree_root != NULL)
1100 return (mtree_root);
1102 /* Handle empty specifications. */
1103 node = create_node(".", S_IFDIR, NULL, &mtree_global);