2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2012, 2013 SRI International
5 * Copyright (c) 1987, 1993
6 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1987, 1993\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)xinstall.c 8.1 (Berkeley) 7/21/93";
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
50 #include <sys/mount.h>
79 * We need to build xinstall during the bootstrap stage when building on a
80 * non-FreeBSD system. Linux does not have the st_flags and st_birthtime
81 * members in struct stat so we need to omit support for changing those fields.
84 #define HAVE_STRUCT_STAT_ST_FLAGS 1
86 #define HAVE_STRUCT_STAT_ST_FLAGS 0
89 #define MAX_CMP_SIZE (16 * 1024 * 1024)
91 #define LN_ABSOLUTE 0x01
92 #define LN_RELATIVE 0x02
94 #define LN_SYMBOLIC 0x08
97 #define DIRECTORY 0x01 /* Tell install it's a directory. */
98 #define SETFLAGS 0x02 /* Tell install to set flags. */
99 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
100 #define BACKUP_SUFFIX ".old"
104 RIPEMD160_CTX RIPEMD160;
117 } digesttype = DIGEST_NONE;
119 extern char **environ;
123 static int dobackup, docompare, dodir, dolink, dopreserve, dostrip, dounpriv,
125 static int haveopt_f, haveopt_g, haveopt_m, haveopt_o;
126 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
128 static const char *group, *owner;
129 static const char *suffix = BACKUP_SUFFIX;
130 static char *destdir, *digest, *fflags, *metafile, *tags;
132 static int compare(int, const char *, size_t, int, const char *, size_t,
134 static char *copy(int, const char *, int, const char *, off_t);
135 static int create_newfile(const char *, int, struct stat *);
136 static int create_tempfile(const char *, char *, size_t);
137 static char *quiet_mktemp(char *template);
138 static char *digest_file(const char *);
139 static void digest_init(DIGEST_CTX *);
140 static void digest_update(DIGEST_CTX *, const char *, size_t);
141 static char *digest_end(DIGEST_CTX *, char *);
142 static int do_link(const char *, const char *, const struct stat *);
143 static void do_symlink(const char *, const char *, const struct stat *);
144 static void makelink(const char *, const char *, const struct stat *);
145 static void install(const char *, const char *, u_long, u_int);
146 static void install_dir(char *);
147 static void metadata_log(const char *, const char *, struct timespec *,
148 const char *, const char *, off_t);
149 static int parseid(const char *, id_t *);
150 static int strip(const char *, int, const char *, char **);
151 static int trymmap(int);
152 static void usage(void);
155 main(int argc, char *argv[])
157 struct stat from_sb, to_sb;
167 group = owner = NULL;
168 while ((ch = getopt(argc, argv, "B:bCcD:df:g:h:l:M:m:N:o:pSsT:Uv")) !=
181 /* For backwards compatibility. */
201 for (p = optarg; *p != '\0'; p++)
204 dolink &= ~(LN_HARD|LN_MIXED);
205 dolink |= LN_SYMBOLIC;
208 dolink &= ~(LN_SYMBOLIC|LN_MIXED);
212 dolink &= ~(LN_SYMBOLIC|LN_HARD);
216 dolink &= ~LN_RELATIVE;
217 dolink |= LN_ABSOLUTE;
220 dolink &= ~LN_ABSOLUTE;
221 dolink |= LN_RELATIVE;
224 errx(1, "%c: invalid link type", *p);
233 if (!(set = setmode(optarg)))
234 errx(EX_USAGE, "invalid file mode: %s",
236 mode = getmode(set, 0);
240 if (!setup_getid(optarg))
241 err(EX_OSERR, "Unable to use user and group "
242 "databases in `%s'", optarg);
249 docompare = dopreserve = 1;
273 /* some options make no sense when creating directories */
274 if (dostrip && dodir) {
275 warnx("-d and -s may not be specified together");
279 if (getenv("DONTSTRIP") != NULL) {
280 warnx("DONTSTRIP set - will not strip installed binaries");
284 /* must have at least two arguments, except when creating directories */
285 if (argc == 0 || (argc == 1 && !dodir))
288 if (digest != NULL) {
289 if (strcmp(digest, "none") == 0) {
290 digesttype = DIGEST_NONE;
291 } else if (strcmp(digest, "md5") == 0) {
292 digesttype = DIGEST_MD5;
293 } else if (strcmp(digest, "rmd160") == 0) {
294 digesttype = DIGEST_RIPEMD160;
295 } else if (strcmp(digest, "sha1") == 0) {
296 digesttype = DIGEST_SHA1;
297 } else if (strcmp(digest, "sha256") == 0) {
298 digesttype = DIGEST_SHA256;
299 } else if (strcmp(digest, "sha512") == 0) {
300 digesttype = DIGEST_SHA512;
302 warnx("unknown digest `%s'", digest);
307 /* need to make a temp copy so we can compare stripped version */
308 if (docompare && dostrip)
311 /* get group and owner id's */
312 if (group != NULL && !dounpriv) {
313 if (gid_from_group(group, &gid) == -1) {
315 if (!parseid(group, &id))
316 errx(1, "unknown group %s", group);
322 if (owner != NULL && !dounpriv) {
323 if (uid_from_user(owner, &uid) == -1) {
325 if (!parseid(owner, &id))
326 errx(1, "unknown user %s", owner);
332 if (fflags != NULL && !dounpriv) {
333 if (strtofflags(&fflags, &fset, NULL))
334 errx(EX_USAGE, "%s: invalid flag", fflags);
338 if (metafile != NULL) {
339 if ((metafp = fopen(metafile, "a")) == NULL)
340 warn("open %s", metafile);
342 digesttype = DIGEST_NONE;
345 for (; *argv != NULL; ++argv)
351 to_name = argv[argc - 1];
352 no_target = stat(to_name, &to_sb);
353 if (!no_target && S_ISDIR(to_sb.st_mode)) {
354 if (dolink & LN_SYMBOLIC) {
355 if (lstat(to_name, &to_sb) != 0)
356 err(EX_OSERR, "%s vanished", to_name);
357 if (S_ISLNK(to_sb.st_mode)) {
360 err(EX_USAGE, "%s", to_name);
362 install(*argv, to_name, fset, iflags);
366 for (; *argv != to_name; ++argv)
367 install(*argv, to_name, fset, iflags | DIRECTORY);
372 /* can't do file1 file2 directory/file */
375 warnx("target directory `%s' does not exist",
378 warnx("target `%s' is not a directory",
383 if (!no_target && !dolink) {
384 if (stat(*argv, &from_sb))
385 err(EX_OSERR, "%s", *argv);
386 if (!S_ISREG(to_sb.st_mode)) {
388 err(EX_OSERR, "%s", to_name);
390 if (to_sb.st_dev == from_sb.st_dev &&
391 to_sb.st_ino == from_sb.st_ino)
393 "%s and %s are the same file", *argv, to_name);
395 install(*argv, to_name, fset, iflags);
401 digest_file(const char *name)
404 switch (digesttype) {
406 return (MD5File(name, NULL));
407 case DIGEST_RIPEMD160:
408 return (RIPEMD160_File(name, NULL));
410 return (SHA1_File(name, NULL));
412 return (SHA256_File(name, NULL));
414 return (SHA512_File(name, NULL));
421 digest_init(DIGEST_CTX *c)
424 switch (digesttype) {
430 case DIGEST_RIPEMD160:
431 RIPEMD160_Init(&(c->RIPEMD160));
434 SHA1_Init(&(c->SHA1));
437 SHA256_Init(&(c->SHA256));
440 SHA512_Init(&(c->SHA512));
446 digest_update(DIGEST_CTX *c, const char *data, size_t len)
449 switch (digesttype) {
453 MD5Update(&(c->MD5), data, len);
455 case DIGEST_RIPEMD160:
456 RIPEMD160_Update(&(c->RIPEMD160), data, len);
459 SHA1_Update(&(c->SHA1), data, len);
462 SHA256_Update(&(c->SHA256), data, len);
465 SHA512_Update(&(c->SHA512), data, len);
471 digest_end(DIGEST_CTX *c, char *buf)
474 switch (digesttype) {
476 return (MD5End(&(c->MD5), buf));
477 case DIGEST_RIPEMD160:
478 return (RIPEMD160_End(&(c->RIPEMD160), buf));
480 return (SHA1_End(&(c->SHA1), buf));
482 return (SHA256_End(&(c->SHA256), buf));
484 return (SHA512_End(&(c->SHA512), buf));
492 * parse uid or gid from arg into id, returning non-zero if successful
495 parseid(const char *name, id_t *id)
499 *id = (id_t)strtoul(name, &ep, 10);
500 if (errno || *ep != '\0')
507 * mktemp implementation used mkstemp to avoid mktemp warnings. We
508 * really do need mktemp semantics here as we will be creating a link.
511 quiet_mktemp(char *template)
515 if ((fd = mkstemp(template)) == -1)
518 if (unlink(template) == -1)
519 err(EX_OSERR, "unlink %s", template);
525 * make a hard link, obeying dorename if set
526 * return -1 on failure
529 do_link(const char *from_name, const char *to_name,
530 const struct stat *target_sb)
532 char tmpl[MAXPATHLEN];
535 if (safecopy && target_sb != NULL) {
536 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
537 /* This usage is safe. */
538 if (quiet_mktemp(tmpl) == NULL)
539 err(EX_OSERR, "%s: mktemp", tmpl);
540 ret = link(from_name, tmpl);
542 if (target_sb->st_mode & S_IFDIR && rmdir(to_name) ==
545 err(EX_OSERR, "%s", to_name);
547 #if HAVE_STRUCT_STAT_ST_FLAGS
548 if (target_sb->st_flags & NOCHANGEBITS)
549 (void)chflags(to_name, target_sb->st_flags &
553 printf("install: link %s -> %s\n",
555 ret = rename(tmpl, to_name);
557 * If rename has posix semantics, then the temporary
558 * file may still exist when from_name and to_name point
559 * to the same file, so unlink it unconditionally.
566 printf("install: link %s -> %s\n",
568 return (link(from_name, to_name));
574 * Make a symbolic link, obeying dorename if set. Exit on failure.
577 do_symlink(const char *from_name, const char *to_name,
578 const struct stat *target_sb)
580 char tmpl[MAXPATHLEN];
582 if (safecopy && target_sb != NULL) {
583 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
584 /* This usage is safe. */
585 if (quiet_mktemp(tmpl) == NULL)
586 err(EX_OSERR, "%s: mktemp", tmpl);
588 if (symlink(from_name, tmpl) == -1)
589 err(EX_OSERR, "symlink %s -> %s", from_name, tmpl);
591 if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) {
593 err(EX_OSERR, "%s", to_name);
595 #if HAVE_STRUCT_STAT_ST_FLAGS
596 if (target_sb->st_flags & NOCHANGEBITS)
597 (void)chflags(to_name, target_sb->st_flags &
601 printf("install: symlink %s -> %s\n",
603 if (rename(tmpl, to_name) == -1) {
604 /* Remove temporary link before exiting. */
606 err(EX_OSERR, "%s: rename", to_name);
610 printf("install: symlink %s -> %s\n",
612 if (symlink(from_name, to_name) == -1)
613 err(EX_OSERR, "symlink %s -> %s", from_name, to_name);
619 * make a link from source to destination
622 makelink(const char *from_name, const char *to_name,
623 const struct stat *target_sb)
625 char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
628 /* Try hard links first. */
629 if (dolink & (LN_HARD|LN_MIXED)) {
630 if (do_link(from_name, to_name, target_sb) == -1) {
631 if ((dolink & LN_HARD) || errno != EXDEV)
632 err(EX_OSERR, "link %s -> %s", from_name, to_name);
634 if (stat(to_name, &to_sb))
635 err(EX_OSERR, "%s: stat", to_name);
636 if (S_ISREG(to_sb.st_mode)) {
638 * XXX: hard links to anything other than
639 * plain files are not metalogged
642 const char *oowner, *ogroup;
647 * XXX: use underlying perms, unless
648 * overridden on command line.
652 mode = (to_sb.st_mode & 0777);
662 dres = digest_file(from_name);
663 metadata_log(to_name, "file", NULL, NULL,
664 dres, to_sb.st_size);
675 /* Symbolic links. */
676 if (dolink & LN_ABSOLUTE) {
677 /* Convert source path to absolute. */
678 if (realpath(from_name, src) == NULL)
679 err(EX_OSERR, "%s: realpath", from_name);
680 do_symlink(src, to_name, target_sb);
681 /* XXX: src may point outside of destdir */
682 metadata_log(to_name, "link", NULL, src, NULL, 0);
686 if (dolink & LN_RELATIVE) {
687 char *to_name_copy, *cp, *d, *ld, *ls, *s;
689 if (*from_name != '/') {
690 /* this is already a relative link */
691 do_symlink(from_name, to_name, target_sb);
692 /* XXX: from_name may point outside of destdir. */
693 metadata_log(to_name, "link", NULL, from_name, NULL, 0);
697 /* Resolve pathnames. */
698 if (realpath(from_name, src) == NULL)
699 err(EX_OSERR, "%s: realpath", from_name);
702 * The last component of to_name may be a symlink,
703 * so use realpath to resolve only the directory.
705 to_name_copy = strdup(to_name);
706 if (to_name_copy == NULL)
707 err(EX_OSERR, "%s: strdup", to_name);
708 cp = dirname(to_name_copy);
709 if (realpath(cp, dst) == NULL)
710 err(EX_OSERR, "%s: realpath", cp);
711 /* .. and add the last component. */
712 if (strcmp(dst, "/") != 0) {
713 if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
714 errx(1, "resolved pathname too long");
716 strcpy(to_name_copy, to_name);
717 cp = basename(to_name_copy);
718 if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
719 errx(1, "resolved pathname too long");
722 /* Trim common path components. */
724 for (s = src, d = dst; *s == *d; ls = s, ld = d, s++, d++)
727 * If we didn't end after a directory separator, then we've
728 * falsely matched the last component. For example, if one
729 * invoked install -lrs /lib/foo.so /libexec/ then the source
730 * would terminate just after the separator while the
731 * destination would terminate in the middle of 'libexec',
732 * leading to a full directory getting falsely eaten.
734 if ((ls != NULL && *ls != '/') || (ld != NULL && *ld != '/'))
739 /* Count the number of directories we need to backtrack. */
740 for (++d, lnk[0] = '\0'; *d; d++)
742 (void)strlcat(lnk, "../", sizeof(lnk));
744 (void)strlcat(lnk, ++s, sizeof(lnk));
746 do_symlink(lnk, to_name, target_sb);
747 /* XXX: Link may point outside of destdir. */
748 metadata_log(to_name, "link", NULL, lnk, NULL, 0);
753 * If absolute or relative was not specified, try the names the
756 do_symlink(from_name, to_name, target_sb);
757 /* XXX: from_name may point outside of destdir. */
758 metadata_log(to_name, "link", NULL, from_name, NULL, 0);
763 * build a path name and install the file
766 install(const char *from_name, const char *to_name, u_long fset, u_int flags)
768 struct stat from_sb, temp_sb, to_sb;
769 struct timespec tsb[2];
770 int devnull, files_match, from_fd, serrno, stripped, target;
771 int tempcopy, temp_fd, to_fd;
772 char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
776 files_match = stripped = 0;
780 /* If try to install NULL file to a directory, fails. */
781 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
783 if (stat(from_name, &from_sb))
784 err(EX_OSERR, "%s", from_name);
785 if (!S_ISREG(from_sb.st_mode)) {
787 err(EX_OSERR, "%s", from_name);
790 /* Build the target path. */
791 if (flags & DIRECTORY) {
792 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s%s",
794 to_name[strlen(to_name) - 1] == '/' ? "" : "/",
795 (p = strrchr(from_name, '/')) ? ++p : from_name);
803 target = (lstat(to_name, &to_sb) == 0);
806 if (target && !safecopy) {
807 if (to_sb.st_mode & S_IFDIR && rmdir(to_name) == -1)
808 err(EX_OSERR, "%s", to_name);
809 #if HAVE_STRUCT_STAT_ST_FLAGS
810 if (to_sb.st_flags & NOCHANGEBITS)
811 (void)chflags(to_name,
812 to_sb.st_flags & ~NOCHANGEBITS);
816 makelink(from_name, to_name, target ? &to_sb : NULL);
820 if (target && !S_ISREG(to_sb.st_mode) && !S_ISLNK(to_sb.st_mode)) {
826 /* Only copy safe if the target exists. */
827 tempcopy = safecopy && target;
829 if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
830 err(EX_OSERR, "%s", from_name);
832 /* If we don't strip, we can compare first. */
833 if (docompare && !dostrip && target && S_ISREG(to_sb.st_mode)) {
834 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
835 err(EX_OSERR, "%s", to_name);
837 files_match = to_sb.st_size == 0;
839 files_match = !(compare(from_fd, from_name,
840 (size_t)from_sb.st_size, to_fd,
841 to_name, (size_t)to_sb.st_size, &digestresult));
843 /* Close "to" file unless we match. */
850 to_fd = create_tempfile(to_name, tempfile,
853 err(EX_OSERR, "%s", tempfile);
855 if ((to_fd = create_newfile(to_name, target,
857 err(EX_OSERR, "%s", to_name);
859 (void)printf("install: %s -> %s\n",
864 stripped = strip(tempcopy ? tempfile : to_name,
865 to_fd, from_name, &digestresult);
867 digestresult = copy(from_fd, from_name, to_fd,
868 tempcopy ? tempfile : to_name, from_sb.st_size);
874 (void)strip(tempcopy ? tempfile : to_name, to_fd,
875 NULL, &digestresult);
878 * Re-open our fd on the target, in case
879 * we did not strip in-place.
882 to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
884 err(EX_OSERR, "stripping %s", to_name);
888 * Compare the stripped temp file with the target.
890 if (docompare && dostrip && target && S_ISREG(to_sb.st_mode)) {
893 /* Re-open to_fd using the real target name. */
894 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
895 err(EX_OSERR, "%s", to_name);
897 if (fstat(temp_fd, &temp_sb)) {
899 (void)unlink(tempfile);
901 err(EX_OSERR, "%s", tempfile);
904 if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
905 to_name, (size_t)to_sb.st_size, &digestresult)
908 * If target has more than one link we need to
909 * replace it in order to snap the extra links.
910 * Need to preserve target file times, though.
912 if (to_sb.st_nlink != 1) {
913 tsb[0] = to_sb.st_atim;
914 tsb[1] = to_sb.st_mtim;
915 (void)utimensat(AT_FDCWD, tempfile, tsb, 0);
918 (void)unlink(tempfile);
920 (void) close(temp_fd);
923 digestresult = digest_file(tempfile);
926 * Move the new file into place if doing a safe copy
927 * and the files are different (or just not compared).
929 if (tempcopy && !files_match) {
930 #if HAVE_STRUCT_STAT_ST_FLAGS
931 /* Try to turn off the immutable bits. */
932 if (to_sb.st_flags & NOCHANGEBITS)
933 (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
936 if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
937 suffix) != strlen(to_name) + strlen(suffix)) {
939 errx(EX_OSERR, "%s: backup filename too long",
943 (void)printf("install: %s -> %s\n", to_name, backup);
944 if (unlink(backup) < 0 && errno != ENOENT) {
946 #if HAVE_STRUCT_STAT_ST_FLAGS
947 if (to_sb.st_flags & NOCHANGEBITS)
948 (void)chflags(to_name, to_sb.st_flags);
952 err(EX_OSERR, "unlink: %s", backup);
954 if (link(to_name, backup) < 0) {
957 #if HAVE_STRUCT_STAT_ST_FLAGS
958 if (to_sb.st_flags & NOCHANGEBITS)
959 (void)chflags(to_name, to_sb.st_flags);
962 err(EX_OSERR, "link: %s to %s", to_name,
967 (void)printf("install: %s -> %s\n", from_name, to_name);
968 if (rename(tempfile, to_name) < 0) {
972 err(EX_OSERR, "rename: %s to %s",
976 /* Re-open to_fd so we aren't hosed by the rename(2). */
978 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
979 err(EX_OSERR, "%s", to_name);
983 * Preserve the timestamp of the source file if necessary.
985 if (dopreserve && !files_match && !devnull) {
986 tsb[0] = from_sb.st_atim;
987 tsb[1] = from_sb.st_mtim;
988 (void)utimensat(AT_FDCWD, to_name, tsb, 0);
991 if (fstat(to_fd, &to_sb) == -1) {
993 (void)unlink(to_name);
995 err(EX_OSERR, "%s", to_name);
999 * Set owner, group, mode for target; do the chown first,
1000 * chown may lose the setuid bits.
1002 if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
1003 (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
1004 (mode != (to_sb.st_mode & ALLPERMS)))) {
1005 #if HAVE_STRUCT_STAT_ST_FLAGS
1006 /* Try to turn off the immutable bits. */
1007 if (to_sb.st_flags & NOCHANGEBITS)
1008 (void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
1013 (gid != (gid_t)-1 && gid != to_sb.st_gid) ||
1014 (uid != (uid_t)-1 && uid != to_sb.st_uid))
1015 if (fchown(to_fd, uid, gid) == -1) {
1017 (void)unlink(to_name);
1019 err(EX_OSERR,"%s: chown/chgrp", to_name);
1022 if (mode != (to_sb.st_mode & ALLPERMS)) {
1024 dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) {
1026 (void)unlink(to_name);
1028 err(EX_OSERR, "%s: chmod", to_name);
1031 #if HAVE_STRUCT_STAT_ST_FLAGS
1033 * If provided a set of flags, set them, otherwise, preserve the
1034 * flags, except for the dump flag.
1035 * NFS does not support flags. Ignore EOPNOTSUPP flags if we're just
1036 * trying to turn off UF_NODUMP. If we're trying to set real flags,
1037 * then warn if the fs doesn't support it, otherwise fail.
1039 if (!dounpriv & !devnull && (flags & SETFLAGS ||
1040 (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) &&
1042 flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
1043 if (flags & SETFLAGS) {
1044 if (errno == EOPNOTSUPP)
1045 warn("%s: chflags", to_name);
1048 (void)unlink(to_name);
1050 err(EX_OSERR, "%s: chflags", to_name);
1058 (void)close(from_fd);
1060 metadata_log(to_name, "file", tsb, NULL, digestresult, to_sb.st_size);
1066 * Compare two files; non-zero means files differ.
1067 * Compute digest and return its address in *dresp
1068 * unless it points to pre-computed digest.
1071 compare(int from_fd, const char *from_name __unused, size_t from_len,
1072 int to_fd, const char *to_name __unused, size_t to_len,
1077 int do_digest, done_compare;
1081 if (from_len != to_len)
1084 do_digest = (digesttype != DIGEST_NONE && dresp != NULL &&
1086 if (from_len <= MAX_CMP_SIZE) {
1090 if (trymmap(from_fd) && trymmap(to_fd)) {
1091 p = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1093 if (p == MAP_FAILED)
1095 q = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1097 if (q == MAP_FAILED) {
1098 munmap(p, from_len);
1102 rv = memcmp(p, q, from_len);
1104 digest_update(&ctx, p, from_len);
1105 munmap(p, from_len);
1106 munmap(q, from_len);
1110 if (!done_compare) {
1111 char buf1[MAXBSIZE];
1112 char buf2[MAXBSIZE];
1116 lseek(from_fd, 0, SEEK_SET);
1117 lseek(to_fd, 0, SEEK_SET);
1119 n1 = read(from_fd, buf1, sizeof(buf1));
1123 n2 = read(to_fd, buf2, n1);
1125 rv = memcmp(buf1, buf2, n1);
1127 rv = 1; /* out of sync */
1129 rv = 1; /* read failure */
1131 digest_update(&ctx, buf1, n1);
1133 lseek(from_fd, 0, SEEK_SET);
1134 lseek(to_fd, 0, SEEK_SET);
1137 rv = 1; /* don't bother in this case */
1141 *dresp = digest_end(&ctx, NULL);
1143 (void)digest_end(&ctx, NULL);
1150 * create_tempfile --
1151 * create a temporary file based on path and open it
1154 create_tempfile(const char *path, char *temp, size_t tsize)
1158 (void)strncpy(temp, path, tsize);
1159 temp[tsize - 1] = '\0';
1160 if ((p = strrchr(temp, '/')) != NULL)
1164 (void)strncpy(p, "INS@XXXXXX", &temp[tsize - 1] - p);
1165 temp[tsize - 1] = '\0';
1166 return (mkstemp(temp));
1171 * create a new file, overwriting an existing one if necessary
1174 create_newfile(const char *path, int target, struct stat *sbp)
1176 char backup[MAXPATHLEN];
1177 int saved_errno = 0;
1182 * Unlink now... avoid ETXTBSY errors later. Try to turn
1183 * off the append/immutable bits -- if we fail, go ahead,
1186 #if HAVE_STRUCT_STAT_ST_FLAGS
1187 if (sbp->st_flags & NOCHANGEBITS)
1188 (void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
1192 if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s",
1193 path, suffix) != strlen(path) + strlen(suffix)) {
1194 saved_errno = errno;
1195 #if HAVE_STRUCT_STAT_ST_FLAGS
1196 if (sbp->st_flags & NOCHANGEBITS)
1197 (void)chflags(path, sbp->st_flags);
1199 errno = saved_errno;
1200 errx(EX_OSERR, "%s: backup filename too long",
1203 (void)snprintf(backup, MAXPATHLEN, "%s%s",
1206 (void)printf("install: %s -> %s\n",
1208 if (rename(path, backup) < 0) {
1209 saved_errno = errno;
1210 #if HAVE_STRUCT_STAT_ST_FLAGS
1211 if (sbp->st_flags & NOCHANGEBITS)
1212 (void)chflags(path, sbp->st_flags);
1214 errno = saved_errno;
1215 err(EX_OSERR, "rename: %s to %s", path, backup);
1218 if (unlink(path) < 0)
1219 saved_errno = errno;
1222 newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
1223 if (newfd < 0 && saved_errno != 0)
1224 errno = saved_errno;
1230 * copy from one file to another
1233 copy(int from_fd, const char *from_name, int to_fd, const char *to_name,
1243 /* Rewind file descriptors. */
1244 if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1245 err(EX_OSERR, "lseek: %s", from_name);
1246 if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1247 err(EX_OSERR, "lseek: %s", to_name);
1252 * Mmap and write if less than 8M (the limit is so we don't totally
1253 * trash memory on big files. This is really a minor hack, but it
1254 * wins some CPU back.
1257 if (size <= 8 * 1048576 && trymmap(from_fd) &&
1258 (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED,
1259 from_fd, (off_t)0)) != MAP_FAILED) {
1260 nw = write(to_fd, p, size);
1263 (void)unlink(to_name);
1266 "short write to %s: %jd bytes written, %jd bytes asked to write",
1267 to_name, (uintmax_t)nw, (uintmax_t)size);
1270 err(EX_OSERR, "%s", to_name);
1273 digest_update(&ctx, p, size);
1274 (void)munmap(p, size);
1278 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
1279 if ((nw = write(to_fd, buf, nr)) != nr) {
1281 (void)unlink(to_name);
1284 "short write to %s: %jd bytes written, %jd bytes asked to write",
1285 to_name, (uintmax_t)nw,
1289 err(EX_OSERR, "%s", to_name);
1292 digest_update(&ctx, buf, nr);
1296 (void)unlink(to_name);
1298 err(EX_OSERR, "%s", from_name);
1301 if (safecopy && fsync(to_fd) == -1) {
1303 (void)unlink(to_name);
1305 err(EX_OSERR, "fsync failed for %s", to_name);
1307 return (digest_end(&ctx, NULL));
1312 * Use strip(1) to strip the target file.
1313 * Just invoke strip(1) on to_name if from_name is NULL, else try
1314 * to run "strip -o to_name -- from_name" and return 0 on failure.
1315 * Return 1 on success and assign result of digest_file(to_name)
1319 strip(const char *to_name, int to_fd, const char *from_name, char **dresp)
1321 const char *stripbin;
1322 const char *args[6];
1324 int error, serrno, status;
1326 stripbin = getenv("STRIPBIN");
1327 if (stripbin == NULL)
1330 if (from_name == NULL) {
1337 args[4] = from_name;
1340 error = posix_spawnp(&pid, stripbin, NULL, NULL,
1341 __DECONST(char **, args), environ);
1343 (void)unlink(to_name);
1344 errc(error == EAGAIN || error == EPROCLIM || error == ENOMEM ?
1345 EX_TEMPFAIL : EX_OSERR, error, "spawn %s", stripbin);
1347 if (waitpid(pid, &status, 0) == -1) {
1349 (void)unlink(to_name);
1350 errc(EX_SOFTWARE, error, "wait");
1354 if (from_name != NULL)
1356 (void)unlink(to_name);
1357 errx(EX_SOFTWARE, "strip command %s failed on %s",
1360 if (from_name != NULL && safecopy && fsync(to_fd) == -1) {
1362 (void)unlink(to_name);
1364 err(EX_OSERR, "fsync failed for %s", to_name);
1367 *dresp = digest_file(to_name);
1373 * build directory hierarchy
1376 install_dir(char *path)
1380 int ch, tried_mkdir;
1382 for (p = path;; ++p)
1383 if (!*p || (p != path && *p == '/')) {
1388 if (stat(path, &sb) < 0) {
1389 if (errno != ENOENT || tried_mkdir)
1390 err(EX_OSERR, "stat %s", path);
1391 if (mkdir(path, 0755) < 0) {
1393 if (errno == EEXIST)
1395 err(EX_OSERR, "mkdir %s", path);
1398 (void)printf("install: mkdir %s\n",
1400 } else if (!S_ISDIR(sb.st_mode))
1401 errx(EX_OSERR, "%s exists but is not a directory", path);
1407 if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
1408 chown(path, uid, gid))
1409 warn("chown %u:%u %s", uid, gid, path);
1410 /* XXXBED: should we do the chmod in the dounpriv case? */
1411 if (chmod(path, mode))
1412 warn("chmod %o %s", mode, path);
1414 metadata_log(path, "dir", NULL, NULL, NULL, 0);
1419 * if metafp is not NULL, output mtree(8) full path name and settings to
1420 * metafp, to allow permissions to be set correctly by other tools,
1421 * or to allow integrity checks to be performed.
1424 metadata_log(const char *path, const char *type, struct timespec *ts,
1425 const char *slink, const char *digestresult, off_t size)
1427 static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1431 struct flock metalog_lock;
1435 /* Buffer for strsvis(3). */
1436 buf = (char *)malloc(4 * strlen(path) + 1);
1438 warnx("%s", strerror(ENOMEM));
1442 /* Lock log file. */
1443 metalog_lock.l_start = 0;
1444 metalog_lock.l_len = 0;
1445 metalog_lock.l_whence = SEEK_SET;
1446 metalog_lock.l_type = F_WRLCK;
1447 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1448 warn("can't lock %s", metafile);
1453 /* Remove destdir. */
1456 destlen = strlen(destdir);
1457 if (strncmp(p, destdir, destlen) == 0 &&
1458 (p[destlen] == '/' || p[destlen] == '\0'))
1461 while (*p && *p == '/')
1463 strsvis(buf, p, VIS_OCTAL, extra);
1465 /* Print details. */
1466 fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1468 fprintf(metafp, " uname=%s", owner);
1470 fprintf(metafp, " gname=%s", group);
1471 fprintf(metafp, " mode=%#o", mode);
1473 strsvis(buf, slink, VIS_CSTYLE, extra); /* encode link */
1474 fprintf(metafp, " link=%s", buf);
1476 if (*type == 'f') /* type=file */
1477 fprintf(metafp, " size=%lld", (long long)size);
1478 if (ts != NULL && dopreserve)
1479 fprintf(metafp, " time=%lld.%09ld",
1480 (long long)ts[1].tv_sec, ts[1].tv_nsec);
1481 if (digestresult && digest)
1482 fprintf(metafp, " %s=%s", digest, digestresult);
1484 fprintf(metafp, " flags=%s", fflags);
1486 fprintf(metafp, " tags=%s", tags);
1487 fputc('\n', metafp);
1491 /* Unlock log file. */
1492 metalog_lock.l_type = F_UNLCK;
1493 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1)
1494 warn("can't unlock %s", metafile);
1500 * print a usage message and die
1505 (void)fprintf(stderr,
1506 "usage: install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1507 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1508 " [-B suffix] [-l linkflags] [-N dbdir]\n"
1510 " install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1511 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1512 " [-B suffix] [-l linkflags] [-N dbdir]\n"
1513 " file1 ... fileN directory\n"
1514 " install -dU [-vU] [-g group] [-m mode] [-N dbdir] [-o owner]\n"
1515 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1516 " directory ...\n");
1523 * return true (1) if mmap should be tried, false (0) if not.
1529 * The ifdef is for bootstrapping - f_fstypename doesn't exist in
1530 * pre-Lite2-merge systems.
1535 if (fstatfs(fd, &stfs) != 0)
1537 if (strcmp(stfs.f_fstypename, "ufs") == 0 ||
1538 strcmp(stfs.f_fstypename, "cd9660") == 0)