2 * SPDX-License-Identifier: BSD-2-Clause
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 #include <sys/param.h>
34 #include <sys/queue.h>
37 #include <sys/types.h>
59 #define ENOATTR ENODATA
62 #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0')
63 #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
65 struct mtree_fileinfo {
66 SLIST_ENTRY(mtree_fileinfo) next;
72 /* Global state used while parsing. */
73 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
74 SLIST_HEAD_INITIALIZER(mtree_fileinfo);
75 static fsnode *mtree_root;
76 static fsnode *mtree_current;
77 static fsnode mtree_global;
78 static fsinode mtree_global_inode;
79 static u_int errors, warnings;
81 static void mtree_error(const char *, ...) __printflike(1, 2);
82 static void mtree_warning(const char *, ...) __printflike(1, 2);
85 mtree_file_push(const char *name, FILE *fp)
87 struct mtree_fileinfo *fi;
89 fi = emalloc(sizeof(*fi));
90 if (strcmp(name, "-") == 0)
91 fi->name = estrdup("(stdin)");
93 fi->name = estrdup(name);
94 if (fi->name == NULL) {
102 SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
107 mtree_print(const char *msgtype, const char *fmt, va_list ap)
109 struct mtree_fileinfo *fi;
111 if (msgtype != NULL) {
112 fi = SLIST_FIRST(&mtree_fileinfo);
114 fprintf(stderr, "%s:%u: ", fi->name, fi->line);
115 fprintf(stderr, "%s: ", msgtype);
117 vfprintf(stderr, fmt, ap);
121 mtree_error(const char *fmt, ...)
126 mtree_print("error", fmt, ap);
134 mtree_warning(const char *fmt, ...)
139 mtree_print("warning", fmt, ap);
146 #ifndef MAKEFS_MAX_TREE_DEPTH
147 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
150 /* construct path to node->name */
152 mtree_file_path(fsnode *node)
156 char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
160 rp[depth] = node->name;
161 for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
162 pnode = pnode->parent) {
163 if (strcmp(pnode->name, ".") == 0)
165 rp[++depth] = pnode->name;
168 sb = sbuf_new_auto();
174 sbuf_cat(sb, rp[depth--]);
177 sbuf_cat(sb, rp[depth]);
179 res = estrdup(sbuf_data(sb));
187 /* mtree_resolve() sets errno to indicate why NULL was returned. */
189 mtree_resolve(const char *spec, int *istemp)
192 char *res, *var = NULL;
193 const char *base, *p, *v;
195 int c, error, quoted, subst;
203 c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
204 *istemp = (c == '`') ? 1 : 0;
205 subst = (c == '`' || c == '"') ? 1 : 0;
206 quoted = (subst || c == '\'') ? 1 : 0;
209 res = estrdup(spec + quoted);
215 sb = sbuf_new_auto();
225 p = strchr(base, '$');
227 sbuf_bcat(sb, base, len);
232 /* The following is safe. spec always starts with a quote. */
236 sbuf_bcat(sb, base, p - base);
249 /* Handle ${X} vs $X. */
257 len -= (p + 1) - base;
266 var = ecalloc(p - v, 1);
267 memcpy(var, v + 1, p - v - 1);
268 if (strcmp(var, ".CURDIR") == 0) {
269 res = getcwd(NULL, 0);
272 } else if (strcmp(var, ".PROG") == 0) {
273 res = estrdup(getprogname());
293 res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
301 skip_over(FILE *fp, const char *cs)
306 while (c != EOF && strchr(cs, c) != NULL)
312 return (ferror(fp) ? errno : -1);
316 skip_to(FILE *fp, const char *cs)
321 while (c != EOF && strchr(cs, c) == NULL)
327 return (ferror(fp) ? errno : -1);
331 read_word(FILE *fp, char *buf, size_t bufsz)
333 struct mtree_fileinfo *fi;
335 int c, done, error, esc, qlvl;
350 error = ferror(fp) ? errno : -1;
352 mtree_error("unexpected end of file");
354 case '#': /* comment -- skip to end of line. */
356 error = skip_to(fp, "\n");
372 } else if (c == buf[qidx]) {
377 } while (buf[qidx] != '`' &&
390 if (!esc && qlvl == 0) {
398 * We going to eat the newline ourselves.
401 mtree_warning("quoted word straddles "
403 fi = SLIST_FIRST(&mtree_fileinfo);
414 } while (idx < bufsz && !done);
417 mtree_error("word too long to fit buffer (max %zu characters)",
419 skip_to(fp, " \t\n");
425 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
429 n = ecalloc(1, sizeof(*n));
430 n->name = estrdup(name);
431 n->type = (type == 0) ? global->type : type;
434 n->inode = ecalloc(1, sizeof(*n->inode));
436 /* Assign global options/defaults. */
437 memcpy(n->inode, global->inode, sizeof(*n->inode));
438 n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
440 if (n->type == S_IFLNK)
441 n->symlink = global->symlink;
442 else if (n->type == S_IFREG)
443 n->contents = global->contents;
449 destroy_node(fsnode *n)
453 assert(n->name != NULL);
454 assert(n->inode != NULL);
462 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
468 val = strtoimax(tok, &end, base);
469 if (end == tok || end[0] != '\0')
471 if (val < min || val > max)
478 read_mtree_keywords(FILE *fp, fsnode *node)
480 char keyword[PATH_MAX];
481 char *name, *p, *value;
490 st = &node->inode->st;
492 error = skip_over(fp, " \t");
496 error = read_word(fp, keyword, sizeof(keyword));
500 if (keyword[0] == '\0')
503 value = strchr(keyword, '=');
508 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
509 * certain conditions:
510 * EINVAL - Value provided for a keyword that does
511 * not take a value. The value is ignored.
512 * ENOATTR - Value missing for a keyword that needs
513 * a value. The keyword is ignored.
514 * ENOSYS - Unsupported keyword encountered. The
515 * keyword is ignored.
516 * ENXIO - Value provided for a keyword that does
517 * not take a value. The value is ignored.
519 switch (keyword[0]) {
521 if (strcmp(keyword, "contents") == 0) {
526 node->contents = estrdup(value);
531 if (strcmp(keyword, "flags") == 0) {
537 #if HAVE_STRUCT_STAT_ST_FLAGS
538 if (!strtofflags(&value, &flset, &flclr)) {
539 st->st_flags &= ~flclr;
540 st->st_flags |= flset;
548 if (strcmp(keyword, "gid") == 0) {
553 error = read_number(value, 10, &num,
557 } else if (strcmp(keyword, "gname") == 0) {
562 if (gid_from_group(value, &gid) == 0)
570 if (strcmp(keyword, "link") == 0) {
575 node->symlink = emalloc(strlen(value) + 1);
576 if (node->symlink == NULL) {
580 if (strunvis(node->symlink, value) < 0) {
588 if (strcmp(keyword, "mode") == 0) {
593 if (value[0] >= '0' && value[0] <= '9') {
594 error = read_number(value, 8, &num,
597 st->st_mode &= S_IFMT;
601 /* Symbolic mode not supported. */
609 if (strcmp(keyword, "optional") == 0) {
612 node->flags |= FSNODE_F_OPTIONAL;
617 if (strcmp(keyword, "size") == 0) {
622 error = read_number(value, 10, &num,
630 if (strcmp(keyword, "tags") == 0) {
636 } else if (strcmp(keyword, "time") == 0) {
641 p = strchr(value, '.');
644 error = read_number(value, 10, &num, 0,
651 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
654 error = read_number(p, 10, &num, 0,
658 st->st_atimensec = num;
659 st->st_ctimensec = num;
660 st->st_mtimensec = num;
662 } else if (strcmp(keyword, "type") == 0) {
667 if (strcmp(value, "dir") == 0)
668 node->type = S_IFDIR;
669 else if (strcmp(value, "file") == 0)
670 node->type = S_IFREG;
671 else if (strcmp(value, "link") == 0)
672 node->type = S_IFLNK;
679 if (strcmp(keyword, "uid") == 0) {
684 error = read_number(value, 10, &num,
688 } else if (strcmp(keyword, "uname") == 0) {
693 if (uid_from_user(value, &uid) == 0)
707 mtree_error("%s: invalid value '%s'", keyword, value);
710 mtree_error("%s: keyword needs a value", keyword);
713 mtree_warning("%s: unsupported keyword", keyword);
716 mtree_error("%s: keyword does not take a value",
725 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
727 /* Nothing more to do for the global defaults. */
728 if (node->name == NULL)
732 * Be intelligent about the file type.
734 if (node->contents != NULL) {
735 if (node->symlink != NULL) {
736 mtree_error("%s: both link and contents keywords "
737 "defined", node->name);
741 } else if (node->type != 0) {
743 if (type == S_IFREG) {
744 /* the named path is the default contents */
745 node->contents = mtree_file_path(node);
748 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
753 if (node->type != type) {
754 mtree_error("%s: file type and defined keywords to not match",
759 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
761 if (node->contents == NULL)
764 name = mtree_resolve(node->contents, &istemp);
768 if (stat(name, &sb) != 0) {
769 mtree_error("%s: contents file '%s' not found", node->name,
776 * Check for hardlinks. If the contents key is used, then the check
777 * will only trigger if the contents file is a link even if it is used
778 * by more than one file
780 if (sb.st_nlink > 1) {
783 st->st_ino = sb.st_ino;
784 st->st_dev = sb.st_dev;
785 curino = link_check(node->inode);
786 if (curino != NULL) {
788 node->inode = curino;
789 node->inode->nlink++;
790 /* Reset st since node->inode has been updated. */
791 st = &node->inode->st;
795 free(node->contents);
796 node->contents = name;
797 st->st_size = sb.st_size;
802 read_mtree_command(FILE *fp)
807 error = read_word(fp, cmd, sizeof(cmd));
811 error = read_mtree_keywords(fp, &mtree_global);
820 read_mtree_spec1(FILE *fp, bool def, const char *name)
822 fsnode *last, *node, *parent;
826 assert(name[0] != '\0');
829 * Treat '..' specially, because it only changes our current
830 * directory. We don't create a node for it. We simply ignore
831 * any keywords that may appear on the line as well.
832 * Going up a directory is a little non-obvious. A directory
833 * node has a corresponding '.' child. The parent of '.' is
834 * not the '.' node of the parent directory, but the directory
835 * node within the parent to which the child relates. However,
836 * going up a directory means we need to find the '.' node to
837 * which the directory node is linked. This we can do via the
838 * first * pointer, because '.' is always the first entry in a
841 if (IS_DOTDOT(name)) {
842 /* This deals with NULL pointers as well. */
843 if (mtree_current == mtree_root) {
844 mtree_warning("ignoring .. in root directory");
848 node = mtree_current;
850 assert(node != NULL);
851 assert(IS_DOT(node->name));
852 assert(node->first == node);
854 /* Get the corresponding directory node in the parent. */
855 node = mtree_current->parent;
857 assert(node != NULL);
858 assert(!IS_DOT(node->name));
862 assert(node != NULL);
863 assert(IS_DOT(node->name));
864 assert(node->first == node);
866 mtree_current = node;
871 * If we don't have a current directory and the first specification
872 * (either implicit or defined) is not '.', then we need to create
873 * a '.' node first (using a recursive call).
875 if (!IS_DOT(name) && mtree_current == NULL) {
876 error = read_mtree_spec1(fp, false, ".");
882 * Lookup the name in the current directory (if we have a current
883 * directory) to make sure we do not create multiple nodes for the
884 * same component. For non-definitions, if we find a node with the
885 * same name, simply change the current directory. For definitions
889 node = mtree_current;
890 while (node != NULL) {
891 assert(node->first == mtree_current);
893 if (strcmp(name, node->name) == 0) {
897 "duplicate definition of %s",
901 "duplicate definition of %s",
906 if (node->type != S_IFDIR) {
907 mtree_error("%s is not a directory", name);
911 assert(!IS_DOT(name));
915 assert(node != NULL);
916 assert(IS_DOT(node->name));
918 mtree_current = node;
926 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
927 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
928 node = create_node(name, type, parent, &mtree_global);
933 error = read_mtree_keywords(fp, node);
940 node->first = (mtree_current != NULL) ? mtree_current : node;
945 if (node->type != S_IFDIR)
948 if (!IS_DOT(node->name)) {
950 node = create_node(".", S_IFDIR, parent, parent);
953 destroy_node(parent);
956 parent->child = node;
960 assert(node != NULL);
961 assert(IS_DOT(node->name));
962 assert(node->first == node);
964 mtree_current = node;
965 if (mtree_root == NULL)
972 read_mtree_spec(FILE *fp)
974 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
978 error = read_word(fp, pathtmp, sizeof(pathtmp));
981 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
987 cp = strchr(pathspec, '/');
989 /* Absolute pathname */
990 mtree_current = mtree_root;
995 /* Disallow '..' as a component. */
996 if (IS_DOTDOT(pathspec)) {
997 mtree_error("absolute path cannot contain "
1002 /* Ignore multiple adjacent slashes and '.'. */
1003 if (pathspec[0] != '\0' && !IS_DOT(pathspec))
1004 error = read_mtree_spec1(fp, false, pathspec);
1005 memmove(pathspec, cp, strlen(cp) + 1);
1006 cp = strchr(pathspec, '/');
1007 } while (!error && cp != NULL);
1009 /* Disallow '.' and '..' as the last component. */
1010 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1011 mtree_error("absolute path cannot contain . or .. "
1017 /* Ignore absolute specifications that end with a slash. */
1018 if (!error && pathspec[0] != '\0')
1019 error = read_mtree_spec1(fp, true, pathspec);
1028 read_mtree(const char *fname, fsnode *node)
1030 struct mtree_fileinfo *fi;
1034 /* We do not yet support nesting... */
1035 assert(node == NULL);
1037 if (strcmp(fname, "-") == 0)
1040 fp = fopen(fname, "r");
1042 err(1, "Can't open `%s'", fname);
1045 error = mtree_file_push(fname, fp);
1049 memset(&mtree_global, 0, sizeof(mtree_global));
1050 memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1051 mtree_global.inode = &mtree_global_inode;
1052 mtree_global_inode.nlink = 1;
1053 mtree_global_inode.st.st_nlink = 1;
1054 mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1055 mtree_global_inode.st.st_mtime = time(NULL);
1056 errors = warnings = 0;
1062 mtree_current = node;
1064 /* Start of a new line... */
1065 fi = SLIST_FIRST(&mtree_fileinfo);
1068 error = skip_over(fp, " \t");
1074 error = ferror(fp) ? errno : -1;
1079 case '\n': /* empty line */
1082 case '#': /* comment -- skip to end of line. */
1083 error = skip_to(fp, "\n");
1087 case '/': /* special commands */
1088 error = read_mtree_command(fp);
1090 default: /* specification */
1092 error = read_mtree_spec(fp);
1100 if (error <= 0 && (errors || warnings)) {
1101 warnx("%u error(s) and %u warning(s) in mtree manifest",
1109 errc(1, error, "Error reading mtree file");
1114 if (mtree_root != NULL)
1115 return (mtree_root);
1117 /* Handle empty specifications. */
1118 node = create_node(".", S_IFDIR, NULL, &mtree_global);