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