xinstall.c revision 1.79 1 /* $NetBSD: xinstall.c,v 1.79 2003/08/07 11:17:50 agc 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. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #if HAVE_CONFIG_H
33 #include "config.h"
34 #else
35 #define HAVE_FUTIMES 1
36 #define HAVE_STRUCT_STAT_ST_FLAGS 1
37 #endif
38
39 #include <sys/cdefs.h>
40 #if defined(__COPYRIGHT) && !defined(lint)
41 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
42 The Regents of the University of California. All rights reserved.\n");
43 #endif /* not lint */
44
45 #if defined(__RCSID) && !defined(lint)
46 #if 0
47 static char sccsid[] = "@(#)xinstall.c 8.1 (Berkeley) 7/21/93";
48 #else
49 __RCSID("$NetBSD: xinstall.c,v 1.79 2003/08/07 11:17:50 agc Exp $");
50 #endif
51 #endif /* not lint */
52
53 #include <sys/param.h>
54 #include <sys/mman.h>
55 #include <sys/stat.h>
56 #include <sys/wait.h>
57
58 #include <ctype.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <grp.h>
63 #include <libgen.h>
64 #include <paths.h>
65 #include <pwd.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 #include <vis.h>
71
72 #include "pathnames.h"
73 #include "stat_flags.h"
74 #include "mtree.h"
75
76 #define STRIP_ARGS_MAX 32
77 #define BACKUP_SUFFIX ".old"
78
79 int dobackup, docopy, dodir, dostrip, dolink, dopreserve, dorename,
80 dounpriv;
81 int numberedbackup;
82 int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
83 char pathbuf[MAXPATHLEN];
84 id_t uid, gid;
85 char *group, *owner, *fflags, *tags;
86 FILE *metafp;
87 char *metafile;
88 u_long fileflags;
89 char *stripArgs;
90 char *afterinstallcmd;
91 char *suffix = BACKUP_SUFFIX;
92 char *destdir;
93
94 #define LN_ABSOLUTE 0x01
95 #define LN_RELATIVE 0x02
96 #define LN_HARD 0x04
97 #define LN_SYMBOLIC 0x08
98 #define LN_MIXED 0x10
99
100 #define DIRECTORY 0x01 /* Tell install it's a directory. */
101 #define SETFLAGS 0x02 /* Tell install to set flags. */
102 #define HASUID 0x04 /* Tell install the uid was given */
103 #define HASGID 0x08 /* Tell install the gid was given */
104
105 void afterinstall(const char *, const char *, int);
106 void backup(const char *);
107 void copy(int, char *, int, char *, off_t);
108 int do_link(char *, char *);
109 void do_symlink(char *, char *);
110 void install(char *, char *, u_int);
111 void install_dir(char *, u_int);
112 int main(int, char *[]);
113 void makelink(char *, char *);
114 void metadata_log(const char *, const char *, struct timeval *, const char *);
115 int parseid(char *, id_t *);
116 void strip(char *);
117 void usage(void);
118 char *xbasename(char *);
119 char *xdirname(char *);
120
121 int
122 main(int argc, char *argv[])
123 {
124 struct stat from_sb, to_sb;
125 void *set;
126 u_int iflags;
127 int ch, no_target;
128 char *p, *to_name;
129
130 setprogname(argv[0]);
131
132 iflags = 0;
133 while ((ch = getopt(argc, argv, "a:cbB:dD:f:g:l:m:M:N:o:prsS:T:U"))
134 != -1)
135 switch((char)ch) {
136 case 'a':
137 afterinstallcmd = strdup(optarg);
138 if (afterinstallcmd == NULL)
139 errx(1, "%s", strerror(ENOMEM));
140 break;
141 case 'B':
142 suffix = optarg;
143 numberedbackup = 0;
144 {
145 /* Check if given suffix really generates
146 different suffixes - catch e.g. ".%" */
147 char suffix_expanded0[FILENAME_MAX],
148 suffix_expanded1[FILENAME_MAX];
149 (void)snprintf(suffix_expanded0, FILENAME_MAX,
150 suffix, 0);
151 (void)snprintf(suffix_expanded1, FILENAME_MAX,
152 suffix, 1);
153 if (strcmp(suffix_expanded0, suffix_expanded1)
154 != 0)
155 numberedbackup = 1;
156 }
157 /* fall through; -B implies -b */
158 /*FALLTHROUGH*/
159 case 'b':
160 dobackup = 1;
161 break;
162 case 'c':
163 docopy = 1;
164 break;
165 case 'd':
166 dodir = 1;
167 break;
168 case 'D':
169 destdir = optarg;
170 break;
171 #if !HAVE_CONFIG_H
172 case 'f':
173 fflags = optarg;
174 break;
175 #endif
176 case 'g':
177 group = optarg;
178 break;
179 case 'l':
180 for (p = optarg; *p; p++)
181 switch (*p) {
182 case 's':
183 dolink &= ~(LN_HARD|LN_MIXED);
184 dolink |= LN_SYMBOLIC;
185 break;
186 case 'h':
187 dolink &= ~(LN_SYMBOLIC|LN_MIXED);
188 dolink |= LN_HARD;
189 break;
190 case 'm':
191 dolink &= ~(LN_SYMBOLIC|LN_HARD);
192 dolink |= LN_MIXED;
193 break;
194 case 'a':
195 dolink &= ~LN_RELATIVE;
196 dolink |= LN_ABSOLUTE;
197 break;
198 case 'r':
199 dolink &= ~LN_ABSOLUTE;
200 dolink |= LN_RELATIVE;
201 break;
202 default:
203 errx(1, "%c: invalid link type", *p);
204 /* NOTREACHED */
205 }
206 break;
207 case 'm':
208 if (!(set = setmode(optarg)))
209 errx(1, "%s: invalid file mode", optarg);
210 mode = getmode(set, 0);
211 free(set);
212 break;
213 case 'M':
214 metafile = optarg;
215 break;
216 case 'N':
217 if (! setup_getid(optarg))
218 errx(1,
219 "Unable to use user and group databases in `%s'",
220 optarg);
221 break;
222 case 'o':
223 owner = optarg;
224 break;
225 case 'p':
226 dopreserve = 1;
227 break;
228 case 'r':
229 dorename = 1;
230 break;
231 case 'S':
232 stripArgs = strdup(optarg);
233 if (stripArgs == NULL)
234 errx(1, "%s", strerror(ENOMEM));
235 /* fall through; -S implies -s */
236 /*FALLTHROUGH*/
237 case 's':
238 dostrip = 1;
239 break;
240 case 'T':
241 tags = optarg;
242 break;
243 case 'U':
244 dounpriv = 1;
245 break;
246 case '?':
247 default:
248 usage();
249 }
250 argc -= optind;
251 argv += optind;
252
253 /* strip and link options make no sense when creating directories */
254 if ((dostrip || dolink) && dodir)
255 usage();
256
257 /* strip and flags make no sense with links */
258 if ((dostrip || fflags) && dolink)
259 usage();
260
261 /* must have at least two arguments, except when creating directories */
262 if (argc < 2 && !dodir)
263 usage();
264
265 /* get group and owner id's */
266 if (group && !dounpriv) {
267 if (gid_from_group(group, &gid) == -1 && ! parseid(group, &gid))
268 errx(1, "unknown group %s", group);
269 iflags |= HASGID;
270 }
271 if (owner && !dounpriv) {
272 if (uid_from_user(owner, &uid) == -1 && ! parseid(owner, &uid))
273 errx(1, "unknown user %s", owner);
274 iflags |= HASUID;
275 }
276
277 #if !HAVE_CONFIG_H
278 if (fflags && !dounpriv) {
279 if (string_to_flags(&fflags, &fileflags, NULL))
280 errx(1, "%s: invalid flag", fflags);
281 iflags |= SETFLAGS;
282 }
283 #endif
284
285 if (metafile) {
286 if ((metafp = fopen(metafile, "a")) == NULL)
287 warn("open %s", metafile);
288 }
289
290 if (dodir) {
291 for (; *argv != NULL; ++argv)
292 install_dir(*argv, iflags);
293 exit (0);
294 }
295
296 no_target = stat(to_name = argv[argc - 1], &to_sb);
297 if (!no_target && S_ISDIR(to_sb.st_mode)) {
298 for (; *argv != to_name; ++argv)
299 install(*argv, to_name, iflags | DIRECTORY);
300 exit(0);
301 }
302
303 /* can't do file1 file2 directory/file */
304 if (argc != 2)
305 usage();
306
307 if (!no_target) {
308 /* makelink() handles checks for links */
309 if (!dolink) {
310 if (stat(*argv, &from_sb))
311 err(1, "%s: stat", *argv);
312 if (!S_ISREG(to_sb.st_mode))
313 errx(1, "%s: not a regular file", to_name);
314 if (to_sb.st_dev == from_sb.st_dev &&
315 to_sb.st_ino == from_sb.st_ino)
316 errx(1, "%s and %s are the same file", *argv,
317 to_name);
318 }
319 /*
320 * Unlink now... avoid ETXTBSY errors later. Try and turn
321 * off the append/immutable bits -- if we fail, go ahead,
322 * it might work.
323 */
324 #if !HAVE_CONFIG_H
325 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
326 if (to_sb.st_flags & NOCHANGEBITS)
327 (void)chflags(to_name,
328 to_sb.st_flags & ~(NOCHANGEBITS));
329 #endif
330 if (dobackup)
331 backup(to_name);
332 else if (!dorename)
333 (void)unlink(to_name);
334 }
335 install(*argv, to_name, iflags);
336 exit(0);
337 }
338
339 /*
340 * parseid --
341 * parse uid or gid from arg into id, returning non-zero if successful
342 */
343 int
344 parseid(char *name, id_t *id)
345 {
346 char *ep;
347
348 errno = 0;
349 *id = (id_t)strtoul(name, &ep, 10);
350 if (errno || *ep != '\0')
351 return (0);
352 return (1);
353 }
354
355 /*
356 * do_link --
357 * make a hard link, obeying dorename if set
358 * return -1 on failure
359 */
360 int
361 do_link(char *from_name, char *to_name)
362 {
363 char tmpl[MAXPATHLEN];
364 int ret;
365
366 if (dorename) {
367 (void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
368 xdirname(to_name));
369 /* This usage is safe. The linker will bitch anyway. */
370 if (mktemp(tmpl) == NULL)
371 err(1, "%s: mktemp", tmpl);
372 ret = link(from_name, tmpl);
373 if (ret == 0) {
374 ret = rename(tmpl, to_name);
375 if (ret < 0)
376 /* remove temporary link before exiting */
377 (void)unlink(tmpl);
378 }
379 return (ret);
380 } else
381 return (link(from_name, to_name));
382 }
383
384 /*
385 * do_symlink --
386 * make a symbolic link, obeying dorename if set
387 * exit on failure
388 */
389 void
390 do_symlink(char *from_name, char *to_name)
391 {
392 char tmpl[MAXPATHLEN];
393
394 if (dorename) {
395 (void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
396 xdirname(to_name));
397 /* This usage is safe. The linker will bitch anyway. */
398 if (mktemp(tmpl) == NULL)
399 err(1, "%s: mktemp", tmpl);
400
401 if (symlink(from_name, tmpl) == -1)
402 err(1, "symlink %s -> %s", from_name, tmpl);
403 if (rename(tmpl, to_name) == -1) {
404 /* remove temporary link before exiting */
405 (void)unlink(tmpl);
406 err(1, "%s: rename", to_name);
407 }
408 } else {
409 if (symlink(from_name, to_name) == -1)
410 err(1, "symlink %s -> %s", from_name, to_name);
411 }
412 }
413
414 /*
415 * makelink --
416 * make a link from source to destination
417 */
418 void
419 makelink(char *from_name, char *to_name)
420 {
421 char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
422 struct stat to_sb;
423
424 /* Try hard links first */
425 if (dolink & (LN_HARD|LN_MIXED)) {
426 if (do_link(from_name, to_name) == -1) {
427 if ((dolink & LN_HARD) || errno != EXDEV)
428 err(1, "link %s -> %s", from_name, to_name);
429 } else {
430 if (stat(to_name, &to_sb))
431 err(1, "%s: stat", to_name);
432 if (S_ISREG(to_sb.st_mode)) {
433 /* XXX: only metalog hardlinked files */
434 int omode;
435 char *oowner, *ogroup, *offlags;
436
437 /* XXX: use underlying perms */
438 omode = mode;
439 mode = (to_sb.st_mode & 0777);
440 oowner = owner;
441 owner = NULL;
442 ogroup = group;
443 group = NULL;
444 offlags = fflags;
445 fflags = NULL;
446 metadata_log(to_name, "file", NULL, NULL);
447 mode = omode;
448 owner = oowner;
449 group = ogroup;
450 fflags = offlags;
451 }
452 return;
453 }
454 }
455
456 /* Symbolic links */
457 if (dolink & LN_ABSOLUTE) {
458 /* Convert source path to absolute */
459 if (realpath(from_name, src) == NULL)
460 err(1, "%s: realpath", from_name);
461 do_symlink(src, to_name);
462 metadata_log(to_name, "link", NULL, src);
463 return;
464 }
465
466 if (dolink & LN_RELATIVE) {
467 char *cp, *d, *s;
468
469 /* Resolve pathnames */
470 if (realpath(from_name, src) == NULL)
471 err(1, "%s: realpath", from_name);
472
473 /*
474 * The last component of to_name may be a symlink,
475 * so use realpath to resolve only the directory.
476 */
477 cp = xdirname(to_name);
478 if (realpath(cp, dst) == NULL)
479 err(1, "%s: realpath", cp);
480 /* .. and add the last component */
481 if (strcmp(dst, "/") != 0) {
482 if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
483 errx(1, "resolved pathname too long");
484 }
485 cp = xbasename(to_name);
486 if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
487 errx(1, "resolved pathname too long");
488
489 /* trim common path components */
490 for (s = src, d = dst; *s == *d; s++, d++)
491 continue;
492 while (*s != '/')
493 s--, d--;
494
495 /* count the number of directories we need to backtrack */
496 for (++d, lnk[0] = '\0'; *d; d++)
497 if (*d == '/')
498 (void)strlcat(lnk, "../", sizeof(lnk));
499
500 (void)strlcat(lnk, ++s, sizeof(lnk));
501
502 do_symlink(lnk, dst);
503 metadata_log(dst, "link", NULL, lnk);
504 return;
505 }
506
507 /*
508 * If absolute or relative was not specified,
509 * try the names the user provided
510 */
511 do_symlink(from_name, to_name);
512 metadata_log(to_name, "link", NULL, from_name);
513 }
514
515 /*
516 * install --
517 * build a path name and install the file
518 */
519 void
520 install(char *from_name, char *to_name, u_int flags)
521 {
522 struct stat from_sb;
523 #if !HAVE_CONFIG_H
524 struct stat to_sb;
525 #endif
526 struct timeval tv[2];
527 int devnull, from_fd, to_fd, serrno, tmpmode;
528 char *p, tmpl[MAXPATHLEN], *oto_name;
529
530 if (!dolink) {
531 /* ensure that from_sb & tv are sane if !dolink */
532 if (stat(from_name, &from_sb))
533 err(1, "%s: stat", from_name);
534 #ifdef BSD4_4
535 TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
536 TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
537 #else
538 tv[0].tv_sec = from_sb.st_atime;
539 tv[0].tv_usec = 0;
540 tv[1].tv_sec = from_sb.st_mtime;
541 tv[1].tv_usec = 0;
542 #endif
543 }
544
545 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
546 if (!dolink) {
547 if (!S_ISREG(from_sb.st_mode))
548 errx(1, "%s: not a regular file", from_name);
549 }
550 /* Build the target path. */
551 if (flags & DIRECTORY) {
552 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
553 to_name,
554 (p = strrchr(from_name, '/')) ? ++p : from_name);
555 to_name = pathbuf;
556 }
557 devnull = 0;
558 } else {
559 #if HAVE_STRUCT_STAT_ST_FLAGS
560 from_sb.st_flags = 0; /* XXX */
561 #endif
562 devnull = 1;
563 }
564
565 /*
566 * Unlink now... avoid ETXTBSY errors later. Try and turn
567 * off the append/immutable bits -- if we fail, go ahead,
568 * it might work.
569 */
570 #if !HAVE_CONFIG_H
571 if (stat(to_name, &to_sb) == 0 &&
572 to_sb.st_flags & (NOCHANGEBITS))
573 (void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
574 #endif
575 if (dorename) {
576 (void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
577 xdirname(to_name));
578 oto_name = to_name;
579 to_name = tmpl;
580 } else {
581 oto_name = NULL; /* pacify gcc */
582 if (dobackup)
583 backup(to_name);
584 else
585 (void)unlink(to_name);
586 }
587
588 if (dolink) {
589 makelink(from_name, dorename ? oto_name : to_name);
590 return;
591 }
592
593 /* Create target. */
594 if (dorename) {
595 if ((to_fd = mkstemp(to_name)) == -1)
596 err(1, "%s: mkstemp", to_name);
597 } else {
598 if ((to_fd = open(to_name,
599 O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
600 err(1, "%s: open", to_name);
601 }
602 if (!devnull) {
603 if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
604 (void)unlink(to_name);
605 err(1, "%s: open", from_name);
606 }
607 copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
608 (void)close(from_fd);
609 }
610
611 if (dostrip) {
612 strip(to_name);
613
614 /*
615 * Re-open our fd on the target, in case we used a strip
616 * that does not work in-place -- like gnu binutils strip.
617 */
618 close(to_fd);
619 if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
620 err(1, "stripping %s", to_name);
621 }
622
623 if (afterinstallcmd != NULL) {
624 afterinstall(afterinstallcmd, to_name, 1);
625
626 /*
627 * Re-open our fd on the target, in case we used an
628 * after-install command that does not work in-place
629 */
630 close(to_fd);
631 if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
632 err(1, "running after install command on %s", to_name);
633 }
634
635 /*
636 * Set owner, group, mode for target; do the chown first,
637 * chown may lose the setuid bits.
638 */
639 if (!dounpriv &&
640 (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
641 serrno = errno;
642 (void)unlink(to_name);
643 errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
644 }
645 tmpmode = mode;
646 if (dounpriv)
647 tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
648 if (fchmod(to_fd, tmpmode) == -1) {
649 serrno = errno;
650 (void)unlink(to_name);
651 errx(1, "%s: chmod: %s", to_name, strerror(serrno));
652 }
653
654 /*
655 * Preserve the date of the source file.
656 */
657 if (dopreserve) {
658 #if HAVE_FUTIMES
659 if (futimes(to_fd, tv) == -1)
660 warn("%s: futimes", to_name);
661 #else
662 if (utimes(to_name, tv) == -1)
663 warn("%s: utimes", to_name);
664 #endif
665 }
666
667 (void)close(to_fd);
668
669 if (dorename) {
670 if (rename(to_name, oto_name) == -1)
671 err(1, "%s: rename", to_name);
672 to_name = oto_name;
673 }
674
675 if (!docopy && !devnull && unlink(from_name))
676 err(1, "%s: unlink", from_name);
677
678 /*
679 * If provided a set of flags, set them, otherwise, preserve the
680 * flags, except for the dump flag.
681 */
682 #if !HAVE_CONFIG_H
683 if (!dounpriv && chflags(to_name,
684 flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
685 {
686 if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
687 warn("%s: chflags", to_name);
688 }
689 #endif
690
691 metadata_log(to_name, "file", tv, NULL);
692 }
693
694 /*
695 * copy --
696 * copy from one file to another
697 */
698 void
699 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
700 {
701 ssize_t nr, nw;
702 int serrno;
703 char *p;
704 char buf[MAXBSIZE];
705
706 /*
707 * There's no reason to do anything other than close the file
708 * now if it's empty, so let's not bother.
709 */
710 if (size > 0) {
711
712 /*
713 * Mmap and write if less than 8M (the limit is so we
714 * don't totally trash memory on big files). This is
715 * really a minor hack, but it wins some CPU back.
716 */
717
718 if (size <= 8 * 1048576) {
719 if ((p = mmap(NULL, (size_t)size, PROT_READ,
720 MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
721 == MAP_FAILED) {
722 goto mmap_failed;
723 }
724 #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
725 if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
726 && errno != EOPNOTSUPP)
727 warnx("madvise: %s", strerror(errno));
728 #endif
729
730 if (write(to_fd, p, size) != size) {
731 serrno = errno;
732 (void)unlink(to_name);
733 errx(1, "%s: write: %s",
734 to_name, strerror(serrno));
735 }
736 } else {
737 mmap_failed:
738 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
739 if ((nw = write(to_fd, buf, nr)) != nr) {
740 serrno = errno;
741 (void)unlink(to_name);
742 errx(1, "%s: write: %s", to_name,
743 strerror(nw > 0 ? EIO : serrno));
744 }
745 }
746 if (nr != 0) {
747 serrno = errno;
748 (void)unlink(to_name);
749 errx(1, "%s: read: %s", from_name, strerror(serrno));
750 }
751 }
752 }
753 }
754
755 /*
756 * strip --
757 * use strip(1) to strip the target file
758 */
759 void
760 strip(char *to_name)
761 {
762 int serrno, status;
763 char *stripprog;
764
765 switch (vfork()) {
766 case -1:
767 serrno = errno;
768 (void)unlink(to_name);
769 errx(1, "vfork: %s", strerror(serrno));
770 /*NOTREACHED*/
771 case 0:
772 stripprog = getenv("STRIP");
773 if (stripprog == NULL)
774 stripprog = _PATH_STRIP;
775
776 if (stripArgs) {
777 /*
778 * build up a command line and let /bin/sh
779 * parse the arguments
780 */
781 char* cmd = (char*)malloc(sizeof(char)*
782 (3+strlen(stripprog)+
783 strlen(stripArgs)+
784 strlen(to_name)));
785
786 if (cmd == NULL)
787 errx(1, "%s", strerror(ENOMEM));
788
789 sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
790
791 execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
792 } else
793 execlp(stripprog, "strip", to_name, NULL);
794
795 warn("%s: exec of strip", stripprog);
796 _exit(1);
797 /*NOTREACHED*/
798 default:
799 if (wait(&status) == -1 || status)
800 (void)unlink(to_name);
801 }
802 }
803
804 /*
805 * afterinstall --
806 * run provided command on the target file or directory after it's been
807 * installed and stripped, but before permissions are set or it's renamed
808 */
809 void
810 afterinstall(const char *command, const char *to_name, int errunlink)
811 {
812 int serrno, status;
813 char *cmd;
814
815 switch (vfork()) {
816 case -1:
817 serrno = errno;
818 if (errunlink)
819 (void)unlink(to_name);
820 errx(1, "vfork: %s", strerror(serrno));
821 /*NOTREACHED*/
822 case 0:
823 /*
824 * build up a command line and let /bin/sh
825 * parse the arguments
826 */
827 cmd = (char*)malloc(sizeof(char)*
828 (2+strlen(command)+
829 strlen(to_name)));
830
831 if (cmd == NULL)
832 errx(1, "%s", strerror(ENOMEM));
833
834 sprintf(cmd, "%s %s", command, to_name);
835
836 execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
837
838 warn("%s: exec of after install command", command);
839 _exit(1);
840 /*NOTREACHED*/
841 default:
842 if ((wait(&status) == -1 || status) && errunlink)
843 (void)unlink(to_name);
844 }
845 }
846
847 /*
848 * backup --
849 * backup file "to_name" to to_name.suffix
850 * if suffix contains a "%", it's taken as a printf(3) pattern
851 * used for a numbered backup.
852 */
853 void
854 backup(const char *to_name)
855 {
856 char bname[FILENAME_MAX];
857
858 if (numberedbackup) {
859 /* Do numbered backup */
860 int cnt;
861 char suffix_expanded[FILENAME_MAX];
862
863 cnt=0;
864 do {
865 (void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
866 cnt);
867 (void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
868 suffix_expanded);
869 cnt++;
870 } while (access(bname, F_OK) == 0);
871 } else {
872 /* Do simple backup */
873 (void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
874 }
875
876 (void)rename(to_name, bname);
877 }
878
879 /*
880 * install_dir --
881 * build directory hierarchy
882 */
883 void
884 install_dir(char *path, u_int flags)
885 {
886 char *p;
887 struct stat sb;
888 int ch;
889
890 for (p = path;; ++p)
891 if (!*p || (p != path && *p == '/')) {
892 ch = *p;
893 *p = '\0';
894 if (stat(path, &sb)) {
895 if (errno != ENOENT || mkdir(path, 0777) < 0) {
896 err(1, "%s: mkdir", path);
897 }
898 }
899 if (!(*p = ch))
900 break;
901 }
902
903 if (afterinstallcmd != NULL)
904 afterinstall(afterinstallcmd, path, 0);
905
906 if (!dounpriv && (
907 ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
908 || chmod(path, mode) == -1 )) {
909 warn("%s: chown/chmod", path);
910 }
911 metadata_log(path, "dir", NULL, NULL);
912 }
913
914 /*
915 * metadata_log --
916 * if metafp is not NULL, output mtree(8) full path name and settings to
917 * metafp, to allow permissions to be set correctly by other tools.
918 */
919 void
920 metadata_log(const char *path, const char *type, struct timeval *tv,
921 const char *link)
922 {
923 static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
924 char *buf, *p;
925 size_t destlen;
926 struct flock metalog_lock;
927
928 if (!metafp)
929 return;
930 buf = (char *)malloc(4 * strlen(path) + 1); /* buf for strsvis(3) */
931 if (buf == NULL) {
932 warnx("%s", strerror(ENOMEM));
933 return;
934 }
935 /* lock log file */
936 metalog_lock.l_start = 0;
937 metalog_lock.l_len = 0;
938 metalog_lock.l_whence = SEEK_SET;
939 metalog_lock.l_type = F_WRLCK;
940 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
941 warn("can't lock %s", metafile);
942 return;
943 }
944
945 strsvis(buf, path, VIS_CSTYLE, extra); /* encode name */
946 p = buf; /* remove destdir */
947 if (destdir) {
948 destlen = strlen(destdir);
949 if (strncmp(p, destdir, destlen) == 0 &&
950 (p[destlen] == '/' || p[destlen] == '\0'))
951 p += destlen;
952 }
953 while (*p && *p == '/') /* remove leading /s */
954 p++;
955 /* print details */
956 fprintf(metafp, ".%s%s type=%s mode=%#o", *p ? "/" : "", p, type, mode);
957 if (link)
958 fprintf(metafp, " link=%s", link);
959 if (owner)
960 fprintf(metafp, " uname=%s", owner);
961 if (group)
962 fprintf(metafp, " gname=%s", group);
963 if (fflags)
964 fprintf(metafp, " flags=%s", fflags);
965 if (tags)
966 fprintf(metafp, " tags=%s", tags);
967 if (tv != NULL && dopreserve)
968 fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
969 fputc('\n', metafp);
970 fflush(metafp); /* flush output */
971 /* unlock log file */
972 metalog_lock.l_type = F_UNLCK;
973 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
974 warn("can't unlock %s", metafile);
975 }
976 free(buf);
977 }
978
979 /*
980 * xbasename --
981 * libc basename(3) that returns a pointer to a static buffer
982 * instead of overwriting that passed-in string.
983 */
984 char *
985 xbasename(char *path)
986 {
987 static char tmp[MAXPATHLEN];
988
989 (void)strlcpy(tmp, path, sizeof(tmp));
990 return (basename(tmp));
991 }
992
993 /*
994 * xdirname --
995 * libc dirname(3) that returns a pointer to a static buffer
996 * instead of overwriting that passed-in string.
997 */
998 char *
999 xdirname(char *path)
1000 {
1001 static char tmp[MAXPATHLEN];
1002
1003 (void)strlcpy(tmp, path, sizeof(tmp));
1004 return (dirname(tmp));
1005 }
1006
1007 /*
1008 * usage --
1009 * print a usage message and die
1010 */
1011 void
1012 usage(void)
1013 {
1014 const char *prog;
1015
1016 prog = getprogname();
1017
1018 (void)fprintf(stderr,
1019 "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1020 " [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
1021 " [-l linkflags] [-S stripflags] file1 file2\n"
1022 " %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1023 " [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
1024 " [-l linkflags] [-S stripflags] file1 ... fileN directory\n"
1025 " %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
1026 " [-N dbdir] [-o owner] [-g group] directory ...\n",
1027 prog, prog, prog);
1028 exit(1);
1029 }
1030