GPIO:further development
[minix.git] / usr.bin / xinstall / xinstall.c
blob1d479fd65e78d8bbea6ef543fb75d8b409e64f62
1 /* $NetBSD: xinstall.c,v 1.115 2011/09/06 18:50:32 joerg Exp $ */
3 /*
4 * Copyright (c) 1987, 1993
5 * The Regents of the University of California. All rights reserved.
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.
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.
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
39 #include <sys/cdefs.h>
40 #if defined(__COPYRIGHT) && !defined(lint)
41 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\
42 The Regents of the University of California. All rights reserved.");
43 #endif /* not lint */
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.115 2011/09/06 18:50:32 joerg Exp $");
50 #endif
51 #endif /* not lint */
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 #include <sys/time.h>
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <grp.h>
65 #include <libgen.h>
66 #include <paths.h>
67 #include <pwd.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72 #include <util.h>
73 #include <vis.h>
75 #include <md5.h>
76 #include <rmd160.h>
77 #include <sha1.h>
78 #include <sha2.h>
80 #include "pathnames.h"
81 #include "mtree.h"
83 #define STRIP_ARGS_MAX 32
84 #define BACKUP_SUFFIX ".old"
86 static int dobackup, dodir, dostrip, dolink, dopreserve, dorename, dounpriv;
87 static int haveopt_f, haveopt_g, haveopt_m, haveopt_o;
88 static int numberedbackup;
89 static int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
90 static char pathbuf[MAXPATHLEN];
91 static uid_t uid = -1;
92 static gid_t gid = -1;
93 static char *group, *owner, *fflags, *tags;
94 static FILE *metafp;
95 static char *metafile;
96 static u_long fileflags;
97 static char *stripArgs;
98 static char *afterinstallcmd;
99 static const char *suffix = BACKUP_SUFFIX;
100 static char *destdir;
102 enum {
103 DIGEST_NONE = 0,
104 DIGEST_MD5,
105 DIGEST_RMD160,
106 DIGEST_SHA1,
107 DIGEST_SHA256,
108 DIGEST_SHA384,
109 DIGEST_SHA512,
110 } digesttype = DIGEST_NONE;
112 static char *digest;
114 #define LN_ABSOLUTE 0x01
115 #define LN_RELATIVE 0x02
116 #define LN_HARD 0x04
117 #define LN_SYMBOLIC 0x08
118 #define LN_MIXED 0x10
120 #define DIRECTORY 0x01 /* Tell install it's a directory. */
121 #define SETFLAGS 0x02 /* Tell install to set flags. */
122 #define HASUID 0x04 /* Tell install the uid was given */
123 #define HASGID 0x08 /* Tell install the gid was given */
125 static void afterinstall(const char *, const char *, int);
126 static void backup(const char *);
127 static char *copy(int, char *, int, char *, off_t);
128 static int do_link(char *, char *);
129 static void do_symlink(char *, char *);
130 static void install(char *, char *, u_int);
131 static void install_dir(char *, u_int);
132 static void makelink(char *, char *);
133 static void metadata_log(const char *, const char *, struct timeval *,
134 const char *, const char *, off_t);
135 static int parseid(char *, id_t *);
136 static void strip(char *);
137 __dead static void usage(void);
138 static char *xbasename(char *);
139 static char *xdirname(char *);
142 main(int argc, char *argv[])
144 struct stat from_sb, to_sb;
145 void *set;
146 u_int iflags;
147 int ch, no_target;
148 char *p, *to_name;
150 setprogname(argv[0]);
152 iflags = 0;
153 while ((ch = getopt(argc, argv, "a:cbB:dD:f:g:h:l:m:M:N:o:prsS:T:U"))
154 != -1)
155 switch((char)ch) {
156 case 'a':
157 afterinstallcmd = strdup(optarg);
158 if (afterinstallcmd == NULL)
159 errx(1, "%s", strerror(ENOMEM));
160 break;
161 case 'B':
162 suffix = optarg;
163 numberedbackup = 0;
165 /* Check if given suffix really generates
166 different suffixes - catch e.g. ".%" */
167 char suffix_expanded0[FILENAME_MAX],
168 suffix_expanded1[FILENAME_MAX];
169 (void)snprintf(suffix_expanded0, FILENAME_MAX,
170 suffix, 0);
171 (void)snprintf(suffix_expanded1, FILENAME_MAX,
172 suffix, 1);
173 if (strcmp(suffix_expanded0, suffix_expanded1)
174 != 0)
175 numberedbackup = 1;
177 /* fall through; -B implies -b */
178 /*FALLTHROUGH*/
179 case 'b':
180 dobackup = 1;
181 break;
182 case 'c':
183 /* ignored; was "docopy" which is now the default. */
184 break;
185 case 'd':
186 dodir = 1;
187 break;
188 case 'D':
189 destdir = optarg;
190 break;
191 #if ! HAVE_NBTOOL_CONFIG_H
192 case 'f':
193 haveopt_f = 1;
194 fflags = optarg;
195 break;
196 #endif
197 case 'g':
198 haveopt_g = 1;
199 group = optarg;
200 break;
201 case 'h':
202 digest = optarg;
203 break;
204 case 'l':
205 for (p = optarg; *p; p++)
206 switch (*p) {
207 case 's':
208 dolink &= ~(LN_HARD|LN_MIXED);
209 dolink |= LN_SYMBOLIC;
210 break;
211 case 'h':
212 dolink &= ~(LN_SYMBOLIC|LN_MIXED);
213 dolink |= LN_HARD;
214 break;
215 case 'm':
216 dolink &= ~(LN_SYMBOLIC|LN_HARD);
217 dolink |= LN_MIXED;
218 break;
219 case 'a':
220 dolink &= ~LN_RELATIVE;
221 dolink |= LN_ABSOLUTE;
222 break;
223 case 'r':
224 dolink &= ~LN_ABSOLUTE;
225 dolink |= LN_RELATIVE;
226 break;
227 default:
228 errx(1, "%c: invalid link type", *p);
229 /* NOTREACHED */
231 break;
232 case 'm':
233 haveopt_m = 1;
234 if (!(set = setmode(optarg)))
235 err(1, "Cannot set file mode `%s'", optarg);
236 mode = getmode(set, 0);
237 free(set);
238 break;
239 case 'M':
240 metafile = optarg;
241 break;
242 case 'N':
243 if (! setup_getid(optarg))
244 errx(1,
245 "Unable to use user and group databases in `%s'",
246 optarg);
247 break;
248 case 'o':
249 haveopt_o = 1;
250 owner = optarg;
251 break;
252 case 'p':
253 dopreserve = 1;
254 #ifdef __minix
255 warn("Minix lacks support for futimes(3)/utimes(2)");
256 #endif
257 break;
258 case 'r':
259 dorename = 1;
260 break;
261 case 'S':
262 stripArgs = strdup(optarg);
263 if (stripArgs == NULL)
264 errx(1, "%s", strerror(ENOMEM));
265 /* fall through; -S implies -s */
266 /*FALLTHROUGH*/
267 case 's':
268 dostrip = 1;
269 break;
270 case 'T':
271 tags = optarg;
272 break;
273 case 'U':
274 dounpriv = 1;
275 break;
276 case '?':
277 default:
278 usage();
280 argc -= optind;
281 argv += optind;
283 /* strip and link options make no sense when creating directories */
284 if ((dostrip || dolink) && dodir)
285 usage();
287 /* strip and flags make no sense with links */
288 if ((dostrip || fflags) && dolink)
289 usage();
291 /* must have at least two arguments, except when creating directories */
292 if (argc < 2 && !dodir)
293 usage();
295 if (digest) {
296 if (0) {
297 } else if (strcmp(digest, "none") == 0) {
298 digesttype = DIGEST_NONE;
299 } else if (strcmp(digest, "md5") == 0) {
300 digesttype = DIGEST_MD5;
301 } else if (strcmp(digest, "rmd160") == 0) {
302 digesttype = DIGEST_RMD160;
303 } else if (strcmp(digest, "sha1") == 0) {
304 digesttype = DIGEST_SHA1;
305 } else if (strcmp(digest, "sha256") == 0) {
306 digesttype = DIGEST_SHA256;
307 } else if (strcmp(digest, "sha384") == 0) {
308 digesttype = DIGEST_SHA384;
309 } else if (strcmp(digest, "sha512") == 0) {
310 digesttype = DIGEST_SHA512;
311 } else {
312 warnx("unknown digest `%s'", digest);
313 usage();
317 /* get group and owner id's */
318 if (group && !dounpriv) {
319 if (gid_from_group(group, &gid) == -1) {
320 id_t id;
321 if (!parseid(group, &id))
322 errx(1, "unknown group %s", group);
323 gid = id;
325 iflags |= HASGID;
327 if (owner && !dounpriv) {
328 if (uid_from_user(owner, &uid) == -1) {
329 id_t id;
330 if (!parseid(owner, &id))
331 errx(1, "unknown user %s", owner);
332 uid = id;
334 iflags |= HASUID;
337 #if ! HAVE_NBTOOL_CONFIG_H
338 if (fflags && !dounpriv) {
339 if (string_to_flags(&fflags, &fileflags, NULL))
340 errx(1, "%s: invalid flag", fflags);
341 /* restore fflags since string_to_flags() changed it */
342 fflags = flags_to_string(fileflags, "-");
343 iflags |= SETFLAGS;
345 #endif
347 if (metafile) {
348 if ((metafp = fopen(metafile, "a")) == NULL)
349 warn("open %s", metafile);
350 } else
351 digesttype = DIGEST_NONE;
353 if (dodir) {
354 for (; *argv != NULL; ++argv)
355 install_dir(*argv, iflags);
356 exit (0);
359 no_target = stat(to_name = argv[argc - 1], &to_sb);
360 if (!no_target && S_ISDIR(to_sb.st_mode)) {
361 for (; *argv != to_name; ++argv)
362 install(*argv, to_name, iflags | DIRECTORY);
363 exit(0);
366 /* can't do file1 file2 directory/file */
367 if (argc != 2) {
368 errx(EXIT_FAILURE, "the last argument (%s) "
369 "must name an existing directory", argv[argc - 1]);
370 /* NOTREACHED */
373 if (!no_target) {
374 /* makelink() handles checks for links */
375 if (!dolink) {
376 if (stat(*argv, &from_sb))
377 err(1, "%s: stat", *argv);
378 if (!S_ISREG(to_sb.st_mode))
379 errx(1, "%s: not a regular file", to_name);
380 if (to_sb.st_dev == from_sb.st_dev &&
381 to_sb.st_ino == from_sb.st_ino)
382 errx(1, "%s and %s are the same file", *argv,
383 to_name);
386 * Unlink now... avoid ETXTBSY errors later. Try and turn
387 * off the append/immutable bits -- if we fail, go ahead,
388 * it might work.
390 #ifndef __minix
391 #if ! HAVE_NBTOOL_CONFIG_H
392 #define NOCHANGEBITS (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
393 if (to_sb.st_flags & NOCHANGEBITS)
394 (void)chflags(to_name,
395 to_sb.st_flags & ~(NOCHANGEBITS));
396 #endif
397 #endif
398 if (dobackup)
399 backup(to_name);
400 else if (!dorename)
401 (void)unlink(to_name);
403 install(*argv, to_name, iflags);
404 exit(0);
408 * parseid --
409 * parse uid or gid from arg into id, returning non-zero if successful
411 static int
412 parseid(char *name, id_t *id)
414 char *ep;
416 errno = 0;
417 *id = (id_t)strtoul(name, &ep, 10);
418 if (errno || *ep != '\0')
419 return (0);
420 return (1);
424 * do_link --
425 * make a hard link, obeying dorename if set
426 * return -1 on failure
428 static int
429 do_link(char *from_name, char *to_name)
431 char tmpl[MAXPATHLEN];
432 int ret;
434 if (dorename) {
435 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
436 /* This usage is safe. */
437 if (mktemp(tmpl) == NULL)
438 err(1, "%s: mktemp", tmpl);
439 ret = link(from_name, tmpl);
440 if (ret == 0) {
441 ret = rename(tmpl, to_name);
442 /* If rename has posix semantics, then the temporary
443 * file may still exist when from_name and to_name point
444 * to the same file, so unlink it unconditionally.
446 (void)unlink(tmpl);
448 return (ret);
449 } else
450 return (link(from_name, to_name));
454 * do_symlink --
455 * make a symbolic link, obeying dorename if set
456 * exit on failure
458 static void
459 do_symlink(char *from_name, char *to_name)
461 char tmpl[MAXPATHLEN];
463 if (dorename) {
464 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
465 /* This usage is safe. */
466 if (mktemp(tmpl) == NULL)
467 err(1, "%s: mktemp", tmpl);
469 if (symlink(from_name, tmpl) == -1)
470 err(1, "symlink %s -> %s", from_name, tmpl);
471 if (rename(tmpl, to_name) == -1) {
472 /* remove temporary link before exiting */
473 (void)unlink(tmpl);
474 err(1, "%s: rename", to_name);
476 } else {
477 if (symlink(from_name, to_name) == -1)
478 err(1, "symlink %s -> %s", from_name, to_name);
483 * makelink --
484 * make a link from source to destination
486 static void
487 makelink(char *from_name, char *to_name)
489 char src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
490 struct stat to_sb;
492 /* Try hard links first */
493 if (dolink & (LN_HARD|LN_MIXED)) {
494 if (do_link(from_name, to_name) == -1) {
495 if ((dolink & LN_HARD) || errno != EXDEV)
496 err(1, "link %s -> %s", from_name, to_name);
497 } else {
498 if (stat(to_name, &to_sb))
499 err(1, "%s: stat", to_name);
500 if (S_ISREG(to_sb.st_mode)) {
501 /* XXX: hard links to anything
502 * other than plain files are not
503 * metalogged
505 int omode;
506 char *oowner, *ogroup, *offlags;
507 char *dres;
509 /* XXX: use underlying perms,
510 * unless overridden on command line.
512 omode = mode;
513 if (!haveopt_m)
514 mode = (to_sb.st_mode & 0777);
515 oowner = owner;
516 if (!haveopt_o)
517 owner = NULL;
518 ogroup = group;
519 if (!haveopt_g)
520 group = NULL;
521 offlags = fflags;
522 if (!haveopt_f)
523 fflags = NULL;
524 switch (digesttype) {
525 case DIGEST_MD5:
526 dres = MD5File(from_name, NULL);
527 break;
528 case DIGEST_RMD160:
529 dres = RMD160File(from_name, NULL);
530 break;
531 case DIGEST_SHA1:
532 dres = SHA1File(from_name, NULL);
533 break;
534 case DIGEST_SHA256:
535 dres = SHA256_File(from_name, NULL);
536 break;
537 case DIGEST_SHA384:
538 dres = SHA384_File(from_name, NULL);
539 break;
540 case DIGEST_SHA512:
541 dres = SHA512_File(from_name, NULL);
542 break;
543 default:
544 dres = NULL;
546 metadata_log(to_name, "file", NULL, NULL,
547 dres, to_sb.st_size);
548 free(dres);
549 mode = omode;
550 owner = oowner;
551 group = ogroup;
552 fflags = offlags;
554 return;
558 /* Symbolic links */
559 if (dolink & LN_ABSOLUTE) {
560 /* Convert source path to absolute */
561 if (realpath(from_name, src) == NULL)
562 err(1, "%s: realpath", from_name);
563 do_symlink(src, to_name);
564 /* XXX: src may point outside of destdir */
565 metadata_log(to_name, "link", NULL, src, NULL, 0);
566 return;
569 if (dolink & LN_RELATIVE) {
570 char *cp, *d, *s;
572 /* Resolve pathnames */
573 if (realpath(from_name, src) == NULL)
574 err(1, "%s: realpath", from_name);
577 * The last component of to_name may be a symlink,
578 * so use realpath to resolve only the directory.
580 cp = xdirname(to_name);
581 if (realpath(cp, dst) == NULL)
582 err(1, "%s: realpath", cp);
583 /* .. and add the last component */
584 if (strcmp(dst, "/") != 0) {
585 if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
586 errx(1, "resolved pathname too long");
588 cp = xbasename(to_name);
589 if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
590 errx(1, "resolved pathname too long");
592 /* trim common path components */
593 for (s = src, d = dst; *s == *d; s++, d++)
594 continue;
595 while (*s != '/')
596 s--, d--;
598 /* count the number of directories we need to backtrack */
599 for (++d, lnk[0] = '\0'; *d; d++)
600 if (*d == '/')
601 (void)strlcat(lnk, "../", sizeof(lnk));
603 (void)strlcat(lnk, ++s, sizeof(lnk));
605 do_symlink(lnk, to_name);
606 /* XXX: lnk may point outside of destdir */
607 metadata_log(to_name, "link", NULL, lnk, NULL, 0);
608 return;
612 * If absolute or relative was not specified,
613 * try the names the user provided
615 do_symlink(from_name, to_name);
616 /* XXX: from_name may point outside of destdir */
617 metadata_log(to_name, "link", NULL, from_name, NULL, 0);
621 * install --
622 * build a path name and install the file
624 static void
625 install(char *from_name, char *to_name, u_int flags)
627 struct stat from_sb;
628 struct stat to_sb;
629 struct timeval tv[2];
630 off_t size;
631 int devnull, from_fd, to_fd, serrno, tmpmode;
632 char *p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
634 size = -1;
635 if (!dolink) {
636 /* ensure that from_sb & tv are sane if !dolink */
637 if (stat(from_name, &from_sb))
638 err(1, "%s: stat", from_name);
639 size = from_sb.st_size;
640 #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
641 TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
642 TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
643 #else
644 tv[0].tv_sec = from_sb.st_atime;
645 tv[0].tv_usec = 0;
646 tv[1].tv_sec = from_sb.st_mtime;
647 tv[1].tv_usec = 0;
648 #endif
651 if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL) != 0) {
652 devnull = 0;
653 if (!dolink) {
654 if (!S_ISREG(from_sb.st_mode))
655 errx(1, "%s: not a regular file", from_name);
657 /* Build the target path. */
658 if (flags & DIRECTORY) {
659 (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
660 to_name,
661 (p = strrchr(from_name, '/')) ? ++p : from_name);
662 to_name = pathbuf;
664 } else {
665 devnull = 1;
666 size = 0;
667 #if HAVE_STRUCT_STAT_ST_FLAGS
668 from_sb.st_flags = 0; /* XXX */
669 #endif
673 * Unlink now... avoid ETXTBSY errors later. Try and turn
674 * off the append/immutable bits -- if we fail, go ahead,
675 * it might work.
677 #ifndef __minix
678 #if ! HAVE_NBTOOL_CONFIG_H
679 if (stat(to_name, &to_sb) == 0 &&
680 to_sb.st_flags & (NOCHANGEBITS))
681 (void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
682 #endif
683 #endif
684 if (dorename) {
685 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
686 oto_name = to_name;
687 to_name = tmpl;
688 } else {
689 oto_name = NULL; /* pacify gcc */
690 if (dobackup)
691 backup(to_name);
692 else
693 (void)unlink(to_name);
696 if (dolink) {
697 makelink(from_name, dorename ? oto_name : to_name);
698 return;
701 /* Create target. */
702 if (dorename) {
703 if ((to_fd = mkstemp(to_name)) == -1)
704 err(1, "%s: mkstemp", to_name);
705 } else {
706 if ((to_fd = open(to_name,
707 O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
708 err(1, "%s: open", to_name);
710 digestresult = NULL;
711 if (!devnull) {
712 if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
713 (void)unlink(to_name);
714 err(1, "%s: open", from_name);
716 digestresult =
717 copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
718 (void)close(from_fd);
721 if (dostrip) {
722 strip(to_name);
725 * Re-open our fd on the target, in case we used a strip
726 * that does not work in-place -- like gnu binutils strip.
728 close(to_fd);
729 if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
730 err(1, "stripping %s", to_name);
733 * Recalculate size and digestresult after stripping.
735 if (fstat(to_fd, &to_sb) != 0)
736 err(1, "%s: fstat", to_name);
737 size = to_sb.st_size;
738 digestresult =
739 copy(to_fd, to_name, -1, NULL, size);
743 if (afterinstallcmd != NULL) {
744 afterinstall(afterinstallcmd, to_name, 1);
747 * Re-open our fd on the target, in case we used an
748 * after-install command that does not work in-place
750 close(to_fd);
751 if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
752 err(1, "running after install command on %s", to_name);
756 * Set owner, group, mode for target; do the chown first,
757 * chown may lose the setuid bits.
759 if (!dounpriv &&
760 (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
761 serrno = errno;
762 (void)unlink(to_name);
763 errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
765 tmpmode = mode;
766 if (dounpriv)
767 tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
768 if (fchmod(to_fd, tmpmode) == -1) {
769 serrno = errno;
770 (void)unlink(to_name);
771 errx(1, "%s: chmod: %s", to_name, strerror(serrno));
775 * Preserve the date of the source file.
777 #ifndef __minix
778 if (dopreserve) {
779 #if HAVE_FUTIMES
780 if (futimes(to_fd, tv) == -1)
781 warn("%s: futimes", to_name);
782 #else
783 if (utimes(to_name, tv) == -1)
784 warn("%s: utimes", to_name);
785 #endif
787 #endif
789 (void)close(to_fd);
791 if (dorename) {
792 if (rename(to_name, oto_name) == -1)
793 err(1, "%s: rename", to_name);
794 to_name = oto_name;
798 * If provided a set of flags, set them, otherwise, preserve the
799 * flags, except for the dump flag.
801 #ifndef __minix
802 #if ! HAVE_NBTOOL_CONFIG_H
803 if (!dounpriv && chflags(to_name,
804 flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
806 if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
807 warn("%s: chflags", to_name);
809 #endif
810 #endif
812 metadata_log(to_name, "file", tv, NULL, digestresult, size);
813 free(digestresult);
817 * copy --
818 * copy from one file to another, returning a digest.
820 * If to_fd < 0, just calculate a digest, don't copy.
822 static char *
823 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
825 ssize_t nr, nw;
826 int serrno;
827 #ifndef __minix
828 u_char *p;
829 #endif
830 u_char buf[MAXBSIZE];
831 MD5_CTX ctxMD5;
832 RMD160_CTX ctxRMD160;
833 SHA1_CTX ctxSHA1;
834 SHA256_CTX ctxSHA256;
835 SHA384_CTX ctxSHA384;
836 SHA512_CTX ctxSHA512;
838 switch (digesttype) {
839 case DIGEST_MD5:
840 MD5Init(&ctxMD5);
841 break;
842 case DIGEST_RMD160:
843 RMD160Init(&ctxRMD160);
844 break;
845 case DIGEST_SHA1:
846 SHA1Init(&ctxSHA1);
847 break;
848 case DIGEST_SHA256:
849 SHA256_Init(&ctxSHA256);
850 break;
851 case DIGEST_SHA384:
852 SHA384_Init(&ctxSHA384);
853 break;
854 case DIGEST_SHA512:
855 SHA512_Init(&ctxSHA512);
856 break;
857 case DIGEST_NONE:
858 if (to_fd < 0)
859 return NULL; /* no need to do anything */
860 default:
861 break;
864 * There's no reason to do anything other than close the file
865 * now if it's empty, so let's not bother.
867 if (size > 0) {
870 * Mmap and write if less than 8M (the limit is so we
871 * don't totally trash memory on big files). This is
872 * really a minor hack, but it wins some CPU back.
875 if (size <= 8 * 1048576) {
876 #ifdef __minix
877 goto mmap_failed;
878 #else
879 if ((p = mmap(NULL, (size_t)size, PROT_READ,
880 MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
881 == MAP_FAILED) {
882 goto mmap_failed;
884 #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
885 if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
886 && errno != EOPNOTSUPP)
887 warnx("madvise: %s", strerror(errno));
888 #endif
890 if (to_fd >= 0 && write(to_fd, p, size) != size) {
891 serrno = errno;
892 (void)unlink(to_name);
893 errx(1, "%s: write: %s",
894 to_name, strerror(serrno));
896 switch (digesttype) {
897 case DIGEST_MD5:
898 MD5Update(&ctxMD5, p, size);
899 break;
900 case DIGEST_RMD160:
901 RMD160Update(&ctxRMD160, p, size);
902 break;
903 case DIGEST_SHA1:
904 SHA1Update(&ctxSHA1, p, size);
905 break;
906 case DIGEST_SHA256:
907 SHA256_Update(&ctxSHA256, p, size);
908 break;
909 case DIGEST_SHA384:
910 SHA384_Update(&ctxSHA384, p, size);
911 break;
912 case DIGEST_SHA512:
913 SHA512_Update(&ctxSHA512, p, size);
914 break;
915 default:
916 break;
918 (void)munmap(p, size);
919 #endif
920 } else {
921 mmap_failed:
922 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
923 if (to_fd >= 0 &&
924 (nw = write(to_fd, buf, nr)) != nr) {
925 serrno = errno;
926 (void)unlink(to_name);
927 errx(1, "%s: write: %s", to_name,
928 strerror(nw > 0 ? EIO : serrno));
930 switch (digesttype) {
931 case DIGEST_MD5:
932 MD5Update(&ctxMD5, buf, nr);
933 break;
934 case DIGEST_RMD160:
935 RMD160Update(&ctxRMD160, buf, nr);
936 break;
937 case DIGEST_SHA1:
938 SHA1Update(&ctxSHA1, buf, nr);
939 break;
940 case DIGEST_SHA256:
941 SHA256_Update(&ctxSHA256, buf, nr);
942 break;
943 case DIGEST_SHA384:
944 SHA384_Update(&ctxSHA384, buf, nr);
945 break;
946 case DIGEST_SHA512:
947 SHA512_Update(&ctxSHA512, buf, nr);
948 break;
949 default:
950 break;
953 if (nr != 0) {
954 serrno = errno;
955 (void)unlink(to_name);
956 errx(1, "%s: read: %s", from_name, strerror(serrno));
960 switch (digesttype) {
961 case DIGEST_MD5:
962 return MD5End(&ctxMD5, NULL);
963 case DIGEST_RMD160:
964 return RMD160End(&ctxRMD160, NULL);
965 case DIGEST_SHA1:
966 return SHA1End(&ctxSHA1, NULL);
967 case DIGEST_SHA256:
968 return SHA256_End(&ctxSHA256, NULL);
969 case DIGEST_SHA384:
970 return SHA384_End(&ctxSHA384, NULL);
971 case DIGEST_SHA512:
972 return SHA512_End(&ctxSHA512, NULL);
973 default:
974 return NULL;
979 * strip --
980 * use strip(1) to strip the target file
982 static void
983 strip(char *to_name)
985 static const char exec_failure[] = ": exec of strip failed: ";
986 int serrno, status;
987 const char * volatile stripprog, *progname;
988 char *cmd;
990 if ((stripprog = getenv("STRIP")) == NULL || *stripprog == '\0') {
991 #ifdef TARGET_STRIP
992 stripprog = TARGET_STRIP;
993 #else
994 stripprog = _PATH_STRIP;
995 #endif
998 cmd = NULL;
1000 if (stripArgs) {
1002 * Build up a command line and let /bin/sh
1003 * parse the arguments.
1005 int ret = asprintf(&cmd, "%s %s %s", stripprog, stripArgs,
1006 to_name);
1008 if (ret == -1 || cmd == NULL)
1009 err(1, "asprintf failed");
1012 switch (vfork()) {
1013 case -1:
1014 serrno = errno;
1015 (void)unlink(to_name);
1016 errx(1, "vfork: %s", strerror(serrno));
1017 /*NOTREACHED*/
1018 case 0:
1020 if (stripArgs)
1021 execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
1022 else
1023 execlp(stripprog, "strip", to_name, NULL);
1025 progname = getprogname();
1026 write(STDERR_FILENO, progname, strlen(progname));
1027 write(STDERR_FILENO, exec_failure, strlen(exec_failure));
1028 write(STDERR_FILENO, stripprog, strlen(stripprog));
1029 write(STDERR_FILENO, "\n", 1);
1030 _exit(1);
1031 /*NOTREACHED*/
1032 default:
1033 if (wait(&status) == -1 || status)
1034 (void)unlink(to_name);
1037 free(cmd);
1041 * afterinstall --
1042 * run provided command on the target file or directory after it's been
1043 * installed and stripped, but before permissions are set or it's renamed
1045 static void
1046 afterinstall(const char *command, const char *to_name, int errunlink)
1048 int serrno, status;
1049 char *cmd;
1051 switch (vfork()) {
1052 case -1:
1053 serrno = errno;
1054 if (errunlink)
1055 (void)unlink(to_name);
1056 errx(1, "vfork: %s", strerror(serrno));
1057 /*NOTREACHED*/
1058 case 0:
1060 * build up a command line and let /bin/sh
1061 * parse the arguments
1063 cmd = (char*)malloc(sizeof(char)*
1064 (2+strlen(command)+
1065 strlen(to_name)));
1067 if (cmd == NULL)
1068 errx(1, "%s", strerror(ENOMEM));
1070 sprintf(cmd, "%s %s", command, to_name);
1072 execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
1074 warn("%s: exec of after install command", command);
1075 _exit(1);
1076 /*NOTREACHED*/
1077 default:
1078 if ((wait(&status) == -1 || status) && errunlink)
1079 (void)unlink(to_name);
1084 * backup --
1085 * backup file "to_name" to to_name.suffix
1086 * if suffix contains a "%", it's taken as a printf(3) pattern
1087 * used for a numbered backup.
1089 static void
1090 backup(const char *to_name)
1092 char bname[FILENAME_MAX];
1094 if (numberedbackup) {
1095 /* Do numbered backup */
1096 int cnt;
1097 char suffix_expanded[FILENAME_MAX];
1099 cnt=0;
1100 do {
1101 (void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
1102 cnt);
1103 (void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
1104 suffix_expanded);
1105 cnt++;
1106 } while (access(bname, F_OK) == 0);
1107 } else {
1108 /* Do simple backup */
1109 (void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
1112 (void)rename(to_name, bname);
1116 * install_dir --
1117 * build directory hierarchy
1119 static void
1120 install_dir(char *path, u_int flags)
1122 char *p;
1123 struct stat sb;
1124 int ch;
1126 for (p = path;; ++p)
1127 if (!*p || (p != path && *p == '/')) {
1128 ch = *p;
1129 *p = '\0';
1130 if (mkdir(path, 0777) < 0) {
1132 * Can't create; path exists or no perms.
1133 * stat() path to determine what's there now.
1135 int sverrno;
1136 sverrno = errno;
1137 if (stat(path, &sb) < 0) {
1138 /* Not there; use mkdir()s error */
1139 errno = sverrno;
1140 err(1, "%s: mkdir", path);
1142 if (!S_ISDIR(sb.st_mode)) {
1143 errx(1,
1144 "%s exists but is not a directory",
1145 path);
1148 if (!(*p = ch))
1149 break;
1152 if (afterinstallcmd != NULL)
1153 afterinstall(afterinstallcmd, path, 0);
1155 if (!dounpriv && (
1156 ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
1157 || chmod(path, mode) == -1 )) {
1158 warn("%s: chown/chmod", path);
1160 metadata_log(path, "dir", NULL, NULL, NULL, 0);
1164 * metadata_log --
1165 * if metafp is not NULL, output mtree(8) full path name and settings to
1166 * metafp, to allow permissions to be set correctly by other tools,
1167 * or to allow integrity checks to be performed.
1169 static void
1170 metadata_log(const char *path, const char *type, struct timeval *tv,
1171 const char *slink, const char *digestresult, off_t size)
1173 static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1174 const char *p;
1175 char *buf;
1176 size_t destlen;
1177 struct flock metalog_lock;
1179 if (!metafp)
1180 return;
1181 buf = (char *)malloc(4 * strlen(path) + 1); /* buf for strsvis(3) */
1182 if (buf == NULL) {
1183 warnx("%s", strerror(ENOMEM));
1184 return;
1186 /* lock log file */
1187 metalog_lock.l_start = 0;
1188 metalog_lock.l_len = 0;
1189 metalog_lock.l_whence = SEEK_SET;
1190 metalog_lock.l_type = F_WRLCK;
1191 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1192 warn("can't lock %s", metafile);
1193 free(buf);
1194 return;
1197 p = path; /* remove destdir */
1198 if (destdir) {
1199 destlen = strlen(destdir);
1200 if (strncmp(p, destdir, destlen) == 0 &&
1201 (p[destlen] == '/' || p[destlen] == '\0'))
1202 p += destlen;
1204 while (*p && *p == '/') /* remove leading /s */
1205 p++;
1206 strsvis(buf, p, VIS_CSTYLE, extra); /* encode name */
1207 p = buf;
1208 /* print details */
1209 fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1210 if (owner)
1211 fprintf(metafp, " uname=%s", owner);
1212 if (group)
1213 fprintf(metafp, " gname=%s", group);
1214 fprintf(metafp, " mode=%#o", mode);
1215 if (slink) {
1216 strsvis(buf, slink, VIS_CSTYLE, extra); /* encode link */
1217 fprintf(metafp, " link=%s", buf);
1219 if (*type == 'f') /* type=file */
1220 fprintf(metafp, " size=%lld", (long long)size);
1221 if (tv != NULL && dopreserve)
1222 fprintf(metafp, " time=%lld.%ld",
1223 (long long)tv[1].tv_sec, (long)tv[1].tv_usec);
1224 if (digestresult && digest)
1225 fprintf(metafp, " %s=%s", digest, digestresult);
1226 if (fflags)
1227 fprintf(metafp, " flags=%s", fflags);
1228 if (tags)
1229 fprintf(metafp, " tags=%s", tags);
1230 fputc('\n', metafp);
1231 fflush(metafp); /* flush output */
1232 /* unlock log file */
1233 metalog_lock.l_type = F_UNLCK;
1234 if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1235 warn("can't unlock %s", metafile);
1237 free(buf);
1241 * xbasename --
1242 * libc basename(3) that returns a pointer to a static buffer
1243 * instead of overwriting that passed-in string.
1245 static char *
1246 xbasename(char *path)
1248 static char tmp[MAXPATHLEN];
1250 (void)strlcpy(tmp, path, sizeof(tmp));
1251 return (basename(tmp));
1255 * xdirname --
1256 * libc dirname(3) that returns a pointer to a static buffer
1257 * instead of overwriting that passed-in string.
1259 static char *
1260 xdirname(char *path)
1262 static char tmp[MAXPATHLEN];
1264 (void)strlcpy(tmp, path, sizeof(tmp));
1265 return (dirname(tmp));
1269 * usage --
1270 * print a usage message and die
1272 static void
1273 usage(void)
1275 const char *prog;
1277 prog = getprogname();
1279 (void)fprintf(stderr,
1280 "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1281 " [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
1282 " [-l linkflags] [-h hash] [-S stripflags] file1 file2\n"
1283 " %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1284 " [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
1285 " [-l linkflags] [-h hash] [-S stripflags] file1 ... fileN directory\n"
1286 " %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
1287 " [-N dbdir] [-o owner] [-g group] directory ...\n",
1288 prog, prog, prog);
1289 exit(1);