2 * Copyright (c) 1992 Keith Muller.
3 * Copyright (c) 1992, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Keith Muller of the University of California, San Diego.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 static char sccsid[] = "@(#)buf_subs.c 8.2 (Berkeley) 4/18/94";
42 static const char rcsid[] =
43 "$FreeBSD: src/bin/pax/buf_subs.c,v 1.12.2.1 2001/08/01 05:03:11 obrien Exp $";
46 #include <sys/types.h>
57 * routines which implement archive and file buffering
60 #define MINFBSZ 512 /* default block size for hole detect */
61 #define MAXFLT 10 /* default media read error limit */
64 * Need to change bufmem to dynamic allocation when the upper
65 * limit on blocking size is removed (though that will violate pax spec)
66 * MAXBLK define and tests will also need to be updated.
68 static char bufmem[MAXBLK+BLKMULT]; /* i/o buffer + pushback id space */
69 static char *buf; /* normal start of i/o buffer */
70 static char *bufend; /* end or last char in i/o buffer */
71 static char *bufpt; /* read/write point in i/o buffer */
72 int blksz = MAXBLK; /* block input/output size in bytes */
73 int wrblksz; /* user spec output size in bytes */
74 int maxflt = MAXFLT; /* MAX consecutive media errors */
75 int rdblksz; /* first read blksize (tapes only) */
76 off_t wrlimit; /* # of bytes written per archive vol */
77 off_t wrcnt; /* # of bytes written on current vol */
78 off_t rdcnt; /* # of bytes read on current vol */
82 * set up the buffering system to operate in a write mode
84 * 0 if ok, -1 if the user specified write block size violates pax spec
95 buf = &(bufmem[BLKMULT]);
97 * Check to make sure the write block size meets pax specs. If the user
98 * does not specify a blocksize, we use the format default blocksize.
99 * We must be picky on writes, so we do not allow the user to create an
100 * archive that might be hard to read elsewhere. If all ok, we then
101 * open the first archive volume
105 if (wrblksz > MAXBLK) {
106 paxwarn(1, "Write block size of %d too large, maximum is: %d",
110 if (wrblksz % BLKMULT) {
111 paxwarn(1, "Write block size of %d is not a %d byte multiple",
115 if (wrblksz > MAXBLK_POSIX) {
116 paxwarn(0, "Write block size of %d larger than POSIX max %d, archive may not be portable",
117 wrblksz, MAXBLK_POSIX);
122 * we only allow wrblksz to be used with all archive operations
124 blksz = rdblksz = wrblksz;
125 if ((ar_open(arcname) < 0) && (ar_next() < 0))
128 bufend = buf + wrblksz;
135 * set up buffering system to read an archive
137 * 0 if ok, -1 otherwise
149 * leave space for the header pushback (see get_arc()). If we are
150 * going to append and user specified a write block size, check it
153 buf = &(bufmem[BLKMULT]);
154 if ((act == APPND) && wrblksz) {
155 if (wrblksz > MAXBLK) {
156 paxwarn(1,"Write block size %d too large, maximum is: %d",
160 if (wrblksz % BLKMULT) {
161 paxwarn(1, "Write block size %d is not a %d byte multiple",
170 if ((ar_open(arcname) < 0) && (ar_next() < 0))
172 bufend = buf + rdblksz;
180 * set up buffer system for copying within the file system
191 buf = &(bufmem[BLKMULT]);
192 rdblksz = blksz = MAXBLK;
197 * Set up the buffering system to append new members to an archive that
198 * was just read. The last block(s) of an archive may contain a format
199 * specific trailer. To append a new member, this trailer has to be
200 * removed from the archive. The first byte of the trailer is replaced by
201 * the start of the header of the first file added to the archive. The
202 * format specific end read function tells us how many bytes to move
203 * backwards in the archive to be positioned BEFORE the trailer. Two
204 * different postions have to be adjusted, the O.S. file offset (e.g. the
205 * position of the tape head) and the write point within the data we have
206 * stored in the read (soon to become write) buffer. We may have to move
207 * back several records (the number depends on the size of the archive
208 * record and the size of the format trailer) to read up the record where
209 * the first byte of the trailer is recorded. Trailers may span (and
210 * overlap) record boundries.
211 * We first calculate which record has the first byte of the trailer. We
212 * move the OS file offset back to the start of this record and read it
213 * up. We set the buffer write pointer to be at this byte (the byte where
214 * the trailer starts). We then move the OS file pointer back to the
215 * start of this record so a flush of this buffer will replace the record
217 * A major problem is rewriting this last record. For archives stored
218 * on disk files, this is trival. However, many devices are really picky
219 * about the conditions under which they will allow a write to occur.
220 * Often devices restrict the conditions where writes can be made writes,
221 * so it may not be feasable to append archives stored on all types of
224 * 0 for success, -1 for failure
229 appnd_start(off_t skcnt)
240 paxwarn(0, "Cannot append to an archive that may have flaws.");
244 * if the user did not specify a write blocksize, inherit the size used
245 * in the last archive volume read. (If a is set we still use rdblksz
246 * until next volume, cannot shift sizes within a single volume).
249 wrblksz = blksz = rdblksz;
254 * make sure that this volume allows appends
260 * Calculate bytes to move back and move in front of record where we
261 * need to start writing from. Remember we have to add in any padding
262 * that might be in the buffer after the trailer in the last block. We
263 * travel skcnt + padding ROUNDED UP to blksize.
265 skcnt += bufend - bufpt;
266 if ((cnt = (skcnt/blksz) * blksz) < skcnt)
268 if (ar_rev((off_t)cnt) < 0)
272 * We may have gone too far if there is valid data in the block we are
273 * now in front of, read up the block and position the pointer after
276 if ((cnt -= skcnt) > 0) {
278 * watch out for stupid tape drives. ar_rev() will set rdblksz
279 * to be real physical blocksize so we must loop until we get
280 * the old rdblksz (now in blksz). If ar_rev() fouls up the
281 * determination of the physical block size, we will fail.
284 bufend = buf + blksz;
285 while (bufpt < bufend) {
286 if ((res = ar_read(bufpt, rdblksz)) <= 0)
290 if (ar_rev((off_t)(bufpt - buf)) < 0)
293 bufend = buf + blksz;
298 bufend = buf + blksz;
306 * At this point we are ready to write. If the device requires special
307 * handling to write at a point were previously recorded data resides,
308 * that is handled in ar_set_wr(). From now on we operate under normal
309 * ARCHIVE mode (write) conditions
317 paxwarn(1, "Unable to rewrite archive trailer, cannot append.");
323 * A read error occurred on this archive volume. Resync the buffer and
324 * try to reset the device (if possible) so we can continue to read. Keep
325 * trying to do this until we get a valid read, or we reach the limit on
326 * consecutive read faults (at which point we give up). The user can
327 * adjust the read error limit through a command line option.
329 * 0 on success, and -1 on failure
340 register int errcnt = 0;
344 * if the user says bail out on first fault, we are out of here...
349 paxwarn(1, "Unable to append when there are archive read errors.");
354 * poke at device and try to get past media error
356 if (ar_rdsync() < 0) {
364 if ((res = ar_read(buf, blksz)) > 0) {
366 * All right! got some data, fill that buffer
375 * Oh well, yet another failed read...
376 * if error limit reached, ditch. o.w. poke device to move past
377 * bad media and try again. if media is badly damaged, we ask
378 * the poor (and upset user at this point) for the next archive
379 * volume. remember the goal on reads is to get the most we
380 * can extract out of the archive.
382 if ((maxflt > 0) && (++errcnt > maxflt))
383 paxwarn(0,"Archive read error limit (%d) reached",maxflt);
384 else if (ar_rdsync() == 0)
396 * push the data used during the archive id phase back into the I/O
397 * buffer. This is required as we cannot be sure that the header does NOT
398 * overlap a block boundry (as in the case we are trying to recover a
399 * flawed archived). This was not designed to be used for any other
400 * purpose. (What software engineering, HA!)
401 * WARNING: do not even THINK of pback greater than BLKMULT, unless the
402 * pback space is increased.
407 pback(char *pt, int cnt)
416 memcpy(bufpt, pt, cnt);
422 * skip foward in the archive during a archive read. Used to get quickly
423 * past file data and padding for files the user did NOT select.
425 * 0 if ok, -1 failure, and 1 when EOF on the archive volume was detected.
442 * consume what data we have in the buffer. If we have to move foward
443 * whole records, we call the low level skip function to see if we can
444 * move within the archive without doing the expensive reads on data we
449 res = MIN((bufend - bufpt), skcnt);
454 * if skcnt is now 0, then no additional i/o is needed
460 * We have to read more, calculate complete and partial record reads
461 * based on rdblksz. we skip over "cnt" complete records
464 cnt = (skcnt/rdblksz) * rdblksz;
467 * if the skip fails, we will have to resync. ar_fow will tell us
468 * how much it can skip over. We will have to read the rest.
470 if (ar_fow(cnt, &skipped) < 0)
472 res += cnt - skipped;
476 * what is left we have to read (which may be the whole thing if
477 * ar_fow() told us the device can only read to skip records);
480 cnt = bufend - bufpt;
482 * if the read fails, we will have to resync
484 if ((cnt <= 0) && ((cnt = buf_fill()) < 0))
497 * flush out any data (and pad if required) the last block. We always pad
498 * with zero (even though we do not have to). Padding with 0 makes it a
499 * lot easier to recover if the archive is damaged. zero paddding SHOULD
500 * BE a requirement....
512 memset(bufpt, 0, bufend - bufpt);
514 (void)buf_flush(blksz);
520 * fill the write buffer from data passed to it in a buffer (usually used
521 * by format specific write routines to pass a file header). On failure we
522 * punt. We do not allow the user to continue to write flawed archives.
523 * We assume these headers are not very large (the memory copy we use is
526 * 0 if buffer was filled ok, -1 o.w. (buffer flush failure)
531 wr_rdbuf(register char *out, register int outcnt)
534 wr_rdbuf(out, outcnt)
542 * while there is data to copy copy into the write buffer. when the
543 * write buffer fills, flush it to the archive and continue
546 cnt = bufend - bufpt;
547 if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0))
550 * only move what we have space for
552 cnt = MIN(cnt, outcnt);
553 memcpy(bufpt, out, cnt);
563 * copy from the read buffer into a supplied buffer a specified number of
564 * bytes. If the read buffer is empty fill it and continue to copy.
565 * usually used to obtain a file header for processing by a format
566 * specific read routine.
568 * number of bytes copied to the buffer, 0 indicates EOF on archive volume,
574 rd_wrbuf(register char *in, register int cpcnt)
584 register int incnt = cpcnt;
587 * loop until we fill the buffer with the requested number of bytes
590 cnt = bufend - bufpt;
591 if ((cnt <= 0) && ((cnt = buf_fill()) <= 0)) {
593 * read error, return what we got (or the error if
594 * no data was copied). The caller must know that an
595 * error occured and has the best knowledge what to
598 if ((res = cpcnt - incnt) > 0)
604 * calculate how much data to copy based on whats left and
607 cnt = MIN(cnt, incnt);
608 memcpy(in, bufpt, cnt);
618 * skip forward during a write. In other words add padding to the file.
619 * we add zero filled padding as it makes flawed archives much easier to
620 * recover from. the caller tells us how many bytes of padding to add
621 * This routine was not designed to add HUGE amount of padding, just small
622 * amounts (a few 512 byte blocks at most)
624 * 0 if ok, -1 if there was a buf_flush failure
639 * loop while there is more padding to add
642 cnt = bufend - bufpt;
643 if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0))
645 cnt = MIN(cnt, skcnt);
646 memset(bufpt, 0, cnt);
655 * fill write buffer with the contents of a file. We are passed an open
656 * file descriptor to the file an the archive structure that describes the
657 * file we are storing. The variable "left" is modified to contain the
658 * number of bytes of the file we were NOT able to write to the archive.
659 * it is important that we always write EXACTLY the number of bytes that
660 * the format specific write routine told us to. The file can also get
661 * bigger, so reading to the end of file would create an improper archive,
662 * we just detect this case and warn the user. We never create a bad
663 * archive if we can avoid it. Of course trying to archive files that are
664 * active is asking for trouble. It we fail, we pass back how much we
665 * could NOT copy and let the caller deal with it.
667 * 0 ok, -1 if archive write failure. a short read of the file returns a
668 * 0, but "left" is set to be greater than zero.
673 wr_rdfile(ARCHD *arcn, int ifd, off_t *left)
676 wr_rdfile(arcn, ifd, left)
683 register int res = 0;
684 register off_t size = arcn->sb.st_size;
688 * while there are more bytes to write
691 cnt = bufend - bufpt;
692 if ((cnt <= 0) && ((cnt = buf_flush(blksz)) < 0)) {
696 cnt = MIN(cnt, size);
697 if ((res = read(ifd, bufpt, cnt)) <= 0)
704 * better check the file did not change during this operation
705 * or the file read failed.
708 syswarn(1, errno, "Read fault on %s", arcn->org_name);
710 paxwarn(1, "File changed size during read %s", arcn->org_name);
711 else if (fstat(ifd, &sb) < 0)
712 syswarn(1, errno, "Failed stat on %s", arcn->org_name);
713 else if (arcn->sb.st_mtime != sb.st_mtime)
714 paxwarn(1, "File %s was modified during copy to archive",
722 * extract the contents of a file from the archive. If we are unable to
723 * extract the entire file (due to failure to write the file) we return
724 * the numbers of bytes we did NOT process. This way the caller knows how
725 * many bytes to skip past to find the next archive header. If the failure
726 * was due to an archive read, we will catch that when we try to skip. If
727 * the format supplies a file data crc value, we calculate the actual crc
728 * so that it can be compared to the value stored in the header
730 * We call a special function to write the file. This function attempts to
731 * restore file holes (blocks of zeros) into the file. When files are
732 * sparse this saves space, and is a LOT faster. For non sparse files
733 * the performance hit is small. As of this writing, no archive supports
734 * information on where the file holes are.
736 * 0 ok, -1 if archive read failure. if we cannot write the entire file,
737 * we return a 0 but "left" is set to be the amount unwritten
742 rd_wrfile(ARCHD *arcn, int ofd, off_t *left)
745 rd_wrfile(arcn, ofd, left)
751 register int cnt = 0;
752 register off_t size = arcn->sb.st_size;
753 register int res = 0;
754 register char *fnm = arcn->name;
762 * pass the blocksize of the file being written to the write routine,
763 * if the size is zero, use the default MINFBSZ
765 if (fstat(ofd, &sb) == 0) {
766 if (sb.st_blksize > 0)
767 sz = (int)sb.st_blksize;
769 syswarn(0,errno,"Unable to obtain block size for file %s",fnm);
774 * Copy the archive to the file the number of bytes specified. We have
775 * to assume that we want to recover file holes as none of the archive
776 * formats can record the location of file holes.
779 cnt = bufend - bufpt;
781 * if we get a read error, we do not want to skip, as we may
782 * miss a header, so we do not set left, but if we get a write
783 * error, we do want to skip over the unprocessed data.
785 if ((cnt <= 0) && ((cnt = buf_fill()) <= 0))
787 cnt = MIN(cnt, size);
788 if ((res = file_write(ofd,bufpt,cnt,&rem,&isem,sz,fnm)) <= 0) {
795 * update the actual crc value
799 crc += *bufpt++ & 0xff;
806 * if the last block has a file hole (all zero), we must make sure this
807 * gets updated in the file. We force the last block of zeros to be
808 * written. just closing with the file offset moved forward may not put
809 * a hole at the end of the file.
811 if (isem && (arcn->sb.st_size > 0L))
812 file_flush(ofd, fnm, isem);
815 * if we failed from archive read, we do not want to skip
817 if ((size > 0L) && (*left == 0L))
821 * some formats record a crc on file data. If so, then we compare the
822 * calculated crc to the crc stored in the archive
824 if (docrc && (size == 0L) && (arcn->crc != crc))
825 paxwarn(1,"Actual crc does not match expected crc %s",arcn->name);
831 * copy the contents of one file to another. used during -rw phase of pax
832 * just as in rd_wrfile() we use a special write function to write the
833 * destination file so we can properly copy files with holes.
838 cp_file(ARCHD *arcn, int fd1, int fd2)
841 cp_file(arcn, fd1, fd2)
848 register off_t cpcnt = 0L;
849 register int res = 0;
850 register char *fnm = arcn->name;
851 register int no_hole = 0;
858 * check for holes in the source file. If none, we will use regular
859 * write instead of file write.
861 if (((off_t)(arcn->sb.st_blocks * BLKMULT)) >= arcn->sb.st_size)
865 * pass the blocksize of the file being written to the write routine,
866 * if the size is zero, use the default MINFBSZ
868 if (fstat(fd2, &sb) == 0) {
869 if (sb.st_blksize > 0)
872 syswarn(0,errno,"Unable to obtain block size for file %s",fnm);
876 * read the source file and copy to destination file until EOF
879 if ((cnt = read(fd1, buf, blksz)) <= 0)
882 res = write(fd2, buf, cnt);
884 res = file_write(fd2, buf, cnt, &rem, &isem, sz, fnm);
891 * check to make sure the copy is valid.
894 syswarn(1, errno, "Failed write during copy of %s to %s",
895 arcn->org_name, arcn->name);
896 else if (cpcnt != arcn->sb.st_size)
897 paxwarn(1, "File %s changed size during copy to %s",
898 arcn->org_name, arcn->name);
899 else if (fstat(fd1, &sb) < 0)
900 syswarn(1, errno, "Failed stat of %s", arcn->org_name);
901 else if (arcn->sb.st_mtime != sb.st_mtime)
902 paxwarn(1, "File %s was modified during copy to %s",
903 arcn->org_name, arcn->name);
906 * if the last block has a file hole (all zero), we must make sure this
907 * gets updated in the file. We force the last block of zeros to be
908 * written. just closing with the file offset moved forward may not put
909 * a hole at the end of the file.
911 if (!no_hole && isem && (arcn->sb.st_size > 0L))
912 file_flush(fd2, fnm, isem);
918 * fill the read buffer with the next record (or what we can get) from
919 * the archive volume.
921 * Number of bytes of data in the read buffer, -1 for read error, and
922 * 0 when finished (user specified termination in ar_next()).
941 * try to fill the buffer. on error the next archive volume is
942 * opened and we try again.
944 if ((cnt = ar_read(buf, blksz)) > 0) {
952 * errors require resync, EOF goes to next archive
968 * force the write buffer to the archive. We are passed the number of
969 * bytes in the buffer at the point of the flush. When we change archives
970 * the record size might change. (either larger or smaller).
972 * 0 if all is ok, -1 when a write error occurs.
977 buf_flush(register int bufcnt)
985 register int push = 0;
986 register int totcnt = 0;
989 * if we have reached the user specified byte count for each archive
990 * volume, prompt for the next volume. (The non-standrad -R flag).
991 * NOTE: If the wrlimit is smaller than wrcnt, we will always write
992 * at least one record. We always round limit UP to next blocksize.
994 if ((wrlimit > 0) && (wrcnt > wrlimit)) {
995 paxwarn(0, "User specified archive volume byte limit reached.");
1004 * The new archive volume might have changed the size of the
1005 * write blocksize. if so we figure out if we need to write
1006 * (one or more times), or if there is now free space left in
1007 * the buffer (it is no longer full). bufcnt has the number of
1008 * bytes in the buffer, (the blocksize, at the point we were
1009 * CALLED). Push has the amount of "extra" data in the buffer
1010 * if the block size has shrunk from a volume change.
1012 bufend = buf + blksz;
1016 push = bufcnt - blksz;
1020 * We have enough data to write at least one archive block
1024 * write a block and check if it all went out ok
1026 cnt = ar_write(buf, blksz);
1034 /* we have extra data to push to the front.
1035 * check for more than 1 block of push, and if
1036 * so we loop back to write again
1038 memcpy(buf, bufend, push);
1040 if (push >= blksz) {
1047 } else if (cnt > 0) {
1049 * Oh drat we got a partial write!
1050 * if format doesnt care about alignment let it go,
1051 * we warned the user in ar_write().... but this means
1052 * the last record on this volume violates pax spec....
1058 memcpy(buf, bufpt, cnt);
1060 if (!frmt->blkalgn || ((cnt % frmt->blkalgn) == 0))
1066 * All done, go to next archive
1073 * The new archive volume might also have changed the block
1074 * size. if so, figure out if we have too much or too little
1075 * data for using the new block size
1077 bufend = buf + blksz;
1081 push = bufcnt - blksz;
1085 * write failed, stop pax. we must not create a bad archive!