]> git.cworth.org Git - tar/blob - src/buffer.c
Imported Upstream version 1.24
[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, 2006, 2007, 2008, 2009, 2010 Free Software
5    Foundation, Inc.
6
7    Written by John Gilmore, on 1985-08-25.
8
9    This program is free software; you can redistribute it and/or modify it
10    under the terms of the GNU General Public License as published by the
11    Free Software Foundation; either version 3, or (at your option) any later
12    version.
13
14    This program is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
17    Public License for more details.
18
19    You should have received a copy of the GNU General Public License along
20    with this program; if not, write to the Free Software Foundation, Inc.,
21    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
22
23 #include <system.h>
24 #include <system-ioctl.h>
25
26 #include <signal.h>
27
28 #include <closeout.h>
29 #include <fnmatch.h>
30 #include <human.h>
31 #include <quotearg.h>
32
33 #include "common.h"
34 #include <rmt.h>
35
36 /* Number of retries before giving up on read.  */
37 #define READ_ERROR_MAX 10
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 union block *record_buffer_aligned[2];
45 static int record_index;
46
47 /* FIXME: The following variables should ideally be static to this
48    module.  However, this cannot be done yet.  The cleanup continues!  */
49
50 union block *record_start;      /* start of record of archive */
51 union block *record_end;        /* last+1 block of archive record */
52 union block *current_block;     /* current block of archive */
53 enum access_mode access_mode;   /* how do we handle the archive */
54 off_t records_read;             /* number of records read from this archive */
55 off_t records_written;          /* likewise, for records written */
56 extern off_t records_skipped;   /* number of records skipped at the start
57                                    of the archive, defined in delete.c */
58
59 static off_t record_start_block; /* block ordinal at record_start */
60
61 /* Where we write list messages (not errors, not interactions) to.  */
62 FILE *stdlis;
63
64 static void backspace_output (void);
65
66 /* PID of child program, if compress_option or remote archive access.  */
67 static pid_t child_pid;
68
69 /* Error recovery stuff  */
70 static int read_error_count;
71
72 /* Have we hit EOF yet?  */
73 static bool hit_eof;
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    FIXME: Either eliminate it or move it to common.h.
81 */
82 extern bool time_to_start_writing;
83
84 bool write_archive_to_stdout;
85
86 void (*flush_write_ptr) (size_t);
87 void (*flush_read_ptr) (void);
88
89 \f
90 char *volume_label;
91 char *continued_file_name;
92 uintmax_t continued_file_size;
93 uintmax_t continued_file_offset;
94
95 \f
96 static int volno = 1;           /* which volume of a multi-volume tape we're
97                                    on */
98 static int global_volno = 1;    /* volume number to print in external
99                                    messages */
100
101 bool write_archive_to_stdout;
102
103 \f
104 /* Multi-volume tracking support */
105
106 /* When creating a multi-volume archive, each `bufmap' represents
107    a member stored (perhaps partly) in the current record buffer.
108    After flushing the record to the output media, all bufmaps that
109    represent fully written members are removed from the list, then
110    the sizeleft and start numbers in the remaining bufmaps are updated.
111
112    When reading from a multi-volume archive, the list degrades to a
113    single element, which keeps information about the member currently
114    being read.
115 */
116
117 struct bufmap
118 {
119   struct bufmap *next;          /* Pointer to the next map entry */
120   size_t start;                 /* Offset of the first data block */
121   char *file_name;              /* Name of the stored file */
122   off_t sizetotal;              /* Size of the stored file */
123   off_t sizeleft;               /* Size left to read/write */
124 };
125 static struct bufmap *bufmap_head, *bufmap_tail;
126
127 /* This variable, when set, inhibits updating the bufmap chain after
128    a write.  This is necessary when writing extended POSIX headers. */
129 static int inhibit_map;
130
131 void
132 mv_begin_write (const char *file_name, off_t totsize, off_t sizeleft)
133 {
134   if (multi_volume_option)
135     {
136       struct bufmap *bp = xmalloc (sizeof bp[0]);
137       if (bufmap_tail)
138         bufmap_tail->next = bp;
139       else
140         bufmap_head = bp;
141       bufmap_tail = bp;
142
143       bp->next = NULL;
144       bp->start = current_block - record_start;
145       bp->file_name = xstrdup (file_name);
146       bp->sizetotal = totsize;
147       bp->sizeleft = sizeleft;
148     }
149 }
150
151 static struct bufmap *
152 bufmap_locate (size_t off)
153 {
154   struct bufmap *map;
155
156   for (map = bufmap_head; map; map = map->next)
157     {
158       if (!map->next
159           || off < map->next->start * BLOCKSIZE)
160         break;
161     }
162   return map;
163 }
164
165 static void
166 bufmap_free (struct bufmap *mark)
167 {
168   struct bufmap *map;
169   for (map = bufmap_head; map && map != mark; )
170     {
171       struct bufmap *next = map->next;
172       free (map->file_name);
173       free (map);
174       map = next;
175     }
176   bufmap_head = map;
177   if (!bufmap_head)
178     bufmap_tail = bufmap_head;
179 }
180
181 static void
182 bufmap_reset (struct bufmap *map, ssize_t fixup)
183 {
184   bufmap_free (map);
185   if (map)
186     {
187       for (; map; map = map->next)
188         map->start += fixup;
189     }
190 }
191
192 \f
193 static struct tar_stat_info dummy;
194
195 void
196 buffer_write_global_xheader ()
197 {
198   xheader_write_global (&dummy.xhdr);
199 }
200
201 void
202 mv_begin_read (struct tar_stat_info *st)
203 {
204   mv_begin_write (st->orig_file_name, st->stat.st_size, st->stat.st_size);
205 }
206
207 void
208 mv_end ()
209 {
210   if (multi_volume_option)
211     bufmap_free (NULL);
212 }
213
214 void
215 mv_size_left (off_t size)
216 {
217   if (bufmap_head)
218     bufmap_head->sizeleft = size;
219 }
220
221 \f
222 /* Functions.  */
223
224 void
225 clear_read_error_count (void)
226 {
227   read_error_count = 0;
228 }
229
230 \f
231 /* Time-related functions */
232
233 double duration;
234
235 void
236 set_start_time ()
237 {
238   gettime (&start_time);
239   volume_start_time = start_time;
240   last_stat_time = start_time;
241 }
242
243 static void
244 set_volume_start_time (void)
245 {
246   gettime (&volume_start_time);
247   last_stat_time = volume_start_time;
248 }
249
250 void
251 compute_duration ()
252 {
253   struct timespec now;
254   gettime (&now);
255   duration += ((now.tv_sec - last_stat_time.tv_sec)
256                + (now.tv_nsec - last_stat_time.tv_nsec) / 1e9);
257   gettime (&last_stat_time);
258 }
259
260 \f
261 /* Compression detection */
262
263 enum compress_type {
264   ct_tar,              /* Plain tar file */
265   ct_none,             /* Unknown compression type */
266   ct_compress,
267   ct_gzip,
268   ct_bzip2,
269   ct_lzip,
270   ct_lzma,
271   ct_lzop,
272   ct_xz
273 };
274
275 struct zip_magic
276 {
277   enum compress_type type;
278   size_t length;
279   char const *magic;
280   char const *program;
281   char const *option;
282 };
283
284 static struct zip_magic const magic[] = {
285   { ct_tar },
286   { ct_none, },
287   { ct_compress, 2, "\037\235",  COMPRESS_PROGRAM, "-Z" },
288   { ct_gzip,     2, "\037\213",  GZIP_PROGRAM,     "-z"  },
289   { ct_bzip2,    3, "BZh",       BZIP2_PROGRAM,    "-j" },
290   { ct_lzip,     4, "LZIP",      LZIP_PROGRAM,     "--lzip" },
291   { ct_lzma,     6, "\xFFLZMA",  LZMA_PROGRAM,     "--lzma" },
292   { ct_lzop,     4, "\211LZO",   LZOP_PROGRAM,     "--lzop" },
293   { ct_xz,       6, "\xFD" "7zXZ",  XZ_PROGRAM,       "-J" },
294 };
295
296 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
297
298 #define compress_option(t) magic[t].option
299 #define compress_program(t) magic[t].program
300
301 /* Check if the file ARCHIVE is a compressed archive. */
302 static enum compress_type
303 check_compressed_archive (bool *pshort)
304 {
305   struct zip_magic const *p;
306   bool sfr;
307   bool temp;
308
309   if (!pshort)
310     pshort = &temp;
311
312   /* Prepare global data needed for find_next_block: */
313   record_end = record_start; /* set up for 1st record = # 0 */
314   sfr = read_full_records;
315   read_full_records = true; /* Suppress fatal error on reading a partial
316                                record */
317   *pshort = find_next_block () == 0;
318
319   /* Restore global values */
320   read_full_records = sfr;
321
322   if (tar_checksum (record_start, true) == HEADER_SUCCESS)
323     /* Probably a valid header */
324     return ct_tar;
325
326   for (p = magic + 2; p < magic + NMAGIC; p++)
327     if (memcmp (record_start->buffer, p->magic, p->length) == 0)
328       return p->type;
329
330   return ct_none;
331 }
332
333 /* Guess if the archive is seekable. */
334 static void
335 guess_seekable_archive (void)
336 {
337   struct stat st;
338
339   if (subcommand_option == DELETE_SUBCOMMAND)
340     {
341       /* The current code in delete.c is based on the assumption that
342          skip_member() reads all data from the archive. So, we should
343          make sure it won't use seeks. On the other hand, the same code
344          depends on the ability to backspace a record in the archive,
345          so setting seekable_archive to false is technically incorrect.
346          However, it is tested only in skip_member(), so it's not a
347          problem. */
348       seekable_archive = false;
349     }
350
351   if (seek_option != -1)
352     {
353       seekable_archive = !!seek_option;
354       return;
355     }
356
357   if (!multi_volume_option && !use_compress_program_option
358       && fstat (archive, &st) == 0)
359     seekable_archive = S_ISREG (st.st_mode);
360   else
361     seekable_archive = false;
362 }
363
364 /* Open an archive named archive_name_array[0]. Detect if it is
365    a compressed archive of known type and use corresponding decompression
366    program if so */
367 static int
368 open_compressed_archive (void)
369 {
370   archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
371                      MODE_RW, rsh_command_option);
372   if (archive == -1)
373     return archive;
374
375   if (!multi_volume_option)
376     {
377       if (!use_compress_program_option)
378         {
379           bool shortfile;
380           enum compress_type type = check_compressed_archive (&shortfile);
381
382           switch (type)
383             {
384             case ct_tar:
385               if (shortfile)
386                 ERROR ((0, 0, _("This does not look like a tar archive")));
387               return archive;
388
389             case ct_none:
390               if (shortfile)
391                 ERROR ((0, 0, _("This does not look like a tar archive")));
392               set_compression_program_by_suffix (archive_name_array[0], NULL);
393               if (!use_compress_program_option)
394                 return archive;
395               break;
396
397             default:
398               use_compress_program_option = compress_program (type);
399               break;
400             }
401         }
402
403       /* FD is not needed any more */
404       rmtclose (archive);
405
406       hit_eof = false; /* It might have been set by find_next_block in
407                           check_compressed_archive */
408
409       /* Open compressed archive */
410       child_pid = sys_child_open_for_uncompress ();
411       read_full_records = true;
412     }
413
414   records_read = 0;
415   record_end = record_start; /* set up for 1st record = # 0 */
416
417   return archive;
418 }
419 \f
420
421 static void
422 print_stats (FILE *fp, const char *text, tarlong numbytes)
423 {
424   char bytes[sizeof (tarlong) * CHAR_BIT];
425   char abbr[LONGEST_HUMAN_READABLE + 1];
426   char rate[LONGEST_HUMAN_READABLE + 1];
427
428   int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
429
430   sprintf (bytes, TARLONG_FORMAT, numbytes);
431
432   fprintf (fp, "%s: %s (%s, %s/s)\n",
433            text, bytes,
434            human_readable (numbytes, abbr, human_opts, 1, 1),
435            (0 < duration && numbytes / duration < (uintmax_t) -1
436             ? human_readable (numbytes / duration, rate, human_opts, 1, 1)
437             : "?"));
438 }
439
440 void
441 print_total_stats ()
442 {
443   switch (subcommand_option)
444     {
445     case CREATE_SUBCOMMAND:
446     case CAT_SUBCOMMAND:
447     case UPDATE_SUBCOMMAND:
448     case APPEND_SUBCOMMAND:
449       /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*".  */
450       print_stats (stderr, _("Total bytes written"),
451                    prev_written + bytes_written);
452       break;
453
454     case DELETE_SUBCOMMAND:
455       {
456         char buf[UINTMAX_STRSIZE_BOUND];
457         print_stats (stderr, _("Total bytes read"),
458                      records_read * record_size);
459         print_stats (stderr, _("Total bytes written"),
460                      prev_written + bytes_written);
461         fprintf (stderr, _("Total bytes deleted: %s\n"),
462                  STRINGIFY_BIGINT ((records_read - records_skipped)
463                                     * record_size
464                                    - (prev_written + bytes_written), buf));
465       }
466       break;
467
468     case EXTRACT_SUBCOMMAND:
469     case LIST_SUBCOMMAND:
470     case DIFF_SUBCOMMAND:
471       print_stats (stderr, _("Total bytes read"),
472                    records_read * record_size);
473       break;
474
475     default:
476       abort ();
477     }
478 }
479
480 /* Compute and return the block ordinal at current_block.  */
481 off_t
482 current_block_ordinal (void)
483 {
484   return record_start_block + (current_block - record_start);
485 }
486
487 /* If the EOF flag is set, reset it, as well as current_block, etc.  */
488 void
489 reset_eof (void)
490 {
491   if (hit_eof)
492     {
493       hit_eof = false;
494       current_block = record_start;
495       record_end = record_start + blocking_factor;
496       access_mode = ACCESS_WRITE;
497     }
498 }
499
500 /* Return the location of the next available input or output block.
501    Return zero for EOF.  Once we have returned zero, we just keep returning
502    it, to avoid accidentally going on to the next file on the tape.  */
503 union block *
504 find_next_block (void)
505 {
506   if (current_block == record_end)
507     {
508       if (hit_eof)
509         return 0;
510       flush_archive ();
511       if (current_block == record_end)
512         {
513           hit_eof = true;
514           return 0;
515         }
516     }
517   return current_block;
518 }
519
520 /* Indicate that we have used all blocks up thru BLOCK. */
521 void
522 set_next_block_after (union block *block)
523 {
524   while (block >= current_block)
525     current_block++;
526
527   /* Do *not* flush the archive here.  If we do, the same argument to
528      set_next_block_after could mean the next block (if the input record
529      is exactly one block long), which is not what is intended.  */
530
531   if (current_block > record_end)
532     abort ();
533 }
534
535 /* Return the number of bytes comprising the space between POINTER
536    through the end of the current buffer of blocks.  This space is
537    available for filling with data, or taking data from.  POINTER is
538    usually (but not always) the result of previous find_next_block call.  */
539 size_t
540 available_space_after (union block *pointer)
541 {
542   return record_end->buffer - pointer->buffer;
543 }
544
545 /* Close file having descriptor FD, and abort if close unsuccessful.  */
546 void
547 xclose (int fd)
548 {
549   if (close (fd) != 0)
550     close_error (_("(pipe)"));
551 }
552
553 static void
554 init_buffer (void)
555 {
556   if (! record_buffer_aligned[record_index])
557     record_buffer_aligned[record_index] =
558       page_aligned_alloc (&record_buffer[record_index], record_size);
559
560   record_start = record_buffer_aligned[record_index];
561   current_block = record_start;
562   record_end = record_start + blocking_factor;
563 }
564
565 /* Open an archive file.  The argument specifies whether we are
566    reading or writing, or both.  */
567 static void
568 _open_archive (enum access_mode wanted_access)
569 {
570   int backed_up_flag = 0;
571
572   if (record_size == 0)
573     FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
574
575   if (archive_names == 0)
576     FATAL_ERROR ((0, 0, _("No archive name given")));
577
578   tar_stat_destroy (&current_stat_info);
579
580   record_index = 0;
581   init_buffer ();
582
583   /* When updating the archive, we start with reading.  */
584   access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
585
586   read_full_records = read_full_records_option;
587
588   records_read = 0;
589
590   if (use_compress_program_option)
591     {
592       switch (wanted_access)
593         {
594         case ACCESS_READ:
595           child_pid = sys_child_open_for_uncompress ();
596           read_full_records = true;
597           record_end = record_start; /* set up for 1st record = # 0 */
598           break;
599
600         case ACCESS_WRITE:
601           child_pid = sys_child_open_for_compress ();
602           break;
603
604         case ACCESS_UPDATE:
605           abort (); /* Should not happen */
606           break;
607         }
608
609       if (!index_file_name
610           && wanted_access == ACCESS_WRITE
611           && strcmp (archive_name_array[0], "-") == 0)
612         stdlis = stderr;
613     }
614   else if (strcmp (archive_name_array[0], "-") == 0)
615     {
616       read_full_records = true; /* could be a pipe, be safe */
617       if (verify_option)
618         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
619
620       switch (wanted_access)
621         {
622         case ACCESS_READ:
623           {
624             bool shortfile;
625             enum compress_type type;
626
627             archive = STDIN_FILENO;
628
629             type = check_compressed_archive (&shortfile);
630             if (type != ct_tar && type != ct_none)
631               FATAL_ERROR ((0, 0,
632                             _("Archive is compressed. Use %s option"),
633                             compress_option (type)));
634             if (shortfile)
635               ERROR ((0, 0, _("This does not look like a tar archive")));
636           }
637           break;
638
639         case ACCESS_WRITE:
640           archive = STDOUT_FILENO;
641           if (!index_file_name)
642             stdlis = stderr;
643           break;
644
645         case ACCESS_UPDATE:
646           archive = STDIN_FILENO;
647           write_archive_to_stdout = true;
648           record_end = record_start; /* set up for 1st record = # 0 */
649           if (!index_file_name)
650             stdlis = stderr;
651           break;
652         }
653     }
654   else if (verify_option)
655     archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
656                        MODE_RW, rsh_command_option);
657   else
658     switch (wanted_access)
659       {
660       case ACCESS_READ:
661         archive = open_compressed_archive ();
662         if (archive >= 0)
663           guess_seekable_archive ();
664         break;
665
666       case ACCESS_WRITE:
667         if (backup_option)
668           {
669             maybe_backup_file (archive_name_array[0], 1);
670             backed_up_flag = 1;
671           }
672         archive = rmtcreat (archive_name_array[0], MODE_RW,
673                             rsh_command_option);
674         break;
675
676       case ACCESS_UPDATE:
677         archive = rmtopen (archive_name_array[0],
678                            O_RDWR | O_CREAT | O_BINARY,
679                            MODE_RW, rsh_command_option);
680
681         switch (check_compressed_archive (NULL))
682           {
683           case ct_none:
684           case ct_tar:
685             break;
686
687           default:
688             FATAL_ERROR ((0, 0,
689                           _("Cannot update compressed archives")));
690           }
691         break;
692       }
693
694   if (archive < 0
695       || (! _isrmt (archive) && !sys_get_archive_stat ()))
696     {
697       int saved_errno = errno;
698
699       if (backed_up_flag)
700         undo_last_backup ();
701       errno = saved_errno;
702       open_fatal (archive_name_array[0]);
703     }
704
705   sys_detect_dev_null_output ();
706   sys_save_archive_dev_ino ();
707   SET_BINARY_MODE (archive);
708
709   switch (wanted_access)
710     {
711     case ACCESS_READ:
712       find_next_block ();       /* read it in, check for EOF */
713       break;
714
715     case ACCESS_UPDATE:
716     case ACCESS_WRITE:
717       records_written = 0;
718       break;
719     }
720 }
721
722 /* Perform a write to flush the buffer.  */
723 static ssize_t
724 _flush_write (void)
725 {
726   ssize_t status;
727
728   checkpoint_run (true);
729   if (tape_length_option && tape_length_option <= bytes_written)
730     {
731       errno = ENOSPC;
732       status = 0;
733     }
734   else if (dev_null_output)
735     status = record_size;
736   else
737     status = sys_write_archive_buffer ();
738
739   if (status && multi_volume_option && !inhibit_map)
740     {
741       struct bufmap *map = bufmap_locate (status);
742       if (map)
743         {
744           size_t delta = status - map->start * BLOCKSIZE;
745           if (delta > map->sizeleft)
746             delta = map->sizeleft;
747           map->sizeleft -= delta;
748           if (map->sizeleft == 0)
749             map = map->next;
750           bufmap_reset (map, map ? (- map->start) : 0);
751         }
752     }
753   return status;
754 }
755
756 /* Handle write errors on the archive.  Write errors are always fatal.
757    Hitting the end of a volume does not cause a write error unless the
758    write was the first record of the volume.  */
759 void
760 archive_write_error (ssize_t status)
761 {
762   /* It might be useful to know how much was written before the error
763      occurred.  */
764   if (totals_option)
765     {
766       int e = errno;
767       print_total_stats ();
768       errno = e;
769     }
770
771   write_fatal_details (*archive_name_cursor, status, record_size);
772 }
773
774 /* Handle read errors on the archive.  If the read should be retried,
775    return to the caller.  */
776 void
777 archive_read_error (void)
778 {
779   read_error (*archive_name_cursor);
780
781   if (record_start_block == 0)
782     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
783
784   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
785      then give up on reading the archive.  */
786
787   if (read_error_count++ > READ_ERROR_MAX)
788     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
789   return;
790 }
791
792 static bool
793 archive_is_dev (void)
794 {
795   struct stat st;
796
797   if (fstat (archive, &st))
798     {
799       stat_diag (*archive_name_cursor);
800       return false;
801     }
802   return S_ISBLK (st.st_mode) || S_ISCHR (st.st_mode);
803 }
804
805 static void
806 short_read (size_t status)
807 {
808   size_t left;                  /* bytes left */
809   char *more;                   /* pointer to next byte to read */
810
811   more = record_start->buffer + status;
812   left = record_size - status;
813
814   if (left && left % BLOCKSIZE == 0
815       && verbose_option
816       && record_start_block == 0 && status != 0
817       && archive_is_dev ())
818     {
819       unsigned long rsize = status / BLOCKSIZE;
820       WARN ((0, 0,
821              ngettext ("Record size = %lu block",
822                        "Record size = %lu blocks",
823                        rsize),
824              rsize));
825     }
826
827   while (left % BLOCKSIZE != 0
828          || (left && status && read_full_records))
829     {
830       if (status)
831         while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
832           archive_read_error ();
833
834       if (status == 0)
835         break;
836
837       if (! read_full_records)
838         {
839           unsigned long rest = record_size - left;
840
841           FATAL_ERROR ((0, 0,
842                         ngettext ("Unaligned block (%lu byte) in archive",
843                                   "Unaligned block (%lu bytes) in archive",
844                                   rest),
845                         rest));
846         }
847
848       left -= status;
849       more += status;
850     }
851
852   record_end = record_start + (record_size - left) / BLOCKSIZE;
853   records_read++;
854 }
855
856 /*  Flush the current buffer to/from the archive.  */
857 void
858 flush_archive (void)
859 {
860   size_t buffer_level = current_block->buffer - record_start->buffer;
861   record_start_block += record_end - record_start;
862   current_block = record_start;
863   record_end = record_start + blocking_factor;
864
865   if (access_mode == ACCESS_READ && time_to_start_writing)
866     {
867       access_mode = ACCESS_WRITE;
868       time_to_start_writing = false;
869       backspace_output ();
870     }
871
872   switch (access_mode)
873     {
874     case ACCESS_READ:
875       flush_read ();
876       break;
877
878     case ACCESS_WRITE:
879       flush_write_ptr (buffer_level);
880       break;
881
882     case ACCESS_UPDATE:
883       abort ();
884     }
885 }
886
887 /* Backspace the archive descriptor by one record worth.  If it's a
888    tape, MTIOCTOP will work.  If it's something else, try to seek on
889    it.  If we can't seek, we lose!  */
890 static void
891 backspace_output (void)
892 {
893 #ifdef MTIOCTOP
894   {
895     struct mtop operation;
896
897     operation.mt_op = MTBSR;
898     operation.mt_count = 1;
899     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
900       return;
901     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
902       return;
903   }
904 #endif
905
906   {
907     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
908
909     /* Seek back to the beginning of this record and start writing there.  */
910
911     position -= record_size;
912     if (position < 0)
913       position = 0;
914     if (rmtlseek (archive, position, SEEK_SET) != position)
915       {
916         /* Lseek failed.  Try a different method.  */
917
918         WARN ((0, 0,
919                _("Cannot backspace archive file; it may be unreadable without -i")));
920
921         /* Replace the first part of the record with NULs.  */
922
923         if (record_start->buffer != output_start)
924           memset (record_start->buffer, 0,
925                   output_start - record_start->buffer);
926       }
927   }
928 }
929
930 off_t
931 seek_archive (off_t size)
932 {
933   off_t start = current_block_ordinal ();
934   off_t offset;
935   off_t nrec, nblk;
936   off_t skipped = (blocking_factor - (current_block - record_start))
937                   * BLOCKSIZE;
938
939   if (size <= skipped)
940     return 0;
941
942   /* Compute number of records to skip */
943   nrec = (size - skipped) / record_size;
944   if (nrec == 0)
945     return 0;
946   offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
947   if (offset < 0)
948     return offset;
949
950   if (offset % record_size)
951     FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
952
953   /* Convert to number of records */
954   offset /= BLOCKSIZE;
955   /* Compute number of skipped blocks */
956   nblk = offset - start;
957
958   /* Update buffering info */
959   records_read += nblk / blocking_factor;
960   record_start_block = offset - blocking_factor;
961   current_block = record_end;
962
963   return nblk;
964 }
965
966 /* Close the archive file.  */
967 void
968 close_archive (void)
969 {
970   if (time_to_start_writing || access_mode == ACCESS_WRITE)
971     {
972       flush_archive ();
973       if (current_block > record_start)
974         flush_archive ();
975     }
976
977   compute_duration ();
978   if (verify_option)
979     verify_volume ();
980
981   if (rmtclose (archive) != 0)
982     close_error (*archive_name_cursor);
983
984   sys_wait_for_child (child_pid, hit_eof);
985
986   tar_stat_destroy (&current_stat_info);
987   free (record_buffer[0]);
988   free (record_buffer[1]);
989   bufmap_free (NULL);
990 }
991
992 /* Called to initialize the global volume number.  */
993 void
994 init_volume_number (void)
995 {
996   FILE *file = fopen (volno_file_option, "r");
997
998   if (file)
999     {
1000       if (fscanf (file, "%d", &global_volno) != 1
1001           || global_volno < 0)
1002         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1003                       quotearg_colon (volno_file_option)));
1004       if (ferror (file))
1005         read_error (volno_file_option);
1006       if (fclose (file) != 0)
1007         close_error (volno_file_option);
1008     }
1009   else if (errno != ENOENT)
1010     open_error (volno_file_option);
1011 }
1012
1013 /* Called to write out the closing global volume number.  */
1014 void
1015 closeout_volume_number (void)
1016 {
1017   FILE *file = fopen (volno_file_option, "w");
1018
1019   if (file)
1020     {
1021       fprintf (file, "%d\n", global_volno);
1022       if (ferror (file))
1023         write_error (volno_file_option);
1024       if (fclose (file) != 0)
1025         close_error (volno_file_option);
1026     }
1027   else
1028     open_error (volno_file_option);
1029 }
1030
1031 \f
1032 static void
1033 increase_volume_number (void)
1034 {
1035   global_volno++;
1036   if (global_volno < 0)
1037     FATAL_ERROR ((0, 0, _("Volume number overflow")));
1038   volno++;
1039 }
1040
1041 static void
1042 change_tape_menu (FILE *read_file)
1043 {
1044   char *input_buffer = NULL;
1045   size_t size = 0;
1046   bool stop = false;
1047
1048   while (!stop)
1049     {
1050       fputc ('\007', stderr);
1051       fprintf (stderr,
1052                _("Prepare volume #%d for %s and hit return: "),
1053                global_volno + 1, quote (*archive_name_cursor));
1054       fflush (stderr);
1055
1056       if (getline (&input_buffer, &size, read_file) <= 0)
1057         {
1058           WARN ((0, 0, _("EOF where user reply was expected")));
1059
1060           if (subcommand_option != EXTRACT_SUBCOMMAND
1061               && subcommand_option != LIST_SUBCOMMAND
1062               && subcommand_option != DIFF_SUBCOMMAND)
1063             WARN ((0, 0, _("WARNING: Archive is incomplete")));
1064
1065           fatal_exit ();
1066         }
1067
1068       if (input_buffer[0] == '\n'
1069           || input_buffer[0] == 'y'
1070           || input_buffer[0] == 'Y')
1071         break;
1072
1073       switch (input_buffer[0])
1074         {
1075         case '?':
1076           {
1077             fprintf (stderr, _("\
1078  n name        Give a new file name for the next (and subsequent) volume(s)\n\
1079  q             Abort tar\n\
1080  y or newline  Continue operation\n"));
1081             if (!restrict_option)
1082               fprintf (stderr, _(" !             Spawn a subshell\n"));
1083             fprintf (stderr, _(" ?             Print this list\n"));
1084           }
1085           break;
1086
1087         case 'q':
1088           /* Quit.  */
1089
1090           WARN ((0, 0, _("No new volume; exiting.\n")));
1091
1092           if (subcommand_option != EXTRACT_SUBCOMMAND
1093               && subcommand_option != LIST_SUBCOMMAND
1094               && subcommand_option != DIFF_SUBCOMMAND)
1095             WARN ((0, 0, _("WARNING: Archive is incomplete")));
1096
1097           fatal_exit ();
1098
1099         case 'n':
1100           /* Get new file name.  */
1101
1102           {
1103             char *name;
1104             char *cursor;
1105
1106             for (name = input_buffer + 1;
1107                  *name == ' ' || *name == '\t';
1108                  name++)
1109               ;
1110
1111             for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1112               ;
1113             *cursor = '\0';
1114
1115             if (name[0])
1116               {
1117                 /* FIXME: the following allocation is never reclaimed.  */
1118                 *archive_name_cursor = xstrdup (name);
1119                 stop = true;
1120               }
1121             else
1122               fprintf (stderr, "%s",
1123                        _("File name not specified. Try again.\n"));
1124           }
1125           break;
1126
1127         case '!':
1128           if (!restrict_option)
1129             {
1130               sys_spawn_shell ();
1131               break;
1132             }
1133           /* FALL THROUGH */
1134
1135         default:
1136           fprintf (stderr, _("Invalid input. Type ? for help.\n"));
1137         }
1138     }
1139   free (input_buffer);
1140 }
1141
1142 /* We've hit the end of the old volume.  Close it and open the next one.
1143    Return nonzero on success.
1144 */
1145 static bool
1146 new_volume (enum access_mode mode)
1147 {
1148   static FILE *read_file;
1149   static int looped;
1150   int prompt;
1151
1152   if (!read_file && !info_script_option)
1153     /* FIXME: if fopen is used, it will never be closed.  */
1154     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1155
1156   if (now_verifying)
1157     return false;
1158   if (verify_option)
1159     verify_volume ();
1160
1161   assign_string (&volume_label, NULL);
1162   assign_string (&continued_file_name, NULL);
1163   continued_file_size = continued_file_offset = 0;
1164   current_block = record_start;
1165
1166   if (rmtclose (archive) != 0)
1167     close_error (*archive_name_cursor);
1168
1169   archive_name_cursor++;
1170   if (archive_name_cursor == archive_name_array + archive_names)
1171     {
1172       archive_name_cursor = archive_name_array;
1173       looped = 1;
1174     }
1175   prompt = looped;
1176
1177  tryagain:
1178   if (prompt)
1179     {
1180       /* We have to prompt from now on.  */
1181
1182       if (info_script_option)
1183         {
1184           if (volno_file_option)
1185             closeout_volume_number ();
1186           if (sys_exec_info_script (archive_name_cursor, global_volno+1))
1187             FATAL_ERROR ((0, 0, _("%s command failed"),
1188                           quote (info_script_option)));
1189         }
1190       else
1191         change_tape_menu (read_file);
1192     }
1193
1194   if (strcmp (archive_name_cursor[0], "-") == 0)
1195     {
1196       read_full_records = true;
1197       archive = STDIN_FILENO;
1198     }
1199   else if (verify_option)
1200     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1201                        rsh_command_option);
1202   else
1203     switch (mode)
1204       {
1205       case ACCESS_READ:
1206         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1207                            rsh_command_option);
1208         guess_seekable_archive ();
1209         break;
1210
1211       case ACCESS_WRITE:
1212         if (backup_option)
1213           maybe_backup_file (*archive_name_cursor, 1);
1214         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1215                             rsh_command_option);
1216         break;
1217
1218       case ACCESS_UPDATE:
1219         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1220                            rsh_command_option);
1221         break;
1222       }
1223
1224   if (archive < 0)
1225     {
1226       open_warn (*archive_name_cursor);
1227       if (!verify_option && mode == ACCESS_WRITE && backup_option)
1228         undo_last_backup ();
1229       prompt = 1;
1230       goto tryagain;
1231     }
1232
1233   SET_BINARY_MODE (archive);
1234
1235   return true;
1236 }
1237
1238 static bool
1239 read_header0 (struct tar_stat_info *info)
1240 {
1241   enum read_header rc;
1242
1243   tar_stat_init (info);
1244   rc = read_header (&current_header, info, read_header_auto);
1245   if (rc == HEADER_SUCCESS)
1246     {
1247       set_next_block_after (current_header);
1248       return true;
1249     }
1250   ERROR ((0, 0, _("This does not look like a tar archive")));
1251   return false;
1252 }
1253
1254 static bool
1255 try_new_volume (void)
1256 {
1257   size_t status;
1258   union block *header;
1259   enum access_mode acc;
1260
1261   switch (subcommand_option)
1262     {
1263     case APPEND_SUBCOMMAND:
1264     case CAT_SUBCOMMAND:
1265     case UPDATE_SUBCOMMAND:
1266       acc = ACCESS_UPDATE;
1267       break;
1268
1269     default:
1270       acc = ACCESS_READ;
1271       break;
1272     }
1273
1274   if (!new_volume (acc))
1275     return true;
1276
1277   while ((status = rmtread (archive, record_start->buffer, record_size))
1278          == SAFE_READ_ERROR)
1279     archive_read_error ();
1280
1281   if (status != record_size)
1282     short_read (status);
1283
1284   header = find_next_block ();
1285   if (!header)
1286     return false;
1287
1288   switch (header->header.typeflag)
1289     {
1290     case XGLTYPE:
1291       {
1292         tar_stat_init (&dummy);
1293         if (read_header (&header, &dummy, read_header_x_global)
1294             != HEADER_SUCCESS_EXTENDED)
1295           {
1296             ERROR ((0, 0, _("This does not look like a tar archive")));
1297             return false;
1298           }
1299
1300         xheader_decode (&dummy); /* decodes values from the global header */
1301         tar_stat_destroy (&dummy);
1302
1303         /* The initial global header must be immediately followed by
1304            an extended PAX header for the first member in this volume.
1305            However, in some cases tar may split volumes in the middle
1306            of a PAX header. This is incorrect, and should be fixed
1307            in the future versions. In the meantime we must be
1308            prepared to correctly list and extract such archives.
1309
1310            If this happens, the following call to read_header returns
1311            HEADER_FAILURE, which is ignored.
1312
1313            See also tests/multiv07.at */
1314
1315         switch (read_header (&header, &dummy, read_header_auto))
1316           {
1317           case HEADER_SUCCESS:
1318             set_next_block_after (header);
1319             break;
1320
1321           case HEADER_FAILURE:
1322             break;
1323
1324           default:
1325             ERROR ((0, 0, _("This does not look like a tar archive")));
1326             return false;
1327           }
1328         break;
1329       }
1330
1331     case GNUTYPE_VOLHDR:
1332       if (!read_header0 (&dummy))
1333         return false;
1334       tar_stat_destroy (&dummy);
1335       assign_string (&volume_label, current_header->header.name);
1336       set_next_block_after (header);
1337       header = find_next_block ();
1338       if (header->header.typeflag != GNUTYPE_MULTIVOL)
1339         break;
1340       /* FALL THROUGH */
1341
1342     case GNUTYPE_MULTIVOL:
1343       if (!read_header0 (&dummy))
1344         return false;
1345       tar_stat_destroy (&dummy);
1346       assign_string (&continued_file_name, current_header->header.name);
1347       continued_file_size =
1348         UINTMAX_FROM_HEADER (current_header->header.size);
1349       continued_file_offset =
1350         UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
1351       break;
1352
1353     default:
1354       break;
1355     }
1356
1357   if (bufmap_head)
1358     {
1359       uintmax_t s;
1360       if (!continued_file_name
1361           || strcmp (continued_file_name, bufmap_head->file_name))
1362         {
1363           if ((archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
1364               && strlen (bufmap_head->file_name) >= NAME_FIELD_SIZE
1365               && strncmp (continued_file_name, bufmap_head->file_name,
1366                           NAME_FIELD_SIZE) == 0)
1367             WARN ((0, 0,
1368  _("%s is possibly continued on this volume: header contains truncated name"),
1369                    quote (bufmap_head->file_name)));
1370           else
1371             {
1372               WARN ((0, 0, _("%s is not continued on this volume"),
1373                      quote (bufmap_head->file_name)));
1374               return false;
1375             }
1376         }
1377
1378       s = continued_file_size + continued_file_offset;
1379
1380       if (bufmap_head->sizetotal != s || s < continued_file_offset)
1381         {
1382           char totsizebuf[UINTMAX_STRSIZE_BOUND];
1383           char s1buf[UINTMAX_STRSIZE_BOUND];
1384           char s2buf[UINTMAX_STRSIZE_BOUND];
1385
1386           WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1387                  quote (continued_file_name),
1388                  STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1389                  STRINGIFY_BIGINT (continued_file_size, s1buf),
1390                  STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1391           return false;
1392         }
1393
1394       if (bufmap_head->sizetotal - bufmap_head->sizeleft !=
1395           continued_file_offset)
1396         {
1397           char totsizebuf[UINTMAX_STRSIZE_BOUND];
1398           char s1buf[UINTMAX_STRSIZE_BOUND];
1399           char s2buf[UINTMAX_STRSIZE_BOUND];
1400
1401           WARN ((0, 0, _("This volume is out of sequence (%s - %s != %s)"),
1402                  STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1403                  STRINGIFY_BIGINT (bufmap_head->sizeleft, s1buf),
1404                  STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1405
1406           return false;
1407         }
1408     }
1409
1410   increase_volume_number ();
1411   return true;
1412 }
1413
1414 \f
1415 #define VOLUME_TEXT " Volume "
1416 #define VOLUME_TEXT_LEN (sizeof VOLUME_TEXT - 1)
1417
1418 char *
1419 drop_volume_label_suffix (const char *label)
1420 {
1421   const char *p;
1422   size_t len = strlen (label);
1423
1424   if (len < 1)
1425     return NULL;
1426
1427   for (p = label + len - 1; p > label && isdigit ((unsigned char) *p); p--)
1428     ;
1429   if (p > label && p - (VOLUME_TEXT_LEN - 1) > label)
1430     {
1431       p -= VOLUME_TEXT_LEN - 1;
1432       if (memcmp (p, VOLUME_TEXT, VOLUME_TEXT_LEN) == 0)
1433         {
1434           char *s = xmalloc ((len = p - label) + 1);
1435           memcpy (s, label, len);
1436           s[len] = 0;
1437           return s;
1438         }
1439     }
1440
1441   return NULL;
1442 }
1443
1444 /* Check LABEL against the volume label, seen as a globbing
1445    pattern.  Return true if the pattern matches.  In case of failure,
1446    retry matching a volume sequence number before giving up in
1447    multi-volume mode.  */
1448 static bool
1449 check_label_pattern (const char *label)
1450 {
1451   char *string;
1452   bool result = false;
1453
1454   if (fnmatch (volume_label_option, label, 0) == 0)
1455     return true;
1456
1457   if (!multi_volume_option)
1458     return false;
1459
1460   string = drop_volume_label_suffix (label);
1461   if (string)
1462     {
1463       result = fnmatch (string, volume_label_option, 0) == 0;
1464       free (string);
1465     }
1466   return result;
1467 }
1468
1469 /* Check if the next block contains a volume label and if this matches
1470    the one given in the command line */
1471 static void
1472 match_volume_label (void)
1473 {
1474   if (!volume_label)
1475     {
1476       union block *label = find_next_block ();
1477
1478       if (!label)
1479         FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1480                       quote (volume_label_option)));
1481       if (label->header.typeflag == GNUTYPE_VOLHDR)
1482         {
1483           if (memchr (label->header.name, '\0', sizeof label->header.name))
1484             assign_string (&volume_label, label->header.name);
1485           else
1486             {
1487               volume_label = xmalloc (sizeof (label->header.name) + 1);
1488               memcpy (volume_label, label->header.name,
1489                       sizeof (label->header.name));
1490               volume_label[sizeof (label->header.name)] = 0;
1491             }
1492         }
1493       else if (label->header.typeflag == XGLTYPE)
1494         {
1495           struct tar_stat_info st;
1496           tar_stat_init (&st);
1497           xheader_read (&st.xhdr, label,
1498                         OFF_FROM_HEADER (label->header.size));
1499           xheader_decode (&st);
1500           tar_stat_destroy (&st);
1501         }
1502     }
1503
1504   if (!volume_label)
1505     FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1506                   quote (volume_label_option)));
1507
1508   if (!check_label_pattern (volume_label))
1509     FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1510                   quote_n (0, volume_label),
1511                   quote_n (1, volume_label_option)));
1512 }
1513
1514 /* Mark the archive with volume label STR. */
1515 static void
1516 _write_volume_label (const char *str)
1517 {
1518   if (archive_format == POSIX_FORMAT)
1519     xheader_store ("GNU.volume.label", &dummy, str);
1520   else
1521     {
1522       union block *label = find_next_block ();
1523
1524       memset (label, 0, BLOCKSIZE);
1525
1526       strcpy (label->header.name, str);
1527       assign_string (&current_stat_info.file_name,
1528                      label->header.name);
1529       current_stat_info.had_trailing_slash =
1530         strip_trailing_slashes (current_stat_info.file_name);
1531
1532       label->header.typeflag = GNUTYPE_VOLHDR;
1533       TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1534       finish_header (&current_stat_info, label, -1);
1535       set_next_block_after (label);
1536     }
1537 }
1538
1539 #define VOL_SUFFIX "Volume"
1540
1541 /* Add a volume label to a part of multi-volume archive */
1542 static void
1543 add_volume_label (void)
1544 {
1545   char buf[UINTMAX_STRSIZE_BOUND];
1546   char *p = STRINGIFY_BIGINT (volno, buf);
1547   char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1548                      + strlen (p) + 2);
1549   sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1550   _write_volume_label (s);
1551   free (s);
1552 }
1553
1554 static void
1555 add_chunk_header (struct bufmap *map)
1556 {
1557   if (archive_format == POSIX_FORMAT)
1558     {
1559       off_t block_ordinal;
1560       union block *blk;
1561       struct tar_stat_info st;
1562
1563       memset (&st, 0, sizeof st);
1564       st.orig_file_name = st.file_name = map->file_name;
1565       st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1566       st.stat.st_uid = getuid ();
1567       st.stat.st_gid = getgid ();
1568       st.orig_file_name = xheader_format_name (&st,
1569                                                "%d/GNUFileParts.%p/%f.%n",
1570                                                volno);
1571       st.file_name = st.orig_file_name;
1572       st.archive_file_size = st.stat.st_size = map->sizeleft;
1573
1574       block_ordinal = current_block_ordinal ();
1575       blk = start_header (&st);
1576       if (!blk)
1577         abort (); /* FIXME */
1578       finish_header (&st, blk, block_ordinal);
1579       free (st.orig_file_name);
1580     }
1581 }
1582
1583
1584 /* Add a volume label to the current archive */
1585 static void
1586 write_volume_label (void)
1587 {
1588   if (multi_volume_option)
1589     add_volume_label ();
1590   else
1591     _write_volume_label (volume_label_option);
1592 }
1593
1594 /* Write GNU multi-volume header */
1595 static void
1596 gnu_add_multi_volume_header (struct bufmap *map)
1597 {
1598   int tmp;
1599   union block *block = find_next_block ();
1600
1601   if (strlen (map->file_name) > NAME_FIELD_SIZE)
1602     WARN ((0, 0,
1603            _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1604            quotearg_colon (map->file_name)));
1605
1606   memset (block, 0, BLOCKSIZE);
1607
1608   strncpy (block->header.name, map->file_name, NAME_FIELD_SIZE);
1609   block->header.typeflag = GNUTYPE_MULTIVOL;
1610
1611   OFF_TO_CHARS (map->sizeleft, block->header.size);
1612   OFF_TO_CHARS (map->sizetotal - map->sizeleft,
1613                 block->oldgnu_header.offset);
1614
1615   tmp = verbose_option;
1616   verbose_option = 0;
1617   finish_header (&current_stat_info, block, -1);
1618   verbose_option = tmp;
1619   set_next_block_after (block);
1620 }
1621
1622 /* Add a multi volume header to the current archive. The exact header format
1623    depends on the archive format. */
1624 static void
1625 add_multi_volume_header (struct bufmap *map)
1626 {
1627   if (archive_format == POSIX_FORMAT)
1628     {
1629       off_t d = map->sizetotal - map->sizeleft;
1630       xheader_store ("GNU.volume.filename", &dummy, map->file_name);
1631       xheader_store ("GNU.volume.size", &dummy, &map->sizeleft);
1632       xheader_store ("GNU.volume.offset", &dummy, &d);
1633     }
1634   else
1635     gnu_add_multi_volume_header (map);
1636 }
1637
1638 \f
1639 /* Low-level flush functions */
1640
1641 /* Simple flush read (no multi-volume or label extensions) */
1642 static void
1643 simple_flush_read (void)
1644 {
1645   size_t status;                /* result from system call */
1646
1647   checkpoint_run (false);
1648
1649   /* Clear the count of errors.  This only applies to a single call to
1650      flush_read.  */
1651
1652   read_error_count = 0;         /* clear error count */
1653
1654   if (write_archive_to_stdout && record_start_block != 0)
1655     {
1656       archive = STDOUT_FILENO;
1657       status = sys_write_archive_buffer ();
1658       archive = STDIN_FILENO;
1659       if (status != record_size)
1660         archive_write_error (status);
1661     }
1662
1663   for (;;)
1664     {
1665       status = rmtread (archive, record_start->buffer, record_size);
1666       if (status == record_size)
1667         {
1668           records_read++;
1669           return;
1670         }
1671       if (status == SAFE_READ_ERROR)
1672         {
1673           archive_read_error ();
1674           continue;             /* try again */
1675         }
1676       break;
1677     }
1678   short_read (status);
1679 }
1680
1681 /* Simple flush write (no multi-volume or label extensions) */
1682 static void
1683 simple_flush_write (size_t level __attribute__((unused)))
1684 {
1685   ssize_t status;
1686
1687   status = _flush_write ();
1688   if (status != record_size)
1689     archive_write_error (status);
1690   else
1691     {
1692       records_written++;
1693       bytes_written += status;
1694     }
1695 }
1696
1697 \f
1698 /* GNU flush functions. These support multi-volume and archive labels in
1699    GNU and PAX archive formats. */
1700
1701 static void
1702 _gnu_flush_read (void)
1703 {
1704   size_t status;                /* result from system call */
1705
1706   checkpoint_run (false);
1707
1708   /* Clear the count of errors.  This only applies to a single call to
1709      flush_read.  */
1710
1711   read_error_count = 0;         /* clear error count */
1712
1713   if (write_archive_to_stdout && record_start_block != 0)
1714     {
1715       archive = STDOUT_FILENO;
1716       status = sys_write_archive_buffer ();
1717       archive = STDIN_FILENO;
1718       if (status != record_size)
1719         archive_write_error (status);
1720     }
1721
1722   for (;;)
1723     {
1724       status = rmtread (archive, record_start->buffer, record_size);
1725       if (status == record_size)
1726         {
1727           records_read++;
1728           return;
1729         }
1730
1731       /* The condition below used to include
1732               || (status > 0 && !read_full_records)
1733          This is incorrect since even if new_volume() succeeds, the
1734          subsequent call to rmtread will overwrite the chunk of data
1735          already read in the buffer, so the processing will fail */
1736       if ((status == 0
1737            || (status == SAFE_READ_ERROR && errno == ENOSPC))
1738           && multi_volume_option)
1739         {
1740           while (!try_new_volume ())
1741             ;
1742           if (current_block == record_end)
1743             /* Necessary for blocking_factor == 1 */
1744             flush_archive();
1745           return;
1746         }
1747       else if (status == SAFE_READ_ERROR)
1748         {
1749           archive_read_error ();
1750           continue;
1751         }
1752       break;
1753     }
1754   short_read (status);
1755 }
1756
1757 static void
1758 gnu_flush_read (void)
1759 {
1760   flush_read_ptr = simple_flush_read; /* Avoid recursion */
1761   _gnu_flush_read ();
1762   flush_read_ptr = gnu_flush_read;
1763 }
1764
1765 static void
1766 _gnu_flush_write (size_t buffer_level)
1767 {
1768   ssize_t status;
1769   union block *header;
1770   char *copy_ptr;
1771   size_t copy_size;
1772   size_t bufsize;
1773   struct bufmap *map;
1774
1775   status = _flush_write ();
1776   if (status != record_size && !multi_volume_option)
1777     archive_write_error (status);
1778   else
1779     {
1780       if (status)
1781         records_written++;
1782       bytes_written += status;
1783     }
1784
1785   if (status == record_size)
1786     {
1787       return;
1788     }
1789
1790   map = bufmap_locate (status);
1791
1792   if (status % BLOCKSIZE)
1793     {
1794       ERROR ((0, 0, _("write did not end on a block boundary")));
1795       archive_write_error (status);
1796     }
1797
1798   /* In multi-volume mode. */
1799   /* ENXIO is for the UNIX PC.  */
1800   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1801     archive_write_error (status);
1802
1803   if (!new_volume (ACCESS_WRITE))
1804     return;
1805
1806   tar_stat_destroy (&dummy);
1807
1808   increase_volume_number ();
1809   prev_written += bytes_written;
1810   bytes_written = 0;
1811
1812   copy_ptr = record_start->buffer + status;
1813   copy_size = buffer_level - status;
1814
1815   /* Switch to the next buffer */
1816   record_index = !record_index;
1817   init_buffer ();
1818
1819   inhibit_map = 1;
1820
1821   if (volume_label_option)
1822     add_volume_label ();
1823
1824   if (map)
1825     add_multi_volume_header (map);
1826
1827   write_extended (true, &dummy, find_next_block ());
1828   tar_stat_destroy (&dummy);
1829
1830   if (map)
1831     add_chunk_header (map);
1832   header = find_next_block ();
1833   bufmap_reset (map, header - record_start);
1834   bufsize = available_space_after (header);
1835   inhibit_map = 0;
1836   while (bufsize < copy_size)
1837     {
1838       memcpy (header->buffer, copy_ptr, bufsize);
1839       copy_ptr += bufsize;
1840       copy_size -= bufsize;
1841       set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
1842       header = find_next_block ();
1843       bufsize = available_space_after (header);
1844     }
1845   memcpy (header->buffer, copy_ptr, copy_size);
1846   memset (header->buffer + copy_size, 0, bufsize - copy_size);
1847   set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
1848   find_next_block ();
1849 }
1850
1851 static void
1852 gnu_flush_write (size_t buffer_level)
1853 {
1854   flush_write_ptr = simple_flush_write; /* Avoid recursion */
1855   _gnu_flush_write (buffer_level);
1856   flush_write_ptr = gnu_flush_write;
1857 }
1858
1859 void
1860 flush_read ()
1861 {
1862   flush_read_ptr ();
1863 }
1864
1865 void
1866 flush_write ()
1867 {
1868   flush_write_ptr (record_size);
1869 }
1870
1871 void
1872 open_archive (enum access_mode wanted_access)
1873 {
1874   flush_read_ptr = gnu_flush_read;
1875   flush_write_ptr = gnu_flush_write;
1876
1877   _open_archive (wanted_access);
1878   switch (wanted_access)
1879     {
1880     case ACCESS_READ:
1881     case ACCESS_UPDATE:
1882       if (volume_label_option)
1883         match_volume_label ();
1884       break;
1885
1886     case ACCESS_WRITE:
1887       records_written = 0;
1888       if (volume_label_option)
1889         write_volume_label ();
1890       break;
1891     }
1892   set_volume_start_time ();
1893 }