Debian Codegraph @

src/org/tukaani/xz/SeekableXZInputStream.java

raw symbols SCIP
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.util.Arrays;
8 import java.util.ArrayList;
9 import java.io.DataInputStream;
10 import java.io.IOException;
11 import java.io.EOFException;
12 import org.tukaani.xz.common.DecoderUtil;
13 import org.tukaani.xz.common.StreamFlags;
14 import org.tukaani.xz.check.Check;
15 import org.tukaani.xz.index.IndexDecoder;
16 import org.tukaani.xz.index.BlockInfo;
17
18 /**
19 * Decompresses a .xz file in random access mode.
20 * This supports decompressing concatenated .xz files.
21 * <p>
22 * Each .xz file consist of one or more Streams. Each Stream consist of zero
23 * or more Blocks. Each Stream contains an Index of Streams' Blocks.
24 * The Indexes from all Streams are loaded in RAM by a constructor of this
25 * class. A typical .xz file has only one Stream, and parsing its Index will
26 * need only three or four seeks.
27 * <p>
28 * To make random access possible, the data in a .xz file must be split
29 * into multiple Blocks of reasonable size. Decompression can only start at
30 * a Block boundary. When seeking to an uncompressed position that is not at
31 * a Block boundary, decompression starts at the beginning of the Block and
32 * throws away data until the target position is reached. Thus, smaller Blocks
33 * mean faster seeks to arbitrary uncompressed positions. On the other hand,
34 * smaller Blocks mean worse compression. So one has to make a compromise
35 * between random access speed and compression ratio.
36 * <p>
37 * Implementation note: This class uses linear search to locate the correct
38 * Stream from the data structures in RAM. It was the simplest to implement
39 * and should be fine as long as there aren't too many Streams. The correct
40 * Block inside a Stream is located using binary search and thus is fast
41 * even with a huge number of Blocks.
42 *
43 * <h2>Memory usage</h2>
44 * <p>
45 * The amount of memory needed for the Indexes is taken into account when
46 * checking the memory usage limit. Each Stream is calculated to need at
47 * least 1&nbsp;KiB of memory and each Block 16 bytes of memory, rounded up
48 * to the next kibibyte. So unless the file has a huge number of Streams or
49 * Blocks, these don't take significant amount of memory.
50 *
51 * <h2>Creating random-accessible .xz files</h2>
52 * <p>
53 * When using {@link XZOutputStream}, a new Block can be started by calling
54 * its {@link XZOutputStream#endBlock() endBlock} method. If you know
55 * that the decompressor will only need to seek to certain uncompressed
56 * positions, it can be a good idea to start a new Block at (some of) these
57 * positions (and only at these positions to get better compression ratio).
58 * <p>
59 * liblzma in XZ Utils supports starting a new Block with
60 * {@code LZMA_FULL_FLUSH}. XZ Utils 5.1.1alpha added threaded
61 * compression which creates multi-Block .xz files. XZ Utils 5.1.1alpha
62 * also added the option {@code --block-size=SIZE} to the xz command
63 * line tool. XZ Utils 5.1.2alpha added a partial implementation of
64 * {@code --block-list=SIZES} which allows specifying sizes of
65 * individual Blocks.
66 *
67 * <h2>Example: getting the uncompressed size of a .xz file</h2>
68 * <blockquote><pre>
69 * String filename = "foo.xz";
70 * SeekableFileInputStream seekableFile
71 * = new SeekableFileInputStream(filename);
72 *
73 * try {
74 * SeekableXZInputStream seekableXZ
75 * = new SeekableXZInputStream(seekableFile);
76 * System.out.println("Uncompressed size: " + seekableXZ.length());
77 * } finally {
78 * seekableFile.close();
79 * }
80 * </pre></blockquote>
81 *
82 * @see SeekableFileInputStream
83 * @see XZInputStream
84 * @see XZOutputStream
85 */
86 public class SeekableXZInputStream extends SeekableInputStream {
87 /**
88 * Cache for big arrays.
89 */
90 private final ArrayCache arrayCache;
91
92 /**
93 * The input stream containing XZ compressed data.
94 */
95 private SeekableInputStream in;
96
97 /**
98 * Memory usage limit after the memory usage of the IndexDecoders have
99 * been subtracted.
100 */
101 private final int memoryLimit;
102
103 /**
104 * Memory usage of the IndexDecoders.
105 * {@code memoryLimit + indexMemoryUsage} equals the original
106 * memory usage limit that was passed to the constructor.
107 */
108 private int indexMemoryUsage = 0;
109
110 /**
111 * List of IndexDecoders, one for each Stream in the file.
112 * The list is in reverse order: The first element is
113 * the last Stream in the file.
114 */
115 private final ArrayList<IndexDecoder> streams
116 = new ArrayList<IndexDecoder>();
117
118 /**
119 * Bitmask of all Check IDs seen.
120 */
121 private int checkTypes = 0;
122
123 /**
124 * Uncompressed size of the file (all Streams).
125 */
126 private long uncompressedSize = 0;
127
128 /**
129 * Uncompressed size of the largest XZ Block in the file.
130 */
131 private long largestBlockSize = 0;
132
133 /**
134 * Number of XZ Blocks in the file.
135 */
136 private int blockCount = 0;
137
138 /**
139 * Size and position information about the current Block.
140 * If there are no Blocks, all values will be {@code -1}.
141 */
142 private final BlockInfo curBlockInfo;
143
144 /**
145 * Temporary (and cached) information about the Block whose information
146 * is queried via {@code getBlockPos} and related functions.
147 */
148 private final BlockInfo queriedBlockInfo;
149
150 /**
151 * Integrity Check in the current XZ Stream. The constructor leaves
152 * this to point to the Check of the first Stream.
153 */
154 private Check check;
155
156 /**
157 * Flag indicating if the integrity checks will be verified.
158 */
159 private final boolean verifyCheck;
160
161 /**
162 * Decoder of the current XZ Block, if any.
163 */
164 private BlockInputStream blockDecoder = null;
165
166 /**
167 * Current uncompressed position.
168 */
169 private long curPos = 0;
170
171 /**
172 * Target position for seeking.
173 */
174 private long seekPos;
175
176 /**
177 * True when {@code seek(long)} has been called but the actual
178 * seeking hasn't been done yet.
179 */
180 private boolean seekNeeded = false;
181
182 /**
183 * True when end of the file was reached. This can be cleared by
184 * calling {@code seek(long)}.
185 */
186 private boolean endReached = false;
187
188 /**
189 * Pending exception from an earlier error.
190 */
191 private IOException exception = null;
192
193 /**
194 * Temporary buffer for read(). This avoids reallocating memory
195 * on every read() call.
196 */
197 private final byte[] tempBuf = new byte[1];
198
199 /**
200 * Creates a new seekable XZ decompressor without a memory usage limit.
201 *
202 * @param in seekable input stream containing one or more
203 * XZ Streams; the whole input stream is used
204 *
205 * @throws XZFormatException
206 * input is not in the XZ format
207 *
208 * @throws CorruptedInputException
209 * XZ data is corrupt or truncated
210 *
211 * @throws UnsupportedOptionsException
212 * XZ headers seem valid but they specify
213 * options not supported by this implementation
214 *
215 * @throws EOFException
216 * less than 6 bytes of input was available
217 * from {@code in}, or (unlikely) the size
218 * of the underlying stream got smaller while
219 * this was reading from it
220 *
221 * @throws IOException may be thrown by {@code in}
222 */
223 public SeekableXZInputStream(SeekableInputStream in)
224 throws IOException {
225 this(in, -1);
226 }
227
228 /**
229 * Creates a new seekable XZ decompressor without a memory usage limit.
230 * <p>
231 * This is identical to {@code SeekableXZInputStream(SeekableInputStream)}
232 * except that this also takes the {@code arrayCache} argument.
233 *
234 * @param in seekable input stream containing one or more
235 * XZ Streams; the whole input stream is used
236 *
237 * @param arrayCache cache to be used for allocating large arrays
238 *
239 * @throws XZFormatException
240 * input is not in the XZ format
241 *
242 * @throws CorruptedInputException
243 * XZ data is corrupt or truncated
244 *
245 * @throws UnsupportedOptionsException
246 * XZ headers seem valid but they specify
247 * options not supported by this implementation
248 *
249 * @throws EOFException
250 * less than 6 bytes of input was available
251 * from {@code in}, or (unlikely) the size
252 * of the underlying stream got smaller while
253 * this was reading from it
254 *
255 * @throws IOException may be thrown by {@code in}
256 *
257 * @since 1.7
258 */
259 public SeekableXZInputStream(SeekableInputStream in, ArrayCache arrayCache)
260 throws IOException {
261 this(in, -1, arrayCache);
262 }
263
264 /**
265 * Creates a new seekable XZ decomporessor with an optional
266 * memory usage limit.
267 *
268 * @param in seekable input stream containing one or more
269 * XZ Streams; the whole input stream is used
270 *
271 * @param memoryLimit memory usage limit in kibibytes (KiB)
272 * or {@code -1} to impose no memory usage limit
273 *
274 * @throws XZFormatException
275 * input is not in the XZ format
276 *
277 * @throws CorruptedInputException
278 * XZ data is corrupt or truncated
279 *
280 * @throws UnsupportedOptionsException
281 * XZ headers seem valid but they specify
282 * options not supported by this implementation
283 *
284 * @throws MemoryLimitException
285 * decoded XZ Indexes would need more memory
286 * than allowed by the memory usage limit
287 *
288 * @throws EOFException
289 * less than 6 bytes of input was available
290 * from {@code in}, or (unlikely) the size
291 * of the underlying stream got smaller while
292 * this was reading from it
293 *
294 * @throws IOException may be thrown by {@code in}
295 */
296 public SeekableXZInputStream(SeekableInputStream in, int memoryLimit)
297 throws IOException {
298 this(in, memoryLimit, true);
299 }
300
301 /**
302 * Creates a new seekable XZ decomporessor with an optional
303 * memory usage limit.
304 * <p>
305 * This is identical to
306 * {@code SeekableXZInputStream(SeekableInputStream,int)}
307 * except that this also takes the {@code arrayCache} argument.
308 *
309 * @param in seekable input stream containing one or more
310 * XZ Streams; the whole input stream is used
311 *
312 * @param memoryLimit memory usage limit in kibibytes (KiB)
313 * or {@code -1} to impose no memory usage limit
314 *
315 * @param arrayCache cache to be used for allocating large arrays
316 *
317 * @throws XZFormatException
318 * input is not in the XZ format
319 *
320 * @throws CorruptedInputException
321 * XZ data is corrupt or truncated
322 *
323 * @throws UnsupportedOptionsException
324 * XZ headers seem valid but they specify
325 * options not supported by this implementation
326 *
327 * @throws MemoryLimitException
328 * decoded XZ Indexes would need more memory
329 * than allowed by the memory usage limit
330 *
331 * @throws EOFException
332 * less than 6 bytes of input was available
333 * from {@code in}, or (unlikely) the size
334 * of the underlying stream got smaller while
335 * this was reading from it
336 *
337 * @throws IOException may be thrown by {@code in}
338 *
339 * @since 1.7
340 */
341 public SeekableXZInputStream(SeekableInputStream in, int memoryLimit,
342 ArrayCache arrayCache)
343 throws IOException {
344 this(in, memoryLimit, true, arrayCache);
345 }
346
347 /**
348 * Creates a new seekable XZ decomporessor with an optional
349 * memory usage limit and ability to disable verification
350 * of integrity checks.
351 * <p>
352 * Note that integrity check verification should almost never be disabled.
353 * Possible reasons to disable integrity check verification:
354 * <ul>
355 * <li>Trying to recover data from a corrupt .xz file.</li>
356 * <li>Speeding up decompression. This matters mostly with SHA-256
357 * or with files that have compressed extremely well. It's recommended
358 * that integrity checking isn't disabled for performance reasons
359 * unless the file integrity is verified externally in some other
360 * way.</li>
361 * </ul>
362 * <p>
363 * {@code verifyCheck} only affects the integrity check of
364 * the actual compressed data. The CRC32 fields in the headers
365 * are always verified.
366 *
367 * @param in seekable input stream containing one or more
368 * XZ Streams; the whole input stream is used
369 *
370 * @param memoryLimit memory usage limit in kibibytes (KiB)
371 * or {@code -1} to impose no memory usage limit
372 *
373 * @param verifyCheck if {@code true}, the integrity checks
374 * will be verified; this should almost never
375 * be set to {@code false}
376 *
377 * @throws XZFormatException
378 * input is not in the XZ format
379 *
380 * @throws CorruptedInputException
381 * XZ data is corrupt or truncated
382 *
383 * @throws UnsupportedOptionsException
384 * XZ headers seem valid but they specify
385 * options not supported by this implementation
386 *
387 * @throws MemoryLimitException
388 * decoded XZ Indexes would need more memory
389 * than allowed by the memory usage limit
390 *
391 * @throws EOFException
392 * less than 6 bytes of input was available
393 * from {@code in}, or (unlikely) the size
394 * of the underlying stream got smaller while
395 * this was reading from it
396 *
397 * @throws IOException may be thrown by {@code in}
398 *
399 * @since 1.6
400 */
401 public SeekableXZInputStream(SeekableInputStream in, int memoryLimit,
402 boolean verifyCheck)
403 throws IOException {
404 this(in, memoryLimit, verifyCheck, ArrayCache.getDefaultCache());
405 }
406
407 /**
408 * Creates a new seekable XZ decomporessor with an optional
409 * memory usage limit and ability to disable verification
410 * of integrity checks.
411 * <p>
412 * This is identical to
413 * {@code SeekableXZInputStream(SeekableInputStream,int,boolean)}
414 * except that this also takes the {@code arrayCache} argument.
415 *
416 * @param in seekable input stream containing one or more
417 * XZ Streams; the whole input stream is used
418 *
419 * @param memoryLimit memory usage limit in kibibytes (KiB)
420 * or {@code -1} to impose no memory usage limit
421 *
422 * @param verifyCheck if {@code true}, the integrity checks
423 * will be verified; this should almost never
424 * be set to {@code false}
425 *
426 * @param arrayCache cache to be used for allocating large arrays
427 *
428 * @throws XZFormatException
429 * input is not in the XZ format
430 *
431 * @throws CorruptedInputException
432 * XZ data is corrupt or truncated
433 *
434 * @throws UnsupportedOptionsException
435 * XZ headers seem valid but they specify
436 * options not supported by this implementation
437 *
438 * @throws MemoryLimitException
439 * decoded XZ Indexes would need more memory
440 * than allowed by the memory usage limit
441 *
442 * @throws EOFException
443 * less than 6 bytes of input was available
444 * from {@code in}, or (unlikely) the size
445 * of the underlying stream got smaller while
446 * this was reading from it
447 *
448 * @throws IOException may be thrown by {@code in}
449 *
450 * @since 1.7
451 */
452 public SeekableXZInputStream(SeekableInputStream in, int memoryLimit,
453 boolean verifyCheck, ArrayCache arrayCache)
454 throws IOException {
455 this.arrayCache = arrayCache;
456 this.verifyCheck = verifyCheck;
457 this.in = in;
458 DataInputStream inData = new DataInputStream(in);
459
460 // Check the magic bytes in the beginning of the file.
461 {
462 in.seek(0);
463 byte[] buf = new byte[XZ.HEADER_MAGIC.length];
464 inData.readFully(buf);
465 if (!Arrays.equals(buf, XZ.HEADER_MAGIC))
466 throw new XZFormatException();
467 }
468
469 // Get the file size and verify that it is a multiple of 4 bytes.
470 long pos = in.length();
471 if ((pos & 3) != 0)
472 throw new CorruptedInputException(
473 "XZ file size is not a multiple of 4 bytes");
474
475 // Parse the headers starting from the end of the file.
476 byte[] buf = new byte[DecoderUtil.STREAM_HEADER_SIZE];
477 long streamPadding = 0;
478
479 while (pos > 0) {
480 if (pos < DecoderUtil.STREAM_HEADER_SIZE)
481 throw new CorruptedInputException();
482
483 // Read the potential Stream Footer.
484 in.seek(pos - DecoderUtil.STREAM_HEADER_SIZE);
485 inData.readFully(buf);
486
487 // Skip Stream Padding four bytes at a time.
488 // Skipping more at once would be faster,
489 // but usually there isn't much Stream Padding.
490 if (buf[8] == 0x00 && buf[9] == 0x00 && buf[10] == 0x00
491 && buf[11] == 0x00) {
492 streamPadding += 4;
493 pos -= 4;
494 continue;
495 }
496
497 // It's not Stream Padding. Update pos.
498 pos -= DecoderUtil.STREAM_HEADER_SIZE;
499
500 // Decode the Stream Footer and check if Backward Size
501 // looks reasonable.
502 StreamFlags streamFooter = DecoderUtil.decodeStreamFooter(buf);
503 if (streamFooter.backwardSize >= pos)
504 throw new CorruptedInputException(
505 "Backward Size in XZ Stream Footer is too big");
506
507 // Check that the Check ID is supported. Store it in case this
508 // is the first Stream in the file.
509 check = Check.getInstance(streamFooter.checkType);
510
511 // Remember which Check IDs have been seen.
512 checkTypes |= 1 << streamFooter.checkType;
513
514 // Seek to the beginning of the Index.
515 in.seek(pos - streamFooter.backwardSize);
516
517 // Decode the Index field.
518 IndexDecoder index;
519 try {
520 index = new IndexDecoder(in, streamFooter, streamPadding,
521 memoryLimit);
522 } catch (MemoryLimitException e) {
523 // IndexDecoder doesn't know how much memory we had
524 // already needed so we need to recreate the exception.
525 assert memoryLimit >= 0;
526 throw new MemoryLimitException(
527 e.getMemoryNeeded() + indexMemoryUsage,
528 memoryLimit + indexMemoryUsage);
529 }
530
531 // Update the memory usage and limit counters.
532 indexMemoryUsage += index.getMemoryUsage();
533 if (memoryLimit >= 0) {
534 memoryLimit -= index.getMemoryUsage();
535 assert memoryLimit >= 0;
536 }
537
538 // Remember the uncompressed size of the largest Block.
539 if (largestBlockSize < index.getLargestBlockSize())
540 largestBlockSize = index.getLargestBlockSize();
541
542 // Calculate the offset to the beginning of this XZ Stream and
543 // check that it looks sane.
544 long off = index.getStreamSize() - DecoderUtil.STREAM_HEADER_SIZE;
545 if (pos < off)
546 throw new CorruptedInputException("XZ Index indicates "
547 + "too big compressed size for the XZ Stream");
548
549 // Seek to the beginning of this Stream.
550 pos -= off;
551 in.seek(pos);
552
553 // Decode the Stream Header.
554 inData.readFully(buf);
555 StreamFlags streamHeader = DecoderUtil.decodeStreamHeader(buf);
556
557 // Verify that the Stream Header matches the Stream Footer.
558 if (!DecoderUtil.areStreamFlagsEqual(streamHeader, streamFooter))
559 throw new CorruptedInputException(
560 "XZ Stream Footer does not match Stream Header");
561
562 // Update the total uncompressed size of the file and check that
563 // it doesn't overflow.
564 uncompressedSize += index.getUncompressedSize();
565 if (uncompressedSize < 0)
566 throw new UnsupportedOptionsException("XZ file is too big");
567
568 // Update the Block count and check that it fits into an int.
569 blockCount += index.getRecordCount();
570 if (blockCount < 0)
571 throw new UnsupportedOptionsException(
572 "XZ file has over " + Integer.MAX_VALUE + " Blocks");
573
574 // Add this Stream to the list of Streams.
575 streams.add(index);
576
577 // Reset to be ready to parse the next Stream.
578 streamPadding = 0;
579 }
580
581 assert pos == 0;
582
583 // Save it now that indexMemoryUsage has been subtracted from it.
584 this.memoryLimit = memoryLimit;
585
586 // Store the relative offsets of the Streams. This way we don't
587 // need to recalculate them in this class when seeking; the
588 // IndexDecoder instances will handle them.
589 IndexDecoder prev = streams.get(streams.size() - 1);
590 for (int i = streams.size() - 2; i >= 0; --i) {
591 IndexDecoder cur = streams.get(i);
592 cur.setOffsets(prev);
593 prev = cur;
594 }
595
596 // Initialize curBlockInfo to point to the first Stream.
597 // The blockNumber will be left to -1 so that .hasNext()
598 // and .setNext() work to get the first Block when starting
599 // to decompress from the beginning of the file.
600 IndexDecoder first = streams.get(streams.size() - 1);
601 curBlockInfo = new BlockInfo(first);
602
603 // queriedBlockInfo needs to be allocated too. The Stream used for
604 // initialization doesn't matter though.
605 queriedBlockInfo = new BlockInfo(first);
606 }
607
608 /**
609 * Gets the types of integrity checks used in the .xz file.
610 * Multiple checks are possible only if there are multiple
611 * concatenated XZ Streams.
612 * <p>
613 * The returned value has a bit set for every check type that is present.
614 * For example, if CRC64 and SHA-256 were used, the return value is
615 * {@code (1 << XZ.CHECK_CRC64) | (1 << XZ.CHECK_SHA256)}.
616 */
617 public int getCheckTypes() {
618 return checkTypes;
619 }
620
621 /**
622 * Gets the amount of memory in kibibytes (KiB) used by
623 * the data structures needed to locate the XZ Blocks.
624 * This is usually useless information but since it is calculated
625 * for memory usage limit anyway, it is nice to make it available to too.
626 */
627 public int getIndexMemoryUsage() {
628 return indexMemoryUsage;
629 }
630
631 /**
632 * Gets the uncompressed size of the largest XZ Block in bytes.
633 * This can be useful if you want to check that the file doesn't
634 * have huge XZ Blocks which could make seeking to arbitrary offsets
635 * very slow. Note that huge Blocks don't automatically mean that
636 * seeking would be slow, for example, seeking to the beginning of
637 * any Block is always fast.
638 */
639 public long getLargestBlockSize() {
640 return largestBlockSize;
641 }
642
643 /**
644 * Gets the number of Streams in the .xz file.
645 *
646 * @since 1.3
647 */
648 public int getStreamCount() {
649 return streams.size();
650 }
651
652 /**
653 * Gets the number of Blocks in the .xz file.
654 *
655 * @since 1.3
656 */
657 public int getBlockCount() {
658 return blockCount;
659 }
660
661 /**
662 * Gets the uncompressed start position of the given Block.
663 *
664 * @throws IndexOutOfBoundsException if
665 * {@code blockNumber < 0} or
666 * {@code blockNumber >= getBlockCount()}.
667 *
668 * @since 1.3
669 */
670 public long getBlockPos(int blockNumber) {
671 locateBlockByNumber(queriedBlockInfo, blockNumber);
672 return queriedBlockInfo.uncompressedOffset;
673 }
674
675 /**
676 * Gets the uncompressed size of the given Block.
677 *
678 * @throws IndexOutOfBoundsException if
679 * {@code blockNumber < 0} or
680 * {@code blockNumber >= getBlockCount()}.
681 *
682 * @since 1.3
683 */
684 public long getBlockSize(int blockNumber) {
685 locateBlockByNumber(queriedBlockInfo, blockNumber);
686 return queriedBlockInfo.uncompressedSize;
687 }
688
689 /**
690 * Gets the position where the given compressed Block starts in
691 * the underlying .xz file.
692 * This information is rarely useful to the users of this class.
693 *
694 * @throws IndexOutOfBoundsException if
695 * {@code blockNumber < 0} or
696 * {@code blockNumber >= getBlockCount()}.
697 *
698 * @since 1.3
699 */
700 public long getBlockCompPos(int blockNumber) {
701 locateBlockByNumber(queriedBlockInfo, blockNumber);
702 return queriedBlockInfo.compressedOffset;
703 }
704
705 /**
706 * Gets the compressed size of the given Block.
707 * This together with the uncompressed size can be used to calculate
708 * the compression ratio of the specific Block.
709 *
710 * @throws IndexOutOfBoundsException if
711 * {@code blockNumber < 0} or
712 * {@code blockNumber >= getBlockCount()}.
713 *
714 * @since 1.3
715 */
716 public long getBlockCompSize(int blockNumber) {
717 locateBlockByNumber(queriedBlockInfo, blockNumber);
718 return (queriedBlockInfo.unpaddedSize + 3) & ~3;
719 }
720
721 /**
722 * Gets integrity check type (Check ID) of the given Block.
723 *
724 * @throws IndexOutOfBoundsException if
725 * {@code blockNumber < 0} or
726 * {@code blockNumber >= getBlockCount()}.
727 *
728 * @see #getCheckTypes()
729 *
730 * @since 1.3
731 */
732 public int getBlockCheckType(int blockNumber) {
733 locateBlockByNumber(queriedBlockInfo, blockNumber);
734 return queriedBlockInfo.getCheckType();
735 }
736
737 /**
738 * Gets the number of the Block that contains the byte at the given
739 * uncompressed position.
740 *
741 * @throws IndexOutOfBoundsException if
742 * {@code pos < 0} or
743 * {@code pos >= length()}.
744 *
745 * @since 1.3
746 */
747 public int getBlockNumber(long pos) {
748 locateBlockByPos(queriedBlockInfo, pos);
749 return queriedBlockInfo.blockNumber;
750 }
751
752 /**
753 * Decompresses the next byte from this input stream.
754 *
755 * @return the next decompressed byte, or {@code -1}
756 * to indicate the end of the compressed stream
757 *
758 * @throws CorruptedInputException
759 * @throws UnsupportedOptionsException
760 * @throws MemoryLimitException
761 *
762 * @throws XZIOException if the stream has been closed
763 *
764 * @throws IOException may be thrown by {@code in}
765 */
766 @Override
767 public int read() throws IOException {
768 return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
769 }
770
771 /**
772 * Decompresses into an array of bytes.
773 * <p>
774 * If {@code len} is zero, no bytes are read and {@code 0}
775 * is returned. Otherwise this will try to decompress {@code len}
776 * bytes of uncompressed data. Less than {@code len} bytes may
777 * be read only in the following situations:
778 * <ul>
779 * <li>The end of the compressed data was reached successfully.</li>
780 * <li>An error is detected after at least one but less than
781 * {@code len} bytes have already been successfully
782 * decompressed. The next call with non-zero {@code len}
783 * will immediately throw the pending exception.</li>
784 * <li>An exception is thrown.</li>
785 * </ul>
786 *
787 * @param buf target buffer for uncompressed data
788 * @param off start offset in {@code buf}
789 * @param len maximum number of uncompressed bytes to read
790 *
791 * @return number of bytes read, or {@code -1} to indicate
792 * the end of the compressed stream
793 *
794 * @throws CorruptedInputException
795 * @throws UnsupportedOptionsException
796 * @throws MemoryLimitException
797 *
798 * @throws XZIOException if the stream has been closed
799 *
800 * @throws IOException may be thrown by {@code in}
801 */
802 @Override
803 public int read(byte[] buf, int off, int len) throws IOException {
804 if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
805 throw new IndexOutOfBoundsException();
806
807 if (len == 0)
808 return 0;
809
810 if (in == null)
811 throw new XZIOException("Stream closed");
812
813 if (exception != null)
814 throw exception;
815
816 int size = 0;
817
818 try {
819 if (seekNeeded)
820 seek();
821
822 if (endReached)
823 return -1;
824
825 while (len > 0) {
826 if (blockDecoder == null) {
827 seek();
828 if (endReached)
829 break;
830 }
831
832 int ret = blockDecoder.read(buf, off, len);
833
834 if (ret > 0) {
835 curPos += ret;
836 size += ret;
837 off += ret;
838 len -= ret;
839 } else if (ret == -1) {
840 blockDecoder = null;
841 }
842 }
843 } catch (IOException e) {
844 // We know that the file isn't simply truncated because we could
845 // parse the Indexes in the constructor. So convert EOFException
846 // to CorruptedInputException.
847 if (e instanceof EOFException)
848 e = new CorruptedInputException();
849
850 exception = e;
851 if (size == 0)
852 throw e;
853 }
854
855 return size;
856 }
857
858 /**
859 * Returns the number of uncompressed bytes that can be read
860 * without blocking. The value is returned with an assumption
861 * that the compressed input data will be valid. If the compressed
862 * data is corrupt, {@code CorruptedInputException} may get
863 * thrown before the number of bytes claimed to be available have
864 * been read from this input stream.
865 *
866 * @return the number of uncompressed bytes that can be read
867 * without blocking
868 */
869 @Override
870 public int available() throws IOException {
871 if (in == null)
872 throw new XZIOException("Stream closed");
873
874 if (exception != null)
875 throw exception;
876
877 if (endReached || seekNeeded || blockDecoder == null)
878 return 0;
879
880 return blockDecoder.available();
881 }
882
883 /**
884 * Closes the stream and calls {@code in.close()}.
885 * If the stream was already closed, this does nothing.
886 * <p>
887 * This is equivalent to {@code close(true)}.
888 *
889 * @throws IOException if thrown by {@code in.close()}
890 */
891 @Override
892 public void close() throws IOException {
893 close(true);
894 }
895
896 /**
897 * Closes the stream and optionally calls {@code in.close()}.
898 * If the stream was already closed, this does nothing.
899 * If {@code close(false)} has been called, a further call of
900 * {@code close(true)} does nothing (it doesn't call {@code in.close()}).
901 * <p>
902 * If you don't want to close the underlying {@code InputStream},
903 * there is usually no need to worry about closing this stream either;
904 * it's fine to do nothing and let the garbage collector handle it.
905 * However, if you are using {@link ArrayCache}, {@code close(false)}
906 * can be useful to put the allocated arrays back to the cache without
907 * closing the underlying {@code InputStream}.
908 * <p>
909 * Note that if you successfully reach the end of the stream
910 * ({@code read} returns {@code -1}), the arrays are automatically
911 * put back to the cache by that {@code read} call. In this
912 * situation {@code close(false)} is redundant (but harmless).
913 *
914 * @throws IOException if thrown by {@code in.close()}
915 *
916 * @since 1.7
917 */
918 public void close(boolean closeInput) throws IOException {
919 if (in != null) {
920 if (blockDecoder != null) {
921 blockDecoder.close();
922 blockDecoder = null;
923 }
924
925 try {
926 if (closeInput)
927 in.close();
928 } finally {
929 in = null;
930 }
931 }
932 }
933
934 /**
935 * Gets the uncompressed size of this input stream. If there are multiple
936 * XZ Streams, the total uncompressed size of all XZ Streams is returned.
937 */
938 @Override
939 public long length() {
940 return uncompressedSize;
941 }
942
943 /**
944 * Gets the current uncompressed position in this input stream.
945 *
946 * @throws XZIOException if the stream has been closed
947 */
948 @Override
949 public long position() throws IOException {
950 if (in == null)
951 throw new XZIOException("Stream closed");
952
953 return seekNeeded ? seekPos : curPos;
954 }
955
956 /**
957 * Seeks to the specified absolute uncompressed position in the stream.
958 * This only stores the new position, so this function itself is always
959 * very fast. The actual seek is done when {@code read} is called
960 * to read at least one byte.
961 * <p>
962 * Seeking past the end of the stream is possible. In that case
963 * {@code read} will return {@code -1} to indicate the end of the stream.
964 *
965 * @param pos new uncompressed read position
966 *
967 * @throws XZIOException
968 * if {@code pos} is negative, or
969 * if stream has been closed
970 */
971 @Override
972 public void seek(long pos) throws IOException {
973 if (in == null)
974 throw new XZIOException("Stream closed");
975
976 if (pos < 0)
977 throw new XZIOException("Negative seek position: " + pos);
978
979 seekPos = pos;
980 seekNeeded = true;
981 }
982
983 /**
984 * Seeks to the beginning of the given XZ Block.
985 *
986 * @throws XZIOException
987 * if {@code blockNumber < 0} or
988 * {@code blockNumber >= getBlockCount()},
989 * or if stream has been closed
990 *
991 * @since 1.3
992 */
993 public void seekToBlock(int blockNumber) throws IOException {
994 if (in == null)
995 throw new XZIOException("Stream closed");
996
997 if (blockNumber < 0 || blockNumber >= blockCount)
998 throw new XZIOException("Invalid XZ Block number: " + blockNumber);
999
1000 // This is a bit silly implementation. Here we locate the uncompressed
1001 // offset of the specified Block, then when doing the actual seek in
1002 // seek(), we need to find the Block number based on seekPos.
1003 //
1004 // NOTE: getBlockPos is a public method that can be overridden.
1005 // Version 1.9 and older called getBlockPos(blockNumber) here.
1006 // Since 1.10, the private method locateBlockByNumber is used
1007 // directly to ensure that subclasses cannot affect the behavior.
1008 locateBlockByNumber(queriedBlockInfo, blockNumber);
1009 seekPos = queriedBlockInfo.uncompressedOffset;
1010 seekNeeded = true;
1011 }
1012
1013 /**
1014 * Does the actual seeking. This is also called when {@code read}
1015 * needs a new Block to decode.
1016 */
1017 private void seek() throws IOException {
1018 // If seek(long) wasn't called, we simply need to get the next Block
1019 // from the same Stream. If there are no more Blocks in this Stream,
1020 // then we behave as if seek(long) had been called.
1021 if (!seekNeeded) {
1022 if (curBlockInfo.hasNext()) {
1023 curBlockInfo.setNext();
1024 initBlockDecoder();
1025 return;
1026 }
1027
1028 seekPos = curPos;
1029 }
1030
1031 seekNeeded = false;
1032
1033 // Check if we are seeking to or past the end of the file.
1034 if (seekPos >= uncompressedSize) {
1035 curPos = seekPos;
1036
1037 if (blockDecoder != null) {
1038 blockDecoder.close();
1039 blockDecoder = null;
1040 }
1041
1042 endReached = true;
1043 return;
1044 }
1045
1046 endReached = false;
1047
1048 // Locate the Block that contains the uncompressed target position.
1049 locateBlockByPos(curBlockInfo, seekPos);
1050
1051 // Seek in the underlying stream and create a new Block decoder
1052 // only if really needed. We can skip it if the current position
1053 // is already in the correct Block and the target position hasn't
1054 // been decompressed yet.
1055 //
1056 // NOTE: If curPos points to the beginning of this Block, it's
1057 // because it was left there after decompressing an earlier Block.
1058 // In that case, decoding of the current Block hasn't been started
1059 // yet. (Decoding of a Block won't be started until at least one
1060 // byte will also be read from it.)
1061 if (!(curPos > curBlockInfo.uncompressedOffset && curPos <= seekPos)) {
1062 // Seek to the beginning of the Block.
1063 in.seek(curBlockInfo.compressedOffset);
1064
1065 // Since it is possible that this Block is from a different
1066 // Stream than the previous Block, initialize a new Check.
1067 check = Check.getInstance(curBlockInfo.getCheckType());
1068
1069 // Create a new Block decoder.
1070 initBlockDecoder();
1071 curPos = curBlockInfo.uncompressedOffset;
1072 }
1073
1074 // If the target wasn't at a Block boundary, decompress and throw
1075 // away data to reach the target position.
1076 if (seekPos > curPos) {
1077 // NOTE: The "if" below is there just in case. In this situation,
1078 // blockDecoder.skip will always skip the requested amount
1079 // or throw an exception.
1080 long skipAmount = seekPos - curPos;
1081 if (blockDecoder.skip(skipAmount) != skipAmount)
1082 throw new CorruptedInputException();
1083
1084 curPos = seekPos;
1085 }
1086 }
1087
1088 /**
1089 * Locates the Block that contains the given uncompressed position.
1090 */
1091 private void locateBlockByPos(BlockInfo info, long pos) {
1092 if (pos < 0 || pos >= uncompressedSize)
1093 throw new IndexOutOfBoundsException(
1094 "Invalid uncompressed position: " + pos);
1095
1096 // Locate the Stream that contains the target position.
1097 IndexDecoder index;
1098 for (int i = 0; ; ++i) {
1099 index = streams.get(i);
1100 if (index.hasUncompressedOffset(pos))
1101 break;
1102 }
1103
1104 // Locate the Block from the Stream that contains the target position.
1105 index.locateBlock(info, pos);
1106
1107 assert (info.compressedOffset & 3) == 0;
1108 assert info.uncompressedSize > 0;
1109 assert pos >= info.uncompressedOffset;
1110 assert pos < info.uncompressedOffset + info.uncompressedSize;
1111 }
1112
1113 /**
1114 * Locates the given Block and stores information about it
1115 * to {@code info}.
1116 */
1117 private void locateBlockByNumber(BlockInfo info, int blockNumber) {
1118 // Validate.
1119 if (blockNumber < 0 || blockNumber >= blockCount)
1120 throw new IndexOutOfBoundsException(
1121 "Invalid XZ Block number: " + blockNumber);
1122
1123 // Skip the search if info already points to the correct Block.
1124 if (info.blockNumber == blockNumber)
1125 return;
1126
1127 // Search the Stream that contains the given Block and then
1128 // search the Block from that Stream.
1129 for (int i = 0; ; ++i) {
1130 IndexDecoder index = streams.get(i);
1131 if (index.hasRecord(blockNumber)) {
1132 index.setBlockInfo(info, blockNumber);
1133 return;
1134 }
1135 }
1136 }
1137
1138 /**
1139 * Initializes a new BlockInputStream. This is a helper function for
1140 * {@code seek()}.
1141 */
1142 private void initBlockDecoder() throws IOException {
1143 try {
1144 // Set it to null first so that GC can collect it if memory
1145 // runs tight when initializing a new BlockInputStream.
1146 if (blockDecoder != null) {
1147 blockDecoder.close();
1148 blockDecoder = null;
1149 }
1150
1151 blockDecoder = new BlockInputStream(
1152 in, check, verifyCheck, memoryLimit,
1153 curBlockInfo.unpaddedSize, curBlockInfo.uncompressedSize,
1154 arrayCache);
1155 } catch (MemoryLimitException e) {
1156 // BlockInputStream doesn't know how much memory we had
1157 // already needed so we need to recreate the exception.
1158 assert memoryLimit >= 0;
1159 throw new MemoryLimitException(
1160 e.getMemoryNeeded() + indexMemoryUsage,
1161 memoryLimit + indexMemoryUsage);
1162 } catch (IndexIndicatorException e) {
1163 // It cannot be Index so the file must be corrupt.
1164 throw new CorruptedInputException();
1165 }
1166 }
1167 }