Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / contrib / tar / src / buffer.c
CommitLineData
984263bc
MD
1/* Buffer management for tar.
2
3 Copyright 1988, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001 Free
4 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/* $FreeBSD: src/contrib/tar/src/buffer.c,v 1.2.2.2 2002/10/11 14:32:25 sobomax Exp $ */
1de703da 23/* $DragonFly: src/contrib/tar/src/Attic/buffer.c,v 1.2 2003/06/17 04:24:06 dillon Exp $ */
984263bc
MD
24
25#include "system.h"
26
27#include <signal.h>
28
29#if MSDOS
30# include <process.h>
31#endif
32
33#if XENIX
34# include <sys/inode.h>
35#endif
36
37#include <fnmatch.h>
38#include <human.h>
39#include <quotearg.h>
40
41#include "common.h"
42#include "rmt.h"
43
44#define PREAD 0 /* read file descriptor from pipe() */
45#define PWRITE 1 /* write file descriptor from pipe() */
46
47/* Number of retries before giving up on read. */
48#define READ_ERROR_MAX 10
49
50/* Globbing pattern to append to volume label if initial match failed. */
51#define VOLUME_LABEL_APPEND " Volume [1-9]*"
52\f
53/* Variables. */
54
55static tarlong prev_written; /* bytes written on previous volumes */
56static tarlong bytes_written; /* bytes written on this volume */
57
58/* FIXME: The following variables should ideally be static to this
59 module. However, this cannot be done yet. The cleanup continues! */
60
61union block *record_start; /* start of record of archive */
62union block *record_end; /* last+1 block of archive record */
63union block *current_block; /* current block of archive */
64enum access_mode access_mode; /* how do we handle the archive */
65off_t records_read; /* number of records read from this archive */
66off_t records_written; /* likewise, for records written */
67
68static struct stat archive_stat; /* stat block for archive file */
69
70static off_t record_start_block; /* block ordinal at record_start */
71
72/* Where we write list messages (not errors, not interactions) to. Stdout
73 unless we're writing a pipe, in which case stderr. */
74FILE *stdlis;
75
76static void backspace_output PARAMS ((void));
77static int new_volume PARAMS ((enum access_mode));
78static void archive_write_error PARAMS ((ssize_t)) __attribute__ ((noreturn));
79static void archive_read_error PARAMS ((void));
80
81#if !MSDOS
82/* Obnoxious test to see if dimwit is trying to dump the archive. */
83dev_t ar_dev;
84ino_t ar_ino;
85#endif
86
87/* PID of child program, if compress_option or remote archive access. */
88static pid_t child_pid;
89
90/* Error recovery stuff */
91static int read_error_count;
92
93/* Have we hit EOF yet? */
94static int hit_eof;
95
96/* Checkpointing counter */
97static int checkpoint;
98
99/* We're reading, but we just read the last block and its time to update. */
100/* As least EXTERN like this one as possible. FIXME! */
101extern int time_to_start_writing;
102
103int file_to_switch_to = -1; /* if remote update, close archive, and use
104 this descriptor to write to */
105
106static int volno = 1; /* which volume of a multi-volume tape we're
107 on */
108static int global_volno = 1; /* volume number to print in external
109 messages */
110static pid_t grandchild_pid;
111
112/* The pointer save_name, which is set in function dump_file() of module
113 create.c, points to the original long filename instead of the new,
114 shorter mangled name that is set in start_header() of module create.c.
115 The pointer save_name is only used in multi-volume mode when the file
116 being processed is non-sparse; if a file is split between volumes, the
117 save_name is used in generating the LF_MULTIVOL record on the second
118 volume. (From Pierce Cantrell, 1991-08-13.) */
119
120char *save_name; /* name of the file we are currently writing */
121off_t save_totsize; /* total size of file we are writing, only
122 valid if save_name is nonzero */
123off_t save_sizeleft; /* where we are in the file we are writing,
124 only valid if save_name is nonzero */
125
126bool write_archive_to_stdout;
127
128/* Used by flush_read and flush_write to store the real info about saved
129 names. */
130static char *real_s_name;
131static off_t real_s_totsize;
132static off_t real_s_sizeleft;
133\f
134/* Functions. */
135
136void
137print_total_written (void)
138{
139 tarlong written = prev_written + bytes_written;
140 char bytes[sizeof (tarlong) * CHAR_BIT];
141 char abbr[LONGEST_HUMAN_READABLE + 1];
142 char rate[LONGEST_HUMAN_READABLE + 1];
143 double seconds;
144
145#if HAVE_CLOCK_GETTIME
146 struct timespec now;
147 if (clock_gettime (CLOCK_REALTIME, &now) == 0)
148 seconds = ((now.tv_sec - start_timespec.tv_sec)
149 + (now.tv_nsec - start_timespec.tv_nsec) / 1e9);
150 else
151#endif
152 seconds = time (0) - start_time;
153
154 sprintf (bytes, TARLONG_FORMAT, written);
155
156 /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*". */
157 fprintf (stderr, _("Total bytes written: %s (%sB, %sB/s)\n"), bytes,
158 human_readable ((uintmax_t) written, abbr, 1, -1024),
159 (0 < seconds && written / seconds < (uintmax_t) -1
160 ? human_readable ((uintmax_t) (written / seconds), rate, 1, -1024)
161 : "?"));
162}
163
164/* Compute and return the block ordinal at current_block. */
165off_t
166current_block_ordinal (void)
167{
168 return record_start_block + (current_block - record_start);
169}
170
171/* If the EOF flag is set, reset it, as well as current_block, etc. */
172void
173reset_eof (void)
174{
175 if (hit_eof)
176 {
177 hit_eof = 0;
178 current_block = record_start;
179 record_end = record_start + blocking_factor;
180 access_mode = ACCESS_WRITE;
181 }
182}
183
184/* Return the location of the next available input or output block.
185 Return zero for EOF. Once we have returned zero, we just keep returning
186 it, to avoid accidentally going on to the next file on the tape. */
187union block *
188find_next_block (void)
189{
190 if (current_block == record_end)
191 {
192 if (hit_eof)
193 return 0;
194 flush_archive ();
195 if (current_block == record_end)
196 {
197 hit_eof = 1;
198 return 0;
199 }
200 }
201 return current_block;
202}
203
204/* Indicate that we have used all blocks up thru BLOCK.
205 FIXME: should the arg have an off-by-1? */
206void
207set_next_block_after (union block *block)
208{
209 while (block >= current_block)
210 current_block++;
211
212 /* Do *not* flush the archive here. If we do, the same argument to
213 set_next_block_after could mean the next block (if the input record
214 is exactly one block long), which is not what is intended. */
215
216 if (current_block > record_end)
217 abort ();
218}
219
220/* Return the number of bytes comprising the space between POINTER
221 through the end of the current buffer of blocks. This space is
222 available for filling with data, or taking data from. POINTER is
223 usually (but not always) the result previous find_next_block call. */
224size_t
225available_space_after (union block *pointer)
226{
227 return record_end->buffer - pointer->buffer;
228}
229
230/* Close file having descriptor FD, and abort if close unsuccessful. */
231static void
232xclose (int fd)
233{
234 if (close (fd) != 0)
235 close_error (_("(pipe)"));
236}
237
238/* Duplicate file descriptor FROM into becoming INTO.
239 INTO is closed first and has to be the next available slot. */
240static void
241xdup2 (int from, int into)
242{
243 if (from != into)
244 {
245 int status = close (into);
246
247 if (status != 0 && errno != EBADF)
248 {
249 int e = errno;
250 FATAL_ERROR ((0, e, _("Cannot close")));
251 }
252 status = dup (from);
253 if (status != into)
254 {
255 if (status < 0)
256 {
257 int e = errno;
258 FATAL_ERROR ((0, e, _("Cannot dup")));
259 }
260 abort ();
261 }
262 xclose (from);
263 }
264}
265
266#if MSDOS
267
268/* Set ARCHIVE for writing, then compressing an archive. */
269static void
270child_open_for_compress (void)
271{
272 FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
273}
274
275/* Set ARCHIVE for uncompressing, then reading an archive. */
276static void
277child_open_for_uncompress (void)
278{
279 FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
280}
281
282#else /* not MSDOS */
283
284/* Return nonzero if NAME is the name of a regular file, or if the file
285 does not exist (so it would be created as a regular file). */
286static int
287is_regular_file (const char *name)
288{
289 struct stat stbuf;
290
291 if (stat (name, &stbuf) == 0)
292 return S_ISREG (stbuf.st_mode);
293 else
294 return errno == ENOENT;
295}
296
297static ssize_t
298write_archive_buffer (void)
299{
300 ssize_t status;
301 ssize_t written = 0;
302
303 while (0 <= (status = rmtwrite (archive, record_start->buffer + written,
304 record_size - written)))
305 {
306 written += status;
307 if (written == record_size
308 || _isrmt (archive)
309 || ! (S_ISFIFO (archive_stat.st_mode)
310 || S_ISSOCK (archive_stat.st_mode)))
311 break;
312 }
313
314 return written ? written : status;
315}
316
317/* Set ARCHIVE for writing, then compressing an archive. */
318static void
319child_open_for_compress (void)
320{
321 int parent_pipe[2];
322 int child_pipe[2];
323 int wait_status;
324
325 xpipe (parent_pipe);
326 child_pid = xfork ();
327
328 if (child_pid > 0)
329 {
330 /* The parent tar is still here! Just clean up. */
331
332 archive = parent_pipe[PWRITE];
333 xclose (parent_pipe[PREAD]);
334 return;
335 }
336
337 /* The new born child tar is here! */
338
339 program_name = _("tar (child)");
340
341 xdup2 (parent_pipe[PREAD], STDIN_FILENO);
342 xclose (parent_pipe[PWRITE]);
343
344 /* Check if we need a grandchild tar. This happens only if either:
345 a) we are writing stdout: to force reblocking;
346 b) the file is to be accessed by rmt: compressor doesn't know how;
347 c) the file is not a plain file. */
348
349 if (strcmp (archive_name_array[0], "-") != 0
350 && !_remdev (archive_name_array[0])
351 && is_regular_file (archive_name_array[0]))
352 {
353 if (backup_option)
354 maybe_backup_file (archive_name_array[0], 1);
355
356 /* We don't need a grandchild tar. Open the archive and launch the
357 compressor. */
358
359 archive = creat (archive_name_array[0], MODE_RW);
360 if (archive < 0)
361 {
362 int saved_errno = errno;
363
364 if (backup_option)
365 undo_last_backup ();
366 errno = saved_errno;
367 open_fatal (archive_name_array[0]);
368 }
369 xdup2 (archive, STDOUT_FILENO);
370 execlp (use_compress_program_option, use_compress_program_option,
371 (char *) 0);
372 exec_fatal (use_compress_program_option);
373 }
374
375 /* We do need a grandchild tar. */
376
377 xpipe (child_pipe);
378 grandchild_pid = xfork ();
379
380 if (grandchild_pid == 0)
381 {
382 /* The newborn grandchild tar is here! Launch the compressor. */
383
384 program_name = _("tar (grandchild)");
385
386 xdup2 (child_pipe[PWRITE], STDOUT_FILENO);
387 xclose (child_pipe[PREAD]);
388 execlp (use_compress_program_option, use_compress_program_option,
389 (char *) 0);
390 exec_fatal (use_compress_program_option);
391 }
392
393 /* The child tar is still here! */
394
395 /* Prepare for reblocking the data from the compressor into the archive. */
396
397 xdup2 (child_pipe[PREAD], STDIN_FILENO);
398 xclose (child_pipe[PWRITE]);
399
400 if (strcmp (archive_name_array[0], "-") == 0)
401 archive = STDOUT_FILENO;
402 else
403 {
404 archive = rmtcreat (archive_name_array[0], MODE_RW, rsh_command_option);
405 if (archive < 0)
406 open_fatal (archive_name_array[0]);
407 }
408
409 /* Let's read out of the stdin pipe and write an archive. */
410
411 while (1)
412 {
413 ssize_t status = 0;
414 char *cursor;
415 size_t length;
416
417 /* Assemble a record. */
418
419 for (length = 0, cursor = record_start->buffer;
420 length < record_size;
421 length += status, cursor += status)
422 {
423 size_t size = record_size - length;
424
425 if (size < BLOCKSIZE)
426 size = BLOCKSIZE;
427 status = safe_read (STDIN_FILENO, cursor, size);
428 if (status <= 0)
429 break;
430 }
431
432 if (status < 0)
433 read_fatal (use_compress_program_option);
434
435 /* Copy the record. */
436
437 if (status == 0)
438 {
439 /* We hit the end of the file. Write last record at
440 full length, as the only role of the grandchild is
441 doing proper reblocking. */
442
443 if (length > 0)
444 {
445 memset (record_start->buffer + length, 0, record_size - length);
446 status = write_archive_buffer ();
447 if (status != record_size)
448 archive_write_error (status);
449 }
450
451 /* There is nothing else to read, break out. */
452 break;
453 }
454
455 status = write_archive_buffer ();
456 if (status != record_size)
457 archive_write_error (status);
458 }
459
460#if 0
461 close_archive ();
462#endif
463
464 /* Propagate any failure of the grandchild back to the parent. */
465
466 while (waitpid (grandchild_pid, &wait_status, 0) == -1)
467 if (errno != EINTR)
468 {
469 waitpid_error (use_compress_program_option);
470 break;
471 }
472
473 if (WIFSIGNALED (wait_status))
474 {
475 kill (child_pid, WTERMSIG (wait_status));
476 exit_status = TAREXIT_FAILURE;
477 }
478 else if (WEXITSTATUS (wait_status) != 0)
479 exit_status = WEXITSTATUS (wait_status);
480
481 exit (exit_status);
482}
483
484static void
485sig_propagate(int sig)
486{
487 kill (grandchild_pid, sig);
488 exit (TAREXIT_FAILURE);
489}
490
491/* Set ARCHIVE for uncompressing, then reading an archive. */
492static void
493child_open_for_uncompress (void)
494{
495 int parent_pipe[2];
496 int child_pipe[2];
497 int wait_status;
498
499 xpipe (parent_pipe);
500 child_pid = xfork ();
501
502 if (child_pid > 0)
503 {
504 /* The parent tar is still here! Just clean up. */
505
506 read_full_records_option = 1;
507 archive = parent_pipe[PREAD];
508 xclose (parent_pipe[PWRITE]);
509 return;
510 }
511
512 /* The newborn child tar is here! */
513
514 program_name = _("tar (child)");
515
516 xdup2 (parent_pipe[PWRITE], STDOUT_FILENO);
517 xclose (parent_pipe[PREAD]);
518
519 /* Check if we need a grandchild tar. This happens only if either:
520 a) we're reading stdin: to force unblocking;
521 b) the file is to be accessed by rmt: compressor doesn't know how;
522 c) the file is not a plain file. */
523
524 if (strcmp (archive_name_array[0], "-") != 0
525 && !_remdev (archive_name_array[0])
526 && is_regular_file (archive_name_array[0]))
527 {
528 /* We don't need a grandchild tar. Open the archive and lauch the
529 uncompressor. */
530
531 archive = open (archive_name_array[0], O_RDONLY | O_BINARY, MODE_RW);
532 if (archive < 0)
533 open_fatal (archive_name_array[0]);
534 xdup2 (archive, STDIN_FILENO);
535 execlp (use_compress_program_option, use_compress_program_option,
536 "-d", (char *) 0);
537 exec_fatal (use_compress_program_option);
538 }
539
540 /* We do need a grandchild tar. */
541
542 xpipe (child_pipe);
543 grandchild_pid = xfork ();
544
545 if (grandchild_pid == 0)
546 {
547 /* The newborn grandchild tar is here! Launch the uncompressor. */
548
549 program_name = _("tar (grandchild)");
550
551 xdup2 (child_pipe[PREAD], STDIN_FILENO);
552 xclose (child_pipe[PWRITE]);
553 execlp (use_compress_program_option, use_compress_program_option,
554 "-d", (char *) 0);
555 exec_fatal (use_compress_program_option);
556 }
557
558 /* The child tar is still here! */
559 signal (SIGTERM, sig_propagate);
560
561 /* Prepare for unblocking the data from the archive into the
562 uncompressor. */
563
564 xdup2 (child_pipe[PWRITE], STDOUT_FILENO);
565 xclose (child_pipe[PREAD]);
566
567 if (strcmp (archive_name_array[0], "-") == 0)
568 archive = STDIN_FILENO;
569 else
570 archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
571 MODE_RW, rsh_command_option);
572 if (archive < 0)
573 open_fatal (archive_name_array[0]);
574
575 /* Let's read the archive and pipe it into stdout. */
576
577 while (1)
578 {
579 char *cursor;
580 size_t maximum;
581 size_t count;
582 ssize_t status;
583
584 read_error_count = 0;
585
586 error_loop:
587 status = rmtread (archive, record_start->buffer, record_size);
588 if (status < 0)
589 {
590 archive_read_error ();
591 goto error_loop;
592 }
593 if (status == 0)
594 break;
595 cursor = record_start->buffer;
596 maximum = status;
597 while (maximum)
598 {
599 count = maximum < BLOCKSIZE ? maximum : BLOCKSIZE;
600 if (full_write (STDOUT_FILENO, cursor, count) != count)
601 write_error (use_compress_program_option);
602 cursor += count;
603 maximum -= count;
604 }
605 }
606
607 xclose (STDOUT_FILENO);
608#if 0
609 close_archive ();
610#endif
611
612 /* Propagate any failure of the grandchild back to the parent. */
613
614 while (waitpid (grandchild_pid, &wait_status, 0) == -1)
615 if (errno != EINTR)
616 {
617 waitpid_error (use_compress_program_option);
618 break;
619 }
620
621 if (WIFSIGNALED (wait_status))
622 {
623 kill (child_pid, WTERMSIG (wait_status));
624 exit_status = TAREXIT_FAILURE;
625 }
626 else if (WEXITSTATUS (wait_status) != 0)
627 exit_status = WEXITSTATUS (wait_status);
628
629 exit (exit_status);
630}
631
632#endif /* not MSDOS */
633
634/* Check the LABEL block against the volume label, seen as a globbing
635 pattern. Return true if the pattern matches. In case of failure,
636 retry matching a volume sequence number before giving up in
637 multi-volume mode. */
638static int
639check_label_pattern (union block *label)
640{
641 char *string;
642 int result;
643
644 if (! memchr (label->header.name, '\0', sizeof label->header.name))
645 return 0;
646
647 if (fnmatch (volume_label_option, label->header.name, 0) == 0)
648 return 1;
649
650 if (!multi_volume_option)
651 return 0;
652
653 string = xmalloc (strlen (volume_label_option)
654 + sizeof VOLUME_LABEL_APPEND + 1);
655 strcpy (string, volume_label_option);
656 strcat (string, VOLUME_LABEL_APPEND);
657 result = fnmatch (string, label->header.name, 0) == 0;
658 free (string);
659 return result;
660}
661
662/* Open an archive file. The argument specifies whether we are
663 reading or writing, or both. */
664void
665open_archive (enum access_mode wanted_access)
666{
667 int backed_up_flag = 0;
668
669 stdlis = to_stdout_option ? stderr : stdout;
670
671 if (record_size == 0)
672 FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
673
674 if (archive_names == 0)
675 FATAL_ERROR ((0, 0, _("No archive name given")));
676
677 current_file_name = 0;
678 current_link_name = 0;
679 save_name = 0;
680 real_s_name = 0;
681
682 if (multi_volume_option)
683 {
684 if (verify_option)
685 FATAL_ERROR ((0, 0, _("Cannot verify multi-volume archives")));
686 record_start = valloc (record_size + (2 * BLOCKSIZE));
687 if (record_start)
688 record_start += 2;
689 }
690 else
691 record_start = valloc (record_size);
692 if (!record_start)
693 FATAL_ERROR ((0, 0, _("Cannot allocate memory for blocking factor %d"),
694 blocking_factor));
695
696 current_block = record_start;
697 record_end = record_start + blocking_factor;
698 /* When updating the archive, we start with reading. */
699 access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
700
701 if (use_compress_program_option)
702 {
703 if (multi_volume_option)
704 FATAL_ERROR ((0, 0, _("Cannot use multi-volume compressed archives")));
705 if (verify_option)
706 FATAL_ERROR ((0, 0, _("Cannot verify compressed archives")));
707
708 switch (wanted_access)
709 {
710 case ACCESS_READ:
711 child_open_for_uncompress ();
712 break;
713
714 case ACCESS_WRITE:
715 child_open_for_compress ();
716 break;
717
718 case ACCESS_UPDATE:
719 FATAL_ERROR ((0, 0, _("Cannot update compressed archives")));
720 break;
721 }
722
723 if (wanted_access == ACCESS_WRITE
724 && strcmp (archive_name_array[0], "-") == 0)
725 stdlis = stderr;
726 }
727 else if (strcmp (archive_name_array[0], "-") == 0)
728 {
729 read_full_records_option = 1; /* could be a pipe, be safe */
730 if (verify_option)
731 FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
732
733 switch (wanted_access)
734 {
735 case ACCESS_READ:
736 archive = STDIN_FILENO;
737 break;
738
739 case ACCESS_WRITE:
740 archive = STDOUT_FILENO;
741 stdlis = stderr;
742 break;
743
744 case ACCESS_UPDATE:
745 archive = STDIN_FILENO;
746 stdlis = stderr;
747 write_archive_to_stdout = 1;
748 break;
749 }
750 }
751 else if (verify_option)
752 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
753 MODE_RW, rsh_command_option);
754 else
755 switch (wanted_access)
756 {
757 case ACCESS_READ:
758 archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
759 MODE_RW, rsh_command_option);
760 break;
761
762 case ACCESS_WRITE:
763 if (backup_option)
764 {
765 maybe_backup_file (archive_name_array[0], 1);
766 backed_up_flag = 1;
767 }
768 archive = rmtcreat (archive_name_array[0], MODE_RW,
769 rsh_command_option);
770 break;
771
772 case ACCESS_UPDATE:
773 archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
774 MODE_RW, rsh_command_option);
775 break;
776 }
777
778 if (archive < 0
779 || (! _isrmt (archive) && fstat (archive, &archive_stat) < 0))
780 {
781 int saved_errno = errno;
782
783 if (backed_up_flag)
784 undo_last_backup ();
785 errno = saved_errno;
786 open_fatal (archive_name_array[0]);
787 }
788
789#if !MSDOS
790
791 /* Detect if outputting to "/dev/null". */
792 {
793 static char const dev_null[] = "/dev/null";
794 struct stat dev_null_stat;
795
796 dev_null_output =
797 (strcmp (archive_name_array[0], dev_null) == 0
798 || (! _isrmt (archive)
799 && S_ISCHR (archive_stat.st_mode)
800 && stat (dev_null, &dev_null_stat) == 0
801 && archive_stat.st_dev == dev_null_stat.st_dev
802 && archive_stat.st_ino == dev_null_stat.st_ino));
803 }
804
805 if (!_isrmt (archive) && S_ISREG (archive_stat.st_mode))
806 {
807 ar_dev = archive_stat.st_dev;
808 ar_ino = archive_stat.st_ino;
809 }
810 else
811 ar_dev = 0;
812
813#endif /* not MSDOS */
814
815#if MSDOS
816 setmode (archive, O_BINARY);
817#endif
818
819 switch (wanted_access)
820 {
821 case ACCESS_UPDATE:
822 records_written = 0;
823 case ACCESS_READ:
824 records_read = 0;
825 record_end = record_start; /* set up for 1st record = # 0 */
826 find_next_block (); /* read it in, check for EOF */
827
828 if (volume_label_option)
829 {
830 union block *label = find_next_block ();
831
832 if (!label)
833 FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
834 quote (volume_label_option)));
835 if (!check_label_pattern (label))
836 FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
837 quote_n (0, label->header.name),
838 quote_n (1, volume_label_option)));
839 }
840 break;
841
842 case ACCESS_WRITE:
843 records_written = 0;
844 if (volume_label_option)
845 {
846 memset (record_start, 0, BLOCKSIZE);
847 if (multi_volume_option)
848 sprintf (record_start->header.name, "%s Volume 1",
849 volume_label_option);
850 else
851 strcpy (record_start->header.name, volume_label_option);
852
853 assign_string (&current_file_name, record_start->header.name);
854
855 record_start->header.typeflag = GNUTYPE_VOLHDR;
856 TIME_TO_CHARS (start_time, record_start->header.mtime);
857 finish_header (record_start);
858#if 0
859 current_block++;
860#endif
861 }
862 break;
863 }
864}
865
866/* Perform a write to flush the buffer. */
867void
868flush_write (void)
869{
870 int copy_back;
871 ssize_t status;
872
873 if (checkpoint_option && !(++checkpoint % 10))
874 WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
875
876 if (tape_length_option && tape_length_option <= bytes_written)
877 {
878 errno = ENOSPC;
879 status = 0;
880 }
881 else if (dev_null_output)
882 status = record_size;
883 else
884 status = write_archive_buffer ();
885 if (status != record_size && !multi_volume_option)
886 archive_write_error (status);
887
888 if (status > 0)
889 {
890 records_written++;
891 bytes_written += status;
892 }
893
894 if (status == record_size)
895 {
896 if (multi_volume_option)
897 {
898 char *cursor;
899
900 if (!save_name)
901 {
902 assign_string (&real_s_name, 0);
903 real_s_totsize = 0;
904 real_s_sizeleft = 0;
905 return;
906 }
907
908 cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
909 while (ISSLASH (*cursor))
910 cursor++;
911
912 assign_string (&real_s_name, cursor);
913 real_s_totsize = save_totsize;
914 real_s_sizeleft = save_sizeleft;
915 }
916 return;
917 }
918
919 /* We're multivol. Panic if we didn't get the right kind of response. */
920
921 /* ENXIO is for the UNIX PC. */
922 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
923 archive_write_error (status);
924
925 /* If error indicates a short write, we just move to the next tape. */
926
927 if (!new_volume (ACCESS_WRITE))
928 return;
929
930 if (totals_option)
931 prev_written += bytes_written;
932 bytes_written = 0;
933
934 if (volume_label_option && real_s_name)
935 {
936 copy_back = 2;
937 record_start -= 2;
938 }
939 else if (volume_label_option || real_s_name)
940 {
941 copy_back = 1;
942 record_start--;
943 }
944 else
945 copy_back = 0;
946
947 if (volume_label_option)
948 {
949 memset (record_start, 0, BLOCKSIZE);
950 sprintf (record_start->header.name, "%s Volume %d",
951 volume_label_option, volno);
952 TIME_TO_CHARS (start_time, record_start->header.mtime);
953 record_start->header.typeflag = GNUTYPE_VOLHDR;
954 finish_header (record_start);
955 }
956
957 if (real_s_name)
958 {
959 int tmp;
960
961 if (volume_label_option)
962 record_start++;
963
964 memset (record_start, 0, BLOCKSIZE);
965
966 /* FIXME: Michael P Urban writes: [a long name file] is being written
967 when a new volume rolls around [...] Looks like the wrong value is
968 being preserved in real_s_name, though. */
969
970 strcpy (record_start->header.name, real_s_name);
971 record_start->header.typeflag = GNUTYPE_MULTIVOL;
972 OFF_TO_CHARS (real_s_sizeleft, record_start->header.size);
973 OFF_TO_CHARS (real_s_totsize - real_s_sizeleft,
974 record_start->oldgnu_header.offset);
975 tmp = verbose_option;
976 verbose_option = 0;
977 finish_header (record_start);
978 verbose_option = tmp;
979
980 if (volume_label_option)
981 record_start--;
982 }
983
984 status = write_archive_buffer ();
985 if (status != record_size)
986 archive_write_error (status);
987
988 bytes_written += status;
989
990 if (copy_back)
991 {
992 record_start += copy_back;
993 memcpy (current_block,
994 record_start + blocking_factor - copy_back,
995 copy_back * BLOCKSIZE);
996 current_block += copy_back;
997
998 if (real_s_sizeleft >= copy_back * BLOCKSIZE)
999 real_s_sizeleft -= copy_back * BLOCKSIZE;
1000 else if ((real_s_sizeleft + BLOCKSIZE - 1) / BLOCKSIZE <= copy_back)
1001 assign_string (&real_s_name, 0);
1002 else
1003 {
1004 char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
1005
1006 while (ISSLASH (*cursor))
1007 cursor++;
1008
1009 assign_string (&real_s_name, cursor);
1010 real_s_sizeleft = save_sizeleft;
1011 real_s_totsize = save_totsize;
1012 }
1013 copy_back = 0;
1014 }
1015}
1016
1017/* Handle write errors on the archive. Write errors are always fatal.
1018 Hitting the end of a volume does not cause a write error unless the
1019 write was the first record of the volume. */
1020static void
1021archive_write_error (ssize_t status)
1022{
1023 /* It might be useful to know how much was written before the error
1024 occurred. */
1025 if (totals_option)
1026 {
1027 int e = errno;
1028 print_total_written ();
1029 errno = e;
1030 }
1031
1032 write_fatal_details (*archive_name_cursor, status, record_size);
1033}
1034
1035/* Handle read errors on the archive. If the read should be retried,
1036 return to the caller. */
1037static void
1038archive_read_error (void)
1039{
1040 read_error (*archive_name_cursor);
1041
1042 if (record_start_block == 0)
1043 FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
1044
1045 /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
1046 then give up on reading the archive. */
1047
1048 if (read_error_count++ > READ_ERROR_MAX)
1049 FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
1050 return;
1051}
1052
1053/* Perform a read to flush the buffer. */
1054void
1055flush_read (void)
1056{
1057 ssize_t status; /* result from system call */
1058 size_t left; /* bytes left */
1059 char *more; /* pointer to next byte to read */
1060
1061 if (checkpoint_option && !(++checkpoint % 10))
1062 WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
1063
1064 /* Clear the count of errors. This only applies to a single call to
1065 flush_read. */
1066
1067 read_error_count = 0; /* clear error count */
1068
1069 if (write_archive_to_stdout && record_start_block != 0)
1070 {
1071 archive = STDOUT_FILENO;
1072 status = write_archive_buffer ();
1073 archive = STDIN_FILENO;
1074 if (status != record_size)
1075 archive_write_error (status);
1076 }
1077 if (multi_volume_option)
1078 {
1079 if (save_name)
1080 {
1081 char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
1082
1083 while (ISSLASH (*cursor))
1084 cursor++;
1085
1086 assign_string (&real_s_name, cursor);
1087 real_s_sizeleft = save_sizeleft;
1088 real_s_totsize = save_totsize;
1089 }
1090 else
1091 {
1092 assign_string (&real_s_name, 0);
1093 real_s_totsize = 0;
1094 real_s_sizeleft = 0;
1095 }
1096 }
1097
1098 error_loop:
1099 status = rmtread (archive, record_start->buffer, record_size);
1100 if (status == record_size)
1101 {
1102 records_read++;
1103 return;
1104 }
1105
1106 if ((status == 0
1107 || (status < 0 && errno == ENOSPC)
1108 || (status > 0 && !read_full_records_option))
1109 && multi_volume_option)
1110 {
1111 union block *cursor;
1112
1113 try_volume:
1114 switch (subcommand_option)
1115 {
1116 case APPEND_SUBCOMMAND:
1117 case CAT_SUBCOMMAND:
1118 case UPDATE_SUBCOMMAND:
1119 if (!new_volume (ACCESS_UPDATE))
1120 return;
1121 break;
1122
1123 default:
1124 if (!new_volume (ACCESS_READ))
1125 return;
1126 break;
1127 }
1128
1129 vol_error:
1130 status = rmtread (archive, record_start->buffer, record_size);
1131 if (status < 0)
1132 {
1133 archive_read_error ();
1134 goto vol_error;
1135 }
1136 if (status != record_size)
1137 goto short_read;
1138
1139 cursor = record_start;
1140
1141 if (cursor->header.typeflag == GNUTYPE_VOLHDR)
1142 {
1143 if (volume_label_option)
1144 {
1145 if (!check_label_pattern (cursor))
1146 {
1147 WARN ((0, 0, _("Volume %s does not match %s"),
1148 quote_n (0, cursor->header.name),
1149 quote_n (1, volume_label_option)));
1150 volno--;
1151 global_volno--;
1152 goto try_volume;
1153 }
1154 }
1155 if (verbose_option)
1156 fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
1157 cursor++;
1158 }
1159 else if (volume_label_option)
1160 WARN ((0, 0, _("WARNING: No volume header")));
1161
1162 if (real_s_name)
1163 {
1164 uintmax_t s1, s2;
1165 if (cursor->header.typeflag != GNUTYPE_MULTIVOL
1166 || strcmp (cursor->header.name, real_s_name))
1167 {
1168 WARN ((0, 0, _("%s is not continued on this volume"),
1169 quote (real_s_name)));
1170 volno--;
1171 global_volno--;
1172 goto try_volume;
1173 }
1174 s1 = UINTMAX_FROM_HEADER (cursor->header.size);
1175 s2 = UINTMAX_FROM_HEADER (cursor->oldgnu_header.offset);
1176 if (real_s_totsize != s1 + s2 || s1 + s2 < s2)
1177 {
1178 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1179 char s1buf[UINTMAX_STRSIZE_BOUND];
1180 char s2buf[UINTMAX_STRSIZE_BOUND];
1181
1182 WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1183 quote (cursor->header.name),
1184 STRINGIFY_BIGINT (save_totsize, totsizebuf),
1185 STRINGIFY_BIGINT (s1, s1buf),
1186 STRINGIFY_BIGINT (s2, s2buf)));
1187 volno--;
1188 global_volno--;
1189 goto try_volume;
1190 }
1191 if (real_s_totsize - real_s_sizeleft
1192 != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
1193 {
1194 WARN ((0, 0, _("This volume is out of sequence")));
1195 volno--;
1196 global_volno--;
1197 goto try_volume;
1198 }
1199 cursor++;
1200 }
1201 current_block = cursor;
1202 records_read++;
1203 return;
1204 }
1205 else if (status < 0)
1206 {
1207 archive_read_error ();
1208 goto error_loop; /* try again */
1209 }
1210
1211 short_read:
1212 more = record_start->buffer + status;
1213 left = record_size - status;
1214
1215 while (left % BLOCKSIZE != 0
1216 || (left && status && read_full_records_option))
1217 {
1218 if (status)
1219 while ((status = rmtread (archive, more, left)) < 0)
1220 archive_read_error ();
1221
1222 if (status == 0)
1223 break;
1224
1225 if (! read_full_records_option)
1226 FATAL_ERROR ((0, 0, _("Unaligned block (%lu bytes) in archive"),
1227 (unsigned long) (record_size - left)));
1228
1229 /* User warned us about this. Fix up. */
1230
1231 left -= status;
1232 more += status;
1233 }
1234
1235 /* FIXME: for size=0, multi-volume support. On the first record, warn
1236 about the problem. */
1237
1238 if (!read_full_records_option && verbose_option
1239 && record_start_block == 0 && status > 0)
1240 WARN ((0, 0, _("Record size = %lu blocks"),
1241 (unsigned long) ((record_size - left) / BLOCKSIZE)));
1242
1243 record_end = record_start + (record_size - left) / BLOCKSIZE;
1244 records_read++;
1245}
1246
1247/* Flush the current buffer to/from the archive. */
1248void
1249flush_archive (void)
1250{
1251 record_start_block += record_end - record_start;
1252 current_block = record_start;
1253 record_end = record_start + blocking_factor;
1254
1255 if (access_mode == ACCESS_READ && time_to_start_writing)
1256 {
1257 access_mode = ACCESS_WRITE;
1258 time_to_start_writing = 0;
1259
1260 if (file_to_switch_to >= 0)
1261 {
1262 if (rmtclose (archive) != 0)
1263 close_warn (*archive_name_cursor);
1264
1265 archive = file_to_switch_to;
1266 }
1267 else
1268 backspace_output ();
1269 }
1270
1271 switch (access_mode)
1272 {
1273 case ACCESS_READ:
1274 flush_read ();
1275 break;
1276
1277 case ACCESS_WRITE:
1278 flush_write ();
1279 break;
1280
1281 case ACCESS_UPDATE:
1282 abort ();
1283 }
1284}
1285
1286/* Backspace the archive descriptor by one record worth. If it's a
1287 tape, MTIOCTOP will work. If it's something else, try to seek on
1288 it. If we can't seek, we lose! */
1289static void
1290backspace_output (void)
1291{
1292#ifdef MTIOCTOP
1293 {
1294 struct mtop operation;
1295
1296 operation.mt_op = MTBSR;
1297 operation.mt_count = 1;
1298 if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1299 return;
1300 if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1301 return;
1302 }
1303#endif
1304
1305 {
1306 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1307
1308 /* Seek back to the beginning of this record and start writing there. */
1309
1310 position -= record_size;
1311 if (position < 0)
1312 position = 0;
1313 if (rmtlseek (archive, position, SEEK_SET) != position)
1314 {
1315 /* Lseek failed. Try a different method. */
1316
1317 WARN ((0, 0,
1318 _("Cannot backspace archive file; it may be unreadable without -i")));
1319
1320 /* Replace the first part of the record with NULs. */
1321
1322 if (record_start->buffer != output_start)
1323 memset (record_start->buffer, 0,
1324 output_start - record_start->buffer);
1325 }
1326 }
1327}
1328
1329/* Close the archive file. */
1330void
1331close_archive (void)
1332{
1333 if (time_to_start_writing || access_mode == ACCESS_WRITE)
1334 flush_archive ();
1335
1336#if !MSDOS
1337
1338 /* Manage to fully drain a pipe we might be reading, so to not break it on
1339 the producer after the EOF block. FIXME: one of these days, GNU tar
1340 might become clever enough to just stop working, once there is no more
1341 work to do, we might have to revise this area in such time. */
1342
1343 if (fast_read_option && namelist_freed && child_pid > 0)
1344 kill(child_pid, SIGTERM);
1345
1346 if (access_mode == ACCESS_READ
1347 && ! _isrmt (archive)
1348 && (S_ISFIFO (archive_stat.st_mode) || S_ISSOCK (archive_stat.st_mode)))
1349 while (rmtread (archive, record_start->buffer, record_size) > 0)
1350 continue;
1351#endif
1352
1353 if (verify_option)
1354 verify_volume ();
1355
1356 if (rmtclose (archive) != 0)
1357 close_warn (*archive_name_cursor);
1358
1359#if !MSDOS
1360
1361 if (child_pid)
1362 {
1363 int wait_status;
1364
1365 while (waitpid (child_pid, &wait_status, 0) == -1)
1366 if (errno != EINTR)
1367 {
1368 waitpid_error (use_compress_program_option);
1369 break;
1370 }
1371
1372 if (!fast_read_option || !namelist_freed)
1373 if (WIFSIGNALED (wait_status))
1374 ERROR ((0, 0, _("Child died with signal %d"),
1375 WTERMSIG (wait_status)));
1376 else if (WEXITSTATUS (wait_status) != 0)
1377 ERROR ((0, 0, _("Child returned status %d"),
1378 WEXITSTATUS (wait_status)));
1379 }
1380#endif /* !MSDOS */
1381
1382 if (current_file_name)
1383 free (current_file_name);
1384 if (current_link_name)
1385 free (current_link_name);
1386 if (save_name)
1387 free (save_name);
1388 if (real_s_name)
1389 free (real_s_name);
1390 free (multi_volume_option ? record_start - 2 : record_start);
1391}
1392
1393/* Called to initialize the global volume number. */
1394void
1395init_volume_number (void)
1396{
1397 FILE *file = fopen (volno_file_option, "r");
1398
1399 if (file)
1400 {
1401 if (fscanf (file, "%d", &global_volno) != 1
1402 || global_volno < 0)
1403 FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1404 quotearg_colon (volno_file_option)));
1405 if (ferror (file))
1406 read_error (volno_file_option);
1407 if (fclose (file) != 0)
1408 close_error (volno_file_option);
1409 }
1410 else if (errno != ENOENT)
1411 open_error (volno_file_option);
1412}
1413
1414/* Called to write out the closing global volume number. */
1415void
1416closeout_volume_number (void)
1417{
1418 FILE *file = fopen (volno_file_option, "w");
1419
1420 if (file)
1421 {
1422 fprintf (file, "%d\n", global_volno);
1423 if (ferror (file))
1424 write_error (volno_file_option);
1425 if (fclose (file) != 0)
1426 close_error (volno_file_option);
1427 }
1428 else
1429 open_error (volno_file_option);
1430}
1431
1432/* We've hit the end of the old volume. Close it and open the next one.
1433 Return nonzero on success. */
1434static int
1435new_volume (enum access_mode access)
1436{
1437 static FILE *read_file;
1438 static int looped;
1439
1440 if (!read_file && !info_script_option)
1441 /* FIXME: if fopen is used, it will never be closed. */
1442 read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1443
1444 if (now_verifying)
1445 return 0;
1446 if (verify_option)
1447 verify_volume ();
1448
1449 if (rmtclose (archive) != 0)
1450 close_warn (*archive_name_cursor);
1451
1452 global_volno++;
1453 if (global_volno < 0)
1454 FATAL_ERROR ((0, 0, _("Volume number overflow")));
1455 volno++;
1456 archive_name_cursor++;
1457 if (archive_name_cursor == archive_name_array + archive_names)
1458 {
1459 archive_name_cursor = archive_name_array;
1460 looped = 1;
1461 }
1462
1463 tryagain:
1464 if (looped)
1465 {
1466 /* We have to prompt from now on. */
1467
1468 if (info_script_option)
1469 {
1470 if (volno_file_option)
1471 closeout_volume_number ();
1472 if (system (info_script_option) != 0)
1473 FATAL_ERROR ((0, 0, _("`%s' command failed"), info_script_option));
1474 }
1475 else
1476 while (1)
1477 {
1478 char input_buffer[80];
1479
1480 fputc ('\007', stderr);
1481 fprintf (stderr,
1482 _("Prepare volume #%d for %s and hit return: "),
1483 global_volno, quote (*archive_name_cursor));
1484 fflush (stderr);
1485
1486 if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1487 {
1488 WARN ((0, 0, _("EOF where user reply was expected")));
1489
1490 if (subcommand_option != EXTRACT_SUBCOMMAND
1491 && subcommand_option != LIST_SUBCOMMAND
1492 && subcommand_option != DIFF_SUBCOMMAND)
1493 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1494
1495 fatal_exit ();
1496 }
1497 if (input_buffer[0] == '\n'
1498 || input_buffer[0] == 'y'
1499 || input_buffer[0] == 'Y')
1500 break;
1501
1502 switch (input_buffer[0])
1503 {
1504 case '?':
1505 {
1506 fprintf (stderr, _("\
1507 n [name] Give a new file name for the next (and subsequent) volume(s)\n\
1508 q Abort tar\n\
1509 ! Spawn a subshell\n\
1510 ? Print this list\n"));
1511 }
1512 break;
1513
1514 case 'q':
1515 /* Quit. */
1516
1517 WARN ((0, 0, _("No new volume; exiting.\n")));
1518
1519 if (subcommand_option != EXTRACT_SUBCOMMAND
1520 && subcommand_option != LIST_SUBCOMMAND
1521 && subcommand_option != DIFF_SUBCOMMAND)
1522 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1523
1524 fatal_exit ();
1525
1526 case 'n':
1527 /* Get new file name. */
1528
1529 {
1530 char *name = &input_buffer[1];
1531 char *cursor;
1532
1533 while (*name == ' ' || *name == '\t')
1534 name++;
1535 cursor = name;
1536 while (*cursor && *cursor != '\n')
1537 cursor++;
1538 *cursor = '\0';
1539
1540 /* FIXME: the following allocation is never reclaimed. */
1541 *archive_name_cursor = xstrdup (name);
1542 }
1543 break;
1544
1545 case '!':
1546#if MSDOS
1547 spawnl (P_WAIT, getenv ("COMSPEC"), "-", 0);
1548#else /* not MSDOS */
1549 {
1550 pid_t child;
1551 const char *shell = getenv ("SHELL");
1552 if (! shell)
1553 shell = "/bin/sh";
1554 child = xfork ();
1555 if (child == 0)
1556 {
1557 execlp (shell, "-sh", "-i", (char *) 0);
1558 exec_fatal (shell);
1559 }
1560 else
1561 {
1562 int wait_status;
1563 while (waitpid (child, &wait_status, 0) == -1)
1564 if (errno != EINTR)
1565 {
1566 waitpid_error (shell);
1567 break;
1568 }
1569 }
1570 }
1571#endif /* not MSDOS */
1572 break;
1573 }
1574 }
1575 }
1576
1577 if (verify_option)
1578 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1579 rsh_command_option);
1580 else
1581 switch (access)
1582 {
1583 case ACCESS_READ:
1584 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1585 rsh_command_option);
1586 break;
1587
1588 case ACCESS_WRITE:
1589 if (backup_option)
1590 maybe_backup_file (*archive_name_cursor, 1);
1591 archive = rmtcreat (*archive_name_cursor, MODE_RW,
1592 rsh_command_option);
1593 break;
1594
1595 case ACCESS_UPDATE:
1596 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1597 rsh_command_option);
1598 break;
1599 }
1600
1601 if (archive < 0)
1602 {
1603 open_warn (*archive_name_cursor);
1604 if (!verify_option && access == ACCESS_WRITE && backup_option)
1605 undo_last_backup ();
1606 goto tryagain;
1607 }
1608
1609#if MSDOS
1610 setmode (archive, O_BINARY);
1611#endif
1612
1613 return 1;
1614}