apply new hurd patch to my tree
[debian/pax] / options.c
1 /*      $OpenBSD: options.c,v 1.70 2008/06/11 00:49:08 pvalchev Exp $   */
2 /*      $NetBSD: options.c,v 1.6 1996/03/26 23:54:18 mrg Exp $  */
3
4 /*-
5  * Copyright (c) 1992 Keith Muller.
6  * Copyright (c) 1992, 1993
7  *      The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Keith Muller of the University of California, San Diego.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36
37 #ifndef lint
38 #if 0
39 static const char sccsid[] = "@(#)options.c     8.2 (Berkeley) 4/18/94";
40 #else
41 static const char rcsid[] = "$OpenBSD: options.c,v 1.70 2008/06/11 00:49:08 pvalchev Exp $";
42 #endif
43 #endif /* not lint */
44
45 #include <sys/types.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/mtio.h>
49 #include <sys/param.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <unistd.h>
54 #include <stdlib.h>
55 #include <limits.h>
56 #include <paths.h>
57 #include "pax.h"
58 #include "options.h"
59 #include "cpio.h"
60 #include "tar.h"
61 #include "extern.h"
62
63 #include "fgetln.h"    /* added, David */
64
65 /*
66  * Routines which handle command line options
67  */
68
69 static char flgch[] = FLGCH;    /* list of all possible flags */
70 static OPLIST *ophead = NULL;   /* head for format specific options -x */
71 static OPLIST *optail = NULL;   /* option tail */
72
73 static int no_op(void);
74 static void printflg(unsigned int);
75 static int c_frmt(const void *, const void *);
76 static off_t str_offt(char *);
77 static char *bsd_getline(FILE *fp);
78 static void pax_options(int, char **);
79 static void pax_usage(void);
80 static void tar_options(int, char **);
81 static void tar_usage(void);
82 static void cpio_options(int, char **);
83 static void cpio_usage(void);
84
85 /* errors from getline */
86 #define GETLINE_FILE_CORRUPT 1
87 #define GETLINE_OUT_OF_MEM 2
88 static int getline_error;
89
90
91 #define GZIP_CMD        "gzip"          /* command to run as gzip */
92 #define COMPRESS_CMD    "compress"      /* command to run as compress */
93 #define BZIP2_CMD       "bzip2"         /* command to run as bzip2 */
94
95 /*
96  *      Format specific routine table - MUST BE IN SORTED ORDER BY NAME
97  *      (see pax.h for description of each function)
98  *
99  *      name, blksz, hdsz, udev, hlk, blkagn, inhead, id, st_read,
100  *      read, end_read, st_write, write, end_write, trail,
101  *      rd_data, wr_data, options
102  */
103
104 FSUB fsub[] = {
105 /* 0: OLD BINARY CPIO */
106         {"bcpio", 5120, sizeof(HD_BCPIO), 1, 0, 0, 1, bcpio_id, cpio_strd,
107         bcpio_rd, bcpio_endrd, cpio_stwr, bcpio_wr, cpio_endwr, cpio_trail,
108         rd_wrfile, wr_rdfile, bad_opt},
109
110 /* 1: OLD OCTAL CHARACTER CPIO */
111         {"cpio", 5120, sizeof(HD_CPIO), 1, 0, 0, 1, cpio_id, cpio_strd,
112         cpio_rd, cpio_endrd, cpio_stwr, cpio_wr, cpio_endwr, cpio_trail,
113         rd_wrfile, wr_rdfile, bad_opt},
114
115 /* 2: SVR4 HEX CPIO */
116         {"sv4cpio", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, vcpio_id, cpio_strd,
117         vcpio_rd, vcpio_endrd, cpio_stwr, vcpio_wr, cpio_endwr, cpio_trail,
118         rd_wrfile, wr_rdfile, bad_opt},
119
120 /* 3: SVR4 HEX CPIO WITH CRC */
121         {"sv4crc", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, crc_id, crc_strd,
122         vcpio_rd, vcpio_endrd, crc_stwr, vcpio_wr, cpio_endwr, cpio_trail,
123         rd_wrfile, wr_rdfile, bad_opt},
124
125 /* 4: OLD TAR */
126         {"tar", 10240, BLKMULT, 0, 1, BLKMULT, 0, tar_id, no_op,
127         tar_rd, tar_endrd, no_op, tar_wr, tar_endwr, tar_trail,
128         rd_wrfile, wr_rdfile, tar_opt},
129
130 /* 5: POSIX USTAR */
131         {"ustar", 10240, BLKMULT, 0, 1, BLKMULT, 0, ustar_id, ustar_strd,
132         ustar_rd, tar_endrd, ustar_stwr, ustar_wr, tar_endwr, tar_trail,
133         rd_wrfile, wr_rdfile, bad_opt},
134 };
135 #define F_OCPIO 0       /* format when called as cpio -6 */
136 #define F_ACPIO 1       /* format when called as cpio -c */
137 #define F_CPIO  3       /* format when called as cpio */
138 #define F_OTAR  4       /* format when called as tar -o */
139 #define F_TAR   5       /* format when called as tar */
140 #define DEFLT   5       /* default write format from list above */
141
142 /*
143  * ford is the archive search order used by get_arc() to determine what kind
144  * of archive we are dealing with. This helps to properly id archive formats
145  * some formats may be subsets of others....
146  */
147 int ford[] = {5, 4, 3, 2, 1, 0, -1 };
148
149 /*
150  * Do we have -C anywhere?
151  */
152 int havechd = 0;
153
154 /*
155  * options()
156  *      figure out if we are pax, tar or cpio. Call the appropriate options
157  *      parser
158  */
159
160 void
161 options(int argc, char **argv)
162 {
163
164         /*
165          * Are we acting like pax, tar or cpio (based on argv[0])
166          */
167         if ((argv0 = strrchr(argv[0], '/')) != NULL)
168                 argv0++;
169         else
170                 argv0 = argv[0];
171
172         if (strcmp(NM_TAR, argv0) == 0) {
173                 tar_options(argc, argv);
174                 return;
175         } else if (strcmp(NM_CPIO, argv0) == 0) {
176                 cpio_options(argc, argv);
177                 return;
178         }
179         /*
180          * assume pax as the default
181          */
182         argv0 = NM_PAX;
183         pax_options(argc, argv);
184 }
185
186 /*
187  * pax_options()
188  *      look at the user specified flags. set globals as required and check if
189  *      the user specified a legal set of flags. If not, complain and exit
190  */
191
192 static void
193 pax_options(int argc, char **argv)
194 {
195         int c;
196         int i;
197         unsigned int flg = 0;
198         unsigned int bflg = 0;
199         char *pt;
200         FSUB tmp;
201
202         /*
203          * process option flags
204          */
205         while ((c=getopt(argc,argv,"ab:cdf:ijklno:p:rs:tuvwx:zB:DE:G:HLOPT:U:XYZ0"))
206             != -1) {
207                 switch (c) {
208                 case 'a':
209                         /*
210                          * append
211                          */
212                         flg |= AF;
213                         break;
214                 case 'b':
215                         /*
216                          * specify blocksize
217                          */
218                         flg |= BF;
219                         if ((wrblksz = (int)str_offt(optarg)) <= 0) {
220                                 paxwarn(1, "Invalid block size %s", optarg);
221                                 pax_usage();
222                         }
223                         break;
224                 case 'c':
225                         /*
226                          * inverse match on patterns
227                          */
228                         cflag = 1;
229                         flg |= CF;
230                         break;
231                 case 'd':
232                         /*
233                          * match only dir on extract, not the subtree at dir
234                          */
235                         dflag = 1;
236                         flg |= DF;
237                         break;
238                 case 'f':
239                         /*
240                          * filename where the archive is stored
241                          */
242                         arcname = optarg;
243                         flg |= FF;
244                         break;
245                 case 'i':
246                         /*
247                          * interactive file rename
248                          */
249                         iflag = 1;
250                         flg |= IF;
251                         break;
252                 case 'j':
253                         /*
254                          * use bzip2.  Non standard option.
255                          */
256                         gzip_program = BZIP2_CMD;
257                         break;
258                 case 'k':
259                         /*
260                          * do not clobber files that exist
261                          */
262                         kflag = 1;
263                         flg |= KF;
264                         break;
265                 case 'l':
266                         /*
267                          * try to link src to dest with copy (-rw)
268                          */
269                         lflag = 1;
270                         flg |= LF;
271                         break;
272                 case 'n':
273                         /*
274                          * select first match for a pattern only
275                          */
276                         nflag = 1;
277                         flg |= NF;
278                         break;
279                 case 'o':
280                         /*
281                          * pass format specific options
282                          */
283                         flg |= OF;
284                         if (opt_add(optarg) < 0)
285                                 pax_usage();
286                         break;
287                 case 'p':
288                         /*
289                          * specify file characteristic options
290                          */
291                         for (pt = optarg; *pt != '\0'; ++pt) {
292                                 switch (*pt) {
293                                 case 'a':
294                                         /*
295                                          * do not preserve access time
296                                          */
297                                         patime = 0;
298                                         break;
299                                 case 'e':
300                                         /*
301                                          * preserve user id, group id, file
302                                          * mode, access/modification times
303                                          */
304                                         pids = 1;
305                                         pmode = 1;
306                                         patime = 1;
307                                         pmtime = 1;
308                                         break;
309                                 case 'm':
310                                         /*
311                                          * do not preserve modification time
312                                          */
313                                         pmtime = 0;
314                                         break;
315                                 case 'o':
316                                         /*
317                                          * preserve uid/gid
318                                          */
319                                         pids = 1;
320                                         break;
321                                 case 'p':
322                                         /*
323                                          * preserve file mode bits
324                                          */
325                                         pmode = 1;
326                                         break;
327                                 default:
328                                         paxwarn(1, "Invalid -p string: %c", *pt);
329                                         pax_usage();
330                                         break;
331                                 }
332                         }
333                         flg |= PF;
334                         break;
335                 case 'r':
336                         /*
337                          * read the archive
338                          */
339                         flg |= RF;
340                         break;
341                 case 's':
342                         /*
343                          * file name substitution name pattern
344                          */
345                         if (rep_add(optarg) < 0) {
346                                 pax_usage();
347                                 break;
348                         }
349                         flg |= SF;
350                         break;
351                 case 't':
352                         /*
353                          * preserve access time on filesystem nodes we read
354                          */
355                         tflag = 1;
356                         flg |= TF;
357                         break;
358                 case 'u':
359                         /*
360                          * ignore those older files
361                          */
362                         uflag = 1;
363                         flg |= UF;
364                         break;
365                 case 'v':
366                         /*
367                          * verbose operation mode
368                          */
369                         vflag = 1;
370                         flg |= VF;
371                         break;
372                 case 'w':
373                         /*
374                          * write an archive
375                          */
376                         flg |= WF;
377                         break;
378                 case 'x':
379                         /*
380                          * specify an archive format on write
381                          */
382                         tmp.name = optarg;
383                         if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
384                             sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL) {
385                                 flg |= XF;
386                                 break;
387                         }
388                         paxwarn(1, "Unknown -x format: %s", optarg);
389                         (void)fputs("pax: Known -x formats are:", stderr);
390                         for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
391                                 (void)fprintf(stderr, " %s", fsub[i].name);
392                         (void)fputs("\n\n", stderr);
393                         pax_usage();
394                         break;
395                 case 'z':
396                         /*
397                          * use gzip.  Non standard option.
398                          */
399                         gzip_program = GZIP_CMD;
400                         break;
401                 case 'B':
402                         /*
403                          * non-standard option on number of bytes written on a
404                          * single archive volume.
405                          */
406                         if ((wrlimit = str_offt(optarg)) <= 0) {
407                                 paxwarn(1, "Invalid write limit %s", optarg);
408                                 pax_usage();
409                         }
410                         if (wrlimit % BLKMULT) {
411                                 paxwarn(1, "Write limit is not a %d byte multiple",
412                                     BLKMULT);
413                                 pax_usage();
414                         }
415                         flg |= CBF;
416                         break;
417                 case 'D':
418                         /*
419                          * On extraction check file inode change time before the
420                          * modification of the file name. Non standard option.
421                          */
422                         Dflag = 1;
423                         flg |= CDF;
424                         break;
425                 case 'E':
426                         /*
427                          * non-standard limit on read faults
428                          * 0 indicates stop after first error, values
429                          * indicate a limit, "NONE" try forever
430                          */
431                         flg |= CEF;
432                         if (strcmp(NONE, optarg) == 0)
433                                 maxflt = -1;
434                         else if ((maxflt = atoi(optarg)) < 0) {
435                                 paxwarn(1, "Error count value must be positive");
436                                 pax_usage();
437                         }
438                         break;
439                 case 'G':
440                         /*
441                          * non-standard option for selecting files within an
442                          * archive by group (gid or name)
443                          */
444                         if (grp_add(optarg) < 0) {
445                                 pax_usage();
446                                 break;
447                         }
448                         flg |= CGF;
449                         break;
450                 case 'H':
451                         /*
452                          * follow command line symlinks only
453                          */
454                         Hflag = 1;
455                         flg |= CHF;
456                         break;
457                 case 'L':
458                         /*
459                          * follow symlinks
460                          */
461                         Lflag = 1;
462                         flg |= CLF;
463                         break;
464                 case 'O':
465                         /*
466                          * Force one volume.  Non standard option.
467                          */
468                         force_one_volume = 1;
469                         break;
470                 case 'P':
471                         /*
472                          * do NOT follow symlinks (default)
473                          */
474                         Lflag = 0;
475                         flg |= CPF;
476                         break;
477                 case 'T':
478                         /*
479                          * non-standard option for selecting files within an
480                          * archive by modification time range (lower,upper)
481                          */
482                         if (trng_add(optarg) < 0) {
483                                 pax_usage();
484                                 break;
485                         }
486                         flg |= CTF;
487                         break;
488                 case 'U':
489                         /*
490                          * non-standard option for selecting files within an
491                          * archive by user (uid or name)
492                          */
493                         if (usr_add(optarg) < 0) {
494                                 pax_usage();
495                                 break;
496                         }
497                         flg |= CUF;
498                         break;
499                 case 'X':
500                         /*
501                          * do not pass over mount points in the file system
502                          */
503                         Xflag = 1;
504                         flg |= CXF;
505                         break;
506                 case 'Y':
507                         /*
508                          * On extraction check file inode change time after the
509                          * modification of the file name. Non standard option.
510                          */
511                         Yflag = 1;
512                         flg |= CYF;
513                         break;
514                 case 'Z':
515                         /*
516                          * On extraction check modification time after the
517                          * modification of the file name. Non standard option.
518                          */
519                         Zflag = 1;
520                         flg |= CZF;
521                         break;
522                 case '0':
523                         /*
524                          * Use \0 as pathname terminator.
525                          * (For use with the -print0 option of find(1).)
526                          */
527                         zeroflag = 1;
528                         flg |= C0F;
529                         break;
530                 default:
531                         pax_usage();
532                         break;
533                 }
534         }
535
536         /*
537          * figure out the operation mode of pax read,write,extract,copy,append
538          * or list. check that we have not been given a bogus set of flags
539          * for the operation mode.
540          */
541         if (ISLIST(flg)) {
542                 act = LIST;
543                 listf = stdout;
544                 bflg = flg & BDLIST;
545         } else if (ISEXTRACT(flg)) {
546                 act = EXTRACT;
547                 bflg = flg & BDEXTR;
548         } else if (ISARCHIVE(flg)) {
549                 act = ARCHIVE;
550                 bflg = flg & BDARCH;
551         } else if (ISAPPND(flg)) {
552                 act = APPND;
553                 bflg = flg & BDARCH;
554         } else if (ISCOPY(flg)) {
555                 act = COPY;
556                 bflg = flg & BDCOPY;
557         } else
558                 pax_usage();
559         if (bflg) {
560                 printflg(flg);
561                 pax_usage();
562         }
563
564         /*
565          * if we are writing (ARCHIVE) we use the default format if the user
566          * did not specify a format. when we write during an APPEND, we will
567          * adopt the format of the existing archive if none was supplied.
568          */
569         if (!(flg & XF) && (act == ARCHIVE))
570                 frmt = &(fsub[DEFLT]);
571
572         /*
573          * process the args as they are interpreted by the operation mode
574          */
575         switch (act) {
576         case LIST:
577         case EXTRACT:
578                 for (; optind < argc; optind++)
579                         if (pat_add(argv[optind], NULL) < 0)
580                                 pax_usage();
581                 break;
582         case COPY:
583                 if (optind >= argc) {
584                         paxwarn(0, "Destination directory was not supplied");
585                         pax_usage();
586                 }
587                 --argc;
588                 dirptr = argv[argc];
589                 /* FALL THROUGH */
590         case ARCHIVE:
591         case APPND:
592                 for (; optind < argc; optind++)
593                         if (ftree_add(argv[optind], 0) < 0)
594                                 pax_usage();
595                 /*
596                  * no read errors allowed on updates/append operation!
597                  */
598                 maxflt = 0;
599                 break;
600         }
601 }
602
603
604 /*
605  * tar_options()
606  *      look at the user specified flags. set globals as required and check if
607  *      the user specified a legal set of flags. If not, complain and exit
608  */
609
610 static void
611 tar_options(int argc, char **argv)
612 {
613         int c;
614         int fstdin = 0;
615         int Oflag = 0;
616         int nincfiles = 0;
617         int incfiles_max = 0;
618         struct incfile {
619                 char *file;
620                 char *dir;
621         };
622         struct incfile *incfiles = NULL;
623
624         /*
625          * Set default values.
626          */
627         rmleadslash = 1;
628
629         /*
630          * process option flags
631          */
632         while ((c = getoldopt(argc, argv,
633             "b:cef:hjmopqruts:vwxzBC:HI:LOPXZ014578")) != -1) {
634                 switch (c) {
635                 case 'b':
636                         /*
637                          * specify blocksize in 512-byte blocks
638                          */
639                         if ((wrblksz = (int)str_offt(optarg)) <= 0) {
640                                 paxwarn(1, "Invalid block size %s", optarg);
641                                 tar_usage();
642                         }
643                         wrblksz *= 512;         /* XXX - check for int oflow */
644                         break;
645                 case 'c':
646                         /*
647                          * create an archive
648                          */
649                         act = ARCHIVE;
650                         break;
651                 case 'e':
652                         /*
653                          * stop after first error
654                          */
655                         maxflt = 0;
656                         break;
657                 case 'f':
658                         /*
659                          * filename where the archive is stored
660                          */
661                         if ((optarg[0] == '-') && (optarg[1]== '\0')) {
662                                 /*
663                                  * treat a - as stdin
664                                  */
665                                 fstdin = 1;
666                                 arcname = NULL;
667                                 break;
668                         }
669                         fstdin = 0;
670                         arcname = optarg;
671                         break;
672                 case 'h':
673                         /*
674                          * follow symlinks
675                          */
676                         Lflag = 1;
677                         break;
678                 case 'j':
679                         /*
680                          * use bzip2.  Non standard option.
681                          */
682                         gzip_program = BZIP2_CMD;
683                         break;
684                 case 'm':
685                         /*
686                          * do not preserve modification time
687                          */
688                         pmtime = 0;
689                         break;
690                 case 'O':
691                         Oflag = 1;
692                         break;
693                 case 'o':
694                         Oflag = 2;
695                         break;
696                 case 'p':
697                         /*
698                          * preserve uid/gid and file mode, regardless of umask
699                          */
700                         pmode = 1;
701                         pids = 1;
702                         break;
703                 case 'q':
704                         /*
705                          * select first match for a pattern only
706                          */
707                         nflag = 1;
708                         break;
709                 case 'r':
710                 case 'u':
711                         /*
712                          * append to the archive
713                          */
714                         act = APPND;
715                         break;
716                 case 's':
717                         /*
718                          * file name substitution name pattern
719                          */
720                         if (rep_add(optarg) < 0) {
721                                 tar_usage();
722                                 break;
723                         }
724                         break;
725                 case 't':
726                         /*
727                          * list contents of the tape
728                          */
729                         act = LIST;
730                         break;
731                 case 'v':
732                         /*
733                          * verbose operation mode
734                          */
735                         vflag++;
736                         break;
737                 case 'w':
738                         /*
739                          * interactive file rename
740                          */
741                         iflag = 1;
742                         break;
743                 case 'x':
744                         /*
745                          * extract an archive, preserving mode,
746                          * and mtime if possible.
747                          */
748                         act = EXTRACT;
749                         pmtime = 1;
750                         break;
751                 case 'z':
752                         /*
753                          * use gzip.  Non standard option.
754                          */
755                         gzip_program = GZIP_CMD;
756                         break;
757                 case 'B':
758                         /*
759                          * Nothing to do here, this is pax default
760                          */
761                         break;
762                 case 'C':
763                         havechd++;
764                         chdname = optarg;
765                         break;
766                 case 'H':
767                         /*
768                          * follow command line symlinks only
769                          */
770                         Hflag = 1;
771                         break;
772                 case 'I':
773                         if (++nincfiles > incfiles_max) {
774                                 incfiles_max = nincfiles + 3;
775                                 incfiles = realloc(incfiles,
776                                     sizeof(*incfiles) * incfiles_max);
777                                 if (incfiles == NULL) {
778                                         paxwarn(0, "Unable to allocate space "
779                                             "for option list");
780                                         exit(1);
781                                 }
782                         }
783                         incfiles[nincfiles - 1].file = optarg;
784                         incfiles[nincfiles - 1].dir = chdname;
785                         break;
786                 case 'L':
787                         /*
788                          * follow symlinks
789                          */
790                         Lflag = 1;
791                         break;
792                 case 'P':
793                         /*
794                          * do not remove leading '/' from pathnames
795                          */
796                         rmleadslash = 0;
797                         break;
798                 case 'X':
799                         /*
800                          * do not pass over mount points in the file system
801                          */
802                         Xflag = 1;
803                         break;
804                 case 'Z':
805                         /*
806                          * use compress.
807                          */
808                         gzip_program = COMPRESS_CMD;
809                         break;
810                 case '0':
811                         arcname = DEV_0;
812                         break;
813                 case '1':
814                         arcname = DEV_1;
815                         break;
816                 case '4':
817                         arcname = DEV_4;
818                         break;
819                 case '5':
820                         arcname = DEV_5;
821                         break;
822                 case '7':
823                         arcname = DEV_7;
824                         break;
825                 case '8':
826                         arcname = DEV_8;
827                         break;
828                 default:
829                         tar_usage();
830                         break;
831                 }
832         }
833         argc -= optind;
834         argv += optind;
835
836         /* Traditional tar behaviour (pax uses stderr unless in list mode) */
837         if (fstdin == 1 && act == ARCHIVE)
838                 listf = stderr;
839         else
840                 listf = stdout;
841
842         /* Traditional tar behaviour (pax wants to read file list from stdin) */
843         if ((act == ARCHIVE || act == APPND) && argc == 0 && nincfiles == 0)
844                 exit(0);
845
846         /*
847          * process the args as they are interpreted by the operation mode
848          */
849         switch (act) {
850         case LIST:
851         case EXTRACT:
852         default:
853                 {
854                         int sawpat = 0;
855                         char *file, *dir;
856
857                         while (nincfiles || *argv != NULL) {
858                                 /*
859                                  * If we queued up any include files,
860                                  * pull them in now.  Otherwise, check
861                                  * for -I and -C positional flags.
862                                  * Anything else must be a file to
863                                  * extract.
864                                  */
865                                 if (nincfiles) {
866                                         file = incfiles->file;
867                                         dir = incfiles->dir;
868                                         incfiles++;
869                                         nincfiles--;
870                                 } else if (strcmp(*argv, "-I") == 0) {
871                                         if (*++argv == NULL)
872                                                 break;
873                                         file = *argv++;
874                                         dir = chdname;
875                                 } else
876                                         file = NULL;
877                                 if (file != NULL) {
878                                         FILE *fp;
879                                         char *str;
880
881                                         if (strcmp(file, "-") == 0)
882                                                 fp = stdin;
883                                         else if ((fp = fopen(file, "r")) == NULL) {
884                                                 paxwarn(1, "Unable to open file '%s' for read", file);
885                                                 tar_usage();
886                                         }
887                                         while ((str = bsd_getline(fp)) != NULL) {
888                                                 if (pat_add(str, dir) < 0)
889                                                         tar_usage();
890                                                 sawpat = 1;
891                                         }
892                                         if (strcmp(file, "-") != 0)
893                                                 fclose(fp);
894                                         if (getline_error) {
895                                                 paxwarn(1, "Problem with file '%s'", file);
896                                                 tar_usage();
897                                         }
898                                 } else if (strcmp(*argv, "-C") == 0) {
899                                         if (*++argv == NULL)
900                                                 break;
901                                         chdname = *argv++;
902                                         havechd++;
903                                 } else if (pat_add(*argv++, chdname) < 0)
904                                         tar_usage();
905                                 else
906                                         sawpat = 1;
907                         }
908                         /*
909                          * if patterns were added, we are doing chdir()
910                          * on a file-by-file basis, else, just one
911                          * global chdir (if any) after opening input.
912                          */
913                         if (sawpat > 0)
914                                 chdname = NULL;
915                 }
916                 break;
917         case ARCHIVE:
918         case APPND:
919                 frmt = &(fsub[Oflag ? F_OTAR : F_TAR]);
920
921                 if (Oflag == 2 && opt_add("write_opt=nodir") < 0)
922                         tar_usage();
923
924                 if (chdname != NULL) {  /* initial chdir() */
925                         if (ftree_add(chdname, 1) < 0)
926                                 tar_usage();
927                 }
928
929                 while (nincfiles || *argv != NULL) {
930                         char *file, *dir;
931
932                         /*
933                          * If we queued up any include files, pull them in
934                          * now.  Otherwise, check for -I and -C positional
935                          * flags.  Anything else must be a file to include
936                          * in the archive.
937                          */
938                         if (nincfiles) {
939                                 file = incfiles->file;
940                                 dir = incfiles->dir;
941                                 incfiles++;
942                                 nincfiles--;
943                         } else if (strcmp(*argv, "-I") == 0) {
944                                 if (*++argv == NULL)
945                                         break;
946                                 file = *argv++;
947                                 dir = NULL;
948                         } else
949                                 file = NULL;
950                         if (file != NULL) {
951                                 FILE *fp;
952                                 char *str;
953
954                                 /* Set directory if needed */
955                                 if (dir) {
956                                         if (ftree_add(dir, 1) < 0)
957                                                 tar_usage();
958                                 }
959
960                                 if (strcmp(file, "-") == 0)
961                                         fp = stdin;
962                                 else if ((fp = fopen(file, "r")) == NULL) {
963                                         paxwarn(1, "Unable to open file '%s' for read", file);
964                                         tar_usage();
965                                 }
966                                 while ((str = bsd_getline(fp)) != NULL) {
967                                         if (ftree_add(str, 0) < 0)
968                                                 tar_usage();
969                                 }
970                                 if (strcmp(file, "-") != 0)
971                                         fclose(fp);
972                                 if (getline_error) {
973                                         paxwarn(1, "Problem with file '%s'",
974                                             file);
975                                         tar_usage();
976                                 }
977                         } else if (strcmp(*argv, "-C") == 0) {
978                                 if (*++argv == NULL)
979                                         break;
980                                 if (ftree_add(*argv++, 1) < 0)
981                                         tar_usage();
982                                 havechd++;
983                         } else if (ftree_add(*argv++, 0) < 0)
984                                 tar_usage();
985                 }
986                 /*
987                  * no read errors allowed on updates/append operation!
988                  */
989                 maxflt = 0;
990                 break;
991         }
992         if (!fstdin && ((arcname == NULL) || (*arcname == '\0'))) {
993                 arcname = getenv("TAPE");
994                 if ((arcname == NULL) || (*arcname == '\0'))
995                         arcname = _PATH_DEFTAPE;
996         }
997 }
998
999 int mkpath(char *);
1000
1001 int
1002 mkpath(path)
1003         char *path;
1004 {
1005         struct stat sb;
1006         char *slash;
1007         int done = 0;
1008
1009         slash = path;
1010
1011         while (!done) {
1012                 slash += strspn(slash, "/");
1013                 slash += strcspn(slash, "/");
1014
1015                 done = (*slash == '\0');
1016                 *slash = '\0';
1017
1018                 if (stat(path, &sb)) {
1019                         if (errno != ENOENT || mkdir(path, 0777)) {
1020                                 paxwarn(1, "%s", path);
1021                                 return (-1);
1022                         }
1023                 } else if (!S_ISDIR(sb.st_mode)) {
1024                         syswarn(1, ENOTDIR, "%s", path);
1025                         return (-1);
1026                 }
1027
1028                 if (!done)
1029                         *slash = '/';
1030         }
1031
1032         return (0);
1033 }
1034 /*
1035  * cpio_options()
1036  *      look at the user specified flags. set globals as required and check if
1037  *      the user specified a legal set of flags. If not, complain and exit
1038  */
1039
1040 static void
1041 cpio_options(int argc, char **argv)
1042 {
1043         int c, i;
1044         char *str;
1045         FSUB tmp;
1046         FILE *fp;
1047
1048         kflag = 1;
1049         pids = 1;
1050         pmode = 1;
1051         pmtime = 0;
1052         arcname = NULL;
1053         dflag = 1;
1054         act = -1;
1055         nodirs = 1;
1056         while ((c=getopt(argc,argv,"abcdfijklmoprstuvzABC:E:F:H:I:LO:SZ6")) != -1)
1057                 switch (c) {
1058                         case 'a':
1059                                 /*
1060                                  * preserve access time on files read
1061                                  */
1062                                 tflag = 1;
1063                                 break;
1064                         case 'b':
1065                                 /*
1066                                  * swap bytes and half-words when reading data
1067                                  */
1068                                 break;
1069                         case 'c':
1070                                 /*
1071                                  * ASCII cpio header
1072                                  */
1073                                 frmt = &(fsub[F_ACPIO]);
1074                                 break;
1075                         case 'd':
1076                                 /*
1077                                  * create directories as needed
1078                                  */
1079                                 nodirs = 0;
1080                                 break;
1081                         case 'f':
1082                                 /*
1083                                  * invert meaning of pattern list
1084                                  */
1085                                 cflag = 1;
1086                                 break;
1087                         case 'i':
1088                                 /*
1089                                  * restore an archive
1090                                  */
1091                                 act = EXTRACT;
1092                                 break;
1093                         case 'j':
1094                                 /*
1095                                  * use bzip2.  Non standard option.
1096                                  */
1097                                 gzip_program = BZIP2_CMD;
1098                                 break;
1099                         case 'k':
1100                                 break;
1101                         case 'l':
1102                                 /*
1103                                  * use links instead of copies when possible
1104                                  */
1105                                 lflag = 1;
1106                                 break;
1107                         case 'm':
1108                                 /*
1109                                  * preserve modification time
1110                                  */
1111                                 pmtime = 1;
1112                                 break;
1113                         case 'o':
1114                                 /*
1115                                  * create an archive
1116                                  */
1117                                 act = ARCHIVE;
1118                                 frmt = &(fsub[F_CPIO]);
1119                                 break;
1120                         case 'p':
1121                                 /*
1122                                  * copy-pass mode
1123                                  */
1124                                 act = COPY;
1125                                 break;
1126                         case 'r':
1127                                 /*
1128                                  * interactively rename files
1129                                  */
1130                                 iflag = 1;
1131                                 break;
1132                         case 's':
1133                                 /*
1134                                  * swap bytes after reading data
1135                                  */
1136                                 break;
1137                         case 't':
1138                                 /*
1139                                  * list contents of archive
1140                                  */
1141                                 act = LIST;
1142                                 listf = stdout;
1143                                 break;
1144                         case 'u':
1145                                 /*
1146                                  * replace newer files
1147                                  */
1148                                 kflag = 0;
1149                                 break;
1150                         case 'v':
1151                                 /*
1152                                  * verbose operation mode
1153                                  */
1154                                 vflag = 1;
1155                                 break;
1156                         case 'z':
1157                                 /*
1158                                  * use gzip.  Non standard option.
1159                                  */
1160                                 gzip_program = GZIP_CMD;
1161                                 break;
1162                         case 'A':
1163                                 /*
1164                                  * append mode
1165                                  */
1166                                 act = APPND;
1167                                 break;
1168                         case 'B':
1169                                 /*
1170                                  * Use 5120 byte block size
1171                                  */
1172                                 wrblksz = 5120;
1173                                 break;
1174                         case 'C':
1175                                 /*
1176                                  * set block size in bytes
1177                                  */
1178                                 wrblksz = atoi(optarg);
1179                                 break;
1180                         case 'E':
1181                                 /*
1182                                  * file with patterns to extract or list
1183                                  */
1184                                 if ((fp = fopen(optarg, "r")) == NULL) {
1185                                         paxwarn(1, "Unable to open file '%s' for read", optarg);
1186                                         cpio_usage();
1187                                 }
1188                                 while ((str = bsd_getline(fp)) != NULL) {
1189                                         pat_add(str, NULL);
1190                                 }
1191                                 fclose(fp);
1192                                 if (getline_error) {
1193                                         paxwarn(1, "Problem with file '%s'", optarg);
1194                                         cpio_usage();
1195                                 }
1196                                 break;
1197                         case 'F':
1198                         case 'I':
1199                         case 'O':
1200                                 /*
1201                                  * filename where the archive is stored
1202                                  */
1203                                 if ((optarg[0] == '-') && (optarg[1]== '\0')) {
1204                                         /*
1205                                          * treat a - as stdin
1206                                          */
1207                                         arcname = NULL;
1208                                         break;
1209                                 }
1210                                 arcname = optarg;
1211                                 break;
1212                         case 'H':
1213                                 /*
1214                                  * specify an archive format on write
1215                                  */
1216                                 tmp.name = optarg;
1217                                 if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
1218                                     sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL)
1219                                         break;
1220                                 paxwarn(1, "Unknown -H format: %s", optarg);
1221                                 (void)fputs("cpio: Known -H formats are:", stderr);
1222                                 for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
1223                                         (void)fprintf(stderr, " %s", fsub[i].name);
1224                                 (void)fputs("\n\n", stderr);
1225                                 cpio_usage();
1226                                 break;
1227                         case 'L':
1228                                 /*
1229                                  * follow symbolic links
1230                                  */
1231                                 Lflag = 1;
1232                                 break;
1233                         case 'S':
1234                                 /*
1235                                  * swap halfwords after reading data
1236                                  */
1237                                 break;
1238                         case 'Z':
1239                                 /*
1240                                  * use compress.  Non standard option.
1241                                  */
1242                                 gzip_program = COMPRESS_CMD;
1243                                 break;
1244                         case '6':
1245                                 /*
1246                                  * process Version 6 cpio format
1247                                  */
1248                                 frmt = &(fsub[F_OCPIO]);
1249                                 break;
1250                         case '?':
1251                         default:
1252                                 cpio_usage();
1253                                 break;
1254                 }
1255         argc -= optind;
1256         argv += optind;
1257
1258         /*
1259          * process the args as they are interpreted by the operation mode
1260          */
1261         switch (act) {
1262                 case LIST:
1263                 case EXTRACT:
1264                         while (*argv != NULL)
1265                                 if (pat_add(*argv++, NULL) < 0)
1266                                         cpio_usage();
1267                         break;
1268                 case COPY:
1269                         if (*argv == NULL) {
1270                                 paxwarn(0, "Destination directory was not supplied");
1271                                 cpio_usage();
1272                         }
1273                         dirptr = *argv;
1274                         if (mkpath(dirptr) < 0)
1275                                 cpio_usage();
1276                         --argc;
1277                         ++argv;
1278                         /* FALL THROUGH */
1279                 case ARCHIVE:
1280                 case APPND:
1281                         if (*argv != NULL)
1282                                 cpio_usage();
1283                         /*
1284                          * no read errors allowed on updates/append operation!
1285                          */
1286                         maxflt = 0;
1287                         while ((str = bsd_getline(stdin)) != NULL) {
1288                                 ftree_add(str, 0);
1289                         }
1290                         if (getline_error) {
1291                                 paxwarn(1, "Problem while reading stdin");
1292                                 cpio_usage();
1293                         }
1294                         break;
1295                 default:
1296                         cpio_usage();
1297                         break;
1298         }
1299 }
1300
1301 /*
1302  * printflg()
1303  *      print out those invalid flag sets found to the user
1304  */
1305
1306 static void
1307 printflg(unsigned int flg)
1308 {
1309         int nxt;
1310         int pos = 0;
1311
1312         (void)fprintf(stderr,"%s: Invalid combination of options:", argv0);
1313         while ((nxt = ffs(flg)) != 0) {
1314                 flg = flg >> nxt;
1315                 pos += nxt;
1316                 (void)fprintf(stderr, " -%c", flgch[pos-1]);
1317         }
1318         (void)putc('\n', stderr);
1319 }
1320
1321 /*
1322  * c_frmt()
1323  *      comparison routine used by bsearch to find the format specified
1324  *      by the user
1325  */
1326
1327 static int
1328 c_frmt(const void *a, const void *b)
1329 {
1330         return(strcmp(((FSUB *)a)->name, ((FSUB *)b)->name));
1331 }
1332
1333 /*
1334  * opt_next()
1335  *      called by format specific options routines to get each format specific
1336  *      flag and value specified with -o
1337  * Return:
1338  *      pointer to next OPLIST entry or NULL (end of list).
1339  */
1340
1341 OPLIST *
1342 opt_next(void)
1343 {
1344         OPLIST *opt;
1345
1346         if ((opt = ophead) != NULL)
1347                 ophead = ophead->fow;
1348         return(opt);
1349 }
1350
1351 /*
1352  * bad_opt()
1353  *      generic routine used to complain about a format specific options
1354  *      when the format does not support options.
1355  */
1356
1357 int
1358 bad_opt(void)
1359 {
1360         OPLIST *opt;
1361
1362         if (ophead == NULL)
1363                 return(0);
1364         /*
1365          * print all we were given
1366          */
1367         paxwarn(1,"These format options are not supported");
1368         while ((opt = opt_next()) != NULL)
1369                 (void)fprintf(stderr, "\t%s = %s\n", opt->name, opt->value);
1370         pax_usage();
1371         return(0);
1372 }
1373
1374 /*
1375  * opt_add()
1376  *      breaks the value supplied to -o into a option name and value. options
1377  *      are given to -o in the form -o name-value,name=value
1378  *      multiple -o may be specified.
1379  * Return:
1380  *      0 if format in name=value format, -1 if -o is passed junk
1381  */
1382
1383 int
1384 opt_add(const char *str)
1385 {
1386         OPLIST *opt;
1387         char *frpt;
1388         char *pt;
1389         char *endpt;
1390         char *dstr;
1391
1392         if ((str == NULL) || (*str == '\0')) {
1393                 paxwarn(0, "Invalid option name");
1394                 return(-1);
1395         }
1396         if ((dstr = strdup(str)) == NULL) {
1397                 paxwarn(0, "Unable to allocate space for option list");
1398                 return(-1);
1399         }
1400         frpt = endpt = dstr;
1401
1402         /*
1403          * break into name and values pieces and stuff each one into a
1404          * OPLIST structure. When we know the format, the format specific
1405          * option function will go through this list
1406          */
1407         while ((frpt != NULL) && (*frpt != '\0')) {
1408                 if ((endpt = strchr(frpt, ',')) != NULL)
1409                         *endpt = '\0';
1410                 if ((pt = strchr(frpt, '=')) == NULL) {
1411                         paxwarn(0, "Invalid options format");
1412                         free(dstr);
1413                         return(-1);
1414                 }
1415                 if ((opt = (OPLIST *)malloc(sizeof(OPLIST))) == NULL) {
1416                         paxwarn(0, "Unable to allocate space for option list");
1417                         free(dstr);
1418                         return(-1);
1419                 }
1420                 *pt++ = '\0';
1421                 opt->name = frpt;
1422                 opt->value = pt;
1423                 opt->fow = NULL;
1424                 if (endpt != NULL)
1425                         frpt = endpt + 1;
1426                 else
1427                         frpt = NULL;
1428                 if (ophead == NULL) {
1429                         optail = ophead = opt;
1430                         continue;
1431                 }
1432                 optail->fow = opt;
1433                 optail = opt;
1434         }
1435         return(0);
1436 }
1437
1438 /*
1439  * str_offt()
1440  *      Convert an expression of the following forms to an off_t > 0.
1441  *      1) A positive decimal number.
1442  *      2) A positive decimal number followed by a b (mult by 512).
1443  *      3) A positive decimal number followed by a k (mult by 1024).
1444  *      4) A positive decimal number followed by a m (mult by 512).
1445  *      5) A positive decimal number followed by a w (mult by sizeof int)
1446  *      6) Two or more positive decimal numbers (with/without k,b or w).
1447  *         separated by x (also * for backwards compatibility), specifying
1448  *         the product of the indicated values.
1449  * Return:
1450  *      0 for an error, a positive value o.w.
1451  */
1452
1453 static off_t
1454 str_offt(char *val)
1455 {
1456         char *expr;
1457         off_t num, t;
1458
1459 #       ifdef LONG_OFF_T
1460         num = strtol(val, &expr, 0);
1461         if ((num == LONG_MAX) || (num <= 0) || (expr == val))
1462 #       else
1463         num = strtoq(val, &expr, 0);
1464         if ((num == LLONG_MAX) || (num <= 0) || (expr == val))
1465 #       endif
1466                 return(0);
1467
1468         switch (*expr) {
1469         case 'b':
1470                 t = num;
1471                 num *= 512;
1472                 if (t > num)
1473                         return(0);
1474                 ++expr;
1475                 break;
1476         case 'k':
1477                 t = num;
1478                 num *= 1024;
1479                 if (t > num)
1480                         return(0);
1481                 ++expr;
1482                 break;
1483         case 'm':
1484                 t = num;
1485                 num *= 1048576;
1486                 if (t > num)
1487                         return(0);
1488                 ++expr;
1489                 break;
1490         case 'w':
1491                 t = num;
1492                 num *= sizeof(int);
1493                 if (t > num)
1494                         return(0);
1495                 ++expr;
1496                 break;
1497         }
1498
1499         switch (*expr) {
1500                 case '\0':
1501                         break;
1502                 case '*':
1503                 case 'x':
1504                         t = num;
1505                         num *= str_offt(expr + 1);
1506                         if (t > num)
1507                                 return(0);
1508                         break;
1509                 default:
1510                         return(0);
1511         }
1512         return(num);
1513 }
1514
1515 char *
1516 bsd_getline(FILE *f)
1517 {
1518         char *name, *temp;
1519         size_t len;
1520
1521         name = fgetln(f, &len);
1522         if (!name) {
1523                 getline_error = ferror(f) ? GETLINE_FILE_CORRUPT : 0;
1524                 return(0);
1525         }
1526         if (name[len-1] != '\n')
1527                 len++;
1528         temp = malloc(len);
1529         if (!temp) {
1530                 getline_error = GETLINE_OUT_OF_MEM;
1531                 return(0);
1532         }
1533         memcpy(temp, name, len-1);
1534         temp[len-1] = 0;
1535         return(temp);
1536 }
1537                         
1538 /*
1539  * no_op()
1540  *      for those option functions where the archive format has nothing to do.
1541  * Return:
1542  *      0
1543  */
1544
1545 static int
1546 no_op(void)
1547 {
1548         return(0);
1549 }
1550
1551 /*
1552  * pax_usage()
1553  *      print the usage summary to the user
1554  */
1555
1556 void
1557 pax_usage(void)
1558 {
1559         (void)fputs(
1560             "usage: pax [-0cdjnOvz] [-E limit] [-f archive] [-G group] [-s replstr]\n"
1561             "           [-T range] [-U user] [pattern ...]\n"
1562             "       pax -r [-0cDdijknOuvYZz] [-E limit] [-f archive] [-G group] [-o options]\n"
1563             "           [-p string] [-s replstr] [-T range] [-U user] [pattern ...]\n"
1564             "       pax -w [-0adHijLOPtuvXz] [-B bytes] [-b blocksize] [-f archive]\n"
1565             "           [-G group] [-o options] [-s replstr] [-T range] [-U user]\n"
1566             "           [-x format] [file ...]\n"
1567             "       pax -rw [-0DdHikLlnOPtuvXYZ] [-G group] [-p string] [-s replstr]\n"
1568             "           [-T range] [-U user] [file ...] directory\n",
1569             stderr);
1570         exit(1);
1571 }
1572
1573 /*
1574  * tar_usage()
1575  *      print the usage summary to the user
1576  */
1577
1578 void
1579 tar_usage(void)
1580 {
1581         (void)fputs(
1582             "usage: tar {crtux}[014578befHhjLmOoPpqsvwXZz]\n"
1583             "           [blocking-factor | archive | replstr] [-C directory] [-I file]\n"
1584             "           [file ...]\n"
1585             "       tar {-crtux} [-014578eHhjLmOoPpqvwXZz] [-b blocking-factor]\n"
1586             "           [-C directory] [-f archive] [-I file] [-s replstr] [file ...]\n",
1587             stderr);
1588         exit(1);
1589 }
1590
1591 /*
1592  * cpio_usage()
1593  *      print the usage summary to the user
1594  */
1595
1596 void
1597 cpio_usage(void)
1598 {
1599         (void)fputs(
1600             "usage: cpio -o [-AaBcjLvZz] [-C bytes] [-F archive] [-H format]\n"
1601             "            [-O archive] < name-list [> archive]\n"
1602             "       cpio -i [-6BbcdfjmrSstuvZz] [-C bytes] [-E file] [-F archive] [-H format]\n"
1603             "            [-I archive] [pattern ...] [< archive]\n"
1604             "       cpio -p [-adLlmuv] destination-directory < name-list\n",
1605             stderr);
1606         exit(1);
1607 }