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