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