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