Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.32
      1 /*	$NetBSD: xinstall.c,v 1.32 1999/01/26 01:34:25 hubertf Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1987, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
     45 #else
     46 __RCSID("$NetBSD: xinstall.c,v 1.32 1999/01/26 01:34:25 hubertf Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 #include <sys/param.h>
     51 #include <sys/wait.h>
     52 #include <sys/mman.h>
     53 #include <sys/stat.h>
     54 
     55 #include <ctype.h>
     56 #include <errno.h>
     57 #include <fcntl.h>
     58 #include <grp.h>
     59 #include <paths.h>
     60 #include <pwd.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <unistd.h>
     65 #include <err.h>
     66 
     67 #include "pathnames.h"
     68 #include "stat_flags.h"
     69 
     70 #define STRIP_ARGS_MAX 32
     71 #define BACKUP_SUFFIX ".old"
     72 
     73 struct passwd *pp;
     74 struct group *gp;
     75 int dobackup=0, docopy=0, dodir=0, dostrip=0, dolink=0, dopreserve=0;
     76 int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
     77 char pathbuf[MAXPATHLEN];
     78 uid_t uid;
     79 gid_t gid;
     80 char *stripArgs=NULL;
     81 char *suffix=BACKUP_SUFFIX;
     82 
     83 #define LN_ABSOLUTE	0x01
     84 #define LN_RELATIVE	0x02
     85 #define LN_HARD		0x04
     86 #define LN_SYMBOLIC	0x08
     87 #define LN_MIXED	0x10
     88 
     89 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
     90 #define	SETFLAGS	0x02		/* Tell install to set flags. */
     91 
     92 void	copy __P((int, char *, int, char *, off_t));
     93 void	makelink __P((char *, char *));
     94 void	install __P((char *, char *, u_long, u_int));
     95 void	install_dir __P((char *));
     96 void	strip __P((char *));
     97 void	backup __P((const char *));
     98 void	usage __P((void));
     99 int	main __P((int, char *[]));
    100 
    101 int
    102 main(argc, argv)
    103 	int argc;
    104 	char *argv[];
    105 {
    106 	struct stat from_sb, to_sb;
    107 	mode_t *set;
    108 	u_long fset;
    109 	u_int iflags;
    110 	int ch, no_target;
    111 	char *p;
    112 	char *flags = NULL, *to_name, *group = NULL, *owner = NULL;
    113 
    114 	iflags = 0;
    115 	while ((ch = getopt(argc, argv, "cbB:df:g:l:m:o:psS:")) != -1)
    116 		switch((char)ch) {
    117 		case 'B':
    118 			suffix = optarg;
    119 			/* fall through; -B implies -b */
    120 		case 'b':
    121 			dobackup = 1;
    122 			break;
    123 		case 'c':
    124 			docopy = 1;
    125 			break;
    126 		case 'd':
    127 			dodir = 1;
    128 			break;
    129 		case 'f':
    130 			flags = optarg;
    131 			if (string_to_flags(&flags, &fset, NULL))
    132 				errx(1, "%s: invalid flag", flags);
    133 			iflags |= SETFLAGS;
    134 			break;
    135 		case 'g':
    136 			group = optarg;
    137 			break;
    138 		case 'l':
    139 			for (p = optarg; *p; p++)
    140 				switch (*p) {
    141 				case 's':
    142 					dolink &= ~(LN_HARD|LN_MIXED);
    143 					dolink |= LN_SYMBOLIC;
    144 					break;
    145 				case 'h':
    146 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    147 					dolink |= LN_HARD;
    148 					break;
    149 				case 'm':
    150 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    151 					dolink |= LN_MIXED;
    152 					break;
    153 				case 'a':
    154 					dolink &= ~LN_RELATIVE;
    155 					dolink |= LN_ABSOLUTE;
    156 					break;
    157 				case 'r':
    158 					dolink &= ~LN_ABSOLUTE;
    159 					dolink |= LN_RELATIVE;
    160 					break;
    161 				default:
    162 					errx(1, "%c: invalid link type", *p);
    163 					break;
    164 				}
    165 			break;
    166 		case 'm':
    167 			if (!(set = setmode(optarg)))
    168 				errx(1, "%s: invalid file mode", optarg);
    169 			mode = getmode(set, 0);
    170 			break;
    171 		case 'o':
    172 			owner = optarg;
    173 			break;
    174 		case 'p':
    175 			dopreserve = 1;
    176 			break;
    177 		case 'S':
    178 			stripArgs = (char*)malloc(sizeof(char)*(strlen(optarg)+1));
    179 			strcpy(stripArgs,optarg);
    180 			/* fall through; -S implies -s */
    181 		case 's':
    182 			dostrip = 1;
    183 			break;
    184 		case '?':
    185 		default:
    186 			usage();
    187 		}
    188 	argc -= optind;
    189 	argv += optind;
    190 
    191 	/* strip and link options make no sense when creating directories */
    192 	if ((dostrip || dolink) && dodir)
    193 		usage();
    194 
    195 	/* strip and flags make no sense with links */
    196 	if ((dostrip || flags) && dolink)
    197 		usage();
    198 
    199 	/* must have at least two arguments, except when creating directories */
    200 	if (argc < 2 && !dodir)
    201 		usage();
    202 
    203 	/* get group and owner id's */
    204 	if (group && !(gp = getgrnam(group)) && !isdigit((unsigned char)*group))
    205 		errx(1, "unknown group %s", group);
    206 	gid = (group) ? ((gp) ? gp->gr_gid : atoi(group)) : -1;
    207 	if (owner && !(pp = getpwnam(owner)) && !isdigit((unsigned char)*owner))
    208 		errx(1, "unknown user %s", owner);
    209 	uid = (owner) ? ((pp) ? pp->pw_uid : atoi(owner)) : -1;
    210 
    211 	if (dodir) {
    212 		for (; *argv != NULL; ++argv)
    213 			install_dir(*argv);
    214 		exit (0);
    215 	}
    216 
    217 	no_target = stat(to_name = argv[argc - 1], &to_sb);
    218 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
    219 		for (; *argv != to_name; ++argv)
    220 			install(*argv, to_name, fset, iflags | DIRECTORY);
    221 		exit(0);
    222 	}
    223 
    224 	/* can't do file1 file2 directory/file */
    225 	if (argc != 2)
    226 		usage();
    227 
    228 	if (!no_target) {
    229 		if (stat(*argv, &from_sb))
    230 			err(1, "%s", *argv);
    231 		if (!S_ISREG(to_sb.st_mode))
    232 			errx(1, "%s: %s", to_name, strerror(EFTYPE));
    233 		if (!dolink && to_sb.st_dev == from_sb.st_dev &&
    234 		    to_sb.st_ino == from_sb.st_ino)
    235 			errx(1, "%s and %s are the same file", *argv, to_name);
    236 		/*
    237 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    238 		 * off the append/immutable bits -- if we fail, go ahead,
    239 		 * it might work.
    240 		 */
    241 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
    242 		if (to_sb.st_flags & NOCHANGEBITS)
    243 			(void)chflags(to_name,
    244 			    to_sb.st_flags & ~(NOCHANGEBITS));
    245 		if (dobackup)
    246 			backup(to_name);
    247 		else
    248 			(void)unlink(to_name);
    249 	}
    250 	install(*argv, to_name, fset, iflags);
    251 	exit(0);
    252 }
    253 
    254 /*
    255  * makelink --
    256  *	make a link from source to destination
    257  */
    258 void
    259 makelink(from_name, to_name)
    260 	char *from_name;
    261 	char *to_name;
    262 {
    263 	char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
    264 
    265 	/* Try hard links first */
    266 	if (dolink & (LN_HARD|LN_MIXED)) {
    267 		if (link(from_name, to_name) == -1) {
    268 			if ((dolink & LN_HARD) || errno != EXDEV)
    269 				err(1, "link %s -> %s", from_name, to_name);
    270 		}
    271 		else
    272 			return;
    273 	}
    274 
    275 	/* Symbolic links */
    276 	if (dolink & LN_ABSOLUTE) {
    277 		/* Convert source path to absolute */
    278 		if (realpath(from_name, src) == NULL)
    279 			err(1, "%s", src);
    280 		if (symlink(src, to_name) == -1)
    281 			err(1, "symlink %s -> %s", src, to_name);
    282 		return;
    283 	}
    284 
    285 	if (dolink & LN_RELATIVE) {
    286 		char *s, *d;
    287 
    288 		/* Resolve pathnames */
    289 		if (realpath(from_name, src) == NULL)
    290 			err(1, "%s", src);
    291 		if (realpath(to_name, dst) == NULL)
    292 			err(1, "%s", dst);
    293 
    294 		/* trim common path components */
    295 		for (s = src, d = dst; *s == *d; s++, d++)
    296 			continue;
    297 		while (*s != '/')
    298 			s--, d--;
    299 
    300 		/* count the number of directories we need to backtrack */
    301 		for (++d, lnk[0] = '\0'; *d; d++)
    302 			if (*d == '/')
    303 				(void) strcat(lnk, "../");
    304 
    305 		(void) strcat(lnk, ++s);
    306 
    307 		if (symlink(lnk, dst) == -1)
    308 			err(1, "symlink %s -> %s", lnk, dst);
    309 		return;
    310 	}
    311 
    312 	/*
    313 	 * If absolute or relative was not specified,
    314 	 * try the names the user provided
    315 	 */
    316 	if (symlink(from_name, to_name) == -1)
    317 		err(1, "symlink %s -> %s", from_name, to_name);
    318 
    319 }
    320 
    321 /*
    322  * install --
    323  *	build a path name and install the file
    324  */
    325 void
    326 install(from_name, to_name, fset, flags)
    327 	char *from_name, *to_name;
    328 	u_long fset;
    329 	u_int flags;
    330 {
    331 	struct stat from_sb, to_sb;
    332 	int devnull, from_fd, to_fd, serrno;
    333 	char *p;
    334 
    335 	/* If try to install NULL file to a directory, fails. */
    336 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    337 		if (stat(from_name, &from_sb))
    338 			err(1, "%s", from_name);
    339 		if (!S_ISREG(from_sb.st_mode))
    340 			errx(1, "%s: %s", from_name, strerror(EFTYPE));
    341 		/* Build the target path. */
    342 		if (flags & DIRECTORY) {
    343 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    344 			    to_name,
    345 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    346 			to_name = pathbuf;
    347 		}
    348 		devnull = 0;
    349 	} else {
    350 		from_sb.st_flags = 0;	/* XXX */
    351 		devnull = 1;
    352 	}
    353 
    354 	/*
    355 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    356 	 * off the append/immutable bits -- if we fail, go ahead,
    357 	 * it might work.
    358 	 */
    359 	if (stat(to_name, &to_sb) == 0 &&
    360 	    to_sb.st_flags & (NOCHANGEBITS))
    361 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    362 	if (dobackup)
    363 		backup(to_name);
    364 	else
    365 		(void)unlink(to_name);
    366 
    367 	if (dolink) {
    368 		makelink(from_name, to_name);
    369 		return;
    370 	}
    371 
    372 	/* Create target. */
    373 	if ((to_fd = open(to_name,
    374 	    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    375 		err(1, "%s", to_name);
    376 	if (!devnull) {
    377 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    378 			(void)unlink(to_name);
    379 			err(1, "%s", from_name);
    380 		}
    381 		copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    382 		(void)close(from_fd);
    383 	}
    384 
    385 	if (dostrip) {
    386 		strip(to_name);
    387 
    388 		/*
    389 		 * Re-open our fd on the target, in case we used a strip
    390 		 *  that does not work in-place -- like gnu binutils strip.
    391 		 */
    392 		close(to_fd);
    393 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    394 		  err(1, "stripping %s", to_name);
    395 	}
    396 
    397 	/*
    398 	 * Set owner, group, mode for target; do the chown first,
    399 	 * chown may lose the setuid bits.
    400 	 */
    401 	if ((gid != -1 || uid != -1) && fchown(to_fd, uid, gid)) {
    402 		serrno = errno;
    403 		(void)unlink(to_name);
    404 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    405 	}
    406 	if (fchmod(to_fd, mode)) {
    407 		serrno = errno;
    408 		(void)unlink(to_name);
    409 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    410 	}
    411 
    412 	/*
    413 	 * If provided a set of flags, set them, otherwise, preserve the
    414 	 * flags, except for the dump flag.
    415 	 */
    416 	if (fchflags(to_fd,
    417 	    flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
    418 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    419 			warn("%s: chflags", to_name);
    420 	}
    421 
    422 	/*
    423 	 * Preserve the date of the source file.
    424 	 */
    425 	if (dopreserve) {
    426 		struct timeval tv[2];
    427 
    428 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    429 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    430 		if (futimes(to_fd, tv) == -1)
    431 			warn("%s: futimes", to_name);
    432 	}
    433 
    434 	(void)close(to_fd);
    435 	if (!docopy && !devnull && unlink(from_name))
    436 		err(1, "%s", from_name);
    437 }
    438 
    439 /*
    440  * copy --
    441  *	copy from one file to another
    442  */
    443 void
    444 copy(from_fd, from_name, to_fd, to_name, size)
    445 	int from_fd, to_fd;
    446 	char *from_name, *to_name;
    447 	off_t size;
    448 {
    449 	int nr, nw;
    450 	int serrno;
    451 	char *p;
    452 	char buf[MAXBSIZE];
    453 
    454 	/*
    455 	 * There's no reason to do anything other than close the file
    456 	 * now if it's empty, so let's not bother.
    457 	 */
    458 	if (size > 0) {
    459 		/*
    460 		 * Mmap and write if less than 8M (the limit is so we don't totally
    461 		 * trash memory on big files).  This is really a minor hack, but it
    462 		 * wins some CPU back.
    463 		 */
    464 		if (size <= 8 * 1048576) {
    465 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    466 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0)) == (char *)-1)
    467 				err(1, "%s", from_name);
    468 			if (write(to_fd, p, size) != size)
    469 				err(1, "%s", to_name);
    470 		} else {
    471 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0)
    472 				if ((nw = write(to_fd, buf, nr)) != nr) {
    473 					serrno = errno;
    474 					(void)unlink(to_name);
    475 					errx(1, "%s: %s",
    476 					    to_name, strerror(nw > 0 ? EIO : serrno));
    477 				}
    478 			if (nr != 0) {
    479 				serrno = errno;
    480 				(void)unlink(to_name);
    481 				errx(1, "%s: %s", from_name, strerror(serrno));
    482 			}
    483 		}
    484 	}
    485 }
    486 
    487 /*
    488  * strip --
    489  *	use strip(1) to strip the target file
    490  */
    491 void
    492 strip(to_name)
    493 	char *to_name;
    494 {
    495 	int serrno, status;
    496 	char *stripprog;
    497 
    498 	switch (vfork()) {
    499 	case -1:
    500 		serrno = errno;
    501 		(void)unlink(to_name);
    502 		errx(1, "vfork: %s", strerror(serrno));
    503 	case 0:
    504 		stripprog = getenv("STRIP");
    505 		if (stripprog == NULL)
    506 			stripprog = _PATH_STRIP;
    507 
    508 		if (stripArgs) {
    509 			/* build up a command line and let /bin/sh parse the arguments */
    510 			char* cmd = (char*)malloc(sizeof(char)*
    511 						  (3+strlen(stripprog)+
    512 						     strlen(stripArgs)+
    513 						     strlen(to_name)));
    514 
    515 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    516 
    517 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    518 		} else
    519 			execl(stripprog, "strip", to_name, NULL);
    520 
    521 		warn("%s", stripprog);
    522 		_exit(1);
    523 	default:
    524 		if (wait(&status) == -1 || status)
    525 			(void)unlink(to_name);
    526 	}
    527 }
    528 
    529 /*
    530  * backup file "to_name" to to_name.suffix
    531  * if suffix contains a "%", it's taken as a printf(3) pattern
    532  * used for a numbered backup.
    533  */
    534 void
    535 backup(to_name)
    536 	const char *to_name;
    537 {
    538 	char backup[FILENAME_MAX];
    539 
    540 	if (strchr(suffix, '%')) {
    541 		/* Do numbered backup */
    542 		int cnt;
    543 		char suffix_expanded[FILENAME_MAX];
    544 
    545 		cnt=0;
    546 		do {
    547 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix, cnt);
    548 			(void)snprintf(backup, FILENAME_MAX, "%s%s",
    549 				       to_name, suffix_expanded);
    550 			cnt++;
    551 		} while (access(backup, F_OK)==0);
    552 	} else {
    553 		/* Do simple backup */
    554 		(void)snprintf(backup, FILENAME_MAX, "%s%s", to_name, suffix);
    555 	}
    556 
    557 	(void)rename(to_name, backup);
    558 }
    559 
    560 /*
    561  * install_dir --
    562  *	build directory heirarchy
    563  */
    564 void
    565 install_dir(path)
    566         char *path;
    567 {
    568         char *p;
    569         struct stat sb;
    570         int ch;
    571 
    572         for (p = path;; ++p)
    573                 if (!*p || (p != path && *p  == '/')) {
    574                         ch = *p;
    575                         *p = '\0';
    576                         if (stat(path, &sb)) {
    577                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    578 					err(1, "%s", path);
    579 					/* NOTREACHED */
    580                                 }
    581                         }
    582                         if (!(*p = ch))
    583 				break;
    584                 }
    585 
    586 	if (((gid != -1 || uid != -1) && chown(path, uid, gid)) ||
    587             chmod(path, mode)) {
    588                 warn("%s", path);
    589         }
    590 }
    591 
    592 /*
    593  * usage --
    594  *	print a usage message and die
    595  */
    596 void
    597 usage()
    598 {
    599 	(void)fprintf(stderr, "\
    600 usage: install [-bcps] [-B suffix] [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 file2\n\
    601        install [-bcps] [-B suffix] [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 ... fileN directory\n\
    602        install -pd [-m mode] [-o owner] [-g group] directory ...\n");
    603 	exit(1);
    604 }
    605