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