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