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