xref: /freebsd/contrib/xz/src/liblzma/common/stream_decoder.c (revision 128836d304d93f2d00eb14069c27089ab46c38d4)
1 // SPDX-License-Identifier: 0BSD
2 
3 ///////////////////////////////////////////////////////////////////////////////
4 //
5 /// \file       stream_decoder.c
6 /// \brief      Decodes .xz Streams
7 //
8 //  Author:     Lasse Collin
9 //
10 ///////////////////////////////////////////////////////////////////////////////
11 
12 #include "stream_decoder.h"
13 #include "block_decoder.h"
14 #include "index.h"
15 
16 
17 typedef struct {
18 	enum {
19 		SEQ_STREAM_HEADER,
20 		SEQ_BLOCK_HEADER,
21 		SEQ_BLOCK_INIT,
22 		SEQ_BLOCK_RUN,
23 		SEQ_INDEX,
24 		SEQ_STREAM_FOOTER,
25 		SEQ_STREAM_PADDING,
26 	} sequence;
27 
28 	/// Block decoder
29 	lzma_next_coder block_decoder;
30 
31 	/// Block options decoded by the Block Header decoder and used by
32 	/// the Block decoder.
33 	lzma_block block_options;
34 
35 	/// Stream Flags from Stream Header
36 	lzma_stream_flags stream_flags;
37 
38 	/// Index is hashed so that it can be compared to the sizes of Blocks
39 	/// with O(1) memory usage.
40 	lzma_index_hash *index_hash;
41 
42 	/// Memory usage limit
43 	uint64_t memlimit;
44 
45 	/// Amount of memory actually needed (only an estimate)
46 	uint64_t memusage;
47 
48 	/// If true, LZMA_NO_CHECK is returned if the Stream has
49 	/// no integrity check.
50 	bool tell_no_check;
51 
52 	/// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
53 	/// an integrity check that isn't supported by this liblzma build.
54 	bool tell_unsupported_check;
55 
56 	/// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
57 	bool tell_any_check;
58 
59 	/// If true, we will tell the Block decoder to skip calculating
60 	/// and verifying the integrity check.
61 	bool ignore_check;
62 
63 	/// If true, we will decode concatenated Streams that possibly have
64 	/// Stream Padding between or after them. LZMA_STREAM_END is returned
65 	/// once the application isn't giving us any new input (LZMA_FINISH),
66 	/// and we aren't in the middle of a Stream, and possible
67 	/// Stream Padding is a multiple of four bytes.
68 	bool concatenated;
69 
70 	/// When decoding concatenated Streams, this is true as long as we
71 	/// are decoding the first Stream. This is needed to avoid misleading
72 	/// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
73 	/// bytes.
74 	bool first_stream;
75 
76 	/// Write position in buffer[] and position in Stream Padding
77 	size_t pos;
78 
79 	/// Buffer to hold Stream Header, Block Header, and Stream Footer.
80 	/// Block Header has biggest maximum size.
81 	uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
82 } lzma_stream_coder;
83 
84 
85 static lzma_ret
stream_decoder_reset(lzma_stream_coder * coder,const lzma_allocator * allocator)86 stream_decoder_reset(lzma_stream_coder *coder, const lzma_allocator *allocator)
87 {
88 	// Initialize the Index hash used to verify the Index.
89 	coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
90 	if (coder->index_hash == NULL)
91 		return LZMA_MEM_ERROR;
92 
93 	// Reset the rest of the variables.
94 	coder->sequence = SEQ_STREAM_HEADER;
95 	coder->pos = 0;
96 
97 	return LZMA_OK;
98 }
99 
100 
101 static lzma_ret
stream_decode(void * coder_ptr,const lzma_allocator * allocator,const uint8_t * restrict in,size_t * restrict in_pos,size_t in_size,uint8_t * restrict out,size_t * restrict out_pos,size_t out_size,lzma_action action)102 stream_decode(void *coder_ptr, const lzma_allocator *allocator,
103 		const uint8_t *restrict in, size_t *restrict in_pos,
104 		size_t in_size, uint8_t *restrict out,
105 		size_t *restrict out_pos, size_t out_size, lzma_action action)
106 {
107 	lzma_stream_coder *coder = coder_ptr;
108 
109 	// When decoding the actual Block, it may be able to produce more
110 	// output even if we don't give it any new input.
111 	while (true)
112 	switch (coder->sequence) {
113 	case SEQ_STREAM_HEADER: {
114 		// Copy the Stream Header to the internal buffer.
115 		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
116 				LZMA_STREAM_HEADER_SIZE);
117 
118 		// Return if we didn't get the whole Stream Header yet.
119 		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
120 			return LZMA_OK;
121 
122 		coder->pos = 0;
123 
124 		// Decode the Stream Header.
125 		const lzma_ret ret = lzma_stream_header_decode(
126 				&coder->stream_flags, coder->buffer);
127 		if (ret != LZMA_OK)
128 			return ret == LZMA_FORMAT_ERROR && !coder->first_stream
129 					? LZMA_DATA_ERROR : ret;
130 
131 		// If we are decoding concatenated Streams, and the later
132 		// Streams have invalid Header Magic Bytes, we give
133 		// LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
134 		coder->first_stream = false;
135 
136 		// Copy the type of the Check so that Block Header and Block
137 		// decoders see it.
138 		coder->block_options.check = coder->stream_flags.check;
139 
140 		// Even if we return LZMA_*_CHECK below, we want
141 		// to continue from Block Header decoding.
142 		coder->sequence = SEQ_BLOCK_HEADER;
143 
144 		// Detect if there's no integrity check or if it is
145 		// unsupported if those were requested by the application.
146 		if (coder->tell_no_check && coder->stream_flags.check
147 				== LZMA_CHECK_NONE)
148 			return LZMA_NO_CHECK;
149 
150 		if (coder->tell_unsupported_check
151 				&& !lzma_check_is_supported(
152 					coder->stream_flags.check))
153 			return LZMA_UNSUPPORTED_CHECK;
154 
155 		if (coder->tell_any_check)
156 			return LZMA_GET_CHECK;
157 
158 		FALLTHROUGH;
159 	}
160 
161 	case SEQ_BLOCK_HEADER: {
162 		if (*in_pos >= in_size)
163 			return LZMA_OK;
164 
165 		if (coder->pos == 0) {
166 			// Detect if it's Index.
167 			if (in[*in_pos] == INDEX_INDICATOR) {
168 				coder->sequence = SEQ_INDEX;
169 				break;
170 			}
171 
172 			// Calculate the size of the Block Header. Note that
173 			// Block Header decoder wants to see this byte too
174 			// so don't advance *in_pos.
175 			coder->block_options.header_size
176 					= lzma_block_header_size_decode(
177 						in[*in_pos]);
178 		}
179 
180 		// Copy the Block Header to the internal buffer.
181 		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
182 				coder->block_options.header_size);
183 
184 		// Return if we didn't get the whole Block Header yet.
185 		if (coder->pos < coder->block_options.header_size)
186 			return LZMA_OK;
187 
188 		coder->pos = 0;
189 		coder->sequence = SEQ_BLOCK_INIT;
190 		FALLTHROUGH;
191 	}
192 
193 	case SEQ_BLOCK_INIT: {
194 		// Checking memusage and doing the initialization needs
195 		// its own sequence point because we need to be able to
196 		// retry if we return LZMA_MEMLIMIT_ERROR.
197 
198 		// Version 1 is needed to support the .ignore_check option.
199 		coder->block_options.version = 1;
200 
201 		// Set up a buffer to hold the filter chain. Block Header
202 		// decoder will initialize all members of this array so
203 		// we don't need to do it here.
204 		lzma_filter filters[LZMA_FILTERS_MAX + 1];
205 		coder->block_options.filters = filters;
206 
207 		// Decode the Block Header.
208 		return_if_error(lzma_block_header_decode(&coder->block_options,
209 				allocator, coder->buffer));
210 
211 		// If LZMA_IGNORE_CHECK was used, this flag needs to be set.
212 		// It has to be set after lzma_block_header_decode() because
213 		// it always resets this to false.
214 		coder->block_options.ignore_check = coder->ignore_check;
215 
216 		// Check the memory usage limit.
217 		const uint64_t memusage = lzma_raw_decoder_memusage(filters);
218 		lzma_ret ret;
219 
220 		if (memusage == UINT64_MAX) {
221 			// One or more unknown Filter IDs.
222 			ret = LZMA_OPTIONS_ERROR;
223 		} else {
224 			// Now we can set coder->memusage since we know that
225 			// the filter chain is valid. We don't want
226 			// lzma_memusage() to return UINT64_MAX in case of
227 			// invalid filter chain.
228 			coder->memusage = memusage;
229 
230 			if (memusage > coder->memlimit) {
231 				// The chain would need too much memory.
232 				ret = LZMA_MEMLIMIT_ERROR;
233 			} else {
234 				// Memory usage is OK.
235 				// Initialize the Block decoder.
236 				ret = lzma_block_decoder_init(
237 						&coder->block_decoder,
238 						allocator,
239 						&coder->block_options);
240 			}
241 		}
242 
243 		// Free the allocated filter options since they are needed
244 		// only to initialize the Block decoder.
245 		lzma_filters_free(filters, allocator);
246 		coder->block_options.filters = NULL;
247 
248 		// Check if memory usage calculation and Block decoder
249 		// initialization succeeded.
250 		if (ret != LZMA_OK)
251 			return ret;
252 
253 		coder->sequence = SEQ_BLOCK_RUN;
254 		FALLTHROUGH;
255 	}
256 
257 	case SEQ_BLOCK_RUN: {
258 		const lzma_ret ret = coder->block_decoder.code(
259 				coder->block_decoder.coder, allocator,
260 				in, in_pos, in_size, out, out_pos, out_size,
261 				action);
262 
263 		if (ret != LZMA_STREAM_END)
264 			return ret;
265 
266 		// Block decoded successfully. Add the new size pair to
267 		// the Index hash.
268 		return_if_error(lzma_index_hash_append(coder->index_hash,
269 				lzma_block_unpadded_size(
270 					&coder->block_options),
271 				coder->block_options.uncompressed_size));
272 
273 		coder->sequence = SEQ_BLOCK_HEADER;
274 		break;
275 	}
276 
277 	case SEQ_INDEX: {
278 		// If we don't have any input, don't call
279 		// lzma_index_hash_decode() since it would return
280 		// LZMA_BUF_ERROR, which we must not do here.
281 		if (*in_pos >= in_size)
282 			return LZMA_OK;
283 
284 		// Decode the Index and compare it to the hash calculated
285 		// from the sizes of the Blocks (if any).
286 		const lzma_ret ret = lzma_index_hash_decode(coder->index_hash,
287 				in, in_pos, in_size);
288 		if (ret != LZMA_STREAM_END)
289 			return ret;
290 
291 		coder->sequence = SEQ_STREAM_FOOTER;
292 		FALLTHROUGH;
293 	}
294 
295 	case SEQ_STREAM_FOOTER: {
296 		// Copy the Stream Footer to the internal buffer.
297 		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
298 				LZMA_STREAM_HEADER_SIZE);
299 
300 		// Return if we didn't get the whole Stream Footer yet.
301 		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
302 			return LZMA_OK;
303 
304 		coder->pos = 0;
305 
306 		// Decode the Stream Footer. The decoder gives
307 		// LZMA_FORMAT_ERROR if the magic bytes don't match,
308 		// so convert that return code to LZMA_DATA_ERROR.
309 		lzma_stream_flags footer_flags;
310 		const lzma_ret ret = lzma_stream_footer_decode(
311 				&footer_flags, coder->buffer);
312 		if (ret != LZMA_OK)
313 			return ret == LZMA_FORMAT_ERROR
314 					? LZMA_DATA_ERROR : ret;
315 
316 		// Check that Index Size stored in the Stream Footer matches
317 		// the real size of the Index field.
318 		if (lzma_index_hash_size(coder->index_hash)
319 				!= footer_flags.backward_size)
320 			return LZMA_DATA_ERROR;
321 
322 		// Compare that the Stream Flags fields are identical in
323 		// both Stream Header and Stream Footer.
324 		return_if_error(lzma_stream_flags_compare(
325 				&coder->stream_flags, &footer_flags));
326 
327 		if (!coder->concatenated)
328 			return LZMA_STREAM_END;
329 
330 		coder->sequence = SEQ_STREAM_PADDING;
331 		FALLTHROUGH;
332 	}
333 
334 	case SEQ_STREAM_PADDING:
335 		assert(coder->concatenated);
336 
337 		// Skip over possible Stream Padding.
338 		while (true) {
339 			if (*in_pos >= in_size) {
340 				// Unless LZMA_FINISH was used, we cannot
341 				// know if there's more input coming later.
342 				if (action != LZMA_FINISH)
343 					return LZMA_OK;
344 
345 				// Stream Padding must be a multiple of
346 				// four bytes.
347 				return coder->pos == 0
348 						? LZMA_STREAM_END
349 						: LZMA_DATA_ERROR;
350 			}
351 
352 			// If the byte is not zero, it probably indicates
353 			// beginning of a new Stream (or the file is corrupt).
354 			if (in[*in_pos] != 0x00)
355 				break;
356 
357 			++*in_pos;
358 			coder->pos = (coder->pos + 1) & 3;
359 		}
360 
361 		// Stream Padding must be a multiple of four bytes (empty
362 		// Stream Padding is OK).
363 		if (coder->pos != 0) {
364 			++*in_pos;
365 			return LZMA_DATA_ERROR;
366 		}
367 
368 		// Prepare to decode the next Stream.
369 		return_if_error(stream_decoder_reset(coder, allocator));
370 		break;
371 
372 	default:
373 		assert(0);
374 		return LZMA_PROG_ERROR;
375 	}
376 
377 	// Never reached
378 }
379 
380 
381 static void
stream_decoder_end(void * coder_ptr,const lzma_allocator * allocator)382 stream_decoder_end(void *coder_ptr, const lzma_allocator *allocator)
383 {
384 	lzma_stream_coder *coder = coder_ptr;
385 	lzma_next_end(&coder->block_decoder, allocator);
386 	lzma_index_hash_end(coder->index_hash, allocator);
387 	lzma_free(coder, allocator);
388 	return;
389 }
390 
391 
392 static lzma_check
stream_decoder_get_check(const void * coder_ptr)393 stream_decoder_get_check(const void *coder_ptr)
394 {
395 	const lzma_stream_coder *coder = coder_ptr;
396 	return coder->stream_flags.check;
397 }
398 
399 
400 static lzma_ret
stream_decoder_memconfig(void * coder_ptr,uint64_t * memusage,uint64_t * old_memlimit,uint64_t new_memlimit)401 stream_decoder_memconfig(void *coder_ptr, uint64_t *memusage,
402 		uint64_t *old_memlimit, uint64_t new_memlimit)
403 {
404 	lzma_stream_coder *coder = coder_ptr;
405 
406 	*memusage = coder->memusage;
407 	*old_memlimit = coder->memlimit;
408 
409 	if (new_memlimit != 0) {
410 		if (new_memlimit < coder->memusage)
411 			return LZMA_MEMLIMIT_ERROR;
412 
413 		coder->memlimit = new_memlimit;
414 	}
415 
416 	return LZMA_OK;
417 }
418 
419 
420 extern lzma_ret
lzma_stream_decoder_init(lzma_next_coder * next,const lzma_allocator * allocator,uint64_t memlimit,uint32_t flags)421 lzma_stream_decoder_init(
422 		lzma_next_coder *next, const lzma_allocator *allocator,
423 		uint64_t memlimit, uint32_t flags)
424 {
425 	lzma_next_coder_init(&lzma_stream_decoder_init, next, allocator);
426 
427 	if (flags & ~LZMA_SUPPORTED_FLAGS)
428 		return LZMA_OPTIONS_ERROR;
429 
430 	lzma_stream_coder *coder = next->coder;
431 	if (coder == NULL) {
432 		coder = lzma_alloc(sizeof(lzma_stream_coder), allocator);
433 		if (coder == NULL)
434 			return LZMA_MEM_ERROR;
435 
436 		next->coder = coder;
437 		next->code = &stream_decode;
438 		next->end = &stream_decoder_end;
439 		next->get_check = &stream_decoder_get_check;
440 		next->memconfig = &stream_decoder_memconfig;
441 
442 		coder->block_decoder = LZMA_NEXT_CODER_INIT;
443 		coder->index_hash = NULL;
444 	}
445 
446 	coder->memlimit = my_max(1, memlimit);
447 	coder->memusage = LZMA_MEMUSAGE_BASE;
448 	coder->tell_no_check = (flags & LZMA_TELL_NO_CHECK) != 0;
449 	coder->tell_unsupported_check
450 			= (flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
451 	coder->tell_any_check = (flags & LZMA_TELL_ANY_CHECK) != 0;
452 	coder->ignore_check = (flags & LZMA_IGNORE_CHECK) != 0;
453 	coder->concatenated = (flags & LZMA_CONCATENATED) != 0;
454 	coder->first_stream = true;
455 
456 	return stream_decoder_reset(coder, allocator);
457 }
458 
459 
460 extern LZMA_API(lzma_ret)
lzma_stream_decoder(lzma_stream * strm,uint64_t memlimit,uint32_t flags)461 lzma_stream_decoder(lzma_stream *strm, uint64_t memlimit, uint32_t flags)
462 {
463 	lzma_next_strm_init(lzma_stream_decoder_init, strm, memlimit, flags);
464 
465 	strm->internal->supported_actions[LZMA_RUN] = true;
466 	strm->internal->supported_actions[LZMA_FINISH] = true;
467 
468 	return LZMA_OK;
469 }
470