Import libarchive-3.3.3
[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 "passphrase.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) __LA_DEAD;
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 *) __LA_DEAD;
119 static void     mode_list(struct cpio *) __LA_DEAD;
120 static void     mode_out(struct cpio *);
121 static void     mode_pass(struct cpio *, const char *);
122 static const char *remove_leading_slash(const char *);
123 static int      restore_time(struct cpio *, struct archive_entry *,
124                     const char *, int fd);
125 static void     usage(void) __LA_DEAD;
126 static void     version(void) __LA_DEAD;
127 static const char * passphrase_callback(struct archive *, void *);
128 static void     passphrase_free(char *);
129
130 int
131 main(int argc, char *argv[])
132 {
133         static char buff[16384];
134         struct cpio _cpio; /* Allocated on stack. */
135         struct cpio *cpio;
136         const char *errmsg;
137         int uid, gid;
138         int opt;
139
140         cpio = &_cpio;
141         memset(cpio, 0, sizeof(*cpio));
142         cpio->buff = buff;
143         cpio->buff_size = sizeof(buff);
144
145 #if defined(HAVE_SIGACTION) && defined(SIGPIPE)
146         { /* Ignore SIGPIPE signals. */
147                 struct sigaction sa;
148                 sigemptyset(&sa.sa_mask);
149                 sa.sa_flags = 0;
150                 sa.sa_handler = SIG_IGN;
151                 sigaction(SIGPIPE, &sa, NULL);
152         }
153 #endif
154
155         /* Set lafe_progname before calling lafe_warnc. */
156         lafe_setprogname(*argv, "bsdcpio");
157
158 #if HAVE_SETLOCALE
159         if (setlocale(LC_ALL, "") == NULL)
160                 lafe_warnc(0, "Failed to set default locale");
161 #endif
162
163         cpio->uid_override = -1;
164         cpio->gid_override = -1;
165         cpio->argv = argv;
166         cpio->argc = argc;
167         cpio->mode = '\0';
168         cpio->verbose = 0;
169         cpio->compress = '\0';
170         cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
171         cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
172         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
173         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
174         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
175         cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
176         cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
177         cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
178 #if !defined(_WIN32) && !defined(__CYGWIN__)
179         if (geteuid() == 0)
180                 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
181 #endif
182         cpio->bytes_per_block = 512;
183         cpio->filename = NULL;
184
185         cpio->matching = archive_match_new();
186         if (cpio->matching == NULL)
187                 lafe_errc(1, 0, "Out of memory");
188
189         while ((opt = cpio_getopt(cpio)) != -1) {
190                 switch (opt) {
191                 case '0': /* GNU convention: --null, -0 */
192                         cpio->option_null = 1;
193                         break;
194                 case 'A': /* NetBSD/OpenBSD */
195                         cpio->option_append = 1;
196                         break;
197                 case 'a': /* POSIX 1997 */
198                         cpio->option_atime_restore = 1;
199                         break;
200                 case 'B': /* POSIX 1997 */
201                         cpio->bytes_per_block = 5120;
202                         break;
203                 case OPTION_B64ENCODE:
204                         cpio->add_filter = opt;
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                         if (archive_match_include_pattern_from_file(
219                             cpio->matching, cpio->argument,
220                             cpio->option_null) != ARCHIVE_OK)
221                                 lafe_errc(1, 0, "Error : %s",
222                                     archive_error_string(cpio->matching));
223                         break;
224                 case 'F': /* NetBSD/OpenBSD/GNU cpio */
225                         cpio->filename = cpio->argument;
226                         break;
227                 case 'f': /* POSIX 1997 */
228                         if (archive_match_exclude_pattern(cpio->matching,
229                             cpio->argument) != ARCHIVE_OK)
230                                 lafe_errc(1, 0, "Error : %s",
231                                     archive_error_string(cpio->matching));
232                         break;
233                 case OPTION_GRZIP:
234                         cpio->compress = opt;
235                         break;
236                 case 'H': /* GNU cpio (also --format) */
237                         cpio->format = cpio->argument;
238                         break;
239                 case 'h':
240                         long_help();
241                         break;
242                 case 'I': /* NetBSD/OpenBSD */
243                         cpio->filename = cpio->argument;
244                         break;
245                 case 'i': /* POSIX 1997 */
246                         if (cpio->mode != '\0')
247                                 lafe_errc(1, 0,
248                                     "Cannot use both -i and -%c", cpio->mode);
249                         cpio->mode = opt;
250                         break;
251                 case 'J': /* GNU tar, others */
252                         cpio->compress = opt;
253                         break;
254                 case 'j': /* GNU tar, others */
255                         cpio->compress = opt;
256                         break;
257                 case OPTION_INSECURE:
258                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
259                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
260                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
261                         break;
262                 case 'L': /* GNU cpio */
263                         cpio->option_follow_links = 1;
264                         break;
265                 case 'l': /* POSIX 1997 */
266                         cpio->option_link = 1;
267                         break;
268                 case OPTION_LRZIP:
269                 case OPTION_LZ4:
270                 case OPTION_LZMA: /* GNU tar, others */
271                 case OPTION_LZOP: /* GNU tar, others */
272                 case OPTION_ZSTD:
273                         cpio->compress = opt;
274                         break;
275                 case 'm': /* POSIX 1997 */
276                         cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
277                         break;
278                 case 'n': /* GNU cpio */
279                         cpio->option_numeric_uid_gid = 1;
280                         break;
281                 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
282                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
283                         break;
284                 case 'O': /* GNU cpio */
285                         cpio->filename = cpio->argument;
286                         break;
287                 case 'o': /* POSIX 1997 */
288                         if (cpio->mode != '\0')
289                                 lafe_errc(1, 0,
290                                     "Cannot use both -o and -%c", cpio->mode);
291                         cpio->mode = opt;
292                         break;
293                 case 'p': /* POSIX 1997 */
294                         if (cpio->mode != '\0')
295                                 lafe_errc(1, 0,
296                                     "Cannot use both -p and -%c", cpio->mode);
297                         cpio->mode = opt;
298                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
299                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
300                         break;
301                 case OPTION_PASSPHRASE:
302                         cpio->passphrase = cpio->argument;
303                         break;
304                 case OPTION_PRESERVE_OWNER:
305                         cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
306                         break;
307                 case OPTION_QUIET: /* GNU cpio */
308                         cpio->quiet = 1;
309                         break;
310                 case 'R': /* GNU cpio, also --owner */
311                         /* TODO: owner_parse should return uname/gname
312                          * also; use that to set [ug]name_override. */
313                         errmsg = owner_parse(cpio->argument, &uid, &gid);
314                         if (errmsg) {
315                                 lafe_warnc(-1, "%s", errmsg);
316                                 usage();
317                         }
318                         if (uid != -1) {
319                                 cpio->uid_override = uid;
320                                 cpio->uname_override = NULL;
321                         }
322                         if (gid != -1) {
323                                 cpio->gid_override = gid;
324                                 cpio->gname_override = NULL;
325                         }
326                         break;
327                 case 'r': /* POSIX 1997 */
328                         cpio->option_rename = 1;
329                         break;
330                 case 't': /* POSIX 1997 */
331                         cpio->option_list = 1;
332                         break;
333                 case 'u': /* POSIX 1997 */
334                         cpio->extract_flags
335                             &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
336                         break;
337                 case OPTION_UUENCODE:
338                         cpio->add_filter = opt;
339                         break;
340                 case 'v': /* POSIX 1997 */
341                         cpio->verbose++;
342                         break;
343                 case 'V': /* GNU cpio */
344                         cpio->dot++;
345                         break;
346                 case OPTION_VERSION: /* GNU convention */
347                         version();
348                         break;
349 #if 0
350                 /*
351                  * cpio_getopt() handles -W specially, so it's not
352                  * available here.
353                  */
354                 case 'W': /* Obscure, but useful GNU convention. */
355                         break;
356 #endif
357                 case 'y': /* tar convention */
358                         cpio->compress = opt;
359                         break;
360                 case 'Z': /* tar convention */
361                         cpio->compress = opt;
362                         break;
363                 case 'z': /* tar convention */
364                         cpio->compress = opt;
365                         break;
366                 default:
367                         usage();
368                 }
369         }
370
371         /*
372          * Sanity-check args, error out on nonsensical combinations.
373          */
374         /* -t implies -i if no mode was specified. */
375         if (cpio->option_list && cpio->mode == '\0')
376                 cpio->mode = 'i';
377         /* -t requires -i */
378         if (cpio->option_list && cpio->mode != 'i')
379                 lafe_errc(1, 0, "Option -t requires -i");
380         /* -n requires -it */
381         if (cpio->option_numeric_uid_gid && !cpio->option_list)
382                 lafe_errc(1, 0, "Option -n requires -it");
383         /* Can only specify format when writing */
384         if (cpio->format != NULL && cpio->mode != 'o')
385                 lafe_errc(1, 0, "Option --format requires -o");
386         /* -l requires -p */
387         if (cpio->option_link && cpio->mode != 'p')
388                 lafe_errc(1, 0, "Option -l requires -p");
389         /* -v overrides -V */
390         if (cpio->dot && cpio->verbose)
391                 cpio->dot = 0;
392         /* TODO: Flag other nonsensical combinations. */
393
394         switch (cpio->mode) {
395         case 'o':
396                 /* TODO: Implement old binary format in libarchive,
397                    use that here. */
398                 if (cpio->format == NULL)
399                         cpio->format = "odc"; /* Default format */
400
401                 mode_out(cpio);
402                 break;
403         case 'i':
404                 while (*cpio->argv != NULL) {
405                         if (archive_match_include_pattern(cpio->matching,
406                             *cpio->argv) != ARCHIVE_OK)
407                                 lafe_errc(1, 0, "Error : %s",
408                                     archive_error_string(cpio->matching));
409                         --cpio->argc;
410                         ++cpio->argv;
411                 }
412                 if (cpio->option_list)
413                         mode_list(cpio);
414                 else
415                         mode_in(cpio);
416                 break;
417         case 'p':
418                 if (*cpio->argv == NULL || **cpio->argv == '\0')
419                         lafe_errc(1, 0,
420                             "-p mode requires a target directory");
421                 mode_pass(cpio, *cpio->argv);
422                 break;
423         default:
424                 lafe_errc(1, 0,
425                     "Must specify at least one of -i, -o, or -p");
426         }
427
428         archive_match_free(cpio->matching);
429         free_cache(cpio->gname_cache);
430         free_cache(cpio->uname_cache);
431         free(cpio->destdir);
432         passphrase_free(cpio->ppbuff);
433         return (cpio->return_value);
434 }
435
436 static void
437 usage(void)
438 {
439         const char      *p;
440
441         p = lafe_getprogname();
442
443         fprintf(stderr, "Brief Usage:\n");
444         fprintf(stderr, "  List:    %s -it < archive\n", p);
445         fprintf(stderr, "  Extract: %s -i < archive\n", p);
446         fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
447         fprintf(stderr, "  Help:    %s --help\n", p);
448         exit(1);
449 }
450
451 static const char *long_help_msg =
452         "First option must be a mode specifier:\n"
453         "  -i Input  -o Output  -p Pass\n"
454         "Common Options:\n"
455         "  -v Verbose filenames     -V  one dot per file\n"
456         "Create: %p -o [options]  < [list of files] > [archive]\n"
457         "  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
458         "  --format {odc|newc|ustar}  Select archive format\n"
459         "List: %p -it < [archive]\n"
460         "Extract: %p -i [options] < [archive]\n";
461
462
463 /*
464  * Note that the word 'bsdcpio' will always appear in the first line
465  * of output.
466  *
467  * In particular, /bin/sh scripts that need to test for the presence
468  * of bsdcpio can use the following template:
469  *
470  * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
471  *          echo bsdcpio; else echo not bsdcpio; fi
472  */
473 static void
474 long_help(void)
475 {
476         const char      *prog;
477         const char      *p;
478
479         prog = lafe_getprogname();
480
481         fflush(stderr);
482
483         p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
484         printf("%s%s: manipulate archive files\n", prog, p);
485
486         for (p = long_help_msg; *p != '\0'; p++) {
487                 if (*p == '%') {
488                         if (p[1] == 'p') {
489                                 fputs(prog, stdout);
490                                 p++;
491                         } else
492                                 putchar('%');
493                 } else
494                         putchar(*p);
495         }
496         version();
497 }
498
499 static void
500 version(void)
501 {
502         fprintf(stdout,"bsdcpio %s - %s \n",
503             BSDCPIO_VERSION_STRING,
504             archive_version_details());
505         exit(0);
506 }
507
508 static void
509 mode_out(struct cpio *cpio)
510 {
511         struct archive_entry *entry, *spare;
512         struct lafe_line_reader *lr;
513         const char *p;
514         int r;
515
516         if (cpio->option_append)
517                 lafe_errc(1, 0, "Append mode not yet supported.");
518
519         cpio->archive_read_disk = archive_read_disk_new();
520         if (cpio->archive_read_disk == NULL)
521                 lafe_errc(1, 0, "Failed to allocate archive object");
522         if (cpio->option_follow_links)
523                 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
524         else
525                 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
526         archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
527
528         cpio->archive = archive_write_new();
529         if (cpio->archive == NULL)
530                 lafe_errc(1, 0, "Failed to allocate archive object");
531         switch (cpio->compress) {
532         case OPTION_GRZIP:
533                 r = archive_write_add_filter_grzip(cpio->archive);
534                 break;
535         case 'J':
536                 r = archive_write_add_filter_xz(cpio->archive);
537                 break;
538         case OPTION_LRZIP:
539                 r = archive_write_add_filter_lrzip(cpio->archive);
540                 break;
541         case OPTION_LZ4:
542                 r = archive_write_add_filter_lz4(cpio->archive);
543                 break;
544         case OPTION_LZMA:
545                 r = archive_write_add_filter_lzma(cpio->archive);
546                 break;
547         case OPTION_LZOP:
548                 r = archive_write_add_filter_lzop(cpio->archive);
549                 break;
550         case OPTION_ZSTD:
551                 r = archive_write_add_filter_zstd(cpio->archive);
552                 break;
553         case 'j': case 'y':
554                 r = archive_write_add_filter_bzip2(cpio->archive);
555                 break;
556         case 'z':
557                 r = archive_write_add_filter_gzip(cpio->archive);
558                 break;
559         case 'Z':
560                 r = archive_write_add_filter_compress(cpio->archive);
561                 break;
562         default:
563                 r = archive_write_add_filter_none(cpio->archive);
564                 break;
565         }
566         if (r < ARCHIVE_WARN)
567                 lafe_errc(1, 0, "Requested compression not available");
568         switch (cpio->add_filter) {
569         case 0:
570                 r = ARCHIVE_OK;
571                 break;
572         case OPTION_B64ENCODE:
573                 r = archive_write_add_filter_b64encode(cpio->archive);
574                 break;
575         case OPTION_UUENCODE:
576                 r = archive_write_add_filter_uuencode(cpio->archive);
577                 break;
578         }
579         if (r < ARCHIVE_WARN)
580                 lafe_errc(1, 0, "Requested filter not available");
581         r = archive_write_set_format_by_name(cpio->archive, cpio->format);
582         if (r != ARCHIVE_OK)
583                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
584         archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
585         cpio->linkresolver = archive_entry_linkresolver_new();
586         archive_entry_linkresolver_set_strategy(cpio->linkresolver,
587             archive_format(cpio->archive));
588         if (cpio->passphrase != NULL)
589                 r = archive_write_set_passphrase(cpio->archive,
590                         cpio->passphrase);
591         else
592                 r = archive_write_set_passphrase_callback(cpio->archive, cpio,
593                         &passphrase_callback);
594         if (r != ARCHIVE_OK)
595                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
596
597         /*
598          * The main loop:  Copy each file into the output archive.
599          */
600         r = archive_write_open_filename(cpio->archive, cpio->filename);
601         if (r != ARCHIVE_OK)
602                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
603         lr = lafe_line_reader("-", cpio->option_null);
604         while ((p = lafe_line_reader_next(lr)) != NULL)
605                 file_to_archive(cpio, p);
606         lafe_line_reader_free(lr);
607
608         /*
609          * The hardlink detection may have queued up a couple of entries
610          * that can now be flushed.
611          */
612         entry = NULL;
613         archive_entry_linkify(cpio->linkresolver, &entry, &spare);
614         while (entry != NULL) {
615                 entry_to_archive(cpio, entry);
616                 archive_entry_free(entry);
617                 entry = NULL;
618                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
619         }
620
621         r = archive_write_close(cpio->archive);
622         if (cpio->dot)
623                 fprintf(stderr, "\n");
624         if (r != ARCHIVE_OK)
625                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
626
627         if (!cpio->quiet) {
628                 int64_t blocks =
629                         (archive_filter_bytes(cpio->archive, 0) + 511)
630                         / 512;
631                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
632                     blocks == 1 ? "block" : "blocks");
633         }
634         archive_write_free(cpio->archive);
635         archive_entry_linkresolver_free(cpio->linkresolver);
636 }
637
638 static const char *
639 remove_leading_slash(const char *p)
640 {
641         const char *rp;
642
643         /* Remove leading "//./" or "//?/" or "//?/UNC/"
644          * (absolute path prefixes used by Windows API) */
645         if ((p[0] == '/' || p[0] == '\\') &&
646             (p[1] == '/' || p[1] == '\\') &&
647             (p[2] == '.' || p[2] == '?') &&
648             (p[3] == '/' || p[3] == '\\'))
649         {
650                 if (p[2] == '?' &&
651                     (p[4] == 'U' || p[4] == 'u') &&
652                     (p[5] == 'N' || p[5] == 'n') &&
653                     (p[6] == 'C' || p[6] == 'c') &&
654                     (p[7] == '/' || p[7] == '\\'))
655                         p += 8;
656                 else
657                         p += 4;
658         }
659         do {
660                 rp = p;
661                 /* Remove leading drive letter from archives created
662                  * on Windows. */
663                 if (((p[0] >= 'a' && p[0] <= 'z') ||
664                      (p[0] >= 'A' && p[0] <= 'Z')) &&
665                          p[1] == ':') {
666                         p += 2;
667                 }
668                 /* Remove leading "/../", "//", etc. */
669                 while (p[0] == '/' || p[0] == '\\') {
670                         if (p[1] == '.' && p[2] == '.' &&
671                                 (p[3] == '/' || p[3] == '\\')) {
672                                 p += 3; /* Remove "/..", leave "/"
673                                          * for next pass. */
674                         } else
675                                 p += 1; /* Remove "/". */
676                 }
677         } while (rp != p);
678         return (p);
679 }
680
681 /*
682  * This is used by both out mode (to copy objects from disk into
683  * an archive) and pass mode (to copy objects from disk to
684  * an archive_write_disk "archive").
685  */
686 static int
687 file_to_archive(struct cpio *cpio, const char *srcpath)
688 {
689         const char *destpath;
690         struct archive_entry *entry, *spare;
691         size_t len;
692         int r;
693
694         /*
695          * Create an archive_entry describing the source file.
696          *
697          */
698         entry = archive_entry_new();
699         if (entry == NULL)
700                 lafe_errc(1, 0, "Couldn't allocate entry");
701         archive_entry_copy_sourcepath(entry, srcpath);
702         r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
703             entry, -1, NULL);
704         if (r < ARCHIVE_FAILED)
705                 lafe_errc(1, 0, "%s",
706                     archive_error_string(cpio->archive_read_disk));
707         if (r < ARCHIVE_OK)
708                 lafe_warnc(0, "%s",
709                     archive_error_string(cpio->archive_read_disk));
710         if (r <= ARCHIVE_FAILED) {
711                 archive_entry_free(entry);
712                 cpio->return_value = 1;
713                 return (r);
714         }
715
716         if (cpio->uid_override >= 0) {
717                 archive_entry_set_uid(entry, cpio->uid_override);
718                 archive_entry_set_uname(entry, cpio->uname_override);
719         }
720         if (cpio->gid_override >= 0) {
721                 archive_entry_set_gid(entry, cpio->gid_override);
722                 archive_entry_set_gname(entry, cpio->gname_override);
723         }
724
725         /*
726          * Generate a destination path for this entry.
727          * "destination path" is the name to which it will be copied in
728          * pass mode or the name that will go into the archive in
729          * output mode.
730          */
731         destpath = srcpath;
732         if (cpio->destdir) {
733                 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
734                 if (len >= cpio->pass_destpath_alloc) {
735                         while (len >= cpio->pass_destpath_alloc) {
736                                 cpio->pass_destpath_alloc += 512;
737                                 cpio->pass_destpath_alloc *= 2;
738                         }
739                         free(cpio->pass_destpath);
740                         cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
741                         if (cpio->pass_destpath == NULL)
742                                 lafe_errc(1, ENOMEM,
743                                     "Can't allocate path buffer");
744                 }
745                 strcpy(cpio->pass_destpath, cpio->destdir);
746                 strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
747                 destpath = cpio->pass_destpath;
748         }
749         if (cpio->option_rename)
750                 destpath = cpio_rename(destpath);
751         if (destpath == NULL)
752                 return (0);
753         archive_entry_copy_pathname(entry, destpath);
754
755         /*
756          * If we're trying to preserve hardlinks, match them here.
757          */
758         spare = NULL;
759         if (cpio->linkresolver != NULL
760             && archive_entry_filetype(entry) != AE_IFDIR) {
761                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
762         }
763
764         if (entry != NULL) {
765                 r = entry_to_archive(cpio, entry);
766                 archive_entry_free(entry);
767                 if (spare != NULL) {
768                         if (r == 0)
769                                 r = entry_to_archive(cpio, spare);
770                         archive_entry_free(spare);
771                 }
772         }
773         return (r);
774 }
775
776 static int
777 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
778 {
779         const char *destpath = archive_entry_pathname(entry);
780         const char *srcpath = archive_entry_sourcepath(entry);
781         int fd = -1;
782         ssize_t bytes_read;
783         int r;
784
785         /* Print out the destination name to the user. */
786         if (cpio->verbose)
787                 fprintf(stderr,"%s", destpath);
788         if (cpio->dot)
789                 fprintf(stderr, ".");
790
791         /*
792          * Option_link only makes sense in pass mode and for
793          * regular files.  Also note: if a link operation fails
794          * because of cross-device restrictions, we'll fall back
795          * to copy mode for that entry.
796          *
797          * TODO: Test other cpio implementations to see if they
798          * hard-link anything other than regular files here.
799          */
800         if (cpio->option_link
801             && archive_entry_filetype(entry) == AE_IFREG)
802         {
803                 struct archive_entry *t;
804                 /* Save the original entry in case we need it later. */
805                 t = archive_entry_clone(entry);
806                 if (t == NULL)
807                         lafe_errc(1, ENOMEM, "Can't create link");
808                 /* Note: link(2) doesn't create parent directories,
809                  * so we use archive_write_header() instead as a
810                  * convenience. */
811                 archive_entry_set_hardlink(t, srcpath);
812                 /* This is a straight link that carries no data. */
813                 archive_entry_set_size(t, 0);
814                 r = archive_write_header(cpio->archive, t);
815                 archive_entry_free(t);
816                 if (r != ARCHIVE_OK)
817                         lafe_warnc(archive_errno(cpio->archive),
818                             "%s", archive_error_string(cpio->archive));
819                 if (r == ARCHIVE_FATAL)
820                         exit(1);
821 #ifdef EXDEV
822                 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
823                         /* Cross-device link:  Just fall through and use
824                          * the original entry to copy the file over. */
825                         lafe_warnc(0, "Copying file instead");
826                 } else
827 #endif
828                 return (0);
829         }
830
831         /*
832          * Make sure we can open the file (if necessary) before
833          * trying to write the header.
834          */
835         if (archive_entry_filetype(entry) == AE_IFREG) {
836                 if (archive_entry_size(entry) > 0) {
837                         fd = open(srcpath, O_RDONLY | O_BINARY);
838                         if (fd < 0) {
839                                 lafe_warnc(errno,
840                                     "%s: could not open file", srcpath);
841                                 goto cleanup;
842                         }
843                 }
844         } else {
845                 archive_entry_set_size(entry, 0);
846         }
847
848         r = archive_write_header(cpio->archive, entry);
849
850         if (r != ARCHIVE_OK)
851                 lafe_warnc(archive_errno(cpio->archive),
852                     "%s: %s",
853                     srcpath,
854                     archive_error_string(cpio->archive));
855
856         if (r == ARCHIVE_FATAL)
857                 exit(1);
858
859         if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
860                 bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
861                 while (bytes_read > 0) {
862                         ssize_t bytes_write;
863                         bytes_write = archive_write_data(cpio->archive,
864                             cpio->buff, bytes_read);
865                         if (bytes_write < 0)
866                                 lafe_errc(1, archive_errno(cpio->archive),
867                                     "%s", archive_error_string(cpio->archive));
868                         if (bytes_write < bytes_read) {
869                                 lafe_warnc(0,
870                                     "Truncated write; file may have "
871                                     "grown while being archived.");
872                         }
873                         bytes_read = read(fd, cpio->buff,
874                             (unsigned)cpio->buff_size);
875                 }
876         }
877
878         fd = restore_time(cpio, entry, srcpath, fd);
879
880 cleanup:
881         if (cpio->verbose)
882                 fprintf(stderr,"\n");
883         if (fd >= 0)
884                 close(fd);
885         return (0);
886 }
887
888 static int
889 restore_time(struct cpio *cpio, struct archive_entry *entry,
890     const char *name, int fd)
891 {
892 #ifndef HAVE_UTIMES
893         static int warned = 0;
894
895         (void)cpio; /* UNUSED */
896         (void)entry; /* UNUSED */
897         (void)name; /* UNUSED */
898
899         if (!warned)
900                 lafe_warnc(0, "Can't restore access times on this platform");
901         warned = 1;
902         return (fd);
903 #else
904 #if defined(_WIN32) && !defined(__CYGWIN__)
905         struct __timeval times[2];
906 #else
907         struct timeval times[2];
908 #endif
909
910         if (!cpio->option_atime_restore)
911                 return (fd);
912
913         times[1].tv_sec = archive_entry_mtime(entry);
914         times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
915
916         times[0].tv_sec = archive_entry_atime(entry);
917         times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
918
919 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
920         if (fd >= 0 && futimes(fd, times) == 0)
921                 return (fd);
922 #endif
923         /*
924          * Some platform cannot restore access times if the file descriptor
925          * is still opened.
926          */
927         if (fd >= 0) {
928                 close(fd);
929                 fd = -1;
930         }
931
932 #ifdef HAVE_LUTIMES
933         if (lutimes(name, times) != 0)
934 #else
935         if ((AE_IFLNK != archive_entry_filetype(entry))
936                         && utimes(name, times) != 0)
937 #endif
938                 lafe_warnc(errno, "Can't update time for %s", name);
939 #endif
940         return (fd);
941 }
942
943
944 static void
945 mode_in(struct cpio *cpio)
946 {
947         struct archive *a;
948         struct archive_entry *entry;
949         struct archive *ext;
950         const char *destpath;
951         int r;
952
953         ext = archive_write_disk_new();
954         if (ext == NULL)
955                 lafe_errc(1, 0, "Couldn't allocate restore object");
956         r = archive_write_disk_set_options(ext, cpio->extract_flags);
957         if (r != ARCHIVE_OK)
958                 lafe_errc(1, 0, "%s", archive_error_string(ext));
959         a = archive_read_new();
960         if (a == NULL)
961                 lafe_errc(1, 0, "Couldn't allocate archive object");
962         archive_read_support_filter_all(a);
963         archive_read_support_format_all(a);
964         if (cpio->passphrase != NULL)
965                 r = archive_read_add_passphrase(a, cpio->passphrase);
966         else
967                 r = archive_read_set_passphrase_callback(a, cpio,
968                         &passphrase_callback);
969         if (r != ARCHIVE_OK)
970                 lafe_errc(1, 0, "%s", archive_error_string(a));
971
972         if (archive_read_open_filename(a, cpio->filename,
973                                         cpio->bytes_per_block))
974                 lafe_errc(1, archive_errno(a),
975                     "%s", archive_error_string(a));
976         for (;;) {
977                 r = archive_read_next_header(a, &entry);
978                 if (r == ARCHIVE_EOF)
979                         break;
980                 if (r != ARCHIVE_OK) {
981                         lafe_errc(1, archive_errno(a),
982                             "%s", archive_error_string(a));
983                 }
984                 if (archive_match_path_excluded(cpio->matching, entry))
985                         continue;
986                 if (cpio->option_rename) {
987                         destpath = cpio_rename(archive_entry_pathname(entry));
988                         archive_entry_set_pathname(entry, destpath);
989                 } else
990                         destpath = archive_entry_pathname(entry);
991                 if (destpath == NULL)
992                         continue;
993                 if (cpio->verbose)
994                         fprintf(stderr, "%s\n", destpath);
995                 if (cpio->dot)
996                         fprintf(stderr, ".");
997                 if (cpio->uid_override >= 0)
998                         archive_entry_set_uid(entry, cpio->uid_override);
999                 if (cpio->gid_override >= 0)
1000                         archive_entry_set_gid(entry, cpio->gid_override);
1001                 r = archive_write_header(ext, entry);
1002                 if (r != ARCHIVE_OK) {
1003                         fprintf(stderr, "%s: %s\n",
1004                             archive_entry_pathname(entry),
1005                             archive_error_string(ext));
1006                 } else if (!archive_entry_size_is_set(entry)
1007                     || archive_entry_size(entry) > 0) {
1008                         r = extract_data(a, ext);
1009                         if (r != ARCHIVE_OK)
1010                                 cpio->return_value = 1;
1011                 }
1012         }
1013         r = archive_read_close(a);
1014         if (cpio->dot)
1015                 fprintf(stderr, "\n");
1016         if (r != ARCHIVE_OK)
1017                 lafe_errc(1, 0, "%s", archive_error_string(a));
1018         r = archive_write_close(ext);
1019         if (r != ARCHIVE_OK)
1020                 lafe_errc(1, 0, "%s", archive_error_string(ext));
1021         if (!cpio->quiet) {
1022                 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1023                               / 512;
1024                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1025                     blocks == 1 ? "block" : "blocks");
1026         }
1027         archive_read_free(a);
1028         archive_write_free(ext);
1029         exit(cpio->return_value);
1030 }
1031
1032 /*
1033  * Exits if there's a fatal error.  Returns ARCHIVE_OK
1034  * if everything is kosher.
1035  */
1036 static int
1037 extract_data(struct archive *ar, struct archive *aw)
1038 {
1039         int r;
1040         size_t size;
1041         const void *block;
1042         int64_t offset;
1043
1044         for (;;) {
1045                 r = archive_read_data_block(ar, &block, &size, &offset);
1046                 if (r == ARCHIVE_EOF)
1047                         return (ARCHIVE_OK);
1048                 if (r != ARCHIVE_OK) {
1049                         lafe_warnc(archive_errno(ar),
1050                             "%s", archive_error_string(ar));
1051                         exit(1);
1052                 }
1053                 r = (int)archive_write_data_block(aw, block, size, offset);
1054                 if (r != ARCHIVE_OK) {
1055                         lafe_warnc(archive_errno(aw),
1056                             "%s", archive_error_string(aw));
1057                         return (r);
1058                 }
1059         }
1060 }
1061
1062 static void
1063 mode_list(struct cpio *cpio)
1064 {
1065         struct archive *a;
1066         struct archive_entry *entry;
1067         int r;
1068
1069         a = archive_read_new();
1070         if (a == NULL)
1071                 lafe_errc(1, 0, "Couldn't allocate archive object");
1072         archive_read_support_filter_all(a);
1073         archive_read_support_format_all(a);
1074         if (cpio->passphrase != NULL)
1075                 r = archive_read_add_passphrase(a, cpio->passphrase);
1076         else
1077                 r = archive_read_set_passphrase_callback(a, cpio,
1078                         &passphrase_callback);
1079         if (r != ARCHIVE_OK)
1080                 lafe_errc(1, 0, "%s", archive_error_string(a));
1081
1082         if (archive_read_open_filename(a, cpio->filename,
1083                                         cpio->bytes_per_block))
1084                 lafe_errc(1, archive_errno(a),
1085                     "%s", archive_error_string(a));
1086         for (;;) {
1087                 r = archive_read_next_header(a, &entry);
1088                 if (r == ARCHIVE_EOF)
1089                         break;
1090                 if (r != ARCHIVE_OK) {
1091                         lafe_errc(1, archive_errno(a),
1092                             "%s", archive_error_string(a));
1093                 }
1094                 if (archive_match_path_excluded(cpio->matching, entry))
1095                         continue;
1096                 if (cpio->verbose)
1097                         list_item_verbose(cpio, entry);
1098                 else
1099                         fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1100         }
1101         r = archive_read_close(a);
1102         if (r != ARCHIVE_OK)
1103                 lafe_errc(1, 0, "%s", archive_error_string(a));
1104         if (!cpio->quiet) {
1105                 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1106                               / 512;
1107                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1108                     blocks == 1 ? "block" : "blocks");
1109         }
1110         archive_read_free(a);
1111         exit(0);
1112 }
1113
1114 /*
1115  * Display information about the current file.
1116  *
1117  * The format here roughly duplicates the output of 'ls -l'.
1118  * This is based on SUSv2, where 'tar tv' is documented as
1119  * listing additional information in an "unspecified format,"
1120  * and 'pax -l' is documented as using the same format as 'ls -l'.
1121  */
1122 static void
1123 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1124 {
1125         char                     size[32];
1126         char                     date[32];
1127         char                     uids[16], gids[16];
1128         const char              *uname, *gname;
1129         FILE                    *out = stdout;
1130         const char              *fmt;
1131         time_t                   mtime;
1132         static time_t            now;
1133
1134         if (!now)
1135                 time(&now);
1136
1137         if (cpio->option_numeric_uid_gid) {
1138                 /* Format numeric uid/gid for display. */
1139                 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1140                 uname = uids;
1141                 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1142                 gname = gids;
1143         } else {
1144                 /* Use uname if it's present, else lookup name from uid. */
1145                 uname = archive_entry_uname(entry);
1146                 if (uname == NULL)
1147                         uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1148                 /* Use gname if it's present, else lookup name from gid. */
1149                 gname = archive_entry_gname(entry);
1150                 if (gname == NULL)
1151                         gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1152         }
1153
1154         /* Print device number or file size. */
1155         if (archive_entry_filetype(entry) == AE_IFCHR
1156             || archive_entry_filetype(entry) == AE_IFBLK) {
1157                 snprintf(size, sizeof(size), "%lu,%lu",
1158                     (unsigned long)archive_entry_rdevmajor(entry),
1159                     (unsigned long)archive_entry_rdevminor(entry));
1160         } else {
1161                 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1162         }
1163
1164         /* Format the time using 'ls -l' conventions. */
1165         mtime = archive_entry_mtime(entry);
1166 #if defined(_WIN32) && !defined(__CYGWIN__)
1167         /* Windows' strftime function does not support %e format. */
1168         if (mtime - now > 365*86400/2
1169                 || mtime - now < -365*86400/2)
1170                 fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1171         else
1172                 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1173 #else
1174         if (mtime - now > 365*86400/2
1175                 || mtime - now < -365*86400/2)
1176                 fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1177         else
1178                 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1179 #endif
1180         strftime(date, sizeof(date), fmt, localtime(&mtime));
1181
1182         fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1183             archive_entry_strmode(entry),
1184             archive_entry_nlink(entry),
1185             uname, gname, size, date,
1186             archive_entry_pathname(entry));
1187
1188         /* Extra information for links. */
1189         if (archive_entry_hardlink(entry)) /* Hard link */
1190                 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1191         else if (archive_entry_symlink(entry)) /* Symbolic link */
1192                 fprintf(out, " -> %s", archive_entry_symlink(entry));
1193         fprintf(out, "\n");
1194 }
1195
1196 static void
1197 mode_pass(struct cpio *cpio, const char *destdir)
1198 {
1199         struct lafe_line_reader *lr;
1200         const char *p;
1201         int r;
1202         size_t destdir_len;
1203
1204         /* Ensure target dir has a trailing '/' to simplify path surgery. */
1205         destdir_len = strlen(destdir);
1206         cpio->destdir = malloc(destdir_len + 8);
1207         memcpy(cpio->destdir, destdir, destdir_len);
1208         if (destdir_len == 0 || destdir[destdir_len - 1] != '/')
1209                 cpio->destdir[destdir_len++] = '/';
1210         cpio->destdir[destdir_len++] = '\0';
1211
1212         cpio->archive = archive_write_disk_new();
1213         if (cpio->archive == NULL)
1214                 lafe_errc(1, 0, "Failed to allocate archive object");
1215         r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1216         if (r != ARCHIVE_OK)
1217                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1218         cpio->linkresolver = archive_entry_linkresolver_new();
1219         archive_write_disk_set_standard_lookup(cpio->archive);
1220
1221         cpio->archive_read_disk = archive_read_disk_new();
1222         if (cpio->archive_read_disk == NULL)
1223                 lafe_errc(1, 0, "Failed to allocate archive object");
1224         if (cpio->option_follow_links)
1225                 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1226         else
1227                 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1228         archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1229
1230         lr = lafe_line_reader("-", cpio->option_null);
1231         while ((p = lafe_line_reader_next(lr)) != NULL)
1232                 file_to_archive(cpio, p);
1233         lafe_line_reader_free(lr);
1234
1235         archive_entry_linkresolver_free(cpio->linkresolver);
1236         r = archive_write_close(cpio->archive);
1237         if (cpio->dot)
1238                 fprintf(stderr, "\n");
1239         if (r != ARCHIVE_OK)
1240                 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1241
1242         if (!cpio->quiet) {
1243                 int64_t blocks =
1244                         (archive_filter_bytes(cpio->archive, 0) + 511)
1245                         / 512;
1246                 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1247                     blocks == 1 ? "block" : "blocks");
1248         }
1249
1250         archive_write_free(cpio->archive);
1251         free(cpio->pass_destpath);
1252 }
1253
1254 /*
1255  * Prompt for a new name for this entry.  Returns a pointer to the
1256  * new name or NULL if the entry should not be copied.  This
1257  * implements the semantics defined in POSIX.1-1996, which specifies
1258  * that an input of '.' means the name should be unchanged.  GNU cpio
1259  * treats '.' as a literal new name.
1260  */
1261 static const char *
1262 cpio_rename(const char *name)
1263 {
1264         static char buff[1024];
1265         FILE *t;
1266         char *p, *ret;
1267 #if defined(_WIN32) && !defined(__CYGWIN__)
1268         FILE *to;
1269
1270         t = fopen("CONIN$", "r");
1271         if (t == NULL)
1272                 return (name);
1273         to = fopen("CONOUT$", "w");
1274         if (to == NULL) {
1275                 fclose(t);
1276                 return (name);
1277         }
1278         fprintf(to, "%s (Enter/./(new name))? ", name);
1279         fclose(to);
1280 #else
1281         t = fopen("/dev/tty", "r+");
1282         if (t == NULL)
1283                 return (name);
1284         fprintf(t, "%s (Enter/./(new name))? ", name);
1285         fflush(t);
1286 #endif
1287
1288         p = fgets(buff, sizeof(buff), t);
1289         fclose(t);
1290         if (p == NULL)
1291                 /* End-of-file is a blank line. */
1292                 return (NULL);
1293
1294         while (*p == ' ' || *p == '\t')
1295                 ++p;
1296         if (*p == '\n' || *p == '\0')
1297                 /* Empty line. */
1298                 return (NULL);
1299         if (*p == '.' && p[1] == '\n')
1300                 /* Single period preserves original name. */
1301                 return (name);
1302         ret = p;
1303         /* Trim the final newline. */
1304         while (*p != '\0' && *p != '\n')
1305                 ++p;
1306         /* Overwrite the final \n with a null character. */
1307         *p = '\0';
1308         return (ret);
1309 }
1310
1311 static void
1312 free_cache(struct name_cache *cache)
1313 {
1314         size_t i;
1315
1316         if (cache != NULL) {
1317                 for (i = 0; i < cache->size; i++)
1318                         free(cache->cache[i].name);
1319                 free(cache);
1320         }
1321 }
1322
1323 /*
1324  * Lookup uname/gname from uid/gid, return NULL if no match.
1325  */
1326 static const char *
1327 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1328     int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1329 {
1330         char asnum[16];
1331         struct name_cache       *cache;
1332         const char *name;
1333         int slot;
1334
1335
1336         if (*name_cache_variable == NULL) {
1337                 *name_cache_variable = calloc(1, sizeof(struct name_cache));
1338                 if (*name_cache_variable == NULL)
1339                         lafe_errc(1, ENOMEM, "No more memory");
1340                 (*name_cache_variable)->size = name_cache_size;
1341         }
1342
1343         cache = *name_cache_variable;
1344         cache->probes++;
1345
1346         slot = id % cache->size;
1347         if (cache->cache[slot].name != NULL) {
1348                 if (cache->cache[slot].id == id) {
1349                         cache->hits++;
1350                         return (cache->cache[slot].name);
1351                 }
1352                 free(cache->cache[slot].name);
1353                 cache->cache[slot].name = NULL;
1354         }
1355
1356         if (lookup_fn(cpio, &name, id)) {
1357                 /* If lookup failed, format it as a number. */
1358                 snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1359                 name = asnum;
1360         }
1361
1362         cache->cache[slot].name = strdup(name);
1363         if (cache->cache[slot].name != NULL) {
1364                 cache->cache[slot].id = id;
1365                 return (cache->cache[slot].name);
1366         }
1367
1368         /*
1369          * Conveniently, NULL marks an empty slot, so
1370          * if the strdup() fails, we've just failed to
1371          * cache it.  No recovery necessary.
1372          */
1373         return (NULL);
1374 }
1375
1376 static const char *
1377 lookup_uname(struct cpio *cpio, uid_t uid)
1378 {
1379         return (lookup_name(cpio, &cpio->uname_cache,
1380                     &lookup_uname_helper, (id_t)uid));
1381 }
1382
1383 static int
1384 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1385 {
1386         struct passwd   *pwent;
1387
1388         (void)cpio; /* UNUSED */
1389
1390         errno = 0;
1391         pwent = getpwuid((uid_t)id);
1392         if (pwent == NULL) {
1393                 if (errno && errno != ENOENT)
1394                         lafe_warnc(errno, "getpwuid(%s) failed",
1395                             cpio_i64toa((int64_t)id));
1396                 return 1;
1397         }
1398
1399         *name = pwent->pw_name;
1400         return 0;
1401 }
1402
1403 static const char *
1404 lookup_gname(struct cpio *cpio, gid_t gid)
1405 {
1406         return (lookup_name(cpio, &cpio->gname_cache,
1407                     &lookup_gname_helper, (id_t)gid));
1408 }
1409
1410 static int
1411 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1412 {
1413         struct group    *grent;
1414
1415         (void)cpio; /* UNUSED */
1416
1417         errno = 0;
1418         grent = getgrgid((gid_t)id);
1419         if (grent == NULL) {
1420                 if (errno && errno != ENOENT)
1421                         lafe_warnc(errno, "getgrgid(%s) failed",
1422                             cpio_i64toa((int64_t)id));
1423                 return 1;
1424         }
1425
1426         *name = grent->gr_name;
1427         return 0;
1428 }
1429
1430 /*
1431  * It would be nice to just use printf() for formatting large numbers,
1432  * but the compatibility problems are a big headache.  Hence the
1433  * following simple utility function.
1434  */
1435 const char *
1436 cpio_i64toa(int64_t n0)
1437 {
1438         /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1439          * We also need 1 byte for '-' and 1 for '\0'.
1440          */
1441         static char buff[22];
1442         int64_t n = n0 < 0 ? -n0 : n0;
1443         char *p = buff + sizeof(buff);
1444
1445         *--p = '\0';
1446         do {
1447                 *--p = '0' + (int)(n % 10);
1448                 n /= 10;
1449         } while (n > 0);
1450         if (n0 < 0)
1451                 *--p = '-';
1452         return p;
1453 }
1454
1455 #define PPBUFF_SIZE 1024
1456 static const char *
1457 passphrase_callback(struct archive *a, void *_client_data)
1458 {
1459         struct cpio *cpio = (struct cpio *)_client_data;
1460         (void)a; /* UNUSED */
1461
1462         if (cpio->ppbuff == NULL) {
1463                 cpio->ppbuff = malloc(PPBUFF_SIZE);
1464                 if (cpio->ppbuff == NULL)
1465                         lafe_errc(1, errno, "Out of memory");
1466         }
1467         return lafe_readpassphrase("Enter passphrase:",
1468                 cpio->ppbuff, PPBUFF_SIZE);
1469 }
1470
1471 static void
1472 passphrase_free(char *ppbuff)
1473 {
1474         if (ppbuff != NULL) {
1475                 memset(ppbuff, 0, PPBUFF_SIZE);
1476                 free(ppbuff);
1477         }
1478 }