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