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