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