]> Dogcows Code - chaz/tar/blob - src/buffer.c
Bugfix. Changes introduced 2004-11-26 broke extraction from stdin.
[chaz/tar] / src / buffer.c
1 /* Buffer management for tar.
2
3 Copyright (C) 1988, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001,
4 2003, 2004 Free Software Foundation, Inc.
5
6 Written by John Gilmore, on 1985-08-25.
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
16 Public License for more details.
17
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21
22 #include <system.h>
23
24 #include <signal.h>
25
26 #include <fnmatch.h>
27 #include <human.h>
28 #include <quotearg.h>
29
30 #include "common.h"
31 #include <rmt.h>
32
33 /* Number of retries before giving up on read. */
34 #define READ_ERROR_MAX 10
35
36 /* Globbing pattern to append to volume label if initial match failed. */
37 #define VOLUME_LABEL_APPEND " Volume [1-9]*"
38 \f
39 /* Variables. */
40
41 static tarlong prev_written; /* bytes written on previous volumes */
42 static tarlong bytes_written; /* bytes written on this volume */
43 static void *record_buffer; /* allocated memory */
44
45 /* FIXME: The following variables should ideally be static to this
46 module. However, this cannot be done yet. The cleanup continues! */
47
48 union block *record_start; /* start of record of archive */
49 union block *record_end; /* last+1 block of archive record */
50 union block *current_block; /* current block of archive */
51 enum access_mode access_mode; /* how do we handle the archive */
52 off_t records_read; /* number of records read from this archive */
53 off_t records_written; /* likewise, for records written */
54
55 static off_t record_start_block; /* block ordinal at record_start */
56
57 /* Where we write list messages (not errors, not interactions) to. */
58 FILE *stdlis;
59
60 static void backspace_output (void);
61 static bool new_volume (enum access_mode);
62
63 /* PID of child program, if compress_option or remote archive access. */
64 static pid_t child_pid;
65
66 /* Error recovery stuff */
67 static int read_error_count;
68
69 /* Have we hit EOF yet? */
70 static bool hit_eof;
71
72 /* Checkpointing counter */
73 static int checkpoint;
74
75 static bool read_full_records = false;
76 static bool reading_from_pipe = false;
77
78 /* We're reading, but we just read the last block and it's time to update.
79 Declared in update.c
80
81 As least EXTERN like this one as possible. (?? --gray)
82 FIXME: Either eliminate it or move it to common.h.
83 */
84 extern bool time_to_start_writing;
85
86 static int volno = 1; /* which volume of a multi-volume tape we're
87 on */
88 static int global_volno = 1; /* volume number to print in external
89 messages */
90
91 /* The pointer save_name, which is set in function dump_file() of module
92 create.c, points to the original long filename instead of the new,
93 shorter mangled name that is set in start_header() of module create.c.
94 The pointer save_name is only used in multi-volume mode when the file
95 being processed is non-sparse; if a file is split between volumes, the
96 save_name is used in generating the LF_MULTIVOL record on the second
97 volume. (From Pierce Cantrell, 1991-08-13.) */
98
99 char *save_name; /* name of the file we are currently writing */
100 off_t save_totsize; /* total size of file we are writing, only
101 valid if save_name is nonzero */
102 off_t save_sizeleft; /* where we are in the file we are writing,
103 only valid if save_name is nonzero */
104
105 bool write_archive_to_stdout;
106
107 /* Used by flush_read and flush_write to store the real info about saved
108 names. */
109 static char *real_s_name;
110 static off_t real_s_totsize;
111 static off_t real_s_sizeleft;
112 \f
113 /* Functions. */
114
115 void
116 clear_read_error_count (void)
117 {
118 read_error_count = 0;
119 }
120
121 \f
122 /* Time-related functions */
123
124 double duration;
125
126 void
127 set_start_time ()
128 {
129 #if HAVE_CLOCK_GETTIME
130 if (clock_gettime (CLOCK_REALTIME, &start_timespec) != 0)
131 #endif
132 start_time = time (0);
133 }
134
135 void
136 compute_duration ()
137 {
138 #if HAVE_CLOCK_GETTIME
139 struct timespec now;
140 if (clock_gettime (CLOCK_REALTIME, &now) == 0)
141 duration += ((now.tv_sec - start_timespec.tv_sec)
142 + (now.tv_nsec - start_timespec.tv_nsec) / 1e9);
143 else
144 #endif
145 duration += time (NULL) - start_time;
146 set_start_time ();
147 }
148
149 \f
150 /* Compression detection */
151
152 enum compress_type {
153 ct_none,
154 ct_compress,
155 ct_gzip,
156 ct_bzip2
157 };
158
159 struct zip_magic
160 {
161 enum compress_type type;
162 unsigned char *magic;
163 size_t length;
164 char *program;
165 char *option;
166 };
167
168 static struct zip_magic magic[] = {
169 { ct_none, },
170 { ct_compress, "\037\235", 2, "compress", "-Z" },
171 { ct_gzip, "\037\213", 2, "gzip", "-z" },
172 { ct_bzip2, "BZh", 3, "bzip2", "-j" },
173 };
174
175 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
176
177 #define compress_option(t) magic[t].option
178 #define compress_program(t) magic[t].program
179
180 /* Check if the file FD is a compressed archive. FD is guaranteed to
181 represent a local file */
182 enum compress_type
183 check_compressed_archive ()
184 {
185 struct zip_magic *p;
186 size_t status;
187 bool sfr, srp;
188
189 /* Prepare global data needed for find_next_block: */
190 record_end = record_start; /* set up for 1st record = # 0 */
191 sfr = read_full_records;
192 read_full_records = true; /* Suppress fatal error on reading a partial
193 record */
194 srp = reading_from_pipe;
195 reading_from_pipe = true; /* Suppress warning message on reading a partial
196 record */
197 find_next_block ();
198
199 /* Restore global values */
200 read_full_records = sfr;
201 reading_from_pipe = srp;
202
203 if (tar_checksum (record_start) == HEADER_SUCCESS)
204 /* Probably a valid header */
205 return ct_none;
206
207 for (p = magic + 1; p < magic + NMAGIC; p++)
208 if (memcmp (record_start->buffer, p->magic, p->length) == 0)
209 {
210 hit_eof = false; /* It might have been set by find_next_block */
211 return p->type;
212 }
213
214 return ct_none;
215 }
216
217 /* Open an archive named archive_name_array[0]. Detect if it is
218 a compressed archive of known type and use corresponding decompression
219 program if so */
220 int
221 open_compressed_archive ()
222 {
223 enum compress_type type;
224
225 int fd = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
226 MODE_RW, rsh_command_option);
227 if (fd == -1 || _isrmt (fd))
228 return fd;
229
230 archive = fd;
231 type = check_compressed_archive ();
232
233 if (type == ct_none)
234 return fd;
235
236 /* FD is not needed any more */
237 rmtclose (fd);
238
239 /* Open compressed archive */
240 use_compress_program_option = compress_program (type);
241 child_pid = sys_child_open_for_uncompress ();
242 read_full_records = reading_from_pipe = true;
243
244 records_read = 0;
245 record_end = record_start; /* set up for 1st record = # 0 */
246
247 return archive;
248 }
249 \f
250
251 void
252 print_total_written (void)
253 {
254 tarlong written = prev_written + bytes_written;
255 char bytes[sizeof (tarlong) * CHAR_BIT];
256 char abbr[LONGEST_HUMAN_READABLE + 1];
257 char rate[LONGEST_HUMAN_READABLE + 1];
258
259 int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
260
261 sprintf (bytes, TARLONG_FORMAT, written);
262
263 /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*". */
264 fprintf (stderr, _("Total bytes written: %s (%s, %s/s)\n"), bytes,
265 human_readable (written, abbr, human_opts, 1, 1),
266 (0 < duration && written / duration < (uintmax_t) -1
267 ? human_readable (written / duration, rate, human_opts, 1, 1)
268 : "?"));
269 }
270
271 /* Compute and return the block ordinal at current_block. */
272 off_t
273 current_block_ordinal (void)
274 {
275 return record_start_block + (current_block - record_start);
276 }
277
278 /* If the EOF flag is set, reset it, as well as current_block, etc. */
279 void
280 reset_eof (void)
281 {
282 if (hit_eof)
283 {
284 hit_eof = false;
285 current_block = record_start;
286 record_end = record_start + blocking_factor;
287 access_mode = ACCESS_WRITE;
288 }
289 }
290
291 /* Return the location of the next available input or output block.
292 Return zero for EOF. Once we have returned zero, we just keep returning
293 it, to avoid accidentally going on to the next file on the tape. */
294 union block *
295 find_next_block (void)
296 {
297 if (current_block == record_end)
298 {
299 if (hit_eof)
300 return 0;
301 flush_archive ();
302 if (current_block == record_end)
303 {
304 hit_eof = true;
305 return 0;
306 }
307 }
308 return current_block;
309 }
310
311 /* Indicate that we have used all blocks up thru BLOCK. */
312 void
313 set_next_block_after (union block *block)
314 {
315 while (block >= current_block)
316 current_block++;
317
318 /* Do *not* flush the archive here. If we do, the same argument to
319 set_next_block_after could mean the next block (if the input record
320 is exactly one block long), which is not what is intended. */
321
322 if (current_block > record_end)
323 abort ();
324 }
325
326 /* Return the number of bytes comprising the space between POINTER
327 through the end of the current buffer of blocks. This space is
328 available for filling with data, or taking data from. POINTER is
329 usually (but not always) the result of previous find_next_block call. */
330 size_t
331 available_space_after (union block *pointer)
332 {
333 return record_end->buffer - pointer->buffer;
334 }
335
336 /* Close file having descriptor FD, and abort if close unsuccessful. */
337 void
338 xclose (int fd)
339 {
340 if (close (fd) != 0)
341 close_error (_("(pipe)"));
342 }
343
344 /* Check the LABEL block against the volume label, seen as a globbing
345 pattern. Return true if the pattern matches. In case of failure,
346 retry matching a volume sequence number before giving up in
347 multi-volume mode. */
348 static bool
349 check_label_pattern (union block *label)
350 {
351 char *string;
352 bool result;
353
354 if (! memchr (label->header.name, '\0', sizeof label->header.name))
355 return false;
356
357 if (fnmatch (volume_label_option, label->header.name, 0) == 0)
358 return true;
359
360 if (!multi_volume_option)
361 return false;
362
363 string = xmalloc (strlen (volume_label_option)
364 + sizeof VOLUME_LABEL_APPEND + 1);
365 strcpy (string, volume_label_option);
366 strcat (string, VOLUME_LABEL_APPEND);
367 result = fnmatch (string, label->header.name, 0) == 0;
368 free (string);
369 return result;
370 }
371
372 /* Open an archive file. The argument specifies whether we are
373 reading or writing, or both. */
374 void
375 open_archive (enum access_mode wanted_access)
376 {
377 int backed_up_flag = 0;
378
379 if (index_file_name)
380 {
381 stdlis = fopen (index_file_name, "w");
382 if (! stdlis)
383 open_error (index_file_name);
384 }
385 else
386 stdlis = to_stdout_option ? stderr : stdout;
387
388 if (record_size == 0)
389 FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
390
391 if (archive_names == 0)
392 FATAL_ERROR ((0, 0, _("No archive name given")));
393
394 tar_stat_destroy (&current_stat_info);
395 save_name = 0;
396 real_s_name = 0;
397
398 record_start =
399 page_aligned_alloc (&record_buffer,
400 (record_size
401 + (multi_volume_option ? 2 * BLOCKSIZE : 0)));
402 if (multi_volume_option)
403 record_start += 2;
404
405 current_block = record_start;
406 record_end = record_start + blocking_factor;
407 /* When updating the archive, we start with reading. */
408 access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
409
410 read_full_records = read_full_records_option;
411 reading_from_pipe = false;
412
413 records_read = 0;
414
415 if (use_compress_program_option)
416 {
417 switch (wanted_access)
418 {
419 case ACCESS_READ:
420 child_pid = sys_child_open_for_uncompress ();
421 read_full_records = reading_from_pipe = true;
422 record_end = record_start; /* set up for 1st record = # 0 */
423 break;
424
425 case ACCESS_WRITE:
426 child_pid = sys_child_open_for_compress ();
427 break;
428
429 case ACCESS_UPDATE:
430 abort (); /* Should not happen */
431 break;
432 }
433
434 if (wanted_access == ACCESS_WRITE
435 && strcmp (archive_name_array[0], "-") == 0)
436 stdlis = stderr;
437 }
438 else if (strcmp (archive_name_array[0], "-") == 0)
439 {
440 read_full_records = true; /* could be a pipe, be safe */
441 if (verify_option)
442 FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
443
444 switch (wanted_access)
445 {
446 case ACCESS_READ:
447 {
448 enum compress_type type;
449
450 archive = STDIN_FILENO;
451
452 type = check_compressed_archive (archive);
453 if (type != ct_none)
454 FATAL_ERROR ((0, 0,
455 _("Archive is compressed. Use %s option"),
456 compress_option (type)));
457 }
458 break;
459
460 case ACCESS_WRITE:
461 archive = STDOUT_FILENO;
462 stdlis = stderr;
463 break;
464
465 case ACCESS_UPDATE:
466 archive = STDIN_FILENO;
467 stdlis = stderr;
468 write_archive_to_stdout = true;
469 break;
470 }
471 }
472 else if (verify_option)
473 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
474 MODE_RW, rsh_command_option);
475 else
476 switch (wanted_access)
477 {
478 case ACCESS_READ:
479 archive = open_compressed_archive ();
480 break;
481
482 case ACCESS_WRITE:
483 if (backup_option)
484 {
485 maybe_backup_file (archive_name_array[0], 1);
486 backed_up_flag = 1;
487 }
488 archive = rmtcreat (archive_name_array[0], MODE_RW,
489 rsh_command_option);
490 break;
491
492 case ACCESS_UPDATE:
493 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
494 MODE_RW, rsh_command_option);
495 break;
496 }
497
498 if (archive < 0
499 || (! _isrmt (archive) && !sys_get_archive_stat ()))
500 {
501 int saved_errno = errno;
502
503 if (backed_up_flag)
504 undo_last_backup ();
505 errno = saved_errno;
506 open_fatal (archive_name_array[0]);
507 }
508
509 sys_detect_dev_null_output ();
510 sys_save_archive_dev_ino ();
511 SET_BINARY_MODE (archive);
512
513 switch (wanted_access)
514 {
515 case ACCESS_UPDATE:
516 records_written = 0;
517 record_end = record_start; /* set up for 1st record = # 0 */
518
519 case ACCESS_READ:
520 find_next_block (); /* read it in, check for EOF */
521
522 if (volume_label_option)
523 {
524 union block *label = find_next_block ();
525
526 if (!label)
527 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
528 quote (volume_label_option)));
529 if (!check_label_pattern (label))
530 FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
531 quote_n (0, label->header.name),
532 quote_n (1, volume_label_option)));
533 }
534 break;
535
536 case ACCESS_WRITE:
537 records_written = 0;
538 if (volume_label_option)
539 {
540 memset (record_start, 0, BLOCKSIZE);
541 if (multi_volume_option)
542 sprintf (record_start->header.name, "%s Volume 1",
543 volume_label_option);
544 else
545 strcpy (record_start->header.name, volume_label_option);
546
547 assign_string (&current_stat_info.file_name,
548 record_start->header.name);
549 current_stat_info.had_trailing_slash =
550 strip_trailing_slashes (current_stat_info.file_name);
551
552 record_start->header.typeflag = GNUTYPE_VOLHDR;
553 TIME_TO_CHARS (start_time, record_start->header.mtime);
554 finish_header (&current_stat_info, record_start, -1);
555 }
556 break;
557 }
558 }
559
560 /* Perform a write to flush the buffer. */
561 void
562 flush_write (void)
563 {
564 int copy_back;
565 ssize_t status;
566
567 if (checkpoint_option && !(++checkpoint % 10))
568 WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
569
570 if (tape_length_option && tape_length_option <= bytes_written)
571 {
572 errno = ENOSPC;
573 status = 0;
574 }
575 else if (dev_null_output)
576 status = record_size;
577 else
578 status = sys_write_archive_buffer ();
579 if (status != record_size && !multi_volume_option)
580 archive_write_error (status);
581
582 if (status > 0)
583 {
584 records_written++;
585 bytes_written += status;
586 }
587
588 if (status == record_size)
589 {
590 if (multi_volume_option)
591 {
592 if (save_name)
593 {
594 assign_string (&real_s_name, safer_name_suffix (save_name, false));
595 real_s_totsize = save_totsize;
596 real_s_sizeleft = save_sizeleft;
597 }
598 else
599 {
600 assign_string (&real_s_name, 0);
601 real_s_totsize = 0;
602 real_s_sizeleft = 0;
603 }
604 }
605 return;
606 }
607
608 /* We're multivol. Panic if we didn't get the right kind of response. */
609
610 /* ENXIO is for the UNIX PC. */
611 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
612 archive_write_error (status);
613
614 /* If error indicates a short write, we just move to the next tape. */
615
616 if (!new_volume (ACCESS_WRITE))
617 return;
618
619 if (totals_option)
620 prev_written += bytes_written;
621 bytes_written = 0;
622
623 if (volume_label_option && real_s_name)
624 {
625 copy_back = 2;
626 record_start -= 2;
627 }
628 else if (volume_label_option || real_s_name)
629 {
630 copy_back = 1;
631 record_start--;
632 }
633 else
634 copy_back = 0;
635
636 if (volume_label_option)
637 {
638 memset (record_start, 0, BLOCKSIZE);
639 sprintf (record_start->header.name, "%s Volume %d",
640 volume_label_option, volno);
641 TIME_TO_CHARS (start_time, record_start->header.mtime);
642 record_start->header.typeflag = GNUTYPE_VOLHDR;
643 finish_header (&current_stat_info, record_start, -1);
644 }
645
646 if (real_s_name)
647 {
648 int tmp;
649
650 if (volume_label_option)
651 record_start++;
652
653 if (strlen (real_s_name) > NAME_FIELD_SIZE)
654 FATAL_ERROR ((0, 0,
655 _("%s: file name too long to be stored in a GNU multivolume header"),
656 quotearg_colon (real_s_name)));
657
658 memset (record_start, 0, BLOCKSIZE);
659
660 /* FIXME: Michael P Urban writes: [a long name file] is being written
661 when a new volume rolls around [...] Looks like the wrong value is
662 being preserved in real_s_name, though. */
663
664 strncpy (record_start->header.name, real_s_name, NAME_FIELD_SIZE);
665 record_start->header.typeflag = GNUTYPE_MULTIVOL;
666
667 OFF_TO_CHARS (real_s_sizeleft, record_start->header.size);
668 OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
669 record_start->oldgnu_header.offset);
670
671 tmp = verbose_option;
672 verbose_option = 0;
673 finish_header (&current_stat_info, record_start, -1);
674 verbose_option = tmp;
675
676 if (volume_label_option)
677 record_start--;
678 }
679
680 status = sys_write_archive_buffer ();
681 if (status != record_size)
682 archive_write_error (status);
683
684 bytes_written += status;
685
686 if (copy_back)
687 {
688 record_start += copy_back;
689 memcpy (current_block,
690 record_start + blocking_factor - copy_back,
691 copy_back * BLOCKSIZE);
692 current_block += copy_back;
693
694 if (real_s_sizeleft >= copy_back * BLOCKSIZE)
695 real_s_sizeleft -= copy_back * BLOCKSIZE;
696 else if ((real_s_sizeleft + BLOCKSIZE - 1) / BLOCKSIZE <= copy_back)
697 assign_string (&real_s_name, 0);
698 else
699 {
700 assign_string (&real_s_name, safer_name_suffix (save_name, false));
701 real_s_sizeleft = save_sizeleft;
702 real_s_totsize = save_totsize;
703 }
704 copy_back = 0;
705 }
706 }
707
708 /* Handle write errors on the archive. Write errors are always fatal.
709 Hitting the end of a volume does not cause a write error unless the
710 write was the first record of the volume. */
711 void
712 archive_write_error (ssize_t status)
713 {
714 /* It might be useful to know how much was written before the error
715 occurred. */
716 if (totals_option)
717 {
718 int e = errno;
719 print_total_written ();
720 errno = e;
721 }
722
723 write_fatal_details (*archive_name_cursor, status, record_size);
724 }
725
726 /* Handle read errors on the archive. If the read should be retried,
727 return to the caller. */
728 void
729 archive_read_error (void)
730 {
731 read_error (*archive_name_cursor);
732
733 if (record_start_block == 0)
734 FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
735
736 /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
737 then give up on reading the archive. */
738
739 if (read_error_count++ > READ_ERROR_MAX)
740 FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
741 return;
742 }
743
744 static void
745 short_read (size_t status)
746 {
747 size_t left; /* bytes left */
748 char *more; /* pointer to next byte to read */
749
750 more = record_start->buffer + status;
751 left = record_size - status;
752
753 while (left % BLOCKSIZE != 0
754 || (left && status && read_full_records))
755 {
756 if (status)
757 while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
758 archive_read_error ();
759
760 if (status == 0)
761 {
762 if (!reading_from_pipe)
763 {
764 char buf[UINTMAX_STRSIZE_BOUND];
765
766 WARN((0, 0, _("Read %s bytes from %s"),
767 STRINGIFY_BIGINT (record_size - left, buf),
768 *archive_name_cursor));
769 }
770 break;
771 }
772
773 if (! read_full_records)
774 {
775 unsigned long rest = record_size - left;
776
777 FATAL_ERROR ((0, 0,
778 ngettext ("Unaligned block (%lu byte) in archive",
779 "Unaligned block (%lu bytes) in archive",
780 rest),
781 rest));
782 }
783
784 /* User warned us about this. Fix up. */
785
786 left -= status;
787 more += status;
788 }
789
790 /* FIXME: for size=0, multi-volume support. On the first record, warn
791 about the problem. */
792
793 if (!read_full_records && verbose_option > 1
794 && record_start_block == 0 && status != 0)
795 {
796 unsigned long rsize = (record_size - left) / BLOCKSIZE;
797 WARN ((0, 0,
798 ngettext ("Record size = %lu block",
799 "Record size = %lu blocks",
800 rsize),
801 rsize));
802 }
803
804 record_end = record_start + (record_size - left) / BLOCKSIZE;
805 records_read++;
806 }
807
808 /* Perform a read to flush the buffer. */
809 void
810 flush_read (void)
811 {
812 size_t status; /* result from system call */
813
814 if (checkpoint_option && !(++checkpoint % 10))
815 WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
816
817 /* Clear the count of errors. This only applies to a single call to
818 flush_read. */
819
820 read_error_count = 0; /* clear error count */
821
822 if (write_archive_to_stdout && record_start_block != 0)
823 {
824 archive = STDOUT_FILENO;
825 status = sys_write_archive_buffer ();
826 archive = STDIN_FILENO;
827 if (status != record_size)
828 archive_write_error (status);
829 }
830 if (multi_volume_option)
831 {
832 if (save_name)
833 {
834 assign_string (&real_s_name, safer_name_suffix (save_name, false));
835 real_s_sizeleft = save_sizeleft;
836 real_s_totsize = save_totsize;
837 }
838 else
839 {
840 assign_string (&real_s_name, 0);
841 real_s_totsize = 0;
842 real_s_sizeleft = 0;
843 }
844 }
845
846 error_loop:
847 status = rmtread (archive, record_start->buffer, record_size);
848 if (status == record_size)
849 {
850 records_read++;
851 return;
852 }
853
854 /* The condition below used to include
855 || (status > 0 && !read_full_records)
856 This is incorrect since even if new_volume() succeeds, the
857 subsequent call to rmtread will overwrite the chunk of data
858 already read in the buffer, so the processing will fail */
859
860 if ((status == 0
861 || (status == SAFE_READ_ERROR && errno == ENOSPC))
862 && multi_volume_option)
863 {
864 union block *cursor;
865
866 try_volume:
867 switch (subcommand_option)
868 {
869 case APPEND_SUBCOMMAND:
870 case CAT_SUBCOMMAND:
871 case UPDATE_SUBCOMMAND:
872 if (!new_volume (ACCESS_UPDATE))
873 return;
874 break;
875
876 default:
877 if (!new_volume (ACCESS_READ))
878 return;
879 break;
880 }
881
882 while ((status = rmtread (archive, record_start->buffer, record_size))
883 == SAFE_READ_ERROR)
884 archive_read_error ();
885
886 if (status != record_size)
887 short_read (status);
888
889 cursor = record_start;
890
891 if (cursor->header.typeflag == GNUTYPE_VOLHDR)
892 {
893 if (volume_label_option)
894 {
895 if (!check_label_pattern (cursor))
896 {
897 WARN ((0, 0, _("Volume %s does not match %s"),
898 quote_n (0, cursor->header.name),
899 quote_n (1, volume_label_option)));
900 volno--;
901 global_volno--;
902 goto try_volume;
903 }
904 }
905 if (verbose_option)
906 fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
907 cursor++;
908 }
909 else if (volume_label_option)
910 WARN ((0, 0, _("WARNING: No volume header")));
911
912 if (real_s_name)
913 {
914 uintmax_t s1, s2;
915 if (cursor->header.typeflag != GNUTYPE_MULTIVOL
916 || strncmp (cursor->header.name, real_s_name, NAME_FIELD_SIZE))
917 {
918 WARN ((0, 0, _("%s is not continued on this volume"),
919 quote (real_s_name)));
920 volno--;
921 global_volno--;
922 goto try_volume;
923 }
924 s1 = UINTMAX_FROM_HEADER (cursor->header.size);
925 s2 = UINTMAX_FROM_HEADER (cursor->oldgnu_header.offset);
926 if (real_s_totsize != s1 + s2 || s1 + s2 < s2)
927 {
928 char totsizebuf[UINTMAX_STRSIZE_BOUND];
929 char s1buf[UINTMAX_STRSIZE_BOUND];
930 char s2buf[UINTMAX_STRSIZE_BOUND];
931
932 WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
933 quote (cursor->header.name),
934 STRINGIFY_BIGINT (save_totsize, totsizebuf),
935 STRINGIFY_BIGINT (s1, s1buf),
936 STRINGIFY_BIGINT (s2, s2buf)));
937 volno--;
938 global_volno--;
939 goto try_volume;
940 }
941 if (real_s_totsize - real_s_sizeleft
942 != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
943 {
944 WARN ((0, 0, _("This volume is out of sequence")));
945 volno--;
946 global_volno--;
947 goto try_volume;
948 }
949 cursor++;
950 }
951 current_block = cursor;
952 records_read++;
953 return;
954 }
955 else if (status == SAFE_READ_ERROR)
956 {
957 archive_read_error ();
958 goto error_loop; /* try again */
959 }
960
961 short_read (status);
962 }
963
964 /* Flush the current buffer to/from the archive. */
965 void
966 flush_archive (void)
967 {
968 record_start_block += record_end - record_start;
969 current_block = record_start;
970 record_end = record_start + blocking_factor;
971
972 if (access_mode == ACCESS_READ && time_to_start_writing)
973 {
974 access_mode = ACCESS_WRITE;
975 time_to_start_writing = false;
976 backspace_output ();
977 }
978
979 switch (access_mode)
980 {
981 case ACCESS_READ:
982 flush_read ();
983 break;
984
985 case ACCESS_WRITE:
986 flush_write ();
987 break;
988
989 case ACCESS_UPDATE:
990 abort ();
991 }
992 }
993
994 /* Backspace the archive descriptor by one record worth. If it's a
995 tape, MTIOCTOP will work. If it's something else, try to seek on
996 it. If we can't seek, we lose! */
997 static void
998 backspace_output (void)
999 {
1000 #ifdef MTIOCTOP
1001 {
1002 struct mtop operation;
1003
1004 operation.mt_op = MTBSR;
1005 operation.mt_count = 1;
1006 if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1007 return;
1008 if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1009 return;
1010 }
1011 #endif
1012
1013 {
1014 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1015
1016 /* Seek back to the beginning of this record and start writing there. */
1017
1018 position -= record_size;
1019 if (position < 0)
1020 position = 0;
1021 if (rmtlseek (archive, position, SEEK_SET) != position)
1022 {
1023 /* Lseek failed. Try a different method. */
1024
1025 WARN ((0, 0,
1026 _("Cannot backspace archive file; it may be unreadable without -i")));
1027
1028 /* Replace the first part of the record with NULs. */
1029
1030 if (record_start->buffer != output_start)
1031 memset (record_start->buffer, 0,
1032 output_start - record_start->buffer);
1033 }
1034 }
1035 }
1036
1037 off_t
1038 seek_archive (off_t size)
1039 {
1040 off_t start = current_block_ordinal ();
1041 off_t offset;
1042 off_t nrec, nblk;
1043 off_t skipped = (blocking_factor - (current_block - record_start));
1044
1045 size -= skipped * BLOCKSIZE;
1046
1047 if (size < record_size)
1048 return 0;
1049 /* FIXME: flush? */
1050
1051 /* Compute number of records to skip */
1052 nrec = size / record_size;
1053 offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
1054 if (offset < 0)
1055 return offset;
1056
1057 if (offset % record_size)
1058 FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
1059
1060 /* Convert to number of records */
1061 offset /= BLOCKSIZE;
1062 /* Compute number of skipped blocks */
1063 nblk = offset - start;
1064
1065 /* Update buffering info */
1066 records_read += nblk / blocking_factor;
1067 record_start_block = offset - blocking_factor;
1068 current_block = record_end;
1069
1070 return nblk;
1071 }
1072
1073 /* Close the archive file. */
1074 void
1075 close_archive (void)
1076 {
1077 if (time_to_start_writing || access_mode == ACCESS_WRITE)
1078 flush_archive ();
1079
1080 sys_drain_input_pipe ();
1081
1082 compute_duration ();
1083 if (verify_option)
1084 verify_volume ();
1085
1086 if (rmtclose (archive) != 0)
1087 close_warn (*archive_name_cursor);
1088
1089 sys_wait_for_child (child_pid);
1090
1091 tar_stat_destroy (&current_stat_info);
1092 if (save_name)
1093 free (save_name);
1094 if (real_s_name)
1095 free (real_s_name);
1096 free (record_buffer);
1097 }
1098
1099 /* Called to initialize the global volume number. */
1100 void
1101 init_volume_number (void)
1102 {
1103 FILE *file = fopen (volno_file_option, "r");
1104
1105 if (file)
1106 {
1107 if (fscanf (file, "%d", &global_volno) != 1
1108 || global_volno < 0)
1109 FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1110 quotearg_colon (volno_file_option)));
1111 if (ferror (file))
1112 read_error (volno_file_option);
1113 if (fclose (file) != 0)
1114 close_error (volno_file_option);
1115 }
1116 else if (errno != ENOENT)
1117 open_error (volno_file_option);
1118 }
1119
1120 /* Called to write out the closing global volume number. */
1121 void
1122 closeout_volume_number (void)
1123 {
1124 FILE *file = fopen (volno_file_option, "w");
1125
1126 if (file)
1127 {
1128 fprintf (file, "%d\n", global_volno);
1129 if (ferror (file))
1130 write_error (volno_file_option);
1131 if (fclose (file) != 0)
1132 close_error (volno_file_option);
1133 }
1134 else
1135 open_error (volno_file_option);
1136 }
1137
1138 /* We've hit the end of the old volume. Close it and open the next one.
1139 Return nonzero on success.
1140 */
1141 static bool
1142 new_volume (enum access_mode mode)
1143 {
1144 static FILE *read_file;
1145 static int looped;
1146
1147 if (!read_file && !info_script_option)
1148 /* FIXME: if fopen is used, it will never be closed. */
1149 read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1150
1151 if (now_verifying)
1152 return false;
1153 if (verify_option)
1154 verify_volume ();
1155
1156 if (rmtclose (archive) != 0)
1157 close_warn (*archive_name_cursor);
1158
1159 global_volno++;
1160 if (global_volno < 0)
1161 FATAL_ERROR ((0, 0, _("Volume number overflow")));
1162 volno++;
1163 archive_name_cursor++;
1164 if (archive_name_cursor == archive_name_array + archive_names)
1165 {
1166 archive_name_cursor = archive_name_array;
1167 looped = 1;
1168 }
1169
1170 tryagain:
1171 if (looped)
1172 {
1173 /* We have to prompt from now on. */
1174
1175 if (info_script_option)
1176 {
1177 if (volno_file_option)
1178 closeout_volume_number ();
1179 if (system (info_script_option) != 0)
1180 FATAL_ERROR ((0, 0, _("`%s' command failed"), info_script_option));
1181 }
1182 else
1183 while (1)
1184 {
1185 char input_buffer[80];
1186
1187 fputc ('\007', stderr);
1188 fprintf (stderr,
1189 _("Prepare volume #%d for %s and hit return: "),
1190 global_volno, quote (*archive_name_cursor));
1191 fflush (stderr);
1192
1193 if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1194 {
1195 WARN ((0, 0, _("EOF where user reply was expected")));
1196
1197 if (subcommand_option != EXTRACT_SUBCOMMAND
1198 && subcommand_option != LIST_SUBCOMMAND
1199 && subcommand_option != DIFF_SUBCOMMAND)
1200 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1201
1202 fatal_exit ();
1203 }
1204 if (input_buffer[0] == '\n'
1205 || input_buffer[0] == 'y'
1206 || input_buffer[0] == 'Y')
1207 break;
1208
1209 switch (input_buffer[0])
1210 {
1211 case '?':
1212 {
1213 /* FIXME: Might it be useful to disable the '!' command? */
1214 fprintf (stderr, _("\
1215 n [name] Give a new file name for the next (and subsequent) volume(s)\n\
1216 q Abort tar\n\
1217 ! Spawn a subshell\n\
1218 ? Print this list\n"));
1219 }
1220 break;
1221
1222 case 'q':
1223 /* Quit. */
1224
1225 WARN ((0, 0, _("No new volume; exiting.\n")));
1226
1227 if (subcommand_option != EXTRACT_SUBCOMMAND
1228 && subcommand_option != LIST_SUBCOMMAND
1229 && subcommand_option != DIFF_SUBCOMMAND)
1230 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1231
1232 fatal_exit ();
1233
1234 case 'n':
1235 /* Get new file name. */
1236
1237 {
1238 char *name = &input_buffer[1];
1239 char *cursor;
1240
1241 for (name = input_buffer + 1;
1242 *name == ' ' || *name == '\t';
1243 name++)
1244 ;
1245
1246 for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1247 ;
1248 *cursor = '\0';
1249
1250 /* FIXME: the following allocation is never reclaimed. */
1251 *archive_name_cursor = xstrdup (name);
1252 }
1253 break;
1254
1255 case '!':
1256 sys_spawn_shell ();
1257 break;
1258 }
1259 }
1260 }
1261
1262 if (strcmp (archive_name_cursor[0], "-") == 0)
1263 {
1264 read_full_records = true;
1265 archive = STDIN_FILENO;
1266 }
1267 else if (verify_option)
1268 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1269 rsh_command_option);
1270 else
1271 switch (mode)
1272 {
1273 case ACCESS_READ:
1274 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1275 rsh_command_option);
1276 break;
1277
1278 case ACCESS_WRITE:
1279 if (backup_option)
1280 maybe_backup_file (*archive_name_cursor, 1);
1281 archive = rmtcreat (*archive_name_cursor, MODE_RW,
1282 rsh_command_option);
1283 break;
1284
1285 case ACCESS_UPDATE:
1286 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1287 rsh_command_option);
1288 break;
1289 }
1290
1291 if (archive < 0)
1292 {
1293 open_warn (*archive_name_cursor);
1294 if (!verify_option && mode == ACCESS_WRITE && backup_option)
1295 undo_last_backup ();
1296 goto tryagain;
1297 }
1298
1299 SET_BINARY_MODE (archive);
1300
1301 return true;
1302 }
1303
This page took 0.090135 seconds and 5 git commands to generate.