1 /* Buffer management for tar.
2 
3    Copyright 1988-2021 Free Software Foundation, Inc.
4 
5    This file is part of GNU tar.
6 
7    GNU tar is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    GNU tar is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 
20    Written by John Gilmore, on 1985-08-25.  */
21 
22 #include <system.h>
23 #include <system-ioctl.h>
24 
25 #include <signal.h>
26 
27 #include <closeout.h>
28 #include <fnmatch.h>
29 #include <human.h>
30 #include <quotearg.h>
31 
32 #include "common.h"
33 #include <rmt.h>
34 
35 /* Number of retries before giving up on read.  */
36 #define READ_ERROR_MAX 10
37 
38 /* Variables.  */
39 
40 static tarlong prev_written;    /* bytes written on previous volumes */
41 static tarlong bytes_written;   /* bytes written on this volume */
42 static void *record_buffer[2];  /* allocated memory */
43 static union block *record_buffer_aligned[2];
44 static int record_index;
45 
46 /* FIXME: The following variables should ideally be static to this
47    module.  However, this cannot be done yet.  The cleanup continues!  */
48 
49 union block *record_start;      /* start of record of archive */
50 union block *record_end;        /* last+1 block of archive record */
51 union block *current_block;     /* current block of archive */
52 enum access_mode access_mode;   /* how do we handle the archive */
53 off_t records_read;             /* number of records read from this archive */
54 off_t records_written;          /* likewise, for records written */
55 extern off_t records_skipped;   /* number of records skipped at the start
56                                    of the archive, defined in delete.c */
57 
58 static off_t record_start_block; /* block ordinal at record_start */
59 
60 /* Where we write list messages (not errors, not interactions) to.  */
61 FILE *stdlis;
62 
63 static void backspace_output (void);
64 
65 /* PID of child program, if compress_option or remote archive access.  */
66 static pid_t child_pid;
67 
68 /* Error recovery stuff  */
69 static int read_error_count;
70 
71 /* Have we hit EOF yet?  */
72 static bool hit_eof;
73 
74 static bool read_full_records = false;
75 
76 /* We're reading, but we just read the last block and it's time to update.
77    Declared in update.c
78 
79    FIXME: Either eliminate it or move it to common.h.
80 */
81 extern bool time_to_start_writing;
82 
83 bool write_archive_to_stdout;
84 
85 static void (*flush_write_ptr) (size_t);
86 static void (*flush_read_ptr) (void);
87 
88 
89 char *volume_label;
90 char *continued_file_name;
91 uintmax_t continued_file_size;
92 uintmax_t continued_file_offset;
93 
94 
95 static int volno = 1;           /* which volume of a multi-volume tape we're
96                                    on */
97 static int global_volno = 1;    /* volume number to print in external
98                                    messages */
99 
100 bool write_archive_to_stdout;
101 
102 
103 /* Multi-volume tracking support */
104 
105 /* When creating a multi-volume archive, each 'bufmap' represents
106    a member stored (perhaps partly) in the current record buffer.
107    Bufmaps are form a single-linked list in chronological order.
108 
109    After flushing the record to the output media, all bufmaps that
110    represent fully written members are removed from the list, the
111    nblocks and sizeleft values in the bufmap_head and start values
112    in all remaining bufmaps are updated.  The information stored
113    in bufmap_head is used to form the volume header.
114 
115    When reading from a multi-volume archive, the list degrades to a
116    single element, which keeps information about the member currently
117    being read.  In that case the sizeleft member is updated explicitly
118    from the extractor code by calling the mv_size_left function.  The
119    information from bufmap_head is compared with the volume header data
120    to ensure that subsequent volumes are fed in the right order.
121 */
122 
123 struct bufmap
124 {
125   struct bufmap *next;          /* Pointer to the next map entry */
126   size_t start;                 /* Offset of the first data block */
127   char *file_name;              /* Name of the stored file */
128   off_t sizetotal;              /* Size of the stored file */
129   off_t sizeleft;               /* Size left to read/write */
130   size_t nblocks;               /* Number of blocks written since reset */
131 };
132 static struct bufmap *bufmap_head, *bufmap_tail;
133 
134 /* This variable, when set, inhibits updating the bufmap chain after
135    a write.  This is necessary when writing extended POSIX headers. */
136 static int inhibit_map;
137 
138 void
mv_begin_write(const char * file_name,off_t totsize,off_t sizeleft)139 mv_begin_write (const char *file_name, off_t totsize, off_t sizeleft)
140 {
141   if (multi_volume_option)
142     {
143       struct bufmap *bp = xmalloc (sizeof bp[0]);
144       if (bufmap_tail)
145 	bufmap_tail->next = bp;
146       else
147 	bufmap_head = bp;
148       bufmap_tail = bp;
149 
150       bp->next = NULL;
151       bp->start = current_block - record_start;
152       bp->file_name = xstrdup (file_name);
153       bp->sizetotal = totsize;
154       bp->sizeleft = sizeleft;
155       bp->nblocks = 0;
156     }
157 }
158 
159 static struct bufmap *
bufmap_locate(size_t off)160 bufmap_locate (size_t off)
161 {
162   struct bufmap *map;
163 
164   for (map = bufmap_head; map; map = map->next)
165     {
166       if (!map->next || off < map->next->start * BLOCKSIZE)
167 	break;
168     }
169   return map;
170 }
171 
172 static void
bufmap_free(struct bufmap * mark)173 bufmap_free (struct bufmap *mark)
174 {
175   struct bufmap *map;
176   for (map = bufmap_head; map && map != mark; )
177     {
178       struct bufmap *next = map->next;
179       free (map->file_name);
180       free (map);
181       map = next;
182     }
183   bufmap_head = map;
184   if (!bufmap_head)
185     bufmap_tail = bufmap_head;
186 }
187 
188 static void
bufmap_reset(struct bufmap * map,ssize_t fixup)189 bufmap_reset (struct bufmap *map, ssize_t fixup)
190 {
191   bufmap_free (map);
192   if (map)
193     {
194       for (; map; map = map->next)
195 	{
196 	  map->start += fixup;
197 	  map->nblocks = 0;
198 	}
199     }
200 }
201 
202 
203 static struct tar_stat_info dummy;
204 
205 void
buffer_write_global_xheader(void)206 buffer_write_global_xheader (void)
207 {
208   xheader_write_global (&dummy.xhdr);
209 }
210 
211 void
mv_begin_read(struct tar_stat_info * st)212 mv_begin_read (struct tar_stat_info *st)
213 {
214   mv_begin_write (st->orig_file_name, st->stat.st_size, st->stat.st_size);
215 }
216 
217 void
mv_end(void)218 mv_end (void)
219 {
220   if (multi_volume_option)
221     bufmap_free (NULL);
222 }
223 
224 void
mv_size_left(off_t size)225 mv_size_left (off_t size)
226 {
227   if (bufmap_head)
228     bufmap_head->sizeleft = size;
229 }
230 
231 
232 /* Functions.  */
233 
234 void
clear_read_error_count(void)235 clear_read_error_count (void)
236 {
237   read_error_count = 0;
238 }
239 
240 
241 /* Time-related functions */
242 
243 static double duration;
244 
245 void
set_start_time(void)246 set_start_time (void)
247 {
248   gettime (&start_time);
249   volume_start_time = start_time;
250   last_stat_time = start_time;
251 }
252 
253 static void
set_volume_start_time(void)254 set_volume_start_time (void)
255 {
256   gettime (&volume_start_time);
257   last_stat_time = volume_start_time;
258 }
259 
260 double
compute_duration(void)261 compute_duration (void)
262 {
263   struct timespec now;
264   gettime (&now);
265   duration += ((now.tv_sec - last_stat_time.tv_sec)
266                + (now.tv_nsec - last_stat_time.tv_nsec) / 1e9);
267   gettime (&last_stat_time);
268   return duration;
269 }
270 
271 
272 /* Compression detection */
273 
274 enum compress_type {
275   ct_none,             /* Unknown compression type */
276   ct_tar,              /* Plain tar file */
277   ct_compress,
278   ct_gzip,
279   ct_bzip2,
280   ct_lzip,
281   ct_lzma,
282   ct_lzop,
283   ct_xz,
284   ct_zstd
285 };
286 
287 static enum compress_type archive_compression_type = ct_none;
288 
289 struct zip_magic
290 {
291   enum compress_type type;
292   size_t length;
293   char const *magic;
294 };
295 
296 struct zip_program
297 {
298   enum compress_type type;
299   char const *program;
300   char const *option;
301 };
302 
303 static struct zip_magic const magic[] = {
304   { ct_none,     0, 0 },
305   { ct_tar,      0, 0 },
306   { ct_compress, 2, "\037\235" },
307   { ct_gzip,     2, "\037\213" },
308   { ct_bzip2,    3, "BZh" },
309   { ct_lzip,     4, "LZIP" },
310   { ct_lzma,     6, "\xFFLZMA" },
311   { ct_lzop,     4, "\211LZO" },
312   { ct_xz,       6, "\xFD" "7zXZ" },
313   { ct_zstd,     4, "\x28\xB5\x2F\xFD" },
314 };
315 
316 #define NMAGIC (sizeof(magic)/sizeof(magic[0]))
317 
318 static struct zip_program zip_program[] = {
319   { ct_compress, COMPRESS_PROGRAM, "-Z" },
320   { ct_compress, GZIP_PROGRAM,     "-z" },
321   { ct_gzip,     GZIP_PROGRAM,     "-z" },
322   { ct_bzip2,    BZIP2_PROGRAM,    "-j" },
323   { ct_bzip2,    "lbzip2",         "-j" },
324   { ct_lzip,     LZIP_PROGRAM,     "--lzip" },
325   { ct_lzma,     LZMA_PROGRAM,     "--lzma" },
326   { ct_lzma,     XZ_PROGRAM,       "-J" },
327   { ct_lzop,     LZOP_PROGRAM,     "--lzop" },
328   { ct_xz,       XZ_PROGRAM,       "-J" },
329   { ct_zstd,     ZSTD_PROGRAM,     "--zstd" },
330   { ct_none }
331 };
332 
333 static struct zip_program const *
find_zip_program(enum compress_type type,int * pstate)334 find_zip_program (enum compress_type type, int *pstate)
335 {
336   int i;
337 
338   for (i = *pstate; zip_program[i].type != ct_none; i++)
339     {
340       if (zip_program[i].type == type)
341 	{
342 	  *pstate = i + 1;
343 	  return zip_program + i;
344 	}
345     }
346   *pstate = i;
347   return NULL;
348 }
349 
350 const char *
first_decompress_program(int * pstate)351 first_decompress_program (int *pstate)
352 {
353   struct zip_program const *zp;
354 
355   if (use_compress_program_option)
356     return use_compress_program_option;
357 
358   if (archive_compression_type == ct_none)
359     return NULL;
360 
361   *pstate = 0;
362   zp = find_zip_program (archive_compression_type, pstate);
363   return zp ? zp->program : NULL;
364 }
365 
366 const char *
next_decompress_program(int * pstate)367 next_decompress_program (int *pstate)
368 {
369   struct zip_program const *zp;
370 
371   if (use_compress_program_option)
372     return NULL;
373   zp = find_zip_program (archive_compression_type, pstate);
374   return zp ? zp->program : NULL;
375 }
376 
377 static const char *
compress_option(enum compress_type type)378 compress_option (enum compress_type type)
379 {
380   struct zip_program const *zp;
381   int i = 0;
382   zp = find_zip_program (type, &i);
383   return zp ? zp->option : NULL;
384 }
385 
386 /* Check if the file ARCHIVE is a compressed archive. */
387 static enum compress_type
check_compressed_archive(bool * pshort)388 check_compressed_archive (bool *pshort)
389 {
390   struct zip_magic const *p;
391   bool sfr;
392   bool temp;
393 
394   if (!pshort)
395     pshort = &temp;
396 
397   /* Prepare global data needed for find_next_block: */
398   record_end = record_start; /* set up for 1st record = # 0 */
399   sfr = read_full_records;
400   read_full_records = true; /* Suppress fatal error on reading a partial
401                                record */
402   *pshort = find_next_block () == 0;
403 
404   /* Restore global values */
405   read_full_records = sfr;
406 
407   if (record_start != record_end /* no files smaller than BLOCKSIZE */
408       && (strcmp (record_start->header.magic, TMAGIC) == 0
409           || strcmp (record_start->buffer + offsetof (struct posix_header,
410                                                       magic),
411                      OLDGNU_MAGIC) == 0)
412       && tar_checksum (record_start, true) == HEADER_SUCCESS)
413     /* Probably a valid header */
414     return ct_tar;
415 
416   for (p = magic + 2; p < magic + NMAGIC; p++)
417     if (memcmp (record_start->buffer, p->magic, p->length) == 0)
418       return p->type;
419 
420   return ct_none;
421 }
422 
423 /* Guess if the archive is seekable. */
424 static void
guess_seekable_archive(void)425 guess_seekable_archive (void)
426 {
427   struct stat st;
428 
429   if (subcommand_option == DELETE_SUBCOMMAND)
430     {
431       /* The current code in delete.c is based on the assumption that
432 	 skip_member() reads all data from the archive. So, we should
433 	 make sure it won't use seeks. On the other hand, the same code
434 	 depends on the ability to backspace a record in the archive,
435 	 so setting seekable_archive to false is technically incorrect.
436          However, it is tested only in skip_member(), so it's not a
437 	 problem. */
438       seekable_archive = false;
439     }
440 
441   if (seek_option != -1)
442     {
443       seekable_archive = !!seek_option;
444       return;
445     }
446 
447   if (!multi_volume_option && !use_compress_program_option
448       && fstat (archive, &st) == 0)
449     seekable_archive = S_ISREG (st.st_mode);
450   else
451     seekable_archive = false;
452 }
453 
454 /* Open an archive named archive_name_array[0]. Detect if it is
455    a compressed archive of known type and use corresponding decompression
456    program if so */
457 static int
open_compressed_archive(void)458 open_compressed_archive (void)
459 {
460   archive = rmtopen (archive_name_array[0], O_RDONLY | O_BINARY,
461                      MODE_RW, rsh_command_option);
462   if (archive == -1)
463     return archive;
464 
465   if (!multi_volume_option)
466     {
467       if (!use_compress_program_option)
468         {
469           bool shortfile;
470           enum compress_type type = check_compressed_archive (&shortfile);
471 
472           switch (type)
473             {
474             case ct_tar:
475               if (shortfile)
476                 ERROR ((0, 0, _("This does not look like a tar archive")));
477               return archive;
478 
479             case ct_none:
480               if (shortfile)
481                 ERROR ((0, 0, _("This does not look like a tar archive")));
482               set_compression_program_by_suffix (archive_name_array[0], NULL);
483               if (!use_compress_program_option)
484 		return archive;
485               break;
486 
487             default:
488               archive_compression_type = type;
489               break;
490             }
491         }
492 
493       /* FD is not needed any more */
494       rmtclose (archive);
495 
496       hit_eof = false; /* It might have been set by find_next_block in
497                           check_compressed_archive */
498 
499       /* Open compressed archive */
500       child_pid = sys_child_open_for_uncompress ();
501       read_full_records = true;
502     }
503 
504   records_read = 0;
505   record_end = record_start; /* set up for 1st record = # 0 */
506 
507   return archive;
508 }
509 
510 static int
print_stats(FILE * fp,const char * text,tarlong numbytes)511 print_stats (FILE *fp, const char *text, tarlong numbytes)
512 {
513   char abbr[LONGEST_HUMAN_READABLE + 1];
514   char rate[LONGEST_HUMAN_READABLE + 1];
515   int n = 0;
516 
517   int human_opts = human_autoscale | human_base_1024 | human_SI | human_B;
518 
519   if (text && text[0])
520     n += fprintf (fp, "%s: ", gettext (text));
521   return n + fprintf (fp, TARLONG_FORMAT " (%s, %s/s)",
522 		      numbytes,
523 		      human_readable (numbytes, abbr, human_opts, 1, 1),
524 		      (0 < duration && numbytes / duration < (uintmax_t) -1
525 		       ? human_readable (numbytes / duration, rate, human_opts, 1, 1)
526 		       : "?"));
527 }
528 
529 /* Format totals to file FP.  FORMATS is an array of strings to output
530    before each data item (bytes read, written, deleted, in that order).
531    EOR is a delimiter to output after each item (used only if deleting
532    from the archive), EOL is a delimiter to add at the end of the output
533    line. */
534 int
format_total_stats(FILE * fp,char const * const * formats,int eor,int eol)535 format_total_stats (FILE *fp, char const *const *formats, int eor, int eol)
536 {
537   int n;
538 
539   switch (subcommand_option)
540     {
541     case CREATE_SUBCOMMAND:
542     case CAT_SUBCOMMAND:
543     case UPDATE_SUBCOMMAND:
544     case APPEND_SUBCOMMAND:
545       n = print_stats (fp, formats[TF_WRITE],
546 		       prev_written + bytes_written);
547       break;
548 
549     case DELETE_SUBCOMMAND:
550       {
551         char buf[UINTMAX_STRSIZE_BOUND];
552         n = print_stats (fp, formats[TF_READ],
553 			 records_read * record_size);
554 
555 	fputc (eor, fp);
556 	n++;
557 
558         n += print_stats (fp, formats[TF_WRITE],
559 			  prev_written + bytes_written);
560 
561 	fputc (eor, fp);
562 	n++;
563 
564 	if (formats[TF_DELETED] && formats[TF_DELETED][0])
565 	  n += fprintf (fp, "%s: ", gettext (formats[TF_DELETED]));
566         n += fprintf (fp, "%s",
567 		      STRINGIFY_BIGINT ((records_read - records_skipped)
568 					* record_size
569 					- (prev_written + bytes_written), buf));
570       }
571       break;
572 
573     case EXTRACT_SUBCOMMAND:
574     case LIST_SUBCOMMAND:
575     case DIFF_SUBCOMMAND:
576       n = print_stats (fp, _(formats[TF_READ]),
577 		       records_read * record_size);
578       break;
579 
580     default:
581       abort ();
582     }
583   if (eol)
584     {
585       fputc (eol, fp);
586       n++;
587     }
588   return n;
589 }
590 
591 static char const *const default_total_format[] = {
592   N_("Total bytes read"),
593   /* Amanda 2.4.1p1 looks for "Total bytes written: [0-9][0-9]*".  */
594   N_("Total bytes written"),
595   N_("Total bytes deleted")
596 };
597 
598 void
print_total_stats(void)599 print_total_stats (void)
600 {
601   format_total_stats (stderr, default_total_format, '\n', '\n');
602 }
603 
604 /* Compute and return the block ordinal at current_block.  */
605 off_t
current_block_ordinal(void)606 current_block_ordinal (void)
607 {
608   return record_start_block + (current_block - record_start);
609 }
610 
611 /* If the EOF flag is set, reset it, as well as current_block, etc.  */
612 void
reset_eof(void)613 reset_eof (void)
614 {
615   if (hit_eof)
616     {
617       hit_eof = false;
618       current_block = record_start;
619       record_end = record_start + blocking_factor;
620       access_mode = ACCESS_WRITE;
621     }
622 }
623 
624 /* Return the location of the next available input or output block.
625    Return zero for EOF.  Once we have returned zero, we just keep returning
626    it, to avoid accidentally going on to the next file on the tape.  */
627 union block *
find_next_block(void)628 find_next_block (void)
629 {
630   if (current_block == record_end)
631     {
632       if (hit_eof)
633         return 0;
634       flush_archive ();
635       if (current_block == record_end)
636         {
637           hit_eof = true;
638           return 0;
639         }
640     }
641   return current_block;
642 }
643 
644 /* Indicate that we have used all blocks up thru BLOCK. */
645 void
set_next_block_after(union block * block)646 set_next_block_after (union block *block)
647 {
648   while (block >= current_block)
649     current_block++;
650 
651   /* Do *not* flush the archive here.  If we do, the same argument to
652      set_next_block_after could mean the next block (if the input record
653      is exactly one block long), which is not what is intended.  */
654 
655   if (current_block > record_end)
656     abort ();
657 }
658 
659 /* Return the number of bytes comprising the space between POINTER
660    through the end of the current buffer of blocks.  This space is
661    available for filling with data, or taking data from.  POINTER is
662    usually (but not always) the result of previous find_next_block call.  */
663 size_t
available_space_after(union block * pointer)664 available_space_after (union block *pointer)
665 {
666   return record_end->buffer - pointer->buffer;
667 }
668 
669 /* Close file having descriptor FD, and abort if close unsuccessful.  */
670 void
xclose(int fd)671 xclose (int fd)
672 {
673   if (close (fd) != 0)
674     close_error (_("(pipe)"));
675 }
676 
677 static void
init_buffer(void)678 init_buffer (void)
679 {
680   if (! record_buffer_aligned[record_index])
681     record_buffer_aligned[record_index] =
682       page_aligned_alloc (&record_buffer[record_index], record_size);
683 
684   record_start = record_buffer_aligned[record_index];
685   current_block = record_start;
686   record_end = record_start + blocking_factor;
687 }
688 
689 static void
check_tty(enum access_mode mode)690 check_tty (enum access_mode mode)
691 {
692   /* Refuse to read archive from and write it to a tty. */
693   if (strcmp (archive_name_array[0], "-") == 0
694       && isatty (mode == ACCESS_READ ? STDIN_FILENO : STDOUT_FILENO))
695     {
696       FATAL_ERROR ((0, 0,
697 		    mode == ACCESS_READ
698 		    ? _("Refusing to read archive contents from terminal "
699 			"(missing -f option?)")
700 		    : _("Refusing to write archive contents to terminal "
701 			"(missing -f option?)")));
702     }
703 }
704 
705 /* Open an archive file.  The argument specifies whether we are
706    reading or writing, or both.  */
707 static void
_open_archive(enum access_mode wanted_access)708 _open_archive (enum access_mode wanted_access)
709 {
710   int backed_up_flag = 0;
711 
712   if (record_size == 0)
713     FATAL_ERROR ((0, 0, _("Invalid value for record_size")));
714 
715   if (archive_names == 0)
716     FATAL_ERROR ((0, 0, _("No archive name given")));
717 
718   tar_stat_destroy (&current_stat_info);
719 
720   record_index = 0;
721   init_buffer ();
722 
723   /* When updating the archive, we start with reading.  */
724   access_mode = wanted_access == ACCESS_UPDATE ? ACCESS_READ : wanted_access;
725   check_tty (access_mode);
726 
727   read_full_records = read_full_records_option;
728 
729   records_read = 0;
730 
731   if (use_compress_program_option)
732     {
733       switch (wanted_access)
734         {
735         case ACCESS_READ:
736           child_pid = sys_child_open_for_uncompress ();
737           read_full_records = true;
738           record_end = record_start; /* set up for 1st record = # 0 */
739           break;
740 
741         case ACCESS_WRITE:
742           child_pid = sys_child_open_for_compress ();
743           break;
744 
745         case ACCESS_UPDATE:
746           abort (); /* Should not happen */
747           break;
748         }
749 
750       if (!index_file_name
751           && wanted_access == ACCESS_WRITE
752           && strcmp (archive_name_array[0], "-") == 0)
753         stdlis = stderr;
754     }
755   else if (strcmp (archive_name_array[0], "-") == 0)
756     {
757       read_full_records = true; /* could be a pipe, be safe */
758       if (verify_option)
759         FATAL_ERROR ((0, 0, _("Cannot verify stdin/stdout archive")));
760 
761       switch (wanted_access)
762         {
763         case ACCESS_READ:
764           {
765             bool shortfile;
766             enum compress_type type;
767 
768             archive = STDIN_FILENO;
769             type = check_compressed_archive (&shortfile);
770             if (type != ct_tar && type != ct_none)
771               FATAL_ERROR ((0, 0,
772                             _("Archive is compressed. Use %s option"),
773                             compress_option (type)));
774             if (shortfile)
775               ERROR ((0, 0, _("This does not look like a tar archive")));
776           }
777           break;
778 
779         case ACCESS_WRITE:
780           archive = STDOUT_FILENO;
781           if (!index_file_name)
782             stdlis = stderr;
783           break;
784 
785         case ACCESS_UPDATE:
786           archive = STDIN_FILENO;
787           write_archive_to_stdout = true;
788           record_end = record_start; /* set up for 1st record = # 0 */
789           if (!index_file_name)
790             stdlis = stderr;
791           break;
792         }
793     }
794   else
795     switch (wanted_access)
796       {
797       case ACCESS_READ:
798         archive = open_compressed_archive ();
799 	if (archive >= 0)
800 	  guess_seekable_archive ();
801         break;
802 
803       case ACCESS_WRITE:
804         if (backup_option)
805           {
806             maybe_backup_file (archive_name_array[0], 1);
807             backed_up_flag = 1;
808           }
809 	if (verify_option)
810 	  archive = rmtopen (archive_name_array[0], O_RDWR | O_CREAT | O_BINARY,
811 			     MODE_RW, rsh_command_option);
812 	else
813 	  archive = rmtcreat (archive_name_array[0], MODE_RW,
814 			      rsh_command_option);
815         break;
816 
817       case ACCESS_UPDATE:
818         archive = rmtopen (archive_name_array[0],
819                            O_RDWR | O_CREAT | O_BINARY,
820                            MODE_RW, rsh_command_option);
821 
822         switch (check_compressed_archive (NULL))
823           {
824           case ct_none:
825           case ct_tar:
826             break;
827 
828           default:
829             FATAL_ERROR ((0, 0,
830                           _("Cannot update compressed archives")));
831           }
832         break;
833       }
834 
835   if (archive < 0
836       || (! _isrmt (archive) && !sys_get_archive_stat ()))
837     {
838       int saved_errno = errno;
839 
840       if (backed_up_flag)
841         undo_last_backup ();
842       errno = saved_errno;
843       open_fatal (archive_name_array[0]);
844     }
845 
846   sys_detect_dev_null_output ();
847   sys_save_archive_dev_ino ();
848   SET_BINARY_MODE (archive);
849 
850   switch (wanted_access)
851     {
852     case ACCESS_READ:
853       find_next_block ();       /* read it in, check for EOF */
854       break;
855 
856     case ACCESS_UPDATE:
857     case ACCESS_WRITE:
858       records_written = 0;
859       break;
860     }
861 }
862 
863 /* Perform a write to flush the buffer.  */
864 static ssize_t
_flush_write(void)865 _flush_write (void)
866 {
867   ssize_t status;
868 
869   checkpoint_run (true);
870   if (tape_length_option && tape_length_option <= bytes_written)
871     {
872       errno = ENOSPC;
873       status = 0;
874     }
875   else if (dev_null_output)
876     status = record_size;
877   else
878     status = sys_write_archive_buffer ();
879 
880   if (status && multi_volume_option && !inhibit_map)
881     {
882       struct bufmap *map = bufmap_locate (status);
883       if (map)
884 	{
885 	  size_t delta = status - map->start * BLOCKSIZE;
886 	  ssize_t diff;
887 	  map->nblocks += delta / BLOCKSIZE;
888 	  if (delta > map->sizeleft)
889 	    delta = map->sizeleft;
890 	  map->sizeleft -= delta;
891 	  if (map->sizeleft == 0)
892 	    {
893 	      diff = map->start + map->nblocks;
894 	      map = map->next;
895 	    }
896 	  else
897 	    diff = map->start;
898 	  bufmap_reset (map, - diff);
899 	}
900     }
901   return status;
902 }
903 
904 /* Handle write errors on the archive.  Write errors are always fatal.
905    Hitting the end of a volume does not cause a write error unless the
906    write was the first record of the volume.  */
907 void
archive_write_error(ssize_t status)908 archive_write_error (ssize_t status)
909 {
910   /* It might be useful to know how much was written before the error
911      occurred.  */
912   if (totals_option)
913     {
914       int e = errno;
915       print_total_stats ();
916       errno = e;
917     }
918 
919   write_fatal_details (*archive_name_cursor, status, record_size);
920 }
921 
922 /* Handle read errors on the archive.  If the read should be retried,
923    return to the caller.  */
924 void
archive_read_error(void)925 archive_read_error (void)
926 {
927   read_error (*archive_name_cursor);
928 
929   if (record_start_block == 0)
930     FATAL_ERROR ((0, 0, _("At beginning of tape, quitting now")));
931 
932   /* Read error in mid archive.  We retry up to READ_ERROR_MAX times and
933      then give up on reading the archive.  */
934 
935   if (read_error_count++ > READ_ERROR_MAX)
936     FATAL_ERROR ((0, 0, _("Too many errors, quitting")));
937   return;
938 }
939 
940 static bool
archive_is_dev(void)941 archive_is_dev (void)
942 {
943   struct stat st;
944 
945   if (fstat (archive, &st))
946     {
947       stat_diag (*archive_name_cursor);
948       return false;
949     }
950   return S_ISBLK (st.st_mode) || S_ISCHR (st.st_mode);
951 }
952 
953 static void
short_read(size_t status)954 short_read (size_t status)
955 {
956   size_t left;                  /* bytes left */
957   char *more;                   /* pointer to next byte to read */
958 
959   more = record_start->buffer + status;
960   left = record_size - status;
961 
962   if (left && left % BLOCKSIZE == 0
963       && (warning_option & WARN_RECORD_SIZE)
964       && record_start_block == 0 && status != 0
965       && archive_is_dev ())
966     {
967       unsigned long rsize = status / BLOCKSIZE;
968       WARN ((0, 0,
969 	     ngettext ("Record size = %lu block",
970 		       "Record size = %lu blocks",
971 		       rsize),
972 	     rsize));
973     }
974 
975   while (left % BLOCKSIZE != 0
976          || (left && status && read_full_records))
977     {
978       if (status)
979         while ((status = rmtread (archive, more, left)) == SAFE_READ_ERROR)
980           archive_read_error ();
981 
982       if (status == 0)
983         break;
984 
985       if (! read_full_records)
986         {
987           unsigned long rest = record_size - left;
988 
989           FATAL_ERROR ((0, 0,
990                         ngettext ("Unaligned block (%lu byte) in archive",
991                                   "Unaligned block (%lu bytes) in archive",
992                                   rest),
993                         rest));
994         }
995 
996       left -= status;
997       more += status;
998     }
999 
1000   record_end = record_start + (record_size - left) / BLOCKSIZE;
1001   records_read++;
1002 }
1003 
1004 /*  Flush the current buffer to/from the archive.  */
1005 void
flush_archive(void)1006 flush_archive (void)
1007 {
1008   size_t buffer_level;
1009 
1010   if (access_mode == ACCESS_READ && time_to_start_writing)
1011     {
1012       access_mode = ACCESS_WRITE;
1013       time_to_start_writing = false;
1014       backspace_output ();
1015       if (record_end - record_start < blocking_factor)
1016 	{
1017 	  memset (record_end, 0,
1018 		  (blocking_factor - (record_end - record_start))
1019 		  * BLOCKSIZE);
1020 	  record_end = record_start + blocking_factor;
1021 	  return;
1022 	}
1023     }
1024 
1025   buffer_level = current_block->buffer - record_start->buffer;
1026   record_start_block += record_end - record_start;
1027   current_block = record_start;
1028   record_end = record_start + blocking_factor;
1029 
1030   switch (access_mode)
1031     {
1032     case ACCESS_READ:
1033       flush_read ();
1034       break;
1035 
1036     case ACCESS_WRITE:
1037       flush_write_ptr (buffer_level);
1038       break;
1039 
1040     case ACCESS_UPDATE:
1041       abort ();
1042     }
1043 }
1044 
1045 /* Backspace the archive descriptor by one record worth.  If it's a
1046    tape, MTIOCTOP will work.  If it's something else, try to seek on
1047    it.  If we can't seek, we lose!  */
1048 static void
backspace_output(void)1049 backspace_output (void)
1050 {
1051 #ifdef MTIOCTOP
1052   {
1053     struct mtop operation;
1054 
1055     operation.mt_op = MTBSR;
1056     operation.mt_count = 1;
1057     if (rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1058       return;
1059     if (errno == EIO && rmtioctl (archive, MTIOCTOP, (char *) &operation) >= 0)
1060       return;
1061   }
1062 #endif
1063 
1064   {
1065     off_t position = rmtlseek (archive, (off_t) 0, SEEK_CUR);
1066 
1067     /* Seek back to the beginning of this record and start writing there.  */
1068 
1069     position -= record_end->buffer - record_start->buffer;
1070     if (position < 0)
1071       position = 0;
1072     if (rmtlseek (archive, position, SEEK_SET) != position)
1073       {
1074         /* Lseek failed.  Try a different method.  */
1075 
1076         WARN ((0, 0,
1077                _("Cannot backspace archive file; it may be unreadable without -i")));
1078 
1079         /* Replace the first part of the record with NULs.  */
1080 
1081         if (record_start->buffer != output_start)
1082           memset (record_start->buffer, 0,
1083                   output_start - record_start->buffer);
1084       }
1085   }
1086 }
1087 
1088 off_t
seek_archive(off_t size)1089 seek_archive (off_t size)
1090 {
1091   off_t start = current_block_ordinal ();
1092   off_t offset;
1093   off_t nrec, nblk;
1094   off_t skipped = (blocking_factor - (current_block - record_start))
1095                   * BLOCKSIZE;
1096 
1097   if (size <= skipped)
1098     return 0;
1099 
1100   /* Compute number of records to skip */
1101   nrec = (size - skipped) / record_size;
1102   if (nrec == 0)
1103     return 0;
1104   offset = rmtlseek (archive, nrec * record_size, SEEK_CUR);
1105   if (offset < 0)
1106     return offset;
1107 
1108   if (offset % record_size)
1109     FATAL_ERROR ((0, 0, _("rmtlseek not stopped at a record boundary")));
1110 
1111   /* Convert to number of records */
1112   offset /= BLOCKSIZE;
1113   /* Compute number of skipped blocks */
1114   nblk = offset - start;
1115 
1116   /* Update buffering info */
1117   records_read += nblk / blocking_factor;
1118   record_start_block = offset - blocking_factor;
1119   current_block = record_end;
1120 
1121   return nblk;
1122 }
1123 
1124 /* Close the archive file.  */
1125 void
close_archive(void)1126 close_archive (void)
1127 {
1128   if (time_to_start_writing || access_mode == ACCESS_WRITE)
1129     {
1130       do
1131 	flush_archive ();
1132       while (current_block > record_start);
1133     }
1134 
1135   compute_duration ();
1136   if (verify_option)
1137     verify_volume ();
1138 
1139   if (rmtclose (archive) != 0)
1140     close_error (*archive_name_cursor);
1141 
1142   sys_wait_for_child (child_pid, hit_eof);
1143 
1144   tar_stat_destroy (&current_stat_info);
1145   free (record_buffer[0]);
1146   free (record_buffer[1]);
1147   bufmap_free (NULL);
1148 }
1149 
1150 void
write_fatal_details(char const * name,ssize_t status,size_t size)1151 write_fatal_details (char const *name, ssize_t status, size_t size)
1152 {
1153   write_error_details (name, status, size);
1154   if (rmtclose (archive) != 0)
1155     close_error (*archive_name_cursor);
1156   sys_wait_for_child (child_pid, false);
1157   fatal_exit ();
1158 }
1159 
1160 /* Called to initialize the global volume number.  */
1161 void
init_volume_number(void)1162 init_volume_number (void)
1163 {
1164   FILE *file = fopen (volno_file_option, "r");
1165 
1166   if (file)
1167     {
1168       if (fscanf (file, "%d", &global_volno) != 1
1169           || global_volno < 0)
1170         FATAL_ERROR ((0, 0, _("%s: contains invalid volume number"),
1171                       quotearg_colon (volno_file_option)));
1172       if (ferror (file))
1173         read_error (volno_file_option);
1174       if (fclose (file) != 0)
1175         close_error (volno_file_option);
1176     }
1177   else if (errno != ENOENT)
1178     open_error (volno_file_option);
1179 }
1180 
1181 /* Called to write out the closing global volume number.  */
1182 void
closeout_volume_number(void)1183 closeout_volume_number (void)
1184 {
1185   FILE *file = fopen (volno_file_option, "w");
1186 
1187   if (file)
1188     {
1189       fprintf (file, "%d\n", global_volno);
1190       if (ferror (file))
1191         write_error (volno_file_option);
1192       if (fclose (file) != 0)
1193         close_error (volno_file_option);
1194     }
1195   else
1196     open_error (volno_file_option);
1197 }
1198 
1199 
1200 static void
increase_volume_number(void)1201 increase_volume_number (void)
1202 {
1203   global_volno++;
1204   if (global_volno < 0)
1205     FATAL_ERROR ((0, 0, _("Volume number overflow")));
1206   volno++;
1207 }
1208 
1209 static void
change_tape_menu(FILE * read_file)1210 change_tape_menu (FILE *read_file)
1211 {
1212   char *input_buffer = NULL;
1213   size_t size = 0;
1214   bool stop = false;
1215 
1216   while (!stop)
1217     {
1218       fputc ('\007', stderr);
1219       fprintf (stderr,
1220                _("Prepare volume #%d for %s and hit return: "),
1221                global_volno + 1, quote (*archive_name_cursor));
1222       fflush (stderr);
1223 
1224       if (getline (&input_buffer, &size, read_file) <= 0)
1225         {
1226           WARN ((0, 0, _("EOF where user reply was expected")));
1227 
1228           if (subcommand_option != EXTRACT_SUBCOMMAND
1229               && subcommand_option != LIST_SUBCOMMAND
1230               && subcommand_option != DIFF_SUBCOMMAND)
1231             WARN ((0, 0, _("WARNING: Archive is incomplete")));
1232 
1233           fatal_exit ();
1234         }
1235 
1236       if (input_buffer[0] == '\n'
1237           || input_buffer[0] == 'y'
1238           || input_buffer[0] == 'Y')
1239         break;
1240 
1241       switch (input_buffer[0])
1242         {
1243         case '?':
1244           {
1245             fprintf (stderr, _("\
1246  n name        Give a new file name for the next (and subsequent) volume(s)\n\
1247  q             Abort tar\n\
1248  y or newline  Continue operation\n"));
1249             if (!restrict_option)
1250               fprintf (stderr, _(" !             Spawn a subshell\n"));
1251             fprintf (stderr, _(" ?             Print this list\n"));
1252           }
1253           break;
1254 
1255         case 'q':
1256           /* Quit.  */
1257 
1258           WARN ((0, 0, _("No new volume; exiting.\n")));
1259 
1260           if (subcommand_option != EXTRACT_SUBCOMMAND
1261               && subcommand_option != LIST_SUBCOMMAND
1262               && subcommand_option != DIFF_SUBCOMMAND)
1263             WARN ((0, 0, _("WARNING: Archive is incomplete")));
1264 
1265           fatal_exit ();
1266 
1267         case 'n':
1268           /* Get new file name.  */
1269 
1270           {
1271             char *name;
1272             char *cursor;
1273 
1274             for (name = input_buffer + 1;
1275                  *name == ' ' || *name == '\t';
1276                  name++)
1277               ;
1278 
1279             for (cursor = name; *cursor && *cursor != '\n'; cursor++)
1280               ;
1281             *cursor = '\0';
1282 
1283             if (name[0])
1284               {
1285                 /* FIXME: the following allocation is never reclaimed.  */
1286                 *archive_name_cursor = xstrdup (name);
1287                 stop = true;
1288               }
1289             else
1290               fprintf (stderr, "%s",
1291                        _("File name not specified. Try again.\n"));
1292           }
1293           break;
1294 
1295         case '!':
1296           if (!restrict_option)
1297             {
1298               sys_spawn_shell ();
1299               break;
1300             }
1301 	  FALLTHROUGH;
1302         default:
1303           fprintf (stderr, _("Invalid input. Type ? for help.\n"));
1304         }
1305     }
1306   free (input_buffer);
1307 }
1308 
1309 /* We've hit the end of the old volume.  Close it and open the next one.
1310    Return nonzero on success.
1311 */
1312 static bool
new_volume(enum access_mode mode)1313 new_volume (enum access_mode mode)
1314 {
1315   static FILE *read_file;
1316   static int looped;
1317   int prompt;
1318 
1319   if (!read_file && !info_script_option)
1320     /* FIXME: if fopen is used, it will never be closed.  */
1321     read_file = archive == STDIN_FILENO ? fopen (TTY_NAME, "r") : stdin;
1322 
1323   if (now_verifying)
1324     return false;
1325   if (verify_option)
1326     verify_volume ();
1327 
1328   assign_string (&volume_label, NULL);
1329   assign_string (&continued_file_name, NULL);
1330   continued_file_size = continued_file_offset = 0;
1331   current_block = record_start;
1332 
1333   if (rmtclose (archive) != 0)
1334     close_error (*archive_name_cursor);
1335 
1336   archive_name_cursor++;
1337   if (archive_name_cursor == archive_name_array + archive_names)
1338     {
1339       archive_name_cursor = archive_name_array;
1340       looped = 1;
1341     }
1342   prompt = looped;
1343 
1344  tryagain:
1345   if (prompt)
1346     {
1347       /* We have to prompt from now on.  */
1348 
1349       if (info_script_option)
1350         {
1351           if (volno_file_option)
1352             closeout_volume_number ();
1353           if (sys_exec_info_script (archive_name_cursor, global_volno+1))
1354             FATAL_ERROR ((0, 0, _("%s command failed"),
1355                           quote (info_script_option)));
1356         }
1357       else
1358         change_tape_menu (read_file);
1359     }
1360 
1361   if (strcmp (archive_name_cursor[0], "-") == 0)
1362     {
1363       read_full_records = true;
1364       archive = STDIN_FILENO;
1365     }
1366   else if (verify_option)
1367     archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1368                        rsh_command_option);
1369   else
1370     switch (mode)
1371       {
1372       case ACCESS_READ:
1373         archive = rmtopen (*archive_name_cursor, O_RDONLY, MODE_RW,
1374                            rsh_command_option);
1375 	guess_seekable_archive ();
1376         break;
1377 
1378       case ACCESS_WRITE:
1379         if (backup_option)
1380           maybe_backup_file (*archive_name_cursor, 1);
1381         archive = rmtcreat (*archive_name_cursor, MODE_RW,
1382                             rsh_command_option);
1383         break;
1384 
1385       case ACCESS_UPDATE:
1386         archive = rmtopen (*archive_name_cursor, O_RDWR | O_CREAT, MODE_RW,
1387                            rsh_command_option);
1388         break;
1389       }
1390 
1391   if (archive < 0)
1392     {
1393       open_warn (*archive_name_cursor);
1394       if (!verify_option && mode == ACCESS_WRITE && backup_option)
1395         undo_last_backup ();
1396       prompt = 1;
1397       goto tryagain;
1398     }
1399 
1400   SET_BINARY_MODE (archive);
1401 
1402   return true;
1403 }
1404 
1405 static bool
read_header0(struct tar_stat_info * info)1406 read_header0 (struct tar_stat_info *info)
1407 {
1408   enum read_header rc;
1409 
1410   tar_stat_init (info);
1411   rc = read_header (&current_header, info, read_header_auto);
1412   if (rc == HEADER_SUCCESS)
1413     {
1414       set_next_block_after (current_header);
1415       return true;
1416     }
1417   ERROR ((0, 0, _("This does not look like a tar archive")));
1418   return false;
1419 }
1420 
1421 static bool
try_new_volume(void)1422 try_new_volume (void)
1423 {
1424   size_t status;
1425   union block *header;
1426   enum access_mode acc;
1427 
1428   switch (subcommand_option)
1429     {
1430     case APPEND_SUBCOMMAND:
1431     case CAT_SUBCOMMAND:
1432     case UPDATE_SUBCOMMAND:
1433       acc = ACCESS_UPDATE;
1434       break;
1435 
1436     default:
1437       acc = ACCESS_READ;
1438       break;
1439     }
1440 
1441   if (!new_volume (acc))
1442     return true;
1443 
1444   while ((status = rmtread (archive, record_start->buffer, record_size))
1445          == SAFE_READ_ERROR)
1446     archive_read_error ();
1447 
1448   if (status != record_size)
1449     short_read (status);
1450 
1451   header = find_next_block ();
1452   if (!header)
1453     {
1454       WARN ((0, 0, _("This does not look like a tar archive")));
1455       return false;
1456     }
1457 
1458   switch (header->header.typeflag)
1459     {
1460     case XGLTYPE:
1461       {
1462 	tar_stat_init (&dummy);
1463 	if (read_header (&header, &dummy, read_header_x_global)
1464 	    != HEADER_SUCCESS_EXTENDED)
1465 	  {
1466 	    WARN ((0, 0, _("This does not look like a tar archive")));
1467 	    return false;
1468 	  }
1469 
1470         xheader_decode (&dummy); /* decodes values from the global header */
1471         tar_stat_destroy (&dummy);
1472 
1473 	/* The initial global header must be immediately followed by
1474 	   an extended PAX header for the first member in this volume.
1475 	   However, in some cases tar may split volumes in the middle
1476 	   of a PAX header. This is incorrect, and should be fixed
1477            in the future versions. In the meantime we must be
1478 	   prepared to correctly list and extract such archives.
1479 
1480 	   If this happens, the following call to read_header returns
1481 	   HEADER_FAILURE, which is ignored.
1482 
1483 	   See also tests/multiv07.at */
1484 
1485 	switch (read_header (&header, &dummy, read_header_auto))
1486 	  {
1487 	  case HEADER_SUCCESS:
1488 	    set_next_block_after (header);
1489 	    break;
1490 
1491 	  case HEADER_FAILURE:
1492 	    break;
1493 
1494 	  default:
1495 	    WARN ((0, 0, _("This does not look like a tar archive")));
1496 	    return false;
1497 	  }
1498         break;
1499       }
1500 
1501     case GNUTYPE_VOLHDR:
1502       if (!read_header0 (&dummy))
1503         return false;
1504       tar_stat_destroy (&dummy);
1505       ASSIGN_STRING_N (&volume_label, current_header->header.name);
1506       set_next_block_after (header);
1507       header = find_next_block ();
1508       if (header->header.typeflag != GNUTYPE_MULTIVOL)
1509         break;
1510       FALLTHROUGH;
1511     case GNUTYPE_MULTIVOL:
1512       if (!read_header0 (&dummy))
1513         return false;
1514       tar_stat_destroy (&dummy);
1515       ASSIGN_STRING_N (&continued_file_name, current_header->header.name);
1516       continued_file_size =
1517         UINTMAX_FROM_HEADER (current_header->header.size);
1518       continued_file_offset =
1519         UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset);
1520       break;
1521 
1522     default:
1523       break;
1524     }
1525 
1526   if (bufmap_head)
1527     {
1528       uintmax_t s;
1529       if (!continued_file_name)
1530 	{
1531 	  WARN ((0, 0, _("%s is not continued on this volume"),
1532 		 quote (bufmap_head->file_name)));
1533 	  return false;
1534 	}
1535 
1536       if (strcmp (continued_file_name, bufmap_head->file_name))
1537         {
1538           if ((archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT)
1539               && strlen (bufmap_head->file_name) >= NAME_FIELD_SIZE
1540               && strncmp (continued_file_name, bufmap_head->file_name,
1541                           NAME_FIELD_SIZE) == 0)
1542             WARN ((0, 0,
1543  _("%s is possibly continued on this volume: header contains truncated name"),
1544                    quote (bufmap_head->file_name)));
1545           else
1546             {
1547               WARN ((0, 0, _("%s is not continued on this volume"),
1548                      quote (bufmap_head->file_name)));
1549               return false;
1550             }
1551         }
1552 
1553       s = continued_file_size + continued_file_offset;
1554 
1555       if (bufmap_head->sizetotal != s || s < continued_file_offset)
1556         {
1557           char totsizebuf[UINTMAX_STRSIZE_BOUND];
1558           char s1buf[UINTMAX_STRSIZE_BOUND];
1559           char s2buf[UINTMAX_STRSIZE_BOUND];
1560 
1561           WARN ((0, 0, _("%s is the wrong size (%s != %s + %s)"),
1562                  quote (continued_file_name),
1563                  STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1564                  STRINGIFY_BIGINT (continued_file_size, s1buf),
1565                  STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1566           return false;
1567         }
1568 
1569       if (bufmap_head->sizetotal - bufmap_head->sizeleft !=
1570 	  continued_file_offset)
1571         {
1572           char totsizebuf[UINTMAX_STRSIZE_BOUND];
1573           char s1buf[UINTMAX_STRSIZE_BOUND];
1574           char s2buf[UINTMAX_STRSIZE_BOUND];
1575 
1576           WARN ((0, 0, _("This volume is out of sequence (%s - %s != %s)"),
1577                  STRINGIFY_BIGINT (bufmap_head->sizetotal, totsizebuf),
1578                  STRINGIFY_BIGINT (bufmap_head->sizeleft, s1buf),
1579                  STRINGIFY_BIGINT (continued_file_offset, s2buf)));
1580 
1581           return false;
1582         }
1583     }
1584 
1585   increase_volume_number ();
1586   return true;
1587 }
1588 
1589 
1590 #define VOLUME_TEXT " Volume "
1591 #define VOLUME_TEXT_LEN (sizeof VOLUME_TEXT - 1)
1592 
1593 char *
drop_volume_label_suffix(const char * label)1594 drop_volume_label_suffix (const char *label)
1595 {
1596   const char *p;
1597   size_t len = strlen (label);
1598 
1599   if (len < 1)
1600     return NULL;
1601 
1602   for (p = label + len - 1; p > label && isdigit ((unsigned char) *p); p--)
1603     ;
1604   if (p > label && p - (VOLUME_TEXT_LEN - 1) > label)
1605     {
1606       p -= VOLUME_TEXT_LEN - 1;
1607       if (memcmp (p, VOLUME_TEXT, VOLUME_TEXT_LEN) == 0)
1608 	{
1609 	  char *s = xmalloc ((len = p - label) + 1);
1610 	  memcpy (s, label, len);
1611 	  s[len] = 0;
1612 	  return s;
1613 	}
1614     }
1615 
1616   return NULL;
1617 }
1618 
1619 /* Check LABEL against the volume label, seen as a globbing
1620    pattern.  Return true if the pattern matches.  In case of failure,
1621    retry matching a volume sequence number before giving up in
1622    multi-volume mode.  */
1623 static bool
check_label_pattern(const char * label)1624 check_label_pattern (const char *label)
1625 {
1626   char *string;
1627   bool result = false;
1628 
1629   if (fnmatch (volume_label_option, label, 0) == 0)
1630     return true;
1631 
1632   if (!multi_volume_option)
1633     return false;
1634 
1635   string = drop_volume_label_suffix (label);
1636   if (string)
1637     {
1638       result = fnmatch (string, volume_label_option, 0) == 0;
1639       free (string);
1640     }
1641   return result;
1642 }
1643 
1644 /* Check if the next block contains a volume label and if this matches
1645    the one given in the command line */
1646 static void
match_volume_label(void)1647 match_volume_label (void)
1648 {
1649   if (!volume_label)
1650     {
1651       union block *label = find_next_block ();
1652 
1653       if (!label)
1654 	FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1655 		      quote (volume_label_option)));
1656       if (label->header.typeflag == GNUTYPE_VOLHDR)
1657 	{
1658 	  ASSIGN_STRING_N (&volume_label, label->header.name);
1659 	}
1660       else if (label->header.typeflag == XGLTYPE)
1661 	{
1662 	  struct tar_stat_info st;
1663 	  tar_stat_init (&st);
1664 	  xheader_read (&st.xhdr, label,
1665 			OFF_FROM_HEADER (label->header.size));
1666 	  xheader_decode (&st);
1667 	  tar_stat_destroy (&st);
1668 	}
1669     }
1670 
1671   if (!volume_label)
1672     FATAL_ERROR ((0, 0, _("Archive not labeled to match %s"),
1673                   quote (volume_label_option)));
1674 
1675   if (!check_label_pattern (volume_label))
1676     FATAL_ERROR ((0, 0, _("Volume %s does not match %s"),
1677                   quote_n (0, volume_label),
1678                   quote_n (1, volume_label_option)));
1679 }
1680 
1681 /* Mark the archive with volume label STR. */
1682 static void
_write_volume_label(const char * str)1683 _write_volume_label (const char *str)
1684 {
1685   if (archive_format == POSIX_FORMAT)
1686     xheader_store ("GNU.volume.label", &dummy, str);
1687   else
1688     {
1689       union block *label = find_next_block ();
1690 
1691       memset (label, 0, BLOCKSIZE);
1692 
1693       strcpy (label->header.name, str);
1694       assign_string (&current_stat_info.file_name, label->header.name);
1695       current_stat_info.had_trailing_slash =
1696         strip_trailing_slashes (current_stat_info.file_name);
1697 
1698       label->header.typeflag = GNUTYPE_VOLHDR;
1699       TIME_TO_CHARS (start_time.tv_sec, label->header.mtime);
1700       finish_header (&current_stat_info, label, -1);
1701       set_next_block_after (label);
1702     }
1703 }
1704 
1705 #define VOL_SUFFIX "Volume"
1706 
1707 /* Add a volume label to a part of multi-volume archive */
1708 static void
add_volume_label(void)1709 add_volume_label (void)
1710 {
1711   char buf[UINTMAX_STRSIZE_BOUND];
1712   char *p = STRINGIFY_BIGINT (volno, buf);
1713   char *s = xmalloc (strlen (volume_label_option) + sizeof VOL_SUFFIX
1714                      + strlen (p) + 2);
1715   sprintf (s, "%s %s %s", volume_label_option, VOL_SUFFIX, p);
1716   _write_volume_label (s);
1717   free (s);
1718 }
1719 
1720 static void
add_chunk_header(struct bufmap * map)1721 add_chunk_header (struct bufmap *map)
1722 {
1723   if (archive_format == POSIX_FORMAT)
1724     {
1725       union block *blk;
1726       struct tar_stat_info st;
1727 
1728       memset (&st, 0, sizeof st);
1729       st.orig_file_name = st.file_name = map->file_name;
1730       st.stat.st_mode = S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
1731       st.stat.st_uid = getuid ();
1732       st.stat.st_gid = getgid ();
1733       st.orig_file_name = xheader_format_name (&st,
1734                                                "%d/GNUFileParts/%f.%n",
1735                                                volno);
1736       st.file_name = st.orig_file_name;
1737       st.archive_file_size = st.stat.st_size = map->sizeleft;
1738 
1739       blk = start_header (&st);
1740       if (!blk)
1741         abort (); /* FIXME */
1742       simple_finish_header (write_extended (false, &st, blk));
1743       free (st.orig_file_name);
1744     }
1745 }
1746 
1747 
1748 /* Add a volume label to the current archive */
1749 static void
write_volume_label(void)1750 write_volume_label (void)
1751 {
1752   if (multi_volume_option)
1753     add_volume_label ();
1754   else
1755     _write_volume_label (volume_label_option);
1756 }
1757 
1758 /* Write GNU multi-volume header */
1759 static void
gnu_add_multi_volume_header(struct bufmap * map)1760 gnu_add_multi_volume_header (struct bufmap *map)
1761 {
1762   int tmp;
1763   union block *block = find_next_block ();
1764   size_t len = strlen (map->file_name);
1765 
1766   if (len > NAME_FIELD_SIZE)
1767     {
1768       WARN ((0, 0,
1769 	     _("%s: file name too long to be stored in a GNU multivolume header, truncated"),
1770 	     quotearg_colon (map->file_name)));
1771       len = NAME_FIELD_SIZE;
1772     }
1773 
1774   memset (block, 0, BLOCKSIZE);
1775 
1776   memcpy (block->header.name, map->file_name, len);
1777   block->header.typeflag = GNUTYPE_MULTIVOL;
1778 
1779   OFF_TO_CHARS (map->sizeleft, block->header.size);
1780   OFF_TO_CHARS (map->sizetotal - map->sizeleft,
1781                 block->oldgnu_header.offset);
1782 
1783   tmp = verbose_option;
1784   verbose_option = 0;
1785   finish_header (&current_stat_info, block, -1);
1786   verbose_option = tmp;
1787   set_next_block_after (block);
1788 }
1789 
1790 /* Add a multi volume header to the current archive. The exact header format
1791    depends on the archive format. */
1792 static void
add_multi_volume_header(struct bufmap * map)1793 add_multi_volume_header (struct bufmap *map)
1794 {
1795   if (archive_format == POSIX_FORMAT)
1796     {
1797       off_t d = map->sizetotal - map->sizeleft;
1798       xheader_store ("GNU.volume.filename", &dummy, map->file_name);
1799       xheader_store ("GNU.volume.size", &dummy, &map->sizeleft);
1800       xheader_store ("GNU.volume.offset", &dummy, &d);
1801     }
1802   else
1803     gnu_add_multi_volume_header (map);
1804 }
1805 
1806 
1807 /* Low-level flush functions */
1808 
1809 /* Simple flush read (no multi-volume or label extensions) */
1810 static void
simple_flush_read(void)1811 simple_flush_read (void)
1812 {
1813   size_t status;                /* result from system call */
1814 
1815   checkpoint_run (false);
1816 
1817   /* Clear the count of errors.  This only applies to a single call to
1818      flush_read.  */
1819 
1820   read_error_count = 0;         /* clear error count */
1821 
1822   if (write_archive_to_stdout && record_start_block != 0)
1823     {
1824       archive = STDOUT_FILENO;
1825       status = sys_write_archive_buffer ();
1826       archive = STDIN_FILENO;
1827       if (status != record_size)
1828         archive_write_error (status);
1829     }
1830 
1831   for (;;)
1832     {
1833       status = rmtread (archive, record_start->buffer, record_size);
1834       if (status == record_size)
1835         {
1836           records_read++;
1837           return;
1838         }
1839       if (status == SAFE_READ_ERROR)
1840         {
1841           archive_read_error ();
1842           continue;             /* try again */
1843         }
1844       break;
1845     }
1846   short_read (status);
1847 }
1848 
1849 /* Simple flush write (no multi-volume or label extensions) */
1850 static void
simple_flush_write(size_t level)1851 simple_flush_write (size_t level __attribute__((unused)))
1852 {
1853   ssize_t status;
1854 
1855   status = _flush_write ();
1856   if (status != record_size)
1857     archive_write_error (status);
1858   else
1859     {
1860       records_written++;
1861       bytes_written += status;
1862     }
1863 }
1864 
1865 
1866 /* GNU flush functions. These support multi-volume and archive labels in
1867    GNU and PAX archive formats. */
1868 
1869 static void
_gnu_flush_read(void)1870 _gnu_flush_read (void)
1871 {
1872   size_t status;                /* result from system call */
1873 
1874   checkpoint_run (false);
1875 
1876   /* Clear the count of errors.  This only applies to a single call to
1877      flush_read.  */
1878 
1879   read_error_count = 0;         /* clear error count */
1880 
1881   if (write_archive_to_stdout && record_start_block != 0)
1882     {
1883       archive = STDOUT_FILENO;
1884       status = sys_write_archive_buffer ();
1885       archive = STDIN_FILENO;
1886       if (status != record_size)
1887         archive_write_error (status);
1888     }
1889 
1890   for (;;)
1891     {
1892       status = rmtread (archive, record_start->buffer, record_size);
1893       if (status == record_size)
1894         {
1895           records_read++;
1896           return;
1897         }
1898 
1899       /* The condition below used to include
1900               || (status > 0 && !read_full_records)
1901          This is incorrect since even if new_volume() succeeds, the
1902          subsequent call to rmtread will overwrite the chunk of data
1903          already read in the buffer, so the processing will fail */
1904       if ((status == 0
1905            || (status == SAFE_READ_ERROR && errno == ENOSPC))
1906           && multi_volume_option)
1907         {
1908           while (!try_new_volume ())
1909             ;
1910 	  if (current_block == record_end)
1911 	    /* Necessary for blocking_factor == 1 */
1912 	    flush_archive();
1913           return;
1914         }
1915       else if (status == SAFE_READ_ERROR)
1916         {
1917           archive_read_error ();
1918           continue;
1919         }
1920       break;
1921     }
1922   short_read (status);
1923 }
1924 
1925 static void
gnu_flush_read(void)1926 gnu_flush_read (void)
1927 {
1928   flush_read_ptr = simple_flush_read; /* Avoid recursion */
1929   _gnu_flush_read ();
1930   flush_read_ptr = gnu_flush_read;
1931 }
1932 
1933 static void
_gnu_flush_write(size_t buffer_level)1934 _gnu_flush_write (size_t buffer_level)
1935 {
1936   ssize_t status;
1937   union block *header;
1938   char *copy_ptr;
1939   size_t copy_size;
1940   size_t bufsize;
1941   struct bufmap *map;
1942 
1943   status = _flush_write ();
1944   if (status != record_size && !multi_volume_option)
1945     archive_write_error (status);
1946   else
1947     {
1948       if (status)
1949         records_written++;
1950       bytes_written += status;
1951     }
1952 
1953   if (status == record_size)
1954     {
1955       return;
1956     }
1957 
1958   map = bufmap_locate (status);
1959 
1960   if (status % BLOCKSIZE)
1961     {
1962       ERROR ((0, 0, _("write did not end on a block boundary")));
1963       archive_write_error (status);
1964     }
1965 
1966   /* In multi-volume mode. */
1967   /* ENXIO is for the UNIX PC.  */
1968   if (status < 0 && errno != ENOSPC && errno != EIO && errno != ENXIO)
1969     archive_write_error (status);
1970 
1971   if (!new_volume (ACCESS_WRITE))
1972     return;
1973 
1974   tar_stat_destroy (&dummy);
1975 
1976   increase_volume_number ();
1977   prev_written += bytes_written;
1978   bytes_written = 0;
1979 
1980   copy_ptr = record_start->buffer + status;
1981   copy_size = buffer_level - status;
1982 
1983   /* Switch to the next buffer */
1984   record_index = !record_index;
1985   init_buffer ();
1986 
1987   inhibit_map = 1;
1988 
1989   if (volume_label_option)
1990     add_volume_label ();
1991 
1992   if (map)
1993     add_multi_volume_header (map);
1994 
1995   write_extended (true, &dummy, find_next_block ());
1996   tar_stat_destroy (&dummy);
1997 
1998   if (map)
1999     add_chunk_header (map);
2000   header = find_next_block ();
2001   bufmap_reset (map, header - record_start);
2002   bufsize = available_space_after (header);
2003   inhibit_map = 0;
2004   while (bufsize < copy_size)
2005     {
2006       memcpy (header->buffer, copy_ptr, bufsize);
2007       copy_ptr += bufsize;
2008       copy_size -= bufsize;
2009       set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
2010       header = find_next_block ();
2011       bufsize = available_space_after (header);
2012     }
2013   memcpy (header->buffer, copy_ptr, copy_size);
2014   memset (header->buffer + copy_size, 0, bufsize - copy_size);
2015   set_next_block_after (header + (copy_size - 1) / BLOCKSIZE);
2016   find_next_block ();
2017 }
2018 
2019 static void
gnu_flush_write(size_t buffer_level)2020 gnu_flush_write (size_t buffer_level)
2021 {
2022   flush_write_ptr = simple_flush_write; /* Avoid recursion */
2023   _gnu_flush_write (buffer_level);
2024   flush_write_ptr = gnu_flush_write;
2025 }
2026 
2027 void
flush_read(void)2028 flush_read (void)
2029 {
2030   flush_read_ptr ();
2031 }
2032 
2033 void
flush_write(void)2034 flush_write (void)
2035 {
2036   flush_write_ptr (record_size);
2037 }
2038 
2039 void
open_archive(enum access_mode wanted_access)2040 open_archive (enum access_mode wanted_access)
2041 {
2042   flush_read_ptr = gnu_flush_read;
2043   flush_write_ptr = gnu_flush_write;
2044 
2045   _open_archive (wanted_access);
2046   switch (wanted_access)
2047     {
2048     case ACCESS_READ:
2049     case ACCESS_UPDATE:
2050       if (volume_label_option)
2051         match_volume_label ();
2052       break;
2053 
2054     case ACCESS_WRITE:
2055       records_written = 0;
2056       if (volume_label_option)
2057         write_volume_label ();
2058       break;
2059     }
2060   set_volume_start_time ();
2061 }
2062