Implement window size passing between real tty and virtual console.
[dragonfly/vkernel-mp.git] / contrib / tar / src / buffer.c
blobe18b5b586c7524815b38015b8eafb70255321283
1 /* Buffer management for tar.
3 Copyright 1988, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001 Free
4 Software Foundation, Inc.
6 Written by John Gilmore, on 1985-08-25.
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.
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.
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. */
22 /* $FreeBSD: src/contrib/tar/src/buffer.c,v 1.2.2.2 2002/10/11 14:32:25 sobomax Exp $ */
23 /* $DragonFly: src/contrib/tar/src/buffer.c,v 1.2 2003/06/17 06:24:06 dillon Exp $ */
25 #include "system.h"
27 #include <signal.h>
29 #if MSDOS
30 # include <process.h>
31 #endif
33 #if XENIX
34 # include <sys/inode.h>
35 #endif
37 #include <fnmatch.h>
38 #include <human.h>
39 #include <quotearg.h>
41 #include "common.h"
42 #include "rmt.h"
44 #define PREAD 0 /* read file descriptor from pipe() */
45 #define PWRITE 1 /* write file descriptor from pipe() */
47 /* Number of retries before giving up on read. */
48 #define READ_ERROR_MAX 10
50 /* Globbing pattern to append to volume label if initial match failed. */
51 #define VOLUME_LABEL_APPEND " Volume [1-9]*"
53 /* Variables. */
55 static tarlong prev_written; /* bytes written on previous volumes */
56 static tarlong bytes_written; /* bytes written on this volume */
58 /* FIXME: The following variables should ideally be static to this
59 module. However, this cannot be done yet. The cleanup continues! */
61 union block *record_start; /* start of record of archive */
62 union block *record_end; /* last+1 block of archive record */
63 union block *current_block; /* current block of archive */
64 enum access_mode access_mode; /* how do we handle the archive */
65 off_t records_read; /* number of records read from this archive */
66 off_t records_written; /* likewise, for records written */
68 static struct stat archive_stat; /* stat block for archive file */
70 static off_t record_start_block; /* block ordinal at record_start */
72 /* Where we write list messages (not errors, not interactions) to. Stdout
73 unless we're writing a pipe, in which case stderr. */
74 FILE *stdlis;
76 static void backspace_output PARAMS ((void));
77 static int new_volume PARAMS ((enum access_mode));
78 static void archive_write_error PARAMS ((ssize_t)) __attribute__ ((noreturn));
79 static void archive_read_error PARAMS ((void));
81 #if !MSDOS
82 /* Obnoxious test to see if dimwit is trying to dump the archive. */
83 dev_t ar_dev;
84 ino_t ar_ino;
85 #endif
87 /* PID of child program, if compress_option or remote archive access. */
88 static pid_t child_pid;
90 /* Error recovery stuff */
91 static int read_error_count;
93 /* Have we hit EOF yet? */
94 static int hit_eof;
96 /* Checkpointing counter */
97 static int checkpoint;
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! */
101 extern int time_to_start_writing;
103 int file_to_switch_to = -1; /* if remote update, close archive, and use
104 this descriptor to write to */
106 static int volno = 1; /* which volume of a multi-volume tape we're
107 on */
108 static int global_volno = 1; /* volume number to print in external
109 messages */
110 static pid_t grandchild_pid;
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.) */
120 char *save_name; /* name of the file we are currently writing */
121 off_t save_totsize; /* total size of file we are writing, only
122 valid if save_name is nonzero */
123 off_t save_sizeleft; /* where we are in the file we are writing,
124 only valid if save_name is nonzero */
126 bool write_archive_to_stdout;
128 /* Used by flush_read and flush_write to store the real info about saved
129 names. */
130 static char *real_s_name;
131 static off_t real_s_totsize;
132 static off_t real_s_sizeleft;
134 /* Functions. */
136 void
137 print_total_written (void)
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;
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;
154 sprintf (bytes, TARLONG_FORMAT, written);
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 : "?"));
164 /* Compute and return the block ordinal at current_block. */
165 off_t
166 current_block_ordinal (void)
168 return record_start_block + (current_block - record_start);
171 /* If the EOF flag is set, reset it, as well as current_block, etc. */
172 void
173 reset_eof (void)
175 if (hit_eof)
177 hit_eof = 0;
178 current_block = record_start;
179 record_end = record_start + blocking_factor;
180 access_mode = ACCESS_WRITE;
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. */
187 union block *
188 find_next_block (void)
190 if (current_block == record_end)
192 if (hit_eof)
193 return 0;
194 flush_archive ();
195 if (current_block == record_end)
197 hit_eof = 1;
198 return 0;
201 return current_block;
204 /* Indicate that we have used all blocks up thru BLOCK.
205 FIXME: should the arg have an off-by-1? */
206 void
207 set_next_block_after (union block *block)
209 while (block >= current_block)
210 current_block++;
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. */
216 if (current_block > record_end)
217 abort ();
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. */
224 size_t
225 available_space_after (union block *pointer)
227 return record_end->buffer - pointer->buffer;
230 /* Close file having descriptor FD, and abort if close unsuccessful. */
231 static void
232 xclose (int fd)
234 if (close (fd) != 0)
235 close_error (_("(pipe)"));
238 /* Duplicate file descriptor FROM into becoming INTO.
239 INTO is closed first and has to be the next available slot. */
240 static void
241 xdup2 (int from, int into)
243 if (from != into)
245 int status = close (into);
247 if (status != 0 && errno != EBADF)
249 int e = errno;
250 FATAL_ERROR ((0, e, _("Cannot close")));
252 status = dup (from);
253 if (status != into)
255 if (status < 0)
257 int e = errno;
258 FATAL_ERROR ((0, e, _("Cannot dup")));
260 abort ();
262 xclose (from);
266 #if MSDOS
268 /* Set ARCHIVE for writing, then compressing an archive. */
269 static void
270 child_open_for_compress (void)
272 FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
275 /* Set ARCHIVE for uncompressing, then reading an archive. */
276 static void
277 child_open_for_uncompress (void)
279 FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
282 #else /* not MSDOS */
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). */
286 static int
287 is_regular_file (const char *name)
289 struct stat stbuf;
291 if (stat (name, &stbuf) == 0)
292 return S_ISREG (stbuf.st_mode);
293 else
294 return errno == ENOENT;
297 static ssize_t
298 write_archive_buffer (void)
300 ssize_t status;
301 ssize_t written = 0;
303 while (0 <= (status = rmtwrite (archive, record_start->buffer + written,
304 record_size - written)))
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;
314 return written ? written : status;
317 /* Set ARCHIVE for writing, then compressing an archive. */
318 static void
319 child_open_for_compress (void)
321 int parent_pipe[2];
322 int child_pipe[2];
323 int wait_status;
325 xpipe (parent_pipe);
326 child_pid = xfork ();
328 if (child_pid > 0)
330 /* The parent tar is still here! Just clean up. */
332 archive = parent_pipe[PWRITE];
333 xclose (parent_pipe[PREAD]);
334 return;
337 /* The new born child tar is here! */
339 program_name = _("tar (child)");
341 xdup2 (parent_pipe[PREAD], STDIN_FILENO);
342 xclose (parent_pipe[PWRITE]);
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. */
349 if (strcmp (archive_name_array[0], "-") != 0
350 && !_remdev (archive_name_array[0])
351 && is_regular_file (archive_name_array[0]))
353 if (backup_option)
354 maybe_backup_file (archive_name_array[0], 1);
356 /* We don't need a grandchild tar. Open the archive and launch the
357 compressor. */
359 archive = creat (archive_name_array[0], MODE_RW);
360 if (archive < 0)
362 int saved_errno = errno;
364 if (backup_option)
365 undo_last_backup ();
366 errno = saved_errno;
367 open_fatal (archive_name_array[0]);
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);
375 /* We do need a grandchild tar. */
377 xpipe (child_pipe);
378 grandchild_pid = xfork ();
380 if (grandchild_pid == 0)
382 /* The newborn grandchild tar is here! Launch the compressor. */
384 program_name = _("tar (grandchild)");
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);
393 /* The child tar is still here! */
395 /* Prepare for reblocking the data from the compressor into the archive. */
397 xdup2 (child_pipe[PREAD], STDIN_FILENO);
398 xclose (child_pipe[PWRITE]);
400 if (strcmp (archive_name_array[0], "-") == 0)
401 archive = STDOUT_FILENO;
402 else
404 archive = rmtcreat (archive_name_array[0], MODE_RW, rsh_command_option);
405 if (archive < 0)
406 open_fatal (archive_name_array[0]);
409 /* Let's read out of the stdin pipe and write an archive. */
411 while (1)
413 ssize_t status = 0;
414 char *cursor;
415 size_t length;
417 /* Assemble a record. */
419 for (length = 0, cursor = record_start->buffer;
420 length < record_size;
421 length += status, cursor += status)
423 size_t size = record_size - length;
425 if (size < BLOCKSIZE)
426 size = BLOCKSIZE;
427 status = safe_read (STDIN_FILENO, cursor, size);
428 if (status <= 0)
429 break;
432 if (status < 0)
433 read_fatal (use_compress_program_option);
435 /* Copy the record. */
437 if (status == 0)
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. */
443 if (length > 0)
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);
451 /* There is nothing else to read, break out. */
452 break;
455 status = write_archive_buffer ();
456 if (status != record_size)
457 archive_write_error (status);
460 #if 0
461 close_archive ();
462 #endif
464 /* Propagate any failure of the grandchild back to the parent. */
466 while (waitpid (grandchild_pid, &wait_status, 0) == -1)
467 if (errno != EINTR)
469 waitpid_error (use_compress_program_option);
470 break;
473 if (WIFSIGNALED (wait_status))
475 kill (child_pid, WTERMSIG (wait_status));
476 exit_status = TAREXIT_FAILURE;
478 else if (WEXITSTATUS (wait_status) != 0)
479 exit_status = WEXITSTATUS (wait_status);
481 exit (exit_status);
484 static void
485 sig_propagate(int sig)
487 kill (grandchild_pid, sig);
488 exit (TAREXIT_FAILURE);
491 /* Set ARCHIVE for uncompressing, then reading an archive. */
492 static void
493 child_open_for_uncompress (void)
495 int parent_pipe[2];
496 int child_pipe[2];
497 int wait_status;
499 xpipe (parent_pipe);
500 child_pid = xfork ();
502 if (child_pid > 0)
504 /* The parent tar is still here! Just clean up. */
506 read_full_records_option = 1;
507 archive = parent_pipe[PREAD];
508 xclose (parent_pipe[PWRITE]);
509 return;
512 /* The newborn child tar is here! */
514 program_name = _("tar (child)");
516 xdup2 (parent_pipe[PWRITE], STDOUT_FILENO);
517 xclose (parent_pipe[PREAD]);
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. */
524 if (strcmp (archive_name_array[0], "-") != 0
525 && !_remdev (archive_name_array[0])
526 && is_regular_file (archive_name_array[0]))
528 /* We don't need a grandchild tar. Open the archive and lauch the
529 uncompressor. */
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);
540 /* We do need a grandchild tar. */
542 xpipe (child_pipe);
543 grandchild_pid = xfork ();
545 if (grandchild_pid == 0)
547 /* The newborn grandchild tar is here! Launch the uncompressor. */
549 program_name = _("tar (grandchild)");
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);
558 /* The child tar is still here! */
559 signal (SIGTERM, sig_propagate);
561 /* Prepare for unblocking the data from the archive into the
562 uncompressor. */
564 xdup2 (child_pipe[PWRITE], STDOUT_FILENO);
565 xclose (child_pipe[PREAD]);
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]);
575 /* Let's read the archive and pipe it into stdout. */
577 while (1)
579 char *cursor;
580 size_t maximum;
581 size_t count;
582 ssize_t status;
584 read_error_count = 0;
586 error_loop:
587 status = rmtread (archive, record_start->buffer, record_size);
588 if (status < 0)
590 archive_read_error ();
591 goto error_loop;
593 if (status == 0)
594 break;
595 cursor = record_start->buffer;
596 maximum = status;
597 while (maximum)
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;
607 xclose (STDOUT_FILENO);
608 #if 0
609 close_archive ();
610 #endif
612 /* Propagate any failure of the grandchild back to the parent. */
614 while (waitpid (grandchild_pid, &wait_status, 0) == -1)
615 if (errno != EINTR)
617 waitpid_error (use_compress_program_option);
618 break;
621 if (WIFSIGNALED (wait_status))
623 kill (child_pid, WTERMSIG (wait_status));
624 exit_status = TAREXIT_FAILURE;
626 else if (WEXITSTATUS (wait_status) != 0)
627 exit_status = WEXITSTATUS (wait_status);
629 exit (exit_status);
632 #endif /* not MSDOS */
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. */
638 static int
639 check_label_pattern (union block *label)
641 char *string;
642 int result;
644 if (! memchr (label->header.name, '\0', sizeof label->header.name))
645 return 0;
647 if (fnmatch (volume_label_option, label->header.name, 0) == 0)
648 return 1;
650 if (!multi_volume_option)
651 return 0;
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;
662 /* Open an archive file. The argument specifies whether we are
663 reading or writing, or both. */
664 void
665 open_archive (enum access_mode wanted_access)
667 int backed_up_flag = 0;
669 stdlis = to_stdout_option ? stderr : stdout;
671 if (record_size == 0)
672 FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
674 if (archive_names == 0)
675 FATAL_ERROR ((0, 0, _("No archive name given")));
677 current_file_name = 0;
678 current_link_name = 0;
679 save_name = 0;
680 real_s_name = 0;
682 if (multi_volume_option)
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;
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));
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;
701 if (use_compress_program_option)
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")));
708 switch (wanted_access)
710 case ACCESS_READ:
711 child_open_for_uncompress ();
712 break;
714 case ACCESS_WRITE:
715 child_open_for_compress ();
716 break;
718 case ACCESS_UPDATE:
719 FATAL_ERROR ((0, 0, _("Cannot update compressed archives")));
720 break;
723 if (wanted_access == ACCESS_WRITE
724 && strcmp (archive_name_array[0], "-") == 0)
725 stdlis = stderr;
727 else if (strcmp (archive_name_array[0], "-") == 0)
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")));
733 switch (wanted_access)
735 case ACCESS_READ:
736 archive = STDIN_FILENO;
737 break;
739 case ACCESS_WRITE:
740 archive = STDOUT_FILENO;
741 stdlis = stderr;
742 break;
744 case ACCESS_UPDATE:
745 archive = STDIN_FILENO;
746 stdlis = stderr;
747 write_archive_to_stdout = 1;
748 break;
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)
757 case ACCESS_READ:
758 archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
759 MODE_RW, rsh_command_option);
760 break;
762 case ACCESS_WRITE:
763 if (backup_option)
765 maybe_backup_file (archive_name_array[0], 1);
766 backed_up_flag = 1;
768 archive = rmtcreat (archive_name_array[0], MODE_RW,
769 rsh_command_option);
770 break;
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;
778 if (archive < 0
779 || (! _isrmt (archive) && fstat (archive, &archive_stat) < 0))
781 int saved_errno = errno;
783 if (backed_up_flag)
784 undo_last_backup ();
785 errno = saved_errno;
786 open_fatal (archive_name_array[0]);
789 #if !MSDOS
791 /* Detect if outputting to "/dev/null". */
793 static char const dev_null[] = "/dev/null";
794 struct stat dev_null_stat;
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));
805 if (!_isrmt (archive) && S_ISREG (archive_stat.st_mode))
807 ar_dev = archive_stat.st_dev;
808 ar_ino = archive_stat.st_ino;
810 else
811 ar_dev = 0;
813 #endif /* not MSDOS */
815 #if MSDOS
816 setmode (archive, O_BINARY);
817 #endif
819 switch (wanted_access)
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 */
828 if (volume_label_option)
830 union block *label = find_next_block ();
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)));
840 break;
842 case ACCESS_WRITE:
843 records_written = 0;
844 if (volume_label_option)
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);
853 assign_string (&current_file_name, record_start->header.name);
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
862 break;
866 /* Perform a write to flush the buffer. */
867 void
868 flush_write (void)
870 int copy_back;
871 ssize_t status;
873 if (checkpoint_option && !(++checkpoint % 10))
874 WARN ((0, 0, _("Write checkpoint %d"), checkpoint));
876 if (tape_length_option && tape_length_option <= bytes_written)
878 errno = ENOSPC;
879 status = 0;
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);
888 if (status > 0)
890 records_written++;
891 bytes_written += status;
894 if (status == record_size)
896 if (multi_volume_option)
898 char *cursor;
900 if (!save_name)
902 assign_string (&real_s_name, 0);
903 real_s_totsize = 0;
904 real_s_sizeleft = 0;
905 return;
908 cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
909 while (ISSLASH (*cursor))
910 cursor++;
912 assign_string (&real_s_name, cursor);
913 real_s_totsize = save_totsize;
914 real_s_sizeleft = save_sizeleft;
916 return;
919 /* We're multivol. Panic if we didn't get the right kind of response. */
921 /* ENXIO is for the UNIX PC. */
922 if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
923 archive_write_error (status);
925 /* If error indicates a short write, we just move to the next tape. */
927 if (!new_volume (ACCESS_WRITE))
928 return;
930 if (totals_option)
931 prev_written += bytes_written;
932 bytes_written = 0;
934 if (volume_label_option && real_s_name)
936 copy_back = 2;
937 record_start -= 2;
939 else if (volume_label_option || real_s_name)
941 copy_back = 1;
942 record_start--;
944 else
945 copy_back = 0;
947 if (volume_label_option)
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);
957 if (real_s_name)
959 int tmp;
961 if (volume_label_option)
962 record_start++;
964 memset (record_start, 0, BLOCKSIZE);
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. */
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;
980 if (volume_label_option)
981 record_start--;
984 status = write_archive_buffer ();
985 if (status != record_size)
986 archive_write_error (status);
988 bytes_written += status;
990 if (copy_back)
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;
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
1004 char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
1006 while (ISSLASH (*cursor))
1007 cursor++;
1009 assign_string (&real_s_name, cursor);
1010 real_s_sizeleft = save_sizeleft;
1011 real_s_totsize = save_totsize;
1013 copy_back = 0;
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. */
1020 static void
1021 archive_write_error (ssize_t status)
1023 /* It might be useful to know how much was written before the error
1024 occurred. */
1025 if (totals_option)
1027 int e = errno;
1028 print_total_written ();
1029 errno = e;
1032 write_fatal_details (*archive_name_cursor, status, record_size);
1035 /* Handle read errors on the archive. If the read should be retried,
1036 return to the caller. */
1037 static void
1038 archive_read_error (void)
1040 read_error (*archive_name_cursor);
1042 if (record_start_block == 0)
1043 FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
1045 /* Read error in mid archive. We retry up to READ_ERROR_MAX times and
1046 then give up on reading the archive. */
1048 if (read_error_count++ > READ_ERROR_MAX)
1049 FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
1050 return;
1053 /* Perform a read to flush the buffer. */
1054 void
1055 flush_read (void)
1057 ssize_t status; /* result from system call */
1058 size_t left; /* bytes left */
1059 char *more; /* pointer to next byte to read */
1061 if (checkpoint_option && !(++checkpoint % 10))
1062 WARN ((0, 0, _("Read checkpoint %d"), checkpoint));
1064 /* Clear the count of errors. This only applies to a single call to
1065 flush_read. */
1067 read_error_count = 0; /* clear error count */
1069 if (write_archive_to_stdout && record_start_block != 0)
1071 archive = STDOUT_FILENO;
1072 status = write_archive_buffer ();
1073 archive = STDIN_FILENO;
1074 if (status != record_size)
1075 archive_write_error (status);
1077 if (multi_volume_option)
1079 if (save_name)
1081 char *cursor = save_name + FILESYSTEM_PREFIX_LEN (save_name);
1083 while (ISSLASH (*cursor))
1084 cursor++;
1086 assign_string (&real_s_name, cursor);
1087 real_s_sizeleft = save_sizeleft;
1088 real_s_totsize = save_totsize;
1090 else
1092 assign_string (&real_s_name, 0);
1093 real_s_totsize = 0;
1094 real_s_sizeleft = 0;
1098 error_loop:
1099 status = rmtread (archive, record_start->buffer, record_size);
1100 if (status == record_size)
1102 records_read++;
1103 return;
1106 if ((status == 0
1107 || (status < 0 && errno == ENOSPC)
1108 || (status > 0 && !read_full_records_option))
1109 && multi_volume_option)
1111 union block *cursor;
1113 try_volume:
1114 switch (subcommand_option)
1116 case APPEND_SUBCOMMAND:
1117 case CAT_SUBCOMMAND:
1118 case UPDATE_SUBCOMMAND:
1119 if (!new_volume (ACCESS_UPDATE))
1120 return;
1121 break;
1123 default:
1124 if (!new_volume (ACCESS_READ))
1125 return;
1126 break;
1129 vol_error:
1130 status = rmtread (archive, record_start->buffer, record_size);
1131 if (status < 0)
1133 archive_read_error ();
1134 goto vol_error;
1136 if (status != record_size)
1137 goto short_read;
1139 cursor = record_start;
1141 if (cursor->header.typeflag == GNUTYPE_VOLHDR)
1143 if (volume_label_option)
1145 if (!check_label_pattern (cursor))
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;
1155 if (verbose_option)
1156 fprintf (stdlis, _("Reading %s\n"), quote (cursor->header.name));
1157 cursor++;
1159 else if (volume_label_option)
1160 WARN ((0, 0, _("WARNING: No volume header")));
1162 if (real_s_name)
1164 uintmax_t s1, s2;
1165 if (cursor->header.typeflag != GNUTYPE_MULTIVOL
1166 || strcmp (cursor->header.name, real_s_name))
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;
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)
1178 char totsizebuf[UINTMAX_STRSIZE_BOUND];
1179 char s1buf[UINTMAX_STRSIZE_BOUND];
1180 char s2buf[UINTMAX_STRSIZE_BOUND];
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;
1191 if (real_s_totsize - real_s_sizeleft
1192 != OFF_FROM_HEADER (cursor->oldgnu_header.offset))
1194 WARN ((0, 0, _("This volume is out of sequence")));
1195 volno--;
1196 global_volno--;
1197 goto try_volume;
1199 cursor++;
1201 current_block = cursor;
1202 records_read++;
1203 return;
1205 else if (status < 0)
1207 archive_read_error ();
1208 goto error_loop; /* try again */
1211 short_read:
1212 more = record_start->buffer + status;
1213 left = record_size - status;
1215 while (left % BLOCKSIZE != 0
1216 || (left && status && read_full_records_option))
1218 if (status)
1219 while ((status = rmtread (archive, more, left)) < 0)
1220 archive_read_error ();
1222 if (status == 0)
1223 break;
1225 if (! read_full_records_option)
1226 FATAL_ERROR ((0, 0, _("Unaligned block (%lu bytes) in archive"),
1227 (unsigned long) (record_size - left)));
1229 /* User warned us about this. Fix up. */
1231 left -= status;
1232 more += status;
1235 /* FIXME: for size=0, multi-volume support. On the first record, warn
1236 about the problem. */
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)));
1243 record_end = record_start + (record_size - left) / BLOCKSIZE;
1244 records_read++;
1247 /* Flush the current buffer to/from the archive. */
1248 void
1249 flush_archive (void)
1251 record_start_block += record_end - record_start;
1252 current_block = record_start;
1253 record_end = record_start + blocking_factor;
1255 if (access_mode == ACCESS_READ && time_to_start_writing)
1257 access_mode = ACCESS_WRITE;
1258 time_to_start_writing = 0;
1260 if (file_to_switch_to >= 0)
1262 if (rmtclose (archive) != 0)
1263 close_warn (*archive_name_cursor);
1265 archive = file_to_switch_to;
1267 else
1268 backspace_output ();
1271 switch (access_mode)
1273 case ACCESS_READ:
1274 flush_read ();
1275 break;
1277 case ACCESS_WRITE:
1278 flush_write ();
1279 break;
1281 case ACCESS_UPDATE:
1282 abort ();
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! */
1289 static void
1290 backspace_output (void)
1292 #ifdef MTIOCTOP
1294 struct mtop operation;
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;
1303 #endif
1306 off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1308 /* Seek back to the beginning of this record and start writing there. */
1310 position -= record_size;
1311 if (position < 0)
1312 position = 0;
1313 if (rmtlseek (archive, position, SEEK_SET) != position)
1315 /* Lseek failed. Try a different method. */
1317 WARN ((0, 0,
1318 _("Cannot backspace archive file; it may be unreadable without -i")));
1320 /* Replace the first part of the record with NULs. */
1322 if (record_start->buffer != output_start)
1323 memset (record_start->buffer, 0,
1324 output_start - record_start->buffer);
1329 /* Close the archive file. */
1330 void
1331 close_archive (void)
1333 if (time_to_start_writing || access_mode == ACCESS_WRITE)
1334 flush_archive ();
1336 #if !MSDOS
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. */
1343 if (fast_read_option && namelist_freed && child_pid > 0)
1344 kill(child_pid, SIGTERM);
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
1353 if (verify_option)
1354 verify_volume ();
1356 if (rmtclose (archive) != 0)
1357 close_warn (*archive_name_cursor);
1359 #if !MSDOS
1361 if (child_pid)
1363 int wait_status;
1365 while (waitpid (child_pid, &wait_status, 0) == -1)
1366 if (errno != EINTR)
1368 waitpid_error (use_compress_program_option);
1369 break;
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)));
1380 #endif /* !MSDOS */
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);
1393 /* Called to initialize the global volume number. */
1394 void
1395 init_volume_number (void)
1397 FILE *file = fopen (volno_file_option, "r");
1399 if (file)
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);
1410 else if (errno != ENOENT)
1411 open_error (volno_file_option);
1414 /* Called to write out the closing global volume number. */
1415 void
1416 closeout_volume_number (void)
1418 FILE *file = fopen (volno_file_option, "w");
1420 if (file)
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);
1428 else
1429 open_error (volno_file_option);
1432 /* We've hit the end of the old volume. Close it and open the next one.
1433 Return nonzero on success. */
1434 static int
1435 new_volume (enum access_mode access)
1437 static FILE *read_file;
1438 static int looped;
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;
1444 if (now_verifying)
1445 return 0;
1446 if (verify_option)
1447 verify_volume ();
1449 if (rmtclose (archive) != 0)
1450 close_warn (*archive_name_cursor);
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)
1459 archive_name_cursor = archive_name_array;
1460 looped = 1;
1463 tryagain:
1464 if (looped)
1466 /* We have to prompt from now on. */
1468 if (info_script_option)
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));
1475 else
1476 while (1)
1478 char input_buffer[80];
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);
1486 if (fgets (input_buffer, sizeof input_buffer, read_file) == 0)
1488 WARN ((0, 0, _("EOF where user reply was expected")));
1490 if (subcommand_option != EXTRACT_SUBCOMMAND
1491 && subcommand_option != LIST_SUBCOMMAND
1492 && subcommand_option != DIFF_SUBCOMMAND)
1493 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1495 fatal_exit ();
1497 if (input_buffer[0] == '\n'
1498 || input_buffer[0] == 'y'
1499 || input_buffer[0] == 'Y')
1500 break;
1502 switch (input_buffer[0])
1504 case '?':
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"));
1512 break;
1514 case 'q':
1515 /* Quit. */
1517 WARN ((0, 0, _("No new volume; exiting.\n")));
1519 if (subcommand_option != EXTRACT_SUBCOMMAND
1520 && subcommand_option != LIST_SUBCOMMAND
1521 && subcommand_option != DIFF_SUBCOMMAND)
1522 WARN ((0, 0, _("WARNING: Archive is incomplete")));
1524 fatal_exit ();
1526 case 'n':
1527 /* Get new file name. */
1530 char *name = &input_buffer[1];
1531 char *cursor;
1533 while (*name == ' ' || *name == '\t')
1534 name++;
1535 cursor = name;
1536 while (*cursor && *cursor != '\n')
1537 cursor++;
1538 *cursor = '\0';
1540 /* FIXME: the following allocation is never reclaimed. */
1541 *archive_name_cursor = xstrdup (name);
1543 break;
1545 case '!':
1546 #if MSDOS
1547 spawnl (P_WAIT, getenv ("COMSPEC"), "-", 0);
1548 #else /* not MSDOS */
1550 pid_t child;
1551 const char *shell = getenv ("SHELL");
1552 if (! shell)
1553 shell = "/bin/sh";
1554 child = xfork ();
1555 if (child == 0)
1557 execlp (shell, "-sh", "-i", (char *) 0);
1558 exec_fatal (shell);
1560 else
1562 int wait_status;
1563 while (waitpid (child, &wait_status, 0) == -1)
1564 if (errno != EINTR)
1566 waitpid_error (shell);
1567 break;
1571 #endif /* not MSDOS */
1572 break;
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)
1583 case ACCESS_READ:
1584 archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1585 rsh_command_option);
1586 break;
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;
1595 case ACCESS_UPDATE:
1596 archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1597 rsh_command_option);
1598 break;
1601 if (archive < 0)
1603 open_warn (*archive_name_cursor);
1604 if (!verify_option && access == ACCESS_WRITE && backup_option)
1605 undo_last_backup ();
1606 goto tryagain;
1609 #if MSDOS
1610 setmode (archive, O_BINARY);
1611 #endif
1613 return 1;