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 try { 148 if (currentCompressedChunk != null) { 149 currentCompressedChunk.close(); 150 currentCompressedChunk = null; 151 } 152 } finally { 153 in.close(); 154 } 155 } 156 157 /** {@inheritDoc} */ 158 @Override 159 public int read(final byte[] b, final int off, final int len) throws IOException { 160 int read = readOnce(b, off, len); 161 if (read == -1) { 162 readNextBlock(); 163 if (endReached) { 164 return -1; 165 } 166 read = readOnce(b, off, len); 167 } 168 return read; 169 } 170 171 /** {@inheritDoc} */ 172 @Override 173 public int available() throws IOException { 174 if (inUncompressedChunk) { 175 return Math.min(uncompressedBytesRemaining, 176 in.available()); 177 } else if (currentCompressedChunk != null) { 178 return currentCompressedChunk.available(); 179 } 180 return 0; 181 } 182 183 /** 184 * @since 1.17 185 */ 186 @Override 187 public long getCompressedCount() { 188 return countingStream.getBytesRead() - unreadBytes; 189 } 190 191 /** 192 * Read from the current chunk into the given array. 193 * 194 * @return -1 if there is no current chunk or the number of bytes 195 * read from the current chunk (which may be -1 if the end of the 196 * chunk is reached). 197 */ 198 private int readOnce(final byte[] b, final int off, final int len) throws IOException { 199 int read = -1; 200 if (inUncompressedChunk) { 201 final int amount = Math.min(uncompressedBytesRemaining, len); 202 if (amount == 0) { 203 return -1; 204 } 205 read = in.read(b, off, amount); 206 if (read != -1) { 207 uncompressedBytesRemaining -= read; 208 count(read); 209 } 210 } else if (currentCompressedChunk != null) { 211 final long before = currentCompressedChunk.getBytesRead(); 212 read = currentCompressedChunk.read(b, off, len); 213 if (read == -1) { 214 currentCompressedChunk.close(); 215 currentCompressedChunk = null; 216 } else { 217 count(currentCompressedChunk.getBytesRead() - before); 218 } 219 } 220 if (read > 0) { 221 checksum.update(b, off, read); 222 } 223 return read; 224 } 225 226 private void readNextBlock() throws IOException { 227 verifyLastChecksumAndReset(); 228 inUncompressedChunk = false; 229 final int type = readOneByte(); 230 if (type == -1) { 231 endReached = true; 232 } else if (type == STREAM_IDENTIFIER_TYPE) { 233 in.unread(type); 234 unreadBytes++; 235 pushedBackBytes(1); 236 readStreamIdentifier(); 237 readNextBlock(); 238 } else if (type == PADDING_CHUNK_TYPE 239 || (type > MAX_UNSKIPPABLE_TYPE && type <= MAX_SKIPPABLE_TYPE)) { 240 skipBlock(); 241 readNextBlock(); 242 } else if (type >= MIN_UNSKIPPABLE_TYPE && type <= MAX_UNSKIPPABLE_TYPE) { 243 throw new IOException("unskippable chunk with type " + type 244 + " (hex " + Integer.toHexString(type) + ")" 245 + " detected."); 246 } else if (type == UNCOMPRESSED_CHUNK_TYPE) { 247 inUncompressedChunk = true; 248 uncompressedBytesRemaining = readSize() - 4 /* CRC */; 249 expectedChecksum = unmask(readCrc()); 250 } else if (type == COMPRESSED_CHUNK_TYPE) { 251 final boolean expectChecksum = dialect.usesChecksumWithCompressedChunks(); 252 final long size = readSize() - (expectChecksum ? 4L : 0L); 253 if (expectChecksum) { 254 expectedChecksum = unmask(readCrc()); 255 } else { 256 expectedChecksum = -1; 257 } 258 currentCompressedChunk = 259 new SnappyCompressorInputStream(new BoundedInputStream(in, size), blockSize); 260 // constructor reads uncompressed size 261 count(currentCompressedChunk.getBytesRead()); 262 } else { 263 // impossible as all potential byte values have been covered 264 throw new IOException("unknown chunk type " + type 265 + " detected."); 266 } 267 } 268 269 private long readCrc() throws IOException { 270 final byte[] b = new byte[4]; 271 final int read = IOUtils.readFully(in, b); 272 count(read); 273 if (read != 4) { 274 throw new IOException("premature end of stream"); 275 } 276 return ByteUtils.fromLittleEndian(b); 277 } 278 279 static long unmask(long x) { 280 // ugly, maybe we should just have used ints and deal with the 281 // overflow 282 x -= MASK_OFFSET; 283 x &= 0xffffFFFFL; 284 return ((x >> 17) | (x << 15)) & 0xffffFFFFL; 285 } 286 287 private int readSize() throws IOException { 288 return (int) ByteUtils.fromLittleEndian(supplier, 3); 289 } 290 291 private void skipBlock() throws IOException { 292 final int size = readSize(); 293 final long read = IOUtils.skip(in, size); 294 count(read); 295 if (read != size) { 296 throw new IOException("premature end of stream"); 297 } 298 } 299 300 private void readStreamIdentifier() throws IOException { 301 final byte[] b = new byte[10]; 302 final int read = IOUtils.readFully(in, b); 303 count(read); 304 if (10 != read || !matches(b, 10)) { 305 throw new IOException("Not a framed Snappy stream"); 306 } 307 } 308 309 private int readOneByte() throws IOException { 310 final int b = in.read(); 311 if (b != -1) { 312 count(1); 313 return b & 0xFF; 314 } 315 return -1; 316 } 317 318 private void verifyLastChecksumAndReset() throws IOException { 319 if (expectedChecksum >= 0 && expectedChecksum != checksum.getValue()) { 320 throw new IOException("Checksum verification failed"); 321 } 322 expectedChecksum = -1; 323 checksum.reset(); 324 } 325 326 /** 327 * Checks if the signature matches what is expected for a .sz file. 328 * 329 * <p>.sz files start with a chunk with tag 0xff and content sNaPpY.</p> 330 * 331 * @param signature the bytes to check 332 * @param length the number of bytes to check 333 * @return true if this is a .sz stream, false otherwise 334 */ 335 public static boolean matches(final byte[] signature, final int length) { 336 337 if (length < SZ_SIGNATURE.length) { 338 return false; 339 } 340 341 byte[] shortenedSig = signature; 342 if (signature.length > SZ_SIGNATURE.length) { 343 shortenedSig = new byte[SZ_SIGNATURE.length]; 344 System.arraycopy(signature, 0, shortenedSig, 0, SZ_SIGNATURE.length); 345 } 346 347 return Arrays.equals(shortenedSig, SZ_SIGNATURE); 348 } 349 350}