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