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