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