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