Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.119
      1  1.119  christos /*	$NetBSD: xinstall.c,v 1.119 2015/06/15 16:33:38 christos Exp $	*/
      2    1.5       jtc 
      3    1.1       cgd /*
      4    1.5       jtc  * Copyright (c) 1987, 1993
      5    1.5       jtc  *	The Regents of the University of California.  All rights reserved.
      6    1.1       cgd  *
      7    1.1       cgd  * Redistribution and use in source and binary forms, with or without
      8    1.1       cgd  * modification, are permitted provided that the following conditions
      9    1.1       cgd  * are met:
     10    1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     11    1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     12    1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     13    1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     14    1.1       cgd  *    documentation and/or other materials provided with the distribution.
     15   1.79       agc  * 3. Neither the name of the University nor the names of its contributors
     16    1.1       cgd  *    may be used to endorse or promote products derived from this software
     17    1.1       cgd  *    without specific prior written permission.
     18    1.1       cgd  *
     19    1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20    1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21    1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22    1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23    1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24    1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25    1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26    1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27    1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28    1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29    1.1       cgd  * SUCH DAMAGE.
     30    1.1       cgd  */
     31    1.1       cgd 
     32   1.80     lukem #if HAVE_NBTOOL_CONFIG_H
     33   1.80     lukem #include "nbtool_config.h"
     34   1.65        tv #else
     35   1.65        tv #define HAVE_FUTIMES 1
     36   1.65        tv #define HAVE_STRUCT_STAT_ST_FLAGS 1
     37   1.65        tv #endif
     38   1.65        tv 
     39   1.20       mrg #include <sys/cdefs.h>
     40   1.67        tv #if defined(__COPYRIGHT) && !defined(lint)
     41  1.103     lukem __COPYRIGHT("@(#) Copyright (c) 1987, 1993\
     42  1.103     lukem  The Regents of the University of California.  All rights reserved.");
     43    1.1       cgd #endif /* not lint */
     44    1.1       cgd 
     45   1.67        tv #if defined(__RCSID) && !defined(lint)
     46    1.5       jtc #if 0
     47    1.5       jtc static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
     48   1.20       mrg #else
     49  1.119  christos __RCSID("$NetBSD: xinstall.c,v 1.119 2015/06/15 16:33:38 christos Exp $");
     50    1.5       jtc #endif
     51    1.1       cgd #endif /* not lint */
     52    1.1       cgd 
     53   1.91  christos #define __MKTEMP_OK__	/* All uses of mktemp have been checked */
     54    1.1       cgd #include <sys/param.h>
     55    1.5       jtc #include <sys/mman.h>
     56    1.1       cgd #include <sys/stat.h>
     57   1.61    simonb #include <sys/wait.h>
     58  1.104  christos #include <sys/time.h>
     59    1.5       jtc 
     60    1.5       jtc #include <ctype.h>
     61   1.67        tv #include <err.h>
     62    1.5       jtc #include <errno.h>
     63    1.5       jtc #include <fcntl.h>
     64    1.1       cgd #include <grp.h>
     65   1.67        tv #include <libgen.h>
     66    1.5       jtc #include <paths.h>
     67    1.1       cgd #include <pwd.h>
     68    1.1       cgd #include <stdio.h>
     69    1.5       jtc #include <stdlib.h>
     70    1.5       jtc #include <string.h>
     71    1.5       jtc #include <unistd.h>
     72  1.101        he #include <util.h>
     73   1.50     lukem #include <vis.h>
     74    1.5       jtc 
     75  1.118    martin #ifdef HAVE_POSIX_SPAWN
     76  1.118    martin #include <spawn.h>
     77  1.118    martin #endif
     78  1.118    martin 
     79   1.84     lukem #include <md5.h>
     80  1.100  christos #include <rmd160.h>
     81   1.84     lukem #include <sha1.h>
     82  1.109       apb #include <sha2.h>
     83   1.84     lukem 
     84    1.1       cgd #include "pathnames.h"
     85   1.74     lukem #include "mtree.h"
     86    1.1       cgd 
     87   1.31   hubertf #define BACKUP_SUFFIX ".old"
     88   1.28  wsanchez 
     89  1.115     joerg static int	dobackup, dodir, dostrip, dolink, dopreserve, dorename, dounpriv;
     90  1.115     joerg static int	haveopt_f, haveopt_g, haveopt_m, haveopt_o;
     91  1.115     joerg static int	numberedbackup;
     92  1.115     joerg static int	mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
     93  1.115     joerg static char	pathbuf[MAXPATHLEN];
     94  1.115     joerg static uid_t	uid = -1;
     95  1.115     joerg static gid_t	gid = -1;
     96  1.115     joerg static char	*group, *owner, *fflags, *tags;
     97  1.115     joerg static FILE	*metafp;
     98  1.115     joerg static char	*metafile;
     99  1.115     joerg static u_long	fileflags;
    100  1.115     joerg static char	*stripArgs;
    101  1.115     joerg static char	*afterinstallcmd;
    102  1.115     joerg static const char *suffix = BACKUP_SUFFIX;
    103  1.115     joerg static char	*destdir;
    104    1.5       jtc 
    105   1.84     lukem enum {
    106   1.84     lukem 	DIGEST_NONE = 0,
    107   1.84     lukem 	DIGEST_MD5,
    108   1.84     lukem 	DIGEST_RMD160,
    109   1.84     lukem 	DIGEST_SHA1,
    110  1.109       apb 	DIGEST_SHA256,
    111  1.109       apb 	DIGEST_SHA384,
    112  1.109       apb 	DIGEST_SHA512,
    113   1.84     lukem } digesttype = DIGEST_NONE;
    114  1.115     joerg 
    115  1.115     joerg static char	*digest;
    116   1.84     lukem 
    117   1.16  christos #define LN_ABSOLUTE	0x01
    118   1.16  christos #define LN_RELATIVE	0x02
    119   1.16  christos #define LN_HARD		0x04
    120   1.16  christos #define LN_SYMBOLIC	0x08
    121   1.16  christos #define LN_MIXED	0x10
    122   1.16  christos 
    123    1.5       jtc #define	DIRECTORY	0x01		/* Tell install it's a directory. */
    124    1.5       jtc #define	SETFLAGS	0x02		/* Tell install to set flags. */
    125   1.50     lukem #define	HASUID		0x04		/* Tell install the uid was given */
    126   1.50     lukem #define	HASGID		0x08		/* Tell install the gid was given */
    127    1.5       jtc 
    128  1.115     joerg static void	afterinstall(const char *, const char *, int);
    129  1.115     joerg static void	backup(const char *);
    130  1.115     joerg static char   *copy(int, char *, int, char *, off_t);
    131  1.115     joerg static int	do_link(char *, char *);
    132  1.115     joerg static void	do_symlink(char *, char *);
    133  1.115     joerg static void	install(char *, char *, u_int);
    134  1.115     joerg static void	install_dir(char *, u_int);
    135  1.115     joerg static void	makelink(char *, char *);
    136  1.115     joerg static void	metadata_log(const char *, const char *, struct timeval *,
    137  1.106       apb 	    const char *, const char *, off_t);
    138  1.115     joerg static int	parseid(char *, id_t *);
    139  1.119  christos static void 	run(const char *, const char *, const char *, int);
    140  1.119  christos static void	strip(const char *);
    141  1.115     joerg __dead static void	usage(void);
    142  1.115     joerg static char   *xbasename(char *);
    143  1.115     joerg static char   *xdirname(char *);
    144    1.1       cgd 
    145    1.5       jtc int
    146   1.48    simonb main(int argc, char *argv[])
    147    1.1       cgd {
    148   1.53     lukem 	struct stat	from_sb, to_sb;
    149   1.53     lukem 	void		*set;
    150   1.53     lukem 	u_int		iflags;
    151   1.53     lukem 	int		ch, no_target;
    152   1.53     lukem 	char		*p, *to_name;
    153   1.43       cgd 
    154   1.43       cgd 	setprogname(argv[0]);
    155    1.1       cgd 
    156    1.5       jtc 	iflags = 0;
    157   1.84     lukem 	while ((ch = getopt(argc, argv, "a:cbB:dD:f:g:h:l:m:M:N:o:prsS:T:U"))
    158   1.75     lukem 	    != -1)
    159    1.1       cgd 		switch((char)ch) {
    160   1.69     lukem 		case 'a':
    161   1.69     lukem 			afterinstallcmd = strdup(optarg);
    162   1.69     lukem 			if (afterinstallcmd == NULL)
    163  1.119  christos 				err(EXIT_FAILURE,
    164  1.119  christos 				    "Can't allocate after command");
    165   1.69     lukem 			break;
    166   1.31   hubertf 		case 'B':
    167   1.31   hubertf 			suffix = optarg;
    168   1.35   hubertf 			numberedbackup = 0;
    169   1.35   hubertf 			{
    170   1.35   hubertf 				/* Check if given suffix really generates
    171   1.35   hubertf 				   different suffixes - catch e.g. ".%" */
    172   1.35   hubertf 				char suffix_expanded0[FILENAME_MAX],
    173   1.35   hubertf 				     suffix_expanded1[FILENAME_MAX];
    174   1.35   hubertf 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
    175   1.35   hubertf 					       suffix, 0);
    176   1.35   hubertf 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
    177   1.35   hubertf 					       suffix, 1);
    178   1.35   hubertf 				if (strcmp(suffix_expanded0, suffix_expanded1)
    179   1.35   hubertf 				    != 0)
    180   1.35   hubertf 					numberedbackup = 1;
    181   1.35   hubertf 			}
    182   1.31   hubertf 			/* fall through; -B implies -b */
    183   1.61    simonb 			/*FALLTHROUGH*/
    184   1.31   hubertf 		case 'b':
    185   1.31   hubertf 			dobackup = 1;
    186   1.31   hubertf 			break;
    187    1.1       cgd 		case 'c':
    188   1.83    simonb 			/* ignored; was "docopy" which is now the default. */
    189    1.1       cgd 			break;
    190   1.26  christos 		case 'd':
    191   1.26  christos 			dodir = 1;
    192   1.26  christos 			break;
    193   1.75     lukem 		case 'D':
    194   1.75     lukem 			destdir = optarg;
    195   1.75     lukem 			break;
    196   1.80     lukem #if ! HAVE_NBTOOL_CONFIG_H
    197    1.5       jtc 		case 'f':
    198  1.106       apb 			haveopt_f = 1;
    199   1.52        tv 			fflags = optarg;
    200    1.5       jtc 			break;
    201   1.65        tv #endif
    202    1.1       cgd 		case 'g':
    203  1.106       apb 			haveopt_g = 1;
    204    1.1       cgd 			group = optarg;
    205    1.1       cgd 			break;
    206   1.84     lukem 		case 'h':
    207   1.84     lukem 			digest = optarg;
    208   1.84     lukem 			break;
    209   1.16  christos 		case 'l':
    210   1.16  christos 			for (p = optarg; *p; p++)
    211   1.16  christos 				switch (*p) {
    212   1.16  christos 				case 's':
    213   1.16  christos 					dolink &= ~(LN_HARD|LN_MIXED);
    214   1.16  christos 					dolink |= LN_SYMBOLIC;
    215   1.16  christos 					break;
    216   1.16  christos 				case 'h':
    217   1.16  christos 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    218   1.16  christos 					dolink |= LN_HARD;
    219   1.16  christos 					break;
    220   1.16  christos 				case 'm':
    221   1.16  christos 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    222   1.16  christos 					dolink |= LN_MIXED;
    223   1.16  christos 					break;
    224   1.16  christos 				case 'a':
    225   1.16  christos 					dolink &= ~LN_RELATIVE;
    226   1.16  christos 					dolink |= LN_ABSOLUTE;
    227   1.16  christos 					break;
    228   1.16  christos 				case 'r':
    229   1.16  christos 					dolink &= ~LN_ABSOLUTE;
    230   1.16  christos 					dolink |= LN_RELATIVE;
    231   1.16  christos 					break;
    232   1.16  christos 				default:
    233  1.119  christos 					errx(EXIT_FAILURE, "%c: invalid link type", *p);
    234   1.61    simonb 					/* NOTREACHED */
    235   1.16  christos 				}
    236   1.16  christos 			break;
    237   1.26  christos 		case 'm':
    238  1.106       apb 			haveopt_m = 1;
    239   1.26  christos 			if (!(set = setmode(optarg)))
    240  1.119  christos 				err(EXIT_FAILURE, "Cannot set file mode `%s'", optarg);
    241   1.26  christos 			mode = getmode(set, 0);
    242   1.42     enami 			free(set);
    243   1.26  christos 			break;
    244   1.50     lukem 		case 'M':
    245   1.50     lukem 			metafile = optarg;
    246   1.50     lukem 			break;
    247   1.74     lukem 		case 'N':
    248   1.74     lukem 			if (! setup_getid(optarg))
    249  1.119  christos 				errx(EXIT_FAILURE,
    250   1.74     lukem 			    "Unable to use user and group databases in `%s'",
    251   1.74     lukem 				    optarg);
    252   1.74     lukem 			break;
    253   1.26  christos 		case 'o':
    254  1.106       apb 			haveopt_o = 1;
    255   1.26  christos 			owner = optarg;
    256   1.26  christos 			break;
    257   1.26  christos 		case 'p':
    258   1.26  christos 			dopreserve = 1;
    259   1.26  christos 			break;
    260   1.33  christos 		case 'r':
    261   1.33  christos 			dorename = 1;
    262   1.33  christos 			break;
    263   1.28  wsanchez 		case 'S':
    264   1.49    simonb 			stripArgs = strdup(optarg);
    265   1.49    simonb 			if (stripArgs == NULL)
    266  1.119  christos 				err(EXIT_FAILURE, "Can't allocate options");
    267   1.28  wsanchez 			/* fall through; -S implies -s */
    268   1.61    simonb 			/*FALLTHROUGH*/
    269   1.26  christos 		case 's':
    270   1.26  christos 			dostrip = 1;
    271   1.26  christos 			break;
    272   1.54     lukem 		case 'T':
    273   1.54     lukem 			tags = optarg;
    274   1.54     lukem 			break;
    275   1.38  sommerfe 		case 'U':
    276   1.50     lukem 			dounpriv = 1;
    277   1.38  sommerfe 			break;
    278    1.1       cgd 		case '?':
    279    1.1       cgd 		default:
    280    1.1       cgd 			usage();
    281    1.1       cgd 		}
    282    1.1       cgd 	argc -= optind;
    283    1.1       cgd 	argv += optind;
    284    1.2       jtc 
    285   1.23        tv 	/* strip and link options make no sense when creating directories */
    286   1.23        tv 	if ((dostrip || dolink) && dodir)
    287   1.16  christos 		usage();
    288   1.16  christos 
    289   1.16  christos 	/* strip and flags make no sense with links */
    290   1.52        tv 	if ((dostrip || fflags) && dolink)
    291    1.2       jtc 		usage();
    292    1.2       jtc 
    293    1.2       jtc 	/* must have at least two arguments, except when creating directories */
    294    1.2       jtc 	if (argc < 2 && !dodir)
    295    1.1       cgd 		usage();
    296    1.1       cgd 
    297   1.84     lukem 	if (digest) {
    298   1.84     lukem 		if (0) {
    299   1.84     lukem 		} else if (strcmp(digest, "none") == 0) {
    300   1.84     lukem 			digesttype = DIGEST_NONE;
    301   1.84     lukem 		} else if (strcmp(digest, "md5") == 0) {
    302   1.84     lukem 			digesttype = DIGEST_MD5;
    303   1.84     lukem 		} else if (strcmp(digest, "rmd160") == 0) {
    304   1.84     lukem 			digesttype = DIGEST_RMD160;
    305   1.84     lukem 		} else if (strcmp(digest, "sha1") == 0) {
    306   1.84     lukem 			digesttype = DIGEST_SHA1;
    307  1.109       apb 		} else if (strcmp(digest, "sha256") == 0) {
    308  1.109       apb 			digesttype = DIGEST_SHA256;
    309  1.109       apb 		} else if (strcmp(digest, "sha384") == 0) {
    310  1.109       apb 			digesttype = DIGEST_SHA384;
    311  1.109       apb 		} else if (strcmp(digest, "sha512") == 0) {
    312  1.109       apb 			digesttype = DIGEST_SHA512;
    313   1.84     lukem 		} else {
    314   1.84     lukem 			warnx("unknown digest `%s'", digest);
    315   1.84     lukem 			usage();
    316   1.84     lukem 		}
    317   1.84     lukem 	}
    318   1.84     lukem 
    319    1.1       cgd 	/* get group and owner id's */
    320   1.52        tv 	if (group && !dounpriv) {
    321  1.114      tron 		if (gid_from_group(group, &gid) == -1) {
    322  1.114      tron 			id_t id;
    323  1.114      tron 			if (!parseid(group, &id))
    324  1.119  christos 				errx(EXIT_FAILURE, "unknown group %s", group);
    325  1.114      tron 			gid = id;
    326  1.114      tron 		}
    327   1.50     lukem 		iflags |= HASGID;
    328   1.50     lukem 	}
    329   1.52        tv 	if (owner && !dounpriv) {
    330  1.114      tron 		if (uid_from_user(owner, &uid) == -1) {
    331  1.114      tron 			id_t id;
    332  1.114      tron 			if (!parseid(owner, &id))
    333  1.119  christos 				errx(EXIT_FAILURE, "unknown user %s", owner);
    334  1.114      tron 			uid = id;
    335  1.114      tron 		}
    336   1.50     lukem 		iflags |= HASUID;
    337   1.50     lukem 	}
    338   1.50     lukem 
    339   1.80     lukem #if ! HAVE_NBTOOL_CONFIG_H
    340   1.52        tv 	if (fflags && !dounpriv) {
    341   1.52        tv 		if (string_to_flags(&fflags, &fileflags, NULL))
    342  1.119  christos 			errx(EXIT_FAILURE, "%s: invalid flag", fflags);
    343   1.98    daniel 		/* restore fflags since string_to_flags() changed it */
    344   1.98    daniel 		fflags = flags_to_string(fileflags, "-");
    345   1.52        tv 		iflags |= SETFLAGS;
    346   1.52        tv 	}
    347   1.65        tv #endif
    348   1.52        tv 
    349   1.50     lukem 	if (metafile) {
    350   1.50     lukem 		if ((metafp = fopen(metafile, "a")) == NULL)
    351   1.50     lukem 			warn("open %s", metafile);
    352   1.84     lukem 	} else
    353   1.84     lukem 		digesttype = DIGEST_NONE;
    354    1.1       cgd 
    355    1.2       jtc 	if (dodir) {
    356    1.2       jtc 		for (; *argv != NULL; ++argv)
    357   1.50     lukem 			install_dir(*argv, iflags);
    358    1.2       jtc 		exit (0);
    359    1.5       jtc 	}
    360    1.2       jtc 
    361    1.1       cgd 	no_target = stat(to_name = argv[argc - 1], &to_sb);
    362    1.2       jtc 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
    363    1.1       cgd 		for (; *argv != to_name; ++argv)
    364   1.50     lukem 			install(*argv, to_name, iflags | DIRECTORY);
    365    1.1       cgd 		exit(0);
    366    1.1       cgd 	}
    367    1.1       cgd 
    368    1.1       cgd 	/* can't do file1 file2 directory/file */
    369   1.99    rillig 	if (argc != 2) {
    370   1.99    rillig 		errx(EXIT_FAILURE, "the last argument (%s) "
    371   1.99    rillig 		    "must name an existing directory", argv[argc - 1]);
    372   1.99    rillig 		/* NOTREACHED */
    373   1.99    rillig 	}
    374    1.1       cgd 
    375    1.1       cgd 	if (!no_target) {
    376   1.61    simonb 		/* makelink() handles checks for links */
    377   1.61    simonb 		if (!dolink) {
    378   1.61    simonb 			if (stat(*argv, &from_sb))
    379  1.119  christos 				err(EXIT_FAILURE, "%s: stat", *argv);
    380   1.61    simonb 			if (!S_ISREG(to_sb.st_mode))
    381  1.119  christos 				errx(EXIT_FAILURE, "%s: not a regular file", to_name);
    382   1.61    simonb 			if (to_sb.st_dev == from_sb.st_dev &&
    383   1.61    simonb 			    to_sb.st_ino == from_sb.st_ino)
    384  1.119  christos 				errx(EXIT_FAILURE, "%s and %s are the same file", *argv,
    385   1.61    simonb 				    to_name);
    386   1.61    simonb 		}
    387    1.5       jtc 		/*
    388    1.5       jtc 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    389    1.5       jtc 		 * off the append/immutable bits -- if we fail, go ahead,
    390    1.5       jtc 		 * it might work.
    391    1.5       jtc 		 */
    392   1.80     lukem #if ! HAVE_NBTOOL_CONFIG_H
    393    1.5       jtc #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
    394    1.5       jtc 		if (to_sb.st_flags & NOCHANGEBITS)
    395    1.5       jtc 			(void)chflags(to_name,
    396    1.5       jtc 			    to_sb.st_flags & ~(NOCHANGEBITS));
    397   1.65        tv #endif
    398   1.32   hubertf 		if (dobackup)
    399   1.32   hubertf 			backup(to_name);
    400   1.34  christos 		else if (!dorename)
    401   1.31   hubertf 			(void)unlink(to_name);
    402    1.1       cgd 	}
    403   1.50     lukem 	install(*argv, to_name, iflags);
    404    1.1       cgd 	exit(0);
    405    1.1       cgd }
    406    1.1       cgd 
    407    1.1       cgd /*
    408   1.50     lukem  * parseid --
    409   1.50     lukem  *	parse uid or gid from arg into id, returning non-zero if successful
    410   1.50     lukem  */
    411  1.115     joerg static int
    412   1.50     lukem parseid(char *name, id_t *id)
    413   1.50     lukem {
    414   1.50     lukem 	char	*ep;
    415   1.50     lukem 
    416   1.50     lukem 	errno = 0;
    417   1.50     lukem 	*id = (id_t)strtoul(name, &ep, 10);
    418   1.50     lukem 	if (errno || *ep != '\0')
    419   1.50     lukem 		return (0);
    420   1.50     lukem 	return (1);
    421   1.50     lukem }
    422   1.50     lukem 
    423   1.50     lukem /*
    424   1.61    simonb  * do_link --
    425   1.61    simonb  *	make a hard link, obeying dorename if set
    426   1.61    simonb  *	return -1 on failure
    427   1.61    simonb  */
    428  1.115     joerg static int
    429   1.61    simonb do_link(char *from_name, char *to_name)
    430   1.61    simonb {
    431   1.61    simonb 	char tmpl[MAXPATHLEN];
    432   1.61    simonb 	int ret;
    433   1.61    simonb 
    434   1.61    simonb 	if (dorename) {
    435  1.112      gson 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
    436   1.91  christos 		/* This usage is safe. */
    437   1.61    simonb 		if (mktemp(tmpl) == NULL)
    438  1.119  christos 			err(EXIT_FAILURE, "%s: mktemp", tmpl);
    439   1.61    simonb 		ret = link(from_name, tmpl);
    440   1.61    simonb 		if (ret == 0) {
    441   1.61    simonb 			ret = rename(tmpl, to_name);
    442   1.96       dbj 			/* If rename has posix semantics, then the temporary
    443   1.96       dbj 			 * file may still exist when from_name and to_name point
    444  1.102     joerg 			 * to the same file, so unlink it unconditionally.
    445   1.96       dbj 			 */
    446   1.96       dbj 			(void)unlink(tmpl);
    447   1.61    simonb 		}
    448   1.61    simonb 		return (ret);
    449   1.61    simonb 	} else
    450   1.61    simonb 		return (link(from_name, to_name));
    451   1.61    simonb }
    452   1.61    simonb 
    453   1.61    simonb /*
    454   1.61    simonb  * do_symlink --
    455   1.61    simonb  *	make a symbolic link, obeying dorename if set
    456   1.61    simonb  *	exit on failure
    457   1.61    simonb  */
    458  1.115     joerg static void
    459   1.61    simonb do_symlink(char *from_name, char *to_name)
    460   1.61    simonb {
    461   1.61    simonb 	char tmpl[MAXPATHLEN];
    462   1.61    simonb 
    463   1.61    simonb 	if (dorename) {
    464  1.112      gson 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
    465   1.91  christos 		/* This usage is safe. */
    466   1.61    simonb 		if (mktemp(tmpl) == NULL)
    467  1.119  christos 			err(EXIT_FAILURE, "%s: mktemp", tmpl);
    468   1.61    simonb 
    469   1.61    simonb 		if (symlink(from_name, tmpl) == -1)
    470  1.119  christos 			err(EXIT_FAILURE, "symlink %s -> %s", from_name, tmpl);
    471   1.61    simonb 		if (rename(tmpl, to_name) == -1) {
    472   1.61    simonb 			/* remove temporary link before exiting */
    473   1.61    simonb 			(void)unlink(tmpl);
    474  1.119  christos 			err(EXIT_FAILURE, "%s: rename", to_name);
    475   1.61    simonb 		}
    476   1.61    simonb 	} else {
    477   1.61    simonb 		if (symlink(from_name, to_name) == -1)
    478  1.119  christos 			err(EXIT_FAILURE, "symlink %s -> %s", from_name, to_name);
    479   1.61    simonb 	}
    480   1.61    simonb }
    481   1.61    simonb 
    482   1.61    simonb /*
    483   1.16  christos  * makelink --
    484   1.16  christos  *	make a link from source to destination
    485   1.16  christos  */
    486  1.115     joerg static void
    487   1.48    simonb makelink(char *from_name, char *to_name)
    488   1.16  christos {
    489   1.53     lukem 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
    490   1.68     lukem 	struct stat	to_sb;
    491   1.16  christos 
    492   1.16  christos 	/* Try hard links first */
    493   1.16  christos 	if (dolink & (LN_HARD|LN_MIXED)) {
    494   1.61    simonb 		if (do_link(from_name, to_name) == -1) {
    495   1.16  christos 			if ((dolink & LN_HARD) || errno != EXDEV)
    496  1.119  christos 				err(EXIT_FAILURE, "link %s -> %s", from_name, to_name);
    497   1.68     lukem 		} else {
    498   1.68     lukem 			if (stat(to_name, &to_sb))
    499  1.119  christos 				err(EXIT_FAILURE, "%s: stat", to_name);
    500   1.69     lukem 			if (S_ISREG(to_sb.st_mode)) {
    501  1.106       apb 					/* XXX: hard links to anything
    502  1.106       apb 					 * other than plain files are not
    503  1.106       apb 					 * metalogged
    504  1.106       apb 					 */
    505   1.69     lukem 				int omode;
    506   1.69     lukem 				char *oowner, *ogroup, *offlags;
    507   1.85     lukem 				char *dres;
    508   1.69     lukem 
    509  1.106       apb 					/* XXX: use underlying perms,
    510  1.106       apb 					 * unless overridden on command line.
    511  1.106       apb 					 */
    512   1.69     lukem 				omode = mode;
    513  1.106       apb 				if (!haveopt_m)
    514  1.106       apb 					mode = (to_sb.st_mode & 0777);
    515   1.69     lukem 				oowner = owner;
    516  1.106       apb 				if (!haveopt_o)
    517  1.106       apb 					owner = NULL;
    518   1.69     lukem 				ogroup = group;
    519  1.106       apb 				if (!haveopt_g)
    520  1.106       apb 					group = NULL;
    521   1.69     lukem 				offlags = fflags;
    522  1.106       apb 				if (!haveopt_f)
    523  1.106       apb 					fflags = NULL;
    524   1.85     lukem 				switch (digesttype) {
    525   1.85     lukem 				case DIGEST_MD5:
    526   1.85     lukem 					dres = MD5File(from_name, NULL);
    527   1.85     lukem 					break;
    528   1.85     lukem 				case DIGEST_RMD160:
    529   1.85     lukem 					dres = RMD160File(from_name, NULL);
    530   1.85     lukem 					break;
    531   1.85     lukem 				case DIGEST_SHA1:
    532   1.85     lukem 					dres = SHA1File(from_name, NULL);
    533   1.85     lukem 					break;
    534  1.109       apb 				case DIGEST_SHA256:
    535  1.109       apb 					dres = SHA256_File(from_name, NULL);
    536  1.109       apb 					break;
    537  1.109       apb 				case DIGEST_SHA384:
    538  1.109       apb 					dres = SHA384_File(from_name, NULL);
    539  1.109       apb 					break;
    540  1.109       apb 				case DIGEST_SHA512:
    541  1.109       apb 					dres = SHA512_File(from_name, NULL);
    542  1.109       apb 					break;
    543   1.85     lukem 				default:
    544   1.85     lukem 					dres = NULL;
    545   1.85     lukem 				}
    546  1.106       apb 				metadata_log(to_name, "file", NULL, NULL,
    547  1.106       apb 				    dres, to_sb.st_size);
    548   1.85     lukem 				free(dres);
    549   1.69     lukem 				mode = omode;
    550   1.69     lukem 				owner = oowner;
    551   1.69     lukem 				group = ogroup;
    552   1.69     lukem 				fflags = offlags;
    553   1.69     lukem 			}
    554   1.16  christos 			return;
    555   1.57     lukem 		}
    556   1.16  christos 	}
    557   1.16  christos 
    558   1.16  christos 	/* Symbolic links */
    559   1.16  christos 	if (dolink & LN_ABSOLUTE) {
    560   1.16  christos 		/* Convert source path to absolute */
    561   1.16  christos 		if (realpath(from_name, src) == NULL)
    562  1.119  christos 			err(EXIT_FAILURE, "%s: realpath", from_name);
    563   1.61    simonb 		do_symlink(src, to_name);
    564   1.90     lukem 			/* XXX: src may point outside of destdir */
    565  1.106       apb 		metadata_log(to_name, "link", NULL, src, NULL, 0);
    566   1.16  christos 		return;
    567   1.16  christos 	}
    568   1.16  christos 
    569   1.16  christos 	if (dolink & LN_RELATIVE) {
    570   1.61    simonb 		char *cp, *d, *s;
    571   1.16  christos 
    572   1.16  christos 		/* Resolve pathnames */
    573   1.16  christos 		if (realpath(from_name, src) == NULL)
    574  1.119  christos 			err(EXIT_FAILURE, "%s: realpath", from_name);
    575   1.61    simonb 
    576   1.61    simonb 		/*
    577   1.61    simonb 		 * The last component of to_name may be a symlink,
    578   1.61    simonb 		 * so use realpath to resolve only the directory.
    579   1.61    simonb 		 */
    580   1.63     perry 		cp = xdirname(to_name);
    581   1.61    simonb 		if (realpath(cp, dst) == NULL)
    582  1.119  christos 			err(EXIT_FAILURE, "%s: realpath", cp);
    583   1.61    simonb 		/* .. and add the last component */
    584   1.61    simonb 		if (strcmp(dst, "/") != 0) {
    585   1.61    simonb 			if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
    586  1.119  christos 				errx(EXIT_FAILURE, "resolved pathname too long");
    587   1.61    simonb 		}
    588   1.61    simonb 		cp = xbasename(to_name);
    589   1.61    simonb 		if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
    590  1.119  christos 			errx(EXIT_FAILURE, "resolved pathname too long");
    591   1.16  christos 
    592   1.16  christos 		/* trim common path components */
    593   1.16  christos 		for (s = src, d = dst; *s == *d; s++, d++)
    594   1.16  christos 			continue;
    595   1.16  christos 		while (*s != '/')
    596   1.16  christos 			s--, d--;
    597   1.16  christos 
    598   1.16  christos 		/* count the number of directories we need to backtrack */
    599   1.16  christos 		for (++d, lnk[0] = '\0'; *d; d++)
    600   1.16  christos 			if (*d == '/')
    601   1.78    itojun 				(void)strlcat(lnk, "../", sizeof(lnk));
    602   1.16  christos 
    603   1.78    itojun 		(void)strlcat(lnk, ++s, sizeof(lnk));
    604   1.16  christos 
    605   1.90     lukem 		do_symlink(lnk, to_name);
    606   1.90     lukem 			/* XXX: lnk may point outside of destdir */
    607  1.106       apb 		metadata_log(to_name, "link", NULL, lnk, NULL, 0);
    608   1.16  christos 		return;
    609   1.16  christos 	}
    610   1.16  christos 
    611   1.16  christos 	/*
    612   1.16  christos 	 * If absolute or relative was not specified,
    613   1.16  christos 	 * try the names the user provided
    614   1.16  christos 	 */
    615   1.61    simonb 	do_symlink(from_name, to_name);
    616   1.90     lukem 		/* XXX: from_name may point outside of destdir */
    617  1.106       apb 	metadata_log(to_name, "link", NULL, from_name, NULL, 0);
    618   1.16  christos }
    619   1.16  christos 
    620   1.16  christos /*
    621    1.1       cgd  * install --
    622    1.1       cgd  *	build a path name and install the file
    623    1.1       cgd  */
    624  1.115     joerg static void
    625   1.50     lukem install(char *from_name, char *to_name, u_int flags)
    626    1.1       cgd {
    627   1.65        tv 	struct stat	from_sb;
    628   1.65        tv 	struct stat	to_sb;
    629   1.53     lukem 	struct timeval	tv[2];
    630  1.108       apb 	off_t		size;
    631   1.60     dillo 	int		devnull, from_fd, to_fd, serrno, tmpmode;
    632   1.84     lukem 	char		*p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
    633    1.5       jtc 
    634  1.108       apb 	size = -1;
    635   1.71     lukem 	if (!dolink) {
    636   1.71     lukem 			/* ensure that from_sb & tv are sane if !dolink */
    637   1.71     lukem 		if (stat(from_name, &from_sb))
    638  1.119  christos 			err(EXIT_FAILURE, "%s: stat", from_name);
    639  1.108       apb 		size = from_sb.st_size;
    640   1.87       jmc #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
    641   1.71     lukem 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    642   1.71     lukem 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    643   1.70     lukem #else
    644   1.71     lukem 		tv[0].tv_sec = from_sb.st_atime;
    645   1.71     lukem 		tv[0].tv_usec = 0;
    646   1.71     lukem 		tv[1].tv_sec = from_sb.st_mtime;
    647   1.71     lukem 		tv[1].tv_usec = 0;
    648   1.70     lukem #endif
    649   1.71     lukem 	}
    650   1.70     lukem 
    651  1.108       apb 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL) != 0) {
    652  1.108       apb 		devnull = 0;
    653   1.56     perry 		if (!dolink) {
    654   1.56     perry 			if (!S_ISREG(from_sb.st_mode))
    655  1.119  christos 				errx(EXIT_FAILURE, "%s: not a regular file", from_name);
    656   1.56     perry 		}
    657    1.5       jtc 		/* Build the target path. */
    658    1.5       jtc 		if (flags & DIRECTORY) {
    659    1.5       jtc 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    660    1.5       jtc 			    to_name,
    661   1.21     lukem 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    662    1.1       cgd 			to_name = pathbuf;
    663    1.1       cgd 		}
    664    1.5       jtc 	} else {
    665  1.108       apb 		devnull = 1;
    666  1.108       apb 		size = 0;
    667   1.65        tv #if HAVE_STRUCT_STAT_ST_FLAGS
    668    1.5       jtc 		from_sb.st_flags = 0;	/* XXX */
    669   1.65        tv #endif
    670    1.5       jtc 	}
    671    1.1       cgd 
    672    1.5       jtc 	/*
    673    1.5       jtc 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    674    1.5       jtc 	 * off the append/immutable bits -- if we fail, go ahead,
    675    1.5       jtc 	 * it might work.
    676    1.5       jtc 	 */
    677   1.80     lukem #if ! HAVE_NBTOOL_CONFIG_H
    678    1.5       jtc 	if (stat(to_name, &to_sb) == 0 &&
    679    1.5       jtc 	    to_sb.st_flags & (NOCHANGEBITS))
    680    1.5       jtc 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    681   1.65        tv #endif
    682   1.33  christos 	if (dorename) {
    683  1.112      gson 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
    684   1.33  christos 		oto_name = to_name;
    685   1.33  christos 		to_name = tmpl;
    686   1.33  christos 	} else {
    687   1.37  christos 		oto_name = NULL;	/* pacify gcc */
    688   1.33  christos 		if (dobackup)
    689   1.33  christos 			backup(to_name);
    690   1.33  christos 		else
    691   1.33  christos 			(void)unlink(to_name);
    692   1.33  christos 	}
    693   1.16  christos 
    694   1.16  christos 	if (dolink) {
    695   1.61    simonb 		makelink(from_name, dorename ? oto_name : to_name);
    696   1.16  christos 		return;
    697   1.16  christos 	}
    698    1.1       cgd 
    699    1.5       jtc 	/* Create target. */
    700   1.33  christos 	if (dorename) {
    701   1.33  christos 		if ((to_fd = mkstemp(to_name)) == -1)
    702  1.119  christos 			err(EXIT_FAILURE, "%s: mkstemp", to_name);
    703   1.33  christos 	} else {
    704   1.33  christos 		if ((to_fd = open(to_name,
    705   1.33  christos 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    706  1.119  christos 			err(EXIT_FAILURE, "%s: open", to_name);
    707   1.33  christos 	}
    708   1.86     lukem 	digestresult = NULL;
    709    1.1       cgd 	if (!devnull) {
    710    1.1       cgd 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    711    1.1       cgd 			(void)unlink(to_name);
    712  1.119  christos 			err(EXIT_FAILURE, "%s: open", from_name);
    713    1.1       cgd 		}
    714   1.84     lukem 		digestresult =
    715   1.84     lukem 		    copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    716    1.1       cgd 		(void)close(from_fd);
    717    1.1       cgd 	}
    718    1.9  jonathan 
    719    1.9  jonathan 	if (dostrip) {
    720    1.1       cgd 		strip(to_name);
    721    1.9  jonathan 
    722    1.9  jonathan 		/*
    723    1.9  jonathan 		 * Re-open our fd on the target, in case we used a strip
    724    1.9  jonathan 		 *  that does not work in-place -- like gnu binutils strip.
    725    1.9  jonathan 		 */
    726    1.9  jonathan 		close(to_fd);
    727    1.9  jonathan 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    728  1.119  christos 			err(EXIT_FAILURE, "stripping %s", to_name);
    729  1.108       apb 
    730  1.108       apb 		/*
    731  1.108       apb 		 * Recalculate size and digestresult after stripping.
    732  1.108       apb 		 */
    733  1.108       apb 		if (fstat(to_fd, &to_sb) != 0)
    734  1.119  christos 			err(EXIT_FAILURE, "%s: fstat", to_name);
    735  1.108       apb 		size = to_sb.st_size;
    736  1.108       apb 		digestresult =
    737  1.108       apb 		    copy(to_fd, to_name, -1, NULL, size);
    738  1.108       apb 
    739   1.69     lukem 	}
    740   1.69     lukem 
    741   1.69     lukem 	if (afterinstallcmd != NULL) {
    742   1.69     lukem 		afterinstall(afterinstallcmd, to_name, 1);
    743   1.69     lukem 
    744   1.69     lukem 		/*
    745   1.69     lukem 		 * Re-open our fd on the target, in case we used an
    746   1.69     lukem 		 * after-install command that does not work in-place
    747   1.69     lukem 		 */
    748   1.69     lukem 		close(to_fd);
    749   1.69     lukem 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    750  1.119  christos 			err(EXIT_FAILURE, "running after install command on %s", to_name);
    751    1.9  jonathan 	}
    752    1.9  jonathan 
    753   1.41       cgd 	/*
    754   1.41       cgd 	 * Set owner, group, mode for target; do the chown first,
    755   1.41       cgd 	 * chown may lose the setuid bits.
    756   1.41       cgd 	 */
    757   1.50     lukem 	if (!dounpriv &&
    758   1.50     lukem 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    759   1.41       cgd 		serrno = errno;
    760   1.41       cgd 		(void)unlink(to_name);
    761  1.119  christos 		errc(EXIT_FAILURE, serrno, "%s: chown/chgrp", to_name);
    762    1.1       cgd 	}
    763   1.60     dillo 	tmpmode = mode;
    764   1.58        tv 	if (dounpriv)
    765   1.60     dillo 		tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
    766   1.60     dillo 	if (fchmod(to_fd, tmpmode) == -1) {
    767    1.5       jtc 		serrno = errno;
    768    1.5       jtc 		(void)unlink(to_name);
    769  1.119  christos 		errc(EXIT_FAILURE, serrno, "%s: chmod", to_name);
    770    1.5       jtc 	}
    771    1.5       jtc 
    772    1.5       jtc 	/*
    773   1.26  christos 	 * Preserve the date of the source file.
    774   1.26  christos 	 */
    775   1.26  christos 	if (dopreserve) {
    776   1.65        tv #if HAVE_FUTIMES
    777   1.65        tv 		if (futimes(to_fd, tv) == -1)
    778   1.65        tv 			warn("%s: futimes", to_name);
    779   1.65        tv #else
    780   1.65        tv 		if (utimes(to_name, tv) == -1)
    781   1.66        tv 			warn("%s: utimes", to_name);
    782   1.65        tv #endif
    783    1.5       jtc 	}
    784    1.5       jtc 
    785    1.1       cgd 	(void)close(to_fd);
    786   1.33  christos 
    787   1.50     lukem 	if (dorename) {
    788   1.33  christos 		if (rename(to_name, oto_name) == -1)
    789  1.119  christos 			err(EXIT_FAILURE, "%s: rename", to_name);
    790   1.50     lukem 		to_name = oto_name;
    791   1.50     lukem 	}
    792   1.33  christos 
    793   1.50     lukem 	/*
    794   1.50     lukem 	 * If provided a set of flags, set them, otherwise, preserve the
    795   1.50     lukem 	 * flags, except for the dump flag.
    796   1.50     lukem 	 */
    797   1.80     lukem #if ! HAVE_NBTOOL_CONFIG_H
    798   1.50     lukem 	if (!dounpriv && chflags(to_name,
    799   1.51     lukem 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    800   1.51     lukem 	{
    801   1.50     lukem 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    802   1.50     lukem 			warn("%s: chflags", to_name);
    803   1.50     lukem 	}
    804   1.65        tv #endif
    805   1.50     lukem 
    806  1.108       apb 	metadata_log(to_name, "file", tv, NULL, digestresult, size);
    807   1.84     lukem 	free(digestresult);
    808    1.1       cgd }
    809    1.1       cgd 
    810    1.1       cgd /*
    811    1.1       cgd  * copy --
    812  1.108       apb  *	copy from one file to another, returning a digest.
    813  1.108       apb  *
    814  1.108       apb  *	If to_fd < 0, just calculate a digest, don't copy.
    815    1.1       cgd  */
    816  1.115     joerg static char *
    817   1.48    simonb copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    818    1.1       cgd {
    819   1.53     lukem 	ssize_t	nr, nw;
    820   1.53     lukem 	int	serrno;
    821   1.95       mrg 	u_char	*p;
    822   1.95       mrg 	u_char	buf[MAXBSIZE];
    823   1.84     lukem 	MD5_CTX		ctxMD5;
    824   1.84     lukem 	RMD160_CTX	ctxRMD160;
    825   1.84     lukem 	SHA1_CTX	ctxSHA1;
    826  1.109       apb 	SHA256_CTX	ctxSHA256;
    827  1.109       apb 	SHA384_CTX	ctxSHA384;
    828  1.109       apb 	SHA512_CTX	ctxSHA512;
    829   1.84     lukem 
    830   1.84     lukem 	switch (digesttype) {
    831   1.84     lukem 	case DIGEST_MD5:
    832   1.84     lukem 		MD5Init(&ctxMD5);
    833   1.84     lukem 		break;
    834   1.84     lukem 	case DIGEST_RMD160:
    835   1.84     lukem 		RMD160Init(&ctxRMD160);
    836   1.84     lukem 		break;
    837   1.84     lukem 	case DIGEST_SHA1:
    838   1.84     lukem 		SHA1Init(&ctxSHA1);
    839   1.84     lukem 		break;
    840  1.109       apb 	case DIGEST_SHA256:
    841  1.109       apb 		SHA256_Init(&ctxSHA256);
    842  1.109       apb 		break;
    843  1.109       apb 	case DIGEST_SHA384:
    844  1.109       apb 		SHA384_Init(&ctxSHA384);
    845  1.109       apb 		break;
    846  1.109       apb 	case DIGEST_SHA512:
    847  1.109       apb 		SHA512_Init(&ctxSHA512);
    848  1.109       apb 		break;
    849   1.84     lukem 	case DIGEST_NONE:
    850  1.108       apb 		if (to_fd < 0)
    851  1.108       apb 			return NULL; /* no need to do anything */
    852   1.84     lukem 	default:
    853   1.84     lukem 		break;
    854   1.84     lukem 	}
    855    1.5       jtc 	/*
    856   1.28  wsanchez 	 * There's no reason to do anything other than close the file
    857   1.28  wsanchez 	 * now if it's empty, so let's not bother.
    858    1.5       jtc 	 */
    859   1.28  wsanchez 	if (size > 0) {
    860   1.45       chs 
    861   1.28  wsanchez 		/*
    862   1.45       chs 		 * Mmap and write if less than 8M (the limit is so we
    863   1.45       chs 		 * don't totally trash memory on big files).  This is
    864   1.45       chs 		 * really a minor hack, but it wins some CPU back.
    865   1.28  wsanchez 		 */
    866   1.45       chs 
    867   1.28  wsanchez 		if (size <= 8 * 1048576) {
    868   1.28  wsanchez 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    869   1.45       chs 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    870   1.45       chs 			    == MAP_FAILED) {
    871   1.45       chs 				goto mmap_failed;
    872   1.36   thorpej 			}
    873   1.77   thorpej #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
    874   1.39  christos 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    875   1.39  christos 			    && errno != EOPNOTSUPP)
    876  1.119  christos 				warn("madvise");
    877   1.44       cgd #endif
    878   1.38  sommerfe 
    879  1.108       apb 			if (to_fd >= 0 && write(to_fd, p, size) != size) {
    880   1.36   thorpej 				serrno = errno;
    881   1.36   thorpej 				(void)unlink(to_name);
    882  1.119  christos 				errc(EXIT_FAILURE, serrno, "%s: write",
    883  1.119  christos 				    to_name);
    884   1.36   thorpej 			}
    885   1.84     lukem 			switch (digesttype) {
    886   1.84     lukem 			case DIGEST_MD5:
    887   1.84     lukem 				MD5Update(&ctxMD5, p, size);
    888   1.84     lukem 				break;
    889   1.84     lukem 			case DIGEST_RMD160:
    890   1.84     lukem 				RMD160Update(&ctxRMD160, p, size);
    891   1.84     lukem 				break;
    892   1.84     lukem 			case DIGEST_SHA1:
    893   1.84     lukem 				SHA1Update(&ctxSHA1, p, size);
    894   1.84     lukem 				break;
    895  1.109       apb 			case DIGEST_SHA256:
    896  1.109       apb 				SHA256_Update(&ctxSHA256, p, size);
    897  1.109       apb 				break;
    898  1.109       apb 			case DIGEST_SHA384:
    899  1.109       apb 				SHA384_Update(&ctxSHA384, p, size);
    900  1.109       apb 				break;
    901  1.109       apb 			case DIGEST_SHA512:
    902  1.109       apb 				SHA512_Update(&ctxSHA512, p, size);
    903  1.109       apb 				break;
    904   1.84     lukem 			default:
    905   1.84     lukem 				break;
    906   1.84     lukem 			}
    907   1.81  christos 			(void)munmap(p, size);
    908   1.28  wsanchez 		} else {
    909   1.84     lukem  mmap_failed:
    910   1.36   thorpej 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    911  1.108       apb 				if (to_fd >= 0 &&
    912  1.108       apb 				    (nw = write(to_fd, buf, nr)) != nr) {
    913   1.28  wsanchez 					serrno = errno;
    914   1.28  wsanchez 					(void)unlink(to_name);
    915  1.119  christos 					errc(EXIT_FAILURE,
    916  1.119  christos 					    nw > 0 ? EIO : serrno,
    917  1.119  christos 					    "%s: write", to_name);
    918   1.28  wsanchez 				}
    919   1.84     lukem 				switch (digesttype) {
    920   1.84     lukem 				case DIGEST_MD5:
    921   1.84     lukem 					MD5Update(&ctxMD5, buf, nr);
    922   1.84     lukem 					break;
    923   1.84     lukem 				case DIGEST_RMD160:
    924   1.84     lukem 					RMD160Update(&ctxRMD160, buf, nr);
    925   1.84     lukem 					break;
    926   1.84     lukem 				case DIGEST_SHA1:
    927   1.84     lukem 					SHA1Update(&ctxSHA1, buf, nr);
    928   1.84     lukem 					break;
    929  1.109       apb 				case DIGEST_SHA256:
    930  1.109       apb 					SHA256_Update(&ctxSHA256, buf, nr);
    931  1.109       apb 					break;
    932  1.109       apb 				case DIGEST_SHA384:
    933  1.109       apb 					SHA384_Update(&ctxSHA384, buf, nr);
    934  1.109       apb 					break;
    935  1.109       apb 				case DIGEST_SHA512:
    936  1.109       apb 					SHA512_Update(&ctxSHA512, buf, nr);
    937  1.109       apb 					break;
    938   1.84     lukem 				default:
    939   1.84     lukem 					break;
    940   1.84     lukem 				}
    941   1.36   thorpej 			}
    942   1.28  wsanchez 			if (nr != 0) {
    943    1.5       jtc 				serrno = errno;
    944    1.5       jtc 				(void)unlink(to_name);
    945  1.119  christos 				errc(EXIT_FAILURE, serrno, "%s: read",
    946  1.119  christos 				    from_name);
    947    1.5       jtc 			}
    948    1.1       cgd 		}
    949    1.1       cgd 	}
    950   1.84     lukem 	switch (digesttype) {
    951   1.84     lukem 	case DIGEST_MD5:
    952   1.84     lukem 		return MD5End(&ctxMD5, NULL);
    953   1.84     lukem 	case DIGEST_RMD160:
    954   1.84     lukem 		return RMD160End(&ctxRMD160, NULL);
    955   1.84     lukem 	case DIGEST_SHA1:
    956   1.84     lukem 		return SHA1End(&ctxSHA1, NULL);
    957  1.109       apb 	case DIGEST_SHA256:
    958  1.109       apb 		return SHA256_End(&ctxSHA256, NULL);
    959  1.109       apb 	case DIGEST_SHA384:
    960  1.109       apb 		return SHA384_End(&ctxSHA384, NULL);
    961  1.109       apb 	case DIGEST_SHA512:
    962  1.109       apb 		return SHA512_End(&ctxSHA512, NULL);
    963   1.84     lukem 	default:
    964   1.84     lukem 		return NULL;
    965   1.84     lukem 	}
    966    1.1       cgd }
    967    1.1       cgd 
    968  1.115     joerg static void
    969  1.119  christos run(const char *command, const char *flags, const char *to_name, int errunlink)
    970    1.1       cgd {
    971  1.119  christos 	char	*args[4];
    972  1.118    martin 	int	status;
    973  1.118    martin 	int	rv;
    974  1.119  christos 	size_t	i;
    975  1.102     joerg 
    976  1.119  christos 	i = 1;
    977  1.119  christos 	status = 0;
    978  1.102     joerg 
    979  1.119  christos 	args[0] = __UNCONST(command);
    980  1.119  christos 	if (flags)
    981  1.119  christos 		args[i++] = __UNCONST(flags);
    982  1.119  christos 	args[i++] = __UNCONST(to_name);
    983  1.119  christos 	args[i] = NULL;
    984    1.1       cgd 
    985  1.118    martin #ifdef HAVE_POSIX_SPAWN
    986  1.119  christos 	if (*command == '/')
    987  1.119  christos 		rv = posix_spawn(NULL, command, NULL, NULL, args, NULL);
    988  1.119  christos 	else
    989  1.119  christos 		rv = posix_spawnp(NULL, command, NULL, NULL, args, NULL);
    990  1.119  christos 	if (rv != 0) {
    991  1.119  christos 		warnc(rv, "Cannot execute %s", command);
    992  1.119  christos 		rv = -1;
    993  1.118    martin 	}
    994  1.118    martin #else
    995    1.1       cgd 	switch (vfork()) {
    996    1.1       cgd 	case -1:
    997  1.119  christos 		rv = errno;
    998  1.119  christos 		if (errunlink)
    999  1.119  christos 			(void)unlink(to_name);
   1000  1.119  christos 		errc(EXIT_FAILURE, rv, "vfork");
   1001   1.61    simonb 		/*NOTREACHED*/
   1002    1.1       cgd 	case 0:
   1003  1.119  christos 		if (*command == '/')
   1004  1.119  christos 			execv(command, args);
   1005  1.102     joerg 		else
   1006  1.119  christos 			execvp(command, args);
   1007  1.119  christos 		rv = errno;
   1008  1.119  christos 		const char *arr[] = {
   1009  1.119  christos 			getprogname(),
   1010  1.119  christos 			": exec failed for ",
   1011  1.119  christos 			command,
   1012  1.119  christos 			" (",
   1013  1.119  christos 			strerror(rv),
   1014  1.119  christos 			")\n",
   1015  1.119  christos 		};
   1016  1.119  christos 		for (i = 0; i < __arraycount(arr); i++)
   1017  1.119  christos 			write(STDERR_FILENO, arr[i], strlen(arr[i]));
   1018   1.22   thorpej 		_exit(1);
   1019   1.61    simonb 		/*NOTREACHED*/
   1020    1.1       cgd 	default:
   1021  1.119  christos 		rv = wait(&status);
   1022  1.119  christos 		break;
   1023    1.1       cgd 	}
   1024  1.118    martin #endif
   1025  1.119  christos 	if ((rv == -1 || status) && errunlink)
   1026  1.119  christos 		(void)unlink(to_name);
   1027  1.119  christos }
   1028  1.102     joerg 
   1029  1.119  christos /*
   1030  1.119  christos  * strip --
   1031  1.119  christos  *	use strip(1) to strip the target file
   1032  1.119  christos  */
   1033  1.119  christos static void
   1034  1.119  christos strip(const char *to_name)
   1035  1.119  christos {
   1036  1.119  christos 	const char *stripprog;
   1037  1.119  christos 
   1038  1.119  christos 	if ((stripprog = getenv("STRIP")) == NULL || *stripprog == '\0') {
   1039  1.119  christos #ifdef TARGET_STRIP
   1040  1.119  christos 		stripprog = TARGET_STRIP;
   1041  1.119  christos #else
   1042  1.119  christos 		stripprog = _PATH_STRIP;
   1043  1.119  christos #endif
   1044  1.119  christos 	}
   1045  1.119  christos 	run(stripprog, stripArgs, to_name, 0);
   1046   1.32   hubertf }
   1047   1.32   hubertf 
   1048   1.32   hubertf /*
   1049   1.69     lukem  * afterinstall --
   1050   1.69     lukem  *	run provided command on the target file or directory after it's been
   1051   1.69     lukem  *	installed and stripped, but before permissions are set or it's renamed
   1052   1.69     lukem  */
   1053  1.115     joerg static void
   1054   1.69     lukem afterinstall(const char *command, const char *to_name, int errunlink)
   1055   1.69     lukem {
   1056  1.119  christos 	run(command, NULL, to_name, errunlink);
   1057   1.69     lukem }
   1058   1.69     lukem 
   1059   1.69     lukem /*
   1060   1.61    simonb  * backup --
   1061   1.61    simonb  *	backup file "to_name" to to_name.suffix
   1062   1.61    simonb  *	if suffix contains a "%", it's taken as a printf(3) pattern
   1063   1.61    simonb  *	used for a numbered backup.
   1064   1.32   hubertf  */
   1065  1.115     joerg static void
   1066   1.48    simonb backup(const char *to_name)
   1067   1.32   hubertf {
   1068   1.61    simonb 	char	bname[FILENAME_MAX];
   1069   1.32   hubertf 
   1070   1.35   hubertf 	if (numberedbackup) {
   1071   1.32   hubertf 		/* Do numbered backup */
   1072   1.32   hubertf 		int cnt;
   1073   1.32   hubertf 		char suffix_expanded[FILENAME_MAX];
   1074   1.32   hubertf 
   1075   1.32   hubertf 		cnt=0;
   1076   1.32   hubertf 		do {
   1077   1.50     lukem 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
   1078   1.50     lukem 			    cnt);
   1079   1.61    simonb 			(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
   1080   1.61    simonb 			    suffix_expanded);
   1081   1.32   hubertf 			cnt++;
   1082   1.61    simonb 		} while (access(bname, F_OK) == 0);
   1083   1.32   hubertf 	} else {
   1084   1.32   hubertf 		/* Do simple backup */
   1085   1.61    simonb 		(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
   1086   1.32   hubertf 	}
   1087   1.32   hubertf 
   1088   1.61    simonb 	(void)rename(to_name, bname);
   1089    1.1       cgd }
   1090    1.1       cgd 
   1091    1.1       cgd /*
   1092    1.5       jtc  * install_dir --
   1093   1.47       wiz  *	build directory hierarchy
   1094    1.2       jtc  */
   1095  1.115     joerg static void
   1096   1.50     lukem install_dir(char *path, u_int flags)
   1097    1.2       jtc {
   1098  1.111      yamt 	char		*p;
   1099  1.111      yamt 	struct stat	sb;
   1100  1.111      yamt 	int		ch;
   1101  1.111      yamt 
   1102  1.111      yamt 	for (p = path;; ++p)
   1103  1.111      yamt 		if (!*p || (p != path && *p  == '/')) {
   1104  1.111      yamt 			ch = *p;
   1105  1.111      yamt 			*p = '\0';
   1106  1.111      yamt 			if (mkdir(path, 0777) < 0) {
   1107  1.110      gson 				/*
   1108  1.110      gson 				 * Can't create; path exists or no perms.
   1109  1.110      gson 				 * stat() path to determine what's there now.
   1110  1.110      gson 				 */
   1111  1.110      gson 				int sverrno;
   1112  1.110      gson 				sverrno = errno;
   1113  1.110      gson 				if (stat(path, &sb) < 0) {
   1114  1.110      gson 					/* Not there; use mkdir()s error */
   1115  1.110      gson 					errno = sverrno;
   1116  1.119  christos 					err(EXIT_FAILURE, "%s: mkdir", path);
   1117  1.111      yamt 				}
   1118  1.110      gson 				if (!S_ISDIR(sb.st_mode)) {
   1119  1.119  christos 					errx(EXIT_FAILURE,
   1120  1.111      yamt 					    "%s exists but is not a directory",
   1121  1.111      yamt 					    path);
   1122  1.110      gson 				}
   1123   1.97    daniel 			}
   1124  1.111      yamt 			if (!(*p = ch))
   1125    1.4       cgd 				break;
   1126  1.111      yamt 		}
   1127    1.2       jtc 
   1128   1.69     lukem 	if (afterinstallcmd != NULL)
   1129   1.69     lukem 		afterinstall(afterinstallcmd, path, 0);
   1130   1.69     lukem 
   1131   1.50     lukem 	if (!dounpriv && (
   1132   1.50     lukem 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
   1133   1.50     lukem 	    || chmod(path, mode) == -1 )) {
   1134  1.111      yamt 		warn("%s: chown/chmod", path);
   1135   1.41       cgd 	}
   1136  1.106       apb 	metadata_log(path, "dir", NULL, NULL, NULL, 0);
   1137    1.2       jtc }
   1138    1.2       jtc 
   1139    1.2       jtc /*
   1140   1.50     lukem  * metadata_log --
   1141   1.50     lukem  *	if metafp is not NULL, output mtree(8) full path name and settings to
   1142  1.106       apb  *	metafp, to allow permissions to be set correctly by other tools,
   1143  1.106       apb  *	or to allow integrity checks to be performed.
   1144   1.50     lukem  */
   1145  1.115     joerg static void
   1146   1.59     perry metadata_log(const char *path, const char *type, struct timeval *tv,
   1147  1.107     lukem 	const char *slink, const char *digestresult, off_t size)
   1148   1.50     lukem {
   1149   1.72      yamt 	static const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
   1150   1.88     lukem 	const char	*p;
   1151   1.88     lukem 	char		*buf;
   1152   1.75     lukem 	size_t		destlen;
   1153   1.73     lukem 	struct flock	metalog_lock;
   1154   1.50     lukem 
   1155   1.50     lukem 	if (!metafp)
   1156   1.50     lukem 		return;
   1157  1.119  christos 	buf = malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
   1158   1.50     lukem 	if (buf == NULL) {
   1159  1.119  christos 		warn("Can't allocate metadata");
   1160   1.50     lukem 		return;
   1161   1.50     lukem 	}
   1162   1.73     lukem 							/* lock log file */
   1163   1.73     lukem 	metalog_lock.l_start = 0;
   1164   1.73     lukem 	metalog_lock.l_len = 0;
   1165   1.73     lukem 	metalog_lock.l_whence = SEEK_SET;
   1166   1.73     lukem 	metalog_lock.l_type = F_WRLCK;
   1167   1.73     lukem 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1168   1.50     lukem 		warn("can't lock %s", metafile);
   1169   1.94  christos 		free(buf);
   1170   1.50     lukem 		return;
   1171   1.50     lukem 	}
   1172   1.50     lukem 
   1173   1.88     lukem 	p = path;					/* remove destdir */
   1174   1.75     lukem 	if (destdir) {
   1175   1.75     lukem 		destlen = strlen(destdir);
   1176   1.76     lukem 		if (strncmp(p, destdir, destlen) == 0 &&
   1177   1.76     lukem 		    (p[destlen] == '/' || p[destlen] == '\0'))
   1178   1.75     lukem 			p += destlen;
   1179   1.75     lukem 	}
   1180   1.75     lukem 	while (*p && *p == '/')				/* remove leading /s */
   1181   1.75     lukem 		p++;
   1182   1.88     lukem 	strsvis(buf, p, VIS_CSTYLE, extra);		/* encode name */
   1183   1.88     lukem 	p = buf;
   1184   1.75     lukem 							/* print details */
   1185  1.106       apb 	fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
   1186  1.106       apb 	if (owner)
   1187  1.106       apb 		fprintf(metafp, " uname=%s", owner);
   1188  1.106       apb 	if (group)
   1189  1.106       apb 		fprintf(metafp, " gname=%s", group);
   1190  1.106       apb 	fprintf(metafp, " mode=%#o", mode);
   1191  1.107     lukem 	if (slink) {
   1192  1.107     lukem 		strsvis(buf, slink, VIS_CSTYLE, extra);	/* encode link */
   1193   1.89     lukem 		fprintf(metafp, " link=%s", buf);
   1194   1.89     lukem 	}
   1195  1.106       apb 	if (*type == 'f') /* type=file */
   1196  1.106       apb 		fprintf(metafp, " size=%lld", (long long)size);
   1197  1.106       apb 	if (tv != NULL && dopreserve)
   1198  1.117       apb 		fprintf(metafp, " time=%lld.%0*lld",
   1199  1.116       apb 			(long long)tv[1].tv_sec,
   1200  1.116       apb 			(tv[1].tv_usec == 0 ? 1 : 9),
   1201  1.117       apb 			(long long)tv[1].tv_usec * 1000);
   1202  1.106       apb 	if (digestresult && digest)
   1203  1.106       apb 		fprintf(metafp, " %s=%s", digest, digestresult);
   1204   1.52        tv 	if (fflags)
   1205   1.52        tv 		fprintf(metafp, " flags=%s", fflags);
   1206   1.54     lukem 	if (tags)
   1207   1.54     lukem 		fprintf(metafp, " tags=%s", tags);
   1208   1.50     lukem 	fputc('\n', metafp);
   1209   1.50     lukem 	fflush(metafp);					/* flush output */
   1210   1.73     lukem 							/* unlock log file */
   1211   1.73     lukem 	metalog_lock.l_type = F_UNLCK;
   1212   1.73     lukem 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1213   1.50     lukem 		warn("can't unlock %s", metafile);
   1214   1.50     lukem 	}
   1215   1.50     lukem 	free(buf);
   1216   1.50     lukem }
   1217   1.50     lukem 
   1218   1.61    simonb /*
   1219   1.61    simonb  * xbasename --
   1220   1.61    simonb  *	libc basename(3) that returns a pointer to a static buffer
   1221   1.61    simonb  *	instead of overwriting that passed-in string.
   1222   1.61    simonb  */
   1223  1.115     joerg static char *
   1224   1.61    simonb xbasename(char *path)
   1225   1.61    simonb {
   1226   1.61    simonb 	static char tmp[MAXPATHLEN];
   1227   1.61    simonb 
   1228   1.61    simonb 	(void)strlcpy(tmp, path, sizeof(tmp));
   1229   1.61    simonb 	return (basename(tmp));
   1230   1.61    simonb }
   1231   1.61    simonb 
   1232   1.61    simonb /*
   1233   1.61    simonb  * xdirname --
   1234   1.61    simonb  *	libc dirname(3) that returns a pointer to a static buffer
   1235   1.61    simonb  *	instead of overwriting that passed-in string.
   1236   1.61    simonb  */
   1237  1.115     joerg static char *
   1238   1.61    simonb xdirname(char *path)
   1239   1.61    simonb {
   1240   1.61    simonb 	static char tmp[MAXPATHLEN];
   1241   1.50     lukem 
   1242   1.61    simonb 	(void)strlcpy(tmp, path, sizeof(tmp));
   1243   1.61    simonb 	return (dirname(tmp));
   1244   1.61    simonb }
   1245   1.50     lukem 
   1246   1.50     lukem /*
   1247    1.1       cgd  * usage --
   1248    1.1       cgd  *	print a usage message and die
   1249    1.1       cgd  */
   1250  1.115     joerg static void
   1251   1.48    simonb usage(void)
   1252    1.1       cgd {
   1253   1.69     lukem 	const char *prog;
   1254   1.69     lukem 
   1255   1.69     lukem 	prog = getprogname();
   1256   1.53     lukem 
   1257   1.69     lukem 	(void)fprintf(stderr,
   1258   1.75     lukem "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1259   1.75     lukem "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
   1260   1.84     lukem "           [-l linkflags] [-h hash] [-S stripflags] file1 file2\n"
   1261   1.75     lukem "       %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1262   1.75     lukem "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
   1263   1.84     lukem "           [-l linkflags] [-h hash] [-S stripflags] file1 ... fileN directory\n"
   1264   1.75     lukem "       %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
   1265   1.74     lukem "           [-N dbdir] [-o owner] [-g group] directory ...\n",
   1266   1.69     lukem 	    prog, prog, prog);
   1267    1.6       jtc 	exit(1);
   1268    1.1       cgd }
   1269