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