]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/archive_read_support_format_tar.c
MFH r324148:
[FreeBSD/stable/10.git] / contrib / libarchive / libarchive / archive_read_support_format_tar.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2011-2012 Michihiro NAKAJIMA
4  * Copyright (c) 2016 Martin Matuska
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
30
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 #include <stddef.h>
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41
42 #include "archive.h"
43 #include "archive_acl_private.h" /* For ACL parsing routines. */
44 #include "archive_entry.h"
45 #include "archive_entry_locale.h"
46 #include "archive_private.h"
47 #include "archive_read_private.h"
48
49 #define tar_min(a,b) ((a) < (b) ? (a) : (b))
50
51 /*
52  * Layout of POSIX 'ustar' tar header.
53  */
54 struct archive_entry_header_ustar {
55         char    name[100];
56         char    mode[8];
57         char    uid[8];
58         char    gid[8];
59         char    size[12];
60         char    mtime[12];
61         char    checksum[8];
62         char    typeflag[1];
63         char    linkname[100];  /* "old format" header ends here */
64         char    magic[6];       /* For POSIX: "ustar\0" */
65         char    version[2];     /* For POSIX: "00" */
66         char    uname[32];
67         char    gname[32];
68         char    rdevmajor[8];
69         char    rdevminor[8];
70         char    prefix[155];
71 };
72
73 /*
74  * Structure of GNU tar header
75  */
76 struct gnu_sparse {
77         char    offset[12];
78         char    numbytes[12];
79 };
80
81 struct archive_entry_header_gnutar {
82         char    name[100];
83         char    mode[8];
84         char    uid[8];
85         char    gid[8];
86         char    size[12];
87         char    mtime[12];
88         char    checksum[8];
89         char    typeflag[1];
90         char    linkname[100];
91         char    magic[8];  /* "ustar  \0" (note blank/blank/null at end) */
92         char    uname[32];
93         char    gname[32];
94         char    rdevmajor[8];
95         char    rdevminor[8];
96         char    atime[12];
97         char    ctime[12];
98         char    offset[12];
99         char    longnames[4];
100         char    unused[1];
101         struct gnu_sparse sparse[4];
102         char    isextended[1];
103         char    realsize[12];
104         /*
105          * Old GNU format doesn't use POSIX 'prefix' field; they use
106          * the 'L' (longname) entry instead.
107          */
108 };
109
110 /*
111  * Data specific to this format.
112  */
113 struct sparse_block {
114         struct sparse_block     *next;
115         int64_t offset;
116         int64_t remaining;
117         int hole;
118 };
119
120 struct tar {
121         struct archive_string    acl_text;
122         struct archive_string    entry_pathname;
123         /* For "GNU.sparse.name" and other similar path extensions. */
124         struct archive_string    entry_pathname_override;
125         struct archive_string    entry_linkpath;
126         struct archive_string    entry_uname;
127         struct archive_string    entry_gname;
128         struct archive_string    longlink;
129         struct archive_string    longname;
130         struct archive_string    pax_header;
131         struct archive_string    pax_global;
132         struct archive_string    line;
133         int                      pax_hdrcharset_binary;
134         int                      header_recursion_depth;
135         int64_t                  entry_bytes_remaining;
136         int64_t                  entry_offset;
137         int64_t                  entry_padding;
138         int64_t                  entry_bytes_unconsumed;
139         int64_t                  realsize;
140         int                      sparse_allowed;
141         struct sparse_block     *sparse_list;
142         struct sparse_block     *sparse_last;
143         int64_t                  sparse_offset;
144         int64_t                  sparse_numbytes;
145         int                      sparse_gnu_major;
146         int                      sparse_gnu_minor;
147         char                     sparse_gnu_pending;
148
149         struct archive_string    localname;
150         struct archive_string_conv *opt_sconv;
151         struct archive_string_conv *sconv;
152         struct archive_string_conv *sconv_acl;
153         struct archive_string_conv *sconv_default;
154         int                      init_default_conversion;
155         int                      compat_2x;
156         int                      process_mac_extensions;
157         int                      read_concatenated_archives;
158         int                      realsize_override;
159 };
160
161 static int      archive_block_is_null(const char *p);
162 static char     *base64_decode(const char *, size_t, size_t *);
163 static int      gnu_add_sparse_entry(struct archive_read *, struct tar *,
164                     int64_t offset, int64_t remaining);
165
166 static void     gnu_clear_sparse_list(struct tar *);
167 static int      gnu_sparse_old_read(struct archive_read *, struct tar *,
168                     const struct archive_entry_header_gnutar *header, size_t *);
169 static int      gnu_sparse_old_parse(struct archive_read *, struct tar *,
170                     const struct gnu_sparse *sparse, int length);
171 static int      gnu_sparse_01_parse(struct archive_read *, struct tar *,
172                     const char *);
173 static ssize_t  gnu_sparse_10_read(struct archive_read *, struct tar *,
174                         size_t *);
175 static int      header_Solaris_ACL(struct archive_read *,  struct tar *,
176                     struct archive_entry *, const void *, size_t *);
177 static int      header_common(struct archive_read *,  struct tar *,
178                     struct archive_entry *, const void *);
179 static int      header_old_tar(struct archive_read *, struct tar *,
180                     struct archive_entry *, const void *);
181 static int      header_pax_extensions(struct archive_read *, struct tar *,
182                     struct archive_entry *, const void *, size_t *);
183 static int      header_pax_global(struct archive_read *, struct tar *,
184                     struct archive_entry *, const void *h, size_t *);
185 static int      header_longlink(struct archive_read *, struct tar *,
186                     struct archive_entry *, const void *h, size_t *);
187 static int      header_longname(struct archive_read *, struct tar *,
188                     struct archive_entry *, const void *h, size_t *);
189 static int      read_mac_metadata_blob(struct archive_read *, struct tar *,
190                     struct archive_entry *, const void *h, size_t *);
191 static int      header_volume(struct archive_read *, struct tar *,
192                     struct archive_entry *, const void *h, size_t *);
193 static int      header_ustar(struct archive_read *, struct tar *,
194                     struct archive_entry *, const void *h);
195 static int      header_gnutar(struct archive_read *, struct tar *,
196                     struct archive_entry *, const void *h, size_t *);
197 static int      archive_read_format_tar_bid(struct archive_read *, int);
198 static int      archive_read_format_tar_options(struct archive_read *,
199                     const char *, const char *);
200 static int      archive_read_format_tar_cleanup(struct archive_read *);
201 static int      archive_read_format_tar_read_data(struct archive_read *a,
202                     const void **buff, size_t *size, int64_t *offset);
203 static int      archive_read_format_tar_skip(struct archive_read *a);
204 static int      archive_read_format_tar_read_header(struct archive_read *,
205                     struct archive_entry *);
206 static int      checksum(struct archive_read *, const void *);
207 static int      pax_attribute(struct archive_read *, struct tar *,
208                     struct archive_entry *, const char *key, const char *value,
209                     size_t value_length);
210 static int      pax_attribute_acl(struct archive_read *, struct tar *,
211                     struct archive_entry *, const char *, int);
212 static int      pax_attribute_xattr(struct archive_entry *, const char *,
213                     const char *);
214 static int      pax_header(struct archive_read *, struct tar *,
215                     struct archive_entry *, struct archive_string *);
216 static void     pax_time(const char *, int64_t *sec, long *nanos);
217 static ssize_t  readline(struct archive_read *, struct tar *, const char **,
218                     ssize_t limit, size_t *);
219 static int      read_body_to_string(struct archive_read *, struct tar *,
220                     struct archive_string *, const void *h, size_t *);
221 static int      solaris_sparse_parse(struct archive_read *, struct tar *,
222                     struct archive_entry *, const char *);
223 static int64_t  tar_atol(const char *, size_t);
224 static int64_t  tar_atol10(const char *, size_t);
225 static int64_t  tar_atol256(const char *, size_t);
226 static int64_t  tar_atol8(const char *, size_t);
227 static int      tar_read_header(struct archive_read *, struct tar *,
228                     struct archive_entry *, size_t *);
229 static int      tohex(int c);
230 static char     *url_decode(const char *);
231 static void     tar_flush_unconsumed(struct archive_read *, size_t *);
232
233
234 int
235 archive_read_support_format_gnutar(struct archive *a)
236 {
237         archive_check_magic(a, ARCHIVE_READ_MAGIC,
238             ARCHIVE_STATE_NEW, "archive_read_support_format_gnutar");
239         return (archive_read_support_format_tar(a));
240 }
241
242
243 int
244 archive_read_support_format_tar(struct archive *_a)
245 {
246         struct archive_read *a = (struct archive_read *)_a;
247         struct tar *tar;
248         int r;
249
250         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
251             ARCHIVE_STATE_NEW, "archive_read_support_format_tar");
252
253         tar = (struct tar *)calloc(1, sizeof(*tar));
254 #ifdef HAVE_COPYFILE_H
255         /* Set this by default on Mac OS. */
256         tar->process_mac_extensions = 1;
257 #endif
258         if (tar == NULL) {
259                 archive_set_error(&a->archive, ENOMEM,
260                     "Can't allocate tar data");
261                 return (ARCHIVE_FATAL);
262         }
263
264         r = __archive_read_register_format(a, tar, "tar",
265             archive_read_format_tar_bid,
266             archive_read_format_tar_options,
267             archive_read_format_tar_read_header,
268             archive_read_format_tar_read_data,
269             archive_read_format_tar_skip,
270             NULL,
271             archive_read_format_tar_cleanup,
272             NULL,
273             NULL);
274
275         if (r != ARCHIVE_OK)
276                 free(tar);
277         return (ARCHIVE_OK);
278 }
279
280 static int
281 archive_read_format_tar_cleanup(struct archive_read *a)
282 {
283         struct tar *tar;
284
285         tar = (struct tar *)(a->format->data);
286         gnu_clear_sparse_list(tar);
287         archive_string_free(&tar->acl_text);
288         archive_string_free(&tar->entry_pathname);
289         archive_string_free(&tar->entry_pathname_override);
290         archive_string_free(&tar->entry_linkpath);
291         archive_string_free(&tar->entry_uname);
292         archive_string_free(&tar->entry_gname);
293         archive_string_free(&tar->line);
294         archive_string_free(&tar->pax_global);
295         archive_string_free(&tar->pax_header);
296         archive_string_free(&tar->longname);
297         archive_string_free(&tar->longlink);
298         archive_string_free(&tar->localname);
299         free(tar);
300         (a->format->data) = NULL;
301         return (ARCHIVE_OK);
302 }
303
304 /*
305  * Validate number field
306  *
307  * This has to be pretty lenient in order to accommodate the enormous
308  * variety of tar writers in the world:
309  *  = POSIX (IEEE Std 1003.1-1988) ustar requires octal values with leading
310  *    zeros and allows fields to be terminated with space or null characters
311  *  = Many writers use different termination (in particular, libarchive
312  *    omits terminator bytes to squeeze one or two more digits)
313  *  = Many writers pad with space and omit leading zeros
314  *  = GNU tar and star write base-256 values if numbers are too
315  *    big to be represented in octal
316  *
317  *  Examples of specific tar headers that we should support:
318  *  = Perl Archive::Tar terminates uid, gid, devminor and devmajor with two
319  *    null bytes, pads size with spaces and other numeric fields with zeroes
320  *  = plexus-archiver prior to 2.6.3 (before switching to commons-compress)
321  *    may have uid and gid fields filled with spaces without any octal digits
322  *    at all and pads all numeric fields with spaces
323  *
324  * This should tolerate all variants in use.  It will reject a field
325  * where the writer just left garbage after a trailing NUL.
326  */
327 static int
328 validate_number_field(const char* p_field, size_t i_size)
329 {
330         unsigned char marker = (unsigned char)p_field[0];
331         if (marker == 128 || marker == 255 || marker == 0) {
332                 /* Base-256 marker, there's nothing we can check. */
333                 return 1;
334         } else {
335                 /* Must be octal */
336                 size_t i = 0;
337                 /* Skip any leading spaces */
338                 while (i < i_size && p_field[i] == ' ') {
339                         ++i;
340                 }
341                 /* Skip octal digits. */
342                 while (i < i_size && p_field[i] >= '0' && p_field[i] <= '7') {
343                         ++i;
344                 }
345                 /* Any remaining characters must be space or NUL padding. */
346                 while (i < i_size) {
347                         if (p_field[i] != ' ' && p_field[i] != 0) {
348                                 return 0;
349                         }
350                         ++i;
351                 }
352                 return 1;
353         }
354 }
355
356 static int
357 archive_read_format_tar_bid(struct archive_read *a, int best_bid)
358 {
359         int bid;
360         const char *h;
361         const struct archive_entry_header_ustar *header;
362
363         (void)best_bid; /* UNUSED */
364
365         bid = 0;
366
367         /* Now let's look at the actual header and see if it matches. */
368         h = __archive_read_ahead(a, 512, NULL);
369         if (h == NULL)
370                 return (-1);
371
372         /* If it's an end-of-archive mark, we can handle it. */
373         if (h[0] == 0 && archive_block_is_null(h)) {
374                 /*
375                  * Usually, I bid the number of bits verified, but
376                  * in this case, 4096 seems excessive so I picked 10 as
377                  * an arbitrary but reasonable-seeming value.
378                  */
379                 return (10);
380         }
381
382         /* If it's not an end-of-archive mark, it must have a valid checksum.*/
383         if (!checksum(a, h))
384                 return (0);
385         bid += 48;  /* Checksum is usually 6 octal digits. */
386
387         header = (const struct archive_entry_header_ustar *)h;
388
389         /* Recognize POSIX formats. */
390         if ((memcmp(header->magic, "ustar\0", 6) == 0)
391             && (memcmp(header->version, "00", 2) == 0))
392                 bid += 56;
393
394         /* Recognize GNU tar format. */
395         if ((memcmp(header->magic, "ustar ", 6) == 0)
396             && (memcmp(header->version, " \0", 2) == 0))
397                 bid += 56;
398
399         /* Type flag must be null, digit or A-Z, a-z. */
400         if (header->typeflag[0] != 0 &&
401             !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
402             !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
403             !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
404                 return (0);
405         bid += 2;  /* 6 bits of variation in an 8-bit field leaves 2 bits. */
406
407         /*
408          * Check format of mode/uid/gid/mtime/size/rdevmajor/rdevminor fields.
409          */
410         if (bid > 0 && (
411             validate_number_field(header->mode, sizeof(header->mode)) == 0
412             || validate_number_field(header->uid, sizeof(header->uid)) == 0
413             || validate_number_field(header->gid, sizeof(header->gid)) == 0
414             || validate_number_field(header->mtime, sizeof(header->mtime)) == 0
415             || validate_number_field(header->size, sizeof(header->size)) == 0
416             || validate_number_field(header->rdevmajor, sizeof(header->rdevmajor)) == 0
417             || validate_number_field(header->rdevminor, sizeof(header->rdevminor)) == 0)) {
418                 bid = 0;
419         }
420
421         return (bid);
422 }
423
424 static int
425 archive_read_format_tar_options(struct archive_read *a,
426     const char *key, const char *val)
427 {
428         struct tar *tar;
429         int ret = ARCHIVE_FAILED;
430
431         tar = (struct tar *)(a->format->data);
432         if (strcmp(key, "compat-2x")  == 0) {
433                 /* Handle UTF-8 filenames as libarchive 2.x */
434                 tar->compat_2x = (val != NULL && val[0] != 0);
435                 tar->init_default_conversion = tar->compat_2x;
436                 return (ARCHIVE_OK);
437         } else if (strcmp(key, "hdrcharset")  == 0) {
438                 if (val == NULL || val[0] == 0)
439                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
440                             "tar: hdrcharset option needs a character-set name");
441                 else {
442                         tar->opt_sconv =
443                             archive_string_conversion_from_charset(
444                                 &a->archive, val, 0);
445                         if (tar->opt_sconv != NULL)
446                                 ret = ARCHIVE_OK;
447                         else
448                                 ret = ARCHIVE_FATAL;
449                 }
450                 return (ret);
451         } else if (strcmp(key, "mac-ext") == 0) {
452                 tar->process_mac_extensions = (val != NULL && val[0] != 0);
453                 return (ARCHIVE_OK);
454         } else if (strcmp(key, "read_concatenated_archives") == 0) {
455                 tar->read_concatenated_archives = (val != NULL && val[0] != 0);
456                 return (ARCHIVE_OK);
457         }
458
459         /* Note: The "warn" return is just to inform the options
460          * supervisor that we didn't handle it.  It will generate
461          * a suitable error if no one used this option. */
462         return (ARCHIVE_WARN);
463 }
464
465 /* utility function- this exists to centralize the logic of tracking
466  * how much unconsumed data we have floating around, and to consume
467  * anything outstanding since we're going to do read_aheads
468  */
469 static void
470 tar_flush_unconsumed(struct archive_read *a, size_t *unconsumed)
471 {
472         if (*unconsumed) {
473 /*
474                 void *data = (void *)__archive_read_ahead(a, *unconsumed, NULL);
475                  * this block of code is to poison claimed unconsumed space, ensuring
476                  * things break if it is in use still.
477                  * currently it WILL break things, so enable it only for debugging this issue
478                 if (data) {
479                         memset(data, 0xff, *unconsumed);
480                 }
481 */
482                 __archive_read_consume(a, *unconsumed);
483                 *unconsumed = 0;
484         }
485 }
486
487 /*
488  * The function invoked by archive_read_next_header().  This
489  * just sets up a few things and then calls the internal
490  * tar_read_header() function below.
491  */
492 static int
493 archive_read_format_tar_read_header(struct archive_read *a,
494     struct archive_entry *entry)
495 {
496         /*
497          * When converting tar archives to cpio archives, it is
498          * essential that each distinct file have a distinct inode
499          * number.  To simplify this, we keep a static count here to
500          * assign fake dev/inode numbers to each tar entry.  Note that
501          * pax format archives may overwrite this with something more
502          * useful.
503          *
504          * Ideally, we would track every file read from the archive so
505          * that we could assign the same dev/ino pair to hardlinks,
506          * but the memory required to store a complete lookup table is
507          * probably not worthwhile just to support the relatively
508          * obscure tar->cpio conversion case.
509          */
510         static int default_inode;
511         static int default_dev;
512         struct tar *tar;
513         const char *p;
514         const wchar_t *wp;
515         int r;
516         size_t l, unconsumed = 0;
517
518         /* Assign default device/inode values. */
519         archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
520         archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
521         /* Limit generated st_ino number to 16 bits. */
522         if (default_inode >= 0xffff) {
523                 ++default_dev;
524                 default_inode = 0;
525         }
526
527         tar = (struct tar *)(a->format->data);
528         tar->entry_offset = 0;
529         gnu_clear_sparse_list(tar);
530         tar->realsize = -1; /* Mark this as "unset" */
531         tar->realsize_override = 0;
532
533         /* Setup default string conversion. */
534         tar->sconv = tar->opt_sconv;
535         if (tar->sconv == NULL) {
536                 if (!tar->init_default_conversion) {
537                         tar->sconv_default =
538                             archive_string_default_conversion_for_read(&(a->archive));
539                         tar->init_default_conversion = 1;
540                 }
541                 tar->sconv = tar->sconv_default;
542         }
543
544         r = tar_read_header(a, tar, entry, &unconsumed);
545
546         tar_flush_unconsumed(a, &unconsumed);
547
548         /*
549          * "non-sparse" files are really just sparse files with
550          * a single block.
551          */
552         if (tar->sparse_list == NULL) {
553                 if (gnu_add_sparse_entry(a, tar, 0, tar->entry_bytes_remaining)
554                     != ARCHIVE_OK)
555                         return (ARCHIVE_FATAL);
556         } else {
557                 struct sparse_block *sb;
558
559                 for (sb = tar->sparse_list; sb != NULL; sb = sb->next) {
560                         if (!sb->hole)
561                                 archive_entry_sparse_add_entry(entry,
562                                     sb->offset, sb->remaining);
563                 }
564         }
565
566         if (r == ARCHIVE_OK && archive_entry_filetype(entry) == AE_IFREG) {
567                 /*
568                  * "Regular" entry with trailing '/' is really
569                  * directory: This is needed for certain old tar
570                  * variants and even for some broken newer ones.
571                  */
572                 if ((wp = archive_entry_pathname_w(entry)) != NULL) {
573                         l = wcslen(wp);
574                         if (l > 0 && wp[l - 1] == L'/') {
575                                 archive_entry_set_filetype(entry, AE_IFDIR);
576                         }
577                 } else if ((p = archive_entry_pathname(entry)) != NULL) {
578                         l = strlen(p);
579                         if (l > 0 && p[l - 1] == '/') {
580                                 archive_entry_set_filetype(entry, AE_IFDIR);
581                         }
582                 }
583         }
584         return (r);
585 }
586
587 static int
588 archive_read_format_tar_read_data(struct archive_read *a,
589     const void **buff, size_t *size, int64_t *offset)
590 {
591         ssize_t bytes_read;
592         struct tar *tar;
593         struct sparse_block *p;
594
595         tar = (struct tar *)(a->format->data);
596
597         for (;;) {
598                 /* Remove exhausted entries from sparse list. */
599                 while (tar->sparse_list != NULL &&
600                     tar->sparse_list->remaining == 0) {
601                         p = tar->sparse_list;
602                         tar->sparse_list = p->next;
603                         free(p);
604                 }
605
606                 if (tar->entry_bytes_unconsumed) {
607                         __archive_read_consume(a, tar->entry_bytes_unconsumed);
608                         tar->entry_bytes_unconsumed = 0;
609                 }
610
611                 /* If we're at end of file, return EOF. */
612                 if (tar->sparse_list == NULL ||
613                     tar->entry_bytes_remaining == 0) {
614                         if (__archive_read_consume(a, tar->entry_padding) < 0)
615                                 return (ARCHIVE_FATAL);
616                         tar->entry_padding = 0;
617                         *buff = NULL;
618                         *size = 0;
619                         *offset = tar->realsize;
620                         return (ARCHIVE_EOF);
621                 }
622
623                 *buff = __archive_read_ahead(a, 1, &bytes_read);
624                 if (bytes_read < 0)
625                         return (ARCHIVE_FATAL);
626                 if (*buff == NULL) {
627                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
628                             "Truncated tar archive");
629                         return (ARCHIVE_FATAL);
630                 }
631                 if (bytes_read > tar->entry_bytes_remaining)
632                         bytes_read = (ssize_t)tar->entry_bytes_remaining;
633                 /* Don't read more than is available in the
634                  * current sparse block. */
635                 if (tar->sparse_list->remaining < bytes_read)
636                         bytes_read = (ssize_t)tar->sparse_list->remaining;
637                 *size = bytes_read;
638                 *offset = tar->sparse_list->offset;
639                 tar->sparse_list->remaining -= bytes_read;
640                 tar->sparse_list->offset += bytes_read;
641                 tar->entry_bytes_remaining -= bytes_read;
642                 tar->entry_bytes_unconsumed = bytes_read;
643
644                 if (!tar->sparse_list->hole)
645                         return (ARCHIVE_OK);
646                 /* Current is hole data and skip this. */
647         }
648 }
649
650 static int
651 archive_read_format_tar_skip(struct archive_read *a)
652 {
653         int64_t bytes_skipped;
654         int64_t request;
655         struct sparse_block *p;
656         struct tar* tar;
657
658         tar = (struct tar *)(a->format->data);
659
660         /* Do not consume the hole of a sparse file. */
661         request = 0;
662         for (p = tar->sparse_list; p != NULL; p = p->next) {
663                 if (!p->hole) {
664                         if (p->remaining >= INT64_MAX - request) {
665                                 return ARCHIVE_FATAL;
666                         }
667                         request += p->remaining;
668                 }
669         }
670         if (request > tar->entry_bytes_remaining)
671                 request = tar->entry_bytes_remaining;
672         request += tar->entry_padding + tar->entry_bytes_unconsumed;
673
674         bytes_skipped = __archive_read_consume(a, request);
675         if (bytes_skipped < 0)
676                 return (ARCHIVE_FATAL);
677
678         tar->entry_bytes_remaining = 0;
679         tar->entry_bytes_unconsumed = 0;
680         tar->entry_padding = 0;
681
682         /* Free the sparse list. */
683         gnu_clear_sparse_list(tar);
684
685         return (ARCHIVE_OK);
686 }
687
688 /*
689  * This function recursively interprets all of the headers associated
690  * with a single entry.
691  */
692 static int
693 tar_read_header(struct archive_read *a, struct tar *tar,
694     struct archive_entry *entry, size_t *unconsumed)
695 {
696         ssize_t bytes;
697         int err;
698         const char *h;
699         const struct archive_entry_header_ustar *header;
700         const struct archive_entry_header_gnutar *gnuheader;
701
702         /* Loop until we find a workable header record. */
703         for (;;) {
704                 tar_flush_unconsumed(a, unconsumed);
705
706                 /* Read 512-byte header record */
707                 h = __archive_read_ahead(a, 512, &bytes);
708                 if (bytes < 0)
709                         return ((int)bytes);
710                 if (bytes == 0) { /* EOF at a block boundary. */
711                         /* Some writers do omit the block of nulls. <sigh> */
712                         return (ARCHIVE_EOF);
713                 }
714                 if (bytes < 512) {  /* Short block at EOF; this is bad. */
715                         archive_set_error(&a->archive,
716                             ARCHIVE_ERRNO_FILE_FORMAT,
717                             "Truncated tar archive");
718                         return (ARCHIVE_FATAL);
719                 }
720                 *unconsumed = 512;
721
722                 /* Header is workable if it's not an end-of-archive mark. */
723                 if (h[0] != 0 || !archive_block_is_null(h))
724                         break;
725
726                 /* Ensure format is set for archives with only null blocks. */
727                 if (a->archive.archive_format_name == NULL) {
728                         a->archive.archive_format = ARCHIVE_FORMAT_TAR;
729                         a->archive.archive_format_name = "tar";
730                 }
731
732                 if (!tar->read_concatenated_archives) {
733                         /* Try to consume a second all-null record, as well. */
734                         tar_flush_unconsumed(a, unconsumed);
735                         h = __archive_read_ahead(a, 512, NULL);
736                         if (h != NULL && h[0] == 0 && archive_block_is_null(h))
737                                 __archive_read_consume(a, 512);
738                         archive_clear_error(&a->archive);
739                         return (ARCHIVE_EOF);
740                 }
741
742                 /*
743                  * We're reading concatenated archives, ignore this block and
744                  * loop to get the next.
745                  */
746         }
747
748         /*
749          * Note: If the checksum fails and we return ARCHIVE_RETRY,
750          * then the client is likely to just retry.  This is a very
751          * crude way to search for the next valid header!
752          *
753          * TODO: Improve this by implementing a real header scan.
754          */
755         if (!checksum(a, h)) {
756                 tar_flush_unconsumed(a, unconsumed);
757                 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
758                 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
759         }
760
761         if (++tar->header_recursion_depth > 32) {
762                 tar_flush_unconsumed(a, unconsumed);
763                 archive_set_error(&a->archive, EINVAL, "Too many special headers");
764                 return (ARCHIVE_WARN);
765         }
766
767         /* Determine the format variant. */
768         header = (const struct archive_entry_header_ustar *)h;
769
770         switch(header->typeflag[0]) {
771         case 'A': /* Solaris tar ACL */
772                 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
773                 a->archive.archive_format_name = "Solaris tar";
774                 err = header_Solaris_ACL(a, tar, entry, h, unconsumed);
775                 break;
776         case 'g': /* POSIX-standard 'g' header. */
777                 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
778                 a->archive.archive_format_name = "POSIX pax interchange format";
779                 err = header_pax_global(a, tar, entry, h, unconsumed);
780                 if (err == ARCHIVE_EOF)
781                         return (err);
782                 break;
783         case 'K': /* Long link name (GNU tar, others) */
784                 err = header_longlink(a, tar, entry, h, unconsumed);
785                 break;
786         case 'L': /* Long filename (GNU tar, others) */
787                 err = header_longname(a, tar, entry, h, unconsumed);
788                 break;
789         case 'V': /* GNU volume header */
790                 err = header_volume(a, tar, entry, h, unconsumed);
791                 break;
792         case 'X': /* Used by SUN tar; same as 'x'. */
793                 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
794                 a->archive.archive_format_name =
795                     "POSIX pax interchange format (Sun variant)";
796                 err = header_pax_extensions(a, tar, entry, h, unconsumed);
797                 break;
798         case 'x': /* POSIX-standard 'x' header. */
799                 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
800                 a->archive.archive_format_name = "POSIX pax interchange format";
801                 err = header_pax_extensions(a, tar, entry, h, unconsumed);
802                 break;
803         default:
804                 gnuheader = (const struct archive_entry_header_gnutar *)h;
805                 if (memcmp(gnuheader->magic, "ustar  \0", 8) == 0) {
806                         a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
807                         a->archive.archive_format_name = "GNU tar format";
808                         err = header_gnutar(a, tar, entry, h, unconsumed);
809                 } else if (memcmp(header->magic, "ustar", 5) == 0) {
810                         if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
811                                 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
812                                 a->archive.archive_format_name = "POSIX ustar format";
813                         }
814                         err = header_ustar(a, tar, entry, h);
815                 } else {
816                         a->archive.archive_format = ARCHIVE_FORMAT_TAR;
817                         a->archive.archive_format_name = "tar (non-POSIX)";
818                         err = header_old_tar(a, tar, entry, h);
819                 }
820         }
821         if (err == ARCHIVE_FATAL)
822                 return (err);
823
824         tar_flush_unconsumed(a, unconsumed);
825
826         h = NULL;
827         header = NULL;
828
829         --tar->header_recursion_depth;
830         /* Yuck.  Apple's design here ends up storing long pathname
831          * extensions for both the AppleDouble extension entry and the
832          * regular entry.
833          */
834         if ((err == ARCHIVE_WARN || err == ARCHIVE_OK) &&
835             tar->header_recursion_depth == 0 &&
836             tar->process_mac_extensions) {
837                 int err2 = read_mac_metadata_blob(a, tar, entry, h, unconsumed);
838                 if (err2 < err)
839                         err = err2;
840         }
841
842         /* We return warnings or success as-is.  Anything else is fatal. */
843         if (err == ARCHIVE_WARN || err == ARCHIVE_OK) {
844                 if (tar->sparse_gnu_pending) {
845                         if (tar->sparse_gnu_major == 1 &&
846                             tar->sparse_gnu_minor == 0) {
847                                 ssize_t bytes_read;
848
849                                 tar->sparse_gnu_pending = 0;
850                                 /* Read initial sparse map. */
851                                 bytes_read = gnu_sparse_10_read(a, tar, unconsumed);
852                                 if (bytes_read < 0)
853                                         return ((int)bytes_read);
854                                 tar->entry_bytes_remaining -= bytes_read;
855                         } else {
856                                 archive_set_error(&a->archive,
857                                     ARCHIVE_ERRNO_MISC,
858                                     "Unrecognized GNU sparse file format");
859                                 return (ARCHIVE_WARN);
860                         }
861                         tar->sparse_gnu_pending = 0;
862                 }
863                 return (err);
864         }
865         if (err == ARCHIVE_EOF)
866                 /* EOF when recursively reading a header is bad. */
867                 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
868         return (ARCHIVE_FATAL);
869 }
870
871 /*
872  * Return true if block checksum is correct.
873  */
874 static int
875 checksum(struct archive_read *a, const void *h)
876 {
877         const unsigned char *bytes;
878         const struct archive_entry_header_ustar *header;
879         int check, sum;
880         size_t i;
881
882         (void)a; /* UNUSED */
883         bytes = (const unsigned char *)h;
884         header = (const struct archive_entry_header_ustar *)h;
885
886         /* Checksum field must hold an octal number */
887         for (i = 0; i < sizeof(header->checksum); ++i) {
888                 char c = header->checksum[i];
889                 if (c != ' ' && c != '\0' && (c < '0' || c > '7'))
890                         return 0;
891         }
892
893         /*
894          * Test the checksum.  Note that POSIX specifies _unsigned_
895          * bytes for this calculation.
896          */
897         sum = (int)tar_atol(header->checksum, sizeof(header->checksum));
898         check = 0;
899         for (i = 0; i < 148; i++)
900                 check += (unsigned char)bytes[i];
901         for (; i < 156; i++)
902                 check += 32;
903         for (; i < 512; i++)
904                 check += (unsigned char)bytes[i];
905         if (sum == check)
906                 return (1);
907
908         /*
909          * Repeat test with _signed_ bytes, just in case this archive
910          * was created by an old BSD, Solaris, or HP-UX tar with a
911          * broken checksum calculation.
912          */
913         check = 0;
914         for (i = 0; i < 148; i++)
915                 check += (signed char)bytes[i];
916         for (; i < 156; i++)
917                 check += 32;
918         for (; i < 512; i++)
919                 check += (signed char)bytes[i];
920         if (sum == check)
921                 return (1);
922
923         return (0);
924 }
925
926 /*
927  * Return true if this block contains only nulls.
928  */
929 static int
930 archive_block_is_null(const char *p)
931 {
932         unsigned i;
933
934         for (i = 0; i < 512; i++)
935                 if (*p++)
936                         return (0);
937         return (1);
938 }
939
940 /*
941  * Interpret 'A' Solaris ACL header
942  */
943 static int
944 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
945     struct archive_entry *entry, const void *h, size_t *unconsumed)
946 {
947         const struct archive_entry_header_ustar *header;
948         size_t size;
949         int err, acl_type;
950         int64_t type;
951         char *acl, *p;
952
953         /*
954          * read_body_to_string adds a NUL terminator, but we need a little
955          * more to make sure that we don't overrun acl_text later.
956          */
957         header = (const struct archive_entry_header_ustar *)h;
958         size = (size_t)tar_atol(header->size, sizeof(header->size));
959         err = read_body_to_string(a, tar, &(tar->acl_text), h, unconsumed);
960         if (err != ARCHIVE_OK)
961                 return (err);
962
963         /* Recursively read next header */
964         err = tar_read_header(a, tar, entry, unconsumed);
965         if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
966                 return (err);
967
968         /* TODO: Examine the first characters to see if this
969          * is an AIX ACL descriptor.  We'll likely never support
970          * them, but it would be polite to recognize and warn when
971          * we do see them. */
972
973         /* Leading octal number indicates ACL type and number of entries. */
974         p = acl = tar->acl_text.s;
975         type = 0;
976         while (*p != '\0' && p < acl + size) {
977                 if (*p < '0' || *p > '7') {
978                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
979                             "Malformed Solaris ACL attribute (invalid digit)");
980                         return(ARCHIVE_WARN);
981                 }
982                 type <<= 3;
983                 type += *p - '0';
984                 if (type > 077777777) {
985                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
986                             "Malformed Solaris ACL attribute (count too large)");
987                         return (ARCHIVE_WARN);
988                 }
989                 p++;
990         }
991         switch ((int)type & ~0777777) {
992         case 01000000:
993                 /* POSIX.1e ACL */
994                 acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
995                 break;
996         case 03000000:
997                 /* NFSv4 ACL */
998                 acl_type = ARCHIVE_ENTRY_ACL_TYPE_NFS4;
999                 break;
1000         default:
1001                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1002                     "Malformed Solaris ACL attribute (unsupported type %o)",
1003                     (int)type);
1004                 return (ARCHIVE_WARN);
1005         }
1006         p++;
1007
1008         if (p >= acl + size) {
1009                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1010                     "Malformed Solaris ACL attribute (body overflow)");
1011                 return(ARCHIVE_WARN);
1012         }
1013
1014         /* ACL text is null-terminated; find the end. */
1015         size -= (p - acl);
1016         acl = p;
1017
1018         while (*p != '\0' && p < acl + size)
1019                 p++;
1020
1021         if (tar->sconv_acl == NULL) {
1022                 tar->sconv_acl = archive_string_conversion_from_charset(
1023                     &(a->archive), "UTF-8", 1);
1024                 if (tar->sconv_acl == NULL)
1025                         return (ARCHIVE_FATAL);
1026         }
1027         archive_strncpy(&(tar->localname), acl, p - acl);
1028         err = archive_acl_from_text_l(archive_entry_acl(entry),
1029             tar->localname.s, acl_type, tar->sconv_acl);
1030         if (err != ARCHIVE_OK) {
1031                 if (errno == ENOMEM) {
1032                         archive_set_error(&a->archive, ENOMEM,
1033                             "Can't allocate memory for ACL");
1034                 } else
1035                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1036                             "Malformed Solaris ACL attribute (unparsable)");
1037         }
1038         return (err);
1039 }
1040
1041 /*
1042  * Interpret 'K' long linkname header.
1043  */
1044 static int
1045 header_longlink(struct archive_read *a, struct tar *tar,
1046     struct archive_entry *entry, const void *h, size_t *unconsumed)
1047 {
1048         int err;
1049
1050         err = read_body_to_string(a, tar, &(tar->longlink), h, unconsumed);
1051         if (err != ARCHIVE_OK)
1052                 return (err);
1053         err = tar_read_header(a, tar, entry, unconsumed);
1054         if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1055                 return (err);
1056         /* Set symlink if symlink already set, else hardlink. */
1057         archive_entry_copy_link(entry, tar->longlink.s);
1058         return (ARCHIVE_OK);
1059 }
1060
1061 static int
1062 set_conversion_failed_error(struct archive_read *a,
1063     struct archive_string_conv *sconv, const char *name)
1064 {
1065         if (errno == ENOMEM) {
1066                 archive_set_error(&a->archive, ENOMEM,
1067                     "Can't allocate memory for %s", name);
1068                 return (ARCHIVE_FATAL);
1069         }
1070         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1071             "%s can't be converted from %s to current locale.",
1072             name, archive_string_conversion_charset_name(sconv));
1073         return (ARCHIVE_WARN);
1074 }
1075
1076 /*
1077  * Interpret 'L' long filename header.
1078  */
1079 static int
1080 header_longname(struct archive_read *a, struct tar *tar,
1081     struct archive_entry *entry, const void *h, size_t *unconsumed)
1082 {
1083         int err;
1084
1085         err = read_body_to_string(a, tar, &(tar->longname), h, unconsumed);
1086         if (err != ARCHIVE_OK)
1087                 return (err);
1088         /* Read and parse "real" header, then override name. */
1089         err = tar_read_header(a, tar, entry, unconsumed);
1090         if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1091                 return (err);
1092         if (archive_entry_copy_pathname_l(entry, tar->longname.s,
1093             archive_strlen(&(tar->longname)), tar->sconv) != 0)
1094                 err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1095         return (err);
1096 }
1097
1098
1099 /*
1100  * Interpret 'V' GNU tar volume header.
1101  */
1102 static int
1103 header_volume(struct archive_read *a, struct tar *tar,
1104     struct archive_entry *entry, const void *h, size_t *unconsumed)
1105 {
1106         (void)h;
1107
1108         /* Just skip this and read the next header. */
1109         return (tar_read_header(a, tar, entry, unconsumed));
1110 }
1111
1112 /*
1113  * Read body of an archive entry into an archive_string object.
1114  */
1115 static int
1116 read_body_to_string(struct archive_read *a, struct tar *tar,
1117     struct archive_string *as, const void *h, size_t *unconsumed)
1118 {
1119         int64_t size;
1120         const struct archive_entry_header_ustar *header;
1121         const void *src;
1122
1123         (void)tar; /* UNUSED */
1124         header = (const struct archive_entry_header_ustar *)h;
1125         size  = tar_atol(header->size, sizeof(header->size));
1126         if ((size > 1048576) || (size < 0)) {
1127                 archive_set_error(&a->archive, EINVAL,
1128                     "Special header too large");
1129                 return (ARCHIVE_FATAL);
1130         }
1131
1132         /* Fail if we can't make our buffer big enough. */
1133         if (archive_string_ensure(as, (size_t)size+1) == NULL) {
1134                 archive_set_error(&a->archive, ENOMEM,
1135                     "No memory");
1136                 return (ARCHIVE_FATAL);
1137         }
1138
1139         tar_flush_unconsumed(a, unconsumed);
1140
1141         /* Read the body into the string. */
1142         *unconsumed = (size_t)((size + 511) & ~ 511);
1143         src = __archive_read_ahead(a, *unconsumed, NULL);
1144         if (src == NULL) {
1145                 *unconsumed = 0;
1146                 return (ARCHIVE_FATAL);
1147         }
1148         memcpy(as->s, src, (size_t)size);
1149         as->s[size] = '\0';
1150         as->length = (size_t)size;
1151         return (ARCHIVE_OK);
1152 }
1153
1154 /*
1155  * Parse out common header elements.
1156  *
1157  * This would be the same as header_old_tar, except that the
1158  * filename is handled slightly differently for old and POSIX
1159  * entries  (POSIX entries support a 'prefix').  This factoring
1160  * allows header_old_tar and header_ustar
1161  * to handle filenames differently, while still putting most of the
1162  * common parsing into one place.
1163  */
1164 static int
1165 header_common(struct archive_read *a, struct tar *tar,
1166     struct archive_entry *entry, const void *h)
1167 {
1168         const struct archive_entry_header_ustar *header;
1169         char    tartype;
1170         int     err = ARCHIVE_OK;
1171
1172         header = (const struct archive_entry_header_ustar *)h;
1173         if (header->linkname[0])
1174                 archive_strncpy(&(tar->entry_linkpath),
1175                     header->linkname, sizeof(header->linkname));
1176         else
1177                 archive_string_empty(&(tar->entry_linkpath));
1178
1179         /* Parse out the numeric fields (all are octal) */
1180         archive_entry_set_mode(entry,
1181                 (mode_t)tar_atol(header->mode, sizeof(header->mode)));
1182         archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
1183         archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
1184         tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size));
1185         if (tar->entry_bytes_remaining < 0) {
1186                 tar->entry_bytes_remaining = 0;
1187                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1188                     "Tar entry has negative size");
1189                 return (ARCHIVE_FATAL);
1190         }
1191         if (tar->entry_bytes_remaining == INT64_MAX) {
1192                 /* Note: tar_atol returns INT64_MAX on overflow */
1193                 tar->entry_bytes_remaining = 0;
1194                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1195                     "Tar entry size overflow");
1196                 return (ARCHIVE_FATAL);
1197         }
1198         tar->realsize = tar->entry_bytes_remaining;
1199         archive_entry_set_size(entry, tar->entry_bytes_remaining);
1200         archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
1201
1202         /* Handle the tar type flag appropriately. */
1203         tartype = header->typeflag[0];
1204
1205         switch (tartype) {
1206         case '1': /* Hard link */
1207                 if (archive_entry_copy_hardlink_l(entry, tar->entry_linkpath.s,
1208                     archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) {
1209                         err = set_conversion_failed_error(a, tar->sconv,
1210                             "Linkname");
1211                         if (err == ARCHIVE_FATAL)
1212                                 return (err);
1213                 }
1214                 /*
1215                  * The following may seem odd, but: Technically, tar
1216                  * does not store the file type for a "hard link"
1217                  * entry, only the fact that it is a hard link.  So, I
1218                  * leave the type zero normally.  But, pax interchange
1219                  * format allows hard links to have data, which
1220                  * implies that the underlying entry is a regular
1221                  * file.
1222                  */
1223                 if (archive_entry_size(entry) > 0)
1224                         archive_entry_set_filetype(entry, AE_IFREG);
1225
1226                 /*
1227                  * A tricky point: Traditionally, tar readers have
1228                  * ignored the size field when reading hardlink
1229                  * entries, and some writers put non-zero sizes even
1230                  * though the body is empty.  POSIX blessed this
1231                  * convention in the 1988 standard, but broke with
1232                  * this tradition in 2001 by permitting hardlink
1233                  * entries to store valid bodies in pax interchange
1234                  * format, but not in ustar format.  Since there is no
1235                  * hard and fast way to distinguish pax interchange
1236                  * from earlier archives (the 'x' and 'g' entries are
1237                  * optional, after all), we need a heuristic.
1238                  */
1239                 if (archive_entry_size(entry) == 0) {
1240                         /* If the size is already zero, we're done. */
1241                 }  else if (a->archive.archive_format
1242                     == ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
1243                         /* Definitely pax extended; must obey hardlink size. */
1244                 } else if (a->archive.archive_format == ARCHIVE_FORMAT_TAR
1245                     || a->archive.archive_format == ARCHIVE_FORMAT_TAR_GNUTAR)
1246                 {
1247                         /* Old-style or GNU tar: we must ignore the size. */
1248                         archive_entry_set_size(entry, 0);
1249                         tar->entry_bytes_remaining = 0;
1250                 } else if (archive_read_format_tar_bid(a, 50) > 50) {
1251                         /*
1252                          * We don't know if it's pax: If the bid
1253                          * function sees a valid ustar header
1254                          * immediately following, then let's ignore
1255                          * the hardlink size.
1256                          */
1257                         archive_entry_set_size(entry, 0);
1258                         tar->entry_bytes_remaining = 0;
1259                 }
1260                 /*
1261                  * TODO: There are still two cases I'd like to handle:
1262                  *   = a ustar non-pax archive with a hardlink entry at
1263                  *     end-of-archive.  (Look for block of nulls following?)
1264                  *   = a pax archive that has not seen any pax headers
1265                  *     and has an entry which is a hardlink entry storing
1266                  *     a body containing an uncompressed tar archive.
1267                  * The first is worth addressing; I don't see any reliable
1268                  * way to deal with the second possibility.
1269                  */
1270                 break;
1271         case '2': /* Symlink */
1272                 archive_entry_set_filetype(entry, AE_IFLNK);
1273                 archive_entry_set_size(entry, 0);
1274                 tar->entry_bytes_remaining = 0;
1275                 if (archive_entry_copy_symlink_l(entry, tar->entry_linkpath.s,
1276                     archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) {
1277                         err = set_conversion_failed_error(a, tar->sconv,
1278                             "Linkname");
1279                         if (err == ARCHIVE_FATAL)
1280                                 return (err);
1281                 }
1282                 break;
1283         case '3': /* Character device */
1284                 archive_entry_set_filetype(entry, AE_IFCHR);
1285                 archive_entry_set_size(entry, 0);
1286                 tar->entry_bytes_remaining = 0;
1287                 break;
1288         case '4': /* Block device */
1289                 archive_entry_set_filetype(entry, AE_IFBLK);
1290                 archive_entry_set_size(entry, 0);
1291                 tar->entry_bytes_remaining = 0;
1292                 break;
1293         case '5': /* Dir */
1294                 archive_entry_set_filetype(entry, AE_IFDIR);
1295                 archive_entry_set_size(entry, 0);
1296                 tar->entry_bytes_remaining = 0;
1297                 break;
1298         case '6': /* FIFO device */
1299                 archive_entry_set_filetype(entry, AE_IFIFO);
1300                 archive_entry_set_size(entry, 0);
1301                 tar->entry_bytes_remaining = 0;
1302                 break;
1303         case 'D': /* GNU incremental directory type */
1304                 /*
1305                  * No special handling is actually required here.
1306                  * It might be nice someday to preprocess the file list and
1307                  * provide it to the client, though.
1308                  */
1309                 archive_entry_set_filetype(entry, AE_IFDIR);
1310                 break;
1311         case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1312                 /*
1313                  * As far as I can tell, this is just like a regular file
1314                  * entry, except that the contents should be _appended_ to
1315                  * the indicated file at the indicated offset.  This may
1316                  * require some API work to fully support.
1317                  */
1318                 break;
1319         case 'N': /* Old GNU "long filename" entry. */
1320                 /* The body of this entry is a script for renaming
1321                  * previously-extracted entries.  Ugh.  It will never
1322                  * be supported by libarchive. */
1323                 archive_entry_set_filetype(entry, AE_IFREG);
1324                 break;
1325         case 'S': /* GNU sparse files */
1326                 /*
1327                  * Sparse files are really just regular files with
1328                  * sparse information in the extended area.
1329                  */
1330                 /* FALLTHROUGH */
1331         case '0':
1332                 /*
1333                  * Enable sparse file "read" support only for regular
1334                  * files and explicit GNU sparse files.  However, we
1335                  * don't allow non-standard file types to be sparse.
1336                  */
1337                 tar->sparse_allowed = 1;
1338                 /* FALLTHROUGH */
1339         default: /* Regular file  and non-standard types */
1340                 /*
1341                  * Per POSIX: non-recognized types should always be
1342                  * treated as regular files.
1343                  */
1344                 archive_entry_set_filetype(entry, AE_IFREG);
1345                 break;
1346         }
1347         return (err);
1348 }
1349
1350 /*
1351  * Parse out header elements for "old-style" tar archives.
1352  */
1353 static int
1354 header_old_tar(struct archive_read *a, struct tar *tar,
1355     struct archive_entry *entry, const void *h)
1356 {
1357         const struct archive_entry_header_ustar *header;
1358         int err = ARCHIVE_OK, err2;
1359
1360         /* Copy filename over (to ensure null termination). */
1361         header = (const struct archive_entry_header_ustar *)h;
1362         if (archive_entry_copy_pathname_l(entry,
1363             header->name, sizeof(header->name), tar->sconv) != 0) {
1364                 err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1365                 if (err == ARCHIVE_FATAL)
1366                         return (err);
1367         }
1368
1369         /* Grab rest of common fields */
1370         err2 = header_common(a, tar, entry, h);
1371         if (err > err2)
1372                 err = err2;
1373
1374         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1375         return (err);
1376 }
1377
1378 /*
1379  * Read a Mac AppleDouble-encoded blob of file metadata,
1380  * if there is one.
1381  */
1382 static int
1383 read_mac_metadata_blob(struct archive_read *a, struct tar *tar,
1384     struct archive_entry *entry, const void *h, size_t *unconsumed)
1385 {
1386         int64_t size;
1387         const void *data;
1388         const char *p, *name;
1389         const wchar_t *wp, *wname;
1390
1391         (void)h; /* UNUSED */
1392
1393         wname = wp = archive_entry_pathname_w(entry);
1394         if (wp != NULL) {
1395                 /* Find the last path element. */
1396                 for (; *wp != L'\0'; ++wp) {
1397                         if (wp[0] == '/' && wp[1] != L'\0')
1398                                 wname = wp + 1;
1399                 }
1400                 /*
1401                  * If last path element starts with "._", then
1402                  * this is a Mac extension.
1403                  */
1404                 if (wname[0] != L'.' || wname[1] != L'_' || wname[2] == L'\0')
1405                         return ARCHIVE_OK;
1406         } else {
1407                 /* Find the last path element. */
1408                 name = p = archive_entry_pathname(entry);
1409                 if (p == NULL)
1410                         return (ARCHIVE_FAILED);
1411                 for (; *p != '\0'; ++p) {
1412                         if (p[0] == '/' && p[1] != '\0')
1413                                 name = p + 1;
1414                 }
1415                 /*
1416                  * If last path element starts with "._", then
1417                  * this is a Mac extension.
1418                  */
1419                 if (name[0] != '.' || name[1] != '_' || name[2] == '\0')
1420                         return ARCHIVE_OK;
1421         }
1422
1423         /* Read the body as a Mac OS metadata blob. */
1424         size = archive_entry_size(entry);
1425
1426         /*
1427          * TODO: Look beyond the body here to peek at the next header.
1428          * If it's a regular header (not an extension header)
1429          * that has the wrong name, just return the current
1430          * entry as-is, without consuming the body here.
1431          * That would reduce the risk of us mis-identifying
1432          * an ordinary file that just happened to have
1433          * a name starting with "._".
1434          *
1435          * Q: Is the above idea really possible?  Even
1436          * when there are GNU or pax extension entries?
1437          */
1438         data = __archive_read_ahead(a, (size_t)size, NULL);
1439         if (data == NULL) {
1440                 *unconsumed = 0;
1441                 return (ARCHIVE_FATAL);
1442         }
1443         archive_entry_copy_mac_metadata(entry, data, (size_t)size);
1444         *unconsumed = (size_t)((size + 511) & ~ 511);
1445         tar_flush_unconsumed(a, unconsumed);
1446         return (tar_read_header(a, tar, entry, unconsumed));
1447 }
1448
1449 /*
1450  * Parse a file header for a pax extended archive entry.
1451  */
1452 static int
1453 header_pax_global(struct archive_read *a, struct tar *tar,
1454     struct archive_entry *entry, const void *h, size_t *unconsumed)
1455 {
1456         int err;
1457
1458         err = read_body_to_string(a, tar, &(tar->pax_global), h, unconsumed);
1459         if (err != ARCHIVE_OK)
1460                 return (err);
1461         err = tar_read_header(a, tar, entry, unconsumed);
1462         return (err);
1463 }
1464
1465 static int
1466 header_pax_extensions(struct archive_read *a, struct tar *tar,
1467     struct archive_entry *entry, const void *h, size_t *unconsumed)
1468 {
1469         int err, err2;
1470
1471         err = read_body_to_string(a, tar, &(tar->pax_header), h, unconsumed);
1472         if (err != ARCHIVE_OK)
1473                 return (err);
1474
1475         /* Parse the next header. */
1476         err = tar_read_header(a, tar, entry, unconsumed);
1477         if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1478                 return (err);
1479
1480         /*
1481          * TODO: Parse global/default options into 'entry' struct here
1482          * before handling file-specific options.
1483          *
1484          * This design (parse standard header, then overwrite with pax
1485          * extended attribute data) usually works well, but isn't ideal;
1486          * it would be better to parse the pax extended attributes first
1487          * and then skip any fields in the standard header that were
1488          * defined in the pax header.
1489          */
1490         err2 = pax_header(a, tar, entry, &tar->pax_header);
1491         err =  err_combine(err, err2);
1492         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1493         return (err);
1494 }
1495
1496
1497 /*
1498  * Parse a file header for a Posix "ustar" archive entry.  This also
1499  * handles "pax" or "extended ustar" entries.
1500  */
1501 static int
1502 header_ustar(struct archive_read *a, struct tar *tar,
1503     struct archive_entry *entry, const void *h)
1504 {
1505         const struct archive_entry_header_ustar *header;
1506         struct archive_string *as;
1507         int err = ARCHIVE_OK, r;
1508
1509         header = (const struct archive_entry_header_ustar *)h;
1510
1511         /* Copy name into an internal buffer to ensure null-termination. */
1512         as = &(tar->entry_pathname);
1513         if (header->prefix[0]) {
1514                 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1515                 if (as->s[archive_strlen(as) - 1] != '/')
1516                         archive_strappend_char(as, '/');
1517                 archive_strncat(as, header->name, sizeof(header->name));
1518         } else {
1519                 archive_strncpy(as, header->name, sizeof(header->name));
1520         }
1521         if (archive_entry_copy_pathname_l(entry, as->s, archive_strlen(as),
1522             tar->sconv) != 0) {
1523                 err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1524                 if (err == ARCHIVE_FATAL)
1525                         return (err);
1526         }
1527
1528         /* Handle rest of common fields. */
1529         r = header_common(a, tar, entry, h);
1530         if (r == ARCHIVE_FATAL)
1531                 return (r);
1532         if (r < err)
1533                 err = r;
1534
1535         /* Handle POSIX ustar fields. */
1536         if (archive_entry_copy_uname_l(entry,
1537             header->uname, sizeof(header->uname), tar->sconv) != 0) {
1538                 err = set_conversion_failed_error(a, tar->sconv, "Uname");
1539                 if (err == ARCHIVE_FATAL)
1540                         return (err);
1541         }
1542
1543         if (archive_entry_copy_gname_l(entry,
1544             header->gname, sizeof(header->gname), tar->sconv) != 0) {
1545                 err = set_conversion_failed_error(a, tar->sconv, "Gname");
1546                 if (err == ARCHIVE_FATAL)
1547                         return (err);
1548         }
1549
1550         /* Parse out device numbers only for char and block specials. */
1551         if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1552                 archive_entry_set_rdevmajor(entry, (dev_t)
1553                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1554                 archive_entry_set_rdevminor(entry, (dev_t)
1555                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1556         }
1557
1558         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1559
1560         return (err);
1561 }
1562
1563
1564 /*
1565  * Parse the pax extended attributes record.
1566  *
1567  * Returns non-zero if there's an error in the data.
1568  */
1569 static int
1570 pax_header(struct archive_read *a, struct tar *tar,
1571     struct archive_entry *entry, struct archive_string *in_as)
1572 {
1573         size_t attr_length, l, line_length, value_length;
1574         char *p;
1575         char *key, *value;
1576         struct archive_string *as;
1577         struct archive_string_conv *sconv;
1578         int err, err2;
1579         char *attr = in_as->s;
1580
1581         attr_length = in_as->length;
1582         tar->pax_hdrcharset_binary = 0;
1583         archive_string_empty(&(tar->entry_gname));
1584         archive_string_empty(&(tar->entry_linkpath));
1585         archive_string_empty(&(tar->entry_pathname));
1586         archive_string_empty(&(tar->entry_pathname_override));
1587         archive_string_empty(&(tar->entry_uname));
1588         err = ARCHIVE_OK;
1589         while (attr_length > 0) {
1590                 /* Parse decimal length field at start of line. */
1591                 line_length = 0;
1592                 l = attr_length;
1593                 p = attr; /* Record start of line. */
1594                 while (l>0) {
1595                         if (*p == ' ') {
1596                                 p++;
1597                                 l--;
1598                                 break;
1599                         }
1600                         if (*p < '0' || *p > '9') {
1601                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1602                                     "Ignoring malformed pax extended attributes");
1603                                 return (ARCHIVE_WARN);
1604                         }
1605                         line_length *= 10;
1606                         line_length += *p - '0';
1607                         if (line_length > 999999) {
1608                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1609                                     "Rejecting pax extended attribute > 1MB");
1610                                 return (ARCHIVE_WARN);
1611                         }
1612                         p++;
1613                         l--;
1614                 }
1615
1616                 /*
1617                  * Parsed length must be no bigger than available data,
1618                  * at least 1, and the last character of the line must
1619                  * be '\n'.
1620                  */
1621                 if (line_length > attr_length
1622                     || line_length < 1
1623                     || attr[line_length - 1] != '\n')
1624                 {
1625                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1626                             "Ignoring malformed pax extended attribute");
1627                         return (ARCHIVE_WARN);
1628                 }
1629
1630                 /* Null-terminate the line. */
1631                 attr[line_length - 1] = '\0';
1632
1633                 /* Find end of key and null terminate it. */
1634                 key = p;
1635                 if (key[0] == '=')
1636                         return (-1);
1637                 while (*p && *p != '=')
1638                         ++p;
1639                 if (*p == '\0') {
1640                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1641                             "Invalid pax extended attributes");
1642                         return (ARCHIVE_WARN);
1643                 }
1644                 *p = '\0';
1645
1646                 value = p + 1;
1647
1648                 /* Some values may be binary data */
1649                 value_length = attr + line_length - 1 - value;
1650
1651                 /* Identify this attribute and set it in the entry. */
1652                 err2 = pax_attribute(a, tar, entry, key, value, value_length);
1653                 if (err2 == ARCHIVE_FATAL)
1654                         return (err2);
1655                 err = err_combine(err, err2);
1656
1657                 /* Skip to next line */
1658                 attr += line_length;
1659                 attr_length -= line_length;
1660         }
1661
1662         /*
1663          * PAX format uses UTF-8 as default charset for its metadata
1664          * unless hdrcharset=BINARY is present in its header.
1665          * We apply the charset specified by the hdrcharset option only
1666          * when the hdrcharset attribute(in PAX header) is BINARY because
1667          * we respect the charset described in PAX header and BINARY also
1668          * means that metadata(filename,uname and gname) character-set
1669          * is unknown.
1670          */
1671         if (tar->pax_hdrcharset_binary)
1672                 sconv = tar->opt_sconv;
1673         else {
1674                 sconv = archive_string_conversion_from_charset(
1675                     &(a->archive), "UTF-8", 1);
1676                 if (sconv == NULL)
1677                         return (ARCHIVE_FATAL);
1678                 if (tar->compat_2x)
1679                         archive_string_conversion_set_opt(sconv,
1680                             SCONV_SET_OPT_UTF8_LIBARCHIVE2X);
1681         }
1682
1683         if (archive_strlen(&(tar->entry_gname)) > 0) {
1684                 if (archive_entry_copy_gname_l(entry, tar->entry_gname.s,
1685                     archive_strlen(&(tar->entry_gname)), sconv) != 0) {
1686                         err = set_conversion_failed_error(a, sconv, "Gname");
1687                         if (err == ARCHIVE_FATAL)
1688                                 return (err);
1689                         /* Use a converted an original name. */
1690                         archive_entry_copy_gname(entry, tar->entry_gname.s);
1691                 }
1692         }
1693         if (archive_strlen(&(tar->entry_linkpath)) > 0) {
1694                 if (archive_entry_copy_link_l(entry, tar->entry_linkpath.s,
1695                     archive_strlen(&(tar->entry_linkpath)), sconv) != 0) {
1696                         err = set_conversion_failed_error(a, sconv, "Linkname");
1697                         if (err == ARCHIVE_FATAL)
1698                                 return (err);
1699                         /* Use a converted an original name. */
1700                         archive_entry_copy_link(entry, tar->entry_linkpath.s);
1701                 }
1702         }
1703         /*
1704          * Some extensions (such as the GNU sparse file extensions)
1705          * deliberately store a synthetic name under the regular 'path'
1706          * attribute and the real file name under a different attribute.
1707          * Since we're supposed to not care about the order, we
1708          * have no choice but to store all of the various filenames
1709          * we find and figure it all out afterwards.  This is the
1710          * figuring out part.
1711          */
1712         as = NULL;
1713         if (archive_strlen(&(tar->entry_pathname_override)) > 0)
1714                 as = &(tar->entry_pathname_override);
1715         else if (archive_strlen(&(tar->entry_pathname)) > 0)
1716                 as = &(tar->entry_pathname);
1717         if (as != NULL) {
1718                 if (archive_entry_copy_pathname_l(entry, as->s,
1719                     archive_strlen(as), sconv) != 0) {
1720                         err = set_conversion_failed_error(a, sconv, "Pathname");
1721                         if (err == ARCHIVE_FATAL)
1722                                 return (err);
1723                         /* Use a converted an original name. */
1724                         archive_entry_copy_pathname(entry, as->s);
1725                 }
1726         }
1727         if (archive_strlen(&(tar->entry_uname)) > 0) {
1728                 if (archive_entry_copy_uname_l(entry, tar->entry_uname.s,
1729                     archive_strlen(&(tar->entry_uname)), sconv) != 0) {
1730                         err = set_conversion_failed_error(a, sconv, "Uname");
1731                         if (err == ARCHIVE_FATAL)
1732                                 return (err);
1733                         /* Use a converted an original name. */
1734                         archive_entry_copy_uname(entry, tar->entry_uname.s);
1735                 }
1736         }
1737         return (err);
1738 }
1739
1740 static int
1741 pax_attribute_xattr(struct archive_entry *entry,
1742         const char *name, const char *value)
1743 {
1744         char *name_decoded;
1745         void *value_decoded;
1746         size_t value_len;
1747
1748         if (strlen(name) < 18 || (memcmp(name, "LIBARCHIVE.xattr.", 17)) != 0)
1749                 return 3;
1750
1751         name += 17;
1752
1753         /* URL-decode name */
1754         name_decoded = url_decode(name);
1755         if (name_decoded == NULL)
1756                 return 2;
1757
1758         /* Base-64 decode value */
1759         value_decoded = base64_decode(value, strlen(value), &value_len);
1760         if (value_decoded == NULL) {
1761                 free(name_decoded);
1762                 return 1;
1763         }
1764
1765         archive_entry_xattr_add_entry(entry, name_decoded,
1766                 value_decoded, value_len);
1767
1768         free(name_decoded);
1769         free(value_decoded);
1770         return 0;
1771 }
1772
1773 static int
1774 pax_attribute_schily_xattr(struct archive_entry *entry,
1775         const char *name, const char *value, size_t value_length)
1776 {
1777         if (strlen(name) < 14 || (memcmp(name, "SCHILY.xattr.", 13)) != 0)
1778                 return 1;
1779
1780         name += 13;
1781
1782         archive_entry_xattr_add_entry(entry, name, value, value_length);
1783
1784         return 0;
1785 }
1786
1787 static int
1788 pax_attribute_acl(struct archive_read *a, struct tar *tar,
1789     struct archive_entry *entry, const char *value, int type)
1790 {
1791         int r;
1792         const char* errstr;
1793
1794         switch (type) {
1795         case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
1796                 errstr = "SCHILY.acl.access";
1797                 break;
1798         case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
1799                 errstr = "SCHILY.acl.default";
1800                 break;
1801         case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
1802                 errstr = "SCHILY.acl.ace";
1803                 break;
1804         default:
1805                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1806                     "Unknown ACL type: %d", type);
1807                 return(ARCHIVE_FATAL);
1808         }
1809
1810         if (tar->sconv_acl == NULL) {
1811                 tar->sconv_acl =
1812                     archive_string_conversion_from_charset(
1813                         &(a->archive), "UTF-8", 1);
1814                 if (tar->sconv_acl == NULL)
1815                         return (ARCHIVE_FATAL);
1816         }
1817
1818         r = archive_acl_from_text_l(archive_entry_acl(entry), value, type,
1819             tar->sconv_acl);
1820         if (r != ARCHIVE_OK) {
1821                 if (r == ARCHIVE_FATAL) {
1822                         archive_set_error(&a->archive, ENOMEM,
1823                             "%s %s", "Can't allocate memory for ",
1824                             errstr);
1825                         return (r);
1826                 }
1827                 archive_set_error(&a->archive,
1828                     ARCHIVE_ERRNO_MISC, "%s %s", "Parse error: ", errstr);
1829         }
1830         return (r);
1831 }
1832
1833 /*
1834  * Parse a single key=value attribute.  key/value pointers are
1835  * assumed to point into reasonably long-lived storage.
1836  *
1837  * Note that POSIX reserves all-lowercase keywords.  Vendor-specific
1838  * extensions should always have keywords of the form "VENDOR.attribute"
1839  * In particular, it's quite feasible to support many different
1840  * vendor extensions here.  I'm using "LIBARCHIVE" for extensions
1841  * unique to this library.
1842  *
1843  * Investigate other vendor-specific extensions and see if
1844  * any of them look useful.
1845  */
1846 static int
1847 pax_attribute(struct archive_read *a, struct tar *tar,
1848     struct archive_entry *entry, const char *key, const char *value, size_t value_length)
1849 {
1850         int64_t s;
1851         long n;
1852         int err = ARCHIVE_OK, r;
1853
1854 #ifndef __FreeBSD__
1855         if (value == NULL)
1856                 value = "";     /* Disable compiler warning; do not pass
1857                                  * NULL pointer to strlen().  */
1858 #endif
1859         switch (key[0]) {
1860         case 'G':
1861                 /* Reject GNU.sparse.* headers on non-regular files. */
1862                 if (strncmp(key, "GNU.sparse", 10) == 0 &&
1863                     !tar->sparse_allowed) {
1864                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1865                             "Non-regular file cannot be sparse");
1866                         return (ARCHIVE_FATAL);
1867                 }
1868
1869                 /* GNU "0.0" sparse pax format. */
1870                 if (strcmp(key, "GNU.sparse.numblocks") == 0) {
1871                         tar->sparse_offset = -1;
1872                         tar->sparse_numbytes = -1;
1873                         tar->sparse_gnu_major = 0;
1874                         tar->sparse_gnu_minor = 0;
1875                 }
1876                 if (strcmp(key, "GNU.sparse.offset") == 0) {
1877                         tar->sparse_offset = tar_atol10(value, strlen(value));
1878                         if (tar->sparse_numbytes != -1) {
1879                                 if (gnu_add_sparse_entry(a, tar,
1880                                     tar->sparse_offset, tar->sparse_numbytes)
1881                                     != ARCHIVE_OK)
1882                                         return (ARCHIVE_FATAL);
1883                                 tar->sparse_offset = -1;
1884                                 tar->sparse_numbytes = -1;
1885                         }
1886                 }
1887                 if (strcmp(key, "GNU.sparse.numbytes") == 0) {
1888                         tar->sparse_numbytes = tar_atol10(value, strlen(value));
1889                         if (tar->sparse_numbytes != -1) {
1890                                 if (gnu_add_sparse_entry(a, tar,
1891                                     tar->sparse_offset, tar->sparse_numbytes)
1892                                     != ARCHIVE_OK)
1893                                         return (ARCHIVE_FATAL);
1894                                 tar->sparse_offset = -1;
1895                                 tar->sparse_numbytes = -1;
1896                         }
1897                 }
1898                 if (strcmp(key, "GNU.sparse.size") == 0) {
1899                         tar->realsize = tar_atol10(value, strlen(value));
1900                         archive_entry_set_size(entry, tar->realsize);
1901                         tar->realsize_override = 1;
1902                 }
1903
1904                 /* GNU "0.1" sparse pax format. */
1905                 if (strcmp(key, "GNU.sparse.map") == 0) {
1906                         tar->sparse_gnu_major = 0;
1907                         tar->sparse_gnu_minor = 1;
1908                         if (gnu_sparse_01_parse(a, tar, value) != ARCHIVE_OK)
1909                                 return (ARCHIVE_WARN);
1910                 }
1911
1912                 /* GNU "1.0" sparse pax format */
1913                 if (strcmp(key, "GNU.sparse.major") == 0) {
1914                         tar->sparse_gnu_major = (int)tar_atol10(value, strlen(value));
1915                         tar->sparse_gnu_pending = 1;
1916                 }
1917                 if (strcmp(key, "GNU.sparse.minor") == 0) {
1918                         tar->sparse_gnu_minor = (int)tar_atol10(value, strlen(value));
1919                         tar->sparse_gnu_pending = 1;
1920                 }
1921                 if (strcmp(key, "GNU.sparse.name") == 0) {
1922                         /*
1923                          * The real filename; when storing sparse
1924                          * files, GNU tar puts a synthesized name into
1925                          * the regular 'path' attribute in an attempt
1926                          * to limit confusion. ;-)
1927                          */
1928                         archive_strcpy(&(tar->entry_pathname_override), value);
1929                 }
1930                 if (strcmp(key, "GNU.sparse.realsize") == 0) {
1931                         tar->realsize = tar_atol10(value, strlen(value));
1932                         archive_entry_set_size(entry, tar->realsize);
1933                         tar->realsize_override = 1;
1934                 }
1935                 break;
1936         case 'L':
1937                 /* Our extensions */
1938 /* TODO: Handle arbitrary extended attributes... */
1939 /*
1940                 if (strcmp(key, "LIBARCHIVE.xxxxxxx") == 0)
1941                         archive_entry_set_xxxxxx(entry, value);
1942 */
1943                 if (strcmp(key, "LIBARCHIVE.creationtime") == 0) {
1944                         pax_time(value, &s, &n);
1945                         archive_entry_set_birthtime(entry, s, n);
1946                 }
1947                 if (memcmp(key, "LIBARCHIVE.xattr.", 17) == 0)
1948                         pax_attribute_xattr(entry, key, value);
1949                 break;
1950         case 'S':
1951                 /* We support some keys used by the "star" archiver */
1952                 if (strcmp(key, "SCHILY.acl.access") == 0) {
1953                         r = pax_attribute_acl(a, tar, entry, value,
1954                             ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1955                         if (r == ARCHIVE_FATAL)
1956                                 return (r);
1957                 } else if (strcmp(key, "SCHILY.acl.default") == 0) {
1958                         r = pax_attribute_acl(a, tar, entry, value,
1959                             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1960                         if (r == ARCHIVE_FATAL)
1961                                 return (r);
1962                 } else if (strcmp(key, "SCHILY.acl.ace") == 0) {
1963                         r = pax_attribute_acl(a, tar, entry, value,
1964                             ARCHIVE_ENTRY_ACL_TYPE_NFS4);
1965                         if (r == ARCHIVE_FATAL)
1966                                 return (r);
1967                 } else if (strcmp(key, "SCHILY.devmajor") == 0) {
1968                         archive_entry_set_rdevmajor(entry,
1969                             (dev_t)tar_atol10(value, strlen(value)));
1970                 } else if (strcmp(key, "SCHILY.devminor") == 0) {
1971                         archive_entry_set_rdevminor(entry,
1972                             (dev_t)tar_atol10(value, strlen(value)));
1973                 } else if (strcmp(key, "SCHILY.fflags") == 0) {
1974                         archive_entry_copy_fflags_text(entry, value);
1975                 } else if (strcmp(key, "SCHILY.dev") == 0) {
1976                         archive_entry_set_dev(entry,
1977                             (dev_t)tar_atol10(value, strlen(value)));
1978                 } else if (strcmp(key, "SCHILY.ino") == 0) {
1979                         archive_entry_set_ino(entry,
1980                             tar_atol10(value, strlen(value)));
1981                 } else if (strcmp(key, "SCHILY.nlink") == 0) {
1982                         archive_entry_set_nlink(entry, (unsigned)
1983                             tar_atol10(value, strlen(value)));
1984                 } else if (strcmp(key, "SCHILY.realsize") == 0) {
1985                         tar->realsize = tar_atol10(value, strlen(value));
1986                         tar->realsize_override = 1;
1987                         archive_entry_set_size(entry, tar->realsize);
1988                 } else if (strncmp(key, "SCHILY.xattr.", 13) == 0) {
1989                         pax_attribute_schily_xattr(entry, key, value,
1990                             value_length);
1991                 } else if (strcmp(key, "SUN.holesdata") == 0) {
1992                         /* A Solaris extension for sparse. */
1993                         r = solaris_sparse_parse(a, tar, entry, value);
1994                         if (r < err) {
1995                                 if (r == ARCHIVE_FATAL)
1996                                         return (r);
1997                                 err = r;
1998                                 archive_set_error(&a->archive,
1999                                     ARCHIVE_ERRNO_MISC,
2000                                     "Parse error: SUN.holesdata");
2001                         }
2002                 }
2003                 break;
2004         case 'a':
2005                 if (strcmp(key, "atime") == 0) {
2006                         pax_time(value, &s, &n);
2007                         archive_entry_set_atime(entry, s, n);
2008                 }
2009                 break;
2010         case 'c':
2011                 if (strcmp(key, "ctime") == 0) {
2012                         pax_time(value, &s, &n);
2013                         archive_entry_set_ctime(entry, s, n);
2014                 } else if (strcmp(key, "charset") == 0) {
2015                         /* TODO: Publish charset information in entry. */
2016                 } else if (strcmp(key, "comment") == 0) {
2017                         /* TODO: Publish comment in entry. */
2018                 }
2019                 break;
2020         case 'g':
2021                 if (strcmp(key, "gid") == 0) {
2022                         archive_entry_set_gid(entry,
2023                             tar_atol10(value, strlen(value)));
2024                 } else if (strcmp(key, "gname") == 0) {
2025                         archive_strcpy(&(tar->entry_gname), value);
2026                 }
2027                 break;
2028         case 'h':
2029                 if (strcmp(key, "hdrcharset") == 0) {
2030                         if (strcmp(value, "BINARY") == 0)
2031                                 /* Binary  mode. */
2032                                 tar->pax_hdrcharset_binary = 1;
2033                         else if (strcmp(value, "ISO-IR 10646 2000 UTF-8") == 0)
2034                                 tar->pax_hdrcharset_binary = 0;
2035                 }
2036                 break;
2037         case 'l':
2038                 /* pax interchange doesn't distinguish hardlink vs. symlink. */
2039                 if (strcmp(key, "linkpath") == 0) {
2040                         archive_strcpy(&(tar->entry_linkpath), value);
2041                 }
2042                 break;
2043         case 'm':
2044                 if (strcmp(key, "mtime") == 0) {
2045                         pax_time(value, &s, &n);
2046                         archive_entry_set_mtime(entry, s, n);
2047                 }
2048                 break;
2049         case 'p':
2050                 if (strcmp(key, "path") == 0) {
2051                         archive_strcpy(&(tar->entry_pathname), value);
2052                 }
2053                 break;
2054         case 'r':
2055                 /* POSIX has reserved 'realtime.*' */
2056                 break;
2057         case 's':
2058                 /* POSIX has reserved 'security.*' */
2059                 /* Someday: if (strcmp(key, "security.acl") == 0) { ... } */
2060                 if (strcmp(key, "size") == 0) {
2061                         /* "size" is the size of the data in the entry. */
2062                         tar->entry_bytes_remaining
2063                             = tar_atol10(value, strlen(value));
2064                         /*
2065                          * The "size" pax header keyword always overrides the
2066                          * "size" field in the tar header.
2067                          * GNU.sparse.realsize, GNU.sparse.size and
2068                          * SCHILY.realsize override this value.
2069                          */
2070                         if (!tar->realsize_override) {
2071                                 archive_entry_set_size(entry,
2072                                     tar->entry_bytes_remaining);
2073                                 tar->realsize
2074                                     = tar->entry_bytes_remaining;
2075                         }
2076                 }
2077                 break;
2078         case 'u':
2079                 if (strcmp(key, "uid") == 0) {
2080                         archive_entry_set_uid(entry,
2081                             tar_atol10(value, strlen(value)));
2082                 } else if (strcmp(key, "uname") == 0) {
2083                         archive_strcpy(&(tar->entry_uname), value);
2084                 }
2085                 break;
2086         }
2087         return (err);
2088 }
2089
2090
2091
2092 /*
2093  * parse a decimal time value, which may include a fractional portion
2094  */
2095 static void
2096 pax_time(const char *p, int64_t *ps, long *pn)
2097 {
2098         char digit;
2099         int64_t s;
2100         unsigned long l;
2101         int sign;
2102         int64_t limit, last_digit_limit;
2103
2104         limit = INT64_MAX / 10;
2105         last_digit_limit = INT64_MAX % 10;
2106
2107         s = 0;
2108         sign = 1;
2109         if (*p == '-') {
2110                 sign = -1;
2111                 p++;
2112         }
2113         while (*p >= '0' && *p <= '9') {
2114                 digit = *p - '0';
2115                 if (s > limit ||
2116                     (s == limit && digit > last_digit_limit)) {
2117                         s = INT64_MAX;
2118                         break;
2119                 }
2120                 s = (s * 10) + digit;
2121                 ++p;
2122         }
2123
2124         *ps = s * sign;
2125
2126         /* Calculate nanoseconds. */
2127         *pn = 0;
2128
2129         if (*p != '.')
2130                 return;
2131
2132         l = 100000000UL;
2133         do {
2134                 ++p;
2135                 if (*p >= '0' && *p <= '9')
2136                         *pn += (*p - '0') * l;
2137                 else
2138                         break;
2139         } while (l /= 10);
2140 }
2141
2142 /*
2143  * Parse GNU tar header
2144  */
2145 static int
2146 header_gnutar(struct archive_read *a, struct tar *tar,
2147     struct archive_entry *entry, const void *h, size_t *unconsumed)
2148 {
2149         const struct archive_entry_header_gnutar *header;
2150         int64_t t;
2151         int err = ARCHIVE_OK;
2152
2153         /*
2154          * GNU header is like POSIX ustar, except 'prefix' is
2155          * replaced with some other fields. This also means the
2156          * filename is stored as in old-style archives.
2157          */
2158
2159         /* Grab fields common to all tar variants. */
2160         err = header_common(a, tar, entry, h);
2161         if (err == ARCHIVE_FATAL)
2162                 return (err);
2163
2164         /* Copy filename over (to ensure null termination). */
2165         header = (const struct archive_entry_header_gnutar *)h;
2166         if (archive_entry_copy_pathname_l(entry,
2167             header->name, sizeof(header->name), tar->sconv) != 0) {
2168                 err = set_conversion_failed_error(a, tar->sconv, "Pathname");
2169                 if (err == ARCHIVE_FATAL)
2170                         return (err);
2171         }
2172
2173         /* Fields common to ustar and GNU */
2174         /* XXX Can the following be factored out since it's common
2175          * to ustar and gnu tar?  Is it okay to move it down into
2176          * header_common, perhaps?  */
2177         if (archive_entry_copy_uname_l(entry,
2178             header->uname, sizeof(header->uname), tar->sconv) != 0) {
2179                 err = set_conversion_failed_error(a, tar->sconv, "Uname");
2180                 if (err == ARCHIVE_FATAL)
2181                         return (err);
2182         }
2183
2184         if (archive_entry_copy_gname_l(entry,
2185             header->gname, sizeof(header->gname), tar->sconv) != 0) {
2186                 err = set_conversion_failed_error(a, tar->sconv, "Gname");
2187                 if (err == ARCHIVE_FATAL)
2188                         return (err);
2189         }
2190
2191         /* Parse out device numbers only for char and block specials */
2192         if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
2193                 archive_entry_set_rdevmajor(entry, (dev_t)
2194                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
2195                 archive_entry_set_rdevminor(entry, (dev_t)
2196                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
2197         } else
2198                 archive_entry_set_rdev(entry, 0);
2199
2200         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
2201
2202         /* Grab GNU-specific fields. */
2203         t = tar_atol(header->atime, sizeof(header->atime));
2204         if (t > 0)
2205                 archive_entry_set_atime(entry, t, 0);
2206         t = tar_atol(header->ctime, sizeof(header->ctime));
2207         if (t > 0)
2208                 archive_entry_set_ctime(entry, t, 0);
2209
2210         if (header->realsize[0] != 0) {
2211                 tar->realsize
2212                     = tar_atol(header->realsize, sizeof(header->realsize));
2213                 archive_entry_set_size(entry, tar->realsize);
2214                 tar->realsize_override = 1;
2215         }
2216
2217         if (header->sparse[0].offset[0] != 0) {
2218                 if (gnu_sparse_old_read(a, tar, header, unconsumed)
2219                     != ARCHIVE_OK)
2220                         return (ARCHIVE_FATAL);
2221         } else {
2222                 if (header->isextended[0] != 0) {
2223                         /* XXX WTF? XXX */
2224                 }
2225         }
2226
2227         return (err);
2228 }
2229
2230 static int
2231 gnu_add_sparse_entry(struct archive_read *a, struct tar *tar,
2232     int64_t offset, int64_t remaining)
2233 {
2234         struct sparse_block *p;
2235
2236         p = (struct sparse_block *)calloc(1, sizeof(*p));
2237         if (p == NULL) {
2238                 archive_set_error(&a->archive, ENOMEM, "Out of memory");
2239                 return (ARCHIVE_FATAL);
2240         }
2241         if (tar->sparse_last != NULL)
2242                 tar->sparse_last->next = p;
2243         else
2244                 tar->sparse_list = p;
2245         tar->sparse_last = p;
2246         if (remaining < 0 || offset < 0 || offset > INT64_MAX - remaining) {
2247                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed sparse map data");
2248                 return (ARCHIVE_FATAL);
2249         }
2250         p->offset = offset;
2251         p->remaining = remaining;
2252         return (ARCHIVE_OK);
2253 }
2254
2255 static void
2256 gnu_clear_sparse_list(struct tar *tar)
2257 {
2258         struct sparse_block *p;
2259
2260         while (tar->sparse_list != NULL) {
2261                 p = tar->sparse_list;
2262                 tar->sparse_list = p->next;
2263                 free(p);
2264         }
2265         tar->sparse_last = NULL;
2266 }
2267
2268 /*
2269  * GNU tar old-format sparse data.
2270  *
2271  * GNU old-format sparse data is stored in a fixed-field
2272  * format.  Offset/size values are 11-byte octal fields (same
2273  * format as 'size' field in ustart header).  These are
2274  * stored in the header, allocating subsequent header blocks
2275  * as needed.  Extending the header in this way is a pretty
2276  * severe POSIX violation; this design has earned GNU tar a
2277  * lot of criticism.
2278  */
2279
2280 static int
2281 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
2282     const struct archive_entry_header_gnutar *header, size_t *unconsumed)
2283 {
2284         ssize_t bytes_read;
2285         const void *data;
2286         struct extended {
2287                 struct gnu_sparse sparse[21];
2288                 char    isextended[1];
2289                 char    padding[7];
2290         };
2291         const struct extended *ext;
2292
2293         if (gnu_sparse_old_parse(a, tar, header->sparse, 4) != ARCHIVE_OK)
2294                 return (ARCHIVE_FATAL);
2295         if (header->isextended[0] == 0)
2296                 return (ARCHIVE_OK);
2297
2298         do {
2299                 tar_flush_unconsumed(a, unconsumed);
2300                 data = __archive_read_ahead(a, 512, &bytes_read);
2301                 if (bytes_read < 0)
2302                         return (ARCHIVE_FATAL);
2303                 if (bytes_read < 512) {
2304                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2305                             "Truncated tar archive "
2306                             "detected while reading sparse file data");
2307                         return (ARCHIVE_FATAL);
2308                 }
2309                 *unconsumed = 512;
2310                 ext = (const struct extended *)data;
2311                 if (gnu_sparse_old_parse(a, tar, ext->sparse, 21) != ARCHIVE_OK)
2312                         return (ARCHIVE_FATAL);
2313         } while (ext->isextended[0] != 0);
2314         if (tar->sparse_list != NULL)
2315                 tar->entry_offset = tar->sparse_list->offset;
2316         return (ARCHIVE_OK);
2317 }
2318
2319 static int
2320 gnu_sparse_old_parse(struct archive_read *a, struct tar *tar,
2321     const struct gnu_sparse *sparse, int length)
2322 {
2323         while (length > 0 && sparse->offset[0] != 0) {
2324                 if (gnu_add_sparse_entry(a, tar,
2325                     tar_atol(sparse->offset, sizeof(sparse->offset)),
2326                     tar_atol(sparse->numbytes, sizeof(sparse->numbytes)))
2327                     != ARCHIVE_OK)
2328                         return (ARCHIVE_FATAL);
2329                 sparse++;
2330                 length--;
2331         }
2332         return (ARCHIVE_OK);
2333 }
2334
2335 /*
2336  * GNU tar sparse format 0.0
2337  *
2338  * Beginning with GNU tar 1.15, sparse files are stored using
2339  * information in the pax extended header.  The GNU tar maintainers
2340  * have gone through a number of variations in the process of working
2341  * out this scheme; fortunately, they're all numbered.
2342  *
2343  * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
2344  * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
2345  * store offset/size for each block.  The repeated instances of these
2346  * latter fields violate the pax specification (which frowns on
2347  * duplicate keys), so this format was quickly replaced.
2348  */
2349
2350 /*
2351  * GNU tar sparse format 0.1
2352  *
2353  * This version replaced the offset/numbytes attributes with
2354  * a single "map" attribute that stored a list of integers.  This
2355  * format had two problems: First, the "map" attribute could be very
2356  * long, which caused problems for some implementations.  More
2357  * importantly, the sparse data was lost when extracted by archivers
2358  * that didn't recognize this extension.
2359  */
2360
2361 static int
2362 gnu_sparse_01_parse(struct archive_read *a, struct tar *tar, const char *p)
2363 {
2364         const char *e;
2365         int64_t offset = -1, size = -1;
2366
2367         for (;;) {
2368                 e = p;
2369                 while (*e != '\0' && *e != ',') {
2370                         if (*e < '0' || *e > '9')
2371                                 return (ARCHIVE_WARN);
2372                         e++;
2373                 }
2374                 if (offset < 0) {
2375                         offset = tar_atol10(p, e - p);
2376                         if (offset < 0)
2377                                 return (ARCHIVE_WARN);
2378                 } else {
2379                         size = tar_atol10(p, e - p);
2380                         if (size < 0)
2381                                 return (ARCHIVE_WARN);
2382                         if (gnu_add_sparse_entry(a, tar, offset, size)
2383                             != ARCHIVE_OK)
2384                                 return (ARCHIVE_FATAL);
2385                         offset = -1;
2386                 }
2387                 if (*e == '\0')
2388                         return (ARCHIVE_OK);
2389                 p = e + 1;
2390         }
2391 }
2392
2393 /*
2394  * GNU tar sparse format 1.0
2395  *
2396  * The idea: The offset/size data is stored as a series of base-10
2397  * ASCII numbers prepended to the file data, so that dearchivers that
2398  * don't support this format will extract the block map along with the
2399  * data and a separate post-process can restore the sparseness.
2400  *
2401  * Unfortunately, GNU tar 1.16 had a bug that added unnecessary
2402  * padding to the body of the file when using this format.  GNU tar
2403  * 1.17 corrected this bug without bumping the version number, so
2404  * it's not possible to support both variants.  This code supports
2405  * the later variant at the expense of not supporting the former.
2406  *
2407  * This variant also replaced GNU.sparse.size with GNU.sparse.realsize
2408  * and introduced the GNU.sparse.major/GNU.sparse.minor attributes.
2409  */
2410
2411 /*
2412  * Read the next line from the input, and parse it as a decimal
2413  * integer followed by '\n'.  Returns positive integer value or
2414  * negative on error.
2415  */
2416 static int64_t
2417 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
2418     int64_t *remaining, size_t *unconsumed)
2419 {
2420         int64_t l, limit, last_digit_limit;
2421         const char *p;
2422         ssize_t bytes_read;
2423         int base, digit;
2424
2425         base = 10;
2426         limit = INT64_MAX / base;
2427         last_digit_limit = INT64_MAX % base;
2428
2429         /*
2430          * Skip any lines starting with '#'; GNU tar specs
2431          * don't require this, but they should.
2432          */
2433         do {
2434                 bytes_read = readline(a, tar, &p,
2435                         (ssize_t)tar_min(*remaining, 100), unconsumed);
2436                 if (bytes_read <= 0)
2437                         return (ARCHIVE_FATAL);
2438                 *remaining -= bytes_read;
2439         } while (p[0] == '#');
2440
2441         l = 0;
2442         while (bytes_read > 0) {
2443                 if (*p == '\n')
2444                         return (l);
2445                 if (*p < '0' || *p >= '0' + base)
2446                         return (ARCHIVE_WARN);
2447                 digit = *p - '0';
2448                 if (l > limit || (l == limit && digit > last_digit_limit))
2449                         l = INT64_MAX; /* Truncate on overflow. */
2450                 else
2451                         l = (l * base) + digit;
2452                 p++;
2453                 bytes_read--;
2454         }
2455         /* TODO: Error message. */
2456         return (ARCHIVE_WARN);
2457 }
2458
2459 /*
2460  * Returns length (in bytes) of the sparse data description
2461  * that was read.
2462  */
2463 static ssize_t
2464 gnu_sparse_10_read(struct archive_read *a, struct tar *tar, size_t *unconsumed)
2465 {
2466         ssize_t bytes_read;
2467         int entries;
2468         int64_t offset, size, to_skip, remaining;
2469
2470         /* Clear out the existing sparse list. */
2471         gnu_clear_sparse_list(tar);
2472
2473         remaining = tar->entry_bytes_remaining;
2474
2475         /* Parse entries. */
2476         entries = (int)gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2477         if (entries < 0)
2478                 return (ARCHIVE_FATAL);
2479         /* Parse the individual entries. */
2480         while (entries-- > 0) {
2481                 /* Parse offset/size */
2482                 offset = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2483                 if (offset < 0)
2484                         return (ARCHIVE_FATAL);
2485                 size = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2486                 if (size < 0)
2487                         return (ARCHIVE_FATAL);
2488                 /* Add a new sparse entry. */
2489                 if (gnu_add_sparse_entry(a, tar, offset, size) != ARCHIVE_OK)
2490                         return (ARCHIVE_FATAL);
2491         }
2492         /* Skip rest of block... */
2493         tar_flush_unconsumed(a, unconsumed);
2494         bytes_read = (ssize_t)(tar->entry_bytes_remaining - remaining);
2495         to_skip = 0x1ff & -bytes_read;
2496         /* Fail if tar->entry_bytes_remaing would get negative */
2497         if (to_skip > remaining)
2498                 return (ARCHIVE_FATAL);
2499         if (to_skip != __archive_read_consume(a, to_skip))
2500                 return (ARCHIVE_FATAL);
2501         return ((ssize_t)(bytes_read + to_skip));
2502 }
2503
2504 /*
2505  * Solaris pax extension for a sparse file. This is recorded with the
2506  * data and hole pairs. The way recording sparse information by Solaris'
2507  * pax simply indicates where data and sparse are, so the stored contents
2508  * consist of both data and hole.
2509  */
2510 static int
2511 solaris_sparse_parse(struct archive_read *a, struct tar *tar,
2512     struct archive_entry *entry, const char *p)
2513 {
2514         const char *e;
2515         int64_t start, end;
2516         int hole = 1;
2517
2518         (void)entry; /* UNUSED */
2519
2520         end = 0;
2521         if (*p == ' ')
2522                 p++;
2523         else
2524                 return (ARCHIVE_WARN);
2525         for (;;) {
2526                 e = p;
2527                 while (*e != '\0' && *e != ' ') {
2528                         if (*e < '0' || *e > '9')
2529                                 return (ARCHIVE_WARN);
2530                         e++;
2531                 }
2532                 start = end;
2533                 end = tar_atol10(p, e - p);
2534                 if (end < 0)
2535                         return (ARCHIVE_WARN);
2536                 if (start < end) {
2537                         if (gnu_add_sparse_entry(a, tar, start,
2538                             end - start) != ARCHIVE_OK)
2539                                 return (ARCHIVE_FATAL);
2540                         tar->sparse_last->hole = hole;
2541                 }
2542                 if (*e == '\0')
2543                         return (ARCHIVE_OK);
2544                 p = e + 1;
2545                 hole = hole == 0;
2546         }
2547 }
2548
2549 /*-
2550  * Convert text->integer.
2551  *
2552  * Traditional tar formats (including POSIX) specify base-8 for
2553  * all of the standard numeric fields.  This is a significant limitation
2554  * in practice:
2555  *   = file size is limited to 8GB
2556  *   = rdevmajor and rdevminor are limited to 21 bits
2557  *   = uid/gid are limited to 21 bits
2558  *
2559  * There are two workarounds for this:
2560  *   = pax extended headers, which use variable-length string fields
2561  *   = GNU tar and STAR both allow either base-8 or base-256 in
2562  *      most fields.  The high bit is set to indicate base-256.
2563  *
2564  * On read, this implementation supports both extensions.
2565  */
2566 static int64_t
2567 tar_atol(const char *p, size_t char_cnt)
2568 {
2569         /*
2570          * Technically, GNU tar considers a field to be in base-256
2571          * only if the first byte is 0xff or 0x80.
2572          */
2573         if (*p & 0x80)
2574                 return (tar_atol256(p, char_cnt));
2575         return (tar_atol8(p, char_cnt));
2576 }
2577
2578 /*
2579  * Note that this implementation does not (and should not!) obey
2580  * locale settings; you cannot simply substitute strtol here, since
2581  * it does obey locale.
2582  */
2583 static int64_t
2584 tar_atol_base_n(const char *p, size_t char_cnt, int base)
2585 {
2586         int64_t l, maxval, limit, last_digit_limit;
2587         int digit, sign;
2588
2589         maxval = INT64_MAX;
2590         limit = INT64_MAX / base;
2591         last_digit_limit = INT64_MAX % base;
2592
2593         /* the pointer will not be dereferenced if char_cnt is zero
2594          * due to the way the && operator is evaluated.
2595          */
2596         while (char_cnt != 0 && (*p == ' ' || *p == '\t')) {
2597                 p++;
2598                 char_cnt--;
2599         }
2600
2601         sign = 1;
2602         if (char_cnt != 0 && *p == '-') {
2603                 sign = -1;
2604                 p++;
2605                 char_cnt--;
2606
2607                 maxval = INT64_MIN;
2608                 limit = -(INT64_MIN / base);
2609                 last_digit_limit = INT64_MIN % base;
2610         }
2611
2612         l = 0;
2613         if (char_cnt != 0) {
2614                 digit = *p - '0';
2615                 while (digit >= 0 && digit < base  && char_cnt != 0) {
2616                         if (l>limit || (l == limit && digit > last_digit_limit)) {
2617                                 return maxval; /* Truncate on overflow. */
2618                         }
2619                         l = (l * base) + digit;
2620                         digit = *++p - '0';
2621                         char_cnt--;
2622                 }
2623         }
2624         return (sign < 0) ? -l : l;
2625 }
2626
2627 static int64_t
2628 tar_atol8(const char *p, size_t char_cnt)
2629 {
2630         return tar_atol_base_n(p, char_cnt, 8);
2631 }
2632
2633 static int64_t
2634 tar_atol10(const char *p, size_t char_cnt)
2635 {
2636         return tar_atol_base_n(p, char_cnt, 10);
2637 }
2638
2639 /*
2640  * Parse a base-256 integer.  This is just a variable-length
2641  * twos-complement signed binary value in big-endian order, except
2642  * that the high-order bit is ignored.  The values here can be up to
2643  * 12 bytes, so we need to be careful about overflowing 64-bit
2644  * (8-byte) integers.
2645  *
2646  * This code unashamedly assumes that the local machine uses 8-bit
2647  * bytes and twos-complement arithmetic.
2648  */
2649 static int64_t
2650 tar_atol256(const char *_p, size_t char_cnt)
2651 {
2652         uint64_t l;
2653         const unsigned char *p = (const unsigned char *)_p;
2654         unsigned char c, neg;
2655
2656         /* Extend 7-bit 2s-comp to 8-bit 2s-comp, decide sign. */
2657         c = *p;
2658         if (c & 0x40) {
2659                 neg = 0xff;
2660                 c |= 0x80;
2661                 l = ~ARCHIVE_LITERAL_ULL(0);
2662         } else {
2663                 neg = 0;
2664                 c &= 0x7f;
2665                 l = 0;
2666         }
2667
2668         /* If more than 8 bytes, check that we can ignore
2669          * high-order bits without overflow. */
2670         while (char_cnt > sizeof(int64_t)) {
2671                 --char_cnt;
2672                 if (c != neg)
2673                         return neg ? INT64_MIN : INT64_MAX;
2674                 c = *++p;
2675         }
2676
2677         /* c is first byte that fits; if sign mismatch, return overflow */
2678         if ((c ^ neg) & 0x80) {
2679                 return neg ? INT64_MIN : INT64_MAX;
2680         }
2681
2682         /* Accumulate remaining bytes. */
2683         while (--char_cnt > 0) {
2684                 l = (l << 8) | c;
2685                 c = *++p;
2686         }
2687         l = (l << 8) | c;
2688         /* Return signed twos-complement value. */
2689         return (int64_t)(l);
2690 }
2691
2692 /*
2693  * Returns length of line (including trailing newline)
2694  * or negative on error.  'start' argument is updated to
2695  * point to first character of line.  This avoids copying
2696  * when possible.
2697  */
2698 static ssize_t
2699 readline(struct archive_read *a, struct tar *tar, const char **start,
2700     ssize_t limit, size_t *unconsumed)
2701 {
2702         ssize_t bytes_read;
2703         ssize_t total_size = 0;
2704         const void *t;
2705         const char *s;
2706         void *p;
2707
2708         tar_flush_unconsumed(a, unconsumed);
2709
2710         t = __archive_read_ahead(a, 1, &bytes_read);
2711         if (bytes_read <= 0)
2712                 return (ARCHIVE_FATAL);
2713         s = t;  /* Start of line? */
2714         p = memchr(t, '\n', bytes_read);
2715         /* If we found '\n' in the read buffer, return pointer to that. */
2716         if (p != NULL) {
2717                 bytes_read = 1 + ((const char *)p) - s;
2718                 if (bytes_read > limit) {
2719                         archive_set_error(&a->archive,
2720                             ARCHIVE_ERRNO_FILE_FORMAT,
2721                             "Line too long");
2722                         return (ARCHIVE_FATAL);
2723                 }
2724                 *unconsumed = bytes_read;
2725                 *start = s;
2726                 return (bytes_read);
2727         }
2728         *unconsumed = bytes_read;
2729         /* Otherwise, we need to accumulate in a line buffer. */
2730         for (;;) {
2731                 if (total_size + bytes_read > limit) {
2732                         archive_set_error(&a->archive,
2733                             ARCHIVE_ERRNO_FILE_FORMAT,
2734                             "Line too long");
2735                         return (ARCHIVE_FATAL);
2736                 }
2737                 if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
2738                         archive_set_error(&a->archive, ENOMEM,
2739                             "Can't allocate working buffer");
2740                         return (ARCHIVE_FATAL);
2741                 }
2742                 memcpy(tar->line.s + total_size, t, bytes_read);
2743                 tar_flush_unconsumed(a, unconsumed);
2744                 total_size += bytes_read;
2745                 /* If we found '\n', clean up and return. */
2746                 if (p != NULL) {
2747                         *start = tar->line.s;
2748                         return (total_size);
2749                 }
2750                 /* Read some more. */
2751                 t = __archive_read_ahead(a, 1, &bytes_read);
2752                 if (bytes_read <= 0)
2753                         return (ARCHIVE_FATAL);
2754                 s = t;  /* Start of line? */
2755                 p = memchr(t, '\n', bytes_read);
2756                 /* If we found '\n', trim the read. */
2757                 if (p != NULL) {
2758                         bytes_read = 1 + ((const char *)p) - s;
2759                 }
2760                 *unconsumed = bytes_read;
2761         }
2762 }
2763
2764 /*
2765  * base64_decode - Base64 decode
2766  *
2767  * This accepts most variations of base-64 encoding, including:
2768  *    * with or without line breaks
2769  *    * with or without the final group padded with '=' or '_' characters
2770  * (The most economical Base-64 variant does not pad the last group and
2771  * omits line breaks; RFC1341 used for MIME requires both.)
2772  */
2773 static char *
2774 base64_decode(const char *s, size_t len, size_t *out_len)
2775 {
2776         static const unsigned char digits[64] = {
2777                 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
2778                 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
2779                 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
2780                 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
2781                 '4','5','6','7','8','9','+','/' };
2782         static unsigned char decode_table[128];
2783         char *out, *d;
2784         const unsigned char *src = (const unsigned char *)s;
2785
2786         /* If the decode table is not yet initialized, prepare it. */
2787         if (decode_table[digits[1]] != 1) {
2788                 unsigned i;
2789                 memset(decode_table, 0xff, sizeof(decode_table));
2790                 for (i = 0; i < sizeof(digits); i++)
2791                         decode_table[digits[i]] = i;
2792         }
2793
2794         /* Allocate enough space to hold the entire output. */
2795         /* Note that we may not use all of this... */
2796         out = (char *)malloc(len - len / 4 + 1);
2797         if (out == NULL) {
2798                 *out_len = 0;
2799                 return (NULL);
2800         }
2801         d = out;
2802
2803         while (len > 0) {
2804                 /* Collect the next group of (up to) four characters. */
2805                 int v = 0;
2806                 int group_size = 0;
2807                 while (group_size < 4 && len > 0) {
2808                         /* '=' or '_' padding indicates final group. */
2809                         if (*src == '=' || *src == '_') {
2810                                 len = 0;
2811                                 break;
2812                         }
2813                         /* Skip illegal characters (including line breaks) */
2814                         if (*src > 127 || *src < 32
2815                             || decode_table[*src] == 0xff) {
2816                                 len--;
2817                                 src++;
2818                                 continue;
2819                         }
2820                         v <<= 6;
2821                         v |= decode_table[*src++];
2822                         len --;
2823                         group_size++;
2824                 }
2825                 /* Align a short group properly. */
2826                 v <<= 6 * (4 - group_size);
2827                 /* Unpack the group we just collected. */
2828                 switch (group_size) {
2829                 case 4: d[2] = v & 0xff;
2830                         /* FALLTHROUGH */
2831                 case 3: d[1] = (v >> 8) & 0xff;
2832                         /* FALLTHROUGH */
2833                 case 2: d[0] = (v >> 16) & 0xff;
2834                         break;
2835                 case 1: /* this is invalid! */
2836                         break;
2837                 }
2838                 d += group_size * 3 / 4;
2839         }
2840
2841         *out_len = d - out;
2842         return (out);
2843 }
2844
2845 static char *
2846 url_decode(const char *in)
2847 {
2848         char *out, *d;
2849         const char *s;
2850
2851         out = (char *)malloc(strlen(in) + 1);
2852         if (out == NULL)
2853                 return (NULL);
2854         for (s = in, d = out; *s != '\0'; ) {
2855                 if (s[0] == '%' && s[1] != '\0' && s[2] != '\0') {
2856                         /* Try to convert % escape */
2857                         int digit1 = tohex(s[1]);
2858                         int digit2 = tohex(s[2]);
2859                         if (digit1 >= 0 && digit2 >= 0) {
2860                                 /* Looks good, consume three chars */
2861                                 s += 3;
2862                                 /* Convert output */
2863                                 *d++ = ((digit1 << 4) | digit2);
2864                                 continue;
2865                         }
2866                         /* Else fall through and treat '%' as normal char */
2867                 }
2868                 *d++ = *s++;
2869         }
2870         *d = '\0';
2871         return (out);
2872 }
2873
2874 static int
2875 tohex(int c)
2876 {
2877         if (c >= '0' && c <= '9')
2878                 return (c - '0');
2879         else if (c >= 'A' && c <= 'F')
2880                 return (c - 'A' + 10);
2881         else if (c >= 'a' && c <= 'f')
2882                 return (c - 'a' + 10);
2883         else
2884                 return (-1);
2885 }