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