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