Debian Codegraph @

src/tar.c

raw ◀ ▶
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 /* Debian specific function prototypes (-Werror=missing-prototypes) */
1257 void debian_longlink_hack_init (void);
1258 void debian_broken_numeric_owner_init (void);
1259 void pristine_tar_compat_init (void);
1260
1261 /* Debian specific environment variable used by pristine-tar to enable use of
1262 * longlinks for filenames exactly 100 bytes long. */
1263 void debian_longlink_hack_init (void) {
1264 char *s=getenv ("TAR_LONGLINK_100");
1265 if (s && strcmp(s, "1") == 0)
1266 debian_longlink_hack=1;
1267 else
1268 debian_longlink_hack=0;
1269 }
1270
1271 /* Debian specific environment variable used by pristine-tar to enable use of
1272 * user and group names even when --numeric-owner is passed. */
1273 void debian_broken_numeric_owner_init (void) {
1274 char *s=getenv ("TAR_BROKEN_NUMERIC_OWNER");
1275 if (s && strcmp(s, "1") == 0)
1276 debian_broken_numeric_owner=1;
1277 else
1278 debian_broken_numeric_owner=0;
1279 }
1280
1281 /* pristine-tar sets this environment variable to force fields in longlinks
1282 * to be zeroed as was the case in tar 1.26. */
1283 void pristine_tar_compat_init (void) {
1284 char *s=getenv ("PRISTINE_TAR_COMPAT");
1285 if (s && strcmp(s, "1") == 0)
1286 pristine_tar_compat=1;
1287 else
1288 pristine_tar_compat=0;
1289 }
1290
1291
1292 static uintmax_t
1293 parse_owner_group (char *arg, uintmax_t field_max, char const **name_option)
1294 {
1295 uintmax_t u = UINTMAX_MAX;
1296 char *end;
1297 char const *name = 0;
1298 char const *invalid_num = 0;
1299 char *colon = strchr (arg, ':');
1300
1301 if (colon)
1302 {
1303 char const *num = colon + 1;
1304 *colon = '\0';
1305 if (*arg)
1306 name = arg;
1307 if (num && (! (xstrtoumax (num, &end, 10, &u, "") == LONGINT_OK
1308 && u <= field_max)))
1309 invalid_num = num;
1310 }
1311 else
1312 {
1313 uintmax_t u1;
1314 switch ('0' <= *arg && *arg <= '9'
1315 ? xstrtoumax (arg, &end, 10, &u1, "")
1316 : LONGINT_INVALID)
1317 {
1318 default:
1319 name = arg;
1320 break;
1321
1322 case LONGINT_OK:
1323 if (u1 <= field_max)
1324 {
1325 u = u1;
1326 break;
1327 }
1328 FALLTHROUGH;
1329 case LONGINT_OVERFLOW:
1330 invalid_num = arg;
1331 break;
1332 }
1333 }
1334
1335 if (invalid_num)
1336 FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (invalid_num),
1337 _("Invalid owner or group ID")));
1338 if (name)
1339 *name_option = name;
1340 return u;
1341 }
1342
1343 #define TAR_SIZE_SUFFIXES "bBcGgkKMmPTtw"
1344
1345 static char const *const sort_mode_arg[] = {
1346 "none",
1347 "name",
1348 #if D_INO_IN_DIRENT
1349 "inode",
1350 #endif
1351 NULL
1352 };
1353
1354 static int sort_mode_flag[] = {
1355 SAVEDIR_SORT_NONE,
1356 SAVEDIR_SORT_NAME,
1357 #if D_INO_IN_DIRENT
1358 SAVEDIR_SORT_INODE
1359 #endif
1360 };
1361
1362 ARGMATCH_VERIFY (sort_mode_arg, sort_mode_flag);
1363
1364 static char const *const hole_detection_args[] =
1365 {
1366 "raw", "seek", NULL
1367 };
1368
1369 static int const hole_detection_types[] =
1370 {
1371 HOLE_DETECTION_RAW, HOLE_DETECTION_SEEK
1372 };
1373
1374 ARGMATCH_VERIFY (hole_detection_args, hole_detection_types);
1375
1376
1377 static void
1378 set_old_files_option (int code, struct option_locus *loc)
1379 {
1380 struct option_locus *prev;
1381 static char const *const code_to_opt[] = {
1382 "--overwrite-dir",
1383 "--no-overwrite-dir",
1384 "--overwrite",
1385 "--unlink-first",
1386 "--keep-old-files",
1387 "--skip-old-files",
1388 "--keep-newer-files"
1389 };
1390
1391 prev = optloc_save (OC_OLD_FILES, loc);
1392 if (prev && optloc_eq (loc, prev) && code != old_files_option)
1393 option_conflict_error (code_to_opt[code], code_to_opt[old_files_option]);
1394
1395 old_files_option = code;
1396 }
1397
1398 static error_t
1399 parse_opt (int key, char *arg, struct argp_state *state)
1400 {
1401 struct tar_args *args = state->input;
1402
1403 switch (key)
1404 {
1405 case ARGP_KEY_INIT:
1406 if (state->root_argp->children)
1407 {
1408 int i;
1409
1410 for (i = 0; state->root_argp->children[i].argp; i++)
1411 state->child_inputs[i] = state->input;
1412 }
1413 break;
1414
1415 case ARGP_KEY_ARG:
1416 /* File name or non-parsed option, because of ARGP_IN_ORDER */
1417 name_add_name (arg);
1418 break;
1419
1420 case 'A':
1421 set_subcommand_option (CAT_SUBCOMMAND);
1422 break;
1423
1424 case 'a':
1425 args->compress_autodetect = true;
1426 break;
1427
1428 case NO_AUTO_COMPRESS_OPTION:
1429 args->compress_autodetect = false;
1430 break;
1431
1432 case 'b':
1433 {
1434 uintmax_t u;
1435 if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
1436 && u == (blocking_factor = u)
1437 && 0 < blocking_factor
1438 && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE))
1439 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1440 _("Invalid blocking factor")));
1441 }
1442 break;
1443
1444 case 'B':
1445 /* Try to reblock input records. For reading 4.2BSD pipes. */
1446
1447 /* It would surely make sense to exchange -B and -R, but it seems
1448 that -B has been used for a long while in Sun tar and most
1449 BSD-derived systems. This is a consequence of the block/record
1450 terminology confusion. */
1451
1452 read_full_records_option = true;
1453 break;
1454
1455 case 'c':
1456 set_subcommand_option (CREATE_SUBCOMMAND);
1457 break;
1458
1459 case CLAMP_MTIME_OPTION:
1460 set_mtime_option = CLAMP_MTIME;
1461 break;
1462
1463 case 'd':
1464 set_subcommand_option (DIFF_SUBCOMMAND);
1465 break;
1466
1467 case 'F':
1468 /* Since -F is only useful with -M, make it implied. Run this
1469 script at the end of each tape. */
1470
1471 info_script_option = arg;
1472 multi_volume_option = true;
1473 break;
1474
1475 case 'f':
1476 if (archive_names == allocated_archive_names)
1477 archive_name_array = x2nrealloc (archive_name_array,
1478 &allocated_archive_names,
1479 sizeof (archive_name_array[0]));
1480
1481 archive_name_array[archive_names++] = arg;
1482 break;
1483
1484 case '0':
1485 case '1':
1486 case '2':
1487 case '3':
1488 case '4':
1489 case '5':
1490 case '6':
1491 case '7':
1492
1493 #ifdef DEVICE_PREFIX
1494 {
1495 int device = key - '0';
1496 int density;
1497 static char buf[sizeof DEVICE_PREFIX + 10];
1498 char *cursor;
1499
1500 if (arg[1])
1501 argp_error (state, _("Malformed density argument: %s"), quote (arg));
1502
1503 strcpy (buf, DEVICE_PREFIX);
1504 cursor = buf + strlen (buf);
1505
1506 #ifdef DENSITY_LETTER
1507
1508 sprintf (cursor, "%d%c", device, arg[0]);
1509
1510 #else /* not DENSITY_LETTER */
1511
1512 switch (arg[0])
1513 {
1514 case 'l':
1515 device += LOW_DENSITY_NUM;
1516 break;
1517
1518 case 'm':
1519 device += MID_DENSITY_NUM;
1520 break;
1521
1522 case 'h':
1523 device += HIGH_DENSITY_NUM;
1524 break;
1525
1526 default:
1527 argp_error (state, _("Unknown density: '%c'"), arg[0]);
1528 }
1529 sprintf (cursor, "%d", device);
1530
1531 #endif /* not DENSITY_LETTER */
1532
1533 if (archive_names == allocated_archive_names)
1534 archive_name_array = x2nrealloc (archive_name_array,
1535 &allocated_archive_names,
1536 sizeof (archive_name_array[0]));
1537 archive_name_array[archive_names++] = xstrdup (buf);
1538 }
1539 break;
1540
1541 #else /* not DEVICE_PREFIX */
1542
1543 argp_error (state,
1544 _("Options '-[0-7][lmh]' not supported by *this* tar"));
1545 exit (EX_USAGE);
1546
1547 #endif /* not DEVICE_PREFIX */
1548 break;
1549
1550 case FULL_TIME_OPTION:
1551 full_time_option = true;
1552 break;
1553
1554 case 'g':
1555 optloc_save (OC_LISTED_INCREMENTAL, args->loc);
1556 listed_incremental_option = arg;
1557 after_date_option = true;
1558 FALLTHROUGH;
1559 case 'G':
1560 /* We are making an incremental dump (FIXME: are we?); save
1561 directories at the beginning of the archive, and include in each
1562 directory its contents. */
1563
1564 incremental_option = true;
1565 break;
1566
1567 case 'h':
1568 /* Follow symbolic links. */
1569 dereference_option = true;
1570 break;
1571
1572 case HARD_DEREFERENCE_OPTION:
1573 hard_dereference_option = true;
1574 break;
1575
1576 case 'i':
1577 /* Ignore zero blocks (eofs). This can't be the default,
1578 because Unix tar writes two blocks of zeros, then pads out
1579 the record with garbage. */
1580
1581 ignore_zeros_option = true;
1582 break;
1583
1584 case 'j':
1585 set_use_compress_program_option (BZIP2_PROGRAM, args->loc);
1586 break;
1587
1588 case 'J':
1589 set_use_compress_program_option (XZ_PROGRAM, args->loc);
1590 break;
1591
1592 case 'k':
1593 /* Don't replace existing files. */
1594 set_old_files_option (KEEP_OLD_FILES, args->loc);
1595 break;
1596
1597 case 'K':
1598 optloc_save (OC_STARTING_FILE, args->loc);
1599 add_starting_file (arg);
1600 break;
1601
1602 case ONE_FILE_SYSTEM_OPTION:
1603 /* When dumping directories, don't dump files/subdirectories
1604 that are on other filesystems. */
1605 one_file_system_option = true;
1606 break;
1607
1608 case ONE_TOP_LEVEL_OPTION:
1609 optloc_save (OC_ONE_TOP_LEVEL, args->loc);
1610 one_top_level_option = true;
1611 one_top_level_dir = arg;
1612 break;
1613
1614 case 'l':
1615 check_links_option = 1;
1616 break;
1617
1618 case 'L':
1619 {
1620 uintmax_t u;
1621 char *p;
1622
1623 if (xstrtoumax (arg, &p, 10, &u, TAR_SIZE_SUFFIXES) != LONGINT_OK)
1624 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1625 _("Invalid tape length")));
1626 if (p > arg && !strchr (TAR_SIZE_SUFFIXES, p[-1]))
1627 tape_length_option = 1024 * (tarlong) u;
1628 else
1629 tape_length_option = (tarlong) u;
1630 multi_volume_option = true;
1631 }
1632 break;
1633
1634 case LEVEL_OPTION:
1635 {
1636 char *p;
1637 incremental_level = strtoul (arg, &p, 10);
1638 if (*p)
1639 USAGE_ERROR ((0, 0, _("Invalid incremental level value")));
1640 }
1641 break;
1642
1643 case LZIP_OPTION:
1644 set_use_compress_program_option (LZIP_PROGRAM, args->loc);
1645 break;
1646
1647 case LZMA_OPTION:
1648 set_use_compress_program_option (LZMA_PROGRAM, args->loc);
1649 break;
1650
1651 case LZOP_OPTION:
1652 set_use_compress_program_option (LZOP_PROGRAM, args->loc);
1653 break;
1654
1655 case 'm':
1656 touch_option = true;
1657 break;
1658
1659 case 'M':
1660 /* Make multivolume archive: when we can't write any more into
1661 the archive, re-open it, and continue writing. */
1662
1663 multi_volume_option = true;
1664 break;
1665
1666 case MTIME_OPTION:
1667 get_date_or_file (args, "--mtime", arg, &mtime_option);
1668 if (set_mtime_option == USE_FILE_MTIME)
1669 set_mtime_option = FORCE_MTIME;
1670 break;
1671
1672 case 'n':
1673 seek_option = 1;
1674 break;
1675
1676 case NO_SEEK_OPTION:
1677 seek_option = 0;
1678 break;
1679
1680 case 'N':
1681 after_date_option = true;
1682 FALLTHROUGH;
1683 case NEWER_MTIME_OPTION:
1684 if (TIME_OPTION_INITIALIZED (newer_mtime_option))
1685 USAGE_ERROR ((0, 0, _("More than one threshold date")));
1686 get_date_or_file (args,
1687 key == NEWER_MTIME_OPTION ? "--newer-mtime"
1688 : "--after-date", arg, &newer_mtime_option);
1689 optloc_save (OC_NEWER, args->loc);
1690 break;
1691
1692 case 'o':
1693 args->o_option = true;
1694 break;
1695
1696 case 'O':
1697 to_stdout_option = true;
1698 break;
1699
1700 case 'p':
1701 same_permissions_option = true;
1702 break;
1703
1704 case 'P':
1705 optloc_save (OC_ABSOLUTE_NAMES, args->loc);
1706 absolute_names_option = true;
1707 break;
1708
1709 case 'r':
1710 set_subcommand_option (APPEND_SUBCOMMAND);
1711 break;
1712
1713 case 'R':
1714 /* Print block numbers for debugging bad tar archives. */
1715
1716 /* It would surely make sense to exchange -B and -R, but it seems
1717 that -B has been used for a long while in Sun tar and most
1718 BSD-derived systems. This is a consequence of the block/record
1719 terminology confusion. */
1720
1721 block_number_option = true;
1722 break;
1723
1724 case 's':
1725 /* Names to extract are sorted. */
1726 optloc_save (OC_SAME_ORDER, args->loc);
1727 same_order_option = true;
1728 break;
1729
1730 case 'S':
1731 sparse_option = true;
1732 break;
1733
1734 case SKIP_OLD_FILES_OPTION:
1735 set_old_files_option (SKIP_OLD_FILES, args->loc);
1736 break;
1737
1738 case HOLE_DETECTION_OPTION:
1739 hole_detection = XARGMATCH ("--hole-detection", arg,
1740 hole_detection_args, hole_detection_types);
1741 sparse_option = true;
1742 break;
1743
1744 case SPARSE_VERSION_OPTION:
1745 sparse_option = true;
1746 {
1747 char *p;
1748 tar_sparse_major = strtoul (arg, &p, 10);
1749 if (*p)
1750 {
1751 if (*p != '.')
1752 USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1753 tar_sparse_minor = strtoul (p + 1, &p, 10);
1754 if (*p)
1755 USAGE_ERROR ((0, 0, _("Invalid sparse version value")));
1756 }
1757 }
1758 break;
1759
1760 case 't':
1761 set_subcommand_option (LIST_SUBCOMMAND);
1762 verbose_option++;
1763 break;
1764
1765 case TEST_LABEL_OPTION:
1766 set_subcommand_option (TEST_LABEL_SUBCOMMAND);
1767 break;
1768
1769 case TRANSFORM_OPTION:
1770 set_transform_expr (arg);
1771 break;
1772
1773 case 'u':
1774 set_subcommand_option (UPDATE_SUBCOMMAND);
1775 break;
1776
1777 case 'U':
1778 set_old_files_option (UNLINK_FIRST_OLD_FILES, args->loc);
1779 break;
1780
1781 case UTC_OPTION:
1782 utc_option = true;
1783 break;
1784
1785 case 'V':
1786 volume_label_option = arg;
1787 break;
1788
1789 case 'v':
1790 verbose_option++;
1791 warning_option |= WARN_VERBOSE_WARNINGS;
1792 break;
1793
1794 case 'w':
1795 interactive_option = true;
1796 break;
1797
1798 case 'W':
1799 optloc_save (OC_VERIFY, args->loc);
1800 verify_option = true;
1801 break;
1802
1803 case WARNING_OPTION:
1804 set_warning_option (arg);
1805 break;
1806
1807 case 'x':
1808 set_subcommand_option (EXTRACT_SUBCOMMAND);
1809 break;
1810
1811 case 'z':
1812 set_use_compress_program_option (GZIP_PROGRAM, args->loc);
1813 break;
1814
1815 case 'Z':
1816 set_use_compress_program_option (COMPRESS_PROGRAM, args->loc);
1817 break;
1818
1819 case ZSTD_OPTION:
1820 set_use_compress_program_option (ZSTD_PROGRAM, args->loc);
1821 break;
1822
1823 case ATIME_PRESERVE_OPTION:
1824 atime_preserve_option =
1825 (arg
1826 ? XARGMATCH ("--atime-preserve", arg,
1827 atime_preserve_args, atime_preserve_types)
1828 : replace_atime_preserve);
1829 if (! O_NOATIME && atime_preserve_option == system_atime_preserve)
1830 FATAL_ERROR ((0, 0,
1831 _("--atime-preserve='system' is not supported"
1832 " on this platform")));
1833 break;
1834
1835 case CHECK_DEVICE_OPTION:
1836 check_device_option = true;
1837 break;
1838
1839 case NO_CHECK_DEVICE_OPTION:
1840 check_device_option = false;
1841 break;
1842
1843 case CHECKPOINT_OPTION:
1844 if (arg)
1845 {
1846 char *p;
1847
1848 if (*arg == '.')
1849 {
1850 checkpoint_compile_action (".");
1851 arg++;
1852 }
1853 checkpoint_option = strtoul (arg, &p, 0);
1854 if (*p)
1855 FATAL_ERROR ((0, 0,
1856 _("--checkpoint value is not an integer")));
1857 }
1858 else
1859 checkpoint_option = DEFAULT_CHECKPOINT;
1860 break;
1861
1862 case CHECKPOINT_ACTION_OPTION:
1863 checkpoint_compile_action (arg);
1864 break;
1865
1866 case BACKUP_OPTION:
1867 backup_option = true;
1868 if (arg)
1869 args->version_control_string = arg;
1870 break;
1871
1872 case DELAY_DIRECTORY_RESTORE_OPTION:
1873 delay_directory_restore_option = true;
1874 break;
1875
1876 case NO_DELAY_DIRECTORY_RESTORE_OPTION:
1877 delay_directory_restore_option = false;
1878 break;
1879
1880 case DELETE_OPTION:
1881 set_subcommand_option (DELETE_SUBCOMMAND);
1882 break;
1883
1884 case FORCE_LOCAL_OPTION:
1885 force_local_option = true;
1886 break;
1887
1888 case 'H':
1889 set_archive_format (arg);
1890 break;
1891
1892 case INDEX_FILE_OPTION:
1893 index_file_name = arg;
1894 break;
1895
1896 case IGNORE_COMMAND_ERROR_OPTION:
1897 ignore_command_error_option = true;
1898 break;
1899
1900 case IGNORE_FAILED_READ_OPTION:
1901 ignore_failed_read_option = true;
1902 break;
1903
1904 case KEEP_DIRECTORY_SYMLINK_OPTION:
1905 keep_directory_symlink_option = true;
1906 break;
1907
1908 case KEEP_NEWER_FILES_OPTION:
1909 set_old_files_option (KEEP_NEWER_FILES, args->loc);
1910 break;
1911
1912 case GROUP_OPTION:
1913 {
1914 uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (gid_t),
1915 &group_name_option);
1916 if (u == UINTMAX_MAX)
1917 {
1918 group_option = -1;
1919 if (group_name_option)
1920 gname_to_gid (group_name_option, &group_option);
1921 }
1922 else
1923 group_option = u;
1924 }
1925 break;
1926
1927 case GROUP_MAP_OPTION:
1928 group_map_read (arg);
1929 break;
1930
1931 case MODE_OPTION:
1932 mode_option = mode_compile (arg);
1933 if (!mode_option)
1934 FATAL_ERROR ((0, 0, _("Invalid mode given on option")));
1935 initial_umask = umask (0);
1936 umask (initial_umask);
1937 break;
1938
1939 case NO_IGNORE_COMMAND_ERROR_OPTION:
1940 ignore_command_error_option = false;
1941 break;
1942
1943 case NO_OVERWRITE_DIR_OPTION:
1944 set_old_files_option (NO_OVERWRITE_DIR_OLD_FILES, args->loc);
1945 break;
1946
1947 case NO_QUOTE_CHARS_OPTION:
1948 for (;*arg; arg++)
1949 set_char_quoting (NULL, *arg, 0);
1950 break;
1951
1952 case NUMERIC_OWNER_OPTION:
1953 numeric_owner_option = true;
1954 break;
1955
1956 case OCCURRENCE_OPTION:
1957 optloc_save (OC_OCCURRENCE, args->loc);
1958 if (!arg)
1959 occurrence_option = 1;
1960 else
1961 {
1962 uintmax_t u;
1963 if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK)
1964 occurrence_option = u;
1965 else
1966 FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
1967 _("Invalid number")));
1968 }
1969 break;
1970
1971 case OLD_ARCHIVE_OPTION:
1972 set_archive_format ("v7");
1973 break;
1974
1975 case OVERWRITE_DIR_OPTION:
1976 set_old_files_option (DEFAULT_OLD_FILES, args->loc);
1977 break;
1978
1979 case OVERWRITE_OPTION:
1980 set_old_files_option (OVERWRITE_OLD_FILES, args->loc);
1981 break;
1982
1983 case OWNER_OPTION:
1984 {
1985 uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (uid_t),
1986 &owner_name_option);
1987 if (u == UINTMAX_MAX)
1988 {
1989 owner_option = -1;
1990 if (owner_name_option)
1991 uname_to_uid (owner_name_option, &owner_option);
1992 }
1993 else
1994 owner_option = u;
1995 }
1996 break;
1997
1998 case OWNER_MAP_OPTION:
1999 owner_map_read (arg);
2000 break;
2001
2002 case QUOTE_CHARS_OPTION:
2003 for (;*arg; arg++)
2004 set_char_quoting (NULL, *arg, 1);
2005 break;
2006
2007 case QUOTING_STYLE_OPTION:
2008 tar_set_quoting_style (arg);
2009 break;
2010
2011 case PAX_OPTION:
2012 {
2013 char *tmp = expand_pax_option (args, arg);
2014 args->pax_option = true;
2015 xheader_set_option (tmp);
2016 free (tmp);
2017 }
2018 break;
2019
2020 case POSIX_OPTION:
2021 set_archive_format ("posix");
2022 break;
2023
2024 case RECORD_SIZE_OPTION:
2025 {
2026 uintmax_t u;
2027
2028 if (! (xstrtoumax (arg, NULL, 10, &u, TAR_SIZE_SUFFIXES) == LONGINT_OK
2029 && u == (size_t) u))
2030 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
2031 _("Invalid record size")));
2032 record_size = u;
2033 if (record_size % BLOCKSIZE != 0)
2034 USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."),
2035 BLOCKSIZE));
2036 blocking_factor = record_size / BLOCKSIZE;
2037 }
2038 break;
2039
2040 case RECURSIVE_UNLINK_OPTION:
2041 recursive_unlink_option = true;
2042 break;
2043
2044 case REMOVE_FILES_OPTION:
2045 remove_files_option = true;
2046 break;
2047
2048 case RESTRICT_OPTION:
2049 restrict_option = true;
2050 break;
2051
2052 case RMT_COMMAND_OPTION:
2053 rmt_command = arg;
2054 break;
2055
2056 case RSH_COMMAND_OPTION:
2057 rsh_command_option = arg;
2058 break;
2059
2060 case SHOW_DEFAULTS_OPTION:
2061 {
2062 char *s = format_default_settings ();
2063 printf ("%s\n", s);
2064 close_stdout ();
2065 free (s);
2066 exit (0);
2067 }
2068
2069 case SHOW_SNAPSHOT_FIELD_RANGES_OPTION:
2070 show_snapshot_field_ranges ();
2071 close_stdout ();
2072 exit (0);
2073
2074 case STRIP_COMPONENTS_OPTION:
2075 {
2076 uintmax_t u;
2077 if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK
2078 && u == (size_t) u))
2079 USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg),
2080 _("Invalid number of elements")));
2081 strip_name_components = u;
2082 }
2083 break;
2084
2085 case SHOW_OMITTED_DIRS_OPTION:
2086 show_omitted_dirs_option = true;
2087 break;
2088
2089 case SHOW_TRANSFORMED_NAMES_OPTION:
2090 show_transformed_names_option = true;
2091 break;
2092
2093 case SORT_OPTION:
2094 savedir_sort_order = XARGMATCH ("--sort", arg,
2095 sort_mode_arg, sort_mode_flag);
2096 break;
2097
2098 case SUFFIX_OPTION:
2099 backup_option = true;
2100 args->backup_suffix_string = arg;
2101 break;
2102
2103 case TO_COMMAND_OPTION:
2104 if (to_command_option)
2105 USAGE_ERROR ((0, 0, _("Only one --to-command option allowed")));
2106 to_command_option = arg;
2107 break;
2108
2109 case TOTALS_OPTION:
2110 if (arg)
2111 set_stat_signal (arg);
2112 else
2113 totals_option = true;
2114 break;
2115
2116 case 'I':
2117 set_use_compress_program_option (arg, args->loc);
2118 break;
2119
2120 case VOLNO_FILE_OPTION:
2121 volno_file_option = arg;
2122 break;
2123
2124 case NO_SAME_OWNER_OPTION:
2125 same_owner_option = -1;
2126 break;
2127
2128 case NO_SAME_PERMISSIONS_OPTION:
2129 same_permissions_option = -1;
2130 break;
2131
2132 case ACLS_OPTION:
2133 set_archive_format ("posix");
2134 acls_option = 1;
2135 break;
2136
2137 case NO_ACLS_OPTION:
2138 acls_option = -1;
2139 break;
2140
2141 case SELINUX_CONTEXT_OPTION:
2142 set_archive_format ("posix");
2143 selinux_context_option = 1;
2144 break;
2145
2146 case NO_SELINUX_CONTEXT_OPTION:
2147 selinux_context_option = -1;
2148 break;
2149
2150 case XATTR_OPTION:
2151 set_xattr_option (1);
2152 break;
2153
2154 case NO_XATTR_OPTION:
2155 set_xattr_option (-1);
2156 break;
2157
2158 case XATTR_INCLUDE:
2159 case XATTR_EXCLUDE:
2160 set_xattr_option (1);
2161 xattrs_mask_add (arg, (key == XATTR_INCLUDE));
2162 break;
2163
2164 case SAME_OWNER_OPTION:
2165 same_owner_option = 1;
2166 break;
2167
2168 case ARGP_KEY_ERROR:
2169 if (args->loc->source == OPTS_FILE)
2170 error (0, 0, _("%s:%lu: location of the error"), args->loc->name,
2171 (unsigned long) args->loc->line);
2172 else if (args->loc->source == OPTS_ENVIRON)
2173 error (0, 0, _("error parsing %s"), args->loc->name);
2174 exit (EX_USAGE);
2175
2176 default:
2177 return ARGP_ERR_UNKNOWN;
2178 }
2179 return 0;
2180 }
2181
2182 extern struct argp names_argp;
2183 static struct argp_child argp_children[] = {
2184 { &names_argp, 0, NULL, GRID_FILE_NAME },
2185 { NULL }
2186 };
2187
2188 static struct argp argp = {
2189 options,
2190 parse_opt,
2191 N_("[FILE]..."),
2192 doc,
2193 argp_children,
2194 tar_help_filter,
2195 NULL
2196 };
2197
2198 void
2199 usage (int status)
2200 {
2201 argp_help (&argp, stderr, ARGP_HELP_SEE, (char*) program_name);
2202 close_stdout ();
2203 exit (status);
2204 }
2205
2206 /* Parse the options for tar. */
2207
2208 static struct argp_option const *
2209 find_argp_option_key (struct argp_option const *o, int key)
2210 {
2211 for (;
2212 !(o->name == NULL
2213 && o->key == 0
2214 && o->arg == 0
2215 && o->flags == 0
2216 && o->doc == NULL); o++)
2217 if (o->key == key)
2218 return o;
2219 return NULL;
2220 }
2221
2222 static struct argp_option const *
2223 find_argp_option (struct argp *ap, int key)
2224 {
2225 struct argp_option const *p = NULL;
2226 struct argp_child const *child;
2227
2228 p = find_argp_option_key (ap->options, key);
2229 if (!p && ap->children)
2230 {
2231 for (child = ap->children; child->argp; child++)
2232 {
2233 p = find_argp_option_key (child->argp->options, key);
2234 if (p)
2235 break;
2236 }
2237 }
2238 return p;
2239 }
2240
2241 static const char *tar_authors[] = {
2242 "John Gilmore",
2243 "Jay Fenlason",
2244 NULL
2245 };
2246
2247 /* Subcommand classes */
2248 #define SUBCL_READ 0x01 /* subcommand reads from the archive */
2249 #define SUBCL_WRITE 0x02 /* subcommand writes to the archive */
2250 #define SUBCL_UPDATE 0x04 /* subcommand updates existing archive */
2251 #define SUBCL_TEST 0x08 /* subcommand tests archive header or meta-info */
2252 #define SUBCL_OCCUR 0x10 /* subcommand allows the use of the occurrence
2253 option */
2254
2255 static int subcommand_class[] = {
2256 /* UNKNOWN_SUBCOMMAND */ 0,
2257 /* APPEND_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE,
2258 /* CAT_SUBCOMMAND */ SUBCL_WRITE,
2259 /* CREATE_SUBCOMMAND */ SUBCL_WRITE,
2260 /* DELETE_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE|SUBCL_OCCUR,
2261 /* DIFF_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR,
2262 /* EXTRACT_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR,
2263 /* LIST_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR,
2264 /* UPDATE_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE,
2265 /* TEST_LABEL_SUBCOMMAND */ SUBCL_TEST
2266 };
2267
2268 /* Return t if the subcommand_option is in class(es) f */
2269 #define IS_SUBCOMMAND_CLASS(f) (subcommand_class[subcommand_option] & (f))
2270
2271 void
2272 more_options (int argc, char **argv, struct option_locus *loc)
2273 {
2274 struct tar_args args = TAR_ARGS_INITIALIZER (loc);
2275 argp_parse (&names_argp, argc, argv, ARGP_IN_ORDER|ARGP_NO_EXIT|ARGP_NO_ERRS,
2276 NULL, &args);
2277 }
2278
2279 static void
2280 parse_default_options (struct tar_args *args)
2281 {
2282 char *opts = getenv ("TAR_OPTIONS");
2283 struct wordsplit ws;
2284 struct option_locus loc = { OPTS_ENVIRON, "TAR_OPTIONS", 0, 0 };
2285 struct option_locus *save_loc_ptr;
2286
2287 if (!opts)
2288 return;
2289
2290 ws.ws_offs = 1;
2291 if (wordsplit (opts, &ws, WRDSF_DEFFLAGS|WRDSF_DOOFFS))
2292 FATAL_ERROR ((0, 0, _("cannot split TAR_OPTIONS: %s"),
2293 wordsplit_strerror (&ws)));
2294 if (ws.ws_wordc)
2295 {
2296 int idx;
2297 ws.ws_wordv[0] = (char*) program_name;
2298 save_loc_ptr = args->loc;
2299 args->loc = &loc;
2300 if (argp_parse (&argp,
2301 ws.ws_offs + ws.ws_wordc,
2302 ws.ws_wordv,
2303 ARGP_IN_ORDER|ARGP_NO_EXIT, &idx, args))
2304 abort (); /* shouldn't happen */
2305 args->loc = save_loc_ptr;
2306 if (name_more_files ())
2307 USAGE_ERROR ((0, 0, _("non-option arguments in %s"), loc.name));
2308 /* Don't free consumed words */
2309 ws.ws_wordc = 0;
2310 }
2311 wordsplit_free (&ws);
2312 }
2313
2314 static void
2315 decode_options (int argc, char **argv)
2316 {
2317 int idx;
2318 struct option_locus loc = { OPTS_COMMAND_LINE, 0, 0, 0 };
2319 struct tar_args args = TAR_ARGS_INITIALIZER (&loc);
2320
2321 argp_version_setup ("tar", tar_authors);
2322
2323 /* Set some default option values. */
2324 args.backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
2325
2326 posixly_correct = getenv ("POSIXLY_CORRECT") != NULL;
2327
2328 subcommand_option = UNKNOWN_SUBCOMMAND;
2329 archive_format = DEFAULT_FORMAT;
2330 blocking_factor = DEFAULT_BLOCKING;
2331 record_size = DEFAULT_BLOCKING * BLOCKSIZE;
2332 excluded = new_exclude ();
2333 hole_detection = HOLE_DETECTION_DEFAULT;
2334
2335 newer_mtime_option.tv_sec = TYPE_MINIMUM (time_t);
2336 newer_mtime_option.tv_nsec = -1;
2337 mtime_option.tv_sec = TYPE_MINIMUM (time_t);
2338 mtime_option.tv_nsec = -1;
2339 recursion_option = FNM_LEADING_DIR;
2340 unquote_option = true;
2341 tar_sparse_major = 1;
2342 tar_sparse_minor = 0;
2343
2344 savedir_sort_order = SAVEDIR_SORT_NONE;
2345
2346 owner_option = -1; owner_name_option = NULL;
2347 group_option = -1; group_name_option = NULL;
2348
2349 check_device_option = true;
2350
2351 incremental_level = -1;
2352
2353 seek_option = -1;
2354
2355 /* Convert old-style tar call by exploding option element and rearranging
2356 options accordingly. */
2357
2358 if (argc > 1 && argv[1][0] != '-')
2359 {
2360 int new_argc; /* argc value for rearranged arguments */
2361 char **new_argv; /* argv value for rearranged arguments */
2362 char *const *in; /* cursor into original argv */
2363 char **out; /* cursor into rearranged argv */
2364 const char *letter; /* cursor into old option letters */
2365 char buffer[3]; /* constructed option buffer */
2366
2367 /* Initialize a constructed option. */
2368
2369 buffer[0] = '-';
2370 buffer[2] = '\0';
2371
2372 /* Allocate a new argument array, and copy program name in it. */
2373
2374 new_argc = argc - 1 + strlen (argv[1]);
2375 new_argv = xmalloc ((new_argc + 1) * sizeof (char *));
2376 in = argv;
2377 out = new_argv;
2378 *out++ = *in++;
2379
2380 /* Copy each old letter option as a separate option, and have the
2381 corresponding argument moved next to it. */
2382
2383 for (letter = *in++; *letter; letter++)
2384 {
2385 struct argp_option const *opt;
2386
2387 buffer[1] = *letter;
2388 *out++ = xstrdup (buffer);
2389 opt = find_argp_option (&argp, *letter);
2390 if (opt && opt->arg)
2391 {
2392 if (in < argv + argc)
2393 *out++ = *in++;
2394 else
2395 USAGE_ERROR ((0, 0, _("Old option '%c' requires an argument."),
2396 *letter));
2397 }
2398 }
2399
2400 /* Copy all remaining options. */
2401
2402 while (in < argv + argc)
2403 *out++ = *in++;
2404 *out = 0;
2405
2406 /* Replace the old option list by the new one. */
2407
2408 argc = new_argc;
2409 argv = new_argv;
2410 }
2411
2412 /* Parse all options and non-options as they appear. */
2413 parse_default_options (&args);
2414
2415 if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, &args))
2416 exit (TAREXIT_FAILURE);
2417
2418 /* Special handling for 'o' option:
2419
2420 GNU tar used to say "output old format".
2421 UNIX98 tar says don't chown files after extracting (we use
2422 "--no-same-owner" for this).
2423
2424 The old GNU tar semantics is retained when used with --create
2425 option, otherwise UNIX98 semantics is assumed */
2426
2427 if (args.o_option)
2428 {
2429 if (subcommand_option == CREATE_SUBCOMMAND)
2430 {
2431 /* GNU Tar <= 1.13 compatibility */
2432 set_archive_format ("v7");
2433 }
2434 else
2435 {
2436 /* UNIX98 compatibility */
2437 same_owner_option = -1;
2438 }
2439 }
2440
2441 /* Handle operands after any "--" argument. */
2442 for (; idx < argc; idx++)
2443 name_add_name (argv[idx]);
2444
2445 /* Derive option values and check option consistency. */
2446
2447 if (archive_format == DEFAULT_FORMAT)
2448 {
2449 if (args.pax_option)
2450 archive_format = POSIX_FORMAT;
2451 else
2452 archive_format = DEFAULT_ARCHIVE_FORMAT;
2453 }
2454
2455 if ((volume_label_option && subcommand_option == CREATE_SUBCOMMAND)
2456 || incremental_option
2457 || multi_volume_option
2458 || sparse_option)
2459 assert_format (FORMAT_MASK (OLDGNU_FORMAT)
2460 | FORMAT_MASK (GNU_FORMAT)
2461 | FORMAT_MASK (POSIX_FORMAT));
2462
2463 if (occurrence_option)
2464 {
2465 if (!name_more_files ())
2466 USAGE_ERROR ((0, 0,
2467 _("--occurrence is meaningless without a file list")));
2468 if (!IS_SUBCOMMAND_CLASS (SUBCL_OCCUR))
2469 {
2470 if (option_set_in_cl (OC_OCCURRENCE))
2471 option_conflict_error ("--occurrence",
2472 subcommand_string (subcommand_option));
2473 else
2474 occurrence_option = 0;
2475 }
2476 }
2477
2478 if (archive_names == 0)
2479 {
2480 /* If no archive file name given, try TAPE from the environment, or
2481 else, DEFAULT_ARCHIVE from the configuration process. */
2482
2483 archive_names = 1;
2484 archive_name_array[0] = getenv ("TAPE");
2485 if (! archive_name_array[0])
2486 archive_name_array[0] = DEFAULT_ARCHIVE;
2487 }
2488
2489 /* Allow multiple archives only with '-M'. */
2490
2491 if (archive_names > 1 && !multi_volume_option)
2492 USAGE_ERROR ((0, 0,
2493 _("Multiple archive files require '-M' option")));
2494
2495 if (listed_incremental_option
2496 && TIME_OPTION_INITIALIZED (newer_mtime_option))
2497 {
2498 struct option_locus *listed_loc = optloc_lookup (OC_LISTED_INCREMENTAL);
2499 struct option_locus *newer_loc = optloc_lookup (OC_NEWER);
2500 if (optloc_eq (listed_loc, newer_loc))
2501 option_conflict_error ("--listed-incremental", "--newer");
2502 else if (listed_loc->source == OPTS_COMMAND_LINE)
2503 listed_incremental_option = NULL;
2504 else
2505 memset (&newer_mtime_option, 0, sizeof (newer_mtime_option));
2506 }
2507
2508 if (incremental_level != -1 && !listed_incremental_option)
2509 WARN ((0, 0,
2510 _("--level is meaningless without --listed-incremental")));
2511
2512 if (volume_label_option)
2513 {
2514 if (archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
2515 {
2516 size_t volume_label_max_len =
2517 (sizeof current_header->header.name
2518 - 1 /* for trailing '\0' */
2519 - (multi_volume_option
2520 ? (sizeof " Volume "
2521 - 1 /* for null at end of " Volume " */
2522 + INT_STRLEN_BOUND (int) /* for volume number */
2523 - 1 /* for sign, as 0 <= volno */)
2524 : 0));
2525 if (volume_label_max_len < strlen (volume_label_option))
2526 USAGE_ERROR ((0, 0,
2527 ngettext ("%s: Volume label is too long (limit is %lu byte)",
2528 "%s: Volume label is too long (limit is %lu bytes)",
2529 volume_label_max_len),
2530 quotearg_colon (volume_label_option),
2531 (unsigned long) volume_label_max_len));
2532 }
2533 /* else FIXME
2534 Label length in PAX format is limited by the volume size. */
2535 }
2536
2537 if (verify_option)
2538 {
2539 if (multi_volume_option)
2540 USAGE_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
2541 if (use_compress_program_option)
2542 USAGE_ERROR ((0, 0, _("Cannot verify compressed archives")));
2543 if (!IS_SUBCOMMAND_CLASS (SUBCL_WRITE))
2544 {
2545 if (option_set_in_cl (OC_VERIFY))
2546 option_conflict_error ("--verify",
2547 subcommand_string (subcommand_option));
2548 else
2549 verify_option = false;
2550 }
2551 }
2552
2553 if (use_compress_program_option)
2554 {
2555 if (multi_volume_option)
2556 USAGE_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
2557 if (IS_SUBCOMMAND_CLASS (SUBCL_UPDATE))
2558 USAGE_ERROR ((0, 0, _("Cannot update compressed archives")));
2559 if (subcommand_option == CAT_SUBCOMMAND)
2560 USAGE_ERROR ((0, 0, _("Cannot concatenate compressed archives")));
2561 }
2562
2563 if (set_mtime_option == CLAMP_MTIME)
2564 {
2565 if (!TIME_OPTION_INITIALIZED (mtime_option))
2566 USAGE_ERROR ((0, 0,
2567 _("--clamp-mtime needs a date specified using --mtime")));
2568 }
2569
2570 /* It is no harm to use --pax-option on non-pax archives in archive
2571 reading mode. It may even be useful, since it allows to override
2572 file attributes from tar headers. Therefore I allow such usage.
2573 --gray */
2574 if (args.pax_option
2575 && archive_format != POSIX_FORMAT
2576 && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2577 USAGE_ERROR ((0, 0, _("--pax-option can be used only on POSIX archives")));
2578
2579 /* star creates non-POSIX typed archives with xattr support, so allow the
2580 extra headers when reading */
2581 if ((acls_option > 0)
2582 && archive_format != POSIX_FORMAT
2583 && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2584 USAGE_ERROR ((0, 0, _("--acls can be used only on POSIX archives")));
2585
2586 if ((selinux_context_option > 0)
2587 && archive_format != POSIX_FORMAT
2588 && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2589 USAGE_ERROR ((0, 0, _("--selinux can be used only on POSIX archives")));
2590
2591 if ((xattrs_option > 0)
2592 && archive_format != POSIX_FORMAT
2593 && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2594 USAGE_ERROR ((0, 0, _("--xattrs can be used only on POSIX archives")));
2595
2596 if (starting_file_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2597 {
2598 if (option_set_in_cl (OC_STARTING_FILE))
2599 option_conflict_error ("--starting-file",
2600 subcommand_string (subcommand_option));
2601 else
2602 starting_file_option = false;
2603 }
2604
2605 if (same_order_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ))
2606 {
2607 if (option_set_in_cl (OC_SAME_ORDER))
2608 option_conflict_error ("--same-order",
2609 subcommand_string (subcommand_option));
2610 else
2611 same_order_option = false;
2612 }
2613
2614 if (one_top_level_option)
2615 {
2616 char *base;
2617
2618 if (absolute_names_option)
2619 {
2620 struct option_locus *one_top_level_loc =
2621 optloc_lookup (OC_ONE_TOP_LEVEL);
2622 struct option_locus *absolute_names_loc =
2623 optloc_lookup (OC_ABSOLUTE_NAMES);
2624
2625 if (optloc_eq (one_top_level_loc, absolute_names_loc))
2626 option_conflict_error ("--one-top-level", "--absolute-names");
2627 else if (one_top_level_loc->source == OPTS_COMMAND_LINE)
2628 absolute_names_option = false;
2629 else
2630 one_top_level_option = false;
2631 }
2632
2633 if (one_top_level_option && !one_top_level_dir)
2634 {
2635 /* If the user wants to guarantee that everything is under one
2636 directory, determine its name now and let it be created later. */
2637 base = base_name (archive_name_array[0]);
2638 one_top_level_dir = strip_compression_suffix (base);
2639 free (base);
2640
2641 if (!one_top_level_dir)
2642 USAGE_ERROR ((0, 0,
2643 _("Cannot deduce top-level directory name; "
2644 "please set it explicitly with --one-top-level=DIR")));
2645 }
2646 }
2647
2648 /* If ready to unlink hierarchies, so we are for simpler files. */
2649 if (recursive_unlink_option)
2650 old_files_option = UNLINK_FIRST_OLD_FILES;
2651
2652 /* Flags for accessing files to be read from or copied into. POSIX says
2653 O_NONBLOCK has unspecified effect on most types of files, but in
2654 practice it never harms and sometimes helps. */
2655 {
2656 int base_open_flags =
2657 (O_BINARY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK
2658 | (dereference_option ? 0 : O_NOFOLLOW)
2659 | (atime_preserve_option == system_atime_preserve ? O_NOATIME : 0));
2660 open_read_flags = O_RDONLY | base_open_flags;
2661 open_searchdir_flags = O_SEARCH | O_DIRECTORY | base_open_flags;
2662 }
2663 fstatat_flags = dereference_option ? 0 : AT_SYMLINK_NOFOLLOW;
2664
2665 if (subcommand_option == TEST_LABEL_SUBCOMMAND)
2666 {
2667 /* --test-label is silent if the user has specified the label name to
2668 compare against. */
2669 if (!name_more_files ())
2670 verbose_option++;
2671 }
2672 else if (utc_option)
2673 verbose_option = 2;
2674
2675 if (tape_length_option && tape_length_option < record_size)
2676 USAGE_ERROR ((0, 0, _("Volume length cannot be less than record size")));
2677
2678 if (same_order_option && listed_incremental_option)
2679 {
2680 struct option_locus *preserve_order_loc = optloc_lookup (OC_SAME_ORDER);
2681 struct option_locus *listed_incremental_loc =
2682 optloc_lookup (OC_LISTED_INCREMENTAL);
2683
2684 if (optloc_eq (preserve_order_loc, listed_incremental_loc))
2685 option_conflict_error ("--preserve-order", "--listed-incremental");
2686 else if (preserve_order_loc->source == OPTS_COMMAND_LINE)
2687 listed_incremental_option = NULL;
2688 else
2689 same_order_option = false;
2690 }
2691
2692 /* Forbid using -c with no input files whatsoever. Check that '-f -',
2693 explicit or implied, is used correctly. */
2694
2695 switch (subcommand_option)
2696 {
2697 case CREATE_SUBCOMMAND:
2698 if (!name_more_files ())
2699 USAGE_ERROR ((0, 0,
2700 _("Cowardly refusing to create an empty archive")));
2701 if (args.compress_autodetect && archive_names
2702 && strcmp (archive_name_array[0], "-"))
2703 set_compression_program_by_suffix (archive_name_array[0],
2704 use_compress_program_option);
2705 break;
2706
2707 case EXTRACT_SUBCOMMAND:
2708 case LIST_SUBCOMMAND:
2709 case DIFF_SUBCOMMAND:
2710 case TEST_LABEL_SUBCOMMAND:
2711 for (archive_name_cursor = archive_name_array;
2712 archive_name_cursor < archive_name_array + archive_names;
2713 archive_name_cursor++)
2714 if (!strcmp (*archive_name_cursor, "-"))
2715 request_stdin ("-f");
2716 break;
2717
2718 case CAT_SUBCOMMAND:
2719 case UPDATE_SUBCOMMAND:
2720 case APPEND_SUBCOMMAND:
2721 for (archive_name_cursor = archive_name_array;
2722 archive_name_cursor < archive_name_array + archive_names;
2723 archive_name_cursor++)
2724 if (!strcmp (*archive_name_cursor, "-"))
2725 USAGE_ERROR ((0, 0,
2726 _("Options '-Aru' are incompatible with '-f -'")));
2727
2728 default:
2729 break;
2730 }
2731
2732 /* Initialize stdlis */
2733 if (index_file_name)
2734 {
2735 stdlis = fopen (index_file_name, "w");
2736 if (! stdlis)
2737 open_fatal (index_file_name);
2738 }
2739 else
2740 stdlis = to_stdout_option ? stderr : stdout;
2741
2742 archive_name_cursor = archive_name_array;
2743
2744 /* Prepare for generating backup names. */
2745
2746 if (args.backup_suffix_string)
2747 simple_backup_suffix = xstrdup (args.backup_suffix_string);
2748
2749 if (backup_option)
2750 {
2751 backup_type = xget_version ("--backup", args.version_control_string);
2752 /* No backup is needed either if explicitly disabled or if
2753 the extracted files are not being written to disk. */
2754 if (backup_type == no_backups || EXTRACT_OVER_PIPE)
2755 backup_option = false;
2756 }
2757
2758 checkpoint_finish_compile ();
2759
2760 report_textual_dates (&args);
2761 }
2762
2763 #ifdef ENABLE_ERROR_PRINT_PROGNAME
2764 /* The error() function from glibc correctly prefixes each message it
2765 prints with program_name as set by set_program_name. However, its
2766 replacement from gnulib, which is linked in on systems where this
2767 function is not available, prints the name returned by getprogname()
2768 instead. Due to this messages output by tar subprocess (which sets its
2769 program name to 'tar (child)') become indiscernible from those printed
2770 by the main process. In particular, this breaks the remfiles01.at and
2771 remfiles02.at test cases.
2772
2773 To avoid this, on such systems the following helper function is used
2774 to print proper program name. Its address is assigned to the
2775 error_print_progname variable, which error() then uses instead of
2776 printing getprogname() result.
2777 */
2778 static void
2779 tar_print_progname (void)
2780 {
2781 fprintf (stderr, "%s: ", program_name);
2782 }
2783 #endif
2784
2785 /* Tar proper. */
2786
2787 /* Main routine for tar. */
2788 int
2789 main (int argc, char **argv)
2790 {
2791 set_start_time ();
2792 set_program_name (argv[0]);
2793 #ifdef ENABLE_ERROR_PRINT_PROGNAME
2794 error_print_progname = tar_print_progname;
2795 #endif
2796 setlocale (LC_ALL, "");
2797 bindtextdomain (PACKAGE, LOCALEDIR);
2798 textdomain (PACKAGE);
2799
2800 exit_failure = TAREXIT_FAILURE;
2801 exit_status = TAREXIT_SUCCESS;
2802 error_hook = checkpoint_flush_actions;
2803
2804 set_quoting_style (0, DEFAULT_QUOTING_STYLE);
2805
•2806 debian_longlink_hack_init ();
2807 debian_broken_numeric_owner_init ();
2808 pristine_tar_compat_init ();
2809
2810 close_stdout_set_file_name (_("stdout"));
2811 /* Make sure we have first three descriptors available */
2812 if (stdopen ())
2813 FATAL_ERROR ((0, 0, "%s",
2814 _("failed to assert availability of the standard file descriptors")));
2815
2816 /* Pre-allocate a few structures. */
2817
2818 allocated_archive_names = 10;
2819 archive_name_array =
2820 xmalloc (sizeof (const char *) * allocated_archive_names);
2821 archive_names = 0;
2822
2823 /* System V fork+wait does not work if SIGCHLD is ignored. */
2824 signal (SIGCHLD, SIG_DFL);
2825
2826 /* Try to disable the ability to unlink a directory. */
2827 priv_set_remove_linkdir ();
2828
2829 /* Decode options. */
2830
2831 decode_options (argc, argv);
2832
2833 name_init ();
2834
2835 /* Main command execution. */
2836
2837 if (volno_file_option)
2838 init_volume_number ();
2839
2840 switch (subcommand_option)
2841 {
2842 case UNKNOWN_SUBCOMMAND:
2843 USAGE_ERROR ((0, 0,
2844 _("You must specify one of the '-Acdtrux', '--delete' or '--test-label' options")));
2845
2846 case CAT_SUBCOMMAND:
2847 case UPDATE_SUBCOMMAND:
2848 case APPEND_SUBCOMMAND:
2849 update_archive ();
2850 break;
2851
2852 case DELETE_SUBCOMMAND:
2853 delete_archive_members ();
2854 break;
2855
2856 case CREATE_SUBCOMMAND:
2857 create_archive ();
2858 break;
2859
2860 case EXTRACT_SUBCOMMAND:
2861 extr_init ();
2862 read_and (extract_archive);
2863
2864 /* FIXME: should extract_finish () even if an ordinary signal is
2865 received. */
2866 extract_finish ();
2867
2868 break;
2869
2870 case LIST_SUBCOMMAND:
2871 read_and (list_archive);
2872 break;
2873
2874 case DIFF_SUBCOMMAND:
2875 diff_init ();
2876 read_and (diff_archive);
2877 break;
2878
2879 case TEST_LABEL_SUBCOMMAND:
2880 test_archive_label ();
2881 }
2882
2883 checkpoint_finish ();
2884
2885 if (totals_option)
2886 print_total_stats ();
2887
2888 if (check_links_option)
2889 check_links ();
2890
2891 if (volno_file_option)
2892 closeout_volume_number ();
2893
2894 /* There is little point to freeing, as we are about to exit,
2895 and freeing is more likely to cause than cure trouble. */
2896 if (false)
2897 {
2898 free (archive_name_array);
2899 xattrs_clear_setup ();
2900 name_term ();
2901 }
2902
2903 if (exit_status == TAREXIT_FAILURE)
2904 error (0, 0, _("Exiting with failure status due to previous errors"));
2905
2906 if (stdlis == stdout)
2907 close_stdout ();
2908 else if (ferror (stderr) || fclose (stderr) != 0)
2909 set_exit_status (TAREXIT_FAILURE);
2910
2911 return exit_status;
2912 }
2913
2914 void
2915 tar_stat_init (struct tar_stat_info *st)
2916 {
2917 memset (st, 0, sizeof (*st));
2918 }
2919
2920 /* Close the stream or file descriptor associated with ST, and remove
2921 all traces of it from ST. Return true if successful, false (with a
2922 diagnostic) otherwise. */
2923 bool
2924 tar_stat_close (struct tar_stat_info *st)
2925 {
2926 int status = (st->dirstream ? closedir (st->dirstream)
2927 : 0 < st->fd ? close (st->fd)
2928 : 0);
2929 st->dirstream = 0;
2930 st->fd = 0;
2931
2932 if (status == 0)
2933 return true;
2934 else
2935 {
2936 close_diag (st->orig_file_name);
2937 return false;
2938 }
2939 }
2940
2941 void
2942 tar_stat_destroy (struct tar_stat_info *st)
2943 {
2944 tar_stat_close (st);
2945 xattr_map_free (&st->xattr_map);
2946 free (st->orig_file_name);
2947 free (st->file_name);
2948 free (st->link_name);
2949 free (st->uname);
2950 free (st->gname);
2951 free (st->cntx_name);
2952 free (st->acls_a_ptr);
2953 free (st->acls_d_ptr);
2954 free (st->sparse_map);
2955 free (st->dumpdir);
2956 xheader_destroy (&st->xhdr);
2957 info_free_exclist (st);
2958 memset (st, 0, sizeof (*st));
2959 }
2960
2961 /* Format mask for all available formats that support nanosecond
2962 timestamp resolution. */
2963 #define NS_PRECISION_FORMAT_MASK FORMAT_MASK (POSIX_FORMAT)
2964
2965 /* Same as timespec_cmp, but ignore nanoseconds if current archive
2966 format does not provide sufficient resolution. */
2967 int
2968 tar_timespec_cmp (struct timespec a, struct timespec b)
2969 {
2970 if (!(FORMAT_MASK (current_format) & NS_PRECISION_FORMAT_MASK))
2971 a.tv_nsec = b.tv_nsec = 0;
2972 return timespec_cmp (a, b);
2973 }
2974
2975 /* Set tar exit status to VAL, unless it is already indicating
2976 a more serious condition. This relies on the fact that the
2977 values of TAREXIT_ constants are ranged by severity. */
2978 void
2979 set_exit_status (int val)
2980 {
2981 if (val > exit_status)
2982 exit_status = val;
2983 }