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