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