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