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