re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / src / tar.c
1 /* A tar (tape archiver) program.
2
3    Copyright 1988, 1992-1997, 1999-2001, 2003-2007, 2012-2016 Free
4    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 3, 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, see <http://www.gnu.org/licenses/>.  */
20
21 #include <system.h>
22
23 #include <fnmatch.h>
24 #include <argp.h>
25 #include <argp-namefrob.h>
26 #include <argp-fmtstream.h>
27 #include <argp-version-etc.h>
28
29 #include <signal.h>
30 #if ! defined SIGCHLD && defined SIGCLD
31 # define SIGCHLD SIGCLD
32 #endif
33
34 /* The following causes "common.h" to produce definitions of all the global
35    variables, rather than just "extern" declarations of them.  GNU tar does
36    depend on the system loader to preset all GLOBAL variables to neutral (or
37    zero) values; explicit initialization is usually not done.  */
38 #define GLOBAL
39 #include "common.h"
40
41 #include <argmatch.h>
42 #include <closeout.h>
43 #include <configmake.h>
44 #include <exitfail.h>
45 #include <parse-datetime.h>
46 #include <rmt.h>
47 #include <rmt-command.h>
48 #include <wordsplit.h>
49 #include <sysexits.h>
50 #include <quotearg.h>
51 #include <version-etc.h>
52 #include <xstrtol.h>
53 #include <stdopen.h>
54 #include <priv-set.h>
55 #include <savedir.h>
56
57 /* Local declarations.  */
58
59 #ifndef DEFAULT_ARCHIVE_FORMAT
60 # define DEFAULT_ARCHIVE_FORMAT GNU_FORMAT
61 #endif
62
63 #ifndef DEFAULT_ARCHIVE
64 # define DEFAULT_ARCHIVE "tar.out"
65 #endif
66
67 #ifndef DEFAULT_BLOCKING
68 # define DEFAULT_BLOCKING 20
69 #endif
70
71 /* Print a message if not all links are dumped */
72 static int check_links_option;
73
74 /* Number of allocated tape drive names.  */
75 static size_t allocated_archive_names;
76
77 \f
78 /* Miscellaneous.  */
79
80 /* Name of option using stdin.  */
81 static const char *stdin_used_by;
82
83 /* Doesn't return if stdin already requested.  */
84 void
85 request_stdin (const char *option)
86 {
87   if (stdin_used_by)
88     USAGE_ERROR ((0, 0, _("Options '%s' and '%s' both want standard input"),
89                   stdin_used_by, option));
90
91   stdin_used_by = option;
92 }
93
94 extern int rpmatch (char const *response);
95
96 /* Returns true if and only if the user typed an affirmative response.  */
97 int
98 confirm (const char *message_action, const char *message_name)
99 {
100   static FILE *confirm_file;
101   static int confirm_file_EOF;
102   bool status = false;
103
104   if (!confirm_file)
105     {
106       if (archive == 0 || stdin_used_by)
107         {
108           confirm_file = fopen (TTY_NAME, "r");
109           if (! confirm_file)
110             open_fatal (TTY_NAME);
111         }
112       else
113         {
114           request_stdin ("-w");
115           confirm_file = stdin;
116         }
117     }
118
119   fprintf (stdlis, "%s %s?", message_action, quote (message_name));
120   fflush (stdlis);
121
122   if (!confirm_file_EOF)
123     {
124       char *response = NULL;
125       size_t response_size = 0;
126       if (getline (&response, &response_size, confirm_file) < 0)
127         confirm_file_EOF = 1;
128       else
129         status = rpmatch (response) > 0;
130       free (response);
131     }
132
133   if (confirm_file_EOF)
134     {
135       fputc ('\n', stdlis);
136       fflush (stdlis);
137     }
138
139   return status;
140 }
141
142 static struct fmttab {
143   char const *name;
144   enum archive_format fmt;
145 } const fmttab[] = {
146   { "v7",      V7_FORMAT },
147   { "oldgnu",  OLDGNU_FORMAT },
148   { "ustar",   USTAR_FORMAT },
149   { "posix",   POSIX_FORMAT },
150 #if 0 /* not fully supported yet */
151   { "star",    STAR_FORMAT },
152 #endif
153   { "gnu",     GNU_FORMAT },
154   { "pax",     POSIX_FORMAT }, /* An alias for posix */
155   { NULL,      0 }
156 };
157
158 static void
159 set_archive_format (char const *name)
160 {
161   struct fmttab const *p;
162
163   for (p = fmttab; strcmp (p->name, name) != 0; )
164     if (! (++p)->name)
165       USAGE_ERROR ((0, 0, _("%s: Invalid archive format"),
166                     quotearg_colon (name)));
167
168   archive_format = p->fmt;
169 }
170
171 static void
172 set_xattr_option (int value)
173 {
174   if (value == 1)
175     set_archive_format ("posix");
176   xattrs_option = value;
177 }
178
179 const char *
180 archive_format_string (enum archive_format fmt)
181 {
182   struct fmttab const *p;
183
184   for (p = fmttab; p->name; p++)
185     if (p->fmt == fmt)
186       return p->name;
187   return "unknown?";
188 }
189
190 #define FORMAT_MASK(n) (1<<(n))
191
192 static void
193 assert_format(unsigned fmt_mask)
194 {
195   if ((FORMAT_MASK (archive_format) & fmt_mask) == 0)
196     USAGE_ERROR ((0, 0,
197                   _("GNU features wanted on incompatible archive format")));
198 }
199
200 const char *
201 subcommand_string (enum subcommand c)
202 {
203   switch (c)
204     {
205     case UNKNOWN_SUBCOMMAND:
206       return "unknown?";
207
208     case APPEND_SUBCOMMAND:
209       return "-r";
210
211     case CAT_SUBCOMMAND:
212       return "-A";
213
214     case CREATE_SUBCOMMAND:
215       return "-c";
216
217     case DELETE_SUBCOMMAND:
218       return "-D";
219
220     case DIFF_SUBCOMMAND:
221       return "-d";
222
223     case EXTRACT_SUBCOMMAND:
224       return "-x";
225
226     case LIST_SUBCOMMAND:
227       return "-t";
228
229     case UPDATE_SUBCOMMAND:
230       return "-u";
231
232     case TEST_LABEL_SUBCOMMAND:
233       return "--test-label";
234     }
235   abort ();
236 }
237
238 static void
239 tar_list_quoting_styles (struct obstack *stk, char const *prefix)
240 {
241   int i;
242   size_t prefixlen = strlen (prefix);
243
244   for (i = 0; quoting_style_args[i]; i++)
245     {
246       obstack_grow (stk, prefix, prefixlen);
247       obstack_grow (stk, quoting_style_args[i],
248                     strlen (quoting_style_args[i]));
249       obstack_1grow (stk, '\n');
250     }
251 }
252
253 static void
254 tar_set_quoting_style (char *arg)
255 {
256   int i;
257
258   for (i = 0; quoting_style_args[i]; i++)
259     if (strcmp (arg, quoting_style_args[i]) == 0)
260       {
261         set_quoting_style (NULL, i);
262         return;
263       }
264   FATAL_ERROR ((0, 0,
265                 _("Unknown quoting style '%s'. Try '%s --quoting-style=help' to get a list."), arg, program_name));
266 }
267
268 \f
269 /* Options.  */
270
271 enum
272 {
273   ACLS_OPTION = CHAR_MAX + 1,
274   ATIME_PRESERVE_OPTION,
275   BACKUP_OPTION,
276   CHECK_DEVICE_OPTION,
277   CHECKPOINT_OPTION,
278   CHECKPOINT_ACTION_OPTION,
279   CLAMP_MTIME_OPTION,
280   DELAY_DIRECTORY_RESTORE_OPTION,
281   HARD_DEREFERENCE_OPTION,
282   DELETE_OPTION,
283   FORCE_LOCAL_OPTION,
284   FULL_TIME_OPTION,
285   GROUP_OPTION,
286   GROUP_MAP_OPTION,
287   IGNORE_COMMAND_ERROR_OPTION,
288   IGNORE_FAILED_READ_OPTION,
289   INDEX_FILE_OPTION,
290   KEEP_DIRECTORY_SYMLINK_OPTION,
291   KEEP_NEWER_FILES_OPTION,
292   LEVEL_OPTION,
293   LZIP_OPTION,
294   LZMA_OPTION,
295   LZOP_OPTION,
296   MODE_OPTION,
297   MTIME_OPTION,
298   NEWER_MTIME_OPTION,
299   NO_ACLS_OPTION,
300   NO_AUTO_COMPRESS_OPTION,
301   NO_CHECK_DEVICE_OPTION,
302   NO_DELAY_DIRECTORY_RESTORE_OPTION,
303   NO_IGNORE_COMMAND_ERROR_OPTION,
304   NO_OVERWRITE_DIR_OPTION,
305   NO_QUOTE_CHARS_OPTION,
306   NO_SAME_OWNER_OPTION,
307   NO_SAME_PERMISSIONS_OPTION,
308   NO_SEEK_OPTION,
309   NO_SELINUX_CONTEXT_OPTION,
310   NO_XATTR_OPTION,
311   NUMERIC_OWNER_OPTION,
312   OCCURRENCE_OPTION,
313   OLD_ARCHIVE_OPTION,
314   ONE_FILE_SYSTEM_OPTION,
315   ONE_TOP_LEVEL_OPTION,
316   OVERWRITE_DIR_OPTION,
317   OVERWRITE_OPTION,
318   OWNER_OPTION,
319   OWNER_MAP_OPTION,
320   PAX_OPTION,
321   POSIX_OPTION,
322   QUOTE_CHARS_OPTION,
323   QUOTING_STYLE_OPTION,
324   RECORD_SIZE_OPTION,
325   RECURSIVE_UNLINK_OPTION,
326   REMOVE_FILES_OPTION,
327   RESTRICT_OPTION,
328   RMT_COMMAND_OPTION,
329   RSH_COMMAND_OPTION,
330   SAME_OWNER_OPTION,
331   SELINUX_CONTEXT_OPTION,
332   SHOW_DEFAULTS_OPTION,
333   SHOW_OMITTED_DIRS_OPTION,
334   SHOW_SNAPSHOT_FIELD_RANGES_OPTION,
335   SHOW_TRANSFORMED_NAMES_OPTION,
336   SKIP_OLD_FILES_OPTION,
337   SORT_OPTION,
338   HOLE_DETECTION_OPTION,
339   SPARSE_VERSION_OPTION,
340   STRIP_COMPONENTS_OPTION,
341   SUFFIX_OPTION,
342   TEST_LABEL_OPTION,
343   TOTALS_OPTION,
344   TO_COMMAND_OPTION,
345   TRANSFORM_OPTION,
346   UTC_OPTION,
347   VOLNO_FILE_OPTION,
348   WARNING_OPTION,
349   XATTR_OPTION,
350   XATTR_EXCLUDE,
351   XATTR_INCLUDE
352 };
353
354 static char const doc[] = N_("\
355 GNU 'tar' saves many files together into a single tape or disk archive, \
356 and can restore individual files from the archive.\n\
357 \n\
358 Examples:\n\
359   tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.\n\
360   tar -tvf archive.tar         # List all files in archive.tar verbosely.\n\
361   tar -xf archive.tar          # Extract all files from archive.tar.\n")
362 "\v"
363 N_("The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
364 The version control may be set with --backup or VERSION_CONTROL, values are:\n\n\
365   none, off       never make backups\n\
366   t, numbered     make numbered backups\n\
367   nil, existing   numbered if numbered backups exist, simple otherwise\n\
368   never, simple   always make simple backups\n");
369
370
371 /* NOTE:
372
373    Available option letters are DEQY and eqy. Consider the following
374    assignments:
375
376    [For Solaris tar compatibility =/= Is it important at all?]
377    e  exit immediately with a nonzero exit status if unexpected errors occur
378    E  use extended headers (--format=posix)
379
380    [q  alias for --occurrence=1 =/= this would better be used for quiet?]
381
382    y  per-file gzip compression
383    Y  per-block gzip compression.
384
385    Additionally, the 'n' letter is assigned for option --seek, which
386    is probably not needed and should be marked as deprecated, so that
387    -n may become available in the future.
388 */
389
390 static struct argp_option options[] = {
391 #define GRID 10
392   {NULL, 0, NULL, 0,
393    N_("Main operation mode:"), GRID },
394
395   {"list", 't', 0, 0,
396    N_("list the contents of an archive"), GRID+1 },
397   {"extract", 'x', 0, 0,
398    N_("extract files from an archive"), GRID+1 },
399   {"get", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
400   {"create", 'c', 0, 0,
401    N_("create a new archive"), GRID+1 },
402   {"diff", 'd', 0, 0,
403    N_("find differences between archive and file system"), GRID+1 },
404   {"compare", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
405   {"append", 'r', 0, 0,
406    N_("append files to the end of an archive"), GRID+1 },
407   {"update", 'u', 0, 0,
408    N_("only append files newer than copy in archive"), GRID+1 },
409   {"catenate", 'A', 0, 0,
410    N_("append tar files to an archive"), GRID+1 },
411   {"concatenate", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
412   {"delete", DELETE_OPTION, 0, 0,
413    N_("delete from the archive (not on mag tapes!)"), GRID+1 },
414   {"test-label", TEST_LABEL_OPTION, NULL, 0,
415    N_("test the archive volume label and exit"), GRID+1 },
416 #undef GRID
417
418 #define GRID 20
419   {NULL, 0, NULL, 0,
420    N_("Operation modifiers:"), GRID },
421
422   {"sparse", 'S', 0, 0,
423    N_("handle sparse files efficiently"), GRID+1 },
424   {"hole-detection", HOLE_DETECTION_OPTION, N_("TYPE"), 0,
425    N_("technique to detect holes"), GRID+1 },
426   {"sparse-version", SPARSE_VERSION_OPTION, N_("MAJOR[.MINOR]"), 0,
427    N_("set version of the sparse format to use (implies --sparse)"), GRID+1},
428   {"incremental", 'G', 0, 0,
429    N_("handle old GNU-format incremental backup"), GRID+1 },
430   {"listed-incremental", 'g', N_("FILE"), 0,
431    N_("handle new GNU-format incremental backup"), GRID+1 },
432   {"level", LEVEL_OPTION, N_("NUMBER"), 0,
433    N_("dump level for created listed-incremental archive"), GRID+1 },
434   {"ignore-failed-read", IGNORE_FAILED_READ_OPTION, 0, 0,
435    N_("do not exit with nonzero on unreadable files"), GRID+1 },
436   {"occurrence", OCCURRENCE_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL,
437    N_("process only the NUMBERth occurrence of each file in the archive;"
438       " this option is valid only in conjunction with one of the subcommands"
439       " --delete, --diff, --extract or --list and when a list of files"
440       " is given either on the command line or via the -T option;"
441       " NUMBER defaults to 1"), GRID+1 },
442   {"seek", 'n', NULL, 0,
443    N_("archive is seekable"), GRID+1 },
444   {"no-seek", NO_SEEK_OPTION, NULL, 0,
445    N_("archive is not seekable"), GRID+1 },
446   {"no-check-device", NO_CHECK_DEVICE_OPTION, NULL, 0,
447    N_("do not check device numbers when creating incremental archives"),
448    GRID+1 },
449   {"check-device", CHECK_DEVICE_OPTION, NULL, 0,
450    N_("check device numbers when creating incremental archives (default)"),
451    GRID+1 },
452 #undef GRID
453
454 #define GRID 30
455   {NULL, 0, NULL, 0,
456    N_("Overwrite control:"), GRID },
457
458   {"verify", 'W', 0, 0,
459    N_("attempt to verify the archive after writing it"), GRID+1 },
460   {"remove-files", REMOVE_FILES_OPTION, 0, 0,
461    N_("remove files after adding them to the archive"), GRID+1 },
462   {"keep-old-files", 'k', 0, 0,
463    N_("don't replace existing files when extracting, "
464       "treat them as errors"), GRID+1 },
465   {"skip-old-files", SKIP_OLD_FILES_OPTION, 0, 0,
466    N_("don't replace existing files when extracting, silently skip over them"),
467    GRID+1 },
468   {"keep-newer-files", KEEP_NEWER_FILES_OPTION, 0, 0,
469    N_("don't replace existing files that are newer than their archive copies"), GRID+1 },
470   {"overwrite", OVERWRITE_OPTION, 0, 0,
471    N_("overwrite existing files when extracting"), GRID+1 },
472   {"unlink-first", 'U', 0, 0,
473    N_("remove each file prior to extracting over it"), GRID+1 },
474   {"recursive-unlink", RECURSIVE_UNLINK_OPTION, 0, 0,
475    N_("empty hierarchies prior to extracting directory"), GRID+1 },
476   {"no-overwrite-dir", NO_OVERWRITE_DIR_OPTION, 0, 0,
477    N_("preserve metadata of existing directories"), GRID+1 },
478   {"overwrite-dir", OVERWRITE_DIR_OPTION, 0, 0,
479    N_("overwrite metadata of existing directories when extracting (default)"),
480    GRID+1 },
481   {"keep-directory-symlink", KEEP_DIRECTORY_SYMLINK_OPTION, 0, 0,
482    N_("preserve existing symlinks to directories when extracting"),
483    GRID+1 },
484   {"one-top-level", ONE_TOP_LEVEL_OPTION, N_("DIR"), OPTION_ARG_OPTIONAL,
485    N_("create a subdirectory to avoid having loose files extracted"),
486    GRID+1 },
487 #undef GRID
488
489 #define GRID 40
490   {NULL, 0, NULL, 0,
491    N_("Select output stream:"), GRID },
492
493   {"to-stdout", 'O', 0, 0,
494    N_("extract files to standard output"), GRID+1 },
495   {"to-command", TO_COMMAND_OPTION, N_("COMMAND"), 0,
496    N_("pipe extracted files to another program"), GRID+1 },
497   {"ignore-command-error", IGNORE_COMMAND_ERROR_OPTION, 0, 0,
498    N_("ignore exit codes of children"), GRID+1 },
499   {"no-ignore-command-error", NO_IGNORE_COMMAND_ERROR_OPTION, 0, 0,
500    N_("treat non-zero exit codes of children as error"), GRID+1 },
501 #undef GRID
502
503 #define GRID 50
504   {NULL, 0, NULL, 0,
505    N_("Handling of file attributes:"), GRID },
506
507   {"owner", OWNER_OPTION, N_("NAME"), 0,
508    N_("force NAME as owner for added files"), GRID+1 },
509   {"group", GROUP_OPTION, N_("NAME"), 0,
510    N_("force NAME as group for added files"), GRID+1 },
511   {"owner-map", OWNER_MAP_OPTION, N_("FILE"), 0,
512    N_("use FILE to map file owner UIDs and names"), GRID+1 },
513   {"group-map", GROUP_MAP_OPTION, N_("FILE"), 0,
514    N_("use FILE to map file owner GIDs and names"), GRID+1 },
515   {"mtime", MTIME_OPTION, N_("DATE-OR-FILE"), 0,
516    N_("set mtime for added files from DATE-OR-FILE"), GRID+1 },
517   {"clamp-mtime", CLAMP_MTIME_OPTION, 0, 0,
518    N_("only set time when the file is more recent than what was given with --mtime"), GRID+1 },
519   {"mode", MODE_OPTION, N_("CHANGES"), 0,
520    N_("force (symbolic) mode CHANGES for added files"), GRID+1 },
521   {"atime-preserve", ATIME_PRESERVE_OPTION,
522    N_("METHOD"), OPTION_ARG_OPTIONAL,
523    N_("preserve access times on dumped files, either by restoring the times"
524       " after reading (METHOD='replace'; default) or by not setting the times"
525       " in the first place (METHOD='system')"), GRID+1 },
526   {"touch", 'm', 0, 0,
527    N_("don't extract file modified time"), GRID+1 },
528   {"same-owner", SAME_OWNER_OPTION, 0, 0,
529    N_("try extracting files with the same ownership as exists in the archive (default for superuser)"), GRID+1 },
530   {"no-same-owner", NO_SAME_OWNER_OPTION, 0, 0,
531    N_("extract files as yourself (default for ordinary users)"), GRID+1 },
532   {"numeric-owner", NUMERIC_OWNER_OPTION, 0, 0,
533    N_("always use numbers for user/group names"), GRID+1 },
534   {"preserve-permissions", 'p', 0, 0,
535    N_("extract information about file permissions (default for superuser)"),
536    GRID+1 },
537   {"same-permissions", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
538   {"no-same-permissions", NO_SAME_PERMISSIONS_OPTION, 0, 0,
539    N_("apply the user's umask when extracting permissions from the archive (default for ordinary users)"), GRID+1 },
540   {"preserve-order", 's', 0, 0,
541    N_("member arguments are listed in the same order as the "
542       "files in the archive"), GRID+1 },
543   {"same-order", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
544   {"delay-directory-restore", DELAY_DIRECTORY_RESTORE_OPTION, 0, 0,
545    N_("delay setting modification times and permissions of extracted"
546       " directories until the end of extraction"), GRID+1 },
547   {"no-delay-directory-restore", NO_DELAY_DIRECTORY_RESTORE_OPTION, 0, 0,
548    N_("cancel the effect of --delay-directory-restore option"), GRID+1 },
549   {"sort", SORT_OPTION, N_("ORDER"), 0,
550 #if D_INO_IN_DIRENT
551    N_("directory sorting order: none (default), name or inode"
552 #else
553    N_("directory sorting order: none (default) or name"
554 #endif
555      ), GRID+1 },
556 #undef GRID
557
558 #define GRID 55
559   {NULL, 0, NULL, 0,
560    N_("Handling of extended file attributes:"), GRID },
561
562   {"xattrs", XATTR_OPTION, 0, 0,
563    N_("Enable extended attributes support"), GRID+1 },
564   {"no-xattrs", NO_XATTR_OPTION, 0, 0,
565    N_("Disable extended attributes support"), GRID+1 },
566   {"xattrs-include", XATTR_INCLUDE, N_("MASK"), 0,
567    N_("specify the include pattern for xattr keys"), GRID+1 },
568   {"xattrs-exclude", XATTR_EXCLUDE, N_("MASK"), 0,
569    N_("specify the exclude pattern for xattr keys"), GRID+1 },
570   {"selinux", SELINUX_CONTEXT_OPTION, 0, 0,
571    N_("Enable the SELinux context support"), GRID+1 },
572   {"no-selinux", NO_SELINUX_CONTEXT_OPTION, 0, 0,
573    N_("Disable the SELinux context support"), GRID+1 },
574   {"acls", ACLS_OPTION, 0, 0,
575    N_("Enable the POSIX ACLs support"), GRID+1 },
576   {"no-acls", NO_ACLS_OPTION, 0, 0,
577    N_("Disable the POSIX ACLs support"), GRID+1 },
578 #undef GRID
579
580 #define GRID 60
581   {NULL, 0, NULL, 0,
582    N_("Device selection and switching:"), GRID },
583
584   {"file", 'f', N_("ARCHIVE"), 0,
585    N_("use archive file or device ARCHIVE"), GRID+1 },
586   {"force-local", FORCE_LOCAL_OPTION, 0, 0,
587    N_("archive file is local even if it has a colon"), GRID+1 },
588   {"rmt-command", RMT_COMMAND_OPTION, N_("COMMAND"), 0,
589    N_("use given rmt COMMAND instead of rmt"), GRID+1 },
590   {"rsh-command", RSH_COMMAND_OPTION, N_("COMMAND"), 0,
591    N_("use remote COMMAND instead of rsh"), GRID+1 },
592 #ifdef DEVICE_PREFIX
593   {"-[0-7][lmh]", 0, NULL, OPTION_DOC, /* It is OK, since 'name' will never be
594                                           translated */
595    N_("specify drive and density"), GRID+1 },
596 #endif
597   {NULL, '0', NULL, OPTION_HIDDEN, NULL, GRID+1 },
598   {NULL, '1', NULL, OPTION_HIDDEN, NULL, GRID+1 },
599   {NULL, '2', NULL, OPTION_HIDDEN, NULL, GRID+1 },
600   {NULL, '3', NULL, OPTION_HIDDEN, NULL, GRID+1 },
601   {NULL, '4', NULL, OPTION_HIDDEN, NULL, GRID+1 },
602   {NULL, '5', NULL, OPTION_HIDDEN, NULL, GRID+1 },
603   {NULL, '6', NULL, OPTION_HIDDEN, NULL, GRID+1 },
604   {NULL, '7', NULL, OPTION_HIDDEN, NULL, GRID+1 },
605   {NULL, '8', NULL, OPTION_HIDDEN, NULL, GRID+1 },
606   {NULL, '9', NULL, OPTION_HIDDEN, NULL, GRID+1 },
607
608   {"multi-volume", 'M', 0, 0,
609    N_("create/list/extract multi-volume archive"), GRID+1 },
610   {"tape-length", 'L', N_("NUMBER"), 0,
611    N_("change tape after writing NUMBER x 1024 bytes"), GRID+1 },
612   {"info-script", 'F', N_("NAME"), 0,
613    N_("run script at end of each tape (implies -M)"), GRID+1 },
614   {"new-volume-script", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
615   {"volno-file", VOLNO_FILE_OPTION, N_("FILE"), 0,
616    N_("use/update the volume number in FILE"), GRID+1 },
617 #undef GRID
618
619 #define GRID 70
620   {NULL, 0, NULL, 0,
621    N_("Device blocking:"), GRID },
622
623   {"blocking-factor", 'b', N_("BLOCKS"), 0,
624    N_("BLOCKS x 512 bytes per record"), GRID+1 },
625   {"record-size", RECORD_SIZE_OPTION, N_("NUMBER"), 0,
626    N_("NUMBER of bytes per record, multiple of 512"), GRID+1 },
627   {"ignore-zeros", 'i', 0, 0,
628    N_("ignore zeroed blocks in archive (means EOF)"), GRID+1 },
629   {"read-full-records", 'B', 0, 0,
630    N_("reblock as we read (for 4.2BSD pipes)"), GRID+1 },
631 #undef GRID
632
633 #define GRID 80
634   {NULL, 0, NULL, 0,
635    N_("Archive format selection:"), GRID },
636
637   {"format", 'H', N_("FORMAT"), 0,
638    N_("create archive of the given format"), GRID+1 },
639
640   {NULL, 0, NULL, 0, N_("FORMAT is one of the following:"), GRID+2 },
641   {"  v7", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("old V7 tar format"),
642    GRID+3 },
643   {"  oldgnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
644    N_("GNU format as per tar <= 1.12"), GRID+3 },
645   {"  gnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
646    N_("GNU tar 1.13.x format"), GRID+3 },
647   {"  ustar", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
648    N_("POSIX 1003.1-1988 (ustar) format"), GRID+3 },
649   {"  pax", 0, NULL, OPTION_DOC|OPTION_NO_TRANS,
650    N_("POSIX 1003.1-2001 (pax) format"), GRID+3 },
651   {"  posix", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("same as pax"), GRID+3 },
652
653   {"old-archive", OLD_ARCHIVE_OPTION, 0, 0, /* FIXME */
654    N_("same as --format=v7"), GRID+8 },
655   {"portability", 0, 0, OPTION_ALIAS, NULL, GRID+8 },
656   {"posix", POSIX_OPTION, 0, 0,
657    N_("same as --format=posix"), GRID+8 },
658   {"pax-option", PAX_OPTION, N_("keyword[[:]=value][,keyword[[:]=value]]..."), 0,
659    N_("control pax keywords"), GRID+8 },
660   {"label", 'V', N_("TEXT"), 0,
661    N_("create archive with volume name TEXT; at list/extract time, use TEXT as a globbing pattern for volume name"), GRID+8 },
662 #undef GRID
663
664 #define GRID 90
665   {NULL, 0, NULL, 0,
666    N_("Compression options:"), GRID },
667   {"auto-compress", 'a', 0, 0,
668    N_("use archive suffix to determine the compression program"), GRID+1 },
669   {"no-auto-compress", NO_AUTO_COMPRESS_OPTION, 0, 0,
670    N_("do not use archive suffix to determine the compression program"),
671    GRID+1 },
672   {"use-compress-program", 'I', N_("PROG"), 0,
673    N_("filter through PROG (must accept -d)"), GRID+1 },
674   /* Note: docstrings for the options below are generated by tar_help_filter */
675   {"bzip2", 'j', 0, 0, NULL, GRID+1 },
676   {"gzip", 'z', 0, 0, NULL, GRID+1 },
677   {"gunzip", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
678   {"ungzip", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
679   {"compress", 'Z', 0, 0, NULL, GRID+1 },
680   {"uncompress", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
681   {"lzip", LZIP_OPTION, 0, 0, NULL, GRID+1 },
682   {"lzma", LZMA_OPTION, 0, 0, NULL, GRID+1 },
683   {"lzop", LZOP_OPTION, 0, 0, NULL, GRID+1 },
684   {"xz", 'J', 0, 0, NULL, GRID+1 },
685 #undef GRID
686
687 #define GRID 100
688   {NULL, 0, NULL, 0,
689    N_("Local file selection:"), GRID },
690   {"one-file-system", ONE_FILE_SYSTEM_OPTION, 0, 0,
691    N_("stay in local file system when creating archive"), GRID+1 },
692   {"absolute-names", 'P', 0, 0,
693    N_("don't strip leading '/'s from file names"), GRID+1 },
694   {"dereference", 'h', 0, 0,
695    N_("follow symlinks; archive and dump the files they point to"), GRID+1 },
696   {"hard-dereference", HARD_DEREFERENCE_OPTION, 0, 0,
697    N_("follow hard links; archive and dump the files they refer to"), GRID+1 },
698   {"starting-file", 'K', N_("MEMBER-NAME"), 0,
699    N_("begin at member MEMBER-NAME when reading the archive"), GRID+1 },
700   {"newer", 'N', N_("DATE-OR-FILE"), 0,
701    N_("only store files newer than DATE-OR-FILE"), GRID+1 },
702   {"after-date", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
703   {"newer-mtime", NEWER_MTIME_OPTION, N_("DATE"), 0,
704    N_("compare date and time when data changed only"), GRID+1 },
705   {"backup", BACKUP_OPTION, N_("CONTROL"), OPTION_ARG_OPTIONAL,
706    N_("backup before removal, choose version CONTROL"), GRID+1 },
707   {"suffix", SUFFIX_OPTION, N_("STRING"), 0,
708    N_("backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX)"), GRID+1 },
709 #undef GRID
710
711 #define GRID 110
712   {NULL, 0, NULL, 0,
713    N_("File name transformations:"), GRID },
714   {"strip-components", STRIP_COMPONENTS_OPTION, N_("NUMBER"), 0,
715    N_("strip NUMBER leading components from file names on extraction"),
716    GRID+1 },
717   {"transform", TRANSFORM_OPTION, N_("EXPRESSION"), 0,
718    N_("use sed replace EXPRESSION to transform file names"), GRID+1 },
719   {"xform", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
720 #undef GRID
721
722 #define GRID 130
723   {NULL, 0, NULL, 0,
724    N_("Informative output:"), GRID },
725
726   {"verbose", 'v', 0, 0,
727    N_("verbosely list files processed"), GRID+1 },
728   {"warning", WARNING_OPTION, N_("KEYWORD"), 0,
729    N_("warning control"), GRID+1 },
730   {"checkpoint", CHECKPOINT_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL,
731    N_("display progress messages every NUMBERth record (default 10)"),
732    GRID+1 },
733   {"checkpoint-action", CHECKPOINT_ACTION_OPTION, N_("ACTION"), 0,
734    N_("execute ACTION on each checkpoint"),
735    GRID+1 },
736   {"check-links", 'l', 0, 0,
737    N_("print a message if not all links are dumped"), GRID+1 },
738   {"totals", TOTALS_OPTION, N_("SIGNAL"), OPTION_ARG_OPTIONAL,
739    N_("print total bytes after processing the archive; "
740       "with an argument - print total bytes when this SIGNAL is delivered; "
741       "Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; "
742       "the names without SIG prefix are also accepted"), GRID+1 },
743   {"utc", UTC_OPTION, 0, 0,
744    N_("print file modification times in UTC"), GRID+1 },
745   {"full-time", FULL_TIME_OPTION, 0, 0,
746    N_("print file time to its full resolution"), GRID+1 },
747   {"index-file", INDEX_FILE_OPTION, N_("FILE"), 0,
748    N_("send verbose output to FILE"), GRID+1 },
749   {"block-number", 'R', 0, 0,
750    N_("show block number within archive with each message"), GRID+1 },
751   {"interactive", 'w', 0, 0,
752    N_("ask for confirmation for every action"), GRID+1 },
753   {"confirmation", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
754   {"show-defaults", SHOW_DEFAULTS_OPTION, 0, 0,
755    N_("show tar defaults"), GRID+1 },
756   {"show-snapshot-field-ranges", SHOW_SNAPSHOT_FIELD_RANGES_OPTION, 0, 0,
757    N_("show valid ranges for snapshot-file fields"), GRID+1 },
758   {"show-omitted-dirs", SHOW_OMITTED_DIRS_OPTION, 0, 0,
759    N_("when listing or extracting, list each directory that does not match search criteria"), GRID+1 },
760   {"show-transformed-names", SHOW_TRANSFORMED_NAMES_OPTION, 0, 0,
761    N_("show file or archive names after transformation"),
762    GRID+1 },
763   {"show-stored-names", 0, 0, OPTION_ALIAS, NULL, GRID+1 },
764   {"quoting-style", QUOTING_STYLE_OPTION, N_("STYLE"), 0,
765    N_("set name quoting style; see below for valid STYLE values"), GRID+1 },
766   {"quote-chars", QUOTE_CHARS_OPTION, N_("STRING"), 0,
767    N_("additionally quote characters from STRING"), GRID+1 },
768   {"no-quote-chars", NO_QUOTE_CHARS_OPTION, N_("STRING"), 0,
769    N_("disable quoting for characters from STRING"), GRID+1 },
770 #undef GRID
771
772 #define GRID 140
773   {NULL, 0, NULL, 0,
774    N_("Compatibility options:"), GRID },
775
776   {NULL, 'o', 0, 0,
777    N_("when creating, same as --old-archive; when extracting, same as --no-same-owner"), GRID+1 },
778 #undef GRID
779
780 #define GRID 150
781   {NULL, 0, NULL, 0,
782    N_("Other options:"), GRID },
783
784   {"restrict", RESTRICT_OPTION, 0, 0,
785    N_("disable use of some potentially harmful options"), -1 },
786 #undef GRID
787
788   {0, 0, 0, 0, 0, 0}
789 };
790
791 static char const *const atime_preserve_args[] =
792 {
793   "replace", "system", NULL
794 };
795
796 static enum atime_preserve const atime_preserve_types[] =
797 {
798   replace_atime_preserve, system_atime_preserve
799 };
800
801 /* Make sure atime_preserve_types has as much entries as atime_preserve_args
802    (minus 1 for NULL guard) */
803 ARGMATCH_VERIFY (atime_preserve_args, atime_preserve_types);
804
805 struct tar_args        /* Variables used during option parsing */
806 {
807   struct option_locus *loc;
808
809   struct textual_date *textual_date; /* Keeps the arguments to --newer-mtime
810                                         and/or --date option if they are
811                                         textual dates */
812   bool o_option;                   /* True if -o option was given */
813   bool pax_option;                 /* True if --pax-option was given */
814   char const *backup_suffix_string;   /* --suffix option argument */
815   char const *version_control_string; /* --backup option argument */
816   bool input_files;                /* True if some input files where given */
817   int compress_autodetect;         /* True if compression autodetection should
818                                       be attempted when creating archives */
819 };
820
821 \f
822 static char *
823 format_default_settings (void)
824 {
825   return xasprintf (
826             "--format=%s -f%s -b%d --quoting-style=%s --rmt-command=%s"
827 #ifdef REMOTE_SHELL
828             " --rsh-command=%s"
829 #endif
830             ,
831             archive_format_string (DEFAULT_ARCHIVE_FORMAT),
832             DEFAULT_ARCHIVE, DEFAULT_BLOCKING,
833             quoting_style_args[DEFAULT_QUOTING_STYLE],
834             DEFAULT_RMT_COMMAND
835 #ifdef REMOTE_SHELL
836             , REMOTE_SHELL
837 #endif
838             );
839 }
840 \f
841 static void
842 option_conflict_error (const char *a, const char *b)
843 {
844   /* TRANSLATORS: Both %s in this statement are replaced with
845      option names. */
846   USAGE_ERROR ((0, 0, _("'%s' cannot be used with '%s'"), a, b));
847 }
848 \f
849 /* Classes of options that can conflict: */
850 enum option_class
851   {
852     OC_COMPRESS,                 /* Compress options: -JjZz, -I, etc. */
853     OC_OCCURRENCE,               /* --occurrence */
854     OC_LISTED_INCREMENTAL,       /* --listed-incremental */
855     OC_NEWER,                    /* --newer, --newer-mtime, --after-date */
856     OC_VERIFY,                   /* --verify */
857     OC_STARTING_FILE,            /* --starting-file */
858     OC_SAME_ORDER,               /* --same-order */
859     OC_ONE_TOP_LEVEL,            /* --one-top-level */
860     OC_ABSOLUTE_NAMES,           /* --absolute-names */
861     OC_OLD_FILES,                /* --keep-old-files, --overwrite, etc. */
862     OC_MAX
863   };
864
865 /* Table of locations of potentially conflicting options.  Two options can
866    conflict only if they procede from the command line.  Otherwise, options
867    in command line silently override those defined in TAR_OPTIONS. */
868 static struct option_locus *option_class[OC_MAX];
869
870 /* Save location of an option of class ID.  Return location of a previous
871    occurrence of an option of that class, or NULL. */
872 static struct option_locus *
873 optloc_save (unsigned int id, struct option_locus *loc)
874 {
875   struct option_locus *optloc;
876   char *p;
877   size_t s;
878
879   if (id >= sizeof (option_class) / sizeof (option_class[0]))
880     abort ();
881   s = sizeof (*loc);
882   if (loc->name)
883     s += strlen (loc->name) + 1;
884   optloc = xmalloc (s);
885   if (loc->name)
886     {
887       p = (char*) optloc + sizeof (*loc);
888       strcpy (p, loc->name);
889       optloc->name = p;
890     }
891   else
892     optloc->name = NULL;
893   optloc->source = loc->source;
894   optloc->line = loc->line;
895   optloc->prev = option_class[id];
896   option_class[id] = optloc;
897   return optloc->prev;
898 }
899
900 /* Return location of a recent option of class ID */
901 static struct option_locus *
902 optloc_lookup (int id)
903 {
904   return option_class[id];
905 }
906
907 /* Return true if the latest occurrence of option ID was in the command line */
908 static int
909 option_set_in_cl (int id)
910 {
911   struct option_locus *loc = optloc_lookup (id);
912   if (!loc)
913     return 0;
914   return loc->source == OPTS_COMMAND_LINE;
915 }
916
917 /* Compare two option locations */
918 static int
919 optloc_eq (struct option_locus *a, struct option_locus *b)
920 {
921   if (a->source != b->source)
922     return 0;
923   if (a->source == OPTS_COMMAND_LINE)
924     return 1;
925   return strcmp (a->name, b->name) == 0;
926 }
927 \f
928 static void
929 set_subcommand_option (enum subcommand subcommand)
930 {
931   if (subcommand_option != UNKNOWN_SUBCOMMAND
932       && subcommand_option != subcommand)
933     USAGE_ERROR ((0, 0,
934                   _("You may not specify more than one '-Acdtrux', '--delete' or  '--test-label' option")));
935
936   subcommand_option = subcommand;
937 }
938
939 static void
940 set_use_compress_program_option (const char *string, struct option_locus *loc)
941 {
942   struct option_locus *p = optloc_save (OC_COMPRESS, loc);
943   if (use_compress_program_option
944       && strcmp (use_compress_program_option, string) != 0
945       && p->source == OPTS_COMMAND_LINE)
946     USAGE_ERROR ((0, 0, _("Conflicting compression options")));
947
948   use_compress_program_option = string;
949 }
950 \f
951 static void
952 sigstat (int signo)
953 {
954   compute_duration ();
955   print_total_stats ();
956 #ifndef HAVE_SIGACTION
957   signal (signo, sigstat);
958 #endif
959 }
960
961 static void
962 stat_on_signal (int signo)
963 {
964 #ifdef HAVE_SIGACTION
965 # ifndef SA_RESTART
966 #  define SA_RESTART 0
967 # endif
968   struct sigaction act;
969   act.sa_handler = sigstat;
970   sigemptyset (&act.sa_mask);
971   act.sa_flags = SA_RESTART;
972   sigaction (signo, &act, NULL);
973 #else
974   signal (signo, sigstat);
975 #endif
976 }
977
978 static void
979 set_stat_signal (const char *name)
980 {
981   static struct sigtab
982   {
983     char const *name;
984     int signo;
985   } const sigtab[] = {
986     { "SIGUSR1", SIGUSR1 },
987     { "USR1", SIGUSR1 },
988     { "SIGUSR2", SIGUSR2 },
989     { "USR2", SIGUSR2 },
990     { "SIGHUP", SIGHUP },
991     { "HUP", SIGHUP },
992     { "SIGINT", SIGINT },
993     { "INT", SIGINT },
994     { "SIGQUIT", SIGQUIT },
995     { "QUIT", SIGQUIT }
996   };
997   struct sigtab const *p;
998
999   for (p = sigtab; p < sigtab + sizeof (sigtab) / sizeof (sigtab[0]); p++)
1000     if (strcmp (p->name, name) == 0)
1001       {
1002         stat_on_signal (p->signo);
1003         return;
1004       }
1005   FATAL_ERROR ((0, 0, _("Unknown signal name: %s"), name));
1006 }
1007
1008 \f
1009 struct textual_date
1010 {
1011   struct textual_date *next;
1012   struct timespec ts;
1013   const char *option;
1014   char *date;
1015 };
1016
1017 static int
1018 get_date_or_file (struct tar_args *args, const char *option,
1019                   const char *str, struct timespec *ts)
1020 {
1021   if (FILE_SYSTEM_PREFIX_LEN (str) != 0
1022       || ISSLASH (*str)
1023       || *str == '.')
1024     {
1025       struct stat st;
1026       if (stat (str, &st) != 0)
1027         {
1028           stat_error (str);
1029           USAGE_ERROR ((0, 0, _("Date sample file not found")));
1030         }
1031       *ts = get_stat_mtime (&st);
1032     }
1033   else
1034     {
1035       if (! parse_datetime (ts, str, NULL))
1036         {
1037           WARN ((0, 0, _("Substituting %s for unknown date format %s"),
1038                  tartime (*ts, false), quote (str)));
1039           ts->tv_nsec = 0;
1040           return 1;
1041         }
1042       else
1043         {
1044           struct textual_date *p = xmalloc (sizeof (*p));
1045           p->ts = *ts;
1046           p->option = option;
1047           p->date = xstrdup (str);
1048           p->next = args->textual_date;
1049           args->textual_date = p;
1050         }
1051     }
1052   return 0;
1053 }
1054
1055 static void
1056 report_textual_dates (struct tar_args *args)
1057 {
1058   struct textual_date *p;
1059   for (p = args->textual_date; p; )
1060     {
1061       struct textual_date *next = p->next;
1062       if (verbose_option)
1063         {
1064           char const *treated_as = tartime (p->ts, true);
1065           if (strcmp (p->date, treated_as) != 0)
1066             WARN ((0, 0, _("Option %s: Treating date '%s' as %s"),
1067                    p->option, p->date, treated_as));
1068         }
1069       free (p->date);
1070       free (p);
1071       p = next;
1072     }
1073 }
1074
1075 \f
1076 /* Default density numbers for [0-9][lmh] device specifications */
1077
1078 #if defined DEVICE_PREFIX && !defined DENSITY_LETTER
1079 # ifndef LOW_DENSITY_NUM
1080 #  define LOW_DENSITY_NUM 0
1081 # endif
1082
1083 # ifndef MID_DENSITY_NUM
1084 #  define MID_DENSITY_NUM 8
1085 # endif
1086
1087 # ifndef HIGH_DENSITY_NUM
1088 #  define HIGH_DENSITY_NUM 16
1089 # endif
1090 #endif
1091
1092 \f
1093 static char *
1094 tar_help_filter (int key, const char *text, void *input)
1095 {
1096   struct obstack stk;
1097   char *s;
1098
1099   switch (key)
1100     {
1101     default:
1102       s = (char*) text;
1103       break;
1104
1105     case 'j':
1106       s = xasprintf (_("filter the archive through %s"), BZIP2_PROGRAM);
1107       break;
1108
1109     case 'z':
1110       s = xasprintf (_("filter the archive through %s"), GZIP_PROGRAM);
1111       break;
1112
1113     case 'Z':
1114       s = xasprintf (_("filter the archive through %s"), COMPRESS_PROGRAM);
1115       break;
1116
1117     case LZIP_OPTION:
1118       s = xasprintf (_("filter the archive through %s"), LZIP_PROGRAM);
1119       break;
1120
1121     case LZMA_OPTION:
1122       s = xasprintf (_("filter the archive through %s"), LZMA_PROGRAM);
1123       break;
1124
1125     case LZOP_OPTION:
1126       s = xasprintf (_("filter the archive through %s"), LZOP_PROGRAM);
1127
1128     case 'J':
1129       s = xasprintf (_("filter the archive through %s"), XZ_PROGRAM);
1130       break;
1131
1132     case ARGP_KEY_HELP_EXTRA:
1133       {
1134         const char *tstr;
1135
1136         obstack_init (&stk);
1137         tstr = _("Valid arguments for the --quoting-style option are:");
1138         obstack_grow (&stk, tstr, strlen (tstr));
1139         obstack_grow (&stk, "\n\n", 2);
1140         tar_list_quoting_styles (&stk, "  ");
1141         tstr = _("\n*This* tar defaults to:\n");
1142         obstack_grow (&stk, tstr, strlen (tstr));
1143         s = format_default_settings ();
1144         obstack_grow (&stk, s, strlen (s));
1145         obstack_1grow (&stk, '\n');
1146         obstack_1grow (&stk, 0);
1147         s = xstrdup (obstack_finish (&stk));
1148         obstack_free (&stk, NULL);
1149       }
1150     }
1151   return s;
1152 }
1153 \f
1154 static char *
1155 expand_pax_option (struct tar_args *targs, const char *arg)
1156 {
1157   struct obstack stk;
1158   char *res;
1159
1160   obstack_init (&stk);
1161   while (*arg)
1162     {
1163       size_t seglen = strcspn (arg, ",");
1164       char *p = memchr (arg, '=', seglen);
1165       if (p)
1166         {
1167           size_t len = p - arg + 1;
1168           obstack_grow (&stk, arg, len);
1169           len = seglen - len;
1170           for (++p; *p && isspace ((unsigned char) *p); p++)
1171             len--;
1172           if (*p == '{' && p[len-1] == '}')
1173             {
1174               struct timespec ts;
1175               char *tmp = xmalloc (len);
1176               memcpy (tmp, p + 1, len-2);
1177               tmp[len-2] = 0;
1178               if (get_date_or_file (targs, "--pax-option", tmp, &ts) == 0)
1179                 {
1180                   char buf[TIMESPEC_STRSIZE_BOUND];
1181                   char const *s = code_timespec (ts, buf);
1182                   obstack_grow (&stk, s, strlen (s));
1183                 }
1184               else
1185                 obstack_grow (&stk, p, len);
1186               free (tmp);
1187             }
1188           else
1189             obstack_grow (&stk, p, len);
1190         }
1191       else
1192         obstack_grow (&stk, arg, seglen);
1193
1194       arg += seglen;
1195       if (*arg)
1196         {
1197           obstack_1grow (&stk, *arg);
1198           arg++;
1199         }
1200     }
1201   obstack_1grow (&stk, 0);
1202   res = xstrdup (obstack_finish (&stk));
1203   obstack_free (&stk, NULL);
1204   return res;
1205 }
1206
1207 \f
1208 static uintmax_t
1209 parse_owner_group (char *arg, uintmax_t field_max, char const **name_option)
1210 {
1211   uintmax_t u = UINTMAX_MAX;
1212   char *end;
1213   char const *name = 0;
1214   char const *invalid_num = 0;
1215   char *colon = strchr (arg, ':');
1216
1217   if (colon)
1218     {
1219       char const *num = colon + 1;
1220       *colon = '\0';
1221       if (*arg)
1222         name = arg;
1223       if (num && (! (xstrtoumax (num, &end, 10, &u, "") == LONGINT_OK
1224                      && u <= field_max)))
1225         invalid_num = num;
1226     }
1227   else
1228     {
1229       uintmax_t u1;
1230       switch ('0' <= *arg && *arg <= '9'
1231               ? xstrtoumax (arg, &end, 10, &u1, "")
1232               : LONGINT_INVALID)
1233         {
1234         default:
1235           name = arg;
1236           break;
1237
1238         case LONGINT_OK:
1239           if (u1 <= field_max)
1240             {
1241               u = u1;
1242               break;
1243             }
1244           /* Fall through.  */
1245         case LONGINT_OVERFLOW:
1246           invalid_num = arg;
1247           break;
1248         }
1249     }
1250
1251   if (invalid_num)
1252     FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (invalid_num),
1253                   _("Invalid owner or group ID")));
1254   if (name)
1255     *name_option = name;
1256   return u;
1257 }
1258
1259 #define TAR_SIZE_SUFFIXES "bBcGgkKMmPTtw"
1260
1261 static char const *const sort_mode_arg[] = {
1262   "none",
1263   "name",
1264 #if D_INO_IN_DIRENT
1265   "inode",
1266 #endif
1267   NULL
1268 };
1269
1270 static int sort_mode_flag[] = {
1271     SAVEDIR_SORT_NONE,
1272     SAVEDIR_SORT_NAME,
1273 #if D_INO_IN_DIRENT
1274     SAVEDIR_SORT_INODE
1275 #endif
1276 };
1277
1278 ARGMATCH_VERIFY (sort_mode_arg, sort_mode_flag);
1279
1280 static char const *const hole_detection_args[] =
1281 {
1282   "raw", "seek", NULL
1283 };
1284
1285 static int const hole_detection_types[] =
1286 {
1287   HOLE_DETECTION_RAW, HOLE_DETECTION_SEEK
1288 };
1289
1290 ARGMATCH_VERIFY (hole_detection_args, hole_detection_types);
1291
1292 \f
1293 static void
1294 set_old_files_option (int code, struct option_locus *loc)
1295 {
1296   struct option_locus *prev;
1297   static char const *const code_to_opt[] = {
1298     "--overwrite-dir",
1299     "--no-overwrite-dir",
1300     "--overwrite",
1301     "--unlink-first",
1302     "--keep-old-files",
1303     "--skip-old-files",
1304     "--keep-newer-files"
1305   };
1306
1307   prev = optloc_save (OC_OLD_FILES, loc);
1308   if (prev && optloc_eq (loc, prev) && code != old_files_option)
1309     option_conflict_error (code_to_opt[code], code_to_opt[old_files_option]);
1310
1311   old_files_option = code;
1312 }
1313 \f
1314 \f
1315 static error_t
1316 parse_opt (int key, char *arg, struct argp_state *state)
1317 {
1318   struct tar_args *args = state->input;
1319
1320   switch (key)
1321     {
1322     case ARGP_KEY_ARG:
1323       /* File name or non-parsed option, because of ARGP_IN_ORDER */
1324       name_add_name (arg);
1325       args->input_files = true;
1326       break;
1327
1328     case 'A':
1329       set_subcommand_option (CAT_SUBCOMMAND);
1330       break;
1331
1332     case 'a':
1333       args->compress_autodetect = true;
1334       break;
1335
1336     case NO_AUTO_COMPRESS_OPTION:
1337       args->compress_autodetect = false;
1338       break;
1339
1340     case 'b':
1341       {
1342         uintmax_t u;
1343         if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1344                && u == (blocking_factor = u)
1345                && 0 < blocking_factor
1346                && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE))
1347           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1348                         _("Invalid blocking factor")));
1349       }
1350       break;
1351
1352     case 'B':
1353       /* Try to reblock input records.  For reading 4.2BSD pipes.  */
1354
1355       /* It would surely make sense to exchange -B and -R, but it seems
1356          that -B has been used for a long while in Sun tar and most
1357          BSD-derived systems.  This is a consequence of the block/record
1358          terminology confusion.  */
1359
1360       read_full_records_option = true;
1361       break;
1362
1363     case 'c':
1364       set_subcommand_option (CREATE_SUBCOMMAND);
1365       break;
1366
1367     case CLAMP_MTIME_OPTION:
1368       set_mtime_option = CLAMP_MTIME;
1369       break;
1370
1371     case 'd':
1372       set_subcommand_option (DIFF_SUBCOMMAND);
1373       break;
1374
1375     case 'f':
1376       if (archive_names == allocated_archive_names)
1377         archive_name_array = x2nrealloc (archive_name_array,
1378                                          &allocated_archive_names,
1379                                          sizeof (archive_name_array[0]));
1380
1381       archive_name_array[archive_names++] = arg;
1382       break;
1383
1384     case 'F':
1385       /* Since -F is only useful with -M, make it implied.  Run this
1386          script at the end of each tape.  */
1387
1388       info_script_option = arg;
1389       multi_volume_option = true;
1390       break;
1391
1392     case FULL_TIME_OPTION:
1393       full_time_option = true;
1394       break;
1395
1396     case 'g':
1397       optloc_save (OC_LISTED_INCREMENTAL, args->loc);
1398       listed_incremental_option = arg;
1399       after_date_option = true;
1400       /* Fall through.  */
1401
1402     case 'G':
1403       /* We are making an incremental dump (FIXME: are we?); save
1404          directories at the beginning of the archive, and include in each
1405          directory its contents.  */
1406
1407       incremental_option = true;
1408       break;
1409
1410     case 'h':
1411       /* Follow symbolic links.  */
1412       dereference_option = true;
1413       break;
1414
1415     case HARD_DEREFERENCE_OPTION:
1416       hard_dereference_option = true;
1417       break;
1418
1419     case 'i':
1420       /* Ignore zero blocks (eofs).  This can't be the default,
1421          because Unix tar writes two blocks of zeros, then pads out
1422          the record with garbage.  */
1423
1424       ignore_zeros_option = true;
1425       break;
1426
1427     case 'j':
1428       set_use_compress_program_option (BZIP2_PROGRAM, args->loc);
1429       break;
1430
1431     case 'J':
1432       set_use_compress_program_option (XZ_PROGRAM, args->loc);
1433       break;
1434
1435     case 'k':
1436       /* Don't replace existing files.  */
1437       set_old_files_option (KEEP_OLD_FILES, args->loc);
1438       break;
1439
1440     case 'K':
1441       optloc_save (OC_STARTING_FILE, args->loc);
1442       starting_file_option = true;
1443       addname (arg, 0, true, NULL);
1444       break;
1445
1446     case ONE_FILE_SYSTEM_OPTION:
1447       /* When dumping directories, don't dump files/subdirectories
1448          that are on other filesystems. */
1449       one_file_system_option = true;
1450       break;
1451
1452     case ONE_TOP_LEVEL_OPTION:
1453       optloc_save (OC_ONE_TOP_LEVEL, args->loc);
1454       one_top_level_option = true;
1455       one_top_level_dir = arg;
1456       break;
1457
1458     case 'l':
1459       check_links_option = 1;
1460       break;
1461
1462     case 'L':
1463       {
1464         uintmax_t u;
1465         char *p;
1466
1467         if (xstrtoumax (arg, &p, 10, &u, TAR_SIZE_SUFFIXES) != LONGINT_OK)
1468           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1469                         _("Invalid tape length")));
1470         if (p > arg && !strchr (TAR_SIZE_SUFFIXES, p[-1]))
1471           tape_length_option = 1024 * (tarlong) u;
1472         else
1473           tape_length_option = (tarlong) u;
1474         multi_volume_option = true;
1475       }
1476       break;
1477
1478     case LEVEL_OPTION:
1479       {
1480         char *p;
1481         incremental_level = strtoul (arg, &p, 10);
1482         if (*p)
1483           USAGE_ERROR ((0, 0, _("Invalid incremental level value")));
1484       }
1485       break;
1486
1487     case LZIP_OPTION:
1488       set_use_compress_program_option (LZIP_PROGRAM, args->loc);
1489       break;
1490
1491     case LZMA_OPTION:
1492       set_use_compress_program_option (LZMA_PROGRAM, args->loc);
1493       break;
1494
1495     case LZOP_OPTION:
1496       set_use_compress_program_option (LZOP_PROGRAM, args->loc);
1497       break;
1498
1499     case 'm':
1500       touch_option = true;
1501       break;
1502
1503     case 'M':
1504       /* Make multivolume archive: when we can't write any more into
1505          the archive, re-open it, and continue writing.  */
1506
1507       multi_volume_option = true;
1508       break;
1509
1510     case MTIME_OPTION:
1511       get_date_or_file (args, "--mtime", arg, &mtime_option);
1512       if (set_mtime_option == USE_FILE_MTIME)
1513         set_mtime_option = FORCE_MTIME;
1514       break;
1515
1516     case 'n':
1517       seek_option = 1;
1518       break;
1519
1520     case NO_SEEK_OPTION:
1521       seek_option = 0;
1522       break;
1523
1524     case 'N':
1525       after_date_option = true;
1526       /* Fall through.  */
1527
1528     case NEWER_MTIME_OPTION:
1529       if (TIME_OPTION_INITIALIZED (newer_mtime_option))
1530         USAGE_ERROR ((0, 0, _("More than one threshold date")));
1531       get_date_or_file (args,
1532                         key == NEWER_MTIME_OPTION ? "--newer-mtime"
1533                         : "--after-date", arg, &newer_mtime_option);
1534       optloc_save (OC_NEWER, args->loc);
1535       break;
1536
1537     case 'o':
1538       args->o_option = true;
1539       break;
1540
1541     case 'O':
1542       to_stdout_option = true;
1543       break;
1544
1545     case 'p':
1546       same_permissions_option = true;
1547       break;
1548
1549     case 'P':
1550       optloc_save (OC_ABSOLUTE_NAMES, args->loc);
1551       absolute_names_option = true;
1552       break;
1553
1554     case 'r':
1555       set_subcommand_option (APPEND_SUBCOMMAND);
1556       break;
1557
1558     case 'R':
1559       /* Print block numbers for debugging bad tar archives.  */
1560
1561       /* It would surely make sense to exchange -B and -R, but it seems
1562          that -B has been used for a long while in Sun tar and most
1563          BSD-derived systems.  This is a consequence of the block/record
1564          terminology confusion.  */
1565
1566       block_number_option = true;
1567       break;
1568
1569     case 's':
1570       /* Names to extract are sorted.  */
1571       optloc_save (OC_SAME_ORDER, args->loc);
1572       same_order_option = true;
1573       break;
1574
1575     case 'S':
1576       sparse_option = true;
1577       break;
1578
1579     case SKIP_OLD_FILES_OPTION:
1580       set_old_files_option (SKIP_OLD_FILES, args->loc);
1581       break;
1582
1583     case HOLE_DETECTION_OPTION:
1584       hole_detection = XARGMATCH ("--hole-detection", arg,
1585                                   hole_detection_args, hole_detection_types);
1586       sparse_option = true;
1587       break;
1588
1589     case SPARSE_VERSION_OPTION:
1590       sparse_option = true;
1591       {
1592         char *p;
1593         tar_sparse_major = strtoul (arg, &p, 10);
1594         if (*p)
1595           {
1596             if (*p != '.')
1597               USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1598             tar_sparse_minor = strtoul (p + 1, &p, 10);
1599             if (*p)
1600               USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1601           }
1602       }
1603       break;
1604
1605     case 't':
1606       set_subcommand_option (LIST_SUBCOMMAND);
1607       verbose_option++;
1608       break;
1609
1610     case TEST_LABEL_OPTION:
1611       set_subcommand_option (TEST_LABEL_SUBCOMMAND);
1612       break;
1613
1614     case 'u':
1615       set_subcommand_option (UPDATE_SUBCOMMAND);
1616       break;
1617
1618     case 'U':
1619       set_old_files_option (UNLINK_FIRST_OLD_FILES, args->loc);
1620       break;
1621
1622     case UTC_OPTION:
1623       utc_option = true;
1624       break;
1625
1626     case 'v':
1627       verbose_option++;
1628       warning_option |= WARN_VERBOSE_WARNINGS;
1629       break;
1630
1631     case 'V':
1632       volume_label_option = arg;
1633       break;
1634
1635     case 'w':
1636       interactive_option = true;
1637       break;
1638
1639     case 'W':
1640       optloc_save (OC_VERIFY, args->loc);
1641       verify_option = true;
1642       break;
1643
1644     case 'x':
1645       set_subcommand_option (EXTRACT_SUBCOMMAND);
1646       break;
1647
1648     case 'z':
1649       set_use_compress_program_option (GZIP_PROGRAM, args->loc);
1650       break;
1651
1652     case 'Z':
1653       set_use_compress_program_option (COMPRESS_PROGRAM, args->loc);
1654       break;
1655
1656     case ATIME_PRESERVE_OPTION:
1657       atime_preserve_option =
1658         (arg
1659          ? XARGMATCH ("--atime-preserve", arg,
1660                       atime_preserve_args, atime_preserve_types)
1661          : replace_atime_preserve);
1662       if (! O_NOATIME && atime_preserve_option == system_atime_preserve)
1663         FATAL_ERROR ((0, 0,
1664                       _("--atime-preserve='system' is not supported"
1665                         " on this platform")));
1666       break;
1667
1668     case CHECK_DEVICE_OPTION:
1669       check_device_option = true;
1670       break;
1671
1672     case NO_CHECK_DEVICE_OPTION:
1673       check_device_option = false;
1674       break;
1675
1676     case CHECKPOINT_OPTION:
1677       if (arg)
1678         {
1679           char *p;
1680
1681           if (*arg == '.')
1682             {
1683               checkpoint_compile_action (".");
1684               arg++;
1685             }
1686           checkpoint_option = strtoul (arg, &p, 0);
1687           if (*p)
1688             FATAL_ERROR ((0, 0,
1689                           _("--checkpoint value is not an integer")));
1690         }
1691       else
1692         checkpoint_option = DEFAULT_CHECKPOINT;
1693       break;
1694
1695     case CHECKPOINT_ACTION_OPTION:
1696       checkpoint_compile_action (arg);
1697       break;
1698
1699     case BACKUP_OPTION:
1700       backup_option = true;
1701       if (arg)
1702         args->version_control_string = arg;
1703       break;
1704
1705     case DELAY_DIRECTORY_RESTORE_OPTION:
1706       delay_directory_restore_option = true;
1707       break;
1708
1709     case NO_DELAY_DIRECTORY_RESTORE_OPTION:
1710       delay_directory_restore_option = false;
1711       break;
1712
1713     case DELETE_OPTION:
1714       set_subcommand_option (DELETE_SUBCOMMAND);
1715       break;
1716
1717     case FORCE_LOCAL_OPTION:
1718       force_local_option = true;
1719       break;
1720
1721     case 'H':
1722       set_archive_format (arg);
1723       break;
1724
1725     case INDEX_FILE_OPTION:
1726       index_file_name = arg;
1727       break;
1728
1729     case IGNORE_COMMAND_ERROR_OPTION:
1730       ignore_command_error_option = true;
1731       break;
1732
1733     case IGNORE_FAILED_READ_OPTION:
1734       ignore_failed_read_option = true;
1735       break;
1736
1737     case KEEP_DIRECTORY_SYMLINK_OPTION:
1738       keep_directory_symlink_option = true;
1739       break;
1740
1741     case KEEP_NEWER_FILES_OPTION:
1742       set_old_files_option (KEEP_NEWER_FILES, args->loc);
1743       break;
1744
1745     case GROUP_OPTION:
1746       {
1747         uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (gid_t),
1748                                          &group_name_option);
1749         if (u == UINTMAX_MAX)
1750           {
1751             group_option = -1;
1752             if (group_name_option)
1753               gname_to_gid (group_name_option, &group_option);
1754           }
1755         else
1756           group_option = u;
1757       }
1758       break;
1759
1760     case GROUP_MAP_OPTION:
1761       group_map_read (arg);
1762       break;
1763       
1764     case MODE_OPTION:
1765       mode_option = mode_compile (arg);
1766       if (!mode_option)
1767         FATAL_ERROR ((0, 0, _("Invalid mode given on option")));
1768       initial_umask = umask (0);
1769       umask (initial_umask);
1770       break;
1771
1772     case NO_IGNORE_COMMAND_ERROR_OPTION:
1773       ignore_command_error_option = false;
1774       break;
1775
1776     case NO_OVERWRITE_DIR_OPTION:
1777       set_old_files_option (NO_OVERWRITE_DIR_OLD_FILES, args->loc);
1778       break;
1779
1780     case NO_QUOTE_CHARS_OPTION:
1781       for (;*arg; arg++)
1782         set_char_quoting (NULL, *arg, 0);
1783       break;
1784
1785     case NUMERIC_OWNER_OPTION:
1786       numeric_owner_option = true;
1787       break;
1788
1789     case OCCURRENCE_OPTION:
1790       optloc_save (OC_OCCURRENCE, args->loc);
1791       if (!arg)
1792         occurrence_option = 1;
1793       else
1794         {
1795           uintmax_t u;
1796           if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK)
1797             occurrence_option = u;
1798           else
1799             FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1800                           _("Invalid number")));
1801         }
1802       break;
1803
1804     case OLD_ARCHIVE_OPTION:
1805       set_archive_format ("v7");
1806       break;
1807
1808     case OVERWRITE_DIR_OPTION:
1809       set_old_files_option (DEFAULT_OLD_FILES, args->loc);
1810       break;
1811
1812     case OVERWRITE_OPTION:
1813       set_old_files_option (OVERWRITE_OLD_FILES, args->loc);
1814       break;
1815
1816     case OWNER_OPTION:
1817       {
1818         uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (uid_t),
1819                                          &owner_name_option);
1820         if (u == UINTMAX_MAX)
1821           {
1822             owner_option = -1;
1823             if (owner_name_option)
1824               uname_to_uid (owner_name_option, &owner_option);
1825           }
1826         else
1827           owner_option = u;
1828       }
1829       break;
1830
1831     case OWNER_MAP_OPTION:
1832       owner_map_read (arg);
1833       break;
1834       
1835     case QUOTE_CHARS_OPTION:
1836       for (;*arg; arg++)
1837         set_char_quoting (NULL, *arg, 1);
1838       break;
1839
1840     case QUOTING_STYLE_OPTION:
1841       tar_set_quoting_style (arg);
1842       break;
1843
1844     case PAX_OPTION:
1845       {
1846         char *tmp = expand_pax_option (args, arg);
1847         args->pax_option = true;
1848         xheader_set_option (tmp);
1849         free (tmp);
1850       }
1851       break;
1852
1853     case POSIX_OPTION:
1854       set_archive_format ("posix");
1855       break;
1856
1857     case RECORD_SIZE_OPTION:
1858       {
1859         uintmax_t u;
1860
1861         if (! (xstrtoumax (arg, NULL, 10, &u, TAR_SIZE_SUFFIXES) == LONGINT_OK
1862                && u == (size_t) u))
1863           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1864                         _("Invalid record size")));
1865         record_size = u;
1866         if (record_size % BLOCKSIZE != 0)
1867           USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
1868                         BLOCKSIZE));
1869         blocking_factor = record_size / BLOCKSIZE;
1870       }
1871       break;
1872
1873     case RECURSIVE_UNLINK_OPTION:
1874       recursive_unlink_option = true;
1875       break;
1876
1877     case REMOVE_FILES_OPTION:
1878       remove_files_option = true;
1879       break;
1880
1881     case RESTRICT_OPTION:
1882       restrict_option = true;
1883       break;
1884
1885     case RMT_COMMAND_OPTION:
1886       rmt_command = arg;
1887       break;
1888
1889     case RSH_COMMAND_OPTION:
1890       rsh_command_option = arg;
1891       break;
1892
1893     case SHOW_DEFAULTS_OPTION:
1894       {
1895         char *s = format_default_settings ();
1896         printf ("%s\n", s);
1897         close_stdout ();
1898         free (s);
1899         exit (0);
1900       }
1901
1902     case SHOW_SNAPSHOT_FIELD_RANGES_OPTION:
1903       show_snapshot_field_ranges ();
1904       close_stdout ();
1905       exit (0);
1906
1907     case STRIP_COMPONENTS_OPTION:
1908       {
1909         uintmax_t u;
1910         if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1911                && u == (size_t) u))
1912           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1913                         _("Invalid number of elements")));
1914         strip_name_components = u;
1915       }
1916       break;
1917
1918     case SHOW_OMITTED_DIRS_OPTION:
1919       show_omitted_dirs_option = true;
1920       break;
1921
1922     case SHOW_TRANSFORMED_NAMES_OPTION:
1923       show_transformed_names_option = true;
1924       break;
1925
1926     case SORT_OPTION:
1927       savedir_sort_order = XARGMATCH ("--sort", arg,
1928                                       sort_mode_arg, sort_mode_flag);
1929       break;
1930
1931     case SUFFIX_OPTION:
1932       backup_option = true;
1933       args->backup_suffix_string = arg;
1934       break;
1935
1936     case TO_COMMAND_OPTION:
1937       if (to_command_option)
1938         USAGE_ERROR ((0, 0, _("Only one --to-command option allowed")));
1939       to_command_option = arg;
1940       break;
1941
1942     case TOTALS_OPTION:
1943       if (arg)
1944         set_stat_signal (arg);
1945       else
1946         totals_option = true;
1947       break;
1948
1949     case TRANSFORM_OPTION:
1950       set_transform_expr (arg);
1951       break;
1952
1953     case 'I':
1954       set_use_compress_program_option (arg, args->loc);
1955       break;
1956
1957     case VOLNO_FILE_OPTION:
1958       volno_file_option = arg;
1959       break;
1960
1961     case NO_SAME_OWNER_OPTION:
1962       same_owner_option = -1;
1963       break;
1964
1965     case NO_SAME_PERMISSIONS_OPTION:
1966       same_permissions_option = -1;
1967       break;
1968
1969     case ACLS_OPTION:
1970       set_archive_format ("posix");
1971       acls_option = 1;
1972       break;
1973
1974     case NO_ACLS_OPTION:
1975       acls_option = -1;
1976       break;
1977
1978     case SELINUX_CONTEXT_OPTION:
1979       set_archive_format ("posix");
1980       selinux_context_option = 1;
1981       break;
1982
1983     case NO_SELINUX_CONTEXT_OPTION:
1984       selinux_context_option = -1;
1985       break;
1986
1987     case XATTR_OPTION:
1988       set_xattr_option (1);
1989       break;
1990
1991     case NO_XATTR_OPTION:
1992       set_xattr_option (-1);
1993       break;
1994
1995     case XATTR_INCLUDE:
1996     case XATTR_EXCLUDE:
1997       set_xattr_option (1);
1998       xattrs_mask_add (arg, (key == XATTR_INCLUDE));
1999       break;
2000
2001     case SAME_OWNER_OPTION:
2002       same_owner_option = 1;
2003       break;
2004
2005     case WARNING_OPTION:
2006       set_warning_option (arg);
2007       break;
2008
2009     case '0':
2010     case '1':
2011     case '2':
2012     case '3':
2013     case '4':
2014     case '5':
2015     case '6':
2016     case '7':
2017
2018 #ifdef DEVICE_PREFIX
2019       {
2020         int device = key - '0';
2021         int density;
2022         static char buf[sizeof DEVICE_PREFIX + 10];
2023         char *cursor;
2024
2025         if (arg[1])
2026           argp_error (state, _("Malformed density argument: %s"), quote (arg));
2027
2028         strcpy (buf, DEVICE_PREFIX);
2029         cursor = buf + strlen (buf);
2030
2031 #ifdef DENSITY_LETTER
2032
2033         sprintf (cursor, "%d%c", device, arg[0]);
2034
2035 #else /* not DENSITY_LETTER */
2036
2037         switch (arg[0])
2038           {
2039           case 'l':
2040             device += LOW_DENSITY_NUM;
2041             break;
2042
2043           case 'm':
2044             device += MID_DENSITY_NUM;
2045             break;
2046
2047           case 'h':
2048             device += HIGH_DENSITY_NUM;
2049             break;
2050
2051           default:
2052             argp_error (state, _("Unknown density: '%c'"), arg[0]);
2053           }
2054         sprintf (cursor, "%d", device);
2055
2056 #endif /* not DENSITY_LETTER */
2057
2058         if (archive_names == allocated_archive_names)
2059           archive_name_array = x2nrealloc (archive_name_array,
2060                                            &allocated_archive_names,
2061                                            sizeof (archive_name_array[0]));
2062         archive_name_array[archive_names++] = xstrdup (buf);
2063       }
2064       break;
2065
2066 #else /* not DEVICE_PREFIX */
2067
2068       argp_error (state,
2069                   _("Options '-[0-7][lmh]' not supported by *this* tar"));
2070
2071 #endif /* not DEVICE_PREFIX */
2072
2073     case ARGP_KEY_ERROR:
2074       if (args->loc->source == OPTS_FILE)
2075         error (0, 0, _("%s:%lu: location of the error"), args->loc->name,
2076                (unsigned long) args->loc->line);
2077       else if (args->loc->source == OPTS_ENVIRON)
2078         error (0, 0, _("error parsing %s"), args->loc->name);
2079       exit (EX_USAGE);
2080
2081     default:
2082       return ARGP_ERR_UNKNOWN;
2083     }
2084   return 0;
2085 }
2086
2087 extern struct argp_child names_argp_children[];
2088
2089 static struct argp argp = {
2090   options,
2091   parse_opt,
2092   N_("[FILE]..."),
2093   doc,
2094   names_argp_children,
2095   tar_help_filter,
2096   NULL
2097 };
2098
2099 void
2100 usage (int status)
2101 {
2102   argp_help (&argp, stderr, ARGP_HELP_SEE, (char*) program_name);
2103   close_stdout ();
2104   exit (status);
2105 }
2106
2107 /* Parse the options for tar.  */
2108
2109 static struct argp_option const *
2110 find_argp_option_key (struct argp_option const *o, int key)
2111 {
2112   for (;
2113        !(o->name == NULL
2114          && o->key == 0
2115          && o->arg == 0
2116          && o->flags == 0
2117          && o->doc == NULL); o++)
2118     if (o->key == key)
2119       return o;
2120   return NULL;
2121 }
2122
2123 static struct argp_option const *
2124 find_argp_option (struct argp *ap, int key)
2125 {
2126   struct argp_option const *p = NULL;
2127   struct argp_child const *child;
2128   
2129   p = find_argp_option_key (ap->options, key);
2130   if (!p && ap->children)
2131     {
2132       for (child = ap->children; child->argp; child++)
2133         {
2134           p = find_argp_option_key (child->argp->options, key);
2135           if (p)
2136             break;
2137         }
2138     }
2139   return p;
2140 }
2141   
2142 static const char *tar_authors[] = {
2143   "John Gilmore",
2144   "Jay Fenlason",
2145   NULL
2146 };
2147 \f
2148 /* Subcommand classes */
2149 #define SUBCL_READ    0x01   /* subcommand reads from the archive */
2150 #define SUBCL_WRITE   0x02   /* subcommand writes to the archive */
2151 #define SUBCL_UPDATE  0x04   /* subcommand updates existing archive */
2152 #define SUBCL_TEST    0x08   /* subcommand tests archive header or meta-info */
2153 #define SUBCL_OCCUR   0x10   /* subcommand allows the use of the occurrence
2154                                 option */
2155
2156 static int subcommand_class[] = {
2157   /* UNKNOWN_SUBCOMMAND */     0,
2158   /* APPEND_SUBCOMMAND  */     SUBCL_WRITE|SUBCL_UPDATE,
2159   /* CAT_SUBCOMMAND     */     SUBCL_WRITE,
2160   /* CREATE_SUBCOMMAND  */     SUBCL_WRITE,
2161   /* DELETE_SUBCOMMAND  */     SUBCL_WRITE|SUBCL_UPDATE|SUBCL_OCCUR,
2162   /* DIFF_SUBCOMMAND    */     SUBCL_READ|SUBCL_OCCUR,
2163   /* EXTRACT_SUBCOMMAND */     SUBCL_READ|SUBCL_OCCUR,
2164   /* LIST_SUBCOMMAND    */     SUBCL_READ|SUBCL_OCCUR,
2165   /* UPDATE_SUBCOMMAND  */     SUBCL_WRITE|SUBCL_UPDATE,
2166   /* TEST_LABEL_SUBCOMMAND */  SUBCL_TEST
2167 };
2168
2169 /* Return t if the subcommand_option is in class(es) f */
2170 #define IS_SUBCOMMAND_CLASS(f) (subcommand_class[subcommand_option] & (f))
2171
2172 static struct tar_args args;
2173
2174 void
2175 more_options (int argc, char **argv, struct option_locus *loc)
2176 {
2177   int idx;
2178
2179   args.loc = loc;
2180   if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER|ARGP_NO_EXIT, &idx, &args))
2181     abort (); /* shouldn't happen */
2182   if (loc->source == OPTS_ENVIRON && args.input_files)
2183     USAGE_ERROR ((0, 0, _("non-option arguments in %s"), loc->name));
2184 }
2185
2186 static void
2187 parse_default_options (void)
2188 {
2189   char *opts = getenv ("TAR_OPTIONS");
2190   struct wordsplit ws;
2191   struct option_locus loc = { OPTS_ENVIRON, "TAR_OPTIONS", 0, 0 };
2192
2193   if (!opts)
2194     return;
2195
2196   ws.ws_offs = 1;
2197   if (wordsplit (opts, &ws, WRDSF_DEFFLAGS|WRDSF_DOOFFS))
2198     FATAL_ERROR ((0, 0, _("cannot split TAR_OPTIONS: %s"),
2199                   wordsplit_strerror (&ws)));
2200   if (ws.ws_wordc)
2201     {
2202       ws.ws_wordv[0] = (char*) program_name;
2203       more_options (ws.ws_offs + ws.ws_wordc, ws.ws_wordv, &loc);
2204     }
2205
2206   wordsplit_free (&ws);
2207 }
2208
2209 static void
2210 decode_options (int argc, char **argv)
2211 {
2212   int idx;
2213   struct option_locus loc = { OPTS_COMMAND_LINE, 0, 0, 0 };
2214
2215   argp_version_setup ("tar", tar_authors);
2216
2217   /* Set some default option values.  */
2218   args.textual_date = NULL;
2219   args.o_option = false;
2220   args.pax_option = false;
2221   args.backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
2222   args.version_control_string = 0;
2223   args.input_files = false;
2224   args.compress_autodetect = false;
2225
2226   subcommand_option = UNKNOWN_SUBCOMMAND;
2227   archive_format = DEFAULT_FORMAT;
2228   blocking_factor = DEFAULT_BLOCKING;
2229   record_size = DEFAULT_BLOCKING * BLOCKSIZE;
2230   excluded = new_exclude ();
2231   hole_detection = HOLE_DETECTION_DEFAULT;
2232
2233   newer_mtime_option.tv_sec = TYPE_MINIMUM (time_t);
2234   newer_mtime_option.tv_nsec = -1;
2235   mtime_option.tv_sec = TYPE_MINIMUM (time_t);
2236   mtime_option.tv_nsec = -1;
2237   recursion_option = FNM_LEADING_DIR;
2238   unquote_option = true;
2239   tar_sparse_major = 1;
2240   tar_sparse_minor = 0;
2241
2242   savedir_sort_order = SAVEDIR_SORT_NONE;
2243
2244   owner_option = -1; owner_name_option = NULL;
2245   group_option = -1; group_name_option = NULL;
2246
2247   check_device_option = true;
2248
2249   incremental_level = -1;
2250
2251   seek_option = -1;
2252
2253   /* Convert old-style tar call by exploding option element and rearranging
2254      options accordingly.  */
2255
2256   if (argc > 1 && argv[1][0] != '-')
2257     {
2258       int new_argc;             /* argc value for rearranged arguments */
2259       char **new_argv;          /* argv value for rearranged arguments */
2260       char *const *in;          /* cursor into original argv */
2261       char **out;               /* cursor into rearranged argv */
2262       const char *letter;       /* cursor into old option letters */
2263       char buffer[3];           /* constructed option buffer */
2264
2265       /* Initialize a constructed option.  */
2266
2267       buffer[0] = '-';
2268       buffer[2] = '\0';
2269
2270       /* Allocate a new argument array, and copy program name in it.  */
2271
2272       new_argc = argc - 1 + strlen (argv[1]);
2273       new_argv = xmalloc ((new_argc + 1) * sizeof (char *));
2274       in = argv;
2275       out = new_argv;
2276       *out++ = *in++;
2277
2278       /* Copy each old letter option as a separate option, and have the
2279          corresponding argument moved next to it.  */
2280
2281       for (letter = *in++; *letter; letter++)
2282         {
2283           struct argp_option const *opt;
2284
2285           buffer[1] = *letter;
2286           *out++ = xstrdup (buffer);
2287           opt = find_argp_option (&argp, *letter);
2288           if (opt && opt->arg)
2289             {
2290               if (in < argv + argc)
2291                 *out++ = *in++;
2292               else
2293                 USAGE_ERROR ((0, 0, _("Old option '%c' requires an argument."),
2294                               *letter));
2295             }
2296         }
2297
2298       /* Copy all remaining options.  */
2299
2300       while (in < argv + argc)
2301         *out++ = *in++;
2302       *out = 0;
2303
2304       /* Replace the old option list by the new one.  */
2305
2306       argc = new_argc;
2307       argv = new_argv;
2308     }
2309
2310   /* Parse all options and non-options as they appear.  */
2311   parse_default_options ();
2312
2313   args.loc = &loc;
2314   if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, &args))
2315     exit (TAREXIT_FAILURE);
2316
2317   /* Special handling for 'o' option:
2318
2319      GNU tar used to say "output old format".
2320      UNIX98 tar says don't chown files after extracting (we use
2321      "--no-same-owner" for this).
2322
2323      The old GNU tar semantics is retained when used with --create
2324      option, otherwise UNIX98 semantics is assumed */
2325
2326   if (args.o_option)
2327     {
2328       if (subcommand_option == CREATE_SUBCOMMAND)
2329         {
2330           /* GNU Tar <= 1.13 compatibility */
2331           set_archive_format ("v7");
2332         }
2333       else
2334         {
2335           /* UNIX98 compatibility */
2336           same_owner_option = -1;
2337         }
2338     }
2339
2340   /* Handle operands after any "--" argument.  */
2341   for (; idx < argc; idx++)
2342     {
2343       name_add_name (argv[idx]);
2344       args.input_files = true;
2345     }
2346
2347   /* Derive option values and check option consistency.  */
2348
2349   if (archive_format == DEFAULT_FORMAT)
2350     {
2351       if (args.pax_option)
2352         archive_format = POSIX_FORMAT;
2353       else
2354         archive_format = DEFAULT_ARCHIVE_FORMAT;
2355     }
2356
2357   if ((volume_label_option && subcommand_option == CREATE_SUBCOMMAND)
2358       || incremental_option
2359       || multi_volume_option
2360       || sparse_option)
2361     assert_format (FORMAT_MASK (OLDGNU_FORMAT)
2362                    | FORMAT_MASK (GNU_FORMAT)
2363                    | FORMAT_MASK (POSIX_FORMAT));
2364
2365   if (occurrence_option)
2366     {
2367       if (!args.input_files)
2368         USAGE_ERROR ((0, 0,
2369                       _("--occurrence is meaningless without a file list")));
2370       if (!IS_SUBCOMMAND_CLASS (SUBCL_OCCUR))
2371         {
2372           if (option_set_in_cl (OC_OCCURRENCE))
2373             option_conflict_error ("--occurrence",
2374                                    subcommand_string (subcommand_option));
2375           else
2376             occurrence_option = 0;
2377         }
2378     }
2379
2380   if (archive_names == 0)
2381     {
2382       /* If no archive file name given, try TAPE from the environment, or
2383          else, DEFAULT_ARCHIVE from the configuration process.  */
2384
2385       archive_names = 1;
2386       archive_name_array[0] = getenv ("TAPE");
2387       if (! archive_name_array[0])
2388         archive_name_array[0] = DEFAULT_ARCHIVE;
2389     }
2390
2391   /* Allow multiple archives only with '-M'.  */
2392
2393   if (archive_names > 1 && !multi_volume_option)
2394     USAGE_ERROR ((0, 0,
2395                   _("Multiple archive files require '-M' option")));
2396
2397   if (listed_incremental_option
2398       && TIME_OPTION_INITIALIZED (newer_mtime_option))
2399     {
2400       struct option_locus *listed_loc = optloc_lookup (OC_LISTED_INCREMENTAL);
2401       struct option_locus *newer_loc = optloc_lookup (OC_NEWER);
2402       if (optloc_eq (listed_loc, newer_loc))
2403         option_conflict_error ("--listed-incremental", "--newer");
2404       else if (listed_loc->source == OPTS_COMMAND_LINE)
2405         listed_incremental_option = NULL;
2406       else
2407         memset (&newer_mtime_option, 0, sizeof (newer_mtime_option));
2408     }
2409
2410   if (incremental_level != -1 && !listed_incremental_option)
2411     WARN ((0, 0,
2412            _("--level is meaningless without --listed-incremental")));
2413
2414   if (volume_label_option)
2415     {
2416       if (archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
2417         {
2418           size_t volume_label_max_len =
2419             (sizeof current_header->header.name
2420              - 1 /* for trailing '\0' */
2421              - (multi_volume_option
2422                 ? (sizeof " Volume "
2423                    - 1 /* for null at end of " Volume " */
2424                    + INT_STRLEN_BOUND (int) /* for volume number */
2425                    - 1 /* for sign, as 0 <= volno */)
2426                 : 0));
2427           if (volume_label_max_len < strlen (volume_label_option))
2428             USAGE_ERROR ((0, 0,
2429                           ngettext ("%s: Volume label is too long (limit is %lu byte)",
2430                                     "%s: Volume label is too long (limit is %lu bytes)",
2431                                     volume_label_max_len),
2432                           quotearg_colon (volume_label_option),
2433                           (unsigned long) volume_label_max_len));
2434         }
2435       /* else FIXME
2436          Label length in PAX format is limited by the volume size. */
2437     }
2438
2439   if (verify_option)
2440     {
2441       if (multi_volume_option)
2442         USAGE_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
2443       if (use_compress_program_option)
2444         USAGE_ERROR ((0, 0, _("Cannot verify compressed archives")));
2445       if (!IS_SUBCOMMAND_CLASS (SUBCL_WRITE))
2446         {
2447           if (option_set_in_cl (OC_VERIFY))
2448             option_conflict_error ("--verify",
2449                                    subcommand_string (subcommand_option));
2450           else
2451             verify_option = false;
2452         }
2453     }
2454
2455   if (use_compress_program_option)
2456     {
2457       if (multi_volume_option)
2458         USAGE_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
2459       if (IS_SUBCOMMAND_CLASS (SUBCL_UPDATE))
2460         USAGE_ERROR ((0, 0, _("Cannot update compressed archives")));
2461       if (subcommand_option == CAT_SUBCOMMAND)
2462         USAGE_ERROR ((0, 0, _("Cannot concatenate compressed archives")));
2463     }
2464
2465   if (set_mtime_option == CLAMP_MTIME)
2466     {
2467       if (!TIME_OPTION_INITIALIZED (mtime_option))
2468         USAGE_ERROR ((0, 0,
2469                       _("--clamp-mtime needs a date specified using --mtime")));
2470     }
2471
2472   /* It is no harm to use --pax-option on non-pax archives in archive
2473      reading mode. It may even be useful, since it allows to override
2474      file attributes from tar headers. Therefore I allow such usage.
2475      --gray */
2476   if (args.pax_option
2477       && archive_format != POSIX_FORMAT
2478       && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2479     USAGE_ERROR ((0, 0, _("--pax-option can be used only on POSIX archives")));
2480
2481   /* star creates non-POSIX typed archives with xattr support, so allow the
2482      extra headers when reading */
2483   if ((acls_option > 0)
2484       && archive_format != POSIX_FORMAT
2485       && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2486     USAGE_ERROR ((0, 0, _("--acls can be used only on POSIX archives")));
2487
2488   if ((selinux_context_option > 0)
2489       && archive_format != POSIX_FORMAT
2490       && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2491     USAGE_ERROR ((0, 0, _("--selinux can be used only on POSIX archives")));
2492
2493   if ((xattrs_option > 0)
2494       && archive_format != POSIX_FORMAT
2495       && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2496     USAGE_ERROR ((0, 0, _("--xattrs can be used only on POSIX archives")));
2497
2498   if (starting_file_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2499     {
2500       if (option_set_in_cl (OC_STARTING_FILE))
2501         option_conflict_error ("--starting-file",
2502                                subcommand_string (subcommand_option));
2503       else
2504         starting_file_option = false;
2505     }
2506
2507   if (same_order_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2508     {
2509       if (option_set_in_cl (OC_SAME_ORDER))
2510         option_conflict_error ("--same-order",
2511                                subcommand_string (subcommand_option));
2512       else
2513         same_order_option = false;
2514     }
2515
2516   if (one_top_level_option)
2517     {
2518       char *base;
2519
2520       if (absolute_names_option)
2521         {
2522           struct option_locus *one_top_level_loc =
2523             optloc_lookup (OC_ONE_TOP_LEVEL);
2524           struct option_locus *absolute_names_loc =
2525             optloc_lookup (OC_ABSOLUTE_NAMES);
2526
2527           if (optloc_eq (one_top_level_loc, absolute_names_loc))
2528             option_conflict_error ("--one-top-level", "--absolute-names");
2529           else if (one_top_level_loc->source == OPTS_COMMAND_LINE)
2530             absolute_names_option = false;
2531           else
2532             one_top_level_option = false;
2533         }
2534
2535       if (one_top_level_option && !one_top_level_dir)
2536         {
2537           /* If the user wants to guarantee that everything is under one
2538              directory, determine its name now and let it be created later.  */
2539           base = base_name (archive_name_array[0]);
2540           one_top_level_dir = strip_compression_suffix (base);
2541           free (base);
2542
2543           if (!one_top_level_dir)
2544             USAGE_ERROR ((0, 0,
2545                           _("Cannot deduce top-level directory name; "
2546                             "please set it explicitly with --one-top-level=DIR")));
2547         }
2548     }
2549
2550   /* If ready to unlink hierarchies, so we are for simpler files.  */
2551   if (recursive_unlink_option)
2552     old_files_option = UNLINK_FIRST_OLD_FILES;
2553
2554   /* Flags for accessing files to be read from or copied into.  POSIX says
2555      O_NONBLOCK has unspecified effect on most types of files, but in
2556      practice it never harms and sometimes helps.  */
2557   {
2558     int base_open_flags =
2559       (O_BINARY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK
2560        | (dereference_option ? 0 : O_NOFOLLOW)
2561        | (atime_preserve_option == system_atime_preserve ? O_NOATIME : 0));
2562     open_read_flags = O_RDONLY | base_open_flags;
2563     open_searchdir_flags = O_SEARCH | O_DIRECTORY | base_open_flags;
2564   }
2565   fstatat_flags = dereference_option ? 0 : AT_SYMLINK_NOFOLLOW;
2566
2567   if (subcommand_option == TEST_LABEL_SUBCOMMAND)
2568     {
2569       /* --test-label is silent if the user has specified the label name to
2570          compare against. */
2571       if (!args.input_files)
2572         verbose_option++;
2573     }
2574   else if (utc_option)
2575     verbose_option = 2;
2576
2577   if (tape_length_option && tape_length_option < record_size)
2578     USAGE_ERROR ((0, 0, _("Volume length cannot be less than record size")));
2579
2580   if (same_order_option && listed_incremental_option)
2581     {
2582       struct option_locus *preserve_order_loc = optloc_lookup (OC_SAME_ORDER);
2583       struct option_locus *listed_incremental_loc =
2584         optloc_lookup (OC_LISTED_INCREMENTAL);
2585
2586       if (optloc_eq (preserve_order_loc, listed_incremental_loc))
2587         option_conflict_error ("--preserve-order", "--listed-incremental");
2588       else if (preserve_order_loc->source == OPTS_COMMAND_LINE)
2589         listed_incremental_option = false;
2590       else
2591         same_order_option = false;
2592     }
2593
2594   /* Forbid using -c with no input files whatsoever.  Check that '-f -',
2595      explicit or implied, is used correctly.  */
2596
2597   switch (subcommand_option)
2598     {
2599     case CREATE_SUBCOMMAND:
2600       if (!args.input_files && !files_from_option)
2601         USAGE_ERROR ((0, 0,
2602                       _("Cowardly refusing to create an empty archive")));
2603       if (args.compress_autodetect && archive_names
2604           && strcmp (archive_name_array[0], "-"))
2605         set_compression_program_by_suffix (archive_name_array[0],
2606                                            use_compress_program_option);
2607       break;
2608
2609     case EXTRACT_SUBCOMMAND:
2610     case LIST_SUBCOMMAND:
2611     case DIFF_SUBCOMMAND:
2612     case TEST_LABEL_SUBCOMMAND:
2613       for (archive_name_cursor = archive_name_array;
2614            archive_name_cursor < archive_name_array + archive_names;
2615            archive_name_cursor++)
2616         if (!strcmp (*archive_name_cursor, "-"))
2617           request_stdin ("-f");
2618       break;
2619
2620     case CAT_SUBCOMMAND:
2621     case UPDATE_SUBCOMMAND:
2622     case APPEND_SUBCOMMAND:
2623       for (archive_name_cursor = archive_name_array;
2624            archive_name_cursor < archive_name_array + archive_names;
2625            archive_name_cursor++)
2626         if (!strcmp (*archive_name_cursor, "-"))
2627           USAGE_ERROR ((0, 0,
2628                         _("Options '-Aru' are incompatible with '-f -'")));
2629
2630     default:
2631       break;
2632     }
2633
2634   /* Initialize stdlis */
2635   if (index_file_name)
2636     {
2637       stdlis = fopen (index_file_name, "w");
2638       if (! stdlis)
2639         open_fatal (index_file_name);
2640     }
2641   else
2642     stdlis = to_stdout_option ? stderr : stdout;
2643
2644   archive_name_cursor = archive_name_array;
2645
2646   /* Prepare for generating backup names.  */
2647
2648   if (args.backup_suffix_string)
2649     simple_backup_suffix = xstrdup (args.backup_suffix_string);
2650
2651   if (backup_option)
2652     {
2653       backup_type = xget_version ("--backup", args.version_control_string);
2654       /* No backup is needed either if explicitely disabled or if
2655          the extracted files are not being written to disk. */
2656       if (backup_type == no_backups || EXTRACT_OVER_PIPE)
2657         backup_option = false;
2658     }
2659
2660   checkpoint_finish_compile ();
2661
2662   report_textual_dates (&args);
2663 }
2664
2665 \f
2666 /* Tar proper.  */
2667
2668 /* Main routine for tar.  */
2669 int
2670 main (int argc, char **argv)
2671 {
2672   set_start_time ();
2673   set_program_name (argv[0]);
2674
2675   setlocale (LC_ALL, "");
2676   bindtextdomain (PACKAGE, LOCALEDIR);
2677   textdomain (PACKAGE);
2678
2679   exit_failure = TAREXIT_FAILURE;
2680   exit_status = TAREXIT_SUCCESS;
2681   error_hook = checkpoint_flush_actions;
2682
2683   set_quoting_style (0, DEFAULT_QUOTING_STYLE);
2684
2685   /* Make sure we have first three descriptors available */
2686   stdopen ();
2687
2688   /* Pre-allocate a few structures.  */
2689
2690   allocated_archive_names = 10;
2691   archive_name_array =
2692     xmalloc (sizeof (const char *) * allocated_archive_names);
2693   archive_names = 0;
2694
2695   /* System V fork+wait does not work if SIGCHLD is ignored.  */
2696   signal (SIGCHLD, SIG_DFL);
2697
2698   /* Try to disable the ability to unlink a directory.  */
2699   priv_set_remove_linkdir ();
2700
2701   /* Decode options.  */
2702
2703   decode_options (argc, argv);
2704
2705   name_init ();
2706
2707   /* Main command execution.  */
2708
2709   if (volno_file_option)
2710     init_volume_number ();
2711
2712   switch (subcommand_option)
2713     {
2714     case UNKNOWN_SUBCOMMAND:
2715       USAGE_ERROR ((0, 0,
2716                     _("You must specify one of the '-Acdtrux', '--delete' or '--test-label' options")));
2717
2718     case CAT_SUBCOMMAND:
2719     case UPDATE_SUBCOMMAND:
2720     case APPEND_SUBCOMMAND:
2721       update_archive ();
2722       break;
2723
2724     case DELETE_SUBCOMMAND:
2725       delete_archive_members ();
2726       break;
2727
2728     case CREATE_SUBCOMMAND:
2729       create_archive ();
2730       break;
2731
2732     case EXTRACT_SUBCOMMAND:
2733       extr_init ();
2734       read_and (extract_archive);
2735
2736       /* FIXME: should extract_finish () even if an ordinary signal is
2737          received.  */
2738       extract_finish ();
2739
2740       break;
2741
2742     case LIST_SUBCOMMAND:
2743       read_and (list_archive);
2744       break;
2745
2746     case DIFF_SUBCOMMAND:
2747       diff_init ();
2748       read_and (diff_archive);
2749       break;
2750
2751     case TEST_LABEL_SUBCOMMAND:
2752       test_archive_label ();
2753     }
2754
2755   checkpoint_finish ();
2756
2757   if (totals_option)
2758     print_total_stats ();
2759
2760   if (check_links_option)
2761     check_links ();
2762
2763   if (volno_file_option)
2764     closeout_volume_number ();
2765
2766   /* Dispose of allocated memory, and return.  */
2767
2768   free (archive_name_array);
2769   xattrs_clear_setup ();
2770   name_term ();
2771
2772   if (exit_status == TAREXIT_FAILURE)
2773     error (0, 0, _("Exiting with failure status due to previous errors"));
2774
2775   if (stdlis == stdout)
2776     close_stdout ();
2777   else if (ferror (stderr) || fclose (stderr) != 0)
2778     set_exit_status (TAREXIT_FAILURE);
2779
2780   return exit_status;
2781 }
2782
2783 void
2784 tar_stat_init (struct tar_stat_info *st)
2785 {
2786   memset (st, 0, sizeof (*st));
2787 }
2788
2789 /* Close the stream or file descriptor associated with ST, and remove
2790    all traces of it from ST.  Return true if successful, false (with a
2791    diagnostic) otherwise.  */
2792 bool
2793 tar_stat_close (struct tar_stat_info *st)
2794 {
2795   int status = (st->dirstream ? closedir (st->dirstream)
2796                 : 0 < st->fd ? close (st->fd)
2797                 : 0);
2798   st->dirstream = 0;
2799   st->fd = 0;
2800
2801   if (status == 0)
2802     return true;
2803   else
2804     {
2805       close_diag (st->orig_file_name);
2806       return false;
2807     }
2808 }
2809
2810 void
2811 tar_stat_destroy (struct tar_stat_info *st)
2812 {
2813   tar_stat_close (st);
2814   xheader_xattr_free (st->xattr_map, st->xattr_map_size);
2815   free (st->orig_file_name);
2816   free (st->file_name);
2817   free (st->link_name);
2818   free (st->uname);
2819   free (st->gname);
2820   free (st->cntx_name);
2821   free (st->acls_a_ptr);
2822   free (st->acls_d_ptr);
2823   free (st->sparse_map);
2824   free (st->dumpdir);
2825   xheader_destroy (&st->xhdr);
2826   info_free_exclist (st);
2827   memset (st, 0, sizeof (*st));
2828 }
2829
2830 /* Format mask for all available formats that support nanosecond
2831    timestamp resolution. */
2832 #define NS_PRECISION_FORMAT_MASK FORMAT_MASK (POSIX_FORMAT)
2833
2834 /* Same as timespec_cmp, but ignore nanoseconds if current archive
2835    format does not provide sufficient resolution.  */
2836 int
2837 tar_timespec_cmp (struct timespec a, struct timespec b)
2838 {
2839   if (!(FORMAT_MASK (current_format) & NS_PRECISION_FORMAT_MASK))
2840     a.tv_nsec = b.tv_nsec = 0;
2841   return timespec_cmp (a, b);
2842 }
2843
2844 /* Set tar exit status to VAL, unless it is already indicating
2845    a more serious condition. This relies on the fact that the
2846    values of TAREXIT_ constants are ranged by severity. */
2847 void
2848 set_exit_status (int val)
2849 {
2850   if (val > exit_status)
2851     exit_status = val;
2852 }