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