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