xinstall.c revision 1.48 1 /* $NetBSD: xinstall.c,v 1.48 2001/09/15 14:55:38 simonb 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.48 2001/09/15 14:55:38 simonb 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 dorename = 0, unpriv = 0;
77 static int numberedbackup = 0;
78 int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
79 char pathbuf[MAXPATHLEN];
80 uid_t uid;
81 gid_t gid;
82 char *stripArgs=NULL;
83 char *suffix=BACKUP_SUFFIX;
84
85 #define LN_ABSOLUTE 0x01
86 #define LN_RELATIVE 0x02
87 #define LN_HARD 0x04
88 #define LN_SYMBOLIC 0x08
89 #define LN_MIXED 0x10
90
91 #define DIRECTORY 0x01 /* Tell install it's a directory. */
92 #define SETFLAGS 0x02 /* Tell install to set flags. */
93
94 void copy(int, char *, int, char *, off_t);
95 void makelink(char *, char *);
96 void install(char *, char *, u_long, u_int);
97 void install_dir(char *);
98 void strip(char *);
99 void backup(const char *);
100 void usage(void);
101 int main(int, char *[]);
102
103 int
104 main(int argc, char *argv[])
105 {
106 struct stat from_sb, to_sb;
107 void *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 setprogname(argv[0]);
115
116 iflags = 0;
117 while ((ch = getopt(argc, argv, "cbB:df:g:l:m:o:prsS:U")) != -1)
118 switch((char)ch) {
119 case 'B':
120 suffix = optarg;
121 numberedbackup = 0;
122 {
123 /* Check if given suffix really generates
124 different suffixes - catch e.g. ".%" */
125 char suffix_expanded0[FILENAME_MAX],
126 suffix_expanded1[FILENAME_MAX];
127 (void)snprintf(suffix_expanded0, FILENAME_MAX,
128 suffix, 0);
129 (void)snprintf(suffix_expanded1, FILENAME_MAX,
130 suffix, 1);
131 if (strcmp(suffix_expanded0, suffix_expanded1)
132 != 0)
133 numberedbackup = 1;
134 }
135 /* fall through; -B implies -b */
136 case 'b':
137 dobackup = 1;
138 break;
139 case 'c':
140 docopy = 1;
141 break;
142 case 'd':
143 dodir = 1;
144 break;
145 case 'f':
146 flags = optarg;
147 if (string_to_flags(&flags, &fset, NULL))
148 errx(1, "%s: invalid flag", flags);
149 iflags |= SETFLAGS;
150 break;
151 case 'g':
152 group = optarg;
153 break;
154 case 'l':
155 for (p = optarg; *p; p++)
156 switch (*p) {
157 case 's':
158 dolink &= ~(LN_HARD|LN_MIXED);
159 dolink |= LN_SYMBOLIC;
160 break;
161 case 'h':
162 dolink &= ~(LN_SYMBOLIC|LN_MIXED);
163 dolink |= LN_HARD;
164 break;
165 case 'm':
166 dolink &= ~(LN_SYMBOLIC|LN_HARD);
167 dolink |= LN_MIXED;
168 break;
169 case 'a':
170 dolink &= ~LN_RELATIVE;
171 dolink |= LN_ABSOLUTE;
172 break;
173 case 'r':
174 dolink &= ~LN_ABSOLUTE;
175 dolink |= LN_RELATIVE;
176 break;
177 default:
178 errx(1, "%c: invalid link type", *p);
179 break;
180 }
181 break;
182 case 'm':
183 if (!(set = setmode(optarg)))
184 errx(1, "%s: invalid file mode", optarg);
185 mode = getmode(set, 0);
186 free(set);
187 break;
188 case 'o':
189 owner = optarg;
190 break;
191 case 'p':
192 dopreserve = 1;
193 break;
194 case 'r':
195 dorename = 1;
196 break;
197 case 'S':
198 stripArgs = (char*)malloc(sizeof(char)*(strlen(optarg)+1));
199 strcpy(stripArgs,optarg);
200 /* fall through; -S implies -s */
201 case 's':
202 dostrip = 1;
203 break;
204 case 'U':
205 unpriv = 1;
206 break;
207 case '?':
208 default:
209 usage();
210 }
211 argc -= optind;
212 argv += optind;
213
214 /* strip and link options make no sense when creating directories */
215 if ((dostrip || dolink) && dodir)
216 usage();
217
218 /* strip and flags make no sense with links */
219 if ((dostrip || flags) && dolink)
220 usage();
221
222 /* must have at least two arguments, except when creating directories */
223 if (argc < 2 && !dodir)
224 usage();
225
226 /* get group and owner id's */
227 if (unpriv)
228 uid = gid = -1;
229 else {
230 if (group && !(gp = getgrnam(group)) &&
231 !isdigit((unsigned char)*group))
232 errx(1, "unknown group %s", group);
233 gid = (group) ? ((gp) ? gp->gr_gid : atoi(group)) : -1;
234 if (owner && !(pp = getpwnam(owner)) &&
235 !isdigit((unsigned char)*owner))
236 errx(1, "unknown user %s", owner);
237 uid = (owner) ? ((pp) ? pp->pw_uid : atoi(owner)) : -1;
238 }
239
240 if (dodir) {
241 for (; *argv != NULL; ++argv)
242 install_dir(*argv);
243 exit (0);
244 }
245
246 no_target = stat(to_name = argv[argc - 1], &to_sb);
247 if (!no_target && S_ISDIR(to_sb.st_mode)) {
248 for (; *argv != to_name; ++argv)
249 install(*argv, to_name, fset, iflags | DIRECTORY);
250 exit(0);
251 }
252
253 /* can't do file1 file2 directory/file */
254 if (argc != 2)
255 usage();
256
257 if (!no_target) {
258 if (stat(*argv, &from_sb))
259 err(1, "%s", *argv);
260 if (!S_ISREG(to_sb.st_mode))
261 errx(1, "%s: not a regular file", to_name);
262 if (!dolink && to_sb.st_dev == from_sb.st_dev &&
263 to_sb.st_ino == from_sb.st_ino)
264 errx(1, "%s and %s are the same file", *argv, to_name);
265 /*
266 * Unlink now... avoid ETXTBSY errors later. Try and turn
267 * off the append/immutable bits -- if we fail, go ahead,
268 * it might work.
269 */
270 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
271 if (to_sb.st_flags & NOCHANGEBITS)
272 (void)chflags(to_name,
273 to_sb.st_flags & ~(NOCHANGEBITS));
274 if (dobackup)
275 backup(to_name);
276 else if (!dorename)
277 (void)unlink(to_name);
278 }
279 install(*argv, to_name, fset, iflags);
280 exit(0);
281 }
282
283 /*
284 * makelink --
285 * make a link from source to destination
286 */
287 void
288 makelink(char *from_name, char *to_name)
289 {
290 char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
291
292 /* Try hard links first */
293 if (dolink & (LN_HARD|LN_MIXED)) {
294 if (link(from_name, to_name) == -1) {
295 if ((dolink & LN_HARD) || errno != EXDEV)
296 err(1, "link %s -> %s", from_name, to_name);
297 }
298 else
299 return;
300 }
301
302 /* Symbolic links */
303 if (dolink & LN_ABSOLUTE) {
304 /* Convert source path to absolute */
305 if (realpath(from_name, src) == NULL)
306 err(1, "%s", src);
307 if (symlink(src, to_name) == -1)
308 err(1, "symlink %s -> %s", src, to_name);
309 return;
310 }
311
312 if (dolink & LN_RELATIVE) {
313 char *s, *d;
314
315 /* Resolve pathnames */
316 if (realpath(from_name, src) == NULL)
317 err(1, "%s", src);
318 if (realpath(to_name, dst) == NULL)
319 err(1, "%s", dst);
320
321 /* trim common path components */
322 for (s = src, d = dst; *s == *d; s++, d++)
323 continue;
324 while (*s != '/')
325 s--, d--;
326
327 /* count the number of directories we need to backtrack */
328 for (++d, lnk[0] = '\0'; *d; d++)
329 if (*d == '/')
330 (void) strcat(lnk, "../");
331
332 (void) strcat(lnk, ++s);
333
334 if (symlink(lnk, dst) == -1)
335 err(1, "symlink %s -> %s", lnk, dst);
336 return;
337 }
338
339 /*
340 * If absolute or relative was not specified,
341 * try the names the user provided
342 */
343 if (symlink(from_name, to_name) == -1)
344 err(1, "symlink %s -> %s", from_name, to_name);
345
346 }
347
348 /*
349 * install --
350 * build a path name and install the file
351 */
352 void
353 install(char *from_name, char *to_name, u_long fset, u_int flags)
354 {
355 struct stat from_sb, to_sb;
356 int devnull, from_fd, to_fd, serrno;
357 char *p, tmpl[MAXPATHLEN], *oto_name;
358
359 /* If try to install NULL file to a directory, fails. */
360 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
361 if (stat(from_name, &from_sb))
362 err(1, "%s", from_name);
363 if (!S_ISREG(from_sb.st_mode))
364 errx(1, "%s: not a regular file", to_name);
365 /* Build the target path. */
366 if (flags & DIRECTORY) {
367 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
368 to_name,
369 (p = strrchr(from_name, '/')) ? ++p : from_name);
370 to_name = pathbuf;
371 }
372 devnull = 0;
373 } else {
374 from_sb.st_flags = 0; /* XXX */
375 devnull = 1;
376 }
377
378 /*
379 * Unlink now... avoid ETXTBSY errors later. Try and turn
380 * off the append/immutable bits -- if we fail, go ahead,
381 * it might work.
382 */
383 if (stat(to_name, &to_sb) == 0 &&
384 to_sb.st_flags & (NOCHANGEBITS))
385 (void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
386 if (dorename) {
387 char *ptr, c, *dir;
388
389 if ((ptr = strrchr(to_name, '/')) != NULL) {
390 c = *++ptr;
391 *ptr = '\0';
392 dir = to_name;
393 } else {
394 c = '\0'; /* pacify gcc */
395 dir = tmpl;
396 *dir = '\0';
397 }
398 (void)snprintf(tmpl, sizeof(tmpl), "%sinst.XXXXXX", dir);
399 if (ptr)
400 *ptr = c;
401 oto_name = to_name;
402 to_name = tmpl;
403
404 } else {
405 oto_name = NULL; /* pacify gcc */
406 if (dobackup)
407 backup(to_name);
408 else
409 (void)unlink(to_name);
410 }
411
412 if (dolink) {
413 makelink(from_name, to_name);
414 return;
415 }
416
417 /* Create target. */
418 if (dorename) {
419 if ((to_fd = mkstemp(to_name)) == -1)
420 err(1, "%s", to_name);
421 } else {
422 if ((to_fd = open(to_name,
423 O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
424 err(1, "%s", to_name);
425 }
426 if (!devnull) {
427 if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
428 (void)unlink(to_name);
429 err(1, "%s", from_name);
430 }
431 copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
432 (void)close(from_fd);
433 }
434
435 if (dostrip) {
436 strip(to_name);
437
438 /*
439 * Re-open our fd on the target, in case we used a strip
440 * that does not work in-place -- like gnu binutils strip.
441 */
442 close(to_fd);
443 if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
444 err(1, "stripping %s", to_name);
445 }
446
447 /*
448 * Set owner, group, mode for target; do the chown first,
449 * chown may lose the setuid bits.
450 */
451 if ((gid != -1 || uid != -1) && fchown(to_fd, uid, gid)) {
452 serrno = errno;
453 (void)unlink(to_name);
454 errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
455 }
456 if (fchmod(to_fd, mode)) {
457 serrno = errno;
458 (void)unlink(to_name);
459 errx(1, "%s: chmod: %s", to_name, strerror(serrno));
460 }
461
462 /*
463 * If provided a set of flags, set them, otherwise, preserve the
464 * flags, except for the dump flag.
465 */
466 if (fchflags(to_fd,
467 flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
468 if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
469 warn("%s: chflags", to_name);
470 }
471
472 /*
473 * Preserve the date of the source file.
474 */
475 if (dopreserve) {
476 struct timeval tv[2];
477
478 #ifdef BSD4_4
479 TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
480 TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
481 #else
482 tv[0].tv_sec = from_sb.st_atime;
483 tv[0].tv_usec = 0;
484 tv[1].tv_sec = from_sb.st_mtime;
485 tv[1].tv_usec = 0;
486 #endif
487 if (futimes(to_fd, tv) == -1)
488 warn("%s: futimes", to_name);
489 }
490
491 (void)close(to_fd);
492
493 if (dorename)
494 if (rename(to_name, oto_name) == -1)
495 err(1, "%s: rename", to_name);
496
497 if (!docopy && !devnull && unlink(from_name))
498 err(1, "%s", from_name);
499 }
500
501 /*
502 * copy --
503 * copy from one file to another
504 */
505 void
506 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
507 {
508 ssize_t nr, nw;
509 int serrno;
510 char *p;
511 char buf[MAXBSIZE];
512
513 /*
514 * There's no reason to do anything other than close the file
515 * now if it's empty, so let's not bother.
516 */
517 if (size > 0) {
518
519 /*
520 * Mmap and write if less than 8M (the limit is so we
521 * don't totally trash memory on big files). This is
522 * really a minor hack, but it wins some CPU back.
523 */
524
525 if (size <= 8 * 1048576) {
526 if ((p = mmap(NULL, (size_t)size, PROT_READ,
527 MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
528 == MAP_FAILED) {
529 goto mmap_failed;
530 }
531 #ifdef MADV_SEQUENTIAL
532 if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
533 && errno != EOPNOTSUPP)
534 warnx("madvise: %s", strerror(errno));
535 #endif
536
537 if (write(to_fd, p, size) != size) {
538 serrno = errno;
539 (void)unlink(to_name);
540 errx(1, "%s: %s",
541 to_name, strerror(serrno));
542 }
543 } else {
544 mmap_failed:
545 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
546 if ((nw = write(to_fd, buf, nr)) != nr) {
547 serrno = errno;
548 (void)unlink(to_name);
549 errx(1, "%s: %s", to_name,
550 strerror(nw > 0 ? EIO : serrno));
551 }
552 }
553 if (nr != 0) {
554 serrno = errno;
555 (void)unlink(to_name);
556 errx(1, "%s: %s", from_name, strerror(serrno));
557 }
558 }
559 }
560 }
561
562 /*
563 * strip --
564 * use strip(1) to strip the target file
565 */
566 void
567 strip(char *to_name)
568 {
569 int serrno, status;
570 char *stripprog;
571
572 switch (vfork()) {
573 case -1:
574 serrno = errno;
575 (void)unlink(to_name);
576 errx(1, "vfork: %s", strerror(serrno));
577 case 0:
578 stripprog = getenv("STRIP");
579 if (stripprog == NULL)
580 stripprog = _PATH_STRIP;
581
582 if (stripArgs) {
583 /* build up a command line and let /bin/sh parse the arguments */
584 char* cmd = (char*)malloc(sizeof(char)*
585 (3+strlen(stripprog)+
586 strlen(stripArgs)+
587 strlen(to_name)));
588
589 sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
590
591 execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
592 } else
593 execlp(stripprog, "strip", to_name, NULL);
594
595 warn("%s", stripprog);
596 _exit(1);
597 default:
598 if (wait(&status) == -1 || status)
599 (void)unlink(to_name);
600 }
601 }
602
603 /*
604 * backup file "to_name" to to_name.suffix
605 * if suffix contains a "%", it's taken as a printf(3) pattern
606 * used for a numbered backup.
607 */
608 void
609 backup(const char *to_name)
610 {
611 char backup[FILENAME_MAX];
612
613 if (numberedbackup) {
614 /* Do numbered backup */
615 int cnt;
616 char suffix_expanded[FILENAME_MAX];
617
618 cnt=0;
619 do {
620 (void)snprintf(suffix_expanded, FILENAME_MAX, suffix, cnt);
621 (void)snprintf(backup, FILENAME_MAX, "%s%s",
622 to_name, suffix_expanded);
623 cnt++;
624 } while (access(backup, F_OK)==0);
625 } else {
626 /* Do simple backup */
627 (void)snprintf(backup, FILENAME_MAX, "%s%s", to_name, suffix);
628 }
629
630 (void)rename(to_name, backup);
631 }
632
633 /*
634 * install_dir --
635 * build directory hierarchy
636 */
637 void
638 install_dir(char *path)
639 {
640 char *p;
641 struct stat sb;
642 int ch;
643
644 for (p = path;; ++p)
645 if (!*p || (p != path && *p == '/')) {
646 ch = *p;
647 *p = '\0';
648 if (stat(path, &sb)) {
649 if (errno != ENOENT || mkdir(path, 0777) < 0) {
650 err(1, "%s", path);
651 /* NOTREACHED */
652 }
653 }
654 if (!(*p = ch))
655 break;
656 }
657
658 if (((gid != -1 || uid != -1) && chown(path, uid, gid)) ||
659 chmod(path, mode)) {
660 warn("%s", path);
661 }
662 }
663
664 /*
665 * usage --
666 * print a usage message and die
667 */
668 void
669 usage(void)
670 {
671 (void)fprintf(stderr, "\
672 usage: install [-Ubcprs] [-B suffix] [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 file2\n\
673 install [-Ubcprs] [-B suffix] [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 ... fileN directory\n\
674 install [-Up] -d [-m mode] [-o owner] [-g group] directory ...\n");
675 exit(1);
676 }
677