9d47c58bcd8b1fdc04799bcc1cf7e1c54fcc3f91
[debian/tar] / src / extract.c
1 /* Extract files from a tar archive.
2    Copyright 1988, 92,93,94,96,97,98, 1999 Free Software Foundation, Inc.
3    Written by John Gilmore, on 1985-11-19.
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published by the
7    Free Software Foundation; either version 2, or (at your option) any later
8    version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
13    Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation, Inc.,
17    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 #include "system.h"
20
21 #if HAVE_UTIME_H
22 # include <utime.h>
23 #else
24 struct utimbuf
25   {
26     long actime;
27     long modtime;
28   };
29 #endif
30
31 #include "common.h"
32
33 static int we_are_root;         /* true if our effective uid == 0 */
34 static mode_t newdir_umask;     /* umask when creating new directories */
35 static mode_t current_umask;    /* current umask (which is set to 0 if -p) */
36
37 struct delayed_set_stat
38   {
39     struct delayed_set_stat *next;
40     char *file_name;
41     struct stat stat_info;
42   };
43
44 static struct delayed_set_stat *delayed_set_stat_head;
45
46 /*--------------------------.
47 | Set up to extract files.  |
48 `--------------------------*/
49
50 void
51 extr_init (void)
52 {
53   we_are_root = geteuid () == 0;
54   same_permissions_option += we_are_root;
55   same_owner_option += we_are_root;
56
57   /* Option -p clears the kernel umask, so it does not affect proper
58      restoration of file permissions.  New intermediate directories will
59      comply with umask at start of program.  */
60
61   newdir_umask = umask (0);
62   if (0 < same_permissions_option)
63     current_umask = 0;
64   else
65     {
66       umask (newdir_umask);     /* restore the kernel umask */
67       current_umask = newdir_umask;
68     }
69
70   /* FIXME: Just make sure we can add files in directories we create.  Maybe
71      should we later remove permissions we are adding, here?  */
72   newdir_umask &= ~ MODE_WXUSR;
73 }
74
75 /*------------------------------------------------------------------.
76 | Restore mode for FILE_NAME, from information given in STAT_INFO.  |
77 `------------------------------------------------------------------*/
78
79 static void
80 set_mode (char *file_name, struct stat *stat_info)
81 {
82   /* Do nothing unless we are restoring the original permissions.
83
84      We must force permission when -k and -U are not selected, because if the
85      file already existed, open or creat would save the permission bits from
86      the previously created file, ignoring the ones we specified.
87
88      But with -k or -U selected, we know *we* created this file, so the mode
89      bits were set by our open.  If the file has abnormal mode bits, we must
90      chmod since writing or chown has probably reset them.  If the file is
91      normal, we merely skip the chmod.  This works because we did umask (0)
92      when -p, so umask will have left the specified mode alone.  */
93
94   if (0 < same_permissions_option
95       && ((!keep_old_files_option && !unlink_first_option)
96           || (stat_info->st_mode & (S_ISUID | S_ISGID | S_ISVTX))))
97     if (chmod (file_name, ~current_umask & stat_info->st_mode) < 0)
98       ERROR ((0, errno, _("%s: Cannot change mode to %04lo"),
99               file_name,
100               (unsigned long) (~current_umask & stat_info->st_mode)));
101 }
102
103 /*----------------------------------------------------------------------.
104 | Restore stat attributes (owner, group, mode and times) for FILE_NAME, |
105 | using information given in STAT_INFO.  SYMLINK_FLAG is non-zero for a |
106 | freshly restored symbolic link.                                       |
107 `----------------------------------------------------------------------*/
108
109 /* FIXME: About proper restoration of symbolic link attributes, we still do
110    not have it right.  Pretesters' reports tell us we need further study and
111    probably more configuration.  For now, just use lchown if it exists, and
112    punt for the rest.  Sigh!  */
113
114 static void
115 set_stat (char *file_name, struct stat *stat_info, int symlink_flag)
116 {
117   struct utimbuf utimbuf;
118
119   if (!symlink_flag)
120     {
121       /* We do the utime before the chmod because some versions of utime are
122          broken and trash the modes of the file.  */
123
124       if (!touch_option)
125         {
126           /* We set the accessed time to `now', which is really the time we
127              started extracting files, unless incremental_option is used, in
128              which case .st_atime is used.  */
129
130           /* FIXME: incremental_option should set ctime too, but how?  */
131
132           if (incremental_option)
133             utimbuf.actime = stat_info->st_atime;
134           else
135             utimbuf.actime = start_time;
136
137           utimbuf.modtime = stat_info->st_mtime;
138
139           if (utime (file_name, &utimbuf) < 0)
140             ERROR ((0, errno,
141                     _("%s: Could not change access and modification times"),
142                     file_name));
143         }
144
145       /* Some systems allow non-root users to give files away.  Once this
146          done, it is not possible anymore to change file permissions, so we
147          have to set permissions prior to possibly giving files away.  */
148
149       set_mode (file_name, stat_info);
150     }
151
152   /* If we are root, set the owner and group of the extracted file, so we
153      extract as the original owner.  Or else, if we are running as a user,
154      leave the owner and group as they are, so we extract as that user.  */
155
156   if (0 < same_owner_option)
157     {
158       /* When lchown exists, it should be used to change the attributes of
159          the symbolic link itself.  In this case, a mere chown would change
160          the attributes of the file the symbolic link is pointing to, and
161          should be avoided.  */
162
163       if (symlink_flag)
164         {
165 #if HAVE_LCHOWN
166           if (lchown (file_name, stat_info->st_uid, stat_info->st_gid) < 0)
167             ERROR ((0, errno, _("%s: Cannot lchown to uid %lu gid %lu"),
168                     file_name,
169                     (unsigned long) stat_info->st_uid,
170                     (unsigned long) stat_info->st_gid));
171 #endif
172         }
173       else
174         {
175           if (chown (file_name, stat_info->st_uid, stat_info->st_gid) < 0)
176             ERROR ((0, errno, _("%s: Cannot chown to uid %lu gid %lu"),
177                     file_name,
178                     (unsigned long) stat_info->st_uid,
179                     (unsigned long) stat_info->st_gid));
180
181           /* On a few systems, and in particular, those allowing to give files
182              away, changing the owner or group destroys the suid or sgid bits.
183              So let's attempt setting these bits once more.  */
184           if (stat_info->st_mode & (S_ISUID | S_ISGID | S_ISVTX))
185             set_mode (file_name, stat_info);
186         }
187     }
188 }
189
190 /*-----------------------------------------------------------------------.
191 | After a file/link/symlink/directory creation has failed, see if it's   |
192 | because some required directory was not present, and if so, create all |
193 | required directories.  Return non-zero if a directory was created.     |
194 `-----------------------------------------------------------------------*/
195
196 static int
197 make_directories (char *file_name)
198 {
199   char *cursor;                 /* points into path */
200   int did_something = 0;        /* did we do anything yet? */
201   int saved_errno = errno;      /* remember caller's errno */
202   int status;
203
204   for (cursor = strchr (file_name, '/');
205        cursor;
206        cursor = strchr (cursor + 1, '/'))
207     {
208       /* Avoid mkdir of empty string, if leading or double '/'.  */
209
210       if (cursor == file_name || cursor[-1] == '/')
211         continue;
212
213       /* Avoid mkdir where last part of path is '.'.  */
214
215       if (cursor[-1] == '.' && (cursor == file_name + 1 || cursor[-2] == '/'))
216         continue;
217
218       *cursor = '\0';           /* truncate the path there */
219       status = mkdir (file_name, ~newdir_umask & MODE_RWX);
220
221       if (status == 0)
222         {
223           print_for_mkdir (file_name, cursor - file_name,
224                            ~newdir_umask & MODE_RWX);
225           did_something = 1;
226
227           *cursor = '/';
228           continue;
229         }
230
231       *cursor = '/';
232
233       if (errno == EEXIST
234 #if MSDOS
235           /* Turbo C mkdir gives a funny errno.  */
236           || errno == EACCES
237 #endif
238           )
239         /* Directory already exists.  */
240         continue;
241
242       /* Some other error in the mkdir.  We return to the caller.  */
243       break;
244     }
245
246   errno = saved_errno;
247   return did_something;         /* tell them to retry if we made one */
248 }
249
250 /*--------------------------------------------------------------------.
251 | Unlink the destination, if we are supposed to do so.                |
252 | Return zero if extraction should not proceed.                       |
253 `--------------------------------------------------------------------*/
254
255 static int
256 unlink_destination (char const *file_name)
257 {
258   if (unlink_first_option
259       && !remove_any_file (file_name, recursive_unlink_option)
260       && errno != ENOENT)
261     {
262       ERROR ((0, errno, _("Cannot remove %s"), file_name));
263       return 0;
264     }
265
266   return 1;
267 }
268
269 /*--------------------------------------------------------------------.
270 | Attempt repairing what went wrong with the extraction.  Delete an   |
271 | already existing file or create missing intermediate directories.   |
272 | Return nonzero if we somewhat increased our chances at a successful |
273 | extraction.  errno is properly restored on zero return.             |
274 `--------------------------------------------------------------------*/
275
276 static int
277 maybe_recoverable (char *file_name)
278 {
279   switch (errno)
280     {
281     case EEXIST:
282       /* Attempt deleting an existing file.  However, with -k or -U, just stay
283          quiet.  */
284
285       if (keep_old_files_option || unlink_first_option)
286         return 0;
287
288       return remove_any_file (file_name, 0);
289
290     case ENOENT:
291       /* Attempt creating missing intermediate directories.  */
292
293       return make_directories (file_name);
294
295     default:
296       /* Just say we can't do anything about it...  */
297
298       return 0;
299     }
300 }
301
302 /*---.
303 | ?  |
304 `---*/
305
306 static void
307 extract_sparse_file (int fd, off_t *sizeleft, off_t totalsize, char *name)
308 {
309   int sparse_ind = 0;
310   size_t written;
311   ssize_t count;
312
313   /* assuming sizeleft is initially totalsize */
314
315   while (*sizeleft > 0)
316     {
317       union block *data_block = find_next_block ();
318       if (! data_block)
319         {
320           ERROR ((0, 0, _("Unexpected EOF on archive file")));
321           return;
322         }
323       if (lseek (fd, sparsearray[sparse_ind].offset, SEEK_SET) < 0)
324         {
325           char buf[UINTMAX_STRSIZE_BOUND];
326           ERROR ((0, errno, _("%s: lseek error at byte %s"),
327                   STRINGIFY_BIGINT (sparsearray[sparse_ind].offset, buf),
328                   name));
329           return;
330         }
331       written = sparsearray[sparse_ind++].numbytes;
332       while (written > BLOCKSIZE)
333         {
334           count = full_write (fd, data_block->buffer, BLOCKSIZE);
335           if (count < 0)
336             ERROR ((0, errno, _("%s: Could not write to file"), name));
337           written -= count;
338           *sizeleft -= count;
339           set_next_block_after (data_block);
340           data_block = find_next_block ();
341           if (! data_block)
342             {
343               ERROR ((0, 0, _("Unexpected EOF on archive file")));
344               return;
345             }
346         }
347
348       count = full_write (fd, data_block->buffer, written);
349
350       if (count < 0)
351         ERROR ((0, errno, _("%s: Could not write to file"), name));
352       else if (count != written)
353         {
354           char buf1[UINTMAX_STRSIZE_BOUND];
355           char buf2[UINTMAX_STRSIZE_BOUND];
356           ERROR ((0, 0, _("%s: Could only write %s of %s bytes"),
357                   name,
358                   STRINGIFY_BIGINT (totalsize - *sizeleft, buf1),
359                   STRINGIFY_BIGINT (totalsize, buf2)));
360           skip_file (*sizeleft);
361         }
362
363       written -= count;
364       *sizeleft -= count;
365       set_next_block_after (data_block);
366     }
367
368   free (sparsearray);
369 }
370
371 /*----------------------------------.
372 | Extract a file from the archive.  |
373 `----------------------------------*/
374
375 void
376 extract_archive (void)
377 {
378   union block *data_block;
379   int fd;
380   int status;
381   ssize_t sstatus;
382   size_t name_length;
383   size_t written;
384   int openflag;
385   off_t size;
386   int skipcrud;
387   int counter;
388   char typeflag;
389 #if 0
390   int sparse_ind = 0;
391 #endif
392   union block *exhdr;
393   struct delayed_set_stat *data;
394
395 #define CURRENT_FILE_NAME (skipcrud + current_file_name)
396
397   set_next_block_after (current_header);
398   decode_header (current_header, &current_stat, &current_format, 1);
399
400   if (interactive_option && !confirm ("extract", current_file_name))
401     {
402       if (current_header->oldgnu_header.isextended)
403         skip_extended_headers ();
404       skip_file (current_stat.st_size);
405       return;
406     }
407
408   /* Print the block from `current_header' and `current_stat'.  */
409
410   if (verbose_option)
411     print_header ();
412
413   /* Check for fully specified file names and other atrocities.  */
414
415   skipcrud = 0;
416   while (!absolute_names_option && CURRENT_FILE_NAME[0] == '/')
417     {
418       static int warned_once;
419
420       if (!warned_once)
421         {
422           warned_once = 1;
423           WARN ((0, 0, _("Removing leading `/' from archive names")));
424         }
425       skipcrud++;               /* force relative path */
426     }
427
428   /* Take a safety backup of a previously existing file.  */
429
430   if (backup_option && !to_stdout_option)
431     if (!maybe_backup_file (CURRENT_FILE_NAME, 0))
432       {
433         ERROR ((0, errno, _("%s: Was unable to backup this file"),
434                 CURRENT_FILE_NAME));
435         if (current_header->oldgnu_header.isextended)
436           skip_extended_headers ();
437         skip_file (current_stat.st_size);
438         return;
439       }
440
441   /* Extract the archive entry according to its type.  */
442
443   typeflag = current_header->header.typeflag;
444   switch (typeflag)
445     {
446       /* JK - What we want to do if the file is sparse is loop through
447          the array of sparse structures in the header and read in and
448          translate the character strings representing 1) the offset at
449          which to write and 2) how many bytes to write into numbers,
450          which we store into the scratch array, "sparsearray".  This
451          array makes our life easier the same way it did in creating the
452          tar file that had to deal with a sparse file.
453
454          After we read in the first five (at most) sparse structures, we
455          check to see if the file has an extended header, i.e., if more
456          sparse structures are needed to describe the contents of the new
457          file.  If so, we read in the extended headers and continue to
458          store their contents into the sparsearray.  */
459
460     case GNUTYPE_SPARSE:
461       sp_array_size = 10;
462       sparsearray =
463         xmalloc (sp_array_size * sizeof (struct sp_array));
464
465       for (counter = 0; counter < SPARSES_IN_OLDGNU_HEADER; counter++)
466         {
467           struct sparse const *s = &current_header->oldgnu_header.sp[counter];
468           sparsearray[counter].offset = OFF_FROM_HEADER (s->offset);
469           sparsearray[counter].numbytes = SIZE_FROM_HEADER (s->numbytes);
470           if (!sparsearray[counter].numbytes)
471             break;
472         }
473
474       if (current_header->oldgnu_header.isextended)
475         {
476           /* Read in the list of extended headers and translate them
477              into the sparsearray as before.  Note that this
478              invalidates current_header.  */
479
480           /* static */ int ind = SPARSES_IN_OLDGNU_HEADER;
481
482           while (1)
483             {
484               exhdr = find_next_block ();
485               if (! exhdr)
486                 {
487                   ERROR ((0, 0, _("Unexpected EOF on archive file")));
488                   return;
489                 }
490               for (counter = 0; counter < SPARSES_IN_SPARSE_HEADER; counter++)
491                 {
492                   struct sparse const *s = &exhdr->sparse_header.sp[counter];
493                   if (counter + ind > sp_array_size - 1)
494                     {
495                       /* Realloc the scratch area since we've run out of
496                          room.  */
497
498                       sp_array_size *= 2;
499                       sparsearray =
500                         xrealloc (sparsearray,
501                                   sp_array_size * sizeof (struct sp_array));
502                     }
503                   if (s->numbytes[0] == 0)
504                     break;
505                   sparsearray[counter + ind].offset =
506                     OFF_FROM_HEADER (s->offset);
507                   sparsearray[counter + ind].numbytes =
508                     SIZE_FROM_HEADER (s->numbytes);
509                 }
510               if (!exhdr->sparse_header.isextended)
511                 break;
512               else
513                 {
514                   ind += SPARSES_IN_SPARSE_HEADER;
515                   set_next_block_after (exhdr);
516                 }
517             }
518           set_next_block_after (exhdr);
519         }
520       /* Fall through.  */
521
522     case AREGTYPE:
523     case REGTYPE:
524     case CONTTYPE:
525
526       /* Appears to be a file.  But BSD tar uses the convention that a slash
527          suffix means a directory.  */
528
529       name_length = strlen (CURRENT_FILE_NAME) - 1;
530       if (CURRENT_FILE_NAME[name_length] == '/')
531         goto really_dir;
532
533       /* FIXME: deal with protection issues.  */
534
535     again_file:
536       openflag = (keep_old_files_option || unlink_first_option ?
537                   O_WRONLY | O_BINARY | O_NONBLOCK | O_CREAT | O_EXCL :
538                   O_WRONLY | O_BINARY | O_NONBLOCK | O_CREAT | O_TRUNC)
539         | ((typeflag == GNUTYPE_SPARSE) ? 0 : O_APPEND);
540
541       /* JK - The last | is a kludge to solve the problem the O_APPEND
542          flag causes with files we are trying to make sparse: when a file
543          is opened with O_APPEND, it writes to the last place that
544          something was written, thereby ignoring any lseeks that we have
545          done.  We add this extra condition to make it able to lseek when
546          a file is sparse, i.e., we don't open the new file with this
547          flag.  (Grump -- this bug caused me to waste a good deal of
548          time, I might add)  */
549
550       if (to_stdout_option)
551         {
552           fd = 1;
553           goto extract_file;
554         }
555
556       if (!unlink_destination (CURRENT_FILE_NAME))
557         {
558           if (current_header->oldgnu_header.isextended)
559             skip_extended_headers ();
560           skip_file (current_stat.st_size);
561           if (backup_option)
562             undo_last_backup ();
563           break;
564         }
565
566 #if O_CTG
567       /* Contiguous files (on the Masscomp) have to specify the size in
568          the open call that creates them.  */
569
570       if (typeflag == CONTTYPE)
571         fd = open (CURRENT_FILE_NAME, openflag | O_CTG,
572                    current_stat.st_mode, current_stat.st_size);
573       else
574         fd = open (CURRENT_FILE_NAME, openflag, current_stat.st_mode);
575
576 #else /* not O_CTG */
577       if (typeflag == CONTTYPE)
578         {
579           static int conttype_diagnosed;
580
581           if (!conttype_diagnosed)
582             {
583               conttype_diagnosed = 1;
584               WARN ((0, 0, _("Extracting contiguous files as regular files")));
585             }
586         }
587       fd = open (CURRENT_FILE_NAME, openflag, current_stat.st_mode);
588
589 #endif /* not O_CTG */
590
591       if (fd < 0)
592         {
593           if (maybe_recoverable (CURRENT_FILE_NAME))
594             goto again_file;
595
596           ERROR ((0, errno, _("%s: Could not create file"),
597                   CURRENT_FILE_NAME));
598           if (current_header->oldgnu_header.isextended)
599             skip_extended_headers ();
600           skip_file (current_stat.st_size);
601           if (backup_option)
602             undo_last_backup ();
603           break;
604         }
605
606     extract_file:
607       if (typeflag == GNUTYPE_SPARSE)
608         {
609           char *name;
610           size_t name_length_bis;
611
612           /* Kludge alert.  NAME is assigned to header.name because
613              during the extraction, the space that contains the header
614              will get scribbled on, and the name will get munged, so any
615              error messages that happen to contain the filename will look
616              REAL interesting unless we do this.  */
617
618           name_length_bis = strlen (CURRENT_FILE_NAME) + 1;
619           name = xmalloc (name_length_bis);
620           memcpy (name, CURRENT_FILE_NAME, name_length_bis);
621           size = current_stat.st_size;
622           extract_sparse_file (fd, &size, current_stat.st_size, name);
623         }
624       else
625         for (size = current_stat.st_size;
626              size > 0;
627              size -= written)
628           {
629             if (multi_volume_option)
630               {
631                 assign_string (&save_name, current_file_name);
632                 save_totsize = current_stat.st_size;
633                 save_sizeleft = size;
634               }
635
636             /* Locate data, determine max length writeable, write it,
637                block that we have used the data, then check if the write
638                worked.  */
639
640             data_block = find_next_block ();
641             if (! data_block)
642               {
643                 ERROR ((0, 0, _("Unexpected EOF on archive file")));
644                 break;          /* FIXME: What happens, then?  */
645               }
646
647             written = available_space_after (data_block);
648
649             if (written > size)
650               written = size;
651             errno = 0;
652             sstatus = full_write (fd, data_block->buffer, written);
653
654             set_next_block_after ((union block *)
655                                   (data_block->buffer + written - 1));
656             if (sstatus == written)
657               continue;
658
659             /* Error in writing to file.  Print it, skip to next file in
660                archive.  */
661
662             if (sstatus < 0)
663               ERROR ((0, errno, _("%s: Could not write to file"),
664                       CURRENT_FILE_NAME));
665             else
666               ERROR ((0, 0, _("%s: Could only write %lu of %lu bytes"),
667                       CURRENT_FILE_NAME,
668                       (unsigned long) sstatus,
669                       (unsigned long) written));
670             skip_file (size - written);
671             break;              /* still do the close, mod time, chmod, etc */
672           }
673
674       if (multi_volume_option)
675         assign_string (&save_name, 0);
676
677       /* If writing to stdout, don't try to do anything to the filename;
678          it doesn't exist, or we don't want to touch it anyway.  */
679
680       if (to_stdout_option)
681         break;
682
683       status = close (fd);
684       if (status < 0)
685         {
686           ERROR ((0, errno, _("%s: Error while closing"), CURRENT_FILE_NAME));
687           if (backup_option)
688             undo_last_backup ();
689         }
690
691       set_stat (CURRENT_FILE_NAME, &current_stat, 0);
692       break;
693
694     case SYMTYPE:
695       if (to_stdout_option)
696         break;
697
698 #ifdef HAVE_SYMLINK
699       if (!unlink_destination (CURRENT_FILE_NAME))
700         break;
701
702       while (status = symlink (current_link_name, CURRENT_FILE_NAME),
703              status != 0)
704         if (!maybe_recoverable (CURRENT_FILE_NAME))
705           break;
706
707       if (status == 0)
708
709         /* Setting the attributes of symbolic links might, on some systems,
710            change the pointed to file, instead of the symbolic link itself.
711            At least some of these systems have a lchown call, and the
712            set_stat routine knows about this.    */
713
714         set_stat (CURRENT_FILE_NAME, &current_stat, 1);
715
716       else
717         {
718           ERROR ((0, errno, _("%s: Could not create symlink to `%s'"),
719                   CURRENT_FILE_NAME, current_link_name));
720           if (backup_option)
721             undo_last_backup ();
722         }
723       break;
724
725 #else
726       {
727         static int warned_once;
728
729         if (!warned_once)
730           {
731             warned_once = 1;
732             WARN ((0, 0,
733                    _("Attempting extraction of symbolic links as hard links")));
734           }
735       }
736       /* Fall through.  */
737
738 #endif
739
740     case LNKTYPE:
741       if (to_stdout_option)
742         break;
743
744       if (!unlink_destination (CURRENT_FILE_NAME))
745         break;
746
747     again_link:
748       {
749         struct stat st1, st2;
750
751         /* MSDOS does not implement links.  However, djgpp's link() actually
752            copies the file.  */
753         status = link (current_link_name, CURRENT_FILE_NAME);
754
755         if (status == 0)
756           break;
757         if (maybe_recoverable (CURRENT_FILE_NAME))
758           goto again_link;
759
760         if (incremental_option && errno == EEXIST)
761           break;
762         if (stat (current_link_name, &st1) == 0
763             && stat (CURRENT_FILE_NAME, &st2) == 0
764             && st1.st_dev == st2.st_dev
765             && st1.st_ino == st2.st_ino)
766           break;
767
768         ERROR ((0, errno, _("%s: Could not link to `%s'"),
769                 CURRENT_FILE_NAME, current_link_name));
770         if (backup_option)
771           undo_last_backup ();
772       }
773       break;
774
775 #if S_IFCHR
776     case CHRTYPE:
777       current_stat.st_mode |= S_IFCHR;
778       goto make_node;
779 #endif
780
781 #if S_IFBLK
782     case BLKTYPE:
783       current_stat.st_mode |= S_IFBLK;
784 #endif
785
786 #if S_IFCHR || S_IFBLK
787     make_node:
788       if (to_stdout_option)
789         break;
790
791       if (!unlink_destination (CURRENT_FILE_NAME))
792         break;
793
794       status = mknod (CURRENT_FILE_NAME, current_stat.st_mode,
795                       current_stat.st_rdev);
796       if (status != 0)
797         {
798           if (maybe_recoverable (CURRENT_FILE_NAME))
799             goto make_node;
800
801           ERROR ((0, errno, _("%s: Could not make node"), CURRENT_FILE_NAME));
802           if (backup_option)
803             undo_last_backup ();
804           break;
805         };
806       set_stat (CURRENT_FILE_NAME, &current_stat, 0);
807       break;
808 #endif
809
810 #if HAVE_MKFIFO || defined mkfifo
811     case FIFOTYPE:
812       if (to_stdout_option)
813         break;
814
815       if (!unlink_destination (CURRENT_FILE_NAME))
816         break;
817
818       while (status = mkfifo (CURRENT_FILE_NAME, current_stat.st_mode),
819              status != 0)
820         if (!maybe_recoverable (CURRENT_FILE_NAME))
821           break;
822
823       if (status == 0)
824         set_stat (CURRENT_FILE_NAME, &current_stat, 0);
825       else
826         {
827           ERROR ((0, errno, _("%s: Could not make fifo"), CURRENT_FILE_NAME));
828           if (backup_option)
829             undo_last_backup ();
830         }
831       break;
832 #endif
833
834     case DIRTYPE:
835     case GNUTYPE_DUMPDIR:
836       name_length = strlen (CURRENT_FILE_NAME) - 1;
837
838     really_dir:
839       /* Check for trailing /, and zap as many as we find.  */
840       while (name_length && CURRENT_FILE_NAME[name_length] == '/')
841         CURRENT_FILE_NAME[name_length--] = '\0';
842
843       if (incremental_option)
844         {
845           /* Read the entry and delete files that aren't listed in the
846              archive.  */
847
848           gnu_restore (skipcrud);
849         }
850       else if (typeflag == GNUTYPE_DUMPDIR)
851         skip_file (current_stat.st_size);
852
853       if (to_stdout_option)
854         break;
855
856     again_dir:
857       status = mkdir (CURRENT_FILE_NAME,
858                       ((we_are_root ? 0 : MODE_WXUSR)
859                        | current_stat.st_mode));
860       if (status != 0)
861         {
862           /* If the directory creation fails, let's consider immediately the
863              case where the directory already exists.  We have three good
864              reasons for clearing out this case before attempting recovery.
865
866              1) It would not be efficient recovering the error by deleting
867              the directory in maybe_recoverable, then recreating it right
868              away.  We only hope we will be able to adjust its permissions
869              adequately, later.
870
871              2) Removing the directory might fail if it is not empty.  By
872              exception, this real error is traditionally not reported.
873
874              3) Let's suppose `DIR' already exists and we are about to
875              extract `DIR/../DIR'.  This would fail because the directory
876              already exists, and maybe_recoverable would react by removing
877              `DIR'.  This then would fail again because there are missing
878              intermediate directories, and maybe_recoverable would react by
879              creating `DIR'.  We would then have an extraction loop.  */
880
881           if (errno == EEXIST)
882             {
883               struct stat st1;
884               int saved_errno = errno;
885
886               if (stat (CURRENT_FILE_NAME, &st1) == 0 && S_ISDIR (st1.st_mode))
887                 goto check_perms;
888
889               errno = saved_errno;
890             }
891
892           if (maybe_recoverable (CURRENT_FILE_NAME))
893             goto again_dir;
894
895           /* If we're trying to create '.', let it be.  */
896
897           /* FIXME: Strange style...  */
898
899           if (CURRENT_FILE_NAME[name_length] == '.'
900               && (name_length == 0
901                   || CURRENT_FILE_NAME[name_length - 1] == '/'))
902             goto check_perms;
903
904           ERROR ((0, errno, _("%s: Could not create directory"),
905                   CURRENT_FILE_NAME));
906           if (backup_option)
907             undo_last_backup ();
908           break;
909         }
910
911     check_perms:
912       if (!we_are_root && MODE_WXUSR != (MODE_WXUSR & current_stat.st_mode))
913         {
914           current_stat.st_mode |= MODE_WXUSR;
915           WARN ((0, 0, _("Added write and execute permission to directory %s"),
916                  CURRENT_FILE_NAME));
917         }
918
919 #if !MSDOS
920       /* MSDOS does not associate time stamps with directories.   In this
921          case, no need to try delaying their restoration.  */
922
923       if (touch_option)
924
925         /* FIXME: I do not believe in this.  Ignoring time stamps does not
926            alleviate the need of delaying the restoration of directories'
927            mode.  Let's ponder this for a little while.  */
928
929         set_mode (CURRENT_FILE_NAME, &current_stat);
930
931       else
932         {
933           data = xmalloc (sizeof (struct delayed_set_stat));
934           data->file_name = xstrdup (CURRENT_FILE_NAME);
935           data->stat_info = current_stat;
936           data->next = delayed_set_stat_head;
937           delayed_set_stat_head = data;
938         }
939 #endif /* !MSDOS */
940       break;
941
942     case GNUTYPE_VOLHDR:
943       if (verbose_option)
944         fprintf (stdlis, _("Reading %s\n"), current_file_name);
945       break;
946
947     case GNUTYPE_NAMES:
948       extract_mangle ();
949       break;
950
951     case GNUTYPE_MULTIVOL:
952       ERROR ((0, 0,
953               _("Cannot extract `%s' -- file is continued from another volume"),
954               current_file_name));
955       skip_file (current_stat.st_size);
956       if (backup_option)
957         undo_last_backup ();
958       break;
959
960     case GNUTYPE_LONGNAME:
961     case GNUTYPE_LONGLINK:
962       ERROR ((0, 0, _("Visible long name error")));
963       skip_file (current_stat.st_size);
964       if (backup_option)
965         undo_last_backup ();
966       break;
967
968     default:
969       WARN ((0, 0,
970              _("Unknown file type '%c' for %s, extracted as normal file"),
971              typeflag, CURRENT_FILE_NAME));
972       goto again_file;
973     }
974
975 #undef CURRENT_FILE_NAME
976 }
977
978 /*----------------------------------------------------------------.
979 | Set back the utime and mode for all the extracted directories.  |
980 `----------------------------------------------------------------*/
981
982 void
983 apply_delayed_set_stat (void)
984 {
985   struct delayed_set_stat *data;
986
987   while (delayed_set_stat_head)
988     {
989       data = delayed_set_stat_head;
990       delayed_set_stat_head = delayed_set_stat_head->next;
991       set_stat (data->file_name, &data->stat_info, 0);
992       free (data->file_name);
993       free (data);
994     }
995 }