1 /* $OpenBSD: options.c,v 1.70 2008/06/11 00:49:08 pvalchev Exp $ */
2 /* $NetBSD: options.c,v 1.6 1996/03/26 23:54:18 mrg Exp $ */
5 * Copyright (c) 1992 Keith Muller.
6 * Copyright (c) 1992, 1993
7 * The Regents of the University of California. All rights reserved.
9 * This code is derived from software contributed to Berkeley by
10 * Keith Muller of the University of California, San Diego.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 static const char sccsid[] = "@(#)options.c 8.2 (Berkeley) 4/18/94";
41 static const char rcsid[] = "$OpenBSD: options.c,v 1.70 2008/06/11 00:49:08 pvalchev Exp $";
45 #include <sys/types.h>
49 #include <sys/param.h>
63 #include "fgetln.h" /* added, David */
66 * Routines which handle command line options
69 static char flgch[] = FLGCH; /* list of all possible flags */
70 static OPLIST *ophead = NULL; /* head for format specific options -x */
71 static OPLIST *optail = NULL; /* option tail */
73 static int no_op(void);
74 static void printflg(unsigned int);
75 static int c_frmt(const void *, const void *);
76 static off_t str_offt(char *);
77 static char *bsd_getline(FILE *fp);
78 static void pax_options(int, char **);
79 static void pax_usage(void);
80 static void tar_options(int, char **);
81 static void tar_usage(void);
82 static void cpio_options(int, char **);
83 static void cpio_usage(void);
85 /* errors from getline */
86 #define GETLINE_FILE_CORRUPT 1
87 #define GETLINE_OUT_OF_MEM 2
88 static int getline_error;
91 #define GZIP_CMD "gzip" /* command to run as gzip */
92 #define COMPRESS_CMD "compress" /* command to run as compress */
93 #define BZIP2_CMD "bzip2" /* command to run as bzip2 */
96 * Format specific routine table - MUST BE IN SORTED ORDER BY NAME
97 * (see pax.h for description of each function)
99 * name, blksz, hdsz, udev, hlk, blkagn, inhead, id, st_read,
100 * read, end_read, st_write, write, end_write, trail,
101 * rd_data, wr_data, options
105 /* 0: OLD BINARY CPIO */
106 {"bcpio", 5120, sizeof(HD_BCPIO), 1, 0, 0, 1, bcpio_id, cpio_strd,
107 bcpio_rd, bcpio_endrd, cpio_stwr, bcpio_wr, cpio_endwr, cpio_trail,
108 rd_wrfile, wr_rdfile, bad_opt},
110 /* 1: OLD OCTAL CHARACTER CPIO */
111 {"cpio", 5120, sizeof(HD_CPIO), 1, 0, 0, 1, cpio_id, cpio_strd,
112 cpio_rd, cpio_endrd, cpio_stwr, cpio_wr, cpio_endwr, cpio_trail,
113 rd_wrfile, wr_rdfile, bad_opt},
115 /* 2: SVR4 HEX CPIO */
116 {"sv4cpio", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, vcpio_id, cpio_strd,
117 vcpio_rd, vcpio_endrd, cpio_stwr, vcpio_wr, cpio_endwr, cpio_trail,
118 rd_wrfile, wr_rdfile, bad_opt},
120 /* 3: SVR4 HEX CPIO WITH CRC */
121 {"sv4crc", 5120, sizeof(HD_VCPIO), 1, 0, 0, 1, crc_id, crc_strd,
122 vcpio_rd, vcpio_endrd, crc_stwr, vcpio_wr, cpio_endwr, cpio_trail,
123 rd_wrfile, wr_rdfile, bad_opt},
126 {"tar", 10240, BLKMULT, 0, 1, BLKMULT, 0, tar_id, no_op,
127 tar_rd, tar_endrd, no_op, tar_wr, tar_endwr, tar_trail,
128 rd_wrfile, wr_rdfile, tar_opt},
131 {"ustar", 10240, BLKMULT, 0, 1, BLKMULT, 0, ustar_id, ustar_strd,
132 ustar_rd, tar_endrd, ustar_stwr, ustar_wr, tar_endwr, tar_trail,
133 rd_wrfile, wr_rdfile, bad_opt},
135 #define F_OCPIO 0 /* format when called as cpio -6 */
136 #define F_ACPIO 1 /* format when called as cpio -c */
137 #define F_CPIO 3 /* format when called as cpio */
138 #define F_OTAR 4 /* format when called as tar -o */
139 #define F_TAR 5 /* format when called as tar */
140 #define DEFLT 5 /* default write format from list above */
143 * ford is the archive search order used by get_arc() to determine what kind
144 * of archive we are dealing with. This helps to properly id archive formats
145 * some formats may be subsets of others....
147 int ford[] = {5, 4, 3, 2, 1, 0, -1 };
150 * Do we have -C anywhere?
156 * figure out if we are pax, tar or cpio. Call the appropriate options
161 options(int argc, char **argv)
165 * Are we acting like pax, tar or cpio (based on argv[0])
167 if ((argv0 = strrchr(argv[0], '/')) != NULL)
172 if (strcmp(NM_TAR, argv0) == 0) {
173 tar_options(argc, argv);
175 } else if (strcmp(NM_CPIO, argv0) == 0) {
176 cpio_options(argc, argv);
180 * assume pax as the default
183 pax_options(argc, argv);
188 * look at the user specified flags. set globals as required and check if
189 * the user specified a legal set of flags. If not, complain and exit
193 pax_options(int argc, char **argv)
197 unsigned int flg = 0;
198 unsigned int bflg = 0;
203 * process option flags
205 while ((c=getopt(argc,argv,"ab:cdf:ijklno:p:rs:tuvwx:zB:DE:G:HLOPT:U:XYZ0"))
219 if ((wrblksz = (int)str_offt(optarg)) <= 0) {
220 paxwarn(1, "Invalid block size %s", optarg);
226 * inverse match on patterns
233 * match only dir on extract, not the subtree at dir
240 * filename where the archive is stored
247 * interactive file rename
254 * use bzip2. Non standard option.
256 gzip_program = BZIP2_CMD;
260 * do not clobber files that exist
267 * try to link src to dest with copy (-rw)
274 * select first match for a pattern only
281 * pass format specific options
284 if (opt_add(optarg) < 0)
289 * specify file characteristic options
291 for (pt = optarg; *pt != '\0'; ++pt) {
295 * do not preserve access time
301 * preserve user id, group id, file
302 * mode, access/modification times
311 * do not preserve modification time
323 * preserve file mode bits
328 paxwarn(1, "Invalid -p string: %c", *pt);
343 * file name substitution name pattern
345 if (rep_add(optarg) < 0) {
353 * preserve access time on filesystem nodes we read
360 * ignore those older files
367 * verbose operation mode
380 * specify an archive format on write
383 if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
384 sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL) {
388 paxwarn(1, "Unknown -x format: %s", optarg);
389 (void)fputs("pax: Known -x formats are:", stderr);
390 for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
391 (void)fprintf(stderr, " %s", fsub[i].name);
392 (void)fputs("\n\n", stderr);
397 * use gzip. Non standard option.
399 gzip_program = GZIP_CMD;
403 * non-standard option on number of bytes written on a
404 * single archive volume.
406 if ((wrlimit = str_offt(optarg)) <= 0) {
407 paxwarn(1, "Invalid write limit %s", optarg);
410 if (wrlimit % BLKMULT) {
411 paxwarn(1, "Write limit is not a %d byte multiple",
419 * On extraction check file inode change time before the
420 * modification of the file name. Non standard option.
427 * non-standard limit on read faults
428 * 0 indicates stop after first error, values
429 * indicate a limit, "NONE" try forever
432 if (strcmp(NONE, optarg) == 0)
434 else if ((maxflt = atoi(optarg)) < 0) {
435 paxwarn(1, "Error count value must be positive");
441 * non-standard option for selecting files within an
442 * archive by group (gid or name)
444 if (grp_add(optarg) < 0) {
452 * follow command line symlinks only
466 * Force one volume. Non standard option.
468 force_one_volume = 1;
472 * do NOT follow symlinks (default)
479 * non-standard option for selecting files within an
480 * archive by modification time range (lower,upper)
482 if (trng_add(optarg) < 0) {
490 * non-standard option for selecting files within an
491 * archive by user (uid or name)
493 if (usr_add(optarg) < 0) {
501 * do not pass over mount points in the file system
508 * On extraction check file inode change time after the
509 * modification of the file name. Non standard option.
516 * On extraction check modification time after the
517 * modification of the file name. Non standard option.
524 * Use \0 as pathname terminator.
525 * (For use with the -print0 option of find(1).)
537 * figure out the operation mode of pax read,write,extract,copy,append
538 * or list. check that we have not been given a bogus set of flags
539 * for the operation mode.
545 } else if (ISEXTRACT(flg)) {
548 } else if (ISARCHIVE(flg)) {
551 } else if (ISAPPND(flg)) {
554 } else if (ISCOPY(flg)) {
565 * if we are writing (ARCHIVE) we use the default format if the user
566 * did not specify a format. when we write during an APPEND, we will
567 * adopt the format of the existing archive if none was supplied.
569 if (!(flg & XF) && (act == ARCHIVE))
570 frmt = &(fsub[DEFLT]);
573 * process the args as they are interpreted by the operation mode
578 for (; optind < argc; optind++)
579 if (pat_add(argv[optind], NULL) < 0)
583 if (optind >= argc) {
584 paxwarn(0, "Destination directory was not supplied");
592 for (; optind < argc; optind++)
593 if (ftree_add(argv[optind], 0) < 0)
596 * no read errors allowed on updates/append operation!
606 * look at the user specified flags. set globals as required and check if
607 * the user specified a legal set of flags. If not, complain and exit
611 tar_options(int argc, char **argv)
617 int incfiles_max = 0;
622 struct incfile *incfiles = NULL;
625 * Set default values.
630 * process option flags
632 while ((c = getoldopt(argc, argv,
633 "b:cef:hjmopqruts:vwxzBC:HI:LOPXZ014578")) != -1) {
637 * specify blocksize in 512-byte blocks
639 if ((wrblksz = (int)str_offt(optarg)) <= 0) {
640 paxwarn(1, "Invalid block size %s", optarg);
643 wrblksz *= 512; /* XXX - check for int oflow */
653 * stop after first error
659 * filename where the archive is stored
661 if ((optarg[0] == '-') && (optarg[1]== '\0')) {
680 * use bzip2. Non standard option.
682 gzip_program = BZIP2_CMD;
686 * do not preserve modification time
698 * preserve uid/gid and file mode, regardless of umask
705 * select first match for a pattern only
712 * append to the archive
718 * file name substitution name pattern
720 if (rep_add(optarg) < 0) {
727 * list contents of the tape
733 * verbose operation mode
739 * interactive file rename
745 * extract an archive, preserving mode,
746 * and mtime if possible.
753 * use gzip. Non standard option.
755 gzip_program = GZIP_CMD;
759 * Nothing to do here, this is pax default
768 * follow command line symlinks only
773 if (++nincfiles > incfiles_max) {
774 incfiles_max = nincfiles + 3;
775 incfiles = realloc(incfiles,
776 sizeof(*incfiles) * incfiles_max);
777 if (incfiles == NULL) {
778 paxwarn(0, "Unable to allocate space "
783 incfiles[nincfiles - 1].file = optarg;
784 incfiles[nincfiles - 1].dir = chdname;
794 * do not remove leading '/' from pathnames
800 * do not pass over mount points in the file system
808 gzip_program = COMPRESS_CMD;
836 /* Traditional tar behaviour (pax uses stderr unless in list mode) */
837 if (fstdin == 1 && act == ARCHIVE)
842 /* Traditional tar behaviour (pax wants to read file list from stdin) */
843 if ((act == ARCHIVE || act == APPND) && argc == 0 && nincfiles == 0)
847 * process the args as they are interpreted by the operation mode
857 while (nincfiles || *argv != NULL) {
859 * If we queued up any include files,
860 * pull them in now. Otherwise, check
861 * for -I and -C positional flags.
862 * Anything else must be a file to
866 file = incfiles->file;
870 } else if (strcmp(*argv, "-I") == 0) {
881 if (strcmp(file, "-") == 0)
883 else if ((fp = fopen(file, "r")) == NULL) {
884 paxwarn(1, "Unable to open file '%s' for read", file);
887 while ((str = bsd_getline(fp)) != NULL) {
888 if (pat_add(str, dir) < 0)
892 if (strcmp(file, "-") != 0)
895 paxwarn(1, "Problem with file '%s'", file);
898 } else if (strcmp(*argv, "-C") == 0) {
903 } else if (pat_add(*argv++, chdname) < 0)
909 * if patterns were added, we are doing chdir()
910 * on a file-by-file basis, else, just one
911 * global chdir (if any) after opening input.
919 frmt = &(fsub[Oflag ? F_OTAR : F_TAR]);
921 if (Oflag == 2 && opt_add("write_opt=nodir") < 0)
924 if (chdname != NULL) { /* initial chdir() */
925 if (ftree_add(chdname, 1) < 0)
929 while (nincfiles || *argv != NULL) {
933 * If we queued up any include files, pull them in
934 * now. Otherwise, check for -I and -C positional
935 * flags. Anything else must be a file to include
939 file = incfiles->file;
943 } else if (strcmp(*argv, "-I") == 0) {
954 /* Set directory if needed */
956 if (ftree_add(dir, 1) < 0)
960 if (strcmp(file, "-") == 0)
962 else if ((fp = fopen(file, "r")) == NULL) {
963 paxwarn(1, "Unable to open file '%s' for read", file);
966 while ((str = bsd_getline(fp)) != NULL) {
967 if (ftree_add(str, 0) < 0)
970 if (strcmp(file, "-") != 0)
973 paxwarn(1, "Problem with file '%s'",
977 } else if (strcmp(*argv, "-C") == 0) {
980 if (ftree_add(*argv++, 1) < 0)
983 } else if (ftree_add(*argv++, 0) < 0)
987 * no read errors allowed on updates/append operation!
992 if (!fstdin && ((arcname == NULL) || (*arcname == '\0'))) {
993 arcname = getenv("TAPE");
994 if ((arcname == NULL) || (*arcname == '\0'))
995 arcname = _PATH_DEFTAPE;
1012 slash += strspn(slash, "/");
1013 slash += strcspn(slash, "/");
1015 done = (*slash == '\0');
1018 if (stat(path, &sb)) {
1019 if (errno != ENOENT || mkdir(path, 0777)) {
1020 paxwarn(1, "%s", path);
1023 } else if (!S_ISDIR(sb.st_mode)) {
1024 syswarn(1, ENOTDIR, "%s", path);
1036 * look at the user specified flags. set globals as required and check if
1037 * the user specified a legal set of flags. If not, complain and exit
1041 cpio_options(int argc, char **argv)
1056 while ((c=getopt(argc,argv,"abcdfijklmoprstuvzABC:E:F:H:I:LO:SZ6")) != -1)
1060 * preserve access time on files read
1066 * swap bytes and half-words when reading data
1073 frmt = &(fsub[F_ACPIO]);
1077 * create directories as needed
1083 * invert meaning of pattern list
1089 * restore an archive
1095 * use bzip2. Non standard option.
1097 gzip_program = BZIP2_CMD;
1103 * use links instead of copies when possible
1109 * preserve modification time
1118 frmt = &(fsub[F_CPIO]);
1128 * interactively rename files
1134 * swap bytes after reading data
1139 * list contents of archive
1146 * replace newer files
1152 * verbose operation mode
1158 * use gzip. Non standard option.
1160 gzip_program = GZIP_CMD;
1170 * Use 5120 byte block size
1176 * set block size in bytes
1178 wrblksz = atoi(optarg);
1182 * file with patterns to extract or list
1184 if ((fp = fopen(optarg, "r")) == NULL) {
1185 paxwarn(1, "Unable to open file '%s' for read", optarg);
1188 while ((str = bsd_getline(fp)) != NULL) {
1192 if (getline_error) {
1193 paxwarn(1, "Problem with file '%s'", optarg);
1201 * filename where the archive is stored
1203 if ((optarg[0] == '-') && (optarg[1]== '\0')) {
1205 * treat a - as stdin
1214 * specify an archive format on write
1217 if ((frmt = (FSUB *)bsearch((void *)&tmp, (void *)fsub,
1218 sizeof(fsub)/sizeof(FSUB), sizeof(FSUB), c_frmt)) != NULL)
1220 paxwarn(1, "Unknown -H format: %s", optarg);
1221 (void)fputs("cpio: Known -H formats are:", stderr);
1222 for (i = 0; i < (sizeof(fsub)/sizeof(FSUB)); ++i)
1223 (void)fprintf(stderr, " %s", fsub[i].name);
1224 (void)fputs("\n\n", stderr);
1229 * follow symbolic links
1235 * swap halfwords after reading data
1240 * use compress. Non standard option.
1242 gzip_program = COMPRESS_CMD;
1246 * process Version 6 cpio format
1248 frmt = &(fsub[F_OCPIO]);
1259 * process the args as they are interpreted by the operation mode
1264 while (*argv != NULL)
1265 if (pat_add(*argv++, NULL) < 0)
1269 if (*argv == NULL) {
1270 paxwarn(0, "Destination directory was not supplied");
1274 if (mkpath(dirptr) < 0)
1284 * no read errors allowed on updates/append operation!
1287 while ((str = bsd_getline(stdin)) != NULL) {
1290 if (getline_error) {
1291 paxwarn(1, "Problem while reading stdin");
1303 * print out those invalid flag sets found to the user
1307 printflg(unsigned int flg)
1312 (void)fprintf(stderr,"%s: Invalid combination of options:", argv0);
1313 while ((nxt = ffs(flg)) != 0) {
1316 (void)fprintf(stderr, " -%c", flgch[pos-1]);
1318 (void)putc('\n', stderr);
1323 * comparison routine used by bsearch to find the format specified
1328 c_frmt(const void *a, const void *b)
1330 return(strcmp(((FSUB *)a)->name, ((FSUB *)b)->name));
1335 * called by format specific options routines to get each format specific
1336 * flag and value specified with -o
1338 * pointer to next OPLIST entry or NULL (end of list).
1346 if ((opt = ophead) != NULL)
1347 ophead = ophead->fow;
1353 * generic routine used to complain about a format specific options
1354 * when the format does not support options.
1365 * print all we were given
1367 paxwarn(1,"These format options are not supported");
1368 while ((opt = opt_next()) != NULL)
1369 (void)fprintf(stderr, "\t%s = %s\n", opt->name, opt->value);
1376 * breaks the value supplied to -o into a option name and value. options
1377 * are given to -o in the form -o name-value,name=value
1378 * multiple -o may be specified.
1380 * 0 if format in name=value format, -1 if -o is passed junk
1384 opt_add(const char *str)
1392 if ((str == NULL) || (*str == '\0')) {
1393 paxwarn(0, "Invalid option name");
1396 if ((dstr = strdup(str)) == NULL) {
1397 paxwarn(0, "Unable to allocate space for option list");
1400 frpt = endpt = dstr;
1403 * break into name and values pieces and stuff each one into a
1404 * OPLIST structure. When we know the format, the format specific
1405 * option function will go through this list
1407 while ((frpt != NULL) && (*frpt != '\0')) {
1408 if ((endpt = strchr(frpt, ',')) != NULL)
1410 if ((pt = strchr(frpt, '=')) == NULL) {
1411 paxwarn(0, "Invalid options format");
1415 if ((opt = (OPLIST *)malloc(sizeof(OPLIST))) == NULL) {
1416 paxwarn(0, "Unable to allocate space for option list");
1428 if (ophead == NULL) {
1429 optail = ophead = opt;
1440 * Convert an expression of the following forms to an off_t > 0.
1441 * 1) A positive decimal number.
1442 * 2) A positive decimal number followed by a b (mult by 512).
1443 * 3) A positive decimal number followed by a k (mult by 1024).
1444 * 4) A positive decimal number followed by a m (mult by 512).
1445 * 5) A positive decimal number followed by a w (mult by sizeof int)
1446 * 6) Two or more positive decimal numbers (with/without k,b or w).
1447 * separated by x (also * for backwards compatibility), specifying
1448 * the product of the indicated values.
1450 * 0 for an error, a positive value o.w.
1460 num = strtol(val, &expr, 0);
1461 if ((num == LONG_MAX) || (num <= 0) || (expr == val))
1463 num = strtoq(val, &expr, 0);
1464 if ((num == LLONG_MAX) || (num <= 0) || (expr == val))
1505 num *= str_offt(expr + 1);
1516 bsd_getline(FILE *f)
1521 name = fgetln(f, &len);
1523 getline_error = ferror(f) ? GETLINE_FILE_CORRUPT : 0;
1526 if (name[len-1] != '\n')
1530 getline_error = GETLINE_OUT_OF_MEM;
1533 memcpy(temp, name, len-1);
1540 * for those option functions where the archive format has nothing to do.
1553 * print the usage summary to the user
1560 "usage: pax [-0cdjnOvz] [-E limit] [-f archive] [-G group] [-s replstr]\n"
1561 " [-T range] [-U user] [pattern ...]\n"
1562 " pax -r [-0cDdijknOuvYZz] [-E limit] [-f archive] [-G group] [-o options]\n"
1563 " [-p string] [-s replstr] [-T range] [-U user] [pattern ...]\n"
1564 " pax -w [-0adHijLOPtuvXz] [-B bytes] [-b blocksize] [-f archive]\n"
1565 " [-G group] [-o options] [-s replstr] [-T range] [-U user]\n"
1566 " [-x format] [file ...]\n"
1567 " pax -rw [-0DdHikLlnOPtuvXYZ] [-G group] [-p string] [-s replstr]\n"
1568 " [-T range] [-U user] [file ...] directory\n",
1575 * print the usage summary to the user
1582 "usage: tar {crtux}[014578befHhjLmOoPpqsvwXZz]\n"
1583 " [blocking-factor | archive | replstr] [-C directory] [-I file]\n"
1585 " tar {-crtux} [-014578eHhjLmOoPpqvwXZz] [-b blocking-factor]\n"
1586 " [-C directory] [-f archive] [-I file] [-s replstr] [file ...]\n",
1593 * print the usage summary to the user
1600 "usage: cpio -o [-AaBcjLvZz] [-C bytes] [-F archive] [-H format]\n"
1601 " [-O archive] < name-list [> archive]\n"
1602 " cpio -i [-6BbcdfjmrSstuvZz] [-C bytes] [-E file] [-F archive] [-H format]\n"
1603 " [-I archive] [pattern ...] [< archive]\n"
1604 " cpio -p [-adLlmuv] destination-directory < name-list\n",