Merge illumos-gate
[unleashed.git] / bin / xinstall / xinstall.c
blob4b7392ecb4eb9c7e929e770481bb7a8812f2b891
1 /* $OpenBSD: xinstall.c,v 1.67 2018/09/16 02:44:07 millert Exp $ */
2 /* $NetBSD: xinstall.c,v 1.9 1995/12/20 10:25:17 jonathan Exp $ */
4 /*
5 * Copyright (c) 1987, 1993
6 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #include <sys/param.h> /* MAXBSIZE */
34 #include <sys/wait.h>
35 #include <sys/mman.h>
36 #include <sys/stat.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <grp.h>
43 #include <paths.h>
44 #include <pwd.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <utime.h>
51 #include <libgen.h>
53 #include "pathnames.h"
54 #include "compat.h"
56 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
58 #define DIRECTORY 0x01 /* Tell install it's a directory. */
59 #define SETFLAGS 0x02 /* Tell install to set flags. */
60 #define USEFSYNC 0x04 /* Tell install to use fsync(2). */
61 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
62 #define BACKUP_SUFFIX ".old"
64 struct passwd *pp;
65 struct group *gp;
66 int dobackup, docompare, dodest, dodir, dopreserve, dostrip;
67 int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
68 char pathbuf[PATH_MAX], tempfile[PATH_MAX];
69 char *suffix = BACKUP_SUFFIX;
70 uid_t uid;
71 gid_t gid;
73 void copy(int, char *, int, char *, off_t, int);
74 int compare(int, const char *, off_t, int, const char *, off_t);
75 void install(char *, char *, u_long, u_int);
76 void install_dir(char *, int);
77 void strip(char *);
78 void usage(void);
79 int create_tempfile(char *, char *, size_t);
80 int file_write(int, char *, size_t, int *, int *, int);
81 void file_flush(int, int);
83 int
84 main(int argc, char *argv[])
86 struct stat from_sb, to_sb;
87 void *set;
88 u_int32_t fset;
89 u_int iflags;
90 int ch, no_target;
91 char *flags, *to_name, *group = NULL, *owner = NULL;
93 iflags = 0;
94 while ((ch = getopt(argc, argv, "B:bCcDdFf:g:m:o:pSs")) != -1)
95 switch(ch) {
96 case 'C':
97 docompare = 1;
98 break;
99 case 'B':
100 suffix = optarg;
101 /* fall through; -B implies -b */
102 case 'b':
103 dobackup = 1;
104 break;
105 case 'c':
106 /* For backwards compatibility. */
107 break;
108 case 'F':
109 iflags |= USEFSYNC;
110 break;
111 case 'g':
112 group = optarg;
113 break;
114 case 'm':
115 if (!(set = setmode(optarg)))
116 errx(1, "%s: invalid file mode", optarg);
117 mode = getmode(set, 0);
118 free(set);
119 break;
120 case 'o':
121 owner = optarg;
122 break;
123 case 'p':
124 docompare = dopreserve = 1;
125 break;
126 case 'S':
127 break;
128 case 's':
129 dostrip = 1;
130 break;
131 case 'D':
132 dodest = 1;
133 break;
134 case 'd':
135 dodir = 1;
136 break;
137 case '?':
138 default:
139 usage();
141 argc -= optind;
142 argv += optind;
144 /* some options make no sense when creating directories */
145 if ((docompare || dostrip) && dodir)
146 usage();
148 /* must have at least two arguments, except when creating directories */
149 if (argc < 2 && !dodir)
150 usage();
152 /* get group and owner id's */
153 if (group && !(gp = getgrnam(group)) && !isdigit((unsigned char)*group))
154 errx(1, "unknown group %s", group);
155 gid = (group) ? ((gp) ? gp->gr_gid : (gid_t)strtoul(group, NULL, 10)) : (gid_t)-1;
156 if (owner && !(pp = getpwnam(owner)) && !isdigit((unsigned char)*owner))
157 errx(1, "unknown user %s", owner);
158 uid = (owner) ? ((pp) ? pp->pw_uid : (uid_t)strtoul(owner, NULL, 10)) : (uid_t)-1;
160 if (dodir) {
161 for (; *argv != NULL; ++argv)
162 install_dir(*argv, mode);
163 exit(0);
164 /* NOTREACHED */
167 if (dodest) {
168 char *dest = dirname(argv[argc - 1]);
169 if (dest == NULL)
170 errx(1, "cannot determine dirname");
172 * When -D is passed, do not chmod the directory with the mode set for
173 * the target file. If more restrictive permissions are required then
174 * '-d -m' ought to be used instead.
176 install_dir(dest, 0755);
179 no_target = stat(to_name = argv[argc - 1], &to_sb);
180 if (!no_target && S_ISDIR(to_sb.st_mode)) {
181 for (; *argv != to_name; ++argv)
182 install(*argv, to_name, fset, iflags | DIRECTORY);
183 exit(0);
184 /* NOTREACHED */
187 /* can't do file1 file2 directory/file */
188 if (argc != 2)
189 errx(1, "Target: %s", argv[argc-1]);
191 if (!no_target) {
192 if (stat(*argv, &from_sb))
193 err(1, "%s", *argv);
194 if (!S_ISREG(to_sb.st_mode))
195 errc(1, EFTYPE, "%s", to_name);
196 if (to_sb.st_dev == from_sb.st_dev &&
197 to_sb.st_ino == from_sb.st_ino)
198 errx(1, "%s and %s are the same file", *argv, to_name);
200 install(*argv, to_name, fset, iflags);
201 exit(0);
202 /* NOTREACHED */
206 * install --
207 * build a path name and install the file
209 void
210 install(char *from_name, char *to_name, u_long fset, u_int flags)
212 struct stat from_sb, to_sb;
213 struct timespec ts[2];
214 int devnull, from_fd, to_fd, serrno, files_match = 0;
215 char *p;
217 (void)memset((void *)&from_sb, 0, sizeof(from_sb));
218 (void)memset((void *)&to_sb, 0, sizeof(to_sb));
220 /* If try to install NULL file to a directory, fails. */
221 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
222 if (stat(from_name, &from_sb))
223 err(1, "%s", from_name);
224 if (!S_ISREG(from_sb.st_mode))
225 errc(1, EFTYPE, "%s", from_name);
226 /* Build the target path. */
227 if (flags & DIRECTORY) {
228 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
229 to_name,
230 (p = strrchr(from_name, '/')) ? ++p : from_name);
231 to_name = pathbuf;
233 devnull = 0;
234 } else {
235 devnull = 1;
238 if (stat(to_name, &to_sb) == 0) {
239 /* Only compare against regular files. */
240 if (docompare && !S_ISREG(to_sb.st_mode)) {
241 docompare = 0;
242 warnc(EFTYPE, "%s", to_name);
244 } else if (docompare) {
245 /* File does not exist so silently ignore compare flag. */
246 docompare = 0;
249 if (!devnull) {
250 if ((from_fd = open(from_name, O_RDONLY, 0)) < 0)
251 err(1, "%s", from_name);
254 to_fd = create_tempfile(to_name, tempfile, sizeof(tempfile));
255 if (to_fd < 0)
256 err(1, "%s", tempfile);
258 if (!devnull)
259 copy(from_fd, from_name, to_fd, tempfile, from_sb.st_size,
260 ((off_t)from_sb.st_blocks * S_BLKSIZE < from_sb.st_size));
262 if (dostrip) {
263 strip(tempfile);
266 * Re-open our fd on the target, in case we used a strip
267 * that does not work in-place -- like gnu binutils strip.
269 close(to_fd);
270 if ((to_fd = open(tempfile, O_RDONLY, 0)) < 0)
271 err(1, "stripping %s", to_name);
275 * Compare the (possibly stripped) temp file to the target.
277 if (docompare) {
278 int temp_fd = to_fd;
279 struct stat temp_sb;
281 /* Re-open to_fd using the real target name. */
282 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
283 err(1, "%s", to_name);
285 if (fstat(temp_fd, &temp_sb)) {
286 serrno = errno;
287 (void)unlink(tempfile);
288 errc(1, serrno, "%s", tempfile);
291 if (compare(temp_fd, tempfile, temp_sb.st_size, to_fd,
292 to_name, to_sb.st_size) == 0) {
294 * If target has more than one link we need to
295 * replace it in order to snap the extra links.
296 * Need to preserve target file times, though.
298 if (to_sb.st_nlink != 1) {
299 ts[0] = to_sb.st_atim;
300 ts[1] = to_sb.st_mtim;
301 futimens(temp_fd, ts);
302 } else {
303 files_match = 1;
304 (void)unlink(tempfile);
307 (void)close(to_fd);
308 to_fd = temp_fd;
312 * Preserve the timestamp of the source file if necessary.
314 if (dopreserve && !files_match) {
315 ts[0] = from_sb.st_atim;
316 ts[1] = from_sb.st_mtim;
317 futimens(to_fd, ts);
321 * Set owner, group, mode for target; do the chown first,
322 * chown may lose the setuid bits.
324 if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
325 fchown(to_fd, uid, gid)) {
326 serrno = errno;
327 (void)unlink(tempfile);
328 errx(1, "%s: chown/chgrp: %s", tempfile, strerror(serrno));
330 if (fchmod(to_fd, mode)) {
331 serrno = errno;
332 (void)unlink(tempfile);
333 errx(1, "%s: chmod: %s", tempfile, strerror(serrno));
336 if (flags & USEFSYNC)
337 fsync(to_fd);
338 (void)close(to_fd);
339 if (!devnull)
340 (void)close(from_fd);
343 * Move the new file into place if the files are different (or just not
344 * compared).
346 if (!files_match) {
347 if (dobackup) {
348 char backup[PATH_MAX];
349 (void)snprintf(backup, PATH_MAX, "%s%s", to_name,
350 suffix);
351 /* It is ok for the target file not to exist. */
352 if (rename(to_name, backup) < 0 && errno != ENOENT) {
353 serrno = errno;
354 unlink(tempfile);
355 errx(1, "rename: %s to %s: %s", to_name,
356 backup, strerror(serrno));
359 if (rename(tempfile, to_name) < 0 ) {
360 serrno = errno;
361 unlink(tempfile);
362 errx(1, "rename: %s to %s: %s", tempfile,
363 to_name, strerror(serrno));
369 * copy --
370 * copy from one file to another
372 void
373 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size,
374 int sparse)
376 ssize_t nr, nw;
377 int serrno;
378 char *p, buf[MAXBSIZE];
380 if (size == 0)
381 return;
383 /* Rewind file descriptors. */
384 if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
385 err(1, "lseek: %s", from_name);
386 if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
387 err(1, "lseek: %s", to_name);
390 * Mmap and write if less than 8M (the limit is so we don't totally
391 * trash memory on big files. This is really a minor hack, but it
392 * wins some CPU back. Sparse files need special treatment.
394 if (!sparse && size <= 8 * 1048576) {
395 size_t siz;
397 if ((p = mmap(NULL, (size_t)size, PROT_READ, MAP_PRIVATE,
398 from_fd, (off_t)0)) == MAP_FAILED) {
399 serrno = errno;
400 (void)unlink(to_name);
401 errc(1, serrno, "%s", from_name);
403 madvise(p, size, MADV_SEQUENTIAL);
404 siz = (size_t)size;
405 if ((nw = write(to_fd, p, siz)) != siz) {
406 serrno = errno;
407 (void)unlink(to_name);
408 errx(1, "%s: %s",
409 to_name, strerror(nw > 0 ? EIO : serrno));
411 (void) munmap(p, (size_t)size);
412 } else {
413 int sz, rem, isem = 1;
414 struct stat sb;
417 * Pass the blocksize of the file being written to the write
418 * routine. if the size is zero, use the default S_BLKSIZE.
420 if (fstat(to_fd, &sb) != 0 || sb.st_blksize == 0)
421 sz = S_BLKSIZE;
422 else
423 sz = sb.st_blksize;
424 rem = sz;
426 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
427 if (sparse)
428 nw = file_write(to_fd, buf, nr, &rem, &isem, sz);
429 else
430 nw = write(to_fd, buf, nr);
431 if (nw != nr) {
432 serrno = errno;
433 (void)unlink(to_name);
434 errx(1, "%s: %s",
435 to_name, strerror(nw > 0 ? EIO : serrno));
438 if (sparse)
439 file_flush(to_fd, isem);
440 if (nr != 0) {
441 serrno = errno;
442 (void)unlink(to_name);
443 errc(1, serrno, "%s", from_name);
449 * compare --
450 * compare two files; non-zero means files differ
453 compare(int from_fd, const char *from_name, off_t from_len, int to_fd,
454 const char *to_name, off_t to_len)
456 caddr_t p1, p2;
457 size_t length;
458 off_t from_off, to_off, remainder;
459 int dfound;
461 if (from_len == 0 && from_len == to_len)
462 return (0);
464 if (from_len != to_len)
465 return (1);
468 * Compare the two files being careful not to mmap
469 * more than 8M at a time.
471 from_off = to_off = (off_t)0;
472 remainder = from_len;
473 do {
474 length = MINIMUM(remainder, 8 * 1048576);
475 remainder -= length;
477 if ((p1 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
478 from_fd, from_off)) == MAP_FAILED)
479 err(1, "%s", from_name);
480 if ((p2 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
481 to_fd, to_off)) == MAP_FAILED)
482 err(1, "%s", to_name);
483 if (length) {
484 madvise(p1, length, MADV_SEQUENTIAL);
485 madvise(p2, length, MADV_SEQUENTIAL);
488 dfound = memcmp(p1, p2, length);
490 (void) munmap(p1, length);
491 (void) munmap(p2, length);
493 from_off += length;
494 to_off += length;
496 } while (!dfound && remainder > 0);
498 return(dfound);
502 * strip --
503 * use strip(1) to strip the target file
505 void
506 strip(char *to_name)
508 int serrno, status;
509 char * volatile path_strip;
510 pid_t pid;
512 if (issetugid() || (path_strip = getenv("STRIP")) == NULL)
513 path_strip = _PATH_STRIP;
515 switch ((pid = vfork())) {
516 case -1:
517 serrno = errno;
518 (void)unlink(to_name);
519 errc(1, serrno, "forks");
520 case 0:
521 execl(path_strip, "strip", "--", to_name, (char *)NULL);
522 warn("%s", path_strip);
523 _exit(1);
524 default:
525 while (waitpid(pid, &status, 0) == -1) {
526 if (errno != EINTR)
527 break;
529 if (!WIFEXITED(status))
530 (void)unlink(to_name);
535 * install_dir --
536 * build directory hierarchy
538 void
539 install_dir(char *path, int mode)
541 char *p;
542 struct stat sb;
543 int ch;
545 for (p = path;; ++p)
546 if (!*p || (p != path && *p == '/')) {
547 ch = *p;
548 *p = '\0';
549 if (mkdir(path, 0777)) {
550 int mkdir_errno = errno;
551 if (stat(path, &sb)) {
552 /* Not there; use mkdir()s errno */
553 errc(1, mkdir_errno, "%s",
554 path);
555 /* NOTREACHED */
557 if (!S_ISDIR(sb.st_mode)) {
558 /* Is there, but isn't a directory */
559 errc(1, ENOTDIR, "%s", path);
560 /* NOTREACHED */
563 if (!(*p = ch))
564 break;
567 if (((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid)) ||
568 chmod(path, mode)) {
569 warn("%s", path);
574 * usage --
575 * print a usage message and die
577 void
578 usage(void)
580 (void)fprintf(stderr, "\
581 usage: install [-bCcDdFps] [-B suffix] [-f flags] [-g group] [-m mode] [-o owner]\n source ... target ...\n");
582 exit(1);
583 /* NOTREACHED */
587 * create_tempfile --
588 * create a temporary file based on path and open it
591 create_tempfile(char *path, char *temp, size_t tsize)
593 char *p;
595 strlcpy(temp, path, tsize);
596 if ((p = strrchr(temp, '/')) != NULL)
597 p++;
598 else
599 p = temp;
600 *p = '\0';
601 strlcat(p, "INS@XXXXXXXXXX", tsize);
603 return(mkstemp(temp));
607 * file_write()
608 * Write/copy a file (during copy or archive extract). This routine knows
609 * how to copy files with lseek holes in it. (Which are read as file
610 * blocks containing all 0's but do not have any file blocks associated
611 * with the data). Typical examples of these are files created by dbm
612 * variants (.pag files). While the file size of these files are huge, the
613 * actual storage is quite small (the files are sparse). The problem is
614 * the holes read as all zeros so are probably stored on the archive that
615 * way (there is no way to determine if the file block is really a hole,
616 * we only know that a file block of all zero's can be a hole).
617 * At this writing, no major archive format knows how to archive files
618 * with holes. However, on extraction (or during copy, -rw) we have to
619 * deal with these files. Without detecting the holes, the files can
620 * consume a lot of file space if just written to disk. This replacement
621 * for write when passed the basic allocation size of a file system block,
622 * uses lseek whenever it detects the input data is all 0 within that
623 * file block. In more detail, the strategy is as follows:
624 * While the input is all zero keep doing an lseek. Keep track of when we
625 * pass over file block boundaries. Only write when we hit a non zero
626 * input. once we have written a file block, we continue to write it to
627 * the end (we stop looking at the input). When we reach the start of the
628 * next file block, start checking for zero blocks again. Working on file
629 * block boundaries significantly reduces the overhead when copying files
630 * that are NOT very sparse. This overhead (when compared to a write) is
631 * almost below the measurement resolution on many systems. Without it,
632 * files with holes cannot be safely copied. It does has a side effect as
633 * it can put holes into files that did not have them before, but that is
634 * not a problem since the file contents are unchanged (in fact it saves
635 * file space). (Except on paging files for diskless clients. But since we
636 * cannot determine one of those file from here, we ignore them). If this
637 * ever ends up on a system where CTG files are supported and the holes
638 * are not desired, just do a conditional test in those routines that
639 * call file_write() and have it call write() instead. BEFORE CLOSING THE
640 * FILE, make sure to call file_flush() when the last write finishes with
641 * an empty block. A lot of file systems will not create an lseek hole at
642 * the end. In this case we drop a single 0 at the end to force the
643 * trailing 0's in the file.
644 * ---Parameters---
645 * rem: how many bytes left in this file system block
646 * isempt: have we written to the file block yet (is it empty)
647 * sz: basic file block allocation size
648 * cnt: number of bytes on this write
649 * str: buffer to write
650 * Return:
651 * number of bytes written, -1 on write (or lseek) error.
655 file_write(int fd, char *str, size_t cnt, int *rem, int *isempt, int sz)
657 char *pt;
658 char *end;
659 size_t wcnt;
660 char *st = str;
663 * while we have data to process
665 while (cnt) {
666 if (!*rem) {
668 * We are now at the start of file system block again
669 * (or what we think one is...). start looking for
670 * empty blocks again
672 *isempt = 1;
673 *rem = sz;
677 * only examine up to the end of the current file block or
678 * remaining characters to write, whatever is smaller
680 wcnt = MINIMUM(cnt, *rem);
681 cnt -= wcnt;
682 *rem -= wcnt;
683 if (*isempt) {
685 * have not written to this block yet, so we keep
686 * looking for zero's
688 pt = st;
689 end = st + wcnt;
692 * look for a zero filled buffer
694 while ((pt < end) && (*pt == '\0'))
695 ++pt;
697 if (pt == end) {
699 * skip, buf is empty so far
701 if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
702 warn("lseek");
703 return(-1);
705 st = pt;
706 continue;
709 * drat, the buf is not zero filled
711 *isempt = 0;
715 * have non-zero data in this file system block, have to write
717 if (write(fd, st, wcnt) != wcnt) {
718 warn("write");
719 return(-1);
721 st += wcnt;
723 return(st - str);
727 * file_flush()
728 * when the last file block in a file is zero, many file systems will not
729 * let us create a hole at the end. To get the last block with zeros, we
730 * write the last BYTE with a zero (back up one byte and write a zero).
732 void
733 file_flush(int fd, int isempt)
735 static char blnk[] = "\0";
738 * silly test, but make sure we are only called when the last block is
739 * filled with all zeros.
741 if (!isempt)
742 return;
745 * move back one byte and write a zero
747 if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
748 warn("Failed seek on file");
749 return;
752 if (write(fd, blnk, 1) < 0)
753 warn("Failed write to file");
754 return;