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