Various formatting fixes
[tar.git] / src / extract.c
blob41f8418fb50556a03eff0bfb88dff36baeb2975c
1 /* Extract files from a tar archive.
3 Copyright 1988-2024 Free Software Foundation, Inc.
5 This file is part of GNU tar.
7 GNU tar is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 GNU tar is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 Written by John Gilmore, on 1985-11-19. */
22 #include <system.h>
23 #include <quotearg.h>
24 #include <errno.h>
25 #include <flexmember.h>
26 #include <hash.h>
27 #include <priv-set.h>
28 #include <root-uid.h>
29 #include <utimens.h>
31 #include "common.h"
33 static bool we_are_root; /* true if our effective uid == 0 */
34 static mode_t newdir_umask; /* umask when creating new directories */
35 static mode_t current_umask; /* current umask (which is set to 0 if -p) */
37 #define ALL_MODE_BITS ((mode_t) ~ (mode_t) 0)
39 #if ! HAVE_FCHMOD && ! defined fchmod
40 # define fchmod(fd, mode) (errno = ENOSYS, -1)
41 #endif
42 #if ! HAVE_FCHOWN && ! defined fchown
43 # define fchown(fd, uid, gid) (errno = ENOSYS, -1)
44 #endif
46 #if (defined HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC \
47 || defined HAVE_STRUCT_STAT_ST_BIRTHTIM_TV_NSEC \
48 || defined HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC \
49 || (defined _WIN32 && ! defined __CYGWIN__))
50 # define HAVE_BIRTHTIME 1
51 #else
52 # define HAVE_BIRTHTIME 0
53 #endif
55 #if HAVE_BIRTHTIME
56 # define BIRTHTIME_EQ(a, b) (timespec_cmp (a, b) == 0)
57 #else
58 # define BIRTHTIME_EQ(a, b) true
59 #endif
61 /* Return true if an error number ERR means the system call is
62 supported in this case. */
63 static bool
64 implemented (int err)
66 return ! (err == ENOSYS
67 || err == ENOTSUP
68 || (EOPNOTSUPP != ENOTSUP && err == EOPNOTSUPP));
71 /* List of directories whose statuses we need to extract after we've
72 finished extracting their subsidiary files. If you consider each
73 contiguous subsequence of elements of the form [D]?[^D]*, where [D]
74 represents an element where AFTER_LINKS is nonzero and [^D]
75 represents an element where AFTER_LINKS is zero, then the head
76 of the subsequence has the longest name, and each non-head element
77 in the prefix is an ancestor (in the directory hierarchy) of the
78 preceding element. */
80 struct delayed_set_stat
82 /* Next directory in list. */
83 struct delayed_set_stat *next;
85 /* Metadata for this directory. */
86 dev_t dev;
87 ino_t ino;
88 mode_t mode; /* The desired mode is MODE & ~ current_umask. */
89 uid_t uid;
90 gid_t gid;
91 struct timespec atime;
92 struct timespec mtime;
94 /* An estimate of the directory's current mode, along with a mask
95 specifying which bits of this estimate are known to be correct.
96 If CURRENT_MODE_MASK is zero, CURRENT_MODE's value doesn't
97 matter. */
98 mode_t current_mode;
99 mode_t current_mode_mask;
101 /* This directory is an intermediate directory that was created
102 as an ancestor of some other directory; it was not mentioned
103 in the archive, so do not set its uid, gid, atime, or mtime,
104 and don't alter its mode outside of MODE_RWX. */
105 bool interdir;
107 /* Whether symbolic links should be followed when accessing the
108 directory. */
109 int atflag;
111 /* Do not set the status of this directory until after delayed
112 links are created. */
113 bool after_links;
115 /* Directory that the name is relative to. */
116 int change_dir;
118 /* extended attributes*/
119 char *cntx_name;
120 char *acls_a_ptr;
121 size_t acls_a_len;
122 char *acls_d_ptr;
123 size_t acls_d_len;
124 size_t xattr_map_size;
125 struct xattr_map xattr_map;
126 /* Length and contents of name. */
127 size_t file_name_len;
128 char *file_name;
131 static struct delayed_set_stat *delayed_set_stat_head;
133 /* Table of delayed stat updates hashed by path; null if none. */
134 static Hash_table *delayed_set_stat_table;
136 /* A link whose creation we have delayed. */
137 struct delayed_link
139 /* The next in a list of delayed links that should be made after
140 this delayed link. */
141 struct delayed_link *next;
143 /* The device, inode number and birthtime of the placeholder.
144 birthtime.tv_nsec is negative if the birthtime is not available.
145 Don't use mtime as this would allow for false matches if some
146 other process removes the placeholder. Don't use ctime as
147 this would cause race conditions and other screwups, e.g.,
148 when restoring hard-linked symlinks. */
149 dev_t dev;
150 ino_t ino;
151 #if HAVE_BIRTHTIME
152 struct timespec birthtime;
153 #endif
155 /* True if the link is symbolic. */
156 bool is_symlink;
158 /* The desired metadata, valid only the link is symbolic. */
159 mode_t mode;
160 uid_t uid;
161 gid_t gid;
162 struct timespec atime;
163 struct timespec mtime;
165 /* The directory that the sources and target are relative to. */
166 int change_dir;
168 /* A list of sources for this link. The sources are all to be
169 hard-linked together. */
170 struct string_list *sources;
172 /* SELinux context */
173 char *cntx_name;
175 /* ACLs */
176 char *acls_a_ptr;
177 size_t acls_a_len;
178 char *acls_d_ptr;
179 size_t acls_d_len;
181 struct xattr_map xattr_map;
183 /* The desired target of the desired link. */
184 char target[FLEXIBLE_ARRAY_MEMBER];
187 /* Table of delayed links hashed by device and inode; null if none. */
188 static Hash_table *delayed_link_table;
190 /* A list of the delayed links in tar file order,
191 and the tail of that list. */
192 static struct delayed_link *delayed_link_head;
193 static struct delayed_link **delayed_link_tail = &delayed_link_head;
195 struct string_list
197 struct string_list *next;
198 char string[FLEXIBLE_ARRAY_MEMBER];
201 static size_t
202 dl_hash (void const *entry, size_t table_size)
204 struct delayed_link const *dl = entry;
205 uintmax_t n = dl->dev;
206 int nshift = TYPE_WIDTH (n) - TYPE_WIDTH (dl->dev);
207 if (0 < nshift)
208 n <<= nshift;
209 n ^= dl->ino;
210 return n % table_size;
213 static bool
214 dl_compare (void const *a, void const *b)
216 struct delayed_link const *da = a, *db = b;
217 return (da->dev == db->dev) & (da->ino == db->ino);
220 static size_t
221 ds_hash (void const *entry, size_t table_size)
223 struct delayed_set_stat const *ds = entry;
224 return hash_string (ds->file_name, table_size);
227 static bool
228 ds_compare (void const *a, void const *b)
230 struct delayed_set_stat const *dsa = a, *dsb = b;
231 return strcmp (dsa->file_name, dsb->file_name) == 0;
234 /* Set up to extract files. */
235 void
236 extr_init (void)
238 we_are_root = geteuid () == ROOT_UID;
239 same_permissions_option += we_are_root;
240 same_owner_option += we_are_root;
242 /* Option -p clears the kernel umask, so it does not affect proper
243 restoration of file permissions. New intermediate directories will
244 comply with umask at start of program. */
246 newdir_umask = umask (0);
247 if (0 < same_permissions_option)
248 current_umask = 0;
249 else
251 umask (newdir_umask); /* restore the kernel umask */
252 current_umask = newdir_umask;
256 /* Use fchmod if possible, fchmodat otherwise. */
257 static int
258 fd_i_chmod (int fd, char const *file, mode_t mode, int atflag)
260 if (0 <= fd)
262 int result = fchmod (fd, mode);
263 if (result == 0 || implemented (errno))
264 return result;
266 return fchmodat (chdir_fd, file, mode, atflag);
269 /* A version of fd_i_chmod which gracefully handles several common error
270 conditions. Additional argument TYPEFLAG is the type of file in tar
271 notation.
273 static int
274 fd_chmod(int fd, char const *file_name, int mode, int atflag, int typeflag)
276 int chmod_errno = fd_i_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
278 /* On Solaris, chmod may fail if we don't have PRIV_ALL, because
279 setuid-root files would otherwise be a backdoor. See
280 http://opensolaris.org/jive/thread.jspa?threadID=95826
281 (2009-09-03). */
282 if (chmod_errno == EPERM && (mode & S_ISUID)
283 && priv_set_restore_linkdir () == 0)
285 chmod_errno = fd_i_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
286 priv_set_remove_linkdir ();
289 /* Linux fchmodat does not support AT_SYMLINK_NOFOLLOW, and
290 returns ENOTSUP even when operating on non-symlinks, try
291 again with the flag disabled if it does not appear to be
292 supported and if the file is not a symlink. This
293 introduces a race, alas. */
294 if (atflag && typeflag != SYMTYPE && ! implemented (chmod_errno))
295 chmod_errno = fd_i_chmod (fd, file_name, mode, 0) == 0 ? 0 : errno;
297 if (chmod_errno && (typeflag != SYMTYPE || implemented (chmod_errno)))
299 errno = chmod_errno;
300 return -1;
302 return 0;
305 /* Use fchown if possible, fchownat otherwise. */
306 static int
307 fd_chown (int fd, char const *file, uid_t uid, gid_t gid, int atflag)
309 if (0 <= fd)
311 int result = fchown (fd, uid, gid);
312 if (result == 0 || implemented (errno))
313 return result;
315 return fchownat (chdir_fd, file, uid, gid, atflag);
318 /* Use fstat if possible, fstatat otherwise. */
319 static int
320 fd_stat (int fd, char const *file, struct stat *st, int atflag)
322 return (0 <= fd
323 ? fstat (fd, st)
324 : fstatat (chdir_fd, file, st, atflag));
327 /* Set the mode for FILE_NAME to MODE.
328 MODE_MASK specifies the bits of MODE that we care about;
329 thus if MODE_MASK is zero, do nothing.
330 If FD is nonnegative, it is a file descriptor for the file.
331 CURRENT_MODE and CURRENT_MODE_MASK specify information known about
332 the file's current mode, using the style of struct delayed_set_stat.
333 TYPEFLAG specifies the type of the file.
334 ATFLAG specifies the flag to use when statting the file. */
335 static void
336 set_mode (char const *file_name,
337 mode_t mode, mode_t mode_mask, int fd,
338 mode_t current_mode, mode_t current_mode_mask,
339 char typeflag, int atflag)
341 if (((current_mode ^ mode) | ~ current_mode_mask) & mode_mask)
343 if (MODE_ALL & ~ mode_mask & ~ current_mode_mask)
345 struct stat st;
346 if (fd_stat (fd, file_name, &st, atflag) != 0)
348 stat_error (file_name);
349 return;
351 current_mode = st.st_mode;
354 current_mode &= MODE_ALL;
355 mode = (current_mode & ~ mode_mask) | (mode & mode_mask);
357 if (current_mode != mode)
359 if (fd_chmod (fd, file_name, mode, atflag, typeflag))
360 chmod_error_details (file_name, mode);
365 /* Check time after successfully setting FILE_NAME's time stamp to T. */
366 static void
367 check_time (char const *file_name, struct timespec t)
369 if (t.tv_sec < 0)
370 WARNOPT (WARN_TIMESTAMP,
371 (0, 0, _("%s: implausibly old time stamp %s"),
372 file_name, tartime (t, true)));
373 else if (timespec_cmp (volume_start_time, t) < 0)
375 struct timespec now;
376 gettime (&now);
377 if (timespec_cmp (now, t) < 0)
379 char buf[TIMESPEC_STRSIZE_BOUND];
380 struct timespec diff;
381 diff.tv_sec = t.tv_sec - now.tv_sec;
382 diff.tv_nsec = t.tv_nsec - now.tv_nsec;
383 if (diff.tv_nsec < 0)
385 diff.tv_nsec += BILLION;
386 diff.tv_sec--;
388 WARNOPT (WARN_TIMESTAMP,
389 (0, 0, _("%s: time stamp %s is %s s in the future"),
390 file_name, tartime (t, true), code_timespec (diff, buf)));
395 /* Restore stat attributes (owner, group, mode and times) for
396 FILE_NAME, using information given in *ST.
397 If FD is nonnegative, it is a file descriptor for the file.
398 CURRENT_MODE and CURRENT_MODE_MASK specify information known about
399 the file's current mode, using the style of struct delayed_set_stat.
400 TYPEFLAG specifies the type of the file.
401 If INTERDIR, this is an intermediate directory.
402 ATFLAG specifies the flag to use when statting the file. */
404 static void
405 set_stat (char const *file_name,
406 struct tar_stat_info const *st,
407 int fd, mode_t current_mode, mode_t current_mode_mask,
408 char typeflag, bool interdir, int atflag)
410 /* Do the utime before the chmod because some versions of utime are
411 broken and trash the modes of the file. */
413 if (! touch_option && ! interdir)
415 struct timespec ts[2];
416 if (incremental_option)
417 ts[0] = st->atime;
418 else
419 ts[0].tv_nsec = UTIME_OMIT;
420 ts[1] = st->mtime;
422 if (fdutimensat (fd, chdir_fd, file_name, ts, atflag) == 0)
424 if (incremental_option)
425 check_time (file_name, ts[0]);
426 check_time (file_name, ts[1]);
428 else if (typeflag != SYMTYPE || implemented (errno))
429 utime_error (file_name);
432 if (0 < same_owner_option && ! interdir)
434 /* Some systems allow non-root users to give files away. Once this
435 done, it is not possible anymore to change file permissions.
436 However, setting file permissions now would be incorrect, since
437 they would apply to the wrong user, and there would be a race
438 condition. So, don't use systems that allow non-root users to
439 give files away. */
440 uid_t uid = st->stat.st_uid;
441 gid_t gid = st->stat.st_gid;
443 if (fd_chown (fd, file_name, uid, gid, atflag) == 0)
445 /* Changing the owner can clear st_mode bits in some cases. */
446 if ((current_mode | ~ current_mode_mask) & S_IXUGO)
447 current_mode_mask &= ~ (current_mode & (S_ISUID | S_ISGID));
449 else if (typeflag != SYMTYPE || implemented (errno))
450 chown_error_details (file_name, uid, gid);
453 set_mode (file_name,
454 st->stat.st_mode & ~ current_umask,
455 0 < same_permissions_option && ! interdir ? MODE_ALL : MODE_RWX,
456 fd, current_mode, current_mode_mask, typeflag, atflag);
458 /* these three calls must be done *after* fd_chown() call because fd_chown
459 causes that linux capabilities becomes cleared. */
460 xattrs_xattrs_set (st, file_name, typeflag, 1);
461 xattrs_acls_set (st, file_name, typeflag);
462 xattrs_selinux_set (st, file_name, typeflag);
465 /* Find the direct ancestor of FILE_NAME in the delayed_set_stat list.
467 static struct delayed_set_stat *
468 find_direct_ancestor (char const *file_name)
470 struct delayed_set_stat *h = delayed_set_stat_head;
471 while (h)
473 if (! h->after_links
474 && strncmp (file_name, h->file_name, h->file_name_len) == 0
475 && ISSLASH (file_name[h->file_name_len])
476 && (last_component (file_name) == file_name + h->file_name_len + 1))
477 break;
478 h = h->next;
480 return h;
483 /* For each entry H in the leading prefix of entries in HEAD that do
484 not have after_links marked, mark H and fill in its dev and ino
485 members. Assume HEAD && ! HEAD->after_links. */
486 static void
487 mark_after_links (struct delayed_set_stat *head)
489 struct delayed_set_stat *h = head;
493 struct stat st;
494 h->after_links = 1;
496 if (deref_stat (h->file_name, &st) != 0)
497 stat_error (h->file_name);
498 else
500 h->dev = st.st_dev;
501 h->ino = st.st_ino;
504 while ((h = h->next) && ! h->after_links);
507 /* Remember to restore stat attributes (owner, group, mode and times)
508 for the directory FILE_NAME, using information given in *ST,
509 once we stop extracting files into that directory.
511 If ST is null, merely create a placeholder node for an intermediate
512 directory that was created by make_directories.
514 NOTICE: this works only if the archive has usual member order, i.e.
515 directory, then the files in that directory. Incremental archive have
516 somewhat reversed order: first go subdirectories, then all other
517 members. To help cope with this case the variable
518 delay_directory_restore_option is set by prepare_to_extract.
520 If an archive was explicitly created so that its member order is
521 reversed, some directory timestamps can be restored incorrectly,
522 e.g.:
523 tar --no-recursion -cf archive dir dir/file1 foo dir/file2
525 static void
526 delay_set_stat (char const *file_name, struct tar_stat_info const *st,
527 mode_t current_mode, mode_t current_mode_mask,
528 mode_t mode, int atflag)
530 size_t file_name_len = strlen (file_name);
531 struct delayed_set_stat *data;
533 if (! (delayed_set_stat_table
534 || (delayed_set_stat_table = hash_initialize (0, 0, ds_hash,
535 ds_compare, NULL))))
536 xalloc_die ();
538 struct delayed_set_stat key;
539 key.file_name = (char *) file_name;
541 data = hash_lookup (delayed_set_stat_table, &key);
542 if (data)
544 if (data->interdir)
546 struct stat real_st;
547 if (fstatat (chdir_fd, data->file_name,
548 &real_st, data->atflag) != 0)
550 stat_error (data->file_name);
552 else
554 data->dev = real_st.st_dev;
555 data->ino = real_st.st_ino;
559 else
561 data = xmalloc (sizeof (*data));
562 data->next = delayed_set_stat_head;
563 delayed_set_stat_head = data;
564 data->file_name_len = file_name_len;
565 data->file_name = xstrdup (file_name);
566 if (! hash_insert (delayed_set_stat_table, data))
567 xalloc_die ();
568 data->after_links = false;
569 if (st)
571 data->dev = st->stat.st_dev;
572 data->ino = st->stat.st_ino;
574 xattr_map_init (&data->xattr_map);
577 data->mode = mode;
578 if (st)
580 data->uid = st->stat.st_uid;
581 data->gid = st->stat.st_gid;
582 data->atime = st->atime;
583 data->mtime = st->mtime;
585 data->current_mode = current_mode;
586 data->current_mode_mask = current_mode_mask;
587 data->interdir = ! st;
588 data->atflag = atflag;
589 data->change_dir = chdir_current;
590 data->cntx_name = NULL;
591 if (st)
592 assign_string_or_null (&data->cntx_name, st->cntx_name);
593 if (st && st->acls_a_ptr)
595 data->acls_a_ptr = xmemdup (st->acls_a_ptr, st->acls_a_len + 1);
596 data->acls_a_len = st->acls_a_len;
598 else
600 data->acls_a_ptr = NULL;
601 data->acls_a_len = 0;
603 if (st && st->acls_d_ptr)
605 data->acls_d_ptr = xmemdup (st->acls_d_ptr, st->acls_d_len + 1);
606 data->acls_d_len = st->acls_d_len;
608 else
610 data->acls_d_ptr = NULL;
611 data->acls_d_len = 0;
613 if (st)
614 xattr_map_copy (&data->xattr_map, &st->xattr_map);
615 if (must_be_dot_or_slash (file_name))
616 mark_after_links (data);
619 /* Update the delayed_set_stat info for an intermediate directory
620 created within the file name of DIR. The intermediate directory turned
621 out to be the same as this directory, e.g. due to ".." or symbolic
622 links. *DIR_STAT_INFO is the status of the directory. */
623 static void
624 repair_delayed_set_stat (char const *dir,
625 struct stat const *dir_stat_info)
627 struct delayed_set_stat *data;
628 for (data = delayed_set_stat_head; data; data = data->next)
630 struct stat st;
631 if (fstatat (chdir_fd, data->file_name, &st, data->atflag) != 0)
633 stat_error (data->file_name);
634 return;
637 if (st.st_dev == dir_stat_info->st_dev
638 && st.st_ino == dir_stat_info->st_ino)
640 data->dev = current_stat_info.stat.st_dev;
641 data->ino = current_stat_info.stat.st_ino;
642 data->mode = current_stat_info.stat.st_mode;
643 data->uid = current_stat_info.stat.st_uid;
644 data->gid = current_stat_info.stat.st_gid;
645 data->atime = current_stat_info.atime;
646 data->mtime = current_stat_info.mtime;
647 data->current_mode = st.st_mode;
648 data->current_mode_mask = ALL_MODE_BITS;
649 data->interdir = false;
650 return;
654 ERROR ((0, 0, _("%s: Unexpected inconsistency when making directory"),
655 quotearg_colon (dir)));
658 static void
659 free_delayed_set_stat (struct delayed_set_stat *data)
661 free (data->file_name);
662 xattr_map_free (&data->xattr_map);
663 free (data->cntx_name);
664 free (data->acls_a_ptr);
665 free (data->acls_d_ptr);
666 free (data);
669 void
670 remove_delayed_set_stat (const char *fname)
672 struct delayed_set_stat *data, *next, *prev = NULL;
673 for (data = delayed_set_stat_head; data; data = next)
675 next = data->next;
676 if (chdir_current == data->change_dir
677 && strcmp (data->file_name, fname) == 0)
679 hash_remove (delayed_set_stat_table, data);
680 free_delayed_set_stat (data);
681 if (prev)
682 prev->next = next;
683 else
684 delayed_set_stat_head = next;
685 return;
687 else
688 prev = data;
692 static void
693 fixup_delayed_set_stat (char const *src, char const *dst)
695 struct delayed_set_stat *data;
696 for (data = delayed_set_stat_head; data; data = data->next)
698 if (chdir_current == data->change_dir
699 && strcmp (data->file_name, src) == 0)
701 free (data->file_name);
702 data->file_name = xstrdup (dst);
703 data->file_name_len = strlen (dst);
704 return;
709 /* After a file/link/directory creation has failed due to ENOENT,
710 create all required directories. Return zero if all the required
711 directories were created, nonzero (issuing a diagnostic) otherwise.
712 Set *INTERDIR_MADE (unless NULL) if at least one directory was created. */
713 static int
714 make_directories (char *file_name, bool *interdir_made)
716 char *cursor0 = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
717 char *cursor; /* points into the file name */
718 char *parent_end = NULL;
719 int parent_errno;
721 for (cursor = cursor0; *cursor; cursor++)
723 mode_t mode;
724 mode_t desired_mode;
725 int status;
727 if (! ISSLASH (*cursor))
728 continue;
730 /* Avoid mkdir of empty string, if leading or double '/'. */
732 if (cursor == cursor0 || ISSLASH (cursor[-1]))
733 continue;
735 /* Avoid mkdir where last part of file name is "." or "..". */
737 if (cursor[-1] == '.'
738 && (cursor == cursor0 + 1 || ISSLASH (cursor[-2])
739 || (cursor[-2] == '.'
740 && (cursor == cursor0 + 2 || ISSLASH (cursor[-3])))))
741 continue;
743 *cursor = '\0'; /* truncate the name there */
744 desired_mode = MODE_RWX & ~ newdir_umask;
745 mode = desired_mode | (we_are_root ? 0 : MODE_WXUSR);
746 status = mkdirat (chdir_fd, file_name, mode);
748 if (status == 0)
750 /* Create a struct delayed_set_stat even if
751 mode == desired_mode, because
752 repair_delayed_set_stat may need to update the struct. */
753 delay_set_stat (file_name,
754 0, mode & ~ current_umask, MODE_RWX,
755 desired_mode, AT_SYMLINK_NOFOLLOW);
756 if (interdir_made)
757 *interdir_made = true;
758 print_for_mkdir (file_name, desired_mode);
759 parent_end = NULL;
761 else
762 switch (errno)
764 case ELOOP: case ENAMETOOLONG: case ENOENT: case ENOTDIR:
765 /* FILE_NAME doesn't exist and couldn't be created; fail now. */
766 mkdir_error (file_name);
767 *cursor = '/';
768 return status;
770 default:
771 /* FILE_NAME may be an existing directory so do not fail now.
772 Instead, arrange to check at loop exit, assuming this is
773 the last loop iteration. */
774 parent_end = cursor;
775 parent_errno = errno;
776 break;
779 *cursor = '/';
782 if (!parent_end)
783 return 0;
785 /* Although we did not create the parent directory, some other
786 process may have created it, so check whether it exists now. */
787 *parent_end = '\0';
788 struct stat st;
789 int stat_status = fstatat (chdir_fd, file_name, &st, 0);
790 if (!stat_status && !S_ISDIR (st.st_mode))
791 stat_status = -1;
792 if (stat_status)
794 errno = parent_errno;
795 mkdir_error (file_name);
797 else if (interdir_made)
798 *interdir_made = true;
800 *parent_end = '/';
802 return stat_status;
805 /* Return true if FILE_NAME (with status *STP, if STP) is not a
806 directory, and has a time stamp newer than (or equal to) that of
807 TAR_STAT. */
808 static bool
809 file_newer_p (const char *file_name, struct stat const *stp,
810 struct tar_stat_info *tar_stat)
812 struct stat st;
814 if (!stp)
816 if (deref_stat (file_name, &st) != 0)
818 if (errno != ENOENT)
820 stat_warn (file_name);
821 /* Be safer: if the file exists, assume it is newer. */
822 return true;
824 return false;
826 stp = &st;
829 return (! S_ISDIR (stp->st_mode)
830 && tar_timespec_cmp (tar_stat->mtime, get_stat_mtime (stp)) <= 0);
833 #define RECOVER_NO 0
834 #define RECOVER_OK 1
835 #define RECOVER_SKIP 2
837 /* Attempt repairing what went wrong with the extraction. Delete an
838 already existing file or create missing intermediate directories.
839 Return RECOVER_OK if we somewhat increased our chances at a successful
840 extraction, RECOVER_NO if there are no chances, and RECOVER_SKIP if the
841 caller should skip extraction of that member. The value of errno is
842 properly restored on returning RECOVER_NO.
844 If REGULAR, the caller was trying to extract onto a regular file.
846 Set *INTERDIR_MADE if an intermediate directory is made as part of
847 the recovery process. */
849 static int
850 maybe_recoverable (char *file_name, bool regular, bool *interdir_made)
852 int e = errno;
853 struct stat st;
854 struct stat const *stp = 0;
856 if (*interdir_made)
857 return RECOVER_NO;
859 switch (e)
861 case ELOOP:
863 /* With open ("symlink", O_NOFOLLOW|...), POSIX says errno == ELOOP,
864 but some operating systems do not conform to the standard. */
865 #ifdef EFTYPE
866 /* NetBSD uses errno == EFTYPE; see <http://gnats.netbsd.org/43154>. */
867 case EFTYPE:
868 #endif
869 /* FreeBSD 8.1 uses errno == EMLINK. */
870 case EMLINK:
871 /* Tru64 5.1B uses errno == ENOTSUP. */
872 case ENOTSUP:
874 if (! regular
875 || old_files_option != OVERWRITE_OLD_FILES || dereference_option)
876 break;
877 if (strchr (file_name, '/'))
879 if (deref_stat (file_name, &st) != 0)
880 break;
881 stp = &st;
883 /* The caller tried to open a symbolic link with O_NOFOLLOW.
884 Fall through, treating it as an already-existing file. */
885 FALLTHROUGH;
886 case EEXIST:
887 /* Remove an old file, if the options allow this. */
889 switch (old_files_option)
891 case SKIP_OLD_FILES:
892 WARNOPT (WARN_EXISTING_FILE,
893 (0, 0, _("%s: skipping existing file"), file_name));
894 return RECOVER_SKIP;
896 case KEEP_OLD_FILES:
897 return RECOVER_NO;
899 case KEEP_NEWER_FILES:
900 if (file_newer_p (file_name, stp, &current_stat_info))
901 break;
902 FALLTHROUGH;
903 case DEFAULT_OLD_FILES:
904 case NO_OVERWRITE_DIR_OLD_FILES:
905 case OVERWRITE_OLD_FILES:
906 if (0 < remove_any_file (file_name, ORDINARY_REMOVE_OPTION))
907 return RECOVER_OK;
908 break;
910 case UNLINK_FIRST_OLD_FILES:
911 break;
913 FALLTHROUGH;
915 case ENOENT:
916 /* Attempt creating missing intermediate directories. */
917 if (make_directories (file_name, interdir_made) == 0 && *interdir_made)
918 return RECOVER_OK;
919 break;
921 default:
922 /* Just say we can't do anything about it... */
923 break;
926 errno = e;
927 return RECOVER_NO;
930 /* Restore stat extended attributes (xattr) for FILE_NAME, using information
931 given in *ST. Restore before extraction because they may affect file layout
932 (e.g. on Lustre distributed parallel filesystem - setting info about how many
933 servers is this file striped over, stripe size, mirror copies, etc.
934 in advance dramatically improves the following performance of reading and
935 writing a file). TYPEFLAG specifies the type of the file. Return a negative
936 number (setting errno) on failure, zero if successful but FILE_NAME was not
937 created (e.g., xattrs not available), and a positive number if FILE_NAME was
938 created. */
939 static int
940 set_xattr (char const *file_name, struct tar_stat_info const *st,
941 mode_t mode, char typeflag)
943 #ifdef HAVE_XATTRS
944 if ((xattrs_option > 0) && st->xattr_map.xm_size)
946 int r = mknodat (chdir_fd, file_name, mode, 0);
947 if (r < 0)
948 return r;
949 xattrs_xattrs_set (st, file_name, typeflag, 0);
950 return 1;
952 #endif
954 return 0;
957 /* Fix the statuses of all directories whose statuses need fixing, and
958 which are not ancestors of FILE_NAME. If AFTER_LINKS is
959 nonzero, do this for all such directories; otherwise, stop at the
960 first directory that is marked to be fixed up only after delayed
961 links are applied. */
962 static void
963 apply_nonancestor_delayed_set_stat (char const *file_name, bool after_links)
965 size_t file_name_len = strlen (file_name);
966 bool check_for_renamed_directories = 0;
968 while (delayed_set_stat_head)
970 struct delayed_set_stat *data = delayed_set_stat_head;
971 bool skip_this_one = 0;
972 struct stat st;
973 mode_t current_mode = data->current_mode;
974 mode_t current_mode_mask = data->current_mode_mask;
976 check_for_renamed_directories |= data->after_links;
978 if (after_links < data->after_links
979 || (data->file_name_len < file_name_len
980 && file_name[data->file_name_len]
981 && (ISSLASH (file_name[data->file_name_len])
982 || ISSLASH (file_name[data->file_name_len - 1]))
983 && memcmp (file_name, data->file_name, data->file_name_len) == 0))
984 break;
986 chdir_do (data->change_dir);
988 if (check_for_renamed_directories)
990 if (fstatat (chdir_fd, data->file_name, &st, data->atflag) != 0)
992 stat_error (data->file_name);
993 skip_this_one = 1;
995 else
997 current_mode = st.st_mode;
998 current_mode_mask = ALL_MODE_BITS;
999 if (! (st.st_dev == data->dev && st.st_ino == data->ino))
1001 ERROR ((0, 0,
1002 _("%s: Directory renamed before its status could be extracted"),
1003 quotearg_colon (data->file_name)));
1004 skip_this_one = 1;
1009 if (! skip_this_one)
1011 struct tar_stat_info sb;
1012 sb.stat.st_mode = data->mode;
1013 sb.stat.st_uid = data->uid;
1014 sb.stat.st_gid = data->gid;
1015 sb.atime = data->atime;
1016 sb.mtime = data->mtime;
1017 sb.cntx_name = data->cntx_name;
1018 sb.acls_a_ptr = data->acls_a_ptr;
1019 sb.acls_a_len = data->acls_a_len;
1020 sb.acls_d_ptr = data->acls_d_ptr;
1021 sb.acls_d_len = data->acls_d_len;
1022 sb.xattr_map = data->xattr_map;
1023 set_stat (data->file_name, &sb,
1024 -1, current_mode, current_mode_mask,
1025 DIRTYPE, data->interdir, data->atflag);
1028 delayed_set_stat_head = data->next;
1029 hash_remove (delayed_set_stat_table, data);
1030 free_delayed_set_stat (data);
1035 static bool
1036 is_directory_link (char const *file_name, struct stat *st)
1038 char buf[1];
1039 return (0 <= readlinkat (chdir_fd, file_name, buf, sizeof buf)
1040 && fstatat (chdir_fd, file_name, st, 0) == 0
1041 && S_ISDIR (st->st_mode));
1044 /* Given struct stat of a directory (or directory member) whose ownership
1045 or permissions of will be restored later, return the temporary permissions
1046 for that directory, sufficiently restrictive so that in the meantime
1047 processes owned by other users do not inadvertently create files under this
1048 directory that inherit the wrong owner, group, or permissions from the
1049 directory.
1051 If not root, though, make the directory writeable and searchable at first,
1052 so that files can be created under it.
1054 static int
1055 safe_dir_mode (struct stat const *st)
1057 return ((st->st_mode
1058 & (0 < same_owner_option || 0 < same_permissions_option
1059 ? S_IRWXU
1060 : MODE_RWX))
1061 | (we_are_root ? 0 : MODE_WXUSR));
1064 /* Extractor functions for various member types */
1066 static int
1067 extract_dir (char *file_name, int typeflag)
1069 int status;
1070 mode_t mode;
1071 mode_t current_mode = 0;
1072 mode_t current_mode_mask = 0;
1073 int atflag = 0;
1074 bool interdir_made = false;
1076 /* Save 'root device' to avoid purging mount points. */
1077 if (one_file_system_option && root_device == 0)
1079 struct stat st;
1081 if (fstatat (chdir_fd, ".", &st, 0) != 0)
1082 stat_diag (".");
1083 else
1084 root_device = st.st_dev;
1087 if (incremental_option)
1088 /* Read the entry and delete files that aren't listed in the archive. */
1089 purge_directory (file_name);
1090 else if (typeflag == GNUTYPE_DUMPDIR)
1091 skip_member ();
1093 mode = safe_dir_mode (&current_stat_info.stat);
1095 for (;;)
1097 status = mkdirat (chdir_fd, file_name, mode);
1098 if (status == 0)
1100 current_mode = mode & ~ current_umask;
1101 current_mode_mask = MODE_RWX;
1102 atflag = AT_SYMLINK_NOFOLLOW;
1103 break;
1106 if (errno == EEXIST)
1108 if (interdir_made
1109 || keep_directory_symlink_option
1110 || old_files_option == NO_OVERWRITE_DIR_OLD_FILES
1111 || old_files_option == DEFAULT_OLD_FILES
1112 || old_files_option == OVERWRITE_OLD_FILES)
1114 struct stat st;
1115 st.st_mode = 0;
1117 if (keep_directory_symlink_option
1118 && is_directory_link (file_name, &st))
1119 return 0;
1121 if ((st.st_mode != 0 && fstatat_flags == 0)
1122 || deref_stat (file_name, &st) == 0)
1124 current_mode = st.st_mode;
1125 current_mode_mask = ALL_MODE_BITS;
1127 if (S_ISDIR (current_mode))
1129 if (interdir_made)
1131 repair_delayed_set_stat (file_name, &st);
1132 return 0;
1134 else if (old_files_option == NO_OVERWRITE_DIR_OLD_FILES)
1136 /* Temporarily change the directory mode to a safe
1137 value, to be able to create files in it, should
1138 the need be.
1140 mode = safe_dir_mode (&st);
1141 status = fd_chmod (-1, file_name, mode,
1142 AT_SYMLINK_NOFOLLOW, DIRTYPE);
1143 if (status == 0)
1145 /* Store the actual directory mode, to be restored
1146 later.
1148 current_stat_info.stat = st;
1149 current_mode = mode & ~ current_umask;
1150 current_mode_mask = MODE_RWX;
1151 atflag = AT_SYMLINK_NOFOLLOW;
1152 break;
1154 else
1156 chmod_error_details (file_name, mode);
1159 break;
1163 else if (old_files_option == UNLINK_FIRST_OLD_FILES)
1165 status = 0;
1166 break;
1169 errno = EEXIST;
1172 switch (maybe_recoverable (file_name, false, &interdir_made))
1174 case RECOVER_OK:
1175 continue;
1177 case RECOVER_SKIP:
1178 break;
1180 case RECOVER_NO:
1181 if (errno != EEXIST)
1183 mkdir_error (file_name);
1184 return 1;
1186 break;
1188 break;
1191 if (status == 0
1192 || old_files_option == DEFAULT_OLD_FILES
1193 || old_files_option == OVERWRITE_OLD_FILES)
1194 delay_set_stat (file_name, &current_stat_info,
1195 current_mode, current_mode_mask,
1196 current_stat_info.stat.st_mode, atflag);
1197 return status;
1202 static int
1203 open_output_file (char const *file_name, int typeflag, mode_t mode,
1204 int file_created, mode_t *current_mode,
1205 mode_t *current_mode_mask)
1207 int fd;
1208 bool overwriting_old_files = old_files_option == OVERWRITE_OLD_FILES;
1209 int openflag = (O_WRONLY | O_BINARY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK
1210 | (file_created
1211 ? O_NOFOLLOW
1212 : (O_CREAT
1213 | (overwriting_old_files
1214 ? O_TRUNC | (dereference_option ? 0 : O_NOFOLLOW)
1215 : O_EXCL))));
1217 if (typeflag == CONTTYPE)
1219 static int conttype_diagnosed;
1221 if (!conttype_diagnosed)
1223 conttype_diagnosed = 1;
1224 WARNOPT (WARN_CONTIGUOUS_CAST,
1225 (0, 0, _("Extracting contiguous files as regular files")));
1229 /* If O_NOFOLLOW is needed but does not work, check for a symlink
1230 separately. There's a race condition, but that cannot be avoided
1231 on hosts lacking O_NOFOLLOW. */
1232 if (! HAVE_WORKING_O_NOFOLLOW
1233 && overwriting_old_files && ! dereference_option)
1235 char buf[1];
1236 if (0 <= readlinkat (chdir_fd, file_name, buf, sizeof buf))
1238 errno = ELOOP;
1239 return -1;
1243 fd = openat (chdir_fd, file_name, openflag, mode);
1244 if (0 <= fd)
1246 if (openflag & O_EXCL)
1248 *current_mode = mode & ~ current_umask;
1249 *current_mode_mask = MODE_RWX;
1251 else
1253 struct stat st;
1254 if (fstat (fd, &st) != 0)
1256 int e = errno;
1257 close (fd);
1258 errno = e;
1259 return -1;
1261 if (! S_ISREG (st.st_mode))
1263 close (fd);
1264 errno = EEXIST;
1265 return -1;
1267 *current_mode = st.st_mode;
1268 *current_mode_mask = ALL_MODE_BITS;
1272 return fd;
1275 static int
1276 extract_file (char *file_name, int typeflag)
1278 int fd;
1279 off_t size;
1280 union block *data_block;
1281 int status;
1282 size_t count;
1283 size_t written;
1284 bool interdir_made = false;
1285 mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1286 & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1287 mode_t current_mode = 0;
1288 mode_t current_mode_mask = 0;
1290 if (to_stdout_option)
1291 fd = STDOUT_FILENO;
1292 else if (to_command_option)
1294 fd = sys_exec_command (file_name, 'f', &current_stat_info);
1295 if (fd < 0)
1297 skip_member ();
1298 return 0;
1301 else
1303 int file_created;
1304 /* Either we pre-create the file in set_xattr(), or we just directly open
1305 the file in open_output_file() with O_CREAT. If pre-creating, we need
1306 to use S_IWUSR so we can open the file O_WRONLY in open_output_file().
1307 The additional mode bit is cleared later by set_stat()->set_mode(). */
1308 while (((file_created = set_xattr (file_name, &current_stat_info,
1309 mode | S_IWUSR, typeflag))
1310 < 0)
1311 || ((fd = open_output_file (file_name, typeflag, mode,
1312 file_created, &current_mode,
1313 &current_mode_mask))
1314 < 0))
1316 int recover = maybe_recoverable (file_name, true, &interdir_made);
1317 if (recover != RECOVER_OK)
1319 skip_member ();
1320 if (recover == RECOVER_SKIP)
1321 return 0;
1322 open_error (file_name);
1323 return 1;
1328 mv_begin_read (&current_stat_info);
1329 if (current_stat_info.is_sparse)
1330 sparse_extract_file (fd, &current_stat_info, &size);
1331 else
1332 for (size = current_stat_info.stat.st_size; size > 0; )
1334 mv_size_left (size);
1336 /* Locate data, determine max length writeable, write it,
1337 block that we have used the data, then check if the write
1338 worked. */
1340 data_block = find_next_block ();
1341 if (! data_block)
1343 ERROR ((0, 0, _("Unexpected EOF in archive")));
1344 break; /* FIXME: What happens, then? */
1347 written = available_space_after (data_block);
1349 if (written > size)
1350 written = size;
1351 errno = 0;
1352 count = blocking_write (fd, data_block->buffer, written);
1353 size -= written;
1355 set_next_block_after ((union block *)
1356 (data_block->buffer + written - 1));
1357 if (count != written)
1359 if (!to_command_option)
1360 write_error_details (file_name, count, written);
1361 /* FIXME: shouldn't we restore from backup? */
1362 break;
1366 skim_file (size, false);
1368 mv_end ();
1370 /* If writing to stdout, don't try to do anything to the filename;
1371 it doesn't exist, or we don't want to touch it anyway. */
1373 if (to_stdout_option)
1374 return 0;
1376 if (! to_command_option)
1377 set_stat (file_name, &current_stat_info, fd,
1378 current_mode, current_mode_mask, typeflag, false,
1379 (old_files_option == OVERWRITE_OLD_FILES
1380 ? 0 : AT_SYMLINK_NOFOLLOW));
1382 status = close (fd);
1383 if (status < 0)
1384 close_error (file_name);
1386 if (to_command_option)
1387 sys_wait_command ();
1389 return status;
1392 /* Return true if NAME is a delayed link. This can happen only if the link
1393 placeholder file has been created. Therefore, try to stat the NAME
1394 first. If it doesn't exist, there is no matching entry in the table.
1395 Otherwise, look for the entry in the table that has the matching dev
1396 and ino numbers. Return false if not found.
1398 Do not rely on comparing file names, which may differ for
1399 various reasons (e.g. relative vs. absolute file names).
1401 static bool
1402 find_delayed_link_source (char const *name)
1404 struct stat st;
1406 if (!delayed_link_table)
1407 return false;
1409 if (fstatat (chdir_fd, name, &st, AT_SYMLINK_NOFOLLOW))
1411 if (errno != ENOENT)
1412 stat_error (name);
1413 return false;
1416 struct delayed_link dl;
1417 dl.dev = st.st_dev;
1418 dl.ino = st.st_ino;
1419 return hash_lookup (delayed_link_table, &dl) != NULL;
1422 /* Create a placeholder file with name FILE_NAME, which will be
1423 replaced after other extraction is done by a symbolic link if
1424 IS_SYMLINK is true, and by a hard link otherwise. Set
1425 *INTERDIR_MADE if an intermediate directory is made in the
1426 process.
1429 static int
1430 create_placeholder_file (char *file_name, bool is_symlink, bool *interdir_made)
1432 int fd;
1433 struct stat st;
1435 while ((fd = openat (chdir_fd, file_name, O_WRONLY | O_CREAT | O_EXCL, 0)) < 0)
1437 if (errno == EEXIST && find_delayed_link_source (file_name))
1439 /* The placeholder file has already been created. This means
1440 that the link being extracted is a duplicate of an already
1441 processed one. Skip it.
1443 return 0;
1446 switch (maybe_recoverable (file_name, false, interdir_made))
1448 case RECOVER_OK:
1449 continue;
1451 case RECOVER_SKIP:
1452 return 0;
1454 case RECOVER_NO:
1455 open_error (file_name);
1456 return -1;
1460 if (fstat (fd, &st) != 0)
1462 stat_error (file_name);
1463 close (fd);
1465 else if (close (fd) != 0)
1466 close_error (file_name);
1467 else
1469 struct delayed_set_stat *h;
1470 struct delayed_link *p =
1471 xmalloc (FLEXNSIZEOF (struct delayed_link, target,
1472 strlen (current_stat_info.link_name) + 1));
1473 p->next = NULL;
1474 p->dev = st.st_dev;
1475 p->ino = st.st_ino;
1476 #if HAVE_BIRTHTIME
1477 p->birthtime = get_stat_birthtime (&st);
1478 #endif
1479 p->is_symlink = is_symlink;
1480 if (is_symlink)
1482 p->mode = current_stat_info.stat.st_mode;
1483 p->uid = current_stat_info.stat.st_uid;
1484 p->gid = current_stat_info.stat.st_gid;
1485 p->atime = current_stat_info.atime;
1486 p->mtime = current_stat_info.mtime;
1488 p->change_dir = chdir_current;
1489 p->sources = xmalloc (FLEXNSIZEOF (struct string_list, string,
1490 strlen (file_name) + 1));
1491 p->sources->next = 0;
1492 strcpy (p->sources->string, file_name);
1493 p->cntx_name = NULL;
1494 assign_string_or_null (&p->cntx_name, current_stat_info.cntx_name);
1495 p->acls_a_ptr = NULL;
1496 p->acls_a_len = 0;
1497 p->acls_d_ptr = NULL;
1498 p->acls_d_len = 0;
1499 xattr_map_init (&p->xattr_map);
1500 xattr_map_copy (&p->xattr_map, &current_stat_info.xattr_map);
1501 strcpy (p->target, current_stat_info.link_name);
1503 *delayed_link_tail = p;
1504 delayed_link_tail = &p->next;
1505 if (! ((delayed_link_table
1506 || (delayed_link_table = hash_initialize (0, 0, dl_hash,
1507 dl_compare, free)))
1508 && hash_insert (delayed_link_table, p)))
1509 xalloc_die ();
1511 if ((h = find_direct_ancestor (file_name)) != NULL)
1512 mark_after_links (h);
1514 return 0;
1517 return -1;
1520 static int
1521 extract_link (char *file_name, MAYBE_UNUSED int typeflag)
1523 bool interdir_made = false;
1524 char const *link_name;
1525 int rc;
1527 link_name = current_stat_info.link_name;
1529 if ((! absolute_names_option && contains_dot_dot (link_name))
1530 || find_delayed_link_source (link_name))
1531 return create_placeholder_file (file_name, false, &interdir_made);
1535 struct stat st1, st2;
1536 int e;
1537 int status = linkat (chdir_fd, link_name, chdir_fd, file_name, 0);
1538 e = errno;
1540 if (status == 0)
1542 if (delayed_link_table
1543 && fstatat (chdir_fd, link_name, &st1, AT_SYMLINK_NOFOLLOW) == 0)
1545 struct delayed_link dl1;
1546 dl1.ino = st1.st_ino;
1547 dl1.dev = st1.st_dev;
1548 struct delayed_link *ds = hash_lookup (delayed_link_table, &dl1);
1549 if (ds && ds->change_dir == chdir_current
1550 && BIRTHTIME_EQ (ds->birthtime, get_stat_birthtime (&st1)))
1552 struct string_list *p
1553 = xmalloc (FLEXNSIZEOF (struct string_list,
1554 string, strlen (file_name) + 1));
1555 strcpy (p->string, file_name);
1556 p->next = ds->sources;
1557 ds->sources = p;
1561 return 0;
1563 else if ((e == EEXIST && strcmp (link_name, file_name) == 0)
1564 || ((fstatat (chdir_fd, link_name, &st1, AT_SYMLINK_NOFOLLOW)
1565 == 0)
1566 && (fstatat (chdir_fd, file_name, &st2, AT_SYMLINK_NOFOLLOW)
1567 == 0)
1568 && st1.st_dev == st2.st_dev
1569 && st1.st_ino == st2.st_ino))
1570 return 0;
1572 errno = e;
1574 while ((rc = maybe_recoverable (file_name, false, &interdir_made))
1575 == RECOVER_OK);
1577 if (rc == RECOVER_SKIP)
1578 return 0;
1579 if (!(incremental_option && errno == EEXIST))
1581 link_error (link_name, file_name);
1582 return 1;
1584 return 0;
1587 static int
1588 extract_symlink (char *file_name, MAYBE_UNUSED int typeflag)
1590 #ifdef HAVE_SYMLINK
1591 bool interdir_made = false;
1593 if (! absolute_names_option
1594 && (IS_ABSOLUTE_FILE_NAME (current_stat_info.link_name)
1595 || contains_dot_dot (current_stat_info.link_name)))
1596 return create_placeholder_file (file_name, true, &interdir_made);
1598 while (symlinkat (current_stat_info.link_name, chdir_fd, file_name) != 0)
1599 switch (maybe_recoverable (file_name, false, &interdir_made))
1601 case RECOVER_OK:
1602 continue;
1604 case RECOVER_SKIP:
1605 return 0;
1607 case RECOVER_NO:
1608 symlink_error (current_stat_info.link_name, file_name);
1609 return -1;
1612 set_stat (file_name, &current_stat_info, -1, 0, 0,
1613 SYMTYPE, false, AT_SYMLINK_NOFOLLOW);
1614 return 0;
1616 #else
1617 static int warned_once;
1619 if (!warned_once)
1621 warned_once = 1;
1622 WARNOPT (WARN_SYMLINK_CAST,
1623 (0, 0,
1624 _("Attempting extraction of symbolic links as hard links")));
1626 return extract_link (file_name, typeflag);
1627 #endif
1630 #if S_IFCHR || S_IFBLK
1631 static int
1632 extract_node (char *file_name, int typeflag)
1634 bool interdir_made = false;
1635 mode_t mode = (current_stat_info.stat.st_mode & (MODE_RWX | S_IFBLK | S_IFCHR)
1636 & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1638 while (mknodat (chdir_fd, file_name, mode, current_stat_info.stat.st_rdev)
1639 != 0)
1640 switch (maybe_recoverable (file_name, false, &interdir_made))
1642 case RECOVER_OK:
1643 continue;
1645 case RECOVER_SKIP:
1646 return 0;
1648 case RECOVER_NO:
1649 mknod_error (file_name);
1650 return -1;
1653 set_stat (file_name, &current_stat_info, -1,
1654 mode & ~ current_umask, MODE_RWX,
1655 typeflag, false, AT_SYMLINK_NOFOLLOW);
1656 return 0;
1658 #endif
1660 #if HAVE_MKFIFO || defined mkfifo
1661 static int
1662 extract_fifo (char *file_name, int typeflag)
1664 bool interdir_made = false;
1665 mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1666 & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1668 while (mkfifoat (chdir_fd, file_name, mode) != 0)
1669 switch (maybe_recoverable (file_name, false, &interdir_made))
1671 case RECOVER_OK:
1672 continue;
1674 case RECOVER_SKIP:
1675 return 0;
1677 case RECOVER_NO:
1678 mkfifo_error (file_name);
1679 return -1;
1682 set_stat (file_name, &current_stat_info, -1,
1683 mode & ~ current_umask, MODE_RWX,
1684 typeflag, false, AT_SYMLINK_NOFOLLOW);
1685 return 0;
1687 #endif
1689 typedef int (*tar_extractor_t) (char *file_name, int typeflag);
1692 /* Prepare to extract a file. Find extractor function.
1693 Return true to proceed with the extraction, false to skip the current
1694 member. */
1696 static bool
1697 prepare_to_extract (char const *file_name, int typeflag, tar_extractor_t *fun)
1699 tar_extractor_t extractor = NULL;
1701 /* Select the extractor */
1702 switch (typeflag)
1704 case GNUTYPE_SPARSE:
1705 extractor = extract_file;
1706 break;
1708 case AREGTYPE:
1709 case REGTYPE:
1710 case CONTTYPE:
1711 /* Appears to be a file. But BSD tar uses the convention that a slash
1712 suffix means a directory. */
1713 if (current_stat_info.had_trailing_slash)
1714 extractor = extract_dir;
1715 else
1716 extractor = extract_file;
1717 break;
1719 case SYMTYPE:
1720 extractor = extract_symlink;
1721 break;
1723 case LNKTYPE:
1724 extractor = extract_link;
1725 break;
1727 #if S_IFCHR
1728 case CHRTYPE:
1729 current_stat_info.stat.st_mode |= S_IFCHR;
1730 extractor = extract_node;
1731 break;
1732 #endif
1734 #if S_IFBLK
1735 case BLKTYPE:
1736 current_stat_info.stat.st_mode |= S_IFBLK;
1737 extractor = extract_node;
1738 break;
1739 #endif
1741 #if HAVE_MKFIFO || defined mkfifo
1742 case FIFOTYPE:
1743 extractor = extract_fifo;
1744 break;
1745 #endif
1747 case DIRTYPE:
1748 case GNUTYPE_DUMPDIR:
1749 extractor = extract_dir;
1750 if (current_stat_info.is_dumpdir)
1751 delay_directory_restore_option = true;
1752 break;
1754 case GNUTYPE_VOLHDR:
1755 return false;
1757 case GNUTYPE_MULTIVOL:
1758 ERROR ((0, 0,
1759 _("%s: Cannot extract -- file is continued from another volume"),
1760 quotearg_colon (current_stat_info.file_name)));
1761 return false;
1763 case GNUTYPE_LONGNAME:
1764 case GNUTYPE_LONGLINK:
1765 ERROR ((0, 0, _("Unexpected long name header")));
1766 return false;
1768 default:
1769 WARNOPT (WARN_UNKNOWN_CAST,
1770 (0, 0,
1771 _("%s: Unknown file type '%c', extracted as normal file"),
1772 quotearg_colon (file_name), typeflag));
1773 extractor = extract_file;
1776 if (EXTRACT_OVER_PIPE)
1778 if (extractor != extract_file)
1779 return false;
1781 else
1783 switch (old_files_option)
1785 case UNLINK_FIRST_OLD_FILES:
1786 if (!remove_any_file (file_name,
1787 recursive_unlink_option
1788 ? RECURSIVE_REMOVE_OPTION
1789 : ORDINARY_REMOVE_OPTION)
1790 && errno && errno != ENOENT)
1792 unlink_error (file_name);
1793 return false;
1795 break;
1797 case KEEP_NEWER_FILES:
1798 if (file_newer_p (file_name, 0, &current_stat_info))
1800 WARNOPT (WARN_IGNORE_NEWER,
1801 (0, 0, _("Current %s is newer or same age"),
1802 quote (file_name)));
1803 return false;
1805 break;
1807 default:
1808 break;
1811 *fun = extractor;
1813 return true;
1816 /* Extract a file from the archive. */
1817 void
1818 extract_archive (void)
1820 char typeflag;
1821 tar_extractor_t fun;
1822 bool skip_dotdot_name;
1824 fatal_exit_hook = extract_finish;
1826 set_next_block_after (current_header);
1828 skip_dotdot_name = (!absolute_names_option
1829 && contains_dot_dot (current_stat_info.orig_file_name));
1830 if (skip_dotdot_name)
1831 ERROR ((0, 0, _("%s: Member name contains '..'"),
1832 quotearg_colon (current_stat_info.orig_file_name)));
1834 if (!current_stat_info.file_name[0]
1835 || skip_dotdot_name
1836 || (interactive_option
1837 && !confirm ("extract", current_stat_info.file_name)))
1839 skip_member ();
1840 return;
1843 /* Print the block from current_header and current_stat. */
1844 if (verbose_option)
1845 print_header (&current_stat_info, current_header, -1);
1847 /* Restore stats for all non-ancestor directories, unless
1848 it is an incremental archive.
1849 (see NOTICE in the comment to delay_set_stat above) */
1850 if (!delay_directory_restore_option)
1852 int dir = chdir_current;
1853 apply_nonancestor_delayed_set_stat (current_stat_info.file_name, false);
1854 chdir_do (dir);
1857 /* Take a safety backup of a previously existing file. */
1859 if (backup_option)
1860 if (!maybe_backup_file (current_stat_info.file_name, 0))
1862 int e = errno;
1863 ERROR ((0, e, _("%s: Was unable to backup this file"),
1864 quotearg_colon (current_stat_info.file_name)));
1865 skip_member ();
1866 return;
1869 /* Extract the archive entry according to its type. */
1870 /* KLUDGE */
1871 typeflag = sparse_member_p (&current_stat_info) ?
1872 GNUTYPE_SPARSE : current_header->header.typeflag;
1874 if (prepare_to_extract (current_stat_info.file_name, typeflag, &fun))
1876 if (fun (current_stat_info.file_name, typeflag) == 0)
1877 return;
1879 else
1880 skip_member ();
1882 if (backup_option)
1883 undo_last_backup ();
1886 /* Extract the link DS whose final extraction was delayed. */
1887 static void
1888 apply_delayed_link (struct delayed_link *ds)
1890 struct string_list *sources = ds->sources;
1891 char const *valid_source = 0;
1893 chdir_do (ds->change_dir);
1895 for (sources = ds->sources; sources; sources = sources->next)
1897 char const *source = sources->string;
1898 struct stat st;
1900 /* Make sure the placeholder file is still there. If not,
1901 don't create a link, as the placeholder was probably
1902 removed by a later extraction. */
1903 if (fstatat (chdir_fd, source, &st, AT_SYMLINK_NOFOLLOW) == 0
1904 && st.st_dev == ds->dev
1905 && st.st_ino == ds->ino
1906 && BIRTHTIME_EQ (get_stat_birthtime (&st), ds->birthtime))
1908 /* Unlink the placeholder, then create a hard link if possible,
1909 a symbolic link otherwise. */
1910 if (unlinkat (chdir_fd, source, 0) != 0)
1911 unlink_error (source);
1912 else if (valid_source
1913 && (linkat (chdir_fd, valid_source, chdir_fd, source, 0)
1914 == 0))
1916 else if (!ds->is_symlink)
1918 if (linkat (chdir_fd, ds->target, chdir_fd, source, 0) != 0)
1919 link_error (ds->target, source);
1921 else if (symlinkat (ds->target, chdir_fd, source) != 0)
1922 symlink_error (ds->target, source);
1923 else
1925 struct tar_stat_info st1;
1926 st1.stat.st_mode = ds->mode;
1927 st1.stat.st_uid = ds->uid;
1928 st1.stat.st_gid = ds->gid;
1929 st1.atime = ds->atime;
1930 st1.mtime = ds->mtime;
1931 st1.cntx_name = ds->cntx_name;
1932 st1.acls_a_ptr = ds->acls_a_ptr;
1933 st1.acls_a_len = ds->acls_a_len;
1934 st1.acls_d_ptr = ds->acls_d_ptr;
1935 st1.acls_d_len = ds->acls_d_len;
1936 st1.xattr_map = ds->xattr_map;
1937 set_stat (source, &st1, -1, 0, 0, SYMTYPE,
1938 false, AT_SYMLINK_NOFOLLOW);
1939 valid_source = source;
1944 /* There is little point to freeing, as we are about to exit,
1945 and freeing is more likely to cause than cure trouble. */
1946 if (false)
1948 for (sources = ds->sources; sources; )
1950 struct string_list *next = sources->next;
1951 free (sources);
1952 sources = next;
1955 xattr_map_free (&ds->xattr_map);
1956 free (ds->cntx_name);
1960 /* Extract the links whose final extraction were delayed. */
1961 static void
1962 apply_delayed_links (void)
1964 for (struct delayed_link *ds = delayed_link_head; ds; ds = ds->next)
1965 apply_delayed_link (ds);
1967 if (false && delayed_link_table)
1969 /* There is little point to freeing, as we are about to exit,
1970 and freeing is more likely to cause than cure trouble.
1971 Also, the above code has not bothered to free the list
1972 in delayed_link_head. */
1973 hash_free (delayed_link_table);
1974 delayed_link_table = NULL;
1978 /* Finish the extraction of an archive. */
1979 void
1980 extract_finish (void)
1982 /* First, fix the status of ordinary directories that need fixing. */
1983 apply_nonancestor_delayed_set_stat ("", false);
1985 /* Then, apply delayed links, so that they don't affect delayed
1986 directory status-setting for ordinary directories. */
1987 apply_delayed_links ();
1989 /* Finally, fix the status of directories that are ancestors
1990 of delayed links. */
1991 apply_nonancestor_delayed_set_stat ("", true);
1993 /* This table should be empty after apply_nonancestor_delayed_set_stat. */
1994 if (false && delayed_set_stat_table)
1996 /* There is little point to freeing, as we are about to exit,
1997 and freeing is more likely to cause than cure trouble. */
1998 hash_free (delayed_set_stat_table);
1999 delayed_set_stat_table = NULL;
2003 bool
2004 rename_directory (char *src, char *dst)
2006 if (renameat (chdir_fd, src, chdir_fd, dst) == 0)
2007 fixup_delayed_set_stat (src, dst);
2008 else
2010 int e = errno;
2012 switch (e)
2014 case ENOENT:
2015 if (make_directories (dst, NULL) == 0)
2017 if (renameat (chdir_fd, src, chdir_fd, dst) == 0)
2018 return true;
2019 e = errno;
2021 break;
2023 case EXDEV:
2024 /* FIXME: Fall back to recursive copying */
2026 default:
2027 break;
2030 ERROR ((0, e, _("Cannot rename %s to %s"),
2031 quote_n (0, src),
2032 quote_n (1, dst)));
2033 return false;
2035 return true;