1 /* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 // vim: expandtab:ts=8:sw=4:softtabstop=4:
3 ///////////////////////////////////////////////////////////////////////////////
4 //
5 /// \file       coder.c
6 /// \brief      Compresses or uncompresses a file
7 //
8 //  Author:     Lasse Collin
9 //
10 //  This file has been put into the public domain.
11 //  You can do whatever you want with this file.
12 //
13 ///////////////////////////////////////////////////////////////////////////////
14 
15 #include "private.h"
16 
17 
18 /// Return value type for coder_init().
19 enum coder_init_ret {
20 	CODER_INIT_NORMAL,
21 	CODER_INIT_PASSTHRU,
22 	CODER_INIT_ERROR,
23 };
24 
25 
26 enum operation_mode opt_mode = MODE_COMPRESS;
27 
28 enum format_type opt_format = FORMAT_AUTO;
29 
30 
31 /// Stream used to communicate with liblzma
32 static lzma_stream strm = LZMA_STREAM_INIT;
33 
34 /// Filters needed for all encoding all formats, and also decoding in raw data
35 static lzma_filter filters[LZMA_FILTERS_MAX + 1];
36 
37 /// Input and output buffers
38 static uint8_t in_buf[IO_BUFFER_SIZE];
39 static uint8_t out_buf[IO_BUFFER_SIZE];
40 
41 /// Number of filters. Zero indicates that we are using a preset.
42 static size_t filters_count = 0;
43 
44 /// Number of the preset (0-9)
45 static size_t preset_number = 6;
46 
47 /// True if we should auto-adjust the compression settings to use less memory
48 /// if memory usage limit is too low for the original settings.
49 static bool auto_adjust = true;
50 
51 /// Indicate if no preset has been explicitly given. In that case, if we need
52 /// to auto-adjust for lower memory usage, we won't print a warning.
53 static bool preset_default = true;
54 
55 /// If a preset is used (no custom filter chain) and preset_extreme is true,
56 /// a significantly slower compression is used to achieve slightly better
57 /// compression ratio.
58 static bool preset_extreme = false;
59 
60 /// Integrity check type
61 #ifdef HAVE_CHECK_CRC64
62 static lzma_check check = LZMA_CHECK_CRC64;
63 #else
64 static lzma_check check = LZMA_CHECK_CRC32;
65 #endif
66 
67 
68 extern void
coder_set_check(lzma_check new_check)69 coder_set_check(lzma_check new_check)
70 {
71 	check = new_check;
72 	return;
73 }
74 
75 
76 extern void
coder_set_preset(size_t new_preset)77 coder_set_preset(size_t new_preset)
78 {
79 	preset_number = new_preset;
80 	preset_default = false;
81 	return;
82 }
83 
84 
85 extern void
coder_set_extreme(void)86 coder_set_extreme(void)
87 {
88 	preset_extreme = true;
89 	return;
90 }
91 
92 
93 extern void
coder_add_filter(lzma_vli id,void * options)94 coder_add_filter(lzma_vli id, void *options)
95 {
96 	if (filters_count == LZMA_FILTERS_MAX)
97 		message_fatal(_("Maximum number of filters is four"));
98 
99 	filters[filters_count].id = id;
100 	filters[filters_count].options = options;
101 	++filters_count;
102 
103 	return;
104 }
105 
106 
107 static void lzma_attribute((noreturn))
memlimit_too_small(uint64_t memory_usage,uint64_t memory_limit)108 memlimit_too_small(uint64_t memory_usage, uint64_t memory_limit)
109 {
110 	message_fatal(_("Memory usage limit (%" PRIu64 " MiB) is too small "
111 			"for the given filter setup (%" PRIu64 " MiB)"),
112 			memory_limit >> 20, memory_usage >> 20);
113 }
114 
115 
116 extern void
coder_set_compression_settings(void)117 coder_set_compression_settings(void)
118 {
119 	// Options for LZMA1 or LZMA2 in case we are using a preset.
120 	static lzma_options_lzma opt_lzma;
121 
122 	if (filters_count == 0) {
123 		// We are using a preset. This is not a good idea in raw mode
124 		// except when playing around with things. Different versions
125 		// of this software may use different options in presets, and
126 		// thus make uncompressing the raw data difficult.
127 		if (opt_format == FORMAT_RAW) {
128 			// The message is shown only if warnings are allowed
129 			// but the exit status isn't changed.
130 			message(V_WARNING, _("Using a preset in raw mode "
131 					"is discouraged."));
132 			message(V_WARNING, _("The exact options of the "
133 					"presets may vary between software "
134 					"versions."));
135 		}
136 
137 		// Get the preset for LZMA1 or LZMA2.
138 		if (preset_extreme)
139 			preset_number |= LZMA_PRESET_EXTREME;
140 
141 		if (lzma_lzma_preset(&opt_lzma, preset_number))
142 			message_bug();
143 
144 		// Use LZMA2 except with --format=lzma we use LZMA1.
145 		filters[0].id = opt_format == FORMAT_LZMA
146 				? LZMA_FILTER_LZMA1 : LZMA_FILTER_LZMA2;
147 		filters[0].options = &opt_lzma;
148 		filters_count = 1;
149 	} else {
150 		preset_default = false;
151 	}
152 
153 	// Terminate the filter options array.
154 	filters[filters_count].id = LZMA_VLI_UNKNOWN;
155 
156 	// If we are using the .lzma format, allow exactly one filter
157 	// which has to be LZMA1.
158 	if (opt_format == FORMAT_LZMA && (filters_count != 1
159 			|| filters[0].id != LZMA_FILTER_LZMA1))
160 		message_fatal(_("The .lzma format supports only "
161 				"the LZMA1 filter"));
162 
163 	// If we are using the .xz format, make sure that there is no LZMA1
164 	// filter to prevent LZMA_PROG_ERROR.
165 	if (opt_format == FORMAT_XZ)
166 		for (size_t i = 0; i < filters_count; ++i)
167 			if (filters[i].id == LZMA_FILTER_LZMA1)
168 				message_fatal(_("LZMA1 cannot be used "
169 						"with the .xz format"));
170 
171 	// Print the selected filter chain.
172 	message_filters(V_DEBUG, filters);
173 
174 	// If using --format=raw, we can be decoding. The memusage function
175 	// also validates the filter chain and the options used for the
176 	// filters.
177 	const uint64_t memory_limit = hardware_memlimit_get();
178 	uint64_t memory_usage;
179 	if (opt_mode == MODE_COMPRESS)
180 		memory_usage = lzma_raw_encoder_memusage(filters);
181 	else
182 		memory_usage = lzma_raw_decoder_memusage(filters);
183 
184 	if (memory_usage == UINT64_MAX)
185 		message_fatal("Unsupported filter chain or filter options");
186 
187 	// Print memory usage info.
188 	message(V_DEBUG, _("%s MiB (%s B) of memory is required per thread, "
189 			"limit is %s MiB (%s B)"),
190 			uint64_to_str(memory_usage >> 20, 0),
191 			uint64_to_str(memory_usage, 1),
192 			uint64_to_str(memory_limit >> 20, 2),
193 			uint64_to_str(memory_limit, 3));
194 
195 	if (memory_usage > memory_limit) {
196 		// If --no-auto-adjust was used or we didn't find LZMA1 or
197 		// LZMA2 as the last filter, give an error immediatelly.
198 		// --format=raw implies --no-auto-adjust.
199 		if (!auto_adjust || opt_format == FORMAT_RAW)
200 			memlimit_too_small(memory_usage, memory_limit);
201 
202 		assert(opt_mode == MODE_COMPRESS);
203 
204 		// Look for the last filter if it is LZMA2 or LZMA1, so
205 		// we can make it use less RAM. With other filters we don't
206 		// know what to do.
207 		size_t i = 0;
208 		while (filters[i].id != LZMA_FILTER_LZMA2
209 				&& filters[i].id != LZMA_FILTER_LZMA1) {
210 			if (filters[i].id == LZMA_VLI_UNKNOWN)
211 				memlimit_too_small(memory_usage, memory_limit);
212 
213 			++i;
214 		}
215 
216 		// Decrease the dictionary size until we meet the memory
217 		// usage limit. First round down to full mebibytes.
218 		lzma_options_lzma *opt = filters[i].options;
219 		const uint32_t orig_dict_size = opt->dict_size;
220 		opt->dict_size &= ~((UINT32_C(1) << 20) - 1);
221 		while (true) {
222 			// If it is below 1 MiB, auto-adjusting failed. We
223 			// could be more sophisticated and scale it down even
224 			// more, but let's see if many complain about this
225 			// version.
226 			//
227 			// FIXME: Displays the scaled memory usage instead
228 			// of the original.
229 			if (opt->dict_size < (UINT32_C(1) << 20))
230 				memlimit_too_small(memory_usage, memory_limit);
231 
232 			memory_usage = lzma_raw_encoder_memusage(filters);
233 			if (memory_usage == UINT64_MAX)
234 				message_bug();
235 
236 			// Accept it if it is low enough.
237 			if (memory_usage <= memory_limit)
238 				break;
239 
240 			// Otherwise 1 MiB down and try again. I hope this
241 			// isn't too slow method for cases where the original
242 			// dict_size is very big.
243 			opt->dict_size -= UINT32_C(1) << 20;
244 		}
245 
246 		// Tell the user that we decreased the dictionary size.
247 		// However, omit the message if no preset or custom chain
248 		// was given. FIXME: Always warn?
249 		if (!preset_default)
250 			message(V_WARNING, "Adjusted LZMA%c dictionary size "
251 					"from %s MiB to %s MiB to not exceed "
252 					"the memory usage limit of %s MiB",
253 					filters[i].id == LZMA_FILTER_LZMA2
254 						? '2' : '1',
255 					uint64_to_str(orig_dict_size >> 20, 0),
256 					uint64_to_str(opt->dict_size >> 20, 1),
257 					uint64_to_str(memory_limit >> 20, 2));
258 	}
259 
260 /*
261 	// Limit the number of worker threads so that memory usage
262 	// limit isn't exceeded.
263 	assert(memory_usage > 0);
264 	size_t thread_limit = memory_limit / memory_usage;
265 	if (thread_limit == 0)
266 		thread_limit = 1;
267 
268 	if (opt_threads > thread_limit)
269 		opt_threads = thread_limit;
270 */
271 
272 	return;
273 }
274 
275 
276 /// Return true if the data in in_buf seems to be in the .xz format.
277 static bool
is_format_xz(void)278 is_format_xz(void)
279 {
280 	return strm.avail_in >= 6 && memcmp(in_buf, "\3757zXZ", 6) == 0;
281 }
282 
283 
284 /// Return true if the data in in_buf seems to be in the .lzma format.
285 static bool
is_format_lzma(void)286 is_format_lzma(void)
287 {
288 	// The .lzma header is 13 bytes.
289 	if (strm.avail_in < 13)
290 		return false;
291 
292 	// Decode the LZMA1 properties.
293 	lzma_filter filter = { .id = LZMA_FILTER_LZMA1 };
294 	if (lzma_properties_decode(&filter, NULL, in_buf, 5) != LZMA_OK)
295 		return false;
296 
297 	// A hack to ditch tons of false positives: We allow only dictionary
298 	// sizes that are 2^n or 2^n + 2^(n-1) or UINT32_MAX. LZMA_Alone
299 	// created only files with 2^n, but accepts any dictionary size.
300 	// If someone complains, this will be reconsidered.
301 	lzma_options_lzma *opt = filter.options;
302 	const uint32_t dict_size = opt->dict_size;
303 	free(opt);
304 
305 	if (dict_size != UINT32_MAX) {
306 		uint32_t d = dict_size - 1;
307 		d |= d >> 2;
308 		d |= d >> 3;
309 		d |= d >> 4;
310 		d |= d >> 8;
311 		d |= d >> 16;
312 		++d;
313 		if (d != dict_size || dict_size == 0)
314 			return false;
315 	}
316 
317 	// Another hack to ditch false positives: Assume that if the
318 	// uncompressed size is known, it must be less than 256 GiB.
319 	// Again, if someone complains, this will be reconsidered.
320 	uint64_t uncompressed_size = 0;
321 	for (size_t i = 0; i < 8; ++i)
322 		uncompressed_size |= (uint64_t)(in_buf[5 + i]) << (i * 8);
323 
324 	if (uncompressed_size != UINT64_MAX
325 			&& uncompressed_size > (UINT64_C(1) << 38))
326 		return false;
327 
328 	return true;
329 }
330 
331 
332 /// Detect the input file type (for now, this done only when decompressing),
333 /// and initialize an appropriate coder. Return value indicates if a normal
334 /// liblzma-based coder was initialized (CODER_INIT_NORMAL), if passthru
335 /// mode should be used (CODER_INIT_PASSTHRU), or if an error occurred
336 /// (CODER_INIT_ERROR).
337 static enum coder_init_ret
coder_init(file_pair * pair)338 coder_init(file_pair *pair)
339 {
340 	lzma_ret ret = LZMA_PROG_ERROR;
341 
342 	if (opt_mode == MODE_COMPRESS) {
343 		switch (opt_format) {
344 		case FORMAT_AUTO:
345 			// args.c ensures this.
346 			assert(0);
347 			break;
348 
349 		case FORMAT_XZ:
350 			ret = lzma_stream_encoder(&strm, filters, check);
351 			break;
352 
353 		case FORMAT_LZMA:
354 			ret = lzma_alone_encoder(&strm, filters[0].options);
355 			break;
356 
357 		case FORMAT_RAW:
358 			ret = lzma_raw_encoder(&strm, filters);
359 			break;
360 		}
361 	} else {
362 		const uint32_t flags = LZMA_TELL_UNSUPPORTED_CHECK
363 				| LZMA_CONCATENATED;
364 
365 		// We abuse FORMAT_AUTO to indicate unknown file format,
366 		// for which we may consider passthru mode.
367 		enum format_type init_format = FORMAT_AUTO;
368 
369 		switch (opt_format) {
370 		case FORMAT_AUTO:
371 			if (is_format_xz())
372 				init_format = FORMAT_XZ;
373 			else if (is_format_lzma())
374 				init_format = FORMAT_LZMA;
375 			break;
376 
377 		case FORMAT_XZ:
378 			if (is_format_xz())
379 				init_format = FORMAT_XZ;
380 			break;
381 
382 		case FORMAT_LZMA:
383 			if (is_format_lzma())
384 				init_format = FORMAT_LZMA;
385 			break;
386 
387 		case FORMAT_RAW:
388 			init_format = FORMAT_RAW;
389 			break;
390 		}
391 
392 		switch (init_format) {
393 		case FORMAT_AUTO:
394 			// Uknown file format. If --decompress --stdout
395 			// --force have been given, then we copy the input
396 			// as is to stdout. Checking for MODE_DECOMPRESS
397 			// is needed, because we don't want to do use
398 			// passthru mode with --test.
399 			if (opt_mode == MODE_DECOMPRESS
400 					&& opt_stdout && opt_force)
401 				return CODER_INIT_PASSTHRU;
402 
403 			ret = LZMA_FORMAT_ERROR;
404 			break;
405 
406 		case FORMAT_XZ:
407 			ret = lzma_stream_decoder(&strm,
408 					hardware_memlimit_get(), flags);
409 			break;
410 
411 		case FORMAT_LZMA:
412 			ret = lzma_alone_decoder(&strm,
413 					hardware_memlimit_get());
414 			break;
415 
416 		case FORMAT_RAW:
417 			// Memory usage has already been checked in
418 			// coder_set_compression_settings().
419 			ret = lzma_raw_decoder(&strm, filters);
420 			break;
421 		}
422 	}
423 
424 	if (ret != LZMA_OK) {
425 		message_error("%s: %s", pair->src_name, message_strm(ret));
426 		return CODER_INIT_ERROR;
427 	}
428 
429 	return CODER_INIT_NORMAL;
430 }
431 
432 
433 /// Compress or decompress using liblzma.
434 static bool
coder_normal(file_pair * pair)435 coder_normal(file_pair *pair)
436 {
437 	// Encoder needs to know when we have given all the input to it.
438 	// The decoders need to know it too when we are using
439 	// LZMA_CONCATENATED. We need to check for src_eof here, because
440 	// the first input chunk has been already read, and that may
441 	// have been the only chunk we will read.
442 	lzma_action action = pair->src_eof ? LZMA_FINISH : LZMA_RUN;
443 
444 	lzma_ret ret;
445 
446 	// Assume that something goes wrong.
447 	bool success = false;
448 
449 	strm.next_out = out_buf;
450 	strm.avail_out = IO_BUFFER_SIZE;
451 
452 	while (!user_abort) {
453 		// Fill the input buffer if it is empty and we haven't reached
454 		// end of file yet.
455 		if (strm.avail_in == 0 && !pair->src_eof) {
456 			strm.next_in = in_buf;
457 			strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
458 
459 			if (strm.avail_in == SIZE_MAX)
460 				break;
461 
462 			if (pair->src_eof)
463 				action = LZMA_FINISH;
464 		}
465 
466 		// Let liblzma do the actual work.
467 		ret = lzma_code(&strm, action);
468 
469 		// Write out if the output buffer became full.
470 		if (strm.avail_out == 0) {
471 			if (opt_mode != MODE_TEST && io_write(pair, out_buf,
472 					IO_BUFFER_SIZE - strm.avail_out))
473 				break;
474 
475 			strm.next_out = out_buf;
476 			strm.avail_out = IO_BUFFER_SIZE;
477 		}
478 
479 		if (ret != LZMA_OK) {
480 			// Determine if the return value indicates that we
481 			// won't continue coding.
482 			const bool stop = ret != LZMA_NO_CHECK
483 					&& ret != LZMA_UNSUPPORTED_CHECK;
484 
485 			if (stop) {
486 				// Write the remaining bytes even if something
487 				// went wrong, because that way the user gets
488 				// as much data as possible, which can be good
489 				// when trying to get at least some useful
490 				// data out of damaged files.
491 				if (opt_mode != MODE_TEST && io_write(pair,
492 						out_buf, IO_BUFFER_SIZE
493 							- strm.avail_out))
494 					break;
495 			}
496 
497 			if (ret == LZMA_STREAM_END) {
498 				// Check that there is no trailing garbage.
499 				// This is needed for LZMA_Alone and raw
500 				// streams.
501 				if (strm.avail_in == 0 && !pair->src_eof) {
502 					// Try reading one more byte.
503 					// Hopefully we don't get any more
504 					// input, and thus pair->src_eof
505 					// becomes true.
506 					strm.avail_in = io_read(
507 							pair, in_buf, 1);
508 					if (strm.avail_in == SIZE_MAX)
509 						break;
510 
511 					assert(strm.avail_in == 0
512 							|| strm.avail_in == 1);
513 				}
514 
515 				if (strm.avail_in == 0) {
516 					assert(pair->src_eof);
517 					success = true;
518 					break;
519 				}
520 
521 				// We hadn't reached the end of the file.
522 				ret = LZMA_DATA_ERROR;
523 				assert(stop);
524 			}
525 
526 			// If we get here and stop is true, something went
527 			// wrong and we print an error. Otherwise it's just
528 			// a warning and coding can continue.
529 			if (stop) {
530 				message_error("%s: %s", pair->src_name,
531 						message_strm(ret));
532 			} else {
533 				message_warning("%s: %s", pair->src_name,
534 						message_strm(ret));
535 
536 				// When compressing, all possible errors set
537 				// stop to true.
538 				assert(opt_mode != MODE_COMPRESS);
539 			}
540 
541 			if (ret == LZMA_MEMLIMIT_ERROR) {
542 				// Figure out how much memory it would have
543 				// actually needed.
544 				uint64_t memusage = lzma_memusage(&strm);
545 				uint64_t memlimit = hardware_memlimit_get();
546 
547 				// Round the memory limit down and usage up.
548 				// This way we don't display a ridiculous
549 				// message like "Limit was 9 MiB, but 9 MiB
550 				// would have been needed".
551 				memusage = (memusage + 1024 * 1024 - 1)
552 						/ (1024 * 1024);
553 				memlimit /= 1024 * 1024;
554 
555 				message_error(_("Limit was %s MiB, "
556 						"but %s MiB would "
557 						"have been needed"),
558 						uint64_to_str(memlimit, 0),
559 						uint64_to_str(memusage, 1));
560 			}
561 
562 			if (stop)
563 				break;
564 		}
565 
566 		// Show progress information under certain conditions.
567 		message_progress_update();
568 	}
569 
570 	return success;
571 }
572 
573 
574 /// Copy from input file to output file without processing the data in any
575 /// way. This is used only when trying to decompress unrecognized files
576 /// with --decompress --stdout --force, so the output is always stdout.
577 static bool
coder_passthru(file_pair * pair)578 coder_passthru(file_pair *pair)
579 {
580 	while (strm.avail_in != 0) {
581 		if (user_abort)
582 			return false;
583 
584 		if (io_write(pair, in_buf, strm.avail_in))
585 			return false;
586 
587 		strm.total_in += strm.avail_in;
588 		strm.total_out = strm.total_in;
589 		message_progress_update();
590 
591 		strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
592 		if (strm.avail_in == SIZE_MAX)
593 			return false;
594 	}
595 
596 	return true;
597 }
598 
599 
600 extern void
coder_run(const char * filename)601 coder_run(const char *filename)
602 {
603 	// Try to open the input and output files.
604 	file_pair *pair = io_open(filename);
605 	if (pair == NULL)
606 		return;
607 
608 	// Initialize the progress indicator.
609 	const uint64_t in_size = pair->src_st.st_size <= (off_t)(0)
610 			? 0 : (uint64_t)(pair->src_st.st_size);
611 	message_progress_start(&strm, pair->src_name, in_size);
612 
613 	// Assume that something goes wrong.
614 	bool success = false;
615 
616 	// Read the first chunk of input data. This is needed to detect
617 	// the input file type (for now, only for decompression).
618 	strm.next_in = in_buf;
619 	strm.avail_in = io_read(pair, in_buf, IO_BUFFER_SIZE);
620 
621 	switch (coder_init(pair)) {
622 	case CODER_INIT_NORMAL:
623 		success = coder_normal(pair);
624 		break;
625 
626 	case CODER_INIT_PASSTHRU:
627 		success = coder_passthru(pair);
628 		break;
629 
630 	case CODER_INIT_ERROR:
631 		break;
632 	}
633 
634 	message_progress_end(success);
635 
636 	// Close the file pair. It needs to know if coding was successful to
637 	// know if the source or target file should be unlinked.
638 	io_close(pair, success);
639 
640 	return;
641 }
642