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