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