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>
83 * Memory strategy threshold, in pages: if physmem is larger then this, use a
86 #define PHYSPAGES_THRESHOLD (32*1024)
88 /* Maximum buffer size in bytes - do not allow it to grow larger than this. */
89 #define BUFSIZE_MAX (2*1024*1024)
92 * Small (default) buffer size in bytes. It's inefficient for this to be
93 * smaller than MAXPHYS.
95 #define BUFSIZE_SMALL (MAXPHYS)
98 * We need to build xinstall during the bootstrap stage when building on a
99 * non-FreeBSD system. Linux does not have the st_flags and st_birthtime
100 * members in struct stat so we need to omit support for changing those fields.
103 #define HAVE_STRUCT_STAT_ST_FLAGS 1
105 #define HAVE_STRUCT_STAT_ST_FLAGS 0
108 #define MAX_CMP_SIZE (16 * 1024 * 1024)
110 #define LN_ABSOLUTE 0x01
111 #define LN_RELATIVE 0x02
113 #define LN_SYMBOLIC 0x08
114 #define LN_MIXED 0x10
116 #define DIRECTORY 0x01 /* Tell install it's a directory. */
117 #define SETFLAGS 0x02 /* Tell install to set flags. */
118 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
119 #define BACKUP_SUFFIX ".old"
125 #ifdef WITH_RIPEMD160
126 RIPEMD160_CTX RIPEMD160;
138 #ifdef WITH_RIPEMD160
144 } digesttype = DIGEST_NONE;
146 extern char **environ;
150 static int dobackup, docompare, dodir, dolink, dopreserve, dostrip, dounpriv,
152 static int haveopt_f, haveopt_g, haveopt_m, haveopt_o;
153 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
155 static const char *group, *owner;
156 static const char *suffix = BACKUP_SUFFIX;
157 static char *destdir, *digest, *fflags, *metafile, *tags;
159 static int compare(int, const char *, size_t, int, const char *, size_t,
161 static char *copy(int, const char *, int, const char *, off_t);
162 static int create_newfile(const char *, int, struct stat *);
163 static int create_tempfile(const char *, char *, size_t);
164 static char *quiet_mktemp(char *template);
165 static char *digest_file(const char *);
166 static void digest_init(DIGEST_CTX *);
167 static void digest_update(DIGEST_CTX *, const char *, size_t);
168 static char *digest_end(DIGEST_CTX *, char *);
169 static int do_link(const char *, const char *, const struct stat *);
170 static void do_symlink(const char *, const char *, const struct stat *);
171 static void makelink(const char *, const char *, const struct stat *);
172 static void install(const char *, const char *, u_long, u_int);
173 static void install_dir(char *);
174 static void metadata_log(const char *, const char *, struct timespec *,
175 const char *, const char *, off_t);
176 static int parseid(const char *, id_t *);
177 static int strip(const char *, int, const char *, char **);
178 static int trymmap(size_t);
179 static void usage(void);
182 main(int argc, char *argv[])
184 struct stat from_sb, to_sb;
194 group = owner = NULL;
195 while ((ch = getopt(argc, argv, "B:bCcD:df:g:h:l:M:m:N:o:pSsT:Uv")) !=
208 /* For backwards compatibility. */
228 for (p = optarg; *p != '\0'; p++)
231 dolink &= ~(LN_HARD|LN_MIXED);
232 dolink |= LN_SYMBOLIC;
235 dolink &= ~(LN_SYMBOLIC|LN_MIXED);
239 dolink &= ~(LN_SYMBOLIC|LN_HARD);
243 dolink &= ~LN_RELATIVE;
244 dolink |= LN_ABSOLUTE;
247 dolink &= ~LN_ABSOLUTE;
248 dolink |= LN_RELATIVE;
251 errx(1, "%c: invalid link type", *p);
260 if (!(set = setmode(optarg)))
261 errx(EX_USAGE, "invalid file mode: %s",
263 mode = getmode(set, 0);
267 if (!setup_getid(optarg))
268 err(EX_OSERR, "Unable to use user and group "
269 "databases in `%s'", optarg);
276 docompare = dopreserve = 1;
300 /* some options make no sense when creating directories */
301 if (dostrip && dodir) {
302 warnx("-d and -s may not be specified together");
306 if (getenv("DONTSTRIP") != NULL) {
307 warnx("DONTSTRIP set - will not strip installed binaries");
311 /* must have at least two arguments, except when creating directories */
312 if (argc == 0 || (argc == 1 && !dodir))
315 if (digest != NULL) {
316 if (strcmp(digest, "none") == 0) {
317 digesttype = DIGEST_NONE;
319 } else if (strcmp(digest, "md5") == 0) {
320 digesttype = DIGEST_MD5;
322 #ifdef WITH_RIPEMD160
323 } else if (strcmp(digest, "rmd160") == 0) {
324 digesttype = DIGEST_RIPEMD160;
326 } else if (strcmp(digest, "sha1") == 0) {
327 digesttype = DIGEST_SHA1;
328 } else if (strcmp(digest, "sha256") == 0) {
329 digesttype = DIGEST_SHA256;
330 } else if (strcmp(digest, "sha512") == 0) {
331 digesttype = DIGEST_SHA512;
333 warnx("unknown digest `%s'", digest);
338 /* need to make a temp copy so we can compare stripped version */
339 if (docompare && dostrip)
342 /* get group and owner id's */
343 if (group != NULL && !dounpriv) {
344 if (gid_from_group(group, &gid) == -1) {
346 if (!parseid(group, &id))
347 errx(1, "unknown group %s", group);
353 if (owner != NULL && !dounpriv) {
354 if (uid_from_user(owner, &uid) == -1) {
356 if (!parseid(owner, &id))
357 errx(1, "unknown user %s", owner);
363 if (fflags != NULL && !dounpriv) {
364 if (strtofflags(&fflags, &fset, NULL))
365 errx(EX_USAGE, "%s: invalid flag", fflags);
369 if (metafile != NULL) {
370 if ((metafp = fopen(metafile, "a")) == NULL)
371 warn("open %s", metafile);
373 digesttype = DIGEST_NONE;
376 for (; *argv != NULL; ++argv)
382 to_name = argv[argc - 1];
383 no_target = stat(to_name, &to_sb);
384 if (!no_target && S_ISDIR(to_sb.st_mode)) {
385 if (dolink & LN_SYMBOLIC) {
386 if (lstat(to_name, &to_sb) != 0)
387 err(EX_OSERR, "%s vanished", to_name);
388 if (S_ISLNK(to_sb.st_mode)) {
391 err(EX_USAGE, "%s", to_name);
393 install(*argv, to_name, fset, iflags);
397 for (; *argv != to_name; ++argv)
398 install(*argv, to_name, fset, iflags | DIRECTORY);
403 /* can't do file1 file2 directory/file */
406 warnx("target directory `%s' does not exist",
409 warnx("target `%s' is not a directory",
414 if (!no_target && !dolink) {
415 if (stat(*argv, &from_sb))
416 err(EX_OSERR, "%s", *argv);
417 if (!S_ISREG(to_sb.st_mode)) {
419 err(EX_OSERR, "%s", to_name);
421 if (to_sb.st_dev == from_sb.st_dev &&
422 to_sb.st_ino == from_sb.st_ino)
424 "%s and %s are the same file", *argv, to_name);
426 install(*argv, to_name, fset, iflags);
432 digest_file(const char *name)
435 switch (digesttype) {
438 return (MD5File(name, NULL));
440 #ifdef WITH_RIPEMD160
441 case DIGEST_RIPEMD160:
442 return (RIPEMD160_File(name, NULL));
445 return (SHA1_File(name, NULL));
447 return (SHA256_File(name, NULL));
449 return (SHA512_File(name, NULL));
456 digest_init(DIGEST_CTX *c)
459 switch (digesttype) {
467 #ifdef WITH_RIPEMD160
468 case DIGEST_RIPEMD160:
469 RIPEMD160_Init(&(c->RIPEMD160));
473 SHA1_Init(&(c->SHA1));
476 SHA256_Init(&(c->SHA256));
479 SHA512_Init(&(c->SHA512));
485 digest_update(DIGEST_CTX *c, const char *data, size_t len)
488 switch (digesttype) {
493 MD5Update(&(c->MD5), data, len);
496 #ifdef WITH_RIPEMD160
497 case DIGEST_RIPEMD160:
498 RIPEMD160_Update(&(c->RIPEMD160), data, len);
502 SHA1_Update(&(c->SHA1), data, len);
505 SHA256_Update(&(c->SHA256), data, len);
508 SHA512_Update(&(c->SHA512), data, len);
514 digest_end(DIGEST_CTX *c, char *buf)
517 switch (digesttype) {
520 return (MD5End(&(c->MD5), buf));
522 #ifdef WITH_RIPEMD160
523 case DIGEST_RIPEMD160:
524 return (RIPEMD160_End(&(c->RIPEMD160), buf));
527 return (SHA1_End(&(c->SHA1), buf));
529 return (SHA256_End(&(c->SHA256), buf));
531 return (SHA512_End(&(c->SHA512), buf));
539 * parse uid or gid from arg into id, returning non-zero if successful
542 parseid(const char *name, id_t *id)
546 *id = (id_t)strtoul(name, &ep, 10);
547 if (errno || *ep != '\0')
554 * mktemp implementation used mkstemp to avoid mktemp warnings. We
555 * really do need mktemp semantics here as we will be creating a link.
558 quiet_mktemp(char *template)
562 if ((fd = mkstemp(template)) == -1)
565 if (unlink(template) == -1)
566 err(EX_OSERR, "unlink %s", template);
572 * make a hard link, obeying dorename if set
573 * return -1 on failure
576 do_link(const char *from_name, const char *to_name,
577 const struct stat *target_sb)
579 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);
587 ret = link(from_name, tmpl);
589 if (target_sb->st_mode & S_IFDIR && rmdir(to_name) ==
592 err(EX_OSERR, "%s", to_name);
594 #if HAVE_STRUCT_STAT_ST_FLAGS
595 if (target_sb->st_flags & NOCHANGEBITS)
596 (void)chflags(to_name, target_sb->st_flags &
600 printf("install: link %s -> %s\n",
602 ret = rename(tmpl, to_name);
604 * If rename has posix semantics, then the temporary
605 * file may still exist when from_name and to_name point
606 * to the same file, so unlink it unconditionally.
613 printf("install: link %s -> %s\n",
615 return (link(from_name, to_name));
621 * Make a symbolic link, obeying dorename if set. Exit on failure.
624 do_symlink(const char *from_name, const char *to_name,
625 const struct stat *target_sb)
627 char tmpl[MAXPATHLEN];
629 if (safecopy && target_sb != NULL) {
630 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
631 /* This usage is safe. */
632 if (quiet_mktemp(tmpl) == NULL)
633 err(EX_OSERR, "%s: mktemp", tmpl);
635 if (symlink(from_name, tmpl) == -1)
636 err(EX_OSERR, "symlink %s -> %s", from_name, tmpl);
638 if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) {
640 err(EX_OSERR, "%s", to_name);
642 #if HAVE_STRUCT_STAT_ST_FLAGS
643 if (target_sb->st_flags & NOCHANGEBITS)
644 (void)chflags(to_name, target_sb->st_flags &
648 printf("install: symlink %s -> %s\n",
650 if (rename(tmpl, to_name) == -1) {
651 /* Remove temporary link before exiting. */
653 err(EX_OSERR, "%s: rename", to_name);
657 printf("install: symlink %s -> %s\n",
659 if (symlink(from_name, to_name) == -1)
660 err(EX_OSERR, "symlink %s -> %s", from_name, to_name);
666 * make a link from source to destination
669 makelink(const char *from_name, const char *to_name,
670 const struct stat *target_sb)
672 char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
675 /* Try hard links first. */
676 if (dolink & (LN_HARD|LN_MIXED)) {
677 if (do_link(from_name, to_name, target_sb) == -1) {
678 if ((dolink & LN_HARD) || errno != EXDEV)
679 err(EX_OSERR, "link %s -> %s", from_name, to_name);
681 if (stat(to_name, &to_sb))
682 err(EX_OSERR, "%s: stat", to_name);
683 if (S_ISREG(to_sb.st_mode)) {
685 * XXX: hard links to anything other than
686 * plain files are not metalogged
689 const char *oowner, *ogroup;
694 * XXX: use underlying perms, unless
695 * overridden on command line.
699 mode = (to_sb.st_mode & 0777);
709 dres = digest_file(from_name);
710 metadata_log(to_name, "file", NULL, NULL,
711 dres, to_sb.st_size);
722 /* Symbolic links. */
723 if (dolink & LN_ABSOLUTE) {
724 /* Convert source path to absolute. */
725 if (realpath(from_name, src) == NULL)
726 err(EX_OSERR, "%s: realpath", from_name);
727 do_symlink(src, to_name, target_sb);
728 /* XXX: src may point outside of destdir */
729 metadata_log(to_name, "link", NULL, src, NULL, 0);
733 if (dolink & LN_RELATIVE) {
734 char *to_name_copy, *cp, *d, *ld, *ls, *s;
736 if (*from_name != '/') {
737 /* this is already a relative link */
738 do_symlink(from_name, to_name, target_sb);
739 /* XXX: from_name may point outside of destdir. */
740 metadata_log(to_name, "link", NULL, from_name, NULL, 0);
744 /* Resolve pathnames. */
745 if (realpath(from_name, src) == NULL)
746 err(EX_OSERR, "%s: realpath", from_name);
749 * The last component of to_name may be a symlink,
750 * so use realpath to resolve only the directory.
752 to_name_copy = strdup(to_name);
753 if (to_name_copy == NULL)
754 err(EX_OSERR, "%s: strdup", to_name);
755 cp = dirname(to_name_copy);
756 if (realpath(cp, dst) == NULL)
757 err(EX_OSERR, "%s: realpath", cp);
758 /* .. and add the last component. */
759 if (strcmp(dst, "/") != 0) {
760 if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
761 errx(1, "resolved pathname too long");
763 strcpy(to_name_copy, to_name);
764 cp = basename(to_name_copy);
765 if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
766 errx(1, "resolved pathname too long");
769 /* Trim common path components. */
771 for (s = src, d = dst; *s == *d; ls = s, ld = d, s++, d++)
774 * If we didn't end after a directory separator, then we've
775 * falsely matched the last component. For example, if one
776 * invoked install -lrs /lib/foo.so /libexec/ then the source
777 * would terminate just after the separator while the
778 * destination would terminate in the middle of 'libexec',
779 * leading to a full directory getting falsely eaten.
781 if ((ls != NULL && *ls != '/') || (ld != NULL && *ld != '/'))
786 /* Count the number of directories we need to backtrack. */
787 for (++d, lnk[0] = '\0'; *d; d++)
789 (void)strlcat(lnk, "../", sizeof(lnk));
791 (void)strlcat(lnk, ++s, sizeof(lnk));
793 do_symlink(lnk, to_name, target_sb);
794 /* XXX: Link may point outside of destdir. */
795 metadata_log(to_name, "link", NULL, lnk, NULL, 0);
800 * If absolute or relative was not specified, try the names the
803 do_symlink(from_name, to_name, target_sb);
804 /* XXX: from_name may point outside of destdir. */
805 metadata_log(to_name, "link", NULL, from_name, NULL, 0);
810 * build a path name and install the file
813 install(const char *from_name, const char *to_name, u_long fset, u_int flags)
815 struct stat from_sb, temp_sb, to_sb;
816 struct timespec tsb[2];
817 int devnull, files_match, from_fd, serrno, stripped, target;
818 int tempcopy, temp_fd, to_fd;
819 char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
823 files_match = stripped = 0;
827 /* If try to install NULL file to a directory, fails. */
828 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
830 if (stat(from_name, &from_sb))
831 err(EX_OSERR, "%s", from_name);
832 if (!S_ISREG(from_sb.st_mode)) {
834 err(EX_OSERR, "%s", from_name);
837 /* Build the target path. */
838 if (flags & DIRECTORY) {
839 (void)snprintf(pathbuf, sizeof(pathbuf), "%s%s%s",
841 to_name[strlen(to_name) - 1] == '/' ? "" : "/",
842 (p = strrchr(from_name, '/')) ? ++p : from_name);
850 target = (lstat(to_name, &to_sb) == 0);
853 if (target && !safecopy) {
854 if (to_sb.st_mode & S_IFDIR && rmdir(to_name) == -1)
855 err(EX_OSERR, "%s", to_name);
856 #if HAVE_STRUCT_STAT_ST_FLAGS
857 if (to_sb.st_flags & NOCHANGEBITS)
858 (void)chflags(to_name,
859 to_sb.st_flags & ~NOCHANGEBITS);
863 makelink(from_name, to_name, target ? &to_sb : NULL);
867 if (target && !S_ISREG(to_sb.st_mode) && !S_ISLNK(to_sb.st_mode)) {
873 /* Only copy safe if the target exists. */
874 tempcopy = safecopy && target;
876 if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
877 err(EX_OSERR, "%s", from_name);
879 /* If we don't strip, we can compare first. */
880 if (docompare && !dostrip && target && S_ISREG(to_sb.st_mode)) {
881 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
882 err(EX_OSERR, "%s", to_name);
884 files_match = to_sb.st_size == 0;
886 files_match = !(compare(from_fd, from_name,
887 (size_t)from_sb.st_size, to_fd,
888 to_name, (size_t)to_sb.st_size, &digestresult));
890 /* Close "to" file unless we match. */
897 to_fd = create_tempfile(to_name, tempfile,
900 err(EX_OSERR, "%s", tempfile);
902 if ((to_fd = create_newfile(to_name, target,
904 err(EX_OSERR, "%s", to_name);
906 (void)printf("install: %s -> %s\n",
911 stripped = strip(tempcopy ? tempfile : to_name,
912 to_fd, from_name, &digestresult);
914 digestresult = copy(from_fd, from_name, to_fd,
915 tempcopy ? tempfile : to_name, from_sb.st_size);
921 (void)strip(tempcopy ? tempfile : to_name, to_fd,
922 NULL, &digestresult);
925 * Re-open our fd on the target, in case
926 * we did not strip in-place.
929 to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
931 err(EX_OSERR, "stripping %s", to_name);
935 * Compare the stripped temp file with the target.
937 if (docompare && dostrip && target && S_ISREG(to_sb.st_mode)) {
940 /* Re-open to_fd using the real target name. */
941 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
942 err(EX_OSERR, "%s", to_name);
944 if (fstat(temp_fd, &temp_sb)) {
946 (void)unlink(tempfile);
948 err(EX_OSERR, "%s", tempfile);
951 if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
952 to_name, (size_t)to_sb.st_size, &digestresult)
955 * If target has more than one link we need to
956 * replace it in order to snap the extra links.
957 * Need to preserve target file times, though.
959 if (to_sb.st_nlink != 1) {
960 tsb[0] = to_sb.st_atim;
961 tsb[1] = to_sb.st_mtim;
962 (void)utimensat(AT_FDCWD, tempfile, tsb, 0);
965 (void)unlink(tempfile);
967 (void) close(temp_fd);
970 digestresult = digest_file(tempfile);
973 * Move the new file into place if doing a safe copy
974 * and the files are different (or just not compared).
976 if (tempcopy && !files_match) {
977 #if HAVE_STRUCT_STAT_ST_FLAGS
978 /* Try to turn off the immutable bits. */
979 if (to_sb.st_flags & NOCHANGEBITS)
980 (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
983 if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
984 suffix) != strlen(to_name) + strlen(suffix)) {
986 errx(EX_OSERR, "%s: backup filename too long",
990 (void)printf("install: %s -> %s\n", to_name, backup);
991 if (unlink(backup) < 0 && errno != ENOENT) {
993 #if HAVE_STRUCT_STAT_ST_FLAGS
994 if (to_sb.st_flags & NOCHANGEBITS)
995 (void)chflags(to_name, to_sb.st_flags);
999 err(EX_OSERR, "unlink: %s", backup);
1001 if (link(to_name, backup) < 0) {
1004 #if HAVE_STRUCT_STAT_ST_FLAGS
1005 if (to_sb.st_flags & NOCHANGEBITS)
1006 (void)chflags(to_name, to_sb.st_flags);
1009 err(EX_OSERR, "link: %s to %s", to_name,
1014 (void)printf("install: %s -> %s\n", from_name, to_name);
1015 if (rename(tempfile, to_name) < 0) {
1019 err(EX_OSERR, "rename: %s to %s",
1023 /* Re-open to_fd so we aren't hosed by the rename(2). */
1024 (void) close(to_fd);
1025 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
1026 err(EX_OSERR, "%s", to_name);
1030 * Preserve the timestamp of the source file if necessary.
1032 if (dopreserve && !files_match && !devnull) {
1033 tsb[0] = from_sb.st_atim;
1034 tsb[1] = from_sb.st_mtim;
1035 (void)utimensat(AT_FDCWD, to_name, tsb, 0);
1038 if (fstat(to_fd, &to_sb) == -1) {
1040 (void)unlink(to_name);
1042 err(EX_OSERR, "%s", to_name);
1046 * Set owner, group, mode for target; do the chown first,
1047 * chown may lose the setuid bits.
1049 if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
1050 (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
1051 (mode != (to_sb.st_mode & ALLPERMS)))) {
1052 #if HAVE_STRUCT_STAT_ST_FLAGS
1053 /* Try to turn off the immutable bits. */
1054 if (to_sb.st_flags & NOCHANGEBITS)
1055 (void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
1059 if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
1060 (uid != (uid_t)-1 && uid != to_sb.st_uid))) {
1061 if (fchown(to_fd, uid, gid) == -1) {
1063 (void)unlink(to_name);
1065 err(EX_OSERR,"%s: chown/chgrp", to_name);
1068 if (mode != (to_sb.st_mode & ALLPERMS)) {
1070 dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) {
1072 (void)unlink(to_name);
1074 err(EX_OSERR, "%s: chmod", to_name);
1077 #if HAVE_STRUCT_STAT_ST_FLAGS
1079 * If provided a set of flags, set them, otherwise, preserve the
1080 * flags, except for the dump flag.
1081 * NFS does not support flags. Ignore EOPNOTSUPP flags if we're just
1082 * trying to turn off UF_NODUMP. If we're trying to set real flags,
1083 * then warn if the fs doesn't support it, otherwise fail.
1085 if (!dounpriv && !devnull && (flags & SETFLAGS ||
1086 (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) &&
1088 flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
1089 if (flags & SETFLAGS) {
1090 if (errno == EOPNOTSUPP)
1091 warn("%s: chflags", to_name);
1094 (void)unlink(to_name);
1096 err(EX_OSERR, "%s: chflags", to_name);
1104 (void)close(from_fd);
1106 metadata_log(to_name, "file", tsb, NULL, digestresult, to_sb.st_size);
1112 * Compare two files; non-zero means files differ.
1113 * Compute digest and return its address in *dresp
1114 * unless it points to pre-computed digest.
1117 compare(int from_fd, const char *from_name __unused, size_t from_len,
1118 int to_fd, const char *to_name __unused, size_t to_len,
1123 int do_digest, done_compare;
1127 if (from_len != to_len)
1130 do_digest = (digesttype != DIGEST_NONE && dresp != NULL &&
1132 if (from_len <= MAX_CMP_SIZE) {
1136 if (trymmap(from_len) && trymmap(to_len)) {
1137 p = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1139 if (p == MAP_FAILED)
1141 q = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1143 if (q == MAP_FAILED) {
1144 munmap(p, from_len);
1148 rv = memcmp(p, q, from_len);
1150 digest_update(&ctx, p, from_len);
1151 munmap(p, from_len);
1152 munmap(q, from_len);
1156 if (!done_compare) {
1157 static char *buf, *buf1, *buf2;
1158 static size_t bufsize;
1163 * Note that buf and bufsize are static. If
1164 * malloc() fails, it will fail at the start
1165 * and not copy only some files.
1167 if (sysconf(_SC_PHYS_PAGES) >
1168 PHYSPAGES_THRESHOLD)
1169 bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
1171 bufsize = BUFSIZE_SMALL;
1172 buf = malloc(bufsize * 2);
1174 err(1, "Not enough memory");
1176 buf2 = buf + bufsize;
1179 lseek(from_fd, 0, SEEK_SET);
1180 lseek(to_fd, 0, SEEK_SET);
1182 n1 = read(from_fd, buf1, bufsize);
1186 n2 = read(to_fd, buf2, n1);
1188 rv = memcmp(buf1, buf2, n1);
1190 rv = 1; /* out of sync */
1192 rv = 1; /* read failure */
1194 digest_update(&ctx, buf1, n1);
1196 lseek(from_fd, 0, SEEK_SET);
1197 lseek(to_fd, 0, SEEK_SET);
1200 rv = 1; /* don't bother in this case */
1204 *dresp = digest_end(&ctx, NULL);
1206 (void)digest_end(&ctx, NULL);
1213 * create_tempfile --
1214 * create a temporary file based on path and open it
1217 create_tempfile(const char *path, char *temp, size_t tsize)
1221 (void)strncpy(temp, path, tsize);
1222 temp[tsize - 1] = '\0';
1223 if ((p = strrchr(temp, '/')) != NULL)
1227 (void)strncpy(p, "INS@XXXXXX", &temp[tsize - 1] - p);
1228 temp[tsize - 1] = '\0';
1229 return (mkstemp(temp));
1234 * create a new file, overwriting an existing one if necessary
1237 create_newfile(const char *path, int target, struct stat *sbp)
1239 char backup[MAXPATHLEN];
1240 int saved_errno = 0;
1245 * Unlink now... avoid ETXTBSY errors later. Try to turn
1246 * off the append/immutable bits -- if we fail, go ahead,
1249 #if HAVE_STRUCT_STAT_ST_FLAGS
1250 if (sbp->st_flags & NOCHANGEBITS)
1251 (void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
1255 if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s",
1256 path, suffix) != strlen(path) + strlen(suffix)) {
1257 saved_errno = errno;
1258 #if HAVE_STRUCT_STAT_ST_FLAGS
1259 if (sbp->st_flags & NOCHANGEBITS)
1260 (void)chflags(path, sbp->st_flags);
1262 errno = saved_errno;
1263 errx(EX_OSERR, "%s: backup filename too long",
1266 (void)snprintf(backup, MAXPATHLEN, "%s%s",
1269 (void)printf("install: %s -> %s\n",
1271 if (rename(path, backup) < 0) {
1272 saved_errno = errno;
1273 #if HAVE_STRUCT_STAT_ST_FLAGS
1274 if (sbp->st_flags & NOCHANGEBITS)
1275 (void)chflags(path, sbp->st_flags);
1277 errno = saved_errno;
1278 err(EX_OSERR, "rename: %s to %s", path, backup);
1281 if (unlink(path) < 0)
1282 saved_errno = errno;
1285 newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
1286 if (newfd < 0 && saved_errno != 0)
1287 errno = saved_errno;
1293 * copy from one file to another
1296 copy(int from_fd, const char *from_name, int to_fd, const char *to_name,
1299 static char *buf = NULL;
1300 static size_t bufsize;
1307 /* Rewind file descriptors. */
1308 if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1309 err(EX_OSERR, "lseek: %s", from_name);
1310 if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1311 err(EX_OSERR, "lseek: %s", to_name);
1316 if (trymmap((size_t)size) &&
1317 (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED,
1318 from_fd, (off_t)0)) != MAP_FAILED) {
1319 nw = write(to_fd, p, size);
1322 (void)unlink(to_name);
1325 "short write to %s: %jd bytes written, %jd bytes asked to write",
1326 to_name, (uintmax_t)nw, (uintmax_t)size);
1329 err(EX_OSERR, "%s", to_name);
1332 digest_update(&ctx, p, size);
1333 (void)munmap(p, size);
1339 * Note that buf and bufsize are static. If
1340 * malloc() fails, it will fail at the start
1341 * and not copy only some files.
1343 if (sysconf(_SC_PHYS_PAGES) >
1344 PHYSPAGES_THRESHOLD)
1345 bufsize = MIN(BUFSIZE_MAX, MAXPHYS * 8);
1347 bufsize = BUFSIZE_SMALL;
1348 buf = malloc(bufsize);
1350 err(1, "Not enough memory");
1352 while ((nr = read(from_fd, buf, bufsize)) > 0) {
1353 if ((nw = write(to_fd, buf, nr)) != nr) {
1355 (void)unlink(to_name);
1358 "short write to %s: %jd bytes written, %jd bytes asked to write",
1359 to_name, (uintmax_t)nw,
1363 err(EX_OSERR, "%s", to_name);
1366 digest_update(&ctx, buf, nr);
1370 (void)unlink(to_name);
1372 err(EX_OSERR, "%s", from_name);
1375 if (safecopy && fsync(to_fd) == -1) {
1377 (void)unlink(to_name);
1379 err(EX_OSERR, "fsync failed for %s", to_name);
1381 return (digest_end(&ctx, NULL));
1386 * Use strip(1) to strip the target file.
1387 * Just invoke strip(1) on to_name if from_name is NULL, else try
1388 * to run "strip -o to_name from_name" and return 0 on failure.
1389 * Return 1 on success and assign result of digest_file(to_name)
1393 strip(const char *to_name, int to_fd, const char *from_name, char **dresp)
1395 const char *stripbin;
1396 const char *args[5];
1397 char *prefixed_from_name;
1399 int error, serrno, status;
1401 prefixed_from_name = NULL;
1402 stripbin = getenv("STRIPBIN");
1403 if (stripbin == NULL)
1406 if (from_name == NULL) {
1413 /* Prepend './' if from_name begins with '-' */
1414 if (from_name[0] == '-') {
1415 if (asprintf(&prefixed_from_name, "./%s", from_name) == -1)
1417 args[3] = prefixed_from_name;
1419 args[3] = from_name;
1423 error = posix_spawnp(&pid, stripbin, NULL, NULL,
1424 __DECONST(char **, args), environ);
1426 (void)unlink(to_name);
1427 errc(error == EAGAIN || error == EPROCLIM || error == ENOMEM ?
1428 EX_TEMPFAIL : EX_OSERR, error, "spawn %s", stripbin);
1430 free(prefixed_from_name);
1431 if (waitpid(pid, &status, 0) == -1) {
1433 (void)unlink(to_name);
1434 errc(EX_SOFTWARE, error, "wait");
1438 if (from_name != NULL)
1440 (void)unlink(to_name);
1441 errx(EX_SOFTWARE, "strip command %s failed on %s",
1444 if (from_name != NULL && safecopy && fsync(to_fd) == -1) {
1446 (void)unlink(to_name);
1448 err(EX_OSERR, "fsync failed for %s", to_name);
1451 *dresp = digest_file(to_name);
1457 * build directory hierarchy
1460 install_dir(char *path)
1464 int ch, tried_mkdir;
1466 for (p = path;; ++p)
1467 if (!*p || (p != path && *p == '/')) {
1472 if (stat(path, &sb) != 0) {
1473 if (errno != ENOENT || tried_mkdir)
1474 err(EX_OSERR, "stat %s", path);
1475 if (mkdir(path, 0755) < 0) {
1477 if (errno == EEXIST)
1479 err(EX_OSERR, "mkdir %s", path);
1482 (void)printf("install: mkdir %s\n",
1484 } else if (!S_ISDIR(sb.st_mode))
1485 errx(EX_OSERR, "%s exists but is not a directory", path);
1491 if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
1492 chown(path, uid, gid))
1493 warn("chown %u:%u %s", uid, gid, path);
1494 /* XXXBED: should we do the chmod in the dounpriv case? */
1495 if (chmod(path, mode))
1496 warn("chmod %o %s", mode, path);
1498 metadata_log(path, "dir", NULL, NULL, NULL, 0);
1503 * if metafp is not NULL, output mtree(8) full path name and settings to
1504 * metafp, to allow permissions to be set correctly by other tools,
1505 * or to allow integrity checks to be performed.
1508 metadata_log(const char *path, const char *type, struct timespec *ts,
1509 const char *slink, const char *digestresult, off_t size)
1511 static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1515 struct flock metalog_lock;
1519 /* Buffer for strsvis(3). */
1520 buf = (char *)malloc(4 * strlen(path) + 1);
1522 warnx("%s", strerror(ENOMEM));
1526 /* Lock log file. */
1527 metalog_lock.l_start = 0;
1528 metalog_lock.l_len = 0;
1529 metalog_lock.l_whence = SEEK_SET;
1530 metalog_lock.l_type = F_WRLCK;
1531 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1532 warn("can't lock %s", metafile);
1537 /* Remove destdir. */
1540 destlen = strlen(destdir);
1541 if (strncmp(p, destdir, destlen) == 0 &&
1542 (p[destlen] == '/' || p[destlen] == '\0'))
1545 while (*p && *p == '/')
1547 strsvis(buf, p, VIS_OCTAL, extra);
1549 /* Print details. */
1550 fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1552 fprintf(metafp, " uname=%s", owner);
1554 fprintf(metafp, " gname=%s", group);
1555 fprintf(metafp, " mode=%#o", mode);
1557 strsvis(buf, slink, VIS_CSTYLE, extra); /* encode link */
1558 fprintf(metafp, " link=%s", buf);
1560 if (*type == 'f') /* type=file */
1561 fprintf(metafp, " size=%lld", (long long)size);
1562 if (ts != NULL && dopreserve)
1563 fprintf(metafp, " time=%lld.%09ld",
1564 (long long)ts[1].tv_sec, ts[1].tv_nsec);
1565 if (digestresult && digest)
1566 fprintf(metafp, " %s=%s", digest, digestresult);
1568 fprintf(metafp, " flags=%s", fflags);
1570 fprintf(metafp, " tags=%s", tags);
1571 fputc('\n', metafp);
1575 /* Unlock log file. */
1576 metalog_lock.l_type = F_UNLCK;
1577 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1)
1578 warn("can't unlock %s", metafile);
1584 * print a usage message and die
1589 (void)fprintf(stderr,
1590 "usage: install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1591 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1592 " [-B suffix] [-l linkflags] [-N dbdir]\n"
1594 " install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1595 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1596 " [-B suffix] [-l linkflags] [-N dbdir]\n"
1597 " file1 ... fileN directory\n"
1598 " install -dU [-vU] [-g group] [-m mode] [-N dbdir] [-o owner]\n"
1599 " [-M log] [-D dest] [-h hash] [-T tags]\n"
1600 " directory ...\n");
1607 * return true (1) if mmap should be tried, false (0) if not.
1610 trymmap(size_t filesize)
1613 * This function existed to skip mmap() for NFS file systems whereas
1614 * nowadays mmap() should be perfectly safe. Nevertheless, using mmap()
1615 * only reduces the number of system calls if we need multiple read()
1616 * syscalls, i.e. if the file size is > MAXBSIZE. However, mmap() is
1617 * more expensive than read() so set the threshold at 4 fewer syscalls.
1618 * Additionally, for larger file size mmap() can significantly increase
1619 * the number of page faults, so avoid it in that case.
1621 * Note: the 8MB limit is not based on any meaningful benchmarking
1622 * results, it is simply reusing the same value that was used before
1623 * and also matches bin/cp.
1625 * XXX: Maybe we shouldn't bother with mmap() at all, since we use
1626 * MAXBSIZE the syscall overhead of read() shouldn't be too high?
1628 return (filesize > 4 * MAXBSIZE && filesize < 8 * 1024 * 1024);