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