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