001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one or more
003 *  contributor license agreements.  See the NOTICE file distributed with
004 *  this work for additional information regarding copyright ownership.
005 *  The ASF licenses this file to You under the Apache License, Version 2.0
006 *  (the "License"); you may not use this file except in compliance with
007 *  the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.commons.compress.utils;
019
020import java.io.IOException;
021import java.io.InputStream;
022import java.nio.Buffer;
023import java.nio.ByteBuffer;
024
025/**
026 * NIO backed bounded input stream for reading a predefined amount of data from.
027 * @ThreadSafe this base class is thread safe but implementations must not be.
028 * @since 1.21
029 */
030public abstract class BoundedArchiveInputStream extends InputStream {
031
032    private final long end;
033    private ByteBuffer singleByteBuffer;
034    private long loc;
035
036    /**
037     * Create a new bounded input stream.
038     *
039     * @param start     position in the stream from where the reading of this bounded stream starts.
040     * @param remaining amount of bytes which are allowed to read from the bounded stream.
041     */
042    public BoundedArchiveInputStream(final long start, final long remaining) {
043        this.end = start + remaining;
044        if (this.end < start) {
045            // check for potential vulnerability due to overflow
046            throw new IllegalArgumentException("Invalid length of stream at offset=" + start + ", length=" + remaining);
047        }
048        loc = start;
049    }
050
051    @Override
052    public synchronized int read() throws IOException {
053        if (loc >= end) {
054            return -1;
055        }
056        if (singleByteBuffer == null) {
057            singleByteBuffer = ByteBuffer.allocate(1);
058        } else {
059            ((Buffer)singleByteBuffer).rewind();
060        }
061        int read = read(loc, singleByteBuffer);
062        if (read < 1) {
063            return -1;
064        }
065        loc++;
066        return singleByteBuffer.get() & 0xff;
067    }
068
069    @Override
070    public synchronized int read(final byte[] b, final int off, int len) throws IOException {
071        if (loc >= end) {
072            return -1;
073        }
074        final long maxLen = Math.min(len, end - loc);
075        if (maxLen <= 0) {
076            return 0;
077        }
078        if (off < 0 || off > b.length || maxLen > b.length - off) {
079            throw new IndexOutOfBoundsException("offset or len are out of bounds");
080        }
081
082        ByteBuffer buf = ByteBuffer.wrap(b, off, (int) maxLen);
083        int ret = read(loc, buf);
084        if (ret > 0) {
085            loc += ret;
086        }
087        return ret;
088    }
089
090    /**
091     * Read content of the stream into a {@link ByteBuffer}.
092     * @param pos position to start the read.
093     * @param buf buffer to add the read content.
094     * @return number of read bytes.
095     * @throws IOException if I/O fails.
096     */
097    protected abstract int read(long pos, ByteBuffer buf) throws IOException;
098}