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