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