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