]> Dogcows Code - chaz/tar/blob - src/buffer.c
(new_volume): Initialize current_block
[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, 2005, 2006 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 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
21
22 #include <system.h>
23 #include <system-ioctl.h>
24
25 #include <signal.h>
26
27 #include <closeout.h>
28 #include <fnmatch.h>
29 #include <getline.h>
30 #include <human.h>
31 #include <quotearg.h>
32
33 #include "common.h"
34 #include <rmt.h>
35
36 /* Number of retries before giving up on read. */
37 #define READ_ERROR_MAX 10
38
39 /* Globbing pattern to append to volume label if initial match failed. */
40 #define VOLUME_LABEL_APPEND " Volume [1-9]*"
41
42 /* Variables. */
43
44 static tarlong prev_written; /* bytes written on previous volumes */
45 static tarlong bytes_written; /* bytes written on this volume */
46 static void *record_buffer[2]; /* allocated memory */
47 union block *record_buffer_aligned[2];
48 static int record_index;
49
50 /* FIXME: The following variables should ideally be static to this
51 module. However, this cannot be done yet. The cleanup continues! */
52
53 union block *record_start; /* start of record of archive */
54 union block *record_end; /* last+1 block of archive record */
55 union block *current_block; /* current block of archive */
56 enum access_mode access_mode; /* how do we handle the archive */
57 off_t records_read; /* number of records read from this archive */
58 off_t records_written; /* likewise, for records written */
59 extern off_t records_skipped; /* number of records skipped at the start
60 of the archive, defined in delete.c */
61
62 static off_t record_start_block; /* block ordinal at record_start */
63
64 /* Where we write list messages (not errors, not interactions) to. */
65 FILE *stdlis;
66
67 static void backspace_output (void);
68
69 /* PID of child program, if compress_option or remote archive access. */
70 static pid_t child_pid;
71
72 /* Error recovery stuff */
73 static int read_error_count;
74
75 /* Have we hit EOF yet? */
76 static bool hit_eof;
77
78 /* Checkpointing counter */
79 static unsigned checkpoint;
80
81 static bool read_full_records = false;
82
83 /* We're reading, but we just read the last block and it's time to update.
84 Declared in update.c
85
86 As least EXTERN like this one as possible. (?? --gray)
87 FIXME: Either eliminate it or move it to common.h.
88 */
89 extern bool time_to_start_writing;
90
91 bool write_archive_to_stdout;
92
93 void (*flush_write_ptr) (size_t);
94 void (*flush_read_ptr) (void);
95
96 \f
97 char *volume_label;
98 char *continued_file_name;
99 uintmax_t continued_file_size;
100 uintmax_t continued_file_offset;
101
102 \f
103 static int volno = 1; /* which volume of a multi-volume tape we're
104 on */
105 static int global_volno = 1; /* volume number to print in external
106 messages */
107
108 bool write_archive_to_stdout;
109
110 /* Used by flush_read and flush_write to store the real info about saved
111 names. */
112 static char *real_s_name;
113 static off_t real_s_totsize;
114 static off_t real_s_sizeleft;
115
116 \f
117 /* Multi-volume tracking support */
118 static char *save_name; /* name of the file we are currently writing */
119 static off_t save_totsize; /* total size of file we are writing, only
120 valid if save_name is nonzero */
121 static off_t save_sizeleft; /* where we are in the file we are writing,
122 only valid if save_name is nonzero */
123
124 void
125 mv_begin (struct tar_stat_info *st)
126 {
127 if (multi_volume_option)
128 {
129 assign_string (&save_name, st->orig_file_name);
130 save_totsize = save_sizeleft = st->stat.st_size;
131 }
132 }
133
134 void
135 mv_end ()
136 {
137 if (multi_volume_option)
138 assign_string (&save_name, 0);
139 }
140
141 void
142 mv_total_size (off_t size)
143 {
144 save_totsize = size;
145 }
146
147 void
148 mv_size_left (off_t size)
149 {
150 save_sizeleft = size;
151 }
152
153 \f
154 /* Functions. */
155
156 void
157 clear_read_error_count (void)
158 {
159 read_error_count = 0;
160 }
161
162 \f
163 /* Time-related functions */
164
165 double duration;
166
167 void
168 set_start_time ()
169 {
170 gettime (&start_time);
171 volume_start_time = start_time;
172 last_stat_time = start_time;
173 }
174
175 void
176 set_volume_start_time ()
177 {
178 gettime (&volume_start_time);
179 last_stat_time = volume_start_time;
180 }
181
182 void
183 compute_duration ()
184 {
185 struct timespec now;
186 gettime (&now);
187 duration += ((now.tv_sec - last_stat_time.tv_sec)
188 + (now.tv_nsec - last_stat_time.tv_nsec) / 1e9);
189 gettime (&last_stat_time);
190 }
191
192 \f
193 /* Compression detection */
194
195 enum compress_type {
196 ct_none,
197 ct_compress,
198 ct_gzip,
199 ct_bzip2
200 };
201
202 struct zip_magic
203 {
204 enum compress_type type;
205 size_t length;
206 char *magic;
207 char *program;
208 char *option;
209 };
210
211 static struct zip_magic const magic[] = {
212 { ct_none, },
213 { ct_compress, 2, "\037\235", "compress", "-Z" },
214 { ct_gzip, 2, "\037\213", "gzip", "-z" },
215 { ct_bzip2, 3, "BZh", "bzip2", "-j" },
216 };
217
218 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
219
220 #define compress_option(t) magic[t].option
221 #define compress_program(t) magic[t].program
222
223 /* Check if the file ARCHIVE is a compressed archive. */
224 enum compress_type
225 check_compressed_archive ()
226 {
227 struct zip_magic const *p;
228 bool sfr;
229
230 /* Prepare global data needed for find_next_block: */
231 record_end = record_start; /* set up for 1st record = # 0 */
232 sfr = read_full_records;
233 read_full_records = true; /* Suppress fatal error on reading a partial
234 record */
235 find_next_block ();
236
237 /* Restore global values */
238 read_full_records = sfr;
239
240 if (tar_checksum (record_start, true) == HEADER_SUCCESS)
241 /* Probably a valid header */
242 return ct_none;
243
244 for (p = magic + 1; p < magic + NMAGIC; p++)
245 if (memcmp (record_start->buffer, p->magic, p->length) == 0)
246 return p->type;
247
248 return ct_none;
249 }
250
251 /* Open an archive named archive_name_array[0]. Detect if it is
252 a compressed archive of known type and use corresponding decompression
253 program if so */
254 int
255 open_compressed_archive ()
256 {
257 archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
258 MODE_RW, rsh_command_option);
259 if (archive == -1)
260 return archive;
261
262 if (!multi_volume_option)
263 {
264 enum compress_type type = check_compressed_archive ();
265
266 if (type == ct_none)
267 return archive;
268
269 /* FD is not needed any more */
270 rmtclose (archive);
271
272 hit_eof = false; /* It might have been set by find_next_block in
273 check_compressed_archive */
274
275 /* Open compressed archive */
276 use_compress_program_option = compress_program (type);
277 child_pid = sys_child_open_for_uncompress ();
278 read_full_records = true;
279 }
280
281 records_read = 0;
282 record_end = record_start; /* set up for 1st record = # 0 */
283
284 return archive;
285 }
286 \f
287
288 static void
289 print_stats (FILE *fp, const char *text, tarlong numbytes)
290 {
291 char bytes[sizeof (tarlong) * CHAR_BIT];
292 char abbr[LONGEST_HUMAN_READABLE + 1];
293 char rate[LONGEST_HUMAN_READABLE + 1];
294
295 int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
296
297 sprintf (bytes, TARLONG_FORMAT, numbytes);
298
299 fprintf (fp, "%s: %s (%s, %s/s)\n",
300 text, bytes,
301 human_readable (numbytes, abbr, human_opts, 1, 1),
302 (0 < duration && numbytes / duration < (uintmax_t) -1
303 ? human_readable (numbytes / duration, rate, human_opts, 1, 1)
304 : "?"));
305 }
306
307 void
308 print_total_stats ()
309 {
310 switch (subcommand_option)
311 {
312 case CREATE_SUBCOMMAND:
313 case CAT_SUBCOMMAND:
314 case UPDATE_SUBCOMMAND:
315 case APPEND_SUBCOMMAND:
316 /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*". */
317 print_stats (stderr, _("Total bytes written"),
318 prev_written + bytes_written);
319 break;
320
321 case DELETE_SUBCOMMAND:
322 {
323 char buf[UINTMAX_STRSIZE_BOUND];
324 print_stats (stderr, _("Total bytes read"),
325 records_read * record_size);
326 print_stats (stderr, _("Total bytes written"),
327 prev_written + bytes_written);
328 fprintf (stderr, _("Total bytes deleted: %s\n"),
329 STRINGIFY_BIGINT ((records_read - records_skipped)
330 * record_size
331 - (prev_written + bytes_written), buf));
332 }
333 break;
334
335 case EXTRACT_SUBCOMMAND:
336 case LIST_SUBCOMMAND:
337 case DIFF_SUBCOMMAND:
338 print_stats (stderr, _("Total bytes read"),
339 records_read * record_size);
340 break;
341
342 default:
343 abort ();
344 }
345 }
346
347 /* Compute and return the block ordinal at current_block. */
348 off_t
349 current_block_ordinal (void)
350 {
351 return record_start_block + (current_block - record_start);
352 }
353
354 /* If the EOF flag is set, reset it, as well as current_block, etc. */
355 void
356 reset_eof (void)
357 {
358 if (hit_eof)
359 {
360 hit_eof = false;
361 current_block = record_start;
362 record_end = record_start + blocking_factor;
363 access_mode = ACCESS_WRITE;
364 }
365 }
366
367 /* Return the location of the next available input or output block.
368 Return zero for EOF. Once we have returned zero, we just keep returning
369 it, to avoid accidentally going on to the next file on the tape. */
370 union block *
371 find_next_block (void)
372 {
373 if (current_block == record_end)
374 {
375 if (hit_eof)
376 return 0;
377 flush_archive ();
378 if (current_block == record_end)
379 {
380 hit_eof = true;
381 return 0;
382 }
383 }
384 return current_block;
385 }
386
387 /* Indicate that we have used all blocks up thru BLOCK. */
388 void
389 set_next_block_after (union block *block)
390 {
391 while (block >= current_block)
392 current_block++;
393
394 /* Do *not* flush the archive here. If we do, the same argument to
395 set_next_block_after could mean the next block (if the input record
396 is exactly one block long), which is not what is intended. */
397
398 if (current_block > record_end)
399 abort ();
400 }
401
402 /* Return the number of bytes comprising the space between POINTER
403 through the end of the current buffer of blocks. This space is
404 available for filling with data, or taking data from. POINTER is
405 usually (but not always) the result of previous find_next_block call. */
406 size_t
407 available_space_after (union block *pointer)
408 {
409 return record_end->buffer - pointer->buffer;
410 }
411
412 /* Close file having descriptor FD, and abort if close unsuccessful. */
413 void
414 xclose (int fd)
415 {
416 if (close (fd) != 0)
417 close_error (_("(pipe)"));
418 }
419
420 static void
421 init_buffer ()
422 {
423 if (! record_buffer_aligned[record_index])
424 record_buffer_aligned[record_index] =
425 page_aligned_alloc (&record_buffer[record_index], record_size);
426
427 record_start = record_buffer_aligned[record_index];
428 current_block = record_start;
429 record_end = record_start + blocking_factor;
430 }
431
432 /* Open an archive file. The argument specifies whether we are
433 reading or writing, or both. */
434 static void
435 _open_archive (enum access_mode wanted_access)
436 {
437 int backed_up_flag = 0;
438
439 if (record_size == 0)
440 FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
441
442 if (archive_names == 0)
443 FATAL_ERROR ((0, 0, _("No archive name given")));
444
445 tar_stat_destroy (&current_stat_info);
446 save_name = 0;
447 real_s_name = 0;
448
449 record_index = 0;
450 init_buffer ();
451
452 /* When updating the archive, we start with reading. */
453 access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
454
455 read_full_records = read_full_records_option;
456
457 records_read = 0;
458
459 if (use_compress_program_option)
460 {
461 switch (wanted_access)
462 {
463 case ACCESS_READ:
464 child_pid = sys_child_open_for_uncompress ();
465 read_full_records = true;
466 record_end = record_start; /* set up for 1st record = # 0 */
467 break;
468
469 case ACCESS_WRITE:
470 child_pid = sys_child_open_for_compress ();
471 break;
472
473 case ACCESS_UPDATE:
474 abort (); /* Should not happen */
475 break;
476 }
477 }
478 else if (strcmp (archive_name_array[0], "-") == 0)
479 {
480 read_full_records = true; /* could be a pipe, be safe */
481 if (verify_option)
482 FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
483
484 switch (wanted_access)
485 {
486 case ACCESS_READ:
487 {
488 enum compress_type type;
489
490 archive = STDIN_FILENO;
491
492 type = check_compressed_archive ();
493 if (type != ct_none)
494 FATAL_ERROR ((0, 0,
495 _("Archive is compressed. Use %s option"),
496 compress_option (type)));
497 }
498 break;
499
500 case ACCESS_WRITE:
501 archive = STDOUT_FILENO;
502 break;
503
504 case ACCESS_UPDATE:
505 archive = STDIN_FILENO;
506 write_archive_to_stdout = true;
507 record_end = record_start; /* set up for 1st record = # 0 */
508 break;
509 }
510 }
511 else if (verify_option)
512 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
513 MODE_RW, rsh_command_option);
514 else
515 switch (wanted_access)
516 {
517 case ACCESS_READ:
518 archive = open_compressed_archive ();
519 break;
520
521 case ACCESS_WRITE:
522 if (backup_option)
523 {
524 maybe_backup_file (archive_name_array[0], 1);
525 backed_up_flag = 1;
526 }
527 archive = rmtcreat (archive_name_array[0], MODE_RW,
528 rsh_command_option);
529 break;
530
531 case ACCESS_UPDATE:
532 archive = rmtopen (archive_name_array[0],
533 O_RDWR | O_CREAT | O_BINARY,
534 MODE_RW, rsh_command_option);
535
536 if (check_compressed_archive () != ct_none)
537 FATAL_ERROR ((0, 0,
538 _("Cannot update compressed archives")));
539 break;
540 }
541
542 if (archive < 0
543 || (! _isrmt (archive) && !sys_get_archive_stat ()))
544 {
545 int saved_errno = errno;
546
547 if (backed_up_flag)
548 undo_last_backup ();
549 errno = saved_errno;
550 open_fatal (archive_name_array[0]);
551 }
552
553 sys_detect_dev_null_output ();
554 sys_save_archive_dev_ino ();
555 SET_BINARY_MODE (archive);
556
557 switch (wanted_access)
558 {
559 case ACCESS_READ:
560 find_next_block (); /* read it in, check for EOF */
561 break;
562
563 case ACCESS_UPDATE:
564 case ACCESS_WRITE:
565 records_written = 0;
566 break;
567 }
568 }
569
570 static void
571 do_checkpoint (bool write)
572 {
573 if (checkpoint_option && !(++checkpoint % checkpoint_option))
574 {
575 switch (checkpoint_style)
576 {
577 case checkpoint_dot:
578 fputc ('.', stdlis);
579 fflush (stdlis);
580 break;
581
582 case checkpoint_text:
583 if (write)
584 /* TRANSLATORS: This is a ``checkpoint of write operation'',
585 *not* ``Writing a checkpoint''.
586 E.g. in Spanish ``Punto de comprobaci@'on de escritura'',
587 *not* ``Escribiendo un punto de comprobaci@'on'' */
588 WARN ((0, 0, _("Write checkpoint %u"), checkpoint));
589 else
590 /* TRANSLATORS: This is a ``checkpoint of read operation'',
591 *not* ``Reading a checkpoint''.
592 E.g. in Spanish ``Punto de comprobaci@'on de lectura'',
593 *not* ``Leyendo un punto de comprobaci@'on'' */
594 WARN ((0, 0, _("Read checkpoint %u"), checkpoint));
595 break;
596 }
597 }
598 }
599
600 /* Perform a write to flush the buffer. */
601 ssize_t
602 _flush_write (void)
603 {
604 ssize_t status;
605
606 do_checkpoint (true);
607 if (tape_length_option && tape_length_option <= bytes_written)
608 {
609 errno = ENOSPC;
610 status = 0;
611 }
612 else if (dev_null_output)
613 status = record_size;
614 else
615 status = sys_write_archive_buffer ();
616
617 return status;
618 }
619
620 /* Handle write errors on the archive. Write errors are always fatal.
621 Hitting the end of a volume does not cause a write error unless the
622 write was the first record of the volume. */
623 void
624 archive_write_error (ssize_t status)
625 {
626 /* It might be useful to know how much was written before the error
627 occurred. */
628 if (totals_option)
629 {
630 int e = errno;
631 print_total_stats ();
632 errno = e;
633 }
634
635 write_fatal_details (*archive_name_cursor, status, record_size);
636 }
637
638 /* Handle read errors on the archive. If the read should be retried,
639 return to the caller. */
640 void
641 archive_read_error (void)
642 {
643 read_error (*archive_name_cursor);
644
645 if (record_start_block == 0)
646 FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
647
648 /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
649 then give up on reading the archive. */
650
651 if (read_error_count++ > READ_ERROR_MAX)
652 FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
653 return;
654 }
655
656 static void
657 short_read (size_t status)
658 {
659 size_t left; /* bytes left */
660 char *more; /* pointer to next byte to read */
661
662 more = record_start->buffer + status;
663 left = record_size - status;
664
665 while (left % BLOCKSIZE != 0
666 || (left && status && read_full_records))
667 {
668 if (status)
669 while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
670 archive_read_error ();
671
672 if (status == 0)
673 break;
674
675 if (! read_full_records)
676 {
677 unsigned long rest = record_size - left;
678
679 FATAL_ERROR ((0, 0,
680 ngettext ("Unaligned block (%lu byte) in archive",
681 "Unaligned block (%lu bytes) in archive",
682 rest),
683 rest));
684 }
685
686 /* User warned us about this. Fix up. */
687
688 left -= status;
689 more += status;
690 }
691
692 /* FIXME: for size=0, multi-volume support. On the first record, warn
693 about the problem. */
694
695 if (!read_full_records && verbose_option > 1
696 && record_start_block == 0 && status != 0)
697 {
698 unsigned long rsize = (record_size - left) / BLOCKSIZE;
699 WARN ((0, 0,
700 ngettext ("Record size = %lu block",
701 "Record size = %lu blocks",
702 rsize),
703 rsize));
704 }
705
706 record_end = record_start + (record_size - left) / BLOCKSIZE;
707 records_read++;
708 }
709
710 /* Flush the current buffer to/from the archive. */
711 void
712 flush_archive (void)
713 {
714 size_t buffer_level = current_block->buffer - record_start->buffer;
715 record_start_block += record_end - record_start;
716 current_block = record_start;
717 record_end = record_start + blocking_factor;
718
719 if (access_mode == ACCESS_READ && time_to_start_writing)
720 {
721 access_mode = ACCESS_WRITE;
722 time_to_start_writing = false;
723 backspace_output ();
724 }
725
726 switch (access_mode)
727 {
728 case ACCESS_READ:
729 flush_read ();
730 break;
731
732 case ACCESS_WRITE:
733 flush_write_ptr (buffer_level);
734 break;
735
736 case ACCESS_UPDATE:
737 abort ();
738 }
739 }
740
741 /* Backspace the archive descriptor by one record worth. If it's a
742 tape, MTIOCTOP will work. If it's something else, try to seek on
743 it. If we can't seek, we lose! */
744 static void
745 backspace_output (void)
746 {
747 #ifdef MTIOCTOP
748 {
749 struct mtop operation;
750
751 operation.mt_op = MTBSR;
752 operation.mt_count = 1;
753 if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
754 return;
755 if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
756 return;
757 }
758 #endif
759
760 {
761 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
762
763 /* Seek back to the beginning of this record and start writing there. */
764
765 position -= record_size;
766 if (position < 0)
767 position = 0;
768 if (rmtlseek (archive, position, SEEK_SET) != position)
769 {
770 /* Lseek failed. Try a different method. */
771
772 WARN ((0, 0,
773 _("Cannot backspace archive file; it may be unreadable without -i")));
774
775 /* Replace the first part of the record with NULs. */
776
777 if (record_start->buffer != output_start)
778 memset (record_start->buffer, 0,
779 output_start - record_start->buffer);
780 }
781 }
782 }
783
784 off_t
785 seek_archive (off_t size)
786 {
787 off_t start = current_block_ordinal ();
788 off_t offset;
789 off_t nrec, nblk;
790 off_t skipped = (blocking_factor - (current_block - record_start));
791
792 size -= skipped * BLOCKSIZE;
793
794 if (size < record_size)
795 return 0;
796 /* FIXME: flush? */
797
798 /* Compute number of records to skip */
799 nrec = size / record_size;
800 offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
801 if (offset < 0)
802 return offset;
803
804 if (offset % record_size)
805 FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
806
807 /* Convert to number of records */
808 offset /= BLOCKSIZE;
809 /* Compute number of skipped blocks */
810 nblk = offset - start;
811
812 /* Update buffering info */
813 records_read += nblk / blocking_factor;
814 record_start_block = offset - blocking_factor;
815 current_block = record_end;
816
817 return nblk;
818 }
819
820 /* Close the archive file. */
821 void
822 close_archive (void)
823 {
824 if (time_to_start_writing || access_mode == ACCESS_WRITE)
825 {
826 flush_archive ();
827 if (current_block > record_start)
828 flush_archive ();
829 }
830
831 sys_drain_input_pipe ();
832
833 compute_duration ();
834 if (verify_option)
835 verify_volume ();
836
837 if (rmtclose (archive) != 0)
838 close_warn (*archive_name_cursor);
839
840 sys_wait_for_child (child_pid);
841
842 tar_stat_destroy (&current_stat_info);
843 if (save_name)
844 free (save_name);
845 if (real_s_name)
846 free (real_s_name);
847 free (record_buffer[0]);
848 free (record_buffer[1]);
849 }
850
851 /* Called to initialize the global volume number. */
852 void
853 init_volume_number (void)
854 {
855 FILE *file = fopen (volno_file_option, "r");
856
857 if (file)
858 {
859 if (fscanf (file, "%d", &global_volno) != 1
860 || global_volno < 0)
861 FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
862 quotearg_colon (volno_file_option)));
863 if (ferror (file))
864 read_error (volno_file_option);
865 if (fclose (file) != 0)
866 close_error (volno_file_option);
867 }
868 else if (errno != ENOENT)
869 open_error (volno_file_option);
870 }
871
872 /* Called to write out the closing global volume number. */
873 void
874 closeout_volume_number (void)
875 {
876 FILE *file = fopen (volno_file_option, "w");
877
878 if (file)
879 {
880 fprintf (file, "%d\n", global_volno);
881 if (ferror (file))
882 write_error (volno_file_option);
883 if (fclose (file) != 0)
884 close_error (volno_file_option);
885 }
886 else
887 open_error (volno_file_option);
888 }
889
890 \f
891 static void
892 increase_volume_number ()
893 {
894 global_volno++;
895 if (global_volno < 0)
896 FATAL_ERROR ((0, 0, _("Volume number overflow")));
897 volno++;
898 }
899
900 void
901 change_tape_menu (FILE *read_file)
902 {
903 char *input_buffer = NULL;
904 size_t size = 0;
905 bool stop = false;
906
907 while (!stop)
908 {
909 fputc ('\007', stderr);
910 fprintf (stderr,
911 _("Prepare volume #%d for %s and hit return: "),
912 global_volno + 1, quote (*archive_name_cursor));
913 fflush (stderr);
914
915 if (getline (&input_buffer, &size, read_file) <= 0)
916 {
917 WARN ((0, 0, _("EOF where user reply was expected")));
918
919 if (subcommand_option != EXTRACT_SUBCOMMAND
920 && subcommand_option != LIST_SUBCOMMAND
921 && subcommand_option != DIFF_SUBCOMMAND)
922 WARN ((0, 0, _("WARNING: Archive is incomplete")));
923
924 fatal_exit ();
925 }
926
927 if (input_buffer[0] == '\n'
928 || input_buffer[0] == 'y'
929 || input_buffer[0] == 'Y')
930 break;
931
932 switch (input_buffer[0])
933 {
934 case '?':
935 {
936 fprintf (stderr, _("\
937 n name Give a new file name for the next (and subsequent) volume(s)\n\
938 q Abort tar\n\
939 y or newline Continue operation\n"));
940 if (!restrict_option)
941 fprintf (stderr, _(" ! Spawn a subshell\n"));
942 fprintf (stderr, _(" ? Print this list\n"));
943 }
944 break;
945
946 case 'q':
947 /* Quit. */
948
949 WARN ((0, 0, _("No new volume; exiting.\n")));
950
951 if (subcommand_option != EXTRACT_SUBCOMMAND
952 && subcommand_option != LIST_SUBCOMMAND
953 && subcommand_option != DIFF_SUBCOMMAND)
954 WARN ((0, 0, _("WARNING: Archive is incomplete")));
955
956 fatal_exit ();
957
958 case 'n':
959 /* Get new file name. */
960
961 {
962 char *name;
963 char *cursor;
964
965 for (name = input_buffer + 1;
966 *name == ' ' || *name == '\t';
967 name++)
968 ;
969
970 for (cursor = name; *cursor && *cursor != '\n'; cursor++)
971 ;
972 *cursor = '\0';
973
974 if (name[0])
975 {
976 /* FIXME: the following allocation is never reclaimed. */
977 *archive_name_cursor = xstrdup (name);
978 stop = true;
979 }
980 else
981 fprintf (stderr, "%s",
982 _("File name not specified. Try again.\n"));
983 }
984 break;
985
986 case '!':
987 if (!restrict_option)
988 {
989 sys_spawn_shell ();
990 break;
991 }
992 /* FALL THROUGH */
993
994 default:
995 fprintf (stderr, _("Invalid input. Type ? for help.\n"));
996 }
997 }
998 free (input_buffer);
999 }
1000
1001 /* We've hit the end of the old volume. Close it and open the next one.
1002 Return nonzero on success.
1003 */
1004 static bool
1005 new_volume (enum access_mode mode)
1006 {
1007 static FILE *read_file;
1008 static int looped;
1009 int prompt;
1010
1011 if (!read_file && !info_script_option)
1012 /* FIXME: if fopen is used, it will never be closed. */
1013 read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1014
1015 if (now_verifying)
1016 return false;
1017 if (verify_option)
1018 verify_volume ();
1019
1020 assign_string (&volume_label, NULL);
1021 assign_string (&continued_file_name, NULL);
1022 continued_file_size = continued_file_offset = 0;
1023 current_block = record_start;
1024
1025 if (rmtclose (archive) != 0)
1026 close_warn (*archive_name_cursor);
1027
1028 archive_name_cursor++;
1029 if (archive_name_cursor == archive_name_array + archive_names)
1030 {
1031 archive_name_cursor = archive_name_array;
1032 looped = 1;
1033 }
1034 prompt = looped;
1035
1036 tryagain:
1037 if (prompt)
1038 {
1039 /* We have to prompt from now on. */
1040
1041 if (info_script_option)
1042 {
1043 if (volno_file_option)
1044 closeout_volume_number ();
1045 if (sys_exec_info_script (archive_name_cursor, global_volno+1))
1046 FATAL_ERROR ((0, 0, _("%s command failed"),
1047 quote (info_script_option)));
1048 }
1049 else
1050 change_tape_menu (read_file);
1051 }
1052
1053 if (strcmp (archive_name_cursor[0], "-") == 0)
1054 {
1055 read_full_records = true;
1056 archive = STDIN_FILENO;
1057 }
1058 else if (verify_option)
1059 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1060 rsh_command_option);
1061 else
1062 switch (mode)
1063 {
1064 case ACCESS_READ:
1065 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1066 rsh_command_option);
1067 break;
1068
1069 case ACCESS_WRITE:
1070 if (backup_option)
1071 maybe_backup_file (*archive_name_cursor, 1);
1072 archive = rmtcreat (*archive_name_cursor, MODE_RW,
1073 rsh_command_option);
1074 break;
1075
1076 case ACCESS_UPDATE:
1077 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1078 rsh_command_option);
1079 break;
1080 }
1081
1082 if (archive < 0)
1083 {
1084 open_warn (*archive_name_cursor);
1085 if (!verify_option && mode == ACCESS_WRITE && backup_option)
1086 undo_last_backup ();
1087 prompt = 1;
1088 goto tryagain;
1089 }
1090
1091 SET_BINARY_MODE (archive);
1092
1093 return true;
1094 }
1095
1096 static bool
1097 read_header0 (struct tar_stat_info *info)
1098 {
1099 enum read_header rc;
1100
1101 tar_stat_init (info);
1102 rc = read_header_primitive (false, info);
1103 if (rc == HEADER_SUCCESS)
1104 {
1105 set_next_block_after (current_header);
1106 return true;
1107 }
1108 ERROR ((0, 0, _("This does not look like a tar archive")));
1109 return false;
1110 }
1111
1112 bool
1113 try_new_volume ()
1114 {
1115 size_t status;
1116 union block *header;
1117 struct tar_stat_info dummy;
1118 int access;
1119
1120 switch (subcommand_option)
1121 {
1122 case APPEND_SUBCOMMAND:
1123 case CAT_SUBCOMMAND:
1124 case UPDATE_SUBCOMMAND:
1125 access = ACCESS_UPDATE;
1126 break;
1127
1128 default:
1129 access = ACCESS_READ;
1130 break;
1131 }
1132
1133 if (!new_volume (access))
1134 return true;
1135
1136 while ((status = rmtread (archive, record_start->buffer, record_size))
1137 == SAFE_READ_ERROR)
1138 archive_read_error ();
1139
1140 if (status != record_size)
1141 short_read (status);
1142
1143 header = find_next_block ();
1144 if (!header)
1145 return false;
1146
1147 switch (header->header.typeflag)
1148 {
1149 case XGLTYPE:
1150 {
1151 if (!read_header0 (&dummy))
1152 return false;
1153 xheader_decode (&dummy); /* decodes values from the global header */
1154 tar_stat_destroy (&dummy);
1155 if (!real_s_name)
1156 {
1157 /* We have read the extended header of the first member in
1158 this volume. Put it back, so next read_header works as
1159 expected. */
1160 current_block = record_start;
1161 }
1162 break;
1163 }
1164
1165 case GNUTYPE_VOLHDR:
1166 if (!read_header0 (&dummy))
1167 return false;
1168 tar_stat_destroy (&dummy);
1169 assign_string (&volume_label, current_header->header.name);
1170 set_next_block_after (header);
1171 header = find_next_block ();
1172 if (header->header.typeflag != GNUTYPE_MULTIVOL)
1173 break;
1174 /* FALL THROUGH */
1175
1176 case GNUTYPE_MULTIVOL:
1177 if (!read_header0 (&dummy))
1178 return false;
1179 tar_stat_destroy (&dummy);
1180 assign_string (&continued_file_name, current_header->header.name);
1181 continued_file_size =
1182 UINTMAX_FROM_HEADER (current_header->header.size);
1183 continued_file_offset =
1184 UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
1185 break;
1186
1187 default:
1188 break;
1189 }
1190
1191 if (real_s_name)
1192 {
1193 uintmax_t s;
1194 if (!continued_file_name
1195 || strcmp (continued_file_name, real_s_name))
1196 {
1197 if ((archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
1198 && strlen (real_s_name) >= NAME_FIELD_SIZE
1199 && strncmp (continued_file_name, real_s_name,
1200 NAME_FIELD_SIZE) == 0)
1201 WARN ((0, 0,
1202 _("%s is possibly continued on this volume: header contains truncated name"),
1203 quote (real_s_name)));
1204 else
1205 {
1206 WARN ((0, 0, _("%s is not continued on this volume"),
1207 quote (real_s_name)));
1208 return false;
1209 }
1210 }
1211
1212 s = continued_file_size + continued_file_offset;
1213
1214 if (real_s_totsize != s || s < continued_file_offset)
1215 {
1216 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1217 char s1buf[UINTMAX_STRSIZE_BOUND];
1218 char s2buf[UINTMAX_STRSIZE_BOUND];
1219
1220 WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1221 quote (continued_file_name),
1222 STRINGIFY_BIGINT (save_totsize, totsizebuf),
1223 STRINGIFY_BIGINT (continued_file_size, s1buf),
1224 STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1225 return false;
1226 }
1227
1228 if (real_s_totsize - real_s_sizeleft != continued_file_offset)
1229 {
1230 WARN ((0, 0, _("This volume is out of sequence")));
1231 return false;
1232 }
1233 }
1234
1235 increase_volume_number ();
1236 return true;
1237 }
1238
1239 \f
1240 /* Check the LABEL block against the volume label, seen as a globbing
1241 pattern. Return true if the pattern matches. In case of failure,
1242 retry matching a volume sequence number before giving up in
1243 multi-volume mode. */
1244 static bool
1245 check_label_pattern (union block *label)
1246 {
1247 char *string;
1248 bool result;
1249
1250 if (! memchr (label->header.name, '\0', sizeof label->header.name))
1251 return false;
1252
1253 if (fnmatch (volume_label_option, label->header.name, 0) == 0)
1254 return true;
1255
1256 if (!multi_volume_option)
1257 return false;
1258
1259 string = xmalloc (strlen (volume_label_option)
1260 + sizeof VOLUME_LABEL_APPEND + 1);
1261 strcpy (string, volume_label_option);
1262 strcat (string, VOLUME_LABEL_APPEND);
1263 result = fnmatch (string, label->header.name, 0) == 0;
1264 free (string);
1265 return result;
1266 }
1267
1268 /* Check if the next block contains a volume label and if this matches
1269 the one given in the command line */
1270 static void
1271 match_volume_label (void)
1272 {
1273 union block *label = find_next_block ();
1274
1275 if (!label)
1276 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1277 quote (volume_label_option)));
1278 if (!check_label_pattern (label))
1279 FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1280 quote_n (0, label->header.name),
1281 quote_n (1, volume_label_option)));
1282 }
1283
1284 /* Mark the archive with volume label STR. */
1285 static void
1286 _write_volume_label (const char *str)
1287 {
1288 if (archive_format == POSIX_FORMAT)
1289 xheader_store ("GNU.volume.label", NULL, str);
1290 else
1291 {
1292 union block *label = find_next_block ();
1293
1294 memset (label, 0, BLOCKSIZE);
1295
1296 strcpy (label->header.name, volume_label_option);
1297 assign_string (&current_stat_info.file_name,
1298 label->header.name);
1299 current_stat_info.had_trailing_slash =
1300 strip_trailing_slashes (current_stat_info.file_name);
1301
1302 label->header.typeflag = GNUTYPE_VOLHDR;
1303 TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1304 finish_header (&current_stat_info, label, -1);
1305 set_next_block_after (label);
1306 }
1307 }
1308
1309 #define VOL_SUFFIX "Volume"
1310
1311 /* Add a volume label to a part of multi-volume archive */
1312 static void
1313 add_volume_label (void)
1314 {
1315 char buf[UINTMAX_STRSIZE_BOUND];
1316 char *p = STRINGIFY_BIGINT (volno, buf);
1317 char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1318 + strlen (p) + 2);
1319 sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1320 _write_volume_label (s);
1321 free (s);
1322 }
1323
1324 static void
1325 add_chunk_header ()
1326 {
1327 if (archive_format == POSIX_FORMAT)
1328 {
1329 off_t block_ordinal;
1330 union block *blk;
1331 struct tar_stat_info st;
1332 static size_t real_s_part_no; /* FIXME */
1333
1334 real_s_part_no++;
1335 memset (&st, 0, sizeof st);
1336 st.orig_file_name = st.file_name = real_s_name;
1337 st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1338 st.stat.st_uid = getuid ();
1339 st.stat.st_gid = getgid ();
1340 st.orig_file_name = xheader_format_name (&st,
1341 "%d/GNUFileParts.%p/%f.%n",
1342 real_s_part_no);
1343 st.file_name = st.orig_file_name;
1344 st.archive_file_size = st.stat.st_size = real_s_sizeleft;
1345
1346 block_ordinal = current_block_ordinal ();
1347 blk = start_header (&st);
1348 if (!blk)
1349 abort (); /* FIXME */
1350 finish_header (&st, blk, block_ordinal);
1351 free (st.orig_file_name);
1352 }
1353 }
1354
1355
1356 /* Add a volume label to the current archive */
1357 static void
1358 write_volume_label (void)
1359 {
1360 if (multi_volume_option)
1361 add_volume_label ();
1362 else
1363 _write_volume_label (volume_label_option);
1364 }
1365
1366 /* Write GNU multi-volume header */
1367 static void
1368 gnu_add_multi_volume_header (void)
1369 {
1370 int tmp;
1371 union block *block = find_next_block ();
1372
1373 if (strlen (real_s_name) > NAME_FIELD_SIZE)
1374 WARN ((0, 0,
1375 _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1376 quotearg_colon (real_s_name)));
1377
1378 memset (block, 0, BLOCKSIZE);
1379
1380 /* FIXME: Michael P Urban writes: [a long name file] is being written
1381 when a new volume rolls around [...] Looks like the wrong value is
1382 being preserved in real_s_name, though. */
1383
1384 strncpy (block->header.name, real_s_name, NAME_FIELD_SIZE);
1385 block->header.typeflag = GNUTYPE_MULTIVOL;
1386
1387 OFF_TO_CHARS (real_s_sizeleft, block->header.size);
1388 OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
1389 block->oldgnu_header.offset);
1390
1391 tmp = verbose_option;
1392 verbose_option = 0;
1393 finish_header (&current_stat_info, block, -1);
1394 verbose_option = tmp;
1395 set_next_block_after (block);
1396 }
1397
1398 /* Add a multi volume header to the current archive. The exact header format
1399 depends on the archive format. */
1400 static void
1401 add_multi_volume_header (void)
1402 {
1403 if (archive_format == POSIX_FORMAT)
1404 {
1405 off_t d = real_s_totsize - real_s_sizeleft;
1406 xheader_store ("GNU.volume.filename", NULL, real_s_name);
1407 xheader_store ("GNU.volume.size", NULL, &real_s_sizeleft);
1408 xheader_store ("GNU.volume.offset", NULL, &d);
1409 }
1410 else
1411 gnu_add_multi_volume_header ();
1412 }
1413
1414 /* Synchronize multi-volume globals */
1415 static void
1416 multi_volume_sync ()
1417 {
1418 if (multi_volume_option)
1419 {
1420 if (save_name)
1421 {
1422 assign_string (&real_s_name,
1423 safer_name_suffix (save_name, false,
1424 absolute_names_option));
1425 real_s_totsize = save_totsize;
1426 real_s_sizeleft = save_sizeleft;
1427 }
1428 else
1429 {
1430 assign_string (&real_s_name, 0);
1431 real_s_totsize = 0;
1432 real_s_sizeleft = 0;
1433 }
1434 }
1435 }
1436
1437 \f
1438 /* Low-level flush functions */
1439
1440 /* Simple flush read (no multi-volume or label extensions) */
1441 static void
1442 simple_flush_read (void)
1443 {
1444 size_t status; /* result from system call */
1445
1446 do_checkpoint (false);
1447
1448 /* Clear the count of errors. This only applies to a single call to
1449 flush_read. */
1450
1451 read_error_count = 0; /* clear error count */
1452
1453 if (write_archive_to_stdout && record_start_block != 0)
1454 {
1455 archive = STDOUT_FILENO;
1456 status = sys_write_archive_buffer ();
1457 archive = STDIN_FILENO;
1458 if (status != record_size)
1459 archive_write_error (status);
1460 }
1461
1462 for (;;)
1463 {
1464 status = rmtread (archive, record_start->buffer, record_size);
1465 if (status == record_size)
1466 {
1467 records_read++;
1468 return;
1469 }
1470 if (status == SAFE_READ_ERROR)
1471 {
1472 archive_read_error ();
1473 continue; /* try again */
1474 }
1475 break;
1476 }
1477 short_read (status);
1478 }
1479
1480 /* Simple flush write (no multi-volume or label extensions) */
1481 static void
1482 simple_flush_write (size_t level __attribute__((unused)))
1483 {
1484 ssize_t status;
1485
1486 status = _flush_write ();
1487 if (status != record_size)
1488 archive_write_error (status);
1489 else
1490 {
1491 records_written++;
1492 bytes_written += status;
1493 }
1494 }
1495
1496 \f
1497 /* GNU flush functions. These support multi-volume and archive labels in
1498 GNU and PAX archive formats. */
1499
1500 static void
1501 _gnu_flush_read (void)
1502 {
1503 size_t status; /* result from system call */
1504
1505 do_checkpoint (false);
1506
1507 /* Clear the count of errors. This only applies to a single call to
1508 flush_read. */
1509
1510 read_error_count = 0; /* clear error count */
1511
1512 if (write_archive_to_stdout && record_start_block != 0)
1513 {
1514 archive = STDOUT_FILENO;
1515 status = sys_write_archive_buffer ();
1516 archive = STDIN_FILENO;
1517 if (status != record_size)
1518 archive_write_error (status);
1519 }
1520
1521 multi_volume_sync ();
1522
1523 for (;;)
1524 {
1525 status = rmtread (archive, record_start->buffer, record_size);
1526 if (status == record_size)
1527 {
1528 records_read++;
1529 return;
1530 }
1531
1532 /* The condition below used to include
1533 || (status > 0 && !read_full_records)
1534 This is incorrect since even if new_volume() succeeds, the
1535 subsequent call to rmtread will overwrite the chunk of data
1536 already read in the buffer, so the processing will fail */
1537 if ((status == 0
1538 || (status == SAFE_READ_ERROR && errno == ENOSPC))
1539 && multi_volume_option)
1540 {
1541 while (!try_new_volume ())
1542 ;
1543 return;
1544 }
1545 else if (status == SAFE_READ_ERROR)
1546 {
1547 archive_read_error ();
1548 continue;
1549 }
1550 break;
1551 }
1552 short_read (status);
1553 }
1554
1555 static void
1556 gnu_flush_read (void)
1557 {
1558 flush_read_ptr = simple_flush_read; /* Avoid recursion */
1559 _gnu_flush_read ();
1560 flush_read_ptr = gnu_flush_read;
1561 }
1562
1563 static void
1564 _gnu_flush_write (size_t buffer_level)
1565 {
1566 ssize_t status;
1567 union block *header;
1568 char *copy_ptr;
1569 size_t copy_size;
1570 size_t bufsize;
1571
1572 status = _flush_write ();
1573 if (status != record_size && !multi_volume_option)
1574 archive_write_error (status);
1575 else
1576 {
1577 records_written++;
1578 bytes_written += status;
1579 }
1580
1581 if (status == record_size)
1582 {
1583 multi_volume_sync ();
1584 return;
1585 }
1586
1587 /* In multi-volume mode. */
1588 /* ENXIO is for the UNIX PC. */
1589 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1590 archive_write_error (status);
1591
1592 if (!new_volume (ACCESS_WRITE))
1593 return;
1594
1595 xheader_destroy (&extended_header);
1596
1597 increase_volume_number ();
1598 prev_written += bytes_written;
1599 bytes_written = 0;
1600
1601 copy_ptr = record_start->buffer + status;
1602 copy_size = buffer_level - status;
1603 /* Switch to the next buffer */
1604 record_index = !record_index;
1605 init_buffer ();
1606
1607 if (volume_label_option)
1608 add_volume_label ();
1609
1610 if (real_s_name)
1611 add_multi_volume_header ();
1612
1613 write_extended (true, NULL, find_next_block ());
1614 if (real_s_name)
1615 add_chunk_header ();
1616 header = find_next_block ();
1617 bufsize = available_space_after (header);
1618 while (bufsize < copy_size)
1619 {
1620 memcpy (header->buffer, copy_ptr, bufsize);
1621 copy_ptr += bufsize;
1622 copy_size -= bufsize;
1623 set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
1624 header = find_next_block ();
1625 bufsize = available_space_after (header);
1626 }
1627 memcpy (header->buffer, copy_ptr, copy_size);
1628 memset (header->buffer + copy_size, 0, bufsize - copy_size);
1629 set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
1630 find_next_block ();
1631 }
1632
1633 static void
1634 gnu_flush_write (size_t buffer_level)
1635 {
1636 flush_write_ptr = simple_flush_write; /* Avoid recursion */
1637 _gnu_flush_write (buffer_level);
1638 flush_write_ptr = gnu_flush_write;
1639 }
1640
1641 void
1642 flush_read ()
1643 {
1644 flush_read_ptr ();
1645 }
1646
1647 void
1648 flush_write ()
1649 {
1650 flush_write_ptr (record_size);
1651 }
1652
1653 void
1654 open_archive (enum access_mode wanted_access)
1655 {
1656 flush_read_ptr = gnu_flush_read;
1657 flush_write_ptr = gnu_flush_write;
1658
1659 _open_archive (wanted_access);
1660 switch (wanted_access)
1661 {
1662 case ACCESS_READ:
1663 if (volume_label_option)
1664 match_volume_label ();
1665 break;
1666
1667 case ACCESS_WRITE:
1668 records_written = 0;
1669 if (volume_label_option)
1670 write_volume_label ();
1671 break;
1672
1673 default:
1674 break;
1675 }
1676 set_volume_start_time ();
1677 }
This page took 0.110937 seconds and 5 git commands to generate.