1 /* pxzcat derived from nbdkit
2 * Copyright (C) 2013 Red Hat Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * * Neither the name of Red Hat nor the names of its contributors may be
17 * used to endorse or promote products derived from this software without
18 * specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
27 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 #include <sys/types.h>
54 #define debug(fs,...) fprintf (stderr, "pxzcat: debug: " fs "\n", ## __VA_ARGS__)
56 #define debug(fs,...) /* nothing */
59 /* Size of buffers used in decompression loop. */
60 #define BUFFER_SIZE (64*1024)
62 #define XZ_HEADER_MAGIC "\xfd" "7zXZ\0"
63 #define XZ_HEADER_MAGIC_LEN 6
64 #define XZ_FOOTER_MAGIC "YZ"
65 #define XZ_FOOTER_MAGIC_LEN 2
67 static void usage (int exitcode);
68 static void xzfile_uncompress (const char *filename, const char *outputfile, unsigned nr_threads);
69 static int check_header_magic (int fd);
70 static lzma_index *parse_indexes (const char *filename, int fd);
71 static void iter_blocks (lzma_index *idx, unsigned nr_threads, const char *filename, int fd, const char *outputfile, int ofd);
73 static struct option long_options[] = {
74 { "output", required_argument, 0, 'o' },
75 { "threads", required_argument, 0, 'T' },
76 { "help", 0, 0, '?' },
80 static const char *options = "o:T:";
83 main (int argc, char *argv[])
87 unsigned nr_threads = 0;
88 const char *outputfile = NULL;
91 c = getopt_long (argc, argv, options, long_options, &longopt_index);
96 /* Long option with no short opt equivalent. */
105 if (sscanf (optarg, "%u", &nr_threads) != 1)
106 error (EXIT_FAILURE, 0, "cannot parse -T option");
110 usage (EXIT_SUCCESS);
113 usage (EXIT_FAILURE);
117 if (optind != argc - 1)
118 usage (EXIT_FAILURE);
120 if (outputfile == NULL)
121 error (EXIT_FAILURE, 0, "you must give the -o (output file) option");
123 /* -T 0 (default) means use all cores. */
124 if (nr_threads == 0) {
125 long i = sysconf (_SC_NPROCESSORS_ONLN);
127 error (EXIT_FAILURE, errno, "could not get number of cores");
128 nr_threads = (unsigned) i;
130 debug ("nr_threads = %u", nr_threads);
132 xzfile_uncompress (argv[optind], outputfile, nr_threads);
140 printf ("usage: pxzcat -o output [-T #threads] input.xz\n");
145 xzfile_uncompress (const char *filename, const char *outputfile,
153 fd = open (filename, O_RDONLY);
155 error (EXIT_FAILURE, errno, "open: %s", filename);
157 /* Check file magic. */
158 if (!check_header_magic (fd))
159 error (EXIT_FAILURE, 0, "%s: not an xz file", filename);
161 /* Read and parse the indexes. */
162 idx = parse_indexes (filename, fd);
164 /* Get the file uncompressed size, create the output file. */
165 size = lzma_index_uncompressed_size (idx);
166 debug ("uncompressed size = %" PRIu64 " bytes", size);
168 /* Avoid annoying ext4 auto_da_alloc which causes a flush on close
169 * unless we are very careful about not truncating the file when it
170 * has zero size. (Thanks Eric Sandeen)
174 ofd = open (outputfile, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0644);
176 error (EXIT_FAILURE, errno, "open: %s", outputfile);
177 /* See above about auto_da_alloc. */
178 write (ofd, "\0", 1);
180 if (ftruncate (ofd, size) == -1)
181 error (EXIT_FAILURE, errno, "ftruncate: %s", outputfile);
183 /* Tell the kernel we won't read the output file. */
184 posix_fadvise (fd, 0, 0, POSIX_FADV_RANDOM|POSIX_FADV_DONTNEED);
186 /* Iterate over blocks. */
187 iter_blocks (idx, nr_threads, filename, fd, outputfile, ofd);
193 check_header_magic (int fd)
195 char buf[XZ_HEADER_MAGIC_LEN];
197 if (lseek (fd, 0, SEEK_SET) == -1)
199 if (read (fd, buf, XZ_HEADER_MAGIC_LEN) != XZ_HEADER_MAGIC_LEN)
201 if (memcmp (buf, XZ_HEADER_MAGIC, XZ_HEADER_MAGIC_LEN) != 0)
206 /* For explanation of this function, see src/xz/list.c:parse_indexes
210 parse_indexes (const char *filename, int fd)
213 off_t pos, index_size;
214 uint8_t footer[LZMA_STREAM_HEADER_SIZE];
215 uint8_t header[LZMA_STREAM_HEADER_SIZE];
216 lzma_stream_flags footer_flags;
217 lzma_stream_flags header_flags;
218 lzma_stream strm = LZMA_STREAM_INIT;
220 lzma_index *combined_index = NULL;
221 lzma_index *this_index = NULL;
222 lzma_vli stream_padding = 0;
223 size_t nr_streams = 0;
225 /* Check file size is a multiple of 4 bytes. */
226 pos = lseek (fd, 0, SEEK_END);
227 if (pos == (off_t) -1)
228 error (EXIT_FAILURE, errno, "%s: lseek", filename);
231 error (EXIT_FAILURE, 0,
232 "%s: not an xz file: size is not a multiple of 4 bytes",
235 /* Jump backwards through the file identifying each stream. */
237 debug ("looping through streams: pos = %" PRIu64, (uint64_t) pos);
239 if (pos < LZMA_STREAM_HEADER_SIZE)
240 error (EXIT_FAILURE, 0,
241 "%s: corrupted file at %" PRIu64, filename, (uint64_t) pos);
243 if (lseek (fd, -LZMA_STREAM_HEADER_SIZE, SEEK_CUR) == -1)
244 error (EXIT_FAILURE, errno, "%s: lseek", filename);
246 if (read (fd, footer, LZMA_STREAM_HEADER_SIZE) != LZMA_STREAM_HEADER_SIZE)
247 error (EXIT_FAILURE, errno, "%s: read stream footer", filename);
249 /* Skip stream padding. */
250 if (footer[8] == 0 && footer[9] == 0 &&
251 footer[10] == 0 && footer[11] == 0) {
257 pos -= LZMA_STREAM_HEADER_SIZE;
260 debug ("decode stream footer at pos = %" PRIu64, (uint64_t) pos);
262 /* Does the stream footer look reasonable? */
263 r = lzma_stream_footer_decode (&footer_flags, footer);
265 error (EXIT_FAILURE, 0,
266 "%s: invalid stream footer (error %d)", filename, r);
268 debug ("backward_size = %" PRIu64, (uint64_t) footer_flags.backward_size);
269 index_size = footer_flags.backward_size;
270 if (pos < index_size + LZMA_STREAM_HEADER_SIZE)
271 error (EXIT_FAILURE, 0, "%s: invalid stream footer", filename);
274 debug ("decode index at pos = %" PRIu64, (uint64_t) pos);
276 /* Seek backwards to the index of this stream. */
277 if (lseek (fd, pos, SEEK_SET) == -1)
278 error (EXIT_FAILURE, errno, "%s: lseek", filename);
280 /* Decode the index. */
281 r = lzma_index_decoder (&strm, &this_index, UINT64_MAX);
283 error (EXIT_FAILURE, 0,
284 "%s: invalid stream index (error %d)", filename, r);
289 strm.avail_in = index_size;
290 if (strm.avail_in > BUFSIZ)
291 strm.avail_in = BUFSIZ;
293 n = read (fd, &buf, strm.avail_in);
295 error (EXIT_FAILURE, errno, "%s: read", filename);
297 index_size -= strm.avail_in;
300 r = lzma_code (&strm, LZMA_RUN);
301 } while (r == LZMA_OK);
303 if (r != LZMA_STREAM_END)
304 error (EXIT_FAILURE, 0, "%s: could not parse index (error %d)",
307 pos -= lzma_index_total_size (this_index) + LZMA_STREAM_HEADER_SIZE;
309 debug ("decode stream header at pos = %" PRIu64, (uint64_t) pos);
311 /* Read and decode the stream header. */
312 if (lseek (fd, pos, SEEK_SET) == -1)
313 error (EXIT_FAILURE, errno, "%s: lseek", filename);
315 if (read (fd, header, LZMA_STREAM_HEADER_SIZE) != LZMA_STREAM_HEADER_SIZE)
316 error (EXIT_FAILURE, errno, "%s: read stream header", filename);
318 r = lzma_stream_header_decode (&header_flags, header);
320 error (EXIT_FAILURE, 0,
321 "%s: invalid stream header (error %d)", filename, r);
323 /* Header and footer of the stream should be equal. */
324 r = lzma_stream_flags_compare (&header_flags, &footer_flags);
326 error (EXIT_FAILURE, 0,
327 "%s: header and footer of stream are not equal (error %d)",
330 /* Store the decoded stream flags in this_index. */
331 r = lzma_index_stream_flags (this_index, &footer_flags);
333 error (EXIT_FAILURE, 0,
334 "%s: cannot read stream_flags from index (error %d)",
337 /* Store the amount of stream padding so far. Needed to calculate
338 * compressed offsets correctly in multi-stream files.
340 r = lzma_index_stream_padding (this_index, stream_padding);
342 error (EXIT_FAILURE, 0,
343 "%s: cannot set stream_padding in index (error %d)",
346 if (combined_index != NULL) {
347 r = lzma_index_cat (this_index, combined_index, NULL);
349 error (EXIT_FAILURE, 0, "%s: cannot combine indexes", filename);
352 combined_index = this_index;
358 return combined_index;
361 /* Return true iff the buffer is all zero bytes.
363 * Note that gcc is smart enough to optimize this properly:
364 * http://stackoverflow.com/questions/1493936/faster-means-of-checking-for-an-empty-buffer-in-c/1493989#1493989
367 is_zero (const char *buffer, size_t size)
371 for (i = 0; i < size; ++i) {
379 struct global_state {
380 /* Current iterator. Threads update this, but it is protected by a
381 * mutex, and each thread takes a copy of it when working on it.
383 lzma_index_iter iter;
384 lzma_bool iter_finished;
385 pthread_mutex_t iter_mutex;
387 /* Note that all threads are accessing these fds, so you have
388 * to use pread/pwrite instead of lseek!
392 const char *filename;
396 const char *outputfile;
400 struct per_thread_state {
402 struct global_state *global;
406 /* Create threads to iterate over the blocks and uncompress. */
407 static void *worker_thread (void *vp);
410 iter_blocks (lzma_index *idx, unsigned nr_threads,
411 const char *filename, int fd, const char *outputfile, int ofd)
413 struct global_state global;
414 struct per_thread_state per_thread[nr_threads];
415 pthread_t thread[nr_threads];
416 unsigned u, nr_errors;
420 lzma_index_iter_init (&global.iter, idx);
421 global.iter_finished = 0;
422 err = pthread_mutex_init (&global.iter_mutex, NULL);
424 error (EXIT_FAILURE, err, "pthread_mutex_init");
426 global.filename = filename;
428 global.outputfile = outputfile;
431 for (u = 0; u < nr_threads; ++u) {
432 per_thread[u].thread_num = u;
433 per_thread[u].global = &global;
436 /* Start the threads. */
437 for (u = 0; u < nr_threads; ++u) {
438 err = pthread_create (&thread[u], NULL, worker_thread, &per_thread[u]);
440 error (EXIT_FAILURE, err, "pthread_create (%u)", u);
443 /* Wait for the threads to exit. */
445 for (u = 0; u < nr_threads; ++u) {
446 err = pthread_join (thread[u], &status);
448 error (0, err, "pthread_join (%u)", u);
451 if (*(int *)status == -1)
459 /* Iterate over the blocks and uncompress. */
461 worker_thread (void *vp)
463 struct per_thread_state *state = vp;
464 struct global_state *global = state->global;
465 lzma_index_iter iter;
467 off_t position, oposition;
468 uint8_t header[LZMA_BLOCK_HEADER_SIZE_MAX];
471 lzma_filter filters[LZMA_FILTERS_MAX + 1];
473 lzma_stream strm = LZMA_STREAM_INIT;
474 uint8_t buf[BUFFER_SIZE];
475 char outbuf[BUFFER_SIZE];
477 lzma_bool iter_finished;
482 /* Get the next block. */
483 err = pthread_mutex_lock (&global->iter_mutex);
484 if (err != 0) abort ();
485 iter_finished = global->iter_finished;
486 if (!iter_finished) {
487 iter_finished = global->iter_finished =
488 lzma_index_iter_next (&global->iter, LZMA_INDEX_ITER_NONEMPTY_BLOCK);
490 /* Take a local copy of this iterator since another thread will
491 * update the global version.
495 err = pthread_mutex_unlock (&global->iter_mutex);
496 if (err != 0) abort ();
500 /* Read the block header. Start by reading a single byte which
501 * tell us how big the block header is.
503 position = iter.block.compressed_file_offset;
504 n = pread (global->fd, header, 1, position);
507 "%s: read: unexpected end of file reading block header byte",
509 return &state->status;
512 error (0, errno, "%s: read", global->filename);
513 return &state->status;
517 if (header[0] == '\0') {
519 "%s: read: unexpected invalid block in file, header[0] = 0",
521 return &state->status;
525 block.check = iter.stream.flags->check;
526 block.filters = filters;
527 block.header_size = lzma_block_header_size_decode (header[0]);
529 /* Now read and decode the block header. */
530 n = pread (global->fd, &header[1], block.header_size-1, position);
531 if (n >= 0 && n != block.header_size-1) {
533 "%s: read: unexpected end of file reading block header",
535 return &state->status;
538 error (0, errno, "%s: read", global->filename);
539 return &state->status;
543 r = lzma_block_header_decode (&block, NULL, header);
545 error (0, errno, "%s: invalid block header (error %d)",
546 global->filename, r);
547 return &state->status;
550 /* What this actually does is it checks that the block header
553 r = lzma_block_compressed_size (&block, iter.block.unpadded_size);
556 "%s: cannot calculate compressed size (error %d)",
557 global->filename, r);
558 return &state->status;
561 /* Where we will start writing to. */
562 oposition = iter.block.uncompressed_file_offset;
564 /* Read the block data and uncompress it. */
565 r = lzma_block_decoder (&strm, &block);
567 error (0, 0, "%s: invalid block (error %d)", global->filename, r);
568 return &state->status;
573 strm.next_out = outbuf;
574 strm.avail_out = sizeof outbuf;
577 lzma_action action = LZMA_RUN;
579 if (strm.avail_in == 0) {
581 n = pread (global->fd, buf, sizeof buf, position);
583 error (0, errno, "%s: read", global->filename);
584 return &state->status;
589 action = LZMA_FINISH;
592 r = lzma_code (&strm, action);
594 if (strm.avail_out == 0 || r == LZMA_STREAM_END) {
595 size_t wsz = sizeof outbuf - strm.avail_out;
597 /* Don't write if the block is all zero, to preserve output file
598 * sparseness. However we have to update oposition.
600 if (!is_zero (outbuf, wsz)) {
601 if (pwrite (global->ofd, outbuf, wsz, oposition) != wsz) {
602 /* XXX Handle short writes. */
603 error (0, errno, "%s: write", global->filename);
604 return &state->status;
609 strm.next_out = outbuf;
610 strm.avail_out = sizeof outbuf;
613 if (r == LZMA_STREAM_END)
617 "%s: could not parse block data (error %d)",
618 global->filename, r);
619 return &state->status;
625 for (i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i)
626 free (filters[i].options);
630 return &state->status;