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