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