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.lz4;
020
021import java.io.IOException;
022import java.io.InputStream;
023import java.util.Arrays;
024
025import org.apache.commons.compress.compressors.CompressorInputStream;
026import org.apache.commons.compress.utils.BoundedInputStream;
027import org.apache.commons.compress.utils.ByteUtils;
028import org.apache.commons.compress.utils.ChecksumCalculatingInputStream;
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 LZ4 frame format.
035 *
036 * <p>Based on the "spec" in the version "1.5.1 (31/03/2015)"</p>
037 *
038 * @see <a href="http://lz4.github.io/lz4/lz4_Frame_format.html">LZ4 Frame Format Description</a>
039 * @since 1.14
040 * @NotThreadSafe
041 */
042public class FramedLZ4CompressorInputStream extends CompressorInputStream
043    implements InputStreamStatistics {
044
045    // used by FramedLZ4CompressorOutputStream as well
046    static final byte[] LZ4_SIGNATURE = new byte[] { //NOSONAR
047        4, 0x22, 0x4d, 0x18
048    };
049    private static final byte[] SKIPPABLE_FRAME_TRAILER = new byte[] {
050        0x2a, 0x4d, 0x18
051    };
052    private static final byte SKIPPABLE_FRAME_PREFIX_BYTE_MASK = 0x50;
053
054    static final int VERSION_MASK = 0xC0;
055    static final int SUPPORTED_VERSION = 0x40;
056    static final int BLOCK_INDEPENDENCE_MASK = 0x20;
057    static final int BLOCK_CHECKSUM_MASK = 0x10;
058    static final int CONTENT_SIZE_MASK = 0x08;
059    static final int CONTENT_CHECKSUM_MASK = 0x04;
060    static final int BLOCK_MAX_SIZE_MASK = 0x70;
061    static final int UNCOMPRESSED_FLAG_MASK = 0x80000000;
062
063    // used in no-arg read method
064    private final byte[] oneByte = new byte[1];
065
066    private final ByteUtils.ByteSupplier supplier = new ByteUtils.ByteSupplier() {
067        @Override
068        public int getAsByte() throws IOException {
069            return readOneByte();
070        }
071    };
072
073    private final CountingInputStream in;
074    private final boolean decompressConcatenated;
075
076    private boolean expectBlockChecksum;
077    private boolean expectBlockDependency;
078    private boolean expectContentSize;
079    private boolean expectContentChecksum;
080
081    private InputStream currentBlock;
082    private boolean endReached, inUncompressed;
083
084    // used for frame header checksum and content checksum, if present
085    private final XXHash32 contentHash = new XXHash32();
086
087    // used for block checksum, if present
088    private final XXHash32 blockHash = new XXHash32();
089
090    // only created if the frame doesn't set the block independence flag
091    private byte[] blockDependencyBuffer;
092
093    /**
094     * Creates a new input stream that decompresses streams compressed
095     * using the LZ4 frame format and stops after decompressing the
096     * first frame.
097     * @param in  the InputStream from which to read the compressed data
098     * @throws IOException if reading fails
099     */
100    public FramedLZ4CompressorInputStream(InputStream in) throws IOException {
101        this(in, false);
102    }
103
104    /**
105     * Creates a new input stream that decompresses streams compressed
106     * using the LZ4 frame format.
107     * @param in  the InputStream from which to read the compressed data
108     * @param decompressConcatenated if true, decompress until the end
109     *          of the input; if false, stop after the first LZ4 frame
110     *          and leave the input position to point to the next byte
111     *          after the frame stream
112     * @throws IOException if reading fails
113     */
114    public FramedLZ4CompressorInputStream(InputStream in, boolean decompressConcatenated) throws IOException {
115        this.in = new CountingInputStream(in);
116        this.decompressConcatenated = decompressConcatenated;
117        init(true);
118    }
119
120    /** {@inheritDoc} */
121    @Override
122    public int read() throws IOException {
123        return read(oneByte, 0, 1) == -1 ? -1 : oneByte[0] & 0xFF;
124    }
125
126    /** {@inheritDoc} */
127    @Override
128    public void close() throws IOException {
129        if (currentBlock != null) {
130            currentBlock.close();
131            currentBlock = null;
132        }
133        in.close();
134    }
135
136    /** {@inheritDoc} */
137    @Override
138    public int read(final byte[] b, final int off, final int len) throws IOException {
139        if (endReached) {
140            return -1;
141        }
142        int r = readOnce(b, off, len);
143        if (r == -1) {
144            nextBlock();
145            if (!endReached) {
146                r = readOnce(b, off, len);
147            }
148        }
149        if (r != -1) {
150            if (expectBlockDependency) {
151                appendToBlockDependencyBuffer(b, off, r);
152            }
153            if (expectContentChecksum) {
154                contentHash.update(b, off, r);
155            }
156        }
157        return r;
158    }
159
160    /**
161     * @since 1.17
162     */
163    @Override
164    public long getCompressedCount() {
165        return in.getBytesRead();
166    }
167
168    private void init(boolean firstFrame) throws IOException {
169        if (readSignature(firstFrame)) {
170            readFrameDescriptor();
171            nextBlock();
172        }
173    }
174
175    private boolean readSignature(boolean firstFrame) throws IOException {
176        String garbageMessage = firstFrame ? "Not a LZ4 frame stream" : "LZ4 frame stream followed by garbage";
177        final byte[] b = new byte[4];
178        int read = IOUtils.readFully(in, b);
179        count(read);
180        if (0 == read && !firstFrame) {
181            // good LZ4 frame and nothing after it
182            endReached = true;
183            return false;
184        }
185        if (4 != read) {
186            throw new IOException(garbageMessage);
187        }
188
189        read = skipSkippableFrame(b);
190        if (0 == read && !firstFrame) {
191            // good LZ4 frame with only some skippable frames after it
192            endReached = true;
193            return false;
194        }
195        if (4 != read || !matches(b, 4)) {
196            throw new IOException(garbageMessage);
197        }
198        return true;
199    }
200
201    private void readFrameDescriptor() throws IOException {
202        int flags = readOneByte();
203        if (flags == -1) {
204            throw new IOException("Premature end of stream while reading frame flags");
205        }
206        contentHash.update(flags);
207        if ((flags & VERSION_MASK) != SUPPORTED_VERSION) {
208            throw new IOException("Unsupported version " + (flags >> 6));
209        }
210        expectBlockDependency = (flags & BLOCK_INDEPENDENCE_MASK) == 0;
211        if (expectBlockDependency) {
212            if (blockDependencyBuffer == null) {
213                blockDependencyBuffer = new byte[BlockLZ4CompressorInputStream.WINDOW_SIZE];
214            }
215        } else {
216            blockDependencyBuffer = null;
217        }
218        expectBlockChecksum = (flags & BLOCK_CHECKSUM_MASK) != 0;
219        expectContentSize = (flags & CONTENT_SIZE_MASK) != 0;
220        expectContentChecksum = (flags & CONTENT_CHECKSUM_MASK) != 0;
221        int bdByte = readOneByte();
222        if (bdByte == -1) { // max size is irrelevant for this implementation
223            throw new IOException("Premature end of stream while reading frame BD byte");
224        }
225        contentHash.update(bdByte);
226        if (expectContentSize) { // for now we don't care, contains the uncompressed size
227            byte[] contentSize = new byte[8];
228            int skipped = IOUtils.readFully(in, contentSize);
229            count(skipped);
230            if (8 != skipped) {
231                throw new IOException("Premature end of stream while reading content size");
232            }
233            contentHash.update(contentSize, 0, contentSize.length);
234        }
235        int headerHash = readOneByte();
236        if (headerHash == -1) { // partial hash of header.
237            throw new IOException("Premature end of stream while reading frame header checksum");
238        }
239        int expectedHash = (int) ((contentHash.getValue() >> 8) & 0xff);
240        contentHash.reset();
241        if (headerHash != expectedHash) {
242            throw new IOException("frame header checksum mismatch.");
243        }
244    }
245
246    private void nextBlock() throws IOException {
247        maybeFinishCurrentBlock();
248        long len = ByteUtils.fromLittleEndian(supplier, 4);
249        boolean uncompressed = (len & UNCOMPRESSED_FLAG_MASK) != 0;
250        int realLen = (int) (len & (~UNCOMPRESSED_FLAG_MASK));
251        if (realLen == 0) {
252            verifyContentChecksum();
253            if (!decompressConcatenated) {
254                endReached = true;
255            } else {
256                init(false);
257            }
258            return;
259        }
260        InputStream capped = new BoundedInputStream(in, realLen);
261        if (expectBlockChecksum) {
262            capped = new ChecksumCalculatingInputStream(blockHash, capped);
263        }
264        if (uncompressed) {
265            inUncompressed = true;
266            currentBlock = capped;
267        } else {
268            inUncompressed = false;
269            BlockLZ4CompressorInputStream s = new BlockLZ4CompressorInputStream(capped);
270            if (expectBlockDependency) {
271                s.prefill(blockDependencyBuffer);
272            }
273            currentBlock = s;
274        }
275    }
276
277    private void maybeFinishCurrentBlock() throws IOException {
278        if (currentBlock != null) {
279            currentBlock.close();
280            currentBlock = null;
281            if (expectBlockChecksum) {
282                verifyChecksum(blockHash, "block");
283                blockHash.reset();
284            }
285        }
286    }
287
288    private void verifyContentChecksum() throws IOException {
289        if (expectContentChecksum) {
290            verifyChecksum(contentHash, "content");
291        }
292        contentHash.reset();
293    }
294
295    private void verifyChecksum(XXHash32 hash, String kind) throws IOException {
296        byte[] checksum = new byte[4];
297        int read = IOUtils.readFully(in, checksum);
298        count(read);
299        if (4 != read) {
300            throw new IOException("Premature end of stream while reading " + kind + " checksum");
301        }
302        long expectedHash = hash.getValue();
303        if (expectedHash != ByteUtils.fromLittleEndian(checksum)) {
304            throw new IOException(kind + " checksum mismatch.");
305        }
306    }
307
308    private int readOneByte() throws IOException {
309        final int b = in.read();
310        if (b != -1) {
311            count(1);
312            return b & 0xFF;
313        }
314        return -1;
315    }
316
317    private int readOnce(byte[] b, int off, int len) throws IOException {
318        if (inUncompressed) {
319            int cnt = currentBlock.read(b, off, len);
320            count(cnt);
321            return cnt;
322        }
323        BlockLZ4CompressorInputStream l = (BlockLZ4CompressorInputStream) currentBlock;
324        long before = l.getBytesRead();
325        int cnt = currentBlock.read(b, off, len);
326        count(l.getBytesRead() - before);
327        return cnt;
328    }
329
330    private static boolean isSkippableFrameSignature(byte[] b) {
331        if ((b[0] & SKIPPABLE_FRAME_PREFIX_BYTE_MASK) != SKIPPABLE_FRAME_PREFIX_BYTE_MASK) {
332            return false;
333        }
334        for (int i = 1; i < 4; i++) {
335            if (b[i] != SKIPPABLE_FRAME_TRAILER[i - 1]) {
336                return false;
337            }
338        }
339        return true;
340    }
341
342    /**
343     * Skips over the contents of a skippable frame as well as
344     * skippable frames following it.
345     *
346     * <p>It then tries to read four more bytes which are supposed to
347     * hold an LZ4 signature and returns the number of bytes read
348     * while storing the bytes in the given array.</p>
349     */
350    private int skipSkippableFrame(byte[] b) throws IOException {
351        int read = 4;
352        while (read == 4 && isSkippableFrameSignature(b)) {
353            long len = ByteUtils.fromLittleEndian(supplier, 4);
354            long skipped = IOUtils.skip(in, len);
355            count(skipped);
356            if (len != skipped) {
357                throw new IOException("Premature end of stream while skipping frame");
358            }
359            read = IOUtils.readFully(in, b);
360            count(read);
361        }
362        return read;
363    }
364
365    private void appendToBlockDependencyBuffer(final byte[] b, final int off, int len) {
366        len = Math.min(len, blockDependencyBuffer.length);
367        if (len > 0) {
368            int keep = blockDependencyBuffer.length - len;
369            if (keep > 0) {
370                // move last keep bytes towards the start of the buffer
371                System.arraycopy(blockDependencyBuffer, len, blockDependencyBuffer, 0, keep);
372            }
373            // append new data
374            System.arraycopy(b, off, blockDependencyBuffer, keep, len);
375        }
376    }
377
378    /**
379     * Checks if the signature matches what is expected for a .lz4 file.
380     *
381     * <p>.lz4 files start with a four byte signature.</p>
382     *
383     * @param signature the bytes to check
384     * @param length    the number of bytes to check
385     * @return          true if this is a .sz stream, false otherwise
386     */
387    public static boolean matches(final byte[] signature, final int length) {
388
389        if (length < LZ4_SIGNATURE.length) {
390            return false;
391        }
392
393        byte[] shortenedSig = signature;
394        if (signature.length > LZ4_SIGNATURE.length) {
395            shortenedSig = new byte[LZ4_SIGNATURE.length];
396            System.arraycopy(signature, 0, shortenedSig, 0, LZ4_SIGNATURE.length);
397        }
398
399        return Arrays.equals(shortenedSig, LZ4_SIGNATURE);
400    }
401}