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