/*
* 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.
*/
/*-
* Copyright (c) 2015 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#define __MKTEMP_OK__ /* All uses of mktemp have been checked */
#include <sys/cdefs.h>
#if defined(__COPYRIGHT) && !defined(lint)
__COPYRIGHT("@(#) Copyright (c) 1987, 1993\
The Regents of the University of California. All rights reserved.");
#endif /* not lint */
#define DIRECTORY 0x01 /* Tell install it's a directory. */
#define SETFLAGS 0x02 /* Tell install to set flags. */
#define HASUID 0x04 /* Tell install the uid was given */
#define HASGID 0x08 /* Tell install the gid was given */
/* can't do file1 file2 directory/file */
if (argc != 2) {
errx(EXIT_FAILURE, "the last argument (%s) "
"must name an existing directory", argv[argc - 1]);
/* NOTREACHED */
}
if (!no_target) {
/* makelink() handles checks for links */
if (!dolink) {
if (stat(*argv, &from_sb))
err(EXIT_FAILURE, "%s: stat", *argv);
if (!S_ISREG(to_sb.st_mode))
errx(EXIT_FAILURE, "%s: not a regular file", to_name);
if (to_sb.st_dev == from_sb.st_dev &&
to_sb.st_ino == from_sb.st_ino)
errx(EXIT_FAILURE, "%s and %s are the same file", *argv,
to_name);
}
/*
* Unlink now... avoid ETXTBSY errors later. Try and turn
* off the append/immutable bits -- if we fail, go ahead,
* it might work.
*/
#if ! HAVE_NBTOOL_CONFIG_H
#define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
if (to_sb.st_flags & NOCHANGEBITS)
(void)chflags(to_name,
to_sb.st_flags & ~(NOCHANGEBITS));
#endif
if (dobackup)
backup(to_name);
else if (!dorename)
(void)unlink(to_name);
}
install(*argv, to_name, iflags);
exit(0);
}
/*
* 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;
/*
* do_link --
* make a hard link, obeying dorename if set
* return -1 on failure
*/
static int
do_link(char *from_name, char *to_name)
{
char tmpl[MAXPATHLEN];
int ret;
if (dorename) {
(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
/* This usage is safe. */
if (mktemp(tmpl) == NULL)
err(EXIT_FAILURE, "%s: mktemp", tmpl);
ret = link(from_name, tmpl);
if (ret == 0) {
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);
}
} else {
ret = link(from_name, to_name);
}
if (ret == 0 && verbose)
(void)printf("install: link %s -> %s\n", from_name, to_name);
return ret;
}
/*
* do_symlink --
* make a symbolic link, obeying dorename if set
* exit on failure
*/
static void
do_symlink(char *from_name, char *to_name)
{
char tmpl[MAXPATHLEN];
if (dorename) {
(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
/* This usage is safe. */
if (mktemp(tmpl) == NULL)
err(EXIT_FAILURE, "%s: mktemp", tmpl);
if (symlink(from_name, tmpl) == -1)
err(EXIT_FAILURE, "symlink %s -> %s", from_name, tmpl);
if (rename(tmpl, to_name) == -1) {
/* remove temporary link before exiting */
(void)unlink(tmpl);
err(EXIT_FAILURE, "%s: rename", to_name);
}
} else {
if (symlink(from_name, to_name) == -1)
err(EXIT_FAILURE, "symlink %s -> %s", from_name, to_name);
}
if (verbose)
(void)printf("install: symlink %s -> %s\n", from_name, to_name);
}
/*
* makelink --
* make a link from source to destination
*/
static void
makelink(char *from_name, char *to_name)
{
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) == -1) {
if ((dolink & LN_HARD) || errno != EXDEV)
err(EXIT_FAILURE, "link %s -> %s", from_name, to_name);
} else {
if (stat(to_name, &to_sb))
err(EXIT_FAILURE, "%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;
char *oowner, *ogroup, *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;
switch (digesttype) {
case DIGEST_MD5:
dres = MD5File(from_name, NULL);
break;
case DIGEST_RMD160:
dres = RMD160File(from_name, NULL);
break;
case DIGEST_SHA1:
dres = SHA1File(from_name, NULL);
break;
case DIGEST_SHA256:
dres = SHA256_File(from_name, NULL);
break;
case DIGEST_SHA384:
dres = SHA384_File(from_name, NULL);
break;
case DIGEST_SHA512:
dres = SHA512_File(from_name, NULL);
break;
default:
dres = NULL;
}
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(EXIT_FAILURE, "%s: realpath", from_name);
do_symlink(src, to_name);
/* XXX: src may point outside of destdir */
metadata_log(to_name, "link", NULL, src, NULL, 0);
return;
}
/*
* The last component of to_name may be a symlink,
* so use realpath to resolve only the directory.
*/
cp = xdirname(to_name);
if (realpath(cp, dst) == NULL)
err(EXIT_FAILURE, "%s: realpath", cp);
/* .. and add the last component */
if (strcmp(dst, "/") != 0) {
if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
errx(EXIT_FAILURE, "resolved pathname too long");
}
cp = xbasename(to_name);
if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
errx(EXIT_FAILURE, "resolved pathname too long");
/* 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);
/* XXX: lnk 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);
/* 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(char *from_name, char *to_name, u_int flags)
{
struct stat from_sb;
struct stat to_sb;
struct timeval tv[2];
off_t size;
int devnull, from_fd, to_fd, serrno, tmpmode;
char *p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
size = -1;
if (!dolink) {
/* ensure that from_sb & tv are sane if !dolink */
if (stat(from_name, &from_sb))
err(EXIT_FAILURE, "%s: stat", from_name);
size = from_sb.st_size;
#if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
#else
tv[0].tv_sec = from_sb.st_atime;
tv[0].tv_usec = 0;
tv[1].tv_sec = from_sb.st_mtime;
tv[1].tv_usec = 0;
#endif
}
/*
* 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);
if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
err(EXIT_FAILURE, "stripping %s", to_name);
/*
* Recalculate size and digestresult after stripping.
*/
if (fstat(to_fd, &to_sb) != 0)
err(EXIT_FAILURE, "%s: fstat", to_name);
size = to_sb.st_size;
digestresult =
copy(to_fd, to_name, -1, NULL, size);
}
if (afterinstallcmd != NULL) {
afterinstall(afterinstallcmd, to_name, 1);
/*
* Re-open our fd on the target, in case we used an
* after-install command that does not work in-place
*/
close(to_fd);
if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
err(EXIT_FAILURE, "running after install command on %s", to_name);
}
/*
* Set owner, group, mode for target; do the chown first,
* chown may lose the setuid bits.
*/
if (!dounpriv &&
(flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
serrno = errno;
(void)unlink(to_name);
errc(EXIT_FAILURE, serrno, "%s: chown/chgrp", to_name);
}
tmpmode = mode;
if (dounpriv)
tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
if (fchmod(to_fd, tmpmode) == -1) {
serrno = errno;
(void)unlink(to_name);
errc(EXIT_FAILURE, serrno, "%s: chmod", to_name);
}
/*
* Preserve the date of the source file.
*/
if (dopreserve) {
#if HAVE_FUTIMES
if (futimes(to_fd, tv) == -1)
warn("%s: futimes", to_name);
#else
if (utimes(to_name, tv) == -1)
warn("%s: utimes", to_name);
#endif
}
(void)close(to_fd);
if (dorename) {
if (rename(to_name, oto_name) == -1)
err(EXIT_FAILURE, "%s: rename", to_name);
to_name = oto_name;
}
if (verbose)
(void)printf("install: %s -> %s\n", from_name, to_name);
/*
* If provided a set of flags, set them, otherwise, preserve the
* flags, except for the dump flag.
*/
#if ! HAVE_NBTOOL_CONFIG_H
if (!dounpriv && chflags(to_name,
flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
{
if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
warn("%s: chflags", to_name);
}
#endif
/*
* copy --
* copy from one file to another, returning a digest.
*
* If to_fd < 0, just calculate a digest, don't copy.
*/
static char *
copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
{
ssize_t nr, nw;
int serrno;
u_char *p;
u_char buf[MAXBSIZE];
MD5_CTX ctxMD5;
RMD160_CTX ctxRMD160;
SHA1_CTX ctxSHA1;
SHA256_CTX ctxSHA256;
SHA384_CTX ctxSHA384;
SHA512_CTX ctxSHA512;
switch (digesttype) {
case DIGEST_MD5:
MD5Init(&ctxMD5);
break;
case DIGEST_RMD160:
RMD160Init(&ctxRMD160);
break;
case DIGEST_SHA1:
SHA1Init(&ctxSHA1);
break;
case DIGEST_SHA256:
SHA256_Init(&ctxSHA256);
break;
case DIGEST_SHA384:
SHA384_Init(&ctxSHA384);
break;
case DIGEST_SHA512:
SHA512_Init(&ctxSHA512);
break;
case DIGEST_NONE:
if (to_fd < 0)
return NULL; /* no need to do anything */
/*FALLTHROUGH*/
default:
break;
}
/*
* There's no reason to do anything other than close the file
* now if it's empty, so let's not bother.
*/
if (size > 0) {
/*
* 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.
*/
/*
* afterinstall --
* run provided command on the target file or directory after it's been
* installed and stripped, but before permissions are set or it's renamed
*/
static void
afterinstall(const char *command, const char *to_name, int errunlink)
{
run(command, NULL, to_name, errunlink);
}
/*
* backup --
* backup file "to_name" to to_name.suffix
* if suffix contains a "%", it's taken as a printf(3) pattern
* used for a numbered backup.
*/
static void
backup(const char *to_name)
{
char bname[FILENAME_MAX];
if (numberedbackup) {
/* Do numbered backup */
int cnt;
char suffix_expanded[FILENAME_MAX];
/*
* 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 timeval *tv,
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;
/*
* The following array is used to make a fast determination of which
* characters are interpreted specially by the shell. If a command
* contains any of these characters, it is executed by the shell, not
* directly by us.
*/
static unsigned char _metachar[128] = {
/* nul soh stx etx eot enq ack bel */
1, 0, 0, 0, 0, 0, 0, 0,
/* bs ht nl vt np cr so si */
0, 0, 1, 0, 0, 0, 0, 0,
/* dle dc1 dc2 dc3 dc4 nak syn etb */
0, 0, 0, 0, 0, 0, 0, 0,
/* can em sub esc fs gs rs us */
0, 0, 0, 0, 0, 0, 0, 0,
/* sp ! " # $ % & ' */
0, 1, 1, 1, 1, 0, 1, 1,
/* ( ) * + , - . / */
1, 1, 1, 0, 0, 0, 0, 0,
/* 0 1 2 3 4 5 6 7 */
0, 0, 0, 0, 0, 0, 0, 0,
/* 8 9 : ; < = > ? */
0, 0, 0, 1, 1, 0, 1, 1,
/* @ A B C D E F G */
0, 0, 0, 0, 0, 0, 0, 0,
/* H I J K L M N O */
0, 0, 0, 0, 0, 0, 0, 0,
/* P Q R S T U V W */
0, 0, 0, 0, 0, 0, 0, 0,
/* X Y Z [ \ ] ^ _ */
0, 0, 0, 1, 1, 1, 1, 0,
/* ` a b c d e f g */
1, 0, 0, 0, 0, 0, 0, 0,
/* h i j k l m n o */
0, 0, 0, 0, 0, 0, 0, 0,
/* p q r s t u v w */
0, 0, 0, 0, 0, 0, 0, 0,
/* x y z { | } ~ del */
0, 0, 0, 1, 1, 1, 1, 0,
};
#define ismeta(c) _metachar[(c) & 0x7f]
static int
needshell(const char *cmd, int white)
{
while (!ismeta(*cmd) && *cmd != ':' && *cmd != '=') {
if (white && isspace((unsigned char)*cmd))
break;
cmd++;
}