Merge from vendor branch LIBARCHIVE:
[dragonfly.git] / contrib / libarchive-2.0 / libarchive / archive_read.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
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
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 /*
27  * This file contains the "essential" portions of the read API, that
28  * is, stuff that will probably always be used by any client that
29  * actually needs to read an archive.  Optional pieces have been, as
30  * far as possible, separated out into separate files to avoid
31  * needlessly bloating statically-linked clients.
32  */
33
34 #include "archive_platform.h"
35 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read.c,v 1.30 2007/03/03 07:37:36 kientzle Exp $");
36
37 #ifdef HAVE_ERRNO_H
38 #include <errno.h>
39 #endif
40 #include <stdio.h>
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #ifdef HAVE_STRING_H
45 #include <string.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #include "archive.h"
52 #include "archive_entry.h"
53 #include "archive_private.h"
54 #include "archive_read_private.h"
55
56 static int      choose_decompressor(struct archive_read *, const void*, size_t);
57 static int      choose_format(struct archive_read *);
58
59 /*
60  * Allocate, initialize and return a struct archive object.
61  */
62 struct archive *
63 archive_read_new(void)
64 {
65         struct archive_read *a;
66         unsigned char   *nulls;
67
68         a = (struct archive_read *)malloc(sizeof(*a));
69         if (a == NULL)
70                 return (NULL);
71         memset(a, 0, sizeof(*a));
72         a->archive.magic = ARCHIVE_READ_MAGIC;
73         a->bytes_per_block = ARCHIVE_DEFAULT_BYTES_PER_BLOCK;
74
75         a->null_length = 1024;
76         nulls = (unsigned char *)malloc(a->null_length);
77         if (nulls == NULL) {
78                 archive_set_error(&a->archive, ENOMEM,
79                     "Can't allocate archive object 'nulls' element");
80                 free(a);
81                 return (NULL);
82         }
83         memset(nulls, 0, a->null_length);
84         a->nulls = nulls;
85
86         a->archive.state = ARCHIVE_STATE_NEW;
87         a->entry = archive_entry_new();
88
89         /* We always support uncompressed archives. */
90         archive_read_support_compression_none(&a->archive);
91
92         return (&a->archive);
93 }
94
95 /*
96  * Record the do-not-extract-to file. This belongs in archive_read_extract.c.
97  */
98 void
99 archive_read_extract_set_skip_file(struct archive *_a, dev_t d, ino_t i)
100 {
101         struct archive_read *a = (struct archive_read *)_a;
102         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY,
103             "archive_read_extract_set_skip_file");
104         a->skip_file_dev = d;
105         a->skip_file_ino = i;
106 }
107
108
109 /*
110  * Open the archive
111  */
112 int
113 archive_read_open(struct archive *a, void *client_data,
114     archive_open_callback *client_opener, archive_read_callback *client_reader,
115     archive_close_callback *client_closer)
116 {
117         /* Old archive_read_open() is just a thin shell around
118          * archive_read_open2. */
119         return archive_read_open2(a, client_data, client_opener,
120             client_reader, NULL, client_closer);
121 }
122
123 int
124 archive_read_open2(struct archive *_a, void *client_data,
125     archive_open_callback *client_opener,
126     archive_read_callback *client_reader,
127     archive_skip_callback *client_skipper,
128     archive_close_callback *client_closer)
129 {
130         struct archive_read *a = (struct archive_read *)_a;
131         const void *buffer;
132         ssize_t bytes_read;
133         int high_bidder;
134         int e;
135
136         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_open");
137
138         if (client_reader == NULL)
139                 __archive_errx(1,
140                     "No reader function provided to archive_read_open");
141
142         /*
143          * Set these NULL initially.  If the open or initial read fails,
144          * we'll leave them NULL to indicate that the file is invalid.
145          * (In particular, this helps ensure that the closer doesn't
146          * get called more than once.)
147          */
148         a->client_opener = NULL;
149         a->client_reader = NULL;
150         a->client_skipper = NULL;
151         a->client_closer = NULL;
152         a->client_data = NULL;
153
154         /* Open data source. */
155         if (client_opener != NULL) {
156                 e =(client_opener)(&a->archive, client_data);
157                 if (e != 0) {
158                         /* If the open failed, call the closer to clean up. */
159                         if (client_closer)
160                                 (client_closer)(&a->archive, client_data);
161                         return (e);
162                 }
163         }
164
165         /* Read first block now for format detection. */
166         bytes_read = (client_reader)(&a->archive, client_data, &buffer);
167
168         if (bytes_read < 0) {
169                 /* If the first read fails, close before returning error. */
170                 if (client_closer)
171                         (client_closer)(&a->archive, client_data);
172                 /* client_reader should have already set error information. */
173                 return (ARCHIVE_FATAL);
174         }
175
176         /* Now that the client callbacks have worked, remember them. */
177         a->client_opener = client_opener; /* Do we need to remember this? */
178         a->client_reader = client_reader;
179         a->client_skipper = client_skipper;
180         a->client_closer = client_closer;
181         a->client_data = client_data;
182
183         /* Select a decompression routine. */
184         high_bidder = choose_decompressor(a, buffer, bytes_read);
185         if (high_bidder < 0)
186                 return (ARCHIVE_FATAL);
187
188         /* Initialize decompression routine with the first block of data. */
189         e = (a->decompressors[high_bidder].init)(a, buffer, bytes_read);
190
191         if (e == ARCHIVE_OK)
192                 a->archive.state = ARCHIVE_STATE_HEADER;
193
194         return (e);
195 }
196
197 /*
198  * Allow each registered decompression routine to bid on whether it
199  * wants to handle this stream.  Return index of winning bidder.
200  */
201 static int
202 choose_decompressor(struct archive_read *a,
203     const void *buffer, size_t bytes_read)
204 {
205         int decompression_slots, i, bid, best_bid, best_bid_slot;
206
207         decompression_slots = sizeof(a->decompressors) /
208             sizeof(a->decompressors[0]);
209
210         best_bid = -1;
211         best_bid_slot = -1;
212
213         for (i = 0; i < decompression_slots; i++) {
214                 if (a->decompressors[i].bid) {
215                         bid = (a->decompressors[i].bid)(buffer, bytes_read);
216                         if ((bid > best_bid) || (best_bid_slot < 0)) {
217                                 best_bid = bid;
218                                 best_bid_slot = i;
219                         }
220                 }
221         }
222
223         /*
224          * There were no bidders; this is a serious programmer error
225          * and demands a quick and definitive abort.
226          */
227         if (best_bid_slot < 0)
228                 __archive_errx(1, "No decompressors were registered; you "
229                     "must call at least one "
230                     "archive_read_support_compression_XXX function in order "
231                     "to successfully read an archive.");
232
233         /*
234          * There were bidders, but no non-zero bids; this means we  can't
235          * support this stream.
236          */
237         if (best_bid < 1) {
238                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
239                     "Unrecognized archive format");
240                 return (ARCHIVE_FATAL);
241         }
242
243         return (best_bid_slot);
244 }
245
246 /*
247  * Read header of next entry.
248  */
249 int
250 archive_read_next_header(struct archive *_a, struct archive_entry **entryp)
251 {
252         struct archive_read *a = (struct archive_read *)_a;
253         struct archive_entry *entry;
254         int slot, ret;
255
256         __archive_check_magic(_a, ARCHIVE_READ_MAGIC,
257             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
258             "archive_read_next_header");
259
260         *entryp = NULL;
261         entry = a->entry;
262         archive_entry_clear(entry);
263         archive_clear_error(&a->archive);
264
265         /*
266          * If client didn't consume entire data, skip any remainder
267          * (This is especially important for GNU incremental directories.)
268          */
269         if (a->archive.state == ARCHIVE_STATE_DATA) {
270                 ret = archive_read_data_skip(&a->archive);
271                 if (ret == ARCHIVE_EOF) {
272                         archive_set_error(&a->archive, EIO, "Premature end-of-file.");
273                         a->archive.state = ARCHIVE_STATE_FATAL;
274                         return (ARCHIVE_FATAL);
275                 }
276                 if (ret != ARCHIVE_OK)
277                         return (ret);
278         }
279
280         /* Record start-of-header. */
281         a->header_position = a->archive.file_position;
282
283         slot = choose_format(a);
284         if (slot < 0) {
285                 a->archive.state = ARCHIVE_STATE_FATAL;
286                 return (ARCHIVE_FATAL);
287         }
288         a->format = &(a->formats[slot]);
289         a->pformat_data = &(a->format->format_data);
290         ret = (a->format->read_header)(a, entry);
291
292         /*
293          * EOF and FATAL are persistent at this layer.  By
294          * modifying the state, we guarantee that future calls to
295          * read a header or read data will fail.
296          */
297         switch (ret) {
298         case ARCHIVE_EOF:
299                 a->archive.state = ARCHIVE_STATE_EOF;
300                 break;
301         case ARCHIVE_OK:
302                 a->archive.state = ARCHIVE_STATE_DATA;
303                 break;
304         case ARCHIVE_WARN:
305                 a->archive.state = ARCHIVE_STATE_DATA;
306                 break;
307         case ARCHIVE_RETRY:
308                 break;
309         case ARCHIVE_FATAL:
310                 a->archive.state = ARCHIVE_STATE_FATAL;
311                 break;
312         }
313
314         *entryp = entry;
315         a->read_data_output_offset = 0;
316         a->read_data_remaining = 0;
317         return (ret);
318 }
319
320 /*
321  * Allow each registered format to bid on whether it wants to handle
322  * the next entry.  Return index of winning bidder.
323  */
324 static int
325 choose_format(struct archive_read *a)
326 {
327         int slots;
328         int i;
329         int bid, best_bid;
330         int best_bid_slot;
331
332         slots = sizeof(a->formats) / sizeof(a->formats[0]);
333         best_bid = -1;
334         best_bid_slot = -1;
335
336         /* Set up a->format and a->pformat_data for convenience of bidders. */
337         a->format = &(a->formats[0]);
338         for (i = 0; i < slots; i++, a->format++) {
339                 if (a->format->bid) {
340                         a->pformat_data = &(a->format->format_data);
341                         bid = (a->format->bid)(a);
342                         if (bid == ARCHIVE_FATAL)
343                                 return (ARCHIVE_FATAL);
344                         if ((bid > best_bid) || (best_bid_slot < 0)) {
345                                 best_bid = bid;
346                                 best_bid_slot = i;
347                         }
348                 }
349         }
350
351         /*
352          * There were no bidders; this is a serious programmer error
353          * and demands a quick and definitive abort.
354          */
355         if (best_bid_slot < 0)
356                 __archive_errx(1, "No formats were registered; you must "
357                     "invoke at least one archive_read_support_format_XXX "
358                     "function in order to successfully read an archive.");
359
360         /*
361          * There were bidders, but no non-zero bids; this means we
362          * can't support this stream.
363          */
364         if (best_bid < 1) {
365                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
366                     "Unrecognized archive format");
367                 return (ARCHIVE_FATAL);
368         }
369
370         return (best_bid_slot);
371 }
372
373 /*
374  * Return the file offset (within the uncompressed data stream) where
375  * the last header started.
376  */
377 int64_t
378 archive_read_header_position(struct archive *_a)
379 {
380         struct archive_read *a = (struct archive_read *)_a;
381         __archive_check_magic(_a, ARCHIVE_READ_MAGIC,
382             ARCHIVE_STATE_ANY, "archive_read_header_position");
383         return (a->header_position);
384 }
385
386 /*
387  * Read data from an archive entry, using a read(2)-style interface.
388  * This is a convenience routine that just calls
389  * archive_read_data_block and copies the results into the client
390  * buffer, filling any gaps with zero bytes.  Clients using this
391  * API can be completely ignorant of sparse-file issues; sparse files
392  * will simply be padded with nulls.
393  *
394  * DO NOT intermingle calls to this function and archive_read_data_block
395  * to read a single entry body.
396  */
397 ssize_t
398 archive_read_data(struct archive *_a, void *buff, size_t s)
399 {
400         struct archive_read *a = (struct archive_read *)_a;
401         char    *dest;
402         size_t   bytes_read;
403         size_t   len;
404         int      r;
405
406         bytes_read = 0;
407         dest = (char *)buff;
408
409         while (s > 0) {
410                 if (a->read_data_remaining <= 0) {
411                         r = archive_read_data_block(&a->archive,
412                             (const void **)&a->read_data_block,
413                             &a->read_data_remaining,
414                             &a->read_data_offset);
415                         if (r == ARCHIVE_EOF)
416                                 return (bytes_read);
417                         /*
418                          * Error codes are all negative, so the status
419                          * return here cannot be confused with a valid
420                          * byte count.  (ARCHIVE_OK is zero.)
421                          */
422                         if (r < ARCHIVE_OK)
423                                 return (r);
424                 }
425
426                 if (a->read_data_offset < a->read_data_output_offset) {
427                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
428                             "Encountered out-of-order sparse blocks");
429                         return (ARCHIVE_RETRY);
430                 }
431
432                 /* Compute the amount of zero padding needed. */
433                 if (a->read_data_output_offset + (off_t)s <
434                     a->read_data_offset) {
435                         len = s;
436                 } else if (a->read_data_output_offset <
437                     a->read_data_offset) {
438                         len = a->read_data_offset -
439                             a->read_data_output_offset;
440                 } else
441                         len = 0;
442
443                 /* Add zeroes. */
444                 memset(dest, 0, len);
445                 s -= len;
446                 a->read_data_output_offset += len;
447                 dest += len;
448                 bytes_read += len;
449
450                 /* Copy data if there is any space left. */
451                 if (s > 0) {
452                         len = a->read_data_remaining;
453                         if (len > s)
454                                 len = s;
455                         memcpy(dest, a->read_data_block, len);
456                         s -= len;
457                         a->read_data_block += len;
458                         a->read_data_remaining -= len;
459                         a->read_data_output_offset += len;
460                         a->read_data_offset += len;
461                         dest += len;
462                         bytes_read += len;
463                 }
464         }
465         return (bytes_read);
466 }
467
468 /*
469  * Skip over all remaining data in this entry.
470  */
471 int
472 archive_read_data_skip(struct archive *_a)
473 {
474         struct archive_read *a = (struct archive_read *)_a;
475         int r;
476         const void *buff;
477         size_t size;
478         off_t offset;
479
480         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
481             "archive_read_data_skip");
482
483         if (a->format->read_data_skip != NULL)
484                 r = (a->format->read_data_skip)(a);
485         else {
486                 while ((r = archive_read_data_block(&a->archive,
487                             &buff, &size, &offset))
488                     == ARCHIVE_OK)
489                         ;
490         }
491
492         if (r == ARCHIVE_EOF)
493                 r = ARCHIVE_OK;
494
495         a->archive.state = ARCHIVE_STATE_HEADER;
496         return (r);
497 }
498
499 /*
500  * Read the next block of entry data from the archive.
501  * This is a zero-copy interface; the client receives a pointer,
502  * size, and file offset of the next available block of data.
503  *
504  * Returns ARCHIVE_OK if the operation is successful, ARCHIVE_EOF if
505  * the end of entry is encountered.
506  */
507 int
508 archive_read_data_block(struct archive *_a,
509     const void **buff, size_t *size, off_t *offset)
510 {
511         struct archive_read *a = (struct archive_read *)_a;
512         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
513             "archive_read_data_block");
514
515         if (a->format->read_data == NULL) {
516                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
517                     "Internal error: "
518                     "No format_read_data_block function registered");
519                 return (ARCHIVE_FATAL);
520         }
521
522         return (a->format->read_data)(a, buff, size, offset);
523 }
524
525 /*
526  * Close the file and release most resources.
527  *
528  * Be careful: client might just call read_new and then read_finish.
529  * Don't assume we actually read anything or performed any non-trivial
530  * initialization.
531  */
532 int
533 archive_read_close(struct archive *_a)
534 {
535         struct archive_read *a = (struct archive_read *)_a;
536         int r = ARCHIVE_OK, r1 = ARCHIVE_OK;
537
538         __archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC,
539             ARCHIVE_STATE_ANY, "archive_read_close");
540         a->archive.state = ARCHIVE_STATE_CLOSED;
541
542         /* Call cleanup functions registered by optional components. */
543         if (a->cleanup_archive_extract != NULL)
544                 r = (a->cleanup_archive_extract)(a);
545
546         /* TODO: Finish the format processing. */
547
548         /* Close the input machinery. */
549         if (a->compression_finish != NULL) {
550                 r1 = (a->compression_finish)(a);
551                 if (r1 < r)
552                         r = r1;
553         }
554
555         return (r);
556 }
557
558 /*
559  * Release memory and other resources.
560  */
561 #if ARCHIVE_API_VERSION > 1
562 int
563 #else
564 /* Temporarily allow library to compile with either 1.x or 2.0 API. */
565 void
566 #endif
567 archive_read_finish(struct archive *_a)
568 {
569         struct archive_read *a = (struct archive_read *)_a;
570         int i;
571         int slots;
572         int r = ARCHIVE_OK;
573
574         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY,
575             "archive_read_finish");
576         if (a->archive.state != ARCHIVE_STATE_CLOSED)
577                 r = archive_read_close(&a->archive);
578
579         /* Cleanup format-specific data. */
580         slots = sizeof(a->formats) / sizeof(a->formats[0]);
581         for (i = 0; i < slots; i++) {
582                 a->pformat_data = &(a->formats[i].format_data);
583                 if (a->formats[i].cleanup)
584                         (a->formats[i].cleanup)(a);
585         }
586
587         /* Casting a pointer to int allows us to remove 'const.' */
588         free((void *)(uintptr_t)(const void *)a->nulls);
589         archive_string_free(&a->archive.error_string);
590         if (a->entry)
591                 archive_entry_free(a->entry);
592         a->archive.magic = 0;
593         free(a);
594 #if ARCHIVE_API_VERSION > 1
595         return (r);
596 #endif
597 }
598
599 /*
600  * Used internally by read format handlers to register their bid and
601  * initialization functions.
602  */
603 int
604 __archive_read_register_format(struct archive_read *a,
605     void *format_data,
606     int (*bid)(struct archive_read *),
607     int (*read_header)(struct archive_read *, struct archive_entry *),
608     int (*read_data)(struct archive_read *, const void **, size_t *, off_t *),
609     int (*read_data_skip)(struct archive_read *),
610     int (*cleanup)(struct archive_read *))
611 {
612         int i, number_slots;
613
614         __archive_check_magic(&a->archive,
615             ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
616             "__archive_read_register_format");
617
618         number_slots = sizeof(a->formats) / sizeof(a->formats[0]);
619
620         for (i = 0; i < number_slots; i++) {
621                 if (a->formats[i].bid == bid)
622                         return (ARCHIVE_WARN); /* We've already installed */
623                 if (a->formats[i].bid == NULL) {
624                         a->formats[i].bid = bid;
625                         a->formats[i].read_header = read_header;
626                         a->formats[i].read_data = read_data;
627                         a->formats[i].read_data_skip = read_data_skip;
628                         a->formats[i].cleanup = cleanup;
629                         a->formats[i].format_data = format_data;
630                         return (ARCHIVE_OK);
631                 }
632         }
633
634         __archive_errx(1, "Not enough slots for format registration");
635         return (ARCHIVE_FATAL); /* Never actually called. */
636 }
637
638 /*
639  * Used internally by decompression routines to register their bid and
640  * initialization functions.
641  */
642 int
643 __archive_read_register_compression(struct archive_read *a,
644     int (*bid)(const void *, size_t),
645     int (*init)(struct archive_read *, const void *, size_t))
646 {
647         int i, number_slots;
648
649         __archive_check_magic(&a->archive,
650             ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
651             "__archive_read_register_compression");
652
653         number_slots = sizeof(a->decompressors) / sizeof(a->decompressors[0]);
654
655         for (i = 0; i < number_slots; i++) {
656                 if (a->decompressors[i].bid == bid)
657                         return (ARCHIVE_OK); /* We've already installed */
658                 if (a->decompressors[i].bid == NULL) {
659                         a->decompressors[i].bid = bid;
660                         a->decompressors[i].init = init;
661                         return (ARCHIVE_OK);
662                 }
663         }
664
665         __archive_errx(1, "Not enough slots for compression registration");
666         return (ARCHIVE_FATAL); /* Never actually executed. */
667 }