]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_read.c
Merge r183430 from vendor/top/dist to head/contrib/top, although with
[FreeBSD/FreeBSD.git] / lib / 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$");
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 #define minimum(a, b) (a < b ? a : b)
57
58 static int      build_stream(struct archive_read *);
59 static int      choose_format(struct archive_read *);
60 static struct archive_vtable *archive_read_vtable(void);
61 static int      _archive_read_close(struct archive *);
62 static int      _archive_read_finish(struct archive *);
63
64 static struct archive_vtable *
65 archive_read_vtable(void)
66 {
67         static struct archive_vtable av;
68         static int inited = 0;
69
70         if (!inited) {
71                 av.archive_finish = _archive_read_finish;
72                 av.archive_close = _archive_read_close;
73         }
74         return (&av);
75 }
76
77 /*
78  * Allocate, initialize and return a struct archive object.
79  */
80 struct archive *
81 archive_read_new(void)
82 {
83         struct archive_read *a;
84
85         a = (struct archive_read *)malloc(sizeof(*a));
86         if (a == NULL)
87                 return (NULL);
88         memset(a, 0, sizeof(*a));
89         a->archive.magic = ARCHIVE_READ_MAGIC;
90
91         a->archive.state = ARCHIVE_STATE_NEW;
92         a->entry = archive_entry_new();
93         a->archive.vtable = archive_read_vtable();
94
95         return (&a->archive);
96 }
97
98 /*
99  * Record the do-not-extract-to file. This belongs in archive_read_extract.c.
100  */
101 void
102 archive_read_extract_set_skip_file(struct archive *_a, dev_t d, ino_t i)
103 {
104         struct archive_read *a = (struct archive_read *)_a;
105         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY,
106             "archive_read_extract_set_skip_file");
107         a->skip_file_dev = d;
108         a->skip_file_ino = i;
109 }
110
111 /*
112  * Set read options for the format.
113  */
114 int
115 archive_read_set_format_options(struct archive *_a, const char *s)
116 {
117         struct archive_read *a;
118         struct archive_format_descriptor *format;
119         char key[64], val[64];
120         size_t i;
121         int len, r;
122
123         a = (struct archive_read *)_a;
124         len = 0;
125         for (i = 0; i < sizeof(a->formats)/sizeof(a->formats[0]); i++) {
126                 format = &a->formats[i];
127                 if (format == NULL || format->options == NULL ||
128                     format->name == NULL)
129                         /* This format does not support option. */
130                         continue;
131
132                 while ((len = __archive_parse_options(s, format->name,
133                     sizeof(key), key, sizeof(val), val)) > 0) {
134                         if (val[0] == '\0')
135                                 r = format->options(a, key, NULL);
136                         else
137                                 r = format->options(a, key, val);
138                         if (r == ARCHIVE_FATAL)
139                                 return (r);
140                         s += len;
141                 }
142         }
143         if (len < 0) {
144                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
145                     "Illegal format options.");
146                 return (ARCHIVE_WARN);
147         }
148         return (ARCHIVE_OK);
149 }
150
151 /*
152  * Set read options for the filter.
153  */
154 int
155 archive_read_set_filter_options(struct archive *_a, const char *s)
156 {
157         struct archive_read *a;
158         struct archive_read_filter *filter;
159         struct archive_read_filter_bidder *bidder;
160         char key[64], val[64];
161         int len, r;
162
163         a = (struct archive_read *)_a;
164         filter = a->filter;
165         len = 0;
166         for (filter = a->filter; filter != NULL; filter = filter->upstream) {
167                 bidder = filter->bidder;
168                 if (bidder == NULL)
169                         continue;
170                 if (bidder->options == NULL)
171                         /* This bidder does not support option */
172                         continue;
173                 while ((len = __archive_parse_options(s, filter->name,
174                     sizeof(key), key, sizeof(val), val)) > 0) {
175                         if (val[0] == '\0')
176                                 r = bidder->options(bidder, key, NULL);
177                         else
178                                 r = bidder->options(bidder, key, val);
179                         if (r == ARCHIVE_FATAL)
180                                 return (r);
181                         s += len;
182                 }
183         }
184         if (len < 0) {
185                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
186                     "Illegal format options.");
187                 return (ARCHIVE_WARN);
188         }
189         return (ARCHIVE_OK);
190 }
191
192 /*
193  * Set read options for the format and the filter.
194  */
195 int
196 archive_read_set_options(struct archive *_a, const char *s)
197 {
198         int r;
199
200         r = archive_read_set_format_options(_a, s);
201         if (r != ARCHIVE_OK)
202                 return (r);
203         r = archive_read_set_filter_options(_a, s);
204         if (r != ARCHIVE_OK)
205                 return (r);
206         return (ARCHIVE_OK);
207 }
208
209 /*
210  * Open the archive
211  */
212 int
213 archive_read_open(struct archive *a, void *client_data,
214     archive_open_callback *client_opener, archive_read_callback *client_reader,
215     archive_close_callback *client_closer)
216 {
217         /* Old archive_read_open() is just a thin shell around
218          * archive_read_open2. */
219         return archive_read_open2(a, client_data, client_opener,
220             client_reader, NULL, client_closer);
221 }
222
223 static ssize_t
224 client_read_proxy(struct archive_read_filter *self, const void **buff)
225 {
226         ssize_t r;
227         r = (self->archive->client.reader)(&self->archive->archive,
228             self->data, buff);
229         self->archive->archive.raw_position += r;
230         return (r);
231 }
232
233 static int64_t
234 client_skip_proxy(struct archive_read_filter *self, int64_t request)
235 {
236         int64_t r;
237         if (self->archive->client.skipper == NULL)
238                 return (0);
239         r = (self->archive->client.skipper)(&self->archive->archive,
240             self->data, request);
241         self->archive->archive.raw_position += r;
242         return (r);
243 }
244
245 static int
246 client_close_proxy(struct archive_read_filter *self)
247 {
248         int r = ARCHIVE_OK;
249
250         if (self->archive->client.closer != NULL)
251                 r = (self->archive->client.closer)((struct archive *)self->archive,
252                     self->data);
253         self->data = NULL;
254         return (r);
255 }
256
257
258 int
259 archive_read_open2(struct archive *_a, void *client_data,
260     archive_open_callback *client_opener,
261     archive_read_callback *client_reader,
262     archive_skip_callback *client_skipper,
263     archive_close_callback *client_closer)
264 {
265         struct archive_read *a = (struct archive_read *)_a;
266         struct archive_read_filter *filter;
267         int e;
268
269         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
270             "archive_read_open");
271
272         if (client_reader == NULL)
273                 __archive_errx(1,
274                     "No reader function provided to archive_read_open");
275
276         /* Open data source. */
277         if (client_opener != NULL) {
278                 e =(client_opener)(&a->archive, client_data);
279                 if (e != 0) {
280                         /* If the open failed, call the closer to clean up. */
281                         if (client_closer)
282                                 (client_closer)(&a->archive, client_data);
283                         return (e);
284                 }
285         }
286
287         /* Save the client functions and mock up the initial source. */
288         a->client.reader = client_reader;
289         a->client.skipper = client_skipper;
290         a->client.closer = client_closer;
291
292         filter = calloc(1, sizeof(*filter));
293         if (filter == NULL)
294                 return (ARCHIVE_FATAL);
295         filter->bidder = NULL;
296         filter->upstream = NULL;
297         filter->archive = a;
298         filter->data = client_data;
299         filter->read = client_read_proxy;
300         filter->skip = client_skip_proxy;
301         filter->close = client_close_proxy;
302         filter->name = "none";
303         filter->code = ARCHIVE_COMPRESSION_NONE;
304         a->filter = filter;
305
306         /* Build out the input pipeline. */
307         e = build_stream(a);
308         if (e == ARCHIVE_OK)
309                 a->archive.state = ARCHIVE_STATE_HEADER;
310
311         return (e);
312 }
313
314 /*
315  * Allow each registered stream transform to bid on whether
316  * it wants to handle this stream.  Repeat until we've finished
317  * building the pipeline.
318  */
319 static int
320 build_stream(struct archive_read *a)
321 {
322         int number_bidders, i, bid, best_bid;
323         struct archive_read_filter_bidder *bidder, *best_bidder;
324         struct archive_read_filter *filter;
325         int r;
326
327         for (;;) {
328                 number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);
329
330                 best_bid = 0;
331                 best_bidder = NULL;
332
333                 bidder = a->bidders;
334                 for (i = 0; i < number_bidders; i++, bidder++) {
335                         if (bidder->bid != NULL) {
336                                 bid = (bidder->bid)(bidder, a->filter);
337                                 if (bid > best_bid) {
338                                         best_bid = bid;
339                                         best_bidder = bidder;
340                                 }
341                         }
342                 }
343
344                 /* If no bidder, we're done. */
345                 if (best_bidder == NULL) {
346                         a->archive.compression_name = a->filter->name;
347                         a->archive.compression_code = a->filter->code;
348                         return (ARCHIVE_OK);
349                 }
350
351                 filter
352                     = (struct archive_read_filter *)calloc(1, sizeof(*filter));
353                 if (filter == NULL)
354                         return (ARCHIVE_FATAL);
355                 filter->bidder = best_bidder;
356                 filter->archive = a;
357                 filter->upstream = a->filter;
358                 r = (best_bidder->init)(filter);
359                 if (r != ARCHIVE_OK) {
360                         free(filter);
361                         return (r);
362                 }
363                 a->filter = filter;
364         }
365 }
366
367 /*
368  * Read header of next entry.
369  */
370 int
371 archive_read_next_header(struct archive *_a, struct archive_entry **entryp)
372 {
373         struct archive_read *a = (struct archive_read *)_a;
374         struct archive_entry *entry;
375         int slot, ret;
376
377         __archive_check_magic(_a, ARCHIVE_READ_MAGIC,
378             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
379             "archive_read_next_header");
380
381         *entryp = NULL;
382         entry = a->entry;
383         archive_entry_clear(entry);
384         archive_clear_error(&a->archive);
385
386         /*
387          * If no format has yet been chosen, choose one.
388          */
389         if (a->format == NULL) {
390                 slot = choose_format(a);
391                 if (slot < 0) {
392                         a->archive.state = ARCHIVE_STATE_FATAL;
393                         return (ARCHIVE_FATAL);
394                 }
395                 a->format = &(a->formats[slot]);
396         }
397
398         /*
399          * If client didn't consume entire data, skip any remainder
400          * (This is especially important for GNU incremental directories.)
401          */
402         if (a->archive.state == ARCHIVE_STATE_DATA) {
403                 ret = archive_read_data_skip(&a->archive);
404                 if (ret == ARCHIVE_EOF) {
405                         archive_set_error(&a->archive, EIO, "Premature end-of-file.");
406                         a->archive.state = ARCHIVE_STATE_FATAL;
407                         return (ARCHIVE_FATAL);
408                 }
409                 if (ret != ARCHIVE_OK)
410                         return (ret);
411         }
412
413         /* Record start-of-header. */
414         a->header_position = a->archive.file_position;
415
416         ret = (a->format->read_header)(a, entry);
417
418         /*
419          * EOF and FATAL are persistent at this layer.  By
420          * modifying the state, we guarantee that future calls to
421          * read a header or read data will fail.
422          */
423         switch (ret) {
424         case ARCHIVE_EOF:
425                 a->archive.state = ARCHIVE_STATE_EOF;
426                 break;
427         case ARCHIVE_OK:
428                 a->archive.state = ARCHIVE_STATE_DATA;
429                 break;
430         case ARCHIVE_WARN:
431                 a->archive.state = ARCHIVE_STATE_DATA;
432                 break;
433         case ARCHIVE_RETRY:
434                 break;
435         case ARCHIVE_FATAL:
436                 a->archive.state = ARCHIVE_STATE_FATAL;
437                 break;
438         }
439
440         *entryp = entry;
441         a->read_data_output_offset = 0;
442         a->read_data_remaining = 0;
443         return (ret);
444 }
445
446 /*
447  * Allow each registered format to bid on whether it wants to handle
448  * the next entry.  Return index of winning bidder.
449  */
450 static int
451 choose_format(struct archive_read *a)
452 {
453         int slots;
454         int i;
455         int bid, best_bid;
456         int best_bid_slot;
457
458         slots = sizeof(a->formats) / sizeof(a->formats[0]);
459         best_bid = -1;
460         best_bid_slot = -1;
461
462         /* Set up a->format and a->pformat_data for convenience of bidders. */
463         a->format = &(a->formats[0]);
464         for (i = 0; i < slots; i++, a->format++) {
465                 if (a->format->bid) {
466                         bid = (a->format->bid)(a);
467                         if (bid == ARCHIVE_FATAL)
468                                 return (ARCHIVE_FATAL);
469                         if ((bid > best_bid) || (best_bid_slot < 0)) {
470                                 best_bid = bid;
471                                 best_bid_slot = i;
472                         }
473                 }
474         }
475
476         /*
477          * There were no bidders; this is a serious programmer error
478          * and demands a quick and definitive abort.
479          */
480         if (best_bid_slot < 0)
481                 __archive_errx(1, "No formats were registered; you must "
482                     "invoke at least one archive_read_support_format_XXX "
483                     "function in order to successfully read an archive.");
484
485         /*
486          * There were bidders, but no non-zero bids; this means we
487          * can't support this stream.
488          */
489         if (best_bid < 1) {
490                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
491                     "Unrecognized archive format");
492                 return (ARCHIVE_FATAL);
493         }
494
495         return (best_bid_slot);
496 }
497
498 /*
499  * Return the file offset (within the uncompressed data stream) where
500  * the last header started.
501  */
502 int64_t
503 archive_read_header_position(struct archive *_a)
504 {
505         struct archive_read *a = (struct archive_read *)_a;
506         __archive_check_magic(_a, ARCHIVE_READ_MAGIC,
507             ARCHIVE_STATE_ANY, "archive_read_header_position");
508         return (a->header_position);
509 }
510
511 /*
512  * Read data from an archive entry, using a read(2)-style interface.
513  * This is a convenience routine that just calls
514  * archive_read_data_block and copies the results into the client
515  * buffer, filling any gaps with zero bytes.  Clients using this
516  * API can be completely ignorant of sparse-file issues; sparse files
517  * will simply be padded with nulls.
518  *
519  * DO NOT intermingle calls to this function and archive_read_data_block
520  * to read a single entry body.
521  */
522 ssize_t
523 archive_read_data(struct archive *_a, void *buff, size_t s)
524 {
525         struct archive_read *a = (struct archive_read *)_a;
526         char    *dest;
527         const void *read_buf;
528         size_t   bytes_read;
529         size_t   len;
530         int      r;
531
532         bytes_read = 0;
533         dest = (char *)buff;
534
535         while (s > 0) {
536                 if (a->read_data_remaining == 0) {
537                         read_buf = a->read_data_block;
538                         r = archive_read_data_block(&a->archive, &read_buf,
539                             &a->read_data_remaining, &a->read_data_offset);
540                         a->read_data_block = read_buf;
541                         if (r == ARCHIVE_EOF)
542                                 return (bytes_read);
543                         /*
544                          * Error codes are all negative, so the status
545                          * return here cannot be confused with a valid
546                          * byte count.  (ARCHIVE_OK is zero.)
547                          */
548                         if (r < ARCHIVE_OK)
549                                 return (r);
550                 }
551
552                 if (a->read_data_offset < a->read_data_output_offset) {
553                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
554                             "Encountered out-of-order sparse blocks");
555                         return (ARCHIVE_RETRY);
556                 }
557
558                 /* Compute the amount of zero padding needed. */
559                 if (a->read_data_output_offset + (off_t)s <
560                     a->read_data_offset) {
561                         len = s;
562                 } else if (a->read_data_output_offset <
563                     a->read_data_offset) {
564                         len = a->read_data_offset -
565                             a->read_data_output_offset;
566                 } else
567                         len = 0;
568
569                 /* Add zeroes. */
570                 memset(dest, 0, len);
571                 s -= len;
572                 a->read_data_output_offset += len;
573                 dest += len;
574                 bytes_read += len;
575
576                 /* Copy data if there is any space left. */
577                 if (s > 0) {
578                         len = a->read_data_remaining;
579                         if (len > s)
580                                 len = s;
581                         memcpy(dest, a->read_data_block, len);
582                         s -= len;
583                         a->read_data_block += len;
584                         a->read_data_remaining -= len;
585                         a->read_data_output_offset += len;
586                         a->read_data_offset += len;
587                         dest += len;
588                         bytes_read += len;
589                 }
590         }
591         return (bytes_read);
592 }
593
594 #if ARCHIVE_API_VERSION < 3
595 /*
596  * Obsolete function provided for compatibility only.  Note that the API
597  * of this function doesn't allow the caller to detect if the remaining
598  * data from the archive entry is shorter than the buffer provided, or
599  * even if an error occurred while reading data.
600  */
601 int
602 archive_read_data_into_buffer(struct archive *a, void *d, ssize_t len)
603 {
604
605         archive_read_data(a, d, len);
606         return (ARCHIVE_OK);
607 }
608 #endif
609
610 /*
611  * Skip over all remaining data in this entry.
612  */
613 int
614 archive_read_data_skip(struct archive *_a)
615 {
616         struct archive_read *a = (struct archive_read *)_a;
617         int r;
618         const void *buff;
619         size_t size;
620         off_t offset;
621
622         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
623             "archive_read_data_skip");
624
625         if (a->format->read_data_skip != NULL)
626                 r = (a->format->read_data_skip)(a);
627         else {
628                 while ((r = archive_read_data_block(&a->archive,
629                             &buff, &size, &offset))
630                     == ARCHIVE_OK)
631                         ;
632         }
633
634         if (r == ARCHIVE_EOF)
635                 r = ARCHIVE_OK;
636
637         a->archive.state = ARCHIVE_STATE_HEADER;
638         return (r);
639 }
640
641 /*
642  * Read the next block of entry data from the archive.
643  * This is a zero-copy interface; the client receives a pointer,
644  * size, and file offset of the next available block of data.
645  *
646  * Returns ARCHIVE_OK if the operation is successful, ARCHIVE_EOF if
647  * the end of entry is encountered.
648  */
649 int
650 archive_read_data_block(struct archive *_a,
651     const void **buff, size_t *size, off_t *offset)
652 {
653         struct archive_read *a = (struct archive_read *)_a;
654         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
655             "archive_read_data_block");
656
657         if (a->format->read_data == NULL) {
658                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
659                     "Internal error: "
660                     "No format_read_data_block function registered");
661                 return (ARCHIVE_FATAL);
662         }
663
664         return (a->format->read_data)(a, buff, size, offset);
665 }
666
667 /*
668  * Close the file and release most resources.
669  *
670  * Be careful: client might just call read_new and then read_finish.
671  * Don't assume we actually read anything or performed any non-trivial
672  * initialization.
673  */
674 static int
675 _archive_read_close(struct archive *_a)
676 {
677         struct archive_read *a = (struct archive_read *)_a;
678         int r = ARCHIVE_OK, r1 = ARCHIVE_OK;
679         size_t i, n;
680
681         __archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC,
682             ARCHIVE_STATE_ANY, "archive_read_close");
683         a->archive.state = ARCHIVE_STATE_CLOSED;
684
685         /* Call cleanup functions registered by optional components. */
686         if (a->cleanup_archive_extract != NULL)
687                 r = (a->cleanup_archive_extract)(a);
688
689         /* TODO: Clean up the formatters. */
690
691         /* Clean up the filter pipeline. */
692         while (a->filter != NULL) {
693                 struct archive_read_filter *t = a->filter->upstream;
694                 if (a->filter->close != NULL) {
695                         r1 = (a->filter->close)(a->filter);
696                         if (r1 < r)
697                                 r = r1;
698                 }
699                 free(a->filter->buffer);
700                 free(a->filter);
701                 a->filter = t;
702         }
703
704         /* Release the bidder objects. */
705         n = sizeof(a->bidders)/sizeof(a->bidders[0]);
706         for (i = 0; i < n; i++) {
707                 if (a->bidders[i].free != NULL) {
708                         r1 = (a->bidders[i].free)(&a->bidders[i]);
709                         if (r1 < r)
710                                 r = r1;
711                 }
712         }
713
714         return (r);
715 }
716
717 /*
718  * Release memory and other resources.
719  */
720 int
721 _archive_read_finish(struct archive *_a)
722 {
723         struct archive_read *a = (struct archive_read *)_a;
724         int i;
725         int slots;
726         int r = ARCHIVE_OK;
727
728         __archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_ANY,
729             "archive_read_finish");
730         if (a->archive.state != ARCHIVE_STATE_CLOSED)
731                 r = archive_read_close(&a->archive);
732
733         /* Cleanup format-specific data. */
734         slots = sizeof(a->formats) / sizeof(a->formats[0]);
735         for (i = 0; i < slots; i++) {
736                 a->format = &(a->formats[i]);
737                 if (a->formats[i].cleanup)
738                         (a->formats[i].cleanup)(a);
739         }
740
741         archive_string_free(&a->archive.error_string);
742         if (a->entry)
743                 archive_entry_free(a->entry);
744         a->archive.magic = 0;
745         free(a);
746 #if ARCHIVE_API_VERSION > 1
747         return (r);
748 #endif
749 }
750
751 /*
752  * Used internally by read format handlers to register their bid and
753  * initialization functions.
754  */
755 int
756 __archive_read_register_format(struct archive_read *a,
757     void *format_data,
758     const char *name,
759     int (*bid)(struct archive_read *),
760     int (*options)(struct archive_read *, const char *, const char *),
761     int (*read_header)(struct archive_read *, struct archive_entry *),
762     int (*read_data)(struct archive_read *, const void **, size_t *, off_t *),
763     int (*read_data_skip)(struct archive_read *),
764     int (*cleanup)(struct archive_read *))
765 {
766         int i, number_slots;
767
768         __archive_check_magic(&a->archive,
769             ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
770             "__archive_read_register_format");
771
772         number_slots = sizeof(a->formats) / sizeof(a->formats[0]);
773
774         for (i = 0; i < number_slots; i++) {
775                 if (a->formats[i].bid == bid)
776                         return (ARCHIVE_WARN); /* We've already installed */
777                 if (a->formats[i].bid == NULL) {
778                         a->formats[i].bid = bid;
779                         a->formats[i].options = options;
780                         a->formats[i].read_header = read_header;
781                         a->formats[i].read_data = read_data;
782                         a->formats[i].read_data_skip = read_data_skip;
783                         a->formats[i].cleanup = cleanup;
784                         a->formats[i].data = format_data;
785                         a->formats[i].name = name;
786                         return (ARCHIVE_OK);
787                 }
788         }
789
790         __archive_errx(1, "Not enough slots for format registration");
791         return (ARCHIVE_FATAL); /* Never actually called. */
792 }
793
794 /*
795  * Used internally by decompression routines to register their bid and
796  * initialization functions.
797  */
798 struct archive_read_filter_bidder *
799 __archive_read_get_bidder(struct archive_read *a)
800 {
801         int i, number_slots;
802
803         __archive_check_magic(&a->archive,
804             ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
805             "__archive_read_get_bidder");
806
807         number_slots = sizeof(a->bidders) / sizeof(a->bidders[0]);
808
809         for (i = 0; i < number_slots; i++) {
810                 if (a->bidders[i].bid == NULL) {
811                         memset(a->bidders + i, 0, sizeof(a->bidders[0]));
812                         return (a->bidders + i);
813                 }
814         }
815
816         __archive_errx(1, "Not enough slots for compression registration");
817         return (NULL); /* Never actually executed. */
818 }
819
820 /*
821  * The next three functions comprise the peek/consume internal I/O
822  * system used by archive format readers.  This system allows fairly
823  * flexible read-ahead and allows the I/O code to operate in a
824  * zero-copy manner most of the time.
825  *
826  * In the ideal case, filters generate blocks of data
827  * and __archive_read_ahead() just returns pointers directly into
828  * those blocks.  Then __archive_read_consume() just bumps those
829  * pointers.  Only if your request would span blocks does the I/O
830  * layer use a copy buffer to provide you with a contiguous block of
831  * data.  The __archive_read_skip() is an optimization; it scans ahead
832  * very quickly (it usually translates into a seek() operation if
833  * you're reading uncompressed disk files).
834  *
835  * A couple of useful idioms:
836  *  * "I just want some data."  Ask for 1 byte and pay attention to
837  *    the "number of bytes available" from __archive_read_ahead().
838  *    You can consume more than you asked for; you just can't consume
839  *    more than is available.  If you consume everything that's
840  *    immediately available, the next read_ahead() call will pull
841  *    the next block.
842  *  * "I want to output a large block of data."  As above, ask for 1 byte,
843  *    emit all that's available (up to whatever limit you have), then
844  *    repeat until you're done.
845  *  * "I want to peek ahead by a large amount."  Ask for 4k or so, then
846  *    double and repeat until you get an error or have enough.  Note
847  *    that the I/O layer will likely end up expanding its copy buffer
848  *    to fit your request, so use this technique cautiously.  This
849  *    technique is used, for example, by some of the format tasting
850  *    code that has uncertain look-ahead needs.
851  *
852  * TODO: Someday, provide a more generic __archive_read_seek() for
853  * those cases where it's useful.  This is tricky because there are lots
854  * of cases where seek() is not available (reading gzip data from a
855  * network socket, for instance), so there needs to be a good way to
856  * communicate whether seek() is available and users of that interface
857  * need to use non-seeking strategies whenever seek() is not available.
858  */
859
860 /*
861  * Looks ahead in the input stream:
862  *  * If 'avail' pointer is provided, that returns number of bytes available
863  *    in the current buffer, which may be much larger than requested.
864  *  * If end-of-file, *avail gets set to zero.
865  *  * If error, *avail gets error code.
866  *  * If request can be met, returns pointer to data, returns NULL
867  *    if request is not met.
868  *
869  * Note: If you just want "some data", ask for 1 byte and pay attention
870  * to *avail, which will have the actual amount available.  If you
871  * know exactly how many bytes you need, just ask for that and treat
872  * a NULL return as an error.
873  *
874  * Important:  This does NOT move the file pointer.  See
875  * __archive_read_consume() below.
876  */
877
878 /*
879  * This is tricky.  We need to provide our clients with pointers to
880  * contiguous blocks of memory but we want to avoid copying whenever
881  * possible.
882  *
883  * Mostly, this code returns pointers directly into the block of data
884  * provided by the client_read routine.  It can do this unless the
885  * request would split across blocks.  In that case, we have to copy
886  * into an internal buffer to combine reads.
887  */
888 const void *
889 __archive_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
890 {
891         return (__archive_read_filter_ahead(a->filter, min, avail));
892 }
893
894 const void *
895 __archive_read_filter_ahead(struct archive_read_filter *filter,
896     size_t min, ssize_t *avail)
897 {
898         ssize_t bytes_read;
899         size_t tocopy;
900
901         if (filter->fatal) {
902                 if (avail)
903                         *avail = ARCHIVE_FATAL;
904                 return (NULL);
905         }
906
907         /*
908          * Keep pulling more data until we can satisfy the request.
909          */
910         for (;;) {
911
912                 /*
913                  * If we can satisfy from the copy buffer, we're done.
914                  */
915                 if (filter->avail >= min) {
916                         if (avail != NULL)
917                                 *avail = filter->avail;
918                         return (filter->next);
919                 }
920
921                 /*
922                  * We can satisfy directly from client buffer if everything
923                  * currently in the copy buffer is still in the client buffer.
924                  */
925                 if (filter->client_total >= filter->client_avail + filter->avail
926                     && filter->client_avail + filter->avail >= min) {
927                         /* "Roll back" to client buffer. */
928                         filter->client_avail += filter->avail;
929                         filter->client_next -= filter->avail;
930                         /* Copy buffer is now empty. */
931                         filter->avail = 0;
932                         filter->next = filter->buffer;
933                         /* Return data from client buffer. */
934                         if (avail != NULL)
935                                 *avail = filter->client_avail;
936                         return (filter->client_next);
937                 }
938
939                 /* Move data forward in copy buffer if necessary. */
940                 if (filter->next > filter->buffer &&
941                     filter->next + min > filter->buffer + filter->buffer_size) {
942                         if (filter->avail > 0)
943                                 memmove(filter->buffer, filter->next, filter->avail);
944                         filter->next = filter->buffer;
945                 }
946
947                 /* If we've used up the client data, get more. */
948                 if (filter->client_avail <= 0) {
949                         if (filter->end_of_file) {
950                                 if (avail != NULL)
951                                         *avail = 0;
952                                 return (NULL);
953                         }
954                         bytes_read = (filter->read)(filter,
955                             &filter->client_buff);
956                         if (bytes_read < 0) {           /* Read error. */
957                                 filter->client_total = filter->client_avail = 0;
958                                 filter->client_next = filter->client_buff = NULL;
959                                 filter->fatal = 1;
960                                 if (avail != NULL)
961                                         *avail = ARCHIVE_FATAL;
962                                 return (NULL);
963                         }
964                         if (bytes_read == 0) {  /* Premature end-of-file. */
965                                 filter->client_total = filter->client_avail = 0;
966                                 filter->client_next = filter->client_buff = NULL;
967                                 filter->end_of_file = 1;
968                                 /* Return whatever we do have. */
969                                 if (avail != NULL)
970                                         *avail = filter->avail;
971                                 return (NULL);
972                         }
973                         filter->position += bytes_read;
974                         filter->client_total = bytes_read;
975                         filter->client_avail = filter->client_total;
976                         filter->client_next = filter->client_buff;
977                 }
978                 else
979                 {
980                         /*
981                          * We can't satisfy the request from the copy
982                          * buffer or the existing client data, so we
983                          * need to copy more client data over to the
984                          * copy buffer.
985                          */
986
987                         /* Ensure the buffer is big enough. */
988                         if (min > filter->buffer_size) {
989                                 size_t s, t;
990                                 char *p;
991
992                                 /* Double the buffer; watch for overflow. */
993                                 s = t = filter->buffer_size;
994                                 if (s == 0)
995                                         s = min;
996                                 while (s < min) {
997                                         t *= 2;
998                                         if (t <= s) { /* Integer overflow! */
999                                                 archive_set_error(
1000                                                         &filter->archive->archive,
1001                                                         ENOMEM,
1002                                                     "Unable to allocate copy buffer");
1003                                                 filter->fatal = 1;
1004                                                 if (avail != NULL)
1005                                                         *avail = ARCHIVE_FATAL;
1006                                                 return (NULL);
1007                                         }
1008                                         s = t;
1009                                 }
1010                                 /* Now s >= min, so allocate a new buffer. */
1011                                 p = (char *)malloc(s);
1012                                 if (p == NULL) {
1013                                         archive_set_error(
1014                                                 &filter->archive->archive,
1015                                                 ENOMEM,
1016                                             "Unable to allocate copy buffer");
1017                                         filter->fatal = 1;
1018                                         if (avail != NULL)
1019                                                 *avail = ARCHIVE_FATAL;
1020                                         return (NULL);
1021                                 }
1022                                 /* Move data into newly-enlarged buffer. */
1023                                 if (filter->avail > 0)
1024                                         memmove(p, filter->next, filter->avail);
1025                                 free(filter->buffer);
1026                                 filter->next = filter->buffer = p;
1027                                 filter->buffer_size = s;
1028                         }
1029
1030                         /* We can add client data to copy buffer. */
1031                         /* First estimate: copy to fill rest of buffer. */
1032                         tocopy = (filter->buffer + filter->buffer_size)
1033                             - (filter->next + filter->avail);
1034                         /* Don't waste time buffering more than we need to. */
1035                         if (tocopy + filter->avail > min)
1036                                 tocopy = min - filter->avail;
1037                         /* Don't copy more than is available. */
1038                         if (tocopy > filter->client_avail)
1039                                 tocopy = filter->client_avail;
1040
1041                         memcpy(filter->next + filter->avail, filter->client_next,
1042                             tocopy);
1043                         /* Remove this data from client buffer. */
1044                         filter->client_next += tocopy;
1045                         filter->client_avail -= tocopy;
1046                         /* add it to copy buffer. */
1047                         filter->avail += tocopy;
1048                 }
1049         }
1050 }
1051
1052 /*
1053  * Move the file pointer forward.  This should be called after
1054  * __archive_read_ahead() returns data to you.  Don't try to move
1055  * ahead by more than the amount of data available according to
1056  * __archive_read_ahead().
1057  */
1058 /*
1059  * Mark the appropriate data as used.  Note that the request here will
1060  * often be much smaller than the size of the previous read_ahead
1061  * request.
1062  */
1063 ssize_t
1064 __archive_read_consume(struct archive_read *a, size_t request)
1065 {
1066         ssize_t r;
1067         r = __archive_read_filter_consume(a->filter, request);
1068         a->archive.file_position += r;
1069         return (r);
1070 }
1071
1072 ssize_t
1073 __archive_read_filter_consume(struct archive_read_filter * filter,
1074     size_t request)
1075 {
1076         if (filter->avail > 0) {
1077                 /* Read came from copy buffer. */
1078                 filter->next += request;
1079                 filter->avail -= request;
1080         } else {
1081                 /* Read came from client buffer. */
1082                 filter->client_next += request;
1083                 filter->client_avail -= request;
1084         }
1085         return (request);
1086 }
1087
1088 /*
1089  * Move the file pointer ahead by an arbitrary amount.  If you're
1090  * reading uncompressed data from a disk file, this will actually
1091  * translate into a seek() operation.  Even in cases where seek()
1092  * isn't feasible, this at least pushes the read-and-discard loop
1093  * down closer to the data source.
1094  */
1095 int64_t
1096 __archive_read_skip(struct archive_read *a, int64_t request)
1097 {
1098         return (__archive_read_filter_skip(a->filter, request));
1099 }
1100
1101 int64_t
1102 __archive_read_filter_skip(struct archive_read_filter *filter, int64_t request)
1103 {
1104         off_t bytes_skipped, total_bytes_skipped = 0;
1105         size_t min;
1106
1107         if (filter->fatal)
1108                 return (-1);
1109         /*
1110          * If there is data in the buffers already, use that first.
1111          */
1112         if (filter->avail > 0) {
1113                 min = minimum(request, (off_t)filter->avail);
1114                 bytes_skipped = __archive_read_consume(filter->archive, min);
1115                 request -= bytes_skipped;
1116                 total_bytes_skipped += bytes_skipped;
1117         }
1118         if (filter->client_avail > 0) {
1119                 min = minimum(request, (off_t)filter->client_avail);
1120                 bytes_skipped = __archive_read_consume(filter->archive, min);
1121                 request -= bytes_skipped;
1122                 total_bytes_skipped += bytes_skipped;
1123         }
1124         if (request == 0)
1125                 return (total_bytes_skipped);
1126         /*
1127          * If a client_skipper was provided, try that first.
1128          */
1129 #if ARCHIVE_API_VERSION < 2
1130         if ((filter->skip != NULL) && (request < SSIZE_MAX)) {
1131 #else
1132         if (filter->skip != NULL) {
1133 #endif
1134                 bytes_skipped = (filter->skip)(filter, request);
1135                 if (bytes_skipped < 0) {        /* error */
1136                         filter->client_total = filter->client_avail = 0;
1137                         filter->client_next = filter->client_buff = NULL;
1138                         filter->fatal = 1;
1139                         return (bytes_skipped);
1140                 }
1141                 filter->archive->archive.file_position += bytes_skipped;
1142                 total_bytes_skipped += bytes_skipped;
1143                 request -= bytes_skipped;
1144                 filter->client_next = filter->client_buff;
1145                 filter->client_avail = filter->client_total = 0;
1146         }
1147         /*
1148          * Note that client_skipper will usually not satisfy the
1149          * full request (due to low-level blocking concerns),
1150          * so even if client_skipper is provided, we may still
1151          * have to use ordinary reads to finish out the request.
1152          */
1153         while (request > 0) {
1154                 const void* dummy_buffer;
1155                 ssize_t bytes_read;
1156                 dummy_buffer = __archive_read_ahead(filter->archive,
1157                     1, &bytes_read);
1158                 if (bytes_read < 0)
1159                         return (bytes_read);
1160                 if (bytes_read == 0) {
1161                         /* We hit EOF before we satisfied the skip request. */
1162                         archive_set_error(&filter->archive->archive,
1163                             ARCHIVE_ERRNO_MISC,
1164                             "Truncated input file (need to skip %jd bytes)",
1165                             (intmax_t)request);
1166                         return (ARCHIVE_FATAL);
1167                 }
1168                 min = (size_t)(minimum(bytes_read, request));
1169                 bytes_read = __archive_read_consume(filter->archive, min);
1170                 total_bytes_skipped += bytes_read;
1171                 request -= bytes_read;
1172         }
1173         return (total_bytes_skipped);
1174 }