Package freenet.support.io

Examples of freenet.support.io.StorageFormatException


    public static LockableRandomAccessBuffer create(DataInputStream dis, FilenameGenerator fg, PersistentFileTracker persistentFileTracker, MasterSecret masterKey)
    throws IOException, StorageFormatException, ResumeFailedException {
        EncryptedRandomAccessBufferType type = EncryptedRandomAccessBufferType.getByBitmask(dis.readInt());
        if(type == null)
            throw new StorageFormatException("Unknown EncryptedRandomAccessBufferType");
        LockableRandomAccessBuffer underlying = BucketTools.restoreRAFFrom(dis, fg, persistentFileTracker, masterKey);
        try {
            return new EncryptedRandomAccessBuffer(type, underlying, masterKey, false);
        } catch (GeneralSecurityException e) {
            Logger.error(EncryptedRandomAccessBuffer.class, "Crypto error resuming: "+e, e);
View Full Code Here


     * @throws IOException If unable to read from the stream.
     */
    public FetchContext(DataInputStream dis) throws StorageFormatException, IOException {
        long magic = dis.readLong();
        if(magic != CLIENT_DETAIL_MAGIC)
            throw new StorageFormatException("Bad magic for fetch settings (FetchContext)");
        int version = dis.readInt();
        if(version != CLIENT_DETAIL_VERSION)
            throw new StorageFormatException("Bad version for fetch settings (FetchContext)");
        maxOutputLength = dis.readLong();
        if(maxOutputLength < 0) throw new StorageFormatException("Bad max output length");
        maxTempLength = dis.readLong();
        if(maxTempLength < 0) throw new StorageFormatException("Bad max temp length");
        maxRecursionLevel = dis.readInt();
        if(maxRecursionLevel < 0) throw new StorageFormatException("Bad max recursion level");
        maxArchiveRestarts = dis.readInt();
        if(maxArchiveRestarts < 0) throw new StorageFormatException("Bad max archive restarts");
        maxArchiveLevels = dis.readInt();
        if(maxArchiveLevels < 0) throw new StorageFormatException("Bad max archive levels");
        dontEnterImplicitArchives = dis.readBoolean();
        maxSplitfileBlockRetries = dis.readInt();
        if(maxSplitfileBlockRetries < -1) throw new StorageFormatException("Bad max splitfile block retries");
        maxNonSplitfileRetries = dis.readInt();
        if(maxNonSplitfileRetries < -1) throw new StorageFormatException("Bad non-splitfile retries");
        maxUSKRetries = dis.readInt();
        if(maxUSKRetries < -1) throw new StorageFormatException("Bad max USK retries");
        allowSplitfiles = dis.readBoolean();
        followRedirects = dis.readBoolean();
        localRequestOnly = dis.readBoolean();
        ignoreStore = dis.readBoolean();
        maxMetadataSize = dis.readInt();
        if(maxMetadataSize < 0) throw new StorageFormatException("Bad max metadata size");
        maxDataBlocksPerSegment = dis.readInt();
        if(maxDataBlocksPerSegment < 0 || maxDataBlocksPerSegment > FECCodec.MAX_TOTAL_BLOCKS_PER_SEGMENT)
            throw new StorageFormatException("Bad max blocks per segment");
        maxCheckBlocksPerSegment = dis.readInt();
        if(maxCheckBlocksPerSegment < 0 || maxCheckBlocksPerSegment > FECCodec.MAX_TOTAL_BLOCKS_PER_SEGMENT)
            throw new StorageFormatException("Bad max blocks per segment");
        returnZIPManifests = dis.readBoolean();
        filterData = dis.readBoolean();
        ignoreTooManyPathComponents = dis.readBoolean();
        int x = dis.readInt();
        if(x < 0) throw new StorageFormatException("Bad allowed MIME types length "+x);
        if(x == 0) {
            allowedMIMETypes = null;
        } else {
            allowedMIMETypes = new HashSet<String>();
            for(int i=0;i<x;i++) {
View Full Code Here

        this.errors = new FailureCodeTracker(false); // FIXME persist???
        this.completeViaTruncation = completeViaTruncation;
        // FIXME this is hideous! Rewrite the writing/parsing code here in a less ugly way. However, it works...
        rafLength = raf.size();
        if(raf.size() < 8 /* FIXME more! */)
            throw new StorageFormatException("Too short");
        // Last 8 bytes: Magic value.
        byte[] buf = new byte[8];
        raf.pread(rafLength-8, buf, 0, 8);
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(buf));
        if(dis.readLong() != END_MAGIC)
            throw new StorageFormatException("Wrong magic bytes");
        // 4 bytes before that: Version.
        byte[] versionBuf = new byte[4];
        raf.pread(rafLength-12, versionBuf, 0, 4);
        dis = new DataInputStream(new ByteArrayInputStream(versionBuf));
        int version = dis.readInt();
        if(version != 1)
            throw new StorageFormatException("Wrong version "+version);
        // 2 bytes: Checksum type
        byte[] checksumTypeBuf = new byte[2];
        raf.pread(rafLength-14, checksumTypeBuf, 0, 2);
        dis = new DataInputStream(new ByteArrayInputStream(checksumTypeBuf));
        int checksumType = dis.readShort();
        if(checksumType != ChecksumChecker.CHECKSUM_CRC)
            throw new StorageFormatException("Unknown checksum type "+checksumType);
        // 4 bytes: Flags. Unused at present.
        byte[] flagsBuf = new byte[4];
        raf.pread(rafLength-18, flagsBuf, 0, 4);
        dis = new DataInputStream(new ByteArrayInputStream(flagsBuf));
        int flags = dis.readInt();
        if(flags != 0)
            throw new StorageFormatException("Unknown flags: "+flags);
        // 4 bytes basic settings length and a checksum, which includes both the settings length and the version.
        buf = new byte[14];
        raf.pread(rafLength-(22+checksumLength), buf, 0, 4);
        byte[] checksum = new byte[checksumLength];
        // Check the checksum.
        raf.pread(rafLength-(18+checksumLength), checksum, 0, checksumLength);
        System.arraycopy(flagsBuf, 0, buf, 4, 4);
        System.arraycopy(checksumTypeBuf, 0, buf, 8, 2);
        System.arraycopy(versionBuf, 0, buf, 10, 4);
        if(!checksumChecker.checkChecksum(buf, 0, 14, checksum))
            throw new StorageFormatException("Checksum failed on basic settings length and version");
        dis = new DataInputStream(new ByteArrayInputStream(buf));
        int basicSettingsLength = dis.readInt();
        if(basicSettingsLength < 0 || basicSettingsLength + 12 + 4 + checksumLength > raf.size() ||
                basicSettingsLength > 1024*1024)
            throw new StorageFormatException("Bad basic settings length");
        byte[] basicSettingsBuffer = new byte[basicSettingsLength];
        long basicSettingsOffset = rafLength-(18+4+checksumLength*2+basicSettingsLength);
        try {
            preadChecksummed(basicSettingsOffset,
                    basicSettingsBuffer, 0, basicSettingsLength);
        } catch (ChecksumFailedException e) {
            throw new StorageFormatException("Basic settings checksum invalid");
        }
        dis = new DataInputStream(new ByteArrayInputStream(basicSettingsBuffer));
        try {
            short s = dis.readShort();
            try {
                splitfileType = SplitfileAlgorithm.getByCode(s);
            } catch (IllegalArgumentException e) {
                throw new StorageFormatException("Invalid splitfile type "+s);
            }
            this.fecCodec = FECCodec.getInstance(splitfileType);
            splitfileSingleCryptoAlgorithm = dis.readByte();
            if(!Metadata.isValidSplitfileCryptoAlgorithm(splitfileSingleCryptoAlgorithm))
                throw new StorageFormatException("Invalid splitfile crypto algorithm "+splitfileType);
            if(dis.readBoolean()) {
                splitfileSingleCryptoKey = new byte[32];
                dis.readFully(splitfileSingleCryptoKey);
            } else {
                splitfileSingleCryptoKey = null;
            }
            finalLength = dis.readLong();
            if(finalLength < 0)
                throw new StorageFormatException("Invalid final length "+finalLength);
            decompressedLength = dis.readLong();
            if(decompressedLength < 0)
                throw new StorageFormatException("Invalid decompressed length "+decompressedLength);
            try {
                clientMetadata = ClientMetadata.construct(dis);
            } catch (MetadataParseException e) {
                throw new StorageFormatException("Invalid MIME type");
            }
            int decompressorCount = dis.readInt();
            if(decompressorCount < 0)
                throw new StorageFormatException("Invalid decompressor count "+decompressorCount);
            decompressors = new ArrayList<COMPRESSOR_TYPE>(decompressorCount);
            for(int i=0;i<decompressorCount;i++) {
                short type = dis.readShort();
                COMPRESSOR_TYPE d = COMPRESSOR_TYPE.getCompressorByMetadataID(type);
                if(d == null) throw new StorageFormatException("Invalid decompressor ID "+type);
                decompressors.add(d);
            }
            offsetKeyList = dis.readLong();
            if(offsetKeyList < 0 || offsetKeyList > rafLength)
                throw new StorageFormatException("Invalid offset (key list)");
            offsetSegmentStatus = dis.readLong();
            if(offsetSegmentStatus < 0 || offsetSegmentStatus > rafLength)
                throw new StorageFormatException("Invalid offset (segment status)");
            offsetGeneralProgress = dis.readLong();
            if(offsetGeneralProgress < 0 || offsetGeneralProgress > rafLength)
                throw new StorageFormatException("Invalid offset (general progress)");
            offsetMainBloomFilter = dis.readLong();
            if(offsetMainBloomFilter < 0 || offsetMainBloomFilter > rafLength)
                throw new StorageFormatException("Invalid offset (main bloom filter)");
            offsetSegmentBloomFilters = dis.readLong();
            if(offsetSegmentBloomFilters < 0 || offsetSegmentBloomFilters > rafLength)
                throw new StorageFormatException("Invalid offset (segment bloom filters)");
            offsetOriginalMetadata = dis.readLong();
            if(offsetOriginalMetadata < 0 || offsetOriginalMetadata > rafLength)
                throw new StorageFormatException("Invalid offset (original metadata)");
            offsetOriginalDetails = dis.readLong();
            if(offsetOriginalDetails < 0 || offsetOriginalDetails > rafLength)
                throw new StorageFormatException("Invalid offset (original metadata)");
            offsetBasicSettings = dis.readLong();
            if(offsetBasicSettings != basicSettingsOffset)
                throw new StorageFormatException("Invalid basic settings offset (not the same as computed)");
            if(completeViaTruncation != dis.readBoolean())
                throw new StorageFormatException("Complete via truncation flag is wrong");
            int compatMode = dis.readInt();
            if(compatMode < 0 || compatMode > CompatibilityMode.values().length)
                throw new StorageFormatException("Invalid compatibility mode "+compatMode);
            finalMinCompatMode = CompatibilityMode.values()[compatMode];
            int segmentCount = dis.readInt();
            if(segmentCount < 0) throw new StorageFormatException("Invalid segment count "+segmentCount);
            this.segments = new SplitFileFetcherSegmentStorage[segmentCount];
            int totalDataBlocks = dis.readInt();
            if(totalDataBlocks < 0)
                throw new StorageFormatException("Invalid total data blocks "+totalDataBlocks);
            int totalCheckBlocks = dis.readInt();
            if(totalCheckBlocks < 0)
                throw new StorageFormatException("Invalid total check blocks "+totalDataBlocks);
            int totalCrossCheckBlocks = dis.readInt();
            if(totalCrossCheckBlocks < 0)
                throw new StorageFormatException("Invalid total cross-check blocks "+totalDataBlocks);
            long dataOffset = 0;
            long crossCheckBlocksOffset;
            if(completeViaTruncation) {
                crossCheckBlocksOffset = totalDataBlocks * CHKBlock.DATA_LENGTH;
            } else {
                crossCheckBlocksOffset = 0;
            }
            long segmentKeysOffset = offsetKeyList;
            long segmentStatusOffset = offsetSegmentStatus;
            int countDataBlocks = 0;
            int countCheckBlocks = 0;
            int countCrossCheckBlocks = 0;
            for(int i=0;i<segments.length;i++) {
                segments[i] = new SplitFileFetcherSegmentStorage(this, dis, i, maxRetries != -1,
                        dataOffset, completeViaTruncation ? crossCheckBlocksOffset : -1,
                                segmentKeysOffset, segmentStatusOffset, keysFetching);
                int dataBlocks = segments[i].dataBlocks;
                countDataBlocks += dataBlocks;
                int checkBlocks = segments[i].checkBlocks;
                countCheckBlocks += checkBlocks;
                int crossCheckBlocks = segments[i].crossSegmentCheckBlocks;
                countCrossCheckBlocks += crossCheckBlocks;
                dataOffset += dataBlocks * CHKBlock.DATA_LENGTH;
                if(completeViaTruncation)
                    crossCheckBlocksOffset += crossCheckBlocks * CHKBlock.DATA_LENGTH;
                else
                    dataOffset += crossCheckBlocks * CHKBlock.DATA_LENGTH;
                segmentKeysOffset +=
                    SplitFileFetcherSegmentStorage.storedKeysLength(dataBlocks+crossCheckBlocks, checkBlocks, splitfileSingleCryptoKey != null, checksumLength);
                segmentStatusOffset +=
                    SplitFileFetcherSegmentStorage.paddedStoredSegmentStatusLength(dataBlocks, checkBlocks,
                            crossCheckBlocks, maxRetries != -1, checksumLength, true);
                if(dataOffset > rafLength)
                    throw new StorageFormatException("Data offset past end of file "+dataOffset+" of "+rafLength);
                if(segments[i].segmentCrossCheckBlockDataOffset > rafLength)
                    throw new StorageFormatException("Cross-check blocks offset past end of file "+segments[i].segmentCrossCheckBlockDataOffset+" of "+rafLength);
                if(logDEBUG) Logger.debug(this, "Segment "+i+": data blocks offset "+
                        segments[i].segmentBlockDataOffset+" cross-check blocks offset "+segments[i].segmentCrossCheckBlockDataOffset+" for segment "+i+" of "+this);
            }
            if(countDataBlocks != totalDataBlocks)
                throw new StorageFormatException("Total data blocks "+countDataBlocks+" but expected "+totalDataBlocks);
            if(countCheckBlocks != totalCheckBlocks)
                throw new StorageFormatException("Total check blocks "+countCheckBlocks+" but expected "+totalCheckBlocks);
            if(countCrossCheckBlocks != totalCrossCheckBlocks)
                throw new StorageFormatException("Total cross-check blocks "+countCrossCheckBlocks+" but expected "+totalCrossCheckBlocks);
            int crossSegments = dis.readInt();
            if(crossSegments == 0)
                this.crossSegments = null;
            else
                this.crossSegments = new SplitFileFetcherCrossSegmentStorage[crossSegments];
            for(int i=0;i<crossSegments;i++) {
                this.crossSegments[i] = new SplitFileFetcherCrossSegmentStorage(this, i, dis);
            }
            this.keyListener = new SplitFileFetcherKeyListener(this, fetcher, dis, false, newSalt);
        } catch (IOException e) {
            // We are reading from an array! Bad as written perhaps?
            throw new StorageFormatException("Cannot read basic settings even though passed checksum: "+e, e);
        }
        for(SplitFileFetcherSegmentStorage segment : segments) {
            boolean needsDecode = false;
            try {
                segment.readMetadata();
                if(segment.hasFailed()) {
                    raf.close();
                    raf.free(); // Failed, so free it.
                    throw new FetchException(FetchExceptionMode.SPLITFILE_ERROR, errors);
                }
            } catch (ChecksumFailedException e) {
                Logger.error(this, "Progress for segment "+segment.segNo+" on "+this+" corrupted.");
                needsDecode = true;
            }
            if(segment.needsDecode())
                needsDecode = true;
            if(needsDecode) {
                if(segmentsToTryDecode == null)
                    segmentsToTryDecode = new ArrayList<SplitFileFetcherSegmentStorage>();
                segmentsToTryDecode.add(segment);
            }
        }
        for(int i=0;i<segments.length;i++) {
            SplitFileFetcherSegmentStorage segment = segments[i];
            try {
                segment.readSegmentKeys();
            } catch (ChecksumFailedException e) {
                throw new StorageFormatException("Keys corrupted");
            }
        }
        if(this.crossSegments != null) {
            for(SplitFileFetcherCrossSegmentStorage crossSegment : this.crossSegments)
                // Must be after reading the metadata for the plain segments.
View Full Code Here

        int length;
        try {
            raf.pread(fileOffset, lengthBuf, 0, lengthBuf.length);
            long len = new DataInputStream(new ByteArrayInputStream(lengthBuf)).readLong();
            if(len + fileOffset > rafLength || len > Integer.MAX_VALUE || len < 0)
                throw new StorageFormatException("Bogus length "+len);
            length = (int)len;
            buf = new byte[length];
            raf.pread(fileOffset+lengthBuf.length, buf, 0, length);
            raf.pread(fileOffset+length+lengthBuf.length, checksumBuf, 0, checksumLength);
        } finally {
View Full Code Here

        this.parent = parent;
        this.segNo = segNo;
        this.keyLength = keyLength;
        dataBlockCount = dis.readInt();
        if(dataBlockCount < 0)
            throw new StorageFormatException("Bogus data block count");
        crossCheckBlockCount = dis.readInt();
        if(crossCheckBlockCount < 0)
            throw new StorageFormatException("Bogus cross-check block count");
        if((crossCheckBlockCount == 0) != (parent.crossSegments == null))
            throw new StorageFormatException("Cross-check block count inconsistent with parent");
        checkBlockCount = dis.readInt();
        if(checkBlockCount < 0)
            throw new StorageFormatException("Bogus check block count");
        totalBlockCount = dataBlockCount + crossCheckBlockCount + checkBlockCount;
        if(totalBlockCount > FECCodec.MAX_TOTAL_BLOCKS_PER_SEGMENT)
            throw new StorageFormatException("Bogus total block count");
        this.statusLength = dis.readInt();
        if(statusLength < 0)
            throw new StorageFormatException("Bogus status length");
        crossSegmentBlockSegments = new SplitFileInserterCrossSegmentStorage[crossCheckBlockCount];
        crossSegmentBlockNumbers = new int[crossCheckBlockCount];
        blocksHaveKeys = new boolean[totalBlockCount];
        this.splitfileCryptoAlgorithm = splitfileCryptoAlgorithm;
        this.splitfileCryptoKey = splitfileCryptoKey;
        crossDataBlocksAllocated = new boolean[dataBlockCount + crossCheckBlockCount];
        blockChooser = new SplitFileInserterSegmentBlockChooser(this, totalBlockCount, random,
                maxRetries, keysFetching, consecutiveRNFsCountAsSuccess);
        try {
            CountedOutputStream cos = new CountedOutputStream(new NullOutputStream());
            DataOutputStream dos = new DataOutputStream(cos);
            innerStoreStatus(dos);
            dos.close();
            int minStatusLength = (int) cos.written() + parent.checker.checksumLength();
            if(minStatusLength > statusLength)
                throw new StorageFormatException("Bad status length (too short)");
        } catch (IOException e) {
            throw new Error(e); // Impossible
        }
    }
View Full Code Here

   
    public void readStatus() throws IOException, ChecksumFailedException, StorageFormatException {
        byte[] data = new byte[statusLength-parent.checker.checksumLength()];
        parent.preadChecksummed(parent.getOffsetSegmentStatus(segNo), data, 0, data.length);
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
        if(dis.readInt() != segNo) throw new StorageFormatException("Bad segment number");
        encoded = dis.readBoolean();
        blockChooser.read(dis);
    }
View Full Code Here

        rafLength = raf.size();
        InputStream ois = new RAFInputStream(raf, 0, rafLength);
        DataInputStream dis = new DataInputStream(ois);
        long magic = dis.readLong();
        if(magic != MAGIC)
            throw new StorageFormatException("Bad magic");
        int checksumType = dis.readInt();
        try {
            this.checker = ChecksumChecker.create(checksumType);
        } catch (IllegalArgumentException e) {
            throw new StorageFormatException("Bad checksum type");
        }
        InputStream is = checker.checksumReaderWithLength(ois, new ArrayBucketFactory(), 1024*1024);
        dis = new DataInputStream(is);
        int version = dis.readInt();
        if(version != VERSION)
            throw new StorageFormatException("Bad version");
        LockableRandomAccessBuffer rafOrig = BucketTools.restoreRAFFrom(dis, persistentFG, persistentFileTracker, masterKey);
        if(originalData == null) {
            this.originalData = rafOrig;
        } else {
            // Check that it's the same, but use the passed-in one.
            if(!originalData.equals(rafOrig))
                throw new StorageFormatException("Original data restored from different filename! Expected "+originalData+" but restored "+rafOrig);
            this.originalData = originalData;
        }
        this.totalDataBlocks = dis.readInt();
        if(totalDataBlocks <= 0) throw new StorageFormatException("Bad total data blocks "+totalDataBlocks);
        this.totalCheckBlocks = dis.readInt();
        if(totalCheckBlocks <= 0) throw new StorageFormatException("Bad total data blocks "+totalCheckBlocks);
        try {
            this.splitfileType = SplitfileAlgorithm.getByCode(dis.readShort());
        } catch (IllegalArgumentException e) {
            throw new StorageFormatException("Bad splitfile type");
        }
        try {
            this.codec = FECCodec.getInstance(splitfileType);
        } catch (IllegalArgumentException e) {
            throw new StorageFormatException("Bad splitfile codec type");
        }
        this.dataLength = dis.readLong();
        if(dataLength <= 0) throw new StorageFormatException("Bad data length");
        if(dataLength != originalData.size())
            throw new ResumeFailedException("Original data size is "+originalData.size()+" should be "+dataLength);
        if(((dataLength + CHKBlock.DATA_LENGTH - 1) / CHKBlock.DATA_LENGTH) != totalDataBlocks)
            throw new StorageFormatException("Data blocks "+totalDataBlocks+" not compatible with size "+dataLength);
        decompressedLength = dis.readLong();
        if(decompressedLength <= 0)
            throw new StorageFormatException("Bogus decompressed length");
        isMetadata = dis.readBoolean();
        short atype = dis.readShort();
        if(atype == -1) {
            archiveType = null;
        } else {
            archiveType = ARCHIVE_TYPE.getArchiveType(atype);
            if(archiveType == null) throw new StorageFormatException("Unknown archive type "+atype);
        }
        try {
            clientMetadata = ClientMetadata.construct(dis);
        } catch (MetadataParseException e) {
            throw new StorageFormatException("Failed to read MIME type: "+e);
        }
        short codec = dis.readShort();
        if(codec == (short)-1)
            compressionCodec = null;
        else {
            compressionCodec = COMPRESSOR_TYPE.getCompressorByMetadataID(codec);
            if(compressionCodec == null)
                throw new StorageFormatException("Unknown compression codec ID "+codec);
        }
        int segmentCount = dis.readInt();
        if(segmentCount <= 0) throw new StorageFormatException("Bad segment count");
        this.segmentSize = dis.readInt();
        if(segmentSize <= 0) throw new StorageFormatException("Bad segment size");
        this.checkSegmentSize = dis.readInt();
        if(checkSegmentSize <= 0) throw new StorageFormatException("Bad check segment size");
        this.crossCheckBlocks = dis.readInt();
        if(crossCheckBlocks < 0) throw new StorageFormatException("Bad cross-check block count");
        if(segmentSize + checkSegmentSize + crossCheckBlocks > FECCodec.MAX_TOTAL_BLOCKS_PER_SEGMENT)
            throw new StorageFormatException("Must be no more than "+FECCodec.MAX_TOTAL_BLOCKS_PER_SEGMENT+" blocks per segment");
        this.splitfileCryptoAlgorithm = dis.readByte();
        if(!Metadata.isValidSplitfileCryptoAlgorithm(splitfileCryptoAlgorithm))
            throw new StorageFormatException("Invalid splitfile crypto algorithm "+splitfileCryptoAlgorithm);
        if(dis.readBoolean()) {
            splitfileCryptoKey = new byte[32];
            dis.readFully(splitfileCryptoKey);
        } else {
            splitfileCryptoKey = null;
        }
        this.keyLength = dis.readInt(); // FIXME validate
        if(keyLength < SplitFileInserterSegmentStorage.getKeyLength(this))
            throw new StorageFormatException("Invalid key length "+keyLength+" should be at least "+
                    SplitFileInserterSegmentStorage.getKeyLength(this));
        int compatMode = dis.readInt();
        if(compatMode < 0 || compatMode > CompatibilityMode.values().length)
            throw new StorageFormatException("Invalid compatibility mode "+compatMode);
        this.cmode = CompatibilityMode.values()[compatMode];
        this.deductBlocksFromSegments = dis.readInt();
        if(deductBlocksFromSegments < 0 || deductBlocksFromSegments > segmentCount)
            throw new StorageFormatException("Bad deductBlocksFromSegments");
        this.maxRetries = dis.readInt();
        if(maxRetries < -1) throw new StorageFormatException("Bad maxRetries");
        this.consecutiveRNFsCountAsSuccess = dis.readInt();
        if(consecutiveRNFsCountAsSuccess < 0)
            throw new StorageFormatException("Bad consecutiveRNFsCountAsSuccess");
        specifySplitfileKeyInMetadata = dis.readBoolean();
        if(dis.readBoolean()) {
            hashThisLayerOnly = new byte[32];
            dis.readFully(hashThisLayerOnly);
        } else {
            hashThisLayerOnly = null;
        }
        topDontCompress = dis.readBoolean();
        topRequiredBlocks = dis.readInt();
        topTotalBlocks = dis.readInt();
        origDataSize = dis.readLong();
        origCompressedDataSize = dis.readLong();
        hashes = HashResult.readHashes(dis);
        dis.close();
        this.hasPaddedLastBlock = (dataLength % CHKBlock.DATA_LENGTH != 0);
        this.segments = new SplitFileInserterSegmentStorage[segmentCount];
        if(crossCheckBlocks != 0)
            this.crossSegments = new SplitFileInserterCrossSegmentStorage[segmentCount];
        else
            crossSegments = null;
        // Read offsets.
        is = checker.checksumReaderWithLength(ois, new ArrayBucketFactory(), 1024*1024);
        dis = new DataInputStream(is);
        if(hasPaddedLastBlock) {
            offsetPaddedLastBlock = readOffset(dis, rafLength, "offsetPaddedLastBlock");
        } else {
            offsetPaddedLastBlock = 0;
        }
        offsetOverallStatus = readOffset(dis, rafLength, "offsetOverallStatus");
        overallStatusLength = dis.readInt();
        if(overallStatusLength < 0) throw new StorageFormatException("Negative overall status length");
        if(overallStatusLength < FailureCodeTracker.getFixedLength(true))
            throw new StorageFormatException("Bad overall status length");
        // Will be read after offsets
        if(crossSegments != null) {
            offsetCrossSegmentBlocks = new long[crossSegments.length];
            for(int i=0;i<crossSegments.length;i++)
                offsetCrossSegmentBlocks[i] = readOffset(dis, rafLength, "cross-segment block offset");
        } else {
            offsetCrossSegmentBlocks = null;
        }
        offsetSegmentCheckBlocks = new long[segmentCount];
        for(int i=0;i<segmentCount;i++)
            offsetSegmentCheckBlocks[i] = readOffset(dis, rafLength, "segment check block offset");
        offsetSegmentStatus = new long[segmentCount];
        for(int i=0;i<segmentCount;i++)
            offsetSegmentStatus[i] = readOffset(dis, rafLength, "segment status offset");
        if(crossSegments != null) {
            offsetCrossSegmentStatus = new long[crossSegments.length];
            for(int i=0;i<crossSegments.length;i++)
                offsetCrossSegmentStatus[i] = readOffset(dis, rafLength, "cross-segment status offset");
        } else {
            offsetCrossSegmentStatus = null;
        }
        offsetSegmentKeys = new long[segmentCount];
        for(int i=0;i<segmentCount;i++)
            offsetSegmentKeys[i] = readOffset(dis, rafLength, "segment keys offset");
        dis.close();
        // Set up segments...
        underlyingOffsetDataSegments = new long[segmentCount];
        is = checker.checksumReaderWithLength(ois, new ArrayBucketFactory(), 1024*1024);
        dis = new DataInputStream(is);
        int blocks = 0;
        for(int i=0;i<segmentCount;i++) {
            segments[i] = new SplitFileInserterSegmentStorage(this, dis, i, keyLength,
                    splitfileCryptoAlgorithm, splitfileCryptoKey, random, maxRetries, consecutiveRNFsCountAsSuccess, keysFetching);
            underlyingOffsetDataSegments[i] = blocks * CHKBlock.DATA_LENGTH;
            blocks += segments[i].dataBlockCount;
            assert(underlyingOffsetDataSegments[i] < dataLength);
        }
        dis.close();
        if(blocks != totalDataBlocks)
            throw new StorageFormatException("Total data blocks should be "+totalDataBlocks+" but is "+blocks);
        if(crossSegments != null) {
            is = checker.checksumReaderWithLength(ois, new ArrayBucketFactory(), 1024*1024);
            dis = new DataInputStream(is);
            for(int i=0;i<crossSegments.length;i++) {
                crossSegments[i] = new SplitFileInserterCrossSegmentStorage(this, dis, i);
View Full Code Here

        // Last 3 statuses are only used during completion.
    }

    private long readOffset(DataInputStream dis, long rafLength, String error) throws IOException, StorageFormatException {
        long l = dis.readLong();
        if(l < 0) throw new StorageFormatException("Negative "+error);
        if(l > rafLength) throw new StorageFormatException("Too big "+error);
        return l;
    }
View Full Code Here

        int length;
        try {
            raf.pread(fileOffset, lengthBuf, 0, lengthBuf.length);
            long len = new DataInputStream(new ByteArrayInputStream(lengthBuf)).readLong();
            if(len + fileOffset > rafLength || len > Integer.MAX_VALUE || len < 0)
                throw new StorageFormatException("Bogus length "+len);
            length = (int)len;
            buf = new byte[length];
            raf.pread(fileOffset+lengthBuf.length, buf, 0, length);
            raf.pread(fileOffset+length+lengthBuf.length, checksumBuf, 0, checker.checksumLength());
        } finally {
View Full Code Here

    public AEADCryptBucket(DataInputStream dis, FilenameGenerator fg,
            PersistentFileTracker persistentFileTracker, MasterSecret masterKey)
    throws IOException, StorageFormatException, ResumeFailedException {
        // Magic already read by caller.
        int version = dis.readInt();
        if(version != VERSION) throw new StorageFormatException("Unknown version "+version);
        int keyLength = dis.readByte();
        if(keyLength < 0 || !(keyLength == 16 || keyLength == 24 || keyLength == 32))
            throw new StorageFormatException("Unknown key length "+keyLength); // FIXME validate this in a more permanent way
        key = new byte[keyLength];
        dis.readFully(key);
        readOnly = dis.readBoolean();
        underlying = BucketTools.restoreFrom(dis, fg, persistentFileTracker, masterKey);
    }
View Full Code Here

TOP

Related Classes of freenet.support.io.StorageFormatException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.