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