Index: head/usr.bin/xinstall/Makefile =================================================================== --- head/usr.bin/xinstall/Makefile (revision 328063) +++ head/usr.bin/xinstall/Makefile (revision 328064) @@ -1,20 +1,21 @@ # @(#)Makefile 8.1 (Berkeley) 6/6/93 # $FreeBSD$ .include PROG= xinstall PROGNAME= install SRCS= xinstall.c getid.c MAN= install.1 .PATH: ${SRCTOP}/contrib/mtree CFLAGS+= -I${SRCTOP}/contrib/mtree CFLAGS+= -I${SRCTOP}/lib/libnetbsd +CFLAGS+= -DHAVE_STRUCT_STAT_ST_FLAGS=1 LIBADD= md HAS_TESTS= SUBDIR.${MK_TESTS}+= tests .include Index: head/usr.bin/xinstall/xinstall.c =================================================================== --- head/usr.bin/xinstall/xinstall.c (revision 328063) +++ head/usr.bin/xinstall/xinstall.c (revision 328064) @@ -1,1459 +1,1480 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2012, 2013 SRI International * Copyright (c) 1987, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1987, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #if 0 #ifndef lint static char sccsid[] = "@(#)xinstall.c 8.1 (Berkeley) 7/21/93"; #endif /* not lint */ #endif #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mtree.h" #define MAX_CMP_SIZE (16 * 1024 * 1024) #define LN_ABSOLUTE 0x01 #define LN_RELATIVE 0x02 #define LN_HARD 0x04 #define LN_SYMBOLIC 0x08 #define LN_MIXED 0x10 #define DIRECTORY 0x01 /* Tell install it's a directory. */ #define SETFLAGS 0x02 /* Tell install to set flags. */ #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND) #define BACKUP_SUFFIX ".old" typedef union { MD5_CTX MD5; RIPEMD160_CTX RIPEMD160; SHA1_CTX SHA1; SHA256_CTX SHA256; SHA512_CTX SHA512; } DIGEST_CTX; static enum { DIGEST_NONE = 0, DIGEST_MD5, DIGEST_RIPEMD160, DIGEST_SHA1, DIGEST_SHA256, DIGEST_SHA512, } digesttype = DIGEST_NONE; extern char **environ; static gid_t gid; static uid_t uid; static int dobackup, docompare, dodir, dolink, dopreserve, dostrip, dounpriv, safecopy, verbose; static int haveopt_f, haveopt_g, haveopt_m, haveopt_o; static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; static FILE *metafp; static const char *group, *owner; static const char *suffix = BACKUP_SUFFIX; static char *destdir, *digest, *fflags, *metafile, *tags; static int compare(int, const char *, size_t, int, const char *, size_t, char **); static char *copy(int, const char *, int, const char *, off_t); static int create_newfile(const char *, int, struct stat *); static int create_tempfile(const char *, char *, size_t); static char *quiet_mktemp(char *template); static char *digest_file(const char *); static void digest_init(DIGEST_CTX *); static void digest_update(DIGEST_CTX *, const char *, size_t); static char *digest_end(DIGEST_CTX *, char *); static int do_link(const char *, const char *, const struct stat *); static void do_symlink(const char *, const char *, const struct stat *); static void makelink(const char *, const char *, const struct stat *); static void install(const char *, const char *, u_long, u_int); static void install_dir(char *); static void metadata_log(const char *, const char *, struct timespec *, const char *, const char *, off_t); static int parseid(const char *, id_t *); static void strip(const char *); static int trymmap(int); static void usage(void); int main(int argc, char *argv[]) { struct stat from_sb, to_sb; mode_t *set; u_long fset; int ch, no_target; u_int iflags; char *p; const char *to_name; fset = 0; iflags = 0; group = owner = NULL; while ((ch = getopt(argc, argv, "B:bCcD:df:g:h:l:M:m:N:o:pSsT:Uv")) != -1) switch((char)ch) { case 'B': suffix = optarg; /* FALLTHROUGH */ case 'b': dobackup = 1; break; case 'C': docompare = 1; break; case 'c': /* For backwards compatibility. */ break; case 'D': destdir = optarg; break; case 'd': dodir = 1; break; case 'f': haveopt_f = 1; fflags = optarg; break; case 'g': haveopt_g = 1; group = optarg; break; case 'h': digest = optarg; break; case 'l': for (p = optarg; *p != '\0'; p++) switch (*p) { case 's': dolink &= ~(LN_HARD|LN_MIXED); dolink |= LN_SYMBOLIC; break; case 'h': dolink &= ~(LN_SYMBOLIC|LN_MIXED); dolink |= LN_HARD; break; case 'm': dolink &= ~(LN_SYMBOLIC|LN_HARD); dolink |= LN_MIXED; break; case 'a': dolink &= ~LN_RELATIVE; dolink |= LN_ABSOLUTE; break; case 'r': dolink &= ~LN_ABSOLUTE; dolink |= LN_RELATIVE; break; default: errx(1, "%c: invalid link type", *p); /* NOTREACHED */ } break; case 'M': metafile = optarg; break; case 'm': haveopt_m = 1; if (!(set = setmode(optarg))) errx(EX_USAGE, "invalid file mode: %s", optarg); mode = getmode(set, 0); free(set); break; case 'N': if (!setup_getid(optarg)) err(EX_OSERR, "Unable to use user and group " "databases in `%s'", optarg); break; case 'o': haveopt_o = 1; owner = optarg; break; case 'p': docompare = dopreserve = 1; break; case 'S': safecopy = 1; break; case 's': dostrip = 1; break; case 'T': tags = optarg; break; case 'U': dounpriv = 1; break; case 'v': verbose = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; /* some options make no sense when creating directories */ if (dostrip && dodir) { warnx("-d and -s may not be specified together"); usage(); } if (getenv("DONTSTRIP") != NULL) { warnx("DONTSTRIP set - will not strip installed binaries"); dostrip = 0; } /* must have at least two arguments, except when creating directories */ if (argc == 0 || (argc == 1 && !dodir)) usage(); if (digest != NULL) { if (strcmp(digest, "none") == 0) { digesttype = DIGEST_NONE; } else if (strcmp(digest, "md5") == 0) { digesttype = DIGEST_MD5; } else if (strcmp(digest, "rmd160") == 0) { digesttype = DIGEST_RIPEMD160; } else if (strcmp(digest, "sha1") == 0) { digesttype = DIGEST_SHA1; } else if (strcmp(digest, "sha256") == 0) { digesttype = DIGEST_SHA256; } else if (strcmp(digest, "sha512") == 0) { digesttype = DIGEST_SHA512; } else { warnx("unknown digest `%s'", digest); usage(); } } /* need to make a temp copy so we can compare stripped version */ if (docompare && dostrip) safecopy = 1; /* get group and owner id's */ if (group != NULL && !dounpriv) { if (gid_from_group(group, &gid) == -1) { id_t id; if (!parseid(group, &id)) errx(1, "unknown group %s", group); gid = id; } } else gid = (gid_t)-1; if (owner != NULL && !dounpriv) { if (uid_from_user(owner, &uid) == -1) { id_t id; if (!parseid(owner, &id)) errx(1, "unknown user %s", owner); uid = id; } } else uid = (uid_t)-1; if (fflags != NULL && !dounpriv) { if (strtofflags(&fflags, &fset, NULL)) errx(EX_USAGE, "%s: invalid flag", fflags); iflags |= SETFLAGS; } if (metafile != NULL) { if ((metafp = fopen(metafile, "a")) == NULL) warn("open %s", metafile); } else digesttype = DIGEST_NONE; if (dodir) { for (; *argv != NULL; ++argv) install_dir(*argv); exit(EX_OK); /* NOTREACHED */ } to_name = argv[argc - 1]; no_target = stat(to_name, &to_sb); if (!no_target && S_ISDIR(to_sb.st_mode)) { if (dolink & LN_SYMBOLIC) { if (lstat(to_name, &to_sb) != 0) err(EX_OSERR, "%s vanished", to_name); if (S_ISLNK(to_sb.st_mode)) { if (argc != 2) { errno = ENOTDIR; err(EX_USAGE, "%s", to_name); } install(*argv, to_name, fset, iflags); exit(EX_OK); } } for (; *argv != to_name; ++argv) install(*argv, to_name, fset, iflags | DIRECTORY); exit(EX_OK); /* NOTREACHED */ } /* can't do file1 file2 directory/file */ if (argc != 2) { if (no_target) warnx("target directory `%s' does not exist", argv[argc - 1]); else warnx("target `%s' is not a directory", argv[argc - 1]); usage(); } if (!no_target && !dolink) { if (stat(*argv, &from_sb)) err(EX_OSERR, "%s", *argv); if (!S_ISREG(to_sb.st_mode)) { errno = EFTYPE; err(EX_OSERR, "%s", to_name); } if (to_sb.st_dev == from_sb.st_dev && to_sb.st_ino == from_sb.st_ino) errx(EX_USAGE, "%s and %s are the same file", *argv, to_name); } install(*argv, to_name, fset, iflags); exit(EX_OK); /* NOTREACHED */ } static char * digest_file(const char *name) { switch (digesttype) { case DIGEST_MD5: return (MD5File(name, NULL)); case DIGEST_RIPEMD160: return (RIPEMD160_File(name, NULL)); case DIGEST_SHA1: return (SHA1_File(name, NULL)); case DIGEST_SHA256: return (SHA256_File(name, NULL)); case DIGEST_SHA512: return (SHA512_File(name, NULL)); default: return (NULL); } } static void digest_init(DIGEST_CTX *c) { switch (digesttype) { case DIGEST_NONE: break; case DIGEST_MD5: MD5Init(&(c->MD5)); break; case DIGEST_RIPEMD160: RIPEMD160_Init(&(c->RIPEMD160)); break; case DIGEST_SHA1: SHA1_Init(&(c->SHA1)); break; case DIGEST_SHA256: SHA256_Init(&(c->SHA256)); break; case DIGEST_SHA512: SHA512_Init(&(c->SHA512)); break; } } static void digest_update(DIGEST_CTX *c, const char *data, size_t len) { switch (digesttype) { case DIGEST_NONE: break; case DIGEST_MD5: MD5Update(&(c->MD5), data, len); break; case DIGEST_RIPEMD160: RIPEMD160_Update(&(c->RIPEMD160), data, len); break; case DIGEST_SHA1: SHA1_Update(&(c->SHA1), data, len); break; case DIGEST_SHA256: SHA256_Update(&(c->SHA256), data, len); break; case DIGEST_SHA512: SHA512_Update(&(c->SHA512), data, len); break; } } static char * digest_end(DIGEST_CTX *c, char *buf) { switch (digesttype) { case DIGEST_MD5: return (MD5End(&(c->MD5), buf)); case DIGEST_RIPEMD160: return (RIPEMD160_End(&(c->RIPEMD160), buf)); case DIGEST_SHA1: return (SHA1_End(&(c->SHA1), buf)); case DIGEST_SHA256: return (SHA256_End(&(c->SHA256), buf)); case DIGEST_SHA512: return (SHA512_End(&(c->SHA512), buf)); default: return (NULL); } } /* * parseid -- * parse uid or gid from arg into id, returning non-zero if successful */ static int parseid(const char *name, id_t *id) { char *ep; errno = 0; *id = (id_t)strtoul(name, &ep, 10); if (errno || *ep != '\0') return (0); return (1); } /* * quiet_mktemp -- * mktemp implementation used mkstemp to avoid mktemp warnings. We * really do need mktemp semantics here as we will be creating a link. */ static char * quiet_mktemp(char *template) { int fd; if ((fd = mkstemp(template)) == -1) return (NULL); close (fd); if (unlink(template) == -1) err(EX_OSERR, "unlink %s", template); return (template); } /* * do_link -- * make a hard link, obeying dorename if set * return -1 on failure */ static int do_link(const char *from_name, const char *to_name, const struct stat *target_sb) { char tmpl[MAXPATHLEN]; int ret; if (safecopy && target_sb != NULL) { (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name); /* This usage is safe. */ if (quiet_mktemp(tmpl) == NULL) err(EX_OSERR, "%s: mktemp", tmpl); ret = link(from_name, tmpl); if (ret == 0) { if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) { unlink(tmpl); err(EX_OSERR, "%s", to_name); } +#if HAVE_STRUCT_STAT_ST_FLAGS if (target_sb->st_flags & NOCHANGEBITS) (void)chflags(to_name, target_sb->st_flags & ~NOCHANGEBITS); +#endif if (verbose) printf("install: link %s -> %s\n", from_name, to_name); ret = rename(tmpl, to_name); /* * If rename has posix semantics, then the temporary * file may still exist when from_name and to_name point * to the same file, so unlink it unconditionally. */ (void)unlink(tmpl); } return (ret); } else { if (verbose) printf("install: link %s -> %s\n", from_name, to_name); return (link(from_name, to_name)); } } /* * do_symlink -- * Make a symbolic link, obeying dorename if set. Exit on failure. */ static void do_symlink(const char *from_name, const char *to_name, const struct stat *target_sb) { char tmpl[MAXPATHLEN]; if (safecopy && target_sb != NULL) { (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name); /* This usage is safe. */ if (quiet_mktemp(tmpl) == NULL) err(EX_OSERR, "%s: mktemp", tmpl); if (symlink(from_name, tmpl) == -1) err(EX_OSERR, "symlink %s -> %s", from_name, tmpl); if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) { (void)unlink(tmpl); err(EX_OSERR, "%s", to_name); } +#if HAVE_STRUCT_STAT_ST_FLAGS if (target_sb->st_flags & NOCHANGEBITS) (void)chflags(to_name, target_sb->st_flags & ~NOCHANGEBITS); +#endif if (verbose) printf("install: symlink %s -> %s\n", from_name, to_name); if (rename(tmpl, to_name) == -1) { /* Remove temporary link before exiting. */ (void)unlink(tmpl); err(EX_OSERR, "%s: rename", to_name); } } else { if (verbose) printf("install: symlink %s -> %s\n", from_name, to_name); if (symlink(from_name, to_name) == -1) err(EX_OSERR, "symlink %s -> %s", from_name, to_name); } } /* * makelink -- * make a link from source to destination */ static void makelink(const char *from_name, const char *to_name, const struct stat *target_sb) { char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN]; struct stat to_sb; /* Try hard links first. */ if (dolink & (LN_HARD|LN_MIXED)) { if (do_link(from_name, to_name, target_sb) == -1) { if ((dolink & LN_HARD) || errno != EXDEV) err(EX_OSERR, "link %s -> %s", from_name, to_name); } else { if (stat(to_name, &to_sb)) err(EX_OSERR, "%s: stat", to_name); if (S_ISREG(to_sb.st_mode)) { /* * XXX: hard links to anything other than * plain files are not metalogged */ int omode; const char *oowner, *ogroup; char *offlags; char *dres; /* * XXX: use underlying perms, unless * overridden on command line. */ omode = mode; if (!haveopt_m) mode = (to_sb.st_mode & 0777); oowner = owner; if (!haveopt_o) owner = NULL; ogroup = group; if (!haveopt_g) group = NULL; offlags = fflags; if (!haveopt_f) fflags = NULL; dres = digest_file(from_name); metadata_log(to_name, "file", NULL, NULL, dres, to_sb.st_size); free(dres); mode = omode; owner = oowner; group = ogroup; fflags = offlags; } return; } } /* Symbolic links. */ if (dolink & LN_ABSOLUTE) { /* Convert source path to absolute. */ if (realpath(from_name, src) == NULL) err(EX_OSERR, "%s: realpath", from_name); do_symlink(src, to_name, target_sb); /* XXX: src may point outside of destdir */ metadata_log(to_name, "link", NULL, src, NULL, 0); return; } if (dolink & LN_RELATIVE) { char *to_name_copy, *cp, *d, *s; if (*from_name != '/') { /* this is already a relative link */ do_symlink(from_name, to_name, target_sb); /* XXX: from_name may point outside of destdir. */ metadata_log(to_name, "link", NULL, from_name, NULL, 0); return; } /* Resolve pathnames. */ if (realpath(from_name, src) == NULL) err(EX_OSERR, "%s: realpath", from_name); /* * The last component of to_name may be a symlink, * so use realpath to resolve only the directory. */ to_name_copy = strdup(to_name); if (to_name_copy == NULL) err(EX_OSERR, "%s: strdup", to_name); cp = dirname(to_name_copy); if (realpath(cp, dst) == NULL) err(EX_OSERR, "%s: realpath", cp); /* .. and add the last component. */ if (strcmp(dst, "/") != 0) { if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst)) errx(1, "resolved pathname too long"); } strcpy(to_name_copy, to_name); cp = basename(to_name_copy); if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst)) errx(1, "resolved pathname too long"); free(to_name_copy); /* Trim common path components. */ for (s = src, d = dst; *s == *d; s++, d++) continue; while (*s != '/') s--, d--; /* Count the number of directories we need to backtrack. */ for (++d, lnk[0] = '\0'; *d; d++) if (*d == '/') (void)strlcat(lnk, "../", sizeof(lnk)); (void)strlcat(lnk, ++s, sizeof(lnk)); do_symlink(lnk, to_name, target_sb); /* XXX: Link may point outside of destdir. */ metadata_log(to_name, "link", NULL, lnk, NULL, 0); return; } /* * If absolute or relative was not specified, try the names the * user provided. */ do_symlink(from_name, to_name, target_sb); /* XXX: from_name may point outside of destdir. */ metadata_log(to_name, "link", NULL, from_name, NULL, 0); } /* * install -- * build a path name and install the file */ static void install(const char *from_name, const char *to_name, u_long fset, u_int flags) { struct stat from_sb, temp_sb, to_sb; struct timespec tsb[2]; int devnull, files_match, from_fd, serrno, target; int tempcopy, temp_fd, to_fd; char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN]; char *digestresult; files_match = 0; from_fd = -1; to_fd = -1; /* If try to install NULL file to a directory, fails. */ if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) { if (!dolink) { if (stat(from_name, &from_sb)) err(EX_OSERR, "%s", from_name); if (!S_ISREG(from_sb.st_mode)) { errno = EFTYPE; err(EX_OSERR, "%s", from_name); } } /* Build the target path. */ if (flags & DIRECTORY) { (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s%s", to_name, to_name[strlen(to_name) - 1] == '/' ? "" : "/", (p = strrchr(from_name, '/')) ? ++p : from_name); to_name = pathbuf; } devnull = 0; } else { devnull = 1; } target = (lstat(to_name, &to_sb) == 0); if (dolink) { if (target && !safecopy) { if (to_sb.st_mode & S_IFDIR && rmdir(to_name) == -1) err(EX_OSERR, "%s", to_name); +#if HAVE_STRUCT_STAT_ST_FLAGS if (to_sb.st_flags & NOCHANGEBITS) (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS); +#endif unlink(to_name); } makelink(from_name, to_name, target ? &to_sb : NULL); return; } if (target && !S_ISREG(to_sb.st_mode) && !S_ISLNK(to_sb.st_mode)) { errno = EFTYPE; warn("%s", to_name); return; } /* Only copy safe if the target exists. */ tempcopy = safecopy && target; if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0) err(EX_OSERR, "%s", from_name); /* If we don't strip, we can compare first. */ if (docompare && !dostrip && target && S_ISREG(to_sb.st_mode)) { if ((to_fd = open(to_name, O_RDONLY, 0)) < 0) err(EX_OSERR, "%s", to_name); if (devnull) files_match = to_sb.st_size == 0; else files_match = !(compare(from_fd, from_name, (size_t)from_sb.st_size, to_fd, to_name, (size_t)to_sb.st_size, &digestresult)); /* Close "to" file unless we match. */ if (!files_match) (void)close(to_fd); } if (!files_match) { if (tempcopy) { to_fd = create_tempfile(to_name, tempfile, sizeof(tempfile)); if (to_fd < 0) err(EX_OSERR, "%s", tempfile); } else { if ((to_fd = create_newfile(to_name, target, &to_sb)) < 0) err(EX_OSERR, "%s", to_name); if (verbose) (void)printf("install: %s -> %s\n", from_name, to_name); } if (!devnull) digestresult = copy(from_fd, from_name, to_fd, tempcopy ? tempfile : to_name, from_sb.st_size); else digestresult = NULL; } if (dostrip) { strip(tempcopy ? tempfile : to_name); /* * Re-open our fd on the target, in case we used a strip * that does not work in-place -- like GNU binutils strip. */ close(to_fd); to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0); if (to_fd < 0) err(EX_OSERR, "stripping %s", to_name); } /* * Compare the stripped temp file with the target. */ if (docompare && dostrip && target && S_ISREG(to_sb.st_mode)) { temp_fd = to_fd; /* Re-open to_fd using the real target name. */ if ((to_fd = open(to_name, O_RDONLY, 0)) < 0) err(EX_OSERR, "%s", to_name); if (fstat(temp_fd, &temp_sb)) { serrno = errno; (void)unlink(tempfile); errno = serrno; err(EX_OSERR, "%s", tempfile); } if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd, to_name, (size_t)to_sb.st_size, &digestresult) == 0) { /* * If target has more than one link we need to * replace it in order to snap the extra links. * Need to preserve target file times, though. */ if (to_sb.st_nlink != 1) { tsb[0] = to_sb.st_atim; tsb[1] = to_sb.st_mtim; (void)utimensat(AT_FDCWD, tempfile, tsb, 0); } else { files_match = 1; (void)unlink(tempfile); } (void) close(temp_fd); } } else if (dostrip) digestresult = digest_file(tempfile); /* * Move the new file into place if doing a safe copy * and the files are different (or just not compared). */ if (tempcopy && !files_match) { +#if HAVE_STRUCT_STAT_ST_FLAGS /* Try to turn off the immutable bits. */ if (to_sb.st_flags & NOCHANGEBITS) (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS); +#endif if (dobackup) { if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name, suffix) != strlen(to_name) + strlen(suffix)) { unlink(tempfile); errx(EX_OSERR, "%s: backup filename too long", to_name); } if (verbose) (void)printf("install: %s -> %s\n", to_name, backup); if (unlink(backup) < 0 && errno != ENOENT) { serrno = errno; +#if HAVE_STRUCT_STAT_ST_FLAGS if (to_sb.st_flags & NOCHANGEBITS) (void)chflags(to_name, to_sb.st_flags); +#endif unlink(tempfile); errno = serrno; err(EX_OSERR, "unlink: %s", backup); } if (link(to_name, backup) < 0) { serrno = errno; unlink(tempfile); +#if HAVE_STRUCT_STAT_ST_FLAGS if (to_sb.st_flags & NOCHANGEBITS) (void)chflags(to_name, to_sb.st_flags); +#endif errno = serrno; err(EX_OSERR, "link: %s to %s", to_name, backup); } } if (verbose) (void)printf("install: %s -> %s\n", from_name, to_name); if (rename(tempfile, to_name) < 0) { serrno = errno; unlink(tempfile); errno = serrno; err(EX_OSERR, "rename: %s to %s", tempfile, to_name); } /* Re-open to_fd so we aren't hosed by the rename(2). */ (void) close(to_fd); if ((to_fd = open(to_name, O_RDONLY, 0)) < 0) err(EX_OSERR, "%s", to_name); } /* * Preserve the timestamp of the source file if necessary. */ if (dopreserve && !files_match && !devnull) { tsb[0] = from_sb.st_atim; tsb[1] = from_sb.st_mtim; (void)utimensat(AT_FDCWD, to_name, tsb, 0); } if (fstat(to_fd, &to_sb) == -1) { serrno = errno; (void)unlink(to_name); errno = serrno; err(EX_OSERR, "%s", to_name); } /* * Set owner, group, mode for target; do the chown first, * chown may lose the setuid bits. */ if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) || (uid != (uid_t)-1 && uid != to_sb.st_uid) || (mode != (to_sb.st_mode & ALLPERMS)))) { +#if HAVE_STRUCT_STAT_ST_FLAGS /* Try to turn off the immutable bits. */ if (to_sb.st_flags & NOCHANGEBITS) (void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS); +#endif } if (!dounpriv & (gid != (gid_t)-1 && gid != to_sb.st_gid) || (uid != (uid_t)-1 && uid != to_sb.st_uid)) if (fchown(to_fd, uid, gid) == -1) { serrno = errno; (void)unlink(to_name); errno = serrno; err(EX_OSERR,"%s: chown/chgrp", to_name); } if (mode != (to_sb.st_mode & ALLPERMS)) { if (fchmod(to_fd, dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) { serrno = errno; (void)unlink(to_name); errno = serrno; err(EX_OSERR, "%s: chmod", to_name); } } - +#if HAVE_STRUCT_STAT_ST_FLAGS /* * If provided a set of flags, set them, otherwise, preserve the * flags, except for the dump flag. * NFS does not support flags. Ignore EOPNOTSUPP flags if we're just * trying to turn off UF_NODUMP. If we're trying to set real flags, * then warn if the fs doesn't support it, otherwise fail. */ if (!dounpriv & !devnull && (flags & SETFLAGS || (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) && fchflags(to_fd, flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) { if (flags & SETFLAGS) { if (errno == EOPNOTSUPP) warn("%s: chflags", to_name); else { serrno = errno; (void)unlink(to_name); errno = serrno; err(EX_OSERR, "%s: chflags", to_name); } } } +#endif (void)close(to_fd); if (!devnull) (void)close(from_fd); metadata_log(to_name, "file", tsb, NULL, digestresult, to_sb.st_size); free(digestresult); } /* * compare -- * compare two files; non-zero means files differ */ static int compare(int from_fd, const char *from_name __unused, size_t from_len, int to_fd, const char *to_name __unused, size_t to_len, char **dresp) { char *p, *q; int rv; int done_compare; DIGEST_CTX ctx; rv = 0; if (from_len != to_len) return 1; if (from_len <= MAX_CMP_SIZE) { if (dresp != NULL) digest_init(&ctx); done_compare = 0; if (trymmap(from_fd) && trymmap(to_fd)) { p = mmap(NULL, from_len, PROT_READ, MAP_SHARED, from_fd, (off_t)0); if (p == MAP_FAILED) goto out; q = mmap(NULL, from_len, PROT_READ, MAP_SHARED, to_fd, (off_t)0); if (q == MAP_FAILED) { munmap(p, from_len); goto out; } rv = memcmp(p, q, from_len); if (dresp != NULL) digest_update(&ctx, p, from_len); munmap(p, from_len); munmap(q, from_len); done_compare = 1; } out: if (!done_compare) { char buf1[MAXBSIZE]; char buf2[MAXBSIZE]; int n1, n2; rv = 0; lseek(from_fd, 0, SEEK_SET); lseek(to_fd, 0, SEEK_SET); while (rv == 0) { n1 = read(from_fd, buf1, sizeof(buf1)); if (n1 == 0) break; /* EOF */ else if (n1 > 0) { n2 = read(to_fd, buf2, n1); if (n2 == n1) rv = memcmp(buf1, buf2, n1); else rv = 1; /* out of sync */ } else rv = 1; /* read failure */ digest_update(&ctx, buf1, n1); } lseek(from_fd, 0, SEEK_SET); lseek(to_fd, 0, SEEK_SET); } } else rv = 1; /* don't bother in this case */ if (dresp != NULL) { if (rv == 0) *dresp = digest_end(&ctx, NULL); else (void)digest_end(&ctx, NULL); } return rv; } /* * create_tempfile -- * create a temporary file based on path and open it */ static int create_tempfile(const char *path, char *temp, size_t tsize) { char *p; (void)strncpy(temp, path, tsize); temp[tsize - 1] = '\0'; if ((p = strrchr(temp, '/')) != NULL) p++; else p = temp; (void)strncpy(p, "INS@XXXX", &temp[tsize - 1] - p); temp[tsize - 1] = '\0'; return (mkstemp(temp)); } /* * create_newfile -- * create a new file, overwriting an existing one if necessary */ static int create_newfile(const char *path, int target, struct stat *sbp) { char backup[MAXPATHLEN]; int saved_errno = 0; int newfd; if (target) { /* * Unlink now... avoid ETXTBSY errors later. Try to turn * off the append/immutable bits -- if we fail, go ahead, * it might work. */ +#if HAVE_STRUCT_STAT_ST_FLAGS if (sbp->st_flags & NOCHANGEBITS) (void)chflags(path, sbp->st_flags & ~NOCHANGEBITS); +#endif if (dobackup) { if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", path, suffix) != strlen(path) + strlen(suffix)) { saved_errno = errno; +#if HAVE_STRUCT_STAT_ST_FLAGS if (sbp->st_flags & NOCHANGEBITS) (void)chflags(path, sbp->st_flags); +#endif errno = saved_errno; errx(EX_OSERR, "%s: backup filename too long", path); } (void)snprintf(backup, MAXPATHLEN, "%s%s", path, suffix); if (verbose) (void)printf("install: %s -> %s\n", path, backup); if (rename(path, backup) < 0) { saved_errno = errno; +#if HAVE_STRUCT_STAT_ST_FLAGS if (sbp->st_flags & NOCHANGEBITS) (void)chflags(path, sbp->st_flags); +#endif errno = saved_errno; err(EX_OSERR, "rename: %s to %s", path, backup); } } else if (unlink(path) < 0) saved_errno = errno; } newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR); if (newfd < 0 && saved_errno != 0) errno = saved_errno; return newfd; } /* * copy -- * copy from one file to another */ static char * copy(int from_fd, const char *from_name, int to_fd, const char *to_name, off_t size) { int nr, nw; int serrno; char *p; char buf[MAXBSIZE]; int done_copy; DIGEST_CTX ctx; /* Rewind file descriptors. */ if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1) err(EX_OSERR, "lseek: %s", from_name); if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1) err(EX_OSERR, "lseek: %s", to_name); digest_init(&ctx); /* * Mmap and write if less than 8M (the limit is so we don't totally * trash memory on big files. This is really a minor hack, but it * wins some CPU back. */ done_copy = 0; if (size <= 8 * 1048576 && trymmap(from_fd) && (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED, from_fd, (off_t)0)) != MAP_FAILED) { nw = write(to_fd, p, size); if (nw != size) { serrno = errno; (void)unlink(to_name); if (nw >= 0) { errx(EX_OSERR, "short write to %s: %jd bytes written, %jd bytes asked to write", to_name, (uintmax_t)nw, (uintmax_t)size); } else { errno = serrno; err(EX_OSERR, "%s", to_name); } } digest_update(&ctx, p, size); (void)munmap(p, size); done_copy = 1; } if (!done_copy) { while ((nr = read(from_fd, buf, sizeof(buf))) > 0) { if ((nw = write(to_fd, buf, nr)) != nr) { serrno = errno; (void)unlink(to_name); if (nw >= 0) { errx(EX_OSERR, "short write to %s: %jd bytes written, %jd bytes asked to write", to_name, (uintmax_t)nw, (uintmax_t)size); } else { errno = serrno; err(EX_OSERR, "%s", to_name); } } digest_update(&ctx, buf, nr); } if (nr != 0) { serrno = errno; (void)unlink(to_name); errno = serrno; err(EX_OSERR, "%s", from_name); } } return (digest_end(&ctx, NULL)); } /* * strip -- * use strip(1) to strip the target file */ static void strip(const char *to_name) { const char *stripbin; const char *args[3]; pid_t pid; int error, status; stripbin = getenv("STRIPBIN"); if (stripbin == NULL) stripbin = "strip"; args[0] = stripbin; args[1] = to_name; args[2] = NULL; error = posix_spawnp(&pid, stripbin, NULL, NULL, __DECONST(char **, args), environ); if (error != 0) { (void)unlink(to_name); errc(error == EAGAIN || error == EPROCLIM || error == ENOMEM ? EX_TEMPFAIL : EX_OSERR, error, "spawn %s", stripbin); } if (waitpid(pid, &status, 0) == -1) { error = errno; (void)unlink(to_name); errc(EX_SOFTWARE, error, "wait"); /* NOTREACHED */ } if (status != 0) { (void)unlink(to_name); errx(EX_SOFTWARE, "strip command %s failed on %s", stripbin, to_name); } } /* * install_dir -- * build directory hierarchy */ static void install_dir(char *path) { char *p; struct stat sb; int ch, tried_mkdir; for (p = path;; ++p) if (!*p || (p != path && *p == '/')) { tried_mkdir = 0; ch = *p; *p = '\0'; again: if (stat(path, &sb) < 0) { if (errno != ENOENT || tried_mkdir) err(EX_OSERR, "stat %s", path); if (mkdir(path, 0755) < 0) { tried_mkdir = 1; if (errno == EEXIST) goto again; err(EX_OSERR, "mkdir %s", path); } if (verbose) (void)printf("install: mkdir %s\n", path); } else if (!S_ISDIR(sb.st_mode)) errx(EX_OSERR, "%s exists but is not a directory", path); if (!(*p = ch)) break; } if (!dounpriv) { if ((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid)) warn("chown %u:%u %s", uid, gid, path); /* XXXBED: should we do the chmod in the dounpriv case? */ if (chmod(path, mode)) warn("chmod %o %s", mode, path); } metadata_log(path, "dir", NULL, NULL, NULL, 0); } /* * metadata_log -- * if metafp is not NULL, output mtree(8) full path name and settings to * metafp, to allow permissions to be set correctly by other tools, * or to allow integrity checks to be performed. */ static void metadata_log(const char *path, const char *type, struct timespec *ts, const char *slink, const char *digestresult, off_t size) { static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' }; const char *p; char *buf; size_t destlen; struct flock metalog_lock; if (!metafp) return; /* Buffer for strsvis(3). */ buf = (char *)malloc(4 * strlen(path) + 1); if (buf == NULL) { warnx("%s", strerror(ENOMEM)); return; } /* Lock log file. */ metalog_lock.l_start = 0; metalog_lock.l_len = 0; metalog_lock.l_whence = SEEK_SET; metalog_lock.l_type = F_WRLCK; if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) { warn("can't lock %s", metafile); free(buf); return; } /* Remove destdir. */ p = path; if (destdir) { destlen = strlen(destdir); if (strncmp(p, destdir, destlen) == 0 && (p[destlen] == '/' || p[destlen] == '\0')) p += destlen; } while (*p && *p == '/') p++; strsvis(buf, p, VIS_OCTAL, extra); p = buf; /* Print details. */ fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type); if (owner) fprintf(metafp, " uname=%s", owner); if (group) fprintf(metafp, " gname=%s", group); fprintf(metafp, " mode=%#o", mode); if (slink) { strsvis(buf, slink, VIS_CSTYLE, extra); /* encode link */ fprintf(metafp, " link=%s", buf); } if (*type == 'f') /* type=file */ fprintf(metafp, " size=%lld", (long long)size); if (ts != NULL && dopreserve) fprintf(metafp, " time=%lld.%09ld", (long long)ts[1].tv_sec, ts[1].tv_nsec); if (digestresult && digest) fprintf(metafp, " %s=%s", digest, digestresult); if (fflags) fprintf(metafp, " flags=%s", fflags); if (tags) fprintf(metafp, " tags=%s", tags); fputc('\n', metafp); /* Flush line. */ fflush(metafp); /* Unlock log file. */ metalog_lock.l_type = F_UNLCK; if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) warn("can't unlock %s", metafile); free(buf); } /* * usage -- * print a usage message and die */ static void usage(void) { (void)fprintf(stderr, "usage: install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n" " [-M log] [-D dest] [-h hash] [-T tags]\n" " [-B suffix] [-l linkflags] [-N dbdir]\n" " file1 file2\n" " install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n" " [-M log] [-D dest] [-h hash] [-T tags]\n" " [-B suffix] [-l linkflags] [-N dbdir]\n" " file1 ... fileN directory\n" " install -dU [-vU] [-g group] [-m mode] [-N dbdir] [-o owner]\n" " [-M log] [-D dest] [-h hash] [-T tags]\n" " directory ...\n"); exit(EX_USAGE); /* NOTREACHED */ } /* * trymmap -- * return true (1) if mmap should be tried, false (0) if not. */ static int trymmap(int fd) { /* * The ifdef is for bootstrapping - f_fstypename doesn't exist in * pre-Lite2-merge systems. */ #ifdef MFSNAMELEN struct statfs stfs; if (fstatfs(fd, &stfs) != 0) return (0); if (strcmp(stfs.f_fstypename, "ufs") == 0 || strcmp(stfs.f_fstypename, "cd9660") == 0) return (1); #endif return (0); } Index: head/usr.sbin/makefs/ffs.c =================================================================== --- head/usr.sbin/makefs/ffs.c (revision 328063) +++ head/usr.sbin/makefs/ffs.c (revision 328064) @@ -1,1181 +1,1185 @@ /* $NetBSD: ffs.c,v 1.45 2011/10/09 22:49:26 christos Exp $ */ /*- * SPDX-License-Identifier: BSD-4-Clause * * Copyright (c) 2001 Wasabi Systems, Inc. * All rights reserved. * * Written by Luke Mewburn for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)ffs_alloc.c 8.19 (Berkeley) 7/13/95 */ #include __FBSDID("$FreeBSD$"); +#if HAVE_NBTOOL_CONFIG_H +#include "nbtool_config.h" +#endif + #include #include #include #include #include #include #include #include #include #include #include #include #include #include "makefs.h" #include "ffs.h" #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS #include #endif #include #include #include #include "ffs/ufs_bswap.h" #include "ffs/ufs_inode.h" #include "ffs/newfs_extern.h" #include "ffs/ffs_extern.h" #undef DIP #define DIP(dp, field) \ ((ffs_opts->version == 1) ? \ (dp)->ffs1_din.di_##field : (dp)->ffs2_din.di_##field) /* * Various file system defaults (cribbed from newfs(8)). */ #define DFL_FRAGSIZE 1024 /* fragment size */ #define DFL_BLKSIZE 8192 /* block size */ #define DFL_SECSIZE 512 /* sector size */ #define DFL_CYLSPERGROUP 65536 /* cylinders per group */ #define DFL_FRAGSPERINODE 4 /* fragments per inode */ #define DFL_ROTDELAY 0 /* rotational delay */ #define DFL_NRPOS 1 /* rotational positions */ #define DFL_RPM 3600 /* rpm of disk */ #define DFL_NSECTORS 64 /* # of sectors */ #define DFL_NTRACKS 16 /* # of tracks */ typedef struct { u_char *buf; /* buf for directory */ doff_t size; /* full size of buf */ doff_t cur; /* offset of current entry */ } dirbuf_t; static int ffs_create_image(const char *, fsinfo_t *); static void ffs_dump_fsinfo(fsinfo_t *); static void ffs_dump_dirbuf(dirbuf_t *, const char *, int); static void ffs_make_dirbuf(dirbuf_t *, const char *, fsnode *, int); static int ffs_populate_dir(const char *, fsnode *, fsinfo_t *); static void ffs_size_dir(fsnode *, fsinfo_t *); static void ffs_validate(const char *, fsnode *, fsinfo_t *); static void ffs_write_file(union dinode *, uint32_t, void *, fsinfo_t *); static void ffs_write_inode(union dinode *, uint32_t, const fsinfo_t *); static void *ffs_build_dinode1(struct ufs1_dinode *, dirbuf_t *, fsnode *, fsnode *, fsinfo_t *); static void *ffs_build_dinode2(struct ufs2_dinode *, dirbuf_t *, fsnode *, fsnode *, fsinfo_t *); /* publicly visible functions */ void ffs_prep_opts(fsinfo_t *fsopts) { ffs_opt_t *ffs_opts = ecalloc(1, sizeof(*ffs_opts)); const option_t ffs_options[] = { { 'b', "bsize", &ffs_opts->bsize, OPT_INT32, 1, INT_MAX, "block size" }, { 'f', "fsize", &ffs_opts->fsize, OPT_INT32, 1, INT_MAX, "fragment size" }, { 'd', "density", &ffs_opts->density, OPT_INT32, 1, INT_MAX, "bytes per inode" }, { 'm', "minfree", &ffs_opts->minfree, OPT_INT32, 0, 99, "minfree" }, { 'M', "maxbpg", &ffs_opts->maxbpg, OPT_INT32, 1, INT_MAX, "max blocks per file in a cg" }, { 'a', "avgfilesize", &ffs_opts->avgfilesize, OPT_INT32, 1, INT_MAX, "expected average file size" }, { 'n', "avgfpdir", &ffs_opts->avgfpdir, OPT_INT32, 1, INT_MAX, "expected # of files per directory" }, { 'x', "extent", &ffs_opts->maxbsize, OPT_INT32, 1, INT_MAX, "maximum # extent size" }, { 'g', "maxbpcg", &ffs_opts->maxblkspercg, OPT_INT32, 1, INT_MAX, "max # of blocks per group" }, { 'v', "version", &ffs_opts->version, OPT_INT32, 1, 2, "UFS version" }, { 'o', "optimization", NULL, OPT_STRBUF, 0, 0, "Optimization (time|space)" }, { 'l', "label", ffs_opts->label, OPT_STRARRAY, 1, sizeof(ffs_opts->label), "UFS label" }, { 's', "softupdates", &ffs_opts->softupdates, OPT_INT32, 0, 1, "enable softupdates" }, { .name = NULL } }; ffs_opts->bsize= -1; ffs_opts->fsize= -1; ffs_opts->cpg= -1; ffs_opts->density= -1; ffs_opts->minfree= -1; ffs_opts->optimization= -1; ffs_opts->maxcontig= -1; ffs_opts->maxbpg= -1; ffs_opts->avgfilesize= -1; ffs_opts->avgfpdir= -1; ffs_opts->version = 1; ffs_opts->softupdates = 0; fsopts->fs_specific = ffs_opts; fsopts->fs_options = copy_opts(ffs_options); } void ffs_cleanup_opts(fsinfo_t *fsopts) { free(fsopts->fs_specific); free(fsopts->fs_options); } int ffs_parse_opts(const char *option, fsinfo_t *fsopts) { ffs_opt_t *ffs_opts = fsopts->fs_specific; option_t *ffs_options = fsopts->fs_options; char buf[1024]; int rv; assert(option != NULL); assert(fsopts != NULL); assert(ffs_opts != NULL); if (debug & DEBUG_FS_PARSE_OPTS) printf("ffs_parse_opts: got `%s'\n", option); rv = set_option(ffs_options, option, buf, sizeof(buf)); if (rv == -1) return 0; if (ffs_options[rv].name == NULL) abort(); switch (ffs_options[rv].letter) { case 'o': if (strcmp(buf, "time") == 0) { ffs_opts->optimization = FS_OPTTIME; } else if (strcmp(buf, "space") == 0) { ffs_opts->optimization = FS_OPTSPACE; } else { warnx("Invalid optimization `%s'", buf); return 0; } break; default: break; } return 1; } void ffs_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts) { struct fs *superblock; struct timeval start; assert(image != NULL); assert(dir != NULL); assert(root != NULL); assert(fsopts != NULL); if (debug & DEBUG_FS_MAKEFS) printf("ffs_makefs: image %s directory %s root %p\n", image, dir, root); /* validate tree and options */ TIMER_START(start); ffs_validate(dir, root, fsopts); TIMER_RESULTS(start, "ffs_validate"); printf("Calculated size of `%s': %lld bytes, %lld inodes\n", image, (long long)fsopts->size, (long long)fsopts->inodes); /* create image */ TIMER_START(start); if (ffs_create_image(image, fsopts) == -1) errx(1, "Image file `%s' not created.", image); TIMER_RESULTS(start, "ffs_create_image"); fsopts->curinode = UFS_ROOTINO; if (debug & DEBUG_FS_MAKEFS) putchar('\n'); /* populate image */ printf("Populating `%s'\n", image); TIMER_START(start); if (! ffs_populate_dir(dir, root, fsopts)) errx(1, "Image file `%s' not populated.", image); TIMER_RESULTS(start, "ffs_populate_dir"); /* ensure no outstanding buffers remain */ if (debug & DEBUG_FS_MAKEFS) bcleanup(); /* update various superblock parameters */ superblock = fsopts->superblock; superblock->fs_fmod = 0; superblock->fs_old_cstotal.cs_ndir = superblock->fs_cstotal.cs_ndir; superblock->fs_old_cstotal.cs_nbfree = superblock->fs_cstotal.cs_nbfree; superblock->fs_old_cstotal.cs_nifree = superblock->fs_cstotal.cs_nifree; superblock->fs_old_cstotal.cs_nffree = superblock->fs_cstotal.cs_nffree; /* write out superblock; image is now complete */ ffs_write_superblock(fsopts->superblock, fsopts); if (close(fsopts->fd) == -1) err(1, "Closing `%s'", image); fsopts->fd = -1; printf("Image `%s' complete\n", image); } /* end of public functions */ static void ffs_validate(const char *dir, fsnode *root, fsinfo_t *fsopts) { int32_t ncg = 1; -#if notyet +#ifdef notyet int32_t spc, nspf, ncyl, fssize; #endif ffs_opt_t *ffs_opts = fsopts->fs_specific; assert(dir != NULL); assert(root != NULL); assert(fsopts != NULL); assert(ffs_opts != NULL); if (debug & DEBUG_FS_VALIDATE) { printf("ffs_validate: before defaults set:\n"); ffs_dump_fsinfo(fsopts); } /* set FFS defaults */ if (fsopts->sectorsize == -1) fsopts->sectorsize = DFL_SECSIZE; if (ffs_opts->fsize == -1) ffs_opts->fsize = MAX(DFL_FRAGSIZE, fsopts->sectorsize); if (ffs_opts->bsize == -1) ffs_opts->bsize = MIN(DFL_BLKSIZE, 8 * ffs_opts->fsize); if (ffs_opts->cpg == -1) ffs_opts->cpg = DFL_CYLSPERGROUP; else ffs_opts->cpgflg = 1; /* fsopts->density is set below */ if (ffs_opts->nsectors == -1) ffs_opts->nsectors = DFL_NSECTORS; if (ffs_opts->minfree == -1) ffs_opts->minfree = MINFREE; if (ffs_opts->optimization == -1) ffs_opts->optimization = DEFAULTOPT; if (ffs_opts->maxcontig == -1) ffs_opts->maxcontig = MAX(1, MIN(MAXPHYS, FFS_MAXBSIZE) / ffs_opts->bsize); /* XXX ondisk32 */ if (ffs_opts->maxbpg == -1) ffs_opts->maxbpg = ffs_opts->bsize / sizeof(int32_t); if (ffs_opts->avgfilesize == -1) ffs_opts->avgfilesize = AVFILESIZ; if (ffs_opts->avgfpdir == -1) ffs_opts->avgfpdir = AFPDIR; if (fsopts->maxsize > 0 && roundup(fsopts->minsize, ffs_opts->bsize) > fsopts->maxsize) errx(1, "`%s' minsize of %lld rounded up to ffs bsize of %d " "exceeds maxsize %lld. Lower bsize, or round the minimum " "and maximum sizes to bsize.", dir, (long long)fsopts->minsize, ffs_opts->bsize, (long long)fsopts->maxsize); /* calculate size of tree */ ffs_size_dir(root, fsopts); fsopts->inodes += UFS_ROOTINO; /* include first two inodes */ if (debug & DEBUG_FS_VALIDATE) printf("ffs_validate: size of tree: %lld bytes, %lld inodes\n", (long long)fsopts->size, (long long)fsopts->inodes); /* add requested slop */ fsopts->size += fsopts->freeblocks; fsopts->inodes += fsopts->freefiles; if (fsopts->freefilepc > 0) fsopts->inodes = fsopts->inodes * (100 + fsopts->freefilepc) / 100; if (fsopts->freeblockpc > 0) fsopts->size = fsopts->size * (100 + fsopts->freeblockpc) / 100; /* add space needed for superblocks */ /* * The old SBOFF (SBLOCK_UFS1) is used here because makefs is * typically used for small filesystems where space matters. * XXX make this an option. */ fsopts->size += (SBLOCK_UFS1 + SBLOCKSIZE) * ncg; /* add space needed to store inodes, x3 for blockmaps, etc */ if (ffs_opts->version == 1) fsopts->size += ncg * DINODE1_SIZE * roundup(fsopts->inodes / ncg, ffs_opts->bsize / DINODE1_SIZE); else fsopts->size += ncg * DINODE2_SIZE * roundup(fsopts->inodes / ncg, ffs_opts->bsize / DINODE2_SIZE); /* add minfree */ if (ffs_opts->minfree > 0) fsopts->size = fsopts->size * (100 + ffs_opts->minfree) / 100; /* * XXX any other fs slop to add, such as csum's, bitmaps, etc ?? */ if (fsopts->size < fsopts->minsize) /* ensure meets minimum size */ fsopts->size = fsopts->minsize; /* round up to the next block */ fsopts->size = roundup(fsopts->size, ffs_opts->bsize); /* round up to requested block size, if any */ if (fsopts->roundup > 0) fsopts->size = roundup(fsopts->size, fsopts->roundup); /* calculate density if necessary */ if (ffs_opts->density == -1) ffs_opts->density = fsopts->size / fsopts->inodes + 1; if (debug & DEBUG_FS_VALIDATE) { printf("ffs_validate: after defaults set:\n"); ffs_dump_fsinfo(fsopts); printf("ffs_validate: dir %s; %lld bytes, %lld inodes\n", dir, (long long)fsopts->size, (long long)fsopts->inodes); } /* now check calculated sizes vs requested sizes */ if (fsopts->maxsize > 0 && fsopts->size > fsopts->maxsize) { errx(1, "`%s' size of %lld is larger than the maxsize of %lld.", dir, (long long)fsopts->size, (long long)fsopts->maxsize); } } static void ffs_dump_fsinfo(fsinfo_t *f) { ffs_opt_t *fs = f->fs_specific; printf("fsopts at %p\n", f); printf("\tsize %lld, inodes %lld, curinode %u\n", (long long)f->size, (long long)f->inodes, f->curinode); printf("\tminsize %lld, maxsize %lld\n", (long long)f->minsize, (long long)f->maxsize); printf("\tfree files %lld, freefile %% %d\n", (long long)f->freefiles, f->freefilepc); printf("\tfree blocks %lld, freeblock %% %d\n", (long long)f->freeblocks, f->freeblockpc); printf("\tneedswap %d, sectorsize %d\n", f->needswap, f->sectorsize); printf("\tbsize %d, fsize %d, cpg %d, density %d\n", fs->bsize, fs->fsize, fs->cpg, fs->density); printf("\tnsectors %d, rpm %d, minfree %d\n", fs->nsectors, fs->rpm, fs->minfree); printf("\tmaxcontig %d, maxbpg %d\n", fs->maxcontig, fs->maxbpg); printf("\toptimization %s\n", fs->optimization == FS_OPTSPACE ? "space" : "time"); } static int ffs_create_image(const char *image, fsinfo_t *fsopts) { #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS struct statvfs sfs; #endif struct fs *fs; char *buf; int i, bufsize; off_t bufrem; int oflags = O_RDWR | O_CREAT; time_t tstamp; assert (image != NULL); assert (fsopts != NULL); /* create image */ if (fsopts->offset == 0) oflags |= O_TRUNC; if ((fsopts->fd = open(image, oflags, 0666)) == -1) { warn("Can't open `%s' for writing", image); return (-1); } /* zero image */ #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS if (fstatvfs(fsopts->fd, &sfs) == -1) { #endif bufsize = 8192; #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS warn("can't fstatvfs `%s', using default %d byte chunk", image, bufsize); } else bufsize = sfs.f_iosize; #endif bufrem = fsopts->size; if (fsopts->sparse) { if (ftruncate(fsopts->fd, bufrem) == -1) { warn("sparse option disabled."); fsopts->sparse = 0; } } if (fsopts->sparse) { /* File truncated at bufrem. Remaining is 0 */ bufrem = 0; buf = NULL; } else { if (debug & DEBUG_FS_CREATE_IMAGE) printf("zero-ing image `%s', %lld sectors, " "using %d byte chunks\n", image, (long long)bufrem, bufsize); buf = ecalloc(1, bufsize); } if (fsopts->offset != 0) if (lseek(fsopts->fd, fsopts->offset, SEEK_SET) == -1) { warn("can't seek"); free(buf); return -1; } while (bufrem > 0) { i = write(fsopts->fd, buf, MIN(bufsize, bufrem)); if (i == -1) { warn("zeroing image, %lld bytes to go", (long long)bufrem); free(buf); return (-1); } bufrem -= i; } if (buf) free(buf); /* make the file system */ if (debug & DEBUG_FS_CREATE_IMAGE) printf("calling mkfs(\"%s\", ...)\n", image); if (stampst.st_ino != 0) tstamp = stampst.st_ctime; else tstamp = start_time.tv_sec; srandom(tstamp); fs = ffs_mkfs(image, fsopts, tstamp); fsopts->superblock = (void *)fs; if (debug & DEBUG_FS_CREATE_IMAGE) { time_t t; t = (time_t)((struct fs *)fsopts->superblock)->fs_time; printf("mkfs returned %p; fs_time %s", fsopts->superblock, ctime(&t)); printf("fs totals: nbfree %lld, nffree %lld, nifree %lld, ndir %lld\n", (long long)fs->fs_cstotal.cs_nbfree, (long long)fs->fs_cstotal.cs_nffree, (long long)fs->fs_cstotal.cs_nifree, (long long)fs->fs_cstotal.cs_ndir); } if (fs->fs_cstotal.cs_nifree + UFS_ROOTINO < fsopts->inodes) { warnx( "Image file `%s' has %lld free inodes; %lld are required.", image, (long long)(fs->fs_cstotal.cs_nifree + UFS_ROOTINO), (long long)fsopts->inodes); return (-1); } return (fsopts->fd); } static void ffs_size_dir(fsnode *root, fsinfo_t *fsopts) { struct direct tmpdir; fsnode * node; int curdirsize, this; ffs_opt_t *ffs_opts = fsopts->fs_specific; /* node may be NULL (empty directory) */ assert(fsopts != NULL); assert(ffs_opts != NULL); if (debug & DEBUG_FS_SIZE_DIR) printf("ffs_size_dir: entry: bytes %lld inodes %lld\n", (long long)fsopts->size, (long long)fsopts->inodes); #define ADDDIRENT(e) do { \ tmpdir.d_namlen = strlen((e)); \ this = DIRSIZ_SWAP(0, &tmpdir, 0); \ if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT) \ printf("ADDDIRENT: was: %s (%d) this %d cur %d\n", \ e, tmpdir.d_namlen, this, curdirsize); \ if (this + curdirsize > roundup(curdirsize, DIRBLKSIZ)) \ curdirsize = roundup(curdirsize, DIRBLKSIZ); \ curdirsize += this; \ if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT) \ printf("ADDDIRENT: now: %s (%d) this %d cur %d\n", \ e, tmpdir.d_namlen, this, curdirsize); \ } while (0); /* * XXX this needs to take into account extra space consumed * by indirect blocks, etc. */ #define ADDSIZE(x) do { \ fsopts->size += roundup((x), ffs_opts->fsize); \ } while (0); curdirsize = 0; for (node = root; node != NULL; node = node->next) { ADDDIRENT(node->name); if (node == root) { /* we're at "." */ assert(strcmp(node->name, ".") == 0); ADDDIRENT(".."); } else if ((node->inode->flags & FI_SIZED) == 0) { /* don't count duplicate names */ node->inode->flags |= FI_SIZED; if (debug & DEBUG_FS_SIZE_DIR_NODE) printf("ffs_size_dir: `%s' size %lld\n", node->name, (long long)node->inode->st.st_size); fsopts->inodes++; if (node->type == S_IFREG) ADDSIZE(node->inode->st.st_size); if (node->type == S_IFLNK) { size_t slen; slen = strlen(node->symlink) + 1; if (slen >= (ffs_opts->version == 1 ? UFS1_MAXSYMLINKLEN : UFS2_MAXSYMLINKLEN)) ADDSIZE(slen); } } if (node->type == S_IFDIR) ffs_size_dir(node->child, fsopts); } ADDSIZE(curdirsize); if (debug & DEBUG_FS_SIZE_DIR) printf("ffs_size_dir: exit: size %lld inodes %lld\n", (long long)fsopts->size, (long long)fsopts->inodes); } static void * ffs_build_dinode1(struct ufs1_dinode *dinp, dirbuf_t *dbufp, fsnode *cur, fsnode *root, fsinfo_t *fsopts) { size_t slen; void *membuf; struct stat *st = stampst.st_ino != 0 ? &stampst : &cur->inode->st; memset(dinp, 0, sizeof(*dinp)); dinp->di_mode = cur->inode->st.st_mode; dinp->di_nlink = cur->inode->nlink; dinp->di_size = cur->inode->st.st_size; #if HAVE_STRUCT_STAT_ST_FLAGS dinp->di_flags = cur->inode->st.st_flags; #endif dinp->di_gen = random(); dinp->di_uid = cur->inode->st.st_uid; dinp->di_gid = cur->inode->st.st_gid; dinp->di_atime = st->st_atime; dinp->di_mtime = st->st_mtime; dinp->di_ctime = st->st_ctime; #if HAVE_STRUCT_STAT_ST_MTIMENSEC dinp->di_atimensec = st->st_atimensec; dinp->di_mtimensec = st->st_mtimensec; dinp->di_ctimensec = st->st_ctimensec; #endif /* not set: di_db, di_ib, di_blocks, di_spare */ membuf = NULL; if (cur == root) { /* "."; write dirbuf */ membuf = dbufp->buf; dinp->di_size = dbufp->size; } else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) { dinp->di_size = 0; /* a device */ dinp->di_rdev = ufs_rw32(cur->inode->st.st_rdev, fsopts->needswap); } else if (S_ISLNK(cur->type)) { /* symlink */ slen = strlen(cur->symlink); if (slen < UFS1_MAXSYMLINKLEN) { /* short link */ memcpy(dinp->di_db, cur->symlink, slen); } else membuf = cur->symlink; dinp->di_size = slen; } return membuf; } static void * ffs_build_dinode2(struct ufs2_dinode *dinp, dirbuf_t *dbufp, fsnode *cur, fsnode *root, fsinfo_t *fsopts) { size_t slen; void *membuf; struct stat *st = stampst.st_ino != 0 ? &stampst : &cur->inode->st; memset(dinp, 0, sizeof(*dinp)); dinp->di_mode = cur->inode->st.st_mode; dinp->di_nlink = cur->inode->nlink; dinp->di_size = cur->inode->st.st_size; #if HAVE_STRUCT_STAT_ST_FLAGS dinp->di_flags = cur->inode->st.st_flags; #endif dinp->di_gen = random(); dinp->di_uid = cur->inode->st.st_uid; dinp->di_gid = cur->inode->st.st_gid; dinp->di_atime = st->st_atime; dinp->di_mtime = st->st_mtime; dinp->di_ctime = st->st_ctime; #if HAVE_STRUCT_STAT_ST_MTIMENSEC dinp->di_atimensec = st->st_atimensec; dinp->di_mtimensec = st->st_mtimensec; dinp->di_ctimensec = st->st_ctimensec; #endif #if HAVE_STRUCT_STAT_BIRTHTIME dinp->di_birthtime = st->st_birthtime; dinp->di_birthnsec = st->st_birthtimensec; #endif /* not set: di_db, di_ib, di_blocks, di_spare */ membuf = NULL; if (cur == root) { /* "."; write dirbuf */ membuf = dbufp->buf; dinp->di_size = dbufp->size; } else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) { dinp->di_size = 0; /* a device */ dinp->di_rdev = ufs_rw64(cur->inode->st.st_rdev, fsopts->needswap); } else if (S_ISLNK(cur->type)) { /* symlink */ slen = strlen(cur->symlink); if (slen < UFS2_MAXSYMLINKLEN) { /* short link */ memcpy(dinp->di_db, cur->symlink, slen); } else membuf = cur->symlink; dinp->di_size = slen; } return membuf; } static int ffs_populate_dir(const char *dir, fsnode *root, fsinfo_t *fsopts) { fsnode *cur; dirbuf_t dirbuf; union dinode din; void *membuf; char path[MAXPATHLEN + 1]; ffs_opt_t *ffs_opts = fsopts->fs_specific; assert(dir != NULL); assert(root != NULL); assert(fsopts != NULL); assert(ffs_opts != NULL); (void)memset(&dirbuf, 0, sizeof(dirbuf)); if (debug & DEBUG_FS_POPULATE) printf("ffs_populate_dir: PASS 1 dir %s node %p\n", dir, root); /* * pass 1: allocate inode numbers, build directory `file' */ for (cur = root; cur != NULL; cur = cur->next) { if ((cur->inode->flags & FI_ALLOCATED) == 0) { cur->inode->flags |= FI_ALLOCATED; if (cur == root && cur->parent != NULL) cur->inode->ino = cur->parent->inode->ino; else { cur->inode->ino = fsopts->curinode; fsopts->curinode++; } } ffs_make_dirbuf(&dirbuf, cur->name, cur, fsopts->needswap); if (cur == root) { /* we're at "."; add ".." */ ffs_make_dirbuf(&dirbuf, "..", cur->parent == NULL ? cur : cur->parent->first, fsopts->needswap); root->inode->nlink++; /* count my parent's link */ } else if (cur->child != NULL) root->inode->nlink++; /* count my child's link */ /* * XXX possibly write file and long symlinks here, * ensuring that blocks get written before inodes? * otoh, this isn't a real filesystem, so who * cares about ordering? :-) */ } if (debug & DEBUG_FS_POPULATE_DIRBUF) ffs_dump_dirbuf(&dirbuf, dir, fsopts->needswap); /* * pass 2: write out dirbuf, then non-directories at this level */ if (debug & DEBUG_FS_POPULATE) printf("ffs_populate_dir: PASS 2 dir %s\n", dir); for (cur = root; cur != NULL; cur = cur->next) { if (cur->inode->flags & FI_WRITTEN) continue; /* skip hard-linked entries */ cur->inode->flags |= FI_WRITTEN; if (cur->contents == NULL) { if (snprintf(path, sizeof(path), "%s/%s/%s", cur->root, cur->path, cur->name) >= (int)sizeof(path)) errx(1, "Pathname too long."); } if (cur->child != NULL) continue; /* child creates own inode */ /* build on-disk inode */ if (ffs_opts->version == 1) membuf = ffs_build_dinode1(&din.ffs1_din, &dirbuf, cur, root, fsopts); else membuf = ffs_build_dinode2(&din.ffs2_din, &dirbuf, cur, root, fsopts); if (debug & DEBUG_FS_POPULATE_NODE) { printf("ffs_populate_dir: writing ino %d, %s", cur->inode->ino, inode_type(cur->type)); if (cur->inode->nlink > 1) printf(", nlink %d", cur->inode->nlink); putchar('\n'); } if (membuf != NULL) { ffs_write_file(&din, cur->inode->ino, membuf, fsopts); } else if (S_ISREG(cur->type)) { ffs_write_file(&din, cur->inode->ino, (cur->contents) ? cur->contents : path, fsopts); } else { assert (! S_ISDIR(cur->type)); ffs_write_inode(&din, cur->inode->ino, fsopts); } } /* * pass 3: write out sub-directories */ if (debug & DEBUG_FS_POPULATE) printf("ffs_populate_dir: PASS 3 dir %s\n", dir); for (cur = root; cur != NULL; cur = cur->next) { if (cur->child == NULL) continue; if ((size_t)snprintf(path, sizeof(path), "%s/%s", dir, cur->name) >= sizeof(path)) errx(1, "Pathname too long."); if (! ffs_populate_dir(path, cur->child, fsopts)) return (0); } if (debug & DEBUG_FS_POPULATE) printf("ffs_populate_dir: DONE dir %s\n", dir); /* cleanup */ if (dirbuf.buf != NULL) free(dirbuf.buf); return (1); } static void ffs_write_file(union dinode *din, uint32_t ino, void *buf, fsinfo_t *fsopts) { int isfile, ffd; char *fbuf, *p; off_t bufleft, chunk, offset; ssize_t nread; struct inode in; struct buf * bp; ffs_opt_t *ffs_opts = fsopts->fs_specific; struct vnode vp = { fsopts, NULL }; assert (din != NULL); assert (buf != NULL); assert (fsopts != NULL); assert (ffs_opts != NULL); isfile = S_ISREG(DIP(din, mode)); fbuf = NULL; ffd = -1; p = NULL; in.i_fs = (struct fs *)fsopts->superblock; in.i_devvp = &vp; if (debug & DEBUG_FS_WRITE_FILE) { printf( "ffs_write_file: ino %u, din %p, isfile %d, %s, size %lld", ino, din, isfile, inode_type(DIP(din, mode) & S_IFMT), (long long)DIP(din, size)); if (isfile) printf(", file '%s'\n", (char *)buf); else printf(", buffer %p\n", buf); } in.i_number = ino; in.i_size = DIP(din, size); if (ffs_opts->version == 1) memcpy(&in.i_din.ffs1_din, &din->ffs1_din, sizeof(in.i_din.ffs1_din)); else memcpy(&in.i_din.ffs2_din, &din->ffs2_din, sizeof(in.i_din.ffs2_din)); if (DIP(din, size) == 0) goto write_inode_and_leave; /* mmm, cheating */ if (isfile) { fbuf = emalloc(ffs_opts->bsize); if ((ffd = open((char *)buf, O_RDONLY, 0444)) == -1) { warn("Can't open `%s' for reading", (char *)buf); goto leave_ffs_write_file; } } else { p = buf; } chunk = 0; for (bufleft = DIP(din, size); bufleft > 0; bufleft -= chunk) { chunk = MIN(bufleft, ffs_opts->bsize); if (!isfile) ; else if ((nread = read(ffd, fbuf, chunk)) == -1) err(EXIT_FAILURE, "Reading `%s', %lld bytes to go", (char *)buf, (long long)bufleft); else if (nread != chunk) errx(EXIT_FAILURE, "Reading `%s', %lld bytes to go, " "read %zd bytes, expected %ju bytes, does " "metalog size= attribute mismatch source size?", (char *)buf, (long long)bufleft, nread, (uintmax_t)chunk); else p = fbuf; offset = DIP(din, size) - bufleft; if (debug & DEBUG_FS_WRITE_FILE_BLOCK) printf( "ffs_write_file: write %p offset %lld size %lld left %lld\n", p, (long long)offset, (long long)chunk, (long long)bufleft); /* * XXX if holey support is desired, do the check here * * XXX might need to write out last bit in fragroundup * sized chunk. however, ffs_balloc() handles this for us */ errno = ffs_balloc(&in, offset, chunk, &bp); bad_ffs_write_file: if (errno != 0) err(1, "Writing inode %d (%s), bytes %lld + %lld", ino, isfile ? (char *)buf : inode_type(DIP(din, mode) & S_IFMT), (long long)offset, (long long)chunk); memcpy(bp->b_data, p, chunk); errno = bwrite(bp); if (errno != 0) goto bad_ffs_write_file; brelse(bp, 0); if (!isfile) p += chunk; } write_inode_and_leave: ffs_write_inode(&in.i_din, in.i_number, fsopts); leave_ffs_write_file: if (fbuf) free(fbuf); if (ffd != -1) close(ffd); } static void ffs_dump_dirbuf(dirbuf_t *dbuf, const char *dir, int needswap) { doff_t i; struct direct *de; uint16_t reclen; assert (dbuf != NULL); assert (dir != NULL); printf("ffs_dump_dirbuf: dir %s size %d cur %d\n", dir, dbuf->size, dbuf->cur); for (i = 0; i < dbuf->size; ) { de = (struct direct *)(dbuf->buf + i); reclen = ufs_rw16(de->d_reclen, needswap); printf( " inode %4d %7s offset %4d reclen %3d namlen %3d name %s\n", ufs_rw32(de->d_ino, needswap), inode_type(DTTOIF(de->d_type)), i, reclen, de->d_namlen, de->d_name); i += reclen; assert(reclen > 0); } } static void ffs_make_dirbuf(dirbuf_t *dbuf, const char *name, fsnode *node, int needswap) { struct direct de, *dp; uint16_t llen, reclen; u_char *newbuf; assert (dbuf != NULL); assert (name != NULL); assert (node != NULL); /* create direct entry */ (void)memset(&de, 0, sizeof(de)); de.d_ino = ufs_rw32(node->inode->ino, needswap); de.d_type = IFTODT(node->type); de.d_namlen = (uint8_t)strlen(name); strcpy(de.d_name, name); reclen = DIRSIZ_SWAP(0, &de, needswap); de.d_reclen = ufs_rw16(reclen, needswap); dp = (struct direct *)(dbuf->buf + dbuf->cur); llen = 0; if (dp != NULL) llen = DIRSIZ_SWAP(0, dp, needswap); if (debug & DEBUG_FS_MAKE_DIRBUF) printf( "ffs_make_dirbuf: dbuf siz %d cur %d lastlen %d\n" " ino %d type %d reclen %d namlen %d name %.30s\n", dbuf->size, dbuf->cur, llen, ufs_rw32(de.d_ino, needswap), de.d_type, reclen, de.d_namlen, de.d_name); if (reclen + dbuf->cur + llen > roundup(dbuf->size, DIRBLKSIZ)) { if (debug & DEBUG_FS_MAKE_DIRBUF) printf("ffs_make_dirbuf: growing buf to %d\n", dbuf->size + DIRBLKSIZ); newbuf = erealloc(dbuf->buf, dbuf->size + DIRBLKSIZ); dbuf->buf = newbuf; dbuf->size += DIRBLKSIZ; memset(dbuf->buf + dbuf->size - DIRBLKSIZ, 0, DIRBLKSIZ); dbuf->cur = dbuf->size - DIRBLKSIZ; } else if (dp) { /* shrink end of previous */ dp->d_reclen = ufs_rw16(llen,needswap); dbuf->cur += llen; } dp = (struct direct *)(dbuf->buf + dbuf->cur); memcpy(dp, &de, reclen); dp->d_reclen = ufs_rw16(dbuf->size - dbuf->cur, needswap); } /* * cribbed from sys/ufs/ffs/ffs_alloc.c */ static void ffs_write_inode(union dinode *dp, uint32_t ino, const fsinfo_t *fsopts) { char *buf; struct ufs1_dinode *dp1; struct ufs2_dinode *dp2, *dip; struct cg *cgp; struct fs *fs; int cg, cgino; uint32_t i; daddr_t d; char sbbuf[FFS_MAXBSIZE]; uint32_t initediblk; ffs_opt_t *ffs_opts = fsopts->fs_specific; assert (dp != NULL); assert (ino > 0); assert (fsopts != NULL); assert (ffs_opts != NULL); fs = (struct fs *)fsopts->superblock; cg = ino_to_cg(fs, ino); cgino = ino % fs->fs_ipg; if (debug & DEBUG_FS_WRITE_INODE) printf("ffs_write_inode: din %p ino %u cg %d cgino %d\n", dp, ino, cg, cgino); ffs_rdfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf, fsopts); cgp = (struct cg *)sbbuf; if (!cg_chkmagic_swap(cgp, fsopts->needswap)) errx(1, "ffs_write_inode: cg %d: bad magic number", cg); assert (isclr(cg_inosused_swap(cgp, fsopts->needswap), cgino)); buf = emalloc(fs->fs_bsize); dp1 = (struct ufs1_dinode *)buf; dp2 = (struct ufs2_dinode *)buf; if (fs->fs_cstotal.cs_nifree == 0) errx(1, "ffs_write_inode: fs out of inodes for ino %u", ino); if (fs->fs_cs(fs, cg).cs_nifree == 0) errx(1, "ffs_write_inode: cg %d out of inodes for ino %u", cg, ino); setbit(cg_inosused_swap(cgp, fsopts->needswap), cgino); ufs_add32(cgp->cg_cs.cs_nifree, -1, fsopts->needswap); fs->fs_cstotal.cs_nifree--; fs->fs_cs(fs, cg).cs_nifree--; if (S_ISDIR(DIP(dp, mode))) { ufs_add32(cgp->cg_cs.cs_ndir, 1, fsopts->needswap); fs->fs_cstotal.cs_ndir++; fs->fs_cs(fs, cg).cs_ndir++; } /* * Initialize inode blocks on the fly for UFS2. */ initediblk = ufs_rw32(cgp->cg_initediblk, fsopts->needswap); while (ffs_opts->version == 2 && cgino + INOPB(fs) > initediblk && initediblk < ufs_rw32(cgp->cg_niblk, fsopts->needswap)) { memset(buf, 0, fs->fs_bsize); dip = (struct ufs2_dinode *)buf; for (i = 0; i < INOPB(fs); i++) { dip->di_gen = random(); dip++; } ffs_wtfs(fsbtodb(fs, ino_to_fsba(fs, cg * fs->fs_ipg + initediblk)), fs->fs_bsize, buf, fsopts); initediblk += INOPB(fs); cgp->cg_initediblk = ufs_rw32(initediblk, fsopts->needswap); } ffs_wtfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf, fsopts); /* now write inode */ d = fsbtodb(fs, ino_to_fsba(fs, ino)); ffs_rdfs(d, fs->fs_bsize, buf, fsopts); if (fsopts->needswap) { if (ffs_opts->version == 1) ffs_dinode1_swap(&dp->ffs1_din, &dp1[ino_to_fsbo(fs, ino)]); else ffs_dinode2_swap(&dp->ffs2_din, &dp2[ino_to_fsbo(fs, ino)]); } else { if (ffs_opts->version == 1) dp1[ino_to_fsbo(fs, ino)] = dp->ffs1_din; else dp2[ino_to_fsbo(fs, ino)] = dp->ffs2_din; } ffs_wtfs(d, fs->fs_bsize, buf, fsopts); free(buf); } void panic(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarnx(fmt, ap); va_end(ap); exit(1); } Index: head/usr.sbin/makefs/mtree.c =================================================================== --- head/usr.sbin/makefs/mtree.c (revision 328063) +++ head/usr.sbin/makefs/mtree.c (revision 328064) @@ -1,1106 +1,1112 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2011 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#if HAVE_NBTOOL_CONFIG_H +#include "nbtool_config.h" +#endif + #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "makefs.h" #ifndef ENOATTR #define ENOATTR ENOMSG #endif #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0') #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0') struct mtree_fileinfo { SLIST_ENTRY(mtree_fileinfo) next; FILE *fp; const char *name; u_int line; }; /* Global state used while parsing. */ static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo = SLIST_HEAD_INITIALIZER(mtree_fileinfo); static fsnode *mtree_root; static fsnode *mtree_current; static fsnode mtree_global; static fsinode mtree_global_inode; static u_int errors, warnings; static void mtree_error(const char *, ...) __printflike(1, 2); static void mtree_warning(const char *, ...) __printflike(1, 2); static int mtree_file_push(const char *name, FILE *fp) { struct mtree_fileinfo *fi; fi = emalloc(sizeof(*fi)); if (strcmp(name, "-") == 0) fi->name = estrdup("(stdin)"); else fi->name = estrdup(name); if (fi->name == NULL) { free(fi); return (ENOMEM); } fi->fp = fp; fi->line = 0; SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next); return (0); } static void mtree_print(const char *msgtype, const char *fmt, va_list ap) { struct mtree_fileinfo *fi; if (msgtype != NULL) { fi = SLIST_FIRST(&mtree_fileinfo); if (fi != NULL) fprintf(stderr, "%s:%u: ", fi->name, fi->line); fprintf(stderr, "%s: ", msgtype); } vfprintf(stderr, fmt, ap); } static void mtree_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); mtree_print("error", fmt, ap); va_end(ap); errors++; fputc('\n', stderr); } static void mtree_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); mtree_print("warning", fmt, ap); va_end(ap); warnings++; fputc('\n', stderr); } #ifndef MAKEFS_MAX_TREE_DEPTH # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2) #endif /* construct path to node->name */ static char * mtree_file_path(fsnode *node) { fsnode *pnode; struct sbuf *sb; char *res, *rp[MAKEFS_MAX_TREE_DEPTH]; int depth; depth = 0; rp[depth] = node->name; for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1; pnode = pnode->parent) { if (strcmp(pnode->name, ".") == 0) break; rp[++depth] = pnode->name; } sb = sbuf_new_auto(); if (sb == NULL) { errno = ENOMEM; return (NULL); } while (depth > 0) { sbuf_cat(sb, rp[depth--]); sbuf_putc(sb, '/'); } sbuf_cat(sb, rp[depth]); sbuf_finish(sb); res = estrdup(sbuf_data(sb)); sbuf_delete(sb); if (res == NULL) errno = ENOMEM; return res; } /* mtree_resolve() sets errno to indicate why NULL was returned. */ static char * mtree_resolve(const char *spec, int *istemp) { struct sbuf *sb; char *res, *var = NULL; const char *base, *p, *v; size_t len; int c, error, quoted, subst; len = strlen(spec); if (len == 0) { errno = EINVAL; return (NULL); } c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0; *istemp = (c == '`') ? 1 : 0; subst = (c == '`' || c == '"') ? 1 : 0; quoted = (subst || c == '\'') ? 1 : 0; if (!subst) { res = estrdup(spec + quoted); if (quoted) res[len - 2] = '\0'; return (res); } sb = sbuf_new_auto(); if (sb == NULL) { errno = ENOMEM; return (NULL); } base = spec + 1; len -= 2; error = 0; while (len > 0) { p = strchr(base, '$'); if (p == NULL) { sbuf_bcat(sb, base, len); base += len; len = 0; continue; } /* The following is safe. spec always starts with a quote. */ if (p[-1] == '\\') p--; if (base != p) { sbuf_bcat(sb, base, p - base); len -= p - base; base = p; } if (*p == '\\') { sbuf_putc(sb, '$'); base += 2; len -= 2; continue; } /* Skip the '$'. */ base++; len--; /* Handle ${X} vs $X. */ v = base; if (*base == '{') { p = strchr(v, '}'); if (p == NULL) p = v; } else p = v; len -= (p + 1) - base; base = p + 1; if (v == p) { sbuf_putc(sb, *v); continue; } error = ENOMEM; var = ecalloc(p - v, 1); memcpy(var, v + 1, p - v - 1); if (strcmp(var, ".CURDIR") == 0) { res = getcwd(NULL, 0); if (res == NULL) break; } else if (strcmp(var, ".PROG") == 0) { res = estrdup(getprogname()); } else { v = getenv(var); if (v != NULL) { res = estrdup(v); } else res = NULL; } error = 0; if (res != NULL) { sbuf_cat(sb, res); free(res); } free(var); var = NULL; } free(var); sbuf_finish(sb); res = (error == 0) ? strdup(sbuf_data(sb)) : NULL; sbuf_delete(sb); if (res == NULL) errno = ENOMEM; return (res); } static int skip_over(FILE *fp, const char *cs) { int c; c = getc(fp); while (c != EOF && strchr(cs, c) != NULL) c = getc(fp); if (c != EOF) { ungetc(c, fp); return (0); } return (ferror(fp) ? errno : -1); } static int skip_to(FILE *fp, const char *cs) { int c; c = getc(fp); while (c != EOF && strchr(cs, c) == NULL) c = getc(fp); if (c != EOF) { ungetc(c, fp); return (0); } return (ferror(fp) ? errno : -1); } static int read_word(FILE *fp, char *buf, size_t bufsz) { struct mtree_fileinfo *fi; size_t idx, qidx; int c, done, error, esc, qlvl; if (bufsz == 0) return (EINVAL); done = 0; esc = 0; idx = 0; qidx = -1; qlvl = 0; do { c = getc(fp); switch (c) { case EOF: buf[idx] = '\0'; error = ferror(fp) ? errno : -1; if (error == -1) mtree_error("unexpected end of file"); return (error); case '#': /* comment -- skip to end of line. */ if (!esc) { error = skip_to(fp, "\n"); if (!error) continue; } break; case '\\': esc++; break; case '`': case '\'': case '"': if (esc) break; if (qlvl == 0) { qlvl++; qidx = idx; } else if (c == buf[qidx]) { qlvl--; if (qlvl > 0) { do { qidx--; } while (buf[qidx] != '`' && buf[qidx] != '\'' && buf[qidx] != '"'); } else qidx = -1; } else { qlvl++; qidx = idx; } break; case ' ': case '\t': case '\n': if (!esc && qlvl == 0) { ungetc(c, fp); c = '\0'; done = 1; break; } if (c == '\n') { /* * We going to eat the newline ourselves. */ if (qlvl > 0) mtree_warning("quoted word straddles " "onto next line."); fi = SLIST_FIRST(&mtree_fileinfo); fi->line++; } break; default: if (esc) buf[idx++] = '\\'; break; } buf[idx++] = c; esc = 0; } while (idx < bufsz && !done); if (idx >= bufsz) { mtree_error("word too long to fit buffer (max %zu characters)", bufsz); skip_to(fp, " \t\n"); } return (0); } static fsnode * create_node(const char *name, u_int type, fsnode *parent, fsnode *global) { fsnode *n; n = ecalloc(1, sizeof(*n)); n->name = estrdup(name); n->type = (type == 0) ? global->type : type; n->parent = parent; n->inode = ecalloc(1, sizeof(*n->inode)); /* Assign global options/defaults. */ memcpy(n->inode, global->inode, sizeof(*n->inode)); n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type; if (n->type == S_IFLNK) n->symlink = global->symlink; else if (n->type == S_IFREG) n->contents = global->contents; return (n); } static void destroy_node(fsnode *n) { assert(n != NULL); assert(n->name != NULL); assert(n->inode != NULL); free(n->inode); free(n->name); free(n); } static int read_number(const char *tok, u_int base, intmax_t *res, intmax_t min, intmax_t max) { char *end; intmax_t val; val = strtoimax(tok, &end, base); if (end == tok || end[0] != '\0') return (EINVAL); if (val < min || val > max) return (EDOM); *res = val; return (0); } static int read_mtree_keywords(FILE *fp, fsnode *node) { char keyword[PATH_MAX]; char *name, *p, *value; gid_t gid; uid_t uid; struct stat *st, sb; intmax_t num; u_long flset, flclr; int error, istemp; uint32_t type; st = &node->inode->st; do { error = skip_over(fp, " \t"); if (error) break; error = read_word(fp, keyword, sizeof(keyword)); if (error) break; if (keyword[0] == '\0') break; value = strchr(keyword, '='); if (value != NULL) *value++ = '\0'; /* * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal * certain conditions: * EINVAL - Value provided for a keyword that does * not take a value. The value is ignored. * ENOATTR - Value missing for a keyword that needs * a value. The keyword is ignored. * ENOSYS - Unsupported keyword encountered. The * keyword is ignored. * ENXIO - Value provided for a keyword that does * not take a value. The value is ignored. */ switch (keyword[0]) { case 'c': if (strcmp(keyword, "contents") == 0) { if (value == NULL) { error = ENOATTR; break; } node->contents = estrdup(value); } else error = ENOSYS; break; case 'f': if (strcmp(keyword, "flags") == 0) { if (value == NULL) { error = ENOATTR; break; } flset = flclr = 0; +#if HAVE_STRUCT_STAT_ST_FLAGS if (!strtofflags(&value, &flset, &flclr)) { st->st_flags &= ~flclr; st->st_flags |= flset; } else error = errno; +#endif } else error = ENOSYS; break; case 'g': if (strcmp(keyword, "gid") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, UINT_MAX); if (!error) st->st_gid = num; } else if (strcmp(keyword, "gname") == 0) { if (value == NULL) { error = ENOATTR; break; } if (gid_from_group(value, &gid) == 0) st->st_gid = gid; else error = EINVAL; } else error = ENOSYS; break; case 'l': if (strcmp(keyword, "link") == 0) { if (value == NULL) { error = ENOATTR; break; } node->symlink = emalloc(strlen(value) + 1); if (node->symlink == NULL) { error = errno; break; } if (strunvis(node->symlink, value) < 0) { error = errno; break; } } else error = ENOSYS; break; case 'm': if (strcmp(keyword, "mode") == 0) { if (value == NULL) { error = ENOATTR; break; } if (value[0] >= '0' && value[0] <= '9') { error = read_number(value, 8, &num, 0, 07777); if (!error) { st->st_mode &= S_IFMT; st->st_mode |= num; } } else { /* Symbolic mode not supported. */ error = EINVAL; break; } } else error = ENOSYS; break; case 'o': if (strcmp(keyword, "optional") == 0) { if (value != NULL) error = ENXIO; node->flags |= FSNODE_F_OPTIONAL; } else error = ENOSYS; break; case 's': if (strcmp(keyword, "size") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, INTMAX_MAX); if (!error) st->st_size = num; } else error = ENOSYS; break; case 't': if (strcmp(keyword, "time") == 0) { if (value == NULL) { error = ENOATTR; break; } p = strchr(value, '.'); if (p != NULL) *p++ = '\0'; error = read_number(value, 10, &num, 0, INTMAX_MAX); if (error) break; st->st_atime = num; st->st_ctime = num; st->st_mtime = num; if (p == NULL) break; error = read_number(p, 10, &num, 0, INTMAX_MAX); if (error) break; if (num != 0) error = EINVAL; } else if (strcmp(keyword, "type") == 0) { if (value == NULL) { error = ENOATTR; break; } if (strcmp(value, "dir") == 0) node->type = S_IFDIR; else if (strcmp(value, "file") == 0) node->type = S_IFREG; else if (strcmp(value, "link") == 0) node->type = S_IFLNK; else error = EINVAL; } else error = ENOSYS; break; case 'u': if (strcmp(keyword, "uid") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, UINT_MAX); if (!error) st->st_uid = num; } else if (strcmp(keyword, "uname") == 0) { if (value == NULL) { error = ENOATTR; break; } if (uid_from_user(value, &uid) == 0) st->st_uid = uid; else error = EINVAL; } else error = ENOSYS; break; default: error = ENOSYS; break; } switch (error) { case EINVAL: mtree_error("%s: invalid value '%s'", keyword, value); break; case ENOATTR: mtree_error("%s: keyword needs a value", keyword); break; case ENOSYS: mtree_warning("%s: unsupported keyword", keyword); break; case ENXIO: mtree_error("%s: keyword does not take a value", keyword); break; } } while (1); if (error) return (error); st->st_mode = (st->st_mode & ~S_IFMT) | node->type; /* Nothing more to do for the global defaults. */ if (node->name == NULL) return (0); /* * Be intelligent about the file type. */ if (node->contents != NULL) { if (node->symlink != NULL) { mtree_error("%s: both link and contents keywords " "defined", node->name); return (0); } type = S_IFREG; } else if (node->type != 0) { type = node->type; if (type == S_IFREG) { /* the named path is the default contents */ node->contents = mtree_file_path(node); } } else type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR; if (node->type == 0) node->type = type; if (node->type != type) { mtree_error("%s: file type and defined keywords to not match", node->name); return (0); } st->st_mode = (st->st_mode & ~S_IFMT) | node->type; if (node->contents == NULL) return (0); name = mtree_resolve(node->contents, &istemp); if (name == NULL) return (errno); if (stat(name, &sb) != 0) { mtree_error("%s: contents file '%s' not found", node->name, name); free(name); return (0); } /* * Check for hardlinks. If the contents key is used, then the check * will only trigger if the contents file is a link even if it is used * by more than one file */ if (sb.st_nlink > 1) { fsinode *curino; st->st_ino = sb.st_ino; st->st_dev = sb.st_dev; curino = link_check(node->inode); if (curino != NULL) { free(node->inode); node->inode = curino; node->inode->nlink++; } } free(node->contents); node->contents = name; st->st_size = sb.st_size; return (0); } static int read_mtree_command(FILE *fp) { char cmd[10]; int error; error = read_word(fp, cmd, sizeof(cmd)); if (error) goto out; error = read_mtree_keywords(fp, &mtree_global); out: skip_to(fp, "\n"); (void)getc(fp); return (error); } static int read_mtree_spec1(FILE *fp, bool def, const char *name) { fsnode *last, *node, *parent; u_int type; int error; assert(name[0] != '\0'); /* * Treat '..' specially, because it only changes our current * directory. We don't create a node for it. We simply ignore * any keywords that may appear on the line as well. * Going up a directory is a little non-obvious. A directory * node has a corresponding '.' child. The parent of '.' is * not the '.' node of the parent directory, but the directory * node within the parent to which the child relates. However, * going up a directory means we need to find the '.' node to * which the directoy node is linked. This we can do via the * first * pointer, because '.' is always the first entry in a * directory. */ if (IS_DOTDOT(name)) { /* This deals with NULL pointers as well. */ if (mtree_current == mtree_root) { mtree_warning("ignoring .. in root directory"); return (0); } node = mtree_current; assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); /* Get the corresponding directory node in the parent. */ node = mtree_current->parent; assert(node != NULL); assert(!IS_DOT(node->name)); node = node->first; assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); mtree_current = node; return (0); } /* * If we don't have a current directory and the first specification * (either implicit or defined) is not '.', then we need to create * a '.' node first (using a recursive call). */ if (!IS_DOT(name) && mtree_current == NULL) { error = read_mtree_spec1(fp, false, "."); if (error) return (error); } /* * Lookup the name in the current directory (if we have a current * directory) to make sure we do not create multiple nodes for the * same component. For non-definitions, if we find a node with the * same name, simply change the current directory. For definitions * more happens. */ last = NULL; node = mtree_current; while (node != NULL) { assert(node->first == mtree_current); if (strcmp(name, node->name) == 0) { if (def == true) { if (!dupsok) mtree_error( "duplicate definition of %s", name); else mtree_warning( "duplicate definition of %s", name); return (0); } if (node->type != S_IFDIR) { mtree_error("%s is not a directory", name); return (0); } assert(!IS_DOT(name)); node = node->child; assert(node != NULL); assert(IS_DOT(node->name)); mtree_current = node; return (0); } last = node; node = last->next; } parent = (mtree_current != NULL) ? mtree_current->parent : NULL; type = (def == false || IS_DOT(name)) ? S_IFDIR : 0; node = create_node(name, type, parent, &mtree_global); if (node == NULL) return (ENOMEM); if (def == true) { error = read_mtree_keywords(fp, node); if (error) { destroy_node(node); return (error); } } node->first = (mtree_current != NULL) ? mtree_current : node; if (last != NULL) last->next = node; if (node->type != S_IFDIR) return (0); if (!IS_DOT(node->name)) { parent = node; node = create_node(".", S_IFDIR, parent, parent); if (node == NULL) { last->next = NULL; destroy_node(parent); return (ENOMEM); } parent->child = node; node->first = node; } assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); mtree_current = node; if (mtree_root == NULL) mtree_root = node; return (0); } static int read_mtree_spec(FILE *fp) { char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1]; char *cp; int error; error = read_word(fp, pathtmp, sizeof(pathtmp)); if (error) goto out; if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) { error = errno; goto out; } error = 0; cp = strchr(pathspec, '/'); if (cp != NULL) { /* Absolute pathname */ mtree_current = mtree_root; do { *cp++ = '\0'; /* Disallow '..' as a component. */ if (IS_DOTDOT(pathspec)) { mtree_error("absolute path cannot contain " ".. component"); goto out; } /* Ignore multiple adjacent slashes and '.'. */ if (pathspec[0] != '\0' && !IS_DOT(pathspec)) error = read_mtree_spec1(fp, false, pathspec); memmove(pathspec, cp, strlen(cp) + 1); cp = strchr(pathspec, '/'); } while (!error && cp != NULL); /* Disallow '.' and '..' as the last component. */ if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) { mtree_error("absolute path cannot contain . or .. " "components"); goto out; } } /* Ignore absolute specfications that end with a slash. */ if (!error && pathspec[0] != '\0') error = read_mtree_spec1(fp, true, pathspec); out: skip_to(fp, "\n"); (void)getc(fp); return (error); } fsnode * read_mtree(const char *fname, fsnode *node) { struct mtree_fileinfo *fi; FILE *fp; int c, error; /* We do not yet support nesting... */ assert(node == NULL); if (strcmp(fname, "-") == 0) fp = stdin; else { fp = fopen(fname, "r"); if (fp == NULL) err(1, "Can't open `%s'", fname); } error = mtree_file_push(fname, fp); if (error) goto out; memset(&mtree_global, 0, sizeof(mtree_global)); memset(&mtree_global_inode, 0, sizeof(mtree_global_inode)); mtree_global.inode = &mtree_global_inode; mtree_global_inode.nlink = 1; mtree_global_inode.st.st_nlink = 1; mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime = mtree_global_inode.st.st_mtime = time(NULL); errors = warnings = 0; setgroupent(1); setpassent(1); mtree_root = node; mtree_current = node; do { /* Start of a new line... */ fi = SLIST_FIRST(&mtree_fileinfo); fi->line++; error = skip_over(fp, " \t"); if (error) break; c = getc(fp); if (c == EOF) { error = ferror(fp) ? errno : -1; break; } switch (c) { case '\n': /* empty line */ error = 0; break; case '#': /* comment -- skip to end of line. */ error = skip_to(fp, "\n"); if (!error) (void)getc(fp); break; case '/': /* special commands */ error = read_mtree_command(fp); break; default: /* specification */ ungetc(c, fp); error = read_mtree_spec(fp); break; } } while (!error); endpwent(); endgrent(); if (error <= 0 && (errors || warnings)) { warnx("%u error(s) and %u warning(s) in mtree manifest", errors, warnings); if (errors) exit(1); } out: if (error > 0) errc(1, error, "Error reading mtree file"); if (fp != stdin) fclose(fp); if (mtree_root != NULL) return (mtree_root); /* Handle empty specifications. */ node = create_node(".", S_IFDIR, NULL, &mtree_global); node->first = node; return (node); }