001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.compress.compressors.snappy;
020
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.PushbackInputStream;
024import java.util.Arrays;
025
026import org.apache.commons.compress.compressors.CompressorInputStream;
027import org.apache.commons.compress.utils.BoundedInputStream;
028import org.apache.commons.compress.utils.ByteUtils;
029import org.apache.commons.compress.utils.CountingInputStream;
030import org.apache.commons.compress.utils.IOUtils;
031import org.apache.commons.compress.utils.InputStreamStatistics;
032
033/**
034 * CompressorInputStream for the framing Snappy format.
035 *
036 * <p>Based on the "spec" in the version "Last revised: 2013-10-25"</p>
037 *
038 * @see <a href="https://github.com/google/snappy/blob/master/framing_format.txt">Snappy framing format description</a>
039 * @since 1.7
040 */
041public class FramedSnappyCompressorInputStream extends CompressorInputStream
042    implements InputStreamStatistics {
043
044    /**
045     * package private for tests only.
046     */
047    static final long MASK_OFFSET = 0xa282ead8L;
048
049    private static final int STREAM_IDENTIFIER_TYPE = 0xff;
050    static final int COMPRESSED_CHUNK_TYPE = 0;
051    private static final int UNCOMPRESSED_CHUNK_TYPE = 1;
052    private static final int PADDING_CHUNK_TYPE = 0xfe;
053    private static final int MIN_UNSKIPPABLE_TYPE = 2;
054    private static final int MAX_UNSKIPPABLE_TYPE = 0x7f;
055    private static final int MAX_SKIPPABLE_TYPE = 0xfd;
056
057    // used by FramedSnappyCompressorOutputStream as well
058    static final byte[] SZ_SIGNATURE = new byte[] { //NOSONAR
059        (byte) STREAM_IDENTIFIER_TYPE, // tag
060        6, 0, 0, // length
061        's', 'N', 'a', 'P', 'p', 'Y'
062    };
063
064    private long unreadBytes;
065    private final CountingInputStream countingStream;
066
067    /** The underlying stream to read compressed data from */
068    private final PushbackInputStream in;
069
070    /** The dialect to expect */
071    private final FramedSnappyDialect dialect;
072
073    private SnappyCompressorInputStream currentCompressedChunk;
074
075    // used in no-arg read method
076    private final byte[] oneByte = new byte[1];
077
078    private boolean endReached, inUncompressedChunk;
079
080    private int uncompressedBytesRemaining;
081    private long expectedChecksum = -1;
082    private final int blockSize;
083    private final PureJavaCrc32C checksum = new PureJavaCrc32C();
084
085    private final ByteUtils.ByteSupplier supplier = new ByteUtils.ByteSupplier() {
086        @Override
087        public int getAsByte() throws IOException {
088            return readOneByte();
089        }
090    };
091
092    /**
093     * Constructs a new input stream that decompresses
094     * snappy-framed-compressed data from the specified input stream
095     * using the {@link FramedSnappyDialect#STANDARD} dialect.
096     * @param in  the InputStream from which to read the compressed data
097     * @throws IOException if reading fails
098     */
099    public FramedSnappyCompressorInputStream(final InputStream in) throws IOException {
100        this(in, FramedSnappyDialect.STANDARD);
101    }
102
103    /**
104     * Constructs a new input stream that decompresses snappy-framed-compressed data
105     * from the specified input stream.
106     * @param in  the InputStream from which to read the compressed data
107     * @param dialect the dialect used by the compressed stream
108     * @throws IOException if reading fails
109     */
110    public FramedSnappyCompressorInputStream(final InputStream in,
111                                             final FramedSnappyDialect dialect)
112        throws IOException {
113        this(in, SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE, dialect);
114    }
115
116    /**
117     * Constructs a new input stream that decompresses snappy-framed-compressed data
118     * from the specified input stream.
119     * @param in  the InputStream from which to read the compressed data
120     * @param blockSize the block size to use for the compressed stream
121     * @param dialect the dialect used by the compressed stream
122     * @throws IOException if reading fails
123     * @since 1.14
124     */
125    public FramedSnappyCompressorInputStream(final InputStream in,
126                                             final int blockSize,
127                                             final FramedSnappyDialect dialect)
128        throws IOException {
129        countingStream = new CountingInputStream(in);
130        this.in = new PushbackInputStream(countingStream, 1);
131        this.blockSize = blockSize;
132        this.dialect = dialect;
133        if (dialect.hasStreamIdentifier()) {
134            readStreamIdentifier();
135        }
136    }
137
138    /** {@inheritDoc} */
139    @Override
140    public int read() throws IOException {
141        return read(oneByte, 0, 1) == -1 ? -1 : oneByte[0] & 0xFF;
142    }
143
144    /** {@inheritDoc} */
145    @Override
146    public void close() throws IOException {
147        if (currentCompressedChunk != null) {
148            currentCompressedChunk.close();
149            currentCompressedChunk = null;
150        }
151        in.close();
152    }
153
154    /** {@inheritDoc} */
155    @Override
156    public int read(final byte[] b, final int off, final int len) throws IOException {
157        int read = readOnce(b, off, len);
158        if (read == -1) {
159            readNextBlock();
160            if (endReached) {
161                return -1;
162            }
163            read = readOnce(b, off, len);
164        }
165        return read;
166    }
167
168    /** {@inheritDoc} */
169    @Override
170    public int available() throws IOException {
171        if (inUncompressedChunk) {
172            return Math.min(uncompressedBytesRemaining,
173                            in.available());
174        } else if (currentCompressedChunk != null) {
175            return currentCompressedChunk.available();
176        }
177        return 0;
178    }
179
180    /**
181     * @since 1.17
182     */
183    @Override
184    public long getCompressedCount() {
185        return countingStream.getBytesRead() - unreadBytes;
186    }
187
188    /**
189     * Read from the current chunk into the given array.
190     *
191     * @return -1 if there is no current chunk or the number of bytes
192     * read from the current chunk (which may be -1 if the end of the
193     * chunk is reached).
194     */
195    private int readOnce(final byte[] b, final int off, final int len) throws IOException {
196        int read = -1;
197        if (inUncompressedChunk) {
198            final int amount = Math.min(uncompressedBytesRemaining, len);
199            if (amount == 0) {
200                return -1;
201            }
202            read = in.read(b, off, amount);
203            if (read != -1) {
204                uncompressedBytesRemaining -= read;
205                count(read);
206            }
207        } else if (currentCompressedChunk != null) {
208            final long before = currentCompressedChunk.getBytesRead();
209            read = currentCompressedChunk.read(b, off, len);
210            if (read == -1) {
211                currentCompressedChunk.close();
212                currentCompressedChunk = null;
213            } else {
214                count(currentCompressedChunk.getBytesRead() - before);
215            }
216        }
217        if (read > 0) {
218            checksum.update(b, off, read);
219        }
220        return read;
221    }
222
223    private void readNextBlock() throws IOException {
224        verifyLastChecksumAndReset();
225        inUncompressedChunk = false;
226        final int type = readOneByte();
227        if (type == -1) {
228            endReached = true;
229        } else if (type == STREAM_IDENTIFIER_TYPE) {
230            in.unread(type);
231            unreadBytes++;
232            pushedBackBytes(1);
233            readStreamIdentifier();
234            readNextBlock();
235        } else if (type == PADDING_CHUNK_TYPE
236                   || (type > MAX_UNSKIPPABLE_TYPE && type <= MAX_SKIPPABLE_TYPE)) {
237            skipBlock();
238            readNextBlock();
239        } else if (type >= MIN_UNSKIPPABLE_TYPE && type <= MAX_UNSKIPPABLE_TYPE) {
240            throw new IOException("unskippable chunk with type " + type
241                                  + " (hex " + Integer.toHexString(type) + ")"
242                                  + " detected.");
243        } else if (type == UNCOMPRESSED_CHUNK_TYPE) {
244            inUncompressedChunk = true;
245            uncompressedBytesRemaining = readSize() - 4 /* CRC */;
246            expectedChecksum = unmask(readCrc());
247        } else if (type == COMPRESSED_CHUNK_TYPE) {
248            final boolean expectChecksum = dialect.usesChecksumWithCompressedChunks();
249            final long size = readSize() - (expectChecksum ? 4L : 0L);
250            if (expectChecksum) {
251                expectedChecksum = unmask(readCrc());
252            } else {
253                expectedChecksum = -1;
254            }
255            currentCompressedChunk =
256                new SnappyCompressorInputStream(new BoundedInputStream(in, size), blockSize);
257            // constructor reads uncompressed size
258            count(currentCompressedChunk.getBytesRead());
259        } else {
260            // impossible as all potential byte values have been covered
261            throw new IOException("unknown chunk type " + type
262                                  + " detected.");
263        }
264    }
265
266    private long readCrc() throws IOException {
267        final byte[] b = new byte[4];
268        final int read = IOUtils.readFully(in, b);
269        count(read);
270        if (read != 4) {
271            throw new IOException("premature end of stream");
272        }
273        return ByteUtils.fromLittleEndian(b);
274    }
275
276    static long unmask(long x) {
277        // ugly, maybe we should just have used ints and deal with the
278        // overflow
279        x -= MASK_OFFSET;
280        x &= 0xffffFFFFL;
281        return ((x >> 17) | (x << 15)) & 0xffffFFFFL;
282    }
283
284    private int readSize() throws IOException {
285        return (int) ByteUtils.fromLittleEndian(supplier, 3);
286    }
287
288    private void skipBlock() throws IOException {
289        final int size = readSize();
290        final long read = IOUtils.skip(in, size);
291        count(read);
292        if (read != size) {
293            throw new IOException("premature end of stream");
294        }
295    }
296
297    private void readStreamIdentifier() throws IOException {
298        final byte[] b = new byte[10];
299        final int read = IOUtils.readFully(in, b);
300        count(read);
301        if (10 != read || !matches(b, 10)) {
302            throw new IOException("Not a framed Snappy stream");
303        }
304    }
305
306    private int readOneByte() throws IOException {
307        final int b = in.read();
308        if (b != -1) {
309            count(1);
310            return b & 0xFF;
311        }
312        return -1;
313    }
314
315    private void verifyLastChecksumAndReset() throws IOException {
316        if (expectedChecksum >= 0 && expectedChecksum != checksum.getValue()) {
317            throw new IOException("Checksum verification failed");
318        }
319        expectedChecksum = -1;
320        checksum.reset();
321    }
322
323    /**
324     * Checks if the signature matches what is expected for a .sz file.
325     *
326     * <p>.sz files start with a chunk with tag 0xff and content sNaPpY.</p>
327     *
328     * @param signature the bytes to check
329     * @param length    the number of bytes to check
330     * @return          true if this is a .sz stream, false otherwise
331     */
332    public static boolean matches(final byte[] signature, final int length) {
333
334        if (length < SZ_SIGNATURE.length) {
335            return false;
336        }
337
338        byte[] shortenedSig = signature;
339        if (signature.length > SZ_SIGNATURE.length) {
340            shortenedSig = new byte[SZ_SIGNATURE.length];
341            System.arraycopy(signature, 0, shortenedSig, 0, SZ_SIGNATURE.length);
342        }
343
344        return Arrays.equals(shortenedSig, SZ_SIGNATURE);
345    }
346
347}