Home | History | Annotate | Line # | Download | only in pax
ar_io.c revision 1.25
      1 /*	$NetBSD: ar_io.c,v 1.25 2002/10/12 19:21:12 thorpej 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.25 2002/10/12 19:21:12 thorpej 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 (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 	} else if (strcmp(NM_TAR, argv0) != 0) {
    437 		(void)fprintf(listf,
    438 		    "%s: %s vol %d, %lu files, " OFFT_F " bytes read, "
    439 		    OFFT_F " bytes written.\n",
    440 		    argv0, frmt->name, arvol-1, flcnt, rdcnt, wrcnt);
    441 	}
    442 
    443 	ar_summary(0);
    444 
    445 	(void)fflush(listf);
    446 	flcnt = 0;
    447 }
    448 
    449 /*
    450  * ar_drain()
    451  *	drain any archive format independent padding from an archive read
    452  *	from a socket or a pipe. This is to prevent the process on the
    453  *	other side of the pipe from getting a SIGPIPE (pax will stop
    454  *	reading an archive once a format dependent trailer is detected).
    455  */
    456 void
    457 ar_drain(void)
    458 {
    459 	int res;
    460 	char drbuf[MAXBLK];
    461 
    462 	/*
    463 	 * we only drain from a pipe/socket. Other devices can be closed
    464 	 * without reading up to end of file. We sure hope that pipe is closed
    465 	 * on the other side so we will get an EOF.
    466 	 */
    467 	if ((artyp != ISPIPE) || (lstrval <= 0))
    468 		return;
    469 
    470 	/*
    471 	 * keep reading until pipe is drained
    472 	 */
    473 #ifdef SUPPORT_RMT
    474 	if (artyp == ISRMT) {
    475 		while ((res = rmtread_with_restart(arfd,
    476 						   drbuf, sizeof(drbuf))) > 0)
    477 			continue;
    478 	} else {
    479 #endif /* SUPPORT_RMT */
    480 		while ((res = read_with_restart(arfd,
    481 						drbuf, sizeof(drbuf))) > 0)
    482 			continue;
    483 #ifdef SUPPORT_RMT
    484 	}
    485 #endif /* SUPPORT_RMT */
    486 	lstrval = res;
    487 }
    488 
    489 /*
    490  * ar_set_wr()
    491  *	Set up device right before switching from read to write in an append.
    492  *	device dependent code (if required) to do this should be added here.
    493  *	For all archive devices we are already positioned at the place we want
    494  *	to start writing when this routine is called.
    495  * Return:
    496  *	0 if all ready to write, -1 otherwise
    497  */
    498 
    499 int
    500 ar_set_wr(void)
    501 {
    502 	off_t cpos;
    503 
    504 	/*
    505 	 * we must make sure the trailer is rewritten on append, ar_next()
    506 	 * will stop us if the archive containing the trailer was not written
    507 	 */
    508 	wr_trail = 0;
    509 
    510 	/*
    511 	 * Add any device dependent code as required here
    512 	 */
    513 	if (artyp != ISREG)
    514 		return(0);
    515 	/*
    516 	 * Ok we have an archive in a regular file. If we were rewriting a
    517 	 * file, we must get rid of all the stuff after the current offset
    518 	 * (it was not written by pax).
    519 	 */
    520 	if (((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0) ||
    521 	    (ftruncate(arfd, cpos) < 0)) {
    522 		syswarn(1, errno, "Unable to truncate archive file");
    523 		return(-1);
    524 	}
    525 	return(0);
    526 }
    527 
    528 /*
    529  * ar_app_ok()
    530  *	check if the last volume in the archive allows appends. We cannot check
    531  *	this until we are ready to write since there is no spec that says all
    532  *	volumes in a single archive have to be of the same type...
    533  * Return:
    534  *	0 if we can append, -1 otherwise.
    535  */
    536 
    537 int
    538 ar_app_ok(void)
    539 {
    540 	if (artyp == ISPIPE) {
    541 		tty_warn(1,
    542 		    "Cannot append to an archive obtained from a pipe.");
    543 		return(-1);
    544 	}
    545 
    546 	if (!invld_rec)
    547 		return(0);
    548 	tty_warn(1,
    549 	    "Cannot append, device record size %d does not support %s spec",
    550 	    rdblksz, argv0);
    551 	return(-1);
    552 }
    553 
    554 #ifdef SYS_NO_RESTART
    555 /*
    556  * read_with_restart()
    557  *	Equivalent to read() but does retry on signals.
    558  *	This function is not needed on 4.2BSD and later.
    559  * Return:
    560  *	Number of bytes written.  -1 indicates an error.
    561  */
    562 
    563 int
    564 read_with_restart(int fd, void *buf, int bsz)
    565 {
    566 	int r;
    567 
    568 	while (((r = read(fd, buf, bsz)) < 0) && errno == EINTR)
    569 		continue;
    570 
    571 	return(r);
    572 }
    573 
    574 /*
    575  * rmtread_with_restart()
    576  *	Equivalent to rmtread() but does retry on signals.
    577  *	This function is not needed on 4.2BSD and later.
    578  * Return:
    579  *	Number of bytes written.  -1 indicates an error.
    580  */
    581 static int
    582 rmtread_with_restart(int fd, void *buf, int bsz)
    583 {
    584 	int r;
    585 
    586 	while (((r = rmtread(fd, buf, bsz)) < 0) && errno == EINTR)
    587 		continue;
    588 
    589 	return(r);
    590 }
    591 #endif
    592 
    593 /*
    594  * xread()
    595  *	Equivalent to read() but does retry on partial read, which may occur
    596  *	on signals.
    597  * Return:
    598  *	Number of bytes read.  0 for end of file, -1 for an error.
    599  */
    600 
    601 int
    602 xread(int fd, void *buf, int bsz)
    603 {
    604 	char *b = buf;
    605 	int nread = 0;
    606 	int r;
    607 
    608 	do {
    609 #ifdef SUPPORT_RMT
    610 		if ((r = rmtread_with_restart(fd, b, bsz)) <= 0)
    611 			break;
    612 #else
    613 		if ((r = read_with_restart(fd, b, bsz)) <= 0)
    614 			break;
    615 #endif /* SUPPORT_RMT */
    616 		b += r;
    617 		bsz -= r;
    618 		nread += r;
    619 	} while (bsz > 0);
    620 
    621 	return(nread ? nread : r);
    622 }
    623 
    624 #ifdef SYS_NO_RESTART
    625 /*
    626  * write_with_restart()
    627  *	Equivalent to write() but does retry on signals.
    628  *	This function is not needed on 4.2BSD and later.
    629  * Return:
    630  *	Number of bytes written.  -1 indicates an error.
    631  */
    632 
    633 int
    634 write_with_restart(int fd, void *buf, int bsz)
    635 {
    636 	int r;
    637 
    638 	while (((r = write(fd, buf, bsz)) < 0) && errno == EINTR)
    639 		;
    640 
    641 	return(r);
    642 }
    643 
    644 /*
    645  * rmtwrite_with_restart()
    646  *	Equivalent to write() but does retry on signals.
    647  *	This function is not needed on 4.2BSD and later.
    648  * Return:
    649  *	Number of bytes written.  -1 indicates an error.
    650  */
    651 
    652 static int
    653 rmtwrite_with_restart(int fd, void *buf, int bsz)
    654 {
    655 	int r;
    656 
    657 	while (((r = rmtwrite(fd, buf, bsz)) < 0) && errno == EINTR)
    658 		;
    659 
    660 	return(r);
    661 }
    662 #endif
    663 
    664 /*
    665  * xwrite()
    666  *	Equivalent to write() but does retry on partial write, which may occur
    667  *	on signals.
    668  * Return:
    669  *	Number of bytes written.  -1 indicates an error.
    670  */
    671 
    672 int
    673 xwrite(int fd, void *buf, int bsz)
    674 {
    675 	char *b = buf;
    676 	int written = 0;
    677 	int r;
    678 
    679 	do {
    680 #ifdef SUPPORT_RMT
    681 		if ((r = rmtwrite_with_restart(fd, b, bsz)) <= 0)
    682 			break;
    683 #else
    684 		if ((r = write_with_restart(fd, b, bsz)) <= 0)
    685 			break;
    686 #endif /* SUPPORT_RMT */
    687 		b += r;
    688 		bsz -= r;
    689 		written += r;
    690 	} while (bsz > 0);
    691 
    692 	return(written ? written : r);
    693 }
    694 
    695 /*
    696  * ar_read()
    697  *	read up to a specified number of bytes from the archive into the
    698  *	supplied buffer. When dealing with tapes we may not always be able to
    699  *	read what we want.
    700  * Return:
    701  *	Number of bytes in buffer. 0 for end of file, -1 for a read error.
    702  */
    703 
    704 int
    705 ar_read(char *buf, int cnt)
    706 {
    707 	int res = 0;
    708 
    709 	/*
    710 	 * if last i/o was in error, no more reads until reset or new volume
    711 	 */
    712 	if (lstrval <= 0)
    713 		return(lstrval);
    714 
    715 	/*
    716 	 * how we read must be based on device type
    717 	 */
    718 	switch (artyp) {
    719 #ifdef SUPPORT_RMT
    720 	case ISRMT:
    721 		if ((res = rmtread_with_restart(arfd, buf, cnt)) > 0) {
    722 			io_ok = 1;
    723 			return res;
    724 		}
    725 		break;
    726 #endif /* SUPPORT_RMT */
    727 	case ISTAPE:
    728 		if ((res = read_with_restart(arfd, buf, cnt)) > 0) {
    729 			/*
    730 			 * CAUTION: tape systems may not always return the same
    731 			 * sized records so we leave blksz == MAXBLK. The
    732 			 * physical record size that a tape drive supports is
    733 			 * very hard to determine in a uniform and portable
    734 			 * manner.
    735 			 */
    736 			io_ok = 1;
    737 			if (res != rdblksz) {
    738 				/*
    739 				 * Record size changed. If this is happens on
    740 				 * any record after the first, we probably have
    741 				 * a tape drive which has a fixed record size
    742 				 * we are getting multiple records in a single
    743 				 * read). Watch out for record blocking that
    744 				 * violates pax spec (must be a multiple of
    745 				 * BLKMULT).
    746 				 */
    747 				rdblksz = res;
    748 				if (rdblksz % BLKMULT)
    749 					invld_rec = 1;
    750 			}
    751 			return(res);
    752 		}
    753 		break;
    754 	case ISREG:
    755 	case ISBLK:
    756 	case ISCHR:
    757 	case ISPIPE:
    758 	default:
    759 		/*
    760 		 * Files are so easy to deal with. These other things cannot
    761 		 * be trusted at all. So when we are dealing with character
    762 		 * devices and pipes we just take what they have ready for us
    763 		 * and return. Trying to do anything else with them runs the
    764 		 * risk of failure.
    765 		 */
    766 		if ((res = read_with_restart(arfd, buf, cnt)) > 0) {
    767 			io_ok = 1;
    768 			return(res);
    769 		}
    770 		break;
    771 	}
    772 
    773 	/*
    774 	 * We are in trouble at this point, something is broken...
    775 	 */
    776 	lstrval = res;
    777 	if (res < 0)
    778 		syswarn(1, errno, "Failed read on archive volume %d", arvol);
    779 	else if (!is_oldgnutar)
    780 		tty_warn(0, "End of archive volume %d reached", arvol);
    781 	return(res);
    782 }
    783 
    784 /*
    785  * ar_write()
    786  *	Write a specified number of bytes in supplied buffer to the archive
    787  *	device so it appears as a single "block". Deals with errors and tries
    788  *	to recover when faced with short writes.
    789  * Return:
    790  *	Number of bytes written. 0 indicates end of volume reached and with no
    791  *	flaws (as best that can be detected). A -1 indicates an unrecoverable
    792  *	error in the archive occurred.
    793  */
    794 
    795 int
    796 ar_write(char *buf, int bsz)
    797 {
    798 	int res;
    799 	off_t cpos;
    800 
    801 	/*
    802 	 * do not allow pax to create a "bad" archive. Once a write fails on
    803 	 * an archive volume prevent further writes to it.
    804 	 */
    805 	if (lstrval <= 0)
    806 		return(lstrval);
    807 
    808 	if ((res = xwrite(arfd, buf, bsz)) == bsz) {
    809 		wr_trail = 1;
    810 		io_ok = 1;
    811 		return(bsz);
    812 	}
    813 	/*
    814 	 * write broke, see what we can do with it. We try to send any partial
    815 	 * writes that may violate pax spec to the next archive volume.
    816 	 */
    817 	if (res < 0)
    818 		lstrval = res;
    819 	else
    820 		lstrval = 0;
    821 
    822 	switch (artyp) {
    823 	case ISREG:
    824 		if ((res > 0) && (res % BLKMULT)) {
    825 			/*
    826 			 * try to fix up partial writes which are not BLKMULT
    827 			 * in size by forcing the runt record to next archive
    828 			 * volume
    829 			 */
    830 			if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0)
    831 				break;
    832 			cpos -= (off_t)res;
    833 			if (ftruncate(arfd, cpos) < 0)
    834 				break;
    835 			res = lstrval = 0;
    836 			break;
    837 		}
    838 		if (res >= 0)
    839 			break;
    840 		/*
    841 		 * if file is out of space, handle it like a return of 0
    842 		 */
    843 		if ((errno == ENOSPC) || (errno == EFBIG) || (errno == EDQUOT))
    844 			res = lstrval = 0;
    845 		break;
    846 	case ISTAPE:
    847 	case ISCHR:
    848 	case ISBLK:
    849 #ifdef SUPPORT_RMT
    850 	case ISRMT:
    851 #endif /* SUPPORT_RMT */
    852 		if (res >= 0)
    853 			break;
    854 		if (errno == EACCES) {
    855 			tty_warn(0,
    856 			    "Write failed, archive is write protected.");
    857 			res = lstrval = 0;
    858 			return(0);
    859 		}
    860 		/*
    861 		 * see if we reached the end of media, if so force a change to
    862 		 * the next volume
    863 		 */
    864 		if ((errno == ENOSPC) || (errno == EIO) || (errno == ENXIO))
    865 			res = lstrval = 0;
    866 		break;
    867 	case ISPIPE:
    868 	default:
    869 		/*
    870 		 * we cannot fix errors to these devices
    871 		 */
    872 		break;
    873 	}
    874 
    875 	/*
    876 	 * Better tell the user the bad news...
    877 	 * if this is a block aligned archive format, we may have a bad archive
    878 	 * if the format wants the header to start at a BLKMULT boundary. While
    879 	 * we can deal with the mis-aligned data, it violates spec and other
    880 	 * archive readers will likely fail. if the format is not block
    881 	 * aligned, the user may be lucky (and the archive is ok).
    882 	 */
    883 	if (res >= 0) {
    884 		if (res > 0)
    885 			wr_trail = 1;
    886 		io_ok = 1;
    887 	}
    888 
    889 	/*
    890 	 * If we were trying to rewrite the trailer and it didn't work, we
    891 	 * must quit right away.
    892 	 */
    893 	if (!wr_trail && (res <= 0)) {
    894 		tty_warn(1,
    895 		    "Unable to append, trailer re-write failed. Quitting.");
    896 		return(res);
    897 	}
    898 
    899 	if (res == 0)
    900 		tty_warn(0, "End of archive volume %d reached", arvol);
    901 	else if (res < 0)
    902 		syswarn(1, errno, "Failed write to archive volume: %d", arvol);
    903 	else if (!frmt->blkalgn || ((res % frmt->blkalgn) == 0))
    904 		tty_warn(0,
    905 		    "WARNING: partial archive write. Archive MAY BE FLAWED");
    906 	else
    907 		tty_warn(1,"WARNING: partial archive write. Archive IS FLAWED");
    908 	return(res);
    909 }
    910 
    911 /*
    912  * ar_rdsync()
    913  *	Try to move past a bad spot on a flawed archive as needed to continue
    914  *	I/O. Clears error flags to allow I/O to continue.
    915  * Return:
    916  *	0 when ok to try i/o again, -1 otherwise.
    917  */
    918 
    919 int
    920 ar_rdsync(void)
    921 {
    922 	long fsbz;
    923 	off_t cpos;
    924 	off_t mpos;
    925 	struct mtop mb;
    926 
    927 	/*
    928 	 * Fail resync attempts at user request (done) or this is going to be
    929 	 * an update/append to a existing archive. if last i/o hit media end,
    930 	 * we need to go to the next volume not try a resync
    931 	 */
    932 	if ((done > 0) || (lstrval == 0))
    933 		return(-1);
    934 
    935 	if ((act == APPND) || (act == ARCHIVE)) {
    936 		tty_warn(1, "Cannot allow updates to an archive with flaws.");
    937 		return(-1);
    938 	}
    939 	if (io_ok)
    940 		did_io = 1;
    941 
    942 	switch(artyp) {
    943 #ifdef SUPPORT_RMT
    944 	case ISRMT:
    945 #endif /* SUPPORT_RMT */
    946 	case ISTAPE:
    947 		/*
    948 		 * if the last i/o was a successful data transfer, we assume
    949 		 * the fault is just a bad record on the tape that we are now
    950 		 * past. If we did not get any data since the last resync try
    951 		 * to move the tape forward one PHYSICAL record past any
    952 		 * damaged tape section. Some tape drives are stubborn and need
    953 		 * to be pushed.
    954 		 */
    955 		if (io_ok) {
    956 			io_ok = 0;
    957 			lstrval = 1;
    958 			break;
    959 		}
    960 		mb.mt_op = MTFSR;
    961 		mb.mt_count = 1;
    962 #ifdef SUPPORT_RMT
    963 		if (artyp == ISRMT) {
    964 			if (rmtioctl(arfd, MTIOCTOP, &mb) < 0)
    965 				break;
    966 		} else {
    967 #endif /* SUPPORT_RMT */
    968 			if (ioctl(arfd, MTIOCTOP, &mb) < 0)
    969 				break;
    970 #ifdef SUPPORT_RMT
    971 		}
    972 #endif /* SUPPORT_RMT */
    973 		lstrval = 1;
    974 		break;
    975 	case ISREG:
    976 	case ISCHR:
    977 	case ISBLK:
    978 		/*
    979 		 * try to step over the bad part of the device.
    980 		 */
    981 		io_ok = 0;
    982 		if (((fsbz = arsb.st_blksize) <= 0) || (artyp != ISREG))
    983 			fsbz = BLKMULT;
    984 		if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0)
    985 			break;
    986 		mpos = fsbz - (cpos % (off_t)fsbz);
    987 		if (lseek(arfd, mpos, SEEK_CUR) < 0)
    988 			break;
    989 		lstrval = 1;
    990 		break;
    991 	case ISPIPE:
    992 	default:
    993 		/*
    994 		 * cannot recover on these archive device types
    995 		 */
    996 		io_ok = 0;
    997 		break;
    998 	}
    999 	if (lstrval <= 0) {
   1000 		tty_warn(1, "Unable to recover from an archive read failure.");
   1001 		return(-1);
   1002 	}
   1003 	tty_warn(0, "Attempting to recover from an archive read failure.");
   1004 	return(0);
   1005 }
   1006 
   1007 /*
   1008  * ar_fow()
   1009  *	Move the I/O position within the archive forward the specified number of
   1010  *	bytes as supported by the device. If we cannot move the requested
   1011  *	number of bytes, return the actual number of bytes moved in skipped.
   1012  * Return:
   1013  *	0 if moved the requested distance, -1 on complete failure, 1 on
   1014  *	partial move (the amount moved is in skipped)
   1015  */
   1016 
   1017 int
   1018 ar_fow(off_t sksz, off_t *skipped)
   1019 {
   1020 	off_t cpos;
   1021 	off_t mpos;
   1022 
   1023 	*skipped = 0;
   1024 	if (sksz <= 0)
   1025 		return(0);
   1026 
   1027 	/*
   1028 	 * we cannot move forward at EOF or error
   1029 	 */
   1030 	if (lstrval <= 0)
   1031 		return(lstrval);
   1032 
   1033 	/*
   1034 	 * Safer to read forward on devices where it is hard to find the end of
   1035 	 * the media without reading to it. With tapes we cannot be sure of the
   1036 	 * number of physical blocks to skip (we do not know physical block
   1037 	 * size at this point), so we must only read forward on tapes!
   1038 	 */
   1039 	if (artyp == ISTAPE || artyp == ISPIPE
   1040 #ifdef SUPPORT_RMT
   1041 	    || artyp == ISRMT
   1042 #endif /* SUPPORT_RMT */
   1043 	    )
   1044 		return(0);
   1045 
   1046 	/*
   1047 	 * figure out where we are in the archive
   1048 	 */
   1049 	if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) >= 0) {
   1050 		/*
   1051 		 * we can be asked to move farther than there are bytes in this
   1052 		 * volume, if so, just go to file end and let normal buf_fill()
   1053 		 * deal with the end of file (it will go to next volume by
   1054 		 * itself)
   1055 		 */
   1056 		mpos = cpos + sksz;
   1057 		if (artyp == ISREG && mpos > arsb.st_size)
   1058 			mpos = arsb.st_size;
   1059 		if ((mpos = lseek(arfd, mpos, SEEK_SET)) >= 0) {
   1060 			*skipped = mpos - cpos;
   1061 			return(0);
   1062 		}
   1063 	} else {
   1064 		if (artyp != ISREG)
   1065 			return(0);		/* non-seekable device */
   1066 	}
   1067 	syswarn(1, errno, "Forward positioning operation on archive failed");
   1068 	lstrval = -1;
   1069 	return(-1);
   1070 }
   1071 
   1072 /*
   1073  * ar_rev()
   1074  *	move the i/o position within the archive backwards the specified byte
   1075  *	count as supported by the device. With tapes drives we RESET rdblksz to
   1076  *	the PHYSICAL blocksize.
   1077  *	NOTE: We should only be called to move backwards so we can rewrite the
   1078  *	last records (the trailer) of an archive (APPEND).
   1079  * Return:
   1080  *	0 if moved the requested distance, -1 on complete failure
   1081  */
   1082 
   1083 int
   1084 ar_rev(off_t sksz)
   1085 {
   1086 	off_t cpos;
   1087 	struct mtop mb;
   1088 	int phyblk;
   1089 
   1090 	/*
   1091 	 * make sure we do not have try to reverse on a flawed archive
   1092 	 */
   1093 	if (lstrval < 0)
   1094 		return(lstrval);
   1095 
   1096 	switch(artyp) {
   1097 	case ISPIPE:
   1098 		if (sksz <= 0)
   1099 			break;
   1100 		/*
   1101 		 * cannot go backwards on these critters
   1102 		 */
   1103 		tty_warn(1, "Reverse positioning on pipes is not supported.");
   1104 		lstrval = -1;
   1105 		return(-1);
   1106 	case ISREG:
   1107 	case ISBLK:
   1108 	case ISCHR:
   1109 	default:
   1110 		if (sksz <= 0)
   1111 			break;
   1112 
   1113 		/*
   1114 		 * For things other than files, backwards movement has a very
   1115 		 * high probability of failure as we really do not know the
   1116 		 * true attributes of the device we are talking to (the device
   1117 		 * may not even have the ability to lseek() in any direction).
   1118 		 * First we figure out where we are in the archive.
   1119 		 */
   1120 		if ((cpos = lseek(arfd, (off_t)0L, SEEK_CUR)) < 0) {
   1121 			syswarn(1, errno,
   1122 			   "Unable to obtain current archive byte offset");
   1123 			lstrval = -1;
   1124 			return(-1);
   1125 		}
   1126 
   1127 		/*
   1128 		 * we may try to go backwards past the start when the archive
   1129 		 * is only a single record. If this hapens and we are on a
   1130 		 * multi volume archive, we need to go to the end of the
   1131 		 * previous volume and continue our movement backwards from
   1132 		 * there.
   1133 		 */
   1134 		if ((cpos -= sksz) < (off_t)0L) {
   1135 			if (arvol > 1) {
   1136 				/*
   1137 				 * this should never happen
   1138 				 */
   1139 				tty_warn(1,
   1140 				    "Reverse position on previous volume.");
   1141 				lstrval = -1;
   1142 				return(-1);
   1143 			}
   1144 			cpos = (off_t)0L;
   1145 		}
   1146 		if (lseek(arfd, cpos, SEEK_SET) < 0) {
   1147 			syswarn(1, errno, "Unable to seek archive backwards");
   1148 			lstrval = -1;
   1149 			return(-1);
   1150 		}
   1151 		break;
   1152 	case ISTAPE:
   1153 #ifdef SUPPORT_RMT
   1154 	case ISRMT:
   1155 #endif /* SUPPORT_RMT */
   1156 		/*
   1157 		 * Calculate and move the proper number of PHYSICAL tape
   1158 		 * blocks. If the sksz is not an even multiple of the physical
   1159 		 * tape size, we cannot do the move (this should never happen).
   1160 		 * (We also cannot handler trailers spread over two vols).
   1161 		 * get_phys() also makes sure we are in front of the filemark.
   1162 		 */
   1163 		if ((phyblk = get_phys()) <= 0) {
   1164 			lstrval = -1;
   1165 			return(-1);
   1166 		}
   1167 
   1168 		/*
   1169 		 * make sure future tape reads only go by physical tape block
   1170 		 * size (set rdblksz to the real size).
   1171 		 */
   1172 		rdblksz = phyblk;
   1173 
   1174 		/*
   1175 		 * if no movement is required, just return (we must be after
   1176 		 * get_phys() so the physical blocksize is properly set)
   1177 		 */
   1178 		if (sksz <= 0)
   1179 			break;
   1180 
   1181 		/*
   1182 		 * ok we have to move. Make sure the tape drive can do it.
   1183 		 */
   1184 		if (sksz % phyblk) {
   1185 			tty_warn(1,
   1186 			    "Tape drive unable to backspace requested amount");
   1187 			lstrval = -1;
   1188 			return(-1);
   1189 		}
   1190 
   1191 		/*
   1192 		 * move backwards the requested number of bytes
   1193 		 */
   1194 		mb.mt_op = MTBSR;
   1195 		mb.mt_count = sksz/phyblk;
   1196 		if (
   1197 #ifdef SUPPORT_RMT
   1198 		    rmtioctl(arfd, MTIOCTOP, &mb)
   1199 #else
   1200 		    ioctl(arfd, MTIOCTOP, &mb)
   1201 #endif /* SUPPORT_RMT */
   1202 		    < 0) {
   1203 			syswarn(1,errno, "Unable to backspace tape %ld blocks.",
   1204 			    (long) mb.mt_count);
   1205 			lstrval = -1;
   1206 			return(-1);
   1207 		}
   1208 		break;
   1209 	}
   1210 	lstrval = 1;
   1211 	return(0);
   1212 }
   1213 
   1214 /*
   1215  * get_phys()
   1216  *	Determine the physical block size on a tape drive. We need the physical
   1217  *	block size so we know how many bytes we skip over when we move with
   1218  *	mtio commands. We also make sure we are BEFORE THE TAPE FILEMARK when
   1219  *	return.
   1220  *	This is one really SLOW routine...
   1221  * Return:
   1222  *	physical block size if ok (ok > 0), -1 otherwise
   1223  */
   1224 
   1225 static int
   1226 get_phys(void)
   1227 {
   1228 	int padsz = 0;
   1229 	int res;
   1230 	int phyblk;
   1231 	struct mtop mb;
   1232 	char scbuf[MAXBLK];
   1233 
   1234 	/*
   1235 	 * move to the file mark, and then back up one record and read it.
   1236 	 * this should tell us the physical record size the tape is using.
   1237 	 */
   1238 	if (lstrval == 1) {
   1239 		/*
   1240 		 * we know we are at file mark when we get back a 0 from
   1241 		 * read()
   1242 		 */
   1243 #ifdef SUPPORT_RMT
   1244 		while ((res = rmtread_with_restart(arfd,
   1245 						   scbuf, sizeof(scbuf))) > 0)
   1246 #else
   1247 		while ((res = read_with_restart(arfd,
   1248 						scbuf, sizeof(scbuf))) > 0)
   1249 #endif /* SUPPORT_RMT */
   1250 			padsz += res;
   1251 		if (res < 0) {
   1252 			syswarn(1, errno, "Unable to locate tape filemark.");
   1253 			return(-1);
   1254 		}
   1255 	}
   1256 
   1257 	/*
   1258 	 * move backwards over the file mark so we are at the end of the
   1259 	 * last record.
   1260 	 */
   1261 	mb.mt_op = MTBSF;
   1262 	mb.mt_count = 1;
   1263 	if (
   1264 #ifdef SUPPORT_RMT
   1265 	    rmtioctl(arfd, MTIOCTOP, &mb)
   1266 #else
   1267 	    ioctl(arfd, MTIOCTOP, &mb)
   1268 #endif /* SUPPORT_RMT */
   1269 	    < 0) {
   1270 		syswarn(1, errno, "Unable to backspace over tape filemark.");
   1271 		return(-1);
   1272 	}
   1273 
   1274 	/*
   1275 	 * move backwards so we are in front of the last record and read it to
   1276 	 * get physical tape blocksize.
   1277 	 */
   1278 	mb.mt_op = MTBSR;
   1279 	mb.mt_count = 1;
   1280 	if (
   1281 #ifdef SUPPORT_RMT
   1282 	    rmtioctl(arfd, MTIOCTOP, &mb)
   1283 #else
   1284 	    ioctl(arfd, MTIOCTOP, &mb)
   1285 #endif /* SUPPORT_RMT */
   1286 	    < 0) {
   1287 		syswarn(1, errno, "Unable to backspace over last tape block.");
   1288 		return(-1);
   1289 	}
   1290 	if ((phyblk =
   1291 #ifdef SUPPORT_RMT
   1292 	     rmtread_with_restart(arfd, scbuf, sizeof(scbuf))
   1293 #else
   1294 	     read_with_restart(arfd, scbuf, sizeof(scbuf))
   1295 #endif /* SUPPORT_RMT */
   1296 	    ) <= 0) {
   1297 		syswarn(1, errno, "Cannot determine archive tape blocksize.");
   1298 		return(-1);
   1299 	}
   1300 
   1301 	/*
   1302 	 * read forward to the file mark, then back up in front of the filemark
   1303 	 * (this is a bit paranoid, but should be safe to do).
   1304 	 */
   1305 	while ((res =
   1306 #ifdef SUPPORT_RMT
   1307 		rmtread_with_restart(arfd, scbuf, sizeof(scbuf))
   1308 #else
   1309 		read_with_restart(arfd, scbuf, sizeof(scbuf))
   1310 #endif /* SUPPORT_RMT */
   1311 	       ) > 0)
   1312 		;
   1313 	if (res < 0) {
   1314 		syswarn(1, errno, "Unable to locate tape filemark.");
   1315 		return(-1);
   1316 	}
   1317 	mb.mt_op = MTBSF;
   1318 	mb.mt_count = 1;
   1319 	if (
   1320 #ifdef SUPPORT_RMT
   1321 	    rmtioctl(arfd, MTIOCTOP, &mb)
   1322 #else
   1323 	    ioctl(arfd, MTIOCTOP, &mb)
   1324 #endif /* SUPPORT_RMT */
   1325 	    < 0) {
   1326 		syswarn(1, errno, "Unable to backspace over tape filemark.");
   1327 		return(-1);
   1328 	}
   1329 
   1330 	/*
   1331 	 * set lstrval so we know that the filemark has not been seen
   1332 	 */
   1333 	lstrval = 1;
   1334 
   1335 	/*
   1336 	 * return if there was no padding
   1337 	 */
   1338 	if (padsz == 0)
   1339 		return(phyblk);
   1340 
   1341 	/*
   1342 	 * make sure we can move backwards over the padding. (this should
   1343 	 * never fail).
   1344 	 */
   1345 	if (padsz % phyblk) {
   1346 		tty_warn(1, "Tape drive unable to backspace requested amount");
   1347 		return(-1);
   1348 	}
   1349 
   1350 	/*
   1351 	 * move backwards over the padding so the head is where it was when
   1352 	 * we were first called (if required).
   1353 	 */
   1354 	mb.mt_op = MTBSR;
   1355 	mb.mt_count = padsz/phyblk;
   1356 	if (
   1357 #ifdef SUPPORT_RMT
   1358 	    rmtioctl(arfd, MTIOCTOP, &mb)
   1359 #else
   1360 	    ioctl(arfd, MTIOCTOP, &mb)
   1361 #endif /* SUPPORT_RMT */
   1362 	    < 0) {
   1363 		syswarn(1,errno,"Unable to backspace tape over %ld pad blocks",
   1364 		    (long)mb.mt_count);
   1365 		return(-1);
   1366 	}
   1367 	return(phyblk);
   1368 }
   1369 
   1370 /*
   1371  * ar_next()
   1372  *	prompts the user for the next volume in this archive. For some devices
   1373  *	we may allow the media to be changed. Otherwise a new archive is
   1374  *	prompted for. By pax spec, if there is no controlling tty or an eof is
   1375  *	read on tty input, we must quit pax.
   1376  * Return:
   1377  *	0 when ready to continue, -1 when all done
   1378  */
   1379 
   1380 int
   1381 ar_next(void)
   1382 {
   1383 	char buf[PAXPATHLEN+2];
   1384 	static int freeit = 0;
   1385 	sigset_t o_mask;
   1386 
   1387 	/*
   1388 	 * WE MUST CLOSE THE DEVICE. A lot of devices must see last close, (so
   1389 	 * things like writing EOF etc will be done) (Watch out ar_close() can
   1390 	 * also be called via a signal handler, so we must prevent a race.
   1391 	 */
   1392 	if (sigprocmask(SIG_BLOCK, &s_mask, &o_mask) < 0)
   1393 		syswarn(0, errno, "Unable to set signal mask");
   1394 	ar_close();
   1395 	if (sigprocmask(SIG_SETMASK, &o_mask, (sigset_t *)NULL) < 0)
   1396 		syswarn(0, errno, "Unable to restore signal mask");
   1397 
   1398 	if (done || !wr_trail || is_oldgnutar || force_one_volume)
   1399 		return(-1);
   1400 
   1401 	tty_prnt("\nATTENTION! %s archive volume change required.\n", argv0);
   1402 
   1403 	/*
   1404 	 * if i/o is on stdin or stdout, we cannot reopen it (we do not know
   1405 	 * the name), the user will be forced to type it in.
   1406 	 */
   1407 	if (strcmp(arcname, STDO) && strcmp(arcname, STDN) && (artyp != ISREG)
   1408 	    && (artyp != ISPIPE)) {
   1409 		if (artyp == ISTAPE
   1410 #ifdef SUPPORT_RMT
   1411 		    || artyp == ISRMT
   1412 #endif /* SUPPORT_RMT */
   1413 		    ) {
   1414 			tty_prnt("%s ready for archive tape volume: %d\n",
   1415 				arcname, arvol);
   1416 			tty_prnt("Load the NEXT TAPE on the tape drive");
   1417 		} else {
   1418 			tty_prnt("%s ready for archive volume: %d\n",
   1419 				arcname, arvol);
   1420 			tty_prnt("Load the NEXT STORAGE MEDIA (if required)");
   1421 		}
   1422 
   1423 		if ((act == ARCHIVE) || (act == APPND))
   1424 			tty_prnt(" and make sure it is WRITE ENABLED.\n");
   1425 		else
   1426 			tty_prnt("\n");
   1427 
   1428 		for(;;) {
   1429 			tty_prnt("Type \"y\" to continue, \".\" to quit %s,",
   1430 				argv0);
   1431 			tty_prnt(" or \"s\" to switch to new device.\nIf you");
   1432 			tty_prnt(" cannot change storage media, type \"s\"\n");
   1433 			tty_prnt("Is the device ready and online? > ");
   1434 
   1435 			if ((tty_read(buf,sizeof(buf))<0) || !strcmp(buf,".")){
   1436 				done = 1;
   1437 				lstrval = -1;
   1438 				tty_prnt("Quitting %s!\n", argv0);
   1439 				vfpart = 0;
   1440 				return(-1);
   1441 			}
   1442 
   1443 			if ((buf[0] == '\0') || (buf[1] != '\0')) {
   1444 				tty_prnt("%s unknown command, try again\n",buf);
   1445 				continue;
   1446 			}
   1447 
   1448 			switch (buf[0]) {
   1449 			case 'y':
   1450 			case 'Y':
   1451 				/*
   1452 				 * we are to continue with the same device
   1453 				 */
   1454 				if (ar_open(arcname) >= 0)
   1455 					return(0);
   1456 				tty_prnt("Cannot re-open %s, try again\n",
   1457 					arcname);
   1458 				continue;
   1459 			case 's':
   1460 			case 'S':
   1461 				/*
   1462 				 * user wants to open a different device
   1463 				 */
   1464 				tty_prnt("Switching to a different archive\n");
   1465 				break;
   1466 			default:
   1467 				tty_prnt("%s unknown command, try again\n",buf);
   1468 				continue;
   1469 			}
   1470 			break;
   1471 		}
   1472 	} else
   1473 		tty_prnt("Ready for archive volume: %d\n", arvol);
   1474 
   1475 	/*
   1476 	 * have to go to a different archive
   1477 	 */
   1478 	for (;;) {
   1479 		tty_prnt("Input archive name or \".\" to quit %s.\n", argv0);
   1480 		tty_prnt("Archive name > ");
   1481 
   1482 		if ((tty_read(buf, sizeof(buf)) < 0) || !strcmp(buf, ".")) {
   1483 			done = 1;
   1484 			lstrval = -1;
   1485 			tty_prnt("Quitting %s!\n", argv0);
   1486 			vfpart = 0;
   1487 			return(-1);
   1488 		}
   1489 		if (buf[0] == '\0') {
   1490 			tty_prnt("Empty file name, try again\n");
   1491 			continue;
   1492 		}
   1493 		if (!strcmp(buf, "..")) {
   1494 			tty_prnt("Illegal file name: .. try again\n");
   1495 			continue;
   1496 		}
   1497 		if (strlen(buf) > PAXPATHLEN) {
   1498 			tty_prnt("File name too long, try again\n");
   1499 			continue;
   1500 		}
   1501 
   1502 		/*
   1503 		 * try to open new archive
   1504 		 */
   1505 		if (ar_open(buf) >= 0) {
   1506 			if (freeit) {
   1507 				(void)free((char *)arcname);
   1508 				freeit = 0;
   1509 			}
   1510 			if ((arcname = strdup(buf)) == NULL) {
   1511 				done = 1;
   1512 				lstrval = -1;
   1513 				tty_warn(0, "Cannot save archive name.");
   1514 				return(-1);
   1515 			}
   1516 			freeit = 1;
   1517 			break;
   1518 		}
   1519 		tty_prnt("Cannot open %s, try again\n", buf);
   1520 		continue;
   1521 	}
   1522 	return(0);
   1523 }
   1524 
   1525 /*
   1526  * ar_start_gzip()
   1527  * starts the gzip compression/decompression process as a child, using magic
   1528  * to keep the fd the same in the calling function (parent).
   1529  */
   1530 void
   1531 ar_start_gzip(int fd, const char *gzp, int wr)
   1532 {
   1533 	int fds[2];
   1534 	const char *gzip_flags;
   1535 
   1536 	if (pipe(fds) < 0)
   1537 		err(1, "could not pipe");
   1538 	zpid = fork();
   1539 	if (zpid < 0)
   1540 		err(1, "could not fork");
   1541 
   1542 	/* parent */
   1543 	if (zpid) {
   1544 		if (wr)
   1545 			dup2(fds[1], fd);
   1546 		else
   1547 			dup2(fds[0], fd);
   1548 		close(fds[0]);
   1549 		close(fds[1]);
   1550 	} else {
   1551 		if (wr) {
   1552 			dup2(fds[0], STDIN_FILENO);
   1553 			dup2(fd, STDOUT_FILENO);
   1554 			gzip_flags = "-c";
   1555 		} else {
   1556 			dup2(fds[1], STDOUT_FILENO);
   1557 			dup2(fd, STDIN_FILENO);
   1558 			gzip_flags = "-dc";
   1559 		}
   1560 		close(fds[0]);
   1561 		close(fds[1]);
   1562 		if (execlp(gzp, gzp, gzip_flags, NULL) < 0)
   1563 			err(1, "could not exec");
   1564 		/* NOTREACHED */
   1565 	}
   1566 }
   1567 
   1568 static const char *
   1569 timefmt(buf, size, sz, tm)
   1570 	char *buf;
   1571 	size_t size;
   1572 	off_t sz;
   1573 	time_t tm;
   1574 {
   1575 	(void)snprintf(buf, size, "%lu secs (" OFFT_F " bytes/sec)",
   1576 	    (unsigned long)tm, (OFFT_T)(sz / tm));
   1577 	return buf;
   1578 }
   1579 
   1580 static const char *
   1581 sizefmt(buf, size, sz)
   1582 	char *buf;
   1583 	size_t size;
   1584 	off_t sz;
   1585 {
   1586 	(void)snprintf(buf, size, OFFT_F " bytes", (OFFT_T)sz);
   1587 	return buf;
   1588 }
   1589 
   1590 void
   1591 ar_summary(int n)
   1592 {
   1593 	time_t secs;
   1594 	int len;
   1595 	char buf[MAXPATHLEN];
   1596 	char tbuf[MAXPATHLEN/4];
   1597 	char s1buf[MAXPATHLEN/8];
   1598 	char s2buf[MAXPATHLEN/8];
   1599 	FILE *outf;
   1600 
   1601 	if (act == LIST)
   1602 		outf = stdout;
   1603 	else
   1604 		outf = stderr;
   1605 
   1606 	/*
   1607 	 * If we are called from a signal (n != 0), use snprintf(3) so that we
   1608 	 * don't reenter stdio(3).
   1609 	 */
   1610 	(void)time(&secs);
   1611 	if ((secs -= starttime) == 0)
   1612 		secs = 1;
   1613 
   1614 	/*
   1615 	 * If we have not determined the format yet, we just say how many bytes
   1616 	 * we have skipped over looking for a header to id. there is no way we
   1617 	 * could have written anything yet.
   1618 	 */
   1619 	if (frmt == NULL) {
   1620 		len = snprintf(buf, sizeof(buf),
   1621 		    "unknown format, %s skipped in %s\n",
   1622 		    sizefmt(s1buf, sizeof(s1buf), rdcnt),
   1623 		    timefmt(tbuf, sizeof(tbuf), rdcnt, secs));
   1624 		if (n == 0)
   1625 			(void)fprintf(outf, "%s: %s", argv0, buf);
   1626 		else
   1627 			(void)write(STDERR_FILENO, buf, len);
   1628 		return;
   1629 	}
   1630 
   1631 
   1632 	if (n != 0) {
   1633 		len = snprintf(buf, sizeof(buf), "Working on `%s' (%s)\n",
   1634 		    archd.name, sizefmt(s1buf, sizeof(s1buf), archd.sb.st_size));
   1635 		(void)write(STDERR_FILENO, buf, len);
   1636 	}
   1637 
   1638 
   1639 	len = snprintf(buf, sizeof(buf),
   1640 	    "%s vol %d, %lu files, %s read, %s written in %s\n",
   1641 	    frmt->name, arvol-1, (unsigned long)flcnt,
   1642 	    sizefmt(s1buf, sizeof(s1buf), rdcnt),
   1643 	    sizefmt(s2buf, sizeof(s2buf), wrcnt),
   1644 	    timefmt(tbuf, sizeof(tbuf), rdcnt + wrcnt, secs));
   1645 	if (n == 0)
   1646 		(void)fprintf(outf, "%s: %s", argv0, buf);
   1647 	else
   1648 		(void)write(STDERR_FILENO, buf, strlen(buf));
   1649 }
   1650 
   1651 /*
   1652  * ar_dochdir(name)
   1653  *	change directory to name, and remember where we came from and
   1654  *	where we change to (for ar_open).
   1655  *
   1656  *	Maybe we could try to be smart and only do the actual chdir
   1657  *	when necessary to write a file read from the archive, but this
   1658  *	is not easy to get right given the pax code structure.
   1659  *
   1660  *	Be sure to not leak descriptors!
   1661  *
   1662  *	We are called N * M times when extracting, and N times when
   1663  *	writing archives, where
   1664  *	N:	number of -C options
   1665  *	M:	number of files in archive
   1666  *
   1667  * Returns 0 if all went well, else -1.
   1668  */
   1669 
   1670 int
   1671 ar_dochdir(char *name)
   1672 {
   1673 	/* First fchdir() back... */
   1674 	if (fchdir(cwdfd) < 0) {
   1675 		syswarn(1, errno, "Can't fchdir to starting directory");
   1676 		return(-1);
   1677 	}
   1678 	if (chdir(name) < 0) {
   1679 		syswarn(1, errno, "Can't chdir to %s", name);
   1680 		return(-1);
   1681 	}
   1682 	return (0);
   1683 }
   1684