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