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