ar_io.c revision 1.22 1 /* $NetBSD: ar_io.c,v 1.22 2002/01/31 19:27:53 tv Exp $ */
2
3 /*-
4 * Copyright (c) 1992 Keith Muller.
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Keith Muller of the University of California, San Diego.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
38 */
39
40 #include <sys/cdefs.h>
41 #if defined(__RCSID) && !defined(lint)
42 #if 0
43 static char sccsid[] = "@(#)ar_io.c 8.2 (Berkeley) 4/18/94";
44 #else
45 __RCSID("$NetBSD: ar_io.c,v 1.22 2002/01/31 19:27:53 tv Exp $");
46 #endif
47 #endif /* not lint */
48
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/mtio.h>
54 #include <sys/param.h>
55 #include <signal.h>
56 #include <string.h>
57 #include <fcntl.h>
58 #include <unistd.h>
59 #include <stdio.h>
60 #include <ctype.h>
61 #include <errno.h>
62 #include <stdlib.h>
63 #include "pax.h"
64 #include "extern.h"
65
66 /*
67 * Routines which deal directly with the archive I/O device/file.
68 */
69
70 #define DMOD 0666 /* default mode of created archives */
71 #define EXT_MODE O_RDONLY /* open mode for list/extract */
72 #define AR_MODE (O_WRONLY | O_CREAT | O_TRUNC) /* mode for archive */
73 #define APP_MODE O_RDWR /* mode for append */
74 #define STDO "<STDOUT>" /* pseudo name for stdout */
75 #define STDN "<STDIN>" /* pseudo name for stdin */
76 static int arfd = -1; /* archive file descriptor */
77 static int artyp = ISREG; /* archive type: file/FIFO/tape */
78 static int arvol = 1; /* archive volume number */
79 static int lstrval = -1; /* return value from last i/o */
80 static int io_ok; /* i/o worked on volume after resync */
81 static int did_io; /* did i/o ever occur on volume? */
82 static int done; /* set via tty termination */
83 static struct stat arsb; /* stat of archive device at open */
84 static int invld_rec; /* tape has out of spec record size */
85 static int wr_trail = 1; /* trailer was rewritten in append */
86 static int can_unlnk = 0; /* do we unlink null archives? */
87 const char *arcname; /* printable name of archive */
88 const char *gzip_program; /* name of gzip program */
89 time_t starttime; /* time the run started */
90 int minusCfd = -1; /* active -C directory */
91 int curdirfd = -1; /* original current directory */
92 int force_one_volume; /* 1 if we ignore volume changes */
93
94 static int get_phys(void);
95 extern sigset_t s_mask;
96 static void ar_start_gzip(int);
97 static const char *timefmt(char *, size_t, off_t, time_t);
98 static const char *sizefmt(char *, size_t, off_t);
99
100 /*
101 * ar_open()
102 * Opens the next archive volume. Determines the type of the device and
103 * sets up block sizes as required by the archive device and the format.
104 * Note: we may be called with name == NULL on the first open only.
105 * Return:
106 * -1 on failure, 0 otherwise
107 */
108
109 int
110 ar_open(const char *name)
111 {
112 struct mtget mb;
113
114 /*
115 * change back to the current directory (for now).
116 */
117 if (curdirfd != -1)
118 fchdir(curdirfd);
119
120 if (arfd != -1)
121 (void)close(arfd);
122 arfd = -1;
123 can_unlnk = did_io = io_ok = invld_rec = 0;
124 artyp = ISREG;
125 flcnt = 0;
126
127 /*
128 * open based on overall operation mode
129 */
130 switch (act) {
131 case LIST:
132 case EXTRACT:
133 if (name == NULL) {
134 arfd = STDIN_FILENO;
135 arcname = STDN;
136 } else if ((arfd = open(name, EXT_MODE, DMOD)) < 0)
137 syswarn(0, errno, "Failed open to read on %s", name);
138 if (zflag)
139 ar_start_gzip(arfd);
140 break;
141 case ARCHIVE:
142 if (name == NULL) {
143 arfd = STDOUT_FILENO;
144 arcname = STDO;
145 } else if ((arfd = open(name, AR_MODE, DMOD)) < 0)
146 syswarn(0, errno, "Failed open to write on %s", name);
147 else
148 can_unlnk = 1;
149 if (zflag)
150 ar_start_gzip(arfd);
151 break;
152 case APPND:
153 if (zflag)
154 err(1, "can not gzip while appending");
155 if (name == NULL) {
156 arfd = STDOUT_FILENO;
157 arcname = STDO;
158 } else if ((arfd = open(name, APP_MODE, DMOD)) < 0)
159 syswarn(0, errno, "Failed open to read/write on %s",
160 name);
161 break;
162 case COPY:
163 /*
164 * arfd not used in COPY mode
165 */
166 arcname = "<NONE>";
167 lstrval = 1;
168 return(0);
169 }
170 if (arfd < 0)
171 return(-1);
172
173 /*
174 * set up is based on device type
175 */
176 if (fstat(arfd, &arsb) < 0) {
177 syswarn(0, errno, "Failed stat on %s", arcname);
178 (void)close(arfd);
179 arfd = -1;
180 can_unlnk = 0;
181 return(-1);
182 }
183 if (S_ISDIR(arsb.st_mode)) {
184 tty_warn(0, "Cannot write an archive on top of a directory %s",
185 arcname);
186 (void)close(arfd);
187 arfd = -1;
188 can_unlnk = 0;
189 return(-1);
190 }
191
192 if (S_ISCHR(arsb.st_mode))
193 artyp = ioctl(arfd, MTIOCGET, &mb) ? ISCHR : ISTAPE;
194 else if (S_ISBLK(arsb.st_mode))
195 artyp = ISBLK;
196 else if ((lseek(arfd, (off_t)0L, SEEK_CUR) == -1) && (errno == ESPIPE))
197 artyp = ISPIPE;
198 else
199 artyp = ISREG;
200
201 /*
202 * make sure we beyond any doubt that we only can unlink regular files
203 * we created
204 */
205 if (artyp != ISREG)
206 can_unlnk = 0;
207
208 /*
209 * change directory if necessary
210 */
211 if (minusCfd != -1)
212 fchdir(minusCfd);
213
214 /*
215 * if we are writing, we are done
216 */
217 if (act == ARCHIVE) {
218 blksz = rdblksz = wrblksz;
219 lstrval = 1;
220 return(0);
221 }
222
223 /*
224 * set default blksz on read. APPNDs writes rdblksz on the last volume
225 * On all new archive volumes, we shift to wrblksz (if the user
226 * specified one, otherwize we will continue to use rdblksz). We
227 * must to set blocksize based on what kind of device the archive is
228 * stored.
229 */
230 switch(artyp) {
231 case ISTAPE:
232 /*
233 * Tape drives come in at least two flavors. Those that support
234 * variable sized records and those that have fixed sized
235 * records. They must be treated differently. For tape drives
236 * that support variable sized records, we must make large
237 * reads to make sure we get the entire record, otherwise we
238 * will just get the first part of the record (up to size we
239 * asked). Tapes with fixed sized records may or may not return
240 * multiple records in a single read. We really do not care
241 * what the physical record size is UNLESS we are going to
242 * append. (We will need the physical block size to rewrite
243 * the trailer). Only when we are appending do we go to the
244 * effort to figure out the true PHYSICAL record size.
245 */
246 blksz = rdblksz = MAXBLK;
247 break;
248 case ISPIPE:
249 case ISBLK:
250 case ISCHR:
251 /*
252 * Blocksize is not a major issue with these devices (but must
253 * be kept a multiple of 512). If the user specified a write
254 * block size, we use that to read. Under append, we must
255 * always keep blksz == rdblksz. Otherwise we go ahead and use
256 * the device optimal blocksize as (and if) returned by stat
257 * and if it is within pax specs.
258 */
259 if ((act == APPND) && wrblksz) {
260 blksz = rdblksz = wrblksz;
261 break;
262 }
263
264 if ((arsb.st_blksize > 0) && (arsb.st_blksize < MAXBLK) &&
265 ((arsb.st_blksize % BLKMULT) == 0))
266 rdblksz = arsb.st_blksize;
267 else
268 rdblksz = DEVBLK;
269 /*
270 * For performance go for large reads when we can without harm
271 */
272 if ((act == APPND) || (artyp == ISCHR))
273 blksz = rdblksz;
274 else
275 blksz = MAXBLK;
276 break;
277 case ISREG:
278 /*
279 * if the user specified wrblksz works, use it. Under appends
280 * we must always keep blksz == rdblksz
281 */
282 if ((act == APPND) && wrblksz && ((arsb.st_size%wrblksz)==0)){
283 blksz = rdblksz = wrblksz;
284 break;
285 }
286 /*
287 * See if we can find the blocking factor from the file size
288 */
289 for (rdblksz = MAXBLK; rdblksz > 0; rdblksz -= BLKMULT)
290 if ((arsb.st_size % rdblksz) == 0)
291 break;
292 /*
293 * When we cannot find a match, we may have a flawed archive.
294 */
295 if (rdblksz <= 0)
296 rdblksz = FILEBLK;
297 /*
298 * for performance go for large reads when we can
299 */
300 if (act == APPND)
301 blksz = rdblksz;
302 else
303 blksz = MAXBLK;
304 break;
305 default:
306 /*
307 * should never happen, worse case, slow...
308 */
309 blksz = rdblksz = BLKMULT;
310 break;
311 }
312 lstrval = 1;
313 return(0);
314 }
315
316 /*
317 * ar_close()
318 * closes archive device, increments volume number, and prints i/o summary
319 */
320 void
321 ar_close(void)
322 {
323 FILE *outf;
324
325 if (arfd < 0) {
326 did_io = io_ok = flcnt = 0;
327 return;
328 }
329
330 if (act == LIST)
331 outf = stdout;
332 else
333 outf = stderr;
334
335 /*
336 * Close archive file. This may take a LONG while on tapes (we may be
337 * forced to wait for the rewind to complete) so tell the user what is
338 * going on (this avoids the user hitting control-c thinking pax is
339 * broken).
340 */
341 if (vflag && (artyp == ISTAPE)) {
342 if (vfpart)
343 (void)putc('\n', outf);
344 (void)fprintf(outf,
345 "%s: Waiting for tape drive close to complete...",
346 argv0);
347 (void)fflush(outf);
348 }
349
350 /*
351 * if nothing was written to the archive (and we created it), we remove
352 * it
353 */
354 if (can_unlnk && (fstat(arfd, &arsb) == 0) && (S_ISREG(arsb.st_mode)) &&
355 (arsb.st_size == 0)) {
356 (void)unlink(arcname);
357 can_unlnk = 0;
358 }
359
360 (void)close(arfd);
361
362 if (vflag && (artyp == ISTAPE)) {
363 (void)fputs("done.\n", outf);
364 vfpart = 0;
365 (void)fflush(outf);
366 }
367 arfd = -1;
368
369 if (!io_ok && !did_io) {
370 flcnt = 0;
371 return;
372 }
373 did_io = io_ok = 0;
374
375 /*
376 * The volume number is only increased when the last device has data
377 * and we have already determined the archive format.
378 */
379 if (frmt != NULL)
380 ++arvol;
381
382 if (!vflag) {
383 flcnt = 0;
384 return;
385 }
386
387 /*
388 * Print out a summary of I/O for this archive volume.
389 */
390 if (vfpart) {
391 (void)putc('\n', outf);
392 vfpart = 0;
393 }
394
395 ar_summary(0);
396
397 (void)fflush(outf);
398 flcnt = 0;
399 }
400
401 /*
402 * ar_drain()
403 * drain any archive format independent padding from an archive read
404 * from a socket or a pipe. This is to prevent the process on the
405 * other side of the pipe from getting a SIGPIPE (pax will stop
406 * reading an archive once a format dependent trailer is detected).
407 */
408 void
409 ar_drain(void)
410 {
411 int res;
412 char drbuf[MAXBLK];
413
414 /*
415 * we only drain from a pipe/socket. Other devices can be closed
416 * without reading up to end of file. We sure hope that pipe is closed
417 * on the other side so we will get an EOF.
418 */
419 if ((artyp != ISPIPE) || (lstrval <= 0))
420 return;
421
422 /*
423 * keep reading until pipe is drained
424 */
425 while ((res = read_with_restart(arfd, drbuf, sizeof(drbuf))) > 0)
426 ;
427 lstrval = res;
428 }
429
430 /*
431 * ar_set_wr()
432 * Set up device right before switching from read to write in an append.
433 * device dependent code (if required) to do this should be added here.
434 * For all archive devices we are already positioned at the place we want
435 * to start writing when this routine is called.
436 * Return:
437 * 0 if all ready to write, -1 otherwise
438 */
439
440 int
441 ar_set_wr(void)
442 {
443 off_t cpos;
444
445 /*
446 * we must make sure the trailer is rewritten on append, ar_next()
447 * will stop us if the archive containing the trailer was not written
448 */
449 wr_trail = 0;
450
451 /*
452 * Add any device dependent code as required here
453 */
454 if (artyp != ISREG)
455 return(0);
456 /*
457 * Ok we have an archive in a regular file. If we were rewriting a
458 * file, we must get rid of all the stuff after the current offset
459 * (it was not written by pax).
460 */
461 if (((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0) ||
462 (ftruncate(arfd, cpos) < 0)) {
463 syswarn(1, errno, "Unable to truncate archive file");
464 return(-1);
465 }
466 return(0);
467 }
468
469 /*
470 * ar_app_ok()
471 * check if the last volume in the archive allows appends. We cannot check
472 * this until we are ready to write since there is no spec that says all
473 * volumes in a single archive have to be of the same type...
474 * Return:
475 * 0 if we can append, -1 otherwise.
476 */
477
478 int
479 ar_app_ok(void)
480 {
481 if (artyp == ISPIPE) {
482 tty_warn(1,
483 "Cannot append to an archive obtained from a pipe.");
484 return(-1);
485 }
486
487 if (!invld_rec)
488 return(0);
489 tty_warn(1,
490 "Cannot append, device record size %d does not support %s spec",
491 rdblksz, argv0);
492 return(-1);
493 }
494
495 #ifdef SYS_NO_RESTART
496 /*
497 * read_with_restart()
498 * Equivalent to read() but does retry on signals.
499 * This function is not needed on 4.2BSD and later.
500 * Return:
501 * Number of bytes written. -1 indicates an error.
502 */
503
504 int
505 read_with_restart(int fd, void *buf, int bsz)
506 {
507 int r;
508
509 while (((r = read(fd, buf, bsz)) < 0) && errno == EINTR)
510 ;
511
512 return(r);
513 }
514 #endif
515
516 /*
517 * xread()
518 * Equivalent to read() but does retry on partial read, which may occur
519 * on signals.
520 * Return:
521 * Number of bytes read. 0 for end of file, -1 for an error.
522 */
523
524 int
525 xread(int fd, void *buf, int bsz)
526 {
527 char *b = buf;
528 int nread = 0;
529 int r;
530
531 do {
532 if ((r = read_with_restart(fd, b, bsz)) <= 0)
533 break;
534 b += r;
535 bsz -= r;
536 nread += r;
537 } while (bsz > 0);
538
539 return(nread ? nread : r);
540 }
541
542 #ifdef SYS_NO_RESTART
543 /*
544 * write_with_restart()
545 * Equivalent to write() but does retry on signals.
546 * This function is not needed on 4.2BSD and later.
547 * Return:
548 * Number of bytes written. -1 indicates an error.
549 */
550
551 int
552 write_with_restart(int fd, void *buf, int bsz)
553 {
554 int r;
555
556 while (((r = write(fd, buf, bsz)) < 0) && errno == EINTR)
557 ;
558
559 return(r);
560 }
561 #endif
562
563 /*
564 * xwrite()
565 * Equivalent to write() but does retry on partial write, which may occur
566 * on signals.
567 * Return:
568 * Number of bytes written. -1 indicates an error.
569 */
570
571 int
572 xwrite(int fd, void *buf, int bsz)
573 {
574 char *b = buf;
575 int written = 0;
576 int r;
577
578 do {
579 if ((r = write_with_restart(fd, b, bsz)) <= 0)
580 break;
581 b += r;
582 bsz -= r;
583 written += r;
584 } while (bsz > 0);
585
586 return(written ? written : r);
587 }
588
589 /*
590 * ar_read()
591 * read up to a specified number of bytes from the archive into the
592 * supplied buffer. When dealing with tapes we may not always be able to
593 * read what we want.
594 * Return:
595 * Number of bytes in buffer. 0 for end of file, -1 for a read error.
596 */
597
598 int
599 ar_read(char *buf, int cnt)
600 {
601 int res = 0;
602
603 /*
604 * if last i/o was in error, no more reads until reset or new volume
605 */
606 if (lstrval <= 0)
607 return(lstrval);
608
609 /*
610 * how we read must be based on device type
611 */
612 switch (artyp) {
613 case ISTAPE:
614 if ((res = read_with_restart(arfd, buf, cnt)) > 0) {
615 /*
616 * CAUTION: tape systems may not always return the same
617 * sized records so we leave blksz == MAXBLK. The
618 * physical record size that a tape drive supports is
619 * very hard to determine in a uniform and portable
620 * manner.
621 */
622 io_ok = 1;
623 if (res != rdblksz) {
624 /*
625 * Record size changed. If this is happens on
626 * any record after the first, we probably have
627 * a tape drive which has a fixed record size
628 * we are getting multiple records in a single
629 * read). Watch out for record blocking that
630 * violates pax spec (must be a multiple of
631 * BLKMULT).
632 */
633 rdblksz = res;
634 if (rdblksz % BLKMULT)
635 invld_rec = 1;
636 }
637 return(res);
638 }
639 break;
640 case ISREG:
641 case ISBLK:
642 case ISCHR:
643 case ISPIPE:
644 default:
645 /*
646 * Files are so easy to deal with. These other things cannot
647 * be trusted at all. So when we are dealing with character
648 * devices and pipes we just take what they have ready for us
649 * and return. Trying to do anything else with them runs the
650 * risk of failure.
651 */
652 if ((res = read_with_restart(arfd, buf, cnt)) > 0) {
653 io_ok = 1;
654 return(res);
655 }
656 break;
657 }
658
659 /*
660 * We are in trouble at this point, something is broken...
661 */
662 lstrval = res;
663 if (res < 0)
664 syswarn(1, errno, "Failed read on archive volume %d", arvol);
665 else if (!is_oldgnutar)
666 tty_warn(0, "End of archive volume %d reached", arvol);
667 return(res);
668 }
669
670 /*
671 * ar_write()
672 * Write a specified number of bytes in supplied buffer to the archive
673 * device so it appears as a single "block". Deals with errors and tries
674 * to recover when faced with short writes.
675 * Return:
676 * Number of bytes written. 0 indicates end of volume reached and with no
677 * flaws (as best that can be detected). A -1 indicates an unrecoverable
678 * error in the archive occurred.
679 */
680
681 int
682 ar_write(char *buf, int bsz)
683 {
684 int res;
685 off_t cpos;
686
687 /*
688 * do not allow pax to create a "bad" archive. Once a write fails on
689 * an archive volume prevent further writes to it.
690 */
691 if (lstrval <= 0)
692 return(lstrval);
693
694 if ((res = xwrite(arfd, buf, bsz)) == bsz) {
695 wr_trail = 1;
696 io_ok = 1;
697 return(bsz);
698 }
699 /*
700 * write broke, see what we can do with it. We try to send any partial
701 * writes that may violate pax spec to the next archive volume.
702 */
703 if (res < 0)
704 lstrval = res;
705 else
706 lstrval = 0;
707
708 switch (artyp) {
709 case ISREG:
710 if ((res > 0) && (res % BLKMULT)) {
711 /*
712 * try to fix up partial writes which are not BLKMULT
713 * in size by forcing the runt record to next archive
714 * volume
715 */
716 if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0)
717 break;
718 cpos -= (off_t)res;
719 if (ftruncate(arfd, cpos) < 0)
720 break;
721 res = lstrval = 0;
722 break;
723 }
724 if (res >= 0)
725 break;
726 /*
727 * if file is out of space, handle it like a return of 0
728 */
729 if ((errno == ENOSPC) || (errno == EFBIG) || (errno == EDQUOT))
730 res = lstrval = 0;
731 break;
732 case ISTAPE:
733 case ISCHR:
734 case ISBLK:
735 if (res >= 0)
736 break;
737 if (errno == EACCES) {
738 tty_warn(0,
739 "Write failed, archive is write protected.");
740 res = lstrval = 0;
741 return(0);
742 }
743 /*
744 * see if we reached the end of media, if so force a change to
745 * the next volume
746 */
747 if ((errno == ENOSPC) || (errno == EIO) || (errno == ENXIO))
748 res = lstrval = 0;
749 break;
750 case ISPIPE:
751 default:
752 /*
753 * we cannot fix errors to these devices
754 */
755 break;
756 }
757
758 /*
759 * Better tell the user the bad news...
760 * if this is a block aligned archive format, we may have a bad archive
761 * if the format wants the header to start at a BLKMULT boundary. While
762 * we can deal with the mis-aligned data, it violates spec and other
763 * archive readers will likely fail. if the format is not block
764 * aligned, the user may be lucky (and the archive is ok).
765 */
766 if (res >= 0) {
767 if (res > 0)
768 wr_trail = 1;
769 io_ok = 1;
770 }
771
772 /*
773 * If we were trying to rewrite the trailer and it didn't work, we
774 * must quit right away.
775 */
776 if (!wr_trail && (res <= 0)) {
777 tty_warn(1,
778 "Unable to append, trailer re-write failed. Quitting.");
779 return(res);
780 }
781
782 if (res == 0)
783 tty_warn(0, "End of archive volume %d reached", arvol);
784 else if (res < 0)
785 syswarn(1, errno, "Failed write to archive volume: %d", arvol);
786 else if (!frmt->blkalgn || ((res % frmt->blkalgn) == 0))
787 tty_warn(0,
788 "WARNING: partial archive write. Archive MAY BE FLAWED");
789 else
790 tty_warn(1,"WARNING: partial archive write. Archive IS FLAWED");
791 return(res);
792 }
793
794 /*
795 * ar_rdsync()
796 * Try to move past a bad spot on a flawed archive as needed to continue
797 * I/O. Clears error flags to allow I/O to continue.
798 * Return:
799 * 0 when ok to try i/o again, -1 otherwise.
800 */
801
802 int
803 ar_rdsync(void)
804 {
805 long fsbz;
806 off_t cpos;
807 off_t mpos;
808 struct mtop mb;
809
810 /*
811 * Fail resync attempts at user request (done) or this is going to be
812 * an update/append to a existing archive. if last i/o hit media end,
813 * we need to go to the next volume not try a resync
814 */
815 if ((done > 0) || (lstrval == 0))
816 return(-1);
817
818 if ((act == APPND) || (act == ARCHIVE)) {
819 tty_warn(1, "Cannot allow updates to an archive with flaws.");
820 return(-1);
821 }
822 if (io_ok)
823 did_io = 1;
824
825 switch(artyp) {
826 case ISTAPE:
827 /*
828 * if the last i/o was a successful data transfer, we assume
829 * the fault is just a bad record on the tape that we are now
830 * past. If we did not get any data since the last resync try
831 * to move the tape forward one PHYSICAL record past any
832 * damaged tape section. Some tape drives are stubborn and need
833 * to be pushed.
834 */
835 if (io_ok) {
836 io_ok = 0;
837 lstrval = 1;
838 break;
839 }
840 mb.mt_op = MTFSR;
841 mb.mt_count = 1;
842 if (ioctl(arfd, MTIOCTOP, &mb) < 0)
843 break;
844 lstrval = 1;
845 break;
846 case ISREG:
847 case ISCHR:
848 case ISBLK:
849 /*
850 * try to step over the bad part of the device.
851 */
852 io_ok = 0;
853 if (((fsbz = arsb.st_blksize) <= 0) || (artyp != ISREG))
854 fsbz = BLKMULT;
855 if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0)
856 break;
857 mpos = fsbz - (cpos % (off_t)fsbz);
858 if (lseek(arfd, mpos, SEEK_CUR) < 0)
859 break;
860 lstrval = 1;
861 break;
862 case ISPIPE:
863 default:
864 /*
865 * cannot recover on these archive device types
866 */
867 io_ok = 0;
868 break;
869 }
870 if (lstrval <= 0) {
871 tty_warn(1, "Unable to recover from an archive read failure.");
872 return(-1);
873 }
874 tty_warn(0, "Attempting to recover from an archive read failure.");
875 return(0);
876 }
877
878 /*
879 * ar_fow()
880 * Move the I/O position within the archive forward the specified number of
881 * bytes as supported by the device. If we cannot move the requested
882 * number of bytes, return the actual number of bytes moved in skipped.
883 * Return:
884 * 0 if moved the requested distance, -1 on complete failure, 1 on
885 * partial move (the amount moved is in skipped)
886 */
887
888 int
889 ar_fow(off_t sksz, off_t *skipped)
890 {
891 off_t cpos;
892 off_t mpos;
893
894 *skipped = 0;
895 if (sksz <= 0)
896 return(0);
897
898 /*
899 * we cannot move forward at EOF or error
900 */
901 if (lstrval <= 0)
902 return(lstrval);
903
904 /*
905 * Safer to read forward on devices where it is hard to find the end of
906 * the media without reading to it. With tapes we cannot be sure of the
907 * number of physical blocks to skip (we do not know physical block
908 * size at this point), so we must only read forward on tapes!
909 */
910 if (artyp == ISTAPE || artyp == ISPIPE)
911 return(0);
912
913 /*
914 * figure out where we are in the archive
915 */
916 if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) >= 0) {
917 /*
918 * we can be asked to move farther than there are bytes in this
919 * volume, if so, just go to file end and let normal buf_fill()
920 * deal with the end of file (it will go to next volume by
921 * itself)
922 */
923 mpos = cpos + sksz;
924 if (artyp == ISREG && mpos > arsb.st_size)
925 mpos = arsb.st_size;
926 if ((mpos = lseek(arfd, mpos, SEEK_SET)) >= 0) {
927 *skipped = mpos - cpos;
928 return(0);
929 }
930 } else {
931 if (artyp != ISREG)
932 return(0); /* non-seekable device */
933 }
934 syswarn(1, errno, "Forward positioning operation on archive failed");
935 lstrval = -1;
936 return(-1);
937 }
938
939 /*
940 * ar_rev()
941 * move the i/o position within the archive backwards the specified byte
942 * count as supported by the device. With tapes drives we RESET rdblksz to
943 * the PHYSICAL blocksize.
944 * NOTE: We should only be called to move backwards so we can rewrite the
945 * last records (the trailer) of an archive (APPEND).
946 * Return:
947 * 0 if moved the requested distance, -1 on complete failure
948 */
949
950 int
951 ar_rev(off_t sksz)
952 {
953 off_t cpos;
954 struct mtop mb;
955 int phyblk;
956
957 /*
958 * make sure we do not have try to reverse on a flawed archive
959 */
960 if (lstrval < 0)
961 return(lstrval);
962
963 switch(artyp) {
964 case ISPIPE:
965 if (sksz <= 0)
966 break;
967 /*
968 * cannot go backwards on these critters
969 */
970 tty_warn(1, "Reverse positioning on pipes is not supported.");
971 lstrval = -1;
972 return(-1);
973 case ISREG:
974 case ISBLK:
975 case ISCHR:
976 default:
977 if (sksz <= 0)
978 break;
979
980 /*
981 * For things other than files, backwards movement has a very
982 * high probability of failure as we really do not know the
983 * true attributes of the device we are talking to (the device
984 * may not even have the ability to lseek() in any direction).
985 * First we figure out where we are in the archive.
986 */
987 if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0) {
988 syswarn(1, errno,
989 "Unable to obtain current archive byte offset");
990 lstrval = -1;
991 return(-1);
992 }
993
994 /*
995 * we may try to go backwards past the start when the archive
996 * is only a single record. If this hapens and we are on a
997 * multi volume archive, we need to go to the end of the
998 * previous volume and continue our movement backwards from
999 * there.
1000 */
1001 if ((cpos -= sksz) < (off_t)0L) {
1002 if (arvol > 1) {
1003 /*
1004 * this should never happen
1005 */
1006 tty_warn(1,
1007 "Reverse position on previous volume.");
1008 lstrval = -1;
1009 return(-1);
1010 }
1011 cpos = (off_t)0L;
1012 }
1013 if (lseek(arfd, cpos, SEEK_SET) < 0) {
1014 syswarn(1, errno, "Unable to seek archive backwards");
1015 lstrval = -1;
1016 return(-1);
1017 }
1018 break;
1019 case ISTAPE:
1020 /*
1021 * Calculate and move the proper number of PHYSICAL tape
1022 * blocks. If the sksz is not an even multiple of the physical
1023 * tape size, we cannot do the move (this should never happen).
1024 * (We also cannot handler trailers spread over two vols).
1025 * get_phys() also makes sure we are in front of the filemark.
1026 */
1027 if ((phyblk = get_phys()) <= 0) {
1028 lstrval = -1;
1029 return(-1);
1030 }
1031
1032 /*
1033 * make sure future tape reads only go by physical tape block
1034 * size (set rdblksz to the real size).
1035 */
1036 rdblksz = phyblk;
1037
1038 /*
1039 * if no movement is required, just return (we must be after
1040 * get_phys() so the physical blocksize is properly set)
1041 */
1042 if (sksz <= 0)
1043 break;
1044
1045 /*
1046 * ok we have to move. Make sure the tape drive can do it.
1047 */
1048 if (sksz % phyblk) {
1049 tty_warn(1,
1050 "Tape drive unable to backspace requested amount");
1051 lstrval = -1;
1052 return(-1);
1053 }
1054
1055 /*
1056 * move backwards the requested number of bytes
1057 */
1058 mb.mt_op = MTBSR;
1059 mb.mt_count = sksz/phyblk;
1060 if (ioctl(arfd, MTIOCTOP, &mb) < 0) {
1061 syswarn(1,errno, "Unable to backspace tape %ld blocks.",
1062 (long) mb.mt_count);
1063 lstrval = -1;
1064 return(-1);
1065 }
1066 break;
1067 }
1068 lstrval = 1;
1069 return(0);
1070 }
1071
1072 /*
1073 * get_phys()
1074 * Determine the physical block size on a tape drive. We need the physical
1075 * block size so we know how many bytes we skip over when we move with
1076 * mtio commands. We also make sure we are BEFORE THE TAPE FILEMARK when
1077 * return.
1078 * This is one really SLOW routine...
1079 * Return:
1080 * physical block size if ok (ok > 0), -1 otherwise
1081 */
1082
1083 static int
1084 get_phys(void)
1085 {
1086 int padsz = 0;
1087 int res;
1088 int phyblk;
1089 struct mtop mb;
1090 char scbuf[MAXBLK];
1091
1092 /*
1093 * move to the file mark, and then back up one record and read it.
1094 * this should tell us the physical record size the tape is using.
1095 */
1096 if (lstrval == 1) {
1097 /*
1098 * we know we are at file mark when we get back a 0 from
1099 * read()
1100 */
1101 while ((res = read_with_restart(arfd, scbuf, sizeof(scbuf))) > 0)
1102 padsz += res;
1103 if (res < 0) {
1104 syswarn(1, errno, "Unable to locate tape filemark.");
1105 return(-1);
1106 }
1107 }
1108
1109 /*
1110 * move backwards over the file mark so we are at the end of the
1111 * last record.
1112 */
1113 mb.mt_op = MTBSF;
1114 mb.mt_count = 1;
1115 if (ioctl(arfd, MTIOCTOP, &mb) < 0) {
1116 syswarn(1, errno, "Unable to backspace over tape filemark.");
1117 return(-1);
1118 }
1119
1120 /*
1121 * move backwards so we are in front of the last record and read it to
1122 * get physical tape blocksize.
1123 */
1124 mb.mt_op = MTBSR;
1125 mb.mt_count = 1;
1126 if (ioctl(arfd, MTIOCTOP, &mb) < 0) {
1127 syswarn(1, errno, "Unable to backspace over last tape block.");
1128 return(-1);
1129 }
1130 if ((phyblk = read_with_restart(arfd, scbuf, sizeof(scbuf))) <= 0) {
1131 syswarn(1, errno, "Cannot determine archive tape blocksize.");
1132 return(-1);
1133 }
1134
1135 /*
1136 * read forward to the file mark, then back up in front of the filemark
1137 * (this is a bit paranoid, but should be safe to do).
1138 */
1139 while ((res = read_with_restart(arfd, scbuf, sizeof(scbuf))) > 0)
1140 ;
1141 if (res < 0) {
1142 syswarn(1, errno, "Unable to locate tape filemark.");
1143 return(-1);
1144 }
1145 mb.mt_op = MTBSF;
1146 mb.mt_count = 1;
1147 if (ioctl(arfd, MTIOCTOP, &mb) < 0) {
1148 syswarn(1, errno, "Unable to backspace over tape filemark.");
1149 return(-1);
1150 }
1151
1152 /*
1153 * set lstrval so we know that the filemark has not been seen
1154 */
1155 lstrval = 1;
1156
1157 /*
1158 * return if there was no padding
1159 */
1160 if (padsz == 0)
1161 return(phyblk);
1162
1163 /*
1164 * make sure we can move backwards over the padding. (this should
1165 * never fail).
1166 */
1167 if (padsz % phyblk) {
1168 tty_warn(1, "Tape drive unable to backspace requested amount");
1169 return(-1);
1170 }
1171
1172 /*
1173 * move backwards over the padding so the head is where it was when
1174 * we were first called (if required).
1175 */
1176 mb.mt_op = MTBSR;
1177 mb.mt_count = padsz/phyblk;
1178 if (ioctl(arfd, MTIOCTOP, &mb) < 0) {
1179 syswarn(1,errno,"Unable to backspace tape over %ld pad blocks",
1180 (long)mb.mt_count);
1181 return(-1);
1182 }
1183 return(phyblk);
1184 }
1185
1186 /*
1187 * ar_next()
1188 * prompts the user for the next volume in this archive. For some devices
1189 * we may allow the media to be changed. Otherwise a new archive is
1190 * prompted for. By pax spec, if there is no controlling tty or an eof is
1191 * read on tty input, we must quit pax.
1192 * Return:
1193 * 0 when ready to continue, -1 when all done
1194 */
1195
1196 int
1197 ar_next(void)
1198 {
1199 char buf[PAXPATHLEN+2];
1200 static int freeit = 0;
1201 sigset_t o_mask;
1202
1203 /*
1204 * WE MUST CLOSE THE DEVICE. A lot of devices must see last close, (so
1205 * things like writing EOF etc will be done) (Watch out ar_close() can
1206 * also be called via a signal handler, so we must prevent a race.
1207 */
1208 if (sigprocmask(SIG_BLOCK, &s_mask, &o_mask) < 0)
1209 syswarn(0, errno, "Unable to set signal mask");
1210 ar_close();
1211 if (sigprocmask(SIG_SETMASK, &o_mask, (sigset_t *)NULL) < 0)
1212 syswarn(0, errno, "Unable to restore signal mask");
1213
1214 if (done || !wr_trail || is_oldgnutar || force_one_volume)
1215 return(-1);
1216
1217 tty_prnt("\nATTENTION! %s archive volume change required.\n", argv0);
1218
1219 /*
1220 * if i/o is on stdin or stdout, we cannot reopen it (we do not know
1221 * the name), the user will be forced to type it in.
1222 */
1223 if (strcmp(arcname, STDO) && strcmp(arcname, STDN) && (artyp != ISREG)
1224 && (artyp != ISPIPE)) {
1225 if (artyp == ISTAPE) {
1226 tty_prnt("%s ready for archive tape volume: %d\n",
1227 arcname, arvol);
1228 tty_prnt("Load the NEXT TAPE on the tape drive");
1229 } else {
1230 tty_prnt("%s ready for archive volume: %d\n",
1231 arcname, arvol);
1232 tty_prnt("Load the NEXT STORAGE MEDIA (if required)");
1233 }
1234
1235 if ((act == ARCHIVE) || (act == APPND))
1236 tty_prnt(" and make sure it is WRITE ENABLED.\n");
1237 else
1238 tty_prnt("\n");
1239
1240 for(;;) {
1241 tty_prnt("Type \"y\" to continue, \".\" to quit %s,",
1242 argv0);
1243 tty_prnt(" or \"s\" to switch to new device.\nIf you");
1244 tty_prnt(" cannot change storage media, type \"s\"\n");
1245 tty_prnt("Is the device ready and online? > ");
1246
1247 if ((tty_read(buf,sizeof(buf))<0) || !strcmp(buf,".")){
1248 done = 1;
1249 lstrval = -1;
1250 tty_prnt("Quitting %s!\n", argv0);
1251 vfpart = 0;
1252 return(-1);
1253 }
1254
1255 if ((buf[0] == '\0') || (buf[1] != '\0')) {
1256 tty_prnt("%s unknown command, try again\n",buf);
1257 continue;
1258 }
1259
1260 switch (buf[0]) {
1261 case 'y':
1262 case 'Y':
1263 /*
1264 * we are to continue with the same device
1265 */
1266 if (ar_open(arcname) >= 0)
1267 return(0);
1268 tty_prnt("Cannot re-open %s, try again\n",
1269 arcname);
1270 continue;
1271 case 's':
1272 case 'S':
1273 /*
1274 * user wants to open a different device
1275 */
1276 tty_prnt("Switching to a different archive\n");
1277 break;
1278 default:
1279 tty_prnt("%s unknown command, try again\n",buf);
1280 continue;
1281 }
1282 break;
1283 }
1284 } else
1285 tty_prnt("Ready for archive volume: %d\n", arvol);
1286
1287 /*
1288 * have to go to a different archive
1289 */
1290 for (;;) {
1291 tty_prnt("Input archive name or \".\" to quit %s.\n", argv0);
1292 tty_prnt("Archive name > ");
1293
1294 if ((tty_read(buf, sizeof(buf)) < 0) || !strcmp(buf, ".")) {
1295 done = 1;
1296 lstrval = -1;
1297 tty_prnt("Quitting %s!\n", argv0);
1298 vfpart = 0;
1299 return(-1);
1300 }
1301 if (buf[0] == '\0') {
1302 tty_prnt("Empty file name, try again\n");
1303 continue;
1304 }
1305 if (!strcmp(buf, "..")) {
1306 tty_prnt("Illegal file name: .. try again\n");
1307 continue;
1308 }
1309 if (strlen(buf) > PAXPATHLEN) {
1310 tty_prnt("File name too long, try again\n");
1311 continue;
1312 }
1313
1314 /*
1315 * try to open new archive
1316 */
1317 if (ar_open(buf) >= 0) {
1318 if (freeit) {
1319 (void)free((char *)arcname);
1320 freeit = 0;
1321 }
1322 if ((arcname = strdup(buf)) == NULL) {
1323 done = 1;
1324 lstrval = -1;
1325 tty_warn(0, "Cannot save archive name.");
1326 return(-1);
1327 }
1328 freeit = 1;
1329 break;
1330 }
1331 tty_prnt("Cannot open %s, try again\n", buf);
1332 continue;
1333 }
1334 return(0);
1335 }
1336
1337 /*
1338 * ar_start_gzip()
1339 * starts the gzip compression/decompression process as a child, using magic
1340 * to keep the fd the same in the calling function (parent).
1341 */
1342 void
1343 ar_start_gzip(int fd)
1344 {
1345 pid_t pid;
1346 int fds[2];
1347 const char *gzip_flags;
1348
1349 if (pipe(fds) < 0)
1350 err(1, "could not pipe");
1351 pid = fork();
1352 if (pid < 0)
1353 err(1, "could not fork");
1354
1355 /* parent */
1356 if (pid) {
1357 switch (act) {
1358 case ARCHIVE:
1359 dup2(fds[1], fd);
1360 break;
1361 case LIST:
1362 case EXTRACT:
1363 dup2(fds[0], fd);
1364 break;
1365 default:
1366 errx(1, "ar_start_gzip: impossible");
1367 }
1368 close(fds[0]);
1369 close(fds[1]);
1370 } else {
1371 switch (act) {
1372 case ARCHIVE:
1373 dup2(fds[0], STDIN_FILENO);
1374 dup2(fd, STDOUT_FILENO);
1375 gzip_flags = "-c";
1376 break;
1377 case LIST:
1378 case EXTRACT:
1379 dup2(fds[1], STDOUT_FILENO);
1380 dup2(fd, STDIN_FILENO);
1381 gzip_flags = "-dc";
1382 break;
1383 default:
1384 errx(1, "ar_start_gzip: impossible");
1385 }
1386 close(fds[0]);
1387 close(fds[1]);
1388 if (execlp(gzip_program, gzip_program, gzip_flags, NULL) < 0)
1389 err(1, "could not exec");
1390 /* NOTREACHED */
1391 }
1392 }
1393
1394 static const char *
1395 timefmt(buf, size, sz, tm)
1396 char *buf;
1397 size_t size;
1398 off_t sz;
1399 time_t tm;
1400 {
1401 (void)snprintf(buf, size, "%lu secs (" OFFT_F " bytes/sec)",
1402 (unsigned long)tm, (OFFT_T)(sz / tm));
1403 return buf;
1404 }
1405
1406 static const char *
1407 sizefmt(buf, size, sz)
1408 char *buf;
1409 size_t size;
1410 off_t sz;
1411 {
1412 (void)snprintf(buf, size, OFFT_F " bytes", (OFFT_T)sz);
1413 return buf;
1414 }
1415
1416 void
1417 ar_summary(int n)
1418 {
1419 time_t secs;
1420 int len;
1421 char buf[MAXPATHLEN];
1422 char tbuf[MAXPATHLEN/4];
1423 char s1buf[MAXPATHLEN/8];
1424 char s2buf[MAXPATHLEN/8];
1425 FILE *outf;
1426
1427 if (act == LIST)
1428 outf = stdout;
1429 else
1430 outf = stderr;
1431
1432 /*
1433 * If we are called from a signal (n != 0), use snprintf(3) so that we
1434 * don't reenter stdio(3).
1435 */
1436 (void)time(&secs);
1437 if ((secs -= starttime) == 0)
1438 secs = 1;
1439
1440 /*
1441 * If we have not determined the format yet, we just say how many bytes
1442 * we have skipped over looking for a header to id. there is no way we
1443 * could have written anything yet.
1444 */
1445 if (frmt == NULL) {
1446 len = snprintf(buf, sizeof(buf),
1447 "unknown format, %s skipped in %s\n",
1448 sizefmt(s1buf, sizeof(s1buf), rdcnt),
1449 timefmt(tbuf, sizeof(tbuf), rdcnt, secs));
1450 if (n == 0)
1451 (void)fprintf(outf, "%s: %s", argv0, buf);
1452 else
1453 (void)write(STDERR_FILENO, buf, len);
1454 return;
1455 }
1456
1457
1458 if (n != 0) {
1459 len = snprintf(buf, sizeof(buf), "Working on `%s' (%s)\n",
1460 archd.name, sizefmt(s1buf, sizeof(s1buf), archd.sb.st_size));
1461 (void)write(STDERR_FILENO, buf, len);
1462 }
1463
1464
1465 len = snprintf(buf, sizeof(buf),
1466 "%s vol %d, %lu files, %s read, %s written in %s\n",
1467 frmt->name, arvol-1, (unsigned long)flcnt,
1468 sizefmt(s1buf, sizeof(s1buf), rdcnt),
1469 sizefmt(s2buf, sizeof(s2buf), wrcnt),
1470 timefmt(tbuf, sizeof(tbuf), rdcnt + wrcnt, secs));
1471 if (n == 0)
1472 (void)fprintf(outf, "%s: %s", argv0, buf);
1473 else
1474 (void)write(STDERR_FILENO, buf, strlen(buf));
1475 }
1476
1477 /*
1478 * ar_dochdir(name)
1479 * change directory to name, and remember where we came from and
1480 * where we change to (for ar_open).
1481 *
1482 * Maybe we could try to be smart and only do the actual chdir
1483 * when necessary to write a file read from the archive, but this
1484 * is not easy to get right given the pax code structure.
1485 *
1486 * Be sure to not leak descriptors!
1487 *
1488 * We are called N * M times when extracting, and N times when
1489 * writing archives, where
1490 * N: number of -C options
1491 * M: number of files in archive
1492 *
1493 * Returns 0 if all went well, else -1.
1494 */
1495
1496 int
1497 ar_dochdir(char *name)
1498 {
1499 if (curdirfd == -1) {
1500 /* first time. remember where we came from */
1501 curdirfd = open(".", O_RDONLY);
1502 if (curdirfd < 0) {
1503 syswarn(0, errno, "failed to open directory .");
1504 return (-1);
1505 }
1506 } else /* XXX if (*name != '/') XXX */ {
1507 /*
1508 * relative chdir. Make sure to get the same directory
1509 * each time by fchdir-ing back first.
1510 */
1511 fchdir(curdirfd);
1512 }
1513
1514 if (minusCfd != -1) {
1515 /* don't leak descriptors */
1516 close(minusCfd);
1517 minusCfd = -1;
1518 }
1519
1520 minusCfd = open(name, O_RDONLY);
1521 if (minusCfd < 0) {
1522 syswarn(0, errno, "failed to open directory %s", name);
1523 return (-1);
1524 }
1525
1526 fchdir(minusCfd);
1527 return (0);
1528 }
1529