Implement window size passing between real tty and virtual console.
[dragonfly/vkernel-mp.git] / contrib / tar / src / tar.c
blob70b42dadce2e694fbeaa7c6a754769af25a05ed5
1 /* A tar (tape archiver) program.
3 Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1999, 2000, 2001
4 Free Software Foundation, Inc.
6 Written by John Gilmore, starting 1985-08-25.
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any later
11 version.
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
16 Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22 /* $FreeBSD: src/contrib/tar/src/tar.c,v 1.2.2.1 2002/07/14 13:19:44 sobomax Exp $ */
23 /* $DragonFly: src/contrib/tar/src/tar.c,v 1.3 2003/07/27 05:20:17 drhodus Exp $ */
25 #include "system.h"
27 #include <fnmatch.h>
28 #include <getopt.h>
30 #include <signal.h>
31 #if ! defined SIGCHLD && defined SIGCLD
32 # define SIGCHLD SIGCLD
33 #endif
35 /* The following causes "common.h" to produce definitions of all the global
36 variables, rather than just "extern" declarations of them. GNU tar does
37 depend on the system loader to preset all GLOBAL variables to neutral (or
38 zero) values; explicit initialization is usually not done. */
39 #define GLOBAL
40 #include "common.h"
42 #include <print-copyr.h>
43 #include <localedir.h>
44 #include <prepargs.h>
45 #include <quotearg.h>
46 #include <xstrtol.h>
48 time_t get_date ();
50 /* Local declarations. */
52 #ifndef DEFAULT_ARCHIVE
53 # define DEFAULT_ARCHIVE "tar.out"
54 #endif
56 #ifndef DEFAULT_BLOCKING
57 # define DEFAULT_BLOCKING 20
58 #endif
60 static void usage PARAMS ((int)) __attribute__ ((noreturn));
62 /* Miscellaneous. */
64 /* Name of option using stdin. */
65 static const char *stdin_used_by;
67 /* Doesn't return if stdin already requested. */
68 void
69 request_stdin (const char *option)
71 if (stdin_used_by)
72 USAGE_ERROR ((0, 0, _("Options `-%s' and `-%s' both want standard input"),
73 stdin_used_by, option));
75 stdin_used_by = option;
78 /* Returns true if and only if the user typed 'y' or 'Y'. */
79 int
80 confirm (const char *message_action, const char *message_name)
82 static FILE *confirm_file;
83 static int confirm_file_EOF;
85 if (!confirm_file)
87 if (archive == 0 || stdin_used_by)
89 confirm_file = fopen (TTY_NAME, "r");
90 if (! confirm_file)
91 open_fatal (TTY_NAME);
93 else
95 request_stdin ("-w");
96 confirm_file = stdin;
100 fprintf (stdlis, "%s %s?", message_action, quote (message_name));
101 fflush (stdlis);
104 int reply = confirm_file_EOF ? EOF : getc (confirm_file);
105 int character;
107 for (character = reply;
108 character != '\n';
109 character = getc (confirm_file))
110 if (character == EOF)
112 confirm_file_EOF = 1;
113 fputc ('\n', stdlis);
114 fflush (stdlis);
115 break;
117 return reply == 'y' || reply == 'Y';
121 /* Options. */
123 /* For long options that unconditionally set a single flag, we have getopt
124 do it. For the others, we share the code for the equivalent short
125 named option, the name of which is stored in the otherwise-unused `val'
126 field of the `struct option'; for long options that have no equivalent
127 short option, we use non-characters as pseudo short options,
128 starting at CHAR_MAX + 1 and going upwards. */
130 enum
132 ANCHORED_OPTION = CHAR_MAX + 1,
133 BACKUP_OPTION,
134 DELETE_OPTION,
135 EXCLUDE_OPTION,
136 GROUP_OPTION,
137 IGNORE_CASE_OPTION,
138 MODE_OPTION,
139 NEWER_MTIME_OPTION,
140 NO_ANCHORED_OPTION,
141 NO_IGNORE_CASE_OPTION,
142 NO_WILDCARDS_OPTION,
143 NO_WILDCARDS_MATCH_SLASH_OPTION,
144 NULL_OPTION,
145 OVERWRITE_OPTION,
146 OVERWRITE_DIR_OPTION,
147 OWNER_OPTION,
148 POSIX_OPTION,
149 PRESERVE_OPTION,
150 RECORD_SIZE_OPTION,
151 RSH_COMMAND_OPTION,
152 SUFFIX_OPTION,
153 USE_COMPRESS_PROGRAM_OPTION,
154 VOLNO_FILE_OPTION,
155 WILDCARDS_OPTION,
156 WILDCARDS_MATCH_SLASH_OPTION,
158 /* Some cleanup is being made in GNU tar long options. Using old names is
159 allowed for a while, but will also send a warning to stderr. Take old
160 names out in 1.14, or in summer 1997, whichever happens last. */
162 OBSOLETE_ABSOLUTE_NAMES,
163 OBSOLETE_BLOCK_COMPRESS,
164 OBSOLETE_BLOCKING_FACTOR,
165 OBSOLETE_BLOCK_NUMBER,
166 OBSOLETE_READ_FULL_RECORDS,
167 OBSOLETE_TOUCH,
168 OBSOLETE_VERSION_CONTROL
171 /* If nonzero, display usage information and exit. */
172 static int show_help;
174 /* If nonzero, print the version on standard output and exit. */
175 static int show_version;
177 static struct option long_options[] =
179 {"absolute-names", no_argument, 0, 'P'},
180 {"absolute-paths", no_argument, 0, OBSOLETE_ABSOLUTE_NAMES},
181 {"after-date", required_argument, 0, 'N'},
182 {"anchored", no_argument, 0, ANCHORED_OPTION},
183 {"append", no_argument, 0, 'r'},
184 {"atime-preserve", no_argument, &atime_preserve_option, 1},
185 {"backup", optional_argument, 0, BACKUP_OPTION},
186 {"block-compress", no_argument, 0, OBSOLETE_BLOCK_COMPRESS},
187 {"block-number", no_argument, 0, 'R'},
188 {"block-size", required_argument, 0, OBSOLETE_BLOCKING_FACTOR},
189 {"blocking-factor", required_argument, 0, 'b'},
190 {"bzip", no_argument, 0, 'j'},
191 {"bzip2", no_argument, 0, 'j'},
192 {"bunzip2", no_argument, 0, 'j'},
193 {"catenate", no_argument, 0, 'A'},
194 {"checkpoint", no_argument, &checkpoint_option, 1},
195 {"compare", no_argument, 0, 'd'},
196 {"compress", no_argument, 0, 'Z'},
197 {"concatenate", no_argument, 0, 'A'},
198 {"confirmation", no_argument, 0, 'w'},
199 /* FIXME: --selective as a synonym for --confirmation? */
200 {"create", no_argument, 0, 'c'},
201 {"delete", no_argument, 0, DELETE_OPTION},
202 {"dereference", no_argument, 0, 'h'},
203 {"diff", no_argument, 0, 'd'},
204 {"directory", required_argument, 0, 'C'},
205 {"exclude", required_argument, 0, EXCLUDE_OPTION},
206 {"exclude-from", required_argument, 0, 'X'},
207 {"extract", no_argument, 0, 'x'},
208 {"fast-read", no_argument, &fast_read_option, 1},
209 {"file", required_argument, 0, 'f'},
210 {"files-from", required_argument, 0, 'T'},
211 {"force-local", no_argument, &force_local_option, 1},
212 {"get", no_argument, 0, 'x'},
213 {"group", required_argument, 0, GROUP_OPTION},
214 {"gunzip", no_argument, 0, 'z'},
215 {"gzip", no_argument, 0, 'z'},
216 {"help", no_argument, &show_help, 1},
217 {"ignore-case", no_argument, 0, IGNORE_CASE_OPTION},
218 {"ignore-failed-read", no_argument, &ignore_failed_read_option, 1},
219 {"ignore-zeros", no_argument, 0, 'i'},
220 /* FIXME: --ignore-end as a new name for --ignore-zeros? */
221 {"incremental", no_argument, 0, 'G'},
222 {"info-script", required_argument, 0, 'F'},
223 {"interactive", no_argument, 0, 'w'},
224 {"keep-old-files", no_argument, 0, 'k'},
225 {"label", required_argument, 0, 'V'},
226 {"list", no_argument, 0, 't'},
227 {"listed-incremental", required_argument, 0, 'g'},
228 {"mode", required_argument, 0, MODE_OPTION},
229 {"modification-time", no_argument, 0, OBSOLETE_TOUCH},
230 {"multi-volume", no_argument, 0, 'M'},
231 {"new-volume-script", required_argument, 0, 'F'},
232 {"newer", required_argument, 0, 'N'},
233 {"newer-mtime", required_argument, 0, NEWER_MTIME_OPTION},
234 {"null", no_argument, 0, NULL_OPTION},
235 {"no-anchored", no_argument, 0, NO_ANCHORED_OPTION},
236 {"no-ignore-case", no_argument, 0, NO_IGNORE_CASE_OPTION},
237 {"no-wildcards", no_argument, 0, NO_WILDCARDS_OPTION},
238 {"no-wildcards-match-slash", no_argument, 0, NO_WILDCARDS_MATCH_SLASH_OPTION},
239 {"norecurse", no_argument, &recursion_option, 0},
240 {"no-recursion", no_argument, &recursion_option, 0},
241 {"no-same-owner", no_argument, &same_owner_option, -1},
242 {"no-same-permissions", no_argument, &same_permissions_option, -1},
243 {"numeric-owner", no_argument, &numeric_owner_option, 1},
244 {"old-archive", no_argument, 0, 'o'},
245 {"one-file-system", no_argument, 0, 'l'},
246 {"overwrite", no_argument, 0, OVERWRITE_OPTION},
247 {"overwrite-dir", no_argument, 0, OVERWRITE_DIR_OPTION},
248 {"owner", required_argument, 0, OWNER_OPTION},
249 {"portability", no_argument, 0, 'o'},
250 {"posix", no_argument, 0, POSIX_OPTION},
251 {"preserve", no_argument, 0, PRESERVE_OPTION},
252 {"preserve-order", no_argument, 0, 's'},
253 {"preserve-permissions", no_argument, 0, 'p'},
254 {"recursion", no_argument, &recursion_option, FNM_LEADING_DIR},
255 {"recursive-unlink", no_argument, &recursive_unlink_option, 1},
256 {"read-full-blocks", no_argument, 0, OBSOLETE_READ_FULL_RECORDS},
257 {"read-full-records", no_argument, 0, 'B'},
258 /* FIXME: --partial-blocks might be a synonym for --read-full-records? */
259 {"record-number", no_argument, 0, OBSOLETE_BLOCK_NUMBER},
260 {"record-size", required_argument, 0, RECORD_SIZE_OPTION},
261 {"remove-files", no_argument, &remove_files_option, 1},
262 {"rsh-command", required_argument, 0, RSH_COMMAND_OPTION},
263 {"same-order", no_argument, 0, 's'},
264 {"same-owner", no_argument, &same_owner_option, 1},
265 {"same-permissions", no_argument, 0, 'p'},
266 {"show-omitted-dirs", no_argument, &show_omitted_dirs_option, 1},
267 {"sparse", no_argument, 0, 'S'},
268 {"starting-file", required_argument, 0, 'K'},
269 {"suffix", required_argument, 0, SUFFIX_OPTION},
270 {"tape-length", required_argument, 0, 'L'},
271 {"to-stdout", no_argument, 0, 'O'},
272 {"totals", no_argument, &totals_option, 1},
273 {"touch", no_argument, 0, 'm'},
274 {"uncompress", no_argument, 0, 'Z'},
275 {"ungzip", no_argument, 0, 'z'},
276 {"unlink", no_argument, 0, 'U'},
277 {"unlink-first", no_argument, 0, 'U'},
278 {"update", no_argument, 0, 'u'},
279 {"use-compress-program", required_argument, 0, USE_COMPRESS_PROGRAM_OPTION},
280 {"verbose", no_argument, 0, 'v'},
281 {"verify", no_argument, 0, 'W'},
282 {"version", no_argument, &show_version, 1},
283 {"version-control", required_argument, 0, OBSOLETE_VERSION_CONTROL},
284 {"volno-file", required_argument, 0, VOLNO_FILE_OPTION},
285 {"wildcards", no_argument, 0, WILDCARDS_OPTION},
286 {"wildcards-match-slash", no_argument, 0, WILDCARDS_MATCH_SLASH_OPTION},
288 {0, 0, 0, 0}
291 /* Print a usage message and exit with STATUS. */
292 static void
293 usage (int status)
295 if (status != TAREXIT_SUCCESS)
296 fprintf (stderr, _("Try `%s --help' for more information.\n"),
297 program_name);
298 else
300 fputs (_("\
301 GNU `tar' saves many files together into a single tape or disk archive, and\n\
302 can restore individual files from the archive.\n"),
303 stdout);
304 printf (_("\nUsage: %s [OPTION]... [FILE]...\n\
306 Examples:\n\
307 %s -cf archive.tar foo bar # Create archive.tar from files foo and bar.\n\
308 %s -tvf archive.tar # List all files in archive.tar verbosely.\n\
309 %s -xf archive.tar # Extract all files from archive.tar.\n"),
310 program_name, program_name, program_name, program_name);
311 fputs (_("\
313 If a long option shows an argument as mandatory, then it is mandatory\n\
314 for the equivalent short option also. Similarly for optional arguments.\n"),
315 stdout);
316 fputs(_("\
318 Main operation mode:\n\
319 -t, --list list the contents of an archive\n\
320 -x, --extract, --get extract files from an archive\n\
321 -c, --create create a new archive\n\
322 -d, --diff, --compare find differences between archive and file system\n\
323 -r, --append append files to the end of an archive\n\
324 -u, --update only append files newer than copy in archive\n\
325 -A, --catenate append tar files to an archive\n\
326 --concatenate same as -A\n\
327 --delete delete from the archive (not on mag tapes!)\n"),
328 stdout);
329 fputs (_("\
331 Operation modifiers:\n\
332 -W, --verify attempt to verify the archive after writing it\n\
333 --remove-files remove files after adding them to the archive\n\
334 -k, --keep-old-files don't replace existing files when extracting\n\
335 --overwrite overwrite existing files when extracting\n\
336 --overwrite-dir overwrite directory metadata when extracting\n\
337 -U, --unlink,\n\
338 --unlink-first remove each file prior to extracting over it\n\
339 --recursive-unlink empty hierarchies prior to extracting directory\n\
340 -S, --sparse handle sparse files efficiently\n\
341 -O, --to-stdout extract files to standard output\n\
342 -G, --incremental handle old GNU-format incremental backup\n\
343 -g, --listed-incremental=FILE\n\
344 handle new GNU-format incremental backup\n\
345 --ignore-failed-read do not exit with nonzero on unreadable files\n\
346 --fast-read stop after desired names in archive have been found\n"),
347 stdout);
348 fputs (_("\
350 Handling of file attributes:\n\
351 --owner=NAME force NAME as owner for added files\n\
352 --group=NAME force NAME as group for added files\n\
353 --mode=CHANGES force (symbolic) mode CHANGES for added files\n\
354 --atime-preserve don't change access times on dumped files\n\
355 -m, --modification-time don't extract file modified time\n\
356 --same-owner try extracting files with the same ownership\n\
357 --show-omitted-dirs show omitted directories while processing the\n\
358 archive\n\
359 --no-same-owner extract files as yourself\n\
360 --numeric-owner always use numbers for user/group names\n\
361 -p, --same-permissions extract permissions information\n\
362 --no-same-permissions do not extract permissions information\n\
363 --preserve-permissions same as -p\n\
364 -s, --same-order sort names to extract to match archive\n\
365 --preserve-order same as -s\n\
366 --preserve same as both -p and -s\n"),
367 stdout);
368 fputs (_("\
370 Device selection and switching:\n\
371 -f, --file=ARCHIVE use archive file or device ARCHIVE\n\
372 --force-local archive file is local even if it has a colon\n\
373 --rsh-command=COMMAND use remote COMMAND instead of rsh\n\
374 -[0-7][lmh] specify drive and density\n\
375 -M, --multi-volume create/list/extract multi-volume archive\n\
376 -L, --tape-length=NUM change tape after writing NUM x 1024 bytes\n\
377 -F, --info-script=FILE run script at end of each tape (implies -M)\n\
378 --new-volume-script=FILE same as -F FILE\n\
379 --volno-file=FILE use/update the volume number in FILE\n"),
380 stdout);
381 fputs (_("\
383 Device blocking:\n\
384 -b, --blocking-factor=BLOCKS BLOCKS x 512 bytes per record\n\
385 --record-size=SIZE SIZE bytes per record, multiple of 512\n\
386 -i, --ignore-zeros ignore zeroed blocks in archive (means EOF)\n\
387 -B, --read-full-records reblock as we read (for 4.2BSD pipes)\n"),
388 stdout);
389 fputs (_("\
391 Archive format selection:\n\
392 -V, --label=NAME create archive with volume name NAME\n\
393 PATTERN at list/extract time, a globbing PATTERN\n\
394 -o, --old-archive, --portability write a V7 format archive\n\
395 --posix write a POSIX format archive\n\
396 -j, -y, --bzip, --bzip2, --bunzip2 filter the archive through bzip2\n\
397 -z, --gzip, --ungzip filter the archive through gzip\n\
398 -Z, --compress, --uncompress filter the archive through compress\n\
399 --use-compress-program=PROG filter through PROG (must accept -d)\n"),
400 stdout);
401 fputs (_("\
403 Local file selection:\n\
404 -C, --directory=DIR change to directory DIR\n\
405 -T, -I, --files-from=NAME get names to extract or create from file NAME\n\
406 --null -T reads null-terminated names, disable -C\n\
407 --exclude=PATTERN exclude files, given as a a globbing PATTERN\n\
408 -X, --exclude-from=FILE exclude patterns listed in FILE\n\
409 --anchored exclude patterns match file name start (default)\n\
410 --no-anchored exclude patterns match after any /\n\
411 --ignore-case exclusion ignores case\n\
412 --no-ignore-case exclusion is case sensitive (default)\n\
413 --wildcards exclude patterns use wildcards (default)\n\
414 --no-wildcards exclude patterns are plain strings\n\
415 --wildcards-match-slash exclude pattern wildcards match '/' (default)\n\
416 --no-wildcards-match-slash exclude pattern wildcards do not match '/'\n\
417 -P, --absolute-names don't strip leading `/'s from file names\n\
418 -h, --dereference dump instead the files symlinks point to\n\
419 -n, --norecurse\n\
420 --no-recursion avoid descending automatically in directories\n\
421 -l, --one-file-system stay in local file system when creating archive\n\
422 -K, --starting-file=NAME begin at file NAME in the archive\n"),
423 stdout);
424 #if !MSDOS
425 fputs (_("\
426 -N, --newer=DATE only store files with creation time newer than\n\
427 DATE\n\
428 --newer-mtime=DATE only store files with modification time newer\n\
429 than DATE\n\
430 --after-date=DATE same as -N\n"),
431 stdout);
432 #endif
433 fputs (_("\
434 --backup[=CONTROL] backup before removal, choose version control\n\
435 --suffix=SUFFIX backup before removal, override usual suffix\n"),
436 stdout);
437 fputs (_("\
439 Informative output:\n\
440 --help print this help, then exit\n\
441 --version print tar program version number, then exit\n\
442 -v, --verbose verbosely list files processed\n\
443 --checkpoint print number of buffer reads/writes\n\
444 --totals print total bytes written while creating archive\n\
445 -R, --block-number show block number within archive with each message\n\
446 -w, --interactive ask for confirmation for every action\n\
447 --confirmation same as -w\n"),
448 stdout);
449 fputs (_("\
451 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
452 The version control may be set with --backup or VERSION_CONTROL, values are:\n\
454 t, numbered make numbered backups\n\
455 nil, existing numbered if numbered backups exist, simple otherwise\n\
456 never, simple always make simple backups\n"),
457 stdout);
458 printf (_("\
460 GNU tar cannot read nor produce `--posix' archives. If POSIXLY_CORRECT\n\
461 is set in the environment, GNU extensions are disallowed with `--posix'.\n\
462 Support for POSIX is only partially implemented, don't count on it yet.\n\
463 ARCHIVE may be FILE, HOST:FILE or USER@HOST:FILE; DATE may be a textual date\n\
464 or a file name starting with `/' or `.', in which case the file's date is used.\n\
465 *This* `tar' defaults to `-f%s -b%d'.\n"),
466 DEFAULT_ARCHIVE, DEFAULT_BLOCKING);
467 fputs (_("\nReport bugs to <bug-tar@gnu.org>.\n"), stdout);
469 exit (status);
472 /* Parse the options for tar. */
474 /* Available option letters are DEHIJQY and aenqy. Some are reserved:
476 e exit immediately with a nonzero exit status if unexpected errors occur
477 E use extended headers (draft POSIX headers, that is)
478 I same as T (for compatibility with Solaris tar)
479 n the archive is quickly seekable, so don't worry about random seeks
480 q stop after extracting the first occurrence of the named file
481 y per-file gzip compression
482 Y per-block gzip compression */
484 #define OPTION_STRING \
485 "-01234567ABC:F:GI:K:L:MnN:OPRST:UV:WX:Zb:cdf:g:hijklmoprstuvwxyz"
487 static void
488 set_subcommand_option (enum subcommand subcommand)
490 if (subcommand_option != UNKNOWN_SUBCOMMAND
491 && subcommand_option != subcommand)
492 USAGE_ERROR ((0, 0,
493 _("You may not specify more than one `-Acdtrux' option")));
495 subcommand_option = subcommand;
498 static void
499 set_use_compress_program_option (const char *string)
501 if (use_compress_program_option && strcmp (use_compress_program_option, string) != 0)
502 USAGE_ERROR ((0, 0, _("Conflicting compression options")));
504 use_compress_program_option = string;
507 static void
508 decode_options (int argc, char **argv)
510 int optchar; /* option letter */
511 int input_files; /* number of input files */
512 const char *backup_suffix_string;
513 const char *version_control_string = 0;
514 int exclude_options = EXCLUDE_WILDCARDS;
516 /* Set some default option values. */
518 subcommand_option = UNKNOWN_SUBCOMMAND;
519 archive_format = DEFAULT_FORMAT;
520 blocking_factor = DEFAULT_BLOCKING;
521 record_size = DEFAULT_BLOCKING * BLOCKSIZE;
522 excluded = new_exclude ();
523 newer_mtime_option = TYPE_MINIMUM (time_t);
524 recursion_option = FNM_LEADING_DIR;
525 namelist_freed = 0;
527 owner_option = -1;
528 group_option = -1;
530 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
532 /* Convert old-style tar call by exploding option element and rearranging
533 options accordingly. */
535 if (argc > 1 && argv[1][0] != '-')
537 int new_argc; /* argc value for rearranged arguments */
538 char **new_argv; /* argv value for rearranged arguments */
539 char *const *in; /* cursor into original argv */
540 char **out; /* cursor into rearranged argv */
541 const char *letter; /* cursor into old option letters */
542 char buffer[3]; /* constructed option buffer */
543 const char *cursor; /* cursor in OPTION_STRING */
545 /* Initialize a constructed option. */
547 buffer[0] = '-';
548 buffer[2] = '\0';
550 /* Allocate a new argument array, and copy program name in it. */
552 new_argc = argc - 1 + strlen (argv[1]);
553 new_argv = xmalloc ((new_argc + 1) * sizeof (char *));
554 in = argv;
555 out = new_argv;
556 *out++ = *in++;
558 /* Copy each old letter option as a separate option, and have the
559 corresponding argument moved next to it. */
561 for (letter = *in++; *letter; letter++)
563 buffer[1] = *letter;
564 *out++ = xstrdup (buffer);
565 cursor = strchr (OPTION_STRING, *letter);
566 if (cursor && cursor[1] == ':')
568 if (in < argv + argc)
569 *out++ = *in++;
570 else
571 USAGE_ERROR ((0, 0, _("Old option `%c' requires an argument."),
572 *letter));
576 /* Copy all remaining options. */
578 while (in < argv + argc)
579 *out++ = *in++;
581 /* And NULL terminate the argv[] array */
582 *out++ = NULL;
584 /* Replace the old option list by the new one. */
586 argc = new_argc;
587 argv = new_argv;
590 /* Parse all options and non-options as they appear. */
592 input_files = 0;
594 prepend_default_options (getenv ("TAR_OPTIONS"), &argc, &argv);
596 while (optchar = getopt_long (argc, argv, OPTION_STRING, long_options, 0),
597 optchar != -1)
598 switch (optchar)
600 case '?':
601 usage (TAREXIT_FAILURE);
603 case 0:
604 break;
606 case 1:
607 /* File name or non-parsed option, because of RETURN_IN_ORDER
608 ordering triggered by the leading dash in OPTION_STRING. */
610 name_add (optarg);
611 input_files++;
612 break;
614 case 'A':
615 set_subcommand_option (CAT_SUBCOMMAND);
616 break;
618 case OBSOLETE_BLOCK_COMPRESS:
619 WARN ((0, 0, _("Obsolete option, now implied by --blocking-factor")));
620 break;
622 case OBSOLETE_BLOCKING_FACTOR:
623 WARN ((0, 0, _("Obsolete option name replaced by --blocking-factor")));
624 /* Fall through. */
626 case 'b':
628 uintmax_t u;
629 if (! (xstrtoumax (optarg, 0, 10, &u, "") == LONGINT_OK
630 && u == (blocking_factor = u)
631 && 0 < blocking_factor
632 && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE))
633 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (optarg),
634 _("Invalid blocking factor")));
636 break;
638 case OBSOLETE_READ_FULL_RECORDS:
639 WARN ((0, 0,
640 _("Obsolete option name replaced by --read-full-records")));
641 /* Fall through. */
643 case 'B':
644 /* Try to reblock input records. For reading 4.2BSD pipes. */
646 /* It would surely make sense to exchange -B and -R, but it seems
647 that -B has been used for a long while in Sun tar ans most
648 BSD-derived systems. This is a consequence of the block/record
649 terminology confusion. */
651 read_full_records_option = 1;
652 break;
654 case 'c':
655 set_subcommand_option (CREATE_SUBCOMMAND);
656 break;
658 case 'C':
659 name_add ("-C");
660 name_add (optarg);
661 break;
663 case 'd':
664 set_subcommand_option (DIFF_SUBCOMMAND);
665 break;
667 case 'f':
668 if (archive_names == allocated_archive_names)
670 allocated_archive_names *= 2;
671 archive_name_array =
672 xrealloc (archive_name_array,
673 sizeof (const char *) * allocated_archive_names);
675 archive_name_array[archive_names++] = optarg;
676 break;
678 case 'F':
679 /* Since -F is only useful with -M, make it implied. Run this
680 script at the end of each tape. */
682 info_script_option = optarg;
683 multi_volume_option = 1;
684 break;
686 case 'g':
687 listed_incremental_option = optarg;
688 after_date_option = 1;
689 /* Fall through. */
691 case 'G':
692 /* We are making an incremental dump (FIXME: are we?); save
693 directories at the beginning of the archive, and include in each
694 directory its contents. */
696 incremental_option = 1;
697 break;
699 case 'h':
700 /* Follow symbolic links. */
702 dereference_option = 1;
703 break;
705 case 'i':
706 /* Ignore zero blocks (eofs). This can't be the default,
707 because Unix tar writes two blocks of zeros, then pads out
708 the record with garbage. */
710 ignore_zeros_option = 1;
711 break;
713 case 'j':
714 case 'y':
715 set_use_compress_program_option ("bzip2");
716 break;
718 case 'k':
719 /* Don't replace existing files. */
720 old_files_option = KEEP_OLD_FILES;
721 break;
723 case 'K':
724 starting_file_option = 1;
725 addname (optarg, 0);
726 break;
728 case 'l':
729 /* When dumping directories, don't dump files/subdirectories
730 that are on other filesystems. */
732 one_file_system_option = 1;
733 break;
735 case 'L':
737 uintmax_t u;
738 if (xstrtoumax (optarg, 0, 10, &u, "") != LONGINT_OK)
739 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (optarg),
740 _("Invalid tape length")));
741 tape_length_option = 1024 * (tarlong) u;
742 multi_volume_option = 1;
744 break;
746 case OBSOLETE_TOUCH:
747 WARN ((0, 0, _("Obsolete option name replaced by --touch")));
748 /* Fall through. */
750 case 'm':
751 touch_option = 1;
752 break;
754 case 'M':
755 /* Make multivolume archive: when we can't write any more into
756 the archive, re-open it, and continue writing. */
758 multi_volume_option = 1;
759 break;
761 case 'n':
762 recursion_option = 0;
763 break;
765 #if !MSDOS
766 case 'N':
767 after_date_option = 1;
768 /* Fall through. */
770 case NEWER_MTIME_OPTION:
771 if (newer_mtime_option != TYPE_MINIMUM (time_t))
772 USAGE_ERROR ((0, 0, _("More than one threshold date")));
774 if (FILESYSTEM_PREFIX_LEN (optarg) != 0
775 || ISSLASH (*optarg)
776 || *optarg == '.')
778 struct stat st;
779 if (deref_stat (dereference_option, optarg, &st) != 0)
781 stat_error (optarg);
782 USAGE_ERROR ((0, 0, _("Date file not found")));
784 newer_mtime_option = st.st_mtime;
786 else
788 newer_mtime_option = get_date (optarg, 0);
789 if (newer_mtime_option == (time_t) -1)
790 WARN ((0, 0, _("Substituting %s for unknown date format %s"),
791 tartime (newer_mtime_option), quote (optarg)));
794 break;
795 #endif /* not MSDOS */
797 case 'o':
798 if (archive_format == DEFAULT_FORMAT)
799 archive_format = V7_FORMAT;
800 else if (archive_format != V7_FORMAT)
801 USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
802 break;
804 case 'O':
805 to_stdout_option = 1;
806 break;
808 case 'p':
809 same_permissions_option = 1;
810 break;
812 case OBSOLETE_ABSOLUTE_NAMES:
813 WARN ((0, 0, _("Obsolete option name replaced by --absolute-names")));
814 /* Fall through. */
816 case 'P':
817 absolute_names_option = 1;
818 break;
820 case 'r':
821 set_subcommand_option (APPEND_SUBCOMMAND);
822 break;
824 case OBSOLETE_BLOCK_NUMBER:
825 WARN ((0, 0, _("Obsolete option name replaced by --block-number")));
826 /* Fall through. */
828 case 'R':
829 /* Print block numbers for debugging bad tar archives. */
831 /* It would surely make sense to exchange -B and -R, but it seems
832 that -B has been used for a long while in Sun tar ans most
833 BSD-derived systems. This is a consequence of the block/record
834 terminology confusion. */
836 block_number_option = 1;
837 break;
839 case 's':
840 /* Names to extr are sorted. */
842 same_order_option = 1;
843 break;
845 case 'S':
846 sparse_option = 1;
847 break;
849 case 't':
850 set_subcommand_option (LIST_SUBCOMMAND);
851 verbose_option++;
852 break;
854 case 'T':
855 case 'I':
856 files_from_option = optarg;
857 break;
859 case 'u':
860 set_subcommand_option (UPDATE_SUBCOMMAND);
861 break;
863 case 'U':
864 old_files_option = UNLINK_FIRST_OLD_FILES;
865 break;
867 case 'v':
868 verbose_option++;
869 break;
871 case 'V':
872 volume_label_option = optarg;
873 break;
875 case 'w':
876 interactive_option = 1;
877 break;
879 case 'W':
880 verify_option = 1;
881 break;
883 case 'x':
884 set_subcommand_option (EXTRACT_SUBCOMMAND);
885 break;
887 case 'X':
888 if (add_exclude_file (add_exclude, excluded, optarg,
889 exclude_options | recursion_option, '\n')
890 != 0)
892 int e = errno;
893 FATAL_ERROR ((0, e, "%s", quotearg_colon (optarg)));
895 break;
897 case 'z':
898 set_use_compress_program_option ("gzip");
899 break;
901 case 'Z':
902 set_use_compress_program_option ("compress");
903 break;
905 case OBSOLETE_VERSION_CONTROL:
906 WARN ((0, 0, _("Obsolete option name replaced by --backup")));
907 /* Fall through. */
909 case ANCHORED_OPTION:
910 exclude_options |= EXCLUDE_ANCHORED;
911 break;
913 case BACKUP_OPTION:
914 backup_option = 1;
915 if (optarg)
916 version_control_string = optarg;
917 break;
919 case DELETE_OPTION:
920 set_subcommand_option (DELETE_SUBCOMMAND);
921 break;
923 case EXCLUDE_OPTION:
924 add_exclude (excluded, optarg, exclude_options | recursion_option);
925 break;
927 case IGNORE_CASE_OPTION:
928 exclude_options |= FNM_CASEFOLD;
929 break;
931 case GROUP_OPTION:
932 if (! (strlen (optarg) < GNAME_FIELD_SIZE
933 && gname_to_gid (optarg, &group_option)))
935 uintmax_t g;
936 if (xstrtoumax (optarg, 0, 10, &g, "") == LONGINT_OK
937 && g == (gid_t) g)
938 group_option = g;
939 else
940 FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (optarg),
941 _("%s: Invalid group")));
943 break;
945 case MODE_OPTION:
946 mode_option
947 = mode_compile (optarg,
948 MODE_MASK_EQUALS | MODE_MASK_PLUS | MODE_MASK_MINUS);
949 if (mode_option == MODE_INVALID)
950 FATAL_ERROR ((0, 0, _("Invalid mode given on option")));
951 if (mode_option == MODE_MEMORY_EXHAUSTED)
952 xalloc_die ();
953 break;
955 case NO_ANCHORED_OPTION:
956 exclude_options &= ~ EXCLUDE_ANCHORED;
957 break;
959 case NO_IGNORE_CASE_OPTION:
960 exclude_options &= ~ FNM_CASEFOLD;
961 break;
963 case NO_WILDCARDS_OPTION:
964 exclude_options &= ~ EXCLUDE_WILDCARDS;
965 break;
967 case NO_WILDCARDS_MATCH_SLASH_OPTION:
968 exclude_options |= FNM_FILE_NAME;
969 break;
971 case NULL_OPTION:
972 filename_terminator = '\0';
973 break;
975 case OVERWRITE_OPTION:
976 old_files_option = OVERWRITE_OLD_FILES;
977 break;
979 case OVERWRITE_DIR_OPTION:
980 old_files_option = OVERWRITE_OLD_DIRS;
981 break;
983 case OWNER_OPTION:
984 if (! (strlen (optarg) < UNAME_FIELD_SIZE
985 && uname_to_uid (optarg, &owner_option)))
987 uintmax_t u;
988 if (xstrtoumax (optarg, 0, 10, &u, "") == LONGINT_OK
989 && u == (uid_t) u)
990 owner_option = u;
991 else
992 FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (optarg),
993 _("Invalid owner")));
995 break;
997 case POSIX_OPTION:
998 #if OLDGNU_COMPATIBILITY
999 if (archive_format == DEFAULT_FORMAT)
1000 archive_format = GNU_FORMAT;
1001 else if (archive_format != GNU_FORMAT)
1002 USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
1003 #else
1004 if (archive_format == DEFAULT_FORMAT)
1005 archive_format = POSIX_FORMAT;
1006 else if (archive_format != POSIX_FORMAT)
1007 USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
1008 #endif
1009 break;
1011 case PRESERVE_OPTION:
1012 same_permissions_option = 1;
1013 same_order_option = 1;
1014 break;
1016 case RECORD_SIZE_OPTION:
1018 uintmax_t u;
1019 if (! (xstrtoumax (optarg, 0, 10, &u, "") == LONGINT_OK
1020 && u == (size_t) u))
1021 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (optarg),
1022 _("Invalid record size")));
1023 record_size = u;
1024 if (record_size % BLOCKSIZE != 0)
1025 USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
1026 BLOCKSIZE));
1027 blocking_factor = record_size / BLOCKSIZE;
1029 break;
1031 case RSH_COMMAND_OPTION:
1032 rsh_command_option = optarg;
1033 break;
1035 case SUFFIX_OPTION:
1036 backup_option = 1;
1037 backup_suffix_string = optarg;
1038 break;
1040 case USE_COMPRESS_PROGRAM_OPTION:
1041 set_use_compress_program_option (optarg);
1042 break;
1044 case VOLNO_FILE_OPTION:
1045 volno_file_option = optarg;
1046 break;
1048 case WILDCARDS_OPTION:
1049 exclude_options |= EXCLUDE_WILDCARDS;
1050 break;
1052 case WILDCARDS_MATCH_SLASH_OPTION:
1053 exclude_options &= ~ FNM_FILE_NAME;
1054 break;
1056 case '0':
1057 case '1':
1058 case '2':
1059 case '3':
1060 case '4':
1061 case '5':
1062 case '6':
1063 case '7':
1065 #ifdef DEVICE_PREFIX
1067 int device = optchar - '0';
1068 int density;
1069 static char buf[sizeof DEVICE_PREFIX + 10];
1070 char *cursor;
1072 density = getopt_long (argc, argv, "lmh", 0, 0);
1073 strcpy (buf, DEVICE_PREFIX);
1074 cursor = buf + strlen (buf);
1076 #ifdef DENSITY_LETTER
1078 sprintf (cursor, "%d%c", device, density);
1080 #else /* not DENSITY_LETTER */
1082 switch (density)
1084 case 'l':
1085 #ifdef LOW_NUM
1086 device += LOW_NUM;
1087 #endif
1088 break;
1090 case 'm':
1091 #ifdef MID_NUM
1092 device += MID_NUM;
1093 #else
1094 device += 8;
1095 #endif
1096 break;
1098 case 'h':
1099 #ifdef HGH_NUM
1100 device += HGH_NUM;
1101 #else
1102 device += 16;
1103 #endif
1104 break;
1106 default:
1107 usage (TAREXIT_FAILURE);
1109 sprintf (cursor, "%d", device);
1111 #endif /* not DENSITY_LETTER */
1113 if (archive_names == allocated_archive_names)
1115 allocated_archive_names *= 2;
1116 archive_name_array =
1117 xrealloc (archive_name_array,
1118 sizeof (const char *) * allocated_archive_names);
1120 archive_name_array[archive_names++] = buf;
1122 /* FIXME: How comes this works for many archives when buf is
1123 not xstrdup'ed? */
1125 break;
1127 #else /* not DEVICE_PREFIX */
1129 USAGE_ERROR ((0, 0,
1130 _("Options `-[0-7][lmh]' not supported by *this* tar")));
1132 #endif /* not DEVICE_PREFIX */
1135 /* Handle operands after any "--" argument. */
1136 for (; optind < argc; optind++)
1138 name_add (argv[optind]);
1139 input_files++;
1142 /* Process trivial options. */
1144 if (show_version)
1146 printf ("tar (GNU %s) %s\n", PACKAGE, VERSION);
1147 print_copyright ("2001 Free Software Foundation, Inc.");
1148 puts (_("\
1149 This program comes with NO WARRANTY, to the extent permitted by law.\n\
1150 You may redistribute it under the terms of the GNU General Public License;\n\
1151 see the file named COPYING for details."));
1153 puts (_("Written by John Gilmore and Jay Fenlason."));
1155 exit (TAREXIT_SUCCESS);
1158 if (show_help)
1159 usage (TAREXIT_SUCCESS);
1161 /* Derive option values and check option consistency. */
1163 if (archive_format == DEFAULT_FORMAT)
1165 #if OLDGNU_COMPATIBILITY
1166 archive_format = OLDGNU_FORMAT;
1167 #else
1168 archive_format = GNU_FORMAT;
1169 #endif
1172 if (archive_format == GNU_FORMAT && getenv ("POSIXLY_CORRECT"))
1173 archive_format = POSIX_FORMAT;
1175 if ((volume_label_option
1176 || incremental_option || multi_volume_option || sparse_option)
1177 && archive_format != OLDGNU_FORMAT && archive_format != GNU_FORMAT)
1178 USAGE_ERROR ((0, 0,
1179 _("GNU features wanted on incompatible archive format")));
1181 if (archive_names == 0)
1183 /* If no archive file name given, try TAPE from the environment, or
1184 else, DEFAULT_ARCHIVE from the configuration process. */
1186 archive_names = 1;
1187 archive_name_array[0] = getenv ("TAPE");
1188 if (! archive_name_array[0])
1189 archive_name_array[0] = DEFAULT_ARCHIVE;
1192 /* Allow multiple archives only with `-M'. */
1194 if (archive_names > 1 && !multi_volume_option)
1195 USAGE_ERROR ((0, 0,
1196 _("Multiple archive files requires `-M' option")));
1198 if (listed_incremental_option
1199 && newer_mtime_option != TYPE_MINIMUM (time_t))
1200 USAGE_ERROR ((0, 0,
1201 _("Cannot combine --listed-incremental with --newer")));
1203 if (volume_label_option)
1205 size_t volume_label_max_len =
1206 (sizeof current_header->header.name
1207 - 1 /* for trailing '\0' */
1208 - (multi_volume_option
1209 ? (sizeof " Volume "
1210 - 1 /* for null at end of " Volume " */
1211 + INT_STRLEN_BOUND (int) /* for volume number */
1212 - 1 /* for sign, as 0 <= volno */)
1213 : 0));
1214 if (volume_label_max_len < strlen (volume_label_option))
1215 USAGE_ERROR ((0, 0,
1216 _("%s: Volume label is too long (limit is %lu bytes)"),
1217 quotearg_colon (volume_label_option),
1218 (unsigned long) volume_label_max_len));
1221 /* If ready to unlink hierarchies, so we are for simpler files. */
1222 if (recursive_unlink_option)
1223 old_files_option = UNLINK_FIRST_OLD_FILES;
1225 /* Forbid using -c with no input files whatsoever. Check that `-f -',
1226 explicit or implied, is used correctly. */
1228 switch (subcommand_option)
1230 case CREATE_SUBCOMMAND:
1231 if (input_files == 0 && !files_from_option)
1232 USAGE_ERROR ((0, 0,
1233 _("Cowardly refusing to create an empty archive")));
1234 break;
1236 case EXTRACT_SUBCOMMAND:
1237 case LIST_SUBCOMMAND:
1238 case DIFF_SUBCOMMAND:
1239 for (archive_name_cursor = archive_name_array;
1240 archive_name_cursor < archive_name_array + archive_names;
1241 archive_name_cursor++)
1242 if (!strcmp (*archive_name_cursor, "-"))
1243 request_stdin ("-f");
1244 break;
1246 case CAT_SUBCOMMAND:
1247 case UPDATE_SUBCOMMAND:
1248 case APPEND_SUBCOMMAND:
1249 for (archive_name_cursor = archive_name_array;
1250 archive_name_cursor < archive_name_array + archive_names;
1251 archive_name_cursor++)
1252 if (!strcmp (*archive_name_cursor, "-"))
1253 USAGE_ERROR ((0, 0,
1254 _("Options `-Aru' are incompatible with `-f -'")));
1256 default:
1257 break;
1260 archive_name_cursor = archive_name_array;
1262 /* Prepare for generating backup names. */
1264 if (backup_suffix_string)
1265 simple_backup_suffix = xstrdup (backup_suffix_string);
1267 if (backup_option)
1268 backup_type = xget_version ("--backup", version_control_string);
1271 /* Tar proper. */
1273 /* Main routine for tar. */
1275 main (int argc, char **argv)
1277 #if HAVE_CLOCK_GETTIME
1278 if (clock_gettime (CLOCK_REALTIME, &start_timespec) != 0)
1279 #endif
1280 start_time = time (0);
1281 program_name = argv[0];
1282 (void) setlocale (LC_ALL, "");
1283 bindtextdomain (PACKAGE, LOCALEDIR);
1284 textdomain (PACKAGE);
1286 exit_status = TAREXIT_SUCCESS;
1287 filename_terminator = '\n';
1288 set_quoting_style (0, escape_quoting_style);
1290 /* Pre-allocate a few structures. */
1292 allocated_archive_names = 10;
1293 archive_name_array =
1294 xmalloc (sizeof (const char *) * allocated_archive_names);
1295 archive_names = 0;
1297 #ifdef SIGCHLD
1298 /* System V fork+wait does not work if SIGCHLD is ignored. */
1299 signal (SIGCHLD, SIG_DFL);
1300 #endif
1302 init_names ();
1304 /* Decode options. */
1306 decode_options (argc, argv);
1307 name_init (argc, argv);
1309 /* Main command execution. */
1311 if (volno_file_option)
1312 init_volume_number ();
1314 switch (subcommand_option)
1316 case UNKNOWN_SUBCOMMAND:
1317 USAGE_ERROR ((0, 0,
1318 _("You must specify one of the `-Acdtrux' options")));
1320 case CAT_SUBCOMMAND:
1321 case UPDATE_SUBCOMMAND:
1322 case APPEND_SUBCOMMAND:
1323 update_archive ();
1324 break;
1326 case DELETE_SUBCOMMAND:
1327 delete_archive_members ();
1328 break;
1330 case CREATE_SUBCOMMAND:
1331 create_archive ();
1332 name_close ();
1334 if (totals_option)
1335 print_total_written ();
1336 break;
1338 case EXTRACT_SUBCOMMAND:
1339 extr_init ();
1340 read_and (extract_archive);
1341 extract_finish ();
1342 break;
1344 case LIST_SUBCOMMAND:
1345 read_and (list_archive);
1346 break;
1348 case DIFF_SUBCOMMAND:
1349 diff_init ();
1350 read_and (diff_archive);
1351 break;
1354 if (volno_file_option)
1355 closeout_volume_number ();
1357 /* Dispose of allocated memory, and return. */
1359 free (archive_name_array);
1360 name_term ();
1362 if (stdlis == stdout && (ferror (stdout) || fclose (stdout) != 0))
1363 FATAL_ERROR ((0, 0, _("Error in writing to standard output")));
1364 if (exit_status == TAREXIT_FAILURE)
1365 error (0, 0, _("Error exit delayed from previous errors"));
1366 exit (exit_status);