1/* A tar (tape archiver) program.
2
3   Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1999, 2000,
4   2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6   Written by John Gilmore, starting 1985-08-25.
7
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.
12
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.
17
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   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
21
22#include <system.h>
23
24#include <fnmatch.h>
25#include <getline.h>
26#include <argp.h>
27#include <argp-namefrob.h>
28#include <argp-fmtstream.h>
29
30#include <signal.h>
31#if ! defined SIGCHLD && defined SIGCLD
32# define SIGCHLD SIGCLD
33#endif
34
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"
41
42#include <argmatch.h>
43#include <closeout.h>
44#include <configmake.h>
45#include <exitfail.h>
46#include <getdate.h>
47#include <rmt.h>
48#include <rmt-command.h>
49#include <prepargs.h>
50#include <quotearg.h>
51#include <version-etc.h>
52#include <xstrtol.h>
53#include <stdopen.h>
54
55/* Local declarations.  */
56
57#ifndef DEFAULT_ARCHIVE_FORMAT
58# define DEFAULT_ARCHIVE_FORMAT GNU_FORMAT
59#endif
60
61#ifndef DEFAULT_ARCHIVE
62# define DEFAULT_ARCHIVE "tar.out"
63#endif
64
65#ifndef DEFAULT_BLOCKING
66# define DEFAULT_BLOCKING 20
67#endif
68
69
70/* Miscellaneous.  */
71
72/* Name of option using stdin.  */
73static const char *stdin_used_by;
74
75/* Doesn't return if stdin already requested.  */
76void
77request_stdin (const char *option)
78{
79  if (stdin_used_by)
80    USAGE_ERROR ((0, 0, _("Options `-%s' and `-%s' both want standard input"),
81		  stdin_used_by, option));
82
83  stdin_used_by = option;
84}
85
86extern int rpmatch (char const *response);
87
88/* Returns true if and only if the user typed an affirmative response.  */
89int
90confirm (const char *message_action, const char *message_name)
91{
92  static FILE *confirm_file;
93  static int confirm_file_EOF;
94  bool status = false;
95
96  if (!confirm_file)
97    {
98      if (archive == 0 || stdin_used_by)
99	{
100	  confirm_file = fopen (TTY_NAME, "r");
101	  if (! confirm_file)
102	    open_fatal (TTY_NAME);
103	}
104      else
105	{
106	  request_stdin ("-w");
107	  confirm_file = stdin;
108	}
109    }
110
111  fprintf (stdlis, "%s %s?", message_action, quote (message_name));
112  fflush (stdlis);
113
114  if (!confirm_file_EOF)
115    {
116      char *response = NULL;
117      size_t response_size = 0;
118      if (getline (&response, &response_size, confirm_file) < 0)
119	confirm_file_EOF = 1;
120      else
121	status = rpmatch (response) > 0;
122      free (response);
123    }
124
125  if (confirm_file_EOF)
126    {
127      fputc ('\n', stdlis);
128      fflush (stdlis);
129    }
130
131  return status;
132}
133
134static struct fmttab {
135  char const *name;
136  enum archive_format fmt;
137} const fmttab[] = {
138  { "v7",      V7_FORMAT },
139  { "oldgnu",  OLDGNU_FORMAT },
140  { "ustar",   USTAR_FORMAT },
141  { "posix",   POSIX_FORMAT },
142#if 0 /* not fully supported yet */
143  { "star",    STAR_FORMAT },
144#endif
145  { "gnu",     GNU_FORMAT },
146  { "pax",     POSIX_FORMAT }, /* An alias for posix */
147  { NULL,      0 }
148};
149
150static void
151set_archive_format (char const *name)
152{
153  struct fmttab const *p;
154
155  for (p = fmttab; strcmp (p->name, name) != 0; )
156    if (! (++p)->name)
157      USAGE_ERROR ((0, 0, _("%s: Invalid archive format"),
158		    quotearg_colon (name)));
159
160  archive_format = p->fmt;
161}
162
163const char *
164archive_format_string (enum archive_format fmt)
165{
166  struct fmttab const *p;
167
168  for (p = fmttab; p->name; p++)
169    if (p->fmt == fmt)
170      return p->name;
171  return "unknown?";
172}
173
174#define FORMAT_MASK(n) (1<<(n))
175
176static void
177assert_format(unsigned fmt_mask)
178{
179  if ((FORMAT_MASK (archive_format) & fmt_mask) == 0)
180    USAGE_ERROR ((0, 0,
181		  _("GNU features wanted on incompatible archive format")));
182}
183
184const char *
185subcommand_string (enum subcommand c)
186{
187  switch (c)
188    {
189    case UNKNOWN_SUBCOMMAND:
190      return "unknown?";
191
192    case APPEND_SUBCOMMAND:
193      return "-r";
194
195    case CAT_SUBCOMMAND:
196      return "-A";
197
198    case CREATE_SUBCOMMAND:
199      return "-c";
200
201    case DELETE_SUBCOMMAND:
202      return "-D";
203
204    case DIFF_SUBCOMMAND:
205      return "-d";
206
207    case EXTRACT_SUBCOMMAND:
208      return "-x";
209
210    case LIST_SUBCOMMAND:
211      return "-t";
212
213    case UPDATE_SUBCOMMAND:
214      return "-u";
215
216    default:
217      abort ();
218    }
219}
220
221void
222tar_list_quoting_styles (argp_fmtstream_t fs, char *prefix)
223{
224  int i;
225
226  for (i = 0; quoting_style_args[i]; i++)
227    argp_fmtstream_printf (fs, "%s%s\n", prefix, quoting_style_args[i]);
228}
229
230void
231tar_set_quoting_style (char *arg)
232{
233  int i;
234
235  for (i = 0; quoting_style_args[i]; i++)
236    if (strcmp (arg, quoting_style_args[i]) == 0)
237      {
238	set_quoting_style (NULL, i);
239	return;
240      }
241  FATAL_ERROR ((0, 0,
242		_("Unknown quoting style `%s'. Try `%s --quoting-style=help' to get a list."), arg, program_invocation_short_name));
243}
244
245
246/* Options.  */
247
248enum
249{
250  ANCHORED_OPTION = CHAR_MAX + 1,
251  ATIME_PRESERVE_OPTION,
252  BACKUP_OPTION,
253  CHECKPOINT_OPTION,
254  DELAY_DIRECTORY_RESTORE_OPTION,
255  DELETE_OPTION,
256  EXCLUDE_CACHES_OPTION,
257  EXCLUDE_CACHES_UNDER_OPTION,
258  EXCLUDE_CACHES_ALL_OPTION,
259  EXCLUDE_OPTION,
260  EXCLUDE_TAG_OPTION,
261  EXCLUDE_TAG_UNDER_OPTION,
262  EXCLUDE_TAG_ALL_OPTION,
263  FORCE_LOCAL_OPTION,
264  GROUP_OPTION,
265  HANG_OPTION,
266  IGNORE_CASE_OPTION,
267  IGNORE_COMMAND_ERROR_OPTION,
268  IGNORE_FAILED_READ_OPTION,
269  INDEX_FILE_OPTION,
270  KEEP_NEWER_FILES_OPTION,
271  MODE_OPTION,
272  MTIME_OPTION,
273  NEWER_MTIME_OPTION,
274  NO_ANCHORED_OPTION,
275  NO_DELAY_DIRECTORY_RESTORE_OPTION,
276  NO_IGNORE_CASE_OPTION,
277  NO_IGNORE_COMMAND_ERROR_OPTION,
278  NO_OVERWRITE_DIR_OPTION,
279  NO_QUOTE_CHARS_OPTION,
280  NO_RECURSION_OPTION,
281  NO_SAME_OWNER_OPTION,
282  NO_SAME_PERMISSIONS_OPTION,
283  NO_UNQUOTE_OPTION,
284  NO_WILDCARDS_MATCH_SLASH_OPTION,
285  NO_WILDCARDS_OPTION,
286  NULL_OPTION,
287  NUMERIC_OWNER_OPTION,
288  OCCURRENCE_OPTION,
289  OLD_ARCHIVE_OPTION,
290  ONE_FILE_SYSTEM_OPTION,
291  OVERWRITE_DIR_OPTION,
292  OVERWRITE_OPTION,
293  OWNER_OPTION,
294  PAX_OPTION,
295  POSIX_OPTION,
296  PRESERVE_OPTION,
297  QUOTE_CHARS_OPTION,
298  QUOTING_STYLE_OPTION,
299  RECORD_SIZE_OPTION,
300  RECURSION_OPTION,
301  RECURSIVE_UNLINK_OPTION,
302  REMOVE_FILES_OPTION,
303  RESTRICT_OPTION,
304  RMT_COMMAND_OPTION,
305  RSH_COMMAND_OPTION,
306  SAME_OWNER_OPTION,
307  SHOW_DEFAULTS_OPTION,
308  SHOW_OMITTED_DIRS_OPTION,
309  SHOW_TRANSFORMED_NAMES_OPTION,
310  SPARSE_VERSION_OPTION,
311  STRIP_COMPONENTS_OPTION,
312  SUFFIX_OPTION,
313  TEST_LABEL_OPTION,
314  TOTALS_OPTION,
315  TO_COMMAND_OPTION,
316  TRANSFORM_OPTION,
317  UNQUOTE_OPTION,
318  USAGE_OPTION,
319  USE_COMPRESS_PROGRAM_OPTION,
320  UTC_OPTION,
321  VERSION_OPTION,
322  VOLNO_FILE_OPTION,
323  WILDCARDS_MATCH_SLASH_OPTION,
324  WILDCARDS_OPTION
325};
326
327const char *argp_program_version = "tar (" PACKAGE_NAME ") " VERSION;
328const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
329static char const doc[] = N_("\
330GNU `tar' saves many files together into a single tape or disk archive, \
331and can restore individual files from the archive.\n\
332\n\
333Examples:\n\
334  tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.\n\
335  tar -tvf archive.tar         # List all files in archive.tar verbosely.\n\
336  tar -xf archive.tar          # Extract all files from archive.tar.\n")
337"\v"
338N_("The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
339The version control may be set with --backup or VERSION_CONTROL, values are:\n\n\
340  none, off       never make backups\n\
341  t, numbered     make numbered backups\n\
342  nil, existing   numbered if numbered backups exist, simple otherwise\n\
343  never, simple   always make simple backups\n");
344
345
346/* NOTE:
347
348   Available option letters are DEIJQY and aeqy. Consider the following
349   assignments:
350
351   [For Solaris tar compatibility =/= Is it important at all?]
352   e  exit immediately with a nonzero exit status if unexpected errors occur
353   E  use extended headers (--format=posix)
354
355   [q  alias for --occurrence=1 =/= this would better be used for quiet?]
356   [I  same as T =/= will harm star compatibility]
357
358   y  per-file gzip compression
359   Y  per-block gzip compression */
360
361static struct argp_option options[] = {
362#define GRID 10
363  {NULL, 0, NULL, 0,
364   N_("Main operation mode:"), GRID },
365
366  {"list", 't', 0, 0,
367   N_("list the contents of an archive"), GRID+1 },
368  {"extract", 'x', 0, 0,
369   N_("extract files from an archive"), GRID+1 },
370  {"get", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
371  {"create", 'c', 0, 0,
372   N_("create a new archive"), GRID+1 },
373  {"diff", 'd', 0, 0,
374   N_("find differences between archive and file system"), GRID+1 },
375  {"compare", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
376  {"append", 'r', 0, 0,
377   N_("append files to the end of an archive"), GRID+1 },
378  {"update", 'u', 0, 0,
379   N_("only append files newer than copy in archive"), GRID+1 },
380  {"catenate", 'A', 0, 0,
381   N_("append tar files to an archive"), GRID+1 },
382  {"concatenate", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
383  {"delete", DELETE_OPTION, 0, 0,
384   N_("delete from the archive (not on mag tapes!)"), GRID+1 },
385  {"test-label", TEST_LABEL_OPTION, NULL, 0,
386   N_("test the archive volume label and exit"), GRID+1 },
387#undef GRID
388
389#define GRID 20
390  {NULL, 0, NULL, 0,
391   N_("Operation modifiers:"), GRID },
392
393  {"sparse", 'S', 0, 0,
394   N_("handle sparse files efficiently"), GRID+1 },
395  {"sparse-version", SPARSE_VERSION_OPTION, N_("MAJOR[.MINOR]"), 0,
396   N_("set version of the sparse format to use (implies --sparse)"), GRID+1},
397  {"incremental", 'G', 0, 0,
398   N_("handle old GNU-format incremental backup"), GRID+1 },
399  {"listed-incremental", 'g', N_("FILE"), 0,
400   N_("handle new GNU-format incremental backup"), GRID+1 },
401  {"ignore-failed-read", IGNORE_FAILED_READ_OPTION, 0, 0,
402   N_("do not exit with nonzero on unreadable files"), GRID+1 },
403  {"occurrence", OCCURRENCE_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL,
404   N_("process only the NUMBERth occurrence of each file in the archive;"
405      " this option is valid only in conjunction with one of the subcommands"
406      " --delete, --diff, --extract or --list and when a list of files"
407      " is given either on the command line or via the -T option;"
408      " NUMBER defaults to 1"), GRID+1 },
409  {"seek", 'n', NULL, 0,
410   N_("archive is seekable"), GRID+1 },
411#undef GRID
412
413#define GRID 30
414  {NULL, 0, NULL, 0,
415   N_("Overwrite control:"), GRID },
416
417  {"verify", 'W', 0, 0,
418   N_("attempt to verify the archive after writing it"), GRID+1 },
419  {"remove-files", REMOVE_FILES_OPTION, 0, 0,
420   N_("remove files after adding them to the archive"), GRID+1 },
421  {"keep-old-files", 'k', 0, 0,
422   N_("don't replace existing files when extracting"), GRID+1 },
423  {"keep-newer-files", KEEP_NEWER_FILES_OPTION, 0, 0,
424   N_("don't replace existing files that are newer than their archive copies"), GRID+1 },
425  {"overwrite", OVERWRITE_OPTION, 0, 0,
426   N_("overwrite existing files when extracting"), GRID+1 },
427  {"unlink-first", 'U', 0, 0,
428   N_("remove each file prior to extracting over it"), GRID+1 },
429  {"recursive-unlink", RECURSIVE_UNLINK_OPTION, 0, 0,
430   N_("empty hierarchies prior to extracting directory"), GRID+1 },
431  {"no-overwrite-dir", NO_OVERWRITE_DIR_OPTION, 0, 0,
432   N_("preserve metadata of existing directories"), GRID+1 },
433  {"overwrite-dir", OVERWRITE_DIR_OPTION, 0, 0,
434   N_("overwrite metadata of existing directories when extracting (default)"),
435   GRID+1 },
436#undef GRID
437
438#define GRID 40
439  {NULL, 0, NULL, 0,
440   N_("Select output stream:"), GRID },
441
442  {"to-stdout", 'O', 0, 0,
443   N_("extract files to standard output"), GRID+1 },
444  {"to-command", TO_COMMAND_OPTION, N_("COMMAND"), 0,
445   N_("pipe extracted files to another program"), GRID+1 },
446  {"ignore-command-error", IGNORE_COMMAND_ERROR_OPTION, 0, 0,
447   N_("ignore exit codes of children"), GRID+1 },
448  {"no-ignore-command-error", NO_IGNORE_COMMAND_ERROR_OPTION, 0, 0,
449   N_("treat non-zero exit codes of children as error"), GRID+1 },
450#undef GRID
451
452#define GRID 50
453  {NULL, 0, NULL, 0,
454   N_("Handling of file attributes:"), GRID },
455
456  {"owner", OWNER_OPTION, N_("NAME"), 0,
457   N_("force NAME as owner for added files"), GRID+1 },
458  {"group", GROUP_OPTION, N_("NAME"), 0,
459   N_("force NAME as group for added files"), GRID+1 },
460  {"mtime", MTIME_OPTION, N_("DATE-OR-FILE"), 0,
461   N_("set mtime for added files from DATE-OR-FILE"), GRID+1 },
462  {"mode", MODE_OPTION, N_("CHANGES"), 0,
463   N_("force (symbolic) mode CHANGES for added files"), GRID+1 },
464  {"atime-preserve", ATIME_PRESERVE_OPTION,
465   N_("METHOD"), OPTION_ARG_OPTIONAL,
466   N_("preserve access times on dumped files, either by restoring the times"
467      " after reading (METHOD='replace'; default) or by not setting the times"
468      " in the first place (METHOD='system')"), GRID+1 },
469  {"touch", 'm', 0, 0,
470   N_("don't extract file modified time"), GRID+1 },
471  {"same-owner", SAME_OWNER_OPTION, 0, 0,
472   N_("try extracting files with the same ownership"), GRID+1 },
473  {"no-same-owner", NO_SAME_OWNER_OPTION, 0, 0,
474   N_("extract files as yourself"), GRID+1 },
475  {"numeric-owner", NUMERIC_OWNER_OPTION, 0, 0,
476   N_("always use numbers for user/group names"), GRID+1 },
477  {"preserve-permissions", 'p', 0, 0,
478   N_("extract information about file permissions (default for superuser)"),
479   GRID+1 },
480  {"same-permissions", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
481  {"no-same-permissions", NO_SAME_PERMISSIONS_OPTION, 0, 0,
482   N_("apply the user's umask when extracting permissions from the archive (default for ordinary users)"), GRID+1 },
483  {"preserve-order", 's', 0, 0,
484   N_("sort names to extract to match archive"), GRID+1 },
485  {"same-order", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
486  {"preserve", PRESERVE_OPTION, 0, 0,
487   N_("same as both -p and -s"), GRID+1 },
488  {"delay-directory-restore", DELAY_DIRECTORY_RESTORE_OPTION, 0, 0,
489   N_("delay setting modification times and permissions of extracted"
490      " directories until the end of extraction"), GRID+1 },
491  {"no-delay-directory-restore", NO_DELAY_DIRECTORY_RESTORE_OPTION, 0, 0,
492   N_("cancel the effect of --delay-directory-restore option"), GRID+1 },
493#undef GRID
494
495#define GRID 60
496  {NULL, 0, NULL, 0,
497   N_("Device selection and switching:"), GRID },
498
499  {"file", 'f', N_("ARCHIVE"), 0,
500   N_("use archive file or device ARCHIVE"), GRID+1 },
501  {"force-local", FORCE_LOCAL_OPTION, 0, 0,
502   N_("archive file is local even if it has a colon"), GRID+1 },
503  {"rmt-command", RMT_COMMAND_OPTION, N_("COMMAND"), 0,
504   N_("use given rmt COMMAND instead of rmt"), GRID+1 },
505  {"rsh-command", RSH_COMMAND_OPTION, N_("COMMAND"), 0,
506   N_("use remote COMMAND instead of rsh"), GRID+1 },
507#ifdef DEVICE_PREFIX
508  {"-[0-7][lmh]", 0, NULL, OPTION_DOC, /* It is OK, since `name' will never be
509					  translated */
510   N_("specify drive and density"), GRID+1 },
511#endif
512  {NULL, '0', NULL, OPTION_HIDDEN, NULL, GRID+1 },
513  {NULL, '1', NULL, OPTION_HIDDEN, NULL, GRID+1 },
514  {NULL, '2', NULL, OPTION_HIDDEN, NULL, GRID+1 },
515  {NULL, '3', NULL, OPTION_HIDDEN, NULL, GRID+1 },
516  {NULL, '4', NULL, OPTION_HIDDEN, NULL, GRID+1 },
517  {NULL, '5', NULL, OPTION_HIDDEN, NULL, GRID+1 },
518  {NULL, '6', NULL, OPTION_HIDDEN, NULL, GRID+1 },
519  {NULL, '7', NULL, OPTION_HIDDEN, NULL, GRID+1 },
520  {NULL, '8', NULL, OPTION_HIDDEN, NULL, GRID+1 },
521  {NULL, '9', NULL, OPTION_HIDDEN, NULL, GRID+1 },
522
523  {"multi-volume", 'M', 0, 0,
524   N_("create/list/extract multi-volume archive"), GRID+1 },
525  {"tape-length", 'L', N_("NUMBER"), 0,
526   N_("change tape after writing NUMBER x 1024 bytes"), GRID+1 },
527  {"info-script", 'F', N_("NAME"), 0,
528   N_("run script at end of each tape (implies -M)"), GRID+1 },
529  {"new-volume-script", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
530  {"volno-file", VOLNO_FILE_OPTION, N_("FILE"), 0,
531   N_("use/update the volume number in FILE"), GRID+1 },
532#undef GRID
533
534#define GRID 70
535  {NULL, 0, NULL, 0,
536   N_("Device blocking:"), GRID },
537
538  {"blocking-factor", 'b', N_("BLOCKS"), 0,
539   N_("BLOCKS x 512 bytes per record"), GRID+1 },
540  {"record-size", RECORD_SIZE_OPTION, N_("NUMBER"), 0,
541   N_("NUMBER of bytes per record, multiple of 512"), GRID+1 },
542  {"ignore-zeros", 'i', 0, 0,
543   N_("ignore zeroed blocks in archive (means EOF)"), GRID+1 },
544  {"read-full-records", 'B', 0, 0,
545   N_("reblock as we read (for 4.2BSD pipes)"), GRID+1 },
546#undef GRID
547
548#define GRID 80
549  {NULL, 0, NULL, 0,
550   N_("Archive format selection:"), GRID },
551
552  {"format", 'H', N_("FORMAT"), 0,
553   N_("create archive of the given format"), GRID+1 },
554
555  {NULL, 0, NULL, 0, N_("FORMAT is one of the following:"), GRID+2 },
556  {"  v7", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("old V7 tar format"),
557   GRID+3 },
558  {"  oldgnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
559   N_("GNU format as per tar <= 1.12"), GRID+3 },
560  {"  gnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
561   N_("GNU tar 1.13.x format"), GRID+3 },
562  {"  ustar", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
563   N_("POSIX 1003.1-1988 (ustar) format"), GRID+3 },
564  {"  pax", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
565   N_("POSIX 1003.1-2001 (pax) format"), GRID+3 },
566  {"  posix", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("same as pax"), GRID+3 },
567
568  {"old-archive", OLD_ARCHIVE_OPTION, 0, 0, /* FIXME */
569   N_("same as --format=v7"), GRID+8 },
570  {"portability", 0, 0, OPTION_ALIAS, NULL, GRID+8 },
571  {"posix", POSIX_OPTION, 0, 0,
572   N_("same as --format=posix"), GRID+8 },
573  {"pax-option", PAX_OPTION, N_("keyword[[:]=value][,keyword[[:]=value]]..."), 0,
574   N_("control pax keywords"), GRID+8 },
575  {"label", 'V', N_("TEXT"), 0,
576   N_("create archive with volume name TEXT; at list/extract time, use TEXT as a globbing pattern for volume name"), GRID+8 },
577  {"bzip2", 'j', 0, 0,
578   N_("filter the archive through bzip2"), GRID+8 },
579  {"gzip", 'z', 0, 0,
580   N_("filter the archive through gzip"), GRID+8 },
581  {"gunzip", 0, 0, OPTION_ALIAS, NULL, GRID+8 },
582  {"ungzip", 0, 0, OPTION_ALIAS, NULL, GRID+8 },
583  {"compress", 'Z', 0, 0,
584   N_("filter the archive through compress"), GRID+8 },
585  {"uncompress", 0, 0, OPTION_ALIAS, NULL, GRID+8 },
586  {"use-compress-program", USE_COMPRESS_PROGRAM_OPTION, N_("PROG"), 0,
587   N_("filter through PROG (must accept -d)"), GRID+8 },
588#undef GRID
589
590#define GRID 90
591  {NULL, 0, NULL, 0,
592   N_("Local file selection:"), GRID },
593
594  {"add-file", ARGP_KEY_ARG, N_("FILE"), 0,
595   N_("add given FILE to the archive (useful if its name starts with a dash)"), GRID+1 },
596  {"directory", 'C', N_("DIR"), 0,
597   N_("change to directory DIR"), GRID+1 },
598  {"files-from", 'T', N_("FILE"), 0,
599   N_("get names to extract or create from FILE"), GRID+1 },
600  {"null", NULL_OPTION, 0, 0,
601   N_("-T reads null-terminated names, disable -C"), GRID+1 },
602  {"unquote", UNQUOTE_OPTION, 0, 0,
603   N_("unquote filenames read with -T (default)"), GRID+1 },
604  {"no-unquote", NO_UNQUOTE_OPTION, 0, 0,
605   N_("do not unquote filenames read with -T"), GRID+1 },
606  {"exclude", EXCLUDE_OPTION, N_("PATTERN"), 0,
607   N_("exclude files, given as a PATTERN"), GRID+1 },
608  {"exclude-from", 'X', N_("FILE"), 0,
609   N_("exclude patterns listed in FILE"), GRID+1 },
610  {"exclude-caches", EXCLUDE_CACHES_OPTION, 0, 0,
611   N_("exclude contents of directories containing CACHEDIR.TAG, "
612      "except for the tag file itself"), GRID+1 },
613  {"exclude-caches-under", EXCLUDE_CACHES_UNDER_OPTION, 0, 0,
614   N_("exclude everything under directories containing CACHEDIR.TAG"),
615   GRID+1 },
616  {"exclude-caches-all", EXCLUDE_CACHES_ALL_OPTION, 0, 0,
617   N_("exclude directories containing CACHEDIR.TAG"), GRID+1 },
618  {"exclude-tag", EXCLUDE_TAG_OPTION, N_("FILE"), 0,
619   N_("exclude contents of directories containing FILE, except"
620      " for FILE itself"), GRID+1 },
621  {"exclude-tag-under", EXCLUDE_TAG_UNDER_OPTION, N_("FILE"), 0,
622   N_("exclude everything under directories containing FILE"), GRID+1 },
623  {"exclude-tag-all", EXCLUDE_TAG_ALL_OPTION, N_("FILE"), 0,
624   N_("exclude directories containing FILE"), GRID+1 },
625  {"no-recursion", NO_RECURSION_OPTION, 0, 0,
626   N_("avoid descending automatically in directories"), GRID+1 },
627  {"one-file-system", ONE_FILE_SYSTEM_OPTION, 0, 0,
628   N_("stay in local file system when creating archive"), GRID+1 },
629  {"recursion", RECURSION_OPTION, 0, 0,
630   N_("recurse into directories (default)"), GRID+1 },
631  {"absolute-names", 'P', 0, 0,
632   N_("don't strip leading `/'s from file names"), GRID+1 },
633  {"dereference", 'h', 0, 0,
634   N_("follow symlinks; archive and dump the files they point to"), GRID+1 },
635  {"starting-file", 'K', N_("MEMBER-NAME"), 0,
636   N_("begin at member MEMBER-NAME in the archive"), GRID+1 },
637  {"newer", 'N', N_("DATE-OR-FILE"), 0,
638   N_("only store files newer than DATE-OR-FILE"), GRID+1 },
639  {"after-date", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
640  {"newer-mtime", NEWER_MTIME_OPTION, N_("DATE"), 0,
641   N_("compare date and time when data changed only"), GRID+1 },
642  {"backup", BACKUP_OPTION, N_("CONTROL"), OPTION_ARG_OPTIONAL,
643   N_("backup before removal, choose version CONTROL"), GRID+1 },
644  {"suffix", SUFFIX_OPTION, N_("STRING"), 0,
645   N_("backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX)"), GRID+1 },
646#undef GRID
647
648#define GRID 92
649  {NULL, 0, NULL, 0,
650   N_("File name transformations:"), GRID },
651  {"strip-components", STRIP_COMPONENTS_OPTION, N_("NUMBER"), 0,
652   N_("strip NUMBER leading components from file names on extraction"),
653   GRID+1 },
654  {"transform", TRANSFORM_OPTION, N_("EXPRESSION"), 0,
655   N_("use sed replace EXPRESSION to transform file names"), GRID+1 },
656#undef GRID
657
658#define GRID 95
659  {NULL, 0, NULL, 0,
660   N_("File name matching options (affect both exclude and include patterns):"),
661   GRID },
662  {"ignore-case", IGNORE_CASE_OPTION, 0, 0,
663   N_("ignore case"), GRID+1 },
664  {"anchored", ANCHORED_OPTION, 0, 0,
665   N_("patterns match file name start"), GRID+1 },
666  {"no-anchored", NO_ANCHORED_OPTION, 0, 0,
667   N_("patterns match after any `/' (default for exclusion)"), GRID+1 },
668  {"no-ignore-case", NO_IGNORE_CASE_OPTION, 0, 0,
669   N_("case sensitive matching (default)"), GRID+1 },
670  {"wildcards", WILDCARDS_OPTION, 0, 0,
671   N_("use wildcards (default for exclusion)"), GRID+1 },
672  {"no-wildcards", NO_WILDCARDS_OPTION, 0, 0,
673   N_("verbatim string matching"), GRID+1 },
674  {"no-wildcards-match-slash", NO_WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
675   N_("wildcards do not match `/'"), GRID+1 },
676  {"wildcards-match-slash", WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
677   N_("wildcards match `/' (default for exclusion)"), GRID+1 },
678#undef GRID
679
680#define GRID 100
681  {NULL, 0, NULL, 0,
682   N_("Informative output:"), GRID },
683
684  {"verbose", 'v', 0, 0,
685   N_("verbosely list files processed"), GRID+1 },
686  {"checkpoint", CHECKPOINT_OPTION, N_("[.]NUMBER"), OPTION_ARG_OPTIONAL,
687   N_("display progress messages every NUMBERth record (default 10)"),
688   GRID+1 },
689  {"check-links", 'l', 0, 0,
690   N_("print a message if not all links are dumped"), GRID+1 },
691  {"totals", TOTALS_OPTION, N_("SIGNAL"), OPTION_ARG_OPTIONAL,
692   N_("print total bytes after processing the archive; "
693      "with an argument - print total bytes when this SIGNAL is delivered; "
694      "Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; "
695      "the names without SIG prefix are also accepted"), GRID+1 },
696  {"utc", UTC_OPTION, 0, 0,
697   N_("print file modification dates in UTC"), GRID+1 },
698  {"index-file", INDEX_FILE_OPTION, N_("FILE"), 0,
699   N_("send verbose output to FILE"), GRID+1 },
700  {"block-number", 'R', 0, 0,
701   N_("show block number within archive with each message"), GRID+1 },
702  {"interactive", 'w', 0, 0,
703   N_("ask for confirmation for every action"), GRID+1 },
704  {"confirmation", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
705  {"show-defaults", SHOW_DEFAULTS_OPTION, 0, 0,
706   N_("show tar defaults"), GRID+1 },
707  {"show-omitted-dirs", SHOW_OMITTED_DIRS_OPTION, 0, 0,
708   N_("when listing or extracting, list each directory that does not match search criteria"), GRID+1 },
709  {"show-transformed-names", SHOW_TRANSFORMED_NAMES_OPTION, 0, 0,
710   N_("show file or archive names after transformation"),
711   GRID+1 },
712  {"show-stored-names", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
713  {"quoting-style", QUOTING_STYLE_OPTION, N_("STYLE"), 0,
714   N_("set name quoting style; see below for valid STYLE values"), GRID+1 },
715  {"quote-chars", QUOTE_CHARS_OPTION, N_("STRING"), 0,
716   N_("additionally quote characters from STRING"), GRID+1 },
717  {"no-quote-chars", NO_QUOTE_CHARS_OPTION, N_("STRING"), 0,
718   N_("disable quoting for characters from STRING"), GRID+1 },
719#undef GRID
720
721#define GRID 110
722  {NULL, 0, NULL, 0,
723   N_("Compatibility options:"), GRID },
724
725  {NULL, 'o', 0, 0,
726   N_("when creating, same as --old-archive; when extracting, same as --no-same-owner"), GRID+1 },
727#undef GRID
728
729#define GRID 120
730  {NULL, 0, NULL, 0,
731   N_("Other options:"), GRID },
732
733  {"restrict", RESTRICT_OPTION, 0, 0,
734   N_("disable use of some potentially harmful options"), -1 },
735
736  {"help",  '?', 0, 0,  N_("give this help list"), -1},
737  {"usage", USAGE_OPTION, 0, 0,  N_("give a short usage message"), -1},
738  {"version", VERSION_OPTION, 0, 0,  N_("print program version"), -1},
739  /* FIXME -V (--label) conflicts with the default short option for
740     --version */
741  {"HANG",	  HANG_OPTION,    "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
742   N_("hang for SECS seconds (default 3600)"), 0},
743#undef GRID
744
745  {0, 0, 0, 0, 0, 0}
746};
747
748static char const *const atime_preserve_args[] =
749{
750  "replace", "system", NULL
751};
752
753static enum atime_preserve const atime_preserve_types[] =
754{
755  replace_atime_preserve, system_atime_preserve
756};
757
758/* Make sure atime_preserve_types has as much entries as atime_preserve_args
759   (minus 1 for NULL guard) */
760ARGMATCH_VERIFY (atime_preserve_args, atime_preserve_types);
761
762/* Wildcard matching settings */
763enum wildcards
764  {
765    default_wildcards, /* For exclusion == enable_wildcards,
766			  for inclusion == disable_wildcards */
767    disable_wildcards,
768    enable_wildcards
769  };
770
771struct tar_args        /* Variables used during option parsing */
772{
773  struct textual_date *textual_date; /* Keeps the arguments to --newer-mtime
774					and/or --date option if they are
775					textual dates */
776  enum wildcards wildcards;        /* Wildcard settings (--wildcards/
777				      --no-wildcards) */
778  int matching_flags;              /* exclude_fnmatch options */
779  int include_anchored;            /* Pattern anchoring options used for
780				      file inclusion */
781  bool o_option;                   /* True if -o option was given */
782  bool pax_option;                 /* True if --pax-option was given */
783  char const *backup_suffix_string;   /* --suffix option argument */
784  char const *version_control_string; /* --backup option argument */
785  bool input_files;                /* True if some input files where given */
786};
787
788#define MAKE_EXCL_OPTIONS(args) \
789 ((((args)->wildcards != disable_wildcards) ? EXCLUDE_WILDCARDS : 0) \
790  | (args)->matching_flags \
791  | recursion_option)
792
793#define MAKE_INCL_OPTIONS(args) \
794 ((((args)->wildcards == enable_wildcards) ? EXCLUDE_WILDCARDS : 0) \
795  | (args)->include_anchored \
796  | (args)->matching_flags \
797  | recursion_option)
798
799#ifdef REMOTE_SHELL
800# define DECL_SHOW_DEFAULT_SETTINGS(stream, printer)                      \
801{                                                                         \
802  printer (stream,                                                        \
803	   "--format=%s -f%s -b%d --quoting-style=%s --rmt-command=%s",   \
804	   archive_format_string (DEFAULT_ARCHIVE_FORMAT),                \
805	   DEFAULT_ARCHIVE, DEFAULT_BLOCKING,                             \
806	   quoting_style_args[DEFAULT_QUOTING_STYLE],                     \
807	   DEFAULT_RMT_COMMAND);                                          \
808  printer (stream, " --rsh-command=%s", REMOTE_SHELL);                    \
809  printer (stream, "\n");                                                 \
810}
811#else
812# define DECL_SHOW_DEFAULT_SETTINGS(stream, printer)                      \
813{                                                                         \
814  printer (stream,                                                        \
815	   "--format=%s -f%s -b%d --quoting-style=%s --rmt-command=%s",   \
816	   archive_format_string (DEFAULT_ARCHIVE_FORMAT),                \
817	   DEFAULT_ARCHIVE, DEFAULT_BLOCKING,                             \
818	   quoting_style_args[DEFAULT_QUOTING_STYLE],                     \
819	   DEFAULT_RMT_COMMAND);                                          \
820  printer (stream, "\n");                                                 \
821}
822#endif
823
824static void
825show_default_settings (FILE *fp)
826     DECL_SHOW_DEFAULT_SETTINGS(fp, fprintf)
827
828static void
829show_default_settings_fs (argp_fmtstream_t fs)
830     DECL_SHOW_DEFAULT_SETTINGS(fs, argp_fmtstream_printf)
831
832static void
833set_subcommand_option (enum subcommand subcommand)
834{
835  if (subcommand_option != UNKNOWN_SUBCOMMAND
836      && subcommand_option != subcommand)
837    USAGE_ERROR ((0, 0,
838		  _("You may not specify more than one `-Acdtrux' option")));
839
840  subcommand_option = subcommand;
841}
842
843static void
844set_use_compress_program_option (const char *string)
845{
846  if (use_compress_program_option
847      && strcmp (use_compress_program_option, string) != 0)
848    USAGE_ERROR ((0, 0, _("Conflicting compression options")));
849
850  use_compress_program_option = string;
851}
852
853static RETSIGTYPE
854sigstat (int signo)
855{
856  compute_duration ();
857  print_total_stats ();
858#ifndef HAVE_SIGACTION
859  signal (signo, sigstat);
860#endif
861}
862
863static void
864stat_on_signal (int signo)
865{
866#ifdef HAVE_SIGACTION
867  struct sigaction act;
868  act.sa_handler = sigstat;
869  sigemptyset (&act.sa_mask);
870  act.sa_flags = 0;
871  sigaction (signo, &act, NULL);
872#else
873  signal (signo, sigstat);
874#endif
875}
876
877void
878set_stat_signal (const char *name)
879{
880  static struct sigtab
881  {
882    char *name;
883    int signo;
884  } sigtab[] = {
885    { "SIGUSR1", SIGUSR1 },
886    { "USR1", SIGUSR1 },
887    { "SIGUSR2", SIGUSR2 },
888    { "USR2", SIGUSR2 },
889    { "SIGHUP", SIGHUP },
890    { "HUP", SIGHUP },
891    { "SIGINT", SIGINT },
892    { "INT", SIGINT },
893    { "SIGQUIT", SIGQUIT },
894    { "QUIT", SIGQUIT }
895  };
896  struct sigtab *p;
897
898  for (p = sigtab; p < sigtab + sizeof (sigtab) / sizeof (sigtab[0]); p++)
899    if (strcmp (p->name, name) == 0)
900      {
901	stat_on_signal (p->signo);
902	return;
903      }
904  FATAL_ERROR ((0, 0, _("Unknown signal name: %s"), name));
905}
906
907
908struct textual_date
909{
910  struct textual_date *next;
911  struct timespec *ts;
912  const char *option;
913  const char *date;
914};
915
916static void
917get_date_or_file (struct tar_args *args, const char *option,
918		  const char *str, struct timespec *ts)
919{
920  if (FILE_SYSTEM_PREFIX_LEN (str) != 0
921      || ISSLASH (*str)
922      || *str == '.')
923    {
924      struct stat st;
925      if (deref_stat (dereference_option, str, &st) != 0)
926	{
927	  stat_error (str);
928	  USAGE_ERROR ((0, 0, _("Date sample file not found")));
929	}
930      *ts = get_stat_mtime (&st);
931    }
932  else
933    {
934      if (! get_date (ts, str, NULL))
935	{
936	  WARN ((0, 0, _("Substituting %s for unknown date format %s"),
937		 tartime (*ts, false), quote (str)));
938	  ts->tv_nsec = 0;
939	}
940      else
941	{
942	  struct textual_date *p = xmalloc (sizeof (*p));
943	  p->ts = ts;
944	  p->option = option;
945	  p->date = str;
946	  p->next = args->textual_date;
947	  args->textual_date = p;
948	}
949    }
950}
951
952static void
953report_textual_dates (struct tar_args *args)
954{
955  struct textual_date *p;
956  for (p = args->textual_date; p; )
957    {
958      struct textual_date *next = p->next;
959      char const *treated_as = tartime (*p->ts, true);
960      if (strcmp (p->date, treated_as) != 0)
961	WARN ((0, 0, _("Option %s: Treating date `%s' as %s"),
962	       p->option, p->date, treated_as));
963      free (p);
964      p = next;
965    }
966}
967
968
969static volatile int _argp_hang;
970
971enum read_file_list_state  /* Result of reading file name from the list file */
972  {
973    file_list_success,     /* OK, name read successfully */
974    file_list_end,         /* End of list file */
975    file_list_zero,        /* Zero separator encountered where it should not */
976    file_list_skip         /* Empty (zero-length) entry encountered, skip it */
977  };
978
979/* Read from FP a sequence of characters up to FILENAME_TERMINATOR and put them
980   into STK.
981 */
982static enum read_file_list_state
983read_name_from_file (FILE *fp, struct obstack *stk)
984{
985  int c;
986  size_t counter = 0;
987
988  for (c = getc (fp); c != EOF && c != filename_terminator; c = getc (fp))
989    {
990      if (c == 0)
991	{
992	  /* We have read a zero separator. The file possibly is
993	     zero-separated */
994	  return file_list_zero;
995	}
996      obstack_1grow (stk, c);
997      counter++;
998    }
999
1000  if (counter == 0 && c != EOF)
1001    return file_list_skip;
1002
1003  obstack_1grow (stk, 0);
1004
1005  return (counter == 0 && c == EOF) ? file_list_end : file_list_success;
1006}
1007
1008
1009static bool files_from_option;  /* When set, tar will not refuse to create
1010				   empty archives */
1011static struct obstack argv_stk; /* Storage for additional command line options
1012				   read using -T option */
1013
1014/* Prevent recursive inclusion of the same file */
1015struct file_id_list
1016{
1017  struct file_id_list *next;
1018  ino_t ino;
1019  dev_t dev;
1020};
1021
1022static struct file_id_list *file_id_list;
1023
1024static void
1025add_file_id (const char *filename)
1026{
1027  struct file_id_list *p;
1028  struct stat st;
1029
1030  if (stat (filename, &st))
1031    stat_fatal (filename);
1032  for (p = file_id_list; p; p = p->next)
1033    if (p->ino == st.st_ino && p->dev == st.st_dev)
1034      {
1035	FATAL_ERROR ((0, 0, _("%s: file list already read"),
1036		      quotearg_colon (filename)));
1037      }
1038  p = xmalloc (sizeof *p);
1039  p->next = file_id_list;
1040  p->ino = st.st_ino;
1041  p->dev = st.st_dev;
1042  file_id_list = p;
1043}
1044
1045/* Default density numbers for [0-9][lmh] device specifications */
1046
1047#ifndef LOW_DENSITY_NUM
1048# define LOW_DENSITY_NUM 0
1049#endif
1050
1051#ifndef MID_DENSITY_NUM
1052# define MID_DENSITY_NUM 8
1053#endif
1054
1055#ifndef HIGH_DENSITY_NUM
1056# define HIGH_DENSITY_NUM 16
1057#endif
1058
1059static void
1060update_argv (const char *filename, struct argp_state *state)
1061{
1062  FILE *fp;
1063  size_t count = 0, i;
1064  char *start, *p;
1065  char **new_argv;
1066  size_t new_argc;
1067  bool is_stdin = false;
1068  enum read_file_list_state read_state;
1069
1070  if (!strcmp (filename, "-"))
1071    {
1072      is_stdin = true;
1073      request_stdin ("-T");
1074      fp = stdin;
1075    }
1076  else
1077    {
1078      add_file_id (filename);
1079      if ((fp = fopen (filename, "r")) == NULL)
1080	open_fatal (filename);
1081    }
1082
1083  while ((read_state = read_name_from_file (fp, &argv_stk)) != file_list_end)
1084    {
1085      switch (read_state)
1086	{
1087	case file_list_success:
1088	  count++;
1089	  break;
1090
1091	case file_list_end: /* won't happen, just to pacify gcc */
1092	  break;
1093
1094	case file_list_zero:
1095	  {
1096	    size_t size;
1097
1098	    WARN ((0, 0, N_("%s: file name read contains nul character"),
1099		   quotearg_colon (filename)));
1100
1101	    /* Prepare new stack contents */
1102	    size = obstack_object_size (&argv_stk);
1103	    p = obstack_finish (&argv_stk);
1104	    for (; size > 0; size--, p++)
1105	      if (*p)
1106		obstack_1grow (&argv_stk, *p);
1107	      else
1108		obstack_1grow (&argv_stk, '\n');
1109	    obstack_1grow (&argv_stk, 0);
1110	    count = 1;
1111	    /* Read rest of files using new filename terminator */
1112	    filename_terminator = 0;
1113	    break;
1114	  }
1115
1116	case file_list_skip:
1117	  break;
1118	}
1119    }
1120
1121  if (!is_stdin)
1122    fclose (fp);
1123
1124  if (count == 0)
1125    return;
1126
1127  start = obstack_finish (&argv_stk);
1128
1129  if (filename_terminator == 0)
1130    for (p = start; *p; p += strlen (p) + 1)
1131      if (p[0] == '-')
1132	count++;
1133
1134  new_argc = state->argc + count;
1135  new_argv = xmalloc (sizeof (state->argv[0]) * (new_argc + 1));
1136  memcpy (new_argv, state->argv, sizeof (state->argv[0]) * (state->argc + 1));
1137  state->argv = new_argv;
1138  memmove (&state->argv[state->next + count], &state->argv[state->next],
1139	   (state->argc - state->next + 1) * sizeof (state->argv[0]));
1140
1141  state->argc = new_argc;
1142
1143  for (i = state->next, p = start; *p; p += strlen (p) + 1, i++)
1144    {
1145      if (filename_terminator == 0 && p[0] == '-')
1146	state->argv[i++] = "--add-file";
1147      state->argv[i] = p;
1148    }
1149}
1150
1151
1152static void
1153tar_help (struct argp_state *state)
1154{
1155  argp_fmtstream_t fs;
1156  state->flags |= ARGP_NO_EXIT;
1157  argp_state_help (state, state->out_stream,
1158		   ARGP_HELP_STD_HELP & ~ARGP_HELP_BUG_ADDR);
1159  /* FIXME: use struct uparams.rmargin (from argp-help.c) instead of 79 */
1160  fs = argp_make_fmtstream (state->out_stream, 0, 79, 0);
1161
1162  argp_fmtstream_printf (fs, "\n%s\n\n",
1163		       _("Valid arguments for --quoting-style options are:"));
1164  tar_list_quoting_styles (fs, "  ");
1165
1166  argp_fmtstream_puts (fs, _("\n*This* tar defaults to:\n"));
1167  show_default_settings_fs (fs);
1168  argp_fmtstream_putc (fs, '\n');
1169  argp_fmtstream_printf (fs, _("Report bugs to %s.\n"),
1170			 argp_program_bug_address);
1171  argp_fmtstream_free (fs);
1172}
1173
1174static error_t
1175parse_opt (int key, char *arg, struct argp_state *state)
1176{
1177  struct tar_args *args = state->input;
1178
1179  switch (key)
1180    {
1181    case ARGP_KEY_ARG:
1182      /* File name or non-parsed option, because of ARGP_IN_ORDER */
1183      name_add_name (arg, MAKE_INCL_OPTIONS (args));
1184      args->input_files = true;
1185      break;
1186
1187    case 'A':
1188      set_subcommand_option (CAT_SUBCOMMAND);
1189      break;
1190
1191    case 'b':
1192      {
1193	uintmax_t u;
1194	if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1195	       && u == (blocking_factor = u)
1196	       && 0 < blocking_factor
1197	       && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE))
1198	  USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1199			_("Invalid blocking factor")));
1200      }
1201      break;
1202
1203    case 'B':
1204      /* Try to reblock input records.  For reading 4.2BSD pipes.  */
1205
1206      /* It would surely make sense to exchange -B and -R, but it seems
1207	 that -B has been used for a long while in Sun tar and most
1208	 BSD-derived systems.  This is a consequence of the block/record
1209	 terminology confusion.  */
1210
1211      read_full_records_option = true;
1212      break;
1213
1214    case 'c':
1215      set_subcommand_option (CREATE_SUBCOMMAND);
1216      break;
1217
1218    case 'C':
1219      name_add_dir (arg);
1220      break;
1221
1222    case 'd':
1223      set_subcommand_option (DIFF_SUBCOMMAND);
1224      break;
1225
1226    case 'f':
1227      if (archive_names == allocated_archive_names)
1228	archive_name_array = x2nrealloc (archive_name_array,
1229					 &allocated_archive_names,
1230					 sizeof (archive_name_array[0]));
1231
1232      archive_name_array[archive_names++] = arg;
1233      break;
1234
1235    case 'F':
1236      /* Since -F is only useful with -M, make it implied.  Run this
1237	 script at the end of each tape.  */
1238
1239      info_script_option = arg;
1240      multi_volume_option = true;
1241      break;
1242
1243    case 'g':
1244      listed_incremental_option = arg;
1245      after_date_option = true;
1246      /* Fall through.  */
1247
1248    case 'G':
1249      /* We are making an incremental dump (FIXME: are we?); save
1250	 directories at the beginning of the archive, and include in each
1251	 directory its contents.  */
1252
1253      incremental_option = true;
1254      break;
1255
1256    case 'h':
1257      /* Follow symbolic links.  */
1258      dereference_option = true;
1259      break;
1260
1261    case 'i':
1262      /* Ignore zero blocks (eofs).  This can't be the default,
1263	 because Unix tar writes two blocks of zeros, then pads out
1264	 the record with garbage.  */
1265
1266      ignore_zeros_option = true;
1267      break;
1268
1269    case 'I':
1270      USAGE_ERROR ((0, 0,
1271		    _("Warning: the -I option is not supported;"
1272		      " perhaps you meant -j or -T?")));
1273      break;
1274
1275    case 'j':
1276      set_use_compress_program_option ("bzip2");
1277      break;
1278
1279    case 'k':
1280      /* Don't replace existing files.  */
1281      old_files_option = KEEP_OLD_FILES;
1282      break;
1283
1284    case 'K':
1285      starting_file_option = true;
1286      addname (arg, 0);
1287      break;
1288
1289    case ONE_FILE_SYSTEM_OPTION:
1290      /* When dumping directories, don't dump files/subdirectories
1291	 that are on other filesystems. */
1292      one_file_system_option = true;
1293      break;
1294
1295    case 'l':
1296      check_links_option = 1;
1297      break;
1298
1299    case 'L':
1300      {
1301	uintmax_t u;
1302	if (xstrtoumax (arg, 0, 10, &u, "") != LONGINT_OK)
1303	  USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1304			_("Invalid tape length")));
1305	tape_length_option = 1024 * (tarlong) u;
1306	multi_volume_option = true;
1307      }
1308      break;
1309
1310    case 'm':
1311      touch_option = true;
1312      break;
1313
1314    case 'M':
1315      /* Make multivolume archive: when we can't write any more into
1316	 the archive, re-open it, and continue writing.  */
1317
1318      multi_volume_option = true;
1319      break;
1320
1321    case MTIME_OPTION:
1322      get_date_or_file (args, "--mtime", arg, &mtime_option);
1323      set_mtime_option = true;
1324      break;
1325
1326    case 'n':
1327      seekable_archive = true;
1328      break;
1329
1330    case 'N':
1331      after_date_option = true;
1332      /* Fall through.  */
1333
1334    case NEWER_MTIME_OPTION:
1335      if (NEWER_OPTION_INITIALIZED (newer_mtime_option))
1336	USAGE_ERROR ((0, 0, _("More than one threshold date")));
1337      get_date_or_file (args,
1338			key == NEWER_MTIME_OPTION ? "--newer-mtime"
1339			  : "--after-date", arg, &newer_mtime_option);
1340      break;
1341
1342    case 'o':
1343      args->o_option = true;
1344      break;
1345
1346    case 'O':
1347      to_stdout_option = true;
1348      break;
1349
1350    case 'p':
1351      same_permissions_option = true;
1352      break;
1353
1354    case 'P':
1355      absolute_names_option = true;
1356      break;
1357
1358    case 'r':
1359      set_subcommand_option (APPEND_SUBCOMMAND);
1360      break;
1361
1362    case 'R':
1363      /* Print block numbers for debugging bad tar archives.  */
1364
1365      /* It would surely make sense to exchange -B and -R, but it seems
1366	 that -B has been used for a long while in Sun tar and most
1367	 BSD-derived systems.  This is a consequence of the block/record
1368	 terminology confusion.  */
1369
1370      block_number_option = true;
1371      break;
1372
1373    case 's':
1374      /* Names to extract are sorted.  */
1375
1376      same_order_option = true;
1377      break;
1378
1379    case 'S':
1380      sparse_option = true;
1381      break;
1382
1383    case SPARSE_VERSION_OPTION:
1384      sparse_option = true;
1385      {
1386	char *p;
1387	tar_sparse_major = strtoul (arg, &p, 10);
1388	if (*p)
1389	  {
1390	    if (*p != '.')
1391	      USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1392	    tar_sparse_minor = strtoul (p + 1, &p, 10);
1393	    if (*p)
1394	      USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1395	  }
1396      }
1397      break;
1398
1399    case 't':
1400      set_subcommand_option (LIST_SUBCOMMAND);
1401      verbose_option++;
1402      break;
1403
1404    case TEST_LABEL_OPTION:
1405      set_subcommand_option (LIST_SUBCOMMAND);
1406      test_label_option = true;
1407      break;
1408
1409    case 'T':
1410      update_argv (arg, state);
1411      /* Indicate we've been given -T option. This is for backward
1412	 compatibility only, so that `tar cfT archive /dev/null will
1413	 succeed */
1414      files_from_option = true;
1415      break;
1416
1417    case 'u':
1418      set_subcommand_option (UPDATE_SUBCOMMAND);
1419      break;
1420
1421    case 'U':
1422      old_files_option = UNLINK_FIRST_OLD_FILES;
1423      break;
1424
1425    case UTC_OPTION:
1426      utc_option = true;
1427      break;
1428
1429    case 'v':
1430      verbose_option++;
1431      break;
1432
1433    case 'V':
1434      volume_label_option = arg;
1435      break;
1436
1437    case 'w':
1438      interactive_option = true;
1439      break;
1440
1441    case 'W':
1442      verify_option = true;
1443      break;
1444
1445    case 'x':
1446      set_subcommand_option (EXTRACT_SUBCOMMAND);
1447      break;
1448
1449    case 'X':
1450      if (add_exclude_file (add_exclude, excluded, arg,
1451			    MAKE_EXCL_OPTIONS (args), '\n')
1452	  != 0)
1453	{
1454	  int e = errno;
1455	  FATAL_ERROR ((0, e, "%s", quotearg_colon (arg)));
1456	}
1457      break;
1458
1459    case 'z':
1460      set_use_compress_program_option ("gzip");
1461      break;
1462
1463    case 'Z':
1464      set_use_compress_program_option ("compress");
1465      break;
1466
1467    case ANCHORED_OPTION:
1468      args->matching_flags |= EXCLUDE_ANCHORED;
1469      break;
1470
1471    case ATIME_PRESERVE_OPTION:
1472      atime_preserve_option =
1473	(arg
1474	 ? XARGMATCH ("--atime-preserve", arg,
1475		      atime_preserve_args, atime_preserve_types)
1476	 : replace_atime_preserve);
1477      if (! O_NOATIME && atime_preserve_option == system_atime_preserve)
1478	FATAL_ERROR ((0, 0,
1479		      _("--atime-preserve='system' is not supported"
1480			" on this platform")));
1481      break;
1482
1483    case CHECKPOINT_OPTION:
1484      if (arg)
1485	{
1486	  char *p;
1487
1488	  if (*arg == '.')
1489	    {
1490	      checkpoint_style = checkpoint_dot;
1491	      arg++;
1492	    }
1493	  checkpoint_option = strtoul (arg, &p, 0);
1494	  if (*p)
1495	    FATAL_ERROR ((0, 0,
1496			  _("--checkpoint value is not an integer")));
1497	}
1498      else
1499	checkpoint_option = 10;
1500      break;
1501
1502    case BACKUP_OPTION:
1503      backup_option = true;
1504      if (arg)
1505	args->version_control_string = arg;
1506      break;
1507
1508    case DELAY_DIRECTORY_RESTORE_OPTION:
1509      delay_directory_restore_option = true;
1510      break;
1511
1512    case NO_DELAY_DIRECTORY_RESTORE_OPTION:
1513      delay_directory_restore_option = false;
1514      break;
1515
1516    case DELETE_OPTION:
1517      set_subcommand_option (DELETE_SUBCOMMAND);
1518      break;
1519
1520    case EXCLUDE_OPTION:
1521      add_exclude (excluded, arg, MAKE_EXCL_OPTIONS (args));
1522      break;
1523
1524    case EXCLUDE_CACHES_OPTION:
1525      add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_contents,
1526			 cachedir_file_p);
1527      break;
1528
1529    case EXCLUDE_CACHES_UNDER_OPTION:
1530      add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_under,
1531			 cachedir_file_p);
1532      break;
1533
1534    case EXCLUDE_CACHES_ALL_OPTION:
1535      add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_all,
1536			 cachedir_file_p);
1537      break;
1538
1539    case EXCLUDE_TAG_OPTION:
1540      add_exclusion_tag (arg, exclusion_tag_contents, NULL);
1541      break;
1542
1543    case EXCLUDE_TAG_UNDER_OPTION:
1544      add_exclusion_tag (arg, exclusion_tag_under, NULL);
1545      break;
1546
1547    case EXCLUDE_TAG_ALL_OPTION:
1548      add_exclusion_tag (arg, exclusion_tag_all, NULL);
1549      break;
1550
1551    case FORCE_LOCAL_OPTION:
1552      force_local_option = true;
1553      break;
1554
1555    case 'H':
1556      set_archive_format (arg);
1557      break;
1558
1559    case INDEX_FILE_OPTION:
1560      index_file_name = arg;
1561      break;
1562
1563    case IGNORE_CASE_OPTION:
1564      args->matching_flags |= FNM_CASEFOLD;
1565      break;
1566
1567    case IGNORE_COMMAND_ERROR_OPTION:
1568      ignore_command_error_option = true;
1569      break;
1570
1571    case IGNORE_FAILED_READ_OPTION:
1572      ignore_failed_read_option = true;
1573      break;
1574
1575    case KEEP_NEWER_FILES_OPTION:
1576      old_files_option = KEEP_NEWER_FILES;
1577      break;
1578
1579    case GROUP_OPTION:
1580      if (! (strlen (arg) < GNAME_FIELD_SIZE
1581	     && gname_to_gid (arg, &group_option)))
1582	{
1583	  uintmax_t g;
1584	  if (xstrtoumax (arg, 0, 10, &g, "") == LONGINT_OK
1585	      && g == (gid_t) g)
1586	    group_option = g;
1587	  else
1588	    FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1589			  _("%s: Invalid group")));
1590	}
1591      break;
1592
1593    case MODE_OPTION:
1594      mode_option = mode_compile (arg);
1595      if (!mode_option)
1596	FATAL_ERROR ((0, 0, _("Invalid mode given on option")));
1597      initial_umask = umask (0);
1598      umask (initial_umask);
1599      break;
1600
1601    case NO_ANCHORED_OPTION:
1602      args->include_anchored = 0; /* Clear the default for comman line args */
1603      args->matching_flags &= ~ EXCLUDE_ANCHORED;
1604      break;
1605
1606    case NO_IGNORE_CASE_OPTION:
1607      args->matching_flags &= ~ FNM_CASEFOLD;
1608      break;
1609
1610    case NO_IGNORE_COMMAND_ERROR_OPTION:
1611      ignore_command_error_option = false;
1612      break;
1613
1614    case NO_OVERWRITE_DIR_OPTION:
1615      old_files_option = NO_OVERWRITE_DIR_OLD_FILES;
1616      break;
1617
1618    case NO_QUOTE_CHARS_OPTION:
1619      for (;*arg; arg++)
1620	set_char_quoting (NULL, *arg, 0);
1621      break;
1622
1623    case NO_WILDCARDS_OPTION:
1624      args->wildcards = disable_wildcards;
1625      break;
1626
1627    case NO_WILDCARDS_MATCH_SLASH_OPTION:
1628      args->matching_flags |= FNM_FILE_NAME;
1629      break;
1630
1631    case NULL_OPTION:
1632      filename_terminator = '\0';
1633      break;
1634
1635    case NUMERIC_OWNER_OPTION:
1636      numeric_owner_option = true;
1637      break;
1638
1639    case OCCURRENCE_OPTION:
1640      if (!arg)
1641	occurrence_option = 1;
1642      else
1643	{
1644	  uintmax_t u;
1645	  if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK)
1646	    occurrence_option = u;
1647	  else
1648	    FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1649			  _("Invalid number")));
1650	}
1651      break;
1652
1653    case OVERWRITE_DIR_OPTION:
1654      old_files_option = DEFAULT_OLD_FILES;
1655      break;
1656
1657    case OVERWRITE_OPTION:
1658      old_files_option = OVERWRITE_OLD_FILES;
1659      break;
1660
1661    case OWNER_OPTION:
1662      if (! (strlen (arg) < UNAME_FIELD_SIZE
1663	     && uname_to_uid (arg, &owner_option)))
1664	{
1665	  uintmax_t u;
1666	  if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1667	      && u == (uid_t) u)
1668	    owner_option = u;
1669	  else
1670	    FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1671			  _("Invalid owner")));
1672	}
1673      break;
1674
1675    case QUOTE_CHARS_OPTION:
1676      for (;*arg; arg++)
1677	set_char_quoting (NULL, *arg, 1);
1678      break;
1679
1680    case QUOTING_STYLE_OPTION:
1681      tar_set_quoting_style (arg);
1682      break;
1683
1684    case PAX_OPTION:
1685      args->pax_option = true;
1686      xheader_set_option (arg);
1687      break;
1688
1689    case POSIX_OPTION:
1690      set_archive_format ("posix");
1691      break;
1692
1693    case PRESERVE_OPTION:
1694      /* FIXME: What it is good for? */
1695      same_permissions_option = true;
1696      same_order_option = true;
1697      break;
1698
1699    case RECORD_SIZE_OPTION:
1700      {
1701	uintmax_t u;
1702	if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1703	       && u == (size_t) u))
1704	  USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1705			_("Invalid record size")));
1706	record_size = u;
1707	if (record_size % BLOCKSIZE != 0)
1708	  USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
1709			BLOCKSIZE));
1710	blocking_factor = record_size / BLOCKSIZE;
1711      }
1712      break;
1713
1714    case RECURSIVE_UNLINK_OPTION:
1715      recursive_unlink_option = true;
1716      break;
1717
1718    case REMOVE_FILES_OPTION:
1719      remove_files_option = true;
1720      break;
1721
1722    case RESTRICT_OPTION:
1723      restrict_option = true;
1724      break;
1725
1726    case RMT_COMMAND_OPTION:
1727      rmt_command = arg;
1728      break;
1729
1730    case RSH_COMMAND_OPTION:
1731      rsh_command_option = arg;
1732      break;
1733
1734    case SHOW_DEFAULTS_OPTION:
1735      show_default_settings (stdout);
1736      close_stdout ();
1737      exit (0);
1738
1739    case STRIP_COMPONENTS_OPTION:
1740      {
1741	uintmax_t u;
1742	if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1743	       && u == (size_t) u))
1744	  USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1745			_("Invalid number of elements")));
1746	strip_name_components = u;
1747      }
1748      break;
1749
1750    case SHOW_OMITTED_DIRS_OPTION:
1751      show_omitted_dirs_option = true;
1752      break;
1753
1754    case SHOW_TRANSFORMED_NAMES_OPTION:
1755      show_transformed_names_option = true;
1756      break;
1757
1758    case SUFFIX_OPTION:
1759      backup_option = true;
1760      args->backup_suffix_string = arg;
1761      break;
1762
1763    case TO_COMMAND_OPTION:
1764      if (to_command_option)
1765        USAGE_ERROR ((0, 0, _("Only one --to-command option allowed")));
1766      to_command_option = arg;
1767      break;
1768
1769    case TOTALS_OPTION:
1770      if (arg)
1771	set_stat_signal (arg);
1772      else
1773	totals_option = true;
1774      break;
1775
1776    case TRANSFORM_OPTION:
1777      set_transform_expr (arg);
1778      break;
1779
1780    case USE_COMPRESS_PROGRAM_OPTION:
1781      set_use_compress_program_option (arg);
1782      break;
1783
1784    case VOLNO_FILE_OPTION:
1785      volno_file_option = arg;
1786      break;
1787
1788    case WILDCARDS_OPTION:
1789      args->wildcards = enable_wildcards;
1790      break;
1791
1792    case WILDCARDS_MATCH_SLASH_OPTION:
1793      args->matching_flags &= ~ FNM_FILE_NAME;
1794      break;
1795
1796    case NO_RECURSION_OPTION:
1797      recursion_option = 0;
1798      break;
1799
1800    case NO_SAME_OWNER_OPTION:
1801      same_owner_option = -1;
1802      break;
1803
1804    case NO_SAME_PERMISSIONS_OPTION:
1805      same_permissions_option = -1;
1806      break;
1807
1808    case RECURSION_OPTION:
1809      recursion_option = FNM_LEADING_DIR;
1810      break;
1811
1812    case SAME_OWNER_OPTION:
1813      same_owner_option = 1;
1814      break;
1815
1816    case UNQUOTE_OPTION:
1817      unquote_option = true;
1818      break;
1819
1820    case NO_UNQUOTE_OPTION:
1821      unquote_option = false;
1822      break;
1823
1824    case '0':
1825    case '1':
1826    case '2':
1827    case '3':
1828    case '4':
1829    case '5':
1830    case '6':
1831    case '7':
1832
1833#ifdef DEVICE_PREFIX
1834      {
1835	int device = key - '0';
1836	int density;
1837	static char buf[sizeof DEVICE_PREFIX + 10];
1838	char *cursor;
1839
1840	if (arg[1])
1841	  argp_error (state, _("Malformed density argument: %s"), quote (arg));
1842
1843	strcpy (buf, DEVICE_PREFIX);
1844	cursor = buf + strlen (buf);
1845
1846#ifdef DENSITY_LETTER
1847
1848	sprintf (cursor, "%d%c", device, arg[0]);
1849
1850#else /* not DENSITY_LETTER */
1851
1852	switch (arg[0])
1853	  {
1854	  case 'l':
1855	    device += LOW_DENSITY_NUM;
1856	    break;
1857
1858	  case 'm':
1859	    device += MID_DENSITY_NUM;
1860	    break;
1861
1862	  case 'h':
1863	    device += HIGH_DENSITY_NUM;
1864	    break;
1865
1866	  default:
1867	    argp_error (state, _("Unknown density: `%c'"), arg[0]);
1868	  }
1869	sprintf (cursor, "%d", device);
1870
1871#endif /* not DENSITY_LETTER */
1872
1873	if (archive_names == allocated_archive_names)
1874	  archive_name_array = x2nrealloc (archive_name_array,
1875					   &allocated_archive_names,
1876					   sizeof (archive_name_array[0]));
1877	archive_name_array[archive_names++] = xstrdup (buf);
1878      }
1879      break;
1880
1881#else /* not DEVICE_PREFIX */
1882
1883      argp_error (state,
1884		  _("Options `-[0-7][lmh]' not supported by *this* tar"));
1885
1886#endif /* not DEVICE_PREFIX */
1887
1888    case '?':
1889      tar_help (state);
1890      close_stdout ();
1891      exit (0);
1892
1893    case USAGE_OPTION:
1894      argp_state_help (state, state->out_stream, ARGP_HELP_USAGE);
1895      close_stdout ();
1896      exit (0);
1897
1898    case VERSION_OPTION:
1899      version_etc (state->out_stream, "tar", PACKAGE_NAME, VERSION,
1900		   "John Gilmore", "Jay Fenlason", (char *) NULL);
1901      close_stdout ();
1902      exit (0);
1903
1904    case HANG_OPTION:
1905      _argp_hang = atoi (arg ? arg : "3600");
1906      while (_argp_hang-- > 0)
1907	sleep (1);
1908      break;
1909
1910    default:
1911      return ARGP_ERR_UNKNOWN;
1912    }
1913  return 0;
1914}
1915
1916static struct argp argp = {
1917  options,
1918  parse_opt,
1919  N_("[FILE]..."),
1920  doc,
1921  NULL,
1922  NULL,
1923  NULL
1924};
1925
1926void
1927usage (int status)
1928{
1929  argp_help (&argp, stderr, ARGP_HELP_SEE, (char*) program_name);
1930  close_stdout ();
1931  exit (status);
1932}
1933
1934/* Parse the options for tar.  */
1935
1936static struct argp_option *
1937find_argp_option (struct argp_option *options, int letter)
1938{
1939  for (;
1940       !(options->name == NULL
1941	 && options->key == 0
1942	 && options->arg == 0
1943	 && options->flags == 0
1944	 && options->doc == NULL); options++)
1945    if (options->key == letter)
1946      return options;
1947  return NULL;
1948}
1949
1950static void
1951decode_options (int argc, char **argv)
1952{
1953  int index;
1954  struct tar_args args;
1955
1956  /* Set some default option values.  */
1957  args.textual_date = NULL;
1958  args.wildcards = default_wildcards;
1959  args.matching_flags = 0;
1960  args.include_anchored = EXCLUDE_ANCHORED;
1961  args.o_option = false;
1962  args.pax_option = false;
1963  args.backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
1964  args.version_control_string = 0;
1965  args.input_files = false;
1966
1967  subcommand_option = UNKNOWN_SUBCOMMAND;
1968  archive_format = DEFAULT_FORMAT;
1969  blocking_factor = DEFAULT_BLOCKING;
1970  record_size = DEFAULT_BLOCKING * BLOCKSIZE;
1971  excluded = new_exclude ();
1972  newer_mtime_option.tv_sec = TYPE_MINIMUM (time_t);
1973  newer_mtime_option.tv_nsec = -1;
1974  recursion_option = FNM_LEADING_DIR;
1975  unquote_option = true;
1976  tar_sparse_major = 1;
1977  tar_sparse_minor = 0;
1978
1979  owner_option = -1;
1980  group_option = -1;
1981
1982  /* Convert old-style tar call by exploding option element and rearranging
1983     options accordingly.  */
1984
1985  if (argc > 1 && argv[1][0] != '-')
1986    {
1987      int new_argc;		/* argc value for rearranged arguments */
1988      char **new_argv;		/* argv value for rearranged arguments */
1989      char *const *in;		/* cursor into original argv */
1990      char **out;		/* cursor into rearranged argv */
1991      const char *letter;	/* cursor into old option letters */
1992      char buffer[3];		/* constructed option buffer */
1993
1994      /* Initialize a constructed option.  */
1995
1996      buffer[0] = '-';
1997      buffer[2] = '\0';
1998
1999      /* Allocate a new argument array, and copy program name in it.  */
2000
2001      new_argc = argc - 1 + strlen (argv[1]);
2002      new_argv = xmalloc ((new_argc + 1) * sizeof (char *));
2003      in = argv;
2004      out = new_argv;
2005      *out++ = *in++;
2006
2007      /* Copy each old letter option as a separate option, and have the
2008	 corresponding argument moved next to it.  */
2009
2010      for (letter = *in++; *letter; letter++)
2011	{
2012	  struct argp_option *opt;
2013
2014	  buffer[1] = *letter;
2015	  *out++ = xstrdup (buffer);
2016	  opt = find_argp_option (options, *letter);
2017	  if (opt && opt->arg)
2018	    {
2019	      if (in < argv + argc)
2020		*out++ = *in++;
2021	      else
2022		USAGE_ERROR ((0, 0, _("Old option `%c' requires an argument."),
2023			      *letter));
2024	    }
2025	}
2026
2027      /* Copy all remaining options.  */
2028
2029      while (in < argv + argc)
2030	*out++ = *in++;
2031      *out = 0;
2032
2033      /* Replace the old option list by the new one.  */
2034
2035      argc = new_argc;
2036      argv = new_argv;
2037    }
2038
2039  /* Parse all options and non-options as they appear.  */
2040
2041  prepend_default_options (getenv ("TAR_OPTIONS"), &argc, &argv);
2042
2043  if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER|ARGP_NO_HELP,
2044		  &index, &args))
2045    exit (TAREXIT_FAILURE);
2046
2047
2048  /* Special handling for 'o' option:
2049
2050     GNU tar used to say "output old format".
2051     UNIX98 tar says don't chown files after extracting (we use
2052     "--no-same-owner" for this).
2053
2054     The old GNU tar semantics is retained when used with --create
2055     option, otherwise UNIX98 semantics is assumed */
2056
2057  if (args.o_option)
2058    {
2059      if (subcommand_option == CREATE_SUBCOMMAND)
2060	{
2061	  /* GNU Tar <= 1.13 compatibility */
2062	  set_archive_format ("v7");
2063	}
2064      else
2065	{
2066	  /* UNIX98 compatibility */
2067	  same_owner_option = -1;
2068	}
2069    }
2070
2071  /* Handle operands after any "--" argument.  */
2072  for (; index < argc; index++)
2073    {
2074      name_add_name (argv[index], MAKE_INCL_OPTIONS (&args));
2075      args.input_files = true;
2076    }
2077
2078  /* Warn about implicit use of the wildcards in command line arguments.
2079     See TODO */
2080  warn_regex_usage = args.wildcards == default_wildcards;
2081
2082  /* Derive option values and check option consistency.  */
2083
2084  if (archive_format == DEFAULT_FORMAT)
2085    {
2086      if (args.pax_option)
2087	archive_format = POSIX_FORMAT;
2088      else
2089	archive_format = DEFAULT_ARCHIVE_FORMAT;
2090    }
2091
2092  if ((volume_label_option && subcommand_option == CREATE_SUBCOMMAND)
2093      || incremental_option
2094      || multi_volume_option
2095      || sparse_option)
2096    assert_format (FORMAT_MASK (OLDGNU_FORMAT)
2097		   | FORMAT_MASK (GNU_FORMAT)
2098		   | FORMAT_MASK (POSIX_FORMAT));
2099
2100  if (occurrence_option)
2101    {
2102      if (!args.input_files)
2103	USAGE_ERROR ((0, 0,
2104		      _("--occurrence is meaningless without a file list")));
2105      if (subcommand_option != DELETE_SUBCOMMAND
2106	  && subcommand_option != DIFF_SUBCOMMAND
2107	  && subcommand_option != EXTRACT_SUBCOMMAND
2108	  && subcommand_option != LIST_SUBCOMMAND)
2109	    USAGE_ERROR ((0, 0,
2110			  _("--occurrence cannot be used in the requested operation mode")));
2111    }
2112
2113  if (seekable_archive && subcommand_option == DELETE_SUBCOMMAND)
2114    {
2115      /* The current code in delete.c is based on the assumption that
2116	 skip_member() reads all data from the archive. So, we should
2117	 make sure it won't use seeks. On the other hand, the same code
2118	 depends on the ability to backspace a record in the archive,
2119	 so setting seekable_archive to false is technically incorrect.
2120         However, it is tested only in skip_member(), so it's not a
2121	 problem. */
2122      seekable_archive = false;
2123    }
2124
2125  if (archive_names == 0)
2126    {
2127      /* If no archive file name given, try TAPE from the environment, or
2128	 else, DEFAULT_ARCHIVE from the configuration process.  */
2129
2130      archive_names = 1;
2131      archive_name_array[0] = getenv ("TAPE");
2132      if (! archive_name_array[0])
2133	archive_name_array[0] = DEFAULT_ARCHIVE;
2134    }
2135
2136  /* Allow multiple archives only with `-M'.  */
2137
2138  if (archive_names > 1 && !multi_volume_option)
2139    USAGE_ERROR ((0, 0,
2140		  _("Multiple archive files require `-M' option")));
2141
2142  if (listed_incremental_option
2143      && NEWER_OPTION_INITIALIZED (newer_mtime_option))
2144    USAGE_ERROR ((0, 0,
2145		  _("Cannot combine --listed-incremental with --newer")));
2146
2147  if (volume_label_option)
2148    {
2149      if (archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
2150	{
2151	  size_t volume_label_max_len =
2152	    (sizeof current_header->header.name
2153	     - 1 /* for trailing '\0' */
2154	     - (multi_volume_option
2155		? (sizeof " Volume "
2156		   - 1 /* for null at end of " Volume " */
2157		   + INT_STRLEN_BOUND (int) /* for volume number */
2158		   - 1 /* for sign, as 0 <= volno */)
2159		: 0));
2160	  if (volume_label_max_len < strlen (volume_label_option))
2161	    USAGE_ERROR ((0, 0,
2162			  ngettext ("%s: Volume label is too long (limit is %lu byte)",
2163				    "%s: Volume label is too long (limit is %lu bytes)",
2164				    volume_label_max_len),
2165			  quotearg_colon (volume_label_option),
2166			  (unsigned long) volume_label_max_len));
2167	}
2168      /* else FIXME
2169	 Label length in PAX format is limited by the volume size. */
2170    }
2171
2172  if (verify_option)
2173    {
2174      if (multi_volume_option)
2175	USAGE_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
2176      if (use_compress_program_option)
2177	USAGE_ERROR ((0, 0, _("Cannot verify compressed archives")));
2178    }
2179
2180  if (use_compress_program_option)
2181    {
2182      if (multi_volume_option)
2183	USAGE_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
2184      if (subcommand_option == UPDATE_SUBCOMMAND
2185	  || subcommand_option == APPEND_SUBCOMMAND
2186	  || subcommand_option == DELETE_SUBCOMMAND)
2187	USAGE_ERROR ((0, 0, _("Cannot update compressed archives")));
2188      if (subcommand_option == CAT_SUBCOMMAND)
2189	USAGE_ERROR ((0, 0, _("Cannot concatenate compressed archives")));
2190    }
2191
2192  /* It is no harm to use --pax-option on non-pax archives in archive
2193     reading mode. It may even be useful, since it allows to override
2194     file attributes from tar headers. Therefore I allow such usage.
2195     --gray */
2196  if (args.pax_option
2197      && archive_format != POSIX_FORMAT
2198      && (subcommand_option != EXTRACT_SUBCOMMAND
2199	  || subcommand_option != DIFF_SUBCOMMAND
2200	  || subcommand_option != LIST_SUBCOMMAND))
2201    USAGE_ERROR ((0, 0, _("--pax-option can be used only on POSIX archives")));
2202
2203  /* If ready to unlink hierarchies, so we are for simpler files.  */
2204  if (recursive_unlink_option)
2205    old_files_option = UNLINK_FIRST_OLD_FILES;
2206
2207
2208  if (test_label_option)
2209    {
2210      /* --test-label is silent if the user has specified the label name to
2211	 compare against. */
2212      if (!args.input_files)
2213	verbose_option++;
2214    }
2215  else if (utc_option)
2216    verbose_option = 2;
2217
2218  /* Forbid using -c with no input files whatsoever.  Check that `-f -',
2219     explicit or implied, is used correctly.  */
2220
2221  switch (subcommand_option)
2222    {
2223    case CREATE_SUBCOMMAND:
2224      if (!args.input_files && !files_from_option)
2225	USAGE_ERROR ((0, 0,
2226		      _("Cowardly refusing to create an empty archive")));
2227      break;
2228
2229    case EXTRACT_SUBCOMMAND:
2230    case LIST_SUBCOMMAND:
2231    case DIFF_SUBCOMMAND:
2232      for (archive_name_cursor = archive_name_array;
2233	   archive_name_cursor < archive_name_array + archive_names;
2234	   archive_name_cursor++)
2235	if (!strcmp (*archive_name_cursor, "-"))
2236	  request_stdin ("-f");
2237      break;
2238
2239    case CAT_SUBCOMMAND:
2240    case UPDATE_SUBCOMMAND:
2241    case APPEND_SUBCOMMAND:
2242      for (archive_name_cursor = archive_name_array;
2243	   archive_name_cursor < archive_name_array + archive_names;
2244	   archive_name_cursor++)
2245	if (!strcmp (*archive_name_cursor, "-"))
2246	  USAGE_ERROR ((0, 0,
2247			_("Options `-Aru' are incompatible with `-f -'")));
2248
2249    default:
2250      break;
2251    }
2252
2253  /* Initialize stdlis */
2254  if (index_file_name)
2255    {
2256      stdlis = fopen (index_file_name, "w");
2257      if (! stdlis)
2258	open_error (index_file_name);
2259    }
2260  else
2261    stdlis = to_stdout_option ? stderr : stdout;
2262
2263  archive_name_cursor = archive_name_array;
2264
2265  /* Prepare for generating backup names.  */
2266
2267  if (args.backup_suffix_string)
2268    simple_backup_suffix = xstrdup (args.backup_suffix_string);
2269
2270  if (backup_option)
2271    {
2272      backup_type = xget_version ("--backup", args.version_control_string);
2273      /* No backup is needed either if explicitely disabled or if
2274	 the extracted files are not being written to disk. */
2275      if (backup_type == no_backups || EXTRACT_OVER_PIPE)
2276	backup_option = false;
2277    }
2278
2279  if (verbose_option)
2280    report_textual_dates (&args);
2281}
2282
2283
2284/* Tar proper.  */
2285
2286/* Main routine for tar.  */
2287int
2288main (int argc, char **argv)
2289{
2290  set_start_time ();
2291  program_name = argv[0];
2292
2293  setlocale (LC_ALL, "");
2294  bindtextdomain (PACKAGE, LOCALEDIR);
2295  textdomain (PACKAGE);
2296
2297  exit_failure = TAREXIT_FAILURE;
2298  exit_status = TAREXIT_SUCCESS;
2299  filename_terminator = '\n';
2300  set_quoting_style (0, DEFAULT_QUOTING_STYLE);
2301
2302  /* Make sure we have first three descriptors available */
2303  stdopen ();
2304
2305  /* Pre-allocate a few structures.  */
2306
2307  allocated_archive_names = 10;
2308  archive_name_array =
2309    xmalloc (sizeof (const char *) * allocated_archive_names);
2310  archive_names = 0;
2311
2312  obstack_init (&argv_stk);
2313
2314#ifdef SIGCHLD
2315  /* System V fork+wait does not work if SIGCHLD is ignored.  */
2316  signal (SIGCHLD, SIG_DFL);
2317#endif
2318
2319  /* Decode options.  */
2320
2321  decode_options (argc, argv);
2322
2323  name_init ();
2324
2325  /* Main command execution.  */
2326
2327  if (volno_file_option)
2328    init_volume_number ();
2329
2330  switch (subcommand_option)
2331    {
2332    case UNKNOWN_SUBCOMMAND:
2333      USAGE_ERROR ((0, 0,
2334		    _("You must specify one of the `-Acdtrux' options")));
2335
2336    case CAT_SUBCOMMAND:
2337    case UPDATE_SUBCOMMAND:
2338    case APPEND_SUBCOMMAND:
2339      update_archive ();
2340      break;
2341
2342    case DELETE_SUBCOMMAND:
2343      delete_archive_members ();
2344      break;
2345
2346    case CREATE_SUBCOMMAND:
2347      create_archive ();
2348      break;
2349
2350    case EXTRACT_SUBCOMMAND:
2351      extr_init ();
2352      read_and (extract_archive);
2353
2354      /* FIXME: should extract_finish () even if an ordinary signal is
2355	 received.  */
2356      extract_finish ();
2357
2358      break;
2359
2360    case LIST_SUBCOMMAND:
2361      read_and (list_archive);
2362      break;
2363
2364    case DIFF_SUBCOMMAND:
2365      diff_init ();
2366      read_and (diff_archive);
2367      break;
2368    }
2369
2370  if (totals_option)
2371    print_total_stats ();
2372
2373  if (check_links_option)
2374    check_links ();
2375
2376  if (volno_file_option)
2377    closeout_volume_number ();
2378
2379  /* Dispose of allocated memory, and return.  */
2380
2381  free (archive_name_array);
2382  name_term ();
2383
2384  if (exit_status == TAREXIT_FAILURE)
2385    error (0, 0, _("Error exit delayed from previous errors"));
2386
2387  if (stdlis == stdout)
2388    close_stdout ();
2389  else if (ferror (stderr) || fclose (stderr) != 0)
2390    exit_status = TAREXIT_FAILURE;
2391
2392  return exit_status;
2393}
2394
2395void
2396tar_stat_init (struct tar_stat_info *st)
2397{
2398  memset (st, 0, sizeof (*st));
2399}
2400
2401void
2402tar_stat_destroy (struct tar_stat_info *st)
2403{
2404  free (st->orig_file_name);
2405  free (st->file_name);
2406  free (st->link_name);
2407  free (st->uname);
2408  free (st->gname);
2409  free (st->sparse_map);
2410  free (st->dumpdir);
2411  xheader_destroy (&st->xhdr);
2412  memset (st, 0, sizeof (*st));
2413}
2414
2415/* Format mask for all available formats that support nanosecond
2416   timestamp resolution. */
2417#define NS_PRECISION_FORMAT_MASK FORMAT_MASK (POSIX_FORMAT)
2418
2419/* Same as timespec_cmp, but ignore nanoseconds if current archive
2420   format does not provide sufficient resolution.  */
2421int
2422tar_timespec_cmp (struct timespec a, struct timespec b)
2423{
2424  if (!(FORMAT_MASK (current_format) & NS_PRECISION_FORMAT_MASK))
2425    a.tv_nsec = b.tv_nsec = 0;
2426  return timespec_cmp (a, b);
2427}
2428