1 /* $NetBSD: unxz.c,v 1.8 2018/10/06 16:36:45 martin Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2011 The NetBSD Foundation, Inc.
9 * This code is derived from software contributed to The NetBSD Foundation
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/cdefs.h>
41 unxz(int i, int o, char *pre, size_t prelen, off_t *bytes_in)
43 lzma_stream strm = LZMA_STREAM_INIT;
44 static const int flags = LZMA_TELL_UNSUPPORTED_CHECK|LZMA_CONCATENATED;
46 lzma_action action = LZMA_RUN;
55 memcpy(ibuf, pre, prelen);
56 strm.avail_in = read(i, ibuf + prelen, sizeof(ibuf) - prelen);
57 if (strm.avail_in == (size_t)-1)
58 maybe_err("read failed");
59 infile_newdata(strm.avail_in);
60 strm.avail_in += prelen;
61 *bytes_in = strm.avail_in;
63 if ((ret = lzma_stream_decoder(&strm, UINT64_MAX, flags)) != LZMA_OK)
64 maybe_errx("Can't initialize decoder (%d)", ret);
68 if ((ret = lzma_code(&strm, LZMA_RUN)) != LZMA_OK)
69 maybe_errx("Can't read headers (%d)", ret);
73 strm.avail_out = sizeof(obuf);
77 if (strm.avail_in == 0) {
79 strm.avail_in = read(i, ibuf, sizeof(ibuf));
80 switch (strm.avail_in) {
82 maybe_err("read failed");
88 infile_newdata(strm.avail_in);
89 *bytes_in += strm.avail_in;
94 ret = lzma_code(&strm, action);
96 // Write and check write error before checking decoder error.
97 // This way as much data as possible gets written to output
98 // even if decoder detected an error.
99 if (strm.avail_out == 0 || ret != LZMA_OK) {
100 const size_t write_size = sizeof(obuf) - strm.avail_out;
102 if (write(o, obuf, write_size) != (ssize_t)write_size)
103 maybe_err("write failed");
105 strm.next_out = obuf;
106 strm.avail_out = sizeof(obuf);
107 bytes_out += write_size;
110 if (ret != LZMA_OK) {
111 if (ret == LZMA_STREAM_END) {
112 // Check that there's no trailing garbage.
113 if (strm.avail_in != 0 || read(i, ibuf, 1))
114 ret = LZMA_DATA_ERROR;
124 msg = strerror(ENOMEM);
127 case LZMA_FORMAT_ERROR:
128 msg = "File format not recognized";
131 case LZMA_OPTIONS_ERROR:
132 // FIXME: Better message?
133 msg = "Unsupported compression options";
136 case LZMA_DATA_ERROR:
137 msg = "File is corrupt";
141 msg = "Unexpected end of input";
144 case LZMA_MEMLIMIT_ERROR:
145 msg = "Reached memory limit";
149 maybe_errx("Unknown error (%d)", ret);
152 maybe_errx("%s", msg);
161 * Copied various bits and pieces from xz support code or brute force
165 #define my_min(A,B) ((A)<(B)?(A):(B))
167 // Some systems have suboptimal BUFSIZ. Use a bit bigger value on them.
168 // We also need that IO_BUFFER_SIZE is a multiple of 8 (sizeof(uint64_t))
170 # define IO_BUFFER_SIZE 8192
172 # define IO_BUFFER_SIZE (BUFSIZ & ~7U)
175 /// is_sparse() accesses the buffer as uint64_t for maximum speed.
176 /// Use an union to make sure that the buffer is properly aligned.
178 uint8_t u8[IO_BUFFER_SIZE];
179 uint32_t u32[IO_BUFFER_SIZE / sizeof(uint32_t)];
180 uint64_t u64[IO_BUFFER_SIZE / sizeof(uint64_t)];
185 io_pread(int fd, io_buf *buf, size_t size, off_t pos)
187 // Using lseek() and read() is more portable than pread() and
188 // for us it is as good as real pread().
189 if (lseek(fd, pos, SEEK_SET) != pos) {
193 const size_t amount = read(fd, buf, size);
194 if (amount == SIZE_MAX)
197 if (amount != size) {
205 * Most of the following is copied (mostly verbatim) from the xz
206 * distribution, from file src/xz/list.c
209 ///////////////////////////////////////////////////////////////////////////////
212 /// \brief Listing information about .xz files
214 // Author: Lasse Collin
216 // This file has been put into the public domain.
217 // You can do whatever you want with this file.
219 ///////////////////////////////////////////////////////////////////////////////
222 /// Information about a .xz file
224 /// Combined Index of all Streams in the file
227 /// Total amount of Stream Padding
228 uint64_t stream_padding;
230 /// Highest memory usage so far
231 uint64_t memusage_max;
233 /// True if all Blocks so far have Compressed Size and
234 /// Uncompressed Size fields
237 /// Oldest XZ Utils version that will decompress the file
238 uint32_t min_version;
242 #define XZ_FILE_INFO_INIT { NULL, 0, 0, true, 50000002 }
245 /// \brief Parse the Index(es) from the given .xz file
247 /// \param xfi Pointer to structure where the decoded information
249 /// \param pair Input file
251 /// \return On success, false is returned. On error, true is returned.
253 // TODO: This function is pretty big. liblzma should have a function that
254 // takes a callback function to parse the Index(es) from a .xz file to make
255 // it easy for applications.
257 parse_indexes(xz_file_info *xfi, int src_fd)
261 if (fstat(src_fd, &st) != 0) {
265 if (st.st_size < 2 * LZMA_STREAM_HEADER_SIZE) {
270 lzma_stream_flags header_flags;
271 lzma_stream_flags footer_flags;
274 // lzma_stream for the Index decoder
275 lzma_stream strm = LZMA_STREAM_INIT;
277 // All Indexes decoded so far
278 lzma_index *combined_index = NULL;
280 // The Index currently being decoded
281 lzma_index *this_index = NULL;
283 // Current position in the file. We parse the file backwards so
284 // initialize it to point to the end of the file.
285 off_t pos = st.st_size;
287 // Each loop iteration decodes one Index.
289 // Check that there is enough data left to contain at least
290 // the Stream Header and Stream Footer. This check cannot
291 // fail in the first pass of this loop.
292 if (pos < 2 * LZMA_STREAM_HEADER_SIZE) {
296 pos -= LZMA_STREAM_HEADER_SIZE;
297 lzma_vli stream_padding = 0;
299 // Locate the Stream Footer. There may be Stream Padding which
300 // we must skip when reading backwards.
302 if (pos < LZMA_STREAM_HEADER_SIZE) {
306 if (io_pread(src_fd, &buf,
307 LZMA_STREAM_HEADER_SIZE, pos))
310 // Stream Padding is always a multiple of four bytes.
315 // To avoid calling io_pread() for every four bytes
316 // of Stream Padding, take advantage that we read
317 // 12 bytes (LZMA_STREAM_HEADER_SIZE) already and
318 // check them too before calling io_pread() again.
323 } while (i >= 0 && buf.u32[i] == 0);
326 // Decode the Stream Footer.
327 ret = lzma_stream_footer_decode(&footer_flags, buf.u8);
328 if (ret != LZMA_OK) {
332 // Check that the Stream Footer doesn't specify something
333 // that we don't support. This can only happen if the xz
334 // version is older than liblzma and liblzma supports
337 // It is enough to check Stream Footer. Stream Header must
338 // match when it is compared against Stream Footer with
339 // lzma_stream_flags_compare().
340 if (footer_flags.version != 0) {
344 // Check that the size of the Index field looks sane.
345 lzma_vli index_size = footer_flags.backward_size;
346 if ((lzma_vli)(pos) < index_size + LZMA_STREAM_HEADER_SIZE) {
350 // Set pos to the beginning of the Index.
354 ret = lzma_index_decoder(&strm, &this_index, UINT64_MAX);
355 if (ret != LZMA_OK) {
360 // Don't give the decoder more input than the
362 strm.avail_in = my_min(IO_BUFFER_SIZE, index_size);
363 if (io_pread(src_fd, &buf, strm.avail_in, pos))
366 pos += strm.avail_in;
367 index_size -= strm.avail_in;
369 strm.next_in = buf.u8;
370 ret = lzma_code(&strm, LZMA_RUN);
372 } while (ret == LZMA_OK);
374 // If the decoding seems to be successful, check also that
375 // the Index decoder consumed as much input as indicated
376 // by the Backward Size field.
377 if (ret == LZMA_STREAM_END)
378 if (index_size != 0 || strm.avail_in != 0)
379 ret = LZMA_DATA_ERROR;
381 if (ret != LZMA_STREAM_END) {
382 // LZMA_BUFFER_ERROR means that the Index decoder
383 // would have liked more input than what the Index
384 // size should be according to Stream Footer.
385 // The message for LZMA_DATA_ERROR makes more
386 // sense in that case.
387 if (ret == LZMA_BUF_ERROR)
388 ret = LZMA_DATA_ERROR;
393 // Decode the Stream Header and check that its Stream Flags
394 // match the Stream Footer.
395 pos -= footer_flags.backward_size + LZMA_STREAM_HEADER_SIZE;
396 if ((lzma_vli)(pos) < lzma_index_total_size(this_index)) {
400 pos -= lzma_index_total_size(this_index);
401 if (io_pread(src_fd, &buf, LZMA_STREAM_HEADER_SIZE, pos))
404 ret = lzma_stream_header_decode(&header_flags, buf.u8);
405 if (ret != LZMA_OK) {
409 ret = lzma_stream_flags_compare(&header_flags, &footer_flags);
410 if (ret != LZMA_OK) {
414 // Store the decoded Stream Flags into this_index. This is
415 // needed so that we can print which Check is used in each
417 ret = lzma_index_stream_flags(this_index, &footer_flags);
421 // Store also the size of the Stream Padding field. It is
422 // needed to show the offsets of the Streams correctly.
423 ret = lzma_index_stream_padding(this_index, stream_padding);
427 if (combined_index != NULL) {
428 // Append the earlier decoded Indexes
430 ret = lzma_index_cat(
431 this_index, combined_index, NULL);
432 if (ret != LZMA_OK) {
437 combined_index = this_index;
440 xfi->stream_padding += stream_padding;
446 // All OK. Make combined_index available to the caller.
447 xfi->idx = combined_index;
451 // Something went wrong, free the allocated memory.
453 lzma_index_end(combined_index, NULL);
454 lzma_index_end(this_index, NULL);
458 /***************** end of copy form list.c *************************/
461 * Small wrapper to extract total length of a file
466 xz_file_info xfi = XZ_FILE_INFO_INIT;
467 if (!parse_indexes(&xfi, fd)) {
468 off_t res = lzma_index_uncompressed_size(xfi.idx);
469 lzma_index_end(xfi.idx, NULL);