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