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