Debian Codegraph @

src/org/tukaani/xz/BlockInputStream.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.io.InputStream;
8 import java.io.DataInputStream;
9 import java.io.ByteArrayInputStream;
10 import java.io.IOException;
11 import java.util.Arrays;
12 import org.tukaani.xz.common.DecoderUtil;
13 import org.tukaani.xz.check.Check;
14
15 class BlockInputStream extends InputStream {
16 private final DataInputStream inData;
17 private final CountingInputStream inCounted;
18 private InputStream filterChain;
19 private final Check check;
20 private final boolean verifyCheck;
21
22 private long uncompressedSizeInHeader = -1;
23 private long compressedSizeInHeader = -1;
24 private long compressedSizeLimit;
25 private final int headerSize;
26 private long uncompressedSize = 0;
27 private boolean endReached = false;
28
29 private final byte[] tempBuf = new byte[1];
30
31 public BlockInputStream(InputStream in,
32 Check check, boolean verifyCheck,
33 int memoryLimit,
34 long unpaddedSizeInIndex,
35 long uncompressedSizeInIndex,
36 ArrayCache arrayCache)
37 throws IOException, IndexIndicatorException {
38 this.check = check;
39 this.verifyCheck = verifyCheck;
40 inData = new DataInputStream(in);
41
42 // Block Header Size or Index Indicator
43 int b = inData.readUnsignedByte();
44
45 // See if this begins the Index field.
46 if (b == 0x00)
47 throw new IndexIndicatorException();
48
49 // Read the rest of the Block Header.
50 headerSize = 4 * (b + 1);
51
52 final byte[] buf = new byte[headerSize];
53 buf[0] = (byte)b;
54 inData.readFully(buf, 1, headerSize - 1);
55
56 // Validate the CRC32.
57 if (!DecoderUtil.isCRC32Valid(buf, 0, headerSize - 4, headerSize - 4))
58 throw new CorruptedInputException("XZ Block Header is corrupt");
59
60 // Check for reserved bits in Block Flags.
61 if ((buf[1] & 0x3C) != 0)
62 throw new UnsupportedOptionsException(
63 "Unsupported options in XZ Block Header");
64
65 // Memory for the Filter Flags field
66 int filterCount = (buf[1] & 0x03) + 1;
67 long[] filterIDs = new long[filterCount];
68 byte[][] filterProps = new byte[filterCount][];
69
70 // Use a stream to parse the fields after the Block Flags field.
71 // Exclude the CRC32 field at the end.
72 ByteArrayInputStream bufStream = new ByteArrayInputStream(
73 buf, 2, headerSize - 6);
74
75 try {
76 // Set the maximum valid compressed size. This is overridden
77 // by the value from the Compressed Size field if it is present.
78 compressedSizeLimit = (DecoderUtil.VLI_MAX & ~3)
79 - headerSize - check.getSize();
80
81 // Decode and validate Compressed Size if the relevant flag
82 // is set in Block Flags.
83 if ((buf[1] & 0x40) != 0x00) {
84 compressedSizeInHeader = DecoderUtil.decodeVLI(bufStream);
85
86 if (compressedSizeInHeader == 0
87 || compressedSizeInHeader > compressedSizeLimit)
88 throw new CorruptedInputException();
89
90 compressedSizeLimit = compressedSizeInHeader;
91 }
92
93 // Decode Uncompressed Size if the relevant flag is set
94 // in Block Flags.
95 if ((buf[1] & 0x80) != 0x00)
96 uncompressedSizeInHeader = DecoderUtil.decodeVLI(bufStream);
97
98 // Decode Filter Flags.
99 for (int i = 0; i < filterCount; ++i) {
100 filterIDs[i] = DecoderUtil.decodeVLI(bufStream);
101
102 long filterPropsSize = DecoderUtil.decodeVLI(bufStream);
103 if (filterPropsSize > bufStream.available())
104 throw new CorruptedInputException();
105
106 filterProps[i] = new byte[(int)filterPropsSize];
107 bufStream.read(filterProps[i]);
108 }
109
110 } catch (IOException e) {
111 throw new CorruptedInputException("XZ Block Header is corrupt");
112 }
113
114 // Check that the remaining bytes are zero.
115 for (int i = bufStream.available(); i > 0; --i)
116 if (bufStream.read() != 0x00)
117 throw new UnsupportedOptionsException(
118 "Unsupported options in XZ Block Header");
119
120 // Validate the Block Header against the Index when doing
121 // random access reading.
122 if (unpaddedSizeInIndex != -1) {
123 // Compressed Data must be at least one byte, so if Block Header
124 // and Check alone take as much or more space than the size
125 // stored in the Index, the file is corrupt.
126 int headerAndCheckSize = headerSize + check.getSize();
127 if (headerAndCheckSize >= unpaddedSizeInIndex)
128 throw new CorruptedInputException(
129 "XZ Index does not match a Block Header");
130
131 // The compressed size calculated from Unpadded Size must
132 // match the value stored in the Compressed Size field in
133 // the Block Header.
134 long compressedSizeFromIndex
135 = unpaddedSizeInIndex - headerAndCheckSize;
136 if (compressedSizeFromIndex > compressedSizeLimit
137 || (compressedSizeInHeader != -1
138 && compressedSizeInHeader != compressedSizeFromIndex))
139 throw new CorruptedInputException(
140 "XZ Index does not match a Block Header");
141
142 // The uncompressed size stored in the Index must match
143 // the value stored in the Uncompressed Size field in
144 // the Block Header.
145 if (uncompressedSizeInHeader != -1
146 && uncompressedSizeInHeader != uncompressedSizeInIndex)
147 throw new CorruptedInputException(
148 "XZ Index does not match a Block Header");
149
150 // For further validation, pretend that the values from the Index
151 // were stored in the Block Header.
152 compressedSizeLimit = compressedSizeFromIndex;
153 compressedSizeInHeader = compressedSizeFromIndex;
154 uncompressedSizeInHeader = uncompressedSizeInIndex;
155 }
156
157 // Check if the Filter IDs are supported, decode
158 // the Filter Properties, and check that they are
159 // supported by this decoder implementation.
160 FilterDecoder[] filters = new FilterDecoder[filterIDs.length];
161
162 for (int i = 0; i < filters.length; ++i) {
163 if (filterIDs[i] == LZMA2Coder.FILTER_ID)
164 filters[i] = new LZMA2Decoder(filterProps[i]);
165
166 else if (filterIDs[i] == DeltaCoder.FILTER_ID)
167 filters[i] = new DeltaDecoder(filterProps[i]);
168
169 else if (BCJDecoder.isBCJFilterID(filterIDs[i]))
170 filters[i] = new BCJDecoder(filterIDs[i], filterProps[i]);
171
172 else
173 throw new UnsupportedOptionsException(
174 "Unknown Filter ID " + filterIDs[i]);
175 }
176
177 RawCoder.validate(filters);
178
179 // Check the memory usage limit.
180 if (memoryLimit >= 0) {
181 int memoryNeeded = 0;
182 for (int i = 0; i < filters.length; ++i)
183 memoryNeeded += filters[i].getMemoryUsage();
184
185 if (memoryNeeded > memoryLimit)
186 throw new MemoryLimitException(memoryNeeded, memoryLimit);
187 }
188
189 // Use an input size counter to calculate
190 // the size of the Compressed Data field.
191 inCounted = new CountingInputStream(in);
192
193 // Initialize the filter chain.
194 filterChain = inCounted;
195 for (int i = filters.length - 1; i >= 0; --i)
196 filterChain = filters[i].getInputStream(filterChain, arrayCache);
197 }
198
199 @Override
200 public int read() throws IOException {
201 return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
202 }
203
204 @Override
205 public int read(byte[] buf, int off, int len) throws IOException {
206 if (endReached)
207 return -1;
208
209 int ret = filterChain.read(buf, off, len);
210
211 if (ret > 0) {
212 if (verifyCheck)
213 check.update(buf, off, ret);
214
215 uncompressedSize += ret;
216
217 // Catch invalid values.
218 long compressedSize = inCounted.getSize();
219 if (compressedSize < 0
220 || compressedSize > compressedSizeLimit
221 || uncompressedSize < 0
222 || (uncompressedSizeInHeader != -1
223 && uncompressedSize > uncompressedSizeInHeader))
224 throw new CorruptedInputException();
225
226 // Check the Block integrity as soon as possible:
227 // - The filter chain shouldn't return less than requested
228 // unless it hit the end of the input.
229 // - If the uncompressed size is known, we know when there
230 // shouldn't be more data coming. We still need to read
231 // one byte to let the filter chain catch errors and to
232 // let it read end of payload marker(s).
233 if (ret < len || uncompressedSize == uncompressedSizeInHeader) {
234 if (filterChain.read() != -1)
235 throw new CorruptedInputException();
236
237 validate();
238 endReached = true;
239 }
240 } else if (ret == -1) {
241 validate();
242 endReached = true;
243 }
244
245 return ret;
246 }
247
248 private void validate() throws IOException {
249 long compressedSize = inCounted.getSize();
250
251 // Validate Compressed Size and Uncompressed Size if they were
252 // present in Block Header.
253 if ((compressedSizeInHeader != -1
254 && compressedSizeInHeader != compressedSize)
255 || (uncompressedSizeInHeader != -1
256 && uncompressedSizeInHeader != uncompressedSize))
257 throw new CorruptedInputException();
258
259 // Block Padding bytes must be zeros.
260 while ((compressedSize++ & 3) != 0)
261 if (inData.readUnsignedByte() != 0x00)
262 throw new CorruptedInputException();
263
264 // Validate the integrity check if verifyCheck is true.
265 byte[] storedCheck = new byte[check.getSize()];
266 inData.readFully(storedCheck);
267 if (verifyCheck && !Arrays.equals(check.finish(), storedCheck))
268 throw new CorruptedInputException("Integrity check ("
269 + check.getName() + ") does not match");
270 }
271
272 @Override
273 public int available() throws IOException {
274 return filterChain.available();
275 }
276
277 @Override
278 public void close() {
279 // This puts all arrays, that were allocated from ArrayCache,
280 // back to the ArrayCache. The last filter in the chain will
281 // call inCounted.close() which, being an instance of
282 // CloseIgnoringInputStream, won't close() the InputStream that
283 // was provided by the application.
284 try {
285 filterChain.close();
286 } catch (IOException e) {
287 // It's a bug if we get here. The InputStreams that we are closing
288 // are all from this package and they are known to not throw
289 // IOException. (They could throw an IOException if we were
290 // closing the application-supplied InputStream, but
291 // inCounted.close() doesn't do that.)
292 assert false;
293 }
294
295 filterChain = null;
296 }
297
298 public long getUnpaddedSize() {
299 return headerSize + inCounted.getSize() + check.getSize();
300 }
301
302 public long getUncompressedSize() {
303 return uncompressedSize;
304 }
305 }