1f455932291db1a2d4e9dad187a73b6e63631427
[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, 2006, 2007, 2010 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 3, 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 <errno.h>
25 #include <priv-set.h>
26
27 #include "common.h"
28
29 static bool we_are_root;        /* true if our effective uid == 0 */
30 static mode_t newdir_umask;     /* umask when creating new directories */
31 static mode_t current_umask;    /* current umask (which is set to 0 if -p) */
32
33 #define ALL_MODE_BITS ((mode_t) ~ (mode_t) 0)
34
35 #if ! HAVE_FCHMOD && ! defined fchmod
36 # define fchmod(fd, mode) (errno = ENOSYS, -1)
37 #endif
38 #if ! HAVE_FCHOWN && ! defined fchown
39 # define fchown(fd, uid, gid) (errno = ENOSYS, -1)
40 #endif
41
42 /* Return true if an error number ERR means the system call is
43    supported in this case.  */
44 static bool
45 implemented (int err)
46 {
47   return ! (err == ENOSYS
48             || err == ENOTSUP
49             || (EOPNOTSUPP != ENOTSUP && err == EOPNOTSUPP));
50 }
51
52 /* List of directories whose statuses we need to extract after we've
53    finished extracting their subsidiary files.  If you consider each
54    contiguous subsequence of elements of the form [D]?[^D]*, where [D]
55    represents an element where AFTER_LINKS is nonzero and [^D]
56    represents an element where AFTER_LINKS is zero, then the head
57    of the subsequence has the longest name, and each non-head element
58    in the prefix is an ancestor (in the directory hierarchy) of the
59    preceding element.  */
60
61 struct delayed_set_stat
62   {
63     /* Next directory in list.  */
64     struct delayed_set_stat *next;
65
66     /* Metadata for this directory.  */
67     dev_t dev;
68     ino_t ino;
69     mode_t mode; /* The desired mode is MODE & ~ current_umask.  */
70     uid_t uid;
71     gid_t gid;
72     struct timespec atime;
73     struct timespec mtime;
74
75     /* An estimate of the directory's current mode, along with a mask
76        specifying which bits of this estimate are known to be correct.
77        If CURRENT_MODE_MASK is zero, CURRENT_MODE's value doesn't
78        matter.  */
79     mode_t current_mode;
80     mode_t current_mode_mask;
81
82     /* This directory is an intermediate directory that was created
83        as an ancestor of some other directory; it was not mentioned
84        in the archive, so do not set its uid, gid, atime, or mtime,
85        and don't alter its mode outside of MODE_RWX.  */
86     bool interdir;
87
88     /* Whether symbolic links should be followed when accessing the
89        directory.  */
90     int atflag;
91
92     /* Do not set the status of this directory until after delayed
93        links are created.  */
94     bool after_links;
95
96     /* Directory that the name is relative to.  */
97     int change_dir;
98
99     /* Length and contents of name.  */
100     size_t file_name_len;
101     char file_name[1];
102   };
103
104 static struct delayed_set_stat *delayed_set_stat_head;
105
106 /* List of links whose creation we have delayed.  */
107 struct delayed_link
108   {
109     /* The next delayed link in the list.  */
110     struct delayed_link *next;
111
112     /* The device, inode number and ctime of the placeholder.  Use
113        ctime, not mtime, to make false matches less likely if some
114        other process removes the placeholder.  */
115     dev_t dev;
116     ino_t ino;
117     struct timespec ctime;
118
119     /* True if the link is symbolic.  */
120     bool is_symlink;
121
122     /* The desired metadata, valid only the link is symbolic.  */
123     mode_t mode;
124     uid_t uid;
125     gid_t gid;
126     struct timespec atime;
127     struct timespec mtime;
128
129     /* The directory that the sources and target are relative to.  */
130     int change_dir;
131
132     /* A list of sources for this link.  The sources are all to be
133        hard-linked together.  */
134     struct string_list *sources;
135
136     /* The desired target of the desired link.  */
137     char target[1];
138   };
139
140 static struct delayed_link *delayed_link_head;
141
142 struct string_list
143   {
144     struct string_list *next;
145     char string[1];
146   };
147
148 /*  Set up to extract files.  */
149 void
150 extr_init (void)
151 {
152   we_are_root = geteuid () == 0;
153   same_permissions_option += we_are_root;
154   same_owner_option += we_are_root;
155
156   /* Option -p clears the kernel umask, so it does not affect proper
157      restoration of file permissions.  New intermediate directories will
158      comply with umask at start of program.  */
159
160   newdir_umask = umask (0);
161   if (0 < same_permissions_option)
162     current_umask = 0;
163   else
164     {
165       umask (newdir_umask);     /* restore the kernel umask */
166       current_umask = newdir_umask;
167     }
168 }
169
170 /* Use fchmod if possible, fchmodat otherwise.  */
171 static int
172 fd_chmod (int fd, char const *file, mode_t mode, int atflag)
173 {
174   if (0 <= fd)
175     {
176       int result = fchmod (fd, mode);
177       if (result == 0 || implemented (errno))
178         return result;
179     }
180   return fchmodat (AT_FDCWD, file, mode, atflag);
181 }
182
183 /* Use fchown if possible, fchownat otherwise.  */
184 static int
185 fd_chown (int fd, char const *file, uid_t uid, gid_t gid, int atflag)
186 {
187   if (0 <= fd)
188     {
189       int result = fchown (fd, uid, gid);
190       if (result == 0 || implemented (errno))
191         return result;
192     }
193   return fchownat (AT_FDCWD, file, uid, gid, atflag);
194 }
195
196 /* Use fstat if possible, fstatat otherwise.  */
197 static int
198 fd_stat (int fd, char const *file, struct stat *st, int atflag)
199 {
200   return (0 <= fd
201           ? fstat (fd, st)
202           : fstatat (AT_FDCWD, file, st, atflag));
203 }
204
205 /* Set the mode for FILE_NAME to MODE.
206    MODE_MASK specifies the bits of MODE that we care about;
207    thus if MODE_MASK is zero, do nothing.
208    If FD is nonnegative, it is a file descriptor for the file.
209    CURRENT_MODE and CURRENT_MODE_MASK specify information known about
210    the file's current mode, using the style of struct delayed_set_stat.
211    TYPEFLAG specifies the type of the file.
212    ATFLAG specifies the flag to use when statting the file.  */
213 static void
214 set_mode (char const *file_name,
215           mode_t mode, mode_t mode_mask, int fd,
216           mode_t current_mode, mode_t current_mode_mask,
217           char typeflag, int atflag)
218 {
219   if (((current_mode ^ mode) | ~ current_mode_mask) & mode_mask)
220     {
221       if (MODE_ALL & ~ mode_mask & ~ current_mode_mask)
222         {
223           struct stat st;
224           if (fd_stat (fd, file_name, &st, atflag) != 0)
225             {
226               stat_error (file_name);
227               return;
228             }
229           current_mode = st.st_mode;
230         }
231
232       current_mode &= MODE_ALL;
233       mode = (current_mode & ~ mode_mask) | (mode & mode_mask);
234
235       if (current_mode != mode)
236         {
237           int chmod_errno =
238             fd_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
239
240           /* On Solaris, chmod may fail if we don't have PRIV_ALL, because
241              setuid-root files would otherwise be a backdoor.  See
242              http://opensolaris.org/jive/thread.jspa?threadID=95826
243              (2009-09-03).  */
244           if (chmod_errno == EPERM && (mode & S_ISUID)
245               && priv_set_restore_linkdir () == 0)
246             {
247               chmod_errno =
248                 fd_chmod (fd, file_name, mode, atflag) == 0 ? 0 : errno;
249               priv_set_remove_linkdir ();
250             }
251
252           /* Linux fchmodat does not support AT_SYMLINK_NOFOLLOW, and
253              returns ENOTSUP even when operating on non-symlinks, try
254              again with the flag disabled if it does not appear to be
255              supported and if the file is not a symlink.  This
256              introduces a race, alas.  */
257           if (atflag && typeflag != SYMTYPE && ! implemented (chmod_errno))
258             chmod_errno = fd_chmod (fd, file_name, mode, 0) == 0 ? 0 : errno;
259
260           if (chmod_errno
261               && (typeflag != SYMTYPE || implemented (chmod_errno)))
262             {
263               errno = chmod_errno;
264               chmod_error_details (file_name, mode);
265             }
266         }
267     }
268 }
269
270 /* Check time after successfully setting FILE_NAME's time stamp to T.  */
271 static void
272 check_time (char const *file_name, struct timespec t)
273 {
274   if (t.tv_sec <= 0)
275     WARNOPT (WARN_TIMESTAMP,
276              (0, 0, _("%s: implausibly old time stamp %s"),
277               file_name, tartime (t, true)));
278   else if (timespec_cmp (volume_start_time, t) < 0)
279     {
280       struct timespec now;
281       gettime (&now);
282       if (timespec_cmp (now, t) < 0)
283         {
284           char buf[TIMESPEC_STRSIZE_BOUND];
285           struct timespec diff;
286           diff.tv_sec = t.tv_sec - now.tv_sec;
287           diff.tv_nsec = t.tv_nsec - now.tv_nsec;
288           if (diff.tv_nsec < 0)
289             {
290               diff.tv_nsec += BILLION;
291               diff.tv_sec--;
292             }
293           WARNOPT (WARN_TIMESTAMP,
294                    (0, 0, _("%s: time stamp %s is %s s in the future"),
295                     file_name, tartime (t, true), code_timespec (diff, buf)));
296         }
297     }
298 }
299
300 /* Restore stat attributes (owner, group, mode and times) for
301    FILE_NAME, using information given in *ST.
302    If FD is nonnegative, it is a file descriptor for the file.
303    CURRENT_MODE and CURRENT_MODE_MASK specify information known about
304    the file's current mode, using the style of struct delayed_set_stat.
305    TYPEFLAG specifies the type of the file.
306    If INTERDIR, this is an intermediate directory.
307    ATFLAG specifies the flag to use when statting the file.  */
308
309 static void
310 set_stat (char const *file_name,
311           struct tar_stat_info const *st,
312           int fd, mode_t current_mode, mode_t current_mode_mask,
313           char typeflag, bool interdir, int atflag)
314 {
315   /* Do the utime before the chmod because some versions of utime are
316      broken and trash the modes of the file.  */
317
318   if (! touch_option && ! interdir)
319     {
320       struct timespec ts[2];
321       if (incremental_option)
322         ts[0] = st->atime;
323       else
324         ts[0].tv_nsec = UTIME_OMIT;
325       ts[1] = st->mtime;
326
327       if (fd_utimensat (fd, AT_FDCWD, file_name, ts, atflag) == 0)
328         {
329           if (incremental_option)
330             check_time (file_name, ts[0]);
331           check_time (file_name, ts[1]);
332         }
333       else if (typeflag != SYMTYPE || implemented (errno))
334         utime_error (file_name);
335     }
336
337   if (0 < same_owner_option && ! interdir)
338     {
339       /* Some systems allow non-root users to give files away.  Once this
340          done, it is not possible anymore to change file permissions.
341          However, setting file permissions now would be incorrect, since
342          they would apply to the wrong user, and there would be a race
343          condition.  So, don't use systems that allow non-root users to
344          give files away.  */
345       uid_t uid = st->stat.st_uid;
346       gid_t gid = st->stat.st_gid;
347
348       if (fd_chown (fd, file_name, uid, gid, atflag) == 0)
349         {
350           /* Changing the owner can clear st_mode bits in some cases.  */
351           if ((current_mode | ~ current_mode_mask) & S_IXUGO)
352             current_mode_mask &= ~ (current_mode & (S_ISUID | S_ISGID));
353         }
354       else if (typeflag != SYMTYPE || implemented (errno))
355         chown_error_details (file_name, uid, gid);
356     }
357
358   set_mode (file_name,
359             st->stat.st_mode & ~ current_umask,
360             0 < same_permissions_option && ! interdir ? MODE_ALL : MODE_RWX,
361             fd, current_mode, current_mode_mask, typeflag, atflag);
362 }
363
364 /* Remember to restore stat attributes (owner, group, mode and times)
365    for the directory FILE_NAME, using information given in *ST,
366    once we stop extracting files into that directory.
367
368    If ST is null, merely create a placeholder node for an intermediate
369    directory that was created by make_directories.
370
371    NOTICE: this works only if the archive has usual member order, i.e.
372    directory, then the files in that directory. Incremental archive have
373    somewhat reversed order: first go subdirectories, then all other
374    members. To help cope with this case the variable
375    delay_directory_restore_option is set by prepare_to_extract.
376
377    If an archive was explicitely created so that its member order is
378    reversed, some directory timestamps can be restored incorrectly,
379    e.g.:
380        tar --no-recursion -cf archive dir dir/file1 foo dir/file2
381 */
382 static void
383 delay_set_stat (char const *file_name, struct tar_stat_info const *st,
384                 mode_t current_mode, mode_t current_mode_mask,
385                 mode_t mode, int atflag)
386 {
387   size_t file_name_len = strlen (file_name);
388   struct delayed_set_stat *data =
389     xmalloc (offsetof (struct delayed_set_stat, file_name)
390              + file_name_len + 1);
391   data->next = delayed_set_stat_head;
392   data->mode = mode;
393   if (st)
394     {
395       data->dev = st->stat.st_dev;
396       data->ino = st->stat.st_ino;
397       data->uid = st->stat.st_uid;
398       data->gid = st->stat.st_gid;
399       data->atime = st->atime;
400       data->mtime = st->mtime;
401     }
402   data->file_name_len = file_name_len;
403   data->current_mode = current_mode;
404   data->current_mode_mask = current_mode_mask;
405   data->interdir = ! st;
406   data->atflag = atflag;
407   data->after_links = 0;
408   data->change_dir = chdir_current;
409   strcpy (data->file_name, file_name);
410   delayed_set_stat_head = data;
411 }
412
413 /* Update the delayed_set_stat info for an intermediate directory
414    created within the file name of DIR.  The intermediate directory turned
415    out to be the same as this directory, e.g. due to ".." or symbolic
416    links.  *DIR_STAT_INFO is the status of the directory.  */
417 static void
418 repair_delayed_set_stat (char const *dir,
419                          struct stat const *dir_stat_info)
420 {
421   struct delayed_set_stat *data;
422   for (data = delayed_set_stat_head;  data;  data = data->next)
423     {
424       struct stat st;
425       if (fstatat (AT_FDCWD, data->file_name, &st, data->atflag) != 0)
426         {
427           stat_error (data->file_name);
428           return;
429         }
430
431       if (st.st_dev == dir_stat_info->st_dev
432           && st.st_ino == dir_stat_info->st_ino)
433         {
434           data->dev = current_stat_info.stat.st_dev;
435           data->ino = current_stat_info.stat.st_ino;
436           data->mode = current_stat_info.stat.st_mode;
437           data->uid = current_stat_info.stat.st_uid;
438           data->gid = current_stat_info.stat.st_gid;
439           data->atime = current_stat_info.atime;
440           data->mtime = current_stat_info.mtime;
441           data->current_mode = st.st_mode;
442           data->current_mode_mask = ALL_MODE_BITS;
443           data->interdir = false;
444           return;
445         }
446     }
447
448   ERROR ((0, 0, _("%s: Unexpected inconsistency when making directory"),
449           quotearg_colon (dir)));
450 }
451
452 /* After a file/link/directory creation has failed, see if
453    it's because some required directory was not present, and if so,
454    create all required directories.  Return non-zero if a directory
455    was created.  */
456 static int
457 make_directories (char *file_name)
458 {
459   char *cursor0 = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
460   char *cursor;                 /* points into the file name */
461   int did_something = 0;        /* did we do anything yet? */
462   int status;
463
464   for (cursor = cursor0; *cursor; cursor++)
465     {
466       mode_t mode;
467       mode_t desired_mode;
468
469       if (! ISSLASH (*cursor))
470         continue;
471
472       /* Avoid mkdir of empty string, if leading or double '/'.  */
473
474       if (cursor == cursor0 || ISSLASH (cursor[-1]))
475         continue;
476
477       /* Avoid mkdir where last part of file name is "." or "..".  */
478
479       if (cursor[-1] == '.'
480           && (cursor == cursor0 + 1 || ISSLASH (cursor[-2])
481               || (cursor[-2] == '.'
482                   && (cursor == cursor0 + 2 || ISSLASH (cursor[-3])))))
483         continue;
484
485       *cursor = '\0';           /* truncate the name there */
486       desired_mode = MODE_RWX & ~ newdir_umask;
487       mode = desired_mode | (we_are_root ? 0 : MODE_WXUSR);
488       status = mkdir (file_name, mode);
489
490       if (status == 0)
491         {
492           /* Create a struct delayed_set_stat even if
493              mode == desired_mode, because
494              repair_delayed_set_stat may need to update the struct.  */
495           delay_set_stat (file_name,
496                           0, mode & ~ current_umask, MODE_RWX,
497                           desired_mode, AT_SYMLINK_NOFOLLOW);
498
499           print_for_mkdir (file_name, cursor - file_name, desired_mode);
500           did_something = 1;
501
502           *cursor = '/';
503           continue;
504         }
505
506       *cursor = '/';
507
508       if (errno == EEXIST)
509         continue;               /* Directory already exists.  */
510       else if ((errno == ENOSYS /* Automounted dirs on Solaris return
511                                    this. Reported by Warren Hyde
512                                    <Warren.Hyde@motorola.com> */
513                || ERRNO_IS_EACCES)  /* Turbo C mkdir gives a funny errno.  */
514                && access (file_name, W_OK) == 0)
515         continue;
516
517       /* Some other error in the mkdir.  We return to the caller.  */
518       break;
519     }
520
521   return did_something;         /* tell them to retry if we made one */
522 }
523
524 static bool
525 file_newer_p (const char *file_name, struct tar_stat_info *tar_stat)
526 {
527   struct stat st;
528
529   if (stat (file_name, &st))
530     {
531       if (errno != ENOENT)
532         {
533           stat_warn (file_name);
534           /* Be on the safe side: if the file does exist assume it is newer */
535           return true;
536         }
537       return false;
538     }
539   if (!S_ISDIR (st.st_mode)
540       && tar_timespec_cmp (tar_stat->mtime, get_stat_mtime (&st)) <= 0)
541     {
542       return true;
543     }
544   return false;
545 }
546
547 #define RECOVER_NO 0
548 #define RECOVER_OK 1
549 #define RECOVER_SKIP 2
550
551 /* Attempt repairing what went wrong with the extraction.  Delete an
552    already existing file or create missing intermediate directories.
553    Return RECOVER_OK if we somewhat increased our chances at a successful
554    extraction, RECOVER_NO if there are no chances, and RECOVER_SKIP if the
555    caller should skip extraction of that member.  The value of errno is
556    properly restored on returning RECOVER_NO.  */
557
558 static int
559 maybe_recoverable (char *file_name, bool *interdir_made)
560 {
561   int e = errno;
562
563   if (*interdir_made)
564     return RECOVER_NO;
565
566   switch (errno)
567     {
568     case EEXIST:
569       /* Remove an old file, if the options allow this.  */
570
571       switch (old_files_option)
572         {
573         case KEEP_OLD_FILES:
574           return RECOVER_SKIP;
575
576         case KEEP_NEWER_FILES:
577           if (file_newer_p (file_name, &current_stat_info))
578             {
579               errno = e;
580               return RECOVER_NO;
581             }
582           /* FALL THROUGH */
583
584         case DEFAULT_OLD_FILES:
585         case NO_OVERWRITE_DIR_OLD_FILES:
586         case OVERWRITE_OLD_FILES:
587           {
588             int r = remove_any_file (file_name, ORDINARY_REMOVE_OPTION);
589             errno = EEXIST;
590             return r > 0 ? RECOVER_OK : RECOVER_NO;
591           }
592
593         case UNLINK_FIRST_OLD_FILES:
594           break;
595         }
596
597     case ENOENT:
598       /* Attempt creating missing intermediate directories.  */
599       if (! make_directories (file_name))
600         {
601           errno = ENOENT;
602           return RECOVER_NO;
603         }
604       *interdir_made = true;
605       return RECOVER_OK;
606
607     default:
608       /* Just say we can't do anything about it...  */
609
610       return RECOVER_NO;
611     }
612 }
613
614 /* Fix the statuses of all directories whose statuses need fixing, and
615    which are not ancestors of FILE_NAME.  If AFTER_LINKS is
616    nonzero, do this for all such directories; otherwise, stop at the
617    first directory that is marked to be fixed up only after delayed
618    links are applied.  */
619 static void
620 apply_nonancestor_delayed_set_stat (char const *file_name, bool after_links)
621 {
622   size_t file_name_len = strlen (file_name);
623   bool check_for_renamed_directories = 0;
624
625   while (delayed_set_stat_head)
626     {
627       struct delayed_set_stat *data = delayed_set_stat_head;
628       bool skip_this_one = 0;
629       struct stat st;
630       mode_t current_mode = data->current_mode;
631       mode_t current_mode_mask = data->current_mode_mask;
632
633       check_for_renamed_directories |= data->after_links;
634
635       if (after_links < data->after_links
636           || (data->file_name_len < file_name_len
637               && file_name[data->file_name_len]
638               && (ISSLASH (file_name[data->file_name_len])
639                   || ISSLASH (file_name[data->file_name_len - 1]))
640               && memcmp (file_name, data->file_name, data->file_name_len) == 0))
641         break;
642
643       chdir_do (data->change_dir);
644
645       if (check_for_renamed_directories)
646         {
647           if (fstatat (AT_FDCWD, data->file_name, &st, data->atflag) != 0)
648             {
649               stat_error (data->file_name);
650               skip_this_one = 1;
651             }
652           else
653             {
654               current_mode = st.st_mode;
655               current_mode_mask = ALL_MODE_BITS;
656               if (! (st.st_dev == data->dev && st.st_ino == data->ino))
657                 {
658                   ERROR ((0, 0,
659                           _("%s: Directory renamed before its status could be extracted"),
660                           quotearg_colon (data->file_name)));
661                   skip_this_one = 1;
662                 }
663             }
664         }
665
666       if (! skip_this_one)
667         {
668           struct tar_stat_info sb;
669           sb.stat.st_mode = data->mode;
670           sb.stat.st_uid = data->uid;
671           sb.stat.st_gid = data->gid;
672           sb.atime = data->atime;
673           sb.mtime = data->mtime;
674           set_stat (data->file_name, &sb,
675                     -1, current_mode, current_mode_mask,
676                     DIRTYPE, data->interdir, data->atflag);
677         }
678
679       delayed_set_stat_head = data->next;
680       free (data);
681     }
682 }
683
684 \f
685
686 /* Extractor functions for various member types */
687
688 static int
689 extract_dir (char *file_name, int typeflag)
690 {
691   int status;
692   mode_t mode;
693   mode_t current_mode = 0;
694   mode_t current_mode_mask = 0;
695   int atflag = 0;
696   bool interdir_made = false;
697
698   /* Save 'root device' to avoid purging mount points. */
699   if (one_file_system_option && root_device == 0)
700     {
701       struct stat st;
702
703       if (stat (".", &st) != 0)
704         stat_diag (".");
705       else
706         root_device = st.st_dev;
707     }
708
709   if (incremental_option)
710     /* Read the entry and delete files that aren't listed in the archive.  */
711     purge_directory (file_name);
712   else if (typeflag == GNUTYPE_DUMPDIR)
713     skip_member ();
714
715   /* If ownership or permissions will be restored later, create the
716      directory with restrictive permissions at first, so that in the
717      meantime processes owned by other users do not inadvertently
718      create files under this directory that inherit the wrong owner,
719      group, or permissions from the directory.  If not root, though,
720      make the directory writeable and searchable at first, so that
721      files can be created under it.  */
722   mode = ((current_stat_info.stat.st_mode
723            & (0 < same_owner_option || 0 < same_permissions_option
724               ? S_IRWXU
725               : MODE_RWX))
726           | (we_are_root ? 0 : MODE_WXUSR));
727
728   for (;;)
729     {
730       status = mkdir (file_name, mode);
731       if (status == 0)
732         {
733           current_mode = mode & ~ current_umask;
734           current_mode_mask = MODE_RWX;
735           atflag = AT_SYMLINK_NOFOLLOW;
736           break;
737         }
738
739       if (errno == EEXIST
740           && (interdir_made
741               || old_files_option == DEFAULT_OLD_FILES
742               || old_files_option == OVERWRITE_OLD_FILES))
743         {
744           struct stat st;
745           if (stat (file_name, &st) == 0)
746             {
747               current_mode = st.st_mode;
748               current_mode_mask = ALL_MODE_BITS;
749
750               if (S_ISDIR (current_mode))
751                 {
752                   if (interdir_made)
753                     {
754                       repair_delayed_set_stat (file_name, &st);
755                       return 0;
756                     }
757                   break;
758                 }
759             }
760           errno = EEXIST;
761         }
762
763       switch (maybe_recoverable (file_name, &interdir_made))
764         {
765         case RECOVER_OK:
766           continue;
767
768         case RECOVER_SKIP:
769           break;
770
771         case RECOVER_NO:
772           if (errno != EEXIST)
773             {
774               mkdir_error (file_name);
775               return 1;
776             }
777           break;
778         }
779       break;
780     }
781
782   if (status == 0
783       || old_files_option == DEFAULT_OLD_FILES
784       || old_files_option == OVERWRITE_OLD_FILES)
785     delay_set_stat (file_name, &current_stat_info,
786                     current_mode, current_mode_mask,
787                     current_stat_info.stat.st_mode, atflag);
788   return status;
789 }
790
791
792
793 static int
794 open_output_file (char const *file_name, int typeflag, mode_t mode,
795                   mode_t *current_mode, mode_t *current_mode_mask)
796 {
797   int fd;
798   bool overwriting_old_files = old_files_option == OVERWRITE_OLD_FILES;
799   int openflag = (O_WRONLY | O_BINARY | O_CREAT
800                   | (overwriting_old_files ? O_TRUNC : O_EXCL));
801
802 #if O_CTG
803   /* Contiguous files (on the Masscomp) have to specify the size in
804      the open call that creates them.  */
805
806   if (typeflag == CONTTYPE)
807     fd = open (file_name, openflag | O_CTG, mode, current_stat_info.stat.st_size);
808   else
809     fd = open (file_name, openflag, mode);
810
811 #else /* not O_CTG */
812   if (typeflag == CONTTYPE)
813     {
814       static int conttype_diagnosed;
815
816       if (!conttype_diagnosed)
817         {
818           conttype_diagnosed = 1;
819           WARNOPT (WARN_CONTIGUOUS_CAST,
820                    (0, 0, _("Extracting contiguous files as regular files")));
821         }
822     }
823   fd = open (file_name, openflag, mode);
824
825 #endif /* not O_CTG */
826
827   if (0 <= fd)
828     {
829       if (overwriting_old_files)
830         {
831           struct stat st;
832           if (fstat (fd, &st) != 0)
833             {
834               int e = errno;
835               close (fd);
836               errno = e;
837               return -1;
838             }
839           if (! S_ISREG (st.st_mode))
840             {
841               close (fd);
842               errno = EEXIST;
843               return -1;
844             }
845           *current_mode = st.st_mode;
846           *current_mode_mask = ALL_MODE_BITS;
847         }
848       else
849         {
850           *current_mode = mode & ~ current_umask;
851           *current_mode_mask = MODE_RWX;
852         }
853     }
854
855   return fd;
856 }
857
858 static int
859 extract_file (char *file_name, int typeflag)
860 {
861   int fd;
862   off_t size;
863   union block *data_block;
864   int status;
865   size_t count;
866   size_t written;
867   bool interdir_made = false;
868   mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
869                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
870   mode_t current_mode = 0;
871   mode_t current_mode_mask = 0;
872
873   if (to_stdout_option)
874     fd = STDOUT_FILENO;
875   else if (to_command_option)
876     {
877       fd = sys_exec_command (file_name, 'f', &current_stat_info);
878       if (fd < 0)
879         {
880           skip_member ();
881           return 0;
882         }
883     }
884   else
885     {
886       int recover = RECOVER_NO;
887       do
888         fd = open_output_file (file_name, typeflag, mode,
889                                &current_mode, &current_mode_mask);
890       while (fd < 0
891              && (recover = maybe_recoverable (file_name, &interdir_made))
892                  == RECOVER_OK);
893
894       if (fd < 0)
895         {
896           skip_member ();
897           if (recover == RECOVER_SKIP)
898             return 0;
899           open_error (file_name);
900           return 1;
901         }
902     }
903
904   mv_begin_read (&current_stat_info);
905   if (current_stat_info.is_sparse)
906     sparse_extract_file (fd, &current_stat_info, &size);
907   else
908     for (size = current_stat_info.stat.st_size; size > 0; )
909       {
910         mv_size_left (size);
911
912         /* Locate data, determine max length writeable, write it,
913            block that we have used the data, then check if the write
914            worked.  */
915
916         data_block = find_next_block ();
917         if (! data_block)
918           {
919             ERROR ((0, 0, _("Unexpected EOF in archive")));
920             break;              /* FIXME: What happens, then?  */
921           }
922
923         written = available_space_after (data_block);
924
925         if (written > size)
926           written = size;
927         errno = 0;
928         count = full_write (fd, data_block->buffer, written);
929         size -= written;
930
931         set_next_block_after ((union block *)
932                               (data_block->buffer + written - 1));
933         if (count != written)
934           {
935             if (!to_command_option)
936               write_error_details (file_name, count, written);
937             /* FIXME: shouldn't we restore from backup? */
938             break;
939           }
940       }
941
942   skip_file (size);
943
944   mv_end ();
945
946   /* If writing to stdout, don't try to do anything to the filename;
947      it doesn't exist, or we don't want to touch it anyway.  */
948
949   if (to_stdout_option)
950     return 0;
951
952   if (! to_command_option)
953     set_stat (file_name, &current_stat_info, fd,
954               current_mode, current_mode_mask, typeflag, false,
955               (old_files_option == OVERWRITE_OLD_FILES
956                ? 0 : AT_SYMLINK_NOFOLLOW));
957
958   status = close (fd);
959   if (status < 0)
960     close_error (file_name);
961
962   if (to_command_option)
963     sys_wait_command ();
964
965   return status;
966 }
967
968 /* Create a placeholder file with name FILE_NAME, which will be
969    replaced after other extraction is done by a symbolic link if
970    IS_SYMLINK is true, and by a hard link otherwise.  Set
971    *INTERDIR_MADE if an intermediate directory is made in the
972    process.  */
973
974 static int
975 create_placeholder_file (char *file_name, bool is_symlink, bool *interdir_made)
976 {
977   int fd;
978   struct stat st;
979
980   while ((fd = open (file_name, O_WRONLY | O_CREAT | O_EXCL, 0)) < 0)
981     {
982       switch (maybe_recoverable (file_name, interdir_made))
983         {
984         case RECOVER_OK:
985           continue;
986
987         case RECOVER_SKIP:
988           return 0;
989
990         case RECOVER_NO:
991           open_error (file_name);
992           return -1;
993         }
994       }
995
996   if (fstat (fd, &st) != 0)
997     {
998       stat_error (file_name);
999       close (fd);
1000     }
1001   else if (close (fd) != 0)
1002     close_error (file_name);
1003   else
1004     {
1005       struct delayed_set_stat *h;
1006       struct delayed_link *p =
1007         xmalloc (offsetof (struct delayed_link, target)
1008                  + strlen (current_stat_info.link_name)
1009                  + 1);
1010       p->next = delayed_link_head;
1011       delayed_link_head = p;
1012       p->dev = st.st_dev;
1013       p->ino = st.st_ino;
1014       p->ctime = get_stat_ctime (&st);
1015       p->is_symlink = is_symlink;
1016       if (is_symlink)
1017         {
1018           p->mode = current_stat_info.stat.st_mode;
1019           p->uid = current_stat_info.stat.st_uid;
1020           p->gid = current_stat_info.stat.st_gid;
1021           p->atime = current_stat_info.atime;
1022           p->mtime = current_stat_info.mtime;
1023         }
1024       p->change_dir = chdir_current;
1025       p->sources = xmalloc (offsetof (struct string_list, string)
1026                             + strlen (file_name) + 1);
1027       p->sources->next = 0;
1028       strcpy (p->sources->string, file_name);
1029       strcpy (p->target, current_stat_info.link_name);
1030
1031       h = delayed_set_stat_head;
1032       if (h && ! h->after_links
1033           && strncmp (file_name, h->file_name, h->file_name_len) == 0
1034           && ISSLASH (file_name[h->file_name_len])
1035           && (last_component (file_name) == file_name + h->file_name_len + 1))
1036         {
1037           do
1038             {
1039               h->after_links = 1;
1040
1041               if (stat (h->file_name, &st) != 0)
1042                 stat_error (h->file_name);
1043               else
1044                 {
1045                   h->dev = st.st_dev;
1046                   h->ino = st.st_ino;
1047                 }
1048             }
1049           while ((h = h->next) && ! h->after_links);
1050         }
1051
1052       return 0;
1053     }
1054
1055   return -1;
1056 }
1057
1058 static int
1059 extract_link (char *file_name, int typeflag)
1060 {
1061   bool interdir_made = false;
1062   char const *link_name;
1063   int rc;
1064
1065   link_name = current_stat_info.link_name;
1066
1067   if (! absolute_names_option && contains_dot_dot (link_name))
1068     return create_placeholder_file (file_name, false, &interdir_made);
1069
1070   do
1071     {
1072       struct stat st1, st2;
1073       int e;
1074       int status = link (link_name, file_name);
1075       e = errno;
1076
1077       if (status == 0)
1078         {
1079           struct delayed_link *ds = delayed_link_head;
1080           if (ds && lstat (link_name, &st1) == 0)
1081             for (; ds; ds = ds->next)
1082               if (ds->change_dir == chdir_current
1083                   && ds->dev == st1.st_dev
1084                   && ds->ino == st1.st_ino
1085                   && timespec_cmp (ds->ctime, get_stat_ctime (&st1)) == 0)
1086                 {
1087                   struct string_list *p =  xmalloc (offsetof (struct string_list, string)
1088                                                     + strlen (file_name) + 1);
1089                   strcpy (p->string, file_name);
1090                   p->next = ds->sources;
1091                   ds->sources = p;
1092                   break;
1093                 }
1094           return 0;
1095         }
1096       else if ((e == EEXIST && strcmp (link_name, file_name) == 0)
1097                || (lstat (link_name, &st1) == 0
1098                    && lstat (file_name, &st2) == 0
1099                    && st1.st_dev == st2.st_dev
1100                    && st1.st_ino == st2.st_ino))
1101         return 0;
1102
1103       errno = e;
1104     }
1105   while ((rc = maybe_recoverable (file_name, &interdir_made)) == RECOVER_OK);
1106
1107   if (rc == RECOVER_SKIP)
1108     return 0;
1109   if (!(incremental_option && errno == EEXIST))
1110     {
1111       link_error (link_name, file_name);
1112       return 1;
1113     }
1114   return 0;
1115 }
1116
1117 static int
1118 extract_symlink (char *file_name, int typeflag)
1119 {
1120 #ifdef HAVE_SYMLINK
1121   bool interdir_made = false;
1122
1123   if (! absolute_names_option
1124       && (IS_ABSOLUTE_FILE_NAME (current_stat_info.link_name)
1125           || contains_dot_dot (current_stat_info.link_name)))
1126     return create_placeholder_file (file_name, true, &interdir_made);
1127
1128   while (symlink (current_stat_info.link_name, file_name))
1129     switch (maybe_recoverable (file_name, &interdir_made))
1130       {
1131       case RECOVER_OK:
1132         continue;
1133
1134       case RECOVER_SKIP:
1135         return 0;
1136
1137       case RECOVER_NO:
1138         symlink_error (current_stat_info.link_name, file_name);
1139         return -1;
1140       }
1141
1142   set_stat (file_name, &current_stat_info, -1, 0, 0,
1143             SYMTYPE, false, AT_SYMLINK_NOFOLLOW);
1144   return 0;
1145
1146 #else
1147   static int warned_once;
1148
1149   if (!warned_once)
1150     {
1151       warned_once = 1;
1152       WARNOPT (WARN_SYMBOLIC_CAST,
1153                (0, 0,
1154                 _("Attempting extraction of symbolic links as hard links")));
1155     }
1156   return extract_link (file_name, typeflag);
1157 #endif
1158 }
1159
1160 #if S_IFCHR || S_IFBLK
1161 static int
1162 extract_node (char *file_name, int typeflag)
1163 {
1164   bool interdir_made = false;
1165   mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1166                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1167
1168   while (mknod (file_name, mode, current_stat_info.stat.st_rdev) != 0)
1169     switch (maybe_recoverable (file_name, &interdir_made))
1170       {
1171       case RECOVER_OK:
1172         continue;
1173
1174       case RECOVER_SKIP:
1175         return 0;
1176
1177       case RECOVER_NO:
1178         mknod_error (file_name);
1179         return -1;
1180       }
1181
1182   set_stat (file_name, &current_stat_info, -1,
1183             mode & ~ current_umask, MODE_RWX,
1184             typeflag, false, AT_SYMLINK_NOFOLLOW);
1185   return 0;
1186 }
1187 #endif
1188
1189 #if HAVE_MKFIFO || defined mkfifo
1190 static int
1191 extract_fifo (char *file_name, int typeflag)
1192 {
1193   bool interdir_made = false;
1194   mode_t mode = (current_stat_info.stat.st_mode & MODE_RWX
1195                  & ~ (0 < same_owner_option ? S_IRWXG | S_IRWXO : 0));
1196
1197   while (mkfifo (file_name, mode) != 0)
1198     switch (maybe_recoverable (file_name, &interdir_made))
1199       {
1200       case RECOVER_OK:
1201         continue;
1202
1203       case RECOVER_SKIP:
1204         return 0;
1205
1206       case RECOVER_NO:
1207         mkfifo_error (file_name);
1208         return -1;
1209       }
1210
1211   set_stat (file_name, &current_stat_info, -1,
1212             mode & ~ current_umask, MODE_RWX,
1213             typeflag, false, AT_SYMLINK_NOFOLLOW);
1214   return 0;
1215 }
1216 #endif
1217
1218 static int
1219 extract_volhdr (char *file_name, int typeflag)
1220 {
1221   skip_member ();
1222   return 0;
1223 }
1224
1225 static int
1226 extract_failure (char *file_name, int typeflag)
1227 {
1228   return 1;
1229 }
1230
1231 typedef int (*tar_extractor_t) (char *file_name, int typeflag);
1232
1233 \f
1234
1235 /* Prepare to extract a file. Find extractor function.
1236    Return zero if extraction should not proceed.  */
1237
1238 static int
1239 prepare_to_extract (char const *file_name, int typeflag, tar_extractor_t *fun)
1240 {
1241   int rc = 1;
1242
1243   if (EXTRACT_OVER_PIPE)
1244     rc = 0;
1245
1246   /* Select the extractor */
1247   switch (typeflag)
1248     {
1249     case GNUTYPE_SPARSE:
1250       *fun = extract_file;
1251       rc = 1;
1252       break;
1253
1254     case AREGTYPE:
1255     case REGTYPE:
1256     case CONTTYPE:
1257       /* Appears to be a file.  But BSD tar uses the convention that a slash
1258          suffix means a directory.  */
1259       if (current_stat_info.had_trailing_slash)
1260         *fun = extract_dir;
1261       else
1262         {
1263           *fun = extract_file;
1264           rc = 1;
1265         }
1266       break;
1267
1268     case SYMTYPE:
1269       *fun = extract_symlink;
1270       break;
1271
1272     case LNKTYPE:
1273       *fun = extract_link;
1274       break;
1275
1276 #if S_IFCHR
1277     case CHRTYPE:
1278       current_stat_info.stat.st_mode |= S_IFCHR;
1279       *fun = extract_node;
1280       break;
1281 #endif
1282
1283 #if S_IFBLK
1284     case BLKTYPE:
1285       current_stat_info.stat.st_mode |= S_IFBLK;
1286       *fun = extract_node;
1287       break;
1288 #endif
1289
1290 #if HAVE_MKFIFO || defined mkfifo
1291     case FIFOTYPE:
1292       *fun = extract_fifo;
1293       break;
1294 #endif
1295
1296     case DIRTYPE:
1297     case GNUTYPE_DUMPDIR:
1298       *fun = extract_dir;
1299       if (current_stat_info.is_dumpdir)
1300         delay_directory_restore_option = true;
1301       break;
1302
1303     case GNUTYPE_VOLHDR:
1304       *fun = extract_volhdr;
1305       break;
1306
1307     case GNUTYPE_MULTIVOL:
1308       ERROR ((0, 0,
1309               _("%s: Cannot extract -- file is continued from another volume"),
1310               quotearg_colon (current_stat_info.file_name)));
1311       *fun = extract_failure;
1312       break;
1313
1314     case GNUTYPE_LONGNAME:
1315     case GNUTYPE_LONGLINK:
1316       ERROR ((0, 0, _("Unexpected long name header")));
1317       *fun = extract_failure;
1318       break;
1319
1320     default:
1321       WARNOPT (WARN_UNKNOWN_CAST,
1322                (0, 0,
1323                 _("%s: Unknown file type `%c', extracted as normal file"),
1324                 quotearg_colon (file_name), typeflag));
1325       *fun = extract_file;
1326     }
1327
1328   /* Determine whether the extraction should proceed */
1329   if (rc == 0)
1330     return 0;
1331
1332   switch (old_files_option)
1333     {
1334     case UNLINK_FIRST_OLD_FILES:
1335       if (!remove_any_file (file_name,
1336                             recursive_unlink_option ? RECURSIVE_REMOVE_OPTION
1337                                                       : ORDINARY_REMOVE_OPTION)
1338           && errno && errno != ENOENT)
1339         {
1340           unlink_error (file_name);
1341           return 0;
1342         }
1343       break;
1344
1345     case KEEP_NEWER_FILES:
1346       if (file_newer_p (file_name, &current_stat_info))
1347         {
1348           WARNOPT (WARN_IGNORE_NEWER,
1349                    (0, 0, _("Current %s is newer or same age"),
1350                     quote (file_name)));
1351           return 0;
1352         }
1353       break;
1354
1355     default:
1356       break;
1357     }
1358
1359   return 1;
1360 }
1361
1362 /* Extract a file from the archive.  */
1363 void
1364 extract_archive (void)
1365 {
1366   char typeflag;
1367   tar_extractor_t fun;
1368
1369   fatal_exit_hook = extract_finish;
1370
1371   set_next_block_after (current_header);
1372
1373   if (!current_stat_info.file_name[0]
1374       || (interactive_option
1375           && !confirm ("extract", current_stat_info.file_name)))
1376     {
1377       skip_member ();
1378       return;
1379     }
1380
1381   /* Print the block from current_header and current_stat.  */
1382   if (verbose_option)
1383     print_header (&current_stat_info, current_header, -1);
1384
1385   /* Restore stats for all non-ancestor directories, unless
1386      it is an incremental archive.
1387      (see NOTICE in the comment to delay_set_stat above) */
1388   if (!delay_directory_restore_option)
1389     {
1390       int dir = chdir_current;
1391       apply_nonancestor_delayed_set_stat (current_stat_info.file_name, 0);
1392       chdir_do (dir);
1393     }
1394
1395   /* Take a safety backup of a previously existing file.  */
1396
1397   if (backup_option)
1398     if (!maybe_backup_file (current_stat_info.file_name, 0))
1399       {
1400         int e = errno;
1401         ERROR ((0, e, _("%s: Was unable to backup this file"),
1402                 quotearg_colon (current_stat_info.file_name)));
1403         skip_member ();
1404         return;
1405       }
1406
1407   /* Extract the archive entry according to its type.  */
1408   /* KLUDGE */
1409   typeflag = sparse_member_p (&current_stat_info) ?
1410                   GNUTYPE_SPARSE : current_header->header.typeflag;
1411
1412   if (prepare_to_extract (current_stat_info.file_name, typeflag, &fun))
1413     {
1414       if (fun && (*fun) (current_stat_info.file_name, typeflag)
1415           && backup_option)
1416         undo_last_backup ();
1417     }
1418   else
1419     skip_member ();
1420
1421 }
1422
1423 /* Extract the links whose final extraction were delayed.  */
1424 static void
1425 apply_delayed_links (void)
1426 {
1427   struct delayed_link *ds;
1428
1429   for (ds = delayed_link_head; ds; )
1430     {
1431       struct string_list *sources = ds->sources;
1432       char const *valid_source = 0;
1433
1434       chdir_do (ds->change_dir);
1435
1436       for (sources = ds->sources; sources; sources = sources->next)
1437         {
1438           char const *source = sources->string;
1439           struct stat st;
1440
1441           /* Make sure the placeholder file is still there.  If not,
1442              don't create a link, as the placeholder was probably
1443              removed by a later extraction.  */
1444           if (lstat (source, &st) == 0
1445               && st.st_dev == ds->dev
1446               && st.st_ino == ds->ino
1447               && timespec_cmp (get_stat_ctime (&st), ds->ctime) == 0)
1448             {
1449               /* Unlink the placeholder, then create a hard link if possible,
1450                  a symbolic link otherwise.  */
1451               if (unlink (source) != 0)
1452                 unlink_error (source);
1453               else if (valid_source && link (valid_source, source) == 0)
1454                 ;
1455               else if (!ds->is_symlink)
1456                 {
1457                   if (link (ds->target, source) != 0)
1458                     link_error (ds->target, source);
1459                 }
1460               else if (symlink (ds->target, source) != 0)
1461                 symlink_error (ds->target, source);
1462               else
1463                 {
1464                   struct tar_stat_info st1;
1465                   st1.stat.st_mode = ds->mode;
1466                   st1.stat.st_uid = ds->uid;
1467                   st1.stat.st_gid = ds->gid;
1468                   st1.atime = ds->atime;
1469                   st1.mtime = ds->mtime;
1470                   set_stat (source, &st1, -1, 0, 0, SYMTYPE,
1471                             false, AT_SYMLINK_NOFOLLOW);
1472                   valid_source = source;
1473                 }
1474             }
1475         }
1476
1477       for (sources = ds->sources; sources; )
1478         {
1479           struct string_list *next = sources->next;
1480           free (sources);
1481           sources = next;
1482         }
1483
1484       {
1485         struct delayed_link *next = ds->next;
1486         free (ds);
1487         ds = next;
1488       }
1489     }
1490
1491   delayed_link_head = 0;
1492 }
1493
1494 /* Finish the extraction of an archive.  */
1495 void
1496 extract_finish (void)
1497 {
1498   /* First, fix the status of ordinary directories that need fixing.  */
1499   apply_nonancestor_delayed_set_stat ("", 0);
1500
1501   /* Then, apply delayed links, so that they don't affect delayed
1502      directory status-setting for ordinary directories.  */
1503   apply_delayed_links ();
1504
1505   /* Finally, fix the status of directories that are ancestors
1506      of delayed links.  */
1507   apply_nonancestor_delayed_set_stat ("", 1);
1508 }
1509
1510 bool
1511 rename_directory (char *src, char *dst)
1512 {
1513   if (rename (src, dst))
1514     {
1515       int e = errno;
1516
1517       switch (e)
1518         {
1519         case ENOENT:
1520           if (make_directories (dst))
1521             {
1522               if (rename (src, dst) == 0)
1523                 return true;
1524               e = errno;
1525             }
1526           break;
1527
1528         case EXDEV:
1529           /* FIXME: Fall back to recursive copying */
1530
1531         default:
1532           break;
1533         }
1534
1535       ERROR ((0, e, _("Cannot rename %s to %s"),
1536               quote_n (0, src),
1537               quote_n (1, dst)));
1538       return false;
1539     }
1540   return true;
1541 }