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