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