blob: ba3dbf3d0a9a4ab64d16e0c96bedff13c0b7f6a0 [file] [log] [blame]
Anders F Bjorklund6bdc7742011-09-19 09:53:20 +02001#include "xzlib.h"
2
3/* values for xz_state how */
4#define LOOK 0 /* look for a gzip/lzma header */
5#define COPY 1 /* copy input directly */
6#define GZIP 2 /* decompress a gzip stream */
7#define LZMA 3 /* decompress a lzma stream */
8
9/* internal lzma file state data structure */
10typedef struct {
11 int mode; /* see lzma modes above */
12 int fd; /* file descriptor */
13 char *path; /* path or fd for error messages */
14 uint64_t pos; /* current position in uncompressed data */
15 unsigned size; /* buffer size, zero if not allocated yet */
16 unsigned want; /* requested buffer size, default is BUFSIZ */
17 unsigned char *in; /* input buffer */
18 unsigned char *out; /* output buffer (double-sized when reading) */
19 unsigned char *next; /* next output data to deliver or write */
20 unsigned have; /* amount of output data unused at next */
21 int eof; /* true if end of input file reached */
22 uint64_t start; /* where the lzma data started, for rewinding */
23 uint64_t raw; /* where the raw data started, for seeking */
24 int how; /* 0: get header, 1: copy, 2: decompress */
25 int direct; /* true if last read direct, false if lzma */
26 /* seek request */
27 uint64_t skip; /* amount to skip (already rewound if backwards) */
28 int seek; /* true if seek request pending */
29 /* error information */
30 int err; /* error code */
31 char *msg; /* error message */
32 /* lzma stream */
33 lzma_stream strm; /* stream structure in-place (not a pointer) */
34#ifdef HAVE_ZLIB_H
35 /* zlib inflate or deflate stream */
36 z_stream zstrm; /* stream structure in-place (not a pointer) */
37#endif
38} xz_state, *xz_statep;
39
40static void xz_error(xz_statep state, int err, const char *msg)
41{
42 /* free previously allocated message and clear */
43 if (state->msg != NULL) {
44 if (state->err != LZMA_MEM_ERROR)
45 free(state->msg);
46 state->msg = NULL;
47 }
48
49 /* set error code, and if no message, then done */
50 state->err = err;
51 if (msg == NULL)
52 return;
53
54 /* for an out of memory error, save as static string */
55 if (err == LZMA_MEM_ERROR) {
56 state->msg = (char *)msg;
57 return;
58 }
59
60 /* construct error message with path */
61 if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) {
62 state->err = LZMA_MEM_ERROR;
63 state->msg = (char *)"out of memory";
64 return;
65 }
66 strcpy(state->msg, state->path);
67 strcat(state->msg, ": ");
68 strcat(state->msg, msg);
69 return;
70}
71
72static void xz_reset(xz_statep state)
73{
74 state->have = 0; /* no output data available */
75 state->eof = 0; /* not at end of file */
76 state->how = LOOK; /* look for gzip header */
77 state->direct = 1; /* default for empty file */
78 state->seek = 0; /* no seek request pending */
79 xz_error(state, LZMA_OK, NULL); /* clear error */
80 state->pos = 0; /* no uncompressed data yet */
81 state->strm.avail_in = 0; /* no input data yet */
82#ifdef HAVE_ZLIB_H
83 state->zstrm.avail_in = 0; /* no input data yet */
84#endif
85}
86
87static xzFile xz_open(const char *path, int fd, const char *mode ATTRIBUTE_UNUSED)
88{
89 xz_statep state;
90
91 /* allocate xzFile structure to return */
92 state = malloc(sizeof(xz_state));
93 if (state == NULL)
94 return NULL;
95 state->size = 0; /* no buffers allocated yet */
96 state->want = BUFSIZ; /* requested buffer size */
97 state->msg = NULL; /* no error message yet */
98
99 /* save the path name for error messages */
100 state->path = malloc(strlen(path) + 1);
101 if (state->path == NULL) {
102 free(state);
103 return NULL;
104 }
105 strcpy(state->path, path);
106
107 /* open the file with the appropriate mode (or just use fd) */
108 state->fd = fd != -1 ? fd :
109 open(path,
110#ifdef O_LARGEFILE
111 O_LARGEFILE |
112#endif
113#ifdef O_BINARY
114 O_BINARY |
115#endif
116 O_RDONLY,
117 0666);
118 if (state->fd == -1) {
119 free(state->path);
120 free(state);
121 return NULL;
122 }
123
124 /* save the current position for rewinding (only if reading) */
125 state->start = lseek(state->fd, 0, SEEK_CUR);
126 if (state->start == (uint64_t) -1) state->start = 0;
127
128 /* initialize stream */
129 xz_reset(state);
130
131 /* return stream */
132 return (xzFile)state;
133}
134
135xzFile xzopen(const char *path, const char *mode)
136{
137 return xz_open(path, -1, mode);
138}
139
140xzFile xzdopen(int fd, const char *mode)
141{
142 char *path; /* identifier for error messages */
143 xzFile xz;
144
145 if (fd == -1 || (path = malloc(7 + 3 * sizeof(int))) == NULL)
146 return NULL;
147 sprintf(path, "<fd:%d>", fd); /* for debugging */
148 xz = xz_open(path, fd, mode);
149 free(path);
150 return xz;
151}
152
153static int xz_load(xz_statep state, unsigned char *buf, unsigned len, unsigned *have)
154{
155 int ret;
156
157 *have = 0;
158 do {
159 ret = read(state->fd, buf + *have, len - *have);
160 if (ret <= 0)
161 break;
162 *have += ret;
163 } while (*have < len);
164 if (ret < 0) {
165 xz_error(state, -1, strerror(errno));
166 return -1;
167 }
168 if (ret == 0)
169 state->eof = 1;
170 return 0;
171}
172
173static int xz_avail(xz_statep state)
174{
175 lzma_stream *strm = &(state->strm);
176
177 if (state->err != LZMA_OK)
178 return -1;
179 if (state->eof == 0) {
180 if (xz_load(state, state->in, state->size,
181 (unsigned *)&(strm->avail_in)) == -1)
182 return -1;
183 strm->next_in = state->in;
184 }
185 return 0;
186}
187
188static int
189is_format_xz(xz_statep state)
190{
191 lzma_stream *strm = &(state->strm);
192
193 return strm->avail_in >= 6 && memcmp(state->in, "\3757zXZ", 6) == 0;
194}
195
196static int
197is_format_lzma(xz_statep state)
198{
199 lzma_stream *strm = &(state->strm);
200
201 lzma_filter filter;
202 lzma_options_lzma *opt;
203 uint32_t dict_size;
204 uint64_t uncompressed_size;
205 size_t i;
206
207 if (strm->avail_in < 13)
208 return 0;
209
210 filter.id = LZMA_FILTER_LZMA1;
211 if (lzma_properties_decode(&filter, NULL, state->in, 5) != LZMA_OK)
212 return 0;
213
214 opt = filter.options;
215 dict_size = opt->dict_size;
216 free(opt);
217
218 /* A hack to ditch tons of false positives: We allow only dictionary
219 * sizes that are 2^n or 2^n + 2^(n-1) or UINT32_MAX. LZMA_Alone
220 * created only files with 2^n, but accepts any dictionary size.
221 * If someone complains, this will be reconsidered.
222 */
223 if (dict_size != UINT32_MAX) {
224 uint32_t d = dict_size - 1;
225 d |= d >> 2;
226 d |= d >> 3;
227 d |= d >> 4;
228 d |= d >> 8;
229 d |= d >> 16;
230 ++d;
231 if (d != dict_size || dict_size == 0)
232 return 0;
233 }
234
235 /* Another hack to ditch false positives: Assume that if the
236 * uncompressed size is known, it must be less than 256 GiB.
237 * Again, if someone complains, this will be reconsidered.
238 */
239 uncompressed_size = 0;
240 for (i = 0; i < 8; ++i)
241 uncompressed_size |= (uint64_t)(state->in[5 + i]) << (i * 8);
242
243 if (uncompressed_size != UINT64_MAX
244 && uncompressed_size > (UINT64_C(1) << 38))
245 return 0;
246
247 return 1;
248}
249
250#ifdef HAVE_ZLIB_H
251/* Get next byte from input, or -1 if end or error. */
252#define NEXT() ((strm->avail_in == 0 && xz_avail(state) == -1) ? -1 : \
253 (strm->avail_in == 0 ? -1 : \
254 (strm->avail_in--, *(strm->next_in)++)))
255
256/* Get a four-byte little-endian integer and return 0 on success and the value
257 in *ret. Otherwise -1 is returned and *ret is not modified. */
258static int gz_next4(xz_statep state, unsigned long *ret)
259{
260 int ch;
261 unsigned long val;
262 z_streamp strm = &(state->zstrm);
263
264 val = NEXT();
265 val += (unsigned)NEXT() << 8;
266 val += (unsigned long)NEXT() << 16;
267 ch = NEXT();
268 if (ch == -1)
269 return -1;
270 val += (unsigned long)ch << 24;
271 *ret = val;
272 return 0;
273}
274#endif
275
276static int xz_head(xz_statep state)
277{
278 lzma_stream *strm = &(state->strm);
279 lzma_stream init = LZMA_STREAM_INIT;
280 int flags;
281 unsigned len;
282
283 /* allocate read buffers and inflate memory */
284 if (state->size == 0) {
285 /* allocate buffers */
286 state->in = malloc(state->want);
287 state->out = malloc(state->want << 1);
288 if (state->in == NULL || state->out == NULL) {
289 if (state->out != NULL)
290 free(state->out);
291 if (state->in != NULL)
292 free(state->in);
293 xz_error(state, LZMA_MEM_ERROR, "out of memory");
294 return -1;
295 }
296 state->size = state->want;
297
298 /* allocate decoder memory */
299 state->strm = init;
300 state->strm.avail_in = 0;
301 state->strm.next_in = NULL;
302 if (lzma_auto_decoder(&state->strm, UINT64_MAX, 0) != LZMA_OK) {
303 free(state->out);
304 free(state->in);
305 state->size = 0;
306 xz_error(state, LZMA_MEM_ERROR, "out of memory");
307 return -1;
308 }
309
310#ifdef HAVE_ZLIB_H
311 /* allocate inflate memory */
312 state->zstrm.zalloc = Z_NULL;
313 state->zstrm.zfree = Z_NULL;
314 state->zstrm.opaque = Z_NULL;
315 state->zstrm.avail_in = 0;
316 state->zstrm.next_in = Z_NULL;
317 if (inflateInit2(&(state->zstrm), -15) != Z_OK) { /* raw inflate */
318 free(state->out);
319 free(state->in);
320 state->size = 0;
321 xz_error(state, LZMA_MEM_ERROR, "out of memory");
322 return -1;
323 }
324#endif
325 }
326
327 /* get some data in the input buffer */
328 if (strm->avail_in == 0) {
329 if (xz_avail(state) == -1)
330 return -1;
331 if (strm->avail_in == 0)
332 return 0;
333 }
334
335 /* look for the xz magic header bytes */
336 if (is_format_xz(state) || is_format_lzma(state)) {
337 state->how = LZMA;
338 state->direct = 0;
339 return 0;
340 }
341
342#ifdef HAVE_ZLIB_H
343 /* look for the gzip magic header bytes 31 and 139 */
344 if (strm->next_in[0] == 31) {
345 strm->avail_in--;
346 strm->next_in++;
347 if (strm->avail_in == 0 && xz_avail(state) == -1)
348 return -1;
349 if (strm->avail_in && strm->next_in[0] == 139) {
350 /* we have a gzip header, woo hoo! */
351 strm->avail_in--;
352 strm->next_in++;
353
354 /* skip rest of header */
355 if (NEXT() != 8) { /* compression method */
356 xz_error(state, LZMA_DATA_ERROR, "unknown compression method");
357 return -1;
358 }
359 flags = NEXT();
360 if (flags & 0xe0) { /* reserved flag bits */
361 xz_error(state, LZMA_DATA_ERROR, "unknown header flags set");
362 return -1;
363 }
364 NEXT(); /* modification time */
365 NEXT();
366 NEXT();
367 NEXT();
368 NEXT(); /* extra flags */
369 NEXT(); /* operating system */
370 if (flags & 4) { /* extra field */
371 len = (unsigned)NEXT();
372 len += (unsigned)NEXT() << 8;
373 while (len--)
374 if (NEXT() < 0)
375 break;
376 }
377 if (flags & 8) /* file name */
378 while (NEXT() > 0)
379 ;
380 if (flags & 16) /* comment */
381 while (NEXT() > 0)
382 ;
383 if (flags & 2) { /* header crc */
384 NEXT();
385 NEXT();
386 }
387 /* an unexpected end of file is not checked for here -- it will be
388 noticed on the first request for uncompressed data */
389
390 /* set up for decompression */
391 inflateReset(&state->zstrm);
392 state->zstrm.adler = crc32(0L, Z_NULL, 0);
393 state->how = GZIP;
394 state->direct = 0;
395 return 0;
396 }
397 else {
398 /* not a gzip file -- save first byte (31) and fall to raw i/o */
399 state->out[0] = 31;
400 state->have = 1;
401 }
402 }
403#endif
404
405 /* doing raw i/o, save start of raw data for seeking, copy any leftover
406 input to output -- this assumes that the output buffer is larger than
407 the input buffer, which also assures space for gzungetc() */
408 state->raw = state->pos;
409 state->next = state->out;
410 if (strm->avail_in) {
411 memcpy(state->next + state->have, strm->next_in, strm->avail_in);
412 state->have += strm->avail_in;
413 strm->avail_in = 0;
414 }
415 state->how = COPY;
416 state->direct = 1;
417 return 0;
418}
419
420static int xz_decomp(xz_statep state)
421{
422 int ret;
423 unsigned had;
424 unsigned long crc, len;
425 lzma_stream *strm = &(state->strm);
426
427 lzma_action action = LZMA_RUN;
428
429 /* fill output buffer up to end of deflate stream */
430 had = strm->avail_out;
431 do {
432 /* get more input for inflate() */
433 if (strm->avail_in == 0 && xz_avail(state) == -1)
434 return -1;
435 if (strm->avail_in == 0) {
436 xz_error(state, LZMA_DATA_ERROR, "unexpected end of file");
437 return -1;
438 }
439 if (state->eof)
440 action = LZMA_FINISH;
441
442 /* decompress and handle errors */
443#ifdef HAVE_ZLIB_H
444 if (state->how == GZIP) {
445 state->zstrm.avail_in = (uInt) state->strm.avail_in;
446 state->zstrm.next_in = (Bytef*) state->strm.next_in;
447 state->zstrm.avail_out = (uInt) state->strm.avail_out;
448 state->zstrm.next_out = (Bytef*) state->strm.next_out;
449 ret = inflate(&state->zstrm, Z_NO_FLUSH);
450 if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
451 xz_error(state, Z_STREAM_ERROR,
452 "internal error: inflate stream corrupt");
453 return -1;
454 }
455 if (ret == Z_MEM_ERROR) ret = LZMA_MEM_ERROR;
456 if (ret == Z_DATA_ERROR) ret = LZMA_DATA_ERROR;
457 if (ret == Z_STREAM_END) ret = LZMA_STREAM_END;
458 state->strm.avail_in = state->zstrm.avail_in;
459 state->strm.next_in = state->zstrm.next_in;
460 state->strm.avail_out = state->zstrm.avail_out;
461 state->strm.next_out = state->zstrm.next_out;
462 }
463 else /* state->how == LZMA */
464#endif
465 ret = lzma_code(strm, action);
466 if (ret == LZMA_MEM_ERROR) {
467 xz_error(state, LZMA_MEM_ERROR, "out of memory");
468 return -1;
469 }
470 if (ret == LZMA_DATA_ERROR) {
471 xz_error(state, LZMA_DATA_ERROR, "compressed data error");
472 return -1;
473 }
474 } while (strm->avail_out && ret != LZMA_STREAM_END);
475
476 /* update available output and crc check value */
477 state->have = had - strm->avail_out;
478 state->next = strm->next_out - state->have;
479#ifdef HAVE_ZLIB_H
480 state->zstrm.adler = crc32(state->zstrm.adler, state->next, state->have);
481#endif
482
483 if (ret == LZMA_STREAM_END) {
484#ifdef HAVE_ZLIB_H
485 if (state->how == GZIP) {
486 if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {
487 xz_error(state, LZMA_DATA_ERROR, "unexpected end of file");
488 return -1;
489 }
490 if (crc != state->zstrm.adler) {
491 xz_error(state, LZMA_DATA_ERROR, "incorrect data check");
492 return -1;
493 }
494 if (len != (state->zstrm.total_out & 0xffffffffL)) {
495 xz_error(state, LZMA_DATA_ERROR, "incorrect length check");
496 return -1;
497 }
498 state->strm.avail_in = 0;
499 state->strm.next_in = NULL;
500 state->strm.avail_out = 0;
501 state->strm.next_out = NULL;
502 }
503 else
504#endif
505 if ( strm->avail_in != 0 || !state->eof) {
506 xz_error(state, LZMA_DATA_ERROR, "trailing garbage");
507 return -1;
508 }
509 state->how = LOOK; /* ready for next stream, once have is 0 (leave
510 state->direct unchanged to remember how) */
511 }
512
513 /* good decompression */
514 return 0;
515}
516
517static int xz_make(xz_statep state)
518{
519 lzma_stream *strm = &(state->strm);
520
521 if (state->how == LOOK) { /* look for lzma / gzip header */
522 if (xz_head(state) == -1)
523 return -1;
524 if (state->have) /* got some data from xz_head() */
525 return 0;
526 }
527 if (state->how == COPY) { /* straight copy */
528 if (xz_load(state, state->out, state->size << 1, &(state->have)) == -1)
529 return -1;
530 state->next = state->out;
531 }
532 else if (state->how == LZMA || state->how == GZIP) { /* decompress */
533 strm->avail_out = state->size << 1;
534 strm->next_out = state->out;
535 if (xz_decomp(state) == -1)
536 return -1;
537 }
538 return 0;
539}
540
541static int xz_skip(xz_statep state, uint64_t len)
542{
543 unsigned n;
544
545 /* skip over len bytes or reach end-of-file, whichever comes first */
546 while (len)
547 /* skip over whatever is in output buffer */
548 if (state->have) {
549 n = (uint64_t)state->have > len ?
550 (unsigned)len : state->have;
551 state->have -= n;
552 state->next += n;
553 state->pos += n;
554 len -= n;
555 }
556
557 /* output buffer empty -- return if we're at the end of the input */
558 else if (state->eof && state->strm.avail_in == 0)
559 break;
560
561 /* need more data to skip -- load up output buffer */
562 else {
563 /* get more output, looking for header if required */
564 if (xz_make(state) == -1)
565 return -1;
566 }
567 return 0;
568}
569
570int xzread(xzFile file, void *buf, unsigned len)
571{
572 unsigned got, n;
573 xz_statep state;
574 lzma_stream *strm;
575
576 /* get internal structure */
577 if (file == NULL)
578 return -1;
579 state = (xz_statep)file;
580 strm = &(state->strm);
581
582 /* check that we're reading and that there's no error */
583 if (state->err != LZMA_OK)
584 return -1;
585
586 /* since an int is returned, make sure len fits in one, otherwise return
587 with an error (this avoids the flaw in the interface) */
588 if ((int)len < 0) {
589 xz_error(state, LZMA_BUF_ERROR, "requested length does not fit in int");
590 return -1;
591 }
592
593 /* if len is zero, avoid unnecessary operations */
594 if (len == 0)
595 return 0;
596
597 /* process a skip request */
598 if (state->seek) {
599 state->seek = 0;
600 if (xz_skip(state, state->skip) == -1)
601 return -1;
602 }
603
604 /* get len bytes to buf, or less than len if at the end */
605 got = 0;
606 do {
607 /* first just try copying data from the output buffer */
608 if (state->have) {
609 n = state->have > len ? len : state->have;
610 memcpy(buf, state->next, n);
611 state->next += n;
612 state->have -= n;
613 }
614
615 /* output buffer empty -- return if we're at the end of the input */
616 else if (state->eof && strm->avail_in == 0)
617 break;
618
619 /* need output data -- for small len or new stream load up our output
620 buffer */
621 else if (state->how == LOOK || len < (state->size << 1)) {
622 /* get more output, looking for header if required */
623 if (xz_make(state) == -1)
624 return -1;
625 continue; /* no progress yet -- go back to memcpy() above */
626 /* the copy above assures that we will leave with space in the
627 output buffer, allowing at least one gzungetc() to succeed */
628 }
629
630 /* large len -- read directly into user buffer */
631 else if (state->how == COPY) { /* read directly */
632 if (xz_load(state, buf, len, &n) == -1)
633 return -1;
634 }
635
636 /* large len -- decompress directly into user buffer */
637 else { /* state->how == LZMA */
638 strm->avail_out = len;
639 strm->next_out = buf;
640 if (xz_decomp(state) == -1)
641 return -1;
642 n = state->have;
643 state->have = 0;
644 }
645
646 /* update progress */
647 len -= n;
648 buf = (char *)buf + n;
649 got += n;
650 state->pos += n;
651 } while (len);
652
653 /* return number of bytes read into user buffer (will fit in int) */
654 return (int)got;
655}
656
657int xzclose(xzFile file)
658{
659 int ret;
660 xz_statep state;
661
662 /* get internal structure */
663 if (file == NULL)
664 return LZMA_DATA_ERROR;
665 state = (xz_statep)file;
666
667 /* free memory and close file */
668 if (state->size) {
669 lzma_end(&(state->strm));
670#ifdef HAVE_LIBZ_H
671 inflateEnd(&(state->zstrm));
672#endif
673 free(state->out);
674 free(state->in);
675 }
676 free(state->path);
677 ret = close(state->fd);
678 free(state);
679 return ret ? ret : LZMA_OK;
680}
681