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