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