xinstall.c revision 32490
1/*
2 * Copyright (c) 1987, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1987, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "From: @(#)xinstall.c	8.1 (Berkeley) 7/21/93";
43#endif
44static const char rcsid[] =
45	"$Id: xinstall.c,v 1.29 1998/01/11 11:43:36 peter Exp $";
46#endif /* not lint */
47
48/*-
49 * Todo:
50 * o for -C, compare original files except in -s case.
51 * o for -C, don't change anything if nothing needs be changed.  In
52 *   particular, don't toggle the immutable flags just to allow null
53 *   attribute changes and don't clear the dump flag.  (I think inode
54 *   ctimes are not updated for null attribute changes, but this is a
55 *   bug.)
56 * o independent of -C, if a copy must be made, then copy to a tmpfile,
57 *   set all attributes except the immutable flags, then rename, then
58 *   set the immutable flags.  It's annoying that the immutable flags
59 *   defeat the atomicicity of rename - it seems that there must be
60 *   a window where the target is not immutable.
61 */
62
63#include <sys/param.h>
64#include <sys/wait.h>
65#include <sys/mman.h>
66#include <sys/stat.h>
67#include <sys/mount.h>
68
69#include <ctype.h>
70#include <err.h>
71#include <errno.h>
72#include <fcntl.h>
73#include <grp.h>
74#include <paths.h>
75#include <pwd.h>
76#include <stdio.h>
77#include <stdlib.h>
78#include <string.h>
79#include <unistd.h>
80#include <sysexits.h>
81#include <utime.h>
82
83#include "pathnames.h"
84
85/* Bootstrap aid - this doesn't exist in most older releases */
86#ifndef MAP_FAILED
87#define MAP_FAILED ((void *)-1)	/* from <sys/mman.h> */
88#endif
89
90int debug, docompare, docopy, dodir, dopreserve, dostrip, verbose, nommap;
91int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
92char *group, *owner, pathbuf[MAXPATHLEN];
93char pathbuf2[MAXPATHLEN];
94
95#define	DIRECTORY	0x01		/* Tell install it's a directory. */
96#define	SETFLAGS	0x02		/* Tell install to set flags. */
97#define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
98
99void	copy __P((int, char *, int, char *, off_t));
100int	compare __P((int, const char *, int, const char *,
101		     const struct stat *, const struct stat *));
102void	install __P((char *, char *, u_long, u_int));
103void	install_dir __P((char *));
104u_long	string_to_flags __P((char **, u_long *, u_long *));
105void	strip __P((char *));
106void	usage __P((void));
107int	trymmap __P((int));
108
109#define ALLOW_NUMERIC_IDS 1
110#ifdef ALLOW_NUMERIC_IDS
111
112uid_t   uid = -1;
113gid_t   gid = -1;
114
115uid_t	resolve_uid __P((char *));
116gid_t	resolve_gid __P((char *));
117u_long	numeric_id __P((char *, char *));
118
119#else
120
121struct passwd *pp;
122struct group *gp;
123
124#endif /* ALLOW_NUMERIC_IDS */
125
126int
127main(argc, argv)
128	int argc;
129	char *argv[];
130{
131	struct stat from_sb, to_sb;
132	mode_t *set;
133	u_long fset;
134	u_int iflags;
135	int ch, no_target;
136	char *flags, *to_name;
137
138	iflags = 0;
139	while ((ch = getopt(argc, argv, "CcdDf:g:m:Mo:psv")) != -1)
140		switch((char)ch) {
141		case 'C':
142			docompare = docopy = 1;
143			break;
144		case 'c':
145			docopy = 1;
146			break;
147		case 'D':
148			debug++;
149			break;
150		case 'd':
151			dodir = 1;
152			break;
153		case 'f':
154			flags = optarg;
155			if (string_to_flags(&flags, &fset, NULL))
156				errx(EX_USAGE, "%s: invalid flag", flags);
157			iflags |= SETFLAGS;
158			break;
159		case 'g':
160			group = optarg;
161			break;
162		case 'm':
163			if (!(set = setmode(optarg)))
164				errx(EX_USAGE, "invalid file mode: %s",
165				     optarg);
166			mode = getmode(set, 0);
167			break;
168		case 'M':
169			nommap = 1;
170			break;
171		case 'o':
172			owner = optarg;
173			break;
174		case 'p':
175			docompare = docopy = dopreserve = 1;
176			break;
177		case 's':
178			dostrip = 1;
179			break;
180		case 'v':
181			verbose = 1;
182			break;
183		case '?':
184		default:
185			usage();
186		}
187	argc -= optind;
188	argv += optind;
189
190	/* some options make no sense when creating directories */
191	if (dostrip && dodir)
192		usage();
193
194	/* must have at least two arguments, except when creating directories */
195	if (argc < 2 && !dodir)
196		usage();
197
198#ifdef ALLOW_NUMERIC_IDS
199
200	if (owner)
201		uid = resolve_uid(owner);
202	if (group)
203		gid = resolve_gid(group);
204
205#else
206
207	/* get group and owner id's */
208	if (owner && !(pp = getpwnam(owner)))
209		errx(EX_NOUSER, "unknown user %s", owner);
210	if (group && !(gp = getgrnam(group)))
211		errx(EX_NOUSER, "unknown group %s", group);
212
213#endif /* ALLOW_NUMERIC_IDS */
214
215	if (dodir) {
216		for (; *argv != NULL; ++argv)
217			install_dir(*argv);
218		exit(EX_OK);
219		/* NOTREACHED */
220	}
221
222	no_target = stat(to_name = argv[argc - 1], &to_sb);
223	if (!no_target && (to_sb.st_mode & S_IFMT) == S_IFDIR) {
224		for (; *argv != to_name; ++argv)
225			install(*argv, to_name, fset, iflags | DIRECTORY);
226		exit(EX_OK);
227		/* NOTREACHED */
228	}
229
230	/* can't do file1 file2 directory/file */
231	if (argc != 2)
232		usage();
233
234	if (!no_target) {
235		if (stat(*argv, &from_sb))
236			err(EX_OSERR, "%s", *argv);
237		if (!S_ISREG(to_sb.st_mode)) {
238			errno = EFTYPE;
239			err(EX_OSERR, "%s", to_name);
240		}
241		if (to_sb.st_dev == from_sb.st_dev &&
242		    to_sb.st_ino == from_sb.st_ino)
243			errx(EX_USAGE,
244			    "%s and %s are the same file", *argv, to_name);
245/*
246 * XXX - It's not at all clear why this code was here, since it completely
247 * duplicates code install().  The version in install() handles the -C flag
248 * correctly, so we'll just disable this for now.
249 */
250#if 0
251		/*
252		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
253		 * off the append/immutable bits -- if we fail, go ahead,
254		 * it might work.
255		 */
256		if (to_sb.st_flags & NOCHANGEBITS)
257			(void)chflags(to_name,
258			    to_sb.st_flags & ~(NOCHANGEBITS));
259		(void)unlink(to_name);
260#endif
261	}
262	install(*argv, to_name, fset, iflags);
263	exit(EX_OK);
264	/* NOTREACHED */
265}
266
267#ifdef ALLOW_NUMERIC_IDS
268
269uid_t
270resolve_uid(s)
271	char *s;
272{
273	struct passwd *pw;
274
275	return ((pw = getpwnam(s)) == NULL) ?
276		(uid_t) numeric_id(s, "user") : pw->pw_uid;
277}
278
279gid_t
280resolve_gid(s)
281	char *s;
282{
283	struct group *gr;
284
285	return ((gr = getgrnam(s)) == NULL) ?
286		(gid_t) numeric_id(s, "group") : gr->gr_gid;
287}
288
289u_long
290numeric_id(name, type)
291	char *name, *type;
292{
293	u_long val;
294	char *ep;
295
296	/*
297	 * XXX
298	 * We know that uid_t's and gid_t's are unsigned longs.
299	 */
300	errno = 0;
301	val = strtoul(name, &ep, 10);
302	if (errno)
303		err(EX_NOUSER, "%s", name);
304	if (*ep != '\0')
305		errx(EX_NOUSER, "unknown %s %s", type, name);
306	return (val);
307}
308
309#endif /* ALLOW_NUMERIC_IDS */
310
311/*
312 * install --
313 *	build a path name and install the file
314 */
315void
316install(from_name, to_name, fset, flags)
317	char *from_name, *to_name;
318	u_long fset;
319	u_int flags;
320{
321	struct stat from_sb, to_sb;
322	int devnull, from_fd, to_fd, serrno;
323	char *p, *old_to_name = 0;
324
325	if (debug >= 2 && !docompare)
326		fprintf(stderr, "install: invoked without -C for %s to %s\n",
327			from_name, to_name);
328
329	/* If try to install NULL file to a directory, fails. */
330	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
331		if (stat(from_name, &from_sb))
332			err(EX_OSERR, "%s", from_name);
333		if (!S_ISREG(from_sb.st_mode)) {
334			errno = EFTYPE;
335			err(EX_OSERR, "%s", from_name);
336		}
337		/* Build the target path. */
338		if (flags & DIRECTORY) {
339			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
340			    to_name,
341			    (p = strrchr(from_name, '/')) ? ++p : from_name);
342			to_name = pathbuf;
343		}
344		devnull = 0;
345	} else {
346		from_sb.st_flags = 0;	/* XXX */
347		devnull = 1;
348	}
349
350	if (docompare) {
351		old_to_name = to_name;
352		/*
353		 * Make a new temporary file in the same file system
354		 * (actually, in in the same directory) as the target so
355		 * that the temporary file can be renamed to the target.
356		 */
357		snprintf(pathbuf2, sizeof pathbuf2, "%s", to_name);
358		p = strrchr(pathbuf2, '/');
359		p = (p == NULL ? pathbuf2 : p + 1);
360		snprintf(p, &pathbuf2[sizeof pathbuf2] - p, "INS@XXXX");
361		to_fd = mkstemp(pathbuf2);
362		if (to_fd < 0)
363			/* XXX should fall back to not comparing. */
364			err(EX_OSERR, "mkstemp: %s for %s", pathbuf2, to_name);
365		to_name = pathbuf2;
366	} else {
367		/*
368		 * Unlink now... avoid errors later.  Try to turn off the
369		 * append/immutable bits -- if we fail, go ahead, it might
370		 * work.
371		 */
372		if (stat(to_name, &to_sb) == 0 && to_sb.st_flags & NOCHANGEBITS)
373			(void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
374		unlink(to_name);
375
376		/* Create target. */
377		to_fd = open(to_name,
378			     O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
379		if (to_fd < 0)
380			err(EX_OSERR, "%s", to_name);
381	}
382
383	if (!devnull) {
384		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
385			serrno = errno;
386			(void)unlink(to_name);
387			errno = serrno;
388			err(EX_OSERR, "%s", from_name);
389		}
390		copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
391		(void)close(from_fd);
392	}
393
394	if (dostrip) {
395		(void)close(to_fd);
396
397		strip(to_name);
398
399		/* Reopen target. */
400		to_fd = open(to_name, O_RDWR, 0);
401		if (to_fd < 0)
402			err(EX_OSERR, "%s", to_name);
403	}
404
405	/*
406	 * Unfortunately, because we strip the installed file and not the
407	 * original one, it is impossible to do the comparison without
408	 * first laboriously copying things over and then comparing.
409	 * It may be possible to better optimize the !dostrip case, however.
410	 * For further study.
411	 */
412	if (docompare) {
413		struct stat old_sb, new_sb, timestamp_sb;
414		int old_fd;
415		struct utimbuf utb;
416
417		old_fd = open(old_to_name, O_RDONLY, 0);
418		if (old_fd < 0 && errno == ENOENT)
419			goto different;
420		if (old_fd < 0)
421			err(EX_OSERR, "%s", old_to_name);
422		fstat(old_fd, &old_sb);
423		if (old_sb.st_flags & NOCHANGEBITS)
424			(void)fchflags(old_fd, old_sb.st_flags & ~NOCHANGEBITS);
425		fstat(to_fd, &new_sb);
426		if (compare(old_fd, old_to_name, to_fd, to_name, &old_sb,
427			    &new_sb)) {
428different:
429			if (debug != 0)
430				fprintf(stderr,
431					"install: renaming for %s: %s to %s\n",
432					from_name, to_name, old_to_name);
433			if (dopreserve && stat(from_name, &timestamp_sb) == 0) {
434				utb.actime = from_sb.st_atime;
435				utb.modtime = from_sb.st_mtime;
436				(void)utime(to_name, &utb);
437			}
438moveit:
439			if (verbose) {
440				printf("install: %s -> %s\n",
441					from_name, old_to_name);
442			}
443			if (rename(to_name, old_to_name) < 0) {
444				serrno = errno;
445				unlink(to_name);
446				unlink(old_to_name);
447				errno = serrno;
448				err(EX_OSERR, "rename: %s to %s", to_name,
449				    old_to_name);
450			}
451			close(old_fd);
452		} else {
453			if (old_sb.st_nlink != 1) {
454				/*
455				 * Replace the target, although it hasn't
456				 * changed, to snap the extra links.  But
457				 * preserve the target file times.
458				 */
459				if (fstat(old_fd, &timestamp_sb) == 0) {
460					utb.actime = timestamp_sb.st_atime;
461					utb.modtime = timestamp_sb.st_mtime;
462					(void)utime(to_name, &utb);
463				}
464				goto moveit;
465			}
466			if (unlink(to_name) < 0)
467				err(EX_OSERR, "unlink: %s", to_name);
468			close(to_fd);
469			to_fd = old_fd;
470		}
471		to_name = old_to_name;
472	}
473
474	/*
475	 * Set owner, group, mode for target; do the chown first,
476	 * chown may lose the setuid bits.
477	 */
478	if ((group || owner) &&
479#ifdef ALLOW_NUMERIC_IDS
480	    fchown(to_fd, owner ? uid : -1, group ? gid : -1)) {
481#else
482	    fchown(to_fd, owner ? pp->pw_uid : -1, group ? gp->gr_gid : -1)) {
483#endif
484		serrno = errno;
485		(void)unlink(to_name);
486		errno = serrno;
487		err(EX_OSERR,"%s: chown/chgrp", to_name);
488	}
489	if (fchmod(to_fd, mode)) {
490		serrno = errno;
491		(void)unlink(to_name);
492		errno = serrno;
493		err(EX_OSERR, "%s: chmod", to_name);
494	}
495
496	/*
497	 * If provided a set of flags, set them, otherwise, preserve the
498	 * flags, except for the dump flag.
499	 */
500	if (fchflags(to_fd,
501	    flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
502		serrno = errno;
503		(void)unlink(to_name);
504		errno = serrno;
505		err(EX_OSERR, "%s: chflags", to_name);
506	}
507
508	(void)close(to_fd);
509	if (!docopy && !devnull && unlink(from_name))
510		err(EX_OSERR, "%s", from_name);
511}
512
513/*
514 * compare --
515 *	compare two files; non-zero means files differ
516 */
517int
518compare(int from_fd, const char *from_name, int to_fd, const char *to_name,
519	const struct stat *from_sb, const struct stat *to_sb)
520{
521	char *p, *q;
522	int rv;
523	size_t tsize;
524	int done_compare;
525
526	if (from_sb->st_size != to_sb->st_size)
527		return 1;
528
529	tsize = (size_t)from_sb->st_size;
530
531	if (tsize <= 8 * 1024 * 1024) {
532		done_compare = 0;
533		if (trymmap(from_fd) && trymmap(to_fd)) {
534			p = mmap(NULL, tsize, PROT_READ, MAP_SHARED, from_fd, (off_t)0);
535			if (p == (char *)MAP_FAILED)
536				goto out;
537			q = mmap(NULL, tsize, PROT_READ, MAP_SHARED, to_fd, (off_t)0);
538			if (q == (char *)MAP_FAILED) {
539				munmap(p, tsize);
540				goto out;
541			}
542
543			rv = memcmp(p, q, tsize);
544			munmap(p, tsize);
545			munmap(q, tsize);
546			done_compare = 1;
547		}
548	out:
549		if (!done_compare) {
550			char buf1[MAXBSIZE];
551			char buf2[MAXBSIZE];
552			int n1, n2;
553
554			rv = 0;
555			lseek(from_fd, 0, SEEK_SET);
556			lseek(to_fd, 0, SEEK_SET);
557			while (rv == 0) {
558				n1 = read(from_fd, buf1, sizeof(buf1));
559				if (n1 == 0)
560					break;		/* EOF */
561				else if (n1 > 0) {
562					n2 = read(to_fd, buf2, n1);
563					if (n2 == n1)
564						rv = memcmp(buf1, buf2, n1);
565					else
566						rv = 1;	/* out of sync */
567				} else
568					rv = 1;		/* read failure */
569			}
570			lseek(from_fd, 0, SEEK_SET);
571			lseek(to_fd, 0, SEEK_SET);
572		}
573	} else
574		rv = 1;	/* don't bother in this case */
575
576	return rv;
577}
578
579/*
580 * copy --
581 *	copy from one file to another
582 */
583void
584copy(from_fd, from_name, to_fd, to_name, size)
585	register int from_fd, to_fd;
586	char *from_name, *to_name;
587	off_t size;
588{
589	register int nr, nw;
590	int serrno;
591	char *p, buf[MAXBSIZE];
592	int done_copy;
593
594	/*
595	 * Mmap and write if less than 8M (the limit is so we don't totally
596	 * trash memory on big files.  This is really a minor hack, but it
597	 * wins some CPU back.
598	 */
599	done_copy = 0;
600	if (size <= 8 * 1048576 && trymmap(from_fd)) {
601		if ((p = mmap(NULL, (size_t)size, PROT_READ,
602				MAP_SHARED, from_fd, (off_t)0)) == (char *)MAP_FAILED)
603			goto out;
604		if ((nw = write(to_fd, p, size)) != size) {
605			serrno = errno;
606			(void)unlink(to_name);
607			errno = nw > 0 ? EIO : serrno;
608			err(EX_OSERR, "%s", to_name);
609		}
610		done_copy = 1;
611	out:
612	}
613	if (!done_copy) {
614		while ((nr = read(from_fd, buf, sizeof(buf))) > 0)
615			if ((nw = write(to_fd, buf, nr)) != nr) {
616				serrno = errno;
617				(void)unlink(to_name);
618				errno = nw > 0 ? EIO : serrno;
619				err(EX_OSERR, "%s", to_name);
620			}
621		if (nr != 0) {
622			serrno = errno;
623			(void)unlink(to_name);
624			errno = serrno;
625			err(EX_OSERR, "%s", from_name);
626		}
627	}
628}
629
630/*
631 * strip --
632 *	use strip(1) to strip the target file
633 */
634void
635strip(to_name)
636	char *to_name;
637{
638	int serrno, status;
639
640	switch (vfork()) {
641	case -1:
642		serrno = errno;
643		(void)unlink(to_name);
644		errno = serrno;
645		err(EX_TEMPFAIL, "fork");
646	case 0:
647		execlp("strip", "strip", to_name, NULL);
648		err(EX_OSERR, "exec(strip)");
649	default:
650		if (wait(&status) == -1 || status) {
651			(void)unlink(to_name);
652			exit(EX_SOFTWARE);
653			/* NOTREACHED */
654		}
655	}
656}
657
658/*
659 * install_dir --
660 *	build directory heirarchy
661 */
662void
663install_dir(path)
664        char *path;
665{
666	register char *p;
667	struct stat sb;
668	int ch;
669
670	for (p = path;; ++p)
671		if (!*p || (p != path && *p  == '/')) {
672			ch = *p;
673			*p = '\0';
674			if (stat(path, &sb)) {
675				if (errno != ENOENT || mkdir(path, 0755) < 0) {
676					err(EX_OSERR, "mkdir %s", path);
677					/* NOTREACHED */
678				}
679			} else if (!S_ISDIR(sb.st_mode))
680				errx(EX_OSERR, "%s exists but is not a directory", path);
681			if (!(*p = ch))
682				break;
683 		}
684
685	if ((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid))
686		warn("chown %u:%u %s", uid, gid, path);
687	if (chmod(path, mode))
688		warn("chmod %o %s", mode, path);
689}
690
691/*
692 * usage --
693 *	print a usage message and die
694 */
695void
696usage()
697{
698	(void)fprintf(stderr,"\
699usage: install [-CcDps] [-f flags] [-g group] [-m mode] [-o owner] file1 file2\n\
700       install [-CcDps] [-f flags] [-g group] [-m mode] [-o owner] file1 ...\n\
701             fileN directory\n\
702       install -d [-g group] [-m mode] [-o owner] directory ...\n");
703	exit(EX_USAGE);
704	/* NOTREACHED */
705}
706
707/*
708 * trymmap --
709 *	return true (1) if mmap should be tried, false (0) if not.
710 */
711int
712trymmap(fd)
713	int fd;
714{
715	struct statfs stfs;
716
717	if (nommap || fstatfs(fd, &stfs) < 0)
718		return 0;
719
720/* NetBSD MOUNT_XXX defines are strings, but doesn't have a MOUNT_NONE. */
721#ifdef	MOUNT_NONE
722	switch(stfs.f_type) {
723	case MOUNT_UFS:		/* should be safe.. */
724	case MOUNT_CD9660:	/* should be safe.. */
725		return 1;
726	}
727#else
728	if (strcmp(stfs.f_fstypename,MOUNT_UFS) == 0 ||
729	    strcmp(stfs.f_fstypename,MOUNT_CD9660) == 0)
730		return 1;
731#endif
732	return 0;
733}
734