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