025c50cfafd2af65f94ecbf68406453b6349ce43
[dragonfly.git] / contrib / libarchive / cpio / cpio.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27
28 #include "cpio_platform.h"
29 __FBSDID("$FreeBSD: src/usr.bin/cpio/cpio.c,v 1.15 2008/12/06 07:30:40 kientzle Exp $");
30
31 #include <sys/types.h>
32 #include <archive.h>
33 #include <archive_entry.h>
34
35 #ifdef HAVE_SYS_MKDEV_H
36 #include <sys/mkdev.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50 #ifdef HAVE_GRP_H
51 #include <grp.h>
52 #endif
53 #ifdef HAVE_LOCALE_H
54 #include <locale.h>
55 #endif
56 #ifdef HAVE_PWD_H
57 #include <pwd.h>
58 #endif
59 #ifdef HAVE_SIGNAL_H
60 #include <signal.h>
61 #endif
62 #ifdef HAVE_STDARG_H
63 #include <stdarg.h>
64 #endif
65 #ifdef HAVE_STDINT_H
66 #include <stdint.h>
67 #endif
68 #include <stdio.h>
69 #ifdef HAVE_STDLIB_H
70 #include <stdlib.h>
71 #endif
72 #ifdef HAVE_STRING_H
73 #include <string.h>
74 #endif
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 #ifdef HAVE_TIME_H
79 #include <time.h>
80 #endif
81
82 #include "cpio.h"
83 #include "err.h"
84 #include "line_reader.h"
85 #include "matching.h"
86
87 /* Fixed size of uname/gname caches. */
88 #define name_cache_size 101
89
90 #ifndef O_BINARY
91 #define O_BINARY 0
92 #endif
93
94 struct name_cache {
95         int     probes;
96         int     hits;
97         size_t  size;
98         struct {
99                 id_t id;
100                 char *name;
101         } cache[name_cache_size];
102 };
103
104 static int      extract_data(struct archive *, struct archive *);
105 const char *    cpio_i64toa(int64_t);
106 static const char *cpio_rename(const char *name);
107 static int      entry_to_archive(struct cpio *, struct archive_entry *);
108 static int      file_to_archive(struct cpio *, const char *);
109 static void     free_cache(struct name_cache *cache);
110 static void     list_item_verbose(struct cpio *, struct archive_entry *);
111 static void     long_help(void);
112 static const char *lookup_gname(struct cpio *, gid_t gid);
113 static int      lookup_gname_helper(struct cpio *,
114                     const char **name, id_t gid);
115 static const char *lookup_uname(struct cpio *, uid_t uid);
116 static int      lookup_uname_helper(struct cpio *,
117                     const char **name, id_t uid);
118 static void     mode_in(struct cpio *);
119 static void     mode_list(struct cpio *);
120 static void     mode_out(struct cpio *);
121 static void     mode_pass(struct cpio *, const char *);
122 static int      restore_time(struct cpio *, struct archive_entry *,
123                     const char *, int fd);
124 static void     usage(void);
125 static void     version(void);
126
127 int
128 main(int argc, char *argv[])
129 {
130         static char buff[16384];
131         struct cpio _cpio; /* Allocated on stack. */
132         struct cpio *cpio;
133         const char *errmsg;
134         int uid, gid;
135         int opt;
136
137         cpio = &_cpio;
138         memset(cpio, 0, sizeof(*cpio));
139         cpio->buff = buff;
140         cpio->buff_size = sizeof(buff);
141
142 #if defined(HAVE_SIGACTION) && defined(SIGPIPE)
143         { /* Ignore SIGPIPE signals. */
144                 struct sigaction sa;
145                 sigemptyset(&sa.sa_mask);
146                 sa.sa_flags = 0;
147                 sa.sa_handler = SIG_IGN;
148                 sigaction(SIGPIPE, &sa, NULL);
149         }
150 #endif
151
152         /* Need lafe_progname before calling lafe_warnc. */
153         if (*argv == NULL)
154                 lafe_progname = "bsdcpio";
155         else {
156 #if defined(_WIN32) && !defined(__CYGWIN__)
157                 lafe_progname = strrchr(*argv, '\\');
158 #else
159                 lafe_progname = strrchr(*argv, '/');
160 #endif
161                 if (lafe_progname != NULL)
162                         lafe_progname++;
163                 else
164                         lafe_progname = *argv;
165         }
166 #if HAVE_SETLOCALE
167         if (setlocale(LC_ALL, "") == NULL)
168                 lafe_warnc(0, "Failed to set default locale");
169 #endif
170
171         cpio->uid_override = -1;
172         cpio->gid_override = -1;
173         cpio->argv = argv;
174         cpio->argc = argc;
175         cpio->mode = '\0';
176         cpio->verbose = 0;
177         cpio->compress = '\0';
178         cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
179         cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
180         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
181         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
182         cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
183         cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
184         cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
185 #if !defined(_WIN32) && !defined(__CYGWIN__)
186         if (geteuid() == 0)
187                 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
188 #endif
189         cpio->bytes_per_block = 512;
190         cpio->filename = NULL;
191
192         while ((opt = cpio_getopt(cpio)) != -1) {
193                 switch (opt) {
194                 case '0': /* GNU convention: --null, -0 */
195                         cpio->option_null = 1;
196                         break;
197                 case 'A': /* NetBSD/OpenBSD */
198                         cpio->option_append = 1;
199                         break;
200                 case 'a': /* POSIX 1997 */
201                         cpio->option_atime_restore = 1;
202                         break;
203                 case 'B': /* POSIX 1997 */
204                         cpio->bytes_per_block = 5120;
205                         break;
206                 case 'C': /* NetBSD/OpenBSD */
207                         cpio->bytes_per_block = atoi(cpio->argument);
208                         if (cpio->bytes_per_block <= 0)
209                                 lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
210                         break;
211                 case 'c': /* POSIX 1997 */
212                         cpio->format = "odc";
213                         break;
214                 case 'd': /* POSIX 1997 */
215                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
216                         break;
217                 case 'E': /* NetBSD/OpenBSD */
218                         lafe_include_from_file(&cpio->matching,
219                             cpio->argument, cpio->option_null);
220                         break;
221                 case 'F': /* NetBSD/OpenBSD/GNU cpio */
222                         cpio->filename = cpio->argument;
223                         break;
224                 case 'f': /* POSIX 1997 */
225                         lafe_exclude(&cpio->matching, cpio->argument);
226                         break;
227                 case 'H': /* GNU cpio (also --format) */
228                         cpio->format = cpio->argument;
229                         break;
230                 case 'h':
231                         long_help();
232                         break;
233                 case 'I': /* NetBSD/OpenBSD */
234                         cpio->filename = cpio->argument;
235                         break;
236                 case 'i': /* POSIX 1997 */
237                         if (cpio->mode != '\0')
238                                 lafe_errc(1, 0,
239                                     "Cannot use both -i and -%c", cpio->mode);
240                         cpio->mode = opt;
241                         break;
242                 case 'J': /* GNU tar, others */
243                         cpio->compress = opt;
244                         break;
245                 case 'j': /* GNU tar, others */
246                         cpio->compress = opt;
247                         break;
248                 case OPTION_INSECURE:
249                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
250                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
251                         break;
252                 case 'L': /* GNU cpio */
253                         cpio->option_follow_links = 1;
254                         break;
255                 case 'l': /* POSIX 1997 */
256                         cpio->option_link = 1;
257                         break;
258                 case OPTION_LZMA: /* GNU tar, others */
259                         cpio->compress = opt;
260                         break;
261                 case 'm': /* POSIX 1997 */
262                         cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
263                         break;
264                 case 'n': /* GNU cpio */
265                         cpio->option_numeric_uid_gid = 1;
266                         break;
267                 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
268                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
269                         break;
270                 case 'O': /* GNU cpio */
271                         cpio->filename = cpio->argument;
272                         break;
273                 case 'o': /* POSIX 1997 */
274                         if (cpio->mode != '\0')
275                                 lafe_errc(1, 0,
276                                     "Cannot use both -o and -%c", cpio->mode);
277                         cpio->mode = opt;
278                         break;
279                 case 'p': /* POSIX 1997 */
280                         if (cpio->mode != '\0')
281                                 lafe_errc(1, 0,
282                                     "Cannot use both -p and -%c", cpio->mode);
283                         cpio->mode = opt;
284                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
285                         break;
286                 case OPTION_PRESERVE_OWNER:
287                         cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
288                         break;
289                 case OPTION_QUIET: /* GNU cpio */
290                         cpio->quiet = 1;
291                         break;
292                 case 'R': /* GNU cpio, also --owner */
293                         /* TODO: owner_parse should return uname/gname
294                          * also; use that to set [ug]name_override. */
295                         errmsg = owner_parse(cpio->argument, &uid, &gid);
296                         if (errmsg) {
297                                 lafe_warnc(-1, "%s", errmsg);
298                                 usage();
299                         }
300                         if (uid != -1) {
301                                 cpio->uid_override = uid;
302                                 cpio->uname_override = NULL;
303                         }
304                         if (gid != -1) {
305                                 cpio->gid_override = gid;
306                                 cpio->gname_override = NULL;
307                         }
308                         break;
309                 case 'r': /* POSIX 1997 */
310                         cpio->option_rename = 1;
311                         break;
312                 case 't': /* POSIX 1997 */
313                         cpio->option_list = 1;
314                         break;
315                 case 'u': /* POSIX 1997 */
316                         cpio->extract_flags
317                             &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
318                         break;
319                 case 'v': /* POSIX 1997 */
320                         cpio->verbose++;
321                         break;
322                 case 'V': /* GNU cpio */
323                         cpio->dot++;
324                         break;
325                 case OPTION_VERSION: /* GNU convention */
326                         version();
327                         break;
328 #if 0
329                 /*
330                  * cpio_getopt() handles -W specially, so it's not
331                  * available here.
332                  */
333                 case 'W': /* Obscure, but useful GNU convention. */
334                         break;
335 #endif
336                 case 'y': /* tar convention */
337                         cpio->compress = opt;
338                         break;
339                 case 'Z': /* tar convention */
340                         cpio->compress = opt;
341                         break;
342                 case 'z': /* tar convention */
343                         cpio->compress = opt;
344                         break;
345                 default:
346                         usage();
347                 }
348         }
349
350         /*
351          * Sanity-check args, error out on nonsensical combinations.
352          */
353         /* -t implies -i if no mode was specified. */
354         if (cpio->option_list && cpio->mode == '\0')
355                 cpio->mode = 'i';
356         /* -t requires -i */
357         if (cpio->option_list && cpio->mode != 'i')
358                 lafe_errc(1, 0, "Option -t requires -i");
359         /* -n requires -it */
360         if (cpio->option_numeric_uid_gid && !cpio->option_list)
361                 lafe_errc(1, 0, "Option -n requires -it");
362         /* Can only specify format when writing */
363         if (cpio->format != NULL && cpio->mode != 'o')
364                 lafe_errc(1, 0, "Option --format requires -o");
365         /* -l requires -p */
366         if (cpio->option_link && cpio->mode != 'p')
367                 lafe_errc(1, 0, "Option -l requires -p");
368         /* -v overrides -V */
369         if (cpio->dot && cpio->verbose)
370                 cpio->dot = 0;
371         /* -v overrides -V */
372         if (cpio->dot && cpio->verbose)
373                 cpio->dot = 0;
374         /* TODO: Flag other nonsensical combinations. */
375
376         switch (cpio->mode) {
377         case 'o':
378                 /* TODO: Implement old binary format in libarchive,
379                    use that here. */
380                 if (cpio->format == NULL)
381                         cpio->format = "odc"; /* Default format */
382
383                 mode_out(cpio);
384                 break;
385         case 'i':
386                 while (*cpio->argv != NULL) {
387                         lafe_include(&cpio->matching, *cpio->argv);
388                         --cpio->argc;
389                         ++cpio->argv;
390                 }
391                 if (cpio->option_list)
392                         mode_list(cpio);
393                 else
394                         mode_in(cpio);
395                 break;
396         case 'p':
397                 if (*cpio->argv == NULL || **cpio->argv == '\0')
398                         lafe_errc(1, 0,
399                             "-p mode requires a target directory");
400                 mode_pass(cpio, *cpio->argv);
401                 break;
402         default:
403                 lafe_errc(1, 0,
404                     "Must specify at least one of -i, -o, or -p");
405         }
406
407         free_cache(cpio->gname_cache);
408         free_cache(cpio->uname_cache);
409         return (cpio->return_value);
410 }
411
412 static void
413 usage(void)
414 {
415         const char      *p;
416
417         p = lafe_progname;
418
419         fprintf(stderr, "Brief Usage:\n");
420         fprintf(stderr, "  List:    %s -it < archive\n", p);
421         fprintf(stderr, "  Extract: %s -i < archive\n", p);
422         fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
423         fprintf(stderr, "  Help:    %s --help\n", p);
424         exit(1);
425 }
426
427 static const char *long_help_msg =
428         "First option must be a mode specifier:\n"
429         "  -i Input  -o Output  -p Pass\n"
430         "Common Options:\n"
431         "  -v Verbose filenames     -V  one dot per file\n"
432         "Create: %p -o [options]  < [list of files] > [archive]\n"
433         "  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
434         "  --format {odc|newc|ustar}  Select archive format\n"
435         "List: %p -it < [archive]\n"
436         "Extract: %p -i [options] < [archive]\n";
437
438
439 /*
440  * Note that the word 'bsdcpio' will always appear in the first line
441  * of output.
442  *
443  * In particular, /bin/sh scripts that need to test for the presence
444  * of bsdcpio can use the following template:
445  *
446  * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
447  *          echo bsdcpio; else echo not bsdcpio; fi
448  */
449 static void
450 long_help(void)
451 {
452         const char      *prog;
453         const char      *p;
454
455         prog = lafe_progname;
456
457         fflush(stderr);
458
459         p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
460         printf("%s%s: manipulate archive files\n", prog, p);
461
462         for (p = long_help_msg; *p != '\0'; p++) {
463                 if (*p == '%') {
464                         if (p[1] == 'p') {
465                                 fputs(prog, stdout);
466                                 p++;
467                         } else
468                                 putchar('%');
469                 } else
470                         putchar(*p);
471         }
472         version();
473 }
474
475 static void
476 version(void)
477 {
478         fprintf(stdout,"bsdcpio %s -- %s\n",
479             BSDCPIO_VERSION_STRING,
480             archive_version_string());
481         exit(0);
482 }
483
484 static void
485 mode_out(struct cpio *cpio)
486 {
487         struct archive_entry *entry, *spare;
488         struct lafe_line_reader *lr;
489         const char *p;
490         int r;
491
492         if (cpio->option_append)
493                 lafe_errc(1, 0, "Append mode not yet supported.");
494
495         cpio->archive_read_disk = archive_read_disk_new();
496         if (cpio->archive_read_disk == NULL)
497                 lafe_errc(1, 0, "Failed to allocate archive object");
498         if (cpio->option_follow_links)
499                 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
500         else
501                 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
502         archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
503
504         cpio->archive = archive_write_new();
505         if (cpio->archive == NULL)
506                 lafe_errc(1, 0, "Failed to allocate archive object");
507         switch (cpio->compress) {
508         case 'J':
509                 r = archive_write_set_compression_xz(cpio->archive);
510                 break;
511         case OPTION_LZMA:
512                 r = archive_write_set_compression_lzma(cpio->archive);
513                 break;
514         case 'j': case 'y':
515                 r = archive_write_set_compression_bzip2(cpio->archive);
516                 break;
517         case 'z':
518                 r = archive_write_set_compression_gzip(cpio->archive);
519                 break;
520         case 'Z':
521                 r = archive_write_set_compression_compress(cpio->archive);
522                 break;
523         default:
524                 r = archive_write_set_compression_none(cpio->archive);
525                 break;
526         }
527         if (r < ARCHIVE_WARN)
528                 lafe_errc(1, 0, "Requested compression not available");
529         r = archive_write_set_format_by_name(cpio->archive, cpio->format);
530         if (r != ARCHIVE_OK)
531                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
532         archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
533         cpio->linkresolver = archive_entry_linkresolver_new();
534         archive_entry_linkresolver_set_strategy(cpio->linkresolver,
535             archive_format(cpio->archive));
536
537         /*
538          * The main loop:  Copy each file into the output archive.
539          */
540         r = archive_write_open_file(cpio->archive, cpio->filename);
541         if (r != ARCHIVE_OK)
542                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
543         lr = lafe_line_reader("-", cpio->option_null);
544         while ((p = lafe_line_reader_next(lr)) != NULL)
545                 file_to_archive(cpio, p);
546         lafe_line_reader_free(lr);
547
548         /*
549          * The hardlink detection may have queued up a couple of entries
550          * that can now be flushed.
551          */
552         entry = NULL;
553         archive_entry_linkify(cpio->linkresolver, &entry, &spare);
554         while (entry != NULL) {
555                 entry_to_archive(cpio, entry);
556                 archive_entry_free(entry);
557                 entry = NULL;
558                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
559         }
560
561         r = archive_write_close(cpio->archive);
562         if (cpio->dot)
563                 fprintf(stderr, "\n");
564         if (r != ARCHIVE_OK)
565                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
566
567         if (!cpio->quiet) {
568                 int64_t blocks =
569                         (archive_position_uncompressed(cpio->archive) + 511)
570                         / 512;
571                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
572                     blocks == 1 ? "block" : "blocks");
573         }
574         archive_write_free(cpio->archive);
575 }
576
577 /*
578  * This is used by both out mode (to copy objects from disk into
579  * an archive) and pass mode (to copy objects from disk to
580  * an archive_write_disk "archive").
581  */
582 static int
583 file_to_archive(struct cpio *cpio, const char *srcpath)
584 {
585         const char *destpath;
586         struct archive_entry *entry, *spare;
587         size_t len;
588         const char *p;
589         int r;
590
591         /*
592          * Create an archive_entry describing the source file.
593          *
594          */
595         entry = archive_entry_new();
596         if (entry == NULL)
597                 lafe_errc(1, 0, "Couldn't allocate entry");
598         archive_entry_copy_sourcepath(entry, srcpath);
599         r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
600             entry, -1, NULL);
601         if (r < ARCHIVE_FAILED)
602                 lafe_errc(1, 0, "%s",
603                     archive_error_string(cpio->archive_read_disk));
604         if (r < ARCHIVE_OK)
605                 lafe_warnc(0, "%s",
606                     archive_error_string(cpio->archive_read_disk));
607         if (r <= ARCHIVE_FAILED) {
608                 cpio->return_value = 1;
609                 return (r);
610         }
611
612         if (cpio->uid_override >= 0) {
613                 archive_entry_set_uid(entry, cpio->uid_override);
614                 archive_entry_set_uname(entry, cpio->uname_override);
615         }
616         if (cpio->gid_override >= 0) {
617                 archive_entry_set_gid(entry, cpio->gid_override);
618                 archive_entry_set_gname(entry, cpio->gname_override);
619         }
620
621         /*
622          * Generate a destination path for this entry.
623          * "destination path" is the name to which it will be copied in
624          * pass mode or the name that will go into the archive in
625          * output mode.
626          */
627         destpath = srcpath;
628         if (cpio->destdir) {
629                 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
630                 if (len >= cpio->pass_destpath_alloc) {
631                         while (len >= cpio->pass_destpath_alloc) {
632                                 cpio->pass_destpath_alloc += 512;
633                                 cpio->pass_destpath_alloc *= 2;
634                         }
635                         free(cpio->pass_destpath);
636                         cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
637                         if (cpio->pass_destpath == NULL)
638                                 lafe_errc(1, ENOMEM,
639                                     "Can't allocate path buffer");
640                 }
641                 strcpy(cpio->pass_destpath, cpio->destdir);
642                 p = srcpath;
643                 while (p[0] == '/')
644                         ++p;
645                 strcat(cpio->pass_destpath, p);
646                 destpath = cpio->pass_destpath;
647         }
648         if (cpio->option_rename)
649                 destpath = cpio_rename(destpath);
650         if (destpath == NULL)
651                 return (0);
652         archive_entry_copy_pathname(entry, destpath);
653
654         /*
655          * If we're trying to preserve hardlinks, match them here.
656          */
657         spare = NULL;
658         if (cpio->linkresolver != NULL
659             && archive_entry_filetype(entry) != AE_IFDIR) {
660                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
661         }
662
663         if (entry != NULL) {
664                 r = entry_to_archive(cpio, entry);
665                 archive_entry_free(entry);
666                 if (spare != NULL) {
667                         if (r == 0)
668                                 r = entry_to_archive(cpio, spare);
669                         archive_entry_free(spare);
670                 }
671         }
672         return (r);
673 }
674
675 static int
676 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
677 {
678         const char *destpath = archive_entry_pathname(entry);
679         const char *srcpath = archive_entry_sourcepath(entry);
680         int fd = -1;
681         ssize_t bytes_read;
682         int r;
683
684         /* Print out the destination name to the user. */
685         if (cpio->verbose)
686                 fprintf(stderr,"%s", destpath);
687         if (cpio->dot)
688                 fprintf(stderr, ".");
689
690         /*
691          * Option_link only makes sense in pass mode and for
692          * regular files.  Also note: if a link operation fails
693          * because of cross-device restrictions, we'll fall back
694          * to copy mode for that entry.
695          *
696          * TODO: Test other cpio implementations to see if they
697          * hard-link anything other than regular files here.
698          */
699         if (cpio->option_link
700             && archive_entry_filetype(entry) == AE_IFREG)
701         {
702                 struct archive_entry *t;
703                 /* Save the original entry in case we need it later. */
704                 t = archive_entry_clone(entry);
705                 if (t == NULL)
706                         lafe_errc(1, ENOMEM, "Can't create link");
707                 /* Note: link(2) doesn't create parent directories,
708                  * so we use archive_write_header() instead as a
709                  * convenience. */
710                 archive_entry_set_hardlink(t, srcpath);
711                 /* This is a straight link that carries no data. */
712                 archive_entry_set_size(t, 0);
713                 r = archive_write_header(cpio->archive, t);
714                 archive_entry_free(t);
715                 if (r != ARCHIVE_OK)
716                         lafe_warnc(archive_errno(cpio->archive),
717                             "%s", archive_error_string(cpio->archive));
718                 if (r == ARCHIVE_FATAL)
719                         exit(1);
720 #ifdef EXDEV
721                 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
722                         /* Cross-device link:  Just fall through and use
723                          * the original entry to copy the file over. */
724                         lafe_warnc(0, "Copying file instead");
725                 } else
726 #endif
727                 return (0);
728         }
729
730         /*
731          * Make sure we can open the file (if necessary) before
732          * trying to write the header.
733          */
734         if (archive_entry_filetype(entry) == AE_IFREG) {
735                 if (archive_entry_size(entry) > 0) {
736                         fd = open(srcpath, O_RDONLY | O_BINARY);
737                         if (fd < 0) {
738                                 lafe_warnc(errno,
739                                     "%s: could not open file", srcpath);
740                                 goto cleanup;
741                         }
742                 }
743         } else {
744                 archive_entry_set_size(entry, 0);
745         }
746
747         r = archive_write_header(cpio->archive, entry);
748
749         if (r != ARCHIVE_OK)
750                 lafe_warnc(archive_errno(cpio->archive),
751                     "%s: %s",
752                     srcpath,
753                     archive_error_string(cpio->archive));
754
755         if (r == ARCHIVE_FATAL)
756                 exit(1);
757
758         if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
759                 bytes_read = read(fd, cpio->buff, cpio->buff_size);
760                 while (bytes_read > 0) {
761                         r = archive_write_data(cpio->archive,
762                             cpio->buff, bytes_read);
763                         if (r < 0)
764                                 lafe_errc(1, archive_errno(cpio->archive),
765                                     "%s", archive_error_string(cpio->archive));
766                         if (r < bytes_read) {
767                                 lafe_warnc(0,
768                                     "Truncated write; file may have grown while being archived.");
769                         }
770                         bytes_read = read(fd, cpio->buff, cpio->buff_size);
771                 }
772         }
773
774         fd = restore_time(cpio, entry, srcpath, fd);
775
776 cleanup:
777         if (cpio->verbose)
778                 fprintf(stderr,"\n");
779         if (fd >= 0)
780                 close(fd);
781         return (0);
782 }
783
784 static int
785 restore_time(struct cpio *cpio, struct archive_entry *entry,
786     const char *name, int fd)
787 {
788 #ifndef HAVE_UTIMES
789         static int warned = 0;
790
791         (void)cpio; /* UNUSED */
792         (void)entry; /* UNUSED */
793         (void)name; /* UNUSED */
794
795         if (!warned)
796                 lafe_warnc(0, "Can't restore access times on this platform");
797         warned = 1;
798         return (fd);
799 #else
800 #if defined(_WIN32) && !defined(__CYGWIN__)
801         struct __timeval times[2];
802 #else
803         struct timeval times[2];
804 #endif
805
806         if (!cpio->option_atime_restore)
807                 return (fd);
808
809         times[1].tv_sec = archive_entry_mtime(entry);
810         times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
811
812         times[0].tv_sec = archive_entry_atime(entry);
813         times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
814
815 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
816         if (fd >= 0 && futimes(fd, times) == 0)
817                 return (fd);
818 #endif
819         /*
820          * Some platform cannot restore access times if the file descriptor
821          * is still opened.
822          */
823         if (fd >= 0) {
824                 close(fd);
825                 fd = -1;
826         }
827
828 #ifdef HAVE_LUTIMES
829         if (lutimes(name, times) != 0)
830 #else
831         if ((AE_IFLNK != archive_entry_filetype(entry))
832                         && utimes(name, times) != 0)
833 #endif
834                 lafe_warnc(errno, "Can't update time for %s", name);
835 #endif
836         return (fd);
837 }
838
839
840 static void
841 mode_in(struct cpio *cpio)
842 {
843         struct archive *a;
844         struct archive_entry *entry;
845         struct archive *ext;
846         const char *destpath;
847         int r;
848
849         ext = archive_write_disk_new();
850         if (ext == NULL)
851                 lafe_errc(1, 0, "Couldn't allocate restore object");
852         r = archive_write_disk_set_options(ext, cpio->extract_flags);
853         if (r != ARCHIVE_OK)
854                 lafe_errc(1, 0, "%s", archive_error_string(ext));
855         a = archive_read_new();
856         if (a == NULL)
857                 lafe_errc(1, 0, "Couldn't allocate archive object");
858         archive_read_support_filter_all(a);
859         archive_read_support_format_all(a);
860
861         if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
862                 lafe_errc(1, archive_errno(a),
863                     "%s", archive_error_string(a));
864         for (;;) {
865                 r = archive_read_next_header(a, &entry);
866                 if (r == ARCHIVE_EOF)
867                         break;
868                 if (r != ARCHIVE_OK) {
869                         lafe_errc(1, archive_errno(a),
870                             "%s", archive_error_string(a));
871                 }
872                 if (lafe_excluded(cpio->matching, archive_entry_pathname(entry)))
873                         continue;
874                 if (cpio->option_rename) {
875                         destpath = cpio_rename(archive_entry_pathname(entry));
876                         archive_entry_set_pathname(entry, destpath);
877                 } else
878                         destpath = archive_entry_pathname(entry);
879                 if (destpath == NULL)
880                         continue;
881                 if (cpio->verbose)
882                         fprintf(stderr, "%s\n", destpath);
883                 if (cpio->dot)
884                         fprintf(stderr, ".");
885                 if (cpio->uid_override >= 0)
886                         archive_entry_set_uid(entry, cpio->uid_override);
887                 if (cpio->gid_override >= 0)
888                         archive_entry_set_gid(entry, cpio->gid_override);
889                 r = archive_write_header(ext, entry);
890                 if (r != ARCHIVE_OK) {
891                         fprintf(stderr, "%s: %s\n",
892                             archive_entry_pathname(entry),
893                             archive_error_string(ext));
894                 } else if (!archive_entry_size_is_set(entry)
895                     || archive_entry_size(entry) > 0) {
896                         r = extract_data(a, ext);
897                         if (r != ARCHIVE_OK)
898                                 cpio->return_value = 1;
899                 }
900         }
901         r = archive_read_close(a);
902         if (cpio->dot)
903                 fprintf(stderr, "\n");
904         if (r != ARCHIVE_OK)
905                 lafe_errc(1, 0, "%s", archive_error_string(a));
906         r = archive_write_close(ext);
907         if (r != ARCHIVE_OK)
908                 lafe_errc(1, 0, "%s", archive_error_string(ext));
909         if (!cpio->quiet) {
910                 int64_t blocks = (archive_position_uncompressed(a) + 511)
911                               / 512;
912                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
913                     blocks == 1 ? "block" : "blocks");
914         }
915         archive_read_free(a);
916         archive_write_free(ext);
917         exit(cpio->return_value);
918 }
919
920 /*
921  * Exits if there's a fatal error.  Returns ARCHIVE_OK
922  * if everything is kosher.
923  */
924 static int
925 extract_data(struct archive *ar, struct archive *aw)
926 {
927         int r;
928         size_t size;
929         const void *block;
930         int64_t offset;
931
932         for (;;) {
933                 r = archive_read_data_block(ar, &block, &size, &offset);
934                 if (r == ARCHIVE_EOF)
935                         return (ARCHIVE_OK);
936                 if (r != ARCHIVE_OK) {
937                         lafe_warnc(archive_errno(ar),
938                             "%s", archive_error_string(ar));
939                         exit(1);
940                 }
941                 r = archive_write_data_block(aw, block, size, offset);
942                 if (r != ARCHIVE_OK) {
943                         lafe_warnc(archive_errno(aw),
944                             "%s", archive_error_string(aw));
945                         return (r);
946                 }
947         }
948 }
949
950 static void
951 mode_list(struct cpio *cpio)
952 {
953         struct archive *a;
954         struct archive_entry *entry;
955         int r;
956
957         a = archive_read_new();
958         if (a == NULL)
959                 lafe_errc(1, 0, "Couldn't allocate archive object");
960         archive_read_support_filter_all(a);
961         archive_read_support_format_all(a);
962
963         if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
964                 lafe_errc(1, archive_errno(a),
965                     "%s", archive_error_string(a));
966         for (;;) {
967                 r = archive_read_next_header(a, &entry);
968                 if (r == ARCHIVE_EOF)
969                         break;
970                 if (r != ARCHIVE_OK) {
971                         lafe_errc(1, archive_errno(a),
972                             "%s", archive_error_string(a));
973                 }
974                 if (lafe_excluded(cpio->matching, archive_entry_pathname(entry)))
975                         continue;
976                 if (cpio->verbose)
977                         list_item_verbose(cpio, entry);
978                 else
979                         fprintf(stdout, "%s\n", archive_entry_pathname(entry));
980         }
981         r = archive_read_close(a);
982         if (r != ARCHIVE_OK)
983                 lafe_errc(1, 0, "%s", archive_error_string(a));
984         if (!cpio->quiet) {
985                 int64_t blocks = (archive_position_uncompressed(a) + 511)
986                               / 512;
987                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
988                     blocks == 1 ? "block" : "blocks");
989         }
990         archive_read_free(a);
991         exit(0);
992 }
993
994 /*
995  * Display information about the current file.
996  *
997  * The format here roughly duplicates the output of 'ls -l'.
998  * This is based on SUSv2, where 'tar tv' is documented as
999  * listing additional information in an "unspecified format,"
1000  * and 'pax -l' is documented as using the same format as 'ls -l'.
1001  */
1002 static void
1003 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1004 {
1005         char                     size[32];
1006         char                     date[32];
1007         char                     uids[16], gids[16];
1008         const char              *uname, *gname;
1009         FILE                    *out = stdout;
1010         const char              *fmt;
1011         time_t                   mtime;
1012         static time_t            now;
1013
1014         if (!now)
1015                 time(&now);
1016
1017         if (cpio->option_numeric_uid_gid) {
1018                 /* Format numeric uid/gid for display. */
1019                 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1020                 uname = uids;
1021                 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1022                 gname = gids;
1023         } else {
1024                 /* Use uname if it's present, else lookup name from uid. */
1025                 uname = archive_entry_uname(entry);
1026                 if (uname == NULL)
1027                         uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1028                 /* Use gname if it's present, else lookup name from gid. */
1029                 gname = archive_entry_gname(entry);
1030                 if (gname == NULL)
1031                         gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1032         }
1033
1034         /* Print device number or file size. */
1035         if (archive_entry_filetype(entry) == AE_IFCHR
1036             || archive_entry_filetype(entry) == AE_IFBLK) {
1037                 snprintf(size, sizeof(size), "%lu,%lu",
1038                     (unsigned long)archive_entry_rdevmajor(entry),
1039                     (unsigned long)archive_entry_rdevminor(entry));
1040         } else {
1041                 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1042         }
1043
1044         /* Format the time using 'ls -l' conventions. */
1045         mtime = archive_entry_mtime(entry);
1046 #if defined(_WIN32) && !defined(__CYGWIN__)
1047         /* Windows' strftime function does not support %e format. */
1048         if (mtime - now > 365*86400/2
1049                 || mtime - now < -365*86400/2)
1050                 fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1051         else
1052                 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1053 #else
1054         if (abs(mtime - now) > (365/2)*86400)
1055                 fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1056         else
1057                 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1058 #endif
1059         strftime(date, sizeof(date), fmt, localtime(&mtime));
1060
1061         fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1062             archive_entry_strmode(entry),
1063             archive_entry_nlink(entry),
1064             uname, gname, size, date,
1065             archive_entry_pathname(entry));
1066
1067         /* Extra information for links. */
1068         if (archive_entry_hardlink(entry)) /* Hard link */
1069                 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1070         else if (archive_entry_symlink(entry)) /* Symbolic link */
1071                 fprintf(out, " -> %s", archive_entry_symlink(entry));
1072         fprintf(out, "\n");
1073 }
1074
1075 static void
1076 mode_pass(struct cpio *cpio, const char *destdir)
1077 {
1078         struct lafe_line_reader *lr;
1079         const char *p;
1080         int r;
1081
1082         /* Ensure target dir has a trailing '/' to simplify path surgery. */
1083         cpio->destdir = malloc(strlen(destdir) + 8);
1084         strcpy(cpio->destdir, destdir);
1085         if (destdir[strlen(destdir) - 1] != '/')
1086                 strcat(cpio->destdir, "/");
1087
1088         cpio->archive = archive_write_disk_new();
1089         if (cpio->archive == NULL)
1090                 lafe_errc(1, 0, "Failed to allocate archive object");
1091         r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1092         if (r != ARCHIVE_OK)
1093                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1094         cpio->linkresolver = archive_entry_linkresolver_new();
1095         archive_write_disk_set_standard_lookup(cpio->archive);
1096
1097         cpio->archive_read_disk = archive_read_disk_new();
1098         if (cpio->archive_read_disk == NULL)
1099                 lafe_errc(1, 0, "Failed to allocate archive object");
1100         if (cpio->option_follow_links)
1101                 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1102         else
1103                 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1104         archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1105
1106         lr = lafe_line_reader("-", cpio->option_null);
1107         while ((p = lafe_line_reader_next(lr)) != NULL)
1108                 file_to_archive(cpio, p);
1109         lafe_line_reader_free(lr);
1110
1111         archive_entry_linkresolver_free(cpio->linkresolver);
1112         r = archive_write_close(cpio->archive);
1113         if (cpio->dot)
1114                 fprintf(stderr, "\n");
1115         if (r != ARCHIVE_OK)
1116                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1117
1118         if (!cpio->quiet) {
1119                 int64_t blocks =
1120                         (archive_position_uncompressed(cpio->archive) + 511)
1121                         / 512;
1122                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1123                     blocks == 1 ? "block" : "blocks");
1124         }
1125
1126         archive_write_free(cpio->archive);
1127 }
1128
1129 /*
1130  * Prompt for a new name for this entry.  Returns a pointer to the
1131  * new name or NULL if the entry should not be copied.  This
1132  * implements the semantics defined in POSIX.1-1996, which specifies
1133  * that an input of '.' means the name should be unchanged.  GNU cpio
1134  * treats '.' as a literal new name.
1135  */
1136 static const char *
1137 cpio_rename(const char *name)
1138 {
1139         static char buff[1024];
1140         FILE *t;
1141         char *p, *ret;
1142
1143         t = fopen("/dev/tty", "r+");
1144         if (t == NULL)
1145                 return (name);
1146         fprintf(t, "%s (Enter/./(new name))? ", name);
1147         fflush(t);
1148
1149         p = fgets(buff, sizeof(buff), t);
1150         fclose(t);
1151         if (p == NULL)
1152                 /* End-of-file is a blank line. */
1153                 return (NULL);
1154
1155         while (*p == ' ' || *p == '\t')
1156                 ++p;
1157         if (*p == '\n' || *p == '\0')
1158                 /* Empty line. */
1159                 return (NULL);
1160         if (*p == '.' && p[1] == '\n')
1161                 /* Single period preserves original name. */
1162                 return (name);
1163         ret = p;
1164         /* Trim the final newline. */
1165         while (*p != '\0' && *p != '\n')
1166                 ++p;
1167         /* Overwrite the final \n with a null character. */
1168         *p = '\0';
1169         return (ret);
1170 }
1171
1172 static void
1173 free_cache(struct name_cache *cache)
1174 {
1175         size_t i;
1176
1177         if (cache != NULL) {
1178                 for (i = 0; i < cache->size; i++)
1179                         free(cache->cache[i].name);
1180                 free(cache);
1181         }
1182 }
1183
1184 /*
1185  * Lookup uname/gname from uid/gid, return NULL if no match.
1186  */
1187 static const char *
1188 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1189     int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1190 {
1191         char asnum[16];
1192         struct name_cache       *cache;
1193         const char *name;
1194         int slot;
1195
1196
1197         if (*name_cache_variable == NULL) {
1198                 *name_cache_variable = malloc(sizeof(struct name_cache));
1199                 if (*name_cache_variable == NULL)
1200                         lafe_errc(1, ENOMEM, "No more memory");
1201                 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1202                 (*name_cache_variable)->size = name_cache_size;
1203         }
1204
1205         cache = *name_cache_variable;
1206         cache->probes++;
1207
1208         slot = id % cache->size;
1209         if (cache->cache[slot].name != NULL) {
1210                 if (cache->cache[slot].id == id) {
1211                         cache->hits++;
1212                         return (cache->cache[slot].name);
1213                 }
1214                 free(cache->cache[slot].name);
1215                 cache->cache[slot].name = NULL;
1216         }
1217
1218         if (lookup_fn(cpio, &name, id) == 0) {
1219                 if (name == NULL || name[0] == '\0') {
1220                         /* If lookup failed, format it as a number. */
1221                         snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1222                         name = asnum;
1223                 }
1224                 cache->cache[slot].name = strdup(name);
1225                 if (cache->cache[slot].name != NULL) {
1226                         cache->cache[slot].id = id;
1227                         return (cache->cache[slot].name);
1228                 }
1229                 /*
1230                  * Conveniently, NULL marks an empty slot, so
1231                  * if the strdup() fails, we've just failed to
1232                  * cache it.  No recovery necessary.
1233                  */
1234         }
1235         return (NULL);
1236 }
1237
1238 static const char *
1239 lookup_uname(struct cpio *cpio, uid_t uid)
1240 {
1241         return (lookup_name(cpio, &cpio->uname_cache,
1242                     &lookup_uname_helper, (id_t)uid));
1243 }
1244
1245 static int
1246 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1247 {
1248         struct passwd   *pwent;
1249
1250         (void)cpio; /* UNUSED */
1251
1252         errno = 0;
1253         pwent = getpwuid((uid_t)id);
1254         if (pwent == NULL) {
1255                 *name = NULL;
1256                 if (errno != 0 && errno != ENOENT)
1257                         lafe_warnc(errno, "getpwuid(%d) failed", id);
1258                 return (errno);
1259         }
1260
1261         *name = pwent->pw_name;
1262         return (0);
1263 }
1264
1265 static const char *
1266 lookup_gname(struct cpio *cpio, gid_t gid)
1267 {
1268         return (lookup_name(cpio, &cpio->gname_cache,
1269                     &lookup_gname_helper, (id_t)gid));
1270 }
1271
1272 static int
1273 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1274 {
1275         struct group    *grent;
1276
1277         (void)cpio; /* UNUSED */
1278
1279         errno = 0;
1280         grent = getgrgid((gid_t)id);
1281         if (grent == NULL) {
1282                 *name = NULL;
1283                 if (errno != 0)
1284                         lafe_warnc(errno, "getgrgid(%d) failed", id);
1285                 return (errno);
1286         }
1287
1288         *name = grent->gr_name;
1289         return (0);
1290 }
1291
1292 /*
1293  * It would be nice to just use printf() for formatting large numbers,
1294  * but the compatibility problems are a big headache.  Hence the
1295  * following simple utility function.
1296  */
1297 const char *
1298 cpio_i64toa(int64_t n0)
1299 {
1300         /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1301          * We also need 1 byte for '-' and 1 for '\0'.
1302          */
1303         static char buff[22];
1304         int64_t n = n0 < 0 ? -n0 : n0;
1305         char *p = buff + sizeof(buff);
1306
1307         *--p = '\0';
1308         do {
1309                 *--p = '0' + (int)(n % 10);
1310                 n /= 10;
1311         } while (n > 0);
1312         if (n0 < 0)
1313                 *--p = '-';
1314         return p;
1315 }