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