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.ByteBuffer;
023
024/**
025 * NIO backed bounded input stream for reading a predefined amount of data from.
026 * @ThreadSafe this base class is thread safe but implementations must not be.
027 * @since 1.21
028 */
029public abstract class BoundedArchiveInputStream extends InputStream {
030
031    private final long end;
032    private ByteBuffer singleByteBuffer;
033    private long loc;
034
035    /**
036     * Create a new bounded input stream.
037     *
038     * @param start     position in the stream from where the reading of this bounded stream starts.
039     * @param remaining amount of bytes which are allowed to read from the bounded stream.
040     */
041    public BoundedArchiveInputStream(final long start, final long remaining) {
042        this.end = start + remaining;
043        if (this.end < start) {
044            // check for potential vulnerability due to overflow
045            throw new IllegalArgumentException("Invalid length of stream at offset=" + start + ", length=" + remaining);
046        }
047        loc = start;
048    }
049
050    @Override
051    public synchronized int read() throws IOException {
052        if (loc >= end) {
053            return -1;
054        }
055        if (singleByteBuffer == null) {
056            singleByteBuffer = ByteBuffer.allocate(1);
057        } else {
058            singleByteBuffer.rewind();
059        }
060        int read = read(loc, singleByteBuffer);
061        if (read < 1) {
062            return -1;
063        }
064        loc++;
065        return singleByteBuffer.get() & 0xff;
066    }
067
068    @Override
069    public synchronized int read(final byte[] b, final int off, int len) throws IOException {
070        if (loc >= end) {
071            return -1;
072        }
073        final long maxLen = Math.min(len, end - loc);
074        if (maxLen <= 0) {
075            return 0;
076        }
077        if (off < 0 || off > b.length || maxLen > b.length - off) {
078            throw new IndexOutOfBoundsException("offset or len are out of bounds");
079        }
080
081        ByteBuffer buf = ByteBuffer.wrap(b, off, (int) maxLen);
082        int ret = read(loc, buf);
083        if (ret > 0) {
084            loc += ret;
085        }
086        return ret;
087    }
088
089    /**
090     * Read content of the stream into a {@link ByteBuffer}.
091     * @param pos position to start the read.
092     * @param buf buffer to add the read content.
093     * @return number of read bytes.
094     * @throws IOException if I/O fails.
095     */
096    protected abstract int read(long pos, ByteBuffer buf) throws IOException;
097}