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