Debian Codegraph @

src/org/tukaani/xz/LZMAInputStream.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 // SPDX-FileContributor: Igor Pavlov <https://7-zip.org/>
5
6 package org.tukaani.xz;
7
8 import java.io.InputStream;
9 import java.io.DataInputStream;
10 import java.io.IOException;
11 import java.io.EOFException;
12 import org.tukaani.xz.lz.LZDecoder;
13 import org.tukaani.xz.rangecoder.RangeDecoderFromStream;
14 import org.tukaani.xz.lzma.LZMADecoder;
15
16 /**
17 * Decompresses legacy .lzma files and raw LZMA streams (no .lzma header).
18 * <p>
19 * <b>IMPORTANT:</b> In contrast to other classes in this package, this class
20 * reads data from its input stream one byte at a time. If the input stream
21 * is for example {@link java.io.FileInputStream}, wrapping it into
22 * {@link java.io.BufferedInputStream} tends to improve performance a lot.
23 * This is not automatically done by this class because there may be use
24 * cases where it is desired that this class won't read any bytes past
25 * the end of the LZMA stream.
26 * <p>
27 * Even when using {@code BufferedInputStream}, the performance tends
28 * to be worse (maybe 10-20&nbsp;% slower) than with {@link LZMA2InputStream}
29 * or {@link XZInputStream} (when the .xz file contains LZMA2-compressed data).
30 *
31 * @since 1.4
32 */
33 public class LZMAInputStream extends InputStream {
34 /**
35 * Largest dictionary size supported by this implementation.
36 * <p>
37 * LZMA allows dictionaries up to one byte less than 4 GiB. This
38 * implementation supports only 16 bytes less than 2 GiB. This
39 * limitation is due to Java using signed 32-bit integers for array
40 * indexing. The limitation shouldn't matter much in practice since so
41 * huge dictionaries are not normally used.
42 */
43 public static final int DICT_SIZE_MAX = Integer.MAX_VALUE & ~15;
44
45 private InputStream in;
46 private ArrayCache arrayCache;
47 private LZDecoder lz;
48 private RangeDecoderFromStream rc;
49 private LZMADecoder lzma;
50
51 private boolean endReached = false;
52 private boolean relaxedEndCondition = false;
53
54 private final byte[] tempBuf = new byte[1];
55
56 /**
57 * Number of uncompressed bytes left to be decompressed, or -1 if
58 * the end marker is used.
59 */
60 private long remainingSize;
61
62 private IOException exception = null;
63
64 /**
65 * Gets approximate decompressor memory requirements as kibibytes for
66 * the given dictionary size and LZMA properties byte (lc, lp, and pb).
67 *
68 * @param dictSize LZMA dictionary size as bytes, should be in
69 * the range [{@code 0}, {@code DICT_SIZE_MAX}]
70 *
71 * @param propsByte LZMA properties byte that encodes the values
72 * of lc, lp, and pb
73 *
74 * @return approximate memory requirements as kibibytes (KiB)
75 *
76 * @throws UnsupportedOptionsException
77 * if {@code dictSize} is outside the
78 * range [{@code 0}, {@code DICT_SIZE_MAX}]
79 *
80 * @throws CorruptedInputException
81 * if {@code propsByte} is invalid
82 */
83 public static int getMemoryUsage(int dictSize, byte propsByte)
84 throws UnsupportedOptionsException, CorruptedInputException {
85 if (dictSize < 0 || dictSize > DICT_SIZE_MAX)
86 throw new UnsupportedOptionsException(
87 "LZMA dictionary is too big for this implementation");
88
89 int props = propsByte & 0xFF;
90 if (props > (4 * 5 + 4) * 9 + 8)
91 throw new CorruptedInputException("Invalid LZMA properties byte");
92
93 props %= 9 * 5;
94 int lp = props / 9;
95 int lc = props - lp * 9;
96
97 return getMemoryUsage(dictSize, lc, lp);
98 }
99
100 /**
101 * Gets approximate decompressor memory requirements as kibibytes for
102 * the given dictionary size, lc, and lp. Note that pb isn't needed.
103 *
104 * @param dictSize LZMA dictionary size as bytes, must be in
105 * the range [{@code 0}, {@code DICT_SIZE_MAX}]
106 *
107 * @param lc number of literal context bits, must be
108 * in the range [0, 8]
109 *
110 * @param lp number of literal position bits, must be
111 * in the range [0, 4]
112 *
113 * @return approximate memory requirements as kibibytes (KiB)
114 */
115 public static int getMemoryUsage(int dictSize, int lc, int lp) {
116 if (lc < 0 || lc > 8 || lp < 0 || lp > 4)
117 throw new IllegalArgumentException("Invalid lc or lp");
118
119 // Probability variables have the type "short". There are
120 // 0x300 (768) probability variables in each literal subcoder.
121 // The number of literal subcoders is 2^(lc + lp).
122 //
123 // Roughly 10 KiB for the base state + LZ decoder's dictionary buffer
124 // + sizeof(short) * number probability variables per literal subcoder
125 // * number of literal subcoders
126 return 10 + getDictSize(dictSize) / 1024
127 + ((2 * 0x300) << (lc + lp)) / 1024;
128 }
129
130 private static int getDictSize(int dictSize) {
131 if (dictSize < 0 || dictSize > DICT_SIZE_MAX)
132 throw new IllegalArgumentException(
133 "LZMA dictionary is too big for this implementation");
134
135 // For performance reasons, use a 4 KiB dictionary if something
136 // smaller was requested. It's a rare situation and the performance
137 // difference isn't huge, and it starts to matter mostly when the
138 // dictionary is just a few bytes. But we need to handle the special
139 // case of dictSize == 0 anyway, which is an allowed value but in
140 // practice means one-byte dictionary.
141 //
142 // Note that using a dictionary bigger than specified in the headers
143 // can hide errors if there is a reference to data beyond the original
144 // dictionary size but is still within 4 KiB.
145 if (dictSize < 4096)
146 dictSize = 4096;
147
148 // Round dictionary size upward to a multiple of 16. This way LZMA
149 // can use LZDecoder.getPos() for calculating LZMA's posMask.
150 return (dictSize + 15) & ~15;
151 }
152
153 /**
154 * Creates a new .lzma file format decompressor without
155 * a memory usage limit.
156 *
157 * @param in input stream from which .lzma data is read;
158 * it might be a good idea to wrap it in
159 * {@code BufferedInputStream}, see the
160 * note at the top of this page
161 *
162 * @throws CorruptedInputException
163 * file is corrupt or perhaps not in
164 * the .lzma format at all
165 *
166 * @throws UnsupportedOptionsException
167 * dictionary size or uncompressed size is too
168 * big for this implementation
169 *
170 * @throws EOFException
171 * file is truncated or perhaps not in
172 * the .lzma format at all
173 *
174 * @throws IOException may be thrown by {@code in}
175 */
176 public LZMAInputStream(InputStream in) throws IOException {
177 this(in, -1);
178 }
179
180 /**
181 * Creates a new .lzma file format decompressor without
182 * a memory usage limit.
183 * <p>
184 * This is identical to {@code LZMAInputStream(InputStream)}
185 * except that this also takes the {@code arrayCache} argument.
186 *
187 * @param in input stream from which .lzma data is read;
188 * it might be a good idea to wrap it in
189 * {@code BufferedInputStream}, see the
190 * note at the top of this page
191 *
192 *
193 * @param arrayCache cache to be used for allocating large arrays
194 *
195 * @throws CorruptedInputException
196 * file is corrupt or perhaps not in
197 * the .lzma format at all
198 *
199 * @throws UnsupportedOptionsException
200 * dictionary size or uncompressed size is too
201 * big for this implementation
202 *
203 * @throws EOFException
204 * file is truncated or perhaps not in
205 * the .lzma format at all
206 *
207 * @throws IOException may be thrown by {@code in}
208 *
209 * @since 1.7
210 */
211 public LZMAInputStream(InputStream in, ArrayCache arrayCache)
212 throws IOException {
213 this(in, -1, arrayCache);
214 }
215
216 /**
217 * Creates a new .lzma file format decompressor with an optional
218 * memory usage limit.
219 *
220 * @param in input stream from which .lzma data is read;
221 * it might be a good idea to wrap it in
222 * {@code BufferedInputStream}, see the
223 * note at the top of this page
224 *
225 * @param memoryLimit memory usage limit in kibibytes (KiB)
226 * or {@code -1} to impose no memory usage limit
227 *
228 * @throws CorruptedInputException
229 * file is corrupt or perhaps not in
230 * the .lzma format at all
231 *
232 * @throws UnsupportedOptionsException
233 * dictionary size or uncompressed size is too
234 * big for this implementation
235 *
236 * @throws MemoryLimitException
237 * memory usage limit was exceeded
238 *
239 * @throws EOFException
240 * file is truncated or perhaps not in
241 * the .lzma format at all
242 *
243 * @throws IOException may be thrown by {@code in}
244 */
245 public LZMAInputStream(InputStream in, int memoryLimit)
246 throws IOException {
247 this(in, memoryLimit, ArrayCache.getDefaultCache());
248 }
249
250 /**
251 * Creates a new .lzma file format decompressor with an optional
252 * memory usage limit.
253 * <p>
254 * This is identical to {@code LZMAInputStream(InputStream, int)}
255 * except that this also takes the {@code arrayCache} argument.
256 *
257 * @param in input stream from which .lzma data is read;
258 * it might be a good idea to wrap it in
259 * {@code BufferedInputStream}, see the
260 * note at the top of this page
261 *
262 * @param memoryLimit memory usage limit in kibibytes (KiB)
263 * or {@code -1} to impose no memory usage limit
264 *
265 * @param arrayCache cache to be used for allocating large arrays
266 *
267 * @throws CorruptedInputException
268 * file is corrupt or perhaps not in
269 * the .lzma format at all
270 *
271 * @throws UnsupportedOptionsException
272 * dictionary size or uncompressed size is too
273 * big for this implementation
274 *
275 * @throws MemoryLimitException
276 * memory usage limit was exceeded
277 *
278 * @throws EOFException
279 * file is truncated or perhaps not in
280 * the .lzma format at all
281 *
282 * @throws IOException may be thrown by {@code in}
283 *
284 * @since 1.7
285 */
286 public LZMAInputStream(InputStream in, int memoryLimit,
287 ArrayCache arrayCache) throws IOException {
288 DataInputStream inData = new DataInputStream(in);
289
290 // Properties byte (lc, lp, and pb)
291 byte propsByte = inData.readByte();
292
293 // Dictionary size is an unsigned 32-bit little endian integer.
294 int dictSize = 0;
295 for (int i = 0; i < 4; ++i)
296 dictSize |= inData.readUnsignedByte() << (8 * i);
297
298 // Uncompressed size is an unsigned 64-bit little endian integer.
299 // The maximum 64-bit value is a special case (becomes -1 here)
300 // which indicates that the end marker is used instead of knowing
301 // the uncompressed size beforehand.
302 long uncompSize = 0;
303 for (int i = 0; i < 8; ++i)
304 uncompSize |= (long)inData.readUnsignedByte() << (8 * i);
305
306 // Check the memory usage limit.
307 int memoryNeeded = getMemoryUsage(dictSize, propsByte);
308 if (memoryLimit != -1 && memoryNeeded > memoryLimit)
309 throw new MemoryLimitException(memoryNeeded, memoryLimit);
310
311 // While rare, .lzma files with known uncompressed size and EOPM
312 // are valid and do exist. Such files were diagnosed as corrupt
313 // before XZ for Java 1.10, and similarly by XZ Utils before 5.2.6.
314 relaxedEndCondition = true;
315
316 initialize(in, uncompSize, propsByte, dictSize, null, arrayCache);
317 }
318
319 /**
320 * Creates a new input stream that decompresses raw LZMA data (no .lzma
321 * header) from {@code in}.
322 * <p>
323 * The caller needs to know if the "end of payload marker (EOPM)" alias
324 * "end of stream marker (EOS marker)" alias "end marker" present.
325 * If the end marker isn't used, the caller must know the exact
326 * uncompressed size of the stream.
327 * <p>
328 * The caller also needs to provide the LZMA properties byte that encodes
329 * the number of literal context bits (lc), literal position bits (lp),
330 * and position bits (pb).
331 * <p>
332 * The dictionary size used when compressing is also needed. Specifying
333 * a too small dictionary size will prevent decompressing the stream.
334 * Specifying a too big dictionary is waste of memory but decompression
335 * will work.
336 * <p>
337 * There is no need to specify a dictionary bigger than
338 * the uncompressed size of the data even if a bigger dictionary
339 * was used when compressing. If you know the uncompressed size
340 * of the data, this might allow saving some memory.
341 *
342 * @param in input stream from which compressed
343 * data is read
344 *
345 * @param uncompSize uncompressed size of the LZMA stream or -1
346 * if the end marker is used in the LZMA stream
347 *
348 * @param propsByte LZMA properties byte that has the encoded
349 * values for literal context bits (lc), literal
350 * position bits (lp), and position bits (pb)
351 *
352 * @param dictSize dictionary size as bytes, must be in the range
353 * [{@code 0}, {@code DICT_SIZE_MAX}]
354 *
355 * @throws CorruptedInputException
356 * if {@code propsByte} is invalid or
357 * the first input byte is not 0x00
358 *
359 * @throws UnsupportedOptionsException
360 * dictionary size or uncompressed size is too
361 * big for this implementation
362 *
363 *
364 */
365 public LZMAInputStream(InputStream in, long uncompSize, byte propsByte,
366 int dictSize) throws IOException {
367 initialize(in, uncompSize, propsByte, dictSize, null,
368 ArrayCache.getDefaultCache());
369 }
370
371 /**
372 * Creates a new input stream that decompresses raw LZMA data (no .lzma
373 * header) from {@code in} optionally with a preset dictionary.
374 *
375 * @param in input stream from which LZMA-compressed
376 * data is read
377 *
378 * @param uncompSize uncompressed size of the LZMA stream or -1
379 * if the end marker is used in the LZMA stream
380 *
381 * @param propsByte LZMA properties byte that has the encoded
382 * values for literal context bits (lc), literal
383 * position bits (lp), and position bits (pb)
384 *
385 * @param dictSize dictionary size as bytes, must be in the range
386 * [{@code 0}, {@code DICT_SIZE_MAX}]
387 *
388 * @param presetDict preset dictionary or {@code null}
389 * to use no preset dictionary
390 *
391 * @throws CorruptedInputException
392 * if {@code propsByte} is invalid or
393 * the first input byte is not 0x00
394 *
395 * @throws UnsupportedOptionsException
396 * dictionary size or uncompressed size is too
397 * big for this implementation
398 *
399 * @throws EOFException file is truncated or corrupt
400 *
401 * @throws IOException may be thrown by {@code in}
402 */
403 public LZMAInputStream(InputStream in, long uncompSize, byte propsByte,
404 int dictSize, byte[] presetDict)
405 throws IOException {
406 initialize(in, uncompSize, propsByte, dictSize, presetDict,
407 ArrayCache.getDefaultCache());
408 }
409
410 /**
411 * Creates a new input stream that decompresses raw LZMA data (no .lzma
412 * header) from {@code in} optionally with a preset dictionary.
413 * <p>
414 * This is identical to {@code LZMAInputStream(InputStream, long, byte,
415 * int, byte[])} except that this also takes the {@code arrayCache}
416 * argument.
417 *
418 * @param in input stream from which LZMA-compressed
419 * data is read
420 *
421 * @param uncompSize uncompressed size of the LZMA stream or -1
422 * if the end marker is used in the LZMA stream
423 *
424 * @param propsByte LZMA properties byte that has the encoded
425 * values for literal context bits (lc), literal
426 * position bits (lp), and position bits (pb)
427 *
428 * @param dictSize dictionary size as bytes, must be in the range
429 * [{@code 0}, {@code DICT_SIZE_MAX}]
430 *
431 * @param presetDict preset dictionary or {@code null}
432 * to use no preset dictionary
433 *
434 * @param arrayCache cache to be used for allocating large arrays
435 *
436 * @throws CorruptedInputException
437 * if {@code propsByte} is invalid or
438 * the first input byte is not 0x00
439 *
440 * @throws UnsupportedOptionsException
441 * dictionary size or uncompressed size is too
442 * big for this implementation
443 *
444 * @throws EOFException file is truncated or corrupt
445 *
446 * @throws IOException may be thrown by {@code in}
447 *
448 * @since 1.7
449 */
450 public LZMAInputStream(InputStream in, long uncompSize, byte propsByte,
451 int dictSize, byte[] presetDict,
452 ArrayCache arrayCache)
453 throws IOException {
454 initialize(in, uncompSize, propsByte, dictSize, presetDict,
455 arrayCache);
456 }
457
458 /**
459 * Creates a new input stream that decompresses raw LZMA data (no .lzma
460 * header) from {@code in} optionally with a preset dictionary.
461 *
462 * @param in input stream from which LZMA-compressed
463 * data is read
464 *
465 * @param uncompSize uncompressed size of the LZMA stream or -1
466 * if the end marker is used in the LZMA stream
467 *
468 * @param lc number of literal context bits, must be
469 * in the range [0, 8]
470 *
471 * @param lp number of literal position bits, must be
472 * in the range [0, 4]
473 *
474 * @param pb number position bits, must be
475 * in the range [0, 4]
476 *
477 * @param dictSize dictionary size as bytes, must be in the range
478 * [{@code 0}, {@code DICT_SIZE_MAX}]
479 *
480 * @param presetDict preset dictionary or {@code null}
481 * to use no preset dictionary
482 *
483 * @throws CorruptedInputException
484 * if the first input byte is not 0x00
485 *
486 * @throws EOFException file is truncated or corrupt
487 *
488 * @throws IOException may be thrown by {@code in}
489 */
490 public LZMAInputStream(InputStream in, long uncompSize,
491 int lc, int lp, int pb,
492 int dictSize, byte[] presetDict)
493 throws IOException {
494 initialize(in, uncompSize, lc, lp, pb, dictSize, presetDict,
495 ArrayCache.getDefaultCache());
496 }
497
498 /**
499 * Creates a new input stream that decompresses raw LZMA data (no .lzma
500 * header) from {@code in} optionally with a preset dictionary.
501 * <p>
502 * This is identical to {@code LZMAInputStream(InputStream, long, int,
503 * int, int, int, byte[])} except that this also takes the
504 * {@code arrayCache} argument.
505 *
506 * @param in input stream from which LZMA-compressed
507 * data is read
508 *
509 * @param uncompSize uncompressed size of the LZMA stream or -1
510 * if the end marker is used in the LZMA stream
511 *
512 * @param lc number of literal context bits, must be
513 * in the range [0, 8]
514 *
515 * @param lp number of literal position bits, must be
516 * in the range [0, 4]
517 *
518 * @param pb number position bits, must be
519 * in the range [0, 4]
520 *
521 * @param dictSize dictionary size as bytes, must be in the range
522 * [{@code 0}, {@code DICT_SIZE_MAX}]
523 *
524 * @param presetDict preset dictionary or {@code null}
525 * to use no preset dictionary
526 *
527 * @param arrayCache cache to be used for allocating large arrays
528 *
529 * @throws CorruptedInputException
530 * if the first input byte is not 0x00
531 *
532 * @throws EOFException file is truncated or corrupt
533 *
534 * @throws IOException may be thrown by {@code in}
535 *
536 * @since 1.7
537 */
538 public LZMAInputStream(InputStream in, long uncompSize,
539 int lc, int lp, int pb,
540 int dictSize, byte[] presetDict,
541 ArrayCache arrayCache)
542 throws IOException {
543 initialize(in, uncompSize, lc, lp, pb, dictSize, presetDict,
544 arrayCache);
545 }
546
547 private void initialize(InputStream in, long uncompSize, byte propsByte,
548 int dictSize, byte[] presetDict,
549 ArrayCache arrayCache)
550 throws IOException {
551 // Validate the uncompressed size since the other "initialize" throws
552 // IllegalArgumentException if uncompSize < -1.
553 if (uncompSize < -1)
554 throw new UnsupportedOptionsException(
555 "Uncompressed size is too big");
556
557 // Decode the properties byte. In contrast to LZMA2, there is no
558 // limit of lc + lp <= 4.
559 int props = propsByte & 0xFF;
560 if (props > (4 * 5 + 4) * 9 + 8)
561 throw new CorruptedInputException("Invalid LZMA properties byte");
562
563 int pb = props / (9 * 5);
564 props -= pb * 9 * 5;
565 int lp = props / 9;
566 int lc = props - lp * 9;
567
568 // Validate the dictionary size since the other "initialize" throws
569 // IllegalArgumentException if dictSize is not supported.
570 if (dictSize < 0 || dictSize > DICT_SIZE_MAX)
571 throw new UnsupportedOptionsException(
572 "LZMA dictionary is too big for this implementation");
573
574 initialize(in, uncompSize, lc, lp, pb, dictSize, presetDict,
575 arrayCache);
576 }
577
578 private void initialize(InputStream in, long uncompSize,
579 int lc, int lp, int pb,
580 int dictSize, byte[] presetDict,
581 ArrayCache arrayCache)
582 throws IOException {
583 // getDictSize validates dictSize and gives a message in
584 // the exception too, so skip validating dictSize here.
585 if (uncompSize < -1 || lc < 0 || lc > 8 || lp < 0 || lp > 4
586 || pb < 0 || pb > 4)
587 throw new IllegalArgumentException();
588
589 this.in = in;
590 this.arrayCache = arrayCache;
591
592 // If uncompressed size is known, use it to avoid wasting memory for
593 // a uselessly large dictionary buffer.
594 dictSize = getDictSize(dictSize);
595 if (uncompSize >= 0 && dictSize > uncompSize)
596 dictSize = getDictSize((int)uncompSize);
597
598 lz = new LZDecoder(getDictSize(dictSize), presetDict, arrayCache);
599 rc = new RangeDecoderFromStream(in);
600 lzma = new LZMADecoder(lz, rc, lc, lp, pb);
601
602 remainingSize = uncompSize;
603 }
604
605 /**
606 * Enables relaxed end-of-stream condition when uncompressed size is known.
607 * This is useful if uncompressed size is known but it is unknown if
608 * the end of stream (EOS) marker is present. After calling this function,
609 * both are allowed.
610 * <p>
611 * This feature was intrudced in XZ for Java 1.9 but it was more relaxed
612 * than it needed to be. It didn't actually check if the EOS marker was
613 * present, which made error detection slightly weaker than it needed
614 * to be. It also meant that after {@code read} had returned
615 * {@code -1}, the input position might not have been at
616 * the end of the stream (too little input may have been read).
617 * These problems were fixed in XZ for Java 1.10.
618 * <p>
619 * This should be called after the constructor before reading any data
620 * from the stream. This is a separate function because adding even more
621 * constructors to this class didn't look like a good alternative.
622 *
623 * @since 1.9
624 */
625 public void enableRelaxedEndCondition() {
626 relaxedEndCondition = true;
627 }
628
629 /**
630 * Decompresses the next byte from this input stream.
631 * <p>
632 * Reading lots of data with {@code read()} from this input stream
633 * may be inefficient. Wrap it in {@code java.io.BufferedInputStream}
634 * if you need to read lots of data one byte at a time.
635 *
636 * @return the next decompressed byte, or {@code -1}
637 * to indicate the end of the compressed stream
638 *
639 * @throws CorruptedInputException
640 *
641 * @throws XZIOException if the stream has been closed
642 *
643 * @throws EOFException
644 * compressed input is truncated or corrupt
645 *
646 * @throws IOException may be thrown by {@code in}
647 */
648 @Override
649 public int read() throws IOException {
650 return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
651 }
652
653 /**
654 * Decompresses into an array of bytes.
655 * <p>
656 * If {@code len} is zero, no bytes are read and {@code 0}
657 * is returned. Otherwise this will block until {@code len}
658 * bytes have been decompressed, the end of the LZMA stream is reached,
659 * or an exception is thrown.
660 *
661 * @param buf target buffer for uncompressed data
662 * @param off start offset in {@code buf}
663 * @param len maximum number of uncompressed bytes to read
664 *
665 * @return number of bytes read, or {@code -1} to indicate
666 * the end of the compressed stream
667 *
668 * @throws CorruptedInputException
669 *
670 * @throws XZIOException if the stream has been closed
671 *
672 * @throws EOFException compressed input is truncated or corrupt
673 *
674 * @throws IOException may be thrown by {@code in}
675 */
676 @Override
677 public int read(byte[] buf, int off, int len) throws IOException {
678 if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
679 throw new IndexOutOfBoundsException();
680
681 if (len == 0)
682 return 0;
683
684 if (in == null)
685 throw new XZIOException("Stream closed");
686
687 if (exception != null)
688 throw exception;
689
690 if (endReached)
691 return -1;
692
693 try {
694 int size = 0;
695
696 while (len > 0) {
697 // If uncompressed size is known and thus no end marker will
698 // be present, set the limit so that the uncompressed size
699 // won't be exceeded.
700 int copySizeMax = len;
701 if (remainingSize >= 0 && remainingSize < len)
702 copySizeMax = (int)remainingSize;
703
704 lz.setLimit(copySizeMax);
705
706 // Decode into the dictionary buffer.
707 try {
708 lzma.decode();
709 } catch (CorruptedInputException e) {
710 // The end marker is encoded with a LZMA symbol that
711 // indicates maximum match distance. This is larger
712 // than any supported dictionary and thus causes
713 // CorruptedInputException from LZDecoder.repeat.
714 if (remainingSize != -1 || !lzma.endMarkerDetected())
715 throw e;
716
717 endReached = true;
718
719 // The exception makes lzma.decode() miss the last range
720 // decoder normalization, so do it here. This might
721 // cause an IOException if it needs to read a byte
722 // from the input stream.
723 rc.normalize();
724 }
725
726 // Copy from the dictionary to buf.
727 int copiedSize = lz.flush(buf, off);
728 off += copiedSize;
729 len -= copiedSize;
730 size += copiedSize;
731
732 if (remainingSize >= 0) {
733 // Update the number of bytes left to be decompressed.
734 remainingSize -= copiedSize;
735 assert remainingSize >= 0;
736
737 if (remainingSize == 0)
738 endReached = true;
739 }
740
741 if (endReached) {
742 // If the last LZMA symbol was a match, there could be
743 // pending bytes waiting to be repeated. In that case
744 // the observed uncompressed size of the LZMA stream
745 // doesn't equal the known uncompressed size and the
746 // file is corrupt.
747 if (lz.hasPending())
748 throw new CorruptedInputException();
749
750 // If the range decoder is in the finished state, there
751 // is nothing more to do. LZMA Utils doesn't do this
752 // check and thus it accepts many invalid files that
753 // this implementation and XZ Utils don't.
754 if (!rc.isFinished()) {
755 // If uncompressed size is unknown: We must have
756 // gotten here because the end marker was detected.
757 // In that case the range decoder should have been
758 // in the finished state. Since it wasn't, the input
759 // is corrupt.
760 //
761 // If uncompressed size is known but the end marker
762 // isn't allowed, the input is corrupt.
763 if (remainingSize == -1 || !relaxedEndCondition)
764 throw new CorruptedInputException();
765
766 // Check if the end marker is present. We need to
767 // allow the decoder to attempt to decode one more
768 // output byte but it shouldn't produce any. Instead,
769 // we should get an exception indicating that the
770 // end marker was detected.
771 lz.setLimit(1);
772
773 boolean endMarkerDetected = false;
774
775 try {
776 lzma.decode();
777 } catch (CorruptedInputException e) {
778 if (!lzma.endMarkerDetected())
779 throw e;
780
781 endMarkerDetected = true;
782
783 // The exception makes lzma.decode() miss the last
784 // range decoder normalization, so do it here.
785 rc.normalize();
786 }
787
788 // The end marker must have been detected.
789 // The range decoder must be in the finished
790 // state after the above normalization.
791 if (!endMarkerDetected || !rc.isFinished())
792 throw new CorruptedInputException();
793
794 // lzma.decode() doesn't attempt to decode more input
795 // if there is no output space available. Since it
796 // just decoded the end marker, the one byte of output
797 // space from lz.setLimit(1) cannot have been consumed.
798 assert !lz.hasPending();
799 assert lz.hasSpace();
800 }
801
802 putArraysToCache();
803 return size == 0 ? -1 : size;
804 }
805 }
806
807 return size;
808
809 } catch (IOException e) {
810 exception = e;
811 throw e;
812 }
813 }
814
815 private void putArraysToCache() {
816 if (lz != null) {
817 lz.putArraysToCache(arrayCache);
818 lz = null;
819 }
820 }
821
822 /**
823 * Closes the stream and calls {@code in.close()}.
824 * If the stream was already closed, this does nothing.
825 *
826 * @throws IOException if thrown by {@code in.close()}
827 */
828 @Override
829 public void close() throws IOException {
830 if (in != null) {
831 putArraysToCache();
832
833 try {
834 in.close();
835 } finally {
836 in = null;
837 }
838 }
839 }
840 }