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