(archive_format_string): Remove static qualifier.
[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
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[2];  /* allocated memory */
44 static int record_index;
45
46 /* FIXME: The following variables should ideally be static to this
47    module.  However, this cannot be done yet.  The cleanup continues!  */
48
49 union block *record_start;      /* start of record of archive */
50 union block *record_end;        /* last+1 block of archive record */
51 union block *current_block;     /* current block of archive */
52 enum access_mode access_mode;   /* how do we handle the archive */
53 off_t records_read;             /* number of records read from this archive */
54 off_t records_written;          /* likewise, for records written */
55
56 static off_t record_start_block; /* block ordinal at record_start */
57
58 /* Where we write list messages (not errors, not interactions) to.  */
59 FILE *stdlis;
60
61 static void backspace_output (void);
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 bool write_archive_to_stdout;
86
87 void (*flush_write_ptr) (size_t);
88 void (*flush_read_ptr) (void);
89
90 \f
91 char *volume_label;
92 char *continued_file_name;
93 uintmax_t continued_file_size;
94 uintmax_t continued_file_offset;
95
96 \f
97 static int volno = 1;           /* which volume of a multi-volume tape we're
98                                    on */
99 static int global_volno = 1;    /* volume number to print in external
100                                    messages */
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
110 \f
111 /* Multi-volume tracking support */
112 static char *save_name;         /* name of the file we are currently writing */
113 static off_t save_totsize;      /* total size of file we are writing, only
114                                    valid if save_name is nonzero */
115 static off_t save_sizeleft;     /* where we are in the file we are writing,
116                                    only valid if save_name is nonzero */
117
118 void
119 mv_begin (struct tar_stat_info *st)
120 {
121   if (multi_volume_option)
122     {
123       assign_string (&save_name,  st->orig_file_name);
124       save_totsize = save_sizeleft = st->stat.st_size;
125     }
126 }
127
128 void
129 mv_end ()
130 {
131   if (multi_volume_option)
132     assign_string (&save_name, 0);
133 }
134
135 void
136 mv_total_size (off_t size)
137 {
138   save_totsize = size;
139 }
140
141 void
142 mv_size_left (off_t size)
143 {
144   save_sizeleft = size;
145 }
146
147 \f
148 /* Functions.  */
149
150 void
151 clear_read_error_count (void)
152 {
153   read_error_count = 0;
154 }
155
156 \f
157 /* Time-related functions */
158
159 double duration;
160
161 void
162 set_start_time ()
163 {
164   gettime (&start_time);
165 }
166
167 void
168 compute_duration ()
169 {
170   struct timespec now;
171   gettime (&now);
172   duration += ((now.tv_sec - start_time.tv_sec)
173                + (now.tv_nsec - start_time.tv_nsec) / 1e9);
174   set_start_time ();
175 }
176
177 \f
178 /* Compression detection */
179
180 enum compress_type {
181   ct_none,
182   ct_compress,
183   ct_gzip,
184   ct_bzip2
185 };
186
187 struct zip_magic
188 {
189   enum compress_type type;
190   size_t length;
191   char *magic;
192   char *program;
193   char *option;
194 };
195
196 static struct zip_magic const magic[] = {
197   { ct_none, },
198   { ct_compress, 2, "\037\235", "compress", "-Z" },
199   { ct_gzip,     2, "\037\213", "gzip", "-z"  },
200   { ct_bzip2,    3, "BZh",      "bzip2", "-j" },
201 };
202
203 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
204
205 #define compress_option(t) magic[t].option
206 #define compress_program(t) magic[t].program
207
208 /* Check if the file ARCHIVE is a compressed archive. */
209 enum compress_type
210 check_compressed_archive ()
211 {
212   struct zip_magic const *p;
213   bool sfr;
214
215   /* Prepare global data needed for find_next_block: */
216   record_end = record_start; /* set up for 1st record = # 0 */
217   sfr = read_full_records;
218   read_full_records = true; /* Suppress fatal error on reading a partial
219                                record */
220   find_next_block ();
221
222   /* Restore global values */
223   read_full_records = sfr;
224
225   if (tar_checksum (record_start, true) == HEADER_SUCCESS)
226     /* Probably a valid header */
227     return ct_none;
228
229   for (p = magic + 1; p < magic + NMAGIC; p++)
230     if (memcmp (record_start->buffer, p->magic, p->length) == 0)
231       return p->type;
232
233   return ct_none;
234 }
235
236 /* Open an archive named archive_name_array[0]. Detect if it is
237    a compressed archive of known type and use corresponding decompression
238    program if so */
239 int
240 open_compressed_archive ()
241 {
242   archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
243                      MODE_RW, rsh_command_option);
244   if (archive == -1)
245     return archive;
246
247   if (!multi_volume_option)
248     {
249       enum compress_type type = check_compressed_archive ();
250
251       if (type == ct_none)
252         return archive;
253
254       /* FD is not needed any more */
255       rmtclose (archive);
256
257       hit_eof = false; /* It might have been set by find_next_block in
258                           check_compressed_archive */
259
260       /* Open compressed archive */
261       use_compress_program_option = compress_program (type);
262       child_pid = sys_child_open_for_uncompress ();
263       read_full_records = true;
264     }
265
266   records_read = 0;
267   record_end = record_start; /* set up for 1st record = # 0 */
268
269   return archive;
270 }
271 \f
272
273 void
274 print_total_written (void)
275 {
276   tarlong written = prev_written + bytes_written;
277   char bytes[sizeof (tarlong) * CHAR_BIT];
278   char abbr[LONGEST_HUMAN_READABLE + 1];
279   char rate[LONGEST_HUMAN_READABLE + 1];
280
281   int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
282
283   sprintf (bytes, TARLONG_FORMAT, written);
284
285   /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*".  */
286   fprintf (stderr, _("Total bytes written: %s (%s, %s/s)\n"), bytes,
287            human_readable (written, abbr, human_opts, 1, 1),
288            (0 < duration && written / duration < (uintmax_t) -1
289             ? human_readable (written / duration, rate, human_opts, 1, 1)
290             : "?"));
291 }
292
293 /* Compute and return the block ordinal at current_block.  */
294 off_t
295 current_block_ordinal (void)
296 {
297   return record_start_block + (current_block - record_start);
298 }
299
300 /* If the EOF flag is set, reset it, as well as current_block, etc.  */
301 void
302 reset_eof (void)
303 {
304   if (hit_eof)
305     {
306       hit_eof = false;
307       current_block = record_start;
308       record_end = record_start + blocking_factor;
309       access_mode = ACCESS_WRITE;
310     }
311 }
312
313 /* Return the location of the next available input or output block.
314    Return zero for EOF.  Once we have returned zero, we just keep returning
315    it, to avoid accidentally going on to the next file on the tape.  */
316 union block *
317 find_next_block (void)
318 {
319   if (current_block == record_end)
320     {
321       if (hit_eof)
322         return 0;
323       flush_archive ();
324       if (current_block == record_end)
325         {
326           hit_eof = true;
327           return 0;
328         }
329     }
330   return current_block;
331 }
332
333 /* Indicate that we have used all blocks up thru BLOCK. */
334 void
335 set_next_block_after (union block *block)
336 {
337   while (block >= current_block)
338     current_block++;
339
340   /* Do *not* flush the archive here.  If we do, the same argument to
341      set_next_block_after could mean the next block (if the input record
342      is exactly one block long), which is not what is intended.  */
343
344   if (current_block > record_end)
345     abort ();
346 }
347
348 /* Return the number of bytes comprising the space between POINTER
349    through the end of the current buffer of blocks.  This space is
350    available for filling with data, or taking data from.  POINTER is
351    usually (but not always) the result of previous find_next_block call.  */
352 size_t
353 available_space_after (union block *pointer)
354 {
355   return record_end->buffer - pointer->buffer;
356 }
357
358 /* Close file having descriptor FD, and abort if close unsuccessful.  */
359 void
360 xclose (int fd)
361 {
362   if (close (fd) != 0)
363     close_error (_("(pipe)"));
364 }
365
366 static void
367 init_buffer ()
368 {
369   if (!record_buffer[record_index])
370     page_aligned_alloc (&record_buffer[record_index], record_size);
371       
372   record_start = record_buffer[record_index];
373   current_block = record_start;
374   record_end = record_start + blocking_factor;
375 }
376
377 /* Open an archive file.  The argument specifies whether we are
378    reading or writing, or both.  */
379 static void
380 _open_archive (enum access_mode wanted_access)
381 {
382   int backed_up_flag = 0;
383
384   if (index_file_name)
385     {
386       stdlis = fopen (index_file_name, "w");
387       if (! stdlis)
388         open_error (index_file_name);
389     }
390   else
391     stdlis = to_stdout_option ? stderr : stdout;
392
393   if (record_size == 0)
394     FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
395
396   if (archive_names == 0)
397     FATAL_ERROR ((0, 0, _("No archive name given")));
398
399   tar_stat_destroy (&current_stat_info);
400   save_name = 0;
401   real_s_name = 0;
402
403   record_index = 0;
404   init_buffer ();
405   
406   /* When updating the archive, we start with reading.  */
407   access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
408
409   read_full_records = read_full_records_option;
410
411   records_read = 0;
412
413   if (use_compress_program_option)
414     {
415       switch (wanted_access)
416         {
417         case ACCESS_READ:
418           child_pid = sys_child_open_for_uncompress ();
419           read_full_records = true;
420           record_end = record_start; /* set up for 1st record = # 0 */
421           break;
422
423         case ACCESS_WRITE:
424           child_pid = sys_child_open_for_compress ();
425           break;
426
427         case ACCESS_UPDATE:
428           abort (); /* Should not happen */
429           break;
430         }
431
432       if (wanted_access == ACCESS_WRITE
433           && strcmp (archive_name_array[0], "-") == 0)
434         stdlis = stderr;
435     }
436   else if (strcmp (archive_name_array[0], "-") == 0)
437     {
438       read_full_records = true; /* could be a pipe, be safe */
439       if (verify_option)
440         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
441
442       switch (wanted_access)
443         {
444         case ACCESS_READ:
445           {
446             enum compress_type type;
447
448             archive = STDIN_FILENO;
449
450             type = check_compressed_archive (archive);
451             if (type != ct_none)
452               FATAL_ERROR ((0, 0,
453                             _("Archive is compressed. Use %s option"),
454                             compress_option (type)));
455           }
456           break;
457
458         case ACCESS_WRITE:
459           archive = STDOUT_FILENO;
460           stdlis = stderr;
461           break;
462
463         case ACCESS_UPDATE:
464           archive = STDIN_FILENO;
465           stdlis = stderr;
466           write_archive_to_stdout = true;
467           break;
468         }
469     }
470   else if (verify_option)
471     archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
472                        MODE_RW, rsh_command_option);
473   else
474     switch (wanted_access)
475       {
476       case ACCESS_READ:
477         archive = open_compressed_archive ();
478         break;
479
480       case ACCESS_WRITE:
481         if (backup_option)
482           {
483             maybe_backup_file (archive_name_array[0], 1);
484             backed_up_flag = 1;
485           }
486         archive = rmtcreat (archive_name_array[0], MODE_RW,
487                             rsh_command_option);
488         break;
489
490       case ACCESS_UPDATE:
491         archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
492                            MODE_RW, rsh_command_option);
493         break;
494       }
495
496   if (archive < 0
497       || (! _isrmt (archive) && !sys_get_archive_stat ()))
498     {
499       int saved_errno = errno;
500
501       if (backed_up_flag)
502         undo_last_backup ();
503       errno = saved_errno;
504       open_fatal (archive_name_array[0]);
505     }
506
507   sys_detect_dev_null_output ();
508   sys_save_archive_dev_ino ();
509   SET_BINARY_MODE (archive);
510
511   switch (wanted_access)
512     {
513     case ACCESS_UPDATE:
514       records_written = 0;
515       record_end = record_start; /* set up for 1st record = # 0 */
516
517     case ACCESS_READ:
518       find_next_block ();       /* read it in, check for EOF */
519       break;
520
521     case ACCESS_WRITE:
522       records_written = 0;
523       break;
524     }
525 }
526
527 /* Perform a write to flush the buffer.  */
528 ssize_t
529 _flush_write (void)
530 {
531   ssize_t status;
532
533   if (checkpoint_option && !(++checkpoint % 10))
534     /* TRANSLATORS: This is a ``checkpoint of write operation'',
535        *not* ``Writing a checkpoint''.
536        E.g. in Spanish ``Punto de comprobaci@'on de escritura'',
537        *not* ``Escribiendo un punto de comprobaci@'on'' */
538     WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
539
540   if (tape_length_option && tape_length_option <= bytes_written)
541     {
542       errno = ENOSPC;
543       status = 0;
544     }
545   else if (dev_null_output)
546     status = record_size;
547   else
548     status = sys_write_archive_buffer ();
549
550   return status;
551 }
552
553 /* Handle write errors on the archive.  Write errors are always fatal.
554    Hitting the end of a volume does not cause a write error unless the
555    write was the first record of the volume.  */
556 void
557 archive_write_error (ssize_t status)
558 {
559   /* It might be useful to know how much was written before the error
560      occurred.  */
561   if (totals_option)
562     {
563       int e = errno;
564       print_total_written ();
565       errno = e;
566     }
567
568   write_fatal_details (*archive_name_cursor, status, record_size);
569 }
570
571 /* Handle read errors on the archive.  If the read should be retried,
572    return to the caller.  */
573 void
574 archive_read_error (void)
575 {
576   read_error (*archive_name_cursor);
577
578   if (record_start_block == 0)
579     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
580
581   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
582      then give up on reading the archive.  */
583
584   if (read_error_count++ > READ_ERROR_MAX)
585     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
586   return;
587 }
588
589 static void
590 short_read (size_t status)
591 {
592   size_t left;                  /* bytes left */
593   char *more;                   /* pointer to next byte to read */
594
595   more = record_start->buffer + status;
596   left = record_size - status;
597
598   while (left % BLOCKSIZE != 0
599          || (left && status && read_full_records))
600     {
601       if (status)
602         while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
603           archive_read_error ();
604
605       if (status == 0)
606         break;
607
608       if (! read_full_records)
609         {
610           unsigned long rest = record_size - left;
611
612           FATAL_ERROR ((0, 0,
613                         ngettext ("Unaligned block (%lu byte) in archive",
614                                   "Unaligned block (%lu bytes) in archive",
615                                   rest),
616                         rest));
617         }
618
619       /* User warned us about this.  Fix up.  */
620
621       left -= status;
622       more += status;
623     }
624
625   /* FIXME: for size=0, multi-volume support.  On the first record, warn
626      about the problem.  */
627
628   if (!read_full_records && verbose_option > 1
629       && record_start_block == 0 && status != 0)
630     {
631       unsigned long rsize = (record_size - left) / BLOCKSIZE;
632       WARN ((0, 0,
633              ngettext ("Record size = %lu block",
634                        "Record size = %lu blocks",
635                        rsize),
636              rsize));
637     }
638
639   record_end = record_start + (record_size - left) / BLOCKSIZE;
640   records_read++;
641 }
642
643 /* Perform a read to flush the buffer.  */
644 size_t
645 _flush_read (void)
646 {
647   size_t status;                /* result from system call */
648
649   if (checkpoint_option && !(++checkpoint % 10))
650     /* TRANSLATORS: This is a ``checkpoint of read operation'',
651        *not* ``Reading a checkpoint''.
652        E.g. in Spanish ``Punto de comprobaci@'on de lectura'',
653        *not* ``Leyendo un punto de comprobaci@'on'' */
654     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
655
656   /* Clear the count of errors.  This only applies to a single call to
657      flush_read.  */
658
659   read_error_count = 0;         /* clear error count */
660
661   if (write_archive_to_stdout && record_start_block != 0)
662     {
663       archive = STDOUT_FILENO;
664       status = sys_write_archive_buffer ();
665       archive = STDIN_FILENO;
666       if (status != record_size)
667         archive_write_error (status);
668     }
669
670   status = rmtread (archive, record_start->buffer, record_size);
671   if (status == record_size)
672     records_read++;
673   return status;
674 }
675
676 /*  Flush the current buffer to/from the archive.  */
677 void
678 flush_archive (void)
679 {
680   size_t buffer_level = current_block->buffer - record_start->buffer;
681   record_start_block += record_end - record_start;
682   current_block = record_start;
683   record_end = record_start + blocking_factor;
684
685   if (access_mode == ACCESS_READ && time_to_start_writing)
686     {
687       access_mode = ACCESS_WRITE;
688       time_to_start_writing = false;
689       backspace_output ();
690     }
691
692   switch (access_mode)
693     {
694     case ACCESS_READ:
695       flush_read ();
696       break;
697
698     case ACCESS_WRITE:
699       flush_write_ptr (buffer_level);
700       break;
701
702     case ACCESS_UPDATE:
703       abort ();
704     }
705 }
706
707 /* Backspace the archive descriptor by one record worth.  If it's a
708    tape, MTIOCTOP will work.  If it's something else, try to seek on
709    it.  If we can't seek, we lose!  */
710 static void
711 backspace_output (void)
712 {
713 #ifdef MTIOCTOP
714   {
715     struct mtop operation;
716
717     operation.mt_op = MTBSR;
718     operation.mt_count = 1;
719     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
720       return;
721     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
722       return;
723   }
724 #endif
725
726   {
727     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
728
729     /* Seek back to the beginning of this record and start writing there.  */
730
731     position -= record_size;
732     if (position < 0)
733       position = 0;
734     if (rmtlseek (archive, position, SEEK_SET) != position)
735       {
736         /* Lseek failed.  Try a different method.  */
737
738         WARN ((0, 0,
739                _("Cannot backspace archive file; it may be unreadable without -i")));
740
741         /* Replace the first part of the record with NULs.  */
742
743         if (record_start->buffer != output_start)
744           memset (record_start->buffer, 0,
745                   output_start - record_start->buffer);
746       }
747   }
748 }
749
750 off_t
751 seek_archive (off_t size)
752 {
753   off_t start = current_block_ordinal ();
754   off_t offset;
755   off_t nrec, nblk;
756   off_t skipped = (blocking_factor - (current_block - record_start));
757
758   size -= skipped * BLOCKSIZE;
759
760   if (size < record_size)
761     return 0;
762   /* FIXME: flush? */
763
764   /* Compute number of records to skip */
765   nrec = size / record_size;
766   offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
767   if (offset < 0)
768     return offset;
769
770   if (offset % record_size)
771     FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
772
773   /* Convert to number of records */
774   offset /= BLOCKSIZE;
775   /* Compute number of skipped blocks */
776   nblk = offset - start;
777
778   /* Update buffering info */
779   records_read += nblk / blocking_factor;
780   record_start_block = offset - blocking_factor;
781   current_block = record_end;
782
783   return nblk;
784 }
785
786 /* Close the archive file.  */
787 void
788 close_archive (void)
789 {
790   if (time_to_start_writing || access_mode == ACCESS_WRITE)
791     {
792       flush_archive ();
793       if (current_block > record_start)
794         flush_archive ();
795     }
796
797   sys_drain_input_pipe ();
798
799   compute_duration ();
800   if (verify_option)
801     verify_volume ();
802
803   if (rmtclose (archive) != 0)
804     close_warn (*archive_name_cursor);
805
806   sys_wait_for_child (child_pid);
807
808   tar_stat_destroy (&current_stat_info);
809   if (save_name)
810     free (save_name);
811   if (real_s_name)
812     free (real_s_name);
813   free (record_buffer[0]);
814   free (record_buffer[1]);
815 }
816
817 /* Called to initialize the global volume number.  */
818 void
819 init_volume_number (void)
820 {
821   FILE *file = fopen (volno_file_option, "r");
822
823   if (file)
824     {
825       if (fscanf (file, "%d", &global_volno) != 1
826           || global_volno < 0)
827         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
828                       quotearg_colon (volno_file_option)));
829       if (ferror (file))
830         read_error (volno_file_option);
831       if (fclose (file) != 0)
832         close_error (volno_file_option);
833     }
834   else if (errno != ENOENT)
835     open_error (volno_file_option);
836 }
837
838 /* Called to write out the closing global volume number.  */
839 void
840 closeout_volume_number (void)
841 {
842   FILE *file = fopen (volno_file_option, "w");
843
844   if (file)
845     {
846       fprintf (file, "%d\n", global_volno);
847       if (ferror (file))
848         write_error (volno_file_option);
849       if (fclose (file) != 0)
850         close_error (volno_file_option);
851     }
852   else
853     open_error (volno_file_option);
854 }
855
856 \f
857 static void
858 increase_volume_number ()
859 {
860   global_volno++;
861   if (global_volno < 0)
862     FATAL_ERROR ((0, 0, _("Volume number overflow")));
863   volno++;
864 }
865
866 /* We've hit the end of the old volume.  Close it and open the next one.
867    Return nonzero on success.
868 */
869 static bool
870 new_volume (enum access_mode mode)
871 {
872   static FILE *read_file;
873   static int looped;
874
875   if (!read_file && !info_script_option)
876     /* FIXME: if fopen is used, it will never be closed.  */
877     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
878
879   if (now_verifying)
880     return false;
881   if (verify_option)
882     verify_volume ();
883
884   assign_string (&volume_label, NULL);
885   assign_string (&continued_file_name, NULL);
886   continued_file_size = continued_file_offset = 0;
887   
888   if (rmtclose (archive) != 0)
889     close_warn (*archive_name_cursor);
890
891   archive_name_cursor++;
892   if (archive_name_cursor == archive_name_array + archive_names)
893     {
894       archive_name_cursor = archive_name_array;
895       looped = 1;
896     }
897
898  tryagain:
899   if (looped)
900     {
901       /* We have to prompt from now on.  */
902
903       if (info_script_option)
904         {
905           if (volno_file_option)
906             closeout_volume_number ();
907           if (sys_exec_info_script (*archive_name_cursor, global_volno+1))
908             FATAL_ERROR ((0, 0, _("%s command failed"),
909                           quote (info_script_option)));
910         }
911       else
912         while (1)
913           {
914             char input_buffer[80];
915
916             fputc ('\007', stderr);
917             fprintf (stderr,
918                      _("Prepare volume #%d for %s and hit return: "),
919                      global_volno + 1, quote (*archive_name_cursor));
920             fflush (stderr);
921
922             if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
923               {
924                 WARN ((0, 0, _("EOF where user reply was expected")));
925
926                 if (subcommand_option != EXTRACT_SUBCOMMAND
927                     && subcommand_option != LIST_SUBCOMMAND
928                     && subcommand_option != DIFF_SUBCOMMAND)
929                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
930
931                 fatal_exit ();
932               }
933             if (input_buffer[0] == '\n'
934                 || input_buffer[0] == 'y'
935                 || input_buffer[0] == 'Y')
936               break;
937
938             switch (input_buffer[0])
939               {
940               case '?':
941                 {
942                   /* FIXME: Might it be useful to disable the '!' command? */
943                   fprintf (stderr, _("\
944  n [name]   Give a new file name for the next (and subsequent) volume(s)\n\
945  q          Abort tar\n\
946  !          Spawn a subshell\n\
947  ?          Print this list\n"));
948                 }
949                 break;
950
951               case 'q':
952                 /* Quit.  */
953
954                 WARN ((0, 0, _("No new volume; exiting.\n")));
955
956                 if (subcommand_option != EXTRACT_SUBCOMMAND
957                     && subcommand_option != LIST_SUBCOMMAND
958                     && subcommand_option != DIFF_SUBCOMMAND)
959                   WARN ((0, 0, _("WARNING: Archive is incomplete")));
960
961                 fatal_exit ();
962
963               case 'n':
964                 /* Get new file name.  */
965
966                 {
967                   char *name = &input_buffer[1];
968                   char *cursor;
969
970                   for (name = input_buffer + 1;
971                        *name == ' ' || *name == '\t';
972                        name++)
973                     ;
974
975                   for (cursor = name; *cursor && *cursor != '\n'; cursor++)
976                     ;
977                   *cursor = '\0';
978
979                   /* FIXME: the following allocation is never reclaimed.  */
980                   *archive_name_cursor = xstrdup (name);
981                 }
982                 break;
983
984               case '!':
985                 sys_spawn_shell ();
986                 break;
987               }
988           }
989     }
990
991   if (strcmp (archive_name_cursor[0], "-") == 0)
992     {
993       read_full_records = true;
994       archive = STDIN_FILENO;
995     }
996   else if (verify_option)
997     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
998                        rsh_command_option);
999   else
1000     switch (mode)
1001       {
1002       case ACCESS_READ:
1003         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1004                            rsh_command_option);
1005         break;
1006
1007       case ACCESS_WRITE:
1008         if (backup_option)
1009           maybe_backup_file (*archive_name_cursor, 1);
1010         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1011                             rsh_command_option);
1012         break;
1013
1014       case ACCESS_UPDATE:
1015         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1016                            rsh_command_option);
1017         break;
1018       }
1019
1020   if (archive < 0)
1021     {
1022       open_warn (*archive_name_cursor);
1023       if (!verify_option && mode == ACCESS_WRITE && backup_option)
1024         undo_last_backup ();
1025       goto tryagain;
1026     }
1027
1028   SET_BINARY_MODE (archive);
1029
1030   return true;
1031 }
1032
1033 static bool
1034 read_header0 ()
1035 {
1036   enum read_header rc = read_header (false);
1037
1038   if (rc == HEADER_SUCCESS)
1039     {
1040       set_next_block_after (current_header);
1041       return true;
1042     }
1043   ERROR ((0, 0, _("This does not look like a tar archive")));
1044   return false;
1045 }
1046
1047 bool
1048 try_new_volume ()
1049 {
1050   size_t status;
1051   union block *header;
1052
1053   switch (subcommand_option)
1054     {
1055     case APPEND_SUBCOMMAND:
1056     case CAT_SUBCOMMAND:
1057     case UPDATE_SUBCOMMAND:
1058       if (!new_volume (ACCESS_UPDATE))
1059         return true;
1060       break;
1061
1062     default:
1063       if (!new_volume (ACCESS_READ))
1064         return true;
1065       break;
1066     }
1067
1068   while ((status = rmtread (archive, record_start->buffer, record_size))
1069          == SAFE_READ_ERROR)
1070     archive_read_error ();
1071
1072   if (status != record_size)
1073     short_read (status);
1074
1075   header = find_next_block ();
1076   if (!header)
1077     return false;
1078   switch (header->header.typeflag)
1079     {
1080     case XGLTYPE:
1081       {
1082         struct tar_stat_info dummy;
1083         if (!read_header0 ())
1084           return false;
1085         tar_stat_init (&dummy);
1086         xheader_decode (&dummy); /* decodes values from the global header */
1087         tar_stat_destroy (&dummy);
1088         if (!real_s_name)
1089           {
1090             /* We have read the extended header of the first member in
1091                this volume. Put it back, so next read_header works as
1092                expected. */
1093             current_block = record_start;
1094           }
1095         break;
1096       }
1097       
1098     case GNUTYPE_VOLHDR:
1099       if (!read_header0 ())
1100         return false;
1101       assign_string (&volume_label, current_header->header.name);
1102       set_next_block_after (header);
1103       header = find_next_block ();
1104       if (header->header.typeflag != GNUTYPE_MULTIVOL)
1105         break;
1106       /* FALL THROUGH */
1107       
1108     case GNUTYPE_MULTIVOL:
1109       if (!read_header0 ())
1110         return false;
1111       assign_string (&continued_file_name, current_header->header.name);
1112       continued_file_size =
1113         UINTMAX_FROM_HEADER (current_header->header.size);
1114       continued_file_offset =
1115         UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
1116       break;
1117       
1118     default:
1119       break;
1120     }
1121
1122   if (real_s_name)
1123     {
1124       uintmax_t s;
1125       if (!continued_file_name 
1126           || strcmp (continued_file_name, real_s_name))
1127         {
1128           WARN ((0, 0, _("%s is not continued on this volume"),
1129                  quote (real_s_name)));
1130           return false;
1131         }
1132
1133       s = continued_file_size + continued_file_offset;
1134
1135       if (real_s_totsize != s || s < continued_file_offset)
1136         {
1137           char totsizebuf[UINTMAX_STRSIZE_BOUND];
1138           char s1buf[UINTMAX_STRSIZE_BOUND];
1139           char s2buf[UINTMAX_STRSIZE_BOUND];
1140
1141           WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1142                  quote (continued_file_name),
1143                  STRINGIFY_BIGINT (save_totsize, totsizebuf),
1144                  STRINGIFY_BIGINT (continued_file_size, s1buf),
1145                  STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1146           return false;
1147         }
1148       
1149       if (real_s_totsize - real_s_sizeleft != continued_file_offset)
1150         {
1151           WARN ((0, 0, _("This volume is out of sequence")));
1152           return false;
1153         }
1154     }
1155
1156   increase_volume_number ();
1157   return true;
1158 }
1159
1160 \f
1161 /* Check the LABEL block against the volume label, seen as a globbing
1162    pattern.  Return true if the pattern matches.  In case of failure,
1163    retry matching a volume sequence number before giving up in
1164    multi-volume mode.  */
1165 static bool
1166 check_label_pattern (union block *label)
1167 {
1168   char *string;
1169   bool result;
1170
1171   if (! memchr (label->header.name, '\0', sizeof label->header.name))
1172     return false;
1173
1174   if (fnmatch (volume_label_option, label->header.name, 0) == 0)
1175     return true;
1176
1177   if (!multi_volume_option)
1178     return false;
1179
1180   string = xmalloc (strlen (volume_label_option)
1181                     + sizeof VOLUME_LABEL_APPEND + 1);
1182   strcpy (string, volume_label_option);
1183   strcat (string, VOLUME_LABEL_APPEND);
1184   result = fnmatch (string, label->header.name, 0) == 0;
1185   free (string);
1186   return result;
1187 }
1188
1189 /* Check if the next block contains a volume label and if this matches
1190    the one given in the command line */
1191 static void
1192 match_volume_label (void)
1193 {
1194   union block *label = find_next_block ();
1195
1196   if (!label)
1197     FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1198                   quote (volume_label_option)));
1199   if (!check_label_pattern (label))
1200     FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1201                   quote_n (0, label->header.name),
1202                   quote_n (1, volume_label_option)));
1203 }
1204
1205 /* Mark the archive with volume label STR. */
1206 static void
1207 _write_volume_label (const char *str)
1208 {
1209   if (archive_format == POSIX_FORMAT)
1210     xheader_store ("GNU.volume.label", NULL, str);
1211   else
1212     {
1213       union block *label = find_next_block ();
1214       
1215       memset (label, 0, BLOCKSIZE);
1216
1217       strcpy (label->header.name, volume_label_option);
1218       assign_string (&current_stat_info.file_name,
1219                      label->header.name);
1220       current_stat_info.had_trailing_slash =
1221         strip_trailing_slashes (current_stat_info.file_name);
1222
1223       label->header.typeflag = GNUTYPE_VOLHDR;
1224       TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1225       finish_header (&current_stat_info, label, -1);
1226       set_next_block_after (label);
1227     }
1228 }
1229
1230 #define VOL_SUFFIX "Volume"
1231
1232 /* Add a volume label to a part of multi-volume archive */
1233 static void
1234 add_volume_label (void)
1235 {
1236   char buf[UINTMAX_STRSIZE_BOUND];
1237   char *p = STRINGIFY_BIGINT (volno, buf);
1238   char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1239                      + strlen (p) + 2);
1240   sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1241   _write_volume_label (s);
1242   free (s);
1243 }
1244
1245 static void
1246 add_chunk_header ()
1247 {
1248   if (archive_format == POSIX_FORMAT)
1249     {
1250       off_t block_ordinal;
1251       union block *blk;
1252       struct tar_stat_info st;
1253       static size_t real_s_part_no; /* FIXME */
1254
1255       real_s_part_no++;
1256       memset (&st, 0, sizeof st);
1257       st.orig_file_name = st.file_name = real_s_name;
1258       st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1259       st.stat.st_uid = getuid ();
1260       st.stat.st_gid = getgid ();
1261       st.orig_file_name = xheader_format_name (&st,
1262                                                "%d/GNUFileParts.%p/%f.%n",
1263                                                real_s_part_no);
1264       st.file_name = st.orig_file_name;
1265       st.archive_file_size = st.stat.st_size = real_s_sizeleft;
1266       
1267       block_ordinal = current_block_ordinal ();
1268       blk = start_header (&st);
1269       free (st.orig_file_name);
1270       if (!blk)
1271         abort (); /* FIXME */
1272       finish_header (&st, blk, block_ordinal);
1273     }
1274 }
1275
1276
1277 /* Add a volume label to the current archive */
1278 static void
1279 write_volume_label (void)
1280 {
1281   if (multi_volume_option)
1282     add_volume_label ();
1283   else
1284     _write_volume_label (volume_label_option);
1285 }
1286
1287 /* Write GNU multi-volume header */
1288 static void
1289 gnu_add_multi_volume_header (void)
1290 {
1291   int tmp;
1292   union block *block = find_next_block ();
1293   
1294   if (strlen (real_s_name) > NAME_FIELD_SIZE)
1295     WARN ((0, 0,
1296            _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1297            quotearg_colon (real_s_name)));
1298   
1299   memset (block, 0, BLOCKSIZE);
1300   
1301   /* FIXME: Michael P Urban writes: [a long name file] is being written
1302      when a new volume rolls around [...]  Looks like the wrong value is
1303      being preserved in real_s_name, though.  */
1304   
1305   strncpy (block->header.name, real_s_name, NAME_FIELD_SIZE);
1306   block->header.typeflag = GNUTYPE_MULTIVOL;
1307   
1308   OFF_TO_CHARS (real_s_sizeleft, block->header.size);
1309   OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
1310                 block->oldgnu_header.offset);
1311   
1312   tmp = verbose_option;
1313   verbose_option = 0;
1314   finish_header (&current_stat_info, block, -1);
1315   verbose_option = tmp;
1316   set_next_block_after (block);
1317 }
1318
1319 /* Add a multi volume header to the current archive. The exact header format
1320    depends on the archive format. */
1321 static void
1322 add_multi_volume_header (void)
1323 {
1324   if (archive_format == POSIX_FORMAT)
1325     {
1326       off_t d = real_s_totsize - real_s_sizeleft;
1327       xheader_store ("GNU.volume.filename", NULL, real_s_name);
1328       xheader_store ("GNU.volume.size", NULL, &real_s_sizeleft);
1329       xheader_store ("GNU.volume.offset", NULL, &d);
1330     }
1331   else
1332     gnu_add_multi_volume_header ();
1333 }
1334
1335 /* Synchronize multi-volume globals */
1336 static void
1337 multi_volume_sync ()
1338 {
1339   if (multi_volume_option)
1340     {
1341       if (save_name)
1342         {
1343           assign_string (&real_s_name,
1344                          safer_name_suffix (save_name, false,
1345                                             absolute_names_option));
1346           real_s_totsize = save_totsize;
1347           real_s_sizeleft = save_sizeleft;
1348         }
1349       else
1350         {
1351           assign_string (&real_s_name, 0);
1352           real_s_totsize = 0;
1353           real_s_sizeleft = 0;
1354         }
1355     }
1356 }
1357
1358 \f
1359 /* Low-level flush functions */
1360
1361 /* Simple flush read (no multi-volume or label extensions) */
1362 static void
1363 simple_flush_read (void)
1364 {
1365   size_t status;                /* result from system call */
1366
1367   if (checkpoint_option && !(++checkpoint % 10))
1368     /* TRANSLATORS: This is a ``checkpoint of read operation'',
1369        *not* ``Reading a checkpoint''.
1370        E.g. in Spanish ``Punto de comprobaci@'on de lectura'',
1371        *not* ``Leyendo un punto de comprobaci@'on'' */
1372     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
1373
1374   /* Clear the count of errors.  This only applies to a single call to
1375      flush_read.  */
1376
1377   read_error_count = 0;         /* clear error count */
1378
1379   if (write_archive_to_stdout && record_start_block != 0)
1380     {
1381       archive = STDOUT_FILENO;
1382       status = sys_write_archive_buffer ();
1383       archive = STDIN_FILENO;
1384       if (status != record_size)
1385         archive_write_error (status);
1386     }
1387   
1388   for (;;)
1389     {
1390       status = rmtread (archive, record_start->buffer, record_size);
1391       if (status == record_size)
1392         {
1393           records_read++;
1394           return;
1395         }
1396       if (status == SAFE_READ_ERROR)
1397         {
1398           archive_read_error ();
1399           continue;             /* try again */
1400         }
1401       break;
1402     }
1403   short_read (status);
1404 }
1405
1406 /* Simple flush write (no multi-volume or label extensions) */
1407 static void
1408 simple_flush_write (size_t level __attribute__((unused)))
1409 {
1410   ssize_t status;
1411
1412   status = _flush_write ();
1413   if (status != record_size)
1414     archive_write_error (status);
1415   else
1416     {
1417       records_written++;
1418       bytes_written += status;
1419     }
1420 }
1421
1422 \f
1423 /* GNU flush functions. These support multi-volume and archive labels in
1424    GNU and PAX archive formats. */
1425
1426 static void
1427 _gnu_flush_read (void)
1428 {
1429   size_t status;                /* result from system call */
1430
1431   if (checkpoint_option && !(++checkpoint % 10))
1432     /* TRANSLATORS: This is a ``checkpoint of read operation'',
1433        *not* ``Reading a checkpoint''.
1434        E.g. in Spanish ``Punto de comprobaci@'on de lectura'',
1435        *not* ``Leyendo un punto de comprobaci@'on'' */
1436     WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
1437
1438   /* Clear the count of errors.  This only applies to a single call to
1439      flush_read.  */
1440
1441   read_error_count = 0;         /* clear error count */
1442
1443   if (write_archive_to_stdout && record_start_block != 0)
1444     {
1445       archive = STDOUT_FILENO;
1446       status = sys_write_archive_buffer ();
1447       archive = STDIN_FILENO;
1448       if (status != record_size)
1449         archive_write_error (status);
1450     }
1451
1452   multi_volume_sync ();
1453
1454   for (;;)
1455     {
1456       status = rmtread (archive, record_start->buffer, record_size);
1457       if (status == record_size)
1458         {
1459           records_read++;
1460           return;
1461         }
1462
1463       /* The condition below used to include
1464               || (status > 0 && !read_full_records)
1465          This is incorrect since even if new_volume() succeeds, the
1466          subsequent call to rmtread will overwrite the chunk of data
1467          already read in the buffer, so the processing will fail */
1468       if ((status == 0
1469            || (status == SAFE_READ_ERROR && errno == ENOSPC))
1470           && multi_volume_option)
1471         {
1472           while (!try_new_volume ())
1473             ;
1474           return;
1475         }
1476       else if (status == SAFE_READ_ERROR)
1477         {
1478           archive_read_error ();
1479           continue; 
1480         }
1481       break;
1482     }
1483   short_read (status);
1484 }
1485
1486 static void
1487 gnu_flush_read (void)
1488 {
1489   flush_read_ptr = simple_flush_read; /* Avoid recursion */
1490   _gnu_flush_read ();
1491   flush_read_ptr = gnu_flush_read; 
1492 }
1493
1494 static void
1495 _gnu_flush_write (size_t buffer_level)
1496 {
1497   ssize_t status;
1498   union block *header;
1499   char *copy_ptr;
1500   size_t copy_size;
1501   size_t bufsize;
1502
1503   status = _flush_write ();
1504   if (status != record_size && !multi_volume_option)
1505     archive_write_error (status);
1506   else
1507     {
1508       records_written++;
1509       bytes_written += status;
1510     }
1511
1512   if (status == record_size)
1513     {
1514       multi_volume_sync ();
1515       return;
1516     }
1517
1518   /* In multi-volume mode. */
1519   /* ENXIO is for the UNIX PC.  */
1520   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1521     archive_write_error (status);
1522
1523   if (!new_volume (ACCESS_WRITE))
1524     return;
1525
1526   xheader_destroy (&extended_header);
1527   
1528   increase_volume_number ();
1529   if (totals_option)
1530     prev_written += bytes_written;
1531   bytes_written = 0;
1532
1533   copy_ptr = record_start->buffer + status;
1534   copy_size = buffer_level - status;
1535   /* Switch to the next buffer */
1536   record_index = !record_index;
1537   init_buffer ();
1538   
1539   if (volume_label_option)
1540     add_volume_label ();
1541
1542   if (real_s_name)
1543     add_multi_volume_header ();
1544
1545   write_extended (true, NULL, find_next_block ());
1546   if (real_s_name)
1547     add_chunk_header ();
1548   header = find_next_block ();
1549   bufsize = available_space_after (header);
1550   while (bufsize < copy_size)
1551     {
1552       memcpy (header->buffer, copy_ptr, bufsize);
1553       copy_ptr += bufsize;
1554       copy_size -= bufsize;
1555       set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
1556       header = find_next_block ();
1557       bufsize = available_space_after (header);
1558     }
1559   memcpy (header->buffer, copy_ptr, copy_size);
1560   memset (header->buffer + copy_size, 0, bufsize - copy_size);
1561   set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
1562   find_next_block ();
1563 }
1564
1565 static void
1566 gnu_flush_write (size_t buffer_level)
1567 {
1568   flush_write_ptr = simple_flush_write; /* Avoid recursion */
1569   _gnu_flush_write (buffer_level);
1570   flush_write_ptr = gnu_flush_write; 
1571 }
1572
1573 void
1574 flush_read ()
1575 {
1576   flush_read_ptr ();
1577 }
1578
1579 void
1580 flush_write ()
1581 {
1582   flush_write_ptr (record_size);
1583 }    
1584
1585 void
1586 open_archive (enum access_mode wanted_access)
1587 {
1588   flush_read_ptr = gnu_flush_read;
1589   flush_write_ptr = gnu_flush_write;
1590
1591   _open_archive (wanted_access);
1592   switch (wanted_access)
1593     {
1594     case ACCESS_READ:
1595       if (volume_label_option)
1596         match_volume_label ();
1597       break;
1598
1599     case ACCESS_WRITE:
1600       records_written = 0;
1601       if (volume_label_option)
1602         write_volume_label ();
1603       break;
1604     }
1605 }
1606