Debian Codegraph @

src/tar.c

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