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