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/param.h>
33 #include <sys/queue.h>
36 #include <sys/types.h>
58 #define ENOATTR ENODATA
61 #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0')
62 #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
64 struct mtree_fileinfo {
65 SLIST_ENTRY(mtree_fileinfo) next;
71 /* Global state used while parsing. */
72 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
73 SLIST_HEAD_INITIALIZER(mtree_fileinfo);
74 static fsnode *mtree_root;
75 static fsnode *mtree_current;
76 static fsnode mtree_global;
77 static fsinode mtree_global_inode;
78 static u_int errors, warnings;
80 static void mtree_error(const char *, ...) __printflike(1, 2);
81 static void mtree_warning(const char *, ...) __printflike(1, 2);
84 mtree_file_push(const char *name, FILE *fp)
86 struct mtree_fileinfo *fi;
88 fi = emalloc(sizeof(*fi));
89 if (strcmp(name, "-") == 0)
90 fi->name = estrdup("(stdin)");
92 fi->name = estrdup(name);
93 if (fi->name == NULL) {
101 SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
106 mtree_print(const char *msgtype, const char *fmt, va_list ap)
108 struct mtree_fileinfo *fi;
110 if (msgtype != NULL) {
111 fi = SLIST_FIRST(&mtree_fileinfo);
113 fprintf(stderr, "%s:%u: ", fi->name, fi->line);
114 fprintf(stderr, "%s: ", msgtype);
116 vfprintf(stderr, fmt, ap);
120 mtree_error(const char *fmt, ...)
125 mtree_print("error", fmt, ap);
133 mtree_warning(const char *fmt, ...)
138 mtree_print("warning", fmt, ap);
145 #ifndef MAKEFS_MAX_TREE_DEPTH
146 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
149 /* construct path to node->name */
151 mtree_file_path(fsnode *node)
155 char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
159 rp[depth] = node->name;
160 for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
161 pnode = pnode->parent) {
162 if (strcmp(pnode->name, ".") == 0)
164 rp[++depth] = pnode->name;
167 sb = sbuf_new_auto();
173 sbuf_cat(sb, rp[depth--]);
176 sbuf_cat(sb, rp[depth]);
178 res = estrdup(sbuf_data(sb));
186 /* mtree_resolve() sets errno to indicate why NULL was returned. */
188 mtree_resolve(const char *spec, int *istemp)
191 char *res, *var = NULL;
192 const char *base, *p, *v;
194 int c, error, quoted, subst;
202 c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
203 *istemp = (c == '`') ? 1 : 0;
204 subst = (c == '`' || c == '"') ? 1 : 0;
205 quoted = (subst || c == '\'') ? 1 : 0;
208 res = estrdup(spec + quoted);
214 sb = sbuf_new_auto();
224 p = strchr(base, '$');
226 sbuf_bcat(sb, base, len);
231 /* The following is safe. spec always starts with a quote. */
235 sbuf_bcat(sb, base, p - base);
248 /* Handle ${X} vs $X. */
256 len -= (p + 1) - base;
265 var = ecalloc(p - v, 1);
266 memcpy(var, v + 1, p - v - 1);
267 if (strcmp(var, ".CURDIR") == 0) {
268 res = getcwd(NULL, 0);
271 } else if (strcmp(var, ".PROG") == 0) {
272 res = estrdup(getprogname());
292 res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
300 skip_over(FILE *fp, const char *cs)
305 while (c != EOF && strchr(cs, c) != NULL)
311 return (ferror(fp) ? errno : -1);
315 skip_to(FILE *fp, const char *cs)
320 while (c != EOF && strchr(cs, c) == NULL)
326 return (ferror(fp) ? errno : -1);
330 read_word(FILE *fp, char *buf, size_t bufsz)
332 struct mtree_fileinfo *fi;
334 int c, done, error, esc, qlvl;
349 error = ferror(fp) ? errno : -1;
351 mtree_error("unexpected end of file");
353 case '#': /* comment -- skip to end of line. */
355 error = skip_to(fp, "\n");
371 } else if (c == buf[qidx]) {
376 } while (buf[qidx] != '`' &&
389 if (!esc && qlvl == 0) {
397 * We going to eat the newline ourselves.
400 mtree_warning("quoted word straddles "
402 fi = SLIST_FIRST(&mtree_fileinfo);
413 } while (idx < bufsz && !done);
416 mtree_error("word too long to fit buffer (max %zu characters)",
418 skip_to(fp, " \t\n");
424 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
428 n = ecalloc(1, sizeof(*n));
429 n->name = estrdup(name);
430 n->type = (type == 0) ? global->type : type;
433 n->inode = ecalloc(1, sizeof(*n->inode));
435 /* Assign global options/defaults. */
436 memcpy(n->inode, global->inode, sizeof(*n->inode));
437 n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
439 if (n->type == S_IFLNK)
440 n->symlink = global->symlink;
441 else if (n->type == S_IFREG)
442 n->contents = global->contents;
448 destroy_node(fsnode *n)
452 assert(n->name != NULL);
453 assert(n->inode != NULL);
461 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
467 val = strtoimax(tok, &end, base);
468 if (end == tok || end[0] != '\0')
470 if (val < min || val > max)
477 read_mtree_keywords(FILE *fp, fsnode *node)
479 char keyword[PATH_MAX];
480 char *name, *p, *value;
489 st = &node->inode->st;
491 error = skip_over(fp, " \t");
495 error = read_word(fp, keyword, sizeof(keyword));
499 if (keyword[0] == '\0')
502 value = strchr(keyword, '=');
507 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
508 * certain conditions:
509 * EINVAL - Value provided for a keyword that does
510 * not take a value. The value is ignored.
511 * ENOATTR - Value missing for a keyword that needs
512 * a value. The keyword is ignored.
513 * ENOSYS - Unsupported keyword encountered. The
514 * keyword is ignored.
515 * ENXIO - Value provided for a keyword that does
516 * not take a value. The value is ignored.
518 switch (keyword[0]) {
520 if (strcmp(keyword, "contents") == 0) {
525 node->contents = estrdup(value);
530 if (strcmp(keyword, "flags") == 0) {
536 #if HAVE_STRUCT_STAT_ST_FLAGS
537 if (!strtofflags(&value, &flset, &flclr)) {
538 st->st_flags &= ~flclr;
539 st->st_flags |= flset;
547 if (strcmp(keyword, "gid") == 0) {
552 error = read_number(value, 10, &num,
556 } else if (strcmp(keyword, "gname") == 0) {
561 if (gid_from_group(value, &gid) == 0)
569 if (strcmp(keyword, "link") == 0) {
574 node->symlink = emalloc(strlen(value) + 1);
575 if (node->symlink == NULL) {
579 if (strunvis(node->symlink, value) < 0) {
587 if (strcmp(keyword, "mode") == 0) {
592 if (value[0] >= '0' && value[0] <= '9') {
593 error = read_number(value, 8, &num,
596 st->st_mode &= S_IFMT;
600 /* Symbolic mode not supported. */
608 if (strcmp(keyword, "optional") == 0) {
611 node->flags |= FSNODE_F_OPTIONAL;
616 if (strcmp(keyword, "size") == 0) {
621 error = read_number(value, 10, &num,
629 if (strcmp(keyword, "tags") == 0) {
635 } else if (strcmp(keyword, "time") == 0) {
640 p = strchr(value, '.');
643 error = read_number(value, 10, &num, 0,
650 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
653 error = read_number(p, 10, &num, 0,
657 st->st_atimensec = num;
658 st->st_ctimensec = num;
659 st->st_mtimensec = num;
661 } else if (strcmp(keyword, "type") == 0) {
666 if (strcmp(value, "dir") == 0)
667 node->type = S_IFDIR;
668 else if (strcmp(value, "file") == 0)
669 node->type = S_IFREG;
670 else if (strcmp(value, "link") == 0)
671 node->type = S_IFLNK;
678 if (strcmp(keyword, "uid") == 0) {
683 error = read_number(value, 10, &num,
687 } else if (strcmp(keyword, "uname") == 0) {
692 if (uid_from_user(value, &uid) == 0)
706 mtree_error("%s: invalid value '%s'", keyword, value);
709 mtree_error("%s: keyword needs a value", keyword);
712 mtree_warning("%s: unsupported keyword", keyword);
715 mtree_error("%s: keyword does not take a value",
724 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
726 /* Nothing more to do for the global defaults. */
727 if (node->name == NULL)
731 * Be intelligent about the file type.
733 if (node->contents != NULL) {
734 if (node->symlink != NULL) {
735 mtree_error("%s: both link and contents keywords "
736 "defined", node->name);
740 } else if (node->type != 0) {
742 if (type == S_IFLNK && node->symlink == NULL) {
743 mtree_error("%s: link type requires link keyword", node->name);
745 } else if (type == S_IFREG) {
746 /* the named path is the default contents */
747 node->contents = mtree_file_path(node);
750 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
755 if (node->type != type) {
756 mtree_error("%s: file type and defined keywords to not match",
761 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
763 if (node->contents == NULL)
766 name = mtree_resolve(node->contents, &istemp);
770 if (stat(name, &sb) != 0) {
771 mtree_error("%s: contents file '%s' not found", node->name,
778 * Check for hardlinks. If the contents key is used, then the check
779 * will only trigger if the contents file is a link even if it is used
780 * by more than one file
782 if (sb.st_nlink > 1) {
785 st->st_ino = sb.st_ino;
786 st->st_dev = sb.st_dev;
787 curino = link_check(node->inode);
788 if (curino != NULL) {
790 node->inode = curino;
791 node->inode->nlink++;
792 /* Reset st since node->inode has been updated. */
793 st = &node->inode->st;
797 free(node->contents);
798 node->contents = name;
799 st->st_size = sb.st_size;
804 read_mtree_command(FILE *fp)
809 error = read_word(fp, cmd, sizeof(cmd));
813 error = read_mtree_keywords(fp, &mtree_global);
822 read_mtree_spec1(FILE *fp, bool def, const char *name)
824 fsnode *last, *node, *parent;
828 assert(name[0] != '\0');
831 * Treat '..' specially, because it only changes our current
832 * directory. We don't create a node for it. We simply ignore
833 * any keywords that may appear on the line as well.
834 * Going up a directory is a little non-obvious. A directory
835 * node has a corresponding '.' child. The parent of '.' is
836 * not the '.' node of the parent directory, but the directory
837 * node within the parent to which the child relates. However,
838 * going up a directory means we need to find the '.' node to
839 * which the directory node is linked. This we can do via the
840 * first * pointer, because '.' is always the first entry in a
843 if (IS_DOTDOT(name)) {
844 /* This deals with NULL pointers as well. */
845 if (mtree_current == mtree_root) {
846 mtree_warning("ignoring .. in root directory");
850 node = mtree_current;
852 assert(node != NULL);
853 assert(IS_DOT(node->name));
854 assert(node->first == node);
856 /* Get the corresponding directory node in the parent. */
857 node = mtree_current->parent;
859 assert(node != NULL);
860 assert(!IS_DOT(node->name));
864 assert(node != NULL);
865 assert(IS_DOT(node->name));
866 assert(node->first == node);
868 mtree_current = node;
873 * If we don't have a current directory and the first specification
874 * (either implicit or defined) is not '.', then we need to create
875 * a '.' node first (using a recursive call).
877 if (!IS_DOT(name) && mtree_current == NULL) {
878 error = read_mtree_spec1(fp, false, ".");
884 * Lookup the name in the current directory (if we have a current
885 * directory) to make sure we do not create multiple nodes for the
886 * same component. For non-definitions, if we find a node with the
887 * same name, simply change the current directory. For definitions
891 node = mtree_current;
892 while (node != NULL) {
893 assert(node->first == mtree_current);
895 if (strcmp(name, node->name) == 0) {
899 "duplicate definition of %s",
903 "duplicate definition of %s",
908 if (node->type != S_IFDIR) {
909 mtree_error("%s is not a directory", name);
913 assert(!IS_DOT(name));
917 assert(node != NULL);
918 assert(IS_DOT(node->name));
920 mtree_current = node;
928 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
929 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
930 node = create_node(name, type, parent, &mtree_global);
935 error = read_mtree_keywords(fp, node);
942 node->first = (mtree_current != NULL) ? mtree_current : node;
947 if (node->type != S_IFDIR)
950 if (!IS_DOT(node->name)) {
952 node = create_node(".", S_IFDIR, parent, parent);
955 destroy_node(parent);
958 parent->child = node;
962 assert(node != NULL);
963 assert(IS_DOT(node->name));
964 assert(node->first == node);
966 mtree_current = node;
967 if (mtree_root == NULL)
974 read_mtree_spec(FILE *fp)
976 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
980 error = read_word(fp, pathtmp, sizeof(pathtmp));
983 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
989 cp = strchr(pathspec, '/');
991 /* Absolute pathname */
992 mtree_current = mtree_root;
997 /* Disallow '..' as a component. */
998 if (IS_DOTDOT(pathspec)) {
999 mtree_error("absolute path cannot contain "
1004 /* Ignore multiple adjacent slashes and '.'. */
1005 if (pathspec[0] != '\0' && !IS_DOT(pathspec))
1006 error = read_mtree_spec1(fp, false, pathspec);
1007 memmove(pathspec, cp, strlen(cp) + 1);
1008 cp = strchr(pathspec, '/');
1009 } while (!error && cp != NULL);
1011 /* Disallow '.' and '..' as the last component. */
1012 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1013 mtree_error("absolute path cannot contain . or .. "
1019 /* Ignore absolute specifications that end with a slash. */
1020 if (!error && pathspec[0] != '\0')
1021 error = read_mtree_spec1(fp, true, pathspec);
1030 read_mtree(const char *fname, fsnode *node)
1032 struct mtree_fileinfo *fi;
1036 /* We do not yet support nesting... */
1037 assert(node == NULL);
1039 if (strcmp(fname, "-") == 0)
1042 fp = fopen(fname, "r");
1044 err(1, "Can't open `%s'", fname);
1047 error = mtree_file_push(fname, fp);
1051 memset(&mtree_global, 0, sizeof(mtree_global));
1052 memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1053 mtree_global.inode = &mtree_global_inode;
1054 mtree_global_inode.nlink = 1;
1055 mtree_global_inode.st.st_nlink = 1;
1056 mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1057 mtree_global_inode.st.st_mtime = time(NULL);
1058 errors = warnings = 0;
1064 mtree_current = node;
1066 /* Start of a new line... */
1067 fi = SLIST_FIRST(&mtree_fileinfo);
1070 error = skip_over(fp, " \t");
1076 error = ferror(fp) ? errno : -1;
1081 case '\n': /* empty line */
1084 case '#': /* comment -- skip to end of line. */
1085 error = skip_to(fp, "\n");
1089 case '/': /* special commands */
1090 error = read_mtree_command(fp);
1092 default: /* specification */
1094 error = read_mtree_spec(fp);
1102 if (error <= 0 && (errors || warnings)) {
1103 warnx("%u error(s) and %u warning(s) in mtree manifest",
1111 errc(1, error, "Error reading mtree file");
1116 if (mtree_root != NULL)
1117 return (mtree_root);
1119 /* Handle empty specifications. */
1120 node = create_node(".", S_IFDIR, NULL, &mtree_global);