When given -c -a, issue a warning if no compressor is associated with the suffix.
[tar.git] / src / buffer.c
blob56273642bf63db3e4f7a7ae02a60d3e1edce436a
1 /* Buffer management for tar.
3 Copyright 1988-2024 Free Software Foundation, Inc.
5 This file is part of GNU tar.
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.
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.
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/>.
20 Written by John Gilmore, on 1985-08-25. */
22 #include <system.h>
24 #include <signal.h>
26 #include <c-ctype.h>
27 #include <closeout.h>
28 #include <fnmatch.h>
29 #include <human.h>
30 #include <quotearg.h>
31 #include <verify.h>
33 #include "common.h"
34 #include <rmt.h>
36 /* Work around GCC bug 109856. */
37 # if 13 <= __GNUC__
38 # pragma GCC diagnostic ignored "-Wnull-dereference"
39 # endif
41 /* Number of retries before giving up on read. */
42 #define READ_ERROR_MAX 10
44 /* Variables. */
46 static tarlong prev_written; /* bytes written on previous volumes */
47 static tarlong bytes_written; /* bytes written on this volume */
48 static void *record_buffer[2]; /* allocated memory */
49 static union block *record_buffer_aligned[2];
50 static int record_index;
52 /* FIXME: The following variables should ideally be static to this
53 module. However, this cannot be done yet. The cleanup continues! */
55 union block *record_start; /* start of record of archive */
56 union block *record_end; /* last+1 block of archive record */
57 union block *current_block; /* current block of archive */
58 enum access_mode access_mode; /* how do we handle the archive */
59 off_t records_read; /* number of records read from this archive */
60 off_t records_written; /* likewise, for records written */
61 extern off_t records_skipped; /* number of records skipped at the start
62 of the archive, defined in delete.c */
64 static off_t record_start_block; /* block ordinal at record_start */
66 /* Where we write list messages (not errors, not interactions) to. */
67 FILE *stdlis;
69 static void backspace_output (void);
71 /* PID of child program, if compress_option or remote archive access. */
72 static pid_t child_pid;
74 /* Error recovery stuff */
75 static int read_error_count;
77 /* Have we hit EOF yet? */
78 static bool hit_eof;
80 static bool read_full_records = false;
82 /* We're reading, but we just read the last block and it's time to update.
83 Declared in update.c
85 FIXME: Either eliminate it or move it to common.h.
87 extern bool time_to_start_writing;
89 bool write_archive_to_stdout;
91 static void (*flush_write_ptr) (size_t);
92 static void (*flush_read_ptr) (void);
95 char *volume_label;
96 char *continued_file_name;
97 uintmax_t continued_file_size;
98 uintmax_t continued_file_offset;
101 static int volno = 1; /* which volume of a multi-volume tape we're
102 on */
103 static int global_volno = 1; /* volume number to print in external
104 messages */
106 bool write_archive_to_stdout;
109 /* Multi-volume tracking support */
111 /* When creating a multi-volume archive, each 'bufmap' represents
112 a member stored (perhaps partly) in the current record buffer.
113 Bufmaps are form a single-linked list in chronological order.
115 After flushing the record to the output media, all bufmaps that
116 represent fully written members are removed from the list, the
117 nblocks and sizeleft values in the bufmap_head and start values
118 in all remaining bufmaps are updated. The information stored
119 in bufmap_head is used to form the volume header.
121 When reading from a multi-volume archive, the list degrades to a
122 single element, which keeps information about the member currently
123 being read. In that case the sizeleft member is updated explicitly
124 from the extractor code by calling the mv_size_left function. The
125 information from bufmap_head is compared with the volume header data
126 to ensure that subsequent volumes are fed in the right order.
129 struct bufmap
131 struct bufmap *next; /* Pointer to the next map entry */
132 size_t start; /* Offset of the first data block */
133 char *file_name; /* Name of the stored file */
134 off_t sizetotal; /* Size of the stored file */
135 off_t sizeleft; /* Size left to read/write */
136 size_t nblocks; /* Number of blocks written since reset */
138 static struct bufmap *bufmap_head, *bufmap_tail;
140 /* This variable, when set, inhibits updating the bufmap chain after
141 a write. This is necessary when writing extended POSIX headers. */
142 static int inhibit_map;
144 void
145 mv_begin_write (const char *file_name, off_t totsize, off_t sizeleft)
147 if (multi_volume_option)
149 struct bufmap *bp = xmalloc (sizeof bp[0]);
150 if (bufmap_tail)
151 bufmap_tail->next = bp;
152 else
153 bufmap_head = bp;
154 bufmap_tail = bp;
156 bp->next = NULL;
157 bp->start = current_block - record_start;
158 bp->file_name = xstrdup (file_name);
159 bp->sizetotal = totsize;
160 bp->sizeleft = sizeleft;
161 bp->nblocks = 0;
165 static struct bufmap *
166 bufmap_locate (size_t off)
168 struct bufmap *map;
170 for (map = bufmap_head; map; map = map->next)
172 if (!map->next || off < map->next->start * BLOCKSIZE)
173 break;
175 return map;
178 static void
179 bufmap_free (struct bufmap *mark)
181 struct bufmap *map;
182 for (map = bufmap_head; map && map != mark; )
184 struct bufmap *next = map->next;
185 free (map->file_name);
186 free (map);
187 map = next;
189 bufmap_head = map;
190 if (!bufmap_head)
191 bufmap_tail = bufmap_head;
194 static void
195 bufmap_reset (struct bufmap *map, ssize_t fixup)
197 bufmap_free (map);
198 if (map)
200 for (; map; map = map->next)
202 map->start += fixup;
203 map->nblocks = 0;
209 static struct tar_stat_info dummy;
211 void
212 buffer_write_global_xheader (void)
214 xheader_write_global (&dummy.xhdr);
217 void
218 mv_begin_read (struct tar_stat_info *st)
220 mv_begin_write (st->orig_file_name, st->stat.st_size, st->stat.st_size);
223 void
224 mv_end (void)
226 if (multi_volume_option)
227 bufmap_free (NULL);
230 void
231 mv_size_left (off_t size)
233 if (bufmap_head)
234 bufmap_head->sizeleft = size;
238 /* Functions. */
240 void
241 clear_read_error_count (void)
243 read_error_count = 0;
247 /* Time-related functions */
249 static double duration;
251 void
252 set_start_time (void)
254 gettime (&start_time);
255 volume_start_time = start_time;
256 last_stat_time = start_time;
259 static void
260 set_volume_start_time (void)
262 gettime (&volume_start_time);
263 last_stat_time = volume_start_time;
266 double
267 compute_duration (void)
269 struct timespec now;
270 gettime (&now);
271 duration += ((now.tv_sec - last_stat_time.tv_sec)
272 + (now.tv_nsec - last_stat_time.tv_nsec) / 1e9);
273 gettime (&last_stat_time);
274 return duration;
278 /* Compression detection */
280 enum compress_type {
281 ct_none, /* Unknown compression type */
282 ct_tar, /* Plain tar file */
283 ct_compress,
284 ct_gzip,
285 ct_bzip2,
286 ct_lzip,
287 ct_lzma,
288 ct_lzop,
289 ct_xz,
290 ct_zstd
293 static enum compress_type archive_compression_type = ct_none;
295 struct zip_magic
297 enum compress_type type;
298 size_t length;
299 char const *magic;
302 struct zip_program
304 enum compress_type type;
305 char const *program;
306 char const *option;
309 static struct zip_magic const magic[] = {
310 { ct_none, 0, 0 },
311 { ct_tar, 0, 0 },
312 { ct_compress, 2, "\037\235" },
313 { ct_gzip, 2, "\037\213" },
314 { ct_bzip2, 3, "BZh" },
315 { ct_lzip, 4, "LZIP" },
316 { ct_lzma, 6, "\xFFLZMA" },
317 { ct_lzma, 3, "\x5d\x00\x00" },
318 { ct_lzop, 4, "\211LZO" },
319 { ct_xz, 6, "\xFD" "7zXZ" },
320 { ct_zstd, 4, "\x28\xB5\x2F\xFD" },
323 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
325 static struct zip_program zip_program[] = {
326 { ct_compress, COMPRESS_PROGRAM, "-Z" },
327 { ct_compress, GZIP_PROGRAM, "-z" },
328 { ct_gzip, GZIP_PROGRAM, "-z" },
329 { ct_bzip2, BZIP2_PROGRAM, "-j" },
330 { ct_bzip2, "lbzip2", "-j" },
331 { ct_lzip, LZIP_PROGRAM, "--lzip" },
332 { ct_lzma, LZMA_PROGRAM, "--lzma" },
333 { ct_lzma, XZ_PROGRAM, "-J" },
334 { ct_lzop, LZOP_PROGRAM, "--lzop" },
335 { ct_xz, XZ_PROGRAM, "-J" },
336 { ct_zstd, ZSTD_PROGRAM, "--zstd" },
338 enum { n_zip_programs = sizeof zip_program / sizeof *zip_program };
340 static struct zip_program const *
341 find_zip_program (enum compress_type type, int *pstate)
343 int i;
345 for (i = *pstate; i < n_zip_programs; i++)
347 if (zip_program[i].type == type)
349 *pstate = i + 1;
350 return zip_program + i;
353 *pstate = i;
354 return NULL;
357 const char *
358 first_decompress_program (int *pstate)
360 struct zip_program const *zp;
362 *pstate = n_zip_programs;
364 if (use_compress_program_option)
365 return use_compress_program_option;
367 if (archive_compression_type == ct_none)
368 return NULL;
370 *pstate = 0;
371 zp = find_zip_program (archive_compression_type, pstate);
372 return zp ? zp->program : NULL;
375 const char *
376 next_decompress_program (int *pstate)
378 struct zip_program const *zp;
380 zp = find_zip_program (archive_compression_type, pstate);
381 return zp ? zp->program : NULL;
384 static const char *
385 compress_option (enum compress_type type)
387 struct zip_program const *zp;
388 int i = 0;
389 zp = find_zip_program (type, &i);
390 return zp ? zp->option : NULL;
393 /* Check if the file ARCHIVE is a compressed archive. */
394 static enum compress_type
395 check_compressed_archive (bool *pshort)
397 struct zip_magic const *p;
398 bool sfr;
399 bool temp;
401 if (!pshort)
402 pshort = &temp;
404 /* Prepare global data needed for find_next_block: */
405 record_end = record_start; /* set up for 1st record = # 0 */
406 sfr = read_full_records;
407 read_full_records = true; /* Suppress fatal error on reading a partial
408 record */
409 *pshort = find_next_block () == 0;
411 /* Restore global values */
412 read_full_records = sfr;
414 if (record_start != record_end /* no files smaller than BLOCKSIZE */
415 && (strcmp (record_start->header.magic, TMAGIC) == 0
416 || strcmp (record_start->buffer + offsetof (struct posix_header,
417 magic),
418 OLDGNU_MAGIC) == 0)
419 && tar_checksum (record_start, true) == HEADER_SUCCESS)
420 /* Probably a valid header */
421 return ct_tar;
423 for (p = magic + 2; p < magic + NMAGIC; p++)
424 if (memcmp (record_start->buffer, p->magic, p->length) == 0)
425 return p->type;
427 return ct_none;
430 /* Open an archive named archive_name_array[0]. Detect if it is
431 a compressed archive of known type and use corresponding decompression
432 program if so */
433 static int
434 open_compressed_archive (void)
436 archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
437 MODE_RW, rsh_command_option);
438 if (archive == -1)
439 return archive;
441 if (!multi_volume_option)
443 if (!use_compress_program_option)
445 bool shortfile;
446 enum compress_type type = check_compressed_archive (&shortfile);
448 switch (type)
450 case ct_tar:
451 if (shortfile)
452 ERROR ((0, 0, _("This does not look like a tar archive")));
453 return archive;
455 case ct_none:
456 if (shortfile)
457 ERROR ((0, 0, _("This does not look like a tar archive")));
458 set_compression_program_by_suffix (archive_name_array[0], NULL,
459 false);
460 if (!use_compress_program_option)
461 return archive;
462 break;
464 default:
465 archive_compression_type = type;
466 break;
470 /* FD is not needed any more */
471 rmtclose (archive);
473 hit_eof = false; /* It might have been set by find_next_block in
474 check_compressed_archive */
476 /* Open compressed archive */
477 child_pid = sys_child_open_for_uncompress ();
478 read_full_records = true;
481 records_read = 0;
482 record_end = record_start; /* set up for 1st record = # 0 */
484 return archive;
487 static int
488 print_stats (FILE *fp, const char *text, tarlong numbytes)
490 char abbr[LONGEST_HUMAN_READABLE + 1];
491 char rate[LONGEST_HUMAN_READABLE + 1];
492 int n = 0;
494 int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
496 if (text && text[0])
497 n += fprintf (fp, "%s: ", gettext (text));
498 return n + fprintf (fp, TARLONG_FORMAT " (%s, %s/s)",
499 numbytes,
500 human_readable (numbytes, abbr, human_opts, 1, 1),
501 (0 < duration && numbytes / duration < (uintmax_t) -1
502 ? human_readable (numbytes / duration, rate, human_opts, 1, 1)
503 : "?"));
506 /* Format totals to file FP. FORMATS is an array of strings to output
507 before each data item (bytes read, written, deleted, in that order).
508 EOR is a delimiter to output after each item (used only if deleting
509 from the archive), EOL is a delimiter to add at the end of the output
510 line. */
512 format_total_stats (FILE *fp, char const *const *formats, int eor, int eol)
514 int n;
516 switch (subcommand_option)
518 case CREATE_SUBCOMMAND:
519 case CAT_SUBCOMMAND:
520 case UPDATE_SUBCOMMAND:
521 case APPEND_SUBCOMMAND:
522 n = print_stats (fp, formats[TF_WRITE],
523 prev_written + bytes_written);
524 break;
526 case DELETE_SUBCOMMAND:
528 char buf[UINTMAX_STRSIZE_BOUND];
529 n = print_stats (fp, formats[TF_READ],
530 records_read * record_size);
532 fputc (eor, fp);
533 n++;
535 n += print_stats (fp, formats[TF_WRITE],
536 prev_written + bytes_written);
538 fputc (eor, fp);
539 n++;
541 if (formats[TF_DELETED] && formats[TF_DELETED][0])
542 n += fprintf (fp, "%s: ", gettext (formats[TF_DELETED]));
543 n += fprintf (fp, "%s",
544 STRINGIFY_BIGINT ((records_read - records_skipped)
545 * record_size
546 - (prev_written + bytes_written), buf));
548 break;
550 case EXTRACT_SUBCOMMAND:
551 case LIST_SUBCOMMAND:
552 case DIFF_SUBCOMMAND:
553 n = print_stats (fp, _(formats[TF_READ]),
554 records_read * record_size);
555 break;
557 default:
558 abort ();
560 if (eol)
562 fputc (eol, fp);
563 n++;
565 return n;
568 static char const *const default_total_format[] = {
569 N_("Total bytes read"),
570 /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*". */
571 N_("Total bytes written"),
572 N_("Total bytes deleted")
575 void
576 print_total_stats (void)
578 format_total_stats (stderr, default_total_format, '\n', '\n');
581 /* Compute and return the block ordinal at current_block. */
582 off_t
583 current_block_ordinal (void)
585 return record_start_block + (current_block - record_start);
588 /* If the EOF flag is set, reset it, as well as current_block, etc. */
589 void
590 reset_eof (void)
592 if (hit_eof)
594 hit_eof = false;
595 current_block = record_start;
596 record_end = record_start + blocking_factor;
597 access_mode = ACCESS_WRITE;
601 /* Return the location of the next available input or output block.
602 Return zero for EOF. Once we have returned zero, we just keep returning
603 it, to avoid accidentally going on to the next file on the tape. */
604 union block *
605 find_next_block (void)
607 if (current_block == record_end)
609 if (hit_eof)
610 return 0;
611 flush_archive ();
612 if (current_block == record_end)
614 hit_eof = true;
615 return 0;
618 return current_block;
621 /* Indicate that we have used all blocks up thru BLOCK. */
622 void
623 set_next_block_after (union block *block)
625 while (block >= current_block)
626 current_block++;
628 /* Do *not* flush the archive here. If we do, the same argument to
629 set_next_block_after could mean the next block (if the input record
630 is exactly one block long), which is not what is intended. */
632 if (current_block > record_end)
633 abort ();
636 /* Return the number of bytes comprising the space between POINTER
637 through the end of the current buffer of blocks. This space is
638 available for filling with data, or taking data from. POINTER is
639 usually (but not always) the result of previous find_next_block call. */
640 size_t
641 available_space_after (union block *pointer)
643 return record_end->buffer - pointer->buffer;
646 /* Close file having descriptor FD, and abort if close unsuccessful. */
647 void
648 xclose (int fd)
650 if (close (fd) != 0)
651 close_error (_("(pipe)"));
654 static void
655 init_buffer (void)
657 if (! record_buffer_aligned[record_index])
658 record_buffer_aligned[record_index] =
659 page_aligned_alloc (&record_buffer[record_index], record_size);
661 record_start = record_buffer_aligned[record_index];
662 current_block = record_start;
663 record_end = record_start + blocking_factor;
666 static void
667 check_tty (enum access_mode mode)
669 /* Refuse to read archive from and write it to a tty. */
670 if (strcmp (archive_name_array[0], "-") == 0
671 && isatty (mode == ACCESS_READ ? STDIN_FILENO : STDOUT_FILENO))
673 FATAL_ERROR ((0, 0,
674 mode == ACCESS_READ
675 ? _("Refusing to read archive contents from terminal "
676 "(missing -f option?)")
677 : _("Refusing to write archive contents to terminal "
678 "(missing -f option?)")));
682 /* Fetch the status of the archive, accessed via WANTED_STATUS. */
684 static void
685 get_archive_status (enum access_mode wanted_access, bool backed_up_flag)
687 if (!sys_get_archive_stat ())
689 int saved_errno = errno;
691 if (backed_up_flag)
692 undo_last_backup ();
693 errno = saved_errno;
694 open_fatal (archive_name_array[0]);
697 seekable_archive
698 = (! (multi_volume_option || use_compress_program_option)
699 && (seek_option < 0
700 ? (_isrmt (archive)
701 || S_ISREG (archive_stat.st_mode)
702 || S_ISBLK (archive_stat.st_mode))
703 : seek_option));
705 if (wanted_access != ACCESS_READ)
706 sys_detect_dev_null_output ();
708 SET_BINARY_MODE (archive);
711 /* Open an archive file. The argument specifies whether we are
712 reading or writing, or both. */
713 static void
714 _open_archive (enum access_mode wanted_access)
716 bool backed_up_flag = false;
718 if (record_size == 0)
719 FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
721 if (archive_names == 0)
722 FATAL_ERROR ((0, 0, _("No archive name given")));
724 tar_stat_destroy (&current_stat_info);
726 record_index = 0;
727 init_buffer ();
729 /* When updating the archive, we start with reading. */
730 access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
731 check_tty (access_mode);
733 read_full_records = read_full_records_option;
735 records_read = 0;
737 if (use_compress_program_option)
739 switch (wanted_access)
741 case ACCESS_READ:
742 child_pid = sys_child_open_for_uncompress ();
743 read_full_records = true;
744 record_end = record_start; /* set up for 1st record = # 0 */
745 break;
747 case ACCESS_WRITE:
748 child_pid = sys_child_open_for_compress ();
749 break;
751 case ACCESS_UPDATE:
752 abort (); /* Should not happen */
753 break;
756 if (!index_file_name
757 && wanted_access == ACCESS_WRITE
758 && strcmp (archive_name_array[0], "-") == 0)
759 stdlis = stderr;
761 else if (strcmp (archive_name_array[0], "-") == 0)
763 read_full_records = true; /* could be a pipe, be safe */
764 if (verify_option)
765 FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
767 switch (wanted_access)
769 case ACCESS_READ:
771 bool shortfile;
772 enum compress_type type;
774 archive = STDIN_FILENO;
775 type = check_compressed_archive (&shortfile);
776 if (type != ct_tar && type != ct_none)
777 FATAL_ERROR ((0, 0,
778 _("Archive is compressed. Use %s option"),
779 compress_option (type)));
780 if (shortfile)
781 ERROR ((0, 0, _("This does not look like a tar archive")));
783 break;
785 case ACCESS_WRITE:
786 archive = STDOUT_FILENO;
787 if (!index_file_name)
788 stdlis = stderr;
789 break;
791 case ACCESS_UPDATE:
792 archive = STDIN_FILENO;
793 write_archive_to_stdout = true;
794 record_end = record_start; /* set up for 1st record = # 0 */
795 if (!index_file_name)
796 stdlis = stderr;
797 break;
800 else
801 switch (wanted_access)
803 case ACCESS_READ:
804 archive = open_compressed_archive ();
805 break;
807 case ACCESS_WRITE:
808 if (backup_option)
810 maybe_backup_file (archive_name_array[0], 1);
811 backed_up_flag = true;
813 if (verify_option)
814 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
815 MODE_RW, rsh_command_option);
816 else
817 archive = rmtcreat (archive_name_array[0], MODE_RW,
818 rsh_command_option);
819 break;
821 case ACCESS_UPDATE:
822 archive = rmtopen (archive_name_array[0],
823 O_RDWR | O_CREAT | O_BINARY,
824 MODE_RW, rsh_command_option);
826 switch (check_compressed_archive (NULL))
828 case ct_none:
829 case ct_tar:
830 break;
832 default:
833 FATAL_ERROR ((0, 0,
834 _("Cannot update compressed archives")));
836 break;
839 get_archive_status (wanted_access, backed_up_flag);
841 switch (wanted_access)
843 case ACCESS_READ:
844 find_next_block (); /* read it in, check for EOF */
845 break;
847 case ACCESS_UPDATE:
848 case ACCESS_WRITE:
849 records_written = 0;
850 break;
854 /* Perform a write to flush the buffer. */
855 static ssize_t
856 _flush_write (void)
858 ssize_t status;
860 checkpoint_run (true);
861 if (tape_length_option && tape_length_option <= bytes_written)
863 errno = ENOSPC;
864 status = 0;
866 else if (dev_null_output)
867 status = record_size;
868 else
869 status = sys_write_archive_buffer ();
871 if (status && multi_volume_option && !inhibit_map)
873 struct bufmap *map = bufmap_locate (status);
874 if (map)
876 size_t delta = status - map->start * BLOCKSIZE;
877 ssize_t diff;
878 map->nblocks += delta / BLOCKSIZE;
879 if (delta > map->sizeleft)
880 delta = map->sizeleft;
881 map->sizeleft -= delta;
882 if (map->sizeleft == 0)
884 diff = map->start + map->nblocks;
885 map = map->next;
887 else
888 diff = map->start;
889 bufmap_reset (map, - diff);
892 return status;
895 /* Handle write errors on the archive. Write errors are always fatal.
896 Hitting the end of a volume does not cause a write error unless the
897 write was the first record of the volume. */
898 void
899 archive_write_error (ssize_t status)
901 /* It might be useful to know how much was written before the error
902 occurred. */
903 if (totals_option)
905 int e = errno;
906 print_total_stats ();
907 errno = e;
910 write_fatal_details (*archive_name_cursor, status, record_size);
913 /* Handle read errors on the archive. If the read should be retried,
914 return to the caller. */
915 void
916 archive_read_error (void)
918 read_error (*archive_name_cursor);
920 if (record_start_block == 0)
921 FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
923 /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
924 then give up on reading the archive. */
926 if (read_error_count++ > READ_ERROR_MAX)
927 FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
928 return;
931 static bool
932 archive_is_dev (void)
934 struct stat st;
936 if (fstat (archive, &st))
938 stat_diag (*archive_name_cursor);
939 return false;
941 return S_ISBLK (st.st_mode) || S_ISCHR (st.st_mode);
944 static void
945 short_read (size_t status)
947 size_t left; /* bytes left */
948 char *more; /* pointer to next byte to read */
950 more = record_start->buffer + status;
951 left = record_size - status;
953 if (left && left % BLOCKSIZE == 0
954 && (warning_option & WARN_RECORD_SIZE)
955 && record_start_block == 0 && status != 0
956 && archive_is_dev ())
958 unsigned long rsize = status / BLOCKSIZE;
959 WARN ((0, 0,
960 ngettext ("Record size = %lu block",
961 "Record size = %lu blocks",
962 rsize),
963 rsize));
966 while (left % BLOCKSIZE != 0
967 || (left && status && read_full_records))
969 if (status)
970 while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
971 archive_read_error ();
973 if (status == 0)
974 break;
976 if (! read_full_records)
978 unsigned long rest = record_size - left;
980 FATAL_ERROR ((0, 0,
981 ngettext ("Unaligned block (%lu byte) in archive",
982 "Unaligned block (%lu bytes) in archive",
983 rest),
984 rest));
987 left -= status;
988 more += status;
991 record_end = record_start + (record_size - left) / BLOCKSIZE;
992 records_read++;
995 /* Flush the current buffer to/from the archive. */
996 void
997 flush_archive (void)
999 size_t buffer_level;
1001 if (access_mode == ACCESS_READ && time_to_start_writing)
1003 access_mode = ACCESS_WRITE;
1004 time_to_start_writing = false;
1005 backspace_output ();
1006 if (record_end - record_start < blocking_factor)
1008 memset (record_end, 0,
1009 (blocking_factor - (record_end - record_start))
1010 * BLOCKSIZE);
1011 record_end = record_start + blocking_factor;
1012 return;
1016 buffer_level = current_block->buffer - record_start->buffer;
1017 record_start_block += record_end - record_start;
1018 current_block = record_start;
1019 record_end = record_start + blocking_factor;
1021 switch (access_mode)
1023 case ACCESS_READ:
1024 flush_read ();
1025 break;
1027 case ACCESS_WRITE:
1028 flush_write_ptr (buffer_level);
1029 break;
1031 case ACCESS_UPDATE:
1032 abort ();
1036 /* Backspace the archive descriptor by one record worth. If it's a
1037 tape, MTIOCTOP will work. If it's something else, try to seek on
1038 it. If we can't seek, we lose! */
1039 static void
1040 backspace_output (void)
1042 if (mtioseek (false, -1))
1043 return;
1046 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1048 /* Seek back to the beginning of this record and start writing there. */
1050 position -= record_end->buffer - record_start->buffer;
1051 if (position < 0)
1052 position = 0;
1053 if (rmtlseek (archive, position, SEEK_SET) != position)
1055 /* Lseek failed. Try a different method. */
1057 WARN ((0, 0,
1058 _("Cannot backspace archive file; it may be unreadable without -i")));
1060 /* Replace the first part of the record with NULs. */
1062 if (record_start->buffer != output_start)
1063 memset (record_start->buffer, 0,
1064 output_start - record_start->buffer);
1069 off_t
1070 seek_archive (off_t size)
1072 off_t start = current_block_ordinal ();
1073 off_t offset;
1074 off_t nrec, nblk;
1075 off_t skipped = (blocking_factor - (current_block - record_start))
1076 * BLOCKSIZE;
1078 if (size <= skipped)
1079 return 0;
1081 /* Compute number of records to skip */
1082 nrec = (size - skipped) / record_size;
1083 if (nrec == 0)
1084 return 0;
1085 offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
1086 if (offset < 0)
1087 return offset;
1089 if (offset % record_size)
1090 FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
1092 /* Convert to number of records */
1093 offset /= BLOCKSIZE;
1094 /* Compute number of skipped blocks */
1095 nblk = offset - start;
1097 /* Update buffering info */
1098 records_read += nblk / blocking_factor;
1099 record_start_block = offset - blocking_factor;
1100 current_block = record_end;
1102 return nblk;
1105 /* Close the archive file. */
1106 void
1107 close_archive (void)
1109 if (time_to_start_writing || access_mode == ACCESS_WRITE)
1112 flush_archive ();
1113 while (current_block > record_start);
1116 compute_duration ();
1117 if (verify_option)
1118 verify_volume ();
1120 if (rmtclose (archive) != 0)
1121 close_error (*archive_name_cursor);
1123 sys_wait_for_child (child_pid, hit_eof);
1125 tar_stat_destroy (&current_stat_info);
1126 free (record_buffer[0]);
1127 free (record_buffer[1]);
1128 bufmap_free (NULL);
1131 void
1132 write_fatal_details (char const *name, ssize_t status, size_t size)
1134 write_error_details (name, status, size);
1135 if (rmtclose (archive) != 0)
1136 close_error (*archive_name_cursor);
1137 sys_wait_for_child (child_pid, false);
1138 fatal_exit ();
1141 /* Called to initialize the global volume number. */
1142 void
1143 init_volume_number (void)
1145 FILE *file = fopen (volno_file_option, "r");
1147 if (file)
1149 if (fscanf (file, "%d", &global_volno) != 1
1150 || global_volno < 0)
1151 FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1152 quotearg_colon (volno_file_option)));
1153 if (ferror (file))
1154 read_error (volno_file_option);
1155 if (fclose (file) != 0)
1156 close_error (volno_file_option);
1158 else if (errno != ENOENT)
1159 open_error (volno_file_option);
1162 /* Called to write out the closing global volume number. */
1163 void
1164 closeout_volume_number (void)
1166 FILE *file = fopen (volno_file_option, "w");
1168 if (file)
1170 fprintf (file, "%d\n", global_volno);
1171 if (ferror (file))
1172 write_error (volno_file_option);
1173 if (fclose (file) != 0)
1174 close_error (volno_file_option);
1176 else
1177 open_error (volno_file_option);
1181 static void
1182 increase_volume_number (void)
1184 global_volno++;
1185 if (global_volno < 0)
1186 FATAL_ERROR ((0, 0, _("Volume number overflow")));
1187 volno++;
1190 static void
1191 change_tape_menu (FILE *read_file)
1193 char *input_buffer = NULL;
1194 size_t size = 0;
1195 bool stop = false;
1197 while (!stop)
1199 fputc ('\007', stderr);
1200 fprintf (stderr,
1201 _("Prepare volume #%d for %s and hit return: "),
1202 global_volno + 1, quote (*archive_name_cursor));
1203 fflush (stderr);
1205 if (getline (&input_buffer, &size, read_file) <= 0)
1207 WARN ((0, 0, _("EOF where user reply was expected")));
1209 if (subcommand_option != EXTRACT_SUBCOMMAND
1210 && subcommand_option != LIST_SUBCOMMAND
1211 && subcommand_option != DIFF_SUBCOMMAND)
1212 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1214 fatal_exit ();
1217 if (input_buffer[0] == '\n'
1218 || input_buffer[0] == 'y'
1219 || input_buffer[0] == 'Y')
1220 break;
1222 switch (input_buffer[0])
1224 case '?':
1226 fprintf (stderr, _("\
1227 n name Give a new file name for the next (and subsequent) volume(s)\n\
1228 q Abort tar\n\
1229 y or newline Continue operation\n"));
1230 if (!restrict_option)
1231 fprintf (stderr, _(" ! Spawn a subshell\n"));
1232 fprintf (stderr, _(" ? Print this list\n"));
1234 break;
1236 case 'q':
1237 /* Quit. */
1239 WARN ((0, 0, _("No new volume; exiting.\n")));
1241 if (subcommand_option != EXTRACT_SUBCOMMAND
1242 && subcommand_option != LIST_SUBCOMMAND
1243 && subcommand_option != DIFF_SUBCOMMAND)
1244 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1246 fatal_exit ();
1248 case 'n':
1249 /* Get new file name. */
1252 char *name;
1253 char *cursor;
1255 for (name = input_buffer + 1;
1256 *name == ' ' || *name == '\t';
1257 name++)
1260 for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1262 *cursor = '\0';
1264 if (name[0])
1266 /* FIXME: the following allocation is never reclaimed. */
1267 *archive_name_cursor = xstrdup (name);
1268 stop = true;
1270 else
1271 fprintf (stderr, "%s",
1272 _("File name not specified. Try again.\n"));
1274 break;
1276 case '!':
1277 if (!restrict_option)
1279 sys_spawn_shell ();
1280 break;
1282 FALLTHROUGH;
1283 default:
1284 fprintf (stderr, _("Invalid input. Type ? for help.\n"));
1287 free (input_buffer);
1290 /* We've hit the end of the old volume. Close it and open the next one.
1291 Return nonzero on success.
1293 static bool
1294 new_volume (enum access_mode mode)
1296 static FILE *read_file;
1297 static int looped;
1298 int prompt;
1300 if (!read_file && !info_script_option)
1301 /* FIXME: if fopen is used, it will never be closed. */
1302 read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1304 if (now_verifying)
1305 return false;
1306 if (verify_option)
1307 verify_volume ();
1309 assign_null (&volume_label);
1310 assign_null (&continued_file_name);
1311 continued_file_size = continued_file_offset = 0;
1312 current_block = record_start;
1314 if (rmtclose (archive) != 0)
1315 close_error (*archive_name_cursor);
1317 archive_name_cursor++;
1318 if (archive_name_cursor == archive_name_array + archive_names)
1320 archive_name_cursor = archive_name_array;
1321 looped = 1;
1323 prompt = looped;
1325 tryagain:
1326 if (prompt)
1328 /* We have to prompt from now on. */
1330 if (info_script_option)
1332 if (volno_file_option)
1333 closeout_volume_number ();
1334 if (sys_exec_info_script (archive_name_cursor, global_volno+1))
1335 FATAL_ERROR ((0, 0, _("%s command failed"),
1336 quote (info_script_option)));
1338 else
1339 change_tape_menu (read_file);
1342 if (strcmp (archive_name_cursor[0], "-") == 0)
1344 read_full_records = true;
1345 archive = STDIN_FILENO;
1347 else if (verify_option)
1348 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1349 rsh_command_option);
1350 else
1351 switch (mode)
1353 case ACCESS_READ:
1354 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1355 rsh_command_option);
1356 break;
1358 case ACCESS_WRITE:
1359 if (backup_option)
1360 maybe_backup_file (*archive_name_cursor, 1);
1361 archive = rmtcreat (*archive_name_cursor, MODE_RW,
1362 rsh_command_option);
1363 break;
1365 case ACCESS_UPDATE:
1366 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1367 rsh_command_option);
1368 break;
1371 if (archive < 0)
1373 open_warn (*archive_name_cursor);
1374 if (!verify_option && mode == ACCESS_WRITE && backup_option)
1375 undo_last_backup ();
1376 prompt = 1;
1377 goto tryagain;
1380 get_archive_status (mode, false);
1382 return true;
1385 static bool
1386 read_header0 (struct tar_stat_info *info)
1388 enum read_header rc;
1390 tar_stat_init (info);
1391 rc = read_header (&current_header, info, read_header_auto);
1392 if (rc == HEADER_SUCCESS)
1394 set_next_block_after (current_header);
1395 return true;
1397 ERROR ((0, 0, _("This does not look like a tar archive")));
1398 return false;
1401 static bool
1402 try_new_volume (void)
1404 size_t status;
1405 union block *header;
1406 enum access_mode acc;
1408 switch (subcommand_option)
1410 case APPEND_SUBCOMMAND:
1411 case CAT_SUBCOMMAND:
1412 case UPDATE_SUBCOMMAND:
1413 acc = ACCESS_UPDATE;
1414 break;
1416 default:
1417 acc = ACCESS_READ;
1418 break;
1421 if (!new_volume (acc))
1422 return true;
1424 while ((status = rmtread (archive, record_start->buffer, record_size))
1425 == SAFE_READ_ERROR)
1426 archive_read_error ();
1428 if (status != record_size)
1429 short_read (status);
1431 header = find_next_block ();
1432 if (!header)
1434 WARN ((0, 0, _("This does not look like a tar archive")));
1435 return false;
1438 switch (header->header.typeflag)
1440 case XGLTYPE:
1442 tar_stat_init (&dummy);
1443 if (read_header (&header, &dummy, read_header_x_global)
1444 != HEADER_SUCCESS_EXTENDED)
1446 WARN ((0, 0, _("This does not look like a tar archive")));
1447 return false;
1450 xheader_decode (&dummy); /* decodes values from the global header */
1451 tar_stat_destroy (&dummy);
1453 /* The initial global header must be immediately followed by
1454 an extended PAX header for the first member in this volume.
1455 However, in some cases tar may split volumes in the middle
1456 of a PAX header. This is incorrect, and should be fixed
1457 in the future versions. In the meantime we must be
1458 prepared to correctly list and extract such archives.
1460 If this happens, the following call to read_header returns
1461 HEADER_FAILURE, which is ignored.
1463 See also tests/multiv07.at */
1465 switch (read_header (&header, &dummy, read_header_auto))
1467 case HEADER_SUCCESS:
1468 set_next_block_after (header);
1469 break;
1471 case HEADER_FAILURE:
1472 break;
1474 default:
1475 WARN ((0, 0, _("This does not look like a tar archive")));
1476 return false;
1478 break;
1481 case GNUTYPE_VOLHDR:
1482 if (!read_header0 (&dummy))
1483 return false;
1484 tar_stat_destroy (&dummy);
1485 ASSIGN_STRING_N (&volume_label, current_header->header.name);
1486 set_next_block_after (header);
1487 header = find_next_block ();
1488 if (! (header && header->header.typeflag == GNUTYPE_MULTIVOL))
1489 break;
1490 FALLTHROUGH;
1491 case GNUTYPE_MULTIVOL:
1492 if (!read_header0 (&dummy))
1493 return false;
1494 tar_stat_destroy (&dummy);
1495 ASSIGN_STRING_N (&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;
1502 default:
1503 break;
1506 if (bufmap_head)
1508 uintmax_t s;
1509 if (!continued_file_name)
1511 WARN ((0, 0, _("%s is not continued on this volume"),
1512 quote (bufmap_head->file_name)));
1513 return false;
1516 if (strcmp (continued_file_name, bufmap_head->file_name))
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
1527 WARN ((0, 0, _("%s is not continued on this volume"),
1528 quote (bufmap_head->file_name)));
1529 return false;
1533 s = continued_file_size + continued_file_offset;
1535 if (bufmap_head->sizetotal != s || s < continued_file_offset)
1537 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1538 char s1buf[UINTMAX_STRSIZE_BOUND];
1539 char s2buf[UINTMAX_STRSIZE_BOUND];
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;
1549 if (bufmap_head->sizetotal - bufmap_head->sizeleft !=
1550 continued_file_offset)
1552 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1553 char s1buf[UINTMAX_STRSIZE_BOUND];
1554 char s2buf[UINTMAX_STRSIZE_BOUND];
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)));
1561 return false;
1565 increase_volume_number ();
1566 return true;
1570 char *
1571 drop_volume_label_suffix (const char *label)
1573 static char const VOLUME_TEXT[] = " Volume ";
1574 idx_t VOLUME_TEXT_LEN = sizeof VOLUME_TEXT - 1;
1575 idx_t prefix_len = 0;
1577 for (idx_t i = 0; label[i]; i++)
1578 if (!c_isdigit (label[i]))
1579 prefix_len = i + 1;
1581 ptrdiff_t len = prefix_len - VOLUME_TEXT_LEN;
1582 return (0 <= len && memcmp (label + len, VOLUME_TEXT, VOLUME_TEXT_LEN) == 0
1583 ? ximemdup0 (label, len)
1584 : NULL);
1587 /* Check LABEL against the volume label, seen as a globbing
1588 pattern. Return true if the pattern matches. In case of failure,
1589 retry matching a volume sequence number before giving up in
1590 multi-volume mode. */
1591 static bool
1592 check_label_pattern (const char *label)
1594 char *string;
1595 bool result = false;
1597 if (fnmatch (volume_label_option, label, 0) == 0)
1598 return true;
1600 if (!multi_volume_option)
1601 return false;
1603 string = drop_volume_label_suffix (label);
1604 if (string)
1606 result = fnmatch (string, volume_label_option, 0) == 0;
1607 free (string);
1609 return result;
1612 /* Check if the next block contains a volume label and if this matches
1613 the one given in the command line */
1614 static void
1615 match_volume_label (void)
1617 if (!volume_label)
1619 union block *label = find_next_block ();
1621 if (!label)
1622 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1623 quote (volume_label_option)));
1624 if (label->header.typeflag == GNUTYPE_VOLHDR)
1626 ASSIGN_STRING_N (&volume_label, label->header.name);
1628 else if (label->header.typeflag == XGLTYPE)
1630 struct tar_stat_info st;
1631 tar_stat_init (&st);
1632 xheader_read (&st.xhdr, label,
1633 OFF_FROM_HEADER (label->header.size));
1634 xheader_decode (&st);
1635 tar_stat_destroy (&st);
1639 if (!volume_label)
1640 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1641 quote (volume_label_option)));
1643 if (!check_label_pattern (volume_label))
1644 FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1645 quote_n (0, volume_label),
1646 quote_n (1, volume_label_option)));
1649 /* Mark the archive with volume label STR. */
1650 static void
1651 _write_volume_label (const char *str)
1653 if (archive_format == POSIX_FORMAT)
1654 xheader_store ("GNU.volume.label", &dummy, str);
1655 else
1657 union block *label = find_next_block ();
1659 assume (label);
1660 memset (label, 0, BLOCKSIZE);
1662 strcpy (label->header.name, str);
1663 assign_string (&current_stat_info.file_name, label->header.name);
1664 current_stat_info.had_trailing_slash =
1665 strip_trailing_slashes (current_stat_info.file_name);
1667 label->header.typeflag = GNUTYPE_VOLHDR;
1668 TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1669 finish_header (&current_stat_info, label, -1);
1670 set_next_block_after (label);
1674 #define VOL_SUFFIX "Volume"
1676 /* Add a volume label to a part of multi-volume archive */
1677 static void
1678 add_volume_label (void)
1680 char buf[UINTMAX_STRSIZE_BOUND];
1681 char *p = STRINGIFY_BIGINT (volno, buf);
1682 char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1683 + strlen (p) + 2);
1684 sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1685 _write_volume_label (s);
1686 free (s);
1689 static void
1690 add_chunk_header (struct bufmap *map)
1692 if (archive_format == POSIX_FORMAT)
1694 union block *blk;
1695 struct tar_stat_info st;
1697 memset (&st, 0, sizeof st);
1698 st.orig_file_name = st.file_name = map->file_name;
1699 st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1700 st.stat.st_uid = getuid ();
1701 st.stat.st_gid = getgid ();
1702 st.orig_file_name = xheader_format_name (&st,
1703 "%d/GNUFileParts/%f.%n",
1704 volno);
1705 st.file_name = st.orig_file_name;
1706 st.archive_file_size = st.stat.st_size = map->sizeleft;
1708 blk = start_header (&st);
1709 if (!blk)
1710 abort (); /* FIXME */
1711 simple_finish_header (write_extended (false, &st, blk));
1712 free (st.orig_file_name);
1717 /* Add a volume label to the current archive */
1718 static void
1719 write_volume_label (void)
1721 if (multi_volume_option)
1722 add_volume_label ();
1723 else
1724 _write_volume_label (volume_label_option);
1727 /* Write GNU multi-volume header */
1728 static void
1729 gnu_add_multi_volume_header (struct bufmap *map)
1731 int tmp;
1732 union block *block = find_next_block ();
1733 size_t len = strlen (map->file_name);
1735 if (len > NAME_FIELD_SIZE)
1737 WARN ((0, 0,
1738 _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1739 quotearg_colon (map->file_name)));
1740 len = NAME_FIELD_SIZE;
1743 memset (block, 0, BLOCKSIZE);
1745 memcpy (block->header.name, map->file_name, len);
1746 block->header.typeflag = GNUTYPE_MULTIVOL;
1748 OFF_TO_CHARS (map->sizeleft, block->header.size);
1749 OFF_TO_CHARS (map->sizetotal - map->sizeleft,
1750 block->oldgnu_header.offset);
1752 tmp = verbose_option;
1753 verbose_option = 0;
1754 finish_header (&current_stat_info, block, -1);
1755 verbose_option = tmp;
1756 set_next_block_after (block);
1759 /* Add a multi volume header to the current archive. The exact header format
1760 depends on the archive format. */
1761 static void
1762 add_multi_volume_header (struct bufmap *map)
1764 if (archive_format == POSIX_FORMAT)
1766 off_t d = map->sizetotal - map->sizeleft;
1767 xheader_store ("GNU.volume.filename", &dummy, map->file_name);
1768 xheader_store ("GNU.volume.size", &dummy, &map->sizeleft);
1769 xheader_store ("GNU.volume.offset", &dummy, &d);
1771 else
1772 gnu_add_multi_volume_header (map);
1776 /* Low-level flush functions */
1778 /* Simple flush read (no multi-volume or label extensions) */
1779 static void
1780 simple_flush_read (void)
1782 size_t status; /* result from system call */
1784 checkpoint_run (false);
1786 /* Clear the count of errors. This only applies to a single call to
1787 flush_read. */
1789 read_error_count = 0; /* clear error count */
1791 if (write_archive_to_stdout && record_start_block != 0)
1793 archive = STDOUT_FILENO;
1794 status = sys_write_archive_buffer ();
1795 archive = STDIN_FILENO;
1796 if (status != record_size)
1797 archive_write_error (status);
1800 for (;;)
1802 status = rmtread (archive, record_start->buffer, record_size);
1803 if (status == record_size)
1805 records_read++;
1806 return;
1808 if (status == SAFE_READ_ERROR)
1810 archive_read_error ();
1811 continue; /* try again */
1813 break;
1815 short_read (status);
1818 /* Simple flush write (no multi-volume or label extensions) */
1819 static void
1820 simple_flush_write (MAYBE_UNUSED size_t level)
1822 ssize_t status;
1824 status = _flush_write ();
1825 if (status != record_size)
1826 archive_write_error (status);
1827 else
1829 records_written++;
1830 bytes_written += status;
1835 /* GNU flush functions. These support multi-volume and archive labels in
1836 GNU and PAX archive formats. */
1838 static void
1839 _gnu_flush_read (void)
1841 size_t status; /* result from system call */
1843 checkpoint_run (false);
1845 /* Clear the count of errors. This only applies to a single call to
1846 flush_read. */
1848 read_error_count = 0; /* clear error count */
1850 if (write_archive_to_stdout && record_start_block != 0)
1852 archive = STDOUT_FILENO;
1853 status = sys_write_archive_buffer ();
1854 archive = STDIN_FILENO;
1855 if (status != record_size)
1856 archive_write_error (status);
1859 for (;;)
1861 status = rmtread (archive, record_start->buffer, record_size);
1862 if (status == record_size)
1864 records_read++;
1865 return;
1868 /* The condition below used to include
1869 || (status > 0 && !read_full_records)
1870 This is incorrect since even if new_volume() succeeds, the
1871 subsequent call to rmtread will overwrite the chunk of data
1872 already read in the buffer, so the processing will fail */
1873 if ((status == 0
1874 || (status == SAFE_READ_ERROR && errno == ENOSPC))
1875 && multi_volume_option)
1877 while (!try_new_volume ())
1879 if (current_block == record_end)
1880 /* Necessary for blocking_factor == 1 */
1881 flush_archive();
1882 return;
1884 else if (status == SAFE_READ_ERROR)
1886 archive_read_error ();
1887 continue;
1889 break;
1891 short_read (status);
1894 static void
1895 gnu_flush_read (void)
1897 flush_read_ptr = simple_flush_read; /* Avoid recursion */
1898 _gnu_flush_read ();
1899 flush_read_ptr = gnu_flush_read;
1902 static void
1903 _gnu_flush_write (size_t buffer_level)
1905 ssize_t status;
1906 union block *header;
1907 char *copy_ptr;
1908 size_t copy_size;
1909 size_t bufsize;
1910 struct bufmap *map;
1912 status = _flush_write ();
1913 if (status != record_size && !multi_volume_option)
1914 archive_write_error (status);
1915 else
1917 if (status)
1918 records_written++;
1919 bytes_written += status;
1922 if (status == record_size)
1924 return;
1927 map = bufmap_locate (status);
1929 if (status % BLOCKSIZE)
1931 ERROR ((0, 0, _("write did not end on a block boundary")));
1932 archive_write_error (status);
1935 /* In multi-volume mode. */
1936 /* ENXIO is for the UNIX PC. */
1937 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1938 archive_write_error (status);
1940 if (!new_volume (ACCESS_WRITE))
1941 return;
1943 tar_stat_destroy (&dummy);
1945 increase_volume_number ();
1946 prev_written += bytes_written;
1947 bytes_written = 0;
1949 copy_ptr = record_start->buffer + status;
1950 copy_size = buffer_level - status;
1952 /* Switch to the next buffer */
1953 record_index = !record_index;
1954 init_buffer ();
1956 inhibit_map = 1;
1958 if (volume_label_option)
1959 add_volume_label ();
1961 if (map)
1962 add_multi_volume_header (map);
1964 write_extended (true, &dummy, find_next_block ());
1965 tar_stat_destroy (&dummy);
1967 if (map)
1968 add_chunk_header (map);
1969 header = find_next_block ();
1970 bufmap_reset (map, header - record_start);
1971 bufsize = available_space_after (header);
1972 inhibit_map = 0;
1973 while (bufsize < copy_size)
1975 memcpy (header->buffer, copy_ptr, bufsize);
1976 copy_ptr += bufsize;
1977 copy_size -= bufsize;
1978 set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
1979 header = find_next_block ();
1980 bufsize = available_space_after (header);
1982 memcpy (header->buffer, copy_ptr, copy_size);
1983 memset (header->buffer + copy_size, 0, bufsize - copy_size);
1984 set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
1985 find_next_block ();
1988 static void
1989 gnu_flush_write (size_t buffer_level)
1991 flush_write_ptr = simple_flush_write; /* Avoid recursion */
1992 _gnu_flush_write (buffer_level);
1993 flush_write_ptr = gnu_flush_write;
1996 void
1997 flush_read (void)
1999 flush_read_ptr ();
2002 void
2003 flush_write (void)
2005 flush_write_ptr (record_size);
2008 void
2009 open_archive (enum access_mode wanted_access)
2011 flush_read_ptr = gnu_flush_read;
2012 flush_write_ptr = gnu_flush_write;
2014 _open_archive (wanted_access);
2015 switch (wanted_access)
2017 case ACCESS_READ:
2018 case ACCESS_UPDATE:
2019 if (volume_label_option)
2020 match_volume_label ();
2021 break;
2023 case ACCESS_WRITE:
2024 records_written = 0;
2025 if (volume_label_option)
2026 write_volume_label ();
2027 break;
2029 set_volume_start_time ();