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