]> git.gag.com Git - debian/tar/blob - src/tar.c
version 1.12.64003
[debian/tar] / src / tar.c
1 /* A tar (tape archiver) program.
2    Copyright (C) 1988, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.
3    Written by John Gilmore, starting 1985-08-25.
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published by the
7    Free Software Foundation; either version 2, or (at your option) any later
8    version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
13    Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation, Inc.,
17    59 Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 #include "system.h"
20
21 #include <getopt.h>
22
23 /* The following causes "common.h" to produce definitions of all the global
24    variables, rather than just "extern" declarations of them.  GNU tar does
25    depend on the system loader to preset all GLOBAL variables to neutral (or
26    zero) values, explicit initialisation is usually not done.  */
27 #define GLOBAL
28 #include "common.h"
29
30 #include "backupfile.h"
31 enum backup_type get_version ();
32
33 /* FIXME: We should use a conversion routine that does reasonable error
34    checking -- atol doesn't.  For now, punt.  */
35 #define intconv atol
36
37 time_t get_date ();
38
39 /* Local declarations.  */
40
41 #ifndef DEFAULT_ARCHIVE
42 # define DEFAULT_ARCHIVE "tar.out"
43 #endif
44
45 #ifndef DEFAULT_BLOCKING
46 # define DEFAULT_BLOCKING 20
47 #endif
48
49 static void usage PARAMS ((int));
50 \f
51 /* Miscellaneous.  */
52
53 /*------------------------------------------------------------------------.
54 | Check if STRING0 is the decimal representation of number, and store its |
55 | value.  If not a decimal number, return 0.                              |
56 `------------------------------------------------------------------------*/
57
58 static int
59 check_decimal (const char *string0, uintmax_t *result)
60 {
61   const char *string = string0;
62   uintmax_t value = 0;
63
64   do
65     switch (*string)
66       {
67       case '0':
68       case '1':
69       case '2':
70       case '3':
71       case '4':
72       case '5':
73       case '6':
74       case '7':
75       case '8':
76       case '9':
77         {
78           uintmax_t v10 = value * 10;
79           uintmax_t v10d = v10 + (*string - '0');
80           if (v10 / 10 != value || v10d < v10)
81             return 0;
82           value = v10d;
83         }
84         break;
85
86       default:
87         return 0;
88       }
89   while (*++string);
90
91   *result = value;
92   return 1;
93 }
94
95 /*----------------------------------------------.
96 | Doesn't return if stdin already requested.    |
97 `----------------------------------------------*/
98
99 /* Name of option using stdin.  */
100 static const char *stdin_used_by = NULL;
101
102 void
103 request_stdin (const char *option)
104 {
105   if (stdin_used_by)
106     USAGE_ERROR ((0, 0, _("Options `-%s' and `-%s' both want standard input"),
107                   stdin_used_by, option));
108
109   stdin_used_by = option;
110 }
111
112 /*--------------------------------------------------------.
113 | Returns true if and only if the user typed 'y' or 'Y'.  |
114 `--------------------------------------------------------*/
115
116 int
117 confirm (const char *message_action, const char *message_name)
118 {
119   static FILE *confirm_file = NULL;
120
121   if (!confirm_file)
122     {
123       if (archive == 0 || stdin_used_by)
124         confirm_file = fopen (TTY_NAME, "r");
125       else
126         {
127           request_stdin ("-w");
128           confirm_file = stdin;
129         }
130
131       if (!confirm_file)
132         FATAL_ERROR ((0, 0, _("Cannot read confirmation from user")));
133     }
134
135   fprintf (stdlis, "%s %s?", message_action, message_name);
136   fflush (stdlis);
137
138   {
139     int reply = getc (confirm_file);
140     int character;
141
142     for (character = reply;
143          character != '\n' && character != EOF;
144          character = getc (confirm_file))
145       continue;
146     return reply == 'y' || reply == 'Y';
147   }
148 }
149 \f
150 /* Options.  */
151
152 /* For long options that unconditionally set a single flag, we have getopt
153    do it.  For the others, we share the code for the equivalent short
154    named option, the name of which is stored in the otherwise-unused `val'
155    field of the `struct option'; for long options that have no equivalent
156    short option, we use nongraphic characters as pseudo short option
157    characters, starting at 2 and going upwards.  */
158
159 #define BACKUP_OPTION                   2
160 #define DELETE_OPTION                   3
161 #define EXCLUDE_OPTION                  4
162 #define GROUP_OPTION                    5
163 #define MODE_OPTION                     6
164 #define NEWER_MTIME_OPTION              7
165 #define NO_RECURSE_OPTION               8
166 #define NULL_OPTION                     9
167 #define OWNER_OPTION                    10
168 #define POSIX_OPTION                    11
169 #define PRESERVE_OPTION                 12
170 #define RECORD_SIZE_OPTION              13
171 #define RSH_COMMAND_OPTION              14
172 #define SUFFIX_OPTION                   15
173 #define USE_COMPRESS_PROGRAM_OPTION     16
174 #define VOLNO_FILE_OPTION               17
175
176 /* Some cleanup is being made in GNU tar long options.  Using old names is
177    allowed for a while, but will also send a warning to stderr.  Take old
178    names out in 1.14, or in summer 1997, whichever happens last.  We use
179    nongraphic characters as pseudo short option characters, starting at 31
180    and going downwards.  */
181
182 #define OBSOLETE_ABSOLUTE_NAMES         31
183 #define OBSOLETE_BLOCK_COMPRESS         30
184 #define OBSOLETE_BLOCKING_FACTOR        29
185 #define OBSOLETE_BLOCK_NUMBER           28
186 #define OBSOLETE_READ_FULL_RECORDS      27
187 #define OBSOLETE_TOUCH                  26
188 #define OBSOLETE_VERSION_CONTROL        25
189
190 /* If nonzero, display usage information and exit.  */
191 static int show_help = 0;
192
193 /* If nonzero, print the version on standard output and exit.  */
194 static int show_version = 0;
195
196 struct option long_options[] =
197 {
198   {"absolute-names", no_argument, NULL, 'P'},
199   {"absolute-paths", no_argument, NULL, OBSOLETE_ABSOLUTE_NAMES},
200   {"after-date", required_argument, NULL, 'N'},
201   {"append", no_argument, NULL, 'r'},
202   {"atime-preserve", no_argument, &atime_preserve_option, 1},
203   {"backup", optional_argument, NULL, BACKUP_OPTION},
204   {"block-compress", no_argument, NULL, OBSOLETE_BLOCK_COMPRESS},
205   {"block-number", no_argument, NULL, 'R'},
206   {"block-size", required_argument, NULL, OBSOLETE_BLOCKING_FACTOR},
207   {"blocking-factor", required_argument, NULL, 'b'},
208   {"catenate", no_argument, NULL, 'A'},
209   {"checkpoint", no_argument, &checkpoint_option, 1},
210   {"compare", no_argument, NULL, 'd'},
211   {"compress", no_argument, NULL, 'Z'},
212   {"concatenate", no_argument, NULL, 'A'},
213   {"confirmation", no_argument, NULL, 'w'},
214   /* FIXME: --selective as a synonym for --confirmation?  */
215   {"create", no_argument, NULL, 'c'},
216   {"delete", no_argument, NULL, DELETE_OPTION},
217   {"dereference", no_argument, NULL, 'h'},
218   {"diff", no_argument, NULL, 'd'},
219   {"directory", required_argument, NULL, 'C'},
220   {"ending-file", required_argument, NULL, 'E'},
221   {"exclude", required_argument, NULL, EXCLUDE_OPTION},
222   {"exclude-from", required_argument, NULL, 'X'},
223   {"extract", no_argument, NULL, 'x'},
224   {"file", required_argument, NULL, 'f'},
225   {"files-from", required_argument, NULL, 'T'},
226   {"force-local", no_argument, &force_local_option, 1},
227   {"get", no_argument, NULL, 'x'},
228   {"group", required_argument, NULL, GROUP_OPTION},
229   {"gunzip", no_argument, NULL, 'z'},
230   {"gzip", no_argument, NULL, 'z'},
231   {"help", no_argument, &show_help, 1},
232   {"ignore-failed-read", no_argument, &ignore_failed_read_option, 1},
233   {"ignore-zeros", no_argument, NULL, 'i'},
234   /* FIXME: --ignore-end as a new name for --ignore-zeros?  */
235   {"incremental", no_argument, NULL, 'G'},
236   {"info-script", required_argument, NULL, 'F'},
237   {"interactive", no_argument, NULL, 'w'},
238   {"keep-old-files", no_argument, NULL, 'k'},
239   {"label", required_argument, NULL, 'V'},
240   {"list", no_argument, NULL, 't'},
241   {"listed-incremental", required_argument, NULL, 'g'},
242   {"mode", required_argument, NULL, MODE_OPTION},
243   {"modification-time", no_argument, NULL, OBSOLETE_TOUCH},
244   {"multi-volume", no_argument, NULL, 'M'},
245   {"new-volume-script", required_argument, NULL, 'F'},
246   {"newer", required_argument, NULL, 'N'},
247   {"newer-mtime", required_argument, NULL, NEWER_MTIME_OPTION},
248   {"null", no_argument, NULL, NULL_OPTION},
249   {"no-recursion", no_argument, NULL, NO_RECURSE_OPTION},
250   {"numeric-owner", no_argument, &numeric_owner_option, 1},
251   {"old-archive", no_argument, NULL, 'o'},
252   {"one-file-system", no_argument, NULL, 'l'},
253   {"owner", required_argument, NULL, OWNER_OPTION},
254   {"portability", no_argument, NULL, 'o'},
255   {"posix", no_argument, NULL, POSIX_OPTION},
256   {"preserve", no_argument, NULL, PRESERVE_OPTION},
257   {"preserve-order", no_argument, NULL, 's'},
258   {"preserve-permissions", no_argument, NULL, 'p'},
259   {"recursive-unlink", no_argument, &recursive_unlink_option, 1},
260   {"read-full-blocks", no_argument, NULL, OBSOLETE_READ_FULL_RECORDS},
261   {"read-full-records", no_argument, NULL, 'B'},
262   /* FIXME: --partial-blocks might be a synonym for --read-full-records?  */
263   {"record-number", no_argument, NULL, OBSOLETE_BLOCK_NUMBER},
264   {"record-size", required_argument, NULL, RECORD_SIZE_OPTION},
265   {"remove-files", no_argument, &remove_files_option, 1},
266   {"rsh-command", required_argument, NULL, RSH_COMMAND_OPTION},
267   {"same-order", no_argument, NULL, 's'},
268   {"same-owner", no_argument, &same_owner_option, 1},
269   {"same-permissions", no_argument, NULL, 'p'},
270   {"show-omitted-dirs", no_argument, &show_omitted_dirs_option, 1},
271   {"sparse", no_argument, NULL, 'S'},
272   {"starting-file", required_argument, NULL, 'K'},
273   {"suffix", required_argument, NULL, SUFFIX_OPTION},
274   {"tape-length", required_argument, NULL, 'L'},
275   {"to-stdout", no_argument, NULL, 'O'},
276   {"totals", no_argument, &totals_option, 1},
277   {"touch", no_argument, NULL, 'm'},
278   {"uncompress", no_argument, NULL, 'Z'},
279   {"ungzip", no_argument, NULL, 'z'},
280   {"unlink-first", no_argument, NULL, 'U'},
281   {"update", no_argument, NULL, 'u'},
282   {"use-compress-program", required_argument, NULL, USE_COMPRESS_PROGRAM_OPTION},
283   {"verbose", no_argument, NULL, 'v'},
284   {"verify", no_argument, NULL, 'W'},
285   {"version", no_argument, &show_version, 1},
286   {"version-control", required_argument, NULL, OBSOLETE_VERSION_CONTROL},
287   {"volno-file", required_argument, NULL, VOLNO_FILE_OPTION},
288
289   {0, 0, 0, 0}
290 };
291
292 /*---------------------------------------------.
293 | Print a usage message and exit with STATUS.  |
294 `---------------------------------------------*/
295
296 static void
297 usage (int status)
298 {
299   if (status != TAREXIT_SUCCESS)
300     fprintf (stderr, _("Try `%s --help' for more information.\n"),
301              program_name);
302   else
303     {
304       fputs (_("\
305 GNU `tar' saves many files together into a single tape or disk archive, and\n\
306 can restore individual files from the archive.\n"),
307              stdout);
308       printf (_("\nUsage: %s [OPTION]... [FILE]...\n"), program_name);
309       fputs (_("\
310 \n\
311 If a long option shows an argument as mandatory, then it is mandatory\n\
312 for the equivalent short option also.  Similarly for optional arguments.\n"),
313              stdout);
314       fputs(_("\
315 \n\
316 Main operation mode:\n\
317   -t, --list              list the contents of an archive\n\
318   -x, --extract, --get    extract files from an archive\n\
319   -c, --create            create a new archive\n\
320   -d, --diff, --compare   find differences between archive and file system\n\
321   -r, --append            append files to the end of an archive\n\
322   -u, --update            only append files newer than copy in archive\n\
323   -A, --catenate          append tar files to an archive\n\
324       --concatenate       same as -A\n\
325       --delete            delete from the archive (not on mag tapes!)\n"),
326             stdout);
327       fputs (_("\
328 \n\
329 Operation modifiers:\n\
330   -W, --verify               attempt to verify the archive after writing it\n\
331       --remove-files         remove files after adding them to the archive\n\
332   -k, --keep-old-files       don't overwrite existing files when extracting\n\
333   -U, --unlink-first         remove each file prior to extracting over it\n\
334       --recursive-unlink     empty hierarchies prior to extracting directory\n\
335   -S, --sparse               handle sparse files efficiently\n\
336   -O, --to-stdout            extract files to standard output\n\
337   -G, --incremental          handle old GNU-format incremental backup\n\
338   -g, --listed-incremental   handle new GNU-format incremental backup\n\
339       --ignore-failed-read   do not exit with nonzero on unreadable files\n"),
340              stdout);
341       fputs (_("\
342 \n\
343 Handling of file attributes:\n\
344       --owner=NAME             force NAME as owner for added files\n\
345       --group=NAME             force NAME as group for added files\n\
346       --mode=CHANGES           force (symbolic) mode CHANGES for added files\n\
347       --atime-preserve         don't change access times on dumped files\n\
348   -m, --modification-time      don't extract file modified time\n\
349       --same-owner             try extracting files with the same ownership\n\
350       --numeric-owner          always use numbers for user/group names\n\
351   -p, --same-permissions       extract all protection information\n\
352       --preserve-permissions   same as -p\n\
353   -s, --same-order             sort names to extract to match archive\n\
354       --preserve-order         same as -s\n\
355       --preserve               same as both -p and -s\n"),
356              stdout);
357       fputs (_("\
358 \n\
359 Device selection and switching:\n\
360   -f, --file=ARCHIVE             use archive file or device ARCHIVE\n\
361       --force-local              archive file is local even if has a colon\n\
362       --rsh-command=COMMAND      use remote COMMAND instead of rsh\n\
363   -[0-7][lmh]                    specify drive and density\n\
364   -M, --multi-volume             create/list/extract multi-volume archive\n\
365   -L, --tape-length=NUM          change tape after writing NUM x 1024 bytes\n\
366   -F, --info-script=FILE         run script at end of each tape (implies -M)\n\
367       --new-volume-script=FILE   same as -F FILE\n\
368       --volno-file=FILE          use/update the volume number in FILE\n"),
369              stdout);
370       fputs (_("\
371 \n\
372 Device blocking:\n\
373   -b, --blocking-factor=BLOCKS   BLOCKS x 512 bytes per record\n\
374       --record-size=SIZE         SIZE bytes per record, multiple of 512\n\
375   -i, --ignore-zeros             ignore zeroed blocks in archive (means EOF)\n\
376   -B, --read-full-records        reblock as we read (for 4.2BSD pipes)\n"),
377              stdout);
378       fputs (_("\
379 \n\
380 Archive format selection:\n\
381   -V, --label=NAME                   create archive with volume name NAME\n\
382               PATTERN                at list/extract time, a globbing PATTERN\n\
383   -o, --old-archive, --portability   write a V7 format archive\n\
384       --posix                        write a POSIX conformant archive\n\
385   -z, --gzip, --ungzip               filter the archive through gzip\n\
386   -Z, --compress, --uncompress       filter the archive through compress\n\
387       --use-compress-program=PROG    filter through PROG (must accept -d)\n"),
388              stdout);
389       fputs (_("\
390 \n\
391 Local file selection:\n\
392   -C, --directory=DIR          change to directory DIR\n\
393   -T, --files-from=NAME        get names to extract or create from file NAME\n\
394       --null                   -T reads null-terminated names, disable -C\n\
395       --exclude=PATTERN        exclude files, given as a globbing PATTERN\n\
396   -X, --exclude-from=FILE      exclude globbing patterns listed in FILE\n\
397   -P, --absolute-names         don't strip leading `/'s from file names\n\
398   -h, --dereference            dump instead the files symlinks point to\n\
399       --no-recursion           avoid descending automatically in directories\n\
400   -l, --one-file-system        stay in local file system when creating archive\n\
401   -E, --ending-file=NAME       end reading the archive before file NAME\n\
402   -K, --starting-file=NAME     begin at file NAME in the archive\n"),
403              stdout);
404 #if !MSDOS
405       fputs (_("\
406   -N, --newer=DATE             only store files newer than DATE\n\
407       --newer-mtime            compare date and time when data changed only\n\
408       --after-date=DATE        same as -N\n"),
409              stdout);
410 #endif
411       fputs (_("\
412       --backup[=CONTROL]       backup before removal, choose version control\n\
413       --suffix=SUFFIX          backup before removel, override usual suffix\n"),
414              stdout);
415       fputs (_("\
416 \n\
417 Informative output:\n\
418       --help            print this help, then exit\n\
419       --version         print tar program version number, then exit\n\
420   -v, --verbose         verbosely list files processed\n\
421       --checkpoint      print directory names while reading the archive\n\
422       --totals          print total bytes written while creating archive\n\
423   -R, --block-number    show block number within archive with each message\n\
424   -w, --interactive     ask for confirmation for every action\n\
425       --confirmation    same as -w\n"),
426              stdout);
427       fputs (_("\
428 \n\
429 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
430 The version control may be set with --backup or VERSION_CONTROL, values are:\n\
431 \n\
432   t, numbered     make numbered backups\n\
433   nil, existing   numbered if numbered backups exist, simple otherwise\n\
434   never, simple   always make simple backups\n"),
435              stdout);
436       printf (_("\
437 \n\
438 GNU tar cannot read nor produce `--posix' archives.  If POSIXLY_CORRECT\n\
439 is set in the environment, GNU extensions are disallowed with `--posix'.\n\
440 Support for POSIX is only partially implemented, don't count on it yet.\n\
441 ARCHIVE may be FILE, HOST:FILE or USER@HOST:FILE; and FILE may be a file\n\
442 or a device.  *This* `tar' defaults to `-f%s -b%d'.\n"),
443               DEFAULT_ARCHIVE, DEFAULT_BLOCKING);
444       fputs (_("\
445 \n\
446 Report bugs to <tar-bugs@gnu.ai.mit.edu>.\n"),
447                stdout);
448     }
449   exit (status);
450 }
451
452 /*----------------------------.
453 | Parse the options for tar.  |
454 `----------------------------*/
455
456 /* Available option letters are DHIJQY and aejnqy.  Some are reserved:
457
458    y  per-file gzip compression
459    Y  per-block gzip compression */
460
461 #define OPTION_STRING \
462   "-01234567ABC:E:F:GK:L:MN:OPRST:UV:WX:Zb:cdf:g:hiklmoprstuvwxz"
463
464 static void
465 set_subcommand_option (enum subcommand subcommand)
466 {
467   if (subcommand_option != UNKNOWN_SUBCOMMAND
468       && subcommand_option != subcommand)
469     USAGE_ERROR ((0, 0,
470                   _("You may not specify more than one `-Acdtrux' option")));
471
472   subcommand_option = subcommand;
473 }
474
475 static void
476 set_use_compress_program_option (const char *string)
477 {
478   if (use_compress_program_option && strcmp (use_compress_program_option, string) != 0)
479     USAGE_ERROR ((0, 0, _("Conflicting compression options")));
480
481   use_compress_program_option = string;
482 }
483
484 static void
485 decode_options (int argc, char *const *argv)
486 {
487   int optchar;                  /* option letter */
488   int input_files;              /* number of input files */
489   const char *backup_suffix_string;
490   const char *version_control_string;
491
492   /* Set some default option values.  */
493
494   subcommand_option = UNKNOWN_SUBCOMMAND;
495   archive_format = DEFAULT_FORMAT;
496   blocking_factor = DEFAULT_BLOCKING;
497   record_size = DEFAULT_BLOCKING * BLOCKSIZE;
498
499   owner_option = -1;
500   group_option = -1;
501
502   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
503   version_control_string = getenv ("VERSION_CONTROL");
504
505   /* Convert old-style tar call by exploding option element and rearranging
506      options accordingly.  */
507
508   if (argc > 1 && argv[1][0] != '-')
509     {
510       int new_argc;             /* argc value for rearranged arguments */
511       char **new_argv;          /* argv value for rearranged arguments */
512       char *const *in;          /* cursor into original argv */
513       char **out;               /* cursor into rearranged argv */
514       const char *letter;       /* cursor into old option letters */
515       char buffer[3];           /* constructed option buffer */
516       const char *cursor;       /* cursor in OPTION_STRING */
517
518       /* Initialize a constructed option.  */
519
520       buffer[0] = '-';
521       buffer[2] = '\0';
522
523       /* Allocate a new argument array, and copy program name in it.  */
524
525       new_argc = argc - 1 + strlen (argv[1]);
526       new_argv = (char **) xmalloc (new_argc * sizeof (char *));
527       in = argv;
528       out = new_argv;
529       *out++ = *in++;
530
531       /* Copy each old letter option as a separate option, and have the
532          corresponding argument moved next to it.  */
533
534       for (letter = *in++; *letter; letter++)
535         {
536           buffer[1] = *letter;
537           *out++ = xstrdup (buffer);
538           cursor = strchr (OPTION_STRING, *letter);
539           if (cursor && cursor[1] == ':')
540             if (in < argv + argc)
541               *out++ = *in++;
542             else
543               USAGE_ERROR ((0, 0, _("Old option `%c' requires an argument."),
544                             *letter));
545         }
546
547       /* Copy all remaining options.  */
548
549       while (in < argv + argc)
550         *out++ = *in++;
551
552       /* Replace the old option list by the new one.  */
553
554       argc = new_argc;
555       argv = new_argv;
556     }
557
558   /* Parse all options and non-options as they appear.  */
559
560   input_files = 0;
561
562   while (optchar = getopt_long (argc, argv, OPTION_STRING, long_options, NULL),
563          optchar != EOF)
564     switch (optchar)
565       {
566       case '?':
567         usage (TAREXIT_FAILURE);
568
569       case 0:
570         break;
571
572       case 1:
573         /* File name or non-parsed option, because of RETURN_IN_ORDER
574            ordering triggerred by the leading dash in OPTION_STRING.  */
575
576         name_add (optarg);
577         input_files++;
578         break;
579
580       case 'A':
581         set_subcommand_option (CAT_SUBCOMMAND);
582         break;
583
584       case OBSOLETE_BLOCK_COMPRESS:
585         WARN ((0, 0, _("Obsolete option, now implied by --blocking-factor")));
586         break;
587
588       case OBSOLETE_BLOCKING_FACTOR:
589         WARN ((0, 0, _("Obsolete option name replaced by --blocking-factor")));
590         /* Fall through.  */
591
592       case 'b':
593         blocking_factor = intconv (optarg);
594         record_size = blocking_factor * (size_t) BLOCKSIZE;
595         break;
596
597       case OBSOLETE_READ_FULL_RECORDS:
598         WARN ((0, 0,
599                _("Obsolete option name replaced by --read-full-records")));
600         /* Fall through.  */
601
602       case 'B':
603         /* Try to reblock input records.  For reading 4.2BSD pipes.  */
604
605         /* It would surely make sense to exchange -B and -R, but it seems
606            that -B has been used for a long while in Sun tar ans most
607            BSD-derived systems.  This is a consequence of the block/record
608            terminology confusion.  */
609
610         read_full_records_option = 1;
611         break;
612
613       case 'c':
614         set_subcommand_option (CREATE_SUBCOMMAND);
615         break;
616
617       case 'C':
618         name_add ("-C");
619         name_add (optarg);
620         break;
621
622       case 'd':
623         set_subcommand_option (DIFF_SUBCOMMAND);
624         break;
625
626       case 'E':
627         ending_file_option = optarg;
628         break;
629
630       case 'f':
631         if (archive_names == allocated_archive_names)
632           {
633             allocated_archive_names *= 2;
634             archive_name_array = (const char **)
635               xrealloc (archive_name_array,
636                         sizeof (const char *) * allocated_archive_names);
637           }
638         archive_name_array[archive_names++] = optarg;
639         break;
640
641       case 'F':
642         /* Since -F is only useful with -M, make it implied.  Run this
643            script at the end of each tape.  */
644
645         info_script_option = optarg;
646         multi_volume_option = 1;
647         break;
648
649       case 'g':
650         listed_incremental_option = optarg;
651         /* Fall through.  */
652
653       case 'G':
654         /* We are making an incremental dump (FIXME: are we?); save
655            directories at the beginning of the archive, and include in each
656            directory its contents.  */
657
658         incremental_option = 1;
659         break;
660
661       case 'h':
662         /* Follow symbolic links.  */
663
664         dereference_option = 1;
665         break;
666
667       case 'i':
668         /* Ignore zero blocks (eofs).  This can't be the default,
669            because Unix tar writes two blocks of zeros, then pads out
670            the record with garbage.  */
671
672         ignore_zeros_option = 1;
673         break;
674
675       case 'k':
676         /* Don't overwrite existing files.  */
677
678         keep_old_files_option = 1;
679         break;
680
681       case 'K':
682         starting_file_option = 1;
683         addname (optarg);
684         break;
685
686       case 'l':
687         /* When dumping directories, don't dump files/subdirectories
688            that are on other filesystems.  */
689
690         one_file_system_option = 1;
691         break;
692
693       case 'L':
694         clear_tarlong (tape_length_option);
695         add_to_tarlong (tape_length_option, intconv (optarg));
696         mult_tarlong (tape_length_option, 1024);
697         multi_volume_option = 1;
698         break;
699
700       case OBSOLETE_TOUCH:
701         WARN ((0, 0, _("Obsolete option name replaced by --touch")));
702         /* Fall through.  */
703
704       case 'm':
705         touch_option = 1;
706         break;
707
708       case 'M':
709         /* Make multivolume archive: when we can't write any more into
710            the archive, re-open it, and continue writing.  */
711
712         multi_volume_option = 1;
713         break;
714
715 #if !MSDOS
716       case 'N':
717         after_date_option = 1;
718         /* Fall through.  */
719
720       case NEWER_MTIME_OPTION:
721         if (newer_mtime_option)
722           USAGE_ERROR ((0, 0, _("More than one threshold date")));
723
724         newer_mtime_option = get_date (optarg, (voidstar) 0);
725         if (newer_mtime_option == (time_t) -1)
726           USAGE_ERROR ((0, 0, _("Invalid date format `%s'"), optarg));
727
728         break;
729 #endif /* not MSDOS */
730
731       case 'o':
732         if (archive_format == DEFAULT_FORMAT)
733           archive_format = V7_FORMAT;
734         else if (archive_format != V7_FORMAT)
735           USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
736         break;
737
738       case 'O':
739         to_stdout_option = 1;
740         break;
741
742       case 'p':
743         same_permissions_option = 1;
744         break;
745
746       case OBSOLETE_ABSOLUTE_NAMES:
747         WARN ((0, 0, _("Obsolete option name replaced by --absolute-names")));
748         /* Fall through.  */
749
750       case 'P':
751         absolute_names_option = 1;
752         break;
753
754       case 'r':
755         set_subcommand_option (APPEND_SUBCOMMAND);
756         break;
757
758       case OBSOLETE_BLOCK_NUMBER:
759         WARN ((0, 0, _("Obsolete option name replaced by --block-number")));
760         /* Fall through.  */
761
762       case 'R':
763         /* Print block numbers for debugging bad tar archives.  */
764
765         /* It would surely make sense to exchange -B and -R, but it seems
766            that -B has been used for a long while in Sun tar ans most
767            BSD-derived systems.  This is a consequence of the block/record
768            terminology confusion.  */
769
770         block_number_option = 1;
771         break;
772
773       case 's':
774         /* Names to extr are sorted.  */
775
776         same_order_option = 1;
777         break;
778
779       case 'S':
780         sparse_option = 1;
781         break;
782
783       case 't':
784         set_subcommand_option (LIST_SUBCOMMAND);
785         verbose_option++;
786         break;
787
788       case 'T':
789         files_from_option = optarg;
790         break;
791
792       case 'u':
793         set_subcommand_option (UPDATE_SUBCOMMAND);
794         break;
795
796       case 'U':
797         unlink_first_option = 1;
798         break;
799
800       case 'v':
801         verbose_option++;
802         break;
803
804       case 'V':
805         volume_label_option = optarg;
806         break;
807
808       case 'w':
809         interactive_option = 1;
810         break;
811
812       case 'W':
813         verify_option = 1;
814         break;
815
816       case 'x':
817         set_subcommand_option (EXTRACT_SUBCOMMAND);
818         break;
819
820       case 'X':
821         exclude_option = 1;
822         add_exclude_file (optarg);
823         break;
824
825       case 'z':
826         set_use_compress_program_option ("gzip");
827         break;
828
829       case 'Z':
830         set_use_compress_program_option ("compress");
831         break;
832
833       case OBSOLETE_VERSION_CONTROL:
834         WARN ((0, 0, _("Obsolete option name replaced by --backup")));
835         /* Fall through.  */
836
837       case BACKUP_OPTION:
838         backup_option = 1;
839         if (optarg)
840           version_control_string = optarg;
841         break;
842
843       case DELETE_OPTION:
844         set_subcommand_option (DELETE_SUBCOMMAND);
845         break;
846
847       case EXCLUDE_OPTION:
848         exclude_option = 1;
849         add_exclude (optarg);
850         break;
851
852       case GROUP_OPTION:
853         if (!gname_to_gid (optarg, &group_option))
854           {
855             uintmax_t g;
856             if (!check_decimal (optarg, &g) || g != (gid_t) g)
857               ERROR ((TAREXIT_FAILURE, 0, _("Invalid group given on option")));
858             else
859               group_option = g;
860           }
861         break;
862
863       case MODE_OPTION:
864         mode_option
865           = mode_compile (optarg,
866                           MODE_MASK_EQUALS | MODE_MASK_PLUS | MODE_MASK_MINUS);
867         if (mode_option == MODE_INVALID)
868           ERROR ((TAREXIT_FAILURE, 0, _("Invalid mode given on option")));
869         if (mode_option == MODE_MEMORY_EXHAUSTED)
870           ERROR ((TAREXIT_FAILURE, 0, _("Memory exhausted")));
871         break;
872
873       case NO_RECURSE_OPTION:
874         no_recurse_option = 1;
875         break;
876
877       case NULL_OPTION:
878         filename_terminator = '\0';
879         break;
880
881       case OWNER_OPTION:
882         if (!uname_to_uid (optarg, &owner_option))
883           {
884             uintmax_t u;
885             if (!check_decimal (optarg, &u) || u != (uid_t) u)
886               ERROR ((TAREXIT_FAILURE, 0, _("Invalid owner given on option")));
887             else
888               owner_option = u;
889           }
890         break;
891
892       case POSIX_OPTION:
893 #if OLDGNU_COMPATIBILITY
894         if (archive_format == DEFAULT_FORMAT)
895           archive_format = GNU_FORMAT;
896         else if (archive_format != GNU_FORMAT)
897           USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
898 #else
899         if (archive_format == DEFAULT_FORMAT)
900           archive_format = POSIX_FORMAT;
901         else if (archive_format != POSIX_FORMAT)
902           USAGE_ERROR ((0, 0, _("Conflicting archive format options")));
903 #endif
904         break;
905
906       case PRESERVE_OPTION:
907         same_permissions_option = 1;
908         same_order_option = 1;
909         break;
910
911       case RECORD_SIZE_OPTION:
912         record_size = intconv (optarg);
913         if (record_size % BLOCKSIZE != 0)
914           USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
915                         BLOCKSIZE));
916         blocking_factor = record_size / BLOCKSIZE;
917         break;
918
919       case RSH_COMMAND_OPTION:
920         rsh_command_option = optarg;
921         break;
922
923       case SUFFIX_OPTION:
924         backup_option = 1;
925         backup_suffix_string = optarg;
926         break;
927
928       case VOLNO_FILE_OPTION:
929         volno_file_option = optarg;
930         break;
931
932       case USE_COMPRESS_PROGRAM_OPTION:
933         set_use_compress_program_option (optarg);
934         break;
935
936       case '0':
937       case '1':
938       case '2':
939       case '3':
940       case '4':
941       case '5':
942       case '6':
943       case '7':
944
945 #ifdef DEVICE_PREFIX
946         {
947           int device = optchar - '0';
948           int density;
949           static char buf[sizeof DEVICE_PREFIX + 10];
950           char *cursor;
951
952           density = getopt_long (argc, argv, "lmh", NULL, NULL);
953           strcpy (buf, DEVICE_PREFIX);
954           cursor = buf + strlen (buf);
955
956 #ifdef DENSITY_LETTER
957
958           sprintf (cursor, "%d%c", device, density);
959
960 #else /* not DENSITY_LETTER */
961
962           switch (density)
963             {
964             case 'l':
965 #ifdef LOW_NUM
966               device += LOW_NUM;
967 #endif
968               break;
969
970             case 'm':
971 #ifdef MID_NUM
972               device += MID_NUM;
973 #else
974               device += 8;
975 #endif
976               break;
977
978             case 'h':
979 #ifdef HGH_NUM
980               device += HGH_NUM;
981 #else
982               device += 16;
983 #endif
984               break;
985
986             default:
987               usage (TAREXIT_FAILURE);
988             }
989           sprintf (cursor, "%d", device);
990
991 #endif /* not DENSITY_LETTER */
992
993           if (archive_names == allocated_archive_names)
994             {
995               allocated_archive_names *= 2;
996               archive_name_array = (const char **)
997                 xrealloc (archive_name_array,
998                           sizeof (const char *) * allocated_archive_names);
999             }
1000           archive_name_array[archive_names++] = buf;
1001
1002           /* FIXME: How comes this works for many archives when buf is
1003              not xstrdup'ed?  */
1004         }
1005         break;
1006
1007 #else /* not DEVICE_PREFIX */
1008
1009         USAGE_ERROR ((0, 0,
1010                       _("Options `-[0-7][lmh]' not supported by *this* tar")));
1011
1012 #endif /* not DEVICE_PREFIX */
1013       }
1014
1015   /* Process trivial options.  */
1016
1017   if (show_version)
1018     {
1019       printf ("tar (GNU %s) %s\n", PACKAGE, VERSION);
1020       fputs (_("\
1021 \n\
1022 Copyright (C) 1988, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.\n"),
1023              stdout);
1024       fputs (_("\
1025 This is free software; see the source for copying conditions.  There is NO\n\
1026 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"),
1027              stdout);
1028       fputs (_("\
1029 \n\
1030 Written by John Gilmore and Jay Fenlason.\n"),
1031              stdout);
1032       exit (TAREXIT_SUCCESS);
1033     }
1034
1035   if (show_help)
1036     usage (TAREXIT_SUCCESS);
1037
1038   /* Derive option values and check option consistency.  */
1039
1040   if (archive_format == DEFAULT_FORMAT)
1041     {
1042 #if OLDGNU_COMPATIBILITY
1043       archive_format = OLDGNU_FORMAT;
1044 #else
1045       archive_format = GNU_FORMAT;
1046 #endif
1047     }
1048
1049   if (archive_format == GNU_FORMAT && getenv ("POSIXLY_CORRECT"))
1050     archive_format = POSIX_FORMAT;
1051
1052   if ((volume_label_option != NULL
1053        || incremental_option || multi_volume_option || sparse_option)
1054       && archive_format != OLDGNU_FORMAT && archive_format != GNU_FORMAT)
1055     USAGE_ERROR ((0, 0,
1056                   _("GNU features wanted on incompatible archive format")));
1057
1058   if (archive_names == 0)
1059     {
1060       /* If no archive file name given, try TAPE from the environment, or
1061          else, DEFAULT_ARCHIVE from the configuration process.  */
1062
1063       archive_names = 1;
1064       archive_name_array[0] = getenv ("TAPE");
1065       if (archive_name_array[0] == NULL)
1066         archive_name_array[0] = DEFAULT_ARCHIVE;
1067     }
1068
1069   /* Allow multiple archives only with `-M'.  */
1070
1071   if (archive_names > 1 && !multi_volume_option)
1072     USAGE_ERROR ((0, 0,
1073                   _("Multiple archive files requires `-M' option")));
1074
1075   /* If ready to unlink hierarchies, so we are for simpler files.  */
1076   if (recursive_unlink_option)
1077     unlink_first_option = 1;
1078
1079   /* Forbid using -c with no input files whatsoever.  Check that `-f -',
1080      explicit or implied, is used correctly.  */
1081
1082   switch (subcommand_option)
1083     {
1084     case CREATE_SUBCOMMAND:
1085       if (input_files == 0 && !files_from_option)
1086         USAGE_ERROR ((0, 0,
1087                       _("Cowardly refusing to create an empty archive")));
1088       break;
1089
1090     case EXTRACT_SUBCOMMAND:
1091     case LIST_SUBCOMMAND:
1092     case DIFF_SUBCOMMAND:
1093       for (archive_name_cursor = archive_name_array;
1094            archive_name_cursor < archive_name_array + archive_names;
1095            archive_name_cursor++)
1096         if (!strcmp (*archive_name_cursor, "-"))
1097           request_stdin ("-f");
1098       break;
1099
1100     case CAT_SUBCOMMAND:
1101     case UPDATE_SUBCOMMAND:
1102     case APPEND_SUBCOMMAND:
1103       for (archive_name_cursor = archive_name_array;
1104            archive_name_cursor < archive_name_array + archive_names;
1105            archive_name_cursor++)
1106         if (!strcmp (*archive_name_cursor, "-"))
1107           USAGE_ERROR ((0, 0,
1108                         _("Options `-Aru' are incompatible with `-f -'")));
1109
1110     default:
1111       break;
1112     }
1113
1114   archive_name_cursor = archive_name_array;
1115
1116   /* Prepare for generating backup names.  */
1117
1118   if (backup_suffix_string)
1119     simple_backup_suffix = xstrdup (backup_suffix_string);
1120
1121   if (backup_option)
1122     backup_type = get_version (version_control_string);
1123 }
1124 \f
1125 /* Tar proper.  */
1126
1127 /*-----------------------.
1128 | Main routine for tar.  |
1129 `-----------------------*/
1130
1131 int
1132 main (int argc, char *const *argv)
1133 {
1134   program_name = argv[0];
1135   setlocale (LC_ALL, "");
1136   bindtextdomain (PACKAGE, LOCALEDIR);
1137   textdomain (PACKAGE);
1138
1139   exit_status = TAREXIT_SUCCESS;
1140   filename_terminator = '\n';
1141
1142   /* Pre-allocate a few structures.  */
1143
1144   allocated_archive_names = 10;
1145   archive_name_array = (const char **)
1146     xmalloc (sizeof (const char *) * allocated_archive_names);
1147   archive_names = 0;
1148
1149   init_names ();
1150
1151   /* Decode options.  */
1152
1153   decode_options (argc, argv);
1154   name_init (argc, argv);
1155
1156   /* Main command execution.  */
1157
1158   if (volno_file_option)
1159     init_volume_number ();
1160
1161   switch (subcommand_option)
1162     {
1163     case UNKNOWN_SUBCOMMAND:
1164       USAGE_ERROR ((0, 0,
1165                     _("You must specify one of the `-Acdtrux' options")));
1166
1167     case CAT_SUBCOMMAND:
1168     case UPDATE_SUBCOMMAND:
1169     case APPEND_SUBCOMMAND:
1170       update_archive ();
1171       break;
1172
1173     case DELETE_SUBCOMMAND:
1174       delete_archive_members ();
1175       break;
1176
1177     case CREATE_SUBCOMMAND:
1178       if (totals_option)
1179         init_total_written ();
1180
1181       create_archive ();
1182       name_close ();
1183
1184       if (totals_option)
1185         print_total_written ();
1186       break;
1187
1188     case EXTRACT_SUBCOMMAND:
1189       extr_init ();
1190       read_and (extract_archive);
1191       break;
1192
1193     case LIST_SUBCOMMAND:
1194       read_and (list_archive);
1195       break;
1196
1197     case DIFF_SUBCOMMAND:
1198       diff_init ();
1199       read_and (diff_archive);
1200       break;
1201     }
1202
1203   if (volno_file_option)
1204     closeout_volume_number ();
1205
1206   /* Dispose of allocated memory, and return.  */
1207
1208   free (archive_name_array);
1209   name_term ();
1210
1211   if (exit_status == TAREXIT_FAILURE)
1212     error (0, 0, _("Error exit delayed from previous errors"));
1213   exit (exit_status);
1214 }