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