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