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