| 1 | // SPDX-License-Identifier: 0BSD |
| 2 | // SPDX-FileCopyrightText: The XZ for Java authors and contributors |
| 3 | // SPDX-FileContributor: Lasse Collin <[email protected]> |
| 4 | |
| 5 | package org.tukaani.xz; |
| 6 | |
| 7 | import java.io.InputStream; |
| 8 | import java.io.DataInputStream; |
| 9 | import java.io.IOException; |
| 10 | import java.io.EOFException; |
| 11 | import org.tukaani.xz.common.DecoderUtil; |
| 12 | import org.tukaani.xz.common.StreamFlags; |
| 13 | import org.tukaani.xz.index.IndexHash; |
| 14 | import org.tukaani.xz.check.Check; |
| 15 | |
| 16 | /** |
| 17 | * Decompresses exactly one XZ Stream in streamed mode (no seeking). |
| 18 | * The decompression stops after the first XZ Stream has been decompressed, |
| 19 | * and the read position in the input stream is left at the first byte |
| 20 | * after the end of the XZ Stream. This can be useful when XZ data has |
| 21 | * been stored inside some other file format or protocol. |
| 22 | * <p> |
| 23 | * Unless you know what you are doing, don't use this class to decompress |
| 24 | * standalone .xz files. For that purpose, use {@code XZInputStream}. |
| 25 | * |
| 26 | * <h2>When uncompressed size is known beforehand</h2> |
| 27 | * <p> |
| 28 | * If you are decompressing complete XZ streams and your application knows |
| 29 | * exactly how much uncompressed data there should be, it is good to try |
| 30 | * reading one more byte by calling {@code read()} and checking that it |
| 31 | * returns {@code -1}. This way the decompressor will parse the file footers |
| 32 | * and verify the integrity checks, giving the caller more confidence that |
| 33 | * the uncompressed data is valid. |
| 34 | * |
| 35 | * @see XZInputStream |
| 36 | */ |
| 37 | public class SingleXZInputStream extends InputStream { |
| 38 | private InputStream in; |
| 39 | private final ArrayCache arrayCache; |
| 40 | private final int memoryLimit; |
| 41 | private final StreamFlags streamHeaderFlags; |
| 42 | private final Check check; |
| 43 | private final boolean verifyCheck; |
| 44 | private BlockInputStream blockDecoder = null; |
| 45 | private final IndexHash indexHash = new IndexHash(); |
| 46 | private boolean endReached = false; |
| 47 | private IOException exception = null; |
| 48 | |
| 49 | private final byte[] tempBuf = new byte[1]; |
| 50 | |
| 51 | /** |
| 52 | * Reads the Stream Header into a buffer. |
| 53 | * This is a helper function for the constructors. |
| 54 | */ |
| 55 | private static byte[] readStreamHeader(InputStream in) throws IOException { |
| 56 | byte[] streamHeader = new byte[DecoderUtil.STREAM_HEADER_SIZE]; |
| 57 | new DataInputStream(in).readFully(streamHeader); |
| 58 | return streamHeader; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Creates a new XZ decompressor that decompresses exactly one |
| 63 | * XZ Stream from {@code in} without a memory usage limit. |
| 64 | * <p> |
| 65 | * This constructor reads and parses the XZ Stream Header (12 bytes) |
| 66 | * from {@code in}. The header of the first Block is not read |
| 67 | * until {@code read} is called. |
| 68 | * |
| 69 | * @param in input stream from which XZ-compressed |
| 70 | * data is read |
| 71 | * |
| 72 | * @throws XZFormatException |
| 73 | * input is not in the XZ format |
| 74 | * |
| 75 | * @throws CorruptedInputException |
| 76 | * XZ header CRC32 doesn't match |
| 77 | * |
| 78 | * @throws UnsupportedOptionsException |
| 79 | * XZ header is valid but specifies options |
| 80 | * not supported by this implementation |
| 81 | * |
| 82 | * @throws EOFException |
| 83 | * less than 12 bytes of input was available |
| 84 | * from {@code in} |
| 85 | * |
| 86 | * @throws IOException may be thrown by {@code in} |
| 87 | */ |
| 88 | public SingleXZInputStream(InputStream in) throws IOException { |
| 89 | this(in, -1); |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * Creates a new XZ decompressor that decompresses exactly one |
| 94 | * XZ Stream from {@code in} without a memory usage limit. |
| 95 | * <p> |
| 96 | * This is identical to {@code SingleXZInputStream(InputStream)} |
| 97 | * except that this also takes the {@code arrayCache} argument. |
| 98 | * |
| 99 | * @param in input stream from which XZ-compressed |
| 100 | * data is read |
| 101 | * |
| 102 | * @param arrayCache cache to be used for allocating large arrays |
| 103 | * |
| 104 | * @throws XZFormatException |
| 105 | * input is not in the XZ format |
| 106 | * |
| 107 | * @throws CorruptedInputException |
| 108 | * XZ header CRC32 doesn't match |
| 109 | * |
| 110 | * @throws UnsupportedOptionsException |
| 111 | * XZ header is valid but specifies options |
| 112 | * not supported by this implementation |
| 113 | * |
| 114 | * @throws EOFException |
| 115 | * less than 12 bytes of input was available |
| 116 | * from {@code in} |
| 117 | * |
| 118 | * @throws IOException may be thrown by {@code in} |
| 119 | * |
| 120 | * @since 1.7 |
| 121 | */ |
| 122 | public SingleXZInputStream(InputStream in, ArrayCache arrayCache) |
| 123 | throws IOException { |
| 124 | this(in, -1, arrayCache); |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * Creates a new XZ decompressor that decompresses exactly one |
| 129 | * XZ Stream from {@code in} with an optional memory usage limit. |
| 130 | * <p> |
| 131 | * This is identical to {@code SingleXZInputStream(InputStream)} |
| 132 | * except that this also takes the {@code memoryLimit} argument. |
| 133 | * |
| 134 | * @param in input stream from which XZ-compressed |
| 135 | * data is read |
| 136 | * |
| 137 | * @param memoryLimit memory usage limit in kibibytes (KiB) |
| 138 | * or {@code -1} to impose no memory usage limit |
| 139 | * |
| 140 | * @throws XZFormatException |
| 141 | * input is not in the XZ format |
| 142 | * |
| 143 | * @throws CorruptedInputException |
| 144 | * XZ header CRC32 doesn't match |
| 145 | * |
| 146 | * @throws UnsupportedOptionsException |
| 147 | * XZ header is valid but specifies options |
| 148 | * not supported by this implementation |
| 149 | * |
| 150 | * @throws EOFException |
| 151 | * less than 12 bytes of input was available |
| 152 | * from {@code in} |
| 153 | * |
| 154 | * @throws IOException may be thrown by {@code in} |
| 155 | */ |
| 156 | public SingleXZInputStream(InputStream in, int memoryLimit) |
| 157 | throws IOException { |
| 158 | this(in, memoryLimit, true); |
| 159 | } |
| 160 | |
| 161 | /** |
| 162 | * Creates a new XZ decompressor that decompresses exactly one |
| 163 | * XZ Stream from {@code in} with an optional memory usage limit. |
| 164 | * <p> |
| 165 | * This is identical to {@code SingleXZInputStream(InputStream)} |
| 166 | * except that this also takes the {@code memoryLimit} and |
| 167 | * {@code arrayCache} arguments. |
| 168 | * |
| 169 | * @param in input stream from which XZ-compressed |
| 170 | * data is read |
| 171 | * |
| 172 | * @param memoryLimit memory usage limit in kibibytes (KiB) |
| 173 | * or {@code -1} to impose no memory usage limit |
| 174 | * |
| 175 | * @param arrayCache cache to be used for allocating large arrays |
| 176 | * |
| 177 | * @throws XZFormatException |
| 178 | * input is not in the XZ format |
| 179 | * |
| 180 | * @throws CorruptedInputException |
| 181 | * XZ header CRC32 doesn't match |
| 182 | * |
| 183 | * @throws UnsupportedOptionsException |
| 184 | * XZ header is valid but specifies options |
| 185 | * not supported by this implementation |
| 186 | * |
| 187 | * @throws EOFException |
| 188 | * less than 12 bytes of input was available |
| 189 | * from {@code in} |
| 190 | * |
| 191 | * @throws IOException may be thrown by {@code in} |
| 192 | * |
| 193 | * @since 1.7 |
| 194 | */ |
| 195 | public SingleXZInputStream(InputStream in, int memoryLimit, |
| 196 | ArrayCache arrayCache) throws IOException { |
| 197 | this(in, memoryLimit, true, arrayCache); |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * Creates a new XZ decompressor that decompresses exactly one |
| 202 | * XZ Stream from {@code in} with an optional memory usage limit |
| 203 | * and ability to disable verification of integrity checks. |
| 204 | * <p> |
| 205 | * This is identical to {@code SingleXZInputStream(InputStream,int)} |
| 206 | * except that this also takes the {@code verifyCheck} argument. |
| 207 | * <p> |
| 208 | * Note that integrity check verification should almost never be disabled. |
| 209 | * Possible reasons to disable integrity check verification: |
| 210 | * <ul> |
| 211 | * <li>Trying to recover data from a corrupt .xz file.</li> |
| 212 | * <li>Speeding up decompression. This matters mostly with SHA-256 |
| 213 | * or with files that have compressed extremely well. It's recommended |
| 214 | * that integrity checking isn't disabled for performance reasons |
| 215 | * unless the file integrity is verified externally in some other |
| 216 | * way.</li> |
| 217 | * </ul> |
| 218 | * <p> |
| 219 | * {@code verifyCheck} only affects the integrity check of the actual |
| 220 | * compressed data. The CRC32 fields in the headers are always verified. |
| 221 | * |
| 222 | * @param in input stream from which XZ-compressed |
| 223 | * data is read |
| 224 | * |
| 225 | * @param memoryLimit memory usage limit in kibibytes (KiB) |
| 226 | * or {@code -1} to impose no memory usage limit |
| 227 | * |
| 228 | * @param verifyCheck if {@code true}, the integrity checks |
| 229 | * will be verified; this should almost never |
| 230 | * be set to {@code false} |
| 231 | * |
| 232 | * @throws XZFormatException |
| 233 | * input is not in the XZ format |
| 234 | * |
| 235 | * @throws CorruptedInputException |
| 236 | * XZ header CRC32 doesn't match |
| 237 | * |
| 238 | * @throws UnsupportedOptionsException |
| 239 | * XZ header is valid but specifies options |
| 240 | * not supported by this implementation |
| 241 | * |
| 242 | * @throws EOFException |
| 243 | * less than 12 bytes of input was available |
| 244 | * from {@code in} |
| 245 | * |
| 246 | * @throws IOException may be thrown by {@code in} |
| 247 | * |
| 248 | * @since 1.6 |
| 249 | */ |
| 250 | public SingleXZInputStream(InputStream in, int memoryLimit, |
| 251 | boolean verifyCheck) throws IOException { |
| 252 | this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache()); |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * Creates a new XZ decompressor that decompresses exactly one |
| 257 | * XZ Stream from {@code in} with an optional memory usage limit |
| 258 | * and ability to disable verification of integrity checks. |
| 259 | * <p> |
| 260 | * This is identical to |
| 261 | * {@code SingleXZInputStream(InputStream,int,boolean)} |
| 262 | * except that this also takes the {@code arrayCache} argument. |
| 263 | * |
| 264 | * @param in input stream from which XZ-compressed |
| 265 | * data is read |
| 266 | * |
| 267 | * @param memoryLimit memory usage limit in kibibytes (KiB) |
| 268 | * or {@code -1} to impose no memory usage limit |
| 269 | * |
| 270 | * @param verifyCheck if {@code true}, the integrity checks |
| 271 | * will be verified; this should almost never |
| 272 | * be set to {@code false} |
| 273 | * |
| 274 | * @param arrayCache cache to be used for allocating large arrays |
| 275 | * |
| 276 | * @throws XZFormatException |
| 277 | * input is not in the XZ format |
| 278 | * |
| 279 | * @throws CorruptedInputException |
| 280 | * XZ header CRC32 doesn't match |
| 281 | * |
| 282 | * @throws UnsupportedOptionsException |
| 283 | * XZ header is valid but specifies options |
| 284 | * not supported by this implementation |
| 285 | * |
| 286 | * @throws EOFException |
| 287 | * less than 12 bytes of input was available |
| 288 | * from {@code in} |
| 289 | * |
| 290 | * @throws IOException may be thrown by {@code in} |
| 291 | * |
| 292 | * @since 1.7 |
| 293 | */ |
| 294 | public SingleXZInputStream(InputStream in, int memoryLimit, |
| 295 | boolean verifyCheck, ArrayCache arrayCache) |
| 296 | throws IOException { |
| 297 | this(in, memoryLimit, verifyCheck, readStreamHeader(in), arrayCache); |
| 298 | } |
| 299 | |
| 300 | SingleXZInputStream(InputStream in, int memoryLimit, boolean verifyCheck, |
| 301 | byte[] streamHeader, ArrayCache arrayCache) |
| 302 | throws IOException { |
| 303 | this.arrayCache = arrayCache; |
| 304 | this.in = in; |
| 305 | this.memoryLimit = memoryLimit; |
| 306 | this.verifyCheck = verifyCheck; |
| 307 | streamHeaderFlags = DecoderUtil.decodeStreamHeader(streamHeader); |
| 308 | check = Check.getInstance(streamHeaderFlags.checkType); |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Gets the ID of the integrity check used in this XZ Stream. |
| 313 | * |
| 314 | * @return the Check ID specified in the XZ Stream Header |
| 315 | */ |
| 316 | public int getCheckType() { |
| 317 | return streamHeaderFlags.checkType; |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * Gets the name of the integrity check used in this XZ Stream. |
| 322 | * |
| 323 | * @return the name of the check specified in the XZ Stream Header |
| 324 | */ |
| 325 | public String getCheckName() { |
| 326 | return check.getName(); |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Decompresses the next byte from this input stream. |
| 331 | * <p> |
| 332 | * Reading lots of data with {@code read()} from this input stream |
| 333 | * may be inefficient. Wrap it in {@link java.io.BufferedInputStream} |
| 334 | * if you need to read lots of data one byte at a time. |
| 335 | * |
| 336 | * @return the next decompressed byte, or {@code -1} |
| 337 | * to indicate the end of the compressed stream |
| 338 | * |
| 339 | * @throws CorruptedInputException |
| 340 | * @throws UnsupportedOptionsException |
| 341 | * @throws MemoryLimitException |
| 342 | * |
| 343 | * @throws XZIOException if the stream has been closed |
| 344 | * |
| 345 | * @throws EOFException |
| 346 | * compressed input is truncated or corrupt |
| 347 | * |
| 348 | * @throws IOException may be thrown by {@code in} |
| 349 | */ |
| 350 | @Override |
| 351 | public int read() throws IOException { |
| 352 | return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF); |
| 353 | } |
| 354 | |
| 355 | /** |
| 356 | * Decompresses into an array of bytes. |
| 357 | * <p> |
| 358 | * If {@code len} is zero, no bytes are read and {@code 0} |
| 359 | * is returned. Otherwise this will try to decompress {@code len} |
| 360 | * bytes of uncompressed data. Less than {@code len} bytes may |
| 361 | * be read only in the following situations: |
| 362 | * <ul> |
| 363 | * <li>The end of the compressed data was reached successfully.</li> |
| 364 | * <li>An error is detected after at least one but less {@code len} |
| 365 | * bytes have already been successfully decompressed. |
| 366 | * The next call with non-zero {@code len} will immediately |
| 367 | * throw the pending exception.</li> |
| 368 | * <li>An exception is thrown.</li> |
| 369 | * </ul> |
| 370 | * |
| 371 | * @param buf target buffer for uncompressed data |
| 372 | * @param off start offset in {@code buf} |
| 373 | * @param len maximum number of uncompressed bytes to read |
| 374 | * |
| 375 | * @return number of bytes read, or {@code -1} to indicate |
| 376 | * the end of the compressed stream |
| 377 | * |
| 378 | * @throws CorruptedInputException |
| 379 | * @throws UnsupportedOptionsException |
| 380 | * @throws MemoryLimitException |
| 381 | * |
| 382 | * @throws XZIOException if the stream has been closed |
| 383 | * |
| 384 | * @throws EOFException |
| 385 | * compressed input is truncated or corrupt |
| 386 | * |
| 387 | * @throws IOException may be thrown by {@code in} |
| 388 | */ |
| 389 | @Override |
| 390 | public int read(byte[] buf, int off, int len) throws IOException { |
| 391 | if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) |
| 392 | throw new IndexOutOfBoundsException(); |
| 393 | |
| 394 | if (len == 0) |
| 395 | return 0; |
| 396 | |
| 397 | if (in == null) |
| 398 | throw new XZIOException("Stream closed"); |
| 399 | |
| 400 | if (exception != null) |
| 401 | throw exception; |
| 402 | |
| 403 | if (endReached) |
| 404 | return -1; |
| 405 | |
| 406 | int size = 0; |
| 407 | |
| 408 | try { |
| 409 | while (len > 0) { |
| 410 | if (blockDecoder == null) { |
| 411 | try { |
| 412 | blockDecoder = new BlockInputStream( |
| 413 | in, check, verifyCheck, memoryLimit, -1, -1, |
| 414 | arrayCache); |
| 415 | } catch (IndexIndicatorException e) { |
| 416 | indexHash.validate(in); |
| 417 | validateStreamFooter(); |
| 418 | endReached = true; |
| 419 | return size > 0 ? size : -1; |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | int ret = blockDecoder.read(buf, off, len); |
| 424 | |
| 425 | if (ret > 0) { |
| 426 | size += ret; |
| 427 | off += ret; |
| 428 | len -= ret; |
| 429 | } else if (ret == -1) { |
| 430 | indexHash.add(blockDecoder.getUnpaddedSize(), |
| 431 | blockDecoder.getUncompressedSize()); |
| 432 | blockDecoder = null; |
| 433 | } |
| 434 | } |
| 435 | } catch (IOException e) { |
| 436 | exception = e; |
| 437 | if (size == 0) |
| 438 | throw e; |
| 439 | } |
| 440 | |
| 441 | return size; |
| 442 | } |
| 443 | |
| 444 | private void validateStreamFooter() throws IOException { |
| 445 | byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE]; |
| 446 | new DataInputStream(in).readFully(buf); |
| 447 | StreamFlags streamFooterFlags = DecoderUtil.decodeStreamFooter(buf); |
| 448 | |
| 449 | if (!DecoderUtil.areStreamFlagsEqual(streamHeaderFlags, |
| 450 | streamFooterFlags) |
| 451 | || indexHash.getIndexSize() != streamFooterFlags.backwardSize) |
| 452 | throw new CorruptedInputException( |
| 453 | "XZ Stream Footer does not match Stream Header"); |
| 454 | } |
| 455 | |
| 456 | /** |
| 457 | * Returns the number of uncompressed bytes that can be read |
| 458 | * without blocking. The value is returned with an assumption |
| 459 | * that the compressed input data will be valid. If the compressed |
| 460 | * data is corrupt, {@code CorruptedInputException} may get |
| 461 | * thrown before the number of bytes claimed to be available have |
| 462 | * been read from this input stream. |
| 463 | * |
| 464 | * @return the number of uncompressed bytes that can be read |
| 465 | * without blocking |
| 466 | */ |
| 467 | @Override |
| 468 | public int available() throws IOException { |
| 469 | if (in == null) |
| 470 | throw new XZIOException("Stream closed"); |
| 471 | |
| 472 | if (exception != null) |
| 473 | throw exception; |
| 474 | |
| 475 | return blockDecoder == null ? 0 : blockDecoder.available(); |
| 476 | } |
| 477 | |
| 478 | /** |
| 479 | * Closes the stream and calls {@code in.close()}. |
| 480 | * If the stream was already closed, this does nothing. |
| 481 | * <p> |
| 482 | * This is equivalent to {@code close(true)}. |
| 483 | * |
| 484 | * @throws IOException if thrown by {@code in.close()} |
| 485 | */ |
| 486 | @Override |
| 487 | public void close() throws IOException { |
| 488 | close(true); |
| 489 | } |
| 490 | |
| 491 | /** |
| 492 | * Closes the stream and optionally calls {@code in.close()}. |
| 493 | * If the stream was already closed, this does nothing. |
| 494 | * If {@code close(false)} has been called, a further call of |
| 495 | * {@code close(true)} does nothing (it doesn't call {@code in.close()}). |
| 496 | * <p> |
| 497 | * If you don't want to close the underlying {@code InputStream}, |
| 498 | * there is usually no need to worry about closing this stream either; |
| 499 | * it's fine to do nothing and let the garbage collector handle it. |
| 500 | * However, if you are using {@link ArrayCache}, {@code close(false)} |
| 501 | * can be useful to put the allocated arrays back to the cache without |
| 502 | * closing the underlying {@code InputStream}. |
| 503 | * <p> |
| 504 | * Note that if you successfully reach the end of the stream |
| 505 | * ({@code read} returns {@code -1}), the arrays are automatically |
| 506 | * put back to the cache by that {@code read} call. In this |
| 507 | * situation {@code close(false)} is redundant (but harmless). |
| 508 | * |
| 509 | * @throws IOException if thrown by {@code in.close()} |
| 510 | * |
| 511 | * @since 1.7 |
| 512 | */ |
| 513 | public void close(boolean closeInput) throws IOException { |
| 514 | if (in != null) { |
| 515 | if (blockDecoder != null) { |
| 516 | blockDecoder.close(); |
| 517 | blockDecoder = null; |
| 518 | } |
| 519 | |
| 520 | try { |
| 521 | if (closeInput) |
| 522 | in.close(); |
| 523 | } finally { |
| 524 | in = null; |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | } |