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