(seek_archive): New function
[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 (void)
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           break;
297
298         case ACCESS_WRITE:
299           child_pid = sys_child_open_for_compress ();
300           break;
301
302         case ACCESS_UPDATE:
303           abort (); /* Should not happen */
304           break;
305         }
306
307       if (wanted_access == ACCESS_WRITE
308           && strcmp (archive_name_array[0], "-") == 0)
309         stdlis = stderr;
310     }
311   else if (strcmp (archive_name_array[0], "-") == 0)
312     {
313       read_full_records_option = true; /* could be a pipe, be safe */
314       if (verify_option)
315         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
316
317       switch (wanted_access)
318         {
319         case ACCESS_READ:
320           archive = STDIN_FILENO;
321           break;
322
323         case ACCESS_WRITE:
324           archive = STDOUT_FILENO;
325           stdlis = stderr;
326           break;
327
328         case ACCESS_UPDATE:
329           archive = STDIN_FILENO;
330           stdlis = stderr;
331           write_archive_to_stdout = true;
332           break;
333         }
334     }
335   else if (verify_option)
336     archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
337                        MODE_RW, rsh_command_option);
338   else
339     switch (wanted_access)
340       {
341       case ACCESS_READ:
342         archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
343                            MODE_RW, rsh_command_option);
344         break;
345
346       case ACCESS_WRITE:
347         if (backup_option)
348           {
349             maybe_backup_file (archive_name_array[0], 1);
350             backed_up_flag = 1;
351           }
352         archive = rmtcreat (archive_name_array[0], MODE_RW,
353                             rsh_command_option);
354         break;
355
356       case ACCESS_UPDATE:
357         archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
358                            MODE_RW, rsh_command_option);
359         break;
360       }
361
362   if (archive < 0
363       || (! _isrmt (archive) && !sys_get_archive_stat ()))
364     {
365       int saved_errno = errno;
366
367       if (backed_up_flag)
368         undo_last_backup ();
369       errno = saved_errno;
370       open_fatal (archive_name_array[0]);
371     }
372
373   sys_detect_dev_null_output ();
374   sys_save_archive_dev_ino ();
375   SET_BINARY_MODE (archive);
376
377   switch (wanted_access)
378     {
379     case ACCESS_UPDATE:
380       records_written = 0;
381     case ACCESS_READ:
382       records_read = 0;
383       record_end = record_start; /* set up for 1st record = # 0 */
384       find_next_block ();       /* read it in, check for EOF */
385
386       if (volume_label_option)
387         {
388           union block *label = find_next_block ();
389
390           if (!label)
391             FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
392                           quote (volume_label_option)));
393           if (!check_label_pattern (label))
394             FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
395                           quote_n (0, label->header.name),
396                           quote_n (1, volume_label_option)));
397         }
398       break;
399
400     case ACCESS_WRITE:
401       records_written = 0;
402       if (volume_label_option)
403         {
404           memset (record_start, 0, BLOCKSIZE);
405           if (multi_volume_option)
406             sprintf (record_start->header.name, "%s Volume 1",
407                      volume_label_option);
408           else
409             strcpy (record_start->header.name, volume_label_option);
410
411           assign_string (&current_stat_info.file_name,
412                          record_start->header.name);
413           current_stat_info.had_trailing_slash =
414             strip_trailing_slashes (current_stat_info.file_name);
415
416           record_start->header.typeflag = GNUTYPE_VOLHDR;
417           TIME_TO_CHARS (start_time, record_start->header.mtime);
418           finish_header (&current_stat_info, record_start, -1);
419         }
420       break;
421     }
422 }
423
424 /* Perform a write to flush the buffer.  */
425 void
426 flush_write (void)
427 {
428   int copy_back;
429   ssize_t status;
430
431   if (checkpoint_option && !(++checkpoint % 10))
432     WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
433
434   if (tape_length_option && tape_length_option <= bytes_written)
435     {
436       errno = ENOSPC;
437       status = 0;
438     }
439   else if (dev_null_output)
440     status = record_size;
441   else
442     status = sys_write_archive_buffer ();
443   if (status != record_size && !multi_volume_option)
444     archive_write_error (status);
445
446   if (status > 0)
447     {
448       records_written++;
449       bytes_written += status;
450     }
451
452   if (status == record_size)
453     {
454       if (multi_volume_option)
455         {
456           if (save_name)
457             {
458               assign_string (&real_s_name, safer_name_suffix (save_name, false));
459               real_s_totsize = save_totsize;
460               real_s_sizeleft = save_sizeleft;
461             }
462           else
463             {
464               assign_string (&real_s_name, 0);
465               real_s_totsize = 0;
466               real_s_sizeleft = 0;
467             }
468         }
469       return;
470     }
471
472   /* We're multivol.  Panic if we didn't get the right kind of response.  */
473
474   /* ENXIO is for the UNIX PC.  */
475   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
476     archive_write_error (status);
477
478   /* If error indicates a short write, we just move to the next tape.  */
479
480   if (!new_volume (ACCESS_WRITE))
481     return;
482
483   if (totals_option)
484     prev_written += bytes_written;
485   bytes_written = 0;
486
487   if (volume_label_option && real_s_name)
488     {
489       copy_back = 2;
490       record_start -= 2;
491     }
492   else if (volume_label_option || real_s_name)
493     {
494       copy_back = 1;
495       record_start--;
496     }
497   else
498     copy_back = 0;
499
500   if (volume_label_option)
501     {
502       memset (record_start, 0, BLOCKSIZE);
503       sprintf (record_start->header.name, "%s Volume %d",
504                volume_label_option, volno);
505       TIME_TO_CHARS (start_time, record_start->header.mtime);
506       record_start->header.typeflag = GNUTYPE_VOLHDR;
507       finish_header (&current_stat_info, record_start, -1);
508     }
509
510   if (real_s_name)
511     {
512       int tmp;
513
514       if (volume_label_option)
515         record_start++;
516
517       memset (record_start, 0, BLOCKSIZE);
518
519       /* FIXME: Michael P Urban writes: [a long name file] is being written
520          when a new volume rolls around [...]  Looks like the wrong value is
521          being preserved in real_s_name, though.  */
522
523       strcpy (record_start->header.name, real_s_name);
524       record_start->header.typeflag = GNUTYPE_MULTIVOL;
525       OFF_TO_CHARS (real_s_sizeleft, record_start->header.size);
526       OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
527                     record_start->oldgnu_header.offset);
528       tmp = verbose_option;
529       verbose_option = 0;
530       finish_header (&current_stat_info, record_start, -1);
531       verbose_option = tmp;
532
533       if (volume_label_option)
534         record_start--;
535     }
536
537   status = sys_write_archive_buffer ();
538   if (status != record_size)
539     archive_write_error (status);
540
541   bytes_written += status;
542
543   if (copy_back)
544     {
545       record_start += copy_back;
546       memcpy (current_block,
547               record_start + blocking_factor - copy_back,
548               copy_back * BLOCKSIZE);
549       current_block += copy_back;
550
551       if (real_s_sizeleft >= copy_back * BLOCKSIZE)
552         real_s_sizeleft -= copy_back * BLOCKSIZE;
553       else if ((real_s_sizeleft + BLOCKSIZE - 1) / BLOCKSIZE <= copy_back)
554         assign_string (&real_s_name, 0);
555       else
556         {
557           assign_string (&real_s_name, safer_name_suffix (save_name, false));
558           real_s_sizeleft = save_sizeleft;
559           real_s_totsize = save_totsize;
560         }
561       copy_back = 0;
562     }
563 }
564
565 /* Handle write errors on the archive.  Write errors are always fatal.
566    Hitting the end of a volume does not cause a write error unless the
567    write was the first record of the volume.  */
568 void
569 archive_write_error (ssize_t status)
570 {
571   /* It might be useful to know how much was written before the error
572      occurred.  */
573   if (totals_option)
574     {
575       int e = errno;
576       print_total_written ();
577       errno = e;
578     }
579
580   write_fatal_details (*archive_name_cursor, status, record_size);
581 }
582
583 /* Handle read errors on the archive.  If the read should be retried,
584    return to the caller.  */
585 void
586 archive_read_error (void)
587 {
588   read_error (*archive_name_cursor);
589
590   if (record_start_block == 0)
591     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
592
593   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
594      then give up on reading the archive.  */
595
596   if (read_error_count++ > READ_ERROR_MAX)
597     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
598   return;
599 }
600
601 static void
602 short_read (size_t status)
603 {
604   size_t left;                  /* bytes left */
605   char *more;                   /* pointer to next byte to read */
606
607   more = record_start->buffer + status;
608   left = record_size - status;
609
610   while (left % BLOCKSIZE != 0
611          || (left && status && read_full_records_option))
612     {
613       if (status)
614         while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
615           archive_read_error ();
616
617       if (status == 0)
618         {
619           char buf[UINTMAX_STRSIZE_BOUND];
620
621           WARN((0, 0, _("Read %s bytes from %s"),
622                 STRINGIFY_BIGINT (record_size - left, buf),
623                 *archive_name_cursor));
624           break;
625         }
626
627       if (! read_full_records_option)
628         {
629           unsigned long rest = record_size - left;
630
631           FATAL_ERROR ((0, 0,
632                         ngettext ("Unaligned block (%lu byte) in archive",
633                                   "Unaligned block (%lu bytes) in archive",
634                                   rest),
635                         rest));
636         }
637
638       /* User warned us about this.  Fix up.  */
639
640       left -= status;
641       more += status;
642     }
643
644   /* FIXME: for size=0, multi-volume support.  On the first record, warn
645      about the problem.  */
646
647   if (!read_full_records_option && verbose_option > 1
648       && record_start_block == 0 && status != 0)
649     {
650       unsigned long rsize = (record_size - left) / BLOCKSIZE;
651       WARN ((0, 0,
652              ngettext ("Record size = %lu block",
653                        "Record size = %lu blocks",
654                        rsize),
655              rsize));
656     }
657
658   record_end = record_start + (record_size - left) / BLOCKSIZE;
659   records_read++;
660 }
661
662 /* Perform a read to flush the buffer.  */
663 void
664 flush_read (void)
665 {
666   size_t status;                /* result from system call */
667
668   if (checkpoint_option && !(++checkpoint % 10))
669     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
670
671   /* Clear the count of errors.  This only applies to a single call to
672      flush_read.  */
673
674   read_error_count = 0;         /* clear error count */
675
676   if (write_archive_to_stdout && record_start_block != 0)
677     {
678       archive = STDOUT_FILENO;
679       status = sys_write_archive_buffer ();
680       archive = STDIN_FILENO;
681       if (status != record_size)
682         archive_write_error (status);
683     }
684   if (multi_volume_option)
685     {
686       if (save_name)
687         {
688           assign_string (&real_s_name, safer_name_suffix (save_name, false));
689           real_s_sizeleft = save_sizeleft;
690           real_s_totsize = save_totsize;
691         }
692       else
693         {
694           assign_string (&real_s_name, 0);
695           real_s_totsize = 0;
696           real_s_sizeleft = 0;
697         }
698     }
699
700  error_loop:
701   status = rmtread (archive, record_start->buffer, record_size);
702   if (status == record_size)
703     {
704       records_read++;
705       return;
706     }
707
708   /* The condition below used to include
709               || (status > 0 && !read_full_records_option)
710      This is incorrect since even if new_volume() succeeds, the
711      subsequent call to rmtread will overwrite the chunk of data
712      already read in the buffer, so the processing will fail */
713
714   if ((status == 0
715        || (status == SAFE_READ_ERROR && errno == ENOSPC))
716       && multi_volume_option)
717     {
718       union block *cursor;
719
720     try_volume:
721       switch (subcommand_option)
722         {
723         case APPEND_SUBCOMMAND:
724         case CAT_SUBCOMMAND:
725         case UPDATE_SUBCOMMAND:
726           if (!new_volume (ACCESS_UPDATE))
727             return;
728           break;
729
730         default:
731           if (!new_volume (ACCESS_READ))
732             return;
733           break;
734         }
735
736       while ((status = rmtread (archive, record_start->buffer, record_size))
737              == SAFE_READ_ERROR)
738         archive_read_error ();
739
740       if (status != record_size)
741         short_read (status);
742
743       cursor = record_start;
744
745       if (cursor->header.typeflag == GNUTYPE_VOLHDR)
746         {
747           if (volume_label_option)
748             {
749               if (!check_label_pattern (cursor))
750                 {
751                   WARN ((0, 0, _("Volume %s does not match %s"),
752                          quote_n (0, cursor->header.name),
753                          quote_n (1, volume_label_option)));
754                   volno--;
755                   global_volno--;
756                   goto try_volume;
757                 }
758             }
759           if (verbose_option)
760             fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
761           cursor++;
762         }
763       else if (volume_label_option)
764         WARN ((0, 0, _("WARNING: No volume header")));
765
766       if (real_s_name)
767         {
768           uintmax_t s1, s2;
769           if (cursor->header.typeflag != GNUTYPE_MULTIVOL
770               || strcmp (cursor->header.name, real_s_name))
771             {
772               WARN ((0, 0, _("%s is not continued on this volume"),
773                      quote (real_s_name)));
774               volno--;
775               global_volno--;
776               goto try_volume;
777             }
778           s1 = UINTMAX_FROM_HEADER (cursor->header.size);
779           s2 = UINTMAX_FROM_HEADER (cursor->oldgnu_header.offset);
780           if (real_s_totsize != s1 + s2 || s1 + s2 < s2)
781             {
782               char totsizebuf[UINTMAX_STRSIZE_BOUND];
783               char s1buf[UINTMAX_STRSIZE_BOUND];
784               char s2buf[UINTMAX_STRSIZE_BOUND];
785
786               WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
787                      quote (cursor->header.name),
788                      STRINGIFY_BIGINT (save_totsize, totsizebuf),
789                      STRINGIFY_BIGINT (s1, s1buf),
790                      STRINGIFY_BIGINT (s2, s2buf)));
791               volno--;
792               global_volno--;
793               goto try_volume;
794             }
795           if (real_s_totsize - real_s_sizeleft
796               != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
797             {
798               WARN ((0, 0, _("This volume is out of sequence")));
799               volno--;
800               global_volno--;
801               goto try_volume;
802             }
803           cursor++;
804         }
805       current_block = cursor;
806       records_read++;
807       return;
808     }
809   else if (status == SAFE_READ_ERROR)
810     {
811       archive_read_error ();
812       goto error_loop;          /* try again */
813     }
814
815   short_read (status);
816 }
817
818 /*  Flush the current buffer to/from the archive.  */
819 void
820 flush_archive (void)
821 {
822   record_start_block += record_end - record_start;
823   current_block = record_start;
824   record_end = record_start + blocking_factor;
825
826   if (access_mode == ACCESS_READ && time_to_start_writing)
827     {
828       access_mode = ACCESS_WRITE;
829       time_to_start_writing = false;
830       backspace_output ();
831     }
832
833   switch (access_mode)
834     {
835     case ACCESS_READ:
836       flush_read ();
837       break;
838
839     case ACCESS_WRITE:
840       flush_write ();
841       break;
842
843     case ACCESS_UPDATE:
844       abort ();
845     }
846 }
847
848 /* Backspace the archive descriptor by one record worth.  If it's a
849    tape, MTIOCTOP will work.  If it's something else, try to seek on
850    it.  If we can't seek, we lose!  */
851 static void
852 backspace_output (void)
853 {
854 #ifdef MTIOCTOP
855   {
856     struct mtop operation;
857
858     operation.mt_op = MTBSR;
859     operation.mt_count = 1;
860     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
861       return;
862     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
863       return;
864   }
865 #endif
866
867   {
868     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
869
870     /* Seek back to the beginning of this record and start writing there.  */
871
872     position -= record_size;
873     if (position < 0)
874       position = 0;
875     if (rmtlseek (archive, position, SEEK_SET) != position)
876       {
877         /* Lseek failed.  Try a different method.  */
878
879         WARN ((0, 0,
880                _("Cannot backspace archive file; it may be unreadable without -i")));
881
882         /* Replace the first part of the record with NULs.  */
883
884         if (record_start->buffer != output_start)
885           memset (record_start->buffer, 0,
886                   output_start - record_start->buffer);
887       }
888   }
889 }
890
891 off_t
892 seek_archive (off_t size)
893 {
894   off_t start = current_block_ordinal ();
895   off_t offset;
896   off_t nrec, nblk;
897   off_t skipped = (blocking_factor - (current_block - record_start));
898   
899   size -= skipped * BLOCKSIZE;
900   
901   if (size < record_size)
902     return 0;
903   /* FIXME: flush? */
904   
905   /* Compute number of records to skip */
906   nrec = size / record_size;
907   offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
908   if (offset < 0)
909     return offset;
910
911   if (offset % record_size)
912     FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
913
914   /* Convert to number of records */
915   offset /= BLOCKSIZE;
916   /* Compute number of skipped blocks */
917   nblk = offset - start;
918
919   /* Update buffering info */
920   records_read += nblk / blocking_factor;
921   record_start_block = offset - blocking_factor;
922   current_block = record_end;
923  
924   return nblk;
925 }
926
927 /* Close the archive file.  */
928 void
929 close_archive (void)
930 {
931   if (time_to_start_writing || access_mode == ACCESS_WRITE)
932     flush_archive ();
933
934   sys_drain_input_pipe ();
935
936   if (verify_option)
937     verify_volume ();
938
939   if (rmtclose (archive) != 0)
940     close_warn (*archive_name_cursor);
941
942   sys_wait_for_child (child_pid);
943
944   tar_stat_destroy (&current_stat_info);
945   if (save_name)
946     free (save_name);
947   if (real_s_name)
948     free (real_s_name);
949   free (multi_volume_option ? record_start - 2 : record_start);
950 }
951
952 /* Called to initialize the global volume number.  */
953 void
954 init_volume_number (void)
955 {
956   FILE *file = fopen (volno_file_option, "r");
957
958   if (file)
959     {
960       if (fscanf (file, "%d", &global_volno) != 1
961           || global_volno < 0)
962         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
963                       quotearg_colon (volno_file_option)));
964       if (ferror (file))
965         read_error (volno_file_option);
966       if (fclose (file) != 0)
967         close_error (volno_file_option);
968     }
969   else if (errno != ENOENT)
970     open_error (volno_file_option);
971 }
972
973 /* Called to write out the closing global volume number.  */
974 void
975 closeout_volume_number (void)
976 {
977   FILE *file = fopen (volno_file_option, "w");
978
979   if (file)
980     {
981       fprintf (file, "%d\n", global_volno);
982       if (ferror (file))
983         write_error (volno_file_option);
984       if (fclose (file) != 0)
985         close_error (volno_file_option);
986     }
987   else
988     open_error (volno_file_option);
989 }
990
991 /* We've hit the end of the old volume.  Close it and open the next one.
992    Return nonzero on success.
993 */
994 static bool
995 new_volume (enum access_mode mode)
996 {
997   static FILE *read_file;
998   static int looped;
999
1000   if (!read_file && !info_script_option)
1001     /* FIXME: if fopen is used, it will never be closed.  */
1002     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1003
1004   if (now_verifying)
1005     return false;
1006   if (verify_option)
1007     verify_volume ();
1008
1009   if (rmtclose (archive) != 0)
1010     close_warn (*archive_name_cursor);
1011
1012   global_volno++;
1013   if (global_volno < 0)
1014     FATAL_ERROR ((0, 0, _("Volume number overflow")));
1015   volno++;
1016   archive_name_cursor++;
1017   if (archive_name_cursor == archive_name_array + archive_names)
1018     {
1019       archive_name_cursor = archive_name_array;
1020       looped = 1;
1021     }
1022
1023  tryagain:
1024   if (looped)
1025     {
1026       /* We have to prompt from now on.  */
1027
1028       if (info_script_option)
1029         {
1030           if (volno_file_option)
1031             closeout_volume_number ();
1032           if (system (info_script_option) != 0)
1033             FATAL_ERROR ((0, 0, _("`%s' command failed"), info_script_option));
1034         }
1035       else
1036         while (1)
1037           {
1038             char input_buffer[80];
1039
1040             fputc ('\007', stderr);
1041             fprintf (stderr,
1042                      _("Prepare volume #%d for %s and hit return: "),
1043                      global_volno, quote (*archive_name_cursor));
1044             fflush (stderr);
1045
1046             if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1047               {
1048                 WARN ((0, 0, _("EOF where user reply was expected")));
1049
1050                 if (subcommand_option != EXTRACT_SUBCOMMAND
1051                     && subcommand_option != LIST_SUBCOMMAND
1052                     && subcommand_option != DIFF_SUBCOMMAND)
1053                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1054
1055                 fatal_exit ();
1056               }
1057             if (input_buffer[0] == '\n'
1058                 || input_buffer[0] == 'y'
1059                 || input_buffer[0] == 'Y')
1060               break;
1061
1062             switch (input_buffer[0])
1063               {
1064               case '?':
1065                 {
1066                   /* FIXME: Might it be useful to disable the '!' command? */
1067                   fprintf (stderr, _("\
1068  n [name]   Give a new file name for the next (and subsequent) volume(s)\n\
1069  q          Abort tar\n\
1070  !          Spawn a subshell\n\
1071  ?          Print this list\n"));
1072                 }
1073                 break;
1074
1075               case 'q':
1076                 /* Quit.  */
1077
1078                 WARN ((0, 0, _("No new volume; exiting.\n")));
1079
1080                 if (subcommand_option != EXTRACT_SUBCOMMAND
1081                     && subcommand_option != LIST_SUBCOMMAND
1082                     && subcommand_option != DIFF_SUBCOMMAND)
1083                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
1084
1085                 fatal_exit ();
1086
1087               case 'n':
1088                 /* Get new file name.  */
1089
1090                 {
1091                   char *name = &input_buffer[1];
1092                   char *cursor;
1093
1094                   for (name = input_buffer + 1;
1095                        *name == ' ' || *name == '\t';
1096                        name++)
1097                     ;
1098
1099                   for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1100                     ;
1101                   *cursor = '\0';
1102
1103                   /* FIXME: the following allocation is never reclaimed.  */
1104                   *archive_name_cursor = xstrdup (name);
1105                 }
1106                 break;
1107
1108               case '!':
1109                 sys_spawn_shell ();
1110                 break;
1111               }
1112           }
1113     }
1114
1115   if (strcmp (archive_name_cursor[0], "-") == 0)
1116     {
1117       read_full_records_option = true;
1118       archive = STDIN_FILENO;
1119     }
1120   else if (verify_option)
1121     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1122                        rsh_command_option);
1123   else
1124     switch (mode)
1125       {
1126       case ACCESS_READ:
1127         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1128                            rsh_command_option);
1129         break;
1130
1131       case ACCESS_WRITE:
1132         if (backup_option)
1133           maybe_backup_file (*archive_name_cursor, 1);
1134         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1135                             rsh_command_option);
1136         break;
1137
1138       case ACCESS_UPDATE:
1139         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1140                            rsh_command_option);
1141         break;
1142       }
1143
1144   if (archive < 0)
1145     {
1146       open_warn (*archive_name_cursor);
1147       if (!verify_option && mode == ACCESS_WRITE && backup_option)
1148         undo_last_backup ();
1149       goto tryagain;
1150     }
1151
1152   SET_BINARY_MODE (archive);
1153
1154   return true;
1155 }
1156