]> git.cworth.org Git - tar/blob - src/extract.c
Preserve timestamp of symlinks when extracting (if utimensat available)
[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 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 <utimens.h>
25 #include <errno.h>
26 #include <xgetcwd.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 /* Status of the permissions of a file that we are extracting.  */
35 enum permstatus
36 {
37   /* This file may have existed already; its permissions are unknown.  */
38   UNKNOWN_PERMSTATUS,
39
40   /* This file was created using the permissions from the archive,
41      except with S_IRWXG | S_IRWXO masked out if 0 < same_owner_option.  */
42   ARCHIVED_PERMSTATUS,
43
44   /* This is an intermediate directory; the archive did not specify
45      its permissions.  */
46   INTERDIR_PERMSTATUS
47 };
48
49 /* List of directories whose statuses we need to extract after we've
50    finished extracting their subsidiary files.  If you consider each
51    contiguous subsequence of elements of the form [D]?[^D]*, where [D]
52    represents an element where AFTER_LINKS is nonzero and [^D]
53    represents an element where AFTER_LINKS is zero, then the head
54    of the subsequence has the longest name, and each non-head element
55    in the prefix is an ancestor (in the directory hierarchy) of the
56    preceding element.  */
57
58 struct delayed_set_stat
59   {
60     struct delayed_set_stat *next;
61     dev_t dev;
62     ino_t ino;
63     mode_t mode;
64     uid_t uid;
65     gid_t gid;
66     struct timespec atime;
67     struct timespec mtime;
68     size_t file_name_len;
69     mode_t invert_permissions;
70     enum permstatus permstatus;
71     bool after_links;
72     char file_name[1];
73   };
74
75 static struct delayed_set_stat *delayed_set_stat_head;
76
77 /* List of links whose creation we have delayed.  */
78 struct delayed_link
79   {
80     /* The next delayed link in the list.  */
81     struct delayed_link *next;
82
83     /* The device, inode number and last-modified time of the placeholder.  */
84     dev_t dev;
85     ino_t ino;
86     struct timespec mtime;
87
88     /* True if the link is symbolic.  */
89     bool is_symlink;
90
91     /* The desired owner and group of the link, if it is a symlink.  */
92     uid_t uid;
93     gid_t gid;
94
95     /* A list of sources for this link.  The sources are all to be
96        hard-linked together.  */
97     struct string_list *sources;
98
99     /* The desired target of the desired link.  */
100     char target[1];
101   };
102
103 static struct delayed_link *delayed_link_head;
104
105 struct string_list
106   {
107     struct string_list *next;
108     char string[1];
109   };
110
111 /*  Set up to extract files.  */
112 void
113 extr_init (void)
114 {
115   we_are_root = geteuid () == 0;
116   same_permissions_option += we_are_root;
117   same_owner_option += we_are_root;
118
119   /* Option -p clears the kernel umask, so it does not affect proper
120      restoration of file permissions.  New intermediate directories will
121      comply with umask at start of program.  */
122
123   newdir_umask = umask (0);
124   if (0 < same_permissions_option)
125     current_umask = 0;
126   else
127     {
128       umask (newdir_umask);     /* restore the kernel umask */
129       current_umask = newdir_umask;
130     }
131 }
132
133 /* If restoring permissions, restore the mode for FILE_NAME from
134    information given in *STAT_INFO (where *CUR_INFO gives
135    the current status if CUR_INFO is nonzero); otherwise invert the
136    INVERT_PERMISSIONS bits from the file's current permissions.
137    PERMSTATUS specifies the status of the file's permissions.
138    TYPEFLAG specifies the type of the file.  */
139 static void
140 set_mode (char const *file_name,
141           struct stat const *stat_info,
142           struct stat const *cur_info,
143           mode_t invert_permissions, enum permstatus permstatus,
144           char typeflag)
145 {
146   mode_t mode;
147
148   if (0 < same_permissions_option
149       && permstatus != INTERDIR_PERMSTATUS)
150     {
151       mode = stat_info->st_mode;
152
153       /* If we created the file and it has a mode that we set already
154          with O_CREAT, then its mode is often set correctly already.
155          But if we are changing ownership, the mode's group and and
156          other permission bits were omitted originally, so it's less
157          likely that the mode is OK now.  Also, on many hosts, some
158          directories inherit the setgid bits from their parents, so we
159          we must set directories' modes explicitly.  */
160       if ((permstatus == ARCHIVED_PERMSTATUS
161            && ! (mode & ~ (0 < same_owner_option ? S_IRWXU : MODE_RWX)))
162           && typeflag != DIRTYPE
163           && typeflag != GNUTYPE_DUMPDIR)
164         return;
165     }
166   else if (! invert_permissions)
167     return;
168   else
169     {
170       /* We must inspect a directory's current permissions, since the
171          directory may have inherited its setgid bit from its parent.
172
173          INVERT_PERMISSIONS happens to be nonzero only for directories
174          that we created, so there's no point optimizing this code for
175          other cases.  */
176       struct stat st;
177       if (! cur_info)
178         {
179           if (stat (file_name, &st) != 0)
180             {
181               stat_error (file_name);
182               return;
183             }
184           cur_info = &st;
185         }
186       mode = cur_info->st_mode ^ invert_permissions;
187     }
188
189   if (chmod (file_name, mode) != 0)
190     chmod_error_details (file_name, mode);
191 }
192
193 /* Check time after successfully setting FILE_NAME's time stamp to T.  */
194 static void
195 check_time (char const *file_name, struct timespec t)
196 {
197   if (t.tv_sec <= 0)
198     WARN ((0, 0, _("%s: implausibly old time stamp %s"),
199            file_name, tartime (t, true)));
200   else if (timespec_cmp (volume_start_time, t) < 0)
201     {
202       struct timespec now;
203       gettime (&now);
204       if (timespec_cmp (now, t) < 0)
205         {
206           char buf[TIMESPEC_STRSIZE_BOUND];
207           struct timespec diff;
208           diff.tv_sec = t.tv_sec - now.tv_sec;
209           diff.tv_nsec = t.tv_nsec - now.tv_nsec;
210           if (diff.tv_nsec < 0)
211             {
212               diff.tv_nsec += BILLION;
213               diff.tv_sec--;
214             }
215           WARN ((0, 0, _("%s: time stamp %s is %s s in the future"),
216                  file_name, tartime (t, true), code_timespec (diff, buf)));
217         }
218     }
219 }
220
221 /* Restore stat attributes (owner, group, mode and times) for
222    FILE_NAME, using information given in *ST.
223    If CUR_INFO is nonzero, *CUR_INFO is the
224    file's current status.
225    If not restoring permissions, invert the
226    INVERT_PERMISSIONS bits from the file's current permissions.
227    PERMSTATUS specifies the status of the file's permissions.
228    TYPEFLAG specifies the type of the file.  */
229
230 /* FIXME: About proper restoration of symbolic link attributes, we still do
231    not have it right.  Pretesters' reports tell us we need further study and
232    probably more configuration.  For now, just use lchown if it exists, and
233    punt for the rest.  Sigh!  */
234
235 static void
236 set_stat (char const *file_name,
237           struct tar_stat_info const *st,
238           struct stat const *cur_info,
239           mode_t invert_permissions, enum permstatus permstatus,
240           char typeflag)
241 {
242   /* We do the utime before the chmod because some versions of utime are
243      broken and trash the modes of the file.  */
244
245   if (! touch_option && permstatus != INTERDIR_PERMSTATUS)
246     {
247       /* We set the accessed time to `now', which is really the time we
248          started extracting files, unless incremental_option is used, in
249          which case .st_atime is used.  */
250
251       /* FIXME: incremental_option should set ctime too, but how?  */
252
253       struct timespec ts[2];
254       if (incremental_option)
255         ts[0] = st->atime;
256       else
257         ts[0] = start_time;
258       ts[1] = st->mtime;
259
260       if (utimens (file_name, ts, typeflag == SYMTYPE) != 0)
261         utime_error (file_name);
262       else
263       {
264         check_time (file_name, ts[0]);
265         check_time (file_name, ts[1]);
266       }
267     }
268
269   /* Some systems allow non-root users to give files away.  Once this
270      done, it is not possible anymore to change file permissions.
271      However, setting file permissions now would be incorrect, since
272      they would apply to the wrong user, and there would be a race
273      condition.  So, don't use systems that allow non-root users to
274      give files away.  */
275
276   if (0 < same_owner_option && permstatus != INTERDIR_PERMSTATUS)
277     {
278       /* When lchown exists, it should be used to change the attributes of
279          the symbolic link itself.  In this case, a mere chown would change
280          the attributes of the file the symbolic link is pointing to, and
281          should be avoided.  */
282       int chown_result = 1;
283
284       if (typeflag == SYMTYPE)
285         {
286 #if HAVE_LCHOWN
287           chown_result = lchown (file_name, st->stat.st_uid, st->stat.st_gid);
288 #endif
289         }
290       else
291         {
292           chown_result = chown (file_name, st->stat.st_uid, st->stat.st_gid);
293         }
294
295       if (chown_result == 0)
296         {
297           /* Changing the owner can flip st_mode bits in some cases, so
298              ignore cur_info if it might be obsolete now.  */
299           if (cur_info
300               && cur_info->st_mode & S_IXUGO
301               && cur_info->st_mode & (S_ISUID | S_ISGID))
302             cur_info = NULL;
303         }
304       else if (chown_result < 0)
305         chown_error_details (file_name,
306                              st->stat.st_uid, st->stat.st_gid);
307     }
308
309   if (typeflag != SYMTYPE)
310     set_mode (file_name, &st->stat, cur_info,
311               invert_permissions, permstatus, typeflag);
312 }
313
314 /* Remember to restore stat attributes (owner, group, mode and times)
315    for the directory FILE_NAME, using information given in *ST,
316    once we stop extracting files into that directory.
317    If not restoring permissions, remember to invert the
318    INVERT_PERMISSIONS bits from the file's current permissions.
319    PERMSTATUS specifies the status of the file's permissions.
320
321    NOTICE: this works only if the archive has usual member order, i.e.
322    directory, then the files in that directory. Incremental archive have
323    somewhat reversed order: first go subdirectories, then all other
324    members. To help cope with this case the variable
325    delay_directory_restore_option is set by prepare_to_extract.
326
327    If an archive was explicitely created so that its member order is
328    reversed, some directory timestamps can be restored incorrectly,
329    e.g.:
330        tar --no-recursion -cf archive dir dir/file1 foo dir/file2
331 */
332 static void
333 delay_set_stat (char const *file_name, struct tar_stat_info const *st,
334                 mode_t invert_permissions, enum permstatus permstatus)
335 {
336   size_t file_name_len = strlen (file_name);
337   struct delayed_set_stat *data =
338     xmalloc (offsetof (struct delayed_set_stat, file_name)
339              + file_name_len + 1);
340   data->next = delayed_set_stat_head;
341   data->dev = st->stat.st_dev;
342   data->ino = st->stat.st_ino;
343   data->mode = st->stat.st_mode;
344   data->uid = st->stat.st_uid;
345   data->gid = st->stat.st_gid;
346   data->atime = st->atime;
347   data->mtime = st->mtime;
348   data->file_name_len = file_name_len;
349   data->invert_permissions = invert_permissions;
350   data->permstatus = permstatus;
351   data->after_links = 0;
352   strcpy (data->file_name, file_name);
353   delayed_set_stat_head = data;
354 }
355
356 /* Update the delayed_set_stat info for an intermediate directory
357    created within the file name of DIR.  The intermediate directory turned
358    out to be the same as this directory, e.g. due to ".." or symbolic
359    links.  *DIR_STAT_INFO is the status of the directory.  */
360 static void
361 repair_delayed_set_stat (char const *dir,
362                          struct stat const *dir_stat_info)
363 {
364   struct delayed_set_stat *data;
365   for (data = delayed_set_stat_head;  data;  data = data->next)
366     {
367       struct stat st;
368       if (stat (data->file_name, &st) != 0)
369         {
370           stat_error (data->file_name);
371           return;
372         }
373
374       if (st.st_dev == dir_stat_info->st_dev
375           && st.st_ino == dir_stat_info->st_ino)
376         {
377           data->dev = current_stat_info.stat.st_dev;
378           data->ino = current_stat_info.stat.st_ino;
379           data->mode = current_stat_info.stat.st_mode;
380           data->uid = current_stat_info.stat.st_uid;
381           data->gid = current_stat_info.stat.st_gid;
382           data->atime = current_stat_info.atime;
383           data->mtime = current_stat_info.mtime;
384           data->invert_permissions =
385             ((current_stat_info.stat.st_mode ^ st.st_mode)
386              & MODE_RWX & ~ current_umask);
387           data->permstatus = ARCHIVED_PERMSTATUS;
388           return;
389         }
390     }
391
392   ERROR ((0, 0, _("%s: Unexpected inconsistency when making directory"),
393           quotearg_colon (dir)));
394 }
395
396 /* After a file/link/directory creation has failed, see if
397    it's because some required directory was not present, and if so,
398    create all required directories.  Return non-zero if a directory
399    was created.  */
400 static int
401 make_directories (char *file_name)
402 {
403   char *cursor0 = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
404   char *cursor;                 /* points into the file name */
405   int did_something = 0;        /* did we do anything yet? */
406   int mode;
407   int invert_permissions;
408   int status;
409
410   for (cursor = cursor0; *cursor; cursor++)
411     {
412       if (! ISSLASH (*cursor))
413         continue;
414
415       /* Avoid mkdir of empty string, if leading or double '/'.  */
416
417       if (cursor == cursor0 || ISSLASH (cursor[-1]))
418         continue;
419
420       /* Avoid mkdir where last part of file name is "." or "..".  */
421
422       if (cursor[-1] == '.'
423           && (cursor == cursor0 + 1 || ISSLASH (cursor[-2])
424               || (cursor[-2] == '.'
425                   && (cursor == cursor0 + 2 || ISSLASH (cursor[-3])))))
426         continue;
427
428       *cursor = '\0';           /* truncate the name there */
429       mode = MODE_RWX & ~ newdir_umask;
430       invert_permissions = we_are_root ? 0 : MODE_WXUSR & ~ mode;
431       status = mkdir (file_name, mode ^ invert_permissions);
432
433       if (status == 0)
434         {
435           /* Create a struct delayed_set_stat even if
436              invert_permissions is zero, because
437              repair_delayed_set_stat may need to update the struct.  */
438           delay_set_stat (file_name,
439                           &current_stat_info,
440                           invert_permissions, INTERDIR_PERMSTATUS);
441
442           print_for_mkdir (file_name, cursor - file_name, mode);
443           did_something = 1;
444
445           *cursor = '/';
446           continue;
447         }
448
449       *cursor = '/';
450
451       if (errno == EEXIST)
452         continue;               /* Directory already exists.  */
453       else if ((errno == ENOSYS /* Automounted dirs on Solaris return
454                                    this. Reported by Warren Hyde
455                                    <Warren.Hyde@motorola.com> */
456                || ERRNO_IS_EACCES)  /* Turbo C mkdir gives a funny errno.  */
457                && access (file_name, W_OK) == 0)
458         continue;
459
460       /* Some other error in the mkdir.  We return to the caller.  */
461       break;
462     }
463
464   return did_something;         /* tell them to retry if we made one */
465 }
466
467 static bool
468 file_newer_p (const char *file_name, struct tar_stat_info *tar_stat)
469 {
470   struct stat st;
471
472   if (stat (file_name, &st))
473     {
474       stat_warn (file_name);
475       /* Be on the safe side: if the file does exist assume it is newer */
476       return errno != ENOENT;
477     }
478   if (!S_ISDIR (st.st_mode)
479       && tar_timespec_cmp (tar_stat->mtime, get_stat_mtime (&st)) <= 0)
480     {
481       return true;
482     }
483   return false;
484 }
485
486 /* Attempt repairing what went wrong with the extraction.  Delete an
487    already existing file or create missing intermediate directories.
488    Return nonzero if we somewhat increased our chances at a successful
489    extraction.  errno is properly restored on zero return.  */
490 static int
491 maybe_recoverable (char *file_name, int *interdir_made)
492 {
493   int e = errno;
494
495   if (*interdir_made)
496     return 0;
497
498   switch (errno)
499     {
500     case EEXIST:
501       /* Remove an old file, if the options allow this.  */
502
503       switch (old_files_option)
504         {
505         case KEEP_OLD_FILES:
506           return 0;
507
508         case KEEP_NEWER_FILES:
509           if (file_newer_p (file_name, &current_stat_info))
510             {
511               errno = e;
512               return 0;
513             }
514           /* FALL THROUGH */
515
516         case DEFAULT_OLD_FILES:
517         case NO_OVERWRITE_DIR_OLD_FILES:
518         case OVERWRITE_OLD_FILES:
519           {
520             int r = remove_any_file (file_name, ORDINARY_REMOVE_OPTION);
521             errno = EEXIST;
522             return r;
523           }
524
525         case UNLINK_FIRST_OLD_FILES:
526           break;
527         }
528
529     case ENOENT:
530       /* Attempt creating missing intermediate directories.  */
531       if (! make_directories (file_name))
532         {
533           errno = ENOENT;
534           return 0;
535         }
536       *interdir_made = 1;
537       return 1;
538
539     default:
540       /* Just say we can't do anything about it...  */
541
542       return 0;
543     }
544 }
545
546 /* Fix the statuses of all directories whose statuses need fixing, and
547    which are not ancestors of FILE_NAME.  If AFTER_LINKS is
548    nonzero, do this for all such directories; otherwise, stop at the
549    first directory that is marked to be fixed up only after delayed
550    links are applied.  */
551 static void
552 apply_nonancestor_delayed_set_stat (char const *file_name, bool after_links)
553 {
554   size_t file_name_len = strlen (file_name);
555   bool check_for_renamed_directories = 0;
556
557   while (delayed_set_stat_head)
558     {
559       struct delayed_set_stat *data = delayed_set_stat_head;
560       bool skip_this_one = 0;
561       struct stat st;
562       struct stat const *cur_info = 0;
563
564       check_for_renamed_directories |= data->after_links;
565
566       if (after_links < data->after_links
567           || (data->file_name_len < file_name_len
568               && file_name[data->file_name_len]
569               && (ISSLASH (file_name[data->file_name_len])
570                   || ISSLASH (file_name[data->file_name_len - 1]))
571               && memcmp (file_name, data->file_name, data->file_name_len) == 0))
572         break;
573
574       if (check_for_renamed_directories)
575         {
576           cur_info = &st;
577           if (stat (data->file_name, &st) != 0)
578             {
579               stat_error (data->file_name);
580               skip_this_one = 1;
581             }
582           else if (! (st.st_dev == data->dev && st.st_ino == data->ino))
583             {
584               ERROR ((0, 0,
585                       _("%s: Directory renamed before its status could be extracted"),
586                       quotearg_colon (data->file_name)));
587               skip_this_one = 1;
588             }
589         }
590
591       if (! skip_this_one)
592         {
593           struct tar_stat_info sb;
594           sb.stat.st_mode = data->mode;
595           sb.stat.st_uid = data->uid;
596           sb.stat.st_gid = data->gid;
597           sb.atime = data->atime;
598           sb.mtime = data->mtime;
599           set_stat (data->file_name, &sb, cur_info,
600                     data->invert_permissions, data->permstatus, DIRTYPE);
601         }
602
603       delayed_set_stat_head = data->next;
604       free (data);
605     }
606 }
607
608 \f
609
610 /* Extractor functions for various member types */
611
612 static int
613 extract_dir (char *file_name, int typeflag)
614 {
615   int status;
616   mode_t mode;
617   int interdir_made = 0;
618
619   /* Save 'root device' to avoid purging mount points. */
620   if (one_file_system_option && root_device == 0)
621     {
622       struct stat st;
623       char *dir = xgetcwd ();
624
625       if (deref_stat (true, dir, &st))
626         stat_diag (dir);
627       else
628         root_device = st.st_dev;
629       free (dir);
630     }
631
632   if (incremental_option)
633     /* Read the entry and delete files that aren't listed in the archive.  */
634     purge_directory (file_name);
635   else if (typeflag == GNUTYPE_DUMPDIR)
636     skip_member ();
637
638   mode = current_stat_info.stat.st_mode | (we_are_root ? 0 : MODE_WXUSR);
639   if (0 < same_owner_option || current_stat_info.stat.st_mode & ~ MODE_RWX)
640     mode &= S_IRWXU;
641
642   while ((status = mkdir (file_name, mode)))
643     {
644       if (errno == EEXIST
645           && (interdir_made
646               || old_files_option == DEFAULT_OLD_FILES
647               || old_files_option == OVERWRITE_OLD_FILES))
648         {
649           struct stat st;
650           if (stat (file_name, &st) == 0)
651             {
652               if (interdir_made)
653                 {
654                   repair_delayed_set_stat (file_name, &st);
655                   return 0;
656                 }
657               if (S_ISDIR (st.st_mode))
658                 {
659                   mode = st.st_mode;
660                   break;
661                 }
662             }
663           errno = EEXIST;
664         }
665
666       if (maybe_recoverable (file_name, &interdir_made))
667         continue;
668
669       if (errno != EEXIST)
670         {
671           mkdir_error (file_name);
672           return 1;
673         }
674       break;
675     }
676
677   if (status == 0
678       || old_files_option == DEFAULT_OLD_FILES
679       || old_files_option == OVERWRITE_OLD_FILES)
680     {
681       if (status == 0)
682         delay_set_stat (file_name, &current_stat_info,
683                         ((mode ^ current_stat_info.stat.st_mode)
684                          & MODE_RWX & ~ current_umask),
685                         ARCHIVED_PERMSTATUS);
686       else /* For an already existing directory, invert_perms must be 0 */
687         delay_set_stat (file_name, &current_stat_info,
688                         0,
689                         UNKNOWN_PERMSTATUS);
690     }
691   return status;
692 }
693
694
695 static int
696 open_output_file (char *file_name, int typeflag, mode_t mode)
697 {
698   int fd;
699   int openflag = (O_WRONLY | O_BINARY | O_CREAT
700                   | (old_files_option == OVERWRITE_OLD_FILES
701                      ? O_TRUNC
702                      : O_EXCL));
703
704 #if O_CTG
705   /* Contiguous files (on the Masscomp) have to specify the size in
706      the open call that creates them.  */
707
708   if (typeflag == CONTTYPE)
709     fd = open (file_name, openflag | O_CTG, mode, current_stat_info.stat.st_size);
710   else
711     fd = open (file_name, openflag, mode);
712
713 #else /* not O_CTG */
714   if (typeflag == CONTTYPE)
715     {
716       static int conttype_diagnosed;
717
718       if (!conttype_diagnosed)
719         {
720           conttype_diagnosed = 1;
721           WARN ((0, 0, _("Extracting contiguous files as regular files")));
722         }
723     }
724   fd = open (file_name, openflag, mode);
725
726 #endif /* not O_CTG */
727
728   return fd;
729 }
730
731 static int
732 extract_file (char *file_name, int typeflag)
733 {
734   int fd;
735   off_t size;
736   union block *data_block;
737   int status;
738   size_t count;
739   size_t written;
740   int interdir_made = 0;
741   mode_t mode = current_stat_info.stat.st_mode & MODE_RWX & ~ current_umask;
742   mode_t invert_permissions =
743     0 < same_owner_option ? mode & (S_IRWXG | S_IRWXO) : 0;
744
745   /* FIXME: deal with protection issues.  */
746
747   if (to_stdout_option)
748     fd = STDOUT_FILENO;
749   else if (to_command_option)
750     {
751       fd = sys_exec_command (file_name, 'f', &current_stat_info);
752       if (fd < 0)
753         {
754           skip_member ();
755           return 0;
756         }
757     }
758   else
759     {
760       do
761         fd = open_output_file (file_name, typeflag, mode ^ invert_permissions);
762       while (fd < 0 && maybe_recoverable (file_name, &interdir_made));
763
764       if (fd < 0)
765         {
766           skip_member ();
767           open_error (file_name);
768           return 1;
769         }
770     }
771
772   mv_begin (&current_stat_info);
773   if (current_stat_info.is_sparse)
774     sparse_extract_file (fd, &current_stat_info, &size);
775   else
776     for (size = current_stat_info.stat.st_size; size > 0; )
777       {
778         mv_size_left (size);
779
780         /* Locate data, determine max length writeable, write it,
781            block that we have used the data, then check if the write
782            worked.  */
783
784         data_block = find_next_block ();
785         if (! data_block)
786           {
787             ERROR ((0, 0, _("Unexpected EOF in archive")));
788             break;              /* FIXME: What happens, then?  */
789           }
790
791         written = available_space_after (data_block);
792
793         if (written > size)
794           written = size;
795         errno = 0;
796         count = full_write (fd, data_block->buffer, written);
797         size -= written;
798
799         set_next_block_after ((union block *)
800                               (data_block->buffer + written - 1));
801         if (count != written)
802           {
803             if (!to_command_option)
804               write_error_details (file_name, count, written);
805             /* FIXME: shouldn't we restore from backup? */
806             break;
807           }
808       }
809
810   skip_file (size);
811
812   mv_end ();
813
814   /* If writing to stdout, don't try to do anything to the filename;
815      it doesn't exist, or we don't want to touch it anyway.  */
816
817   if (to_stdout_option)
818     return 0;
819
820   status = close (fd);
821   if (status < 0)
822     close_error (file_name);
823
824   if (to_command_option)
825     sys_wait_command ();
826   else
827     set_stat (file_name, &current_stat_info, NULL, invert_permissions,
828               (old_files_option == OVERWRITE_OLD_FILES ?
829                UNKNOWN_PERMSTATUS : ARCHIVED_PERMSTATUS),
830               typeflag);
831
832   return status;
833 }
834
835 /* Create a placeholder file with name FILE_NAME, which will be
836    replaced after other extraction is done by a symbolic link if
837    IS_SYMLINK is true, and by a hard link otherwise.  Set
838    *INTERDIR_MADE if an intermediate directory is made in the
839    process.  */
840
841 static int
842 create_placeholder_file (char *file_name, bool is_symlink, int *interdir_made)
843 {
844   int fd;
845   struct stat st;
846
847   while ((fd = open (file_name, O_WRONLY | O_CREAT | O_EXCL, 0)) < 0)
848     if (! maybe_recoverable (file_name, interdir_made))
849       break;
850
851   if (fd < 0)
852     open_error (file_name);
853   else if (fstat (fd, &st) != 0)
854     {
855       stat_error (file_name);
856       close (fd);
857     }
858   else if (close (fd) != 0)
859     close_error (file_name);
860   else
861     {
862       struct delayed_set_stat *h;
863       struct delayed_link *p =
864         xmalloc (offsetof (struct delayed_link, target)
865                  + strlen (current_stat_info.link_name)
866                  + 1);
867       p->next = delayed_link_head;
868       delayed_link_head = p;
869       p->dev = st.st_dev;
870       p->ino = st.st_ino;
871       p->mtime = get_stat_mtime (&st);
872       p->is_symlink = is_symlink;
873       if (is_symlink)
874         {
875           p->uid = current_stat_info.stat.st_uid;
876           p->gid = current_stat_info.stat.st_gid;
877         }
878       p->sources = xmalloc (offsetof (struct string_list, string)
879                             + strlen (file_name) + 1);
880       p->sources->next = 0;
881       strcpy (p->sources->string, file_name);
882       strcpy (p->target, current_stat_info.link_name);
883
884       h = delayed_set_stat_head;
885       if (h && ! h->after_links
886           && strncmp (file_name, h->file_name, h->file_name_len) == 0
887           && ISSLASH (file_name[h->file_name_len])
888           && (last_component (file_name) == file_name + h->file_name_len + 1))
889         {
890           do
891             {
892               h->after_links = 1;
893
894               if (stat (h->file_name, &st) != 0)
895                 stat_error (h->file_name);
896               else
897                 {
898                   h->dev = st.st_dev;
899                   h->ino = st.st_ino;
900                 }
901             }
902           while ((h = h->next) && ! h->after_links);
903         }
904
905       return 0;
906     }
907
908   return -1;
909 }
910
911 static int
912 extract_link (char *file_name, int typeflag)
913 {
914   int interdir_made = 0;
915   char const *link_name;
916
917   link_name = current_stat_info.link_name;
918   
919   if (! absolute_names_option && contains_dot_dot (link_name))
920     return create_placeholder_file (file_name, false, &interdir_made);
921
922   do
923     {
924       struct stat st1, st2;
925       int e;
926       int status = link (link_name, file_name);
927       e = errno;
928
929       if (status == 0)
930         {
931           struct delayed_link *ds = delayed_link_head;
932           if (ds && lstat (link_name, &st1) == 0)
933             for (; ds; ds = ds->next)
934               if (ds->dev == st1.st_dev
935                   && ds->ino == st1.st_ino
936                   && timespec_cmp (ds->mtime, get_stat_mtime (&st1)) == 0)
937                 {
938                   struct string_list *p =  xmalloc (offsetof (struct string_list, string)
939                                                     + strlen (file_name) + 1);
940                   strcpy (p->string, file_name);
941                   p->next = ds->sources;
942                   ds->sources = p;
943                   break;
944                 }
945           return 0;
946         }
947       else if ((e == EEXIST && strcmp (link_name, file_name) == 0)
948                || (lstat (link_name, &st1) == 0
949                    && lstat (file_name, &st2) == 0
950                    && st1.st_dev == st2.st_dev
951                    && st1.st_ino == st2.st_ino))
952         return 0;
953
954       errno = e;
955     }
956   while (maybe_recoverable (file_name, &interdir_made));
957
958   if (!(incremental_option && errno == EEXIST))
959     {
960       link_error (link_name, file_name);
961       return 1;
962     }
963   return 0;
964 }
965
966 static int
967 extract_symlink (char *file_name, int typeflag)
968 {
969 #ifdef HAVE_SYMLINK
970   int status;
971   int interdir_made = 0;
972
973   if (! absolute_names_option
974       && (IS_ABSOLUTE_FILE_NAME (current_stat_info.link_name)
975           || contains_dot_dot (current_stat_info.link_name)))
976     return create_placeholder_file (file_name, true, &interdir_made);
977
978   while ((status = symlink (current_stat_info.link_name, file_name)))
979     if (!maybe_recoverable (file_name, &interdir_made))
980       break;
981
982   if (status == 0)
983     set_stat (file_name, &current_stat_info, NULL, 0, 0, SYMTYPE);
984   else
985     symlink_error (current_stat_info.link_name, file_name);
986   return status;
987
988 #else
989   static int warned_once;
990
991   if (!warned_once)
992     {
993       warned_once = 1;
994       WARN ((0, 0, _("Attempting extraction of symbolic links as hard links")));
995     }
996   return extract_link (file_name, typeflag);
997 #endif
998 }
999
1000 #if S_IFCHR || S_IFBLK
1001 static int
1002 extract_node (char *file_name, int typeflag)
1003 {
1004   int status;
1005   int interdir_made = 0;
1006   mode_t mode = current_stat_info.stat.st_mode & ~ current_umask;
1007   mode_t invert_permissions =
1008     0 < same_owner_option ? mode & (S_IRWXG | S_IRWXO) : 0;
1009
1010   do
1011     status = mknod (file_name, mode ^ invert_permissions,
1012                     current_stat_info.stat.st_rdev);
1013   while (status && maybe_recoverable (file_name, &interdir_made));
1014
1015   if (status != 0)
1016     mknod_error (file_name);
1017   else
1018     set_stat (file_name, &current_stat_info, NULL, invert_permissions,
1019               ARCHIVED_PERMSTATUS, typeflag);
1020   return status;
1021 }
1022 #endif
1023
1024 #if HAVE_MKFIFO || defined mkfifo
1025 static int
1026 extract_fifo (char *file_name, int typeflag)
1027 {
1028   int status;
1029   int interdir_made = 0;
1030   mode_t mode = current_stat_info.stat.st_mode & ~ current_umask;
1031   mode_t invert_permissions =
1032     0 < same_owner_option ? mode & (S_IRWXG | S_IRWXO) : 0;
1033
1034   while ((status = mkfifo (file_name, mode)) != 0)
1035     if (!maybe_recoverable (file_name, &interdir_made))
1036       break;
1037
1038   if (status == 0)
1039     set_stat (file_name, &current_stat_info, NULL, invert_permissions,
1040               ARCHIVED_PERMSTATUS, typeflag);
1041   else
1042     mkfifo_error (file_name);
1043   return status;
1044 }
1045 #endif
1046
1047 static int
1048 extract_volhdr (char *file_name, int typeflag)
1049 {
1050   if (verbose_option)
1051     fprintf (stdlis, _("Reading %s\n"), quote (current_stat_info.file_name));
1052   skip_member ();
1053   return 0;
1054 }
1055
1056 static int
1057 extract_failure (char *file_name, int typeflag)
1058 {
1059   return 1;
1060 }
1061
1062 typedef int (*tar_extractor_t) (char *file_name, int typeflag);
1063
1064 \f
1065
1066 /* Prepare to extract a file. Find extractor function.
1067    Return zero if extraction should not proceed.  */
1068
1069 static int
1070 prepare_to_extract (char const *file_name, int typeflag, tar_extractor_t *fun)
1071 {
1072   int rc = 1;
1073
1074   if (EXTRACT_OVER_PIPE)
1075     rc = 0;
1076
1077   /* Select the extractor */
1078   switch (typeflag)
1079     {
1080     case GNUTYPE_SPARSE:
1081       *fun = extract_file;
1082       rc = 1;
1083       break;
1084
1085     case AREGTYPE:
1086     case REGTYPE:
1087     case CONTTYPE:
1088       /* Appears to be a file.  But BSD tar uses the convention that a slash
1089          suffix means a directory.  */
1090       if (current_stat_info.had_trailing_slash)
1091         *fun = extract_dir;
1092       else
1093         {
1094           *fun = extract_file;
1095           rc = 1;
1096         }
1097       break;
1098
1099     case SYMTYPE:
1100       *fun = extract_symlink;
1101       break;
1102
1103     case LNKTYPE:
1104       *fun = extract_link;
1105       break;
1106
1107 #if S_IFCHR
1108     case CHRTYPE:
1109       current_stat_info.stat.st_mode |= S_IFCHR;
1110       *fun = extract_node;
1111       break;
1112 #endif
1113
1114 #if S_IFBLK
1115     case BLKTYPE:
1116       current_stat_info.stat.st_mode |= S_IFBLK;
1117       *fun = extract_node;
1118       break;
1119 #endif
1120
1121 #if HAVE_MKFIFO || defined mkfifo
1122     case FIFOTYPE:
1123       *fun = extract_fifo;
1124       break;
1125 #endif
1126
1127     case DIRTYPE:
1128     case GNUTYPE_DUMPDIR:
1129       *fun = extract_dir;
1130       if (current_stat_info.is_dumpdir)
1131         delay_directory_restore_option = true;
1132       break;
1133
1134     case GNUTYPE_VOLHDR:
1135       *fun = extract_volhdr;
1136       break;
1137
1138     case GNUTYPE_MULTIVOL:
1139       ERROR ((0, 0,
1140               _("%s: Cannot extract -- file is continued from another volume"),
1141               quotearg_colon (current_stat_info.file_name)));
1142       *fun = extract_failure;
1143       break;
1144
1145     case GNUTYPE_LONGNAME:
1146     case GNUTYPE_LONGLINK:
1147       ERROR ((0, 0, _("Unexpected long name header")));
1148       *fun = extract_failure;
1149       break;
1150
1151     default:
1152       WARN ((0, 0,
1153              _("%s: Unknown file type `%c', extracted as normal file"),
1154              quotearg_colon (file_name), typeflag));
1155       *fun = extract_file;
1156     }
1157
1158   /* Determine whether the extraction should proceed */
1159   if (rc == 0)
1160     return 0;
1161
1162   switch (old_files_option)
1163     {
1164     case UNLINK_FIRST_OLD_FILES:
1165       if (!remove_any_file (file_name,
1166                             recursive_unlink_option ? RECURSIVE_REMOVE_OPTION
1167                                                       : ORDINARY_REMOVE_OPTION)
1168           && errno && errno != ENOENT)
1169         {
1170           unlink_error (file_name);
1171           return 0;
1172         }
1173       break;
1174
1175     case KEEP_NEWER_FILES:
1176       if (file_newer_p (file_name, &current_stat_info))
1177         {
1178           WARN ((0, 0, _("Current %s is newer or same age"),
1179                  quote (file_name)));
1180           return 0;
1181         }
1182       break;
1183
1184     default:
1185       break;
1186     }
1187
1188   return 1;
1189 }
1190
1191 /* Extract a file from the archive.  */
1192 void
1193 extract_archive (void)
1194 {
1195   char typeflag;
1196   tar_extractor_t fun;
1197
1198   set_next_block_after (current_header);
1199   decode_header (current_header, &current_stat_info, &current_format, 1);
1200   if (!current_stat_info.file_name[0]
1201       || (interactive_option
1202           && !confirm ("extract", current_stat_info.file_name)))
1203     {
1204       skip_member ();
1205       return;
1206     }
1207
1208   /* Print the block from current_header and current_stat.  */
1209   if (verbose_option)
1210     print_header (&current_stat_info, -1);
1211
1212   /* Restore stats for all non-ancestor directories, unless
1213      it is an incremental archive.
1214      (see NOTICE in the comment to delay_set_stat above) */
1215   if (!delay_directory_restore_option)
1216     apply_nonancestor_delayed_set_stat (current_stat_info.file_name, 0);
1217
1218   /* Take a safety backup of a previously existing file.  */
1219
1220   if (backup_option)
1221     if (!maybe_backup_file (current_stat_info.file_name, 0))
1222       {
1223         int e = errno;
1224         ERROR ((0, e, _("%s: Was unable to backup this file"),
1225                 quotearg_colon (current_stat_info.file_name)));
1226         skip_member ();
1227         return;
1228       }
1229
1230   /* Extract the archive entry according to its type.  */
1231   /* KLUDGE */
1232   typeflag = sparse_member_p (&current_stat_info) ?
1233                   GNUTYPE_SPARSE : current_header->header.typeflag;
1234
1235   if (prepare_to_extract (current_stat_info.file_name, typeflag, &fun))
1236     {
1237       if (fun && (*fun) (current_stat_info.file_name, typeflag)
1238           && backup_option)
1239         undo_last_backup ();
1240     }
1241   else
1242     skip_member ();
1243
1244 }
1245
1246 /* Extract the symbolic links whose final extraction were delayed.  */
1247 static void
1248 apply_delayed_links (void)
1249 {
1250   struct delayed_link *ds;
1251
1252   for (ds = delayed_link_head; ds; )
1253     {
1254       struct string_list *sources = ds->sources;
1255       char const *valid_source = 0;
1256
1257       for (sources = ds->sources; sources; sources = sources->next)
1258         {
1259           char const *source = sources->string;
1260           struct stat st;
1261
1262           /* Make sure the placeholder file is still there.  If not,
1263              don't create a link, as the placeholder was probably
1264              removed by a later extraction.  */
1265           if (lstat (source, &st) == 0
1266               && st.st_dev == ds->dev
1267               && st.st_ino == ds->ino
1268               && timespec_cmp (get_stat_mtime (&st), ds->mtime) == 0)
1269             {
1270               /* Unlink the placeholder, then create a hard link if possible,
1271                  a symbolic link otherwise.  */
1272               if (unlink (source) != 0)
1273                 unlink_error (source);
1274               else if (valid_source && link (valid_source, source) == 0)
1275                 ;
1276               else if (!ds->is_symlink)
1277                 {
1278                   if (link (ds->target, source) != 0)
1279                     link_error (ds->target, source);
1280                 }
1281               else if (symlink (ds->target, source) != 0)
1282                 symlink_error (ds->target, source);
1283               else
1284                 {
1285                   struct tar_stat_info st1;
1286                   st1.stat.st_uid = ds->uid;
1287                   st1.stat.st_gid = ds->gid;
1288                   set_stat (source, &st1, NULL, 0, 0, SYMTYPE);
1289                   valid_source = source;
1290                 }
1291             }
1292         }
1293
1294       for (sources = ds->sources; sources; )
1295         {
1296           struct string_list *next = sources->next;
1297           free (sources);
1298           sources = next;
1299         }
1300
1301       {
1302         struct delayed_link *next = ds->next;
1303         free (ds);
1304         ds = next;
1305       }
1306     }
1307
1308   delayed_link_head = 0;
1309 }
1310
1311 /* Finish the extraction of an archive.  */
1312 void
1313 extract_finish (void)
1314 {
1315   /* First, fix the status of ordinary directories that need fixing.  */
1316   apply_nonancestor_delayed_set_stat ("", 0);
1317
1318   /* Then, apply delayed links, so that they don't affect delayed
1319      directory status-setting for ordinary directories.  */
1320   apply_delayed_links ();
1321
1322   /* Finally, fix the status of directories that are ancestors
1323      of delayed links.  */
1324   apply_nonancestor_delayed_set_stat ("", 1);
1325 }
1326
1327 bool
1328 rename_directory (char *src, char *dst)
1329 {
1330   if (rename (src, dst))
1331     {
1332       int e = errno;
1333
1334       switch (e)
1335         {
1336         case ENOENT:
1337           if (make_directories (dst))
1338             {
1339               if (rename (src, dst) == 0)
1340                 return true;
1341               e = errno;
1342             }
1343           break;
1344
1345         case EXDEV:
1346           /* FIXME: Fall back to recursive copying */
1347
1348         default:
1349           break;
1350         }
1351
1352       ERROR ((0, e, _("Cannot rename %s to %s"),
1353               quote_n (0, src),
1354               quote_n (1, dst)));
1355       return false;
1356     }
1357   return true;
1358 }
1359
1360 void
1361 fatal_exit (void)
1362 {
1363   extract_finish ();
1364   error (TAREXIT_FAILURE, 0, _("Error is not recoverable: exiting now"));
1365   abort ();
1366 }
1367
1368 void
1369 xalloc_die (void)
1370 {
1371   error (0, 0, "%s", _("memory exhausted"));
1372   fatal_exit ();
1373 }