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