xref: /freebsd/bin/pax/buf_subs.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
1 /*-
2  * Copyright (c) 1992 Keith Muller.
3  * Copyright (c) 1992, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Keith Muller of the University of California, San Diego.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 #if 0
36 static char sccsid[] = "@(#)buf_subs.c	8.2 (Berkeley) 4/18/94";
37 #endif
38 #endif /* not lint */
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <errno.h>
45 #include <unistd.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include "pax.h"
50 #include "extern.h"
51 
52 /*
53  * routines which implement archive and file buffering
54  */
55 
56 #define MINFBSZ		512		/* default block size for hole detect */
57 #define MAXFLT		10		/* default media read error limit */
58 
59 /*
60  * Need to change bufmem to dynamic allocation when the upper
61  * limit on blocking size is removed (though that will violate pax spec)
62  * MAXBLK define and tests will also need to be updated.
63  */
64 static char bufmem[MAXBLK+BLKMULT];	/* i/o buffer + pushback id space */
65 static char *buf;			/* normal start of i/o buffer */
66 static char *bufend;			/* end or last char in i/o buffer */
67 static char *bufpt;			/* read/write point in i/o buffer */
68 int blksz = MAXBLK;			/* block input/output size in bytes */
69 int wrblksz;				/* user spec output size in bytes */
70 int maxflt = MAXFLT;			/* MAX consecutive media errors */
71 int rdblksz;				/* first read blksize (tapes only) */
72 off_t wrlimit;				/* # of bytes written per archive vol */
73 off_t wrcnt;				/* # of bytes written on current vol */
74 off_t rdcnt;				/* # of bytes read on current vol */
75 
76 /*
77  * wr_start()
78  *	set up the buffering system to operate in a write mode
79  * Return:
80  *	0 if ok, -1 if the user specified write block size violates pax spec
81  */
82 
83 int
84 wr_start(void)
85 {
86 	buf = &(bufmem[BLKMULT]);
87 	/*
88 	 * Check to make sure the write block size meets pax specs. If the user
89 	 * does not specify a blocksize, we use the format default blocksize.
90 	 * We must be picky on writes, so we do not allow the user to create an
91 	 * archive that might be hard to read elsewhere. If all ok, we then
92 	 * open the first archive volume
93 	 */
94 	if (!wrblksz)
95 		wrblksz = frmt->bsz;
96 	if (wrblksz > MAXBLK) {
97 		paxwarn(1, "Write block size of %d too large, maximum is: %d",
98 			wrblksz, MAXBLK);
99 		return(-1);
100 	}
101 	if (wrblksz % BLKMULT) {
102 		paxwarn(1, "Write block size of %d is not a %d byte multiple",
103 		    wrblksz, BLKMULT);
104 		return(-1);
105 	}
106 	if (wrblksz > MAXBLK_POSIX) {
107 		paxwarn(0, "Write block size of %d larger than POSIX max %d, archive may not be portable",
108 			wrblksz, MAXBLK_POSIX);
109 		return(-1);
110 	}
111 
112 	/*
113 	 * we only allow wrblksz to be used with all archive operations
114 	 */
115 	blksz = rdblksz = wrblksz;
116 	if ((ar_open(arcname) < 0) && (ar_next() < 0))
117 		return(-1);
118 	wrcnt = 0;
119 	bufend = buf + wrblksz;
120 	bufpt = buf;
121 	return(0);
122 }
123 
124 /*
125  * rd_start()
126  *	set up buffering system to read an archive
127  * Return:
128  *	0 if ok, -1 otherwise
129  */
130 
131 int
132 rd_start(void)
133 {
134 	/*
135 	 * leave space for the header pushback (see get_arc()). If we are
136 	 * going to append and user specified a write block size, check it
137 	 * right away
138 	 */
139 	buf = &(bufmem[BLKMULT]);
140 	if ((act == APPND) && wrblksz) {
141 		if (wrblksz > MAXBLK) {
142 			paxwarn(1,"Write block size %d too large, maximum is: %d",
143 				wrblksz, MAXBLK);
144 			return(-1);
145 		}
146 		if (wrblksz % BLKMULT) {
147 			paxwarn(1, "Write block size %d is not a %d byte multiple",
148 			wrblksz, BLKMULT);
149 			return(-1);
150 		}
151 	}
152 
153 	/*
154 	 * open the archive
155 	 */
156 	if ((ar_open(arcname) < 0) && (ar_next() < 0))
157 		return(-1);
158 	bufend = buf + rdblksz;
159 	bufpt = bufend;
160 	rdcnt = 0;
161 	return(0);
162 }
163 
164 /*
165  * cp_start()
166  *	set up buffer system for copying within the file system
167  */
168 
169 void
170 cp_start(void)
171 {
172 	buf = &(bufmem[BLKMULT]);
173 	rdblksz = blksz = MAXBLK;
174 }
175 
176 /*
177  * appnd_start()
178  *	Set up the buffering system to append new members to an archive that
179  *	was just read. The last block(s) of an archive may contain a format
180  *	specific trailer. To append a new member, this trailer has to be
181  *	removed from the archive. The first byte of the trailer is replaced by
182  *	the start of the header of the first file added to the archive. The
183  *	format specific end read function tells us how many bytes to move
184  *	backwards in the archive to be positioned BEFORE the trailer. Two
185  *	different positions have to be adjusted, the O.S. file offset (e.g. the
186  *	position of the tape head) and the write point within the data we have
187  *	stored in the read (soon to become write) buffer. We may have to move
188  *	back several records (the number depends on the size of the archive
189  *	record and the size of the format trailer) to read up the record where
190  *	the first byte of the trailer is recorded. Trailers may span (and
191  *	overlap) record boundaries.
192  *	We first calculate which record has the first byte of the trailer. We
193  *	move the OS file offset back to the start of this record and read it
194  *	up. We set the buffer write pointer to be at this byte (the byte where
195  *	the trailer starts). We then move the OS file pointer back to the
196  *	start of this record so a flush of this buffer will replace the record
197  *	in the archive.
198  *	A major problem is rewriting this last record. For archives stored
199  *	on disk files, this is trivial. However, many devices are really picky
200  *	about the conditions under which they will allow a write to occur.
201  *	Often devices restrict the conditions where writes can be made writes,
202  *	so it may not be feasible to append archives stored on all types of
203  *	devices.
204  * Return:
205  *	0 for success, -1 for failure
206  */
207 
208 int
209 appnd_start(off_t skcnt)
210 {
211 	int res;
212 	off_t cnt;
213 
214 	if (exit_val != 0) {
215 		paxwarn(0, "Cannot append to an archive that may have flaws.");
216 		return(-1);
217 	}
218 	/*
219 	 * if the user did not specify a write blocksize, inherit the size used
220 	 * in the last archive volume read. (If a is set we still use rdblksz
221 	 * until next volume, cannot shift sizes within a single volume).
222 	 */
223 	if (!wrblksz)
224 		wrblksz = blksz = rdblksz;
225 	else
226 		blksz = rdblksz;
227 
228 	/*
229 	 * make sure that this volume allows appends
230 	 */
231 	if (ar_app_ok() < 0)
232 		return(-1);
233 
234 	/*
235 	 * Calculate bytes to move back and move in front of record where we
236 	 * need to start writing from. Remember we have to add in any padding
237 	 * that might be in the buffer after the trailer in the last block. We
238 	 * travel skcnt + padding ROUNDED UP to blksize.
239 	 */
240 	skcnt += bufend - bufpt;
241 	if ((cnt = (skcnt/blksz) * blksz) < skcnt)
242 		cnt += blksz;
243 	if (ar_rev((off_t)cnt) < 0)
244 		goto out;
245 
246 	/*
247 	 * We may have gone too far if there is valid data in the block we are
248 	 * now in front of, read up the block and position the pointer after
249 	 * the valid data.
250 	 */
251 	if ((cnt -= skcnt) > 0) {
252 		/*
253 		 * watch out for stupid tape drives. ar_rev() will set rdblksz
254 		 * to be real physical blocksize so we must loop until we get
255 		 * the old rdblksz (now in blksz). If ar_rev() fouls up the
256 		 * determination of the physical block size, we will fail.
257 		 */
258 		bufpt = buf;
259 		bufend = buf + blksz;
260 		while (bufpt < bufend) {
261 			if ((res = ar_read(bufpt, rdblksz)) <= 0)
262 				goto out;
263 			bufpt += res;
264 		}
265 		if (ar_rev((off_t)(bufpt - buf)) < 0)
266 			goto out;
267 		bufpt = buf + cnt;
268 		bufend = buf + blksz;
269 	} else {
270 		/*
271 		 * buffer is empty
272 		 */
273 		bufend = buf + blksz;
274 		bufpt = buf;
275 	}
276 	rdblksz = blksz;
277 	rdcnt -= skcnt;
278 	wrcnt = 0;
279 
280 	/*
281 	 * At this point we are ready to write. If the device requires special
282 	 * handling to write at a point were previously recorded data resides,
283 	 * that is handled in ar_set_wr(). From now on we operate under normal
284 	 * ARCHIVE mode (write) conditions
285 	 */
286 	if (ar_set_wr() < 0)
287 		return(-1);
288 	act = ARCHIVE;
289 	return(0);
290 
291     out:
292 	paxwarn(1, "Unable to rewrite archive trailer, cannot append.");
293 	return(-1);
294 }
295 
296 /*
297  * rd_sync()
298  *	A read error occurred on this archive volume. Resync the buffer and
299  *	try to reset the device (if possible) so we can continue to read. Keep
300  *	trying to do this until we get a valid read, or we reach the limit on
301  *	consecutive read faults (at which point we give up). The user can
302  *	adjust the read error limit through a command line option.
303  * Returns:
304  *	0 on success, and -1 on failure
305  */
306 
307 int
308 rd_sync(void)
309 {
310 	int errcnt = 0;
311 	int res;
312 
313 	/*
314 	 * if the user says bail out on first fault, we are out of here...
315 	 */
316 	if (maxflt == 0)
317 		return(-1);
318 	if (act == APPND) {
319 		paxwarn(1, "Unable to append when there are archive read errors.");
320 		return(-1);
321 	}
322 
323 	/*
324 	 * poke at device and try to get past media error
325 	 */
326 	if (ar_rdsync() < 0) {
327 		if (ar_next() < 0)
328 			return(-1);
329 		else
330 			rdcnt = 0;
331 	}
332 
333 	for (;;) {
334 		if ((res = ar_read(buf, blksz)) > 0) {
335 			/*
336 			 * All right! got some data, fill that buffer
337 			 */
338 			bufpt = buf;
339 			bufend = buf + res;
340 			rdcnt += res;
341 			return(0);
342 		}
343 
344 		/*
345 		 * Oh well, yet another failed read...
346 		 * if error limit reached, ditch. o.w. poke device to move past
347 		 * bad media and try again. if media is badly damaged, we ask
348 		 * the poor (and upset user at this point) for the next archive
349 		 * volume. remember the goal on reads is to get the most we
350 		 * can extract out of the archive.
351 		 */
352 		if ((maxflt > 0) && (++errcnt > maxflt))
353 			paxwarn(0,"Archive read error limit (%d) reached",maxflt);
354 		else if (ar_rdsync() == 0)
355 			continue;
356 		if (ar_next() < 0)
357 			break;
358 		rdcnt = 0;
359 		errcnt = 0;
360 	}
361 	return(-1);
362 }
363 
364 /*
365  * pback()
366  *	push the data used during the archive id phase back into the I/O
367  *	buffer. This is required as we cannot be sure that the header does NOT
368  *	overlap a block boundary (as in the case we are trying to recover a
369  *	flawed archived). This was not designed to be used for any other
370  *	purpose. (What software engineering, HA!)
371  *	WARNING: do not even THINK of pback greater than BLKMULT, unless the
372  *	pback space is increased.
373  */
374 
375 void
376 pback(char *pt, int cnt)
377 {
378 	bufpt -= cnt;
379 	memcpy(bufpt, pt, cnt);
380 	return;
381 }
382 
383 /*
384  * rd_skip()
385  *	skip forward in the archive during an archive read. Used to get quickly
386  *	past file data and padding for files the user did NOT select.
387  * Return:
388  *	0 if ok, -1 failure, and 1 when EOF on the archive volume was detected.
389  */
390 
391 int
392 rd_skip(off_t skcnt)
393 {
394 	off_t res;
395 	off_t cnt;
396 	off_t skipped = 0;
397 
398 	/*
399 	 * consume what data we have in the buffer. If we have to move forward
400 	 * whole records, we call the low level skip function to see if we can
401 	 * move within the archive without doing the expensive reads on data we
402 	 * do not want.
403 	 */
404 	if (skcnt == 0)
405 		return(0);
406 	res = MIN((bufend - bufpt), skcnt);
407 	bufpt += res;
408 	skcnt -= res;
409 
410 	/*
411 	 * if skcnt is now 0, then no additional i/o is needed
412 	 */
413 	if (skcnt == 0)
414 		return(0);
415 
416 	/*
417 	 * We have to read more, calculate complete and partial record reads
418 	 * based on rdblksz. we skip over "cnt" complete records
419 	 */
420 	res = skcnt%rdblksz;
421 	cnt = (skcnt/rdblksz) * rdblksz;
422 
423 	/*
424 	 * if the skip fails, we will have to resync. ar_fow will tell us
425 	 * how much it can skip over. We will have to read the rest.
426 	 */
427 	if (ar_fow(cnt, &skipped) < 0)
428 		return(-1);
429 	res += cnt - skipped;
430 	rdcnt += skipped;
431 
432 	/*
433 	 * what is left we have to read (which may be the whole thing if
434 	 * ar_fow() told us the device can only read to skip records);
435 	 */
436 	while (res > 0L) {
437 		cnt = bufend - bufpt;
438 		/*
439 		 * if the read fails, we will have to resync
440 		 */
441 		if ((cnt <= 0) && ((cnt = buf_fill()) < 0))
442 			return(-1);
443 		if (cnt == 0)
444 			return(1);
445 		cnt = MIN(cnt, res);
446 		bufpt += cnt;
447 		res -= cnt;
448 	}
449 	return(0);
450 }
451 
452 /*
453  * wr_fin()
454  *	flush out any data (and pad if required) the last block. We always pad
455  *	with zero (even though we do not have to). Padding with 0 makes it a
456  *	lot easier to recover if the archive is damaged. zero padding SHOULD
457  *	BE a requirement....
458  */
459 
460 void
461 wr_fin(void)
462 {
463 	if (bufpt > buf) {
464 		memset(bufpt, 0, bufend - bufpt);
465 		bufpt = bufend;
466 		(void)buf_flush(blksz);
467 	}
468 }
469 
470 /*
471  * wr_rdbuf()
472  *	fill the write buffer from data passed to it in a buffer (usually used
473  *	by format specific write routines to pass a file header). On failure we
474  *	punt. We do not allow the user to continue to write flawed archives.
475  *	We assume these headers are not very large (the memory copy we use is
476  *	a bit expensive).
477  * Return:
478  *	0 if buffer was filled ok, -1 o.w. (buffer flush failure)
479  */
480 
481 int
482 wr_rdbuf(char *out, int outcnt)
483 {
484 	int cnt;
485 
486 	/*
487 	 * while there is data to copy copy into the write buffer. when the
488 	 * write buffer fills, flush it to the archive and continue
489 	 */
490 	while (outcnt > 0) {
491 		cnt = bufend - bufpt;
492 		if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0))
493 			return(-1);
494 		/*
495 		 * only move what we have space for
496 		 */
497 		cnt = MIN(cnt, outcnt);
498 		memcpy(bufpt, out, cnt);
499 		bufpt += cnt;
500 		out += cnt;
501 		outcnt -= cnt;
502 	}
503 	return(0);
504 }
505 
506 /*
507  * rd_wrbuf()
508  *	copy from the read buffer into a supplied buffer a specified number of
509  *	bytes. If the read buffer is empty fill it and continue to copy.
510  *	usually used to obtain a file header for processing by a format
511  *	specific read routine.
512  * Return
513  *	number of bytes copied to the buffer, 0 indicates EOF on archive volume,
514  *	-1 is a read error
515  */
516 
517 int
518 rd_wrbuf(char *in, int cpcnt)
519 {
520 	int res;
521 	int cnt;
522 	int incnt = cpcnt;
523 
524 	/*
525 	 * loop until we fill the buffer with the requested number of bytes
526 	 */
527 	while (incnt > 0) {
528 		cnt = bufend - bufpt;
529 		if ((cnt <= 0) && ((cnt = buf_fill()) <= 0)) {
530 			/*
531 			 * read error, return what we got (or the error if
532 			 * no data was copied). The caller must know that an
533 			 * error occurred and has the best knowledge what to
534 			 * do with it
535 			 */
536 			if ((res = cpcnt - incnt) > 0)
537 				return(res);
538 			return(cnt);
539 		}
540 
541 		/*
542 		 * calculate how much data to copy based on whats left and
543 		 * state of buffer
544 		 */
545 		cnt = MIN(cnt, incnt);
546 		memcpy(in, bufpt, cnt);
547 		bufpt += cnt;
548 		incnt -= cnt;
549 		in += cnt;
550 	}
551 	return(cpcnt);
552 }
553 
554 /*
555  * wr_skip()
556  *	skip forward during a write. In other words add padding to the file.
557  *	we add zero filled padding as it makes flawed archives much easier to
558  *	recover from. the caller tells us how many bytes of padding to add
559  *	This routine was not designed to add HUGE amount of padding, just small
560  *	amounts (a few 512 byte blocks at most)
561  * Return:
562  *	0 if ok, -1 if there was a buf_flush failure
563  */
564 
565 int
566 wr_skip(off_t skcnt)
567 {
568 	int cnt;
569 
570 	/*
571 	 * loop while there is more padding to add
572 	 */
573 	while (skcnt > 0L) {
574 		cnt = bufend - bufpt;
575 		if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0))
576 			return(-1);
577 		cnt = MIN(cnt, skcnt);
578 		memset(bufpt, 0, cnt);
579 		bufpt += cnt;
580 		skcnt -= cnt;
581 	}
582 	return(0);
583 }
584 
585 /*
586  * wr_rdfile()
587  *	fill write buffer with the contents of a file. We are passed an open
588  *	file descriptor to the file and the archive structure that describes the
589  *	file we are storing. The variable "left" is modified to contain the
590  *	number of bytes of the file we were NOT able to write to the archive.
591  *	it is important that we always write EXACTLY the number of bytes that
592  *	the format specific write routine told us to. The file can also get
593  *	bigger, so reading to the end of file would create an improper archive,
594  *	we just detect this case and warn the user. We never create a bad
595  *	archive if we can avoid it. Of course trying to archive files that are
596  *	active is asking for trouble. It we fail, we pass back how much we
597  *	could NOT copy and let the caller deal with it.
598  * Return:
599  *	0 ok, -1 if archive write failure. a short read of the file returns a
600  *	0, but "left" is set to be greater than zero.
601  */
602 
603 int
604 wr_rdfile(ARCHD *arcn, int ifd, off_t *left)
605 {
606 	int cnt;
607 	int res = 0;
608 	off_t size = arcn->sb.st_size;
609 	struct stat sb;
610 
611 	/*
612 	 * while there are more bytes to write
613 	 */
614 	while (size > 0L) {
615 		cnt = bufend - bufpt;
616 		if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0)) {
617 			*left = size;
618 			return(-1);
619 		}
620 		cnt = MIN(cnt, size);
621 		if ((res = read(ifd, bufpt, cnt)) <= 0)
622 			break;
623 		size -= res;
624 		bufpt += res;
625 	}
626 
627 	/*
628 	 * better check the file did not change during this operation
629 	 * or the file read failed.
630 	 */
631 	if (res < 0)
632 		syswarn(1, errno, "Read fault on %s", arcn->org_name);
633 	else if (size != 0L)
634 		paxwarn(1, "File changed size during read %s", arcn->org_name);
635 	else if (fstat(ifd, &sb) < 0)
636 		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
637 	else if (arcn->sb.st_mtime != sb.st_mtime)
638 		paxwarn(1, "File %s was modified during copy to archive",
639 			arcn->org_name);
640 	*left = size;
641 	return(0);
642 }
643 
644 /*
645  * rd_wrfile()
646  *	extract the contents of a file from the archive. If we are unable to
647  *	extract the entire file (due to failure to write the file) we return
648  *	the numbers of bytes we did NOT process. This way the caller knows how
649  *	many bytes to skip past to find the next archive header. If the failure
650  *	was due to an archive read, we will catch that when we try to skip. If
651  *	the format supplies a file data crc value, we calculate the actual crc
652  *	so that it can be compared to the value stored in the header
653  * NOTE:
654  *	We call a special function to write the file. This function attempts to
655  *	restore file holes (blocks of zeros) into the file. When files are
656  *	sparse this saves space, and is a LOT faster. For non sparse files
657  *	the performance hit is small. As of this writing, no archive supports
658  *	information on where the file holes are.
659  * Return:
660  *	0 ok, -1 if archive read failure. if we cannot write the entire file,
661  *	we return a 0 but "left" is set to be the amount unwritten
662  */
663 
664 int
665 rd_wrfile(ARCHD *arcn, int ofd, off_t *left)
666 {
667 	int cnt = 0;
668 	off_t size = arcn->sb.st_size;
669 	int res = 0;
670 	char *fnm = arcn->name;
671 	int isem = 1;
672 	int rem;
673 	int sz = MINFBSZ;
674 	struct stat sb;
675 	u_long crc = 0L;
676 
677 	/*
678 	 * pass the blocksize of the file being written to the write routine,
679 	 * if the size is zero, use the default MINFBSZ
680 	 */
681 	if (fstat(ofd, &sb) == 0) {
682 		if (sb.st_blksize > 0)
683 			sz = (int)sb.st_blksize;
684 	} else
685 		syswarn(0,errno,"Unable to obtain block size for file %s",fnm);
686 	rem = sz;
687 	*left = 0L;
688 
689 	/*
690 	 * Copy the archive to the file the number of bytes specified. We have
691 	 * to assume that we want to recover file holes as none of the archive
692 	 * formats can record the location of file holes.
693 	 */
694 	while (size > 0L) {
695 		cnt = bufend - bufpt;
696 		/*
697 		 * if we get a read error, we do not want to skip, as we may
698 		 * miss a header, so we do not set left, but if we get a write
699 		 * error, we do want to skip over the unprocessed data.
700 		 */
701 		if ((cnt <= 0) && ((cnt = buf_fill()) <= 0))
702 			break;
703 		cnt = MIN(cnt, size);
704 		if ((res = file_write(ofd,bufpt,cnt,&rem,&isem,sz,fnm)) <= 0) {
705 			*left = size;
706 			break;
707 		}
708 
709 		if (docrc) {
710 			/*
711 			 * update the actual crc value
712 			 */
713 			cnt = res;
714 			while (--cnt >= 0)
715 				crc += *bufpt++ & 0xff;
716 		} else
717 			bufpt += res;
718 		size -= res;
719 	}
720 
721 	/*
722 	 * if the last block has a file hole (all zero), we must make sure this
723 	 * gets updated in the file. We force the last block of zeros to be
724 	 * written. just closing with the file offset moved forward may not put
725 	 * a hole at the end of the file.
726 	 */
727 	if (isem && (arcn->sb.st_size > 0L))
728 		file_flush(ofd, fnm, isem);
729 
730 	/*
731 	 * if we failed from archive read, we do not want to skip
732 	 */
733 	if ((size > 0L) && (*left == 0L))
734 		return(-1);
735 
736 	/*
737 	 * some formats record a crc on file data. If so, then we compare the
738 	 * calculated crc to the crc stored in the archive
739 	 */
740 	if (docrc && (size == 0L) && (arcn->crc != crc))
741 		paxwarn(1,"Actual crc does not match expected crc %s",arcn->name);
742 	return(0);
743 }
744 
745 /*
746  * cp_file()
747  *	copy the contents of one file to another. used during -rw phase of pax
748  *	just as in rd_wrfile() we use a special write function to write the
749  *	destination file so we can properly copy files with holes.
750  */
751 
752 void
753 cp_file(ARCHD *arcn, int fd1, int fd2)
754 {
755 	int cnt;
756 	off_t cpcnt = 0L;
757 	int res = 0;
758 	char *fnm = arcn->name;
759 	int no_hole = 0;
760 	int isem = 1;
761 	int rem;
762 	int sz = MINFBSZ;
763 	struct stat sb;
764 
765 	/*
766 	 * check for holes in the source file. If none, we will use regular
767 	 * write instead of file write.
768 	 */
769 	 if (((off_t)(arcn->sb.st_blocks * BLKMULT)) >= arcn->sb.st_size)
770 		++no_hole;
771 
772 	/*
773 	 * pass the blocksize of the file being written to the write routine,
774 	 * if the size is zero, use the default MINFBSZ
775 	 */
776 	if (fstat(fd2, &sb) == 0) {
777 		if (sb.st_blksize > 0)
778 			sz = sb.st_blksize;
779 	} else
780 		syswarn(0,errno,"Unable to obtain block size for file %s",fnm);
781 	rem = sz;
782 
783 	/*
784 	 * read the source file and copy to destination file until EOF
785 	 */
786 	for(;;) {
787 		if ((cnt = read(fd1, buf, blksz)) <= 0)
788 			break;
789 		if (no_hole)
790 			res = write(fd2, buf, cnt);
791 		else
792 			res = file_write(fd2, buf, cnt, &rem, &isem, sz, fnm);
793 		if (res != cnt)
794 			break;
795 		cpcnt += cnt;
796 	}
797 
798 	/*
799 	 * check to make sure the copy is valid.
800 	 */
801 	if (res < 0)
802 		syswarn(1, errno, "Failed write during copy of %s to %s",
803 			arcn->org_name, arcn->name);
804 	else if (cpcnt != arcn->sb.st_size)
805 		paxwarn(1, "File %s changed size during copy to %s",
806 			arcn->org_name, arcn->name);
807 	else if (fstat(fd1, &sb) < 0)
808 		syswarn(1, errno, "Failed stat of %s", arcn->org_name);
809 	else if (arcn->sb.st_mtime != sb.st_mtime)
810 		paxwarn(1, "File %s was modified during copy to %s",
811 			arcn->org_name, arcn->name);
812 
813 	/*
814 	 * if the last block has a file hole (all zero), we must make sure this
815 	 * gets updated in the file. We force the last block of zeros to be
816 	 * written. just closing with the file offset moved forward may not put
817 	 * a hole at the end of the file.
818 	 */
819 	if (!no_hole && isem && (arcn->sb.st_size > 0L))
820 		file_flush(fd2, fnm, isem);
821 	return;
822 }
823 
824 /*
825  * buf_fill()
826  *	fill the read buffer with the next record (or what we can get) from
827  *	the archive volume.
828  * Return:
829  *	Number of bytes of data in the read buffer, -1 for read error, and
830  *	0 when finished (user specified termination in ar_next()).
831  */
832 
833 int
834 buf_fill(void)
835 {
836 	int cnt;
837 	static int fini = 0;
838 
839 	if (fini)
840 		return(0);
841 
842 	for(;;) {
843 		/*
844 		 * try to fill the buffer. on error the next archive volume is
845 		 * opened and we try again.
846 		 */
847 		if ((cnt = ar_read(buf, blksz)) > 0) {
848 			bufpt = buf;
849 			bufend = buf + cnt;
850 			rdcnt += cnt;
851 			return(cnt);
852 		}
853 
854 		/*
855 		 * errors require resync, EOF goes to next archive
856 		 */
857 		if (cnt < 0)
858 			break;
859 		if (ar_next() < 0) {
860 			fini = 1;
861 			return(0);
862 		}
863 		rdcnt = 0;
864 	}
865 	exit_val = 1;
866 	return(-1);
867 }
868 
869 /*
870  * buf_flush()
871  *	force the write buffer to the archive. We are passed the number of
872  *	bytes in the buffer at the point of the flush. When we change archives
873  *	the record size might change. (either larger or smaller).
874  * Return:
875  *	0 if all is ok, -1 when a write error occurs.
876  */
877 
878 int
879 buf_flush(int bufcnt)
880 {
881 	int cnt;
882 	int push = 0;
883 	int totcnt = 0;
884 
885 	/*
886 	 * if we have reached the user specified byte count for each archive
887 	 * volume, prompt for the next volume. (The non-standard -R flag).
888 	 * NOTE: If the wrlimit is smaller than wrcnt, we will always write
889 	 * at least one record. We always round limit UP to next blocksize.
890 	 */
891 	if ((wrlimit > 0) && (wrcnt > wrlimit)) {
892 		paxwarn(0, "User specified archive volume byte limit reached.");
893 		if (ar_next() < 0) {
894 			wrcnt = 0;
895 			exit_val = 1;
896 			return(-1);
897 		}
898 		wrcnt = 0;
899 
900 		/*
901 		 * The new archive volume might have changed the size of the
902 		 * write blocksize. if so we figure out if we need to write
903 		 * (one or more times), or if there is now free space left in
904 		 * the buffer (it is no longer full). bufcnt has the number of
905 		 * bytes in the buffer, (the blocksize, at the point we were
906 		 * CALLED). Push has the amount of "extra" data in the buffer
907 		 * if the block size has shrunk from a volume change.
908 		 */
909 		bufend = buf + blksz;
910 		if (blksz > bufcnt)
911 			return(0);
912 		if (blksz < bufcnt)
913 			push = bufcnt - blksz;
914 	}
915 
916 	/*
917 	 * We have enough data to write at least one archive block
918 	 */
919 	for (;;) {
920 		/*
921 		 * write a block and check if it all went out ok
922 		 */
923 		cnt = ar_write(buf, blksz);
924 		if (cnt == blksz) {
925 			/*
926 			 * the write went ok
927 			 */
928 			wrcnt += cnt;
929 			totcnt += cnt;
930 			if (push > 0) {
931 				/* we have extra data to push to the front.
932 				 * check for more than 1 block of push, and if
933 				 * so we loop back to write again
934 				 */
935 				memcpy(buf, bufend, push);
936 				bufpt = buf + push;
937 				if (push >= blksz) {
938 					push -= blksz;
939 					continue;
940 				}
941 			} else
942 				bufpt = buf;
943 			return(totcnt);
944 		} else if (cnt > 0) {
945 			/*
946 			 * Oh drat we got a partial write!
947 			 * if format doesn't care about alignment let it go,
948 			 * we warned the user in ar_write().... but this means
949 			 * the last record on this volume violates pax spec....
950 			 */
951 			totcnt += cnt;
952 			wrcnt += cnt;
953 			bufpt = buf + cnt;
954 			cnt = bufcnt - cnt;
955 			memcpy(buf, bufpt, cnt);
956 			bufpt = buf + cnt;
957 			if (!frmt->blkalgn || ((cnt % frmt->blkalgn) == 0))
958 				return(totcnt);
959 			break;
960 		}
961 
962 		/*
963 		 * All done, go to next archive
964 		 */
965 		wrcnt = 0;
966 		if (ar_next() < 0)
967 			break;
968 
969 		/*
970 		 * The new archive volume might also have changed the block
971 		 * size. if so, figure out if we have too much or too little
972 		 * data for using the new block size
973 		 */
974 		bufend = buf + blksz;
975 		if (blksz > bufcnt)
976 			return(0);
977 		if (blksz < bufcnt)
978 			push = bufcnt - blksz;
979 	}
980 
981 	/*
982 	 * write failed, stop pax. we must not create a bad archive!
983 	 */
984 	exit_val = 1;
985 	return(-1);
986 }
987