]> git.gag.com Git - debian/tar/blob - src/tar.c
(verify_volume): Call set_next_block_after
[debian/tar] / src / tar.c
1 /* A tar (tape archiver) program.
2
3    Copyright (C) 1988, 1992, 1993, 1994, 1995, 1996, 1997, 1999, 2000,
4    2001, 2003, 2004 Free Software Foundation, Inc.
5
6    Written by John Gilmore, starting 1985-08-25.
7
8    This program is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by the
10    Free Software Foundation; either version 2, or (at your option) any later
11    version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
16    Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation, Inc.,
20    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "system.h"
23
24 #include <fnmatch.h>
25 #include <argp.h>
26
27 #include <signal.h>
28 #if ! defined SIGCHLD && defined SIGCLD
29 # define SIGCHLD SIGCLD
30 #endif
31
32 /* The following causes "common.h" to produce definitions of all the global
33    variables, rather than just "extern" declarations of them.  GNU tar does
34    depend on the system loader to preset all GLOBAL variables to neutral (or
35    zero) values; explicit initialization is usually not done.  */
36 #define GLOBAL
37 #include "common.h"
38
39 #include <getdate.h>
40 #include <localedir.h>
41 #include <prepargs.h>
42 #include <quotearg.h>
43 #include <xstrtol.h>
44
45 /* Local declarations.  */
46
47 #ifndef DEFAULT_ARCHIVE_FORMAT
48 # define DEFAULT_ARCHIVE_FORMAT GNU_FORMAT
49 #endif
50
51 #ifndef DEFAULT_ARCHIVE
52 # define DEFAULT_ARCHIVE "tar.out"
53 #endif
54
55 #ifndef DEFAULT_BLOCKING
56 # define DEFAULT_BLOCKING 20
57 #endif
58
59 \f
60 /* Miscellaneous.  */
61
62 /* Name of option using stdin.  */
63 static const char *stdin_used_by;
64
65 /* Doesn't return if stdin already requested.  */
66 void
67 request_stdin (const char *option)
68 {
69   if (stdin_used_by)
70     USAGE_ERROR ((0, 0, _("Options `-%s' and `-%s' both want standard input"),
71                   stdin_used_by, option));
72
73   stdin_used_by = option;
74 }
75
76 /* Returns true if and only if the user typed 'y' or 'Y'.  */
77 int
78 confirm (const char *message_action, const char *message_name)
79 {
80   static FILE *confirm_file;
81   static int confirm_file_EOF;
82
83   if (!confirm_file)
84     {
85       if (archive == 0 || stdin_used_by)
86         {
87           confirm_file = fopen (TTY_NAME, "r");
88           if (! confirm_file)
89             open_fatal (TTY_NAME);
90         }
91       else
92         {
93           request_stdin ("-w");
94           confirm_file = stdin;
95         }
96     }
97
98   fprintf (stdlis, "%s %s?", message_action, quote (message_name));
99   fflush (stdlis);
100
101   {
102     int reply = confirm_file_EOF ? EOF : getc (confirm_file);
103     int character;
104
105     for (character = reply;
106          character != '\n';
107          character = getc (confirm_file))
108       if (character == EOF)
109         {
110           confirm_file_EOF = 1;
111           fputc ('\n', stdlis);
112           fflush (stdlis);
113           break;
114         }
115     return reply == 'y' || reply == 'Y';
116   }
117 }
118
119 static struct fmttab {
120   char const *name;
121   enum archive_format fmt;
122 } const fmttab[] = {
123   { "v7",      V7_FORMAT },
124   { "oldgnu",  OLDGNU_FORMAT },
125   { "ustar",   USTAR_FORMAT },
126   { "posix",   POSIX_FORMAT },
127 #if 0 /* not fully supported yet */
128   { "star",    STAR_FORMAT },
129 #endif
130   { "gnu",     GNU_FORMAT },
131   { "pax",     POSIX_FORMAT }, /* An alias for posix */
132   { NULL,        0 }
133 };
134
135 static void
136 set_archive_format (char const *name)
137 {
138   struct fmttab const *p;
139
140   for (p = fmttab; strcmp (p->name, name) != 0; )
141     if (! (++p)->name)
142       USAGE_ERROR ((0, 0, _("%s: Invalid archive format"),
143                     quotearg_colon (name)));
144
145   archive_format = p->fmt;
146 }
147
148 static const char *
149 archive_format_string (enum archive_format fmt)
150 {
151   struct fmttab const *p;
152
153   for (p = fmttab; p->name; p++)
154     if (p->fmt == fmt)
155       return p->name;
156   return "unknown?";
157 }
158
159 #define FORMAT_MASK(n) (1<<(n))
160
161 static void
162 assert_format(unsigned fmt_mask)
163 {
164   if ((FORMAT_MASK(archive_format) & fmt_mask) == 0)
165     USAGE_ERROR ((0, 0,
166                   _("GNU features wanted on incompatible archive format")));
167 }
168
169
170 \f
171 /* Options.  */
172
173 /* For long options that unconditionally set a single flag, we have getopt
174    do it.  For the others, we share the code for the equivalent short
175    named option, the name of which is stored in the otherwise-unused `val'
176    field of the `struct option'; for long options that have no equivalent
177    short option, we use non-characters as pseudo short options,
178    starting at CHAR_MAX + 1 and going upwards.  */
179
180 enum
181 {
182   ANCHORED_OPTION = CHAR_MAX + 1,
183   ATIME_PRESERVE_OPTION,
184   BACKUP_OPTION,
185   CHECKPOINT_OPTION,
186   CHECK_LINKS_OPTION,
187   DELETE_OPTION,
188   EXCLUDE_OPTION,
189   FORCE_LOCAL_OPTION,
190   GROUP_OPTION,
191   IGNORE_CASE_OPTION,
192   IGNORE_FAILED_READ_OPTION,
193   INDEX_FILE_OPTION,
194   KEEP_NEWER_FILES_OPTION,
195   LICENSE_OPTION,
196   MODE_OPTION,
197   NEWER_MTIME_OPTION,
198   NO_ANCHORED_OPTION,
199   NO_IGNORE_CASE_OPTION,
200   NO_OVERWRITE_DIR_OPTION,
201   NO_RECURSION_OPTION,
202   NO_SAME_OWNER_OPTION,
203   NO_SAME_PERMISSIONS_OPTION,
204   NO_WILDCARDS_OPTION,
205   NO_WILDCARDS_MATCH_SLASH_OPTION,
206   NULL_OPTION,
207   NUMERIC_OWNER_OPTION,
208   OCCURRENCE_OPTION,
209   OLD_ARCHIVE_OPTION,
210   OVERWRITE_OPTION,
211   OWNER_OPTION,
212   PAX_OPTION,
213   POSIX_OPTION,
214   PRESERVE_OPTION,
215   RECORD_SIZE_OPTION,
216   RECURSION_OPTION,
217   RECURSIVE_UNLINK_OPTION,
218   REMOVE_FILES_OPTION,
219   RMT_COMMAND_OPTION,
220   RSH_COMMAND_OPTION,
221   SAME_OWNER_OPTION,
222   SHOW_DEFAULTS_OPTION,
223   SHOW_OMITTED_DIRS_OPTION,
224   STRIP_COMPONENTS_OPTION,
225   SUFFIX_OPTION,
226   TOTALS_OPTION,
227   USAGE_OPTION,
228   USE_COMPRESS_PROGRAM_OPTION,
229   UTC_OPTION,
230   VERSION_OPTION,
231   VOLNO_FILE_OPTION,
232   WILDCARDS_OPTION,
233   WILDCARDS_MATCH_SLASH_OPTION
234 };
235
236 const char *argp_program_version = "tar (" PACKAGE ") " VERSION;
237 const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
238 static char doc[] = N_("GNU `tar' saves many files together into a single tape or disk archive, and can restore individual files from the archive.\n\
239 \n\
240 Examples:\n\
241   tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.\n\
242   tar -tvf archive.tar         # List all files in archive.tar verbosely.\n\
243   tar -xf archive.tar          # Extract all files from archive.tar.\n\
244 \vThe backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
245 The version control may be set with --backup or VERSION_CONTROL, values are:\n\n\
246   t, numbered     make numbered backups\n\
247   nil, existing   numbered if numbered backups exist, simple otherwise\n\
248   never, simple   always make simple backups\n");
249
250
251 /* NOTE:
252
253    Available option letters are DEIJQY and aeqy. Consider the following
254    assignments:
255
256    [For Solaris tar compatibility]
257    e  exit immediately with a nonzero exit status if unexpected errors occur
258    E  use extended headers (--format=posix)
259    [q  alias for --occurrence=1 =/= this would better be used for quiet?]
260    [I  same as T =/= will harm star compatibility]
261    
262    y  per-file gzip compression
263    Y  per-block gzip compression */
264
265 static struct argp_option options[] = {
266   {NULL, 0, NULL, 0,
267    N_("Main operation mode:"), 0},
268   
269   {"list", 't', 0, 0,
270    N_("list the contents of an archive"), 10 },
271   {"extract", 'x', 0, 0,
272    N_("extract files from an archive"), 10 },
273   {"get", 0, 0, OPTION_ALIAS, NULL, 0 },
274   {"create", 'c', 0, 0,
275    N_("create a new archive"), 10 },
276   {"diff", 'd', 0, 0,
277    N_("find differences between archive and file system"), 10 },
278   {"compare", 0, 0, OPTION_ALIAS, NULL, 10},
279   {"append", 'r', 0, 0,
280    N_("append files to the end of an archive"), 10 },
281   {"update", 'u', 0, 0,
282    N_("only append files newer than copy in archive"), 10 },
283   {"catenate", 'A', 0, 0,
284    N_("append tar files to an archive"), 10 },
285   {"concatenate", 0, 0, OPTION_ALIAS, NULL, 10},
286   {"delete", DELETE_OPTION, 0, 0,
287    N_("delete from the archive (not on mag tapes!)"), 10 },
288
289   {NULL, 0, NULL, 0,
290    N_("Operation modifiers:"), 20},
291
292   {"verify", 'W', 0, 0,
293    N_("attempt to verify the archive after writing it"), 21 },
294   {"remove-files", REMOVE_FILES_OPTION, 0, 0,
295    N_("remove files after adding them to the archive"), 21 },
296   {"keep-old-files", 'k', 0, 0,
297    N_("don't replace existing files when extracting"), 21 },
298   {"keep-newer-files", KEEP_NEWER_FILES_OPTION, 0, 0,
299    N_("don't replace existing files that are newer than their archive copies"), 21 },
300   {"no-overwrite-dir", NO_OVERWRITE_DIR_OPTION, 0, 0,
301    N_("preserve metadata of existing directories"), 21 },
302   {"overwrite", OVERWRITE_OPTION, 0, 0,
303    N_("overwrite existing files when extracting"), 21 },
304   {"unlink-first", 'U', 0, 0,
305    N_("remove each file prior to extracting over it"), 21 },
306   {"recursive-unlink", RECURSIVE_UNLINK_OPTION, 0, 0,
307    N_("empty hierarchies prior to extracting directory"), 21 },
308   {"sparse", 'S', 0, 0,
309    N_("handle sparse files efficiently"), 21 },
310   {"to-stdout", 'O', 0, 0,
311    N_("extract files to standard output"), 21 },
312   {"incremental", 'G', 0, 0,
313    N_("handle old GNU-format incremental backup"), 21 },
314   {"listed-incremental", 'g', N_("FILE"), 0,
315    N_("handle new GNU-format incremental backup"), 21 },
316   {"ignore-failed-read", IGNORE_FAILED_READ_OPTION, 0, 0,
317    N_("do not exit with nonzero on unreadable files"), 21 },
318   {"occurrence", OCCURRENCE_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL,
319    N_("process only the NUMth occurrence of each file in the archive. This option is valid only in conjunction with one of the subcommands --delete, --diff, --extract or --list and when a list of files is given either on the command line or via -T option. NUMBER defaults to 1."), 21 },
320   {"seek", 'n', NULL, 0,
321    N_("Archive is seekable"), 21 },
322     
323   {NULL, 0, NULL, 0,
324    N_("Handling of file attributes:"), 30 },
325
326   {"owner", OWNER_OPTION, N_("NAME"), 0,
327    N_("force NAME as owner for added files"), 31 },
328   {"group", GROUP_OPTION, N_("NAME"), 0,
329    N_("force NAME as group for added files"), 31 },
330   {"mode", MODE_OPTION, N_("CHANGES"), 0,
331    N_("force (symbolic) mode CHANGES for added files"), 31 },
332   {"atime-preserve", ATIME_PRESERVE_OPTION, 0, 0,
333    N_("don't change access times on dumped files"), 31 },
334   {"touch", 'm', 0, 0,
335    N_("don't extract file modified time"), 31 },
336   {"same-owner", SAME_OWNER_OPTION, 0, 0,
337    N_("try extracting files with the same ownership"), 31 },
338   {"no-same-owner", NO_SAME_OWNER_OPTION, 0, 0,
339    N_("extract files as yourself"), 31 },
340   {"numeric-owner", NUMERIC_OWNER_OPTION, 0, 0,
341    N_("always use numbers for user/group names"), 31 },
342   {"preserve-permissions", 'p', 0, 0,
343    N_("extract permissions information"), 31 },
344   {"same-permissions", 0, 0, OPTION_ALIAS, NULL, 31 },
345   {"no-same-permissions", NO_SAME_PERMISSIONS_OPTION, 0, 0,
346    N_("do not extract permissions information"), 31 },
347   {"preserve-order", 's', 0, 0,
348    N_("sort names to extract to match archive"), 31 },
349   {"same-order", 0, 0, OPTION_ALIAS, NULL, 31 },
350   {"preserve", PRESERVE_OPTION, 0, 0,
351    N_("same as both -p and -s"), 31 },
352
353   {NULL, 0, NULL, 0,
354    N_("Device selection and switching:"), 40 },
355   
356   {"file", 'f', N_("ARCHIVE"), 0,
357    N_("use archive file or device ARCHIVE"), 41 },
358   {"force-local", FORCE_LOCAL_OPTION, 0, 0,
359    N_("archive file is local even if has a colon"), 41 },
360   {"rmt-command", RMT_COMMAND_OPTION, N_("COMMAND"), 0,
361    N_("use given rmt COMMAND instead of rmt"), 41 }, 
362   {"rsh-command", RSH_COMMAND_OPTION, N_("COMMAND"), 0,
363    N_("use remote COMMAND instead of rsh"), 41 },
364 #ifdef DEVICE_PREFIX
365   {"-[0-7][lmh]", 0, NULL, OPTION_DOC,
366    N_("specify drive and density"), 41 },
367 #endif  
368   {NULL, '0', NULL, OPTION_HIDDEN, NULL, 41 },
369   {NULL, '1', NULL, OPTION_HIDDEN, NULL, 41 },
370   {NULL, '2', NULL, OPTION_HIDDEN, NULL, 41 },
371   {NULL, '3', NULL, OPTION_HIDDEN, NULL, 41 },
372   {NULL, '4', NULL, OPTION_HIDDEN, NULL, 41 },
373   {NULL, '5', NULL, OPTION_HIDDEN, NULL, 41 },
374   {NULL, '6', NULL, OPTION_HIDDEN, NULL, 41 },
375   {NULL, '7', NULL, OPTION_HIDDEN, NULL, 41 },
376   {NULL, '8', NULL, OPTION_HIDDEN, NULL, 41 },
377   {NULL, '9', NULL, OPTION_HIDDEN, NULL, 41 },
378   
379   {"multi-volume", 'M', 0, 0,
380    N_("create/list/extract multi-volume archive"), 41 },
381   {"tape-length", 'L', N_("NUMBER"), 0,
382    N_("change tape after writing NUMBER x 1024 bytes"), 41 },
383   {"info-script", 'F', N_("NAME"), 0,
384    N_("run script at end of each tape (implies -M)"), 41 },
385   {"new-volume-script", 0, 0, OPTION_ALIAS, NULL, 41 },
386   {"volno-file", VOLNO_FILE_OPTION, N_("FILE"), 0,
387    N_("use/update the volume number in FILE"), 41 },
388
389   {NULL, 0, NULL, 0,
390    N_("Device blocking:"), 50 },
391
392   {"blocking-factor", 'b', N_("BLOCKS"), 0,
393    N_("BLOCKS x 512 bytes per record"), 51 },
394   {"record-size", RECORD_SIZE_OPTION, N_("NUMBER"), 0,
395    N_("SIZE bytes per record, multiple of 512"), 51 },
396   {"ignore-zeros", 'i', 0, 0,
397    N_("ignore zeroed blocks in archive (means EOF)"), 51 },
398   {"read-full-records", 'B', 0, 0,
399    N_("reblock as we read (for 4.2BSD pipes)"), 51 }, 
400
401   {NULL, 0, NULL, 0,
402    N_("Archive format selection:"), 60 },
403   
404   {"format", 'H', N_("FORMAT"), 0,
405    N_("create archive of the given format."), 61 },
406
407   {"", 0, NULL, OPTION_DOC, N_("FORMAT is one of the following:"), 62},
408   {"", 0, NULL, OPTION_DOC, N_("v7        old V7 tar format"), 63},
409   {"", 0, NULL, OPTION_DOC, N_("oldgnu    GNU format as per tar <= 1.12"), 63},
410   {"", 0, NULL, OPTION_DOC, N_("gnu       GNU tar 1.13.x format"), 63},
411   {"", 0, NULL, OPTION_DOC, N_("ustar     POSIX 1003.1-1988 (ustar) format"), 63 },
412   {"", 0, NULL, OPTION_DOC, N_("posix     POSIX 1003.1-2001 (pax) format"), 63 },
413
414   {"old-archive", OLD_ARCHIVE_OPTION, 0, 0, /* FIXME */
415    N_("same as --format=v7"), 68 },
416   {"portability", 0, 0, OPTION_ALIAS, NULL, 68 },
417   {"posix", POSIX_OPTION, 0, 0,
418    N_("same as --format=posix"), 68 },
419   {"pax-option", PAX_OPTION, N_("keyword[[:]=value][,keyword[[:]=value], ...]"), 0,
420    N_("control pax keywords"), 68 },
421   {"label", 'V', N_("TEXT"), 0,
422    N_("create archive with volume name NAME. At list/extract time, use TEXT as a globbing pattern"), 68 },
423   {"bzip2", 'j', 0, 0,
424    N_("filter the archive through bzip2"), 68 },
425   {"gzip", 'z', 0, 0,
426    N_("filter the archive through gzip"), 68 },
427   {"gunzip", 0, 0, OPTION_ALIAS, NULL, 68 },
428   {"ungzip", 0, 0, OPTION_ALIAS, NULL, 68 },
429   {"compress", 'Z', 0, 0,
430    N_("filter the archive through compress"), 68 },
431   {"uncompress", 0, 0, OPTION_ALIAS, NULL, 68 },
432   {"use-compress-program", USE_COMPRESS_PROGRAM_OPTION, N_("PROG"), 0,
433    N_("filter through PROG (must accept -d)"), 68 },
434
435   {NULL, 0, NULL, 0,
436    N_("Local file selection:"), 70 },
437
438   {"directory", 'C', N_("DIR"), 0,
439    N_("change to directory DIR"), 71 },
440   {"files-from", 'T', N_("FILE-OF-NAMES"), 0,
441    N_("get names to extract or create from file NAME"), 71 },
442   {"null", NULL_OPTION, 0, 0,
443    N_("-T reads null-terminated names, disable -C"), 71 },
444   {"exclude", EXCLUDE_OPTION, N_("PATTERN"), 0,
445    N_("exclude files, given as a PATTERN"), 71 },
446   {"exclude-from", 'X', N_("FILE"), 0,
447    N_("exclude patterns listed in FILE"), 71 },
448   {"ignore-case", IGNORE_CASE_OPTION, 0, 0,
449    N_("exclusion ignores case"), 71 },
450   {"anchored", ANCHORED_OPTION, 0, 0,
451    N_("exclude patterns match file name start"), 71 },
452   {"no-anchored", NO_ANCHORED_OPTION, 0, 0,
453    N_("exclude patterns match after any / (default)"), 71 },
454   {"no-ignore-case", NO_IGNORE_CASE_OPTION, 0, 0,
455    N_("exclusion is case sensitive (default)"), 71 },
456   {"no-wildcards", NO_WILDCARDS_OPTION, 0, 0,
457    N_("exclude patterns are plain strings"), 71 },
458   {"no-wildcards-match-slash", NO_WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
459    N_("exclude pattern wildcards do not match '/'"), 71 },
460   {"no-recursion", NO_RECURSION_OPTION, 0, 0,
461    N_("avoid descending automatically in directories"), 71 },
462   {"one-file-system", 'l', 0, 0, /* FIXME: emit warning */
463    N_("stay in local file system when creating archive"), 71 },
464   {"recursion", RECURSION_OPTION, 0, 0,
465    N_("recurse into directories (default)"), 71 },
466   {"absolute-names", 'P', 0, 0,
467    N_("don't strip leading `/'s from file names"), 71 },
468   {"dereference", 'h', 0, 0,
469    N_("dump instead the files symlinks point to"), 71 },
470   {"starting-file", 'K', N_("MEMBER-NAME"), 0,
471    N_("begin at member MEMBER-NAME in the archive"), 71 },
472   {"strip-components", STRIP_COMPONENTS_OPTION, N_("NUMBER"), 0,
473    N_("strip NUMBER leading components from file names"), 71 },
474   {"newer", 'N', N_("DATE-OR-FILE"), 0,
475    N_("only store files newer than DATE-OR-FILE"), 71 },
476   {"newer-mtime", NEWER_MTIME_OPTION, N_("DATE"), 0,
477    N_("compare date and time when data changed only"), 71 },
478   {"after-date", 'N', N_("DATE"), 0,
479    N_("same as -N"), 71 },
480   {"backup", BACKUP_OPTION, N_("CONTROL"), OPTION_ARG_OPTIONAL,
481    N_("backup before removal, choose version CONTROL"), 71 },
482   {"suffix", SUFFIX_OPTION, N_("STRING"), 0,
483    N_("backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX"), 71 },
484   {"wildcards", WILDCARDS_OPTION, 0, 0,
485    N_("exclude patterns use wildcards (default)"), 71 },
486   {"wildcards-match-slash", WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
487    N_("exclude pattern wildcards match '/' (default)"), 71 },
488
489   {NULL, 0, NULL, 0,
490    N_("Informative output:"), 80 },
491   
492   {"verbose", 'v', 0, 0,
493    N_("verbosely list files processed"), 81 },
494   {"checkpoint", CHECKPOINT_OPTION, 0, 0,
495    N_("display progress messages every 10th record"), 81 },
496   {"check-links", CHECK_LINKS_OPTION, 0, 0,
497    N_("print a message if not all links are dumped"), 82 },
498   {"totals", TOTALS_OPTION, 0, 0,
499    N_("print total bytes written while creating archive"), 82 },
500   {"utc", UTC_OPTION, 0, 0,
501    N_("print file modification dates in UTC"), 82 },
502   {"index-file", INDEX_FILE_OPTION, N_("FILE"), 0,
503    N_("send verbose output to FILE"), 82 },
504   {"block-number", 'R', 0, 0,
505    N_("show block number within archive with each message"), 82 },
506   {"interactive", 'w', 0, 0,
507    N_("ask for confirmation for every action"), 82 },
508   {"confirmation", 0, 0, OPTION_ALIAS, NULL, 82 },
509   {"show-defaults", SHOW_DEFAULTS_OPTION, 0, 0,
510    N_("Show tar defaults"), 82 },
511   {"show-omitted-dirs", SHOW_OMITTED_DIRS_OPTION, 0, 0,
512    N_("When listing or extracting, list each directory that does not match search criteria"), 82 },
513   
514   {NULL, 0, NULL, 0,
515    N_("Compatibility options:"), 90 },
516
517   {NULL, 'o', 0, 0,
518    N_("when creating, same as --old-archive. When extracting, same as --no-same-owner"), 91 },
519
520   {NULL, 0, NULL, 0,
521    N_("Other options:"), 100 },
522
523   {"help",  '?', 0, 0,  N_("Give this help list"), -1},
524   {"usage", USAGE_OPTION, 0, 0,  N_("Give a short usage message"), -1},
525   {"license", LICENSE_OPTION, 0, 0, N_("Print license and exit"), -1},
526   {"version", VERSION_OPTION, 0, 0,  N_("Print program version"), -1},
527   /* FIXME -V (--label) conflicts with the default short option for
528      --version */
529   
530   {0, 0, 0, 0, 0, 0}
531 };
532
533 struct tar_args {
534   char const *textual_date_option;
535   int exclude_options;
536   bool o_option;
537   int pax_option;
538   char const *backup_suffix_string;
539   char const *version_control_string;
540   int input_files;
541 };
542
543 static void
544 show_default_settings (FILE *stream)
545 {
546   fprintf (stream,
547            "--format=%s -f%s -b%d --rmt-command=%s --rsh-command=%s\n",
548            archive_format_string (DEFAULT_ARCHIVE_FORMAT),
549            DEFAULT_ARCHIVE, DEFAULT_BLOCKING,
550            DEFAULT_RMT_COMMAND, REMOTE_SHELL);
551 }
552
553 static void
554 set_subcommand_option (enum subcommand subcommand)
555 {
556   if (subcommand_option != UNKNOWN_SUBCOMMAND
557       && subcommand_option != subcommand)
558     USAGE_ERROR ((0, 0,
559                   _("You may not specify more than one `-Acdtrux' option")));
560
561   subcommand_option = subcommand;
562 }
563
564 static void
565 set_use_compress_program_option (const char *string)
566 {
567   if (use_compress_program_option
568       && strcmp (use_compress_program_option, string) != 0)
569     USAGE_ERROR ((0, 0, _("Conflicting compression options")));
570
571   use_compress_program_option = string;
572 }
573
574 void
575 license ()
576 {
577   printf ("tar (%s) %s\n%s\n", PACKAGE_NAME, PACKAGE_VERSION,
578           "Copyright (C) 2004 Free Software Foundation, Inc.\n");
579   puts (_("Based on the work of John Gilmore and Jay Fenlason. See AUTHORS\n\
580 for complete list of authors.\n"));
581   printf (_("   GNU tar is free software; you can redistribute it and/or modify\n"
582     "   it under the terms of the GNU General Public License as published by\n"
583     "   the Free Software Foundation; either version 2 of the License, or\n"
584     "   (at your option) any later version.\n"
585     "\n"
586     "   GNU tar is distributed in the hope that it will be useful,\n"
587     "   but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
588     "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
589     "   GNU General Public License for more details.\n"
590     "\n"
591     "   You should have received a copy of the GNU General Public License\n"
592     "   along with GNU tar; if not, write to the Free Software\n"
593     "   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA\n\n"));
594   exit (0);
595 }
596
597 static error_t
598 parse_opt(int key, char *arg, struct argp_state *state)
599 {
600   struct tar_args *args = state->input;
601   
602   switch (key)
603     {
604       case 1:
605         /* File name or non-parsed option, because of ARGP_IN_ORDER */
606         name_add (optarg);
607         args->input_files++;
608         break;
609
610     case 'A':
611       set_subcommand_option (CAT_SUBCOMMAND);
612       break;
613       
614     case 'b':
615       {
616         uintmax_t u;
617         if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
618                && u == (blocking_factor = u)
619                && 0 < blocking_factor
620                && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE))
621           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
622                         _("Invalid blocking factor")));
623       }
624       break;
625
626     case 'B':
627       /* Try to reblock input records.  For reading 4.2BSD pipes.  */
628       
629       /* It would surely make sense to exchange -B and -R, but it seems
630          that -B has been used for a long while in Sun tar and most
631          BSD-derived systems.  This is a consequence of the block/record
632          terminology confusion.  */
633       
634       read_full_records_option = true;
635       break;
636
637     case 'c':
638       set_subcommand_option (CREATE_SUBCOMMAND);
639       break;
640
641     case 'C':
642       name_add ("-C");
643       name_add (arg);
644       break;
645
646     case 'd':
647       set_subcommand_option (DIFF_SUBCOMMAND);
648       break;
649
650     case 'f':
651       if (archive_names == allocated_archive_names)
652         {
653           allocated_archive_names *= 2;
654           archive_name_array =
655             xrealloc (archive_name_array,
656                       sizeof (const char *) * allocated_archive_names);
657         }
658       archive_name_array[archive_names++] = arg;
659       break;
660
661     case 'F':
662       /* Since -F is only useful with -M, make it implied.  Run this
663          script at the end of each tape.  */
664       
665       info_script_option = arg;
666       multi_volume_option = true;
667       break;
668       
669     case 'g':
670       listed_incremental_option = arg;
671       after_date_option = true;
672       /* Fall through.  */
673       
674     case 'G':
675       /* We are making an incremental dump (FIXME: are we?); save
676          directories at the beginning of the archive, and include in each
677          directory its contents.  */
678       
679       incremental_option = true;
680       break;
681       
682     case 'h':
683       /* Follow symbolic links.  */
684       dereference_option = true;
685       break;
686       
687     case 'i':
688       /* Ignore zero blocks (eofs).  This can't be the default,
689          because Unix tar writes two blocks of zeros, then pads out
690          the record with garbage.  */
691       
692       ignore_zeros_option = true;
693       break;
694       
695     case 'I':
696       USAGE_ERROR ((0, 0,
697                     _("Warning: the -I option is not supported;"
698                       " perhaps you meant -j or -T?")));
699       break;
700       
701     case 'j':
702       set_use_compress_program_option ("bzip2");
703       break;
704       
705     case 'k':
706       /* Don't replace existing files.  */
707       old_files_option = KEEP_OLD_FILES;
708       break;
709       
710     case 'K':
711       starting_file_option = true;
712       addname (arg, 0);
713       break;
714       
715     case 'l':
716       /* When dumping directories, don't dump files/subdirectories
717          that are on other filesystems.  */
718       
719       one_file_system_option = true;
720       break;
721       
722     case 'L':
723       {
724         uintmax_t u;
725         if (xstrtoumax (arg, 0, 10, &u, "") != LONGINT_OK)
726           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
727                         _("Invalid tape length")));
728         tape_length_option = 1024 * (tarlong) u;
729         multi_volume_option = true;
730       }
731       break;
732       
733     case 'm':
734       touch_option = true;
735       break;
736       
737     case 'M':
738       /* Make multivolume archive: when we can't write any more into
739          the archive, re-open it, and continue writing.  */
740       
741       multi_volume_option = true;
742       break;
743
744     case 'n':
745       seekable_archive = true;
746       break;
747       
748 #if !MSDOS
749     case 'N':
750       after_date_option = true;
751       /* Fall through.  */
752
753     case NEWER_MTIME_OPTION:
754       if (NEWER_OPTION_INITIALIZED (newer_mtime_option))
755         USAGE_ERROR ((0, 0, _("More than one threshold date")));
756       
757       if (FILE_SYSTEM_PREFIX_LEN (arg) != 0
758           || ISSLASH (*arg)
759           || *arg == '.')
760         {
761           struct stat st;
762           if (deref_stat (dereference_option, arg, &st) != 0)
763             {
764               stat_error (arg);
765               USAGE_ERROR ((0, 0, _("Date file not found")));
766             }
767           newer_mtime_option.tv_sec = st.st_mtime;
768           newer_mtime_option.tv_nsec = TIMESPEC_NS (st.st_mtim);
769         }
770       else
771         {
772           if (! get_date (&newer_mtime_option, arg, NULL))
773             {
774               WARN ((0, 0, _("Substituting %s for unknown date format %s"),
775                      tartime (newer_mtime_option.tv_sec), quote (arg)));
776               newer_mtime_option.tv_nsec = 0;
777             }
778           else
779             args->textual_date_option = arg;
780         }
781       
782       break;
783 #endif /* not MSDOS */
784       
785     case 'o':
786       args->o_option = true;
787       break;
788       
789     case 'O':
790       to_stdout_option = true;
791       break;
792
793     case 'p':
794       same_permissions_option = true;
795       break;
796       
797     case 'P':
798       absolute_names_option = true;
799       break;
800       
801     case 'r':
802       set_subcommand_option (APPEND_SUBCOMMAND);
803       break;
804       
805     case 'R':
806       /* Print block numbers for debugging bad tar archives.  */
807       
808       /* It would surely make sense to exchange -B and -R, but it seems
809          that -B has been used for a long while in Sun tar ans most
810          BSD-derived systems.  This is a consequence of the block/record
811          terminology confusion.  */
812       
813       block_number_option = true;
814       break;
815       
816     case 's':
817       /* Names to extr are sorted.  */
818       
819       same_order_option = true;
820       break;
821       
822     case 'S':
823       sparse_option = true;
824       break;
825       
826     case 't':
827       set_subcommand_option (LIST_SUBCOMMAND);
828       verbose_option++;
829       break;
830
831     case 'T':
832       files_from_option = arg;
833       break;
834       
835     case 'u':
836       set_subcommand_option (UPDATE_SUBCOMMAND);
837       break;
838       
839     case 'U':
840       old_files_option = UNLINK_FIRST_OLD_FILES;
841       break;
842       
843     case UTC_OPTION:
844       utc_option = true;
845       break;
846       
847     case 'v':
848       verbose_option++;
849       break;
850       
851     case 'V':
852       volume_label_option = arg;
853       break;
854       
855     case 'w':
856       interactive_option = true;
857       break;
858       
859     case 'W':
860       verify_option = true;
861       break;
862       
863     case 'x':
864       set_subcommand_option (EXTRACT_SUBCOMMAND);
865       break;
866       
867     case 'X':
868       if (add_exclude_file (add_exclude, excluded, arg,
869                             args->exclude_options | recursion_option, '\n')
870           != 0)
871         {
872           int e = errno;
873           FATAL_ERROR ((0, e, "%s", quotearg_colon (arg)));
874         }
875       break;
876       
877     case 'y':
878       USAGE_ERROR ((0, 0,
879                     _("Warning: the -y option is not supported;"
880                       " perhaps you meant -j?")));
881       break;
882       
883     case 'z':
884       set_use_compress_program_option ("gzip");
885       break;
886       
887     case 'Z':
888       set_use_compress_program_option ("compress");
889       break;
890       
891     case ANCHORED_OPTION:
892       args->exclude_options |= EXCLUDE_ANCHORED;
893       break;
894       
895     case ATIME_PRESERVE_OPTION:
896       atime_preserve_option = true;
897       break;
898       
899     case CHECKPOINT_OPTION:
900       checkpoint_option = true;
901       break;
902       
903     case BACKUP_OPTION:
904       backup_option = true;
905       if (arg)
906         args->version_control_string = arg;
907       break;
908       
909     case DELETE_OPTION:
910       set_subcommand_option (DELETE_SUBCOMMAND);
911       break;
912       
913     case EXCLUDE_OPTION:
914       add_exclude (excluded, arg, args->exclude_options | recursion_option);
915       break;
916       
917     case FORCE_LOCAL_OPTION:
918       force_local_option = true;
919       break;
920       
921     case 'H':
922       set_archive_format (arg);
923       break;
924       
925     case INDEX_FILE_OPTION:
926       index_file_name = arg;
927       break;
928       
929     case IGNORE_CASE_OPTION:
930       args->exclude_options |= FNM_CASEFOLD;
931       break;
932       
933     case IGNORE_FAILED_READ_OPTION:
934       ignore_failed_read_option = true;
935       break;
936       
937     case KEEP_NEWER_FILES_OPTION:
938       old_files_option = KEEP_NEWER_FILES;
939       break;
940       
941     case GROUP_OPTION:
942       if (! (strlen (arg) < GNAME_FIELD_SIZE
943              && gname_to_gid (arg, &group_option)))
944         {
945           uintmax_t g;
946           if (xstrtoumax (arg, 0, 10, &g, "") == LONGINT_OK
947               && g == (gid_t) g)
948             group_option = g;
949           else
950             FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
951                           _("%s: Invalid group")));
952         }
953       break;
954       
955     case MODE_OPTION:
956       mode_option
957         = mode_compile (arg,
958                         MODE_MASK_EQUALS | MODE_MASK_PLUS | MODE_MASK_MINUS);
959       if (mode_option == MODE_INVALID)
960         FATAL_ERROR ((0, 0, _("Invalid mode given on option")));
961       if (mode_option == MODE_MEMORY_EXHAUSTED)
962         xalloc_die ();
963       break;
964       
965     case NO_ANCHORED_OPTION:
966       args->exclude_options &= ~ EXCLUDE_ANCHORED;
967       break;
968       
969     case NO_IGNORE_CASE_OPTION:
970       args->exclude_options &= ~ FNM_CASEFOLD;
971       break;
972       
973     case NO_OVERWRITE_DIR_OPTION:
974       old_files_option = NO_OVERWRITE_DIR_OLD_FILES;
975       break;
976       
977     case NO_WILDCARDS_OPTION:
978       args->exclude_options &= ~ EXCLUDE_WILDCARDS;
979       break;
980       
981     case NO_WILDCARDS_MATCH_SLASH_OPTION:
982       args->exclude_options |= FNM_FILE_NAME;
983       break;
984       
985     case NULL_OPTION:
986       filename_terminator = '\0';
987       break;
988       
989     case NUMERIC_OWNER_OPTION:
990       numeric_owner_option = true;
991       break;
992       
993     case OCCURRENCE_OPTION:
994       if (!arg)
995         occurrence_option = 1;
996       else
997         {
998           uintmax_t u;
999           if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK)
1000             occurrence_option = u;
1001           else
1002             FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1003                           _("Invalid number")));
1004         }
1005       break;
1006       
1007     case OVERWRITE_OPTION:
1008       old_files_option = OVERWRITE_OLD_FILES;
1009       break;
1010
1011     case OWNER_OPTION:
1012       if (! (strlen (arg) < UNAME_FIELD_SIZE
1013              && uname_to_uid (arg, &owner_option)))
1014         {
1015           uintmax_t u;
1016           if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1017               && u == (uid_t) u)
1018             owner_option = u;
1019           else
1020             FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1021                           _("Invalid owner")));
1022         }
1023       break;
1024       
1025     case PAX_OPTION:
1026       args->pax_option++;
1027       xheader_set_option (arg);
1028       break;
1029       
1030     case POSIX_OPTION:
1031       set_archive_format ("posix");
1032       break;
1033       
1034     case PRESERVE_OPTION:
1035       same_permissions_option = true;
1036       same_order_option = true;
1037       break;
1038       
1039     case RECORD_SIZE_OPTION:
1040       {
1041         uintmax_t u;
1042         if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1043                && u == (size_t) u))
1044           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1045                         _("Invalid record size")));
1046         record_size = u;
1047         if (record_size % BLOCKSIZE != 0)
1048           USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
1049                         BLOCKSIZE));
1050         blocking_factor = record_size / BLOCKSIZE;
1051       }
1052       break;
1053       
1054     case RECURSIVE_UNLINK_OPTION:
1055       recursive_unlink_option = true;
1056       break;
1057       
1058     case REMOVE_FILES_OPTION:
1059       remove_files_option = true;
1060       break;
1061       
1062     case RMT_COMMAND_OPTION:
1063       rmt_command_option = arg;
1064       break;
1065       
1066     case RSH_COMMAND_OPTION:
1067       rsh_command_option = arg;
1068       break;
1069       
1070     case SHOW_DEFAULTS_OPTION:
1071       show_default_settings (stdout);
1072       exit(0);
1073       
1074     case STRIP_COMPONENTS_OPTION:
1075       {
1076         uintmax_t u;
1077         if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1078                && u == (size_t) u))
1079           USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1080                         _("Invalid number of elements")));
1081         strip_name_components = u;
1082       }
1083       break;
1084
1085     case SHOW_OMITTED_DIRS_OPTION:
1086       show_omitted_dirs_option = true;
1087       break;
1088       
1089     case SUFFIX_OPTION:
1090       backup_option = true;
1091       args->backup_suffix_string = arg;
1092       break;
1093       
1094     case TOTALS_OPTION:
1095       totals_option = true;
1096       break;
1097       
1098     case USE_COMPRESS_PROGRAM_OPTION:
1099       set_use_compress_program_option (arg);
1100       break;
1101       
1102     case VOLNO_FILE_OPTION:
1103       volno_file_option = arg;
1104       break;
1105       
1106     case WILDCARDS_OPTION:
1107       args->exclude_options |= EXCLUDE_WILDCARDS;
1108       break;
1109       
1110     case WILDCARDS_MATCH_SLASH_OPTION:
1111       args->exclude_options &= ~ FNM_FILE_NAME;
1112       break;
1113
1114     case CHECK_LINKS_OPTION:
1115       check_links_option = 1;
1116       break;
1117       
1118     case NO_RECURSION_OPTION:
1119       recursion_option = 0;
1120       break;
1121
1122     case NO_SAME_OWNER_OPTION:
1123       same_owner_option = -1;
1124       break;
1125
1126     case NO_SAME_PERMISSIONS_OPTION:
1127       same_permissions_option = -1;
1128       break;
1129
1130     case RECURSION_OPTION:
1131       recursion_option = FNM_LEADING_DIR;
1132       break;
1133
1134     case SAME_OWNER_OPTION:
1135       same_owner_option = 1;
1136       break;
1137       
1138     case '0':
1139     case '1':
1140     case '2':
1141     case '3':
1142     case '4':
1143     case '5':
1144     case '6':
1145     case '7':
1146
1147 #ifdef DEVICE_PREFIX
1148       {
1149         int device = key - '0';
1150         int density;
1151         static char buf[sizeof DEVICE_PREFIX + 10];
1152         char *cursor;
1153
1154         if (arg[1])
1155           argp_error (state, _("Malformed density argument: '%s'"), arg);
1156         
1157         strcpy (buf, DEVICE_PREFIX);
1158         cursor = buf + strlen (buf);
1159
1160 #ifdef DENSITY_LETTER
1161
1162         sprintf (cursor, "%d%c", device, arg[0]);
1163         
1164 #else /* not DENSITY_LETTER */
1165
1166         switch (arg[0])
1167           {
1168           case 'l':
1169 #ifdef LOW_NUM
1170             device += LOW_NUM;
1171 #endif
1172             break;
1173             
1174           case 'm':
1175 #ifdef MID_NUM
1176             device += MID_NUM;
1177 #else
1178             device += 8;
1179 #endif
1180             break;
1181             
1182           case 'h':
1183 #ifdef HGH_NUM
1184             device += HGH_NUM;
1185 #else
1186             device += 16;
1187 #endif
1188             break;
1189
1190           default:
1191             argp_error (state, _("Unknown density: '%c'"), arg[0]);
1192           }
1193         sprintf (cursor, "%d", device);
1194         
1195 #endif /* not DENSITY_LETTER */
1196
1197         if (archive_names == allocated_archive_names)
1198           {
1199             allocated_archive_names *= 2;
1200             archive_name_array =
1201               xrealloc (archive_name_array,
1202                         sizeof (const char *) * allocated_archive_names);
1203           }
1204         archive_name_array[archive_names++] = strdup (buf);
1205       }
1206       break;
1207
1208 #else /* not DEVICE_PREFIX */
1209
1210       argp_error (state, 
1211                   _("Options `-[0-7][lmh]' not supported by *this* tar"));
1212       
1213 #endif /* not DEVICE_PREFIX */
1214       
1215     case '?':
1216       state->flags |= ARGP_NO_EXIT;
1217       argp_state_help (state, state->out_stream,
1218                        ARGP_HELP_STD_HELP & ~ARGP_HELP_BUG_ADDR);
1219       fprintf (state->out_stream, _("\n*This* tar defaults to:\n"));
1220       show_default_settings (state->out_stream);
1221       fprintf (state->out_stream, "\n");
1222       fprintf (state->out_stream, _("Report bugs to %s.\n"), 
1223                argp_program_bug_address);
1224       exit (0);
1225
1226     case USAGE_OPTION:
1227       argp_state_help (state, state->out_stream,
1228                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
1229       break;
1230
1231     case VERSION_OPTION:
1232       fprintf (state->out_stream, "%s\n", argp_program_version);
1233       exit (0);
1234
1235     case LICENSE_OPTION:
1236       license ();
1237       break;
1238
1239     default:
1240       return ARGP_ERR_UNKNOWN;
1241     }
1242   return 0;
1243 }
1244
1245 static struct argp argp = {
1246   options,
1247   parse_opt,
1248   N_("[FILE]..."),
1249   doc,
1250   NULL,
1251   NULL,
1252   NULL
1253 };
1254
1255 void
1256 usage (int status)
1257 {
1258   argp_help (&argp, stderr, ARGP_HELP_SEE, program_name);
1259   exit (status);
1260 }
1261
1262 /* Parse the options for tar.  */
1263
1264 static struct argp_option *
1265 find_argp_option (struct argp_option *options, int letter)
1266 {
1267   for (;
1268        !(options->name == NULL
1269          && options->key == 0
1270          && options->arg == 0
1271          && options->flags == 0
1272          && options->doc == NULL); options++)
1273     if (options->key == letter)
1274       return options;
1275   return NULL;
1276 }
1277
1278 static void
1279 decode_options (int argc, char **argv)
1280 {
1281   int index;
1282   struct tar_args args;
1283   
1284   /* Set some default option values.  */
1285   args.textual_date_option = NULL;
1286   args.exclude_options = EXCLUDE_WILDCARDS;
1287   args.o_option = 0;
1288   args.pax_option = 0;
1289   args.backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
1290   args.version_control_string = 0;
1291   args.input_files = 0;
1292
1293   subcommand_option = UNKNOWN_SUBCOMMAND;
1294   archive_format = DEFAULT_FORMAT;
1295   blocking_factor = DEFAULT_BLOCKING;
1296   record_size = DEFAULT_BLOCKING * BLOCKSIZE;
1297   excluded = new_exclude ();
1298   newer_mtime_option.tv_sec = TYPE_MINIMUM (time_t);
1299   newer_mtime_option.tv_nsec = -1;
1300   recursion_option = FNM_LEADING_DIR;
1301
1302   owner_option = -1;
1303   group_option = -1;
1304
1305   /* Convert old-style tar call by exploding option element and rearranging
1306      options accordingly.  */
1307
1308   if (argc > 1 && argv[1][0] != '-')
1309     {
1310       int new_argc;             /* argc value for rearranged arguments */
1311       char **new_argv;          /* argv value for rearranged arguments */
1312       char *const *in;          /* cursor into original argv */
1313       char **out;               /* cursor into rearranged argv */
1314       const char *letter;       /* cursor into old option letters */
1315       char buffer[3];           /* constructed option buffer */
1316
1317       /* Initialize a constructed option.  */
1318
1319       buffer[0] = '-';
1320       buffer[2] = '\0';
1321
1322       /* Allocate a new argument array, and copy program name in it.  */
1323
1324       new_argc = argc - 1 + strlen (argv[1]);
1325       new_argv = xmalloc ((new_argc + 1) * sizeof (char *));
1326       in = argv;
1327       out = new_argv;
1328       *out++ = *in++;
1329
1330       /* Copy each old letter option as a separate option, and have the
1331          corresponding argument moved next to it.  */
1332
1333       for (letter = *in++; *letter; letter++)
1334         {
1335           struct argp_option *opt;
1336           
1337           buffer[1] = *letter;
1338           *out++ = xstrdup (buffer);
1339           opt = find_argp_option (options, *letter);
1340           if (opt && opt->arg)
1341             {
1342               if (in < argv + argc)
1343                 *out++ = *in++;
1344               else
1345                 USAGE_ERROR ((0, 0, _("Old option `%c' requires an argument."),
1346                               *letter));
1347             }
1348         }
1349
1350       /* Copy all remaining options.  */
1351
1352       while (in < argv + argc)
1353         *out++ = *in++;
1354       *out = 0;
1355
1356       /* Replace the old option list by the new one.  */
1357
1358       argc = new_argc;
1359       argv = new_argv;
1360     }
1361
1362   /* Parse all options and non-options as they appear.  */
1363
1364   prepend_default_options (getenv ("TAR_OPTIONS"), &argc, &argv);
1365
1366   if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER|ARGP_NO_HELP,
1367                   &index, &args))
1368     exit (1); /* FIXME */
1369       
1370
1371   /* Special handling for 'o' option:
1372
1373      GNU tar used to say "output old format".
1374      UNIX98 tar says don't chown files after extracting (we use
1375      "--no-same-owner" for this).
1376
1377      The old GNU tar semantics is retained when used with --create
1378      option, otherwise UNIX98 semantics is assumed */
1379
1380   if (args.o_option)
1381     {
1382       if (subcommand_option == CREATE_SUBCOMMAND)
1383         {
1384           /* GNU Tar <= 1.13 compatibility */
1385           set_archive_format ("v7");
1386         }
1387       else
1388         {
1389           /* UNIX98 compatibility */
1390           same_owner_option = 1;
1391         }
1392     }
1393
1394   /* Handle operands after any "--" argument.  */
1395   for (; index < argc; index++)
1396     {
1397       name_add (argv[index]);
1398       args.input_files++;
1399     }
1400
1401   /* Derive option values and check option consistency.  */
1402
1403   if (archive_format == DEFAULT_FORMAT)
1404     {
1405       if (args.pax_option)
1406         archive_format = POSIX_FORMAT;
1407       else
1408         archive_format = DEFAULT_ARCHIVE_FORMAT;
1409     }
1410
1411   if (volume_label_option && subcommand_option == CREATE_SUBCOMMAND)
1412     assert_format (FORMAT_MASK (OLDGNU_FORMAT)
1413                    | FORMAT_MASK (GNU_FORMAT));
1414
1415
1416   if (incremental_option || multi_volume_option)
1417     assert_format (FORMAT_MASK (OLDGNU_FORMAT) | FORMAT_MASK (GNU_FORMAT));
1418
1419   if (sparse_option)
1420     assert_format (FORMAT_MASK (OLDGNU_FORMAT)
1421                    | FORMAT_MASK (GNU_FORMAT)
1422                    | FORMAT_MASK (POSIX_FORMAT));
1423
1424   if (occurrence_option)
1425     {
1426       if (!args.input_files && !files_from_option)
1427         USAGE_ERROR ((0, 0,
1428                       _("--occurrence is meaningless without a file list")));
1429       if (subcommand_option != DELETE_SUBCOMMAND
1430           && subcommand_option != DIFF_SUBCOMMAND
1431           && subcommand_option != EXTRACT_SUBCOMMAND
1432           && subcommand_option != LIST_SUBCOMMAND)
1433             USAGE_ERROR ((0, 0,
1434                           _("--occurrence cannot be used in the requested operation mode")));
1435     }
1436
1437   if (archive_names == 0)
1438     {
1439       /* If no archive file name given, try TAPE from the environment, or
1440          else, DEFAULT_ARCHIVE from the configuration process.  */
1441
1442       archive_names = 1;
1443       archive_name_array[0] = getenv ("TAPE");
1444       if (! archive_name_array[0])
1445         archive_name_array[0] = DEFAULT_ARCHIVE;
1446     }
1447
1448   /* Allow multiple archives only with `-M'.  */
1449
1450   if (archive_names > 1 && !multi_volume_option)
1451     USAGE_ERROR ((0, 0,
1452                   _("Multiple archive files require `-M' option")));
1453
1454   if (listed_incremental_option
1455       && NEWER_OPTION_INITIALIZED (newer_mtime_option))
1456     USAGE_ERROR ((0, 0,
1457                   _("Cannot combine --listed-incremental with --newer")));
1458
1459   if (volume_label_option)
1460     {
1461       size_t volume_label_max_len =
1462         (sizeof current_header->header.name
1463          - 1 /* for trailing '\0' */
1464          - (multi_volume_option
1465             ? (sizeof " Volume "
1466                - 1 /* for null at end of " Volume " */
1467                + INT_STRLEN_BOUND (int) /* for volume number */
1468                - 1 /* for sign, as 0 <= volno */)
1469             : 0));
1470       if (volume_label_max_len < strlen (volume_label_option))
1471         USAGE_ERROR ((0, 0,
1472                       ngettext ("%s: Volume label is too long (limit is %lu byte)",
1473                                 "%s: Volume label is too long (limit is %lu bytes)",
1474                                 volume_label_max_len),
1475                       quotearg_colon (volume_label_option),
1476                       (unsigned long) volume_label_max_len));
1477     }
1478
1479   if (verify_option)
1480     {
1481       if (multi_volume_option)
1482         USAGE_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
1483       if (use_compress_program_option)
1484         USAGE_ERROR ((0, 0, _("Cannot verify compressed archives")));
1485     }
1486
1487   if (use_compress_program_option)
1488     {
1489       if (multi_volume_option)
1490         USAGE_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
1491       if (subcommand_option == UPDATE_SUBCOMMAND)
1492         USAGE_ERROR ((0, 0, _("Cannot update compressed archives")));
1493     }
1494
1495   /* It is no harm to use --pax-option on non-pax archives in archive
1496      reading mode. It may even be useful, since it allows to override
1497      file attributes from tar headers. Therefore I allow such usage.
1498      --gray */
1499   if (args.pax_option
1500       && archive_format != POSIX_FORMAT
1501       && (subcommand_option != EXTRACT_SUBCOMMAND
1502           || subcommand_option != DIFF_SUBCOMMAND
1503           || subcommand_option != LIST_SUBCOMMAND))
1504     USAGE_ERROR ((0, 0, _("--pax-option can be used only on POSIX archives")));
1505
1506   /* If ready to unlink hierarchies, so we are for simpler files.  */
1507   if (recursive_unlink_option)
1508     old_files_option = UNLINK_FIRST_OLD_FILES;
1509
1510   if (utc_option)
1511     verbose_option = 2;
1512
1513   if (!rmt_command_option)
1514     rmt_command_option = DEFAULT_RMT_COMMAND;
1515   
1516   /* Forbid using -c with no input files whatsoever.  Check that `-f -',
1517      explicit or implied, is used correctly.  */
1518
1519   switch (subcommand_option)
1520     {
1521     case CREATE_SUBCOMMAND:
1522       if (args.input_files == 0 && !files_from_option)
1523         USAGE_ERROR ((0, 0,
1524                       _("Cowardly refusing to create an empty archive")));
1525       break;
1526
1527     case EXTRACT_SUBCOMMAND:
1528     case LIST_SUBCOMMAND:
1529     case DIFF_SUBCOMMAND:
1530       for (archive_name_cursor = archive_name_array;
1531            archive_name_cursor < archive_name_array + archive_names;
1532            archive_name_cursor++)
1533         if (!strcmp (*archive_name_cursor, "-"))
1534           request_stdin ("-f");
1535       break;
1536
1537     case CAT_SUBCOMMAND:
1538     case UPDATE_SUBCOMMAND:
1539     case APPEND_SUBCOMMAND:
1540       for (archive_name_cursor = archive_name_array;
1541            archive_name_cursor < archive_name_array + archive_names;
1542            archive_name_cursor++)
1543         if (!strcmp (*archive_name_cursor, "-"))
1544           USAGE_ERROR ((0, 0,
1545                         _("Options `-Aru' are incompatible with `-f -'")));
1546
1547     default:
1548       break;
1549     }
1550
1551   archive_name_cursor = archive_name_array;
1552
1553   /* Prepare for generating backup names.  */
1554
1555   if (args.backup_suffix_string)
1556     simple_backup_suffix = xstrdup (args.backup_suffix_string);
1557
1558   if (backup_option)
1559     backup_type = xget_version ("--backup", args.version_control_string);
1560
1561   if (verbose_option && args.textual_date_option)
1562     {
1563       /* FIXME: tartime should support nanoseconds, too, so that this
1564          comparison doesn't complain about lost nanoseconds.  */
1565       char const *treated_as = tartime (newer_mtime_option.tv_sec);
1566       if (strcmp (args.textual_date_option, treated_as) != 0)
1567         WARN ((0, 0,
1568                ngettext ("Treating date `%s' as %s + %ld nanosecond",
1569                          "Treating date `%s' as %s + %ld nanoseconds",
1570                          newer_mtime_option.tv_nsec),
1571                args.textual_date_option, treated_as,
1572                newer_mtime_option.tv_nsec));
1573     }
1574 }
1575
1576 \f
1577 /* Tar proper.  */
1578
1579 /* Main routine for tar.  */
1580 int
1581 main (int argc, char **argv)
1582 {
1583 #if HAVE_CLOCK_GETTIME
1584   if (clock_gettime (CLOCK_REALTIME, &start_timespec) != 0)
1585 #endif
1586     start_time = time (0);
1587   program_name = argv[0];
1588   setlocale (LC_ALL, "");
1589   bindtextdomain (PACKAGE, LOCALEDIR);
1590   textdomain (PACKAGE);
1591
1592   exit_status = TAREXIT_SUCCESS;
1593   filename_terminator = '\n';
1594   set_quoting_style (0, escape_quoting_style);
1595
1596   /* Pre-allocate a few structures.  */
1597
1598   allocated_archive_names = 10;
1599   archive_name_array =
1600     xmalloc (sizeof (const char *) * allocated_archive_names);
1601   archive_names = 0;
1602
1603 #ifdef SIGCHLD
1604   /* System V fork+wait does not work if SIGCHLD is ignored.  */
1605   signal (SIGCHLD, SIG_DFL);
1606 #endif
1607
1608   init_names ();
1609
1610   /* Decode options.  */
1611
1612   decode_options (argc, argv);
1613   name_init ();
1614
1615   /* Main command execution.  */
1616
1617   if (volno_file_option)
1618     init_volume_number ();
1619
1620   switch (subcommand_option)
1621     {
1622     case UNKNOWN_SUBCOMMAND:
1623       USAGE_ERROR ((0, 0,
1624                     _("You must specify one of the `-Acdtrux' options")));
1625
1626     case CAT_SUBCOMMAND:
1627     case UPDATE_SUBCOMMAND:
1628     case APPEND_SUBCOMMAND:
1629       update_archive ();
1630       break;
1631
1632     case DELETE_SUBCOMMAND:
1633       delete_archive_members ();
1634       break;
1635
1636     case CREATE_SUBCOMMAND:
1637       create_archive ();
1638       name_close ();
1639
1640       if (totals_option)
1641         print_total_written ();
1642       break;
1643
1644     case EXTRACT_SUBCOMMAND:
1645       extr_init ();
1646       read_and (extract_archive);
1647
1648       /* FIXME: should extract_finish () even if an ordinary signal is
1649          received.  */
1650       extract_finish ();
1651
1652       break;
1653
1654     case LIST_SUBCOMMAND:
1655       read_and (list_archive);
1656       break;
1657
1658     case DIFF_SUBCOMMAND:
1659       diff_init ();
1660       read_and (diff_archive);
1661       break;
1662     }
1663
1664   if (check_links_option)
1665     check_links ();
1666
1667   if (volno_file_option)
1668     closeout_volume_number ();
1669
1670   /* Dispose of allocated memory, and return.  */
1671
1672   free (archive_name_array);
1673   name_term ();
1674
1675   if (stdlis != stderr && (ferror (stdlis) || fclose (stdlis) != 0))
1676     FATAL_ERROR ((0, 0, _("Error in writing to standard output")));
1677   if (exit_status == TAREXIT_FAILURE)
1678     error (0, 0, _("Error exit delayed from previous errors"));
1679   if (ferror (stderr) || fclose (stderr) != 0)
1680     exit_status = TAREXIT_FAILURE;
1681   return exit_status;
1682 }
1683
1684 void
1685 tar_stat_init (struct tar_stat_info *st)
1686 {
1687   memset (st, 0, sizeof (*st));
1688 }
1689
1690 void
1691 tar_stat_destroy (struct tar_stat_info *st)
1692 {
1693   free (st->orig_file_name);
1694   free (st->file_name);
1695   free (st->link_name);
1696   free (st->uname);
1697   free (st->gname);
1698   free (st->sparse_map);
1699   memset (st, 0, sizeof (*st));
1700 }