8dc6e88888dcb632c2b226b1737a5a8f77743a08
[debian/tar] / src / buffer.c
1 /* Buffer management for tar.
2
3    Copyright (C) 1988, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001,
4    2003, 2004 Free Software Foundation, Inc.
5
6    Written by John Gilmore, on 1985-08-25.
7
8    This program is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by the
10    Free Software Foundation; either version 2, or (at your option) any later
11    version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
16    Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation, Inc.,
20    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "system.h"
23
24 #include <signal.h>
25
26 #include <fnmatch.h>
27 #include <human.h>
28 #include <quotearg.h>
29
30 #include "common.h"
31 #include "rmt.h"
32
33 /* Number of retries before giving up on read.  */
34 #define READ_ERROR_MAX 10
35
36 /* Globbing pattern to append to volume label if initial match failed.  */
37 #define VOLUME_LABEL_APPEND " Volume [1-9]*"
38 \f
39 /* Variables.  */
40
41 static tarlong prev_written;    /* bytes written on previous volumes */
42 static tarlong bytes_written;   /* bytes written on this volume */
43
44 /* FIXME: The following variables should ideally be static to this
45    module.  However, this cannot be done yet.  The cleanup continues!  */
46
47 union block *record_start;      /* start of record of archive */
48 union block *record_end;        /* last+1 block of archive record */
49 union block *current_block;     /* current block of archive */
50 enum access_mode access_mode;   /* how do we handle the archive */
51 off_t records_read;             /* number of records read from this archive */
52 off_t records_written;          /* likewise, for records written */
53
54 static off_t record_start_block; /* block ordinal at record_start */
55
56 /* Where we write list messages (not errors, not interactions) to.  */
57 FILE *stdlis;
58
59 static void backspace_output (void);
60 static bool new_volume (enum access_mode);
61
62 /* PID of child program, if compress_option or remote archive access.  */
63 static pid_t child_pid;
64
65 /* Error recovery stuff  */
66 static int read_error_count;
67
68 /* Have we hit EOF yet?  */
69 static int hit_eof;
70
71 /* Checkpointing counter */
72 static int checkpoint;
73
74 /* We're reading, but we just read the last block and it's time to update.
75    Declared in update.c
76
77    As least EXTERN like this one as possible. (?? --gray)
78    FIXME: Either eliminate it or move it to common.h. 
79 */
80 extern bool time_to_start_writing;
81
82 static int volno = 1;           /* which volume of a multi-volume tape we're
83                                    on */
84 static int global_volno = 1;    /* volume number to print in external
85                                    messages */
86
87 /* The pointer save_name, which is set in function dump_file() of module
88    create.c, points to the original long filename instead of the new,
89    shorter mangled name that is set in start_header() of module create.c.
90    The pointer save_name is only used in multi-volume mode when the file
91    being processed is non-sparse; if a file is split between volumes, the
92    save_name is used in generating the LF_MULTIVOL record on the second
93    volume.  (From Pierce Cantrell, 1991-08-13.)  */
94
95 char *save_name;                /* name of the file we are currently writing */
96 off_t save_totsize;             /* total size of file we are writing, only
97                                    valid if save_name is nonzero */
98 off_t save_sizeleft;            /* where we are in the file we are writing,
99                                    only valid if save_name is nonzero */
100
101 bool write_archive_to_stdout;
102
103 /* Used by flush_read and flush_write to store the real info about saved
104    names.  */
105 static char *real_s_name;
106 static off_t real_s_totsize;
107 static off_t real_s_sizeleft;
108 \f
109 /* Functions.  */
110
111 void
112 clear_read_error_count ()
113 {
114   read_error_count = 0;
115 }
116
117 void
118 print_total_written (void)
119 {
120   tarlong written = prev_written + bytes_written;
121   char bytes[sizeof (tarlong) * CHAR_BIT];
122   char abbr[LONGEST_HUMAN_READABLE + 1];
123   char rate[LONGEST_HUMAN_READABLE + 1];
124   double seconds;
125   int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
126
127 #if HAVE_CLOCK_GETTIME
128   struct timespec now;
129   if (clock_gettime (CLOCK_REALTIME, &now) == 0)
130     seconds = ((now.tv_sec - start_timespec.tv_sec)
131                + (now.tv_nsec - start_timespec.tv_nsec) / 1e9);
132   else
133 #endif
134     seconds = time (0) - start_time;
135
136   sprintf (bytes, TARLONG_FORMAT, written);
137
138   /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*".  */
139   fprintf (stderr, _("Total bytes written: %s (%s, %s/s)\n"), bytes,
140            human_readable (written, abbr, human_opts, 1, 1),
141            (0 < seconds && written / seconds < (uintmax_t) -1
142             ? human_readable (written / seconds, rate, human_opts, 1, 1)
143             : "?"));
144 }
145
146 /* Compute and return the block ordinal at current_block.  */
147 off_t
148 current_block_ordinal (void)
149 {
150   return record_start_block + (current_block - record_start);
151 }
152
153 /* If the EOF flag is set, reset it, as well as current_block, etc.  */
154 void
155 reset_eof (void)
156 {
157   if (hit_eof)
158     {
159       hit_eof = 0;
160       current_block = record_start;
161       record_end = record_start + blocking_factor;
162       access_mode = ACCESS_WRITE;
163     }
164 }
165
166 /* Return the location of the next available input or output block.
167    Return zero for EOF.  Once we have returned zero, we just keep returning
168    it, to avoid accidentally going on to the next file on the tape.  */
169 union block *
170 find_next_block (void)
171 {
172   if (current_block == record_end)
173     {
174       if (hit_eof)
175         return 0;
176       flush_archive ();
177       if (current_block == record_end)
178         {
179           hit_eof = 1;
180           return 0;
181         }
182     }
183   return current_block;
184 }
185
186 /* Indicate that we have used all blocks up thru BLOCK. */
187 void
188 set_next_block_after (union block *block)
189 {
190   while (block >= current_block)
191     current_block++;
192
193   /* Do *not* flush the archive here.  If we do, the same argument to
194      set_next_block_after could mean the next block (if the input record
195      is exactly one block long), which is not what is intended.  */
196
197   if (current_block > record_end)
198     abort ();
199 }
200
201 /* Return the number of bytes comprising the space between POINTER
202    through the end of the current buffer of blocks.  This space is
203    available for filling with data, or taking data from.  POINTER is
204    usually (but not always) the result of previous find_next_block call.  */
205 size_t
206 available_space_after (union block *pointer)
207 {
208   return record_end->buffer - pointer->buffer;
209 }
210
211 /* Close file having descriptor FD, and abort if close unsuccessful.  */
212 void
213 xclose (int fd)
214 {
215   if (close (fd) != 0)
216     close_error (_("(pipe)"));
217 }
218
219 /* Check the LABEL block against the volume label, seen as a globbing
220    pattern.  Return true if the pattern matches.  In case of failure,
221    retry matching a volume sequence number before giving up in
222    multi-volume mode.  */
223 static bool
224 check_label_pattern (union block *label)
225 {
226   char *string;
227   bool result;
228
229   if (! memchr (label->header.name, '\0', sizeof label->header.name))
230     return false;
231
232   if (fnmatch (volume_label_option, label->header.name, 0) == 0)
233     return true;
234
235   if (!multi_volume_option)
236     return false;
237
238   string = xmalloc (strlen (volume_label_option)
239                     + sizeof VOLUME_LABEL_APPEND + 1);
240   strcpy (string, volume_label_option);
241   strcat (string, VOLUME_LABEL_APPEND);
242   result = fnmatch (string, label->header.name, 0) == 0;
243   free (string);
244   return result;
245 }
246
247 /* Open an archive file.  The argument specifies whether we are
248    reading or writing, or both.  */
249 void
250 open_archive (enum access_mode wanted_access)
251 {
252   int backed_up_flag = 0;
253
254   if (index_file_name)
255     {
256       stdlis = fopen (index_file_name, "w");
257       if (! stdlis)
258         open_error (index_file_name);
259     }
260   else
261     stdlis = to_stdout_option ? stderr : stdout;
262
263   if (record_size == 0)
264     FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
265
266   if (archive_names == 0)
267     FATAL_ERROR ((0, 0, _("No archive name given")));
268
269   tar_stat_destroy (&current_stat_info);
270   save_name = 0;
271   real_s_name = 0;
272
273   if (multi_volume_option)
274     {
275       record_start = valloc (record_size + (2 * BLOCKSIZE));
276       if (record_start)
277         record_start += 2;
278     }
279   else
280     record_start = valloc (record_size);
281   if (!record_start)
282     FATAL_ERROR ((0, 0, _("Cannot allocate memory for blocking factor %d"),
283                   blocking_factor));
284
285   current_block = record_start;
286   record_end = record_start + blocking_factor;
287   /* When updating the archive, we start with reading.  */
288   access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
289
290   if (use_compress_program_option)
291     {
292       switch (wanted_access)
293         {
294         case ACCESS_READ:
295           child_pid = sys_child_open_for_uncompress ();
296           read_full_records_option = false;
297           break;
298
299         case ACCESS_WRITE:
300           child_pid = sys_child_open_for_compress ();
301           break;
302
303         case ACCESS_UPDATE:
304           abort (); /* Should not happen */
305           break;
306         }
307
308       if (wanted_access == ACCESS_WRITE
309           && strcmp (archive_name_array[0], "-") == 0)
310         stdlis = stderr;
311     }
312   else if (strcmp (archive_name_array[0], "-") == 0)
313     {
314       read_full_records_option = true; /* could be a pipe, be safe */
315       if (verify_option)
316         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
317
318       switch (wanted_access)
319         {
320         case ACCESS_READ:
321           archive = STDIN_FILENO;
322           break;
323
324         case ACCESS_WRITE:
325           archive = STDOUT_FILENO;
326           stdlis = stderr;
327           break;
328
329         case ACCESS_UPDATE:
330           archive = STDIN_FILENO;
331           stdlis = stderr;
332           write_archive_to_stdout = true;
333           break;
334         }
335     }
336   else if (verify_option)
337     archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
338                        MODE_RW, rsh_command_option);
339   else
340     switch (wanted_access)
341       {
342       case ACCESS_READ:
343         archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
344                            MODE_RW, rsh_command_option);
345         break;
346
347       case ACCESS_WRITE:
348         if (backup_option)
349           {
350             maybe_backup_file (archive_name_array[0], 1);
351             backed_up_flag = 1;
352           }
353         archive = rmtcreat (archive_name_array[0], MODE_RW,
354                             rsh_command_option);
355         break;
356
357       case ACCESS_UPDATE:
358         archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
359                            MODE_RW, rsh_command_option);
360         break;
361       }
362
363   if (archive < 0
364       || (! _isrmt (archive) && !sys_get_archive_stat ()))
365     {
366       int saved_errno = errno;
367
368       if (backed_up_flag)
369         undo_last_backup ();
370       errno = saved_errno;
371       open_fatal (archive_name_array[0]);
372     }
373
374   sys_detect_dev_null_output ();
375   sys_save_archive_dev_ino ();
376   SET_BINARY_MODE (archive);
377
378   switch (wanted_access)
379     {
380     case ACCESS_UPDATE:
381       records_written = 0;
382     case ACCESS_READ:
383       records_read = 0;
384       record_end = record_start; /* set up for 1st record = # 0 */
385       find_next_block ();       /* read it in, check for EOF */
386
387       if (volume_label_option)
388         {
389           union block *label = find_next_block ();
390
391           if (!label)
392             FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
393                           quote (volume_label_option)));
394           if (!check_label_pattern (label))
395             FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
396                           quote_n (0, label->header.name),
397                           quote_n (1, volume_label_option)));
398         }
399       break;
400
401     case ACCESS_WRITE:
402       records_written = 0;
403       if (volume_label_option)
404         {
405           memset (record_start, 0, BLOCKSIZE);
406           if (multi_volume_option)
407             sprintf (record_start->header.name, "%s Volume 1",
408                      volume_label_option);
409           else
410             strcpy (record_start->header.name, volume_label_option);
411
412           assign_string (&current_stat_info.file_name,
413                          record_start->header.name);
414           current_stat_info.had_trailing_slash =
415             strip_trailing_slashes (current_stat_info.file_name);
416
417           record_start->header.typeflag = GNUTYPE_VOLHDR;
418           TIME_TO_CHARS (start_time, record_start->header.mtime);
419           finish_header (&current_stat_info, record_start, -1);
420         }
421       break;
422     }
423 }
424
425 /* Perform a write to flush the buffer.  */
426 void
427 flush_write (void)
428 {
429   int copy_back;
430   ssize_t status;
431
432   if (checkpoint_option && !(++checkpoint % 10))
433     WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
434
435   if (tape_length_option && tape_length_option <= bytes_written)
436     {
437       errno = ENOSPC;
438       status = 0;
439     }
440   else if (dev_null_output)
441     status = record_size;
442   else
443     status = sys_write_archive_buffer ();
444   if (status != record_size && !multi_volume_option)
445     archive_write_error (status);
446
447   if (status > 0)
448     {
449       records_written++;
450       bytes_written += status;
451     }
452
453   if (status == record_size)
454     {
455       if (multi_volume_option)
456         {
457           if (save_name)
458             {
459               assign_string (&real_s_name, safer_name_suffix (save_name, false));
460               real_s_totsize = save_totsize;
461               real_s_sizeleft = save_sizeleft;
462             }
463           else
464             {
465               assign_string (&real_s_name, 0);
466               real_s_totsize = 0;
467               real_s_sizeleft = 0;
468             }
469         }
470       return;
471     }
472
473   /* We're multivol.  Panic if we didn't get the right kind of response.  */
474
475   /* ENXIO is for the UNIX PC.  */
476   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
477     archive_write_error (status);
478
479   /* If error indicates a short write, we just move to the next tape.  */
480
481   if (!new_volume (ACCESS_WRITE))
482     return;
483
484   if (totals_option)
485     prev_written += bytes_written;
486   bytes_written = 0;
487
488   if (volume_label_option && real_s_name)
489     {
490       copy_back = 2;
491       record_start -= 2;
492     }
493   else if (volume_label_option || real_s_name)
494     {
495       copy_back = 1;
496       record_start--;
497     }
498   else
499     copy_back = 0;
500
501   if (volume_label_option)
502     {
503       memset (record_start, 0, BLOCKSIZE);
504       sprintf (record_start->header.name, "%s Volume %d",
505                volume_label_option, volno);
506       TIME_TO_CHARS (start_time, record_start->header.mtime);
507       record_start->header.typeflag = GNUTYPE_VOLHDR;
508       finish_header (&current_stat_info, record_start, -1);
509     }
510
511   if (real_s_name)
512     {
513       int tmp;
514
515       if (volume_label_option)
516         record_start++;
517
518       memset (record_start, 0, BLOCKSIZE);
519
520       /* FIXME: Michael P Urban writes: [a long name file] is being written
521          when a new volume rolls around [...]  Looks like the wrong value is
522          being preserved in real_s_name, though.  */
523
524       strcpy (record_start->header.name, real_s_name);
525       record_start->header.typeflag = GNUTYPE_MULTIVOL;
526       OFF_TO_CHARS (real_s_sizeleft, record_start->header.size);
527       OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
528                     record_start->oldgnu_header.offset);
529       tmp = verbose_option;
530       verbose_option = 0;
531       finish_header (&current_stat_info, record_start, -1);
532       verbose_option = tmp;
533
534       if (volume_label_option)
535         record_start--;
536     }
537
538   status = sys_write_archive_buffer ();
539   if (status != record_size)
540     archive_write_error (status);
541
542   bytes_written += status;
543
544   if (copy_back)
545     {
546       record_start += copy_back;
547       memcpy (current_block,
548               record_start + blocking_factor - copy_back,
549               copy_back * BLOCKSIZE);
550       current_block += copy_back;
551
552       if (real_s_sizeleft >= copy_back * BLOCKSIZE)
553         real_s_sizeleft -= copy_back * BLOCKSIZE;
554       else if ((real_s_sizeleft + BLOCKSIZE - 1) / BLOCKSIZE <= copy_back)
555         assign_string (&real_s_name, 0);
556       else
557         {
558           assign_string (&real_s_name, safer_name_suffix (save_name, false));
559           real_s_sizeleft = save_sizeleft;
560           real_s_totsize = save_totsize;
561         }
562       copy_back = 0;
563     }
564 }
565
566 /* Handle write errors on the archive.  Write errors are always fatal.
567    Hitting the end of a volume does not cause a write error unless the
568    write was the first record of the volume.  */
569 void
570 archive_write_error (ssize_t status)
571 {
572   /* It might be useful to know how much was written before the error
573      occurred.  */
574   if (totals_option)
575     {
576       int e = errno;
577       print_total_written ();
578       errno = e;
579     }
580
581   write_fatal_details (*archive_name_cursor, status, record_size);
582 }
583
584 /* Handle read errors on the archive.  If the read should be retried,
585    return to the caller.  */
586 void
587 archive_read_error (void)
588 {
589   read_error (*archive_name_cursor);
590
591   if (record_start_block == 0)
592     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
593
594   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
595      then give up on reading the archive.  */
596
597   if (read_error_count++ > READ_ERROR_MAX)
598     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
599   return;
600 }
601
602 static void
603 short_read (ssize_t status)
604 {
605   size_t left;                  /* bytes left */
606   char *more;                   /* pointer to next byte to read */
607
608   more = record_start->buffer + status;
609   left = record_size - status;
610
611   while (left % BLOCKSIZE != 0
612          || (left && status && read_full_records_option))
613     {
614       if (status)
615         while ((status = rmtread (archive, more, left)) < 0)
616           archive_read_error ();
617
618       if (status == 0)
619         {
620           char buf[UINTMAX_STRSIZE_BOUND];
621           
622           WARN((0, 0, _("Read %s bytes from %s"),
623                 STRINGIFY_BIGINT (record_size - left, buf),
624                 *archive_name_cursor));
625           break;
626         }
627   
628       if (! read_full_records_option)
629         {
630           unsigned long rest = record_size - left;
631           
632           FATAL_ERROR ((0, 0,
633                         ngettext ("Unaligned block (%lu byte) in archive",
634                                   "Unaligned block (%lu bytes) in archive",
635                                   rest),
636                         rest));
637         }
638
639       /* User warned us about this.  Fix up.  */
640
641       left -= status;
642       more += status;
643     }
644
645   /* FIXME: for size=0, multi-volume support.  On the first record, warn
646      about the problem.  */
647
648   if (!read_full_records_option && verbose_option > 1
649       && record_start_block == 0 && status > 0)
650     {
651       unsigned long rsize = (record_size - left) / BLOCKSIZE;
652       WARN ((0, 0,
653              ngettext ("Record size = %lu block",
654                        "Record size = %lu blocks",
655                        rsize),
656              rsize));
657     }
658
659   record_end = record_start + (record_size - left) / BLOCKSIZE;
660   records_read++;
661 }
662
663 /* Perform a read to flush the buffer.  */
664 void
665 flush_read (void)
666 {
667   ssize_t status;               /* result from system call */
668
669   if (checkpoint_option && !(++checkpoint % 10))
670     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
671
672   /* Clear the count of errors.  This only applies to a single call to
673      flush_read.  */
674
675   read_error_count = 0;         /* clear error count */
676
677   if (write_archive_to_stdout && record_start_block != 0)
678     {
679       archive = STDOUT_FILENO;
680       status = sys_write_archive_buffer ();
681       archive = STDIN_FILENO;
682       if (status != record_size)
683         archive_write_error (status);
684     }
685   if (multi_volume_option)
686     {
687       if (save_name)
688         {
689           assign_string (&real_s_name, safer_name_suffix (save_name, false));
690           real_s_sizeleft = save_sizeleft;
691           real_s_totsize = save_totsize;
692         }
693       else
694         {
695           assign_string (&real_s_name, 0);
696           real_s_totsize = 0;
697           real_s_sizeleft = 0;
698         }
699     }
700
701  error_loop:
702   status = rmtread (archive, record_start->buffer, record_size);
703   if (status == record_size)
704     {
705       records_read++;
706       return;
707     }
708
709   /* The condition below used to include
710               || (status > 0 && !read_full_records_option)
711      This is incorrect since even if new_volume() succeeds, the
712      subsequent call to rmtread will overwrite the chunk of data
713      already read in the buffer, so the processing will fail */
714         
715   if ((status == 0
716        || (status < 0 && errno == ENOSPC))
717       && multi_volume_option)
718     {
719       union block *cursor;
720
721     try_volume:
722       switch (subcommand_option)
723         {
724         case APPEND_SUBCOMMAND:
725         case CAT_SUBCOMMAND:
726         case UPDATE_SUBCOMMAND:
727           if (!new_volume (ACCESS_UPDATE))
728             return;
729           break;
730
731         default:
732           if (!new_volume (ACCESS_READ))
733             return;
734           break;
735         }
736
737       while ((status =
738               rmtread (archive, record_start->buffer, record_size)) < 0)
739         archive_read_error ();
740       
741       if (status != record_size)
742         short_read (status); 
743
744       cursor = record_start;
745
746       if (cursor->header.typeflag == GNUTYPE_VOLHDR)
747         {
748           if (volume_label_option)
749             {
750               if (!check_label_pattern (cursor))
751                 {
752                   WARN ((0, 0, _("Volume %s does not match %s"),
753                          quote_n (0, cursor->header.name),
754                          quote_n (1, volume_label_option)));
755                   volno--;
756                   global_volno--;
757                   goto try_volume;
758                 }
759             }
760           if (verbose_option)
761             fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
762           cursor++;
763         }
764       else if (volume_label_option)
765         WARN ((0, 0, _("WARNING: No volume header")));
766
767       if (real_s_name)
768         {
769           uintmax_t s1, s2;
770           if (cursor->header.typeflag != GNUTYPE_MULTIVOL
771               || strcmp (cursor->header.name, real_s_name))
772             {
773               WARN ((0, 0, _("%s is not continued on this volume"),
774                      quote (real_s_name)));
775               volno--;
776               global_volno--;
777               goto try_volume;
778             }
779           s1 = UINTMAX_FROM_HEADER (cursor->header.size);
780           s2 = UINTMAX_FROM_HEADER (cursor->oldgnu_header.offset);
781           if (real_s_totsize != s1 + s2 || s1 + s2 < s2)
782             {
783               char totsizebuf[UINTMAX_STRSIZE_BOUND];
784               char s1buf[UINTMAX_STRSIZE_BOUND];
785               char s2buf[UINTMAX_STRSIZE_BOUND];
786
787               WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
788                      quote (cursor->header.name),
789                      STRINGIFY_BIGINT (save_totsize, totsizebuf),
790                      STRINGIFY_BIGINT (s1, s1buf),
791                      STRINGIFY_BIGINT (s2, s2buf)));
792               volno--;
793               global_volno--;
794               goto try_volume;
795             }
796           if (real_s_totsize - real_s_sizeleft
797               != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
798             {
799               WARN ((0, 0, _("This volume is out of sequence")));
800               volno--;
801               global_volno--;
802               goto try_volume;
803             }
804           cursor++;
805         }
806       current_block = cursor;
807       records_read++;
808       return;
809     }
810   else if (status < 0)
811     {
812       archive_read_error ();
813       goto error_loop;          /* try again */
814     }
815
816   short_read (status);
817 }
818
819 /*  Flush the current buffer to/from the archive.  */
820 void
821 flush_archive (void)
822 {
823   record_start_block += record_end - record_start;
824   current_block = record_start;
825   record_end = record_start + blocking_factor;
826
827   if (access_mode == ACCESS_READ && time_to_start_writing)
828     {
829       access_mode = ACCESS_WRITE;
830       time_to_start_writing = false;
831       backspace_output ();
832     }
833
834   switch (access_mode)
835     {
836     case ACCESS_READ:
837       flush_read ();
838       break;
839
840     case ACCESS_WRITE:
841       flush_write ();
842       break;
843
844     case ACCESS_UPDATE:
845       abort ();
846     }
847 }
848
849 /* Backspace the archive descriptor by one record worth.  If it's a
850    tape, MTIOCTOP will work.  If it's something else, try to seek on
851    it.  If we can't seek, we lose!  */
852 static void
853 backspace_output (void)
854 {
855 #ifdef MTIOCTOP
856   {
857     struct mtop operation;
858
859     operation.mt_op = MTBSR;
860     operation.mt_count = 1;
861     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
862       return;
863     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
864       return;
865   }
866 #endif
867
868   {
869     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
870
871     /* Seek back to the beginning of this record and start writing there.  */
872
873     position -= record_size;
874     if (position < 0)
875       position = 0;
876     if (rmtlseek (archive, position, SEEK_SET) != position)
877       {
878         /* Lseek failed.  Try a different method.  */
879
880         WARN ((0, 0,
881                _("Cannot backspace archive file; it may be unreadable without -i")));
882
883         /* Replace the first part of the record with NULs.  */
884
885         if (record_start->buffer != output_start)
886           memset (record_start->buffer, 0,
887                   output_start - record_start->buffer);
888       }
889   }
890 }
891
892 /* Close the archive file.  */
893 void
894 close_archive (void)
895 {
896   if (time_to_start_writing || access_mode == ACCESS_WRITE)
897     flush_archive ();
898
899   sys_drain_input_pipe ();
900   
901   if (verify_option)
902     verify_volume ();
903
904   if (rmtclose (archive) != 0)
905     close_warn (*archive_name_cursor);
906
907   sys_wait_for_child (child_pid);
908   
909   tar_stat_destroy (&current_stat_info);
910   if (save_name)
911     free (save_name);
912   if (real_s_name)
913     free (real_s_name);
914   free (multi_volume_option ? record_start - 2 : record_start);
915 }
916
917 /* Called to initialize the global volume number.  */
918 void
919 init_volume_number (void)
920 {
921   FILE *file = fopen (volno_file_option, "r");
922
923   if (file)
924     {
925       if (fscanf (file, "%d", &global_volno) != 1
926           || global_volno < 0)
927         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
928                       quotearg_colon (volno_file_option)));
929       if (ferror (file))
930         read_error (volno_file_option);
931       if (fclose (file) != 0)
932         close_error (volno_file_option);
933     }
934   else if (errno != ENOENT)
935     open_error (volno_file_option);
936 }
937
938 /* Called to write out the closing global volume number.  */
939 void
940 closeout_volume_number (void)
941 {
942   FILE *file = fopen (volno_file_option, "w");
943
944   if (file)
945     {
946       fprintf (file, "%d\n", global_volno);
947       if (ferror (file))
948         write_error (volno_file_option);
949       if (fclose (file) != 0)
950         close_error (volno_file_option);
951     }
952   else
953     open_error (volno_file_option);
954 }
955
956 /* We've hit the end of the old volume.  Close it and open the next one.
957    Return nonzero on success.
958 */
959 static bool
960 new_volume (enum access_mode access)
961 {
962   static FILE *read_file;
963   static int looped;
964
965   if (!read_file && !info_script_option)
966     /* FIXME: if fopen is used, it will never be closed.  */
967     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
968
969   if (now_verifying)
970     return false;
971   if (verify_option)
972     verify_volume ();
973
974   if (rmtclose (archive) != 0)
975     close_warn (*archive_name_cursor);
976
977   global_volno++;
978   if (global_volno < 0)
979     FATAL_ERROR ((0, 0, _("Volume number overflow")));
980   volno++;
981   archive_name_cursor++;
982   if (archive_name_cursor == archive_name_array + archive_names)
983     {
984       archive_name_cursor = archive_name_array;
985       looped = 1;
986     }
987
988  tryagain:
989   if (looped)
990     {
991       /* We have to prompt from now on.  */
992
993       if (info_script_option)
994         {
995           if (volno_file_option)
996             closeout_volume_number ();
997           if (system (info_script_option) != 0)
998             FATAL_ERROR ((0, 0, _("`%s' command failed"), info_script_option));
999         }
1000       else
1001         while (1)
1002           {
1003             char input_buffer[80];
1004
1005             fputc ('\007', stderr);
1006             fprintf (stderr,
1007                      _("Prepare volume #%d for %s and hit return: "),
1008                      global_volno, quote (*archive_name_cursor));
1009             fflush (stderr);
1010
1011             if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1012               {
1013                 WARN ((0, 0, _("EOF where user reply was expected")));
1014
1015                 if (subcommand_option != EXTRACT_SUBCOMMAND
1016                     && subcommand_option != LIST_SUBCOMMAND
1017                     && subcommand_option != DIFF_SUBCOMMAND)
1018                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1019
1020                 fatal_exit ();
1021               }
1022             if (input_buffer[0] == '\n'
1023                 || input_buffer[0] == 'y'
1024                 || input_buffer[0] == 'Y')
1025               break;
1026
1027             switch (input_buffer[0])
1028               {
1029               case '?':
1030                 {
1031                   /* FIXME: Might it be useful to disable the '!' command? */
1032                   fprintf (stderr, _("\
1033  n [name]   Give a new file name for the next (and subsequent) volume(s)\n\
1034  q          Abort tar\n\
1035  !          Spawn a subshell\n\
1036  ?          Print this list\n"));
1037                 }
1038                 break;
1039
1040               case 'q':
1041                 /* Quit.  */
1042
1043                 WARN ((0, 0, _("No new volume; exiting.\n")));
1044
1045                 if (subcommand_option != EXTRACT_SUBCOMMAND
1046                     && subcommand_option != LIST_SUBCOMMAND
1047                     && subcommand_option != DIFF_SUBCOMMAND)
1048                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1049
1050                 fatal_exit ();
1051
1052               case 'n':
1053                 /* Get new file name.  */
1054
1055                 {
1056                   char *name = &input_buffer[1];
1057                   char *cursor;
1058
1059                   for (name = input_buffer + 1;
1060                        *name == ' ' || *name == '\t';
1061                        name++)
1062                     ;
1063
1064                   for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1065                     ;
1066                   *cursor = '\0';
1067
1068                   /* FIXME: the following allocation is never reclaimed.  */
1069                   *archive_name_cursor = xstrdup (name);
1070                 }
1071                 break;
1072
1073               case '!':
1074                 sys_spawn_shell ();
1075                 break;
1076               }
1077           }
1078     }
1079
1080   if (strcmp (archive_name_cursor[0], "-") == 0)
1081     {
1082       read_full_records_option = true;
1083       archive = STDIN_FILENO;
1084     }
1085   else if (verify_option)
1086     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1087                        rsh_command_option);
1088   else
1089     switch (access)
1090       {
1091       case ACCESS_READ:
1092         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1093                            rsh_command_option);
1094         break;
1095
1096       case ACCESS_WRITE:
1097         if (backup_option)
1098           maybe_backup_file (*archive_name_cursor, 1);
1099         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1100                             rsh_command_option);
1101         break;
1102
1103       case ACCESS_UPDATE:
1104         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1105                            rsh_command_option);
1106         break;
1107       }
1108
1109   if (archive < 0)
1110     {
1111       open_warn (*archive_name_cursor);
1112       if (!verify_option && access == ACCESS_WRITE && backup_option)
1113         undo_last_backup ();
1114       goto tryagain;
1115     }
1116
1117   SET_BINARY_MODE (archive);
1118
1119   return true;
1120 }
1121