1 /*-
2  * Copyright (c) 2003-2011 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: head/lib/libarchive/archive_read.c 201157 2009-12-29 05:30:23Z kientzle $");
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	choose_filters(struct archive_read *);
59 static int	choose_format(struct archive_read *);
60 static void	free_filters(struct archive_read *);
61 static int	close_filters(struct archive_read *);
62 static struct archive_vtable *archive_read_vtable(void);
63 static int64_t	_archive_filter_bytes(struct archive *, int);
64 static int	_archive_filter_code(struct archive *, int);
65 static const char *_archive_filter_name(struct archive *, int);
66 static int  _archive_filter_count(struct archive *);
67 static int	_archive_read_close(struct archive *);
68 static int	_archive_read_data_block(struct archive *,
69 		    const void **, size_t *, int64_t *);
70 static int	_archive_read_free(struct archive *);
71 static int	_archive_read_next_header(struct archive *,
72 		    struct archive_entry **);
73 static int	_archive_read_next_header2(struct archive *,
74 		    struct archive_entry *);
75 static int64_t  advance_file_pointer(struct archive_read_filter *, int64_t);
76 
77 static struct archive_vtable *
78 archive_read_vtable(void)
79 {
80 	static struct archive_vtable av;
81 	static int inited = 0;
82 
83 	if (!inited) {
84 		av.archive_filter_bytes = _archive_filter_bytes;
85 		av.archive_filter_code = _archive_filter_code;
86 		av.archive_filter_name = _archive_filter_name;
87 		av.archive_filter_count = _archive_filter_count;
88 		av.archive_read_data_block = _archive_read_data_block;
89 		av.archive_read_next_header = _archive_read_next_header;
90 		av.archive_read_next_header2 = _archive_read_next_header2;
91 		av.archive_free = _archive_read_free;
92 		av.archive_close = _archive_read_close;
93 		inited = 1;
94 	}
95 	return (&av);
96 }
97 
98 /*
99  * Allocate, initialize and return a struct archive object.
100  */
101 struct archive *
102 archive_read_new(void)
103 {
104 	struct archive_read *a;
105 
106 	a = (struct archive_read *)malloc(sizeof(*a));
107 	if (a == NULL)
108 		return (NULL);
109 	memset(a, 0, sizeof(*a));
110 	a->archive.magic = ARCHIVE_READ_MAGIC;
111 
112 	a->archive.state = ARCHIVE_STATE_NEW;
113 	a->entry = archive_entry_new2(&a->archive);
114 	a->archive.vtable = archive_read_vtable();
115 
116 	return (&a->archive);
117 }
118 
119 /*
120  * Record the do-not-extract-to file. This belongs in archive_read_extract.c.
121  */
122 void
123 archive_read_extract_set_skip_file(struct archive *_a, int64_t d, int64_t i)
124 {
125 	struct archive_read *a = (struct archive_read *)_a;
126 
127 	if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_MAGIC,
128 		ARCHIVE_STATE_ANY, "archive_read_extract_set_skip_file"))
129 		return;
130 	a->skip_file_set = 1;
131 	a->skip_file_dev = d;
132 	a->skip_file_ino = i;
133 }
134 
135 /*
136  * Open the archive
137  */
138 int
139 archive_read_open(struct archive *a, void *client_data,
140     archive_open_callback *client_opener, archive_read_callback *client_reader,
141     archive_close_callback *client_closer)
142 {
143 	/* Old archive_read_open() is just a thin shell around
144 	 * archive_read_open1. */
145 	archive_read_set_open_callback(a, client_opener);
146 	archive_read_set_read_callback(a, client_reader);
147 	archive_read_set_close_callback(a, client_closer);
148 	archive_read_set_callback_data(a, client_data);
149 	return archive_read_open1(a);
150 }
151 
152 
153 int
154 archive_read_open2(struct archive *a, void *client_data,
155     archive_open_callback *client_opener,
156     archive_read_callback *client_reader,
157     archive_skip_callback *client_skipper,
158     archive_close_callback *client_closer)
159 {
160 	/* Old archive_read_open2() is just a thin shell around
161 	 * archive_read_open1. */
162 	archive_read_set_callback_data(a, client_data);
163 	archive_read_set_open_callback(a, client_opener);
164 	archive_read_set_read_callback(a, client_reader);
165 	archive_read_set_skip_callback(a, client_skipper);
166 	archive_read_set_close_callback(a, client_closer);
167 	return archive_read_open1(a);
168 }
169 
170 static ssize_t
171 client_read_proxy(struct archive_read_filter *self, const void **buff)
172 {
173 	ssize_t r;
174 	r = (self->archive->client.reader)(&self->archive->archive,
175 	    self->data, buff);
176 	return (r);
177 }
178 
179 static int64_t
180 client_skip_proxy(struct archive_read_filter *self, int64_t request)
181 {
182 	if (request < 0)
183 		__archive_errx(1, "Negative skip requested.");
184 	if (request == 0)
185 		return 0;
186 
187 	if (self->archive->client.skipper != NULL) {
188 		/* Seek requests over 1GiB are broken down into
189 		 * multiple seeks.  This avoids overflows when the
190 		 * requests get passed through 32-bit arguments. */
191 		int64_t skip_limit = (int64_t)1 << 30;
192 		int64_t total = 0;
193 		for (;;) {
194 			int64_t get, ask = request;
195 			if (ask > skip_limit)
196 				ask = skip_limit;
197 			get = (self->archive->client.skipper)(&self->archive->archive,
198 			    self->data, ask);
199 			if (get == 0)
200 				return (total);
201 			request -= get;
202 			total += get;
203 		}
204 	} else if (self->archive->client.seeker != NULL
205 		&& request > 64 * 1024) {
206 		/* If the client provided a seeker but not a skipper,
207 		 * we can use the seeker to skip forward.
208 		 *
209 		 * Note: This isn't always a good idea.  The client
210 		 * skipper is allowed to skip by less than requested
211 		 * if it needs to maintain block alignment.  The
212 		 * seeker is not allowed to play such games, so using
213 		 * the seeker here may be a performance loss compared
214 		 * to just reading and discarding.  That's why we
215 		 * only do this for skips of over 64k.
216 		 */
217 		int64_t before = self->position;
218 		int64_t after = (self->archive->client.seeker)(&self->archive->archive,
219 		    self->data, request, SEEK_CUR);
220 		if (after != before + request)
221 			return ARCHIVE_FATAL;
222 		return after - before;
223 	}
224 	return 0;
225 }
226 
227 static int64_t
228 client_seek_proxy(struct archive_read_filter *self, int64_t offset, int whence)
229 {
230 	/* DO NOT use the skipper here!  If we transparently handled
231 	 * forward seek here by using the skipper, that will break
232 	 * other libarchive code that assumes a successful forward
233 	 * seek means it can also seek backwards.
234 	 */
235 	if (self->archive->client.seeker == NULL)
236 		return (ARCHIVE_FAILED);
237 	return (self->archive->client.seeker)(&self->archive->archive,
238 	    self->data, offset, whence);
239 }
240 
241 static int
242 client_close_proxy(struct archive_read_filter *self)
243 {
244 	int r = ARCHIVE_OK;
245 
246 	if (self->archive->client.closer != NULL)
247 		r = (self->archive->client.closer)((struct archive *)self->archive,
248 		    self->data);
249 	return (r);
250 }
251 
252 int
253 archive_read_set_open_callback(struct archive *_a,
254     archive_open_callback *client_opener)
255 {
256 	struct archive_read *a = (struct archive_read *)_a;
257 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
258 	    "archive_read_set_open_callback");
259 	a->client.opener = client_opener;
260 	return ARCHIVE_OK;
261 }
262 
263 int
264 archive_read_set_read_callback(struct archive *_a,
265     archive_read_callback *client_reader)
266 {
267 	struct archive_read *a = (struct archive_read *)_a;
268 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
269 	    "archive_read_set_read_callback");
270 	a->client.reader = client_reader;
271 	return ARCHIVE_OK;
272 }
273 
274 int
275 archive_read_set_skip_callback(struct archive *_a,
276     archive_skip_callback *client_skipper)
277 {
278 	struct archive_read *a = (struct archive_read *)_a;
279 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
280 	    "archive_read_set_skip_callback");
281 	a->client.skipper = client_skipper;
282 	return ARCHIVE_OK;
283 }
284 
285 int
286 archive_read_set_seek_callback(struct archive *_a,
287     archive_seek_callback *client_seeker)
288 {
289 	struct archive_read *a = (struct archive_read *)_a;
290 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
291 	    "archive_read_set_seek_callback");
292 	a->client.seeker = client_seeker;
293 	return ARCHIVE_OK;
294 }
295 
296 int
297 archive_read_set_close_callback(struct archive *_a,
298     archive_close_callback *client_closer)
299 {
300 	struct archive_read *a = (struct archive_read *)_a;
301 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
302 	    "archive_read_set_close_callback");
303 	a->client.closer = client_closer;
304 	return ARCHIVE_OK;
305 }
306 
307 int
308 archive_read_set_callback_data(struct archive *_a, void *client_data)
309 {
310 	struct archive_read *a = (struct archive_read *)_a;
311 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
312 	    "archive_read_set_callback_data");
313 	a->client.data = client_data;
314 	return ARCHIVE_OK;
315 }
316 
317 int
318 archive_read_open1(struct archive *_a)
319 {
320 	struct archive_read *a = (struct archive_read *)_a;
321 	struct archive_read_filter *filter;
322 	int slot, e;
323 
324 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
325 	    "archive_read_open");
326 	archive_clear_error(&a->archive);
327 
328 	if (a->client.reader == NULL) {
329 		archive_set_error(&a->archive, EINVAL,
330 		    "No reader function provided to archive_read_open");
331 		a->archive.state = ARCHIVE_STATE_FATAL;
332 		return (ARCHIVE_FATAL);
333 	}
334 
335 	/* Open data source. */
336 	if (a->client.opener != NULL) {
337 		e =(a->client.opener)(&a->archive, a->client.data);
338 		if (e != 0) {
339 			/* If the open failed, call the closer to clean up. */
340 			if (a->client.closer)
341 				(a->client.closer)(&a->archive, a->client.data);
342 			return (e);
343 		}
344 	}
345 
346 	filter = calloc(1, sizeof(*filter));
347 	if (filter == NULL)
348 		return (ARCHIVE_FATAL);
349 	filter->bidder = NULL;
350 	filter->upstream = NULL;
351 	filter->archive = a;
352 	filter->data = a->client.data;
353 	filter->read = client_read_proxy;
354 	filter->skip = client_skip_proxy;
355 	filter->seek = client_seek_proxy;
356 	filter->close = client_close_proxy;
357 	filter->name = "none";
358 	filter->code = ARCHIVE_COMPRESSION_NONE;
359 	a->filter = filter;
360 
361 	/* Build out the input pipeline. */
362 	e = choose_filters(a);
363 	if (e < ARCHIVE_WARN) {
364 		a->archive.state = ARCHIVE_STATE_FATAL;
365 		return (ARCHIVE_FATAL);
366 	}
367 
368 	slot = choose_format(a);
369 	if (slot < 0) {
370 		close_filters(a);
371 		a->archive.state = ARCHIVE_STATE_FATAL;
372 		return (ARCHIVE_FATAL);
373 	}
374 	a->format = &(a->formats[slot]);
375 
376 	a->archive.state = ARCHIVE_STATE_HEADER;
377 	return (e);
378 }
379 
380 /*
381  * Allow each registered stream transform to bid on whether
382  * it wants to handle this stream.  Repeat until we've finished
383  * building the pipeline.
384  */
385 static int
386 choose_filters(struct archive_read *a)
387 {
388 	int number_bidders, i, bid, best_bid;
389 	struct archive_read_filter_bidder *bidder, *best_bidder;
390 	struct archive_read_filter *filter;
391 	ssize_t avail;
392 	int r;
393 
394 	for (;;) {
395 		number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);
396 
397 		best_bid = 0;
398 		best_bidder = NULL;
399 
400 		bidder = a->bidders;
401 		for (i = 0; i < number_bidders; i++, bidder++) {
402 			if (bidder->bid != NULL) {
403 				bid = (bidder->bid)(bidder, a->filter);
404 				if (bid > best_bid) {
405 					best_bid = bid;
406 					best_bidder = bidder;
407 				}
408 			}
409 		}
410 
411 		/* If no bidder, we're done. */
412 		if (best_bidder == NULL) {
413 			/* Verify the filter by asking it for some data. */
414 			__archive_read_filter_ahead(a->filter, 1, &avail);
415 			if (avail < 0) {
416 				close_filters(a);
417 				free_filters(a);
418 				return (ARCHIVE_FATAL);
419 			}
420 			a->archive.compression_name = a->filter->name;
421 			a->archive.compression_code = a->filter->code;
422 			return (ARCHIVE_OK);
423 		}
424 
425 		filter
426 		    = (struct archive_read_filter *)calloc(1, sizeof(*filter));
427 		if (filter == NULL)
428 			return (ARCHIVE_FATAL);
429 		filter->bidder = best_bidder;
430 		filter->archive = a;
431 		filter->upstream = a->filter;
432 		a->filter = filter;
433 		r = (best_bidder->init)(a->filter);
434 		if (r != ARCHIVE_OK) {
435 			close_filters(a);
436 			free_filters(a);
437 			return (ARCHIVE_FATAL);
438 		}
439 	}
440 }
441 
442 /*
443  * Read header of next entry.
444  */
445 static int
446 _archive_read_next_header2(struct archive *_a, struct archive_entry *entry)
447 {
448 	struct archive_read *a = (struct archive_read *)_a;
449 	int r1 = ARCHIVE_OK, r2;
450 
451 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
452 	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
453 	    "archive_read_next_header");
454 
455 	archive_entry_clear(entry);
456 	archive_clear_error(&a->archive);
457 
458 	/*
459 	 * If client didn't consume entire data, skip any remainder
460 	 * (This is especially important for GNU incremental directories.)
461 	 */
462 	if (a->archive.state == ARCHIVE_STATE_DATA) {
463 		r1 = archive_read_data_skip(&a->archive);
464 		if (r1 == ARCHIVE_EOF)
465 			archive_set_error(&a->archive, EIO,
466 			    "Premature end-of-file.");
467 		if (r1 == ARCHIVE_EOF || r1 == ARCHIVE_FATAL) {
468 			a->archive.state = ARCHIVE_STATE_FATAL;
469 			return (ARCHIVE_FATAL);
470 		}
471 	}
472 
473 	/* Record start-of-header offset in uncompressed stream. */
474 	a->header_position = a->filter->position;
475 
476 	++_a->file_count;
477 	r2 = (a->format->read_header)(a, entry);
478 
479 	/*
480 	 * EOF and FATAL are persistent at this layer.  By
481 	 * modifying the state, we guarantee that future calls to
482 	 * read a header or read data will fail.
483 	 */
484 	switch (r2) {
485 	case ARCHIVE_EOF:
486 		a->archive.state = ARCHIVE_STATE_EOF;
487 		--_a->file_count;/* Revert a file counter. */
488 		break;
489 	case ARCHIVE_OK:
490 		a->archive.state = ARCHIVE_STATE_DATA;
491 		break;
492 	case ARCHIVE_WARN:
493 		a->archive.state = ARCHIVE_STATE_DATA;
494 		break;
495 	case ARCHIVE_RETRY:
496 		break;
497 	case ARCHIVE_FATAL:
498 		a->archive.state = ARCHIVE_STATE_FATAL;
499 		break;
500 	}
501 
502 	a->read_data_output_offset = 0;
503 	a->read_data_remaining = 0;
504 	/* EOF always wins; otherwise return the worst error. */
505 	return (r2 < r1 || r2 == ARCHIVE_EOF) ? r2 : r1;
506 }
507 
508 int
509 _archive_read_next_header(struct archive *_a, struct archive_entry **entryp)
510 {
511 	int ret;
512 	struct archive_read *a = (struct archive_read *)_a;
513 	*entryp = NULL;
514 	ret = _archive_read_next_header2(_a, a->entry);
515 	*entryp = a->entry;
516 	return ret;
517 }
518 
519 /*
520  * Allow each registered format to bid on whether it wants to handle
521  * the next entry.  Return index of winning bidder.
522  */
523 static int
524 choose_format(struct archive_read *a)
525 {
526 	int slots;
527 	int i;
528 	int bid, best_bid;
529 	int best_bid_slot;
530 
531 	slots = sizeof(a->formats) / sizeof(a->formats[0]);
532 	best_bid = -1;
533 	best_bid_slot = -1;
534 
535 	/* Set up a->format for convenience of bidders. */
536 	a->format = &(a->formats[0]);
537 	for (i = 0; i < slots; i++, a->format++) {
538 		if (a->format->bid) {
539 			bid = (a->format->bid)(a, best_bid);
540 			if (bid == ARCHIVE_FATAL)
541 				return (ARCHIVE_FATAL);
542 			if (a->filter->position != 0)
543 				__archive_read_seek(a, 0, SEEK_SET);
544 			if ((bid > best_bid) || (best_bid_slot < 0)) {
545 				best_bid = bid;
546 				best_bid_slot = i;
547 			}
548 		}
549 	}
550 
551 	/*
552 	 * There were no bidders; this is a serious programmer error
553 	 * and demands a quick and definitive abort.
554 	 */
555 	if (best_bid_slot < 0) {
556 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
557 		    "No formats registered");
558 		return (ARCHIVE_FATAL);
559 	}
560 
561 	/*
562 	 * There were bidders, but no non-zero bids; this means we
563 	 * can't support this stream.
564 	 */
565 	if (best_bid < 1) {
566 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
567 		    "Unrecognized archive format");
568 		return (ARCHIVE_FATAL);
569 	}
570 
571 	return (best_bid_slot);
572 }
573 
574 /*
575  * Return the file offset (within the uncompressed data stream) where
576  * the last header started.
577  */
578 int64_t
579 archive_read_header_position(struct archive *_a)
580 {
581 	struct archive_read *a = (struct archive_read *)_a;
582 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
583 	    ARCHIVE_STATE_ANY, "archive_read_header_position");
584 	return (a->header_position);
585 }
586 
587 /*
588  * Read data from an archive entry, using a read(2)-style interface.
589  * This is a convenience routine that just calls
590  * archive_read_data_block and copies the results into the client
591  * buffer, filling any gaps with zero bytes.  Clients using this
592  * API can be completely ignorant of sparse-file issues; sparse files
593  * will simply be padded with nulls.
594  *
595  * DO NOT intermingle calls to this function and archive_read_data_block
596  * to read a single entry body.
597  */
598 ssize_t
599 archive_read_data(struct archive *_a, void *buff, size_t s)
600 {
601 	struct archive_read *a = (struct archive_read *)_a;
602 	char	*dest;
603 	const void *read_buf;
604 	size_t	 bytes_read;
605 	size_t	 len;
606 	int	 r;
607 
608 	bytes_read = 0;
609 	dest = (char *)buff;
610 
611 	while (s > 0) {
612 		if (a->read_data_remaining == 0) {
613 			read_buf = a->read_data_block;
614 			r = _archive_read_data_block(&a->archive, &read_buf,
615 			    &a->read_data_remaining, &a->read_data_offset);
616 			a->read_data_block = read_buf;
617 			if (r == ARCHIVE_EOF)
618 				return (bytes_read);
619 			/*
620 			 * Error codes are all negative, so the status
621 			 * return here cannot be confused with a valid
622 			 * byte count.  (ARCHIVE_OK is zero.)
623 			 */
624 			if (r < ARCHIVE_OK)
625 				return (r);
626 		}
627 
628 		if (a->read_data_offset < a->read_data_output_offset) {
629 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
630 			    "Encountered out-of-order sparse blocks");
631 			return (ARCHIVE_RETRY);
632 		}
633 
634 		/* Compute the amount of zero padding needed. */
635 		if (a->read_data_output_offset + (int64_t)s <
636 		    a->read_data_offset) {
637 			len = s;
638 		} else if (a->read_data_output_offset <
639 		    a->read_data_offset) {
640 			len = (size_t)(a->read_data_offset -
641 			    a->read_data_output_offset);
642 		} else
643 			len = 0;
644 
645 		/* Add zeroes. */
646 		memset(dest, 0, len);
647 		s -= len;
648 		a->read_data_output_offset += len;
649 		dest += len;
650 		bytes_read += len;
651 
652 		/* Copy data if there is any space left. */
653 		if (s > 0) {
654 			len = a->read_data_remaining;
655 			if (len > s)
656 				len = s;
657 			memcpy(dest, a->read_data_block, len);
658 			s -= len;
659 			a->read_data_block += len;
660 			a->read_data_remaining -= len;
661 			a->read_data_output_offset += len;
662 			a->read_data_offset += len;
663 			dest += len;
664 			bytes_read += len;
665 		}
666 	}
667 	return (bytes_read);
668 }
669 
670 /*
671  * Skip over all remaining data in this entry.
672  */
673 int
674 archive_read_data_skip(struct archive *_a)
675 {
676 	struct archive_read *a = (struct archive_read *)_a;
677 	int r;
678 	const void *buff;
679 	size_t size;
680 	int64_t offset;
681 
682 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
683 	    "archive_read_data_skip");
684 
685 	if (a->format->read_data_skip != NULL)
686 		r = (a->format->read_data_skip)(a);
687 	else {
688 		while ((r = archive_read_data_block(&a->archive,
689 			    &buff, &size, &offset))
690 		    == ARCHIVE_OK)
691 			;
692 	}
693 
694 	if (r == ARCHIVE_EOF)
695 		r = ARCHIVE_OK;
696 
697 	a->archive.state = ARCHIVE_STATE_HEADER;
698 	return (r);
699 }
700 
701 /*
702  * Read the next block of entry data from the archive.
703  * This is a zero-copy interface; the client receives a pointer,
704  * size, and file offset of the next available block of data.
705  *
706  * Returns ARCHIVE_OK if the operation is successful, ARCHIVE_EOF if
707  * the end of entry is encountered.
708  */
709 static int
710 _archive_read_data_block(struct archive *_a,
711     const void **buff, size_t *size, int64_t *offset)
712 {
713 	struct archive_read *a = (struct archive_read *)_a;
714 	archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_DATA,
715 	    "archive_read_data_block");
716 
717 	if (a->format->read_data == NULL) {
718 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
719 		    "Internal error: "
720 		    "No format_read_data_block function registered");
721 		return (ARCHIVE_FATAL);
722 	}
723 
724 	return (a->format->read_data)(a, buff, size, offset);
725 }
726 
727 static int
728 close_filters(struct archive_read *a)
729 {
730 	struct archive_read_filter *f = a->filter;
731 	int r = ARCHIVE_OK;
732 	/* Close each filter in the pipeline. */
733 	while (f != NULL) {
734 		struct archive_read_filter *t = f->upstream;
735 		if (!f->closed && f->close != NULL) {
736 			int r1 = (f->close)(f);
737 			f->closed = 1;
738 			if (r1 < r)
739 				r = r1;
740 		}
741 		free(f->buffer);
742 		f->buffer = NULL;
743 		f = t;
744 	}
745 	return r;
746 }
747 
748 static void
749 free_filters(struct archive_read *a)
750 {
751 	while (a->filter != NULL) {
752 		struct archive_read_filter *t = a->filter->upstream;
753 		free(a->filter);
754 		a->filter = t;
755 	}
756 }
757 
758 /*
759  * return the count of # of filters in use
760  */
761 static int
762 _archive_filter_count(struct archive *_a)
763 {
764 	struct archive_read *a = (struct archive_read *)_a;
765 	struct archive_read_filter *p = a->filter;
766 	int count = 0;
767 	while(p) {
768 		count++;
769 		p = p->upstream;
770 	}
771 	return count;
772 }
773 
774 /*
775  * Close the file and all I/O.
776  */
777 static int
778 _archive_read_close(struct archive *_a)
779 {
780 	struct archive_read *a = (struct archive_read *)_a;
781 	int r = ARCHIVE_OK, r1 = ARCHIVE_OK;
782 
783 	archive_check_magic(&a->archive, ARCHIVE_READ_MAGIC,
784 	    ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close");
785 	if (a->archive.state == ARCHIVE_STATE_CLOSED)
786 		return (ARCHIVE_OK);
787 	archive_clear_error(&a->archive);
788 	a->archive.state = ARCHIVE_STATE_CLOSED;
789 
790 	/* TODO: Clean up the formatters. */
791 
792 	/* Release the filter objects. */
793 	r1 = close_filters(a);
794 	if (r1 < r)
795 		r = r1;
796 
797 	return (r);
798 }
799 
800 /*
801  * Release memory and other resources.
802  */
803 static int
804 _archive_read_free(struct archive *_a)
805 {
806 	struct archive_read *a = (struct archive_read *)_a;
807 	int i, n;
808 	int slots;
809 	int r = ARCHIVE_OK;
810 
811 	if (_a == NULL)
812 		return (ARCHIVE_OK);
813 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
814 	    ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free");
815 	if (a->archive.state != ARCHIVE_STATE_CLOSED
816 	    && a->archive.state != ARCHIVE_STATE_FATAL)
817 		r = archive_read_close(&a->archive);
818 
819 	/* Call cleanup functions registered by optional components. */
820 	if (a->cleanup_archive_extract != NULL)
821 		r = (a->cleanup_archive_extract)(a);
822 
823 	/* Cleanup format-specific data. */
824 	slots = sizeof(a->formats) / sizeof(a->formats[0]);
825 	for (i = 0; i < slots; i++) {
826 		a->format = &(a->formats[i]);
827 		if (a->formats[i].cleanup)
828 			(a->formats[i].cleanup)(a);
829 	}
830 
831 	/* Free the filters */
832 	free_filters(a);
833 
834 	/* Release the bidder objects. */
835 	n = sizeof(a->bidders)/sizeof(a->bidders[0]);
836 	for (i = 0; i < n; i++) {
837 		if (a->bidders[i].free != NULL) {
838 			int r1 = (a->bidders[i].free)(&a->bidders[i]);
839 			if (r1 < r)
840 				r = r1;
841 		}
842 	}
843 
844 	archive_string_free(&a->archive.error_string);
845 	if (a->entry)
846 		archive_entry_free(a->entry);
847 	a->archive.magic = 0;
848 	__archive_clean(&a->archive);
849 	free(a);
850 	return (r);
851 }
852 
853 static struct archive_read_filter *
854 get_filter(struct archive *_a, int n)
855 {
856 	struct archive_read *a = (struct archive_read *)_a;
857 	struct archive_read_filter *f = a->filter;
858 	/* We use n == -1 for 'the last filter', which is always the client proxy. */
859 	if (n == -1 && f != NULL) {
860 		struct archive_read_filter *last = f;
861 		f = f->upstream;
862 		while (f != NULL) {
863 			last = f;
864 			f = f->upstream;
865 		}
866 		return (last);
867 	}
868 	if (n < 0)
869 		return NULL;
870 	while (n > 0 && f != NULL) {
871 		f = f->upstream;
872 		--n;
873 	}
874 	return (f);
875 }
876 
877 static int
878 _archive_filter_code(struct archive *_a, int n)
879 {
880 	struct archive_read_filter *f = get_filter(_a, n);
881 	return f == NULL ? -1 : f->code;
882 }
883 
884 static const char *
885 _archive_filter_name(struct archive *_a, int n)
886 {
887 	struct archive_read_filter *f = get_filter(_a, n);
888 	return f == NULL ? NULL : f->name;
889 }
890 
891 static int64_t
892 _archive_filter_bytes(struct archive *_a, int n)
893 {
894 	struct archive_read_filter *f = get_filter(_a, n);
895 	return f == NULL ? -1 : f->position;
896 }
897 
898 /*
899  * Used internally by read format handlers to register their bid and
900  * initialization functions.
901  */
902 int
903 __archive_read_register_format(struct archive_read *a,
904     void *format_data,
905     const char *name,
906     int (*bid)(struct archive_read *, int),
907     int (*options)(struct archive_read *, const char *, const char *),
908     int (*read_header)(struct archive_read *, struct archive_entry *),
909     int (*read_data)(struct archive_read *, const void **, size_t *, int64_t *),
910     int (*read_data_skip)(struct archive_read *),
911     int (*cleanup)(struct archive_read *))
912 {
913 	int i, number_slots;
914 
915 	archive_check_magic(&a->archive,
916 	    ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
917 	    "__archive_read_register_format");
918 
919 	number_slots = sizeof(a->formats) / sizeof(a->formats[0]);
920 
921 	for (i = 0; i < number_slots; i++) {
922 		if (a->formats[i].bid == bid)
923 			return (ARCHIVE_WARN); /* We've already installed */
924 		if (a->formats[i].bid == NULL) {
925 			a->formats[i].bid = bid;
926 			a->formats[i].options = options;
927 			a->formats[i].read_header = read_header;
928 			a->formats[i].read_data = read_data;
929 			a->formats[i].read_data_skip = read_data_skip;
930 			a->formats[i].cleanup = cleanup;
931 			a->formats[i].data = format_data;
932 			a->formats[i].name = name;
933 			return (ARCHIVE_OK);
934 		}
935 	}
936 
937 	archive_set_error(&a->archive, ENOMEM,
938 	    "Not enough slots for format registration");
939 	return (ARCHIVE_FATAL);
940 }
941 
942 /*
943  * Used internally by decompression routines to register their bid and
944  * initialization functions.
945  */
946 int
947 __archive_read_get_bidder(struct archive_read *a,
948     struct archive_read_filter_bidder **bidder)
949 {
950 	int i, number_slots;
951 
952 	number_slots = sizeof(a->bidders) / sizeof(a->bidders[0]);
953 
954 	for (i = 0; i < number_slots; i++) {
955 		if (a->bidders[i].bid == NULL) {
956 			memset(a->bidders + i, 0, sizeof(a->bidders[0]));
957 			*bidder = (a->bidders + i);
958 			return (ARCHIVE_OK);
959 		}
960 	}
961 
962 	archive_set_error(&a->archive, ENOMEM,
963 	    "Not enough slots for filter registration");
964 	return (ARCHIVE_FATAL);
965 }
966 
967 /*
968  * The next section implements the peek/consume internal I/O
969  * system used by archive readers.  This system allows simple
970  * read-ahead for consumers while preserving zero-copy operation
971  * most of the time.
972  *
973  * The two key operations:
974  *  * The read-ahead function returns a pointer to a block of data
975  *    that satisfies a minimum request.
976  *  * The consume function advances the file pointer.
977  *
978  * In the ideal case, filters generate blocks of data
979  * and __archive_read_ahead() just returns pointers directly into
980  * those blocks.  Then __archive_read_consume() just bumps those
981  * pointers.  Only if your request would span blocks does the I/O
982  * layer use a copy buffer to provide you with a contiguous block of
983  * data.
984  *
985  * A couple of useful idioms:
986  *  * "I just want some data."  Ask for 1 byte and pay attention to
987  *    the "number of bytes available" from __archive_read_ahead().
988  *    Consume whatever you actually use.
989  *  * "I want to output a large block of data."  As above, ask for 1 byte,
990  *    emit all that's available (up to whatever limit you have), consume
991  *    it all, then repeat until you're done.  This effectively means that
992  *    you're passing along the blocks that came from your provider.
993  *  * "I want to peek ahead by a large amount."  Ask for 4k or so, then
994  *    double and repeat until you get an error or have enough.  Note
995  *    that the I/O layer will likely end up expanding its copy buffer
996  *    to fit your request, so use this technique cautiously.  This
997  *    technique is used, for example, by some of the format tasting
998  *    code that has uncertain look-ahead needs.
999  */
1000 
1001 /*
1002  * Looks ahead in the input stream:
1003  *  * If 'avail' pointer is provided, that returns number of bytes available
1004  *    in the current buffer, which may be much larger than requested.
1005  *  * If end-of-file, *avail gets set to zero.
1006  *  * If error, *avail gets error code.
1007  *  * If request can be met, returns pointer to data.
1008  *  * If minimum request cannot be met, returns NULL.
1009  *
1010  * Note: If you just want "some data", ask for 1 byte and pay attention
1011  * to *avail, which will have the actual amount available.  If you
1012  * know exactly how many bytes you need, just ask for that and treat
1013  * a NULL return as an error.
1014  *
1015  * Important:  This does NOT move the file pointer.  See
1016  * __archive_read_consume() below.
1017  */
1018 const void *
1019 __archive_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
1020 {
1021 	return (__archive_read_filter_ahead(a->filter, min, avail));
1022 }
1023 
1024 const void *
1025 __archive_read_filter_ahead(struct archive_read_filter *filter,
1026     size_t min, ssize_t *avail)
1027 {
1028 	ssize_t bytes_read;
1029 	size_t tocopy;
1030 
1031 	if (filter->fatal) {
1032 		if (avail)
1033 			*avail = ARCHIVE_FATAL;
1034 		return (NULL);
1035 	}
1036 
1037 	/*
1038 	 * Keep pulling more data until we can satisfy the request.
1039 	 */
1040 	for (;;) {
1041 
1042 		/*
1043 		 * If we can satisfy from the copy buffer (and the
1044 		 * copy buffer isn't empty), we're done.  In particular,
1045 		 * note that min == 0 is a perfectly well-defined
1046 		 * request.
1047 		 */
1048 		if (filter->avail >= min && filter->avail > 0) {
1049 			if (avail != NULL)
1050 				*avail = filter->avail;
1051 			return (filter->next);
1052 		}
1053 
1054 		/*
1055 		 * We can satisfy directly from client buffer if everything
1056 		 * currently in the copy buffer is still in the client buffer.
1057 		 */
1058 		if (filter->client_total >= filter->client_avail + filter->avail
1059 		    && filter->client_avail + filter->avail >= min) {
1060 			/* "Roll back" to client buffer. */
1061 			filter->client_avail += filter->avail;
1062 			filter->client_next -= filter->avail;
1063 			/* Copy buffer is now empty. */
1064 			filter->avail = 0;
1065 			filter->next = filter->buffer;
1066 			/* Return data from client buffer. */
1067 			if (avail != NULL)
1068 				*avail = filter->client_avail;
1069 			return (filter->client_next);
1070 		}
1071 
1072 		/* Move data forward in copy buffer if necessary. */
1073 		if (filter->next > filter->buffer &&
1074 		    filter->next + min > filter->buffer + filter->buffer_size) {
1075 			if (filter->avail > 0)
1076 				memmove(filter->buffer, filter->next, filter->avail);
1077 			filter->next = filter->buffer;
1078 		}
1079 
1080 		/* If we've used up the client data, get more. */
1081 		if (filter->client_avail <= 0) {
1082 			if (filter->end_of_file) {
1083 				if (avail != NULL)
1084 					*avail = 0;
1085 				return (NULL);
1086 			}
1087 			bytes_read = (filter->read)(filter,
1088 			    &filter->client_buff);
1089 			if (bytes_read < 0) {		/* Read error. */
1090 				filter->client_total = filter->client_avail = 0;
1091 				filter->client_next = filter->client_buff = NULL;
1092 				filter->fatal = 1;
1093 				if (avail != NULL)
1094 					*avail = ARCHIVE_FATAL;
1095 				return (NULL);
1096 			}
1097 			if (bytes_read == 0) {	/* Premature end-of-file. */
1098 				filter->client_total = filter->client_avail = 0;
1099 				filter->client_next = filter->client_buff = NULL;
1100 				filter->end_of_file = 1;
1101 				/* Return whatever we do have. */
1102 				if (avail != NULL)
1103 					*avail = filter->avail;
1104 				return (NULL);
1105 			}
1106 			filter->client_total = bytes_read;
1107 			filter->client_avail = filter->client_total;
1108 			filter->client_next = filter->client_buff;
1109 		}
1110 		else
1111 		{
1112 			/*
1113 			 * We can't satisfy the request from the copy
1114 			 * buffer or the existing client data, so we
1115 			 * need to copy more client data over to the
1116 			 * copy buffer.
1117 			 */
1118 
1119 			/* Ensure the buffer is big enough. */
1120 			if (min > filter->buffer_size) {
1121 				size_t s, t;
1122 				char *p;
1123 
1124 				/* Double the buffer; watch for overflow. */
1125 				s = t = filter->buffer_size;
1126 				if (s == 0)
1127 					s = min;
1128 				while (s < min) {
1129 					t *= 2;
1130 					if (t <= s) { /* Integer overflow! */
1131 						archive_set_error(
1132 							&filter->archive->archive,
1133 							ENOMEM,
1134 						    "Unable to allocate copy buffer");
1135 						filter->fatal = 1;
1136 						if (avail != NULL)
1137 							*avail = ARCHIVE_FATAL;
1138 						return (NULL);
1139 					}
1140 					s = t;
1141 				}
1142 				/* Now s >= min, so allocate a new buffer. */
1143 				p = (char *)malloc(s);
1144 				if (p == NULL) {
1145 					archive_set_error(
1146 						&filter->archive->archive,
1147 						ENOMEM,
1148 					    "Unable to allocate copy buffer");
1149 					filter->fatal = 1;
1150 					if (avail != NULL)
1151 						*avail = ARCHIVE_FATAL;
1152 					return (NULL);
1153 				}
1154 				/* Move data into newly-enlarged buffer. */
1155 				if (filter->avail > 0)
1156 					memmove(p, filter->next, filter->avail);
1157 				free(filter->buffer);
1158 				filter->next = filter->buffer = p;
1159 				filter->buffer_size = s;
1160 			}
1161 
1162 			/* We can add client data to copy buffer. */
1163 			/* First estimate: copy to fill rest of buffer. */
1164 			tocopy = (filter->buffer + filter->buffer_size)
1165 			    - (filter->next + filter->avail);
1166 			/* Don't waste time buffering more than we need to. */
1167 			if (tocopy + filter->avail > min)
1168 				tocopy = min - filter->avail;
1169 			/* Don't copy more than is available. */
1170 			if (tocopy > filter->client_avail)
1171 				tocopy = filter->client_avail;
1172 
1173 			memcpy(filter->next + filter->avail, filter->client_next,
1174 			    tocopy);
1175 			/* Remove this data from client buffer. */
1176 			filter->client_next += tocopy;
1177 			filter->client_avail -= tocopy;
1178 			/* add it to copy buffer. */
1179 			filter->avail += tocopy;
1180 		}
1181 	}
1182 }
1183 
1184 /*
1185  * Move the file pointer forward.
1186  */
1187 int64_t
1188 __archive_read_consume(struct archive_read *a, int64_t request)
1189 {
1190 	return (__archive_read_filter_consume(a->filter, request));
1191 }
1192 
1193 int64_t
1194 __archive_read_filter_consume(struct archive_read_filter * filter,
1195     int64_t request)
1196 {
1197 	int64_t skipped;
1198 
1199 	if (request == 0)
1200 		return 0;
1201 
1202 	skipped = advance_file_pointer(filter, request);
1203 	if (skipped == request)
1204 		return (skipped);
1205 	/* We hit EOF before we satisfied the skip request. */
1206 	if (skipped < 0)  /* Map error code to 0 for error message below. */
1207 		skipped = 0;
1208 	archive_set_error(&filter->archive->archive,
1209 	    ARCHIVE_ERRNO_MISC,
1210 	    "Truncated input file (needed %jd bytes, only %jd available)",
1211 	    (intmax_t)request, (intmax_t)skipped);
1212 	return (ARCHIVE_FATAL);
1213 }
1214 
1215 /*
1216  * Advance the file pointer by the amount requested.
1217  * Returns the amount actually advanced, which may be less than the
1218  * request if EOF is encountered first.
1219  * Returns a negative value if there's an I/O error.
1220  */
1221 static int64_t
1222 advance_file_pointer(struct archive_read_filter *filter, int64_t request)
1223 {
1224 	int64_t bytes_skipped, total_bytes_skipped = 0;
1225 	ssize_t bytes_read;
1226 	size_t min;
1227 
1228 	if (filter->fatal)
1229 		return (-1);
1230 
1231 	/* Use up the copy buffer first. */
1232 	if (filter->avail > 0) {
1233 		min = (size_t)minimum(request, (int64_t)filter->avail);
1234 		filter->next += min;
1235 		filter->avail -= min;
1236 		request -= min;
1237 		filter->position += min;
1238 		total_bytes_skipped += min;
1239 	}
1240 
1241 	/* Then use up the client buffer. */
1242 	if (filter->client_avail > 0) {
1243 		min = (size_t)minimum(request, (int64_t)filter->client_avail);
1244 		filter->client_next += min;
1245 		filter->client_avail -= min;
1246 		request -= min;
1247 		filter->position += min;
1248 		total_bytes_skipped += min;
1249 	}
1250 	if (request == 0)
1251 		return (total_bytes_skipped);
1252 
1253 	/* If there's an optimized skip function, use it. */
1254 	if (filter->skip != NULL) {
1255 		bytes_skipped = (filter->skip)(filter, request);
1256 		if (bytes_skipped < 0) {	/* error */
1257 			filter->fatal = 1;
1258 			return (bytes_skipped);
1259 		}
1260 		filter->position += bytes_skipped;
1261 		total_bytes_skipped += bytes_skipped;
1262 		request -= bytes_skipped;
1263 		if (request == 0)
1264 			return (total_bytes_skipped);
1265 	}
1266 
1267 	/* Use ordinary reads as necessary to complete the request. */
1268 	for (;;) {
1269 		bytes_read = (filter->read)(filter, &filter->client_buff);
1270 		if (bytes_read < 0) {
1271 			filter->client_buff = NULL;
1272 			filter->fatal = 1;
1273 			return (bytes_read);
1274 		}
1275 
1276 		if (bytes_read == 0) {
1277 			filter->client_buff = NULL;
1278 			filter->end_of_file = 1;
1279 			return (total_bytes_skipped);
1280 		}
1281 
1282 		if (bytes_read >= request) {
1283 			filter->client_next =
1284 			    ((const char *)filter->client_buff) + request;
1285 			filter->client_avail = (size_t)(bytes_read - request);
1286 			filter->client_total = bytes_read;
1287 			total_bytes_skipped += request;
1288 			filter->position += request;
1289 			return (total_bytes_skipped);
1290 		}
1291 
1292 		filter->position += bytes_read;
1293 		total_bytes_skipped += bytes_read;
1294 		request -= bytes_read;
1295 	}
1296 }
1297 
1298 /**
1299  * Returns ARCHIVE_FAILED if seeking isn't supported.
1300  */
1301 int64_t
1302 __archive_read_seek(struct archive_read *a, int64_t offset, int whence)
1303 {
1304 	return __archive_read_filter_seek(a->filter, offset, whence);
1305 }
1306 
1307 int64_t
1308 __archive_read_filter_seek(struct archive_read_filter *filter, int64_t offset, int whence)
1309 {
1310 	int64_t r;
1311 
1312 	if (filter->closed || filter->fatal)
1313 		return (ARCHIVE_FATAL);
1314 	if (filter->seek == NULL)
1315 		return (ARCHIVE_FAILED);
1316 	r = filter->seek(filter, offset, whence);
1317 	if (r >= 0) {
1318 		/*
1319 		 * Ouch.  Clearing the buffer like this hurts, especially
1320 		 * at bid time.  A lot of our efficiency at bid time comes
1321 		 * from having bidders reuse the data we've already read.
1322 		 *
1323 		 * TODO: If the seek request is in data we already
1324 		 * have, then don't call the seek callback.
1325 		 *
1326 		 * TODO: Zip seeks to end-of-file at bid time.  If
1327 		 * other formats also start doing this, we may need to
1328 		 * find a way for clients to fudge the seek offset to
1329 		 * a block boundary.
1330 		 *
1331 		 * Hmmm... If whence was SEEK_END, we know the file
1332 		 * size is (r - offset).  Can we use that to simplify
1333 		 * the TODO items above?
1334 		 */
1335 		filter->avail = filter->client_avail = 0;
1336 		filter->next = filter->buffer;
1337 		filter->position = r;
1338 		filter->end_of_file = 0;
1339 	}
1340 	return r;
1341 }
1342