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