859146cab39596ade8449693f1b7dbd235b36170
[debian/tar] / src / extract.c
1 /* Extract files from a tar archive.
2
3    Copyright 1988, 1992-1994, 1996-2001, 2003-2007, 2010, 2012-2013
4    Free Software Foundation, Inc.
5
6    This file is part of GNU tar.
7
8    GNU tar is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    GNU tar is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Written by John Gilmore, on 1985-11-19.  */
22
23 #include <system.h>
24 #include <quotearg.h>
25 #include <errno.h>
26 #include <priv-set.h>
27 #include <root-uid.h>
28 #include <utimens.h>
29
30 #include "common.h"
31
32 static bool we_are_root;        /* true if our effective uid == 0 */
33 static mode_t newdir_umask;     /* umask when creating new directories */
34 static mode_t current_umask;    /* current umask (which is set to 0 if -p) */
35
36 #define ALL_MODE_BITS ((mode_t) ~ (mode_t) 0)
37
38 #if ! HAVE_FCHMOD && ! defined fchmod
39 # define fchmod(fd, mode) (errno = ENOSYS, -1)
40 #endif
41 #if ! HAVE_FCHOWN && ! defined fchown
42 # define fchown(fd, uid, gid) (errno = ENOSYS, -1)
43 #endif
44
45 /* Return true if an error number ERR means the system call is
46    supported in this case.  */
47 static bool
48 implemented (int err)
49 {
50   return ! (err == ENOSYS
51             || err == ENOTSUP
52             || (EOPNOTSUPP != ENOTSUP && err == EOPNOTSUPP));
53 }
54
55 /* List of directories whose statuses we need to extract after we've
56    finished extracting their subsidiary files.  If you consider each
57    contiguous subsequence of elements of the form [D]?[^D]*, where [D]
58    represents an element where AFTER_LINKS is nonzero and [^D]
59    represents an element where AFTER_LINKS is zero, then the head
60    of the subsequence has the longest name, and each non-head element
61    in the prefix is an ancestor (in the directory hierarchy) of the
62    preceding element.  */
63
64 struct delayed_set_stat
65   {
66     /* Next directory in list.  */
67     struct delayed_set_stat *next;
68
69     /* Metadata for this directory.  */
70     dev_t dev;
71     ino_t ino;
72     mode_t mode; /* The desired mode is MODE & ~ current_umask.  */
73     uid_t uid;
74     gid_t gid;
75     struct timespec atime;
76     struct timespec mtime;
77
78     /* An estimate of the directory's current mode, along with a mask
79        specifying which bits of this estimate are known to be correct.
80        If CURRENT_MODE_MASK is zero, CURRENT_MODE's value doesn't
81        matter.  */
82     mode_t current_mode;
83     mode_t current_mode_mask;
84
85     /* This directory is an intermediate directory that was created
86        as an ancestor of some other directory; it was not mentioned
87        in the archive, so do not set its uid, gid, atime, or mtime,
88        and don't alter its mode outside of MODE_RWX.  */
89     bool interdir;
90
91     /* Whether symbolic links should be followed when accessing the
92        directory.  */
93     int atflag;
94
95     /* Do not set the status of this directory until after delayed
96        links are created.  */
97     bool after_links;
98
99     /* Directory that the name is relative to.  */
100     int change_dir;
101
102     /* extended attributes*/
103     char *cntx_name;
104     char *acls_a_ptr;
105     size_t acls_a_len;
106     char *acls_d_ptr;
107     size_t acls_d_len;
108     size_t xattr_map_size;
109     struct xattr_array *xattr_map;
110     /* Length and contents of name.  */
111     size_t file_name_len;
112     char file_name[1];
113   };
114
115 static struct delayed_set_stat *delayed_set_stat_head;
116
117 /* List of links whose creation we have delayed.  */
118 struct delayed_link
119   {
120     /* The next delayed link in the list.  */
121     struct delayed_link *next;
122
123     /* The device, inode number and birthtime of the placeholder.
124        birthtime.tv_nsec is negative if the birthtime is not available.
125        Don't use mtime as this would allow for false matches if some
126        other process removes the placeholder.  Don't use ctime as
127        this would cause race conditions and other screwups, e.g.,
128        when restoring hard-linked symlinks.  */
129     dev_t dev;
130     ino_t ino;
131     struct timespec birthtime;
132
133     /* True if the link is symbolic.  */
134     bool is_symlink;
135
136     /* The desired metadata, valid only the link is symbolic.  */
137     mode_t mode;
138     uid_t uid;
139     gid_t gid;
140     struct timespec atime;
141     struct timespec mtime;
142
143     /* The directory that the sources and target are relative to.  */
144     int change_dir;
145
146     /* A list of sources for this link.  The sources are all to be
147        hard-linked together.  */
148     struct string_list *sources;
149
150     /* SELinux context */
151     char *cntx_name;
152
153     /* ACLs */
154     char *acls_a_ptr;
155     size_t acls_a_len;
156     char *acls_d_ptr;
157     size_t acls_d_len;
158
159     size_t xattr_map_size;
160     struct xattr_array *xattr_map;
161
162     /* The desired target of the desired link.  */
163     char target[1];
164   };
165
166 static struct delayed_link *delayed_link_head;
167
168 struct string_list
169   {
170     struct string_list *next;
171     char string[1];
172   };
173
174 /*  Set up to extract files.  */
175 void
176 extr_init (void)
177 {
178   we_are_root = geteuid () == ROOT_UID;
179   same_permissions_option += we_are_root;
180   same_owner_option += we_are_root;
181
182   /* Option -p clears the kernel umask, so it does not affect proper
183      restoration of file permissions.  New intermediate directories will
184      comply with umask at start of program.  */
185
186   newdir_umask = umask (0);
187   if (0 < same_permissions_option)
188     current_umask = 0;
189   else
190     {
191       umask (newdir_umask);     /* restore the kernel umask */
192       current_umask = newdir_umask;
193     }
194
195   /* If the user wants to guarantee that everything is under one directory,
196      determine its name now and let it be created later.  */
197   if (one_top_level_option && !one_top_level_dir)
198     {
199       char *base = base_name (archive_name_array[0]);
200
201       one_top_level_dir = strip_compression_suffix (base);
202       free (base);
203       
204       if (!one_top_level_dir)
205         USAGE_ERROR ((0, 0, _("Cannot deduce top-level directory name; please set it explicitly with --one-top-level=DIR")));
206     }
207 }
208
209 /* Use fchmod if possible, fchmodat otherwise.  */
210 static int
211 fd_chmod (int fd, char const *file, mode_t mode, int atflag)
212 {
213   if (0 <= fd)
214     {
215       int result = fchmod (fd, mode);
216       if (result == 0 || implemented (errno))
217         return result;
218     }
219   return fchmodat (chdir_fd, file, mode, atflag);
220 }
221
222 /* Use fchown if possible, fchownat otherwise.  */
223 static int
224 fd_chown (int fd, char const *file, uid_t uid, gid_t gid, int atflag)
225 {
226   if (0 <= fd)
227     {
228       int result = fchown (fd, uid, gid);
229       if (result == 0 || implemented (errno))
230         return result;
231     }
232   return fchownat (chdir_fd, file, uid, gid, atflag);
233 }
234
235 /* Use fstat if possible, fstatat otherwise.  */
236 static int
237 fd_stat (int fd, char const *file, struct stat *st, int atflag)
238 {
239   return (0 <= fd
240           ? fstat (fd, st)
241           : fstatat (chdir_fd, file, st, atflag));
242 }
243
244 /* Set the mode for FILE_NAME to MODE.
245    MODE_MASK specifies the bits of MODE that we care about;
246    thus if MODE_MASK is zero, do nothing.
247    If FD is nonnegative, it is a file descriptor for the file.
248    CURRENT_MODE and CURRENT_MODE_MASK specify information known about
249    the file's current mode, using the style of struct delayed_set_stat.
250    TYPEFLAG specifies the type of the file.
251    ATFLAG specifies the flag to use when statting the file.  */
252 static void
253 set_mode (char const *file_name,
254           mode_t mode, mode_t mode_mask, int fd,
255           mode_t current_mode, mode_t current_mode_mask,
256           char typeflag, int atflag)
257 {
258   if (((current_mode ^ mode) | ~ current_mode_mask) & mode_mask)
259     {
260       if (MODE_ALL & ~ mode_mask & ~ current_mode_mask)
261         {
262           struct stat st;
263           if (fd_stat (fd, file_name, &st, atflag) != 0)
264             {
265               stat_error (file_name);
266               return;
267             }
268           current_mode = st.st_mode;
269         }
270
271       current_mode &= MODE_ALL;
272       mode = (current_mode & ~ mode_mask) | (mode & mode_mask);
273
274       if (current_mode != mode)
275         {
276           int chmod_errno =
277             fd_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
278
279           /* On Solaris, chmod may fail if we don't have PRIV_ALL, because
280              setuid-root files would otherwise be a backdoor.  See
281              http://opensolaris.org/jive/thread.jspa?threadID=95826
282              (2009-09-03).  */
283           if (chmod_errno == EPERM && (mode & S_ISUID)
284               && priv_set_restore_linkdir () == 0)
285             {
286               chmod_errno =
287                 fd_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
288               priv_set_remove_linkdir ();
289             }
290
291           /* Linux fchmodat does not support AT_SYMLINK_NOFOLLOW, and
292              returns ENOTSUP even when operating on non-symlinks, try
293              again with the flag disabled if it does not appear to be
294              supported and if the file is not a symlink.  This
295              introduces a race, alas.  */
296           if (atflag && typeflag != SYMTYPE && ! implemented (chmod_errno))
297             chmod_errno = fd_chmod (fd, file_name, mode, 0) == 0 ? 0 : errno;
298
299           if (chmod_errno
300               && (typeflag != SYMTYPE || implemented (chmod_errno)))
301             {
302               errno = chmod_errno;
303               chmod_error_details (file_name, mode);
304             }
305         }
306     }
307 }
308
309 /* Check time after successfully setting FILE_NAME's time stamp to T.  */
310 static void
311 check_time (char const *file_name, struct timespec t)
312 {
313   if (t.tv_sec < 0)
314     WARNOPT (WARN_TIMESTAMP,
315              (0, 0, _("%s: implausibly old time stamp %s"),
316               file_name, tartime (t, true)));
317   else if (timespec_cmp (volume_start_time, t) < 0)
318     {
319       struct timespec now;
320       gettime (&now);
321       if (timespec_cmp (now, t) < 0)
322         {
323           char buf[TIMESPEC_STRSIZE_BOUND];
324           struct timespec diff;
325           diff.tv_sec = t.tv_sec - now.tv_sec;
326           diff.tv_nsec = t.tv_nsec - now.tv_nsec;
327           if (diff.tv_nsec < 0)
328             {
329               diff.tv_nsec += BILLION;
330               diff.tv_sec--;
331             }
332           WARNOPT (WARN_TIMESTAMP,
333                    (0, 0, _("%s: time stamp %s is %s s in the future"),
334                     file_name, tartime (t, true), code_timespec (diff, buf)));
335         }
336     }
337 }
338
339 /* Restore stat attributes (owner, group, mode and times) for
340    FILE_NAME, using information given in *ST.
341    If FD is nonnegative, it is a file descriptor for the file.
342    CURRENT_MODE and CURRENT_MODE_MASK specify information known about
343    the file's current mode, using the style of struct delayed_set_stat.
344    TYPEFLAG specifies the type of the file.
345    If INTERDIR, this is an intermediate directory.
346    ATFLAG specifies the flag to use when statting the file.  */
347
348 static void
349 set_stat (char const *file_name,
350           struct tar_stat_info const *st,
351           int fd, mode_t current_mode, mode_t current_mode_mask,
352           char typeflag, bool interdir, int atflag)
353 {
354   /* Do the utime before the chmod because some versions of utime are
355      broken and trash the modes of the file.  */
356
357   if (! touch_option && ! interdir)
358     {
359       struct timespec ts[2];
360       if (incremental_option)
361         ts[0] = st->atime;
362       else
363         ts[0].tv_nsec = UTIME_OMIT;
364       ts[1] = st->mtime;
365
366       if (fdutimensat (fd, chdir_fd, file_name, ts, atflag) == 0)
367         {
368           if (incremental_option)
369             check_time (file_name, ts[0]);
370           check_time (file_name, ts[1]);
371         }
372       else if (typeflag != SYMTYPE || implemented (errno))
373         utime_error (file_name);
374     }
375
376   if (0 < same_owner_option && ! interdir)
377     {
378       /* Some systems allow non-root users to give files away.  Once this
379          done, it is not possible anymore to change file permissions.
380          However, setting file permissions now would be incorrect, since
381          they would apply to the wrong user, and there would be a race
382          condition.  So, don't use systems that allow non-root users to
383          give files away.  */
384       uid_t uid = st->stat.st_uid;
385       gid_t gid = st->stat.st_gid;
386
387       if (fd_chown (fd, file_name, uid, gid, atflag) == 0)
388         {
389           /* Changing the owner can clear st_mode bits in some cases.  */
390           if ((current_mode | ~ current_mode_mask) & S_IXUGO)
391             current_mode_mask &= ~ (current_mode & (S_ISUID | S_ISGID));
392         }
393       else if (typeflag != SYMTYPE || implemented (errno))
394         chown_error_details (file_name, uid, gid);
395     }
396
397   set_mode (file_name,
398             st->stat.st_mode & ~ current_umask,
399             0 < same_permissions_option && ! interdir ? MODE_ALL : MODE_RWX,
400             fd, current_mode, current_mode_mask, typeflag, atflag);
401
402   /* these three calls must be done *after* fd_chown() call because fd_chown
403      causes that linux capabilities becomes cleared. */
404   xattrs_xattrs_set (st, file_name, typeflag, 1);
405   xattrs_acls_set (st, file_name, typeflag);
406   xattrs_selinux_set (st, file_name, typeflag);
407 }
408
409 /* For each entry H in the leading prefix of entries in HEAD that do
410    not have after_links marked, mark H and fill in its dev and ino
411    members.  Assume HEAD && ! HEAD->after_links.  */
412 static void
413 mark_after_links (struct delayed_set_stat *head)
414 {
415   struct delayed_set_stat *h = head;
416
417   do
418     {
419       struct stat st;
420       h->after_links = 1;
421
422       if (deref_stat (h->file_name, &st) != 0)
423         stat_error (h->file_name);
424       else
425         {
426           h->dev = st.st_dev;
427           h->ino = st.st_ino;
428         }
429     }
430   while ((h = h->next) && ! h->after_links);
431 }
432
433 /* Remember to restore stat attributes (owner, group, mode and times)
434    for the directory FILE_NAME, using information given in *ST,
435    once we stop extracting files into that directory.
436
437    If ST is null, merely create a placeholder node for an intermediate
438    directory that was created by make_directories.
439
440    NOTICE: this works only if the archive has usual member order, i.e.
441    directory, then the files in that directory. Incremental archive have
442    somewhat reversed order: first go subdirectories, then all other
443    members. To help cope with this case the variable
444    delay_directory_restore_option is set by prepare_to_extract.
445
446    If an archive was explicitely created so that its member order is
447    reversed, some directory timestamps can be restored incorrectly,
448    e.g.:
449        tar --no-recursion -cf archive dir dir/file1 foo dir/file2
450 */
451 static void
452 delay_set_stat (char const *file_name, struct tar_stat_info const *st,
453                 mode_t current_mode, mode_t current_mode_mask,
454                 mode_t mode, int atflag)
455 {
456   size_t file_name_len = strlen (file_name);
457   struct delayed_set_stat *data =
458     xmalloc (offsetof (struct delayed_set_stat, file_name)
459              + file_name_len + 1);
460   data->next = delayed_set_stat_head;
461   data->mode = mode;
462   if (st)
463     {
464       data->dev = st->stat.st_dev;
465       data->ino = st->stat.st_ino;
466       data->uid = st->stat.st_uid;
467       data->gid = st->stat.st_gid;
468       data->atime = st->atime;
469       data->mtime = st->mtime;
470     }
471   data->file_name_len = file_name_len;
472   data->current_mode = current_mode;
473   data->current_mode_mask = current_mode_mask;
474   data->interdir = ! st;
475   data->atflag = atflag;
476   data->after_links = 0;
477   data->change_dir = chdir_current;
478   data->cntx_name = NULL;
479   if (st)
480     assign_string (&data->cntx_name, st->cntx_name);
481   if (st && st->acls_a_ptr)
482     {
483       data->acls_a_ptr = xmemdup (st->acls_a_ptr, st->acls_a_len + 1);
484       data->acls_a_len = st->acls_a_len;
485     }
486   else
487     {
488       data->acls_a_ptr = NULL;
489       data->acls_a_len = 0;
490     }
491   if (st && st->acls_d_ptr)
492     {
493       data->acls_d_ptr = xmemdup (st->acls_d_ptr, st->acls_d_len + 1);
494       data->acls_d_len = st->acls_d_len;
495     }
496   else
497     {
498       data->acls_d_ptr = NULL;
499       data->acls_d_len = 0;
500     }
501   if (st)
502     xheader_xattr_copy (st, &data->xattr_map, &data->xattr_map_size);
503   else
504     {
505       data->xattr_map = NULL;
506       data->xattr_map_size = 0;
507     }
508   strcpy (data->file_name, file_name);
509   delayed_set_stat_head = data;
510   if (must_be_dot_or_slash (file_name))
511     mark_after_links (data);
512 }
513
514 /* Update the delayed_set_stat info for an intermediate directory
515    created within the file name of DIR.  The intermediate directory turned
516    out to be the same as this directory, e.g. due to ".." or symbolic
517    links.  *DIR_STAT_INFO is the status of the directory.  */
518 static void
519 repair_delayed_set_stat (char const *dir,
520                          struct stat const *dir_stat_info)
521 {
522   struct delayed_set_stat *data;
523   for (data = delayed_set_stat_head;  data;  data = data->next)
524     {
525       struct stat st;
526       if (fstatat (chdir_fd, data->file_name, &st, data->atflag) != 0)
527         {
528           stat_error (data->file_name);
529           return;
530         }
531
532       if (st.st_dev == dir_stat_info->st_dev
533           && st.st_ino == dir_stat_info->st_ino)
534         {
535           data->dev = current_stat_info.stat.st_dev;
536           data->ino = current_stat_info.stat.st_ino;
537           data->mode = current_stat_info.stat.st_mode;
538           data->uid = current_stat_info.stat.st_uid;
539           data->gid = current_stat_info.stat.st_gid;
540           data->atime = current_stat_info.atime;
541           data->mtime = current_stat_info.mtime;
542           data->current_mode = st.st_mode;
543           data->current_mode_mask = ALL_MODE_BITS;
544           data->interdir = false;
545           return;
546         }
547     }
548
549   ERROR ((0, 0, _("%s: Unexpected inconsistency when making directory"),
550           quotearg_colon (dir)));
551 }
552
553 /* After a file/link/directory creation has failed, see if
554    it's because some required directory was not present, and if so,
555    create all required directories.  Return zero if all the required
556    directories were created, nonzero (issuing a diagnostic) otherwise.
557    Set *INTERDIR_MADE if at least one directory was created.  */
558 static int
559 make_directories (char *file_name, bool *interdir_made)
560 {
561   char *cursor0 = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
562   char *cursor;                 /* points into the file name */
563
564   for (cursor = cursor0; *cursor; cursor++)
565     {
566       mode_t mode;
567       mode_t desired_mode;
568       int status;
569
570       if (! ISSLASH (*cursor))
571         continue;
572
573       /* Avoid mkdir of empty string, if leading or double '/'.  */
574
575       if (cursor == cursor0 || ISSLASH (cursor[-1]))
576         continue;
577
578       /* Avoid mkdir where last part of file name is "." or "..".  */
579
580       if (cursor[-1] == '.'
581           && (cursor == cursor0 + 1 || ISSLASH (cursor[-2])
582               || (cursor[-2] == '.'
583                   && (cursor == cursor0 + 2 || ISSLASH (cursor[-3])))))
584         continue;
585
586       *cursor = '\0';           /* truncate the name there */
587       desired_mode = MODE_RWX & ~ newdir_umask;
588       mode = desired_mode | (we_are_root ? 0 : MODE_WXUSR);
589       status = mkdirat (chdir_fd, file_name, mode);
590
591       if (status == 0)
592         {
593           /* Create a struct delayed_set_stat even if
594              mode == desired_mode, because
595              repair_delayed_set_stat may need to update the struct.  */
596           delay_set_stat (file_name,
597                           0, mode & ~ current_umask, MODE_RWX,
598                           desired_mode, AT_SYMLINK_NOFOLLOW);
599
600           print_for_mkdir (file_name, cursor - file_name, desired_mode);
601           *interdir_made = true;
602         }
603       else if (errno == EEXIST)
604         status = 0;
605       else
606         {
607           /* Check whether the desired file exists.  Even when the
608              file exists, mkdir can fail with some errno value E other
609              than EEXIST, so long as E describes an error condition
610              that also applies.  */
611           int e = errno;
612           struct stat st;
613           status = fstatat (chdir_fd, file_name, &st, 0);
614           if (status)
615             {
616               errno = e;
617               mkdir_error (file_name);
618             }
619         }
620
621       *cursor = '/';
622       if (status)
623         return status;
624     }
625
626   return 0;
627 }
628
629 /* Return true if FILE_NAME (with status *STP, if STP) is not a
630    directory, and has a time stamp newer than (or equal to) that of
631    TAR_STAT.  */
632 static bool
633 file_newer_p (const char *file_name, struct stat const *stp,
634               struct tar_stat_info *tar_stat)
635 {
636   struct stat st;
637
638   if (!stp)
639     {
640       if (deref_stat (file_name, &st) != 0)
641         {
642           if (errno != ENOENT)
643             {
644               stat_warn (file_name);
645               /* Be safer: if the file exists, assume it is newer.  */
646               return true;
647             }
648           return false;
649         }
650       stp = &st;
651     }
652
653   return (! S_ISDIR (stp->st_mode)
654           && tar_timespec_cmp (tar_stat->mtime, get_stat_mtime (stp)) <= 0);
655 }
656
657 #define RECOVER_NO 0
658 #define RECOVER_OK 1
659 #define RECOVER_SKIP 2
660
661 /* Attempt repairing what went wrong with the extraction.  Delete an
662    already existing file or create missing intermediate directories.
663    Return RECOVER_OK if we somewhat increased our chances at a successful
664    extraction, RECOVER_NO if there are no chances, and RECOVER_SKIP if the
665    caller should skip extraction of that member.  The value of errno is
666    properly restored on returning RECOVER_NO.
667
668    If REGULAR, the caller was trying to extract onto a regular file.
669
670    Set *INTERDIR_MADE if an intermediate directory is made as part of
671    the recovery process.  */
672
673 static int
674 maybe_recoverable (char *file_name, bool regular, bool *interdir_made)
675 {
676   int e = errno;
677   struct stat st;
678   struct stat const *stp = 0;
679
680   if (*interdir_made)
681     return RECOVER_NO;
682
683   switch (e)
684     {
685     case ELOOP:
686
687       /* With open ("symlink", O_NOFOLLOW|...), POSIX says errno == ELOOP,
688          but some operating systems do not conform to the standard.  */
689 #ifdef EFTYPE
690       /* NetBSD uses errno == EFTYPE; see <http://gnats.netbsd.org/43154>.  */
691     case EFTYPE:
692 #endif
693       /* FreeBSD 8.1 uses errno == EMLINK.  */
694     case EMLINK:
695       /* Tru64 5.1B uses errno == ENOTSUP.  */
696     case ENOTSUP:
697
698       if (! regular
699           || old_files_option != OVERWRITE_OLD_FILES || dereference_option)
700         break;
701       if (strchr (file_name, '/'))
702         {
703           if (deref_stat (file_name, &st) != 0)
704             break;
705           stp = &st;
706         }
707
708       /* The caller tried to open a symbolic link with O_NOFOLLOW.
709          Fall through, treating it as an already-existing file.  */
710
711     case EEXIST:
712       /* Remove an old file, if the options allow this.  */
713
714       switch (old_files_option)
715         {
716         case SKIP_OLD_FILES:
717           WARNOPT (WARN_EXISTING_FILE,
718                    (0, 0, _("%s: skipping existing file"), file_name));
719           return RECOVER_SKIP;
720
721         case KEEP_OLD_FILES:
722           return RECOVER_NO;
723
724         case KEEP_NEWER_FILES:
725           if (file_newer_p (file_name, stp, &current_stat_info))
726             break;
727           /* FALL THROUGH */
728
729         case DEFAULT_OLD_FILES:
730         case NO_OVERWRITE_DIR_OLD_FILES:
731         case OVERWRITE_OLD_FILES:
732           if (0 < remove_any_file (file_name, ORDINARY_REMOVE_OPTION))
733             return RECOVER_OK;
734           break;
735
736         case UNLINK_FIRST_OLD_FILES:
737           break;
738         }
739
740     case ENOENT:
741       /* Attempt creating missing intermediate directories.  */
742       if (make_directories (file_name, interdir_made) == 0 && *interdir_made)
743         return RECOVER_OK;
744       break;
745
746     default:
747       /* Just say we can't do anything about it...  */
748       break;
749     }
750
751   errno = e;
752   return RECOVER_NO;
753 }
754
755 /* Restore stat extended attributes (xattr) for FILE_NAME, using information
756    given in *ST.  Restore before extraction because they may affect file layout
757    (e.g. on Lustre distributed parallel filesystem - setting info about how many
758    servers is this file striped over, stripe size, mirror copies, etc.
759    in advance dramatically improves the following  performance of reading and
760    writing a file).  If not restoring permissions, invert the INVERT_PERMISSIONS
761    bits from the file's current permissions.  TYPEFLAG specifies the type of the
762    file.  FILE_CREATED indicates set_xattr has created the file */
763 static int
764 set_xattr (char const *file_name, struct tar_stat_info const *st,
765            mode_t invert_permissions, char typeflag, int *file_created)
766 {
767   int status = 0;
768
769 #ifdef HAVE_XATTRS
770   bool interdir_made = false;
771
772   if ((xattrs_option > 0) && st->xattr_map_size)
773     {
774       mode_t mode = current_stat_info.stat.st_mode & MODE_RWX & ~ current_umask;
775
776       do
777         status = mknodat (chdir_fd, file_name, mode ^ invert_permissions, 0);
778       while (status && maybe_recoverable ((char *)file_name, false,
779                                           &interdir_made));
780
781       xattrs_xattrs_set (st, file_name, typeflag, 0);
782       *file_created = 1;
783     }
784 #endif
785
786   return(status);
787 }
788
789 /* Fix the statuses of all directories whose statuses need fixing, and
790    which are not ancestors of FILE_NAME.  If AFTER_LINKS is
791    nonzero, do this for all such directories; otherwise, stop at the
792    first directory that is marked to be fixed up only after delayed
793    links are applied.  */
794 static void
795 apply_nonancestor_delayed_set_stat (char const *file_name, bool after_links)
796 {
797   size_t file_name_len = strlen (file_name);
798   bool check_for_renamed_directories = 0;
799
800   while (delayed_set_stat_head)
801     {
802       struct delayed_set_stat *data = delayed_set_stat_head;
803       bool skip_this_one = 0;
804       struct stat st;
805       mode_t current_mode = data->current_mode;
806       mode_t current_mode_mask = data->current_mode_mask;
807
808       check_for_renamed_directories |= data->after_links;
809
810       if (after_links < data->after_links
811           || (data->file_name_len < file_name_len
812               && file_name[data->file_name_len]
813               && (ISSLASH (file_name[data->file_name_len])
814                   || ISSLASH (file_name[data->file_name_len - 1]))
815               && memcmp (file_name, data->file_name, data->file_name_len) == 0))
816         break;
817
818       chdir_do (data->change_dir);
819
820       if (check_for_renamed_directories)
821         {
822           if (fstatat (chdir_fd, data->file_name, &st, data->atflag) != 0)
823             {
824               stat_error (data->file_name);
825               skip_this_one = 1;
826             }
827           else
828             {
829               current_mode = st.st_mode;
830               current_mode_mask = ALL_MODE_BITS;
831               if (! (st.st_dev == data->dev && st.st_ino == data->ino))
832                 {
833                   ERROR ((0, 0,
834                           _("%s: Directory renamed before its status could be extracted"),
835                           quotearg_colon (data->file_name)));
836                   skip_this_one = 1;
837                 }
838             }
839         }
840
841       if (! skip_this_one)
842         {
843           struct tar_stat_info sb;
844           sb.stat.st_mode = data->mode;
845           sb.stat.st_uid = data->uid;
846           sb.stat.st_gid = data->gid;
847           sb.atime = data->atime;
848           sb.mtime = data->mtime;
849           sb.cntx_name = data->cntx_name;
850           sb.acls_a_ptr = data->acls_a_ptr;
851           sb.acls_a_len = data->acls_a_len;
852           sb.acls_d_ptr = data->acls_d_ptr;
853           sb.acls_d_len = data->acls_d_len;
854           sb.xattr_map = data->xattr_map;
855           sb.xattr_map_size = data->xattr_map_size;
856           set_stat (data->file_name, &sb,
857                     -1, current_mode, current_mode_mask,
858                     DIRTYPE, data->interdir, data->atflag);
859         }
860
861       delayed_set_stat_head = data->next;
862       xheader_xattr_free (data->xattr_map, data->xattr_map_size);
863       free (data->cntx_name);
864       free (data->acls_a_ptr);
865       free (data->acls_d_ptr);
866       free (data);
867     }
868 }
869
870 \f
871 static bool
872 is_directory_link (const char *file_name)
873 {
874   struct stat st;
875   int e = errno;
876   int res;
877   
878   res = (fstatat (chdir_fd, file_name, &st, AT_SYMLINK_NOFOLLOW) == 0 &&
879          S_ISLNK (st.st_mode) &&
880          fstatat (chdir_fd, file_name, &st, 0) == 0 &&
881          S_ISDIR (st.st_mode));
882   errno = e;
883   return res;
884 }
885 \f
886 /* Extractor functions for various member types */
887
888 static int
889 extract_dir (char *file_name, int typeflag)
890 {
891   int status;
892   mode_t mode;
893   mode_t current_mode = 0;
894   mode_t current_mode_mask = 0;
895   int atflag = 0;
896   bool interdir_made = false;
897
898   /* Save 'root device' to avoid purging mount points. */
899   if (one_file_system_option && root_device == 0)
900     {
901       struct stat st;
902
903       if (fstatat (chdir_fd, ".", &st, 0) != 0)
904         stat_diag (".");
905       else
906         root_device = st.st_dev;
907     }
908
909   if (incremental_option)
910     /* Read the entry and delete files that aren't listed in the archive.  */
911     purge_directory (file_name);
912   else if (typeflag == GNUTYPE_DUMPDIR)
913     skip_member ();
914
915   /* If ownership or permissions will be restored later, create the
916      directory with restrictive permissions at first, so that in the
917      meantime processes owned by other users do not inadvertently
918      create files under this directory that inherit the wrong owner,
919      group, or permissions from the directory.  If not root, though,
920      make the directory writeable and searchable at first, so that
921      files can be created under it.  */
922   mode = ((current_stat_info.stat.st_mode
923            & (0 < same_owner_option || 0 < same_permissions_option
924               ? S_IRWXU
925               : MODE_RWX))
926           | (we_are_root ? 0 : MODE_WXUSR));
927
928   for (;;)
929     {
930       status = mkdirat (chdir_fd, file_name, mode);
931       if (status == 0)
932         {
933           current_mode = mode & ~ current_umask;
934           current_mode_mask = MODE_RWX;
935           atflag = AT_SYMLINK_NOFOLLOW;
936           break;
937         }
938
939       if (errno == EEXIST
940           && (interdir_made
941               || keep_directory_symlink_option
942               || old_files_option == DEFAULT_OLD_FILES
943               || old_files_option == OVERWRITE_OLD_FILES))
944         {
945           struct stat st;
946
947           if (keep_directory_symlink_option && is_directory_link (file_name))
948             return 0;
949           
950           if (deref_stat (file_name, &st) == 0)
951             {
952               current_mode = st.st_mode;
953               current_mode_mask = ALL_MODE_BITS;
954
955               if (S_ISDIR (current_mode))
956                 {
957                   if (interdir_made)
958                     {
959                       repair_delayed_set_stat (file_name, &st);
960                       return 0;
961                     }
962                   break;
963                 }
964             }
965           errno = EEXIST;
966         }
967
968       switch (maybe_recoverable (file_name, false, &interdir_made))
969         {
970         case RECOVER_OK:
971           continue;
972
973         case RECOVER_SKIP:
974           break;
975
976         case RECOVER_NO:
977           if (errno != EEXIST)
978             {
979               mkdir_error (file_name);
980               return 1;
981             }
982           break;
983         }
984       break;
985     }
986
987   if (status == 0
988       || old_files_option == DEFAULT_OLD_FILES
989       || old_files_option == OVERWRITE_OLD_FILES)
990     delay_set_stat (file_name, &current_stat_info,
991                     current_mode, current_mode_mask,
992                     current_stat_info.stat.st_mode, atflag);
993   return status;
994 }
995
996
997
998 static int
999 open_output_file (char const *file_name, int typeflag, mode_t mode,
1000                   int file_created, mode_t *current_mode,
1001                   mode_t *current_mode_mask)
1002 {
1003   int fd;
1004   bool overwriting_old_files = old_files_option == OVERWRITE_OLD_FILES;
1005   int openflag = (O_WRONLY | O_BINARY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK
1006                   | O_CREAT
1007                   | (overwriting_old_files
1008                      ? O_TRUNC | (dereference_option ? 0 : O_NOFOLLOW)
1009                      : O_EXCL));
1010
1011   /* File might be created in set_xattr. So clear O_EXCL to avoid open() fail */
1012   if (file_created)
1013     openflag = openflag & ~O_EXCL;
1014
1015   if (typeflag == CONTTYPE)
1016     {
1017       static int conttype_diagnosed;
1018
1019       if (!conttype_diagnosed)
1020         {
1021           conttype_diagnosed = 1;
1022           WARNOPT (WARN_CONTIGUOUS_CAST,
1023                    (0, 0, _("Extracting contiguous files as regular files")));
1024         }
1025     }
1026
1027   /* If O_NOFOLLOW is needed but does not work, check for a symlink
1028      separately.  There's a race condition, but that cannot be avoided
1029      on hosts lacking O_NOFOLLOW.  */
1030   if (! HAVE_WORKING_O_NOFOLLOW
1031       && overwriting_old_files && ! dereference_option)
1032     {
1033       struct stat st;
1034       if (fstatat (chdir_fd, file_name, &st, AT_SYMLINK_NOFOLLOW) == 0
1035           && S_ISLNK (st.st_mode))
1036         {
1037           errno = ELOOP;
1038           return -1;
1039         }
1040     }
1041
1042   fd = openat (chdir_fd, file_name, openflag, mode);
1043   if (0 <= fd)
1044     {
1045       if (overwriting_old_files)
1046         {
1047           struct stat st;
1048           if (fstat (fd, &st) != 0)
1049             {
1050               int e = errno;
1051               close (fd);
1052               errno = e;
1053               return -1;
1054             }
1055           if (! S_ISREG (st.st_mode))
1056             {
1057               close (fd);
1058               errno = EEXIST;
1059               return -1;
1060             }
1061           *current_mode = st.st_mode;
1062           *current_mode_mask = ALL_MODE_BITS;
1063         }
1064       else
1065         {
1066           *current_mode = mode & ~ current_umask;
1067           *current_mode_mask = MODE_RWX;
1068         }
1069     }
1070
1071   return fd;
1072 }
1073
1074 static int
1075 extract_file (char *file_name, int typeflag)
1076 {
1077   int fd;
1078   off_t size;
1079   union block *data_block;
1080   int status;
1081   size_t count;
1082   size_t written;
1083   bool interdir_made = false;
1084   mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1085                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1086   mode_t invert_permissions = 0 < same_owner_option ? mode & (S_IRWXG | S_IRWXO)
1087                                                     : 0;
1088   mode_t current_mode = 0;
1089   mode_t current_mode_mask = 0;
1090
1091   if (to_stdout_option)
1092     fd = STDOUT_FILENO;
1093   else if (to_command_option)
1094     {
1095       fd = sys_exec_command (file_name, 'f', &current_stat_info);
1096       if (fd < 0)
1097         {
1098           skip_member ();
1099           return 0;
1100         }
1101     }
1102   else
1103     {
1104       int file_created = 0;
1105       if (set_xattr (file_name, &current_stat_info, invert_permissions,
1106                      typeflag, &file_created))
1107         {
1108           skip_member ();
1109           open_error (file_name);
1110           return 1;
1111         }
1112
1113       while ((fd = open_output_file (file_name, typeflag, mode,
1114                                      file_created, &current_mode,
1115                                      &current_mode_mask))
1116              < 0)
1117         {
1118           int recover = maybe_recoverable (file_name, true, &interdir_made);
1119           if (recover != RECOVER_OK)
1120             {
1121               skip_member ();
1122               if (recover == RECOVER_SKIP)
1123                 return 0;
1124               open_error (file_name);
1125               return 1;
1126             }
1127         }
1128     }
1129
1130   mv_begin_read (&current_stat_info);
1131   if (current_stat_info.is_sparse)
1132     sparse_extract_file (fd, &current_stat_info, &size);
1133   else
1134     for (size = current_stat_info.stat.st_size; size > 0; )
1135       {
1136         mv_size_left (size);
1137
1138         /* Locate data, determine max length writeable, write it,
1139            block that we have used the data, then check if the write
1140            worked.  */
1141
1142         data_block = find_next_block ();
1143         if (! data_block)
1144           {
1145             ERROR ((0, 0, _("Unexpected EOF in archive")));
1146             break;              /* FIXME: What happens, then?  */
1147           }
1148
1149         written = available_space_after (data_block);
1150
1151         if (written > size)
1152           written = size;
1153         errno = 0;
1154         count = blocking_write (fd, data_block->buffer, written);
1155         size -= written;
1156
1157         set_next_block_after ((union block *)
1158                               (data_block->buffer + written - 1));
1159         if (count != written)
1160           {
1161             if (!to_command_option)
1162               write_error_details (file_name, count, written);
1163             /* FIXME: shouldn't we restore from backup? */
1164             break;
1165           }
1166       }
1167
1168   skip_file (size);
1169
1170   mv_end ();
1171
1172   /* If writing to stdout, don't try to do anything to the filename;
1173      it doesn't exist, or we don't want to touch it anyway.  */
1174
1175   if (to_stdout_option)
1176     return 0;
1177
1178   if (! to_command_option)
1179     set_stat (file_name, &current_stat_info, fd,
1180               current_mode, current_mode_mask, typeflag, false,
1181               (old_files_option == OVERWRITE_OLD_FILES
1182                ? 0 : AT_SYMLINK_NOFOLLOW));
1183
1184   status = close (fd);
1185   if (status < 0)
1186     close_error (file_name);
1187
1188   if (to_command_option)
1189     sys_wait_command ();
1190
1191   return status;
1192 }
1193
1194 /* Create a placeholder file with name FILE_NAME, which will be
1195    replaced after other extraction is done by a symbolic link if
1196    IS_SYMLINK is true, and by a hard link otherwise.  Set
1197    *INTERDIR_MADE if an intermediate directory is made in the
1198    process.  */
1199
1200 static int
1201 create_placeholder_file (char *file_name, bool is_symlink, bool *interdir_made)
1202 {
1203   int fd;
1204   struct stat st;
1205
1206   while ((fd = openat (chdir_fd, file_name, O_WRONLY | O_CREAT | O_EXCL, 0)) < 0)
1207     {
1208       switch (maybe_recoverable (file_name, false, interdir_made))
1209         {
1210         case RECOVER_OK:
1211           continue;
1212
1213         case RECOVER_SKIP:
1214           return 0;
1215
1216         case RECOVER_NO:
1217           open_error (file_name);
1218           return -1;
1219         }
1220       }
1221
1222   if (fstat (fd, &st) != 0)
1223     {
1224       stat_error (file_name);
1225       close (fd);
1226     }
1227   else if (close (fd) != 0)
1228     close_error (file_name);
1229   else
1230     {
1231       struct delayed_set_stat *h;
1232       struct delayed_link *p =
1233         xmalloc (offsetof (struct delayed_link, target)
1234                  + strlen (current_stat_info.link_name)
1235                  + 1);
1236       p->next = delayed_link_head;
1237       delayed_link_head = p;
1238       p->dev = st.st_dev;
1239       p->ino = st.st_ino;
1240       p->birthtime = get_stat_birthtime (&st);
1241       p->is_symlink = is_symlink;
1242       if (is_symlink)
1243         {
1244           p->mode = current_stat_info.stat.st_mode;
1245           p->uid = current_stat_info.stat.st_uid;
1246           p->gid = current_stat_info.stat.st_gid;
1247           p->atime = current_stat_info.atime;
1248           p->mtime = current_stat_info.mtime;
1249         }
1250       p->change_dir = chdir_current;
1251       p->sources = xmalloc (offsetof (struct string_list, string)
1252                             + strlen (file_name) + 1);
1253       p->sources->next = 0;
1254       strcpy (p->sources->string, file_name);
1255       p->cntx_name = NULL;
1256       assign_string (&p->cntx_name, current_stat_info.cntx_name);
1257       p->acls_a_ptr = NULL;
1258       p->acls_a_len = 0;
1259       p->acls_d_ptr = NULL;
1260       p->acls_d_len = 0;
1261       xheader_xattr_copy (&current_stat_info, &p->xattr_map, &p->xattr_map_size);
1262       strcpy (p->target, current_stat_info.link_name);
1263
1264       h = delayed_set_stat_head;
1265       if (h && ! h->after_links
1266           && strncmp (file_name, h->file_name, h->file_name_len) == 0
1267           && ISSLASH (file_name[h->file_name_len])
1268           && (last_component (file_name) == file_name + h->file_name_len + 1))
1269         mark_after_links (h);
1270
1271       return 0;
1272     }
1273
1274   return -1;
1275 }
1276
1277 static int
1278 extract_link (char *file_name, int typeflag)
1279 {
1280   bool interdir_made = false;
1281   char const *link_name;
1282   int rc;
1283
1284   link_name = current_stat_info.link_name;
1285
1286   if (! absolute_names_option && contains_dot_dot (link_name))
1287     return create_placeholder_file (file_name, false, &interdir_made);
1288
1289   do
1290     {
1291       struct stat st1, st2;
1292       int e;
1293       int status = linkat (chdir_fd, link_name, chdir_fd, file_name, 0);
1294       e = errno;
1295
1296       if (status == 0)
1297         {
1298           struct delayed_link *ds = delayed_link_head;
1299           if (ds
1300               && fstatat (chdir_fd, link_name, &st1, AT_SYMLINK_NOFOLLOW) == 0)
1301             for (; ds; ds = ds->next)
1302               if (ds->change_dir == chdir_current
1303                   && ds->dev == st1.st_dev
1304                   && ds->ino == st1.st_ino
1305                   && (timespec_cmp (ds->birthtime, get_stat_birthtime (&st1))
1306                       == 0))
1307                 {
1308                   struct string_list *p =  xmalloc (offsetof (struct string_list, string)
1309                                                     + strlen (file_name) + 1);
1310                   strcpy (p->string, file_name);
1311                   p->next = ds->sources;
1312                   ds->sources = p;
1313                   break;
1314                 }
1315           return 0;
1316         }
1317       else if ((e == EEXIST && strcmp (link_name, file_name) == 0)
1318                || ((fstatat (chdir_fd, link_name, &st1, AT_SYMLINK_NOFOLLOW)
1319                     == 0)
1320                    && (fstatat (chdir_fd, file_name, &st2, AT_SYMLINK_NOFOLLOW)
1321                        == 0)
1322                    && st1.st_dev == st2.st_dev
1323                    && st1.st_ino == st2.st_ino))
1324         return 0;
1325
1326       errno = e;
1327     }
1328   while ((rc = maybe_recoverable (file_name, false, &interdir_made))
1329          == RECOVER_OK);
1330
1331   if (rc == RECOVER_SKIP)
1332     return 0;
1333   if (!(incremental_option && errno == EEXIST))
1334     {
1335       link_error (link_name, file_name);
1336       return 1;
1337     }
1338   return 0;
1339 }
1340
1341 static int
1342 extract_symlink (char *file_name, int typeflag)
1343 {
1344 #ifdef HAVE_SYMLINK
1345   bool interdir_made = false;
1346
1347   if (! absolute_names_option
1348       && (IS_ABSOLUTE_FILE_NAME (current_stat_info.link_name)
1349           || contains_dot_dot (current_stat_info.link_name)))
1350     return create_placeholder_file (file_name, true, &interdir_made);
1351
1352   while (symlinkat (current_stat_info.link_name, chdir_fd, file_name) != 0)
1353     switch (maybe_recoverable (file_name, false, &interdir_made))
1354       {
1355       case RECOVER_OK:
1356         continue;
1357
1358       case RECOVER_SKIP:
1359         return 0;
1360
1361       case RECOVER_NO:
1362         symlink_error (current_stat_info.link_name, file_name);
1363         return -1;
1364       }
1365
1366   set_stat (file_name, &current_stat_info, -1, 0, 0,
1367             SYMTYPE, false, AT_SYMLINK_NOFOLLOW);
1368   return 0;
1369
1370 #else
1371   static int warned_once;
1372
1373   if (!warned_once)
1374     {
1375       warned_once = 1;
1376       WARNOPT (WARN_SYMLINK_CAST,
1377                (0, 0,
1378                 _("Attempting extraction of symbolic links as hard links")));
1379     }
1380   return extract_link (file_name, typeflag);
1381 #endif
1382 }
1383
1384 #if S_IFCHR || S_IFBLK
1385 static int
1386 extract_node (char *file_name, int typeflag)
1387 {
1388   bool interdir_made = false;
1389   mode_t mode = (current_stat_info.stat.st_mode & (MODE_RWX | S_IFBLK | S_IFCHR)
1390                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1391
1392   while (mknodat (chdir_fd, file_name, mode, current_stat_info.stat.st_rdev)
1393          != 0)
1394     switch (maybe_recoverable (file_name, false, &interdir_made))
1395       {
1396       case RECOVER_OK:
1397         continue;
1398
1399       case RECOVER_SKIP:
1400         return 0;
1401
1402       case RECOVER_NO:
1403         mknod_error (file_name);
1404         return -1;
1405       }
1406
1407   set_stat (file_name, &current_stat_info, -1,
1408             mode & ~ current_umask, MODE_RWX,
1409             typeflag, false, AT_SYMLINK_NOFOLLOW);
1410   return 0;
1411 }
1412 #endif
1413
1414 #if HAVE_MKFIFO || defined mkfifo
1415 static int
1416 extract_fifo (char *file_name, int typeflag)
1417 {
1418   bool interdir_made = false;
1419   mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1420                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1421
1422   while (mkfifoat (chdir_fd, file_name, mode) != 0)
1423     switch (maybe_recoverable (file_name, false, &interdir_made))
1424       {
1425       case RECOVER_OK:
1426         continue;
1427
1428       case RECOVER_SKIP:
1429         return 0;
1430
1431       case RECOVER_NO:
1432         mkfifo_error (file_name);
1433         return -1;
1434       }
1435
1436   set_stat (file_name, &current_stat_info, -1,
1437             mode & ~ current_umask, MODE_RWX,
1438             typeflag, false, AT_SYMLINK_NOFOLLOW);
1439   return 0;
1440 }
1441 #endif
1442
1443 static int
1444 extract_volhdr (char *file_name, int typeflag)
1445 {
1446   skip_member ();
1447   return 0;
1448 }
1449
1450 static int
1451 extract_failure (char *file_name, int typeflag)
1452 {
1453   return 1;
1454 }
1455
1456 static int
1457 extract_skip (char *file_name, int typeflag)
1458 {
1459   skip_member ();
1460   return 0;
1461 }
1462
1463 typedef int (*tar_extractor_t) (char *file_name, int typeflag);
1464
1465 \f
1466
1467 /* Prepare to extract a file. Find extractor function.
1468    Return zero if extraction should not proceed.  */
1469
1470 static int
1471 prepare_to_extract (char const *file_name, int typeflag, tar_extractor_t *fun)
1472 {
1473   int rc = 1;
1474
1475   if (EXTRACT_OVER_PIPE)
1476     rc = 0;
1477
1478   /* Select the extractor */
1479   switch (typeflag)
1480     {
1481     case GNUTYPE_SPARSE:
1482       *fun = extract_file;
1483       rc = 1;
1484       break;
1485
1486     case AREGTYPE:
1487     case REGTYPE:
1488     case CONTTYPE:
1489       /* Appears to be a file.  But BSD tar uses the convention that a slash
1490          suffix means a directory.  */
1491       if (current_stat_info.had_trailing_slash)
1492         *fun = extract_dir;
1493       else
1494         {
1495           *fun = extract_file;
1496           rc = 1;
1497         }
1498       break;
1499
1500     case SYMTYPE:
1501       *fun = extract_symlink;
1502       break;
1503
1504     case LNKTYPE:
1505       *fun = extract_link;
1506       break;
1507
1508 #if S_IFCHR
1509     case CHRTYPE:
1510       current_stat_info.stat.st_mode |= S_IFCHR;
1511       *fun = extract_node;
1512       break;
1513 #endif
1514
1515 #if S_IFBLK
1516     case BLKTYPE:
1517       current_stat_info.stat.st_mode |= S_IFBLK;
1518       *fun = extract_node;
1519       break;
1520 #endif
1521
1522 #if HAVE_MKFIFO || defined mkfifo
1523     case FIFOTYPE:
1524       *fun = extract_fifo;
1525       break;
1526 #endif
1527
1528     case DIRTYPE:
1529     case GNUTYPE_DUMPDIR:
1530       *fun = extract_dir;
1531       if (current_stat_info.is_dumpdir)
1532         delay_directory_restore_option = true;
1533       break;
1534
1535     case GNUTYPE_VOLHDR:
1536       *fun = extract_volhdr;
1537       break;
1538
1539     case GNUTYPE_MULTIVOL:
1540       ERROR ((0, 0,
1541               _("%s: Cannot extract -- file is continued from another volume"),
1542               quotearg_colon (current_stat_info.file_name)));
1543       *fun = extract_skip;
1544       break;
1545
1546     case GNUTYPE_LONGNAME:
1547     case GNUTYPE_LONGLINK:
1548       ERROR ((0, 0, _("Unexpected long name header")));
1549       *fun = extract_failure;
1550       break;
1551
1552     default:
1553       WARNOPT (WARN_UNKNOWN_CAST,
1554                (0, 0,
1555                 _("%s: Unknown file type '%c', extracted as normal file"),
1556                 quotearg_colon (file_name), typeflag));
1557       *fun = extract_file;
1558     }
1559
1560   /* Determine whether the extraction should proceed */
1561   if (rc == 0)
1562     return 0;
1563
1564   switch (old_files_option)
1565     {
1566     case UNLINK_FIRST_OLD_FILES:
1567       if (!remove_any_file (file_name,
1568                             recursive_unlink_option ? RECURSIVE_REMOVE_OPTION
1569                                                       : ORDINARY_REMOVE_OPTION)
1570           && errno && errno != ENOENT)
1571         {
1572           unlink_error (file_name);
1573           return 0;
1574         }
1575       break;
1576
1577     case KEEP_NEWER_FILES:
1578       if (file_newer_p (file_name, 0, &current_stat_info))
1579         {
1580           WARNOPT (WARN_IGNORE_NEWER,
1581                    (0, 0, _("Current %s is newer or same age"),
1582                     quote (file_name)));
1583           return 0;
1584         }
1585       break;
1586
1587     default:
1588       break;
1589     }
1590
1591   return 1;
1592 }
1593
1594 /* Extract a file from the archive.  */
1595 void
1596 extract_archive (void)
1597 {
1598   char typeflag;
1599   tar_extractor_t fun;
1600
1601   fatal_exit_hook = extract_finish;
1602
1603   set_next_block_after (current_header);
1604
1605   if (!current_stat_info.file_name[0]
1606       || (interactive_option
1607           && !confirm ("extract", current_stat_info.file_name)))
1608     {
1609       skip_member ();
1610       return;
1611     }
1612
1613   /* Print the block from current_header and current_stat.  */
1614   if (verbose_option)
1615     print_header (&current_stat_info, current_header, -1);
1616
1617   /* Restore stats for all non-ancestor directories, unless
1618      it is an incremental archive.
1619      (see NOTICE in the comment to delay_set_stat above) */
1620   if (!delay_directory_restore_option)
1621     {
1622       int dir = chdir_current;
1623       apply_nonancestor_delayed_set_stat (current_stat_info.file_name, 0);
1624       chdir_do (dir);
1625     }
1626
1627   /* Take a safety backup of a previously existing file.  */
1628
1629   if (backup_option)
1630     if (!maybe_backup_file (current_stat_info.file_name, 0))
1631       {
1632         int e = errno;
1633         ERROR ((0, e, _("%s: Was unable to backup this file"),
1634                 quotearg_colon (current_stat_info.file_name)));
1635         skip_member ();
1636         return;
1637       }
1638
1639   /* Extract the archive entry according to its type.  */
1640   /* KLUDGE */
1641   typeflag = sparse_member_p (&current_stat_info) ?
1642                   GNUTYPE_SPARSE : current_header->header.typeflag;
1643
1644   if (prepare_to_extract (current_stat_info.file_name, typeflag, &fun))
1645     {
1646       if (fun && (*fun) (current_stat_info.file_name, typeflag)
1647           && backup_option)
1648         undo_last_backup ();
1649     }
1650   else
1651     skip_member ();
1652
1653 }
1654
1655 /* Extract the links whose final extraction were delayed.  */
1656 static void
1657 apply_delayed_links (void)
1658 {
1659   struct delayed_link *ds;
1660
1661   for (ds = delayed_link_head; ds; )
1662     {
1663       struct string_list *sources = ds->sources;
1664       char const *valid_source = 0;
1665
1666       chdir_do (ds->change_dir);
1667
1668       for (sources = ds->sources; sources; sources = sources->next)
1669         {
1670           char const *source = sources->string;
1671           struct stat st;
1672
1673           /* Make sure the placeholder file is still there.  If not,
1674              don't create a link, as the placeholder was probably
1675              removed by a later extraction.  */
1676           if (fstatat (chdir_fd, source, &st, AT_SYMLINK_NOFOLLOW) == 0
1677               && st.st_dev == ds->dev
1678               && st.st_ino == ds->ino
1679               && timespec_cmp (get_stat_birthtime (&st), ds->birthtime) == 0)
1680             {
1681               /* Unlink the placeholder, then create a hard link if possible,
1682                  a symbolic link otherwise.  */
1683               if (unlinkat (chdir_fd, source, 0) != 0)
1684                 unlink_error (source);
1685               else if (valid_source
1686                        && (linkat (chdir_fd, valid_source, chdir_fd, source, 0)
1687                            == 0))
1688                 ;
1689               else if (!ds->is_symlink)
1690                 {
1691                   if (linkat (chdir_fd, ds->target, chdir_fd, source, 0) != 0)
1692                     link_error (ds->target, source);
1693                 }
1694               else if (symlinkat (ds->target, chdir_fd, source) != 0)
1695                 symlink_error (ds->target, source);
1696               else
1697                 {
1698                   struct tar_stat_info st1;
1699                   st1.stat.st_mode = ds->mode;
1700                   st1.stat.st_uid = ds->uid;
1701                   st1.stat.st_gid = ds->gid;
1702                   st1.atime = ds->atime;
1703                   st1.mtime = ds->mtime;
1704                   st1.cntx_name = ds->cntx_name;
1705                   st1.acls_a_ptr = ds->acls_a_ptr;
1706                   st1.acls_a_len = ds->acls_a_len;
1707                   st1.acls_d_ptr = ds->acls_d_ptr;
1708                   st1.acls_d_len = ds->acls_d_len;
1709                   st1.xattr_map = ds->xattr_map;
1710                   st1.xattr_map_size = ds->xattr_map_size;
1711                   set_stat (source, &st1, -1, 0, 0, SYMTYPE,
1712                             false, AT_SYMLINK_NOFOLLOW);
1713                   valid_source = source;
1714                 }
1715             }
1716         }
1717
1718       for (sources = ds->sources; sources; )
1719         {
1720           struct string_list *next = sources->next;
1721           free (sources);
1722           sources = next;
1723         }
1724
1725    xheader_xattr_free (ds->xattr_map, ds->xattr_map_size);
1726    free (ds->cntx_name);
1727
1728       {
1729         struct delayed_link *next = ds->next;
1730         free (ds);
1731         ds = next;
1732       }
1733     }
1734
1735   delayed_link_head = 0;
1736 }
1737
1738 /* Finish the extraction of an archive.  */
1739 void
1740 extract_finish (void)
1741 {
1742   /* First, fix the status of ordinary directories that need fixing.  */
1743   apply_nonancestor_delayed_set_stat ("", 0);
1744
1745   /* Then, apply delayed links, so that they don't affect delayed
1746      directory status-setting for ordinary directories.  */
1747   apply_delayed_links ();
1748
1749   /* Finally, fix the status of directories that are ancestors
1750      of delayed links.  */
1751   apply_nonancestor_delayed_set_stat ("", 1);
1752 }
1753
1754 bool
1755 rename_directory (char *src, char *dst)
1756 {
1757   if (renameat (chdir_fd, src, chdir_fd, dst) != 0)
1758     {
1759       int e = errno;
1760       bool interdir_made;
1761
1762       switch (e)
1763         {
1764         case ENOENT:
1765           if (make_directories (dst, &interdir_made) == 0)
1766             {
1767               if (renameat (chdir_fd, src, chdir_fd, dst) == 0)
1768                 return true;
1769               e = errno;
1770             }
1771           break;
1772
1773         case EXDEV:
1774           /* FIXME: Fall back to recursive copying */
1775
1776         default:
1777           break;
1778         }
1779
1780       ERROR ((0, e, _("Cannot rename %s to %s"),
1781               quote_n (0, src),
1782               quote_n (1, dst)));
1783       return false;
1784     }
1785   return true;
1786 }