Import libarchive-2.2.5 which fixes a forgotten 'break'. Without this,
[dragonfly.git] / contrib / libarchive-1.3.1 / libarchive / archive_read_support_format_tar.c
1 /*-
2  * Copyright (c) 2003-2006 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  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_tar.c,v 1.43 2006/09/05 05:59:46 kientzle Exp $");
29
30 #include <sys/stat.h>
31 #ifdef MAJOR_IN_MKDEV
32 #include <sys/mkdev.h>
33 #else
34 #ifdef MAJOR_IN_SYSMACROS
35 #include <sys/sysmacros.h>
36 #endif
37 #endif
38 #include <errno.h>
39 #include <stddef.h>
40 /* #include <stdint.h> */ /* See archive_platform.h */
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44
45 /* Obtain suitable wide-character manipulation functions. */
46 #ifdef HAVE_WCHAR_H
47 #include <wchar.h>
48 #else
49 /* Good enough for equality testing, which is all we need. */
50 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
51 {
52         int diff = *s1 - *s2;
53         while (*s1 && diff == 0)
54                 diff = (int)*++s1 - (int)*++s2;
55         return diff;
56 }
57 /* Good enough for equality testing, which is all we need. */
58 static int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n)
59 {
60         int diff = *s1 - *s2;
61         while (*s1 && diff == 0 && n-- > 0)
62                 diff = (int)*++s1 - (int)*++s2;
63         return diff;
64 }
65 static size_t wcslen(const wchar_t *s)
66 {
67         const wchar_t *p = s;
68         while (*p)
69                 p++;
70         return p - s;
71 }
72 #endif
73
74 #include "archive.h"
75 #include "archive_entry.h"
76 #include "archive_private.h"
77
78 /*
79  * Layout of POSIX 'ustar' tar header.
80  */
81 struct archive_entry_header_ustar {
82         char    name[100];
83         char    mode[8];
84         char    uid[8];
85         char    gid[8];
86         char    size[12];
87         char    mtime[12];
88         char    checksum[8];
89         char    typeflag[1];
90         char    linkname[100];  /* "old format" header ends here */
91         char    magic[6];       /* For POSIX: "ustar\0" */
92         char    version[2];     /* For POSIX: "00" */
93         char    uname[32];
94         char    gname[32];
95         char    rdevmajor[8];
96         char    rdevminor[8];
97         char    prefix[155];
98 };
99
100 /*
101  * Structure of GNU tar header
102  */
103 struct gnu_sparse {
104         char    offset[12];
105         char    numbytes[12];
106 };
107
108 struct archive_entry_header_gnutar {
109         char    name[100];
110         char    mode[8];
111         char    uid[8];
112         char    gid[8];
113         char    size[12];
114         char    mtime[12];
115         char    checksum[8];
116         char    typeflag[1];
117         char    linkname[100];
118         char    magic[8];  /* "ustar  \0" (note blank/blank/null at end) */
119         char    uname[32];
120         char    gname[32];
121         char    rdevmajor[8];
122         char    rdevminor[8];
123         char    atime[12];
124         char    ctime[12];
125         char    offset[12];
126         char    longnames[4];
127         char    unused[1];
128         struct gnu_sparse sparse[4];
129         char    isextended[1];
130         char    realsize[12];
131         /*
132          * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
133          * entry instead.
134          */
135 };
136
137 /*
138  * Data specific to this format.
139  */
140 struct sparse_block {
141         struct sparse_block     *next;
142         off_t   offset;
143         off_t   remaining;
144 };
145
146 struct tar {
147         struct archive_string    acl_text;
148         struct archive_string    entry_name;
149         struct archive_string    entry_linkname;
150         struct archive_string    entry_uname;
151         struct archive_string    entry_gname;
152         struct archive_string    longlink;
153         struct archive_string    longname;
154         struct archive_string    pax_header;
155         struct archive_string    pax_global;
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         struct sparse_block     *sparse_list;
163 };
164
165 static size_t   UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
166 static int      archive_block_is_null(const unsigned char *p);
167 static char     *base64_decode(const wchar_t *, size_t, size_t *);
168 static int      gnu_read_sparse_data(struct archive *, struct tar *,
169                     const struct archive_entry_header_gnutar *header);
170 static void     gnu_parse_sparse_data(struct archive *, struct tar *,
171                     const struct gnu_sparse *sparse, int length);
172 static int      header_Solaris_ACL(struct archive *,  struct tar *,
173                     struct archive_entry *, struct stat *, const void *);
174 static int      header_common(struct archive *,  struct tar *,
175                     struct archive_entry *, struct stat *, const void *);
176 static int      header_old_tar(struct archive *, struct tar *,
177                     struct archive_entry *, struct stat *, const void *);
178 static int      header_pax_extensions(struct archive *, struct tar *,
179                     struct archive_entry *, struct stat *, const void *);
180 static int      header_pax_global(struct archive *, struct tar *,
181                     struct archive_entry *, struct stat *, const void *h);
182 static int      header_longlink(struct archive *, struct tar *,
183                     struct archive_entry *, struct stat *, const void *h);
184 static int      header_longname(struct archive *, struct tar *,
185                     struct archive_entry *, struct stat *, const void *h);
186 static int      header_volume(struct archive *, struct tar *,
187                     struct archive_entry *, struct stat *, const void *h);
188 static int      header_ustar(struct archive *, struct tar *,
189                     struct archive_entry *, struct stat *, const void *h);
190 static int      header_gnutar(struct archive *, struct tar *,
191                     struct archive_entry *, struct stat *, const void *h);
192 static int      archive_read_format_tar_bid(struct archive *);
193 static int      archive_read_format_tar_cleanup(struct archive *);
194 static int      archive_read_format_tar_read_data(struct archive *a,
195                     const void **buff, size_t *size, off_t *offset);
196 static int      archive_read_format_tar_skip(struct archive *a);
197 static int      archive_read_format_tar_read_header(struct archive *,
198                     struct archive_entry *);
199 static int      checksum(struct archive *, const void *);
200 static int      pax_attribute(struct archive_entry *, struct stat *,
201                     wchar_t *key, wchar_t *value);
202 static int      pax_header(struct archive *, struct tar *,
203                     struct archive_entry *, struct stat *, char *attr);
204 static void     pax_time(const wchar_t *, int64_t *sec, long *nanos);
205 static int      read_body_to_string(struct archive *, struct tar *,
206                     struct archive_string *, const void *h);
207 static int64_t  tar_atol(const char *, unsigned);
208 static int64_t  tar_atol10(const wchar_t *, unsigned);
209 static int64_t  tar_atol256(const char *, unsigned);
210 static int64_t  tar_atol8(const char *, unsigned);
211 static int      tar_read_header(struct archive *, struct tar *,
212                     struct archive_entry *, struct stat *);
213 static int      tohex(int c);
214 static char     *url_decode(const char *);
215 static int      utf8_decode(wchar_t *, const char *, size_t length);
216 static char     *wide_to_narrow(const wchar_t *wval);
217
218 /*
219  * ANSI C99 defines constants for these, but not everyone supports
220  * those constants, so I define a couple of static variables here and
221  * compute the values.  These calculations should be portable to any
222  * 2s-complement architecture.
223  */
224 #ifdef UINT64_MAX
225 static const uint64_t max_uint64 = UINT64_MAX;
226 #else
227 static const uint64_t max_uint64 = ~(uint64_t)0;
228 #endif
229 #ifdef INT64_MAX
230 static const int64_t max_int64 = INT64_MAX;
231 #else
232 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
233 #endif
234 #ifdef INT64_MIN
235 static const int64_t min_int64 = INT64_MIN;
236 #else
237 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
238 #endif
239
240 int
241 archive_read_support_format_gnutar(struct archive *a)
242 {
243         return (archive_read_support_format_tar(a));
244 }
245
246
247 int
248 archive_read_support_format_tar(struct archive *a)
249 {
250         struct tar *tar;
251         int r;
252
253         tar = malloc(sizeof(*tar));
254         if (tar == NULL) {
255                 archive_set_error(a, ENOMEM, "Can't allocate tar data");
256                 return (ARCHIVE_FATAL);
257         }
258         memset(tar, 0, sizeof(*tar));
259
260         r = __archive_read_register_format(a, tar,
261             archive_read_format_tar_bid,
262             archive_read_format_tar_read_header,
263             archive_read_format_tar_read_data,
264             archive_read_format_tar_skip,
265             archive_read_format_tar_cleanup);
266
267         if (r != ARCHIVE_OK)
268                 free(tar);
269         return (ARCHIVE_OK);
270 }
271
272 static int
273 archive_read_format_tar_cleanup(struct archive *a)
274 {
275         struct tar *tar;
276
277         tar = *(a->pformat_data);
278         archive_string_free(&tar->acl_text);
279         archive_string_free(&tar->entry_name);
280         archive_string_free(&tar->entry_linkname);
281         archive_string_free(&tar->entry_uname);
282         archive_string_free(&tar->entry_gname);
283         archive_string_free(&tar->pax_global);
284         archive_string_free(&tar->pax_header);
285         if (tar->pax_entry != NULL)
286                 free(tar->pax_entry);
287         free(tar);
288         *(a->pformat_data) = NULL;
289         return (ARCHIVE_OK);
290 }
291
292
293 static int
294 archive_read_format_tar_bid(struct archive *a)
295 {
296         int bid;
297         ssize_t bytes_read;
298         const void *h;
299         const struct archive_entry_header_ustar *header;
300
301         /*
302          * If we're already reading a non-tar file, don't
303          * bother to bid.
304          */
305         if (a->archive_format != 0 &&
306             (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
307             ARCHIVE_FORMAT_TAR)
308                 return (0);
309         bid = 0;
310
311         /*
312          * If we're already reading a tar format, start the bid at 1 as
313          * a failsafe.
314          */
315         if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
316             ARCHIVE_FORMAT_TAR)
317                 bid++;
318
319         /* Now let's look at the actual header and see if it matches. */
320         if (a->compression_read_ahead != NULL)
321                 bytes_read = (a->compression_read_ahead)(a, &h, 512);
322         else
323                 bytes_read = 0; /* Empty file. */
324         if (bytes_read < 0)
325                 return (ARCHIVE_FATAL);
326         if (bytes_read == 0  &&  bid > 0) {
327                 /* An archive without a proper end-of-archive marker. */
328                 /* Hold our nose and bid 1 anyway. */
329                 return (1);
330         }
331         if (bytes_read < 512) {
332                 /* If it's a new archive, then just return a zero bid. */
333                 if (bid == 0)
334                         return (0);
335                 /*
336                  * If we already know this is a tar archive,
337                  * then we have a problem.
338                  */
339                 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
340                     "Truncated tar archive");
341                 return (ARCHIVE_FATAL);
342         }
343
344         /* If it's an end-of-archive mark, we can handle it. */
345         if ((*(const char *)h) == 0 && archive_block_is_null(h)) {
346                 /* If it's a known tar file, end-of-archive is definite. */
347                 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
348                     ARCHIVE_FORMAT_TAR)
349                         return (512);
350                 /* Empty archive? */
351                 return (1);
352         }
353
354         /* If it's not an end-of-archive mark, it must have a valid checksum.*/
355         if (!checksum(a, h))
356                 return (0);
357         bid += 48;  /* Checksum is usually 6 octal digits. */
358
359         header = h;
360
361         /* Recognize POSIX formats. */
362         if ((memcmp(header->magic, "ustar\0", 6) == 0)
363             &&(memcmp(header->version, "00", 2)==0))
364                 bid += 56;
365
366         /* Recognize GNU tar format. */
367         if ((memcmp(header->magic, "ustar ", 6) == 0)
368             &&(memcmp(header->version, " \0", 2)==0))
369                 bid += 56;
370
371         /* Type flag must be null, digit or A-Z, a-z. */
372         if (header->typeflag[0] != 0 &&
373             !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
374             !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
375             !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
376                 return (0);
377         bid += 2;  /* 6 bits of variation in an 8-bit field leaves 2 bits. */
378
379         /* Sanity check: Look at first byte of mode field. */
380         switch (255 & (unsigned)header->mode[0]) {
381         case 0: case 255:
382                 /* Base-256 value: No further verification possible! */
383                 break;
384         case ' ': /* Not recommended, but not illegal, either. */
385                 break;
386         case '0': case '1': case '2': case '3':
387         case '4': case '5': case '6': case '7':
388                 /* Octal Value. */
389                 /* TODO: Check format of remainder of this field. */
390                 break;
391         default:
392                 /* Not a valid mode; bail out here. */
393                 return (0);
394         }
395         /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
396
397         return (bid);
398 }
399
400 /*
401  * The function invoked by archive_read_header().  This
402  * just sets up a few things and then calls the internal
403  * tar_read_header() function below.
404  */
405 static int
406 archive_read_format_tar_read_header(struct archive *a,
407     struct archive_entry *entry)
408 {
409         /*
410          * When converting tar archives to cpio archives, it is
411          * essential that each distinct file have a distinct inode
412          * number.  To simplify this, we keep a static count here to
413          * assign fake dev/inode numbers to each tar entry.  Note that
414          * pax format archives may overwrite this with something more
415          * useful.
416          *
417          * Ideally, we would track every file read from the archive so
418          * that we could assign the same dev/ino pair to hardlinks,
419          * but the memory required to store a complete lookup table is
420          * probably not worthwhile just to support the relatively
421          * obscure tar->cpio conversion case.
422          */
423         static int default_inode;
424         static int default_dev;
425         struct stat st;
426         struct tar *tar;
427         const char *p;
428         int r;
429         size_t l;
430
431         memset(&st, 0, sizeof(st));
432         /* Assign default device/inode values. */
433         st.st_dev = 1 + default_dev; /* Don't use zero. */
434         st.st_ino = ++default_inode; /* Don't use zero. */
435         /* Limit generated st_ino number to 16 bits. */
436         if (default_inode >= 0xffff) {
437                 ++default_dev;
438                 default_inode = 0;
439         }
440
441         tar = *(a->pformat_data);
442         tar->entry_offset = 0;
443
444         r = tar_read_header(a, tar, entry, &st);
445
446         if (r == ARCHIVE_OK) {
447                 /*
448                  * "Regular" entry with trailing '/' is really
449                  * directory: This is needed for certain old tar
450                  * variants and even for some broken newer ones.
451                  */
452                 p = archive_entry_pathname(entry);
453                 l = strlen(p);
454                 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
455                         st.st_mode &= ~S_IFMT;
456                         st.st_mode |= S_IFDIR;
457                 }
458
459                 /* Copy the final stat data into the entry. */
460                 archive_entry_copy_stat(entry, &st);
461         }
462         return (r);
463 }
464
465 static int
466 archive_read_format_tar_read_data(struct archive *a,
467     const void **buff, size_t *size, off_t *offset)
468 {
469         ssize_t bytes_read;
470         struct tar *tar;
471         struct sparse_block *p;
472
473         tar = *(a->pformat_data);
474         if (tar->sparse_list != NULL) {
475                 /* Remove exhausted entries from sparse list. */
476                 while (tar->sparse_list != NULL &&
477                     tar->sparse_list->remaining == 0) {
478                         p = tar->sparse_list;
479                         tar->sparse_list = p->next;
480                         free(p);
481                 }
482                 if (tar->sparse_list == NULL) {
483                         /* We exhausted the entire sparse list. */
484                         tar->entry_bytes_remaining = 0;
485                 }
486         }
487
488         if (tar->entry_bytes_remaining > 0) {
489                 bytes_read = (a->compression_read_ahead)(a, buff, 1);
490                 if (bytes_read <= 0)
491                         return (ARCHIVE_FATAL);
492                 if (bytes_read > tar->entry_bytes_remaining)
493                         bytes_read = tar->entry_bytes_remaining;
494                 if (tar->sparse_list != NULL) {
495                         /* Don't read more than is available in the
496                          * current sparse block. */
497                         if (tar->sparse_list->remaining < bytes_read)
498                                 bytes_read = tar->sparse_list->remaining;
499                         tar->entry_offset = tar->sparse_list->offset;
500                         tar->sparse_list->remaining -= bytes_read;
501                         tar->sparse_list->offset += bytes_read;
502                 }
503                 *size = bytes_read;
504                 *offset = tar->entry_offset;
505                 tar->entry_offset += bytes_read;
506                 tar->entry_bytes_remaining -= bytes_read;
507                 (a->compression_read_consume)(a, bytes_read);
508                 return (ARCHIVE_OK);
509         } else {
510                 while (tar->entry_padding > 0) {
511                         bytes_read = (a->compression_read_ahead)(a, buff, 1);
512                         if (bytes_read <= 0)
513                                 return (ARCHIVE_FATAL);
514                         if (bytes_read > tar->entry_padding)
515                                 bytes_read = tar->entry_padding;
516                         (a->compression_read_consume)(a, bytes_read);
517                         tar->entry_padding -= bytes_read;
518                 }
519                 *buff = NULL;
520                 *size = 0;
521                 *offset = tar->entry_offset;
522                 return (ARCHIVE_EOF);
523         }
524 }
525
526 static int
527 archive_read_format_tar_skip(struct archive *a)
528 {
529         ssize_t bytes_skipped;
530         struct tar* tar;
531         struct sparse_block *p;
532         int r = ARCHIVE_OK;
533         const void *b;  /* dummy variables */
534         size_t s;
535         off_t o;
536
537
538         tar = *(a->pformat_data);
539         if (a->compression_skip == NULL) {
540                 while (r == ARCHIVE_OK)
541                         r = archive_read_format_tar_read_data(a, &b, &s, &o);
542                 return (r);
543         }
544         bytes_skipped = (a->compression_skip)(a, tar->entry_bytes_remaining);
545         if (bytes_skipped < 0)
546                 return (ARCHIVE_FATAL);
547         /* same code as above in _tar_read_data() */
548         tar->entry_bytes_remaining -= bytes_skipped;
549         while (tar->sparse_list != NULL &&
550             tar->sparse_list->remaining == 0) {
551                 p = tar->sparse_list;
552                 tar->sparse_list = p->next;
553                 free(p);
554                 if (tar->sparse_list != NULL)
555                         tar->entry_offset = tar->sparse_list->offset;
556         }
557         if (tar->sparse_list != NULL) {
558                 if (tar->sparse_list->remaining < bytes_skipped)
559                         bytes_skipped = tar->sparse_list->remaining;
560                 tar->sparse_list->remaining -= bytes_skipped;
561         }
562         tar->entry_offset += bytes_skipped;
563         tar->entry_bytes_remaining -= bytes_skipped;
564         /* Reuse padding code above. */
565         while (r == ARCHIVE_OK)
566                 r = archive_read_format_tar_read_data(a, &b, &s, &o);
567         return (r);
568 }
569
570 /*
571  * This function recursively interprets all of the headers associated
572  * with a single entry.
573  */
574 static int
575 tar_read_header(struct archive *a, struct tar *tar,
576     struct archive_entry *entry, struct stat *st)
577 {
578         ssize_t bytes;
579         int err;
580         const void *h;
581         const struct archive_entry_header_ustar *header;
582
583         /* Read 512-byte header record */
584         bytes = (a->compression_read_ahead)(a, &h, 512);
585         if (bytes < 512) {
586                 /*
587                  * If we're here, it's becase the _bid function accepted
588                  * this file.  So just call a short read end-of-archive
589                  * and be done with it.
590                  */
591                 return (ARCHIVE_EOF);
592         }
593         (a->compression_read_consume)(a, 512);
594
595         /* Check for end-of-archive mark. */
596         if (((*(const char *)h)==0) && archive_block_is_null(h)) {
597                 /* Try to consume a second all-null record, as well. */
598                 bytes = (a->compression_read_ahead)(a, &h, 512);
599                 if (bytes > 0)
600                         (a->compression_read_consume)(a, bytes);
601                 archive_set_error(a, 0, NULL);
602                 return (ARCHIVE_EOF);
603         }
604
605         /*
606          * Note: If the checksum fails and we return ARCHIVE_RETRY,
607          * then the client is likely to just retry.  This is a very
608          * crude way to search for the next valid header!
609          *
610          * TODO: Improve this by implementing a real header scan.
611          */
612         if (!checksum(a, h)) {
613                 archive_set_error(a, EINVAL, "Damaged tar archive");
614                 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
615         }
616
617         if (++tar->header_recursion_depth > 32) {
618                 archive_set_error(a, EINVAL, "Too many special headers");
619                 return (ARCHIVE_WARN);
620         }
621
622         /* Determine the format variant. */
623         header = h;
624         switch(header->typeflag[0]) {
625         case 'A': /* Solaris tar ACL */
626                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
627                 a->archive_format_name = "Solaris tar";
628                 err = header_Solaris_ACL(a, tar, entry, st, h);
629                 break;
630         case 'g': /* POSIX-standard 'g' header. */
631                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
632                 a->archive_format_name = "POSIX pax interchange format";
633                 err = header_pax_global(a, tar, entry, st, h);
634                 break;
635         case 'K': /* Long link name (GNU tar, others) */
636                 err = header_longlink(a, tar, entry, st, h);
637                 break;
638         case 'L': /* Long filename (GNU tar, others) */
639                 err = header_longname(a, tar, entry, st, h);
640                 break;
641         case 'V': /* GNU volume header */
642                 err = header_volume(a, tar, entry, st, h);
643                 break;
644         case 'X': /* Used by SUN tar; same as 'x'. */
645                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
646                 a->archive_format_name =
647                     "POSIX pax interchange format (Sun variant)";
648                 err = header_pax_extensions(a, tar, entry, st, h);
649                 break;
650         case 'x': /* POSIX-standard 'x' header. */
651                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
652                 a->archive_format_name = "POSIX pax interchange format";
653                 err = header_pax_extensions(a, tar, entry, st, h);
654                 break;
655         default:
656                 if (memcmp(header->magic, "ustar  \0", 8) == 0) {
657                         a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
658                         a->archive_format_name = "GNU tar format";
659                         err = header_gnutar(a, tar, entry, st, h);
660                 } else if (memcmp(header->magic, "ustar", 5) == 0) {
661                         if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
662                                 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
663                                 a->archive_format_name = "POSIX ustar format";
664                         }
665                         err = header_ustar(a, tar, entry, st, h);
666                 } else {
667                         a->archive_format = ARCHIVE_FORMAT_TAR;
668                         a->archive_format_name = "tar (non-POSIX)";
669                         err = header_old_tar(a, tar, entry, st, h);
670                 }
671         }
672         --tar->header_recursion_depth;
673         return (err);
674 }
675
676 /*
677  * Return true if block checksum is correct.
678  */
679 static int
680 checksum(struct archive *a, const void *h)
681 {
682         const unsigned char *bytes;
683         const struct archive_entry_header_ustar *header;
684         int check, i, sum;
685
686         (void)a; /* UNUSED */
687         bytes = h;
688         header = h;
689
690         /*
691          * Test the checksum.  Note that POSIX specifies _unsigned_
692          * bytes for this calculation.
693          */
694         sum = tar_atol(header->checksum, sizeof(header->checksum));
695         check = 0;
696         for (i = 0; i < 148; i++)
697                 check += (unsigned char)bytes[i];
698         for (; i < 156; i++)
699                 check += 32;
700         for (; i < 512; i++)
701                 check += (unsigned char)bytes[i];
702         if (sum == check)
703                 return (1);
704
705         /*
706          * Repeat test with _signed_ bytes, just in case this archive
707          * was created by an old BSD, Solaris, or HP-UX tar with a
708          * broken checksum calculation.
709          */
710         check = 0;
711         for (i = 0; i < 148; i++)
712                 check += (signed char)bytes[i];
713         for (; i < 156; i++)
714                 check += 32;
715         for (; i < 512; i++)
716                 check += (signed char)bytes[i];
717         if (sum == check)
718                 return (1);
719
720         return (0);
721 }
722
723 /*
724  * Return true if this block contains only nulls.
725  */
726 static int
727 archive_block_is_null(const unsigned char *p)
728 {
729         unsigned i;
730
731         for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
732                 if (*p++)
733                         return (0);
734         return (1);
735 }
736
737 /*
738  * Interpret 'A' Solaris ACL header
739  */
740 static int
741 header_Solaris_ACL(struct archive *a, struct tar *tar,
742     struct archive_entry *entry, struct stat *st, const void *h)
743 {
744         int err, err2;
745         char *p;
746         wchar_t *wp;
747
748         err = read_body_to_string(a, tar, &(tar->acl_text), h);
749         err2 = tar_read_header(a, tar, entry, st);
750         err = err_combine(err, err2);
751
752         /* XXX Ensure p doesn't overrun acl_text */
753
754         /* Skip leading octal number. */
755         /* XXX TODO: Parse the octal number and sanity-check it. */
756         p = tar->acl_text.s;
757         while (*p != '\0')
758                 p++;
759         p++;
760
761         wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
762         if (wp != NULL) {
763                 utf8_decode(wp, p, strlen(p));
764                 err2 = __archive_entry_acl_parse_w(entry, wp,
765                     ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
766                 err = err_combine(err, err2);
767                 free(wp);
768         }
769
770         return (err);
771 }
772
773 /*
774  * Interpret 'K' long linkname header.
775  */
776 static int
777 header_longlink(struct archive *a, struct tar *tar,
778     struct archive_entry *entry, struct stat *st, const void *h)
779 {
780         int err, err2;
781
782         err = read_body_to_string(a, tar, &(tar->longlink), h);
783         err2 = tar_read_header(a, tar, entry, st);
784         if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
785                 /* Set symlink if symlink already set, else hardlink. */
786                 archive_entry_set_link(entry, tar->longlink.s);
787         }
788         return (err_combine(err, err2));
789 }
790
791 /*
792  * Interpret 'L' long filename header.
793  */
794 static int
795 header_longname(struct archive *a, struct tar *tar,
796     struct archive_entry *entry, struct stat *st, const void *h)
797 {
798         int err, err2;
799
800         err = read_body_to_string(a, tar, &(tar->longname), h);
801         /* Read and parse "real" header, then override name. */
802         err2 = tar_read_header(a, tar, entry, st);
803         if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
804                 archive_entry_set_pathname(entry, tar->longname.s);
805         return (err_combine(err, err2));
806 }
807
808
809 /*
810  * Interpret 'V' GNU tar volume header.
811  */
812 static int
813 header_volume(struct archive *a, struct tar *tar,
814     struct archive_entry *entry, struct stat *st, const void *h)
815 {
816         (void)h;
817
818         /* Just skip this and read the next header. */
819         return (tar_read_header(a, tar, entry, st));
820 }
821
822 /*
823  * Read body of an archive entry into an archive_string object.
824  */
825 static int
826 read_body_to_string(struct archive *a, struct tar *tar,
827     struct archive_string *as, const void *h)
828 {
829         off_t size, padded_size;
830         ssize_t bytes_read, bytes_to_copy;
831         const struct archive_entry_header_ustar *header;
832         const void *src;
833         char *dest;
834
835         (void)tar; /* UNUSED */
836         header = h;
837         size  = tar_atol(header->size, sizeof(header->size));
838
839         /* Read the body into the string. */
840         archive_string_ensure(as, size+1);
841         padded_size = (size + 511) & ~ 511;
842         dest = as->s;
843         while (padded_size > 0) {
844                 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
845                 if (bytes_read < 0)
846                         return (ARCHIVE_FATAL);
847                 if (bytes_read > padded_size)
848                         bytes_read = padded_size;
849                 (a->compression_read_consume)(a, bytes_read);
850                 bytes_to_copy = bytes_read;
851                 if ((off_t)bytes_to_copy > size)
852                         bytes_to_copy = (ssize_t)size;
853                 memcpy(dest, src, bytes_to_copy);
854                 dest += bytes_to_copy;
855                 size -= bytes_to_copy;
856                 padded_size -= bytes_read;
857         }
858         *dest = '\0';
859         return (ARCHIVE_OK);
860 }
861
862 /*
863  * Parse out common header elements.
864  *
865  * This would be the same as header_old_tar, except that the
866  * filename is handled slightly differently for old and POSIX
867  * entries  (POSIX entries support a 'prefix').  This factoring
868  * allows header_old_tar and header_ustar
869  * to handle filenames differently, while still putting most of the
870  * common parsing into one place.
871  */
872 static int
873 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
874     struct stat *st, const void *h)
875 {
876         const struct archive_entry_header_ustar *header;
877         char    tartype;
878
879         (void)a; /* UNUSED */
880
881         header = h;
882         if (header->linkname[0])
883                 archive_strncpy(&(tar->entry_linkname), header->linkname,
884                     sizeof(header->linkname));
885         else
886                 archive_string_empty(&(tar->entry_linkname));
887
888         /* Parse out the numeric fields (all are octal) */
889         st->st_mode  = tar_atol(header->mode, sizeof(header->mode));
890         st->st_uid   = tar_atol(header->uid, sizeof(header->uid));
891         st->st_gid   = tar_atol(header->gid, sizeof(header->gid));
892         st->st_size  = tar_atol(header->size, sizeof(header->size));
893         st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
894
895         /* Handle the tar type flag appropriately. */
896         tartype = header->typeflag[0];
897         st->st_mode &= ~S_IFMT;
898
899         switch (tartype) {
900         case '1': /* Hard link */
901                 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
902                 /*
903                  * The following may seem odd, but: Technically, tar
904                  * does not store the file type for a "hard link"
905                  * entry, only the fact that it is a hard link.  So, I
906                  * leave the type zero normally.  But, pax interchange
907                  * format allows hard links to have data, which
908                  * implies that the underlying entry is a regular
909                  * file.
910                  */
911                 if (st->st_size > 0)
912                         st->st_mode |= S_IFREG;
913
914                 /*
915                  * A tricky point: Traditionally, tar readers have
916                  * ignored the size field when reading hardlink
917                  * entries, and some writers put non-zero sizes even
918                  * though the body is empty.  POSIX.1-2001 broke with
919                  * this tradition by permitting hardlink entries to
920                  * store valid bodies in pax interchange format, but
921                  * not in ustar format.  Since there is no hard and
922                  * fast way to distinguish pax interchange from
923                  * earlier archives (the 'x' and 'g' entries are
924                  * optional, after all), we need a heuristic.  Here, I
925                  * use the bid function to test whether or not there's
926                  * a valid header following.  Of course, if we know
927                  * this is pax interchange format, then we must obey
928                  * the size.
929                  *
930                  * This heuristic will only fail for a pax interchange
931                  * archive that is storing hardlink bodies, no pax
932                  * extended attribute entries have yet occurred, and
933                  * we encounter a hardlink entry for a file that is
934                  * itself an uncompressed tar archive.
935                  */
936                 if (st->st_size > 0  &&
937                     a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE  &&
938                     archive_read_format_tar_bid(a) > 50)
939                         st->st_size = 0;
940                 break;
941         case '2': /* Symlink */
942                 st->st_mode |= S_IFLNK;
943                 st->st_size = 0;
944                 archive_entry_set_symlink(entry, tar->entry_linkname.s);
945                 break;
946         case '3': /* Character device */
947                 st->st_mode |= S_IFCHR;
948                 st->st_size = 0;
949                 break;
950         case '4': /* Block device */
951                 st->st_mode |= S_IFBLK;
952                 st->st_size = 0;
953                 break;
954         case '5': /* Dir */
955                 st->st_mode |= S_IFDIR;
956                 st->st_size = 0;
957                 break;
958         case '6': /* FIFO device */
959                 st->st_mode |= S_IFIFO;
960                 st->st_size = 0;
961                 break;
962         case 'D': /* GNU incremental directory type */
963                 /*
964                  * No special handling is actually required here.
965                  * It might be nice someday to preprocess the file list and
966                  * provide it to the client, though.
967                  */
968                 st->st_mode |= S_IFDIR;
969                 break;
970         case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
971                 /*
972                  * As far as I can tell, this is just like a regular file
973                  * entry, except that the contents should be _appended_ to
974                  * the indicated file at the indicated offset.  This may
975                  * require some API work to fully support.
976                  */
977                 break;
978         case 'N': /* Old GNU "long filename" entry. */
979                 /* The body of this entry is a script for renaming
980                  * previously-extracted entries.  Ugh.  It will never
981                  * be supported by libarchive. */
982                 st->st_mode |= S_IFREG;
983                 break;
984         case 'S': /* GNU sparse files */
985                 /*
986                  * Sparse files are really just regular files with
987                  * sparse information in the extended area.
988                  */
989                 /* FALL THROUGH */
990         default: /* Regular file  and non-standard types */
991                 /*
992                  * Per POSIX: non-recognized types should always be
993                  * treated as regular files.
994                  */
995                 st->st_mode |= S_IFREG;
996                 break;
997         }
998         return (0);
999 }
1000
1001 /*
1002  * Parse out header elements for "old-style" tar archives.
1003  */
1004 static int
1005 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1006     struct stat *st, const void *h)
1007 {
1008         const struct archive_entry_header_ustar *header;
1009
1010         /* Copy filename over (to ensure null termination). */
1011         header = h;
1012         archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1013         archive_entry_set_pathname(entry, tar->entry_name.s);
1014
1015         /* Grab rest of common fields */
1016         header_common(a, tar, entry, st, h);
1017
1018         tar->entry_bytes_remaining = st->st_size;
1019         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1020         return (0);
1021 }
1022
1023 /*
1024  * Parse a file header for a pax extended archive entry.
1025  */
1026 static int
1027 header_pax_global(struct archive *a, struct tar *tar,
1028     struct archive_entry *entry, struct stat *st, const void *h)
1029 {
1030         int err, err2;
1031
1032         err = read_body_to_string(a, tar, &(tar->pax_global), h);
1033         err2 = tar_read_header(a, tar, entry, st);
1034         return (err_combine(err, err2));
1035 }
1036
1037 static int
1038 header_pax_extensions(struct archive *a, struct tar *tar,
1039     struct archive_entry *entry, struct stat *st, const void *h)
1040 {
1041         int err, err2;
1042
1043         read_body_to_string(a, tar, &(tar->pax_header), h);
1044
1045         /* Parse the next header. */
1046         err = tar_read_header(a, tar, entry, st);
1047
1048         /*
1049          * TODO: Parse global/default options into 'entry' struct here
1050          * before handling file-specific options.
1051          *
1052          * This design (parse standard header, then overwrite with pax
1053          * extended attribute data) usually works well, but isn't ideal;
1054          * it would be better to parse the pax extended attributes first
1055          * and then skip any fields in the standard header that were
1056          * defined in the pax header.
1057          */
1058         err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1059         err =  err_combine(err, err2);
1060         tar->entry_bytes_remaining = st->st_size;
1061         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1062         return (err);
1063 }
1064
1065
1066 /*
1067  * Parse a file header for a Posix "ustar" archive entry.  This also
1068  * handles "pax" or "extended ustar" entries.
1069  */
1070 static int
1071 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1072     struct stat *st, const void *h)
1073 {
1074         const struct archive_entry_header_ustar *header;
1075         struct archive_string *as;
1076
1077         header = h;
1078
1079         /* Copy name into an internal buffer to ensure null-termination. */
1080         as = &(tar->entry_name);
1081         if (header->prefix[0]) {
1082                 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1083                 if (as->s[archive_strlen(as) - 1] != '/')
1084                         archive_strappend_char(as, '/');
1085                 archive_strncat(as, header->name, sizeof(header->name));
1086         } else
1087                 archive_strncpy(as, header->name, sizeof(header->name));
1088
1089         archive_entry_set_pathname(entry, as->s);
1090
1091         /* Handle rest of common fields. */
1092         header_common(a, tar, entry, st, h);
1093
1094         /* Handle POSIX ustar fields. */
1095         archive_strncpy(&(tar->entry_uname), header->uname,
1096             sizeof(header->uname));
1097         archive_entry_set_uname(entry, tar->entry_uname.s);
1098
1099         archive_strncpy(&(tar->entry_gname), header->gname,
1100             sizeof(header->gname));
1101         archive_entry_set_gname(entry, tar->entry_gname.s);
1102
1103         /* Parse out device numbers only for char and block specials. */
1104         if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1105                 st->st_rdev = makedev(
1106                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1107                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1108         }
1109
1110         tar->entry_bytes_remaining = st->st_size;
1111         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1112
1113         return (0);
1114 }
1115
1116
1117 /*
1118  * Parse the pax extended attributes record.
1119  *
1120  * Returns non-zero if there's an error in the data.
1121  */
1122 static int
1123 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1124     struct stat *st, char *attr)
1125 {
1126         size_t attr_length, l, line_length;
1127         char *line, *p;
1128         wchar_t *key, *wp, *value;
1129         int err, err2;
1130
1131         attr_length = strlen(attr);
1132         err = ARCHIVE_OK;
1133         while (attr_length > 0) {
1134                 /* Parse decimal length field at start of line. */
1135                 line_length = 0;
1136                 l = attr_length;
1137                 line = p = attr; /* Record start of line. */
1138                 while (l>0) {
1139                         if (*p == ' ') {
1140                                 p++;
1141                                 l--;
1142                                 break;
1143                         }
1144                         if (*p < '0' || *p > '9')
1145                                 return (-1);
1146                         line_length *= 10;
1147                         line_length += *p - '0';
1148                         if (line_length > 999999) {
1149                                 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1150                                     "Rejecting pax extended attribute > 1MB");
1151                                 return (ARCHIVE_WARN);
1152                         }
1153                         p++;
1154                         l--;
1155                 }
1156
1157                 if (line_length > attr_length)
1158                         return (0);
1159
1160                 /* Ensure pax_entry buffer is big enough. */
1161                 if (tar->pax_entry_length <= line_length) {
1162                         wchar_t *old_entry = tar->pax_entry;
1163
1164                         if (tar->pax_entry_length <= 0)
1165                                 tar->pax_entry_length = 1024;
1166                         while (tar->pax_entry_length <= line_length + 1)
1167                                 tar->pax_entry_length *= 2;
1168
1169                         old_entry = tar->pax_entry;
1170                         tar->pax_entry = realloc(tar->pax_entry,
1171                             tar->pax_entry_length * sizeof(wchar_t));
1172                         if (tar->pax_entry == NULL) {
1173                                 free(old_entry);
1174                                 archive_set_error(a, ENOMEM,
1175                                         "No memory");
1176                                 return (ARCHIVE_FATAL);
1177                         }
1178                 }
1179
1180                 /* Decode UTF-8 to wchar_t, null-terminate result. */
1181                 if (utf8_decode(tar->pax_entry, p,
1182                         line_length - (p - attr) - 1)) {
1183                         archive_set_error(a, ARCHIVE_ERRNO_MISC,
1184                            "Invalid UTF8 character in pax extended attribute");
1185                         err = err_combine(err, ARCHIVE_WARN);
1186                 }
1187
1188                 /* Null-terminate 'key' value. */
1189                 wp = key = tar->pax_entry;
1190                 if (key[0] == L'=')
1191                         return (-1);
1192                 while (*wp && *wp != L'=')
1193                         ++wp;
1194                 if (*wp == L'\0' || wp == NULL) {
1195                         archive_set_error(a, ARCHIVE_ERRNO_MISC,
1196                             "Invalid pax extended attributes");
1197                         return (ARCHIVE_WARN);
1198                 }
1199                 *wp = 0;
1200
1201                 /* Identify null-terminated 'value' portion. */
1202                 value = wp + 1;
1203
1204                 /* Identify this attribute and set it in the entry. */
1205                 err2 = pax_attribute(entry, st, key, value);
1206                 err = err_combine(err, err2);
1207
1208                 /* Skip to next line */
1209                 attr += line_length;
1210                 attr_length -= line_length;
1211         }
1212         return (err);
1213 }
1214
1215 static int
1216 pax_attribute_xattr(struct archive_entry *entry,
1217         wchar_t *name, wchar_t *value)
1218 {
1219         char *name_decoded, *name_narrow;
1220         void *value_decoded;
1221         size_t value_len;
1222
1223         if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1224                 return 3;
1225
1226         name += 17;
1227
1228         /* URL-decode name */
1229         name_narrow = wide_to_narrow(name);
1230         if (name_narrow == NULL)
1231                 return 2;
1232         name_decoded = url_decode(name_narrow);
1233         free(name_narrow);
1234         if (name_decoded == NULL)
1235                 return 2;
1236
1237         /* Base-64 decode value */
1238         value_decoded = base64_decode(value, wcslen(value), &value_len);
1239         if (value_decoded == NULL) {
1240                 free(name_decoded);
1241                 return 1;
1242         }
1243
1244         archive_entry_xattr_add_entry(entry, name_decoded,
1245                 value_decoded, value_len);
1246
1247         free(name_decoded);
1248         free(value_decoded);
1249         return 0;
1250 }
1251
1252 /*
1253  * Parse a single key=value attribute.  key/value pointers are
1254  * assumed to point into reasonably long-lived storage.
1255  *
1256  * Note that POSIX reserves all-lowercase keywords.  Vendor-specific
1257  * extensions should always have keywords of the form "VENDOR.attribute"
1258  * In particular, it's quite feasible to support many different
1259  * vendor extensions here.  I'm using "LIBARCHIVE" for extensions
1260  * unique to this library (currently, there are none).
1261  *
1262  * Investigate other vendor-specific extensions, as well and see if
1263  * any of them look useful.
1264  */
1265 static int
1266 pax_attribute(struct archive_entry *entry, struct stat *st,
1267     wchar_t *key, wchar_t *value)
1268 {
1269         int64_t s;
1270         long n;
1271
1272         switch (key[0]) {
1273         case 'L':
1274                 /* Our extensions */
1275 /* TODO: Handle arbitrary extended attributes... */
1276 /*
1277                 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1278                         archive_entry_set_xxxxxx(entry, value);
1279 */
1280                 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1281                         pax_attribute_xattr(entry, key, value);
1282                 break;
1283         case 'S':
1284                 /* We support some keys used by the "star" archiver */
1285                 if (wcscmp(key, L"SCHILY.acl.access")==0)
1286                         __archive_entry_acl_parse_w(entry, value,
1287                             ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1288                 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1289                         __archive_entry_acl_parse_w(entry, value,
1290                             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1291                 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1292                         st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1293                             minor(st->st_rdev));
1294                 else if (wcscmp(key, L"SCHILY.devminor")==0)
1295                         st->st_rdev = makedev(major(st->st_rdev),
1296                             tar_atol10(value, wcslen(value)));
1297                 else if (wcscmp(key, L"SCHILY.fflags")==0)
1298                         archive_entry_copy_fflags_text_w(entry, value);
1299                 else if (wcscmp(key, L"SCHILY.nlink")==0)
1300                         st->st_nlink = tar_atol10(value, wcslen(value));
1301                 break;
1302         case 'a':
1303                 if (wcscmp(key, L"atime")==0) {
1304                         pax_time(value, &s, &n);
1305                         st->st_atime = s;
1306                         ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1307                 }
1308                 break;
1309         case 'c':
1310                 if (wcscmp(key, L"ctime")==0) {
1311                         pax_time(value, &s, &n);
1312                         st->st_ctime = s;
1313                         ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1314                 } else if (wcscmp(key, L"charset")==0) {
1315                         /* TODO: Publish charset information in entry. */
1316                 } else if (wcscmp(key, L"comment")==0) {
1317                         /* TODO: Publish comment in entry. */
1318                 }
1319                 break;
1320         case 'g':
1321                 if (wcscmp(key, L"gid")==0)
1322                         st->st_gid = tar_atol10(value, wcslen(value));
1323                 else if (wcscmp(key, L"gname")==0)
1324                         archive_entry_copy_gname_w(entry, value);
1325                 break;
1326         case 'l':
1327                 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1328                 if (wcscmp(key, L"linkpath")==0) {
1329                         if (archive_entry_hardlink(entry))
1330                                 archive_entry_copy_hardlink_w(entry, value);
1331                         else
1332                                 archive_entry_copy_symlink_w(entry, value);
1333                 }
1334                 break;
1335         case 'm':
1336                 if (wcscmp(key, L"mtime")==0) {
1337                         pax_time(value, &s, &n);
1338                         st->st_mtime = s;
1339                         ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1340                 }
1341                 break;
1342         case 'p':
1343                 if (wcscmp(key, L"path")==0)
1344                         archive_entry_copy_pathname_w(entry, value);
1345                 break;
1346         case 'r':
1347                 /* POSIX has reserved 'realtime.*' */
1348                 break;
1349         case 's':
1350                 /* POSIX has reserved 'security.*' */
1351                 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1352                 if (wcscmp(key, L"size")==0)
1353                         st->st_size = tar_atol10(value, wcslen(value));
1354                 break;
1355         case 'u':
1356                 if (wcscmp(key, L"uid")==0)
1357                         st->st_uid = tar_atol10(value, wcslen(value));
1358                 else if (wcscmp(key, L"uname")==0)
1359                         archive_entry_copy_uname_w(entry, value);
1360                 break;
1361         }
1362         return (0);
1363 }
1364
1365
1366
1367 /*
1368  * parse a decimal time value, which may include a fractional portion
1369  */
1370 static void
1371 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1372 {
1373         char digit;
1374         int64_t s;
1375         unsigned long l;
1376         int sign;
1377         int64_t limit, last_digit_limit;
1378
1379         limit = max_int64 / 10;
1380         last_digit_limit = max_int64 % 10;
1381
1382         s = 0;
1383         sign = 1;
1384         if (*p == '-') {
1385                 sign = -1;
1386                 p++;
1387         }
1388         while (*p >= '0' && *p <= '9') {
1389                 digit = *p - '0';
1390                 if (s > limit ||
1391                     (s == limit && digit > last_digit_limit)) {
1392                         s = max_uint64;
1393                         break;
1394                 }
1395                 s = (s * 10) + digit;
1396                 ++p;
1397         }
1398
1399         *ps = s * sign;
1400
1401         /* Calculate nanoseconds. */
1402         *pn = 0;
1403
1404         if (*p != '.')
1405                 return;
1406
1407         l = 100000000UL;
1408         do {
1409                 ++p;
1410                 if (*p >= '0' && *p <= '9')
1411                         *pn += (*p - '0') * l;
1412                 else
1413                         break;
1414         } while (l /= 10);
1415 }
1416
1417 /*
1418  * Parse GNU tar header
1419  */
1420 static int
1421 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1422     struct stat *st, const void *h)
1423 {
1424         const struct archive_entry_header_gnutar *header;
1425
1426         (void)a;
1427
1428         /*
1429          * GNU header is like POSIX ustar, except 'prefix' is
1430          * replaced with some other fields. This also means the
1431          * filename is stored as in old-style archives.
1432          */
1433
1434         /* Grab fields common to all tar variants. */
1435         header_common(a, tar, entry, st, h);
1436
1437         /* Copy filename over (to ensure null termination). */
1438         header = h;
1439         archive_strncpy(&(tar->entry_name), header->name,
1440             sizeof(header->name));
1441         archive_entry_set_pathname(entry, tar->entry_name.s);
1442
1443         /* Fields common to ustar and GNU */
1444         /* XXX Can the following be factored out since it's common
1445          * to ustar and gnu tar?  Is it okay to move it down into
1446          * header_common, perhaps?  */
1447         archive_strncpy(&(tar->entry_uname),
1448             header->uname, sizeof(header->uname));
1449         archive_entry_set_uname(entry, tar->entry_uname.s);
1450
1451         archive_strncpy(&(tar->entry_gname),
1452             header->gname, sizeof(header->gname));
1453         archive_entry_set_gname(entry, tar->entry_gname.s);
1454
1455         /* Parse out device numbers only for char and block specials */
1456         if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1457                 st->st_rdev = makedev (
1458                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1459                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1460         else
1461                 st->st_rdev = 0;
1462
1463         tar->entry_bytes_remaining = st->st_size;
1464         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1465
1466         /* Grab GNU-specific fields. */
1467         st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1468         st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1469         if (header->realsize[0] != 0) {
1470                 st->st_size = tar_atol(header->realsize,
1471                     sizeof(header->realsize));
1472         }
1473
1474         if (header->sparse[0].offset[0] != 0) {
1475                 gnu_read_sparse_data(a, tar, header);
1476         } else {
1477                 if (header->isextended[0] != 0) {
1478                         /* XXX WTF? XXX */
1479                 }
1480         }
1481
1482         return (0);
1483 }
1484
1485 static int
1486 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1487     const struct archive_entry_header_gnutar *header)
1488 {
1489         ssize_t bytes_read;
1490         const void *data;
1491         struct extended {
1492                 struct gnu_sparse sparse[21];
1493                 char    isextended[1];
1494                 char    padding[7];
1495         };
1496         const struct extended *ext;
1497
1498         gnu_parse_sparse_data(a, tar, header->sparse, 4);
1499         if (header->isextended[0] == 0)
1500                 return (ARCHIVE_OK);
1501
1502         do {
1503                 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1504                 if (bytes_read < 0)
1505                         return (ARCHIVE_FATAL);
1506                 if (bytes_read < 512) {
1507                         archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1508                             "Truncated tar archive "
1509                             "detected while reading sparse file data");
1510                         return (ARCHIVE_FATAL);
1511                 }
1512                 (a->compression_read_consume)(a, 512);
1513                 ext = (const struct extended *)data;
1514                 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1515         } while (ext->isextended[0] != 0);
1516         if (tar->sparse_list != NULL)
1517                 tar->entry_offset = tar->sparse_list->offset;
1518         return (ARCHIVE_OK);
1519 }
1520
1521 static void
1522 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1523     const struct gnu_sparse *sparse, int length)
1524 {
1525         struct sparse_block *last;
1526         struct sparse_block *p;
1527
1528         (void)a; /* UNUSED */
1529
1530         last = tar->sparse_list;
1531         while (last != NULL && last->next != NULL)
1532                 last = last->next;
1533
1534         while (length > 0 && sparse->offset[0] != 0) {
1535                 p = malloc(sizeof(*p));
1536                 if (p == NULL)
1537                         __archive_errx(1, "Out of memory");
1538                 memset(p, 0, sizeof(*p));
1539                 if (last != NULL)
1540                         last->next = p;
1541                 else
1542                         tar->sparse_list = p;
1543                 last = p;
1544                 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1545                 p->remaining =
1546                     tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1547                 sparse++;
1548                 length--;
1549         }
1550 }
1551
1552 /*-
1553  * Convert text->integer.
1554  *
1555  * Traditional tar formats (including POSIX) specify base-8 for
1556  * all of the standard numeric fields.  This is a significant limitation
1557  * in practice:
1558  *   = file size is limited to 8GB
1559  *   = rdevmajor and rdevminor are limited to 21 bits
1560  *   = uid/gid are limited to 21 bits
1561  *
1562  * There are two workarounds for this:
1563  *   = pax extended headers, which use variable-length string fields
1564  *   = GNU tar and STAR both allow either base-8 or base-256 in
1565  *      most fields.  The high bit is set to indicate base-256.
1566  *
1567  * On read, this implementation supports both extensions.
1568  */
1569 static int64_t
1570 tar_atol(const char *p, unsigned char_cnt)
1571 {
1572         /*
1573          * Technically, GNU tar considers a field to be in base-256
1574          * only if the first byte is 0xff or 0x80.
1575          */
1576         if (*p & 0x80)
1577                 return (tar_atol256(p, char_cnt));
1578         return (tar_atol8(p, char_cnt));
1579 }
1580
1581 /*
1582  * Note that this implementation does not (and should not!) obey
1583  * locale settings; you cannot simply substitute strtol here, since
1584  * it does obey locale.
1585  */
1586 static int64_t
1587 tar_atol8(const char *p, unsigned char_cnt)
1588 {
1589         int64_t l, limit, last_digit_limit;
1590         int digit, sign, base;
1591
1592         base = 8;
1593         limit = max_int64 / base;
1594         last_digit_limit = max_int64 % base;
1595
1596         while (*p == ' ' || *p == '\t')
1597                 p++;
1598         if (*p == '-') {
1599                 sign = -1;
1600                 p++;
1601         } else
1602                 sign = 1;
1603
1604         l = 0;
1605         digit = *p - '0';
1606         while (digit >= 0 && digit < base  && char_cnt-- > 0) {
1607                 if (l>limit || (l == limit && digit > last_digit_limit)) {
1608                         l = max_uint64; /* Truncate on overflow. */
1609                         break;
1610                 }
1611                 l = (l * base) + digit;
1612                 digit = *++p - '0';
1613         }
1614         return (sign < 0) ? -l : l;
1615 }
1616
1617
1618 /*
1619  * Note that this implementation does not (and should not!) obey
1620  * locale settings; you cannot simply substitute strtol here, since
1621  * it does obey locale.
1622  */
1623 static int64_t
1624 tar_atol10(const wchar_t *p, unsigned char_cnt)
1625 {
1626         int64_t l, limit, last_digit_limit;
1627         int base, digit, sign;
1628
1629         base = 10;
1630         limit = max_int64 / base;
1631         last_digit_limit = max_int64 % base;
1632
1633         while (*p == ' ' || *p == '\t')
1634                 p++;
1635         if (*p == '-') {
1636                 sign = -1;
1637                 p++;
1638         } else
1639                 sign = 1;
1640
1641         l = 0;
1642         digit = *p - '0';
1643         while (digit >= 0 && digit < base  && char_cnt-- > 0) {
1644                 if (l > limit || (l == limit && digit > last_digit_limit)) {
1645                         l = max_uint64; /* Truncate on overflow. */
1646                         break;
1647                 }
1648                 l = (l * base) + digit;
1649                 digit = *++p - '0';
1650         }
1651         return (sign < 0) ? -l : l;
1652 }
1653
1654 /*
1655  * Parse a base-256 integer.  This is just a straight signed binary
1656  * value in big-endian order, except that the high-order bit is
1657  * ignored.  Remember that "int64_t" may or may not be exactly 64
1658  * bits; the implementation here tries to avoid making any assumptions
1659  * about the actual size of an int64_t.  It does assume we're using
1660  * twos-complement arithmetic, though.
1661  */
1662 static int64_t
1663 tar_atol256(const char *_p, unsigned char_cnt)
1664 {
1665         int64_t l, upper_limit, lower_limit;
1666         const unsigned char *p = (const unsigned char *)_p;
1667
1668         upper_limit = max_int64 / 256;
1669         lower_limit = min_int64 / 256;
1670
1671         /* Pad with 1 or 0 bits, depending on sign. */
1672         if ((0x40 & *p) == 0x40)
1673                 l = (int64_t)-1;
1674         else
1675                 l = 0;
1676         l = (l << 6) | (0x3f & *p++);
1677         while (--char_cnt > 0) {
1678                 if (l > upper_limit) {
1679                         l = max_int64; /* Truncate on overflow */
1680                         break;
1681                 } else if (l < lower_limit) {
1682                         l = min_int64;
1683                         break;
1684                 }
1685                 l = (l << 8) | (0xff & (int64_t)*p++);
1686         }
1687         return (l);
1688 }
1689
1690 static int
1691 utf8_decode(wchar_t *dest, const char *src, size_t length)
1692 {
1693         size_t n;
1694         int err;
1695
1696         err = 0;
1697         while (length > 0) {
1698                 n = UTF8_mbrtowc(dest, src, length);
1699                 if (n == 0)
1700                         break;
1701                 dest++;
1702                 src += n;
1703                 length -= n;
1704         }
1705         *dest++ = L'\0';
1706         return (err);
1707 }
1708
1709 /*
1710  * Copied and simplified from FreeBSD libc/locale.
1711  */
1712 static size_t
1713 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1714 {
1715         int ch, i, len, mask;
1716         unsigned long wch;
1717
1718         if (s == NULL || n == 0 || pwc == NULL)
1719                 return (0);
1720
1721         /*
1722          * Determine the number of octets that make up this character from
1723          * the first octet, and a mask that extracts the interesting bits of
1724          * the first octet.
1725          */
1726         ch = (unsigned char)*s;
1727         if ((ch & 0x80) == 0) {
1728                 mask = 0x7f;
1729                 len = 1;
1730         } else if ((ch & 0xe0) == 0xc0) {
1731                 mask = 0x1f;
1732                 len = 2;
1733         } else if ((ch & 0xf0) == 0xe0) {
1734                 mask = 0x0f;
1735                 len = 3;
1736         } else if ((ch & 0xf8) == 0xf0) {
1737                 mask = 0x07;
1738                 len = 4;
1739         } else if ((ch & 0xfc) == 0xf8) {
1740                 mask = 0x03;
1741                 len = 5;
1742         } else if ((ch & 0xfe) == 0xfc) {
1743                 mask = 0x01;
1744                 len = 6;
1745         } else {
1746                 /* Invalid first byte; convert to '?' */
1747                 *pwc = '?';
1748                 return (1);
1749         }
1750
1751         if (n < (size_t)len) {
1752                 /* Invalid first byte; convert to '?' */
1753                 *pwc = '?';
1754                 return (1);
1755         }
1756
1757         /*
1758          * Decode the octet sequence representing the character in chunks
1759          * of 6 bits, most significant first.
1760          */
1761         wch = (unsigned char)*s++ & mask;
1762         i = len;
1763         while (--i != 0) {
1764                 if ((*s & 0xc0) != 0x80) {
1765                         /* Invalid intermediate byte; consume one byte and
1766                          * emit '?' */
1767                         *pwc = '?';
1768                         return (1);
1769                 }
1770                 wch <<= 6;
1771                 wch |= *s++ & 0x3f;
1772         }
1773
1774         /* Assign the value to the output; out-of-range values
1775          * just get truncated. */
1776         *pwc = (wchar_t)wch;
1777 #ifdef WCHAR_MAX
1778         /*
1779          * If platform has WCHAR_MAX, we can do something
1780          * more sensible with out-of-range values.
1781          */
1782         if (wch >= WCHAR_MAX)
1783                 *pwc = '?';
1784 #endif
1785         /* Return number of bytes input consumed: 0 for end-of-string. */
1786         return (wch == L'\0' ? 0 : len);
1787 }
1788
1789
1790 /*
1791  * base64_decode - Base64 decode
1792  *
1793  * This accepts most variations of base-64 encoding, including:
1794  *    * with or without line breaks
1795  *    * with or without the final group padded with '=' or '_' characters
1796  * (The most economical Base-64 variant does not pad the last group and
1797  * omits line breaks; RFC1341 used for MIME requires both.)
1798  */
1799 static char *
1800 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1801 {
1802         static const unsigned char digits[64] =
1803             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1804         static unsigned char decode_table[128];
1805         char *out, *d;
1806
1807         /* If the decode table is not yet initialized, prepare it. */
1808         if (decode_table[digits[1]] != 1) {
1809                 size_t i;
1810                 memset(decode_table, 0xff, sizeof(decode_table));
1811                 for (i = 0; i < sizeof(digits); i++)
1812                         decode_table[digits[i]] = i;
1813         }
1814
1815         /* Allocate enough space to hold the entire output. */
1816         /* Note that we may not use all of this... */
1817         out = malloc((len * 3 + 3) / 4);
1818         if (out == NULL) {
1819                 *out_len = 0;
1820                 return (NULL);
1821         }
1822         d = out;
1823
1824         while (len > 0) {
1825                 /* Collect the next group of (up to) four characters. */
1826                 int v = 0;
1827                 int group_size = 0;
1828                 while (group_size < 4 && len > 0) {
1829                         /* '=' or '_' padding indicates final group. */
1830                         if (*src == '=' || *src == '_') {
1831                                 len = 0;
1832                                 break;
1833                         }
1834                         /* Skip illegal characters (including line breaks) */
1835                         if (*src > 127 || *src < 32
1836                             || decode_table[*src] == 0xff) {
1837                                 len--;
1838                                 src++;
1839                                 continue;
1840                         }
1841                         v <<= 6;
1842                         v |= decode_table[*src++];
1843                         len --;
1844                         group_size++;
1845                 }
1846                 /* Align a short group properly. */
1847                 v <<= 6 * (4 - group_size);
1848                 /* Unpack the group we just collected. */
1849                 switch (group_size) {
1850                 case 4: d[2] = v & 0xff;
1851                         /* FALLTHROUGH */
1852                 case 3: d[1] = (v >> 8) & 0xff;
1853                         /* FALLTHROUGH */
1854                 case 2: d[0] = (v >> 16) & 0xff;
1855                         break;
1856                 case 1: /* this is invalid! */
1857                         break;
1858                 }
1859                 d += group_size * 3 / 4;
1860         }
1861
1862         *out_len = d - out;
1863         return (out);
1864 }
1865
1866 /*
1867  * This is a little tricky because the C99 standard wcstombs()
1868  * function returns the number of bytes that were converted,
1869  * not the number that should be converted.  As a result,
1870  * we can never accurately size the output buffer (without
1871  * doing a tedious output size calculation in advance).
1872  * This approach (try a conversion, then try again if it fails)
1873  * will almost always succeed on the first try, and is thus
1874  * much faster, at the cost of sometimes requiring multiple
1875  * passes while we expand the buffer.
1876  */
1877 static char *
1878 wide_to_narrow(const wchar_t *wval)
1879 {
1880         int converted_length;
1881         /* Guess an output buffer size and try the conversion. */
1882         int alloc_length = wcslen(wval) * 3;
1883         char *mbs_val = malloc(alloc_length + 1);
1884         if (mbs_val == NULL)
1885                 return (NULL);
1886         converted_length = wcstombs(mbs_val, wval, alloc_length);
1887
1888         /* If we exhausted the buffer, resize and try again. */
1889         while (converted_length >= alloc_length) {
1890                 free(mbs_val);
1891                 alloc_length *= 2;
1892                 mbs_val = malloc(alloc_length + 1);
1893                 if (mbs_val == NULL)
1894                         return (NULL);
1895                 converted_length = wcstombs(mbs_val, wval, alloc_length);
1896         }
1897
1898         /* Ensure a trailing null and return the final string. */
1899         mbs_val[alloc_length] = '\0';
1900         return (mbs_val);
1901 }
1902
1903 static char *
1904 url_decode(const char *in)
1905 {
1906         char *out, *d;
1907         const char *s;
1908
1909         out = malloc(strlen(in) + 1);
1910         if (out == NULL)
1911                 return (NULL);
1912         for (s = in, d = out; *s != '\0'; ) {
1913                 if (*s == '%') {
1914                         /* Try to convert % escape */
1915                         int digit1 = tohex(s[1]);
1916                         int digit2 = tohex(s[2]);
1917                         if (digit1 >= 0 && digit2 >= 0) {
1918                                 /* Looks good, consume three chars */
1919                                 s += 3;
1920                                 /* Convert output */
1921                                 *d++ = ((digit1 << 4) | digit2);
1922                                 continue;
1923                         }
1924                         /* Else fall through and treat '%' as normal char */
1925                 }
1926                 *d++ = *s++;
1927         }
1928         *d = '\0';
1929         return (out);
1930 }
1931
1932 static int
1933 tohex(int c)
1934 {
1935         if (c >= '0' && c <= '9')
1936                 return (c - '0');
1937         else if (c >= 'A' && c <= 'F')
1938                 return (c - 'A' + 10);
1939         else if (c >= 'a' && c <= 'f')
1940                 return (c - 'a' + 10);
1941         else
1942                 return (-1);
1943 }