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.
27 * $FreeBSD: head/usr.sbin/makefs/mtree.c 332986 2018-04-25 02:43:53Z pfg $
30 #if HAVE_NBTOOL_CONFIG_H
31 #include "nbtool_config.h"
34 #include <sys/param.h>
35 #include <sys/queue.h>
38 #include <sys/types.h>
60 #define ENOATTR ENODATA
63 #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0')
64 #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0')
66 struct mtree_fileinfo {
67 SLIST_ENTRY(mtree_fileinfo) next;
73 /* Global state used while parsing. */
74 static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo =
75 SLIST_HEAD_INITIALIZER(mtree_fileinfo);
76 static fsnode *mtree_root;
77 static fsnode *mtree_current;
78 static fsnode mtree_global;
79 static fsinode mtree_global_inode;
80 static u_int errors, warnings;
82 static void mtree_error(const char *, ...) __printflike(1, 2);
83 static void mtree_warning(const char *, ...) __printflike(1, 2);
86 mtree_file_push(const char *name, FILE *fp)
88 struct mtree_fileinfo *fi;
90 fi = emalloc(sizeof(*fi));
91 if (strcmp(name, "-") == 0)
92 fi->name = estrdup("(stdin)");
94 fi->name = estrdup(name);
95 if (fi->name == NULL) {
103 SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next);
108 mtree_print(const char *msgtype, const char *fmt, va_list ap)
110 struct mtree_fileinfo *fi;
112 if (msgtype != NULL) {
113 fi = SLIST_FIRST(&mtree_fileinfo);
115 fprintf(stderr, "%s:%u: ", fi->name, fi->line);
116 fprintf(stderr, "%s: ", msgtype);
118 vfprintf(stderr, fmt, ap);
122 mtree_error(const char *fmt, ...)
127 mtree_print("error", fmt, ap);
135 mtree_warning(const char *fmt, ...)
140 mtree_print("warning", fmt, ap);
147 #ifndef MAKEFS_MAX_TREE_DEPTH
148 # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2)
151 /* construct path to node->name */
153 mtree_file_path(fsnode *node)
157 char *res, *rp[MAKEFS_MAX_TREE_DEPTH];
161 rp[depth] = node->name;
162 for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1;
163 pnode = pnode->parent) {
164 if (strcmp(pnode->name, ".") == 0)
166 rp[++depth] = pnode->name;
169 sb = sbuf_new_auto();
175 sbuf_cat(sb, rp[depth--]);
178 sbuf_cat(sb, rp[depth]);
180 res = estrdup(sbuf_data(sb));
188 /* mtree_resolve() sets errno to indicate why NULL was returned. */
190 mtree_resolve(const char *spec, int *istemp)
193 char *res, *var = NULL;
194 const char *base, *p, *v;
196 int c, error, quoted, subst;
204 c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0;
205 *istemp = (c == '`') ? 1 : 0;
206 subst = (c == '`' || c == '"') ? 1 : 0;
207 quoted = (subst || c == '\'') ? 1 : 0;
210 res = estrdup(spec + quoted);
216 sb = sbuf_new_auto();
226 p = strchr(base, '$');
228 sbuf_bcat(sb, base, len);
233 /* The following is safe. spec always starts with a quote. */
237 sbuf_bcat(sb, base, p - base);
250 /* Handle ${X} vs $X. */
258 len -= (p + 1) - base;
267 var = ecalloc(p - v, 1);
268 memcpy(var, v + 1, p - v - 1);
269 if (strcmp(var, ".CURDIR") == 0) {
270 res = getcwd(NULL, 0);
273 } else if (strcmp(var, ".PROG") == 0) {
274 res = estrdup(getprogname());
294 res = (error == 0) ? strdup(sbuf_data(sb)) : NULL;
302 skip_over(FILE *fp, const char *cs)
307 while (c != EOF && strchr(cs, c) != NULL)
313 return (ferror(fp) ? errno : -1);
317 skip_to(FILE *fp, const char *cs)
322 while (c != EOF && strchr(cs, c) == NULL)
328 return (ferror(fp) ? errno : -1);
332 read_word(FILE *fp, char *buf, size_t bufsz)
334 struct mtree_fileinfo *fi;
336 int c, done, error, esc, qlvl;
351 error = ferror(fp) ? errno : -1;
353 mtree_error("unexpected end of file");
355 case '#': /* comment -- skip to end of line. */
357 error = skip_to(fp, "\n");
373 } else if (c == buf[qidx]) {
378 } while (buf[qidx] != '`' &&
391 if (!esc && qlvl == 0) {
399 * We going to eat the newline ourselves.
402 mtree_warning("quoted word straddles "
404 fi = SLIST_FIRST(&mtree_fileinfo);
415 } while (idx < bufsz && !done);
418 mtree_error("word too long to fit buffer (max %zu characters)",
420 skip_to(fp, " \t\n");
426 create_node(const char *name, u_int type, fsnode *parent, fsnode *global)
430 n = ecalloc(1, sizeof(*n));
431 n->name = estrdup(name);
432 n->type = (type == 0) ? global->type : type;
435 n->inode = ecalloc(1, sizeof(*n->inode));
437 /* Assign global options/defaults. */
438 memcpy(n->inode, global->inode, sizeof(*n->inode));
439 n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type;
441 if (n->type == S_IFLNK)
442 n->symlink = global->symlink;
443 else if (n->type == S_IFREG)
444 n->contents = global->contents;
450 destroy_node(fsnode *n)
454 assert(n->name != NULL);
455 assert(n->inode != NULL);
463 read_number(const char *tok, u_int base, intmax_t *res, intmax_t min,
469 val = strtoimax(tok, &end, base);
470 if (end == tok || end[0] != '\0')
472 if (val < min || val > max)
479 read_mtree_keywords(FILE *fp, fsnode *node)
481 char keyword[PATH_MAX];
482 char *name, *p, *value;
491 st = &node->inode->st;
493 error = skip_over(fp, " \t");
497 error = read_word(fp, keyword, sizeof(keyword));
501 if (keyword[0] == '\0')
504 value = strchr(keyword, '=');
509 * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal
510 * certain conditions:
511 * EINVAL - Value provided for a keyword that does
512 * not take a value. The value is ignored.
513 * ENOATTR - Value missing for a keyword that needs
514 * a value. The keyword is ignored.
515 * ENOSYS - Unsupported keyword encountered. The
516 * keyword is ignored.
517 * ENXIO - Value provided for a keyword that does
518 * not take a value. The value is ignored.
520 switch (keyword[0]) {
522 if (strcmp(keyword, "contents") == 0) {
527 node->contents = estrdup(value);
532 if (strcmp(keyword, "flags") == 0) {
538 #if HAVE_STRUCT_STAT_ST_FLAGS
539 if (!strtofflags(&value, &flset, &flclr)) {
540 st->st_flags &= ~flclr;
541 st->st_flags |= flset;
549 if (strcmp(keyword, "gid") == 0) {
554 error = read_number(value, 10, &num,
558 } else if (strcmp(keyword, "gname") == 0) {
563 if (gid_from_group(value, &gid) == 0)
571 if (strcmp(keyword, "link") == 0) {
576 node->symlink = emalloc(strlen(value) + 1);
577 if (node->symlink == NULL) {
581 if (strunvis(node->symlink, value) < 0) {
589 if (strcmp(keyword, "mode") == 0) {
594 if (value[0] >= '0' && value[0] <= '9') {
595 error = read_number(value, 8, &num,
598 st->st_mode &= S_IFMT;
602 /* Symbolic mode not supported. */
610 if (strcmp(keyword, "optional") == 0) {
613 node->flags |= FSNODE_F_OPTIONAL;
618 if (strcmp(keyword, "size") == 0) {
623 error = read_number(value, 10, &num,
631 if (strcmp(keyword, "time") == 0) {
636 p = strchr(value, '.');
639 error = read_number(value, 10, &num, 0,
648 error = read_number(p, 10, &num, 0,
654 } else if (strcmp(keyword, "type") == 0) {
659 if (strcmp(value, "dir") == 0)
660 node->type = S_IFDIR;
661 else if (strcmp(value, "file") == 0)
662 node->type = S_IFREG;
663 else if (strcmp(value, "link") == 0)
664 node->type = S_IFLNK;
671 if (strcmp(keyword, "uid") == 0) {
676 error = read_number(value, 10, &num,
680 } else if (strcmp(keyword, "uname") == 0) {
685 if (uid_from_user(value, &uid) == 0)
699 mtree_error("%s: invalid value '%s'", keyword, value);
702 mtree_error("%s: keyword needs a value", keyword);
705 mtree_warning("%s: unsupported keyword", keyword);
708 mtree_error("%s: keyword does not take a value",
717 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
719 /* Nothing more to do for the global defaults. */
720 if (node->name == NULL)
724 * Be intelligent about the file type.
726 if (node->contents != NULL) {
727 if (node->symlink != NULL) {
728 mtree_error("%s: both link and contents keywords "
729 "defined", node->name);
733 } else if (node->type != 0) {
735 if (type == S_IFREG) {
736 /* the named path is the default contents */
737 node->contents = mtree_file_path(node);
740 type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR;
745 if (node->type != type) {
746 mtree_error("%s: file type and defined keywords to not match",
751 st->st_mode = (st->st_mode & ~S_IFMT) | node->type;
753 if (node->contents == NULL)
756 name = mtree_resolve(node->contents, &istemp);
760 if (stat(name, &sb) != 0) {
761 mtree_error("%s: contents file '%s' not found", node->name,
768 * Check for hardlinks. If the contents key is used, then the check
769 * will only trigger if the contents file is a link even if it is used
770 * by more than one file
772 if (sb.st_nlink > 1) {
775 st->st_ino = sb.st_ino;
776 st->st_dev = sb.st_dev;
777 curino = link_check(node->inode);
778 if (curino != NULL) {
780 node->inode = curino;
781 node->inode->nlink++;
785 free(node->contents);
786 node->contents = name;
787 st->st_size = sb.st_size;
792 read_mtree_command(FILE *fp)
797 error = read_word(fp, cmd, sizeof(cmd));
801 error = read_mtree_keywords(fp, &mtree_global);
810 read_mtree_spec1(FILE *fp, bool def, const char *name)
812 fsnode *last, *node, *parent;
816 assert(name[0] != '\0');
819 * Treat '..' specially, because it only changes our current
820 * directory. We don't create a node for it. We simply ignore
821 * any keywords that may appear on the line as well.
822 * Going up a directory is a little non-obvious. A directory
823 * node has a corresponding '.' child. The parent of '.' is
824 * not the '.' node of the parent directory, but the directory
825 * node within the parent to which the child relates. However,
826 * going up a directory means we need to find the '.' node to
827 * which the directoy node is linked. This we can do via the
828 * first * pointer, because '.' is always the first entry in a
831 if (IS_DOTDOT(name)) {
832 /* This deals with NULL pointers as well. */
833 if (mtree_current == mtree_root) {
834 mtree_warning("ignoring .. in root directory");
838 node = mtree_current;
840 assert(node != NULL);
841 assert(IS_DOT(node->name));
842 assert(node->first == node);
844 /* Get the corresponding directory node in the parent. */
845 node = mtree_current->parent;
847 assert(node != NULL);
848 assert(!IS_DOT(node->name));
852 assert(node != NULL);
853 assert(IS_DOT(node->name));
854 assert(node->first == node);
856 mtree_current = node;
861 * If we don't have a current directory and the first specification
862 * (either implicit or defined) is not '.', then we need to create
863 * a '.' node first (using a recursive call).
865 if (!IS_DOT(name) && mtree_current == NULL) {
866 error = read_mtree_spec1(fp, false, ".");
872 * Lookup the name in the current directory (if we have a current
873 * directory) to make sure we do not create multiple nodes for the
874 * same component. For non-definitions, if we find a node with the
875 * same name, simply change the current directory. For definitions
879 node = mtree_current;
880 while (node != NULL) {
881 assert(node->first == mtree_current);
883 if (strcmp(name, node->name) == 0) {
887 "duplicate definition of %s",
891 "duplicate definition of %s",
896 if (node->type != S_IFDIR) {
897 mtree_error("%s is not a directory", name);
901 assert(!IS_DOT(name));
905 assert(node != NULL);
906 assert(IS_DOT(node->name));
908 mtree_current = node;
916 parent = (mtree_current != NULL) ? mtree_current->parent : NULL;
917 type = (def == false || IS_DOT(name)) ? S_IFDIR : 0;
918 node = create_node(name, type, parent, &mtree_global);
923 error = read_mtree_keywords(fp, node);
930 node->first = (mtree_current != NULL) ? mtree_current : node;
935 if (node->type != S_IFDIR)
938 if (!IS_DOT(node->name)) {
940 node = create_node(".", S_IFDIR, parent, parent);
943 destroy_node(parent);
946 parent->child = node;
950 assert(node != NULL);
951 assert(IS_DOT(node->name));
952 assert(node->first == node);
954 mtree_current = node;
955 if (mtree_root == NULL)
962 read_mtree_spec(FILE *fp)
964 char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1];
968 error = read_word(fp, pathtmp, sizeof(pathtmp));
971 if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) {
977 cp = strchr(pathspec, '/');
979 /* Absolute pathname */
980 mtree_current = mtree_root;
985 /* Disallow '..' as a component. */
986 if (IS_DOTDOT(pathspec)) {
987 mtree_error("absolute path cannot contain "
992 /* Ignore multiple adjacent slashes and '.'. */
993 if (pathspec[0] != '\0' && !IS_DOT(pathspec))
994 error = read_mtree_spec1(fp, false, pathspec);
995 memmove(pathspec, cp, strlen(cp) + 1);
996 cp = strchr(pathspec, '/');
997 } while (!error && cp != NULL);
999 /* Disallow '.' and '..' as the last component. */
1000 if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) {
1001 mtree_error("absolute path cannot contain . or .. "
1007 /* Ignore absolute specfications that end with a slash. */
1008 if (!error && pathspec[0] != '\0')
1009 error = read_mtree_spec1(fp, true, pathspec);
1018 read_mtree(const char *fname, fsnode *node)
1020 struct mtree_fileinfo *fi;
1024 /* We do not yet support nesting... */
1025 assert(node == NULL);
1027 if (strcmp(fname, "-") == 0)
1030 fp = fopen(fname, "r");
1032 err(1, "Can't open `%s'", fname);
1035 error = mtree_file_push(fname, fp);
1039 memset(&mtree_global, 0, sizeof(mtree_global));
1040 memset(&mtree_global_inode, 0, sizeof(mtree_global_inode));
1041 mtree_global.inode = &mtree_global_inode;
1042 mtree_global_inode.nlink = 1;
1043 mtree_global_inode.st.st_nlink = 1;
1044 mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
1045 mtree_global_inode.st.st_mtime = time(NULL);
1046 errors = warnings = 0;
1052 mtree_current = node;
1054 /* Start of a new line... */
1055 fi = SLIST_FIRST(&mtree_fileinfo);
1058 error = skip_over(fp, " \t");
1064 error = ferror(fp) ? errno : -1;
1069 case '\n': /* empty line */
1072 case '#': /* comment -- skip to end of line. */
1073 error = skip_to(fp, "\n");
1077 case '/': /* special commands */
1078 error = read_mtree_command(fp);
1080 default: /* specification */
1082 error = read_mtree_spec(fp);
1090 if (error <= 0 && (errors || warnings)) {
1091 warnx("%u error(s) and %u warning(s) in mtree manifest",
1099 errc(1, error, "Error reading mtree file");
1104 if (mtree_root != NULL)
1105 return (mtree_root);
1107 /* Handle empty specifications. */
1108 node = create_node(".", S_IFDIR, NULL, &mtree_global);