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