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