befc2c00a3e2319ded8753231913b387815510b0
[pxzcat.git] / pxzcat.c
1 /* pxzcat derived from nbdkit
2  * Copyright (C) 2013 Red Hat Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  * * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
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.
15  *
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.
19  *
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
31  * SUCH DAMAGE.
32  */
33
34 #include <config.h>
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stdint.h>
40 #include <inttypes.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <sys/types.h>
44 #include <error.h>
45 #include <errno.h>
46 #include <getopt.h>
47
48 #include <lzma.h>
49
50 #define DEBUG 1
51
52 #if DEBUG
53 #define debug(fs,...) fprintf (stderr, "pxzcat: debug: " fs "\n", ## __VA_ARGS__)
54 #else
55 #define debug(fs,...) /* nothing */
56 #endif
57
58 #define XZ_HEADER_MAGIC     "\xfd" "7zXZ\0"
59 #define XZ_HEADER_MAGIC_LEN 6
60 #define XZ_FOOTER_MAGIC     "YZ"
61 #define XZ_FOOTER_MAGIC_LEN 2
62
63 static void usage (int exitcode);
64 static void xzfile_uncompress (const char *filename, const char *outputfile);
65 static int check_header_magic (int fd);
66 static lzma_index *parse_indexes (const char *filename, int fd);
67 static void iter_blocks (lzma_index *idx, const char *filename, int fd, const char *outputfile, int ofd);
68
69 static struct option long_options[] = {
70   { "output",   required_argument,  0, 'o' },
71   { "help",     0,                  0, '?' },
72   { NULL,       0,                  0, 0   }
73 };
74
75 static const char *options = "o:";
76
77 int
78 main (int argc, char *argv[])
79 {
80   int c;
81   int longopt_index;
82   const char *outputfile = NULL;
83
84   for (;;) {
85     c = getopt_long (argc, argv, options, long_options, &longopt_index);
86     if (c == -1)
87       break;
88
89     switch (c) {
90       /* Long option with no short opt equivalent. */
91     case 0:
92       abort ();
93
94     case 'o':
95       outputfile = optarg;
96       break;
97
98     case '?':
99       usage (EXIT_SUCCESS);
100
101     default:
102       usage (EXIT_FAILURE);
103     }
104   }
105
106   if (outputfile == NULL)
107     error (EXIT_FAILURE, 0, "you must give the -o (output file) option\n");
108
109   if (optind != argc - 1)
110     usage (EXIT_FAILURE);
111
112   xzfile_uncompress (argv[optind], outputfile);
113
114   exit (EXIT_SUCCESS);
115 }
116
117 static void
118 usage (int exitcode)
119 {
120   printf ("usage: pxzcat -o output input.xz\n");
121   exit (exitcode);
122 }
123
124 static void
125 xzfile_uncompress (const char *filename, const char *outputfile)
126 {
127   int fd, ofd;
128   uint64_t size;
129   lzma_index *idx;
130
131   /* Open the file. */
132   fd = open (filename, O_RDONLY);
133   if (fd == -1)
134     error (EXIT_FAILURE, errno, "open: %s", filename);
135
136   /* Check file magic. */
137   if (!check_header_magic (fd))
138     error (EXIT_FAILURE, 0, "%s: not an xz file", filename);
139
140   /* Read and parse the indexes. */
141   idx = parse_indexes (filename, fd);
142
143   /* Get the file uncompressed size, create the output file. */
144   size = lzma_index_uncompressed_size (idx);
145   debug ("uncompressed size = %" PRIu64 " bytes", size);
146
147   ofd = open (outputfile, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0644);
148   if (ofd == -1)
149     error (EXIT_FAILURE, errno, "open: %s", outputfile);
150   if (ftruncate (ofd, size) == -1)
151     error (EXIT_FAILURE, errno, "ftruncate: %s", outputfile);
152
153   /* Iterate over blocks and uncompress. */
154   iter_blocks (idx, filename, fd, outputfile, ofd);
155
156   close (fd);
157 }
158
159 static int
160 check_header_magic (int fd)
161 {
162   char buf[XZ_HEADER_MAGIC_LEN];
163
164   if (lseek (fd, 0, SEEK_SET) == -1)
165     return 0;
166   if (read (fd, buf, XZ_HEADER_MAGIC_LEN) != XZ_HEADER_MAGIC_LEN)
167     return 0;
168   if (memcmp (buf, XZ_HEADER_MAGIC, XZ_HEADER_MAGIC_LEN) != 0)
169     return 0;
170   return 1;
171 }
172
173 /* For explanation of this function, see src/xz/list.c:parse_indexes
174  * in the xz sources.
175  */
176 static lzma_index *
177 parse_indexes (const char *filename, int fd)
178 {
179   lzma_ret r;
180   off_t pos, index_size;
181   uint8_t footer[LZMA_STREAM_HEADER_SIZE];
182   uint8_t header[LZMA_STREAM_HEADER_SIZE];
183   lzma_stream_flags footer_flags;
184   lzma_stream_flags header_flags;
185   lzma_stream strm = LZMA_STREAM_INIT;
186   ssize_t n;
187   lzma_index *combined_index = NULL;
188   lzma_index *this_index = NULL;
189   lzma_vli stream_padding = 0;
190   size_t nr_streams = 0;
191
192   /* Check file size is a multiple of 4 bytes. */
193   pos = lseek (fd, 0, SEEK_END);
194   if (pos == (off_t) -1)
195     error (EXIT_FAILURE, errno, "%s: lseek", filename);
196
197   if ((pos & 3) != 0)
198     error (EXIT_FAILURE, 0,
199            "%s: not an xz file: size is not a multiple of 4 bytes",
200            filename);
201
202   /* Jump backwards through the file identifying each stream. */
203   while (pos > 0) {
204     debug ("looping through streams: pos = %" PRIu64, (uint64_t) pos);
205
206     if (pos < LZMA_STREAM_HEADER_SIZE)
207       error (EXIT_FAILURE, 0,
208              "%s: corrupted file at %" PRIu64, filename, (uint64_t) pos);
209
210     if (lseek (fd, -LZMA_STREAM_HEADER_SIZE, SEEK_CUR) == -1)
211       error (EXIT_FAILURE, errno, "%s: lseek", filename);
212
213     if (read (fd, footer, LZMA_STREAM_HEADER_SIZE) != LZMA_STREAM_HEADER_SIZE)
214       error (EXIT_FAILURE, errno, "%s: read stream footer", filename);
215
216     /* Skip stream padding. */
217     if (footer[8] == 0 && footer[9] == 0 &&
218         footer[10] == 0 && footer[11] == 0) {
219       stream_padding += 4;
220       pos -= 4;
221       continue;
222     }
223
224     pos -= LZMA_STREAM_HEADER_SIZE;
225     nr_streams++;
226
227     debug ("decode stream footer at pos = %" PRIu64, (uint64_t) pos);
228
229     /* Does the stream footer look reasonable? */
230     r = lzma_stream_footer_decode (&footer_flags, footer);
231     if (r != LZMA_OK)
232       error (EXIT_FAILURE, 0,
233              "%s: invalid stream footer (error %d)", filename, r);
234
235     debug ("backward_size = %" PRIu64, (uint64_t) footer_flags.backward_size);
236     index_size = footer_flags.backward_size;
237     if (pos < index_size + LZMA_STREAM_HEADER_SIZE)
238       error (EXIT_FAILURE, 0, "%s: invalid stream footer", filename);
239
240     pos -= index_size;
241     debug ("decode index at pos = %" PRIu64, (uint64_t) pos);
242
243     /* Seek backwards to the index of this stream. */
244     if (lseek (fd, pos, SEEK_SET) == -1)
245       error (EXIT_FAILURE, errno, "%s: lseek", filename);
246
247     /* Decode the index. */
248     r = lzma_index_decoder (&strm, &this_index, UINT64_MAX);
249     if (r != LZMA_OK)
250       error (EXIT_FAILURE, 0,
251              "%s: invalid stream index (error %d)", filename, r);
252
253     do {
254       uint8_t buf[BUFSIZ];
255
256       strm.avail_in = index_size;
257       if (strm.avail_in > BUFSIZ)
258         strm.avail_in = BUFSIZ;
259
260       n = read (fd, &buf, strm.avail_in);
261       if (n == -1)
262         error (EXIT_FAILURE, errno, "%s: read", filename);
263
264       index_size -= strm.avail_in;
265
266       strm.next_in = buf;
267       r = lzma_code (&strm, LZMA_RUN);
268     } while (r == LZMA_OK);
269
270     if (r != LZMA_STREAM_END)
271       error (EXIT_FAILURE, 0, "%s: could not parse index (error %d)",
272              filename, r);
273
274     pos -= lzma_index_total_size (this_index) + LZMA_STREAM_HEADER_SIZE;
275
276     debug ("decode stream header at pos = %" PRIu64, (uint64_t) pos);
277
278     /* Read and decode the stream header. */
279     if (lseek (fd, pos, SEEK_SET) == -1)
280       error (EXIT_FAILURE, errno, "%s: lseek", filename);
281
282     if (read (fd, header, LZMA_STREAM_HEADER_SIZE) != LZMA_STREAM_HEADER_SIZE)
283       error (EXIT_FAILURE, errno, "%s: read stream header", filename);
284
285     r = lzma_stream_header_decode (&header_flags, header);
286     if (r != LZMA_OK)
287       error (EXIT_FAILURE, 0,
288              "%s: invalid stream header (error %d)", filename, r);
289
290     /* Header and footer of the stream should be equal. */
291     r = lzma_stream_flags_compare (&header_flags, &footer_flags);
292     if (r != LZMA_OK)
293       error (EXIT_FAILURE, 0,
294              "%s: header and footer of stream are not equal (error %d)",
295              filename, r);
296
297     /* Store the decoded stream flags in this_index. */
298     r = lzma_index_stream_flags (this_index, &footer_flags);
299     if (r != LZMA_OK)
300       error (EXIT_FAILURE, 0,
301              "%s: cannot read stream_flags from index (error %d)",
302              filename, r);
303
304     /* Store the amount of stream padding so far.  Needed to calculate
305      * compressed offsets correctly in multi-stream files.
306      */
307     r = lzma_index_stream_padding (this_index, stream_padding);
308     if (r != LZMA_OK)
309       error (EXIT_FAILURE, 0,
310              "%s: cannot set stream_padding in index (error %d)",
311              filename, r);
312
313     if (combined_index != NULL) {
314       r = lzma_index_cat (this_index, combined_index, NULL);
315       if (r != LZMA_OK)
316         error (EXIT_FAILURE, 0, "%s: cannot combine indexes", filename);
317     }
318
319     combined_index = this_index;
320     this_index = NULL;
321   }
322
323   lzma_end (&strm);
324
325   return combined_index;
326 }
327
328 /* Iterate over the blocks and uncompress. */
329 static void
330 iter_blocks (lzma_index *idx,
331              const char *filename, int fd, const char *outputfile, int ofd)
332 {
333   lzma_index_iter iter;
334   uint8_t header[LZMA_BLOCK_HEADER_SIZE_MAX];
335   ssize_t n;
336   lzma_block block;
337   lzma_filter filters[LZMA_FILTERS_MAX + 1];
338   lzma_ret r;
339   lzma_stream strm = LZMA_STREAM_INIT;
340   char outbuf[BUFSIZ];
341   size_t i;
342
343   lzma_index_iter_init (&iter, idx);
344   while (!lzma_index_iter_next (&iter, LZMA_INDEX_ITER_NONEMPTY_BLOCK)) {
345     /* Seek to the start of the block in the input file. */
346     if (lseek (fd, iter.block.compressed_file_offset, SEEK_SET) == -1)
347       error (EXIT_FAILURE, errno, "lseek");
348
349     /* Read the block header.  Start by reading a single byte which
350      * tell us how big the block header is.
351      */
352     n = read (fd, header, 1);
353     if (n == 0)
354       error (EXIT_FAILURE, 0,
355              "%s: read: unexpected end of file reading block header byte",
356              filename);
357     if (n == -1)
358       error (EXIT_FAILURE, errno, "%s: read", filename);
359
360     if (header[0] == '\0')
361       error (EXIT_FAILURE, errno,
362              "%s: read: unexpected invalid block in file, header[0] = 0",
363              filename);
364
365     block.version = 0;
366     block.check = iter.stream.flags->check;
367     block.filters = filters;
368     block.header_size = lzma_block_header_size_decode (header[0]);
369
370     /* Now read and decode the block header. */
371     n = read (fd, &header[1], block.header_size-1);
372     if (n >= 0 && n != block.header_size-1)
373       error (EXIT_FAILURE, 0,
374              "%s: read: unexpected end of file reading block header",
375              filename);
376     if (n == -1)
377       error (EXIT_FAILURE, errno, "%s: read", filename);
378
379     r = lzma_block_header_decode (&block, NULL, header);
380     if (r != LZMA_OK)
381       error (EXIT_FAILURE, errno, "%s: invalid block header (error %d)",
382              filename, r);
383
384     /* What this actually does is it checks that the block header
385      * matches the index.
386      */
387     r = lzma_block_compressed_size (&block, iter.block.unpadded_size);
388     if (r != LZMA_OK)
389       error (EXIT_FAILURE, errno,
390              "%s: cannot calculate compressed size (error %d)", filename, r);
391
392     /* Read the block data and uncompress it. */
393     r = lzma_block_decoder (&strm, &block);
394     if (r != LZMA_OK)
395       error (EXIT_FAILURE, 0, "%s: invalid block (error %d)", filename, r);
396
397     strm.next_in = NULL;
398     strm.avail_in = 0;
399     strm.next_out = outbuf;
400     strm.avail_out = sizeof outbuf;
401
402     for (;;) {
403       uint8_t buf[BUFSIZ];
404       lzma_action action = LZMA_RUN;
405
406       if (strm.avail_in == 0) {
407         strm.next_in = buf;
408         n = read (fd, buf, sizeof buf);
409         if (n == -1)
410           error (EXIT_FAILURE, errno, "%s: read", filename);
411         strm.avail_in = n;
412         if (n == 0)
413           action = LZMA_FINISH;
414       }
415
416       r = lzma_code (&strm, action);
417
418       if (strm.avail_out == 0 || r == LZMA_STREAM_END) {
419         size_t wsz = sizeof outbuf - strm.avail_out;
420         if (write (ofd, outbuf, wsz) != wsz)
421           /* XXX Handle short writes. */
422           error (EXIT_FAILURE, errno, "%s: write", filename);
423         strm.next_out = outbuf;
424         strm.avail_out = sizeof outbuf;
425       }
426
427       if (r == LZMA_STREAM_END)
428         break;
429       if (r != LZMA_OK)
430         error (EXIT_FAILURE, 0,
431                "%s: could not parse block data (error %d)", filename, r);
432     }
433
434     lzma_end (&strm);
435
436     for (i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i)
437       free (filters[i].options);
438   }
439 }