Debian Codegraph @

src/buffer.c

raw ◀ ▶
1 Debian patch touch this file
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 (&current_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 records_read++;
991 }
992
993 /* Flush the current buffer to/from the archive. */
994 void
995 flush_archive (void)
996 {
997 size_t buffer_level;
998
999 if (access_mode == ACCESS_READ && time_to_start_writing)
1000 {
1001 access_mode = ACCESS_WRITE;
1002 time_to_start_writing = false;
1003 backspace_output ();
1004 if (record_end - record_start < blocking_factor)
1005 {
1006 memset (record_end, 0,
1007 (blocking_factor - (record_end - record_start))
1008 * BLOCKSIZE);
1009 record_end = record_start + blocking_factor;
1010 return;
1011 }
1012 }
1013
1014 buffer_level = current_block->buffer - record_start->buffer;
1015 record_start_block += record_end - record_start;
1016 current_block = record_start;
1017 record_end = record_start + blocking_factor;
1018
1019 switch (access_mode)
1020 {
1021 case ACCESS_READ:
1022 flush_read ();
1023 break;
1024
1025 case ACCESS_WRITE:
1026 flush_write_ptr (buffer_level);
1027 break;
1028
1029 case ACCESS_UPDATE:
1030 abort ();
1031 }
1032 }
1033
1034 /* Backspace the archive descriptor by one record worth. If it's a
1035 tape, MTIOCTOP will work. If it's something else, try to seek on
1036 it. If we can't seek, we lose! */
1037 static void
1038 backspace_output (void)
1039 {
1040 if (mtioseek (false, -1))
1041 return;
1042
1043 {
1044 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1045
1046 /* Seek back to the beginning of this record and start writing there. */
1047
1048 position -= record_end->buffer - record_start->buffer;
1049 if (position < 0)
1050 position = 0;
1051 if (rmtlseek (archive, position, SEEK_SET) != position)
1052 {
1053 /* Lseek failed. Try a different method. */
1054
1055 WARN ((0, 0,
1056 _("Cannot backspace archive file; it may be unreadable without -i")));
1057
1058 /* Replace the first part of the record with NULs. */
1059
1060 if (record_start->buffer != output_start)
1061 memset (record_start->buffer, 0,
1062 output_start - record_start->buffer);
1063 }
1064 }
1065 }
1066
1067 off_t
1068 seek_archive (off_t size)
1069 {
1070 off_t start = current_block_ordinal ();
1071 off_t offset;
1072 off_t nrec, nblk;
1073 off_t skipped = (blocking_factor - (current_block - record_start))
1074 * BLOCKSIZE;
1075
1076 if (size <= skipped)
1077 return 0;
1078
1079 /* Compute number of records to skip */
1080 nrec = (size - skipped) / record_size;
1081 if (nrec == 0)
1082 return 0;
1083 offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
1084 if (offset < 0)
1085 return offset;
1086
1087 if (offset % record_size)
1088 FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
1089
1090 /* Convert to number of records */
1091 offset /= BLOCKSIZE;
1092 /* Compute number of skipped blocks */
1093 nblk = offset - start;
1094
1095 /* Update buffering info */
1096 records_read += nblk / blocking_factor;
1097 record_start_block = offset - blocking_factor;
1098 current_block = record_end;
1099
1100 return nblk;
1101 }
1102
1103 /* Close the archive file. */
1104 void
1105 close_archive (void)
1106 {
1107 if (time_to_start_writing || access_mode == ACCESS_WRITE)
1108 {
1109 do
1110 flush_archive ();
1111 while (current_block > record_start);
1112 }
1113
1114 compute_duration ();
1115 if (verify_option)
1116 verify_volume ();
1117
1118 if (rmtclose (archive) != 0)
1119 close_error (*archive_name_cursor);
1120
1121 sys_wait_for_child (child_pid, hit_eof);
1122
1123 tar_stat_destroy (&current_stat_info);
1124 free (record_buffer[0]);
1125 free (record_buffer[1]);
1126 bufmap_free (NULL);
1127 }
1128
1129 void
1130 write_fatal_details (char const *name, ssize_t status, size_t size)
1131 {
1132 write_error_details (name, status, size);
1133 if (rmtclose (archive) != 0)
1134 close_error (*archive_name_cursor);
1135 sys_wait_for_child (child_pid, false);
1136 fatal_exit ();
1137 }
1138
1139 /* Called to initialize the global volume number. */
1140 void
1141 init_volume_number (void)
1142 {
1143 FILE *file = fopen (volno_file_option, "r");
1144
1145 if (file)
1146 {
1147 if (fscanf (file, "%d", &global_volno) != 1
1148 || global_volno < 0)
1149 FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1150 quotearg_colon (volno_file_option)));
1151 if (ferror (file))
1152 read_error (volno_file_option);
1153 if (fclose (file) != 0)
1154 close_error (volno_file_option);
1155 }
1156 else if (errno != ENOENT)
1157 open_error (volno_file_option);
1158 }
1159
1160 /* Called to write out the closing global volume number. */
1161 void
1162 closeout_volume_number (void)
1163 {
1164 FILE *file = fopen (volno_file_option, "w");
1165
1166 if (file)
1167 {
1168 fprintf (file, "%d\n", global_volno);
1169 if (ferror (file))
1170 write_error (volno_file_option);
1171 if (fclose (file) != 0)
1172 close_error (volno_file_option);
1173 }
1174 else
1175 open_error (volno_file_option);
1176 }
1177
1178
1179 static void
1180 increase_volume_number (void)
1181 {
1182 global_volno++;
1183 if (global_volno < 0)
1184 FATAL_ERROR ((0, 0, _("Volume number overflow")));
1185 volno++;
1186 }
1187
1188 static void
1189 change_tape_menu (FILE *read_file)
1190 {
1191 char *input_buffer = NULL;
1192 size_t size = 0;
1193 bool stop = false;
1194
1195 while (!stop)
1196 {
1197 fputc ('\007', stderr);
1198 fprintf (stderr,
1199 _("Prepare volume #%d for %s and hit return: "),
1200 global_volno + 1, quote (*archive_name_cursor));
1201 fflush (stderr);
1202
1203 if (getline (&input_buffer, &size, read_file) <= 0)
1204 {
1205 WARN ((0, 0, _("EOF where user reply was expected")));
1206
1207 if (subcommand_option != EXTRACT_SUBCOMMAND
1208 && subcommand_option != LIST_SUBCOMMAND
1209 && subcommand_option != DIFF_SUBCOMMAND)
1210 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1211
1212 fatal_exit ();
1213 }
1214
1215 if (input_buffer[0] == '\n'
1216 || input_buffer[0] == 'y'
1217 || input_buffer[0] == 'Y')
1218 break;
1219
1220 switch (input_buffer[0])
1221 {
1222 case '?':
1223 {
1224 fprintf (stderr, _("\
1225 n name Give a new file name for the next (and subsequent) volume(s)\n\
1226 q Abort tar\n\
1227 y or newline Continue operation\n"));
1228 if (!restrict_option)
1229 fprintf (stderr, _(" ! Spawn a subshell\n"));
1230 fprintf (stderr, _(" ? Print this list\n"));
1231 }
1232 break;
1233
1234 case 'q':
1235 /* Quit. */
1236
1237 WARN ((0, 0, _("No new volume; exiting.\n")));
1238
1239 if (subcommand_option != EXTRACT_SUBCOMMAND
1240 && subcommand_option != LIST_SUBCOMMAND
1241 && subcommand_option != DIFF_SUBCOMMAND)
1242 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1243
1244 fatal_exit ();
1245
1246 case 'n':
1247 /* Get new file name. */
1248
1249 {
1250 char *name;
1251 char *cursor;
1252
1253 for (name = input_buffer + 1;
1254 *name == ' ' || *name == '\t';
1255 name++)
1256 ;
1257
1258 for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1259 ;
1260 *cursor = '\0';
1261
1262 if (name[0])
1263 {
1264 /* FIXME: the following allocation is never reclaimed. */
1265 *archive_name_cursor = xstrdup (name);
1266 stop = true;
1267 }
1268 else
1269 fprintf (stderr, "%s",
1270 _("File name not specified. Try again.\n"));
1271 }
1272 break;
1273
1274 case '!':
1275 if (!restrict_option)
1276 {
1277 sys_spawn_shell ();
1278 break;
1279 }
1280 FALLTHROUGH;
1281 default:
1282 fprintf (stderr, _("Invalid input. Type ? for help.\n"));
1283 }
1284 }
1285 free (input_buffer);
1286 }
1287
1288 /* We've hit the end of the old volume. Close it and open the next one.
1289 Return nonzero on success.
1290 */
1291 static bool
1292 new_volume (enum access_mode mode)
1293 {
1294 static FILE *read_file;
1295 static int looped;
1296 int prompt;
1297
1298 if (!read_file && !info_script_option)
1299 /* FIXME: if fopen is used, it will never be closed. */
1300 read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1301
1302 if (now_verifying)
1303 return false;
1304 if (verify_option)
1305 verify_volume ();
1306
1307 assign_null (&volume_label);
1308 assign_null (&continued_file_name);
1309 continued_file_size = continued_file_offset = 0;
1310 current_block = record_start;
1311
1312 if (rmtclose (archive) != 0)
1313 close_error (*archive_name_cursor);
1314
1315 archive_name_cursor++;
1316 if (archive_name_cursor == archive_name_array + archive_names)
1317 {
1318 archive_name_cursor = archive_name_array;
1319 looped = 1;
1320 }
1321 prompt = looped;
1322
1323 tryagain:
1324 if (prompt)
1325 {
1326 /* We have to prompt from now on. */
1327
1328 if (info_script_option)
1329 {
1330 if (volno_file_option)
1331 closeout_volume_number ();
1332 if (sys_exec_info_script (archive_name_cursor, global_volno+1))
1333 FATAL_ERROR ((0, 0, _("%s command failed"),
1334 quote (info_script_option)));
1335 }
1336 else
1337 change_tape_menu (read_file);
1338 }
1339
1340 if (strcmp (archive_name_cursor[0], "-") == 0)
1341 {
1342 read_full_records = true;
1343 archive = STDIN_FILENO;
1344 }
1345 else if (verify_option)
1346 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1347 rsh_command_option);
1348 else
1349 switch (mode)
1350 {
1351 case ACCESS_READ:
1352 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1353 rsh_command_option);
1354 break;
1355
1356 case ACCESS_WRITE:
1357 if (backup_option)
1358 maybe_backup_file (*archive_name_cursor, 1);
1359 archive = rmtcreat (*archive_name_cursor, MODE_RW,
1360 rsh_command_option);
1361 break;
1362
1363 case ACCESS_UPDATE:
1364 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1365 rsh_command_option);
1366 break;
1367 }
1368
1369 if (archive < 0)
1370 {
1371 open_warn (*archive_name_cursor);
1372 if (!verify_option && mode == ACCESS_WRITE && backup_option)
1373 undo_last_backup ();
1374 prompt = 1;
1375 goto tryagain;
1376 }
1377
1378 get_archive_status (mode, false);
1379
1380 return true;
1381 }
1382
1383 static bool
1384 read_header0 (struct tar_stat_info *info)
1385 {
1386 enum read_header rc;
1387
1388 tar_stat_init (info);
1389 rc = read_header (&current_header, info, read_header_auto);
1390 if (rc == HEADER_SUCCESS)
1391 {
1392 set_next_block_after (current_header);
1393 return true;
1394 }
1395 ERROR ((0, 0, _("This does not look like a tar archive")));
1396 return false;
1397 }
1398
1399 static bool
1400 try_new_volume (void)
1401 {
1402 size_t status;
1403 union block *header;
1404 enum access_mode acc;
1405
1406 switch (subcommand_option)
1407 {
1408 case APPEND_SUBCOMMAND:
1409 case CAT_SUBCOMMAND:
1410 case UPDATE_SUBCOMMAND:
1411 acc = ACCESS_UPDATE;
1412 break;
1413
1414 default:
1415 acc = ACCESS_READ;
1416 break;
1417 }
1418
1419 if (!new_volume (acc))
1420 return true;
1421
1422 while ((status = rmtread (archive, record_start->buffer, record_size))
1423 == SAFE_READ_ERROR)
1424 archive_read_error ();
1425
1426 if (status != record_size)
1427 short_read (status);
1428
1429 header = find_next_block ();
1430 if (!header)
1431 {
1432 WARN ((0, 0, _("This does not look like a tar archive")));
1433 return false;
1434 }
1435
1436 switch (header->header.typeflag)
1437 {
1438 case XGLTYPE:
1439 {
1440 tar_stat_init (&dummy);
1441 if (read_header (&header, &dummy, read_header_x_global)
1442 != HEADER_SUCCESS_EXTENDED)
1443 {
1444 WARN ((0, 0, _("This does not look like a tar archive")));
1445 return false;
1446 }
1447
1448 xheader_decode (&dummy); /* decodes values from the global header */
1449 tar_stat_destroy (&dummy);
1450
1451 /* The initial global header must be immediately followed by
1452 an extended PAX header for the first member in this volume.
1453 However, in some cases tar may split volumes in the middle
1454 of a PAX header. This is incorrect, and should be fixed
1455 in the future versions. In the meantime we must be
1456 prepared to correctly list and extract such archives.
1457
1458 If this happens, the following call to read_header returns
1459 HEADER_FAILURE, which is ignored.
1460
1461 See also tests/multiv07.at */
1462
1463 switch (read_header (&header, &dummy, read_header_auto))
1464 {
1465 case HEADER_SUCCESS:
1466 set_next_block_after (header);
1467 break;
1468
1469 case HEADER_FAILURE:
1470 break;
1471
1472 default:
1473 WARN ((0, 0, _("This does not look like a tar archive")));
1474 return false;
1475 }
1476 break;
1477 }
1478
1479 case GNUTYPE_VOLHDR:
1480 if (!read_header0 (&dummy))
1481 return false;
1482 tar_stat_destroy (&dummy);
1483 ASSIGN_STRING_N (&volume_label, current_header->header.name);
1484 set_next_block_after (header);
1485 header = find_next_block ();
1486 if (! (header && header->header.typeflag == GNUTYPE_MULTIVOL))
1487 break;
1488 FALLTHROUGH;
1489 case GNUTYPE_MULTIVOL:
1490 if (!read_header0 (&dummy))
1491 return false;
1492 tar_stat_destroy (&dummy);
1493 ASSIGN_STRING_N (&continued_file_name, current_header->header.name);
1494 continued_file_size =
1495 UINTMAX_FROM_HEADER (current_header->header.size);
1496 continued_file_offset =
1497 UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
1498 break;
1499
1500 default:
1501 break;
1502 }
1503
1504 if (bufmap_head)
1505 {
1506 uintmax_t s;
1507 if (!continued_file_name)
1508 {
1509 WARN ((0, 0, _("%s is not continued on this volume"),
1510 quote (bufmap_head->file_name)));
1511 return false;
1512 }
1513
1514 if (strcmp (continued_file_name, bufmap_head->file_name))
1515 {
1516 if ((archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
1517 && strlen (bufmap_head->file_name) >= NAME_FIELD_SIZE
1518 && strncmp (continued_file_name, bufmap_head->file_name,
1519 NAME_FIELD_SIZE) == 0)
1520 WARN ((0, 0,
1521 _("%s is possibly continued on this volume: header contains truncated name"),
1522 quote (bufmap_head->file_name)));
1523 else
1524 {
1525 WARN ((0, 0, _("%s is not continued on this volume"),
1526 quote (bufmap_head->file_name)));
1527 return false;
1528 }
1529 }
1530
1531 s = continued_file_size + continued_file_offset;
1532
1533 if (bufmap_head->sizetotal != s || s < continued_file_offset)
1534 {
1535 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1536 char s1buf[UINTMAX_STRSIZE_BOUND];
1537 char s2buf[UINTMAX_STRSIZE_BOUND];
1538
1539 WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1540 quote (continued_file_name),
1541 STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1542 STRINGIFY_BIGINT (continued_file_size, s1buf),
1543 STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1544 return false;
1545 }
1546
1547 if (bufmap_head->sizetotal - bufmap_head->sizeleft !=
1548 continued_file_offset)
1549 {
1550 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1551 char s1buf[UINTMAX_STRSIZE_BOUND];
1552 char s2buf[UINTMAX_STRSIZE_BOUND];
1553
1554 WARN ((0, 0, _("This volume is out of sequence (%s - %s != %s)"),
1555 STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1556 STRINGIFY_BIGINT (bufmap_head->sizeleft, s1buf),
1557 STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1558
1559 return false;
1560 }
1561 }
1562
1563 increase_volume_number ();
1564 return true;
1565 }
1566
1567
1568 #define VOLUME_TEXT " Volume "
1569 #define VOLUME_TEXT_LEN (sizeof VOLUME_TEXT - 1)
1570
1571 char *
1572 drop_volume_label_suffix (const char *label)
1573 {
1574 const char *p;
1575 size_t len = strlen (label);
1576
1577 if (len < 1)
1578 return NULL;
1579
1580 for (p = label + len - 1; p > label && isdigit ((unsigned char) *p); p--)
1581 ;
1582 if (p > label && p - (VOLUME_TEXT_LEN - 1) > label)
1583 {
1584 p -= VOLUME_TEXT_LEN - 1;
1585 if (memcmp (p, VOLUME_TEXT, VOLUME_TEXT_LEN) == 0)
1586 {
1587 char *s = xmalloc ((len = p - label) + 1);
1588 memcpy (s, label, len);
1589 s[len] = 0;
1590 return s;
1591 }
1592 }
1593
1594 return NULL;
1595 }
1596
1597 /* Check LABEL against the volume label, seen as a globbing
1598 pattern. Return true if the pattern matches. In case of failure,
1599 retry matching a volume sequence number before giving up in
1600 multi-volume mode. */
1601 static bool
1602 check_label_pattern (const char *label)
1603 {
1604 char *string;
1605 bool result = false;
1606
1607 if (fnmatch (volume_label_option, label, 0) == 0)
1608 return true;
1609
1610 if (!multi_volume_option)
1611 return false;
1612
1613 string = drop_volume_label_suffix (label);
1614 if (string)
1615 {
1616 result = fnmatch (string, volume_label_option, 0) == 0;
1617 free (string);
1618 }
1619 return result;
1620 }
1621
1622 /* Check if the next block contains a volume label and if this matches
1623 the one given in the command line */
1624 static void
1625 match_volume_label (void)
1626 {
1627 if (!volume_label)
1628 {
1629 union block *label = find_next_block ();
1630
1631 if (!label)
1632 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1633 quote (volume_label_option)));
1634 if (label->header.typeflag == GNUTYPE_VOLHDR)
1635 {
1636 ASSIGN_STRING_N (&volume_label, label->header.name);
1637 }
1638 else if (label->header.typeflag == XGLTYPE)
1639 {
1640 struct tar_stat_info st;
1641 tar_stat_init (&st);
1642 xheader_read (&st.xhdr, label,
1643 OFF_FROM_HEADER (label->header.size));
1644 xheader_decode (&st);
1645 tar_stat_destroy (&st);
1646 }
1647 }
1648
1649 if (!volume_label)
1650 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1651 quote (volume_label_option)));
1652
1653 if (!check_label_pattern (volume_label))
1654 FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1655 quote_n (0, volume_label),
1656 quote_n (1, volume_label_option)));
1657 }
1658
1659 /* Mark the archive with volume label STR. */
1660 static void
1661 _write_volume_label (const char *str)
1662 {
1663 if (archive_format == POSIX_FORMAT)
1664 xheader_store ("GNU.volume.label", &dummy, str);
1665 else
1666 {
1667 union block *label = find_next_block ();
1668
1669 assume (label);
1670 memset (label, 0, BLOCKSIZE);
1671
1672 strcpy (label->header.name, str);
1673 assign_string (&current_stat_info.file_name, label->header.name);
1674 current_stat_info.had_trailing_slash =
1675 strip_trailing_slashes (current_stat_info.file_name);
1676
1677 label->header.typeflag = GNUTYPE_VOLHDR;
1678 TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1679 finish_header (&current_stat_info, label, -1);
1680 set_next_block_after (label);
1681 }
1682 }
1683
1684 #define VOL_SUFFIX "Volume"
1685
1686 /* Add a volume label to a part of multi-volume archive */
1687 static void
1688 add_volume_label (void)
1689 {
1690 char buf[UINTMAX_STRSIZE_BOUND];
1691 char *p = STRINGIFY_BIGINT (volno, buf);
1692 char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1693 + strlen (p) + 2);
1694 sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1695 _write_volume_label (s);
1696 free (s);
1697 }
1698
1699 static void
1700 add_chunk_header (struct bufmap *map)
1701 {
1702 if (archive_format == POSIX_FORMAT)
1703 {
1704 union block *blk;
1705 struct tar_stat_info st;
1706
1707 memset (&st, 0, sizeof st);
1708 st.orig_file_name = st.file_name = map->file_name;
1709 st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1710 st.stat.st_uid = getuid ();
1711 st.stat.st_gid = getgid ();
1712 st.orig_file_name = xheader_format_name (&st,
1713 "%d/GNUFileParts/%f.%n",
1714 volno);
1715 st.file_name = st.orig_file_name;
1716 st.archive_file_size = st.stat.st_size = map->sizeleft;
1717
1718 blk = start_header (&st);
1719 if (!blk)
1720 abort (); /* FIXME */
1721 simple_finish_header (write_extended (false, &st, blk));
1722 free (st.orig_file_name);
1723 }
1724 }
1725
1726
1727 /* Add a volume label to the current archive */
1728 static void
1729 write_volume_label (void)
1730 {
1731 if (multi_volume_option)
1732 add_volume_label ();
1733 else
1734 _write_volume_label (volume_label_option);
1735 }
1736
1737 /* Write GNU multi-volume header */
1738 static void
1739 gnu_add_multi_volume_header (struct bufmap *map)
1740 {
1741 int tmp;
1742 union block *block = find_next_block ();
1743 size_t len = strlen (map->file_name);
1744
1745 if (len > NAME_FIELD_SIZE)
1746 {
1747 WARN ((0, 0,
1748 _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1749 quotearg_colon (map->file_name)));
1750 len = NAME_FIELD_SIZE;
1751 }
1752
1753 memset (block, 0, BLOCKSIZE);
1754
1755 memcpy (block->header.name, map->file_name, len);
1756 block->header.typeflag = GNUTYPE_MULTIVOL;
1757
1758 OFF_TO_CHARS (map->sizeleft, block->header.size);
1759 OFF_TO_CHARS (map->sizetotal - map->sizeleft,
1760 block->oldgnu_header.offset);
1761
1762 tmp = verbose_option;
1763 verbose_option = 0;
1764 finish_header (&current_stat_info, block, -1);
1765 verbose_option = tmp;
1766 set_next_block_after (block);
1767 }
1768
1769 /* Add a multi volume header to the current archive. The exact header format
1770 depends on the archive format. */
1771 static void
1772 add_multi_volume_header (struct bufmap *map)
1773 {
1774 if (archive_format == POSIX_FORMAT)
1775 {
1776 off_t d = map->sizetotal - map->sizeleft;
1777 xheader_store ("GNU.volume.filename", &dummy, map->file_name);
1778 xheader_store ("GNU.volume.size", &dummy, &map->sizeleft);
1779 xheader_store ("GNU.volume.offset", &dummy, &d);
1780 }
1781 else
1782 gnu_add_multi_volume_header (map);
1783 }
1784
1785
1786 /* Low-level flush functions */
1787
1788 /* Simple flush read (no multi-volume or label extensions) */
1789 static void
1790 simple_flush_read (void)
1791 {
1792 size_t status; /* result from system call */
1793
1794 checkpoint_run (false);
1795
1796 /* Clear the count of errors. This only applies to a single call to
1797 flush_read. */
1798
1799 read_error_count = 0; /* clear error count */
1800
1801 if (write_archive_to_stdout && record_start_block != 0)
1802 {
1803 archive = STDOUT_FILENO;
1804 status = sys_write_archive_buffer ();
1805 archive = STDIN_FILENO;
1806 if (status != record_size)
1807 archive_write_error (status);
1808 }
1809
1810 for (;;)
1811 {
1812 status = rmtread (archive, record_start->buffer, record_size);
1813 if (status == record_size)
1814 {
1815 records_read++;
1816 return;
1817 }
1818 if (status == SAFE_READ_ERROR)
1819 {
1820 archive_read_error ();
1821 continue; /* try again */
1822 }
1823 break;
1824 }
1825 short_read (status);
1826 }
1827
1828 /* Simple flush write (no multi-volume or label extensions) */
1829 static void
1830 simple_flush_write (MAYBE_UNUSED size_t level)
1831 {
1832 ssize_t status;
1833
1834 status = _flush_write ();
1835 if (status != record_size)
1836 archive_write_error (status);
1837 else
1838 {
1839 records_written++;
1840 bytes_written += status;
1841 }
1842 }
1843
1844
1845 /* GNU flush functions. These support multi-volume and archive labels in
1846 GNU and PAX archive formats. */
1847
1848 static void
1849 _gnu_flush_read (void)
1850 {
1851 size_t status; /* result from system call */
1852
1853 checkpoint_run (false);
1854
1855 /* Clear the count of errors. This only applies to a single call to
1856 flush_read. */
1857
1858 read_error_count = 0; /* clear error count */
1859
1860 if (write_archive_to_stdout && record_start_block != 0)
1861 {
1862 archive = STDOUT_FILENO;
1863 status = sys_write_archive_buffer ();
1864 archive = STDIN_FILENO;
1865 if (status != record_size)
1866 archive_write_error (status);
1867 }
1868
1869 for (;;)
1870 {
1871 status = rmtread (archive, record_start->buffer, record_size);
1872 if (status == record_size)
1873 {
1874 records_read++;
1875 return;
1876 }
1877
1878 /* The condition below used to include
1879 || (status > 0 && !read_full_records)
1880 This is incorrect since even if new_volume() succeeds, the
1881 subsequent call to rmtread will overwrite the chunk of data
1882 already read in the buffer, so the processing will fail */
1883 if ((status == 0
1884 || (status == SAFE_READ_ERROR && errno == ENOSPC))
1885 && multi_volume_option)
1886 {
1887 while (!try_new_volume ())
1888 ;
1889 if (current_block == record_end)
1890 /* Necessary for blocking_factor == 1 */
1891 flush_archive();
1892 return;
1893 }
1894 else if (status == SAFE_READ_ERROR)
1895 {
1896 archive_read_error ();
1897 continue;
1898 }
1899 break;
1900 }
1901 short_read (status);
1902 }
1903
1904 static void
1905 gnu_flush_read (void)
1906 {
1907 flush_read_ptr = simple_flush_read; /* Avoid recursion */
1908 _gnu_flush_read ();
1909 flush_read_ptr = gnu_flush_read;
1910 }
1911
1912 static void
1913 _gnu_flush_write (size_t buffer_level)
1914 {
1915 ssize_t status;
1916 union block *header;
1917 char *copy_ptr;
1918 size_t copy_size;
1919 size_t bufsize;
1920 struct bufmap *map;
1921
1922 status = _flush_write ();
1923 if (status != record_size && !multi_volume_option)
1924 archive_write_error (status);
1925 else
1926 {
1927 if (status)
1928 records_written++;
1929 bytes_written += status;
1930 }
1931
1932 if (status == record_size)
1933 {
1934 return;
1935 }
1936
1937 map = bufmap_locate (status);
1938
1939 if (status % BLOCKSIZE)
1940 {
1941 ERROR ((0, 0, _("write did not end on a block boundary")));
1942 archive_write_error (status);
1943 }
1944
1945 /* In multi-volume mode. */
1946 /* ENXIO is for the UNIX PC. */
1947 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1948 archive_write_error (status);
1949
1950 if (!new_volume (ACCESS_WRITE))
1951 return;
1952
1953 tar_stat_destroy (&dummy);
1954
1955 increase_volume_number ();
1956 prev_written += bytes_written;
1957 bytes_written = 0;
1958
1959 copy_ptr = record_start->buffer + status;
1960 copy_size = buffer_level - status;
1961
1962 /* Switch to the next buffer */
1963 record_index = !record_index;
1964 init_buffer ();
1965
1966 inhibit_map = 1;
1967
1968 if (volume_label_option)
1969 add_volume_label ();
1970
1971 if (map)
1972 add_multi_volume_header (map);
1973
1974 write_extended (true, &dummy, find_next_block ());
1975 tar_stat_destroy (&dummy);
1976
1977 if (map)
1978 add_chunk_header (map);
1979 header = find_next_block ();
1980 bufmap_reset (map, header - record_start);
1981 bufsize = available_space_after (header);
1982 inhibit_map = 0;
1983 while (bufsize < copy_size)
1984 {
1985 memcpy (header->buffer, copy_ptr, bufsize);
1986 copy_ptr += bufsize;
1987 copy_size -= bufsize;
1988 set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
1989 header = find_next_block ();
1990 bufsize = available_space_after (header);
1991 }
1992 memcpy (header->buffer, copy_ptr, copy_size);
1993 memset (header->buffer + copy_size, 0, bufsize - copy_size);
1994 set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
1995 find_next_block ();
1996 }
1997
1998 static void
1999 gnu_flush_write (size_t buffer_level)
2000 {
2001 flush_write_ptr = simple_flush_write; /* Avoid recursion */
2002 _gnu_flush_write (buffer_level);
2003 flush_write_ptr = gnu_flush_write;
2004 }
2005
2006 void
2007 flush_read (void)
2008 {
2009 flush_read_ptr ();
2010 }
2011
2012 void
2013 flush_write (void)
2014 {
2015 flush_write_ptr (record_size);
2016 }
2017
2018 void
2019 open_archive (enum access_mode wanted_access)
2020 {
2021 flush_read_ptr = gnu_flush_read;
2022 flush_write_ptr = gnu_flush_write;
2023
2024 _open_archive (wanted_access);
2025 switch (wanted_access)
2026 {
2027 case ACCESS_READ:
2028 case ACCESS_UPDATE:
2029 if (volume_label_option)
2030 match_volume_label ();
2031 break;
2032
2033 case ACCESS_WRITE:
2034 records_written = 0;
2035 if (volume_label_option)
2036 write_volume_label ();
2037 break;
2038 }
2039 set_volume_start_time ();
2040 }