]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/cpio/cpio.c
add -n option to suppress clearing the build tree and add -DNO_CLEAN
[FreeBSD/FreeBSD.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_STAT_H
36 #include <sys/stat.h>
37 #endif
38 #ifdef HAVE_ERRNO_H
39 #include <errno.h>
40 #endif
41 #ifdef HAVE_FCNTL_H
42 #include <fcntl.h>
43 #endif
44 #ifdef HAVE_STDARG_H
45 #include <stdarg.h>
46 #endif
47 #include <stdio.h>
48 #ifdef HAVE_STDLIB_H
49 #include <stdlib.h>
50 #endif
51 #ifdef HAVE_STRING_H
52 #include <string.h>
53 #endif
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57
58 #include "cpio.h"
59 #include "matching.h"
60
61 static int      copy_data(struct archive *, struct archive *);
62 static const char *cpio_rename(const char *name);
63 static int      entry_to_archive(struct cpio *, struct archive_entry *);
64 static int      file_to_archive(struct cpio *, const char *);
65 static void     long_help(void);
66 static void     mode_in(struct cpio *);
67 static void     mode_list(struct cpio *);
68 static void     mode_out(struct cpio *);
69 static void     mode_pass(struct cpio *, const char *);
70 static void     restore_time(struct cpio *, struct archive_entry *,
71                     const char *, int fd);
72 static void     usage(void);
73 static void     version(void);
74
75 int
76 main(int argc, char *argv[])
77 {
78         static char buff[16384];
79         struct cpio _cpio; /* Allocated on stack. */
80         struct cpio *cpio;
81         int uid, gid;
82         int opt;
83
84         cpio = &_cpio;
85         memset(cpio, 0, sizeof(*cpio));
86         cpio->buff = buff;
87         cpio->buff_size = sizeof(buff);
88
89         /* Need cpio_progname before calling cpio_warnc. */
90         if (*argv == NULL)
91                 cpio_progname = "bsdcpio";
92         else {
93                 cpio_progname = strrchr(*argv, '/');
94                 if (cpio_progname != NULL)
95                         cpio_progname++;
96                 else
97                         cpio_progname = *argv;
98         }
99
100         cpio->uid_override = -1;
101         cpio->gid_override = -1;
102         cpio->argv = argv;
103         cpio->argc = argc;
104         cpio->line_separator = '\n';
105         cpio->mode = '\0';
106         cpio->verbose = 0;
107         cpio->compress = '\0';
108         /* TODO: Implement old binary format in libarchive, use that here. */
109         cpio->format = "odc"; /* Default format */
110         cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
111         cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
112         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
113         cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
114         cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
115         cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
116         cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
117         if (geteuid() == 0)
118                 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
119         cpio->bytes_per_block = 512;
120         cpio->filename = NULL;
121
122         while ((opt = cpio_getopt(cpio)) != -1) {
123                 switch (opt) {
124                 case '0': /* GNU convention: --null, -0 */
125                         cpio->line_separator = '\0';
126                         break;
127                 case 'A': /* NetBSD/OpenBSD */
128                         cpio->option_append = 1;
129                         break;
130                 case 'a': /* POSIX 1997 */
131                         cpio->option_atime_restore = 1;
132                         break;
133                 case 'B': /* POSIX 1997 */
134                         cpio->bytes_per_block = 5120;
135                         break;
136                 case 'C': /* NetBSD/OpenBSD */
137                         cpio->bytes_per_block = atoi(optarg);
138                         if (cpio->bytes_per_block <= 0)
139                                 cpio_errc(1, 0, "Invalid blocksize %s", optarg);
140                         break;
141                 case 'c': /* POSIX 1997 */
142                         cpio->format = "odc";
143                         break;
144                 case 'd': /* POSIX 1997 */
145                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
146                         break;
147                 case 'E': /* NetBSD/OpenBSD */
148                         include_from_file(cpio, optarg);
149                         break;
150                 case 'F': /* NetBSD/OpenBSD/GNU cpio */
151                         cpio->filename = optarg;
152                         break;
153                 case 'f': /* POSIX 1997 */
154                         exclude(cpio, optarg);
155                         break;
156                 case 'H': /* GNU cpio (also --format) */
157                         cpio->format = optarg;
158                         break;
159                 case 'h':
160                         long_help();
161                         break;
162                 case 'I': /* NetBSD/OpenBSD */
163                         cpio->filename = optarg;
164                         break;
165                 case 'i': /* POSIX 1997 */
166                         cpio->mode = opt;
167                         break;
168                 case OPTION_INSECURE:
169                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
170                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
171                         break;
172                 case 'L': /* GNU cpio */
173                         cpio->option_follow_links = 1;
174                         break;
175                 case 'l': /* POSIX 1997 */
176                         cpio->option_link = 1;
177                         break;
178                 case 'm': /* POSIX 1997 */
179                         cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
180                         break;
181                 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
182                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
183                         break;
184                 case 'O': /* GNU cpio */
185                         cpio->filename = optarg;
186                         break;
187                 case 'o': /* POSIX 1997 */
188                         cpio->mode = opt;
189                         break;
190                 case 'p': /* POSIX 1997 */
191                         cpio->mode = opt;
192                         cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
193                         break;
194                 case OPTION_QUIET: /* GNU cpio */
195                         cpio->quiet = 1;
196                         break;
197                 case 'R': /* GNU cpio, also --owner */
198                         if (owner_parse(optarg, &uid, &gid))
199                                 usage();
200                         if (uid != -1)
201                                 cpio->uid_override = uid;
202                         if (gid != -1)
203                                 cpio->gid_override = gid;
204                         break;
205                 case 'r': /* POSIX 1997 */
206                         cpio->option_rename = 1;
207                         break;
208                 case 't': /* POSIX 1997 */
209                         cpio->option_list = 1;
210                         break;
211                 case 'u': /* POSIX 1997 */
212                         cpio->extract_flags
213                             &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
214                         break;
215                 case 'v': /* POSIX 1997 */
216                         cpio->verbose++;
217                         break;
218                 case OPTION_VERSION: /* GNU convention */
219                         version();
220                         break;
221 #if 0
222                 /*
223                  * cpio_getopt() handles -W specially, so it's not
224                  * available here.
225                  */
226                 case 'W': /* Obscure, but useful GNU convention. */
227                         break;
228 #endif
229                 case 'y': /* tar convention */
230                         cpio->compress = opt;
231                         break;
232                 case 'Z': /* tar convention */
233                         cpio->compress = opt;
234                         break;
235                 case 'z': /* tar convention */
236                         cpio->compress = opt;
237                         break;
238                 default:
239                         usage();
240                 }
241         }
242
243         /* TODO: Sanity-check args, error out on nonsensical combinations. */
244
245         cpio->argc -= optind;
246         cpio->argv += optind;
247
248         switch (cpio->mode) {
249         case 'o':
250                 mode_out(cpio);
251                 break;
252         case 'i':
253                 while (*cpio->argv != NULL) {
254                         include(cpio, *cpio->argv);
255                         --cpio->argc;
256                         ++cpio->argv;
257                 }
258                 if (cpio->option_list)
259                         mode_list(cpio);
260                 else
261                         mode_in(cpio);
262                 break;
263         case 'p':
264                 if (*cpio->argv == NULL || **cpio->argv == '\0')
265                         cpio_errc(1, 0,
266                             "-p mode requires a target directory");
267                 mode_pass(cpio, *cpio->argv);
268                 break;
269         default:
270                 cpio_errc(1, 0,
271                     "Must specify at least one of -i, -o, or -p");
272         }
273
274         return (0);
275 }
276
277 void
278 usage(void)
279 {
280         const char      *p;
281
282         p = cpio_progname;
283
284         fprintf(stderr, "Brief Usage:\n");
285         fprintf(stderr, "  List:    %s -it < archive\n", p);
286         fprintf(stderr, "  Extract: %s -i < archive\n", p);
287         fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
288 #ifdef HAVE_GETOPT_LONG
289         fprintf(stderr, "  Help:    %s --help\n", p);
290 #else
291         fprintf(stderr, "  Help:    %s -h\n", p);
292 #endif
293         exit(1);
294 }
295
296 static const char *long_help_msg =
297         "First option must be a mode specifier:\n"
298         "  -i Input  -o Output  -p Pass\n"
299         "Common Options:\n"
300         "  -v    Verbose\n"
301         "Create: %p -o [options]  < [list of files] > [archive]\n"
302         "  -z, -y  Compress archive with gzip/bzip2\n"
303         "  --format {odc|newc|ustar}  Select archive format\n"
304         "List: %p -it < [archive]\n"
305         "Extract: %p -i [options] < [archive]\n";
306
307
308 /*
309  * Note that the word 'bsdcpio' will always appear in the first line
310  * of output.
311  *
312  * In particular, /bin/sh scripts that need to test for the presence
313  * of bsdcpio can use the following template:
314  *
315  * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
316  *          echo bsdcpio; else echo not bsdcpio; fi
317  */
318 static void
319 long_help(void)
320 {
321         const char      *prog;
322         const char      *p;
323
324         prog = cpio_progname;
325
326         fflush(stderr);
327
328         p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
329         printf("%s%s: manipulate archive files\n", prog, p);
330
331         for (p = long_help_msg; *p != '\0'; p++) {
332                 if (*p == '%') {
333                         if (p[1] == 'p') {
334                                 fputs(prog, stdout);
335                                 p++;
336                         } else
337                                 putchar('%');
338                 } else
339                         putchar(*p);
340         }
341         version();
342 }
343
344 static void
345 version(void)
346 {
347         fprintf(stdout,"bsdcpio %s -- %s\n",
348             BSDCPIO_VERSION_STRING,
349             archive_version());
350         exit(0);
351 }
352
353 static void
354 mode_out(struct cpio *cpio)
355 {
356         unsigned long blocks;
357         struct archive_entry *entry, *spare;
358         struct line_reader *lr;
359         const char *p;
360         int r;
361
362         if (cpio->option_append)
363                 cpio_errc(1, 0, "Append mode not yet supported.");
364         cpio->archive = archive_write_new();
365         if (cpio->archive == NULL)
366                 cpio_errc(1, 0, "Failed to allocate archive object");
367         switch (cpio->compress) {
368         case 'j': case 'y':
369                 archive_write_set_compression_bzip2(cpio->archive);
370                 break;
371         case 'z':
372                 archive_write_set_compression_gzip(cpio->archive);
373                 break;
374         case 'Z':
375                 archive_write_set_compression_compress(cpio->archive);
376                 break;
377         default:
378                 archive_write_set_compression_none(cpio->archive);
379                 break;
380         }
381         r = archive_write_set_format_by_name(cpio->archive, cpio->format);
382         if (r != ARCHIVE_OK)
383                 cpio_errc(1, 0, archive_error_string(cpio->archive));
384         archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
385         cpio->linkresolver = archive_entry_linkresolver_new();
386         archive_entry_linkresolver_set_strategy(cpio->linkresolver,
387             archive_format(cpio->archive));
388
389         r = archive_write_open_file(cpio->archive, cpio->filename);
390         if (r != ARCHIVE_OK)
391                 cpio_errc(1, 0, archive_error_string(cpio->archive));
392         lr = process_lines_init("-", cpio->line_separator);
393         while ((p = process_lines_next(lr)) != NULL)
394                 file_to_archive(cpio, p);
395         process_lines_free(lr);
396
397         /*
398          * The hardlink detection may have queued up a couple of entries
399          * that can now be flushed.
400          */
401         entry = NULL;
402         archive_entry_linkify(cpio->linkresolver, &entry, &spare);
403         while (entry != NULL) {
404                 entry_to_archive(cpio, entry);
405                 archive_entry_free(entry);
406                 entry = NULL;
407                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
408         }
409
410         r = archive_write_close(cpio->archive);
411         if (r != ARCHIVE_OK)
412                 cpio_errc(1, 0, archive_error_string(cpio->archive));
413
414         if (!cpio->quiet) {
415                 blocks = (archive_position_uncompressed(cpio->archive) + 511)
416                               / 512;
417                 fprintf(stderr, "%lu %s\n", blocks,
418                     blocks == 1 ? "block" : "blocks");
419         }
420         archive_write_finish(cpio->archive);
421 }
422
423 /*
424  * This is used by both out mode (to copy objects from disk into
425  * an archive) and pass mode (to copy objects from disk to
426  * an archive_write_disk "archive").
427  */
428 static int
429 file_to_archive(struct cpio *cpio, const char *srcpath)
430 {
431         struct stat st;
432         const char *destpath;
433         struct archive_entry *entry, *spare;
434         size_t len;
435         const char *p;
436         int lnklen;
437         int r;
438
439         /*
440          * Create an archive_entry describing the source file.
441          */
442         entry = archive_entry_new();
443         if (entry == NULL)
444                 cpio_errc(1, 0, "Couldn't allocate entry");
445         archive_entry_copy_sourcepath(entry, srcpath);
446
447         /* Get stat information. */
448         if (cpio->option_follow_links)
449                 r = stat(srcpath, &st);
450         else
451                 r = lstat(srcpath, &st);
452         if (r != 0) {
453                 cpio_warnc(errno, "Couldn't stat \"%s\"", srcpath);
454                 archive_entry_free(entry);
455                 return (0);
456         }
457
458         if (cpio->uid_override >= 0)
459                 st.st_uid = cpio->uid_override;
460         if (cpio->gid_override >= 0)
461                 st.st_gid = cpio->uid_override;
462         archive_entry_copy_stat(entry, &st);
463
464         /* If its a symlink, pull the target. */
465         if (S_ISLNK(st.st_mode)) {
466                 lnklen = readlink(srcpath, cpio->buff, cpio->buff_size);
467                 if (lnklen < 0) {
468                         cpio_warnc(errno,
469                             "%s: Couldn't read symbolic link", srcpath);
470                         archive_entry_free(entry);
471                         return (0);
472                 }
473                 cpio->buff[lnklen] = 0;
474                 archive_entry_set_symlink(entry, cpio->buff);
475         }
476
477         /*
478          * Generate a destination path for this entry.
479          * "destination path" is the name to which it will be copied in
480          * pass mode or the name that will go into the archive in
481          * output mode.
482          */
483         destpath = srcpath;
484         if (cpio->destdir) {
485                 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
486                 if (len >= cpio->pass_destpath_alloc) {
487                         while (len >= cpio->pass_destpath_alloc) {
488                                 cpio->pass_destpath_alloc += 512;
489                                 cpio->pass_destpath_alloc *= 2;
490                         }
491                         free(cpio->pass_destpath);
492                         cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
493                         if (cpio->pass_destpath == NULL)
494                                 cpio_errc(1, ENOMEM,
495                                     "Can't allocate path buffer");
496                 }
497                 strcpy(cpio->pass_destpath, cpio->destdir);
498                 p = srcpath;
499                 while (p[0] == '/')
500                         ++p;
501                 strcat(cpio->pass_destpath, p);
502                 destpath = cpio->pass_destpath;
503         }
504         if (cpio->option_rename)
505                 destpath = cpio_rename(destpath);
506         if (destpath == NULL)
507                 return (0);
508         archive_entry_copy_pathname(entry, destpath);
509
510         /*
511          * If we're trying to preserve hardlinks, match them here.
512          */
513         spare = NULL;
514         if (cpio->linkresolver != NULL
515             && !S_ISDIR(st.st_mode)) {
516                 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
517         }
518
519         if (entry != NULL) {
520                 r = entry_to_archive(cpio, entry);
521                 archive_entry_free(entry);
522         }
523         if (spare != NULL) {
524                 if (r == 0)
525                         r = entry_to_archive(cpio, spare);
526                 archive_entry_free(spare);
527         }
528         return (r);
529 }
530
531 static int
532 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
533 {
534         const char *destpath = archive_entry_pathname(entry);
535         const char *srcpath = archive_entry_sourcepath(entry);
536         int fd = -1;
537         ssize_t bytes_read;
538         int r;
539
540         /* Print out the destination name to the user. */
541         if (cpio->verbose)
542                 fprintf(stderr,"%s", destpath);
543
544         /*
545          * Option_link only makes sense in pass mode and for
546          * regular files.  Also note: if a link operation fails
547          * because of cross-device restrictions, we'll fall back
548          * to copy mode for that entry.
549          *
550          * TODO: Test other cpio implementations to see if they
551          * hard-link anything other than regular files here.
552          */
553         if (cpio->option_link
554             && archive_entry_filetype(entry) == AE_IFREG)
555         {
556                 struct archive_entry *t;
557                 /* Save the original entry in case we need it later. */
558                 t = archive_entry_clone(entry);
559                 if (t == NULL)
560                         cpio_errc(1, ENOMEM, "Can't create link");
561                 /* Note: link(2) doesn't create parent directories,
562                  * so we use archive_write_header() instead as a
563                  * convenience. */
564                 archive_entry_set_hardlink(t, srcpath);
565                 /* This is a straight link that carries no data. */
566                 archive_entry_set_size(t, 0);
567                 r = archive_write_header(cpio->archive, t);
568                 archive_entry_free(t);
569                 if (r != ARCHIVE_OK)
570                         cpio_warnc(archive_errno(cpio->archive),
571                             archive_error_string(cpio->archive));
572                 if (r == ARCHIVE_FATAL)
573                         exit(1);
574 #ifdef EXDEV
575                 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
576                         /* Cross-device link:  Just fall through and use
577                          * the original entry to copy the file over. */
578                         cpio_warnc(0, "Copying file instead");
579                 } else
580 #endif
581                 return (0);
582         }
583
584         /*
585          * Make sure we can open the file (if necessary) before
586          * trying to write the header.
587          */
588         if (archive_entry_filetype(entry) == AE_IFREG) {
589                 if (archive_entry_size(entry) > 0) {
590                         fd = open(srcpath, O_RDONLY);
591                         if (fd < 0) {
592                                 cpio_warnc(errno,
593                                     "%s: could not open file", srcpath);
594                                 goto cleanup;
595                         }
596                 }
597         } else {
598                 archive_entry_set_size(entry, 0);
599         }
600
601         r = archive_write_header(cpio->archive, entry);
602
603         if (r != ARCHIVE_OK)
604                 cpio_warnc(archive_errno(cpio->archive),
605                     "%s: %s",
606                     destpath,
607                     archive_error_string(cpio->archive));
608
609         if (r == ARCHIVE_FATAL)
610                 exit(1);
611
612         if (r >= ARCHIVE_WARN && fd >= 0) {
613                 bytes_read = read(fd, cpio->buff, cpio->buff_size);
614                 while (bytes_read > 0) {
615                         r = archive_write_data(cpio->archive,
616                             cpio->buff, bytes_read);
617                         if (r < 0)
618                                 cpio_errc(1, archive_errno(cpio->archive),
619                                     archive_error_string(cpio->archive));
620                         if (r < bytes_read) {
621                                 cpio_warnc(0,
622                                     "Truncated write; file may have grown while being archived.");
623                         }
624                         bytes_read = read(fd, cpio->buff, cpio->buff_size);
625                 }
626         }
627
628         restore_time(cpio, entry, srcpath, fd);
629
630 cleanup:
631         if (cpio->verbose)
632                 fprintf(stderr,"\n");
633         if (fd >= 0)
634                 close(fd);
635         return (0);
636 }
637
638 static void
639 restore_time(struct cpio *cpio, struct archive_entry *entry,
640     const char *name, int fd)
641 {
642 #ifndef HAVE_UTIMES
643         static int warned = 0;
644
645         (void)cpio; /* UNUSED */
646         (void)entry; /* UNUSED */
647         (void)name; /* UNUSED */
648         (void)fd; /* UNUSED */
649
650         if (!warned)
651                 cpio_warnc(0, "Can't restore access times on this platform");
652         warned = 1;
653         return;
654 #else
655         struct timeval times[2];
656
657         if (!cpio->option_atime_restore)
658                 return;
659
660         times[1].tv_sec = archive_entry_mtime(entry);
661         times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
662
663         times[0].tv_sec = archive_entry_atime(entry);
664         times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
665
666 #ifdef HAVE_FUTIMES
667         if (fd >= 0 && futimes(fd, times) == 0)
668                 return;
669 #endif
670
671 #ifdef HAVE_LUTIMES
672         if (lutimes(name, times) != 0)
673 #else
674         if (!S_ISLNK(archive_entry_mode(entry)) && utimes(name, times) != 0)
675 #endif
676                 cpio_warnc(errno, "Can't update time for %s", name);
677 #endif
678 }
679
680
681 static void
682 mode_in(struct cpio *cpio)
683 {
684         struct archive *a;
685         struct archive_entry *entry;
686         struct archive *ext;
687         const char *destpath;
688         unsigned long blocks;
689         int r;
690
691         ext = archive_write_disk_new();
692         if (ext == NULL)
693                 cpio_errc(1, 0, "Couldn't allocate restore object");
694         r = archive_write_disk_set_options(ext, cpio->extract_flags);
695         if (r != ARCHIVE_OK)
696                 cpio_errc(1, 0, archive_error_string(ext));
697         a = archive_read_new();
698         if (a == NULL)
699                 cpio_errc(1, 0, "Couldn't allocate archive object");
700         archive_read_support_compression_all(a);
701         archive_read_support_format_all(a);
702
703         if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
704                 cpio_errc(1, archive_errno(a),
705                     archive_error_string(a));
706         for (;;) {
707                 r = archive_read_next_header(a, &entry);
708                 if (r == ARCHIVE_EOF)
709                         break;
710                 if (r != ARCHIVE_OK) {
711                         cpio_errc(1, archive_errno(a),
712                             archive_error_string(a));
713                 }
714                 if (excluded(cpio, archive_entry_pathname(entry)))
715                         continue;
716                 if (cpio->option_rename) {
717                         destpath = cpio_rename(archive_entry_pathname(entry));
718                         archive_entry_set_pathname(entry, destpath);
719                 } else
720                         destpath = archive_entry_pathname(entry);
721                 if (destpath == NULL)
722                         continue;
723                 if (cpio->verbose)
724                         fprintf(stdout, "%s\n", destpath);
725                 if (cpio->uid_override >= 0)
726                         archive_entry_set_uid(entry, cpio->uid_override);
727                 if (cpio->gid_override >= 0)
728                         archive_entry_set_gid(entry, cpio->gid_override);
729                 r = archive_write_header(ext, entry);
730                 if (r != ARCHIVE_OK) {
731                         fprintf(stderr, "%s: %s\n",
732                             archive_entry_pathname(entry),
733                             archive_error_string(ext));
734                 } else if (archive_entry_size(entry) > 0) {
735                         r = copy_data(a, ext);
736                 }
737         }
738         r = archive_read_close(a);
739         if (r != ARCHIVE_OK)
740                 cpio_errc(1, 0, archive_error_string(a));
741         r = archive_write_close(ext);
742         if (r != ARCHIVE_OK)
743                 cpio_errc(1, 0, archive_error_string(ext));
744         if (!cpio->quiet) {
745                 blocks = (archive_position_uncompressed(a) + 511)
746                               / 512;
747                 fprintf(stderr, "%lu %s\n", blocks,
748                     blocks == 1 ? "block" : "blocks");
749         }
750         archive_read_finish(a);
751         archive_write_finish(ext);
752         exit(0);
753 }
754
755 static int
756 copy_data(struct archive *ar, struct archive *aw)
757 {
758         int r;
759         size_t size;
760         const void *block;
761         off_t offset;
762
763         for (;;) {
764                 r = archive_read_data_block(ar, &block, &size, &offset);
765                 if (r == ARCHIVE_EOF)
766                         return (ARCHIVE_OK);
767                 if (r != ARCHIVE_OK) {
768                         cpio_warnc(archive_errno(ar),
769                             "%s", archive_error_string(ar));
770                         return (r);
771                 }
772                 r = archive_write_data_block(aw, block, size, offset);
773                 if (r != ARCHIVE_OK) {
774                         cpio_warnc(archive_errno(aw),
775                             archive_error_string(aw));
776                         return (r);
777                 }
778         }
779 }
780
781 static void
782 mode_list(struct cpio *cpio)
783 {
784         struct archive *a;
785         struct archive_entry *entry;
786         unsigned long blocks;
787         int r;
788
789         a = archive_read_new();
790         if (a == NULL)
791                 cpio_errc(1, 0, "Couldn't allocate archive object");
792         archive_read_support_compression_all(a);
793         archive_read_support_format_all(a);
794
795         if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
796                 cpio_errc(1, archive_errno(a),
797                     archive_error_string(a));
798         for (;;) {
799                 r = archive_read_next_header(a, &entry);
800                 if (r == ARCHIVE_EOF)
801                         break;
802                 if (r != ARCHIVE_OK) {
803                         cpio_errc(1, archive_errno(a),
804                             archive_error_string(a));
805                 }
806                 if (excluded(cpio, archive_entry_pathname(entry)))
807                         continue;
808                 if (cpio->verbose) {
809                         /* TODO: uname/gname lookups */
810                         /* TODO: Clean this up. */
811                         fprintf(stdout,
812                             "%s%3d %8s%8s " CPIO_FILESIZE_PRINTF " %s\n",
813                             archive_entry_strmode(entry),
814                             archive_entry_nlink(entry),
815                             archive_entry_uname(entry),
816                             archive_entry_gname(entry),
817                             (CPIO_FILESIZE_TYPE)archive_entry_size(entry),
818                             archive_entry_pathname(entry));
819                 } else
820                         fprintf(stdout, "%s\n", archive_entry_pathname(entry));
821         }
822         r = archive_read_close(a);
823         if (r != ARCHIVE_OK)
824                 cpio_errc(1, 0, archive_error_string(a));
825         if (!cpio->quiet) {
826                 blocks = (archive_position_uncompressed(a) + 511)
827                               / 512;
828                 fprintf(stderr, "%lu %s\n", blocks,
829                     blocks == 1 ? "block" : "blocks");
830         }
831         archive_read_finish(a);
832         exit(0);
833 }
834
835 static void
836 mode_pass(struct cpio *cpio, const char *destdir)
837 {
838         unsigned long blocks;
839         struct line_reader *lr;
840         const char *p;
841         int r;
842
843         /* Ensure target dir has a trailing '/' to simplify path surgery. */
844         cpio->destdir = malloc(strlen(destdir) + 8);
845         strcpy(cpio->destdir, destdir);
846         if (destdir[strlen(destdir) - 1] != '/')
847                 strcat(cpio->destdir, "/");
848
849         cpio->archive = archive_write_disk_new();
850         if (cpio->archive == NULL)
851                 cpio_errc(1, 0, "Failed to allocate archive object");
852         r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
853         if (r != ARCHIVE_OK)
854                 cpio_errc(1, 0, archive_error_string(cpio->archive));
855         cpio->linkresolver = archive_entry_linkresolver_new();
856         archive_write_disk_set_standard_lookup(cpio->archive);
857         lr = process_lines_init("-", cpio->line_separator);
858         while ((p = process_lines_next(lr)) != NULL)
859                 file_to_archive(cpio, p);
860         process_lines_free(lr);
861
862         archive_entry_linkresolver_free(cpio->linkresolver);
863         r = archive_write_close(cpio->archive);
864         if (r != ARCHIVE_OK)
865                 cpio_errc(1, 0, archive_error_string(cpio->archive));
866
867         if (!cpio->quiet) {
868                 blocks = (archive_position_uncompressed(cpio->archive) + 511)
869                               / 512;
870                 fprintf(stderr, "%lu %s\n", blocks,
871                     blocks == 1 ? "block" : "blocks");
872         }
873
874         archive_write_finish(cpio->archive);
875 }
876
877 /*
878  * Prompt for a new name for this entry.  Returns a pointer to the
879  * new name or NULL if the entry should not be copied.  This
880  * implements the semantics defined in POSIX.1-1996, which specifies
881  * that an input of '.' means the name should be unchanged.  GNU cpio
882  * treats '.' as a literal new name.
883  */
884 static const char *
885 cpio_rename(const char *name)
886 {
887         static char buff[1024];
888         FILE *t;
889         char *p, *ret;
890
891         t = fopen("/dev/tty", "r+");
892         if (t == NULL)
893                 return (name);
894         fprintf(t, "%s (Enter/./(new name))? ", name);
895         fflush(t);
896
897         p = fgets(buff, sizeof(buff), t);
898         fclose(t);
899         if (p == NULL)
900                 /* End-of-file is a blank line. */
901                 return (NULL);
902
903         while (*p == ' ' || *p == '\t')
904                 ++p;
905         if (*p == '\n' || *p == '\0')
906                 /* Empty line. */
907                 return (NULL);
908         if (*p == '.' && p[1] == '\n')
909                 /* Single period preserves original name. */
910                 return (name);
911         ret = p;
912         /* Trim the final newline. */
913         while (*p != '\0' && *p != '\n')
914                 ++p;
915         /* Overwrite the final \n with a null character. */
916         *p = '\0';
917         return (ret);
918 }
919
920
921 /*
922  * Read lines from file and do something with each one.  If option_null
923  * is set, lines are terminated with zero bytes; otherwise, they're
924  * terminated with newlines.
925  *
926  * This uses a self-sizing buffer to handle arbitrarily-long lines.
927  */
928 struct line_reader {
929         FILE *f;
930         char *buff, *buff_end, *line_start, *line_end, *p;
931         char *pathname;
932         size_t buff_length;
933         int separator;
934         int ret;
935 };
936
937 struct line_reader *
938 process_lines_init(const char *pathname, char separator)
939 {
940         struct line_reader *lr;
941
942         lr = calloc(1, sizeof(*lr));
943         if (lr == NULL)
944                 cpio_errc(1, ENOMEM, "Can't open %s", pathname);
945
946         lr->separator = separator;
947         lr->pathname = strdup(pathname);
948
949         if (strcmp(pathname, "-") == 0)
950                 lr->f = stdin;
951         else
952                 lr->f = fopen(pathname, "r");
953         if (lr->f == NULL)
954                 cpio_errc(1, errno, "Couldn't open %s", pathname);
955         lr->buff_length = 8192;
956         lr->buff = malloc(lr->buff_length);
957         if (lr->buff == NULL)
958                 cpio_errc(1, ENOMEM, "Can't read %s", pathname);
959         lr->line_start = lr->line_end = lr->buff_end = lr->buff;
960
961         return (lr);
962 }
963
964 const char *
965 process_lines_next(struct line_reader *lr)
966 {
967         size_t bytes_wanted, bytes_read, new_buff_size;
968         char *line_start, *p;
969
970         for (;;) {
971                 /* If there's a line in the buffer, return it immediately. */
972                 while (lr->line_end < lr->buff_end) {
973                         if (*lr->line_end == lr->separator) {
974                                 *lr->line_end = '\0';
975                                 line_start = lr->line_start;
976                                 lr->line_start = lr->line_end + 1;
977                                 lr->line_end = lr->line_start;
978                                 return (line_start);
979                         } else
980                                 lr->line_end++;
981                 }
982
983                 /* If we're at end-of-file, process the final data. */
984                 if (lr->f == NULL) {
985                         /* If there's more text, return one last line. */
986                         if (lr->line_end > lr->line_start) {
987                                 *lr->line_end = '\0';
988                                 line_start = lr->line_start;
989                                 lr->line_start = lr->line_end + 1;
990                                 lr->line_end = lr->line_start;
991                                 return (line_start);
992                         }
993                         /* Otherwise, we're done. */
994                         return (NULL);
995                 }
996
997                 /* Buffer only has part of a line. */
998                 if (lr->line_start > lr->buff) {
999                         /* Move a leftover fractional line to the beginning. */
1000                         memmove(lr->buff, lr->line_start,
1001                             lr->buff_end - lr->line_start);
1002                         lr->buff_end -= lr->line_start - lr->buff;
1003                         lr->line_end -= lr->line_start - lr->buff;
1004                         lr->line_start = lr->buff;
1005                 } else {
1006                         /* Line is too big; enlarge the buffer. */
1007                         new_buff_size = lr->buff_length * 2;
1008                         if (new_buff_size <= lr->buff_length)
1009                                 cpio_errc(1, ENOMEM,
1010                                     "Line too long in %s", lr->pathname);
1011                         lr->buff_length = new_buff_size;
1012                         p = realloc(lr->buff, new_buff_size);
1013                         if (p == NULL)
1014                                 cpio_errc(1, ENOMEM,
1015                                     "Line too long in %s", lr->pathname);
1016                         lr->buff_end = p + (lr->buff_end - lr->buff);
1017                         lr->line_end = p + (lr->line_end - lr->buff);
1018                         lr->line_start = lr->buff = p;
1019                 }
1020
1021                 /* Get some more data into the buffer. */
1022                 bytes_wanted = lr->buff + lr->buff_length - lr->buff_end;
1023                 bytes_read = fread(lr->buff_end, 1, bytes_wanted, lr->f);
1024                 lr->buff_end += bytes_read;
1025
1026                 if (ferror(lr->f))
1027                         cpio_errc(1, errno, "Can't read %s", lr->pathname);
1028                 if (feof(lr->f)) {
1029                         if (lr->f != stdin)
1030                                 fclose(lr->f);
1031                         lr->f = NULL;
1032                 }
1033         }
1034 }
1035
1036 void
1037 process_lines_free(struct line_reader *lr)
1038 {
1039         free(lr->buff);
1040         free(lr->pathname);
1041         free(lr);
1042 }