(check_label_pattern): Make sure header name is a string before
[debian/tar] / src / buffer.c
1 /* Buffer management for tar.
2    Copyright 1988, 92, 93, 94, 96, 97, 99, 2000 Free Software Foundation, Inc.
3    Written by John Gilmore, on 1985-08-25.
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 #include <signal.h>
22 #include <time.h>
23 #ifndef time
24 time_t time ();
25 #endif
26
27 #if MSDOS
28 # include <process.h>
29 #endif
30
31 #if XENIX
32 # include <sys/inode.h>
33 #endif
34
35 #include <fnmatch.h>
36 #include <human.h>
37 #include <quotearg.h>
38
39 #include "common.h"
40 #include "rmt.h"
41
42 #define PREAD 0                 /* read file descriptor from pipe() */
43 #define PWRITE 1                /* write file descriptor from pipe() */
44
45 /* Number of retries before giving up on read.  */
46 #define READ_ERROR_MAX 10
47
48 /* Globbing pattern to append to volume label if initial match failed.  */
49 #define VOLUME_LABEL_APPEND " Volume [1-9]*"
50 \f
51 /* Variables.  */
52
53 static tarlong prev_written;    /* bytes written on previous volumes */
54 static tarlong bytes_written;   /* bytes written on this volume */
55
56 /* FIXME: The following four variables should ideally be static to this
57    module.  However, this cannot be done yet, as update.c uses the first
58    three a lot, and compare.c uses the fourth.  The cleanup continues!  */
59
60 union block *record_start;      /* start of record of archive */
61 union block *record_end;        /* last+1 block of archive record */
62 union block *current_block;     /* current block of archive */
63 enum access_mode access_mode;   /* how do we handle the archive */
64 static struct stat archive_stat; /* stat block for archive file */
65
66 static off_t record_start_block; /* block ordinal at record_start */
67
68 /* Where we write list messages (not errors, not interactions) to.  Stdout
69    unless we're writing a pipe, in which case stderr.  */
70 FILE *stdlis;
71
72 static void backspace_output PARAMS ((void));
73 static int new_volume PARAMS ((enum access_mode));
74 static void archive_write_error PARAMS ((ssize_t)) __attribute__ ((noreturn));
75 static void archive_read_error PARAMS ((void));
76
77 #if !MSDOS
78 /* Obnoxious test to see if dimwit is trying to dump the archive.  */
79 dev_t ar_dev;
80 ino_t ar_ino;
81 #endif
82
83 /* PID of child program, if compress_option or remote archive access.  */
84 static pid_t child_pid;
85
86 /* Error recovery stuff  */
87 static int read_error_count;
88
89 /* Have we hit EOF yet?  */
90 static int hit_eof;
91
92 /* Checkpointing counter */
93 static int checkpoint;
94
95 /* We're reading, but we just read the last block and its time to update.  */
96 /* As least EXTERN like this one as possible.  FIXME!  */
97 extern int time_to_start_writing;
98
99 int file_to_switch_to = -1;     /* if remote update, close archive, and use
100                                    this descriptor to write to */
101
102 static int volno = 1;           /* which volume of a multi-volume tape we're
103                                    on */
104 static int global_volno = 1;    /* volume number to print in external
105                                    messages */
106
107 /* The pointer save_name, which is set in function dump_file() of module
108    create.c, points to the original long filename instead of the new,
109    shorter mangled name that is set in start_header() of module create.c.
110    The pointer save_name is only used in multi-volume mode when the file
111    being processed is non-sparse; if a file is split between volumes, the
112    save_name is used in generating the LF_MULTIVOL record on the second
113    volume.  (From Pierce Cantrell, 1991-08-13.)  */
114
115 char *save_name;                /* name of the file we are currently writing */
116 off_t save_totsize;             /* total size of file we are writing, only
117                                    valid if save_name is nonzero */
118 off_t save_sizeleft;            /* where we are in the file we are writing,
119                                    only valid if save_name is nonzero */
120
121 int write_archive_to_stdout;
122
123 /* Used by flush_read and flush_write to store the real info about saved
124    names.  */
125 static char *real_s_name;
126 static off_t real_s_totsize;
127 static off_t real_s_sizeleft;
128 \f
129 /* Functions.  */
130
131 void
132 print_total_written (void)
133 {
134   tarlong written = prev_written + bytes_written;
135   char bytes[sizeof (tarlong) * CHAR_BIT];
136   char abbr[LONGEST_HUMAN_READABLE + 1];
137   char rate[LONGEST_HUMAN_READABLE + 1];
138   double seconds;
139
140 #if HAVE_CLOCK_GETTIME
141   struct timespec now;
142   if (clock_gettime (CLOCK_REALTIME, &now) == 0)
143     seconds = ((now.tv_sec - start_timespec.tv_sec)
144                + (now.tv_nsec - start_timespec.tv_nsec) / 1e9);
145   else
146 #endif
147     seconds = time (0) - start_time;
148
149   sprintf (bytes, TARLONG_FORMAT, written);
150
151   /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*".  */
152   fprintf (stderr, _("Total bytes written: %s (%sB, %sB/s)\n"), bytes,
153            human_readable ((uintmax_t) written, abbr, 1, -1024),
154            (0 < seconds && written / seconds < (uintmax_t) -1
155             ? human_readable ((uintmax_t) (written / seconds), rate, 1, -1024)
156             : "?"));
157 }
158
159 /* Compute and return the block ordinal at current_block.  */
160 off_t
161 current_block_ordinal (void)
162 {
163   return record_start_block + (current_block - record_start);
164 }
165
166 /* If the EOF flag is set, reset it, as well as current_block, etc.  */
167 void
168 reset_eof (void)
169 {
170   if (hit_eof)
171     {
172       hit_eof = 0;
173       current_block = record_start;
174       record_end = record_start + blocking_factor;
175       access_mode = ACCESS_WRITE;
176     }
177 }
178
179 /* Return the location of the next available input or output block.
180    Return zero for EOF.  Once we have returned zero, we just keep returning
181    it, to avoid accidentally going on to the next file on the tape.  */
182 union block *
183 find_next_block (void)
184 {
185   if (current_block == record_end)
186     {
187       if (hit_eof)
188         return 0;
189       flush_archive ();
190       if (current_block == record_end)
191         {
192           hit_eof = 1;
193           return 0;
194         }
195     }
196   return current_block;
197 }
198
199 /* Indicate that we have used all blocks up thru BLOCK.
200    FIXME: should the arg have an off-by-1?  */
201 void
202 set_next_block_after (union block *block)
203 {
204   while (block >= current_block)
205     current_block++;
206
207   /* Do *not* flush the archive here.  If we do, the same argument to
208      set_next_block_after could mean the next block (if the input record
209      is exactly one block long), which is not what is intended.  */
210
211   if (current_block > record_end)
212     abort ();
213 }
214
215 /* Return the number of bytes comprising the space between POINTER
216    through the end of the current buffer of blocks.  This space is
217    available for filling with data, or taking data from.  POINTER is
218    usually (but not always) the result previous find_next_block call.  */
219 size_t
220 available_space_after (union block *pointer)
221 {
222   return record_end->buffer - pointer->buffer;
223 }
224
225 /* Close file having descriptor FD, and abort if close unsuccessful.  */
226 static void
227 xclose (int fd)
228 {
229   if (close (fd) != 0)
230     close_error (_("(pipe)"));
231 }
232
233 /* Duplicate file descriptor FROM into becoming INTO.
234    INTO is closed first and has to be the next available slot.  */
235 static void
236 xdup2 (int from, int into)
237 {
238   if (from != into)
239     {
240       int status = close (into);
241
242       if (status != 0 && errno != EBADF)
243         {
244           int e = errno;
245           FATAL_ERROR ((0, e, _("Cannot close")));
246         }
247       status = dup (from);
248       if (status != into)
249         {
250           if (status < 0)
251             {
252               int e = errno;
253               FATAL_ERROR ((0, e, _("Cannot dup")));
254             }
255           abort ();
256         }
257       xclose (from);
258     }
259 }
260
261 #if MSDOS
262
263 /* Set ARCHIVE for writing, then compressing an archive.  */
264 static void
265 child_open_for_compress (void)
266 {
267   FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
268 }
269
270 /* Set ARCHIVE for uncompressing, then reading an archive.  */
271 static void
272 child_open_for_uncompress (void)
273 {
274   FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
275 }
276
277 #else /* not MSDOS */
278
279 /* Return nonzero if NAME is the name of a regular file, or if the file
280    does not exist (so it would be created as a regular file).  */
281 static int
282 is_regular_file (const char *name)
283 {
284   struct stat stbuf;
285
286   if (stat (name, &stbuf) == 0)
287     return S_ISREG (stbuf.st_mode);
288   else
289     return errno == ENOENT;
290 }
291
292 static ssize_t
293 write_archive_buffer (void)
294 {
295   ssize_t status;
296   ssize_t written = 0;
297
298   while (0 <= (status = rmtwrite (archive, record_start->buffer + written,
299                                   record_size - written)))
300     {
301       written += status;
302       if (written == record_size
303           || _isrmt (archive) || ! S_ISFIFO (archive_stat.st_mode))
304         break;
305     }
306
307   return written ? written : status;
308 }
309
310 /* Set ARCHIVE for writing, then compressing an archive.  */
311 static void
312 child_open_for_compress (void)
313 {
314   int parent_pipe[2];
315   int child_pipe[2];
316   pid_t grandchild_pid;
317   int wait_status;
318
319   xpipe (parent_pipe);
320   child_pid = xfork ();
321
322   if (child_pid > 0)
323     {
324       /* The parent tar is still here!  Just clean up.  */
325
326       archive = parent_pipe[PWRITE];
327       xclose (parent_pipe[PREAD]);
328       return;
329     }
330
331   /* The new born child tar is here!  */
332
333   program_name = _("tar (child)");
334
335   xdup2 (parent_pipe[PREAD], STDIN_FILENO);
336   xclose (parent_pipe[PWRITE]);
337
338   /* Check if we need a grandchild tar.  This happens only if either:
339      a) we are writing stdout: to force reblocking;
340      b) the file is to be accessed by rmt: compressor doesn't know how;
341      c) the file is not a plain file.  */
342
343   if (strcmp (archive_name_array[0], "-") != 0
344       && !_remdev (archive_name_array[0])
345       && is_regular_file (archive_name_array[0]))
346     {
347       if (backup_option)
348         maybe_backup_file (archive_name_array[0], 1);
349
350       /* We don't need a grandchild tar.  Open the archive and launch the
351          compressor.  */
352
353       archive = creat (archive_name_array[0], MODE_RW);
354       if (archive < 0)
355         {
356           int saved_errno = errno;
357
358           if (backup_option)
359             undo_last_backup ();
360           errno = saved_errno;
361           open_fatal (archive_name_array[0]);
362         }
363       xdup2 (archive, STDOUT_FILENO);
364       execlp (use_compress_program_option, use_compress_program_option,
365               (char *) 0);
366       exec_fatal (use_compress_program_option);
367     }
368
369   /* We do need a grandchild tar.  */
370
371   xpipe (child_pipe);
372   grandchild_pid = xfork ();
373
374   if (grandchild_pid == 0)
375     {
376       /* The newborn grandchild tar is here!  Launch the compressor.  */
377
378       program_name = _("tar (grandchild)");
379
380       xdup2 (child_pipe[PWRITE], STDOUT_FILENO);
381       xclose (child_pipe[PREAD]);
382       execlp (use_compress_program_option, use_compress_program_option,
383               (char *) 0);
384       exec_fatal (use_compress_program_option);
385     }
386
387   /* The child tar is still here!  */
388
389   /* Prepare for reblocking the data from the compressor into the archive.  */
390
391   xdup2 (child_pipe[PREAD], STDIN_FILENO);
392   xclose (child_pipe[PWRITE]);
393
394   if (strcmp (archive_name_array[0], "-") == 0)
395     archive = STDOUT_FILENO;
396   else
397     {
398       archive = rmtcreat (archive_name_array[0], MODE_RW, rsh_command_option);
399       if (archive < 0)
400         open_fatal (archive_name_array[0]);
401     }
402
403   /* Let's read out of the stdin pipe and write an archive.  */
404
405   while (1)
406     {
407       ssize_t status = 0;
408       char *cursor;
409       size_t length;
410
411       /* Assemble a record.  */
412
413       for (length = 0, cursor = record_start->buffer;
414            length < record_size;
415            length += status, cursor += status)
416         {
417           size_t size = record_size - length;
418
419           if (size < BLOCKSIZE)
420             size = BLOCKSIZE;
421           status = safe_read (STDIN_FILENO, cursor, size);
422           if (status <= 0)
423             break;
424         }
425
426       if (status < 0)
427         read_fatal (use_compress_program_option);
428
429       /* Copy the record.  */
430
431       if (status == 0)
432         {
433           /* We hit the end of the file.  Write last record at
434              full length, as the only role of the grandchild is
435              doing proper reblocking.  */
436
437           if (length > 0)
438             {
439               memset (record_start->buffer + length, 0, record_size - length);
440               status = write_archive_buffer ();
441               if (status != record_size)
442                 archive_write_error (status);
443             }
444
445           /* There is nothing else to read, break out.  */
446           break;
447         }
448
449       status = write_archive_buffer ();
450       if (status != record_size)
451         archive_write_error (status);
452     }
453
454 #if 0
455   close_archive ();
456 #endif
457
458   /* Propagate any failure of the grandchild back to the parent.  */
459
460   while (waitpid (grandchild_pid, &wait_status, 0) == -1)
461     if (errno != EINTR)
462       {
463         waitpid_error (use_compress_program_option);
464         break;
465       }
466
467   if (WIFSIGNALED (wait_status))
468     {
469       kill (child_pid, WTERMSIG (wait_status));
470       exit_status = TAREXIT_FAILURE;
471     }
472   else if (WEXITSTATUS (wait_status) != 0)
473     exit_status = WEXITSTATUS (wait_status);
474
475   exit (exit_status);
476 }
477
478 /* Set ARCHIVE for uncompressing, then reading an archive.  */
479 static void
480 child_open_for_uncompress (void)
481 {
482   int parent_pipe[2];
483   int child_pipe[2];
484   pid_t grandchild_pid;
485   int wait_status;
486
487   xpipe (parent_pipe);
488   child_pid = xfork ();
489
490   if (child_pid > 0)
491     {
492       /* The parent tar is still here!  Just clean up.  */
493
494       read_full_records_option = 1;
495       archive = parent_pipe[PREAD];
496       xclose (parent_pipe[PWRITE]);
497       return;
498     }
499
500   /* The newborn child tar is here!  */
501
502   program_name = _("tar (child)");
503
504   xdup2 (parent_pipe[PWRITE], STDOUT_FILENO);
505   xclose (parent_pipe[PREAD]);
506
507   /* Check if we need a grandchild tar.  This happens only if either:
508      a) we're reading stdin: to force unblocking;
509      b) the file is to be accessed by rmt: compressor doesn't know how;
510      c) the file is not a plain file.  */
511
512   if (strcmp (archive_name_array[0], "-") != 0
513       && !_remdev (archive_name_array[0])
514       && is_regular_file (archive_name_array[0]))
515     {
516       /* We don't need a grandchild tar.  Open the archive and lauch the
517          uncompressor.  */
518
519       archive = open (archive_name_array[0], O_RDONLY | O_BINARY, MODE_RW);
520       if (archive < 0)
521         open_fatal (archive_name_array[0]);
522       xdup2 (archive, STDIN_FILENO);
523       execlp (use_compress_program_option, use_compress_program_option,
524               "-d", (char *) 0);
525       exec_fatal (use_compress_program_option);
526     }
527
528   /* We do need a grandchild tar.  */
529
530   xpipe (child_pipe);
531   grandchild_pid = xfork ();
532
533   if (grandchild_pid == 0)
534     {
535       /* The newborn grandchild tar is here!  Launch the uncompressor.  */
536
537       program_name = _("tar (grandchild)");
538
539       xdup2 (child_pipe[PREAD], STDIN_FILENO);
540       xclose (child_pipe[PWRITE]);
541       execlp (use_compress_program_option, use_compress_program_option,
542               "-d", (char *) 0);
543       exec_fatal (use_compress_program_option);
544     }
545
546   /* The child tar is still here!  */
547
548   /* Prepare for unblocking the data from the archive into the
549      uncompressor.  */
550
551   xdup2 (child_pipe[PWRITE], STDOUT_FILENO);
552   xclose (child_pipe[PREAD]);
553
554   if (strcmp (archive_name_array[0], "-") == 0)
555     archive = STDIN_FILENO;
556   else
557     archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
558                        MODE_RW, rsh_command_option);
559   if (archive < 0)
560     open_fatal (archive_name_array[0]);
561
562   /* Let's read the archive and pipe it into stdout.  */
563
564   while (1)
565     {
566       char *cursor;
567       size_t maximum;
568       size_t count;
569       ssize_t status;
570
571       read_error_count = 0;
572
573     error_loop:
574       status = rmtread (archive, record_start->buffer, record_size);
575       if (status < 0)
576         {
577           archive_read_error ();
578           goto error_loop;
579         }
580       if (status == 0)
581         break;
582       cursor = record_start->buffer;
583       maximum = status;
584       while (maximum)
585         {
586           count = maximum < BLOCKSIZE ? maximum : BLOCKSIZE;
587           status = full_write (STDOUT_FILENO, cursor, count);
588           if (status < 0)
589             write_error (use_compress_program_option);
590
591           if (status != count)
592             {
593               ERROR ((0, 0, _("Write to compression program short %lu bytes"),
594                       (unsigned long) (count - status)));
595               count = status;
596             }
597
598           cursor += count;
599           maximum -= count;
600         }
601     }
602
603   xclose (STDOUT_FILENO);
604 #if 0
605   close_archive ();
606 #endif
607
608   /* Propagate any failure of the grandchild back to the parent.  */
609
610   while (waitpid (grandchild_pid, &wait_status, 0) == -1)
611     if (errno != EINTR)
612       {
613         waitpid_error (use_compress_program_option);
614         break;
615       }
616
617   if (WIFSIGNALED (wait_status))
618     {
619       kill (child_pid, WTERMSIG (wait_status));
620       exit_status = TAREXIT_FAILURE;
621     }
622   else if (WEXITSTATUS (wait_status) != 0)
623     exit_status = WEXITSTATUS (wait_status);
624
625   exit (exit_status);
626 }
627
628 #endif /* not MSDOS */
629
630 /* Check the LABEL block against the volume label, seen as a globbing
631    pattern.  Return true if the pattern matches.  In case of failure,
632    retry matching a volume sequence number before giving up in
633    multi-volume mode.  */
634 static int
635 check_label_pattern (union block *label)
636 {
637   char *string;
638   int result;
639
640   if (! memchr (label->header.name, '\0', sizeof label->header.name))
641     return 0;
642
643   if (fnmatch (volume_label_option, label->header.name, 0) == 0)
644     return 1;
645
646   if (!multi_volume_option)
647     return 0;
648
649   string = xmalloc (strlen (volume_label_option)
650                     + sizeof VOLUME_LABEL_APPEND + 1);
651   strcpy (string, volume_label_option);
652   strcat (string, VOLUME_LABEL_APPEND);
653   result = fnmatch (string, label->header.name, 0) == 0;
654   free (string);
655   return result;
656 }
657
658 /* Open an archive file.  The argument specifies whether we are
659    reading or writing, or both.  */
660 void
661 open_archive (enum access_mode wanted_access)
662 {
663   int backed_up_flag = 0;
664
665   stdlis = to_stdout_option ? stderr : stdout;
666
667   if (record_size == 0)
668     FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
669
670   if (archive_names == 0)
671     FATAL_ERROR ((0, 0, _("No archive name given")));
672
673   current_file_name = 0;
674   current_link_name = 0;
675   save_name = 0;
676   real_s_name = 0;
677
678   if (multi_volume_option)
679     {
680       if (verify_option)
681         FATAL_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
682       record_start = valloc (record_size + (2 * BLOCKSIZE));
683       if (record_start)
684         record_start += 2;
685     }
686   else
687     record_start = valloc (record_size);
688   if (!record_start)
689     FATAL_ERROR ((0, 0, _("Cannot allocate memory for blocking factor %d"),
690                   blocking_factor));
691
692   current_block = record_start;
693   record_end = record_start + blocking_factor;
694   /* When updating the archive, we start with reading.  */
695   access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
696
697   if (use_compress_program_option)
698     {
699       if (multi_volume_option)
700         FATAL_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
701       if (verify_option)
702         FATAL_ERROR ((0, 0, _("Cannot verify compressed archives")));
703
704       switch (wanted_access)
705         {
706         case ACCESS_READ:
707           child_open_for_uncompress ();
708           break;
709
710         case ACCESS_WRITE:
711           child_open_for_compress ();
712           break;
713
714         case ACCESS_UPDATE:
715           FATAL_ERROR ((0, 0, _("Cannot update compressed archives")));
716           break;
717         }
718
719       if (wanted_access == ACCESS_WRITE
720           && strcmp (archive_name_array[0], "-") == 0)
721         stdlis = stderr;
722     }
723   else if (strcmp (archive_name_array[0], "-") == 0)
724     {
725       read_full_records_option = 1; /* could be a pipe, be safe */
726       if (verify_option)
727         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
728
729       switch (wanted_access)
730         {
731         case ACCESS_READ:
732           archive = STDIN_FILENO;
733           break;
734
735         case ACCESS_WRITE:
736           archive = STDOUT_FILENO;
737           stdlis = stderr;
738           break;
739
740         case ACCESS_UPDATE:
741           archive = STDIN_FILENO;
742           stdlis = stderr;
743           write_archive_to_stdout = 1;
744           break;
745         }
746     }
747   else if (verify_option)
748     archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
749                        MODE_RW, rsh_command_option);
750   else
751     switch (wanted_access)
752       {
753       case ACCESS_READ:
754         archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
755                            MODE_RW, rsh_command_option);
756         break;
757
758       case ACCESS_WRITE:
759         if (backup_option)
760           {
761             maybe_backup_file (archive_name_array[0], 1);
762             backed_up_flag = 1;
763           }
764         archive = rmtcreat (archive_name_array[0], MODE_RW,
765                             rsh_command_option);
766         break;
767
768       case ACCESS_UPDATE:
769         archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
770                            MODE_RW, rsh_command_option);
771         break;
772       }
773
774   if (archive < 0
775       || (! _isrmt (archive) && fstat (archive, &archive_stat) < 0))
776     {
777       int saved_errno = errno;
778
779       if (backed_up_flag)
780         undo_last_backup ();
781       errno = saved_errno;
782       open_fatal (archive_name_array[0]);
783     }
784
785 #if !MSDOS
786
787   /* Detect if outputting to "/dev/null".  */
788   {
789     static char const dev_null[] = "/dev/null";
790     struct stat dev_null_stat;
791
792     dev_null_output =
793       (strcmp (archive_name_array[0], dev_null) == 0
794        || (! _isrmt (archive)
795            && S_ISCHR (archive_stat.st_mode)
796            && stat (dev_null, &dev_null_stat) == 0
797            && archive_stat.st_dev == dev_null_stat.st_dev
798            && archive_stat.st_ino == dev_null_stat.st_ino));
799   }
800
801   if (!_isrmt (archive) && S_ISREG (archive_stat.st_mode))
802     {
803       ar_dev = archive_stat.st_dev;
804       ar_ino = archive_stat.st_ino;
805     }
806   else
807     ar_dev = 0;
808
809 #endif /* not MSDOS */
810
811 #if MSDOS
812   setmode (archive, O_BINARY);
813 #endif
814
815   switch (wanted_access)
816     {
817     case ACCESS_READ:
818     case ACCESS_UPDATE:
819       record_end = record_start; /* set up for 1st record = # 0 */
820       find_next_block ();       /* read it in, check for EOF */
821
822       if (volume_label_option)
823         {
824           union block *label = find_next_block ();
825
826           if (!label)
827             FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
828                           quote (volume_label_option)));
829           if (!check_label_pattern (label))
830             FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
831                           quote_n (0, label->header.name),
832                           quote_n (1, volume_label_option)));
833         }
834       break;
835
836     case ACCESS_WRITE:
837       if (volume_label_option)
838         {
839           memset (record_start, 0, BLOCKSIZE);
840           if (multi_volume_option)
841             sprintf (record_start->header.name, "%s Volume 1",
842                      volume_label_option);
843           else
844             strcpy (record_start->header.name, volume_label_option);
845
846           assign_string (&current_file_name, record_start->header.name);
847
848           record_start->header.typeflag = GNUTYPE_VOLHDR;
849           TIME_TO_CHARS (start_time, record_start->header.mtime);
850           finish_header (record_start);
851 #if 0
852           current_block++;
853 #endif
854         }
855       break;
856     }
857 }
858
859 /* Perform a write to flush the buffer.  */
860 void
861 flush_write (void)
862 {
863   int copy_back;
864   ssize_t status;
865
866   if (checkpoint_option && !(++checkpoint % 10))
867     WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
868
869   if (tape_length_option && tape_length_option <= bytes_written)
870     {
871       errno = ENOSPC;
872       status = 0;
873     }
874   else if (dev_null_output)
875     status = record_size;
876   else
877     status = write_archive_buffer ();
878   if (status != record_size && !multi_volume_option)
879     archive_write_error (status);
880
881   if (status > 0)
882     bytes_written += status;
883
884   if (status == record_size)
885     {
886       if (multi_volume_option)
887         {
888           char *cursor;
889
890           if (!save_name)
891             {
892               assign_string (&real_s_name, 0);
893               real_s_totsize = 0;
894               real_s_sizeleft = 0;
895               return;
896             }
897
898           cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
899           while (*cursor == '/')
900             cursor++;
901
902           assign_string (&real_s_name, cursor);
903           real_s_totsize = save_totsize;
904           real_s_sizeleft = save_sizeleft;
905         }
906       return;
907     }
908
909   /* We're multivol.  Panic if we didn't get the right kind of response.  */
910
911   /* ENXIO is for the UNIX PC.  */
912   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
913     archive_write_error (status);
914
915   /* If error indicates a short write, we just move to the next tape.  */
916
917   if (!new_volume (ACCESS_WRITE))
918     return;
919
920   if (totals_option)
921     prev_written += bytes_written;
922   bytes_written = 0;
923
924   if (volume_label_option && real_s_name)
925     {
926       copy_back = 2;
927       record_start -= 2;
928     }
929   else if (volume_label_option || real_s_name)
930     {
931       copy_back = 1;
932       record_start--;
933     }
934   else
935     copy_back = 0;
936
937   if (volume_label_option)
938     {
939       memset (record_start, 0, BLOCKSIZE);
940       sprintf (record_start->header.name, "%s Volume %d",
941                volume_label_option, volno);
942       TIME_TO_CHARS (start_time, record_start->header.mtime);
943       record_start->header.typeflag = GNUTYPE_VOLHDR;
944       finish_header (record_start);
945     }
946
947   if (real_s_name)
948     {
949       int tmp;
950
951       if (volume_label_option)
952         record_start++;
953
954       memset (record_start, 0, BLOCKSIZE);
955
956       /* FIXME: Michael P Urban writes: [a long name file] is being written
957          when a new volume rolls around [...]  Looks like the wrong value is
958          being preserved in real_s_name, though.  */
959
960       strcpy (record_start->header.name, real_s_name);
961       record_start->header.typeflag = GNUTYPE_MULTIVOL;
962       OFF_TO_CHARS (real_s_sizeleft, record_start->header.size);
963       OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
964                     record_start->oldgnu_header.offset);
965       tmp = verbose_option;
966       verbose_option = 0;
967       finish_header (record_start);
968       verbose_option = tmp;
969
970       if (volume_label_option)
971         record_start--;
972     }
973
974   status = write_archive_buffer ();
975   if (status != record_size)
976     archive_write_error (status);
977
978   bytes_written += status;
979
980   if (copy_back)
981     {
982       record_start += copy_back;
983       memcpy (current_block,
984               record_start + blocking_factor - copy_back,
985               copy_back * BLOCKSIZE);
986       current_block += copy_back;
987
988       if (real_s_sizeleft >= copy_back * BLOCKSIZE)
989         real_s_sizeleft -= copy_back * BLOCKSIZE;
990       else if ((real_s_sizeleft + BLOCKSIZE - 1) / BLOCKSIZE <= copy_back)
991         assign_string (&real_s_name, 0);
992       else
993         {
994           char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
995
996           while (*cursor == '/')
997             cursor++;
998
999           assign_string (&real_s_name, cursor);
1000           real_s_sizeleft = save_sizeleft;
1001           real_s_totsize = save_totsize;
1002         }
1003       copy_back = 0;
1004     }
1005 }
1006
1007 /* Handle write errors on the archive.  Write errors are always fatal.
1008    Hitting the end of a volume does not cause a write error unless the
1009    write was the first record of the volume.  */
1010 static void
1011 archive_write_error (ssize_t status)
1012 {
1013   /* It might be useful to know how much was written before the error
1014      occurred.  */
1015   if (totals_option)
1016     {
1017       int e = errno;
1018       print_total_written ();
1019       errno = e;
1020     }
1021
1022   write_fatal_details (*archive_name_cursor, status, record_size);
1023 }
1024
1025 /* Handle read errors on the archive.  If the read should be retried,
1026    return to the caller.  */
1027 static void
1028 archive_read_error (void)
1029 {
1030   read_error (*archive_name_cursor);
1031
1032   if (record_start_block == 0)
1033     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
1034
1035   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
1036      then give up on reading the archive.  */
1037
1038   if (read_error_count++ > READ_ERROR_MAX)
1039     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
1040   return;
1041 }
1042
1043 /* Perform a read to flush the buffer.  */
1044 void
1045 flush_read (void)
1046 {
1047   ssize_t status;               /* result from system call */
1048   size_t left;                  /* bytes left */
1049   char *more;                   /* pointer to next byte to read */
1050
1051   if (checkpoint_option && !(++checkpoint % 10))
1052     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
1053
1054   /* Clear the count of errors.  This only applies to a single call to
1055      flush_read.  */
1056
1057   read_error_count = 0;         /* clear error count */
1058
1059   if (write_archive_to_stdout && record_start_block != 0)
1060     {
1061       archive = STDOUT_FILENO;
1062       status = write_archive_buffer ();
1063       archive = STDIN_FILENO;
1064       if (status != record_size)
1065         archive_write_error (status);
1066     }
1067   if (multi_volume_option)
1068     {
1069       if (save_name)
1070         {
1071           char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
1072
1073           while (*cursor == '/')
1074             cursor++;
1075
1076           assign_string (&real_s_name, cursor);
1077           real_s_sizeleft = save_sizeleft;
1078           real_s_totsize = save_totsize;
1079         }
1080       else
1081         {
1082           assign_string (&real_s_name, 0);
1083           real_s_totsize = 0;
1084           real_s_sizeleft = 0;
1085         }
1086     }
1087
1088  error_loop:
1089   status = rmtread (archive, record_start->buffer, record_size);
1090   if (status == record_size)
1091     return;
1092
1093   if ((status == 0
1094        || (status < 0 && errno == ENOSPC)
1095        || (status > 0 && !read_full_records_option))
1096       && multi_volume_option)
1097     {
1098       union block *cursor;
1099
1100     try_volume:
1101       switch (subcommand_option)
1102         {
1103         case APPEND_SUBCOMMAND:
1104         case CAT_SUBCOMMAND:
1105         case UPDATE_SUBCOMMAND:
1106           if (!new_volume (ACCESS_UPDATE))
1107             return;
1108           break;
1109
1110         default:
1111           if (!new_volume (ACCESS_READ))
1112             return;
1113           break;
1114         }
1115
1116     vol_error:
1117       status = rmtread (archive, record_start->buffer, record_size);
1118       if (status < 0)
1119         {
1120           archive_read_error ();
1121           goto vol_error;
1122         }
1123       if (status != record_size)
1124         goto short_read;
1125
1126       cursor = record_start;
1127
1128       if (cursor->header.typeflag == GNUTYPE_VOLHDR)
1129         {
1130           if (volume_label_option)
1131             {
1132               if (!check_label_pattern (cursor))
1133                 {
1134                   WARN ((0, 0, _("Volume %s does not match %s"),
1135                          quote_n (0, cursor->header.name),
1136                          quote_n (1, volume_label_option)));
1137                   volno--;
1138                   global_volno--;
1139                   goto try_volume;
1140                 }
1141             }
1142           if (verbose_option)
1143             fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
1144           cursor++;
1145         }
1146       else if (volume_label_option)
1147         WARN ((0, 0, _("WARNING: No volume header")));
1148
1149       if (real_s_name)
1150         {
1151           uintmax_t s1, s2;
1152           if (cursor->header.typeflag != GNUTYPE_MULTIVOL
1153               || strcmp (cursor->header.name, real_s_name))
1154             {
1155               WARN ((0, 0, _("%s is not continued on this volume"),
1156                      quote (real_s_name)));
1157               volno--;
1158               global_volno--;
1159               goto try_volume;
1160             }
1161           s1 = UINTMAX_FROM_HEADER (cursor->header.size);
1162           s2 = UINTMAX_FROM_HEADER (cursor->oldgnu_header.offset);
1163           if (real_s_totsize != s1 + s2 || s1 + s2 < s2)
1164             {
1165               char totsizebuf[UINTMAX_STRSIZE_BOUND];
1166               char s1buf[UINTMAX_STRSIZE_BOUND];
1167               char s2buf[UINTMAX_STRSIZE_BOUND];
1168
1169               WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1170                      quote (cursor->header.name),
1171                      STRINGIFY_BIGINT (save_totsize, totsizebuf),
1172                      STRINGIFY_BIGINT (s1, s1buf),
1173                      STRINGIFY_BIGINT (s2, s2buf)));
1174               volno--;
1175               global_volno--;
1176               goto try_volume;
1177             }
1178           if (real_s_totsize - real_s_sizeleft
1179               != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
1180             {
1181               WARN ((0, 0, _("This volume is out of sequence")));
1182               volno--;
1183               global_volno--;
1184               goto try_volume;
1185             }
1186           cursor++;
1187         }
1188       current_block = cursor;
1189       return;
1190     }
1191   else if (status < 0)
1192     {
1193       archive_read_error ();
1194       goto error_loop;          /* try again */
1195     }
1196
1197  short_read:
1198   more = record_start->buffer + status;
1199   left = record_size - status;
1200
1201   while (left % BLOCKSIZE != 0)
1202     {
1203       if (status)
1204         while ((status = rmtread (archive, more, left)) < 0)
1205           archive_read_error ();
1206
1207       if (status == 0)
1208         {
1209           ERROR ((0, 0, _("%d garbage bytes ignored at end of archive"),
1210                   (int) ((record_size - left) % BLOCKSIZE)));
1211           break;
1212         }
1213
1214       if (! read_full_records_option)
1215         FATAL_ERROR ((0, 0, _("Unaligned block (%lu bytes) in archive"),
1216                       (unsigned long) (record_size - left)));
1217
1218       /* User warned us about this.  Fix up.  */
1219
1220       left -= status;
1221       more += status;
1222     }
1223
1224   /* FIXME: for size=0, multi-volume support.  On the first record, warn
1225      about the problem.  */
1226
1227   if (!read_full_records_option && verbose_option
1228       && record_start_block == 0 && status > 0)
1229     WARN ((0, 0, _("Record size = %lu blocks"),
1230            (unsigned long) ((record_size - left) / BLOCKSIZE)));
1231
1232   record_end = record_start + (record_size - left) / BLOCKSIZE;
1233 }
1234
1235 /*  Flush the current buffer to/from the archive.  */
1236 void
1237 flush_archive (void)
1238 {
1239   record_start_block += record_end - record_start;
1240   current_block = record_start;
1241   record_end = record_start + blocking_factor;
1242
1243   if (access_mode == ACCESS_READ && time_to_start_writing)
1244     {
1245       access_mode = ACCESS_WRITE;
1246       time_to_start_writing = 0;
1247
1248       if (file_to_switch_to >= 0)
1249         {
1250           if (rmtclose (archive) != 0)
1251             close_warn (*archive_name_cursor);
1252
1253           archive = file_to_switch_to;
1254         }
1255       else
1256         backspace_output ();
1257     }
1258
1259   switch (access_mode)
1260     {
1261     case ACCESS_READ:
1262       flush_read ();
1263       break;
1264
1265     case ACCESS_WRITE:
1266       flush_write ();
1267       break;
1268
1269     case ACCESS_UPDATE:
1270       abort ();
1271     }
1272 }
1273
1274 /* Backspace the archive descriptor by one record worth.  If it's a
1275    tape, MTIOCTOP will work.  If it's something else, try to seek on
1276    it.  If we can't seek, we lose!  */
1277 static void
1278 backspace_output (void)
1279 {
1280 #ifdef MTIOCTOP
1281   {
1282     struct mtop operation;
1283
1284     operation.mt_op = MTBSR;
1285     operation.mt_count = 1;
1286     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1287       return;
1288     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1289       return;
1290   }
1291 #endif
1292
1293   {
1294     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1295
1296     /* Seek back to the beginning of this record and start writing there.  */
1297
1298     position -= record_size;
1299     if (position < 0)
1300       position = 0;
1301     if (rmtlseek (archive, position, SEEK_SET) != position)
1302       {
1303         /* Lseek failed.  Try a different method.  */
1304
1305         WARN ((0, 0,
1306                _("Cannot backspace archive file; it may be unreadable without -i")));
1307
1308         /* Replace the first part of the record with NULs.  */
1309
1310         if (record_start->buffer != output_start)
1311           memset (record_start->buffer, 0,
1312                   output_start - record_start->buffer);
1313       }
1314   }
1315 }
1316
1317 /* Close the archive file.  */
1318 void
1319 close_archive (void)
1320 {
1321   if (time_to_start_writing || access_mode == ACCESS_WRITE)
1322     flush_archive ();
1323
1324 #if !MSDOS
1325
1326   /* Manage to fully drain a pipe we might be reading, so to not break it on
1327      the producer after the EOF block.  FIXME: one of these days, GNU tar
1328      might become clever enough to just stop working, once there is no more
1329      work to do, we might have to revise this area in such time.  */
1330
1331   if (access_mode == ACCESS_READ
1332       && ! _isrmt (archive)
1333       && S_ISFIFO (archive_stat.st_mode))
1334     while (rmtread (archive, record_start->buffer, record_size) > 0)
1335       continue;
1336 #endif
1337
1338   if (verify_option)
1339     verify_volume ();
1340
1341   if (rmtclose (archive) != 0)
1342     close_warn (*archive_name_cursor);
1343
1344 #if !MSDOS
1345
1346   if (child_pid)
1347     {
1348       int wait_status;
1349
1350       while (waitpid (child_pid, &wait_status, 0) == -1)
1351         if (errno != EINTR)
1352           {
1353             waitpid_error (use_compress_program_option);
1354             break;
1355           }
1356
1357       if (WIFSIGNALED (wait_status))
1358         ERROR ((0, 0, _("Child died with signal %d"),
1359                 WTERMSIG (wait_status)));
1360       else if (WEXITSTATUS (wait_status) != 0)
1361         ERROR ((0, 0, _("Child returned status %d"),
1362                 WEXITSTATUS (wait_status)));
1363     }
1364 #endif /* !MSDOS */
1365
1366   if (current_file_name)
1367     free (current_file_name);
1368   if (current_link_name)
1369     free (current_link_name);
1370   if (save_name)
1371     free (save_name);
1372   if (real_s_name)
1373     free (real_s_name);
1374   free (multi_volume_option ? record_start - 2 : record_start);
1375 }
1376
1377 /* Called to initialize the global volume number.  */
1378 void
1379 init_volume_number (void)
1380 {
1381   FILE *file = fopen (volno_file_option, "r");
1382
1383   if (file)
1384     {
1385       if (fscanf (file, "%d", &global_volno) != 1
1386           || global_volno < 0)
1387         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1388                       quotearg_colon (volno_file_option)));
1389       if (ferror (file))
1390         read_error (volno_file_option);
1391       if (fclose (file) != 0)
1392         close_error (volno_file_option);
1393     }
1394   else if (errno != ENOENT)
1395     open_error (volno_file_option);
1396 }
1397
1398 /* Called to write out the closing global volume number.  */
1399 void
1400 closeout_volume_number (void)
1401 {
1402   FILE *file = fopen (volno_file_option, "w");
1403
1404   if (file)
1405     {
1406       fprintf (file, "%d\n", global_volno);
1407       if (ferror (file))
1408         write_error (volno_file_option);
1409       if (fclose (file) != 0)
1410         close_error (volno_file_option);
1411     }
1412   else
1413     open_error (volno_file_option);
1414 }
1415
1416 /* We've hit the end of the old volume.  Close it and open the next one.
1417    Return nonzero on success.  */
1418 static int
1419 new_volume (enum access_mode access)
1420 {
1421   static FILE *read_file;
1422   static int looped;
1423
1424   if (!read_file && !info_script_option)
1425     /* FIXME: if fopen is used, it will never be closed.  */
1426     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1427
1428   if (now_verifying)
1429     return 0;
1430   if (verify_option)
1431     verify_volume ();
1432
1433   if (rmtclose (archive) != 0)
1434     close_warn (*archive_name_cursor);
1435
1436   global_volno++;
1437   if (global_volno < 0)
1438     FATAL_ERROR ((0, 0, _("Volume number overflow")));
1439   volno++;
1440   archive_name_cursor++;
1441   if (archive_name_cursor == archive_name_array + archive_names)
1442     {
1443       archive_name_cursor = archive_name_array;
1444       looped = 1;
1445     }
1446
1447  tryagain:
1448   if (looped)
1449     {
1450       /* We have to prompt from now on.  */
1451
1452       if (info_script_option)
1453         {
1454           if (volno_file_option)
1455             closeout_volume_number ();
1456           system (info_script_option);
1457         }
1458       else
1459         while (1)
1460           {
1461             char input_buffer[80];
1462
1463             fputc ('\007', stderr);
1464             fprintf (stderr,
1465                      _("Prepare volume #%d for %s and hit return: "),
1466                      global_volno, quote (*archive_name_cursor));
1467             fflush (stderr);
1468
1469             if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1470               {
1471                 WARN ((0, 0, _("EOF where user reply was expected")));
1472
1473                 if (subcommand_option != EXTRACT_SUBCOMMAND
1474                     && subcommand_option != LIST_SUBCOMMAND
1475                     && subcommand_option != DIFF_SUBCOMMAND)
1476                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1477
1478                 fatal_exit ();
1479               }
1480             if (input_buffer[0] == '\n'
1481                 || input_buffer[0] == 'y'
1482                 || input_buffer[0] == 'Y')
1483               break;
1484
1485             switch (input_buffer[0])
1486               {
1487               case '?':
1488                 {
1489                   fprintf (stderr, _("\
1490  n [name]   Give a new file name for the next (and subsequent) volume(s)\n\
1491  q          Abort tar\n\
1492  !          Spawn a subshell\n\
1493  ?          Print this list\n"));
1494                 }
1495                 break;
1496
1497               case 'q':
1498                 /* Quit.  */
1499
1500                 WARN ((0, 0, _("No new volume; exiting.\n")));
1501
1502                 if (subcommand_option != EXTRACT_SUBCOMMAND
1503                     && subcommand_option != LIST_SUBCOMMAND
1504                     && subcommand_option != DIFF_SUBCOMMAND)
1505                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1506
1507                 fatal_exit ();
1508
1509               case 'n':
1510                 /* Get new file name.  */
1511
1512                 {
1513                   char *name = &input_buffer[1];
1514                   char *cursor;
1515
1516                   while (*name == ' ' || *name == '\t')
1517                     name++;
1518                   cursor = name;
1519                   while (*cursor && *cursor != '\n')
1520                     cursor++;
1521                   *cursor = '\0';
1522
1523                   /* FIXME: the following allocation is never reclaimed.  */
1524                   *archive_name_cursor = xstrdup (name);
1525                 }
1526                 break;
1527
1528               case '!':
1529 #if MSDOS
1530                 spawnl (P_WAIT, getenv ("COMSPEC"), "-", 0);
1531 #else /* not MSDOS */
1532                 {
1533                   pid_t child;
1534                   const char *shell = getenv ("SHELL");
1535                   if (! shell)
1536                     shell = "/bin/sh";
1537                   child = xfork ();
1538                   if (child == 0)
1539                     {
1540                       execlp (shell, "-sh", "-i", 0);
1541                       exec_fatal (shell);
1542                     }
1543                   else
1544                     {
1545                       int wait_status;
1546                       while (waitpid (child, &wait_status, 0) == -1)
1547                         if (errno != EINTR)
1548                           {
1549                             waitpid_error (shell);
1550                             break;
1551                           }
1552                     }
1553                 }
1554 #endif /* not MSDOS */
1555                 break;
1556               }
1557           }
1558     }
1559
1560   if (verify_option)
1561     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1562                        rsh_command_option);
1563   else
1564     switch (access)
1565       {
1566       case ACCESS_READ:
1567         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1568                            rsh_command_option);
1569         break;
1570
1571       case ACCESS_WRITE:
1572         if (backup_option)
1573           maybe_backup_file (*archive_name_cursor, 1);
1574         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1575                             rsh_command_option);
1576         break;
1577
1578       case ACCESS_UPDATE:
1579         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1580                            rsh_command_option);
1581         break;
1582       }
1583
1584   if (archive < 0)
1585     {
1586       open_warn (*archive_name_cursor);
1587       if (!verify_option && access == ACCESS_WRITE && backup_option)
1588         undo_last_backup ();
1589       goto tryagain;
1590     }
1591
1592 #if MSDOS
1593   setmode (archive, O_BINARY);
1594 #endif
1595
1596   return 1;
1597 }