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