]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - usr.bin/xinstall/xinstall.c
MFC r315161: Try to slight untangle I/O and loop status handling.
[FreeBSD/stable/10.git] / usr.bin / xinstall / xinstall.c
1 /*
2  * Copyright (c) 2012, 2013 SRI International
3  * Copyright (c) 1987, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1987, 1993\n\
34         The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36
37 #if 0
38 #ifndef lint
39 static char sccsid[] = "@(#)xinstall.c  8.1 (Berkeley) 7/21/93";
40 #endif /* not lint */
41 #endif
42
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45
46 #include <sys/param.h>
47 #include <sys/mman.h>
48 #include <sys/mount.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/wait.h>
52
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <grp.h>
57 #include <libgen.h>
58 #include <md5.h>
59 #include <paths.h>
60 #include <pwd.h>
61 #include <ripemd.h>
62 #include <sha.h>
63 #include <sha256.h>
64 #include <sha512.h>
65 #include <stdint.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <sysexits.h>
70 #include <unistd.h>
71 #include <vis.h>
72
73 #include "mtree.h"
74
75 /* Bootstrap aid - this doesn't exist in most older releases */
76 #ifndef MAP_FAILED
77 #define MAP_FAILED ((void *)-1) /* from <sys/mman.h> */
78 #endif
79
80 #define MAX_CMP_SIZE    (16 * 1024 * 1024)
81
82 #define LN_ABSOLUTE     0x01
83 #define LN_RELATIVE     0x02
84 #define LN_HARD         0x04
85 #define LN_SYMBOLIC     0x08
86 #define LN_MIXED        0x10
87
88 #define DIRECTORY       0x01            /* Tell install it's a directory. */
89 #define SETFLAGS        0x02            /* Tell install to set flags. */
90 #define NOCHANGEBITS    (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
91 #define BACKUP_SUFFIX   ".old"
92
93 typedef union {
94         MD5_CTX         MD5;
95         RIPEMD160_CTX   RIPEMD160;
96         SHA1_CTX        SHA1;
97         SHA256_CTX      SHA256;
98         SHA512_CTX      SHA512;
99 }       DIGEST_CTX;
100
101 static enum {
102         DIGEST_NONE = 0,
103         DIGEST_MD5,
104         DIGEST_RIPEMD160,
105         DIGEST_SHA1,
106         DIGEST_SHA256,
107         DIGEST_SHA512,
108 } digesttype = DIGEST_NONE;
109
110 static gid_t gid;
111 static uid_t uid;
112 static int dobackup, docompare, dodir, dolink, dopreserve, dostrip, dounpriv,
113     safecopy, verbose;
114 static int haveopt_f, haveopt_g, haveopt_m, haveopt_o;
115 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
116 static FILE *metafp;
117 static const char *group, *owner;
118 static const char *suffix = BACKUP_SUFFIX;
119 static char *destdir, *digest, *fflags, *metafile, *tags;
120
121 static int      compare(int, const char *, size_t, int, const char *, size_t,
122                     char **);
123 static char     *copy(int, const char *, int, const char *, off_t);
124 static int      create_newfile(const char *, int, struct stat *);
125 static int      create_tempfile(const char *, char *, size_t);
126 static char     *quiet_mktemp(char *template);
127 static char     *digest_file(const char *);
128 static void     digest_init(DIGEST_CTX *);
129 static void     digest_update(DIGEST_CTX *, const unsigned char *, size_t);
130 static char     *digest_end(DIGEST_CTX *, char *);
131 static int      do_link(const char *, const char *, const struct stat *);
132 static void     do_symlink(const char *, const char *, const struct stat *);
133 static void     makelink(const char *, const char *, const struct stat *);
134 static void     install(const char *, const char *, u_long, u_int);
135 static void     install_dir(char *);
136 static void     metadata_log(const char *, const char *, struct timeval *,
137                     const char *, const char *, off_t);
138 static int      parseid(const char *, id_t *);
139 static void     strip(const char *);
140 static int      trymmap(int);
141 static void     usage(void);
142
143 int
144 main(int argc, char *argv[])
145 {
146         struct stat from_sb, to_sb;
147         mode_t *set;
148         u_long fset;
149         int ch, no_target;
150         u_int iflags;
151         char *p;
152         const char *to_name;
153
154         fset = 0;
155         iflags = 0;
156         group = owner = NULL;
157         while ((ch = getopt(argc, argv, "B:bCcD:df:g:h:l:M:m:N:o:pSsT:Uv")) !=
158              -1)
159                 switch((char)ch) {
160                 case 'B':
161                         suffix = optarg;
162                         /* FALLTHROUGH */
163                 case 'b':
164                         dobackup = 1;
165                         break;
166                 case 'C':
167                         docompare = 1;
168                         break;
169                 case 'c':
170                         /* For backwards compatibility. */
171                         break;
172                 case 'D':
173                         destdir = optarg;
174                         break;
175                 case 'd':
176                         dodir = 1;
177                         break;
178                 case 'f':
179                         haveopt_f = 1;
180                         fflags = optarg;
181                         break;
182                 case 'g':
183                         haveopt_g = 1;
184                         group = optarg;
185                         break;
186                 case 'h':
187                         digest = optarg;
188                         break;
189                 case 'l':
190                         for (p = optarg; *p != '\0'; p++)
191                                 switch (*p) {
192                                 case 's':
193                                         dolink &= ~(LN_HARD|LN_MIXED);
194                                         dolink |= LN_SYMBOLIC;
195                                         break;
196                                 case 'h':
197                                         dolink &= ~(LN_SYMBOLIC|LN_MIXED);
198                                         dolink |= LN_HARD;
199                                         break;
200                                 case 'm':
201                                         dolink &= ~(LN_SYMBOLIC|LN_HARD);
202                                         dolink |= LN_MIXED;
203                                         break;
204                                 case 'a':
205                                         dolink &= ~LN_RELATIVE;
206                                         dolink |= LN_ABSOLUTE;
207                                         break;
208                                 case 'r':
209                                         dolink &= ~LN_ABSOLUTE;
210                                         dolink |= LN_RELATIVE;
211                                         break;
212                                 default:
213                                         errx(1, "%c: invalid link type", *p);
214                                         /* NOTREACHED */
215                                 }
216                         break;
217                 case 'M':
218                         metafile = optarg;
219                         break;
220                 case 'm':
221                         haveopt_m = 1;
222                         if (!(set = setmode(optarg)))
223                                 errx(EX_USAGE, "invalid file mode: %s",
224                                      optarg);
225                         mode = getmode(set, 0);
226                         free(set);
227                         break;
228                 case 'N':
229                         if (!setup_getid(optarg))
230                                 err(EX_OSERR, "Unable to use user and group "
231                                     "databases in `%s'", optarg);
232                         break;
233                 case 'o':
234                         haveopt_o = 1;
235                         owner = optarg;
236                         break;
237                 case 'p':
238                         docompare = dopreserve = 1;
239                         break;
240                 case 'S':
241                         safecopy = 1;
242                         break;
243                 case 's':
244                         dostrip = 1;
245                         break;
246                 case 'T':
247                         tags = optarg;
248                         break;
249                 case 'U':
250                         dounpriv = 1;
251                         break;
252                 case 'v':
253                         verbose = 1;
254                         break;
255                 case '?':
256                 default:
257                         usage();
258                 }
259         argc -= optind;
260         argv += optind;
261
262         /* some options make no sense when creating directories */
263         if (dostrip && dodir) {
264                 warnx("-d and -s may not be specified together");
265                 usage();
266         }
267
268         if (getenv("DONTSTRIP") != NULL) {
269                 warnx("DONTSTRIP set - will not strip installed binaries");
270                 dostrip = 0;
271         }
272
273         /* must have at least two arguments, except when creating directories */
274         if (argc == 0 || (argc == 1 && !dodir))
275                 usage();
276
277         if (digest != NULL) {
278                 if (strcmp(digest, "none") == 0) {
279                         digesttype = DIGEST_NONE;
280                 } else if (strcmp(digest, "md5") == 0) {
281                        digesttype = DIGEST_MD5;
282                 } else if (strcmp(digest, "rmd160") == 0) {
283                         digesttype = DIGEST_RIPEMD160;
284                 } else if (strcmp(digest, "sha1") == 0) {
285                         digesttype = DIGEST_SHA1;
286                 } else if (strcmp(digest, "sha256") == 0) {
287                         digesttype = DIGEST_SHA256;
288                 } else if (strcmp(digest, "sha512") == 0) {
289                         digesttype = DIGEST_SHA512;
290                 } else {
291                         warnx("unknown digest `%s'", digest);
292                         usage();
293                 }
294         }
295
296         /* need to make a temp copy so we can compare stripped version */
297         if (docompare && dostrip)
298                 safecopy = 1;
299
300         /* get group and owner id's */
301         if (group != NULL && !dounpriv) {
302                 if (gid_from_group(group, &gid) == -1) {
303                         id_t id;
304                         if (!parseid(group, &id))
305                                 errx(1, "unknown group %s", group);
306                         gid = id;
307                 }
308         } else
309                 gid = (gid_t)-1;
310
311         if (owner != NULL && !dounpriv) {
312                 if (uid_from_user(owner, &uid) == -1) {
313                         id_t id;
314                         if (!parseid(owner, &id))
315                                 errx(1, "unknown user %s", owner);
316                         uid = id;
317                 }
318         } else
319                 uid = (uid_t)-1;
320
321         if (fflags != NULL && !dounpriv) {
322                 if (strtofflags(&fflags, &fset, NULL))
323                         errx(EX_USAGE, "%s: invalid flag", fflags);
324                 iflags |= SETFLAGS;
325         }
326
327         if (metafile != NULL) {
328                 if ((metafp = fopen(metafile, "a")) == NULL)
329                         warn("open %s", metafile);
330         } else
331                 digesttype = DIGEST_NONE;
332
333         if (dodir) {
334                 for (; *argv != NULL; ++argv)
335                         install_dir(*argv);
336                 exit(EX_OK);
337                 /* NOTREACHED */
338         }
339
340         to_name = argv[argc - 1];
341         no_target = stat(to_name, &to_sb);
342         if (!no_target && S_ISDIR(to_sb.st_mode)) {
343                 if (dolink & LN_SYMBOLIC) {
344                         if (lstat(to_name, &to_sb) != 0)
345                                 err(EX_OSERR, "%s vanished", to_name);
346                         if (S_ISLNK(to_sb.st_mode)) {
347                                 if (argc != 2) {
348                                         errno = ENOTDIR;
349                                         err(EX_USAGE, "%s", to_name);
350                                 }
351                                 install(*argv, to_name, fset, iflags);
352                                 exit(EX_OK);
353                         }
354                 }
355                 for (; *argv != to_name; ++argv)
356                         install(*argv, to_name, fset, iflags | DIRECTORY);
357                 exit(EX_OK);
358                 /* NOTREACHED */
359         }
360
361         /* can't do file1 file2 directory/file */
362         if (argc != 2) {
363                 if (no_target)
364                         warnx("target directory `%s' does not exist", 
365                             argv[argc - 1]);
366                 else
367                         warnx("target `%s' is not a directory",
368                             argv[argc - 1]);
369                 usage();
370         }
371
372         if (!no_target && !dolink) {
373                 if (stat(*argv, &from_sb))
374                         err(EX_OSERR, "%s", *argv);
375                 if (!S_ISREG(to_sb.st_mode)) {
376                         errno = EFTYPE;
377                         err(EX_OSERR, "%s", to_name);
378                 }
379                 if (to_sb.st_dev == from_sb.st_dev &&
380                     to_sb.st_ino == from_sb.st_ino)
381                         errx(EX_USAGE, 
382                             "%s and %s are the same file", *argv, to_name);
383         }
384         install(*argv, to_name, fset, iflags);
385         exit(EX_OK);
386         /* NOTREACHED */
387 }
388
389 static char *
390 digest_file(const char *name)
391 {
392
393         switch (digesttype) {
394         case DIGEST_MD5:
395                 return (MD5File(name, NULL));
396         case DIGEST_RIPEMD160:
397                 return (RIPEMD160_File(name, NULL));
398         case DIGEST_SHA1:
399                 return (SHA1_File(name, NULL));
400         case DIGEST_SHA256:
401                 return (SHA256_File(name, NULL));
402         case DIGEST_SHA512:
403                 return (SHA512_File(name, NULL));
404         default:
405                 return (NULL);
406         }
407 }
408
409 static void
410 digest_init(DIGEST_CTX *c)
411 {
412
413         switch (digesttype) {
414         case DIGEST_NONE:
415                 break;
416         case DIGEST_MD5:
417                 MD5Init(&(c->MD5));
418                 break;
419         case DIGEST_RIPEMD160:
420                 RIPEMD160_Init(&(c->RIPEMD160));
421                 break;
422         case DIGEST_SHA1:
423                 SHA1_Init(&(c->SHA1));
424                 break;
425         case DIGEST_SHA256:
426                 SHA256_Init(&(c->SHA256));
427                 break;
428         case DIGEST_SHA512:
429                 SHA512_Init(&(c->SHA512));
430                 break;
431         }
432 }
433
434 static void
435 digest_update(DIGEST_CTX *c, const unsigned char *data, size_t len)
436 {
437
438         switch (digesttype) {
439         case DIGEST_NONE:
440                 break;
441         case DIGEST_MD5:
442                 MD5Update(&(c->MD5), data, len);
443                 break;
444         case DIGEST_RIPEMD160:
445                 RIPEMD160_Update(&(c->RIPEMD160), data, len);
446                 break;
447         case DIGEST_SHA1:
448                 SHA1_Update(&(c->SHA1), data, len);
449                 break;
450         case DIGEST_SHA256:
451                 SHA256_Update(&(c->SHA256), data, len);
452                 break;
453         case DIGEST_SHA512:
454                 SHA512_Update(&(c->SHA512), data, len);
455                 break;
456         }
457 }
458
459 static char *
460 digest_end(DIGEST_CTX *c, char *buf)
461 {
462
463         switch (digesttype) {
464         case DIGEST_MD5:
465                 return (MD5End(&(c->MD5), buf));
466         case DIGEST_RIPEMD160:
467                 return (RIPEMD160_End(&(c->RIPEMD160), buf));
468         case DIGEST_SHA1:
469                 return (SHA1_End(&(c->SHA1), buf));
470         case DIGEST_SHA256:
471                 return (SHA256_End(&(c->SHA256), buf));
472         case DIGEST_SHA512:
473                 return (SHA512_End(&(c->SHA512), buf));
474         default:
475                 return (NULL);
476         }
477 }
478
479 /*
480  * parseid --
481  *      parse uid or gid from arg into id, returning non-zero if successful
482  */
483 static int
484 parseid(const char *name, id_t *id)
485 {
486         char    *ep;
487         errno = 0;
488         *id = (id_t)strtoul(name, &ep, 10);
489         if (errno || *ep != '\0')
490                 return (0);
491         return (1);
492 }
493
494 /*
495  * quiet_mktemp --
496  *      mktemp implementation used mkstemp to avoid mktemp warnings.  We
497  *      really do need mktemp semantics here as we will be creating a link.
498  */
499 static char *
500 quiet_mktemp(char *template)
501 {
502         int fd;
503
504         if ((fd = mkstemp(template)) == -1)
505                 return (NULL);
506         close (fd);
507         if (unlink(template) == -1)
508                 err(EX_OSERR, "unlink %s", template);
509         return (template);
510 }
511
512 /*
513  * do_link --
514  *      make a hard link, obeying dorename if set
515  *      return -1 on failure
516  */
517 static int
518 do_link(const char *from_name, const char *to_name,
519     const struct stat *target_sb)
520 {
521         char tmpl[MAXPATHLEN];
522         int ret;
523
524         if (safecopy && target_sb != NULL) {
525                 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
526                 /* This usage is safe. */
527                 if (quiet_mktemp(tmpl) == NULL)
528                         err(EX_OSERR, "%s: mktemp", tmpl);
529                 ret = link(from_name, tmpl);
530                 if (ret == 0) {
531                         if (target_sb->st_mode & S_IFDIR && rmdir(to_name) ==
532                             -1) {
533                                 unlink(tmpl);
534                                 err(EX_OSERR, "%s", to_name);
535                         }
536                         if (target_sb->st_flags & NOCHANGEBITS)
537                                 (void)chflags(to_name, target_sb->st_flags &
538                                      ~NOCHANGEBITS);
539                         if (verbose)
540                                 printf("install: link %s -> %s\n",
541                                     from_name, to_name);
542                         ret = rename(tmpl, to_name);
543                         /*
544                          * If rename has posix semantics, then the temporary
545                          * file may still exist when from_name and to_name point
546                          * to the same file, so unlink it unconditionally.
547                          */
548                         (void)unlink(tmpl);
549                 }
550                 return (ret);
551         } else {
552                 if (verbose)
553                         printf("install: link %s -> %s\n",
554                             from_name, to_name);
555                 return (link(from_name, to_name));
556         }
557 }
558
559 /*
560  * do_symlink --
561  *      Make a symbolic link, obeying dorename if set. Exit on failure.
562  */
563 static void
564 do_symlink(const char *from_name, const char *to_name,
565     const struct stat *target_sb)
566 {
567         char tmpl[MAXPATHLEN];
568
569         if (safecopy && target_sb != NULL) {
570                 (void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
571                 /* This usage is safe. */
572                 if (quiet_mktemp(tmpl) == NULL)
573                         err(EX_OSERR, "%s: mktemp", tmpl);
574
575                 if (symlink(from_name, tmpl) == -1)
576                         err(EX_OSERR, "symlink %s -> %s", from_name, tmpl);
577
578                 if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) {
579                         (void)unlink(tmpl);
580                         err(EX_OSERR, "%s", to_name);
581                 }
582                 if (target_sb->st_flags & NOCHANGEBITS)
583                         (void)chflags(to_name, target_sb->st_flags &
584                              ~NOCHANGEBITS);
585                 if (verbose)
586                         printf("install: symlink %s -> %s\n",
587                             from_name, to_name);
588                 if (rename(tmpl, to_name) == -1) {
589                         /* Remove temporary link before exiting. */
590                         (void)unlink(tmpl);
591                         err(EX_OSERR, "%s: rename", to_name);
592                 }
593         } else {
594                 if (verbose)
595                         printf("install: symlink %s -> %s\n",
596                             from_name, to_name);
597                 if (symlink(from_name, to_name) == -1)
598                         err(EX_OSERR, "symlink %s -> %s", from_name, to_name);
599         }
600 }
601
602 /*
603  * makelink --
604  *      make a link from source to destination
605  */
606 static void
607 makelink(const char *from_name, const char *to_name,
608     const struct stat *target_sb)
609 {
610         char    src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
611         struct stat     to_sb;
612
613         /* Try hard links first. */
614         if (dolink & (LN_HARD|LN_MIXED)) {
615                 if (do_link(from_name, to_name, target_sb) == -1) {
616                         if ((dolink & LN_HARD) || errno != EXDEV)
617                                 err(EX_OSERR, "link %s -> %s", from_name, to_name);
618                 } else {
619                         if (stat(to_name, &to_sb))
620                                 err(EX_OSERR, "%s: stat", to_name);
621                         if (S_ISREG(to_sb.st_mode)) {
622                                 /*
623                                  * XXX: hard links to anything other than
624                                  * plain files are not metalogged
625                                  */
626                                 int omode;
627                                 const char *oowner, *ogroup;
628                                 char *offlags;
629                                 char *dres;
630
631                                 /*
632                                  * XXX: use underlying perms, unless
633                                  * overridden on command line.
634                                  */
635                                 omode = mode;
636                                 if (!haveopt_m)
637                                         mode = (to_sb.st_mode & 0777);
638                                 oowner = owner;
639                                 if (!haveopt_o)
640                                         owner = NULL;
641                                 ogroup = group;
642                                 if (!haveopt_g)
643                                         group = NULL;
644                                 offlags = fflags;
645                                 if (!haveopt_f)
646                                         fflags = NULL;
647                                 dres = digest_file(from_name);
648                                 metadata_log(to_name, "file", NULL, NULL,
649                                     dres, to_sb.st_size);
650                                 free(dres);
651                                 mode = omode;
652                                 owner = oowner;
653                                 group = ogroup;
654                                 fflags = offlags;
655                         }
656                         return;
657                 }
658         }
659
660         /* Symbolic links. */
661         if (dolink & LN_ABSOLUTE) {
662                 /* Convert source path to absolute. */
663                 if (realpath(from_name, src) == NULL)
664                         err(EX_OSERR, "%s: realpath", from_name);
665                 do_symlink(src, to_name, target_sb);
666                 /* XXX: src may point outside of destdir */
667                 metadata_log(to_name, "link", NULL, src, NULL, 0);
668                 return;
669         }
670
671         if (dolink & LN_RELATIVE) {
672                 char *cp, *d, *s;
673
674                 /* Resolve pathnames. */
675                 if (realpath(from_name, src) == NULL)
676                         err(EX_OSERR, "%s: realpath", from_name);
677
678                 /*
679                  * The last component of to_name may be a symlink,
680                  * so use realpath to resolve only the directory.
681                  */
682                 cp = dirname(to_name);
683                 if (realpath(cp, dst) == NULL)
684                         err(EX_OSERR, "%s: realpath", cp);
685                 /* .. and add the last component. */
686                 if (strcmp(dst, "/") != 0) {
687                         if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
688                                 errx(1, "resolved pathname too long");
689                 }
690                 cp = basename(to_name);
691                 if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
692                         errx(1, "resolved pathname too long");
693
694                 /* Trim common path components. */
695                 for (s = src, d = dst; *s == *d; s++, d++)
696                         continue;
697                 while (*s != '/')
698                         s--, d--;
699
700                 /* Count the number of directories we need to backtrack. */
701                 for (++d, lnk[0] = '\0'; *d; d++)
702                         if (*d == '/')
703                                 (void)strlcat(lnk, "../", sizeof(lnk));
704
705                 (void)strlcat(lnk, ++s, sizeof(lnk));
706
707                 do_symlink(lnk, to_name, target_sb);
708                 /* XXX: Link may point outside of destdir. */
709                 metadata_log(to_name, "link", NULL, lnk, NULL, 0);
710                 return;
711         }
712
713         /*
714          * If absolute or relative was not specified, try the names the
715          * user provided.
716          */
717         do_symlink(from_name, to_name, target_sb);
718         /* XXX: from_name may point outside of destdir. */
719         metadata_log(to_name, "link", NULL, from_name, NULL, 0);
720 }
721
722 /*
723  * install --
724  *      build a path name and install the file
725  */
726 static void
727 install(const char *from_name, const char *to_name, u_long fset, u_int flags)
728 {
729         struct stat from_sb, temp_sb, to_sb;
730         struct timeval tvb[2];
731         int devnull, files_match, from_fd, serrno, target;
732         int tempcopy, temp_fd, to_fd;
733         char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
734         char *digestresult;
735
736         files_match = 0;
737         from_fd = -1;
738         to_fd = -1;
739
740         /* If try to install NULL file to a directory, fails. */
741         if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
742                 if (!dolink) {
743                         if (stat(from_name, &from_sb))
744                                 err(EX_OSERR, "%s", from_name);
745                         if (!S_ISREG(from_sb.st_mode)) {
746                                 errno = EFTYPE;
747                                 err(EX_OSERR, "%s", from_name);
748                         }
749                 }
750                 /* Build the target path. */
751                 if (flags & DIRECTORY) {
752                         (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
753                             to_name,
754                             (p = strrchr(from_name, '/')) ? ++p : from_name);
755                         to_name = pathbuf;
756                 }
757                 devnull = 0;
758         } else {
759                 devnull = 1;
760         }
761
762         target = (lstat(to_name, &to_sb) == 0);
763
764         if (dolink) {
765                 if (target && !safecopy) {
766                         if (to_sb.st_mode & S_IFDIR && rmdir(to_name) == -1)
767                                 err(EX_OSERR, "%s", to_name);
768                         if (to_sb.st_flags & NOCHANGEBITS)
769                                 (void)chflags(to_name,
770                                     to_sb.st_flags & ~NOCHANGEBITS);
771                         unlink(to_name);
772                 }
773                 makelink(from_name, to_name, target ? &to_sb : NULL);
774                 return;
775         }
776
777         if (target && !S_ISREG(to_sb.st_mode) && !S_ISLNK(to_sb.st_mode)) {
778                 errno = EFTYPE;
779                 warn("%s", to_name);
780                 return;
781         }
782
783         /* Only copy safe if the target exists. */
784         tempcopy = safecopy && target;
785
786         if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
787                 err(EX_OSERR, "%s", from_name);
788
789         /* If we don't strip, we can compare first. */
790         if (docompare && !dostrip && target && S_ISREG(to_sb.st_mode)) {
791                 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
792                         err(EX_OSERR, "%s", to_name);
793                 if (devnull)
794                         files_match = to_sb.st_size == 0;
795                 else
796                         files_match = !(compare(from_fd, from_name,
797                             (size_t)from_sb.st_size, to_fd,
798                             to_name, (size_t)to_sb.st_size, &digestresult));
799
800                 /* Close "to" file unless we match. */
801                 if (!files_match)
802                         (void)close(to_fd);
803         }
804
805         if (!files_match) {
806                 if (tempcopy) {
807                         to_fd = create_tempfile(to_name, tempfile,
808                             sizeof(tempfile));
809                         if (to_fd < 0)
810                                 err(EX_OSERR, "%s", tempfile);
811                 } else {
812                         if ((to_fd = create_newfile(to_name, target,
813                             &to_sb)) < 0)
814                                 err(EX_OSERR, "%s", to_name);
815                         if (verbose)
816                                 (void)printf("install: %s -> %s\n",
817                                     from_name, to_name);
818                 }
819                 if (!devnull)
820                         digestresult = copy(from_fd, from_name, to_fd,
821                              tempcopy ? tempfile : to_name, from_sb.st_size);
822                 else
823                         digestresult = NULL;
824         }
825
826         if (dostrip) {
827                 strip(tempcopy ? tempfile : to_name);
828
829                 /*
830                  * Re-open our fd on the target, in case we used a strip
831                  * that does not work in-place -- like GNU binutils strip.
832                  */
833                 close(to_fd);
834                 to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
835                 if (to_fd < 0)
836                         err(EX_OSERR, "stripping %s", to_name);
837         }
838
839         /*
840          * Compare the stripped temp file with the target.
841          */
842         if (docompare && dostrip && target && S_ISREG(to_sb.st_mode)) {
843                 temp_fd = to_fd;
844
845                 /* Re-open to_fd using the real target name. */
846                 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
847                         err(EX_OSERR, "%s", to_name);
848
849                 if (fstat(temp_fd, &temp_sb)) {
850                         serrno = errno;
851                         (void)unlink(tempfile);
852                         errno = serrno;
853                         err(EX_OSERR, "%s", tempfile);
854                 }
855
856                 if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
857                             to_name, (size_t)to_sb.st_size, &digestresult)
858                             == 0) {
859                         /*
860                          * If target has more than one link we need to
861                          * replace it in order to snap the extra links.
862                          * Need to preserve target file times, though.
863                          */
864                         if (to_sb.st_nlink != 1) {
865                                 tvb[0].tv_sec = to_sb.st_atime;
866                                 tvb[0].tv_usec = 0;
867                                 tvb[1].tv_sec = to_sb.st_mtime;
868                                 tvb[1].tv_usec = 0;
869                                 (void)utimes(tempfile, tvb);
870                         } else {
871                                 files_match = 1;
872                                 (void)unlink(tempfile);
873                         }
874                         (void) close(temp_fd);
875                 }
876         } else if (dostrip)
877                 digestresult = digest_file(tempfile);
878
879         /*
880          * Move the new file into place if doing a safe copy
881          * and the files are different (or just not compared).
882          */
883         if (tempcopy && !files_match) {
884                 /* Try to turn off the immutable bits. */
885                 if (to_sb.st_flags & NOCHANGEBITS)
886                         (void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
887                 if (dobackup) {
888                         if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
889                             suffix) != strlen(to_name) + strlen(suffix)) {
890                                 unlink(tempfile);
891                                 errx(EX_OSERR, "%s: backup filename too long",
892                                     to_name);
893                         }
894                         if (verbose)
895                                 (void)printf("install: %s -> %s\n", to_name, backup);
896                         if (unlink(backup) < 0 && errno != ENOENT) {
897                                 serrno = errno;
898                                 if (to_sb.st_flags & NOCHANGEBITS)
899                                         (void)chflags(to_name, to_sb.st_flags);
900                                 unlink(tempfile);
901                                 errno = serrno;
902                                 err(EX_OSERR, "unlink: %s", backup);
903                         }
904                         if (link(to_name, backup) < 0) {
905                                 serrno = errno;
906                                 unlink(tempfile);
907                                 if (to_sb.st_flags & NOCHANGEBITS)
908                                         (void)chflags(to_name, to_sb.st_flags);
909                                 errno = serrno;
910                                 err(EX_OSERR, "link: %s to %s", to_name,
911                                      backup);
912                         }
913                 }
914                 if (verbose)
915                         (void)printf("install: %s -> %s\n", from_name, to_name);
916                 if (rename(tempfile, to_name) < 0) {
917                         serrno = errno;
918                         unlink(tempfile);
919                         errno = serrno;
920                         err(EX_OSERR, "rename: %s to %s",
921                             tempfile, to_name);
922                 }
923
924                 /* Re-open to_fd so we aren't hosed by the rename(2). */
925                 (void) close(to_fd);
926                 if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
927                         err(EX_OSERR, "%s", to_name);
928         }
929
930         /*
931          * Preserve the timestamp of the source file if necessary.
932          */
933         if (dopreserve && !files_match && !devnull) {
934                 tvb[0].tv_sec = from_sb.st_atime;
935                 tvb[0].tv_usec = 0;
936                 tvb[1].tv_sec = from_sb.st_mtime;
937                 tvb[1].tv_usec = 0;
938                 (void)utimes(to_name, tvb);
939         }
940
941         if (fstat(to_fd, &to_sb) == -1) {
942                 serrno = errno;
943                 (void)unlink(to_name);
944                 errno = serrno;
945                 err(EX_OSERR, "%s", to_name);
946         }
947
948         /*
949          * Set owner, group, mode for target; do the chown first,
950          * chown may lose the setuid bits.
951          */
952         if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
953             (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
954             (mode != (to_sb.st_mode & ALLPERMS)))) {
955                 /* Try to turn off the immutable bits. */
956                 if (to_sb.st_flags & NOCHANGEBITS)
957                         (void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
958         }
959
960         if (!dounpriv & 
961             (gid != (gid_t)-1 && gid != to_sb.st_gid) ||
962             (uid != (uid_t)-1 && uid != to_sb.st_uid))
963                 if (fchown(to_fd, uid, gid) == -1) {
964                         serrno = errno;
965                         (void)unlink(to_name);
966                         errno = serrno;
967                         err(EX_OSERR,"%s: chown/chgrp", to_name);
968                 }
969
970         if (mode != (to_sb.st_mode & ALLPERMS)) {
971                 if (fchmod(to_fd,
972                      dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) {
973                         serrno = errno;
974                         (void)unlink(to_name);
975                         errno = serrno;
976                         err(EX_OSERR, "%s: chmod", to_name);
977                 }
978         }
979
980         /*
981          * If provided a set of flags, set them, otherwise, preserve the
982          * flags, except for the dump flag.
983          * NFS does not support flags.  Ignore EOPNOTSUPP flags if we're just
984          * trying to turn off UF_NODUMP.  If we're trying to set real flags,
985          * then warn if the fs doesn't support it, otherwise fail.
986          */
987         if (!dounpriv & !devnull && (flags & SETFLAGS ||
988             (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) &&
989             fchflags(to_fd,
990             flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
991                 if (flags & SETFLAGS) {
992                         if (errno == EOPNOTSUPP)
993                                 warn("%s: chflags", to_name);
994                         else {
995                                 serrno = errno;
996                                 (void)unlink(to_name);
997                                 errno = serrno;
998                                 err(EX_OSERR, "%s: chflags", to_name);
999                         }
1000                 }
1001         }
1002
1003         (void)close(to_fd);
1004         if (!devnull)
1005                 (void)close(from_fd);
1006
1007         metadata_log(to_name, "file", tvb, NULL, digestresult, to_sb.st_size);
1008         free(digestresult);
1009 }
1010
1011 /*
1012  * compare --
1013  *      compare two files; non-zero means files differ
1014  */
1015 static int
1016 compare(int from_fd, const char *from_name __unused, size_t from_len,
1017         int to_fd, const char *to_name __unused, size_t to_len,
1018         char **dresp)
1019 {
1020         char *p, *q;
1021         int rv;
1022         int done_compare;
1023         DIGEST_CTX ctx;
1024
1025         rv = 0;
1026         if (from_len != to_len)
1027                 return 1;
1028
1029         if (from_len <= MAX_CMP_SIZE) {
1030                 if (dresp != NULL)
1031                         digest_init(&ctx);
1032                 done_compare = 0;
1033                 if (trymmap(from_fd) && trymmap(to_fd)) {
1034                         p = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1035                             from_fd, (off_t)0);
1036                         if (p == (char *)MAP_FAILED)
1037                                 goto out;
1038                         q = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1039                             to_fd, (off_t)0);
1040                         if (q == (char *)MAP_FAILED) {
1041                                 munmap(p, from_len);
1042                                 goto out;
1043                         }
1044
1045                         rv = memcmp(p, q, from_len);
1046                         if (dresp != NULL)
1047                                 digest_update(&ctx, p, from_len);
1048                         munmap(p, from_len);
1049                         munmap(q, from_len);
1050                         done_compare = 1;
1051                 }
1052         out:
1053                 if (!done_compare) {
1054                         char buf1[MAXBSIZE];
1055                         char buf2[MAXBSIZE];
1056                         int n1, n2;
1057
1058                         rv = 0;
1059                         lseek(from_fd, 0, SEEK_SET);
1060                         lseek(to_fd, 0, SEEK_SET);
1061                         while (rv == 0) {
1062                                 n1 = read(from_fd, buf1, sizeof(buf1));
1063                                 if (n1 == 0)
1064                                         break;          /* EOF */
1065                                 else if (n1 > 0) {
1066                                         n2 = read(to_fd, buf2, n1);
1067                                         if (n2 == n1)
1068                                                 rv = memcmp(buf1, buf2, n1);
1069                                         else
1070                                                 rv = 1; /* out of sync */
1071                                 } else
1072                                         rv = 1;         /* read failure */
1073                                 digest_update(&ctx, buf1, n1);
1074                         }
1075                         lseek(from_fd, 0, SEEK_SET);
1076                         lseek(to_fd, 0, SEEK_SET);
1077                 }
1078         } else
1079                 rv = 1; /* don't bother in this case */
1080
1081         if (dresp != NULL) {
1082                 if (rv == 0)
1083                         *dresp = digest_end(&ctx, NULL);
1084                 else
1085                         (void)digest_end(&ctx, NULL);
1086         }
1087
1088         return rv;
1089 }
1090
1091 /*
1092  * create_tempfile --
1093  *      create a temporary file based on path and open it
1094  */
1095 static int
1096 create_tempfile(const char *path, char *temp, size_t tsize)
1097 {
1098         char *p;
1099
1100         (void)strncpy(temp, path, tsize);
1101         temp[tsize - 1] = '\0';
1102         if ((p = strrchr(temp, '/')) != NULL)
1103                 p++;
1104         else
1105                 p = temp;
1106         (void)strncpy(p, "INS@XXXX", &temp[tsize - 1] - p);
1107         temp[tsize - 1] = '\0';
1108         return (mkstemp(temp));
1109 }
1110
1111 /*
1112  * create_newfile --
1113  *      create a new file, overwriting an existing one if necessary
1114  */
1115 static int
1116 create_newfile(const char *path, int target, struct stat *sbp)
1117 {
1118         char backup[MAXPATHLEN];
1119         int saved_errno = 0;
1120         int newfd;
1121
1122         if (target) {
1123                 /*
1124                  * Unlink now... avoid ETXTBSY errors later.  Try to turn
1125                  * off the append/immutable bits -- if we fail, go ahead,
1126                  * it might work.
1127                  */
1128                 if (sbp->st_flags & NOCHANGEBITS)
1129                         (void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
1130
1131                 if (dobackup) {
1132                         if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s",
1133                             path, suffix) != strlen(path) + strlen(suffix)) {
1134                                 saved_errno = errno;
1135                                 if (sbp->st_flags & NOCHANGEBITS)
1136                                         (void)chflags(path, sbp->st_flags);
1137                                 errno = saved_errno;
1138                                 errx(EX_OSERR, "%s: backup filename too long",
1139                                     path);
1140                         }
1141                         (void)snprintf(backup, MAXPATHLEN, "%s%s",
1142                             path, suffix);
1143                         if (verbose)
1144                                 (void)printf("install: %s -> %s\n",
1145                                     path, backup);
1146                         if (rename(path, backup) < 0) {
1147                                 saved_errno = errno;
1148                                 if (sbp->st_flags & NOCHANGEBITS)
1149                                         (void)chflags(path, sbp->st_flags);
1150                                 errno = saved_errno;
1151                                 err(EX_OSERR, "rename: %s to %s", path, backup);
1152                         }
1153                 } else
1154                         if (unlink(path) < 0)
1155                                 saved_errno = errno;
1156         }
1157
1158         newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
1159         if (newfd < 0 && saved_errno != 0)
1160                 errno = saved_errno;
1161         return newfd;
1162 }
1163
1164 /*
1165  * copy --
1166  *      copy from one file to another
1167  */
1168 static char *
1169 copy(int from_fd, const char *from_name, int to_fd, const char *to_name,
1170     off_t size)
1171 {
1172         int nr, nw;
1173         int serrno;
1174         char *p, buf[MAXBSIZE];
1175         int done_copy;
1176         DIGEST_CTX ctx;
1177
1178         /* Rewind file descriptors. */
1179         if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1180                 err(EX_OSERR, "lseek: %s", from_name);
1181         if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1182                 err(EX_OSERR, "lseek: %s", to_name);
1183
1184         digest_init(&ctx);
1185
1186         /*
1187          * Mmap and write if less than 8M (the limit is so we don't totally
1188          * trash memory on big files.  This is really a minor hack, but it
1189          * wins some CPU back.
1190          */
1191         done_copy = 0;
1192         if (size <= 8 * 1048576 && trymmap(from_fd) &&
1193             (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED,
1194                     from_fd, (off_t)0)) != (char *)MAP_FAILED) {
1195                 nw = write(to_fd, p, size);
1196                 if (nw != size) {
1197                         serrno = errno;
1198                         (void)unlink(to_name);
1199                         if (nw >= 0) {
1200                                 errx(EX_OSERR,
1201      "short write to %s: %jd bytes written, %jd bytes asked to write",
1202                                     to_name, (uintmax_t)nw, (uintmax_t)size);
1203                         } else {
1204                                 errno = serrno;
1205                                 err(EX_OSERR, "%s", to_name);
1206                         }
1207                 }
1208                 digest_update(&ctx, p, size);
1209                 (void)munmap(p, size);
1210                 done_copy = 1;
1211         }
1212         if (!done_copy) {
1213                 while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
1214                         if ((nw = write(to_fd, buf, nr)) != nr) {
1215                                 serrno = errno;
1216                                 (void)unlink(to_name);
1217                                 if (nw >= 0) {
1218                                         errx(EX_OSERR,
1219      "short write to %s: %jd bytes written, %jd bytes asked to write",
1220                                             to_name, (uintmax_t)nw,
1221                                             (uintmax_t)size);
1222                                 } else {
1223                                         errno = serrno;
1224                                         err(EX_OSERR, "%s", to_name);
1225                                 }
1226                         }
1227                         digest_update(&ctx, buf, nr);
1228                 }
1229                 if (nr != 0) {
1230                         serrno = errno;
1231                         (void)unlink(to_name);
1232                         errno = serrno;
1233                         err(EX_OSERR, "%s", from_name);
1234                 }
1235         }
1236         return (digest_end(&ctx, NULL));
1237 }
1238
1239 /*
1240  * strip --
1241  *      use strip(1) to strip the target file
1242  */
1243 static void
1244 strip(const char *to_name)
1245 {
1246         const char *stripbin;
1247         int serrno, status;
1248
1249         switch (fork()) {
1250         case -1:
1251                 serrno = errno;
1252                 (void)unlink(to_name);
1253                 errno = serrno;
1254                 err(EX_TEMPFAIL, "fork");
1255         case 0:
1256                 stripbin = getenv("STRIPBIN");
1257                 if (stripbin == NULL)
1258                         stripbin = "strip";
1259                 execlp(stripbin, stripbin, to_name, (char *)NULL);
1260                 err(EX_OSERR, "exec(%s)", stripbin);
1261         default:
1262                 if (wait(&status) == -1 || status) {
1263                         serrno = errno;
1264                         (void)unlink(to_name);
1265                         errc(EX_SOFTWARE, serrno, "wait");
1266                         /* NOTREACHED */
1267                 }
1268         }
1269 }
1270
1271 /*
1272  * install_dir --
1273  *      build directory hierarchy
1274  */
1275 static void
1276 install_dir(char *path)
1277 {
1278         char *p;
1279         struct stat sb;
1280         int ch;
1281
1282         for (p = path;; ++p)
1283                 if (!*p || (p != path && *p  == '/')) {
1284                         ch = *p;
1285                         *p = '\0';
1286                         if (stat(path, &sb)) {
1287                                 if (errno != ENOENT || mkdir(path, 0755) < 0) {
1288                                         err(EX_OSERR, "mkdir %s", path);
1289                                         /* NOTREACHED */
1290                                 } else if (verbose)
1291                                         (void)printf("install: mkdir %s\n",
1292                                                      path);
1293                         } else if (!S_ISDIR(sb.st_mode))
1294                                 errx(EX_OSERR, "%s exists but is not a directory", path);
1295                         if (!(*p = ch))
1296                                 break;
1297                 }
1298
1299         if (!dounpriv) {
1300                 if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
1301                     chown(path, uid, gid))
1302                         warn("chown %u:%u %s", uid, gid, path);
1303                 /* XXXBED: should we do the chmod in the dounpriv case? */
1304                 if (chmod(path, mode))
1305                         warn("chmod %o %s", mode, path);
1306         }
1307         metadata_log(path, "dir", NULL, NULL, NULL, 0);
1308 }
1309
1310 /*
1311  * metadata_log --
1312  *      if metafp is not NULL, output mtree(8) full path name and settings to
1313  *      metafp, to allow permissions to be set correctly by other tools,
1314  *      or to allow integrity checks to be performed.
1315  */
1316 static void
1317 metadata_log(const char *path, const char *type, struct timeval *tv,
1318         const char *slink, const char *digestresult, off_t size)
1319 {
1320         static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1321         const char *p;
1322         char *buf;
1323         size_t destlen;
1324         struct flock metalog_lock;
1325
1326         if (!metafp)    
1327                 return;
1328         /* Buffer for strsvis(3). */
1329         buf = (char *)malloc(4 * strlen(path) + 1);
1330         if (buf == NULL) {
1331                 warnx("%s", strerror(ENOMEM));
1332                 return;
1333         }
1334
1335         /* Lock log file. */
1336         metalog_lock.l_start = 0;
1337         metalog_lock.l_len = 0;
1338         metalog_lock.l_whence = SEEK_SET;
1339         metalog_lock.l_type = F_WRLCK;
1340         if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1341                 warn("can't lock %s", metafile);
1342                 free(buf);
1343                 return;
1344         }
1345
1346         /* Remove destdir. */
1347         p = path;
1348         if (destdir) {
1349                 destlen = strlen(destdir);
1350                 if (strncmp(p, destdir, destlen) == 0 &&
1351                     (p[destlen] == '/' || p[destlen] == '\0'))
1352                         p += destlen;
1353         }
1354         while (*p && *p == '/')
1355                 p++;
1356         strsvis(buf, p, VIS_OCTAL, extra);
1357         p = buf;
1358         /* Print details. */
1359         fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1360         if (owner)
1361                 fprintf(metafp, " uname=%s", owner);
1362         if (group)
1363                 fprintf(metafp, " gname=%s", group);
1364         fprintf(metafp, " mode=%#o", mode);
1365         if (slink) {
1366                 strsvis(buf, slink, VIS_CSTYLE, extra); /* encode link */
1367                 fprintf(metafp, " link=%s", buf);
1368         }
1369         if (*type == 'f') /* type=file */
1370                 fprintf(metafp, " size=%lld", (long long)size);
1371         if (tv != NULL && dopreserve)
1372                 fprintf(metafp, " time=%lld.%ld",
1373                         (long long)tv[1].tv_sec, (long)tv[1].tv_usec);
1374         if (digestresult && digest)
1375                 fprintf(metafp, " %s=%s", digest, digestresult);
1376         if (fflags)
1377                 fprintf(metafp, " flags=%s", fflags);
1378         if (tags)
1379                 fprintf(metafp, " tags=%s", tags);
1380         fputc('\n', metafp);
1381         /* Flush line. */
1382         fflush(metafp);
1383
1384         /* Unlock log file. */
1385         metalog_lock.l_type = F_UNLCK;
1386         if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1)
1387                 warn("can't unlock %s", metafile);
1388         free(buf);
1389 }
1390
1391 /*
1392  * usage --
1393  *      print a usage message and die
1394  */
1395 static void
1396 usage(void)
1397 {
1398         (void)fprintf(stderr,
1399 "usage: install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1400 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1401 "               [-B suffix] [-l linkflags] [-N dbdir]\n"
1402 "               file1 file2\n"
1403 "       install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1404 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1405 "               [-B suffix] [-l linkflags] [-N dbdir]\n"
1406 "               file1 ... fileN directory\n"
1407 "       install -dU [-vU] [-g group] [-m mode] [-N dbdir] [-o owner]\n"
1408 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1409 "               directory ...\n");
1410         exit(EX_USAGE);
1411         /* NOTREACHED */
1412 }
1413
1414 /*
1415  * trymmap --
1416  *      return true (1) if mmap should be tried, false (0) if not.
1417  */
1418 static int
1419 trymmap(int fd)
1420 {
1421 /*
1422  * The ifdef is for bootstrapping - f_fstypename doesn't exist in
1423  * pre-Lite2-merge systems.
1424  */
1425 #ifdef MFSNAMELEN
1426         struct statfs stfs;
1427
1428         if (fstatfs(fd, &stfs) != 0)
1429                 return (0);
1430         if (strcmp(stfs.f_fstypename, "ufs") == 0 ||
1431             strcmp(stfs.f_fstypename, "cd9660") == 0)
1432                 return (1);
1433 #endif
1434         return (0);
1435 }