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