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