xref: /netbsd-src/bin/pax/options.c (revision 2b9c0f9f43ba74451b873b59bedeb267f2fc4a30)
1 /*	$NetBSD: options.c,v 1.121 2024/08/05 13:37:27 riastradh Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992 Keith Muller.
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #if HAVE_NBTOOL_CONFIG_H
37 #include "nbtool_config.h"
38 #endif
39 
40 #include <sys/cdefs.h>
41 #if !defined(lint)
42 #if 0
43 static char sccsid[] = "@(#)options.c	8.2 (Berkeley) 4/18/94";
44 #else
45 __RCSID("$NetBSD: options.c,v 1.121 2024/08/05 13:37:27 riastradh Exp $");
46 #endif
47 #endif /* not lint */
48 
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <sys/stat.h>
52 #include <sys/param.h>
53 #include <ctype.h>
54 #include <errno.h>
55 #if HAVE_NBTOOL_CONFIG_H
56 #include "compat_getopt.h"
57 #else
58 #include <getopt.h>
59 #endif
60 #include <limits.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <strings.h>
65 #include <unistd.h>
66 #include <inttypes.h>
67 #include <paths.h>
68 #include <util.h>
69 #include "pax.h"
70 #include "options.h"
71 #include "cpio.h"
72 #include "tar.h"
73 #include "extern.h"
74 #ifndef SMALL
75 #include "mtree.h"
76 #endif	/* SMALL */
77 
78 char *chdname;
79 #if !HAVE_NBTOOL_CONFIG_H
80 int do_chroot;
81 #endif
82 
83 /*
84  * Routines which handle command line options
85  */
86 struct stat tst;		/* Timestamp to set if non-0 */
87 
88 static int nopids;		/* tar mode: suppress "pids" for -p option */
89 static char flgch[] = FLGCH;	/* list of all possible flags (pax) */
90 static OPLIST *ophead = NULL;	/* head for format specific options -x */
91 static OPLIST *optail = NULL;	/* option tail */
92 
93 static int opt_add(const char *);
94 static int no_op(void);
95 static void printflg(unsigned int);
96 static int c_frmt(const void *, const void *);
97 static off_t str_offt(char *);
98 static char *get_line(FILE *fp);
99 #ifndef SMALL
100 static int set_tstamp(const char *, struct stat *);
101 #endif
102 static void pax_options(int, char **);
103 __dead static void pax_usage(void);
104 static void tar_options(int, char **);
105 __dead static void tar_usage(void);
106 #ifndef NO_CPIO
107 static void cpio_options(int, char **);
108 __dead static void cpio_usage(void);
109 #endif
110 
111 /* errors from get_line */
112 #define GETLINE_FILE_CORRUPT 1
113 #define GETLINE_OUT_OF_MEM 2
114 static int get_line_error;
115 
116 #define BZIP2_CMD	"bzip2"		/* command to run as bzip2 */
117 #define GZIP_CMD	"gzip"		/* command to run as gzip */
118 #define XZ_CMD		"xz"		/* command to run as xz */
119 #define COMPRESS_CMD	"compress"	/* command to run as compress */
120 
121 /*
122  * Long options.
123  */
124 #define	OPT_USE_COMPRESS_PROGRAM	0
125 #define	OPT_CHECKPOINT			1
126 #define	OPT_UNLINK			2
127 #define	OPT_HELP			3
128 #define	OPT_ATIME_PRESERVE		4
129 #define	OPT_IGNORE_FAILED_READ		5
130 #define	OPT_REMOVE_FILES		6
131 #define	OPT_NULL			7
132 #define	OPT_TOTALS			8
133 #define	OPT_VERSION			9
134 #define	OPT_EXCLUDE			10
135 #define	OPT_BLOCK_COMPRESS		11
136 #define	OPT_NORECURSE			12
137 #define	OPT_FORCE_LOCAL			13
138 #define	OPT_INSECURE			14
139 #define	OPT_STRICT			15
140 #define	OPT_SPARSE			16
141 #define OPT_XZ				17
142 #define OPT_GNU				18
143 #define	OPT_TIMESTAMP			19
144 #if !HAVE_NBTOOL_CONFIG_H
145 #define	OPT_CHROOT			20
146 #endif
147 
148 /*
149  *	Format specific routine table - MUST BE IN SORTED ORDER BY NAME
150  *	(see pax.h for description of each function)
151  *
152  *	name, blksz, hdsz, udev, hlk, blkagn, inhead, id, st_read,
153  *	read, end_read, st_write, write, end_write, trail,
154  *	subtrail, rd_data, wr_data, options
155  */
156 
157 FSUB fsub[] = {
158 #ifndef NO_CPIO
159 /* 0: OLD BINARY CPIO */
160 	{ "bcpio", 5120, sizeof(HD_BCPIO), 1, 0, 0, 1, bcpio_id, cpio_strd,
161 	bcpio_rd, bcpio_endrd, cpio_stwr, bcpio_wr, cpio_endwr, NULL,
162 	cpio_subtrail, rd_wrfile, wr_rdfile, bad_opt },
163 
164 /* 1: OLD OCTAL CHARACTER CPIO */
165 	{ "cpio", 5120, sizeof(HD_CPIO), 1, 0, 0, 1, cpio_id, cpio_strd,
166 	cpio_rd, cpio_endrd, cpio_stwr, cpio_wr, cpio_endwr, NULL,
167 	cpio_subtrail, rd_wrfile, wr_rdfile, bad_opt },
168 
169 /* 2: SVR4 HEX CPIO */
170 	{ "sv4cpio", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, vcpio_id, cpio_strd,
171 	vcpio_rd, vcpio_endrd, cpio_stwr, vcpio_wr, cpio_endwr, NULL,
172 	cpio_subtrail, rd_wrfile, wr_rdfile, bad_opt },
173 
174 /* 3: SVR4 HEX CPIO WITH CRC */
175 	{ "sv4crc", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, crc_id, crc_strd,
176 	vcpio_rd, vcpio_endrd, crc_stwr, vcpio_wr, cpio_endwr, NULL,
177 	cpio_subtrail, rd_wrfile, wr_rdfile, bad_opt },
178 #endif
179 /* 4: OLD TAR */
180 	{ "tar", 10240, BLKMULT, 0, 1, BLKMULT, 0, tar_id, no_op,
181 	tar_rd, tar_endrd, no_op, tar_wr, tar_endwr, tar_trail,
182 	NULL, rd_wrfile, wr_rdfile, tar_opt },
183 
184 /* 5: POSIX USTAR */
185 	{ "ustar", 10240, BLKMULT, 0, 1, BLKMULT, 0, ustar_id, ustar_strd,
186 	ustar_rd, tar_endrd, ustar_stwr, ustar_wr, tar_endwr, tar_trail,
187 	NULL, rd_wrfile, wr_rdfile, bad_opt }
188 };
189 #ifndef NO_CPIO
190 #define F_BCPIO		0	/* old binary cpio format */
191 #define F_CPIO		1	/* old octal character cpio format */
192 #define F_SV4CPIO	2	/* SVR4 hex cpio format */
193 #define F_SV4CRC	3	/* SVR4 hex with crc cpio format */
194 #define F_TAR		4	/* old V7 UNIX tar format */
195 #define F_USTAR		5	/* ustar format */
196 #else
197 #define F_TAR		0	/* old V7 UNIX tar format */
198 #define F_USTAR		1	/* ustar format */
199 #endif
200 #define DEFLT		F_USTAR	/* default write format from list above */
201 
202 /*
203  * ford is the archive search order used by get_arc() to determine what kind
204  * of archive we are dealing with. This helps to properly id archive formats
205  * some formats may be subsets of others....
206  */
207 int ford[] = {F_USTAR, F_TAR,
208 #ifndef NO_CPIO
209     F_SV4CRC, F_SV4CPIO, F_CPIO, F_BCPIO,
210 #endif
211     -1};
212 
213 /*
214  * filename record separator
215  */
216 int sep = '\n';
217 
218 /*
219  * Do we have -C anywhere?
220  */
221 int havechd = 0;
222 
223 /*
224  * options()
225  *	figure out if we are pax, tar or cpio. Call the appropriate options
226  *	parser
227  */
228 
229 void
230 options(int argc, char **argv)
231 {
232 
233 	/*
234 	 * Are we acting like pax, tar or cpio (based on argv[0])
235 	 */
236 	if ((argv0 = strrchr(argv[0], '/')) != NULL)
237 		argv0++;
238 	else
239 		argv0 = argv[0];
240 
241 	if (strstr(argv0, NM_TAR)) {
242 		argv0 = NM_TAR;
243 		tar_options(argc, argv);
244 #ifndef NO_CPIO
245 	} else if (strstr(argv0, NM_CPIO)) {
246 		argv0 = NM_CPIO;
247 		cpio_options(argc, argv);
248 #endif
249 	} else {
250 		argv0 = NM_PAX;
251 		pax_options(argc, argv);
252 	}
253 }
254 
255 struct option pax_longopts[] = {
256 	{ "insecure",		no_argument,		0,
257 						OPT_INSECURE },
258 	{ "force-local",	no_argument,		0,
259 						OPT_FORCE_LOCAL },
260 	{ "use-compress-program", required_argument,	0,
261 						OPT_USE_COMPRESS_PROGRAM },
262 	{ "xz",			no_argument,		0,
263 						OPT_XZ },
264 	{ "gnu",		no_argument,		0,
265 						OPT_GNU },
266 	{ "timestamp",		required_argument,	0,
267 						OPT_TIMESTAMP },
268 	{ 0,			0,			0,
269 						0 },
270 };
271 
272 /*
273  * pax_options()
274  *	look at the user specified flags. set globals as required and check if
275  *	the user specified a legal set of flags. If not, complain and exit
276  */
277 
278 static void
279 pax_options(int argc, char **argv)
280 {
281 	int c;
282 	size_t i;
283 	u_int64_t flg = 0;
284 	u_int64_t bflg = 0;
285 	char *pt;
286 	FSUB tmp;
287 
288 	/*
289 	 * process option flags
290 	 */
291 	while ((c = getopt_long(argc, argv,
292 	    "0ab:cdf:ijklno:p:rs:tuvwx:zAB:DE:G:HLMN:OPT:U:VXYZ",
293 	    pax_longopts, NULL)) != -1) {
294 		switch (c) {
295 		case '0':
296 			sep = '\0';
297 			break;
298 		case 'a':
299 			/*
300 			 * append
301 			 */
302 			flg |= AF;
303 			break;
304 		case 'b':
305 			/*
306 			 * specify blocksize
307 			 */
308 			flg |= BF;
309 			if ((wrblksz = (int)str_offt(optarg)) <= 0) {
310 				tty_warn(1, "Invalid block size %s", optarg);
311 				pax_usage();
312 			}
313 			break;
314 		case 'c':
315 			/*
316 			 * inverse match on patterns
317 			 */
318 			cflag = 1;
319 			flg |= CF;
320 			break;
321 		case 'd':
322 			/*
323 			 * match only dir on extract, not the subtree at dir
324 			 */
325 			dflag = 1;
326 			flg |= DF;
327 			break;
328 		case 'f':
329 			/*
330 			 * filename where the archive is stored
331 			 */
332 			arcname = optarg;
333 			flg |= FF;
334 			break;
335 		case 'i':
336 			/*
337 			 * interactive file rename
338 			 */
339 			iflag = 1;
340 			flg |= IF;
341 			break;
342 		case 'j':
343 			/*
344 			 * pass through bzip2
345 			 */
346 			gzip_program = BZIP2_CMD;
347 			break;
348 		case 'k':
349 			/*
350 			 * do not clobber files that exist
351 			 */
352 			kflag = 1;
353 			flg |= KF;
354 			break;
355 		case 'l':
356 			/*
357 			 * try to link src to dest with copy (-rw)
358 			 */
359 			lflag = 1;
360 			flg |= LF;
361 			break;
362 		case 'n':
363 			/*
364 			 * select first match for a pattern only
365 			 */
366 			nflag = 1;
367 			flg |= NF;
368 			break;
369 		case 'o':
370 			/*
371 			 * pass format specific options
372 			 */
373 			flg |= OF;
374 			if (opt_add(optarg) < 0)
375 				pax_usage();
376 			break;
377 		case 'p':
378 			/*
379 			 * specify file characteristic options
380 			 */
381 			for (pt = optarg; *pt != '\0'; ++pt) {
382 				switch(*pt) {
383 				case 'a':
384 					/*
385 					 * do not preserve access time
386 					 */
387 					patime = 0;
388 					break;
389 				case 'e':
390 					/*
391 					 * preserve user id, group id, file
392 					 * mode, access/modification times
393 					 * and file flags.
394 					 */
395 					pids = 1;
396 					pmode = 1;
397 					patime = 1;
398 					pmtime = 1;
399 					pfflags = 1;
400 					break;
401 #if 0
402 				case 'f':
403 					/*
404 					 * do not preserve file flags
405 					 */
406 					pfflags = 0;
407 					break;
408 #endif
409 				case 'm':
410 					/*
411 					 * do not preserve modification time
412 					 */
413 					pmtime = 0;
414 					break;
415 				case 'o':
416 					/*
417 					 * preserve uid/gid
418 					 */
419 					pids = 1;
420 					break;
421 				case 'p':
422 					/*
423 					 * preserve file mode bits
424 					 */
425 					pmode = 1;
426 					break;
427 				default:
428 					tty_warn(1, "Invalid -p string: %c",
429 					    *pt);
430 					pax_usage();
431 					break;
432 				}
433 			}
434 			flg |= PF;
435 			break;
436 		case 'r':
437 			/*
438 			 * read the archive
439 			 */
440 			flg |= RF;
441 			break;
442 		case 's':
443 			/*
444 			 * file name substitution name pattern
445 			 */
446 			if (rep_add(optarg) < 0) {
447 				pax_usage();
448 				break;
449 			}
450 			flg |= SF;
451 			break;
452 		case 't':
453 			/*
454 			 * preserve access time on filesystem nodes we read
455 			 */
456 			tflag = 1;
457 			flg |= TF;
458 			break;
459 		case 'u':
460 			/*
461 			 * ignore those older files
462 			 */
463 			uflag = 1;
464 			flg |= UF;
465 			break;
466 		case 'v':
467 			/*
468 			 * verbose operation mode
469 			 */
470 			vflag = 1;
471 			flg |= VF;
472 			break;
473 		case 'w':
474 			/*
475 			 * write an archive
476 			 */
477 			flg |= WF;
478 			break;
479 		case 'x':
480 			/*
481 			 * specify an archive format on write
482 			 */
483 			tmp.name = optarg;
484 			frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
485 			    sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt);
486 			if (frmt != NULL) {
487 				flg |= XF;
488 				break;
489 			}
490 			tty_warn(1, "Unknown -x format: %s", optarg);
491 			(void)fputs("pax: Known -x formats are:", stderr);
492 			for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
493 				(void)fprintf(stderr, " %s", fsub[i].name);
494 			(void)fputs("\n\n", stderr);
495 			pax_usage();
496 			break;
497 		case 'z':
498 			/*
499 			 * use gzip.  Non standard option.
500 			 */
501 			gzip_program = GZIP_CMD;
502 			break;
503 		case 'A':
504 			Aflag = 1;
505 			flg |= CAF;
506 			break;
507 		case 'B':
508 			/*
509 			 * non-standard option on number of bytes written on a
510 			 * single archive volume.
511 			 */
512 			if ((wrlimit = str_offt(optarg)) <= 0) {
513 				tty_warn(1, "Invalid write limit %s", optarg);
514 				pax_usage();
515 			}
516 			if (wrlimit % BLKMULT) {
517 				tty_warn(1,
518 				    "Write limit is not a %d byte multiple",
519 				    BLKMULT);
520 				pax_usage();
521 			}
522 			flg |= CBF;
523 			break;
524 		case 'D':
525 			/*
526 			 * On extraction check file inode change time before the
527 			 * modification of the file name. Non standard option.
528 			 */
529 			Dflag = 1;
530 			flg |= CDF;
531 			break;
532 		case 'E':
533 			/*
534 			 * non-standard limit on read faults
535 			 * 0 indicates stop after first error, values
536 			 * indicate a limit, "none" try forever
537 			 */
538 			flg |= CEF;
539 			if (strcmp(none, optarg) == 0)
540 				maxflt = -1;
541 			else if ((maxflt = atoi(optarg)) < 0) {
542 				tty_warn(1,
543 				    "Error count value must be positive");
544 				pax_usage();
545 			}
546 			break;
547 		case 'G':
548 			/*
549 			 * non-standard option for selecting files within an
550 			 * archive by group (gid or name)
551 			 */
552 			if (grp_add(optarg) < 0) {
553 				pax_usage();
554 				break;
555 			}
556 			flg |= CGF;
557 			break;
558 		case 'H':
559 			/*
560 			 * follow command line symlinks only
561 			 */
562 			Hflag = 1;
563 			flg |= CHF;
564 			break;
565 		case 'L':
566 			/*
567 			 * follow symlinks
568 			 */
569 			Lflag = 1;
570 			flg |= CLF;
571 			break;
572 #ifdef SMALL
573 		case 'M':
574 		case 'N':
575 			tty_warn(1, "Support for -%c is not compiled in", c);
576 			exit(1);
577 #else	/* !SMALL */
578 		case 'M':
579 			/*
580 			 * Treat list of filenames on stdin as an
581 			 * mtree(8) specfile.  Non standard option.
582 			 */
583 			Mflag = 1;
584 			flg |= CMF;
585 			break;
586 		case 'N':
587 			/*
588 			 * Use alternative directory for user db lookups.
589 			 */
590 			if (!setup_getid(optarg)) {
591 				tty_warn(1,
592 			    "Unable to use user and group databases in `%s'",
593 				    optarg);
594 				pax_usage();
595 			}
596 			break;
597 #endif	/* !SMALL */
598 		case 'O':
599 			/*
600 			 * Force one volume.  Non standard option.
601 			 */
602 			force_one_volume = 1;
603 			break;
604 		case 'P':
605 			/*
606 			 * do NOT follow symlinks (default)
607 			 */
608 			Lflag = 0;
609 			flg |= CPF;
610 			break;
611 		case 'T':
612 			/*
613 			 * non-standard option for selecting files within an
614 			 * archive by modification time range (lower,upper)
615 			 */
616 			if (trng_add(optarg) < 0) {
617 				pax_usage();
618 				break;
619 			}
620 			flg |= CTF;
621 			break;
622 		case 'U':
623 			/*
624 			 * non-standard option for selecting files within an
625 			 * archive by user (uid or name)
626 			 */
627 			if (usr_add(optarg) < 0) {
628 				pax_usage();
629 				break;
630 			}
631 			flg |= CUF;
632 			break;
633 		case 'V':
634 			/*
635 			 * somewhat verbose operation mode (no listing)
636 			 */
637 			Vflag = 1;
638 			flg |= VSF;
639 			break;
640 		case 'X':
641 			/*
642 			 * do not pass over mount points in the file system
643 			 */
644 			Xflag = 1;
645 			flg |= CXF;
646 			break;
647 		case 'Y':
648 			/*
649 			 * On extraction check file inode change time after the
650 			 * modification of the file name. Non standard option.
651 			 */
652 			Yflag = 1;
653 			flg |= CYF;
654 			break;
655 		case 'Z':
656 			/*
657 			 * On extraction check modification time after the
658 			 * modification of the file name. Non standard option.
659 			 */
660 			Zflag = 1;
661 			flg |= CZF;
662 			break;
663 		case OPT_INSECURE:
664 			secure = 0;
665 			break;
666 		case OPT_FORCE_LOCAL:
667 			forcelocal = 1;
668 			break;
669 		case OPT_USE_COMPRESS_PROGRAM:
670 			gzip_program = optarg;
671 			break;
672 		case OPT_XZ:
673 			gzip_program = XZ_CMD;
674 			break;
675 		case OPT_GNU:
676 			is_gnutar = 1;
677 			break;
678 #ifndef SMALL
679 		case OPT_TIMESTAMP:
680 			if (set_tstamp(optarg, &tst) == -1) {
681 				tty_warn(1, "Invalid timestamp `%s'", optarg);
682 				tar_usage();
683 			}
684 			break;
685 #endif
686 		case '?':
687 		default:
688 			pax_usage();
689 			break;
690 		}
691 	}
692 
693 	/*
694 	 * figure out the operation mode of pax read,write,extract,copy,append
695 	 * or list. check that we have not been given a bogus set of flags
696 	 * for the operation mode.
697 	 */
698 	if (ISLIST(flg)) {
699 		act = LIST;
700 		listf = stdout;
701 		bflg = flg & BDLIST;
702 	} else if (ISEXTRACT(flg)) {
703 		act = EXTRACT;
704 		bflg = flg & BDEXTR;
705 	} else if (ISARCHIVE(flg)) {
706 		act = ARCHIVE;
707 		bflg = flg & BDARCH;
708 	} else if (ISAPPND(flg)) {
709 		act = APPND;
710 		bflg = flg & BDARCH;
711 	} else if (ISCOPY(flg)) {
712 		act = COPY;
713 		bflg = flg & BDCOPY;
714 	} else
715 		pax_usage();
716 	if (bflg) {
717 		printflg(flg);
718 		pax_usage();
719 	}
720 
721 	/*
722 	 * if we are writing (ARCHIVE) we use the default format if the user
723 	 * did not specify a format. when we write during an APPEND, we will
724 	 * adopt the format of the existing archive if none was supplied.
725 	 */
726 	if (!(flg & XF) && (act == ARCHIVE))
727 		frmt = &(fsub[DEFLT]);
728 
729 	/*
730 	 * process the args as they are interpreted by the operation mode
731 	 */
732 	switch (act) {
733 	case LIST:
734 	case EXTRACT:
735 		for (; optind < argc; optind++)
736 			if (pat_add(argv[optind], NULL, 0) < 0)
737 				pax_usage();
738 		break;
739 	case COPY:
740 		if (optind >= argc) {
741 			tty_warn(0, "Destination directory was not supplied");
742 			pax_usage();
743 		}
744 		--argc;
745 		dirptr = argv[argc];
746 		if (mkpath(dirptr) < 0)
747 			exit(1);
748 		/* FALLTHROUGH */
749 	case ARCHIVE:
750 	case APPND:
751 		for (; optind < argc; optind++)
752 			if (ftree_add(argv[optind], 0) < 0)
753 				pax_usage();
754 		/*
755 		 * no read errors allowed on updates/append operation!
756 		 */
757 		maxflt = 0;
758 		break;
759 	}
760 }
761 
762 
763 /*
764  * tar_options()
765  *	look at the user specified flags. set globals as required and check if
766  *	the user specified a legal set of flags. If not, complain and exit
767  */
768 
769 struct option tar_longopts[] = {
770 	{ "block-size",		required_argument,	0,	'b' },
771 	{ "bunzip2",		no_argument,		0,	'j' },
772 	{ "bzip2",		no_argument,		0,	'j' },
773 	{ "create",		no_argument,		0,	'c' },	/* F */
774 	/* -e -- no corresponding long option */
775 	{ "file",		required_argument,	0,	'f' },
776 	{ "dereference",	no_argument,		0,	'h' },
777 	{ "keep-old-files",	no_argument,		0,	'k' },
778 	{ "one-file-system",	no_argument,		0,	'l' },
779 	{ "modification-time",	no_argument,		0,	'm' },
780 	{ "old-archive",	no_argument,		0,	'o' },
781 	{ "portability",	no_argument,		0,	'o' },
782 	{ "same-permissions",	no_argument,		0,	'p' },
783 	{ "preserve-permissions", no_argument,		0,	'p' },
784 	{ "preserve",		no_argument,		0,	'p' },
785 	{ "fast-read",		no_argument,		0,	'q' },
786 	{ "append",		no_argument,		0,	'r' },	/* F */
787 	{ "update",		no_argument,		0,	'u' },	/* F */
788 	{ "list",		no_argument,		0,	't' },	/* F */
789 	{ "verbose",		no_argument,		0,	'v' },
790 	{ "interactive",	no_argument,		0,	'w' },
791 	{ "confirmation",	no_argument,		0,	'w' },
792 	{ "extract",		no_argument,		0,	'x' },	/* F */
793 	{ "get",		no_argument,		0,	'x' },	/* F */
794 	{ "gzip",		no_argument,		0,	'z' },
795 	{ "gunzip",		no_argument,		0,	'z' },
796 	{ "read-full-blocks",	no_argument,		0,	'B' },
797 	{ "directory",		required_argument,	0,	'C' },
798 	{ "xz",			no_argument,		0,	'J' },
799 	{ "to-stdout",		no_argument,		0,	'O' },
800 	{ "absolute-paths",	no_argument,		0,	'P' },
801 	{ "sparse",		no_argument,		0,	'S' },
802 	{ "files-from",		required_argument,	0,	'T' },
803 	{ "summary",		no_argument,		0,	'V' },
804 	{ "stats",		no_argument,		0,	'V' },
805 	{ "exclude-from",	required_argument,	0,	'X' },
806 	{ "compress",		no_argument,		0,	'Z' },
807 	{ "uncompress",		no_argument,		0,	'Z' },
808 	{ "strict",		no_argument,		0,
809 						OPT_STRICT },
810 	{ "atime-preserve",	no_argument,		0,
811 						OPT_ATIME_PRESERVE },
812 	{ "unlink",		no_argument,		0,
813 						OPT_UNLINK },
814 	{ "use-compress-program", required_argument,	0,
815 						OPT_USE_COMPRESS_PROGRAM },
816 	{ "force-local",	no_argument,		0,
817 						OPT_FORCE_LOCAL },
818 	{ "insecure",		no_argument,		0,
819 						OPT_INSECURE },
820 	{ "exclude",		required_argument,	0,
821 						OPT_EXCLUDE },
822 	{ "no-recursion",	no_argument,		0,
823 						OPT_NORECURSE },
824 #if !HAVE_NBTOOL_CONFIG_H
825 	{ "chroot",		no_argument,		0,
826 						OPT_CHROOT },
827 #endif
828 	{ "timestamp",		required_argument,	0,
829 						OPT_TIMESTAMP },
830 #if 0 /* Not implemented */
831 	{ "catenate",		no_argument,		0,	'A' },	/* F */
832 	{ "concatenate",	no_argument,		0,	'A' },	/* F */
833 	{ "diff",		no_argument,		0,	'd' },	/* F */
834 	{ "compare",		no_argument,		0,	'd' },	/* F */
835 	{ "checkpoint",		no_argument,		0,
836 						OPT_CHECKPOINT },
837 	{ "help",		no_argument,		0,
838 						OPT_HELP },
839 	{ "info-script",	required_argument,	0,	'F' },
840 	{ "new-volume-script",	required_argument,	0,	'F' },
841 	{ "incremental",	no_argument,		0,	'G' },
842 	{ "listed-incremental",	required_argument,	0,	'g' },
843 	{ "ignore-zeros",	no_argument,		0,	'i' },
844 	{ "ignore-failed-read",	no_argument,		0,
845 						OPT_IGNORE_FAILED_READ },
846 	{ "starting-file",	no_argument,		0,	'K' },
847 	{ "tape-length",	required_argument,	0,	'L' },
848 	{ "multi-volume",	no_argument,		0,	'M' },
849 	{ "after-date",		required_argument,	0,	'N' },
850 	{ "newer",		required_argument,	0,	'N' },
851 	{ "record-number",	no_argument,		0,	'R' },
852 	{ "remove-files",	no_argument,		0,
853 						OPT_REMOVE_FILES },
854 	{ "same-order",		no_argument,		0,	's' },
855 	{ "preserve-order",	no_argument,		0,	's' },
856 	{ "null",		no_argument,		0,
857 						OPT_NULL },
858 	{ "totals",		no_argument,		0,
859 						OPT_TOTALS },
860 	{ "volume-name",	required_argument,	0,	'V' }, /* XXX */
861 	{ "label",		required_argument,	0,	'V' }, /* XXX */
862 	{ "version",		no_argument,		0,
863 						OPT_VERSION },
864 	{ "verify",		no_argument,		0,	'W' },
865 	{ "block-compress",	no_argument,		0,
866 						OPT_BLOCK_COMPRESS },
867 #endif
868 	{ 0,			0,			0,	0 },
869 };
870 
871 static void
872 tar_set_action(int op)
873 {
874 	if (act != ERROR && act != op)
875 		tar_usage();
876 	act = op;
877 }
878 
879 static void
880 tar_options(int argc, char **argv)
881 {
882 	int c;
883 	int fstdin = 0;
884 	int Oflag = 0;
885 	int nincfiles = 0;
886 	int incfiles_max = 0;
887 	struct incfile {
888 		char *file;
889 		char *dir;
890 	};
891 	struct incfile *incfiles = NULL;
892 
893 	/*
894 	 * Set default values.
895 	 */
896 	rmleadslash = 1;
897 	is_gnutar = 1;
898 
899 	/*
900 	 * process option flags
901 	 */
902 	while ((c = getoldopt(argc, argv,
903 	    "+b:cef:hjklmopqrs:tuvwxzBC:HI:JOPST:X:Z014578",
904 	    tar_longopts, NULL))
905 	    != -1)  {
906 		switch(c) {
907 		case 'b':
908 			/*
909 			 * specify blocksize in 512-byte blocks
910 			 */
911 			if ((wrblksz = (int)str_offt(optarg)) <= 0) {
912 				tty_warn(1, "Invalid block size %s", optarg);
913 				tar_usage();
914 			}
915 			wrblksz *= 512;		/* XXX - check for int oflow */
916 			break;
917 		case 'c':
918 			/*
919 			 * create an archive
920 			 */
921 			tar_set_action(ARCHIVE);
922 			break;
923 		case 'e':
924 			/*
925 			 * stop after first error
926 			 */
927 			maxflt = 0;
928 			break;
929 		case 'f':
930 			/*
931 			 * filename where the archive is stored
932 			 */
933 			if ((optarg[0] == '-') && (optarg[1]== '\0')) {
934 				/*
935 				 * treat a - as stdin
936 				 */
937 				fstdin = 1;
938 				arcname = NULL;
939 				break;
940 			}
941 			fstdin = 0;
942 			arcname = optarg;
943 			break;
944 		case 'h':
945 			/*
946 			 * follow symlinks
947 			 */
948 			Lflag = 1;
949 			break;
950 		case 'j':
951 			/*
952 			 * pass through bzip2. not a standard option
953 			 */
954 			gzip_program = BZIP2_CMD;
955 			break;
956 		case 'k':
957 			/*
958 			 * do not clobber files that exist
959 			 */
960 			kflag = 1;
961 			break;
962 		case 'l':
963 			/*
964 			 * do not pass over mount points in the file system
965 			 */
966 			Xflag = 1;
967 			break;
968 		case 'm':
969 			/*
970 			 * do not preserve modification time
971 			 */
972 			pmtime = 0;
973 			break;
974 		case 'o':
975 			/*
976 			 * This option does several things based on whether
977 			 * this is a create or extract operation.
978 			 */
979 			if (act == ARCHIVE) {
980 				/* GNU tar: write V7 format archives. */
981 				Oflag = 1;
982 				/* 4.2BSD: don't add directory entries. */
983 				if (opt_add("write_opt=nodir") < 0)
984 					tar_usage();
985 
986 			} else {
987 				/* SUS: don't preserve owner/group. */
988 				pids = 0;
989 				nopids = 1;
990 			}
991 			break;
992 		case 'p':
993 			/*
994 			 * preserve user id, group id, file
995 			 * mode, access/modification times
996 			 */
997 			if (!nopids)
998 				pids = 1;
999 			pmode = 1;
1000 			patime = 1;
1001 			pmtime = 1;
1002 			break;
1003 		case 'q':
1004 			/*
1005 			 * select first match for a pattern only
1006 			 */
1007 			nflag = 1;
1008 			break;
1009 		case 'r':
1010 		case 'u':
1011 			/*
1012 			 * append to the archive
1013 			 */
1014 			tar_set_action(APPND);
1015 			break;
1016 		case 's':
1017 			/*
1018 			 * file name substitution name pattern
1019 			 */
1020 			if (rep_add(optarg) < 0) {
1021 				tar_usage();
1022 				break;
1023 			}
1024 			break;
1025 		case 't':
1026 			/*
1027 			 * list contents of the tape
1028 			 */
1029 			tar_set_action(LIST);
1030 			break;
1031 		case 'v':
1032 			/*
1033 			 * verbose operation mode
1034 			 */
1035 			vflag = 1;
1036 			break;
1037 		case 'w':
1038 			/*
1039 			 * interactive file rename
1040 			 */
1041 			iflag = 1;
1042 			break;
1043 		case 'x':
1044 			/*
1045 			 * extract an archive, preserving mode,
1046 			 * and mtime if possible.
1047 			 */
1048 			tar_set_action(EXTRACT);
1049 			pmtime = 1;
1050 			break;
1051 		case 'z':
1052 			/*
1053 			 * use gzip.  Non standard option.
1054 			 */
1055 			gzip_program = GZIP_CMD;
1056 			break;
1057 		case 'B':
1058 			/*
1059 			 * Nothing to do here, this is pax default
1060 			 */
1061 			break;
1062 		case 'C':
1063 			havechd++;
1064 			chdname = optarg;
1065 			break;
1066 		case 'H':
1067 			/*
1068 			 * follow command line symlinks only
1069 			 */
1070 			Hflag = 1;
1071 			break;
1072 		case 'I':
1073 		case 'T':
1074 			if (++nincfiles > incfiles_max) {
1075 				incfiles_max = nincfiles + 3;
1076 				incfiles = realloc(incfiles,
1077 				    sizeof(*incfiles) * incfiles_max);
1078 				if (incfiles == NULL) {
1079 					tty_warn(0, "Unable to allocate space "
1080 					    "for option list");
1081 					exit(1);
1082 				}
1083 			}
1084 			incfiles[nincfiles - 1].file = optarg;
1085 			incfiles[nincfiles - 1].dir = chdname;
1086 			break;
1087 		case 'J':
1088 			gzip_program = XZ_CMD;
1089 			break;
1090 		case 'O':
1091 			Oflag = 1;
1092 			break;
1093 		case 'P':
1094 			/*
1095 			 * do not remove leading '/' from pathnames
1096 			 */
1097 			rmleadslash = 0;
1098 			Aflag = 1;
1099 			break;
1100 		case 'S':
1101 			/* do nothing; we already generate sparse files */
1102 			break;
1103 		case 'V':
1104 			/*
1105 			 * semi-verbose operation mode (no listing)
1106 			 */
1107 			Vflag = 1;
1108 			break;
1109 		case 'X':
1110 			/*
1111 			 * GNU tar compat: exclude the files listed in optarg
1112 			 */
1113 			if (tar_gnutar_X_compat(optarg) != 0)
1114 				tar_usage();
1115 			break;
1116 		case 'Z':
1117 			/*
1118 			 * use compress.
1119 			 */
1120 			gzip_program = COMPRESS_CMD;
1121 			break;
1122 		case '0':
1123 			arcname = DEV_0;
1124 			break;
1125 		case '1':
1126 			arcname = DEV_1;
1127 			break;
1128 		case '4':
1129 			arcname = DEV_4;
1130 			break;
1131 		case '5':
1132 			arcname = DEV_5;
1133 			break;
1134 		case '7':
1135 			arcname = DEV_7;
1136 			break;
1137 		case '8':
1138 			arcname = DEV_8;
1139 			break;
1140 		case OPT_ATIME_PRESERVE:
1141 			patime = 1;
1142 			break;
1143 		case OPT_UNLINK:
1144 			/* Just ignore -- we always unlink first. */
1145 			break;
1146 		case OPT_USE_COMPRESS_PROGRAM:
1147 			gzip_program = optarg;
1148 			break;
1149 		case OPT_FORCE_LOCAL:
1150 			forcelocal = 1;
1151 			break;
1152 		case OPT_INSECURE:
1153 			secure = 0;
1154 			break;
1155 		case OPT_STRICT:
1156 			/* disable gnu extensions */
1157 			is_gnutar = 0;
1158 			break;
1159 		case OPT_EXCLUDE:
1160 			if (tar_gnutar_minus_minus_exclude(optarg) != 0)
1161 				tar_usage();
1162 			break;
1163 		case OPT_NORECURSE:
1164 			dflag = 1;
1165 			break;
1166 #if !HAVE_NBTOOL_CONFIG_H
1167 		case OPT_CHROOT:
1168 			do_chroot = 1;
1169 			break;
1170 #endif
1171 #ifndef SMALL
1172 		case OPT_TIMESTAMP:
1173 			if (set_tstamp(optarg, &tst) == -1) {
1174 				tty_warn(1, "Invalid timestamp `%s'", optarg);
1175 				tar_usage();
1176 			}
1177 			break;
1178 #endif
1179 		default:
1180 			tar_usage();
1181 			break;
1182 		}
1183 	}
1184 	argc -= optind;
1185 	argv += optind;
1186 
1187 	/* Tar requires an action. */
1188 	if (act == ERROR)
1189 		tar_usage();
1190 
1191 	/* Traditional tar behaviour (pax uses stderr unless in list mode) */
1192 	if (fstdin == 1 && act == ARCHIVE)
1193 		listf = stderr;
1194 	else
1195 		listf = stdout;
1196 
1197 	/* Traditional tar behaviour (pax wants to read file list from stdin) */
1198 	if ((act == ARCHIVE || act == APPND) && argc == 0 && nincfiles == 0)
1199 		exit(0);
1200 	/*
1201 	 * if we are writing (ARCHIVE) specify tar, otherwise run like pax
1202 	 * (unless -o specified)
1203 	 */
1204 	if (act == ARCHIVE || act == APPND)
1205 		frmt = &(fsub[Oflag ? F_TAR : F_USTAR]);
1206 	else if (Oflag) {
1207 		if (act == EXTRACT)
1208 			to_stdout = 1;
1209 		else {
1210 			tty_warn(1, "The -O/-o options are only valid when "
1211 			    "writing or extracting an archive");
1212 			tar_usage();
1213 		}
1214 	}
1215 
1216 	/*
1217 	 * process the args as they are interpreted by the operation mode
1218 	 */
1219 	switch (act) {
1220 	case LIST:
1221 	case EXTRACT:
1222 	default:
1223 		{
1224 			int sawpat = 0;
1225 			int dirisnext = 0;
1226 			char *file, *dir = NULL;
1227 			int mustfreedir = 0;
1228 
1229 			while (nincfiles || *argv != NULL) {
1230 				/*
1231 				 * If we queued up any include files,
1232 				 * pull them in now.  Otherwise, check
1233 				 * for -I and -C positional flags.
1234 				 * Anything else must be a file to
1235 				 * extract.
1236 				 */
1237 				if (nincfiles) {
1238 					file = incfiles->file;
1239 					dir = incfiles->dir;
1240 					mustfreedir = 0;
1241 					incfiles++;
1242 					nincfiles--;
1243 				} else if (strcmp(*argv, "-I") == 0) {
1244 					if (*++argv == NULL)
1245 						break;
1246 					file = *argv++;
1247 					dir = chdname;
1248 					mustfreedir = 0;
1249 				} else {
1250 					file = NULL;
1251 					dir = NULL;
1252 					mustfreedir = 0;
1253 				}
1254 				if (file != NULL) {
1255 					FILE *fp;
1256 					char *str;
1257 
1258 					if (strcmp(file, "-") == 0)
1259 						fp = stdin;
1260 					else if ((fp = fopen(file, "r")) == NULL) {
1261 						tty_warn(1, "Unable to open file '%s' for read", file);
1262 						tar_usage();
1263 					}
1264 					while ((str = get_line(fp)) != NULL) {
1265 						if (dirisnext) {
1266 							if (dir && mustfreedir)
1267 								free(dir);
1268 							dir = str;
1269 							mustfreedir = 1;
1270 							dirisnext = 0;
1271 							continue;
1272 						}
1273 						if (strcmp(str, "-C") == 0) {
1274 							havechd++;
1275 							dirisnext = 1;
1276 							free(str);
1277 							continue;
1278 						}
1279 						if (strncmp(str, "-C ", 3) == 0) {
1280 							havechd++;
1281 							if (dir && mustfreedir)
1282 								free(dir);
1283 							dir = strdup(str + 3);
1284 							mustfreedir = 1;
1285 							free(str);
1286 							continue;
1287 						}
1288 						if (pat_add(str, dir, NOGLOB_MTCH) < 0)
1289 							tar_usage();
1290 						sawpat = 1;
1291 					}
1292 					/* Bomb if given -C w/out a dir. */
1293 					if (dirisnext)
1294 						tar_usage();
1295 					if (dir && mustfreedir)
1296 						free(dir);
1297 					if (strcmp(file, "-") != 0)
1298 						fclose(fp);
1299 					if (get_line_error) {
1300 						tty_warn(1, "Problem with file '%s'", file);
1301 						tar_usage();
1302 					}
1303 				} else if (strcmp(*argv, "-C") == 0) {
1304 					if (*++argv == NULL)
1305  						break;
1306 					chdname = *argv++;
1307 					havechd++;
1308 				} else if (pat_add(*argv++, chdname, 0) < 0)
1309 					tar_usage();
1310 				else
1311 					sawpat = 1;
1312 			}
1313 			/*
1314 			 * if patterns were added, we are doing	chdir()
1315 			 * on a file-by-file basis, else, just one
1316 			 * global chdir (if any) after opening input.
1317 			 */
1318 			if (sawpat > 0)
1319 				chdname = NULL;
1320 		}
1321 		break;
1322 	case ARCHIVE:
1323 	case APPND:
1324 		if (chdname != NULL) {	/* initial chdir() */
1325 			if (ftree_add(chdname, 1) < 0)
1326 				tar_usage();
1327 		}
1328 
1329 		while (nincfiles || *argv != NULL) {
1330 			char *file, *dir;
1331 
1332 			/*
1333 			 * If we queued up any include files, pull them in
1334 			 * now.  Otherwise, check for -I and -C positional
1335 			 * flags.  Anything else must be a file to include
1336 			 * in the archive.
1337 			 */
1338 			if (nincfiles) {
1339 				file = incfiles->file;
1340 				dir = incfiles->dir;
1341 				incfiles++;
1342 				nincfiles--;
1343 			} else if (strcmp(*argv, "-I") == 0) {
1344 				if (*++argv == NULL)
1345 					break;
1346 				file = *argv++;
1347 				dir = NULL;
1348 			} else {
1349 				file = NULL;
1350 				dir = NULL;
1351 			}
1352 			if (file != NULL) {
1353 				FILE *fp;
1354 				char *str;
1355 				int dirisnext = 0;
1356 
1357 				/* Set directory if needed */
1358 				if (dir) {
1359 					if (ftree_add(dir, 1) < 0)
1360 						tar_usage();
1361 				}
1362 
1363 				if (strcmp(file, "-") == 0)
1364 					fp = stdin;
1365 				else if ((fp = fopen(file, "r")) == NULL) {
1366 					tty_warn(1, "Unable to open file '%s' for read", file);
1367 					tar_usage();
1368 				}
1369 				while ((str = get_line(fp)) != NULL) {
1370 					if (dirisnext) {
1371 						if (ftree_add(str, 1) < 0)
1372 							tar_usage();
1373 						dirisnext = 0;
1374 						continue;
1375 					}
1376 					if (strcmp(str, "-C") == 0) {
1377 						dirisnext = 1;
1378 						continue;
1379 					}
1380 					if (strncmp(str, "-C ", 3) == 0) {
1381 						if (ftree_add(str + 3, 1) < 0)
1382 							tar_usage();
1383 						continue;
1384 					}
1385 					if (ftree_add(str, 0) < 0)
1386 						tar_usage();
1387 				}
1388 				/* Bomb if given -C w/out a dir. */
1389 				if (dirisnext)
1390 					tar_usage();
1391 				if (strcmp(file, "-") != 0)
1392 					fclose(fp);
1393 				if (get_line_error) {
1394 					tty_warn(1, "Problem with file '%s'",
1395 					    file);
1396 					tar_usage();
1397 				}
1398 			} else if (strcmp(*argv, "-C") == 0) {
1399 				if (*++argv == NULL)
1400 					break;
1401 				if (ftree_add(*argv++, 1) < 0)
1402 					tar_usage();
1403 			} else if (ftree_add(*argv++, 0) < 0)
1404 				tar_usage();
1405 		}
1406 		/*
1407 		 * no read errors allowed on updates/append operation!
1408 		 */
1409 		maxflt = 0;
1410 		break;
1411 	}
1412 	if (!fstdin && ((arcname == NULL) || (*arcname == '\0'))) {
1413 		arcname = getenv("TAPE");
1414 		if ((arcname == NULL) || (*arcname == '\0'))
1415 			arcname = _PATH_DEFTAPE;
1416 	}
1417 }
1418 
1419 int
1420 mkpath(char *path)
1421 {
1422 	char *slash;
1423 	int done = 0;
1424 
1425 	slash = path;
1426 
1427 	while (!done) {
1428 		slash += strspn(slash, "/");
1429 		slash += strcspn(slash, "/");
1430 
1431 		done = (*slash == '\0');
1432 		*slash = '\0';
1433 
1434 		if (domkdir(path, 0777) == -1)
1435 			goto out;
1436 
1437 		if (!done)
1438 			*slash = '/';
1439 	}
1440 
1441 	return 0;
1442 out:
1443 	/* Can't create or or not a directory */
1444 	syswarn(1, errno, "Cannot create directory `%s'", path);
1445 	return -1;
1446 }
1447 
1448 
1449 #ifndef NO_CPIO
1450 struct option cpio_longopts[] = {
1451 	{ "reset-access-time",	no_argument,		0,	'a' },
1452 	{ "make-directories",	no_argument,		0, 	'd' },
1453 	{ "nonmatching",	no_argument,		0,	'f' },
1454 	{ "extract",		no_argument,		0,	'i' },
1455 	{ "link",		no_argument,		0,	'l' },
1456 	{ "preserve-modification-time", no_argument,	0,	'm' },
1457 	{ "create",		no_argument,		0,	'o' },
1458 	{ "pass-through",	no_argument,		0,	'p' },
1459 	{ "rename",		no_argument,		0,	'r' },
1460 	{ "list",		no_argument,		0,	't' },
1461 	{ "unconditional",	no_argument,		0,	'u' },
1462 	{ "verbose",		no_argument,		0,	'v' },
1463 	{ "append",		no_argument,		0,	'A' },
1464 	{ "pattern-file",	required_argument,	0,	'E' },
1465 	{ "file",		required_argument,	0,	'F' },
1466 	{ "force-local",	no_argument,		0,
1467 						OPT_FORCE_LOCAL },
1468 	{ "format",		required_argument,	0,	'H' },
1469 	{ "dereference",	no_argument,		0,	'L' },
1470 	{ "swap-halfwords",	no_argument,		0,	'S' },
1471 	{ "summary",		no_argument,		0,	'V' },
1472 	{ "stats",		no_argument,		0,	'V' },
1473 	{ "insecure",		no_argument,		0,
1474 						OPT_INSECURE },
1475 	{ "sparse",		no_argument,		0,
1476 						OPT_SPARSE },
1477 	{ "xz",			no_argument,		0,
1478 						OPT_XZ },
1479 
1480 #ifdef notyet
1481 /* Not implemented */
1482 	{ "null",		no_argument,		0,	'0' },
1483 	{ "swap",		no_argument,		0,	'b' },
1484 	{ "numeric-uid-gid",	no_argument,		0,	'n' },
1485 	{ "swap-bytes",		no_argument,		0,	's' },
1486 	{ "message",		required_argument,	0,	'M' },
1487 	{ "owner",		required_argument,	0	'R' },
1488 	{ "dot",		no_argument,		0,	'V' }, /* xxx */
1489 	{ "block-size",		required_argument,	0,
1490 						OPT_BLOCK_SIZE },
1491 	{ "no-absolute-pathnames", no_argument,		0,
1492 						OPT_NO_ABSOLUTE_PATHNAMES },
1493 	{ "no-preserve-owner",	no_argument,		0,
1494 						OPT_NO_PRESERVE_OWNER },
1495 	{ "only-verify-crc",	no_argument,		0,
1496 						OPT_ONLY_VERIFY_CRC },
1497 	{ "rsh-command",	required_argument,	0,
1498 						OPT_RSH_COMMAND },
1499 	{ "version",		no_argument,		0,
1500 						OPT_VERSION },
1501 #endif
1502 	{ 0,			0,			0,	0 },
1503 };
1504 
1505 static void
1506 cpio_set_action(int op)
1507 {
1508 	if ((act == APPND && op == ARCHIVE) || (act == ARCHIVE && op == APPND))
1509 		act = APPND;
1510 	else if (act == EXTRACT && op == LIST)
1511 		act = op;
1512 	else if (act != ERROR && act != op)
1513 		cpio_usage();
1514 	else
1515 		act = op;
1516 }
1517 
1518 /*
1519  * cpio_options()
1520  *	look at the user specified flags. set globals as required and check if
1521  *	the user specified a legal set of flags. If not, complain and exit
1522  */
1523 
1524 static void
1525 cpio_options(int argc, char **argv)
1526 {
1527 	FSUB tmp;
1528 	u_int64_t flg = 0;
1529 	u_int64_t bflg = 0;
1530 	int c;
1531 	size_t i;
1532 	FILE *fp;
1533 	char *str;
1534 
1535 	uflag = 1;
1536 	kflag = 1;
1537 	pids = 1;
1538 	pmode = 1;
1539 	pmtime = 0;
1540 	arcname = NULL;
1541 	dflag = 1;
1542 	nodirs = 1;
1543 	/*
1544 	 * process option flags
1545 	 */
1546 	while ((c = getoldopt(argc, argv,
1547 	    "+abcdfiklmoprstuvzABC:E:F:H:I:LM:O:R:SVZ6",
1548 	    cpio_longopts, NULL)) != -1) {
1549 		switch(c) {
1550 		case 'a':
1551 			/*
1552 			 * preserve access time on filesystem nodes we read
1553 			 */
1554 			tflag = 1;
1555 			flg |= TF;
1556 			break;
1557 #ifdef notyet
1558 		case 'b':
1559 			/*
1560 			 * swap bytes and half-words when reading data
1561 			 */
1562 			break;
1563 #endif
1564 		case 'c':
1565 			/*
1566 			 * ASCII cpio header
1567 			 */
1568 			frmt = &fsub[F_SV4CPIO];
1569 			break;
1570 		case 'd':
1571 			/*
1572 			 * create directories as needed
1573 			 * pax does this by default ..
1574 			 */
1575 			nodirs = 0;
1576 			break;
1577 		case 'f':
1578 			/*
1579 			 * inverse match on patterns
1580 			 */
1581 			cflag = 1;
1582 			flg |= CF;
1583 			break;
1584 		case 'i':
1585 			/*
1586 			 * read the archive
1587 			 */
1588 			cpio_set_action(EXTRACT);
1589 			flg |= RF;
1590 			break;
1591 #ifdef notyet
1592 		case 'k':
1593 			break;
1594 #endif
1595 		case 'l':
1596 			/*
1597 			 * try to link src to dest with copy (-rw)
1598 			 */
1599 			lflag = 1;
1600 			flg |= LF;
1601 			break;
1602 		case 'm':
1603 			/*
1604 			 * preserve mtime
1605 			 */
1606 			flg |= PF;
1607 			pmtime = 1;
1608 			break;
1609 		case 'o':
1610 			/*
1611 			 * write an archive
1612 			 */
1613 			cpio_set_action(ARCHIVE);
1614 			frmt = &(fsub[F_SV4CRC]);
1615 			flg |= WF;
1616 			break;
1617 		case 'p':
1618 			/*
1619 			 * cpio -p is like pax -rw
1620 			 */
1621 			cpio_set_action(COPY);
1622 			flg |= RF | WF;
1623 			break;
1624 		case 'r':
1625 			/*
1626 			 * interactive file rename
1627 			 */
1628 			iflag = 1;
1629 			flg |= IF;
1630 			break;
1631 #ifdef notyet
1632 		case 's':
1633 			/*
1634 			 * swap bytes after reading data
1635 			 */
1636 			break;
1637 #endif
1638 		case 't':
1639 			/*
1640 			 * list contents of archive
1641 			 */
1642 			cpio_set_action(LIST);
1643 			listf = stdout;
1644 			flg &= ~RF;
1645 			break;
1646 		case 'u':
1647 			/*
1648 			 * don't ignore those older files
1649 			 */
1650 			uflag = 0;
1651 			kflag = 0;
1652 			flg |= UF;
1653 			break;
1654 		case 'v':
1655 			/*
1656 			 * verbose operation mode
1657 			 */
1658 			vflag = 1;
1659 			flg |= VF;
1660 			break;
1661 		case 'z':
1662 			/*
1663 			 * use gzip.  Non standard option.
1664 			 */
1665 			gzip_program = GZIP_CMD;
1666 			break;
1667 		case 'A':
1668 			/*
1669 			 * append to an archive
1670 			 */
1671 			cpio_set_action(APPND);
1672 			flg |= AF;
1673 			break;
1674 		case 'B':
1675 			/*
1676 			 * set blocksize to 5120
1677 			 */
1678 			blksz = 5120;
1679 			break;
1680 		case 'C':
1681 			/*
1682 			 * specify blocksize
1683 			 */
1684 			if ((blksz = (int)str_offt(optarg)) <= 0) {
1685 				tty_warn(1, "Invalid block size %s", optarg);
1686 				cpio_usage();
1687 			}
1688 			break;
1689 		case 'E':
1690 			/*
1691 			 * file with patterns to extract or list
1692 			 */
1693 			if ((fp = fopen(optarg, "r")) == NULL) {
1694 				tty_warn(1, "Unable to open file '%s' for read",
1695 				    optarg);
1696 				cpio_usage();
1697 			}
1698 			while ((str = get_line(fp)) != NULL) {
1699 				pat_add(str, NULL, 0);
1700 			}
1701 			fclose(fp);
1702 			if (get_line_error) {
1703 				tty_warn(1, "Problem with file '%s'", optarg);
1704 				cpio_usage();
1705 			}
1706 			break;
1707 		case 'H':
1708 			/*
1709 			 * specify an archive format on write
1710 			 */
1711 			tmp.name = optarg;
1712 			frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
1713 			    sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt);
1714 			if (frmt != NULL) {
1715 				flg |= XF;
1716 				break;
1717 			}
1718 			tty_warn(1, "Unknown -H format: %s", optarg);
1719 			(void)fputs("cpio: Known -H formats are:", stderr);
1720 			for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
1721 				(void)fprintf(stderr, " %s", fsub[i].name);
1722 			(void)fputs("\n\n", stderr);
1723 			cpio_usage();
1724 			break;
1725 		case 'F':
1726 		case 'I':
1727 		case 'O':
1728 			/*
1729 			 * filename where the archive is stored
1730 			 */
1731 			if ((optarg[0] == '-') && (optarg[1]== '\0')) {
1732 				/*
1733 				 * treat a - as stdin
1734 				 */
1735 				arcname = NULL;
1736 				break;
1737 			}
1738 			arcname = optarg;
1739 			break;
1740 		case 'L':
1741 			/*
1742 			 * follow symlinks
1743 			 */
1744 			Lflag = 1;
1745 			flg |= CLF;
1746 			break;
1747 #ifdef notyet
1748 		case 'M':
1749 			arg = optarg;
1750 			break;
1751 		case 'R':
1752 			arg = optarg;
1753 			break;
1754 #endif
1755 		case 'S':
1756 			/*
1757 			 * swap halfwords after reading data
1758 			 */
1759 			cpio_swp_head = 1;
1760 			break;
1761 #ifdef notyet
1762 		case 'V':		/* print a '.' for each file processed */
1763 			break;
1764 #endif
1765 		case 'V':
1766 			/*
1767 			 * semi-verbose operation mode (no listing)
1768 			 */
1769 			Vflag = 1;
1770 			flg |= VF;
1771 			break;
1772 		case 'Z':
1773 			/*
1774 			 * use compress.  Non standard option.
1775 			 */
1776 			gzip_program = COMPRESS_CMD;
1777 			break;
1778 		case '6':
1779 			/*
1780 			 * process Version 6 cpio format
1781 			 */
1782 			frmt = &(fsub[F_BCPIO]);
1783 			break;
1784 		case OPT_FORCE_LOCAL:
1785 			forcelocal = 1;
1786 			break;
1787 		case OPT_INSECURE:
1788 			secure = 0;
1789 			break;
1790 		case OPT_SPARSE:
1791 			/* do nothing; we already generate sparse files */
1792 			break;
1793 		case OPT_XZ:
1794 			gzip_program = XZ_CMD;
1795 			break;
1796 		default:
1797 			cpio_usage();
1798 			break;
1799 		}
1800 	}
1801 
1802 	/*
1803 	 * figure out the operation mode of cpio. check that we have not been
1804 	 * given a bogus set of flags for the operation mode.
1805 	 */
1806 	if (ISLIST(flg)) {
1807 		act = LIST;
1808 		bflg = flg & BDLIST;
1809 	} else if (ISEXTRACT(flg)) {
1810 		act = EXTRACT;
1811 		bflg = flg & BDEXTR;
1812 	} else if (ISARCHIVE(flg)) {
1813 		act = ARCHIVE;
1814 		bflg = flg & BDARCH;
1815 	} else if (ISAPPND(flg)) {
1816 		act = APPND;
1817 		bflg = flg & BDARCH;
1818 	} else if (ISCOPY(flg)) {
1819 		act = COPY;
1820 		bflg = flg & BDCOPY;
1821 	} else
1822 		cpio_usage();
1823 	if (bflg) {
1824 		cpio_usage();
1825 	}
1826 
1827 	/*
1828 	 * if we are writing (ARCHIVE) we use the default format if the user
1829 	 * did not specify a format. when we write during an APPEND, we will
1830 	 * adopt the format of the existing archive if none was supplied.
1831 	 */
1832 	if (!(flg & XF) && (act == ARCHIVE))
1833 		frmt = &(fsub[F_BCPIO]);
1834 
1835 	/*
1836 	 * process the args as they are interpreted by the operation mode
1837 	 */
1838 	switch (act) {
1839 	case LIST:
1840 	case EXTRACT:
1841 		for (; optind < argc; optind++)
1842 			if (pat_add(argv[optind], NULL, 0) < 0)
1843 				cpio_usage();
1844 		break;
1845 	case COPY:
1846 		if (optind >= argc) {
1847 			tty_warn(0, "Destination directory was not supplied");
1848 			cpio_usage();
1849 		}
1850 		--argc;
1851 		dirptr = argv[argc];
1852 		/* FALLTHROUGH */
1853 	case ARCHIVE:
1854 	case APPND:
1855 		if (argc != optind) {
1856 			for (; optind < argc; optind++)
1857 				if (ftree_add(argv[optind], 0) < 0)
1858 					cpio_usage();
1859 			break;
1860 		}
1861 		/*
1862 		 * no read errors allowed on updates/append operation!
1863 		 */
1864 		maxflt = 0;
1865 		while ((str = get_line(stdin)) != NULL) {
1866 			ftree_add(str, 0);
1867 		}
1868 		if (get_line_error) {
1869 			tty_warn(1, "Problem while reading stdin");
1870 			cpio_usage();
1871 		}
1872 		break;
1873 	default:
1874 		cpio_usage();
1875 		break;
1876 	}
1877 }
1878 #endif
1879 
1880 /*
1881  * printflg()
1882  *	print out those invalid flag sets found to the user
1883  */
1884 
1885 static void
1886 printflg(unsigned int flg)
1887 {
1888 	int nxt;
1889 
1890 	(void)fprintf(stderr,"%s: Invalid combination of options:", argv0);
1891 	while ((nxt = ffs(flg)) != 0) {
1892 		flg &= ~(1 << (nxt - 1));
1893 		(void)fprintf(stderr, " -%c", flgch[nxt - 1]);
1894 	}
1895 	(void)putc('\n', stderr);
1896 }
1897 
1898 /*
1899  * c_frmt()
1900  *	comparison routine used by bsearch to find the format specified
1901  *	by the user
1902  */
1903 
1904 static int
1905 c_frmt(const void *a, const void *b)
1906 {
1907 	return strcmp(((const FSUB *)a)->name, ((const FSUB *)b)->name);
1908 }
1909 
1910 /*
1911  * opt_next()
1912  *	called by format specific options routines to get each format specific
1913  *	flag and value specified with -o
1914  * Return:
1915  *	pointer to next OPLIST entry or NULL (end of list).
1916  */
1917 
1918 OPLIST *
1919 opt_next(void)
1920 {
1921 	OPLIST *opt;
1922 
1923 	if ((opt = ophead) != NULL)
1924 		ophead = ophead->fow;
1925 	return opt;
1926 }
1927 
1928 /*
1929  * bad_opt()
1930  *	generic routine used to complain about a format specific options
1931  *	when the format does not support options.
1932  */
1933 
1934 int
1935 bad_opt(void)
1936 {
1937 	OPLIST *opt;
1938 
1939 	if (ophead == NULL)
1940 		return 0;
1941 	/*
1942 	 * print all we were given
1943 	 */
1944 	tty_warn(1," These format options are not supported for %s",
1945 	    frmt->name);
1946 	while ((opt = opt_next()) != NULL)
1947 		(void)fprintf(stderr, "\t%s = %s\n", opt->name, opt->value);
1948 	if (strcmp(NM_TAR, argv0) == 0)
1949 		tar_usage();
1950 #ifndef NO_CPIO
1951 	else if (strcmp(NM_CPIO, argv0) == 0)
1952 		cpio_usage();
1953 #endif
1954 	else
1955 		pax_usage();
1956 	return 0;
1957 }
1958 
1959 /*
1960  * opt_add()
1961  *	breaks the value supplied to -o into a option name and value. options
1962  *	are given to -o in the form -o name-value,name=value
1963  *	multiple -o may be specified.
1964  * Return:
1965  *	0 if format in name=value format, -1 if -o is passed junk
1966  */
1967 
1968 int
1969 opt_add(const char *str)
1970 {
1971 	OPLIST *opt;
1972 	char *frpt;
1973 	char *pt;
1974 	char *endpt;
1975 	char *dstr;
1976 
1977 	if ((str == NULL) || (*str == '\0')) {
1978 		tty_warn(0, "Invalid option name");
1979 		return -1;
1980 	}
1981 	if ((dstr = strdup(str)) == NULL) {
1982 		tty_warn(0, "Unable to allocate space for option list");
1983 		return -1;
1984 	}
1985 	frpt = endpt = dstr;
1986 
1987 	/*
1988 	 * break into name and values pieces and stuff each one into a
1989 	 * OPLIST structure. When we know the format, the format specific
1990 	 * option function will go through this list
1991 	 */
1992 	while ((frpt != NULL) && (*frpt != '\0')) {
1993 		if ((endpt = strchr(frpt, ',')) != NULL)
1994 			*endpt = '\0';
1995 		if ((pt = strchr(frpt, '=')) == NULL) {
1996 			tty_warn(0, "Invalid options format");
1997 			free(dstr);
1998 			return -1;
1999 		}
2000 		if ((opt = (OPLIST *)malloc(sizeof(OPLIST))) == NULL) {
2001 			tty_warn(0, "Unable to allocate space for option list");
2002 			free(dstr);
2003 			return -1;
2004 		}
2005 		*pt++ = '\0';
2006 		opt->name = frpt;
2007 		opt->value = pt;
2008 		opt->fow = NULL;
2009 		if (endpt != NULL)
2010 			frpt = endpt + 1;
2011 		else
2012 			frpt = NULL;
2013 		if (ophead == NULL) {
2014 			optail = ophead = opt;
2015 			continue;
2016 		}
2017 		optail->fow = opt;
2018 		optail = opt;
2019 	}
2020 	return 0;
2021 }
2022 
2023 /*
2024  * str_offt()
2025  *	Convert an expression of the following forms to an off_t > 0.
2026  *	1) A positive decimal number.
2027  *	2) A positive decimal number followed by a b (mult by 512).
2028  *	3) A positive decimal number followed by a k (mult by 1024).
2029  *	4) A positive decimal number followed by a m (mult by 512).
2030  *	5) A positive decimal number followed by a w (mult by sizeof int)
2031  *	6) Two or more positive decimal numbers (with/without k,b or w).
2032  *	   separated by x (also * for backwards compatibility), specifying
2033  *	   the product of the indicated values.
2034  * Return:
2035  *	0 for an error, a positive value o.w.
2036  */
2037 
2038 static off_t
2039 str_offt(char *val)
2040 {
2041 	char *expr;
2042 	off_t num, t;
2043 
2044 	num = STRTOOFFT(val, &expr, 0);
2045 	if ((num == OFFT_MAX) || (num <= 0) || (expr == val))
2046 		return 0;
2047 
2048 	switch(*expr) {
2049 	case 'b':
2050 		t = num;
2051 		num *= 512;
2052 		if (t > num)
2053 			return 0;
2054 		++expr;
2055 		break;
2056 	case 'k':
2057 		t = num;
2058 		num *= 1024;
2059 		if (t > num)
2060 			return 0;
2061 		++expr;
2062 		break;
2063 	case 'm':
2064 		t = num;
2065 		num *= 1048576;
2066 		if (t > num)
2067 			return 0;
2068 		++expr;
2069 		break;
2070 	case 'w':
2071 		t = num;
2072 		num *= sizeof(int);
2073 		if (t > num)
2074 			return 0;
2075 		++expr;
2076 		break;
2077 	}
2078 
2079 	switch(*expr) {
2080 		case '\0':
2081 			break;
2082 		case '*':
2083 		case 'x':
2084 			t = num;
2085 			num *= str_offt(expr + 1);
2086 			if (t > num)
2087 				return 0;
2088 			break;
2089 		default:
2090 			return 0;
2091 	}
2092 	return num;
2093 }
2094 
2095 static char *
2096 get_line(FILE *f)
2097 {
2098 	char *name, *temp;
2099 	size_t len;
2100 
2101 	name = fgetln(f, &len);
2102 	if (!name) {
2103 		get_line_error = ferror(f) ? GETLINE_FILE_CORRUPT : 0;
2104 		return 0;
2105 	}
2106 	if (name[len-1] != '\n')
2107 		len++;
2108 	temp = malloc(len);
2109 	if (!temp) {
2110 		get_line_error = GETLINE_OUT_OF_MEM;
2111 		return 0;
2112 	}
2113 	memcpy(temp, name, len-1);
2114 	temp[len-1] = 0;
2115 	return temp;
2116 }
2117 
2118 #ifndef SMALL
2119 /*
2120  * set_tstamp()
2121  *	Use a specific timestamp for all individual files created in the
2122  *	archive
2123  */
2124 static int
2125 set_tstamp(const char *b, struct stat *st)
2126 {
2127 	time_t when;
2128 	char *eb;
2129 	long long l;
2130 
2131 	if (stat(b, st) != -1)
2132 		return 0;
2133 
2134 #ifndef HAVE_NBTOOL_CONFIG_H
2135 	errno = 0;
2136 	if ((when = parsedate(b, NULL, NULL)) == -1 && errno != 0)
2137 #endif
2138 	{
2139 		errno = 0;
2140 		l = strtoll(b, &eb, 0);
2141 		if (b == eb || *eb || errno)
2142 			return -1;
2143 		when = (time_t)l;
2144 	}
2145 
2146 	st->st_ino = 1;
2147 #if HAVE_STRUCT_STAT_BIRTHTIME
2148 	st->st_birthtime =
2149 #endif
2150 	st->st_mtime = st->st_ctime = st->st_atime = when;
2151 	return 0;
2152 }
2153 #endif
2154 
2155 /*
2156  * no_op()
2157  *	for those option functions where the archive format has nothing to do.
2158  * Return:
2159  *	0
2160  */
2161 
2162 static int
2163 no_op(void)
2164 {
2165 	return 0;
2166 }
2167 
2168 /*
2169  * pax_usage()
2170  *	print the usage summary to the user
2171  */
2172 
2173 static void
2174 pax_usage(void)
2175 {
2176 	fprintf(stderr,
2177 "usage: pax [-0cdjnvzVO] [-E limit] [-f archive] [-N dbdir] [-s replstr] ...\n"
2178 "           [-U user] ... [-G group] ... [-T [from_date][,to_date]] ...\n"
2179 "           [pattern ...]\n");
2180 	fprintf(stderr,
2181 "       pax -r [-cdijknuvzADOVYZ] [-E limit] [-f archive] [-N dbdir]\n"
2182 "           [-o options] ... [-p string] ... [-s replstr] ... [-U user] ...\n"
2183 "           [-G group] ... [-T [from_date][,to_date]] ... [pattern ...]\n");
2184 	fprintf(stderr,
2185 "       pax -w [-dijtuvzAHLMOPVX] [-b blocksize] [[-a] [-f archive]] [-x format]\n"
2186 "           [-B bytes] [-N dbdir] [-o options] ... [-s replstr] ...\n"
2187 "           [-U user] ... [-G group] ...\n"
2188 "           [-T [from_date][,to_date][/[c][m]]] ... [file ...]\n");
2189 	fprintf(stderr,
2190 "       pax -r -w [-dijklntuvzADHLMOPVXYZ] [-N dbdir] [-p string] ...\n"
2191 "           [-s replstr] ... [-U user] ... [-G group] ...\n"
2192 "           [-T [from_date][,to_date][/[c][m]]] ... [file ...] directory\n");
2193 	exit(1);
2194 	/* NOTREACHED */
2195 }
2196 
2197 /*
2198  * tar_usage()
2199  *	print the usage summary to the user
2200  */
2201 
2202 static void
2203 tar_usage(void)
2204 {
2205 	(void)fputs("usage: tar [-]{crtux}[-befhjklmopqvwzHJOPSXZ014578] "
2206 		    "[archive] [blocksize]\n"
2207 		    "           [-C directory] [-T file] [-s replstr] "
2208 		    "[file ...]\n", stderr);
2209 	exit(1);
2210 	/* NOTREACHED */
2211 }
2212 
2213 #ifndef NO_CPIO
2214 /*
2215  * cpio_usage()
2216  *	print the usage summary to the user
2217  */
2218 
2219 static void
2220 cpio_usage(void)
2221 {
2222 
2223 	(void)fputs("usage: cpio -o [-aABcLvzZ] [-C bytes] [-F archive] "
2224 		    "[-H format] [-O archive]\n"
2225 		    "               < name-list [> archive]\n"
2226 		    "       cpio -i [-bBcdfmrsStuvzZ6] [-C bytes] [-E file] "
2227 		    "[-F archive] [-H format] \n"
2228 		    "               [-I archive] "
2229 		    "[pattern ...] [< archive]\n"
2230 		    "       cpio -p [-adlLmuv] destination-directory "
2231 		    "< name-list\n", stderr);
2232 	exit(1);
2233 	/* NOTREACHED */
2234 }
2235 #endif
2236