- Add ral(4) for Ralink RT2500/RT2501/RT2600 chip based wireless NIC
[dragonfly.git] / contrib / libarchive / archive_read_support_format_tar.c
1 /*-
2  * Copyright (c) 2003-2004 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_tar.c,v 1.32 2005/04/06 04:19:30 kientzle Exp $");
29
30 #include <sys/stat.h>
31 #include <errno.h>
32 /* #include <stdint.h> */ /* See archive_platform.h */
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <wchar.h>
37
38 #include "archive.h"
39 #include "archive_entry.h"
40 #include "archive_private.h"
41
42 /*
43  * Layout of POSIX 'ustar' tar header.
44  */
45 struct archive_entry_header_ustar {
46         char    name[100];
47         char    mode[8];
48         char    uid[8];
49         char    gid[8];
50         char    size[12];
51         char    mtime[12];
52         char    checksum[8];
53         char    typeflag[1];
54         char    linkname[100];  /* "old format" header ends here */
55         char    magic[6];       /* For POSIX: "ustar\0" */
56         char    version[2];     /* For POSIX: "00" */
57         char    uname[32];
58         char    gname[32];
59         char    rdevmajor[8];
60         char    rdevminor[8];
61         char    prefix[155];
62 };
63
64 /*
65  * Structure of GNU tar header
66  */
67 struct gnu_sparse {
68         char    offset[12];
69         char    numbytes[12];
70 };
71
72 struct archive_entry_header_gnutar {
73         char    name[100];
74         char    mode[8];
75         char    uid[8];
76         char    gid[8];
77         char    size[12];
78         char    mtime[12];
79         char    checksum[8];
80         char    typeflag[1];
81         char    linkname[100];
82         char    magic[8];  /* "ustar  \0" (note blank/blank/null at end) */
83         char    uname[32];
84         char    gname[32];
85         char    rdevmajor[8];
86         char    rdevminor[8];
87         char    atime[12];
88         char    ctime[12];
89         char    offset[12];
90         char    longnames[4];
91         char    unused[1];
92         struct gnu_sparse sparse[4];
93         char    isextended[1];
94         char    realsize[12];
95         /*
96          * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
97          * entry instead.
98          */
99 };
100
101 /*
102  * Data specific to this format.
103  */
104 struct sparse_block {
105         struct sparse_block     *next;
106         off_t   offset;
107         off_t   remaining;
108 };
109
110 struct tar {
111         struct archive_string    acl_text;
112         struct archive_string    entry_name;
113         struct archive_string    entry_linkname;
114         struct archive_string    entry_uname;
115         struct archive_string    entry_gname;
116         struct archive_string    longlink;
117         struct archive_string    longname;
118         struct archive_string    pax_header;
119         struct archive_string    pax_global;
120         wchar_t                 *pax_entry;
121         size_t                   pax_entry_length;
122         int                      header_recursion_depth;
123         off_t                    entry_bytes_remaining;
124         off_t                    entry_offset;
125         off_t                    entry_padding;
126         struct sparse_block     *sparse_list;
127 };
128
129 static size_t   UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
130 static int      archive_block_is_null(const unsigned char *p);
131 int             gnu_read_sparse_data(struct archive *, struct tar *,
132                     const struct archive_entry_header_gnutar *header);
133 void            gnu_parse_sparse_data(struct archive *, struct tar *,
134                     const struct gnu_sparse *sparse, int length);
135 static int      header_Solaris_ACL(struct archive *,  struct tar *,
136                     struct archive_entry *, struct stat *, const void *);
137 static int      header_common(struct archive *,  struct tar *,
138                     struct archive_entry *, struct stat *, const void *);
139 static int      header_old_tar(struct archive *, struct tar *,
140                     struct archive_entry *, struct stat *, const void *);
141 static int      header_pax_extensions(struct archive *, struct tar *,
142                     struct archive_entry *, struct stat *, const void *);
143 static int      header_pax_global(struct archive *, struct tar *,
144                     struct archive_entry *, struct stat *, const void *h);
145 static int      header_longlink(struct archive *, struct tar *,
146                     struct archive_entry *, struct stat *, const void *h);
147 static int      header_longname(struct archive *, struct tar *,
148                     struct archive_entry *, struct stat *, const void *h);
149 static int      header_volume(struct archive *, struct tar *,
150                     struct archive_entry *, struct stat *, const void *h);
151 static int      header_ustar(struct archive *, struct tar *,
152                     struct archive_entry *, struct stat *, const void *h);
153 static int      header_gnutar(struct archive *, struct tar *,
154                     struct archive_entry *, struct stat *, const void *h);
155 static int      archive_read_format_tar_bid(struct archive *);
156 static int      archive_read_format_tar_cleanup(struct archive *);
157 static int      archive_read_format_tar_read_data(struct archive *a,
158                     const void **buff, size_t *size, off_t *offset);
159 static int      archive_read_format_tar_read_header(struct archive *,
160                     struct archive_entry *);
161 static int      checksum(struct archive *, const void *);
162 static int      pax_attribute(struct archive_entry *, struct stat *,
163                     wchar_t *key, wchar_t *value);
164 static int      pax_header(struct archive *, struct tar *,
165                     struct archive_entry *, struct stat *, char *attr);
166 static void     pax_time(const wchar_t *, int64_t *sec, long *nanos);
167 static int      read_body_to_string(struct archive *, struct tar *,
168                     struct archive_string *, const void *h);
169 static int64_t  tar_atol(const char *, unsigned);
170 static int64_t  tar_atol10(const wchar_t *, unsigned);
171 static int64_t  tar_atol256(const char *, unsigned);
172 static int64_t  tar_atol8(const char *, unsigned);
173 static int      tar_read_header(struct archive *, struct tar *,
174                     struct archive_entry *, struct stat *);
175 static int      utf8_decode(wchar_t *, const char *, size_t length);
176
177 /*
178  * ANSI C99 defines constants for these, but not everyone supports
179  * those constants, so I define a couple of static variables here and
180  * compute the values.  These calculations should be portable to any
181  * 2s-complement architecture.
182  */
183 #ifdef UINT64_MAX
184 static const uint64_t max_uint64 = UINT64_MAX;
185 #else
186 static const uint64_t max_uint64 = ~(uint64_t)0;
187 #endif
188 #ifdef INT64_MAX
189 static const int64_t max_int64 = INT64_MAX;
190 #else
191 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
192 #endif
193 #ifdef INT64_MIN
194 static const int64_t min_int64 = INT64_MIN;
195 #else
196 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
197 #endif
198
199 int
200 archive_read_support_format_gnutar(struct archive *a)
201 {
202         return (archive_read_support_format_tar(a));
203 }
204
205
206 int
207 archive_read_support_format_tar(struct archive *a)
208 {
209         struct tar *tar;
210         int r;
211
212         tar = malloc(sizeof(*tar));
213         memset(tar, 0, sizeof(*tar));
214
215         r = __archive_read_register_format(a, tar,
216             archive_read_format_tar_bid,
217             archive_read_format_tar_read_header,
218             archive_read_format_tar_read_data,
219             NULL,
220             archive_read_format_tar_cleanup);
221
222         if (r != ARCHIVE_OK)
223                 free(tar);
224         return (ARCHIVE_OK);
225 }
226
227 static int
228 archive_read_format_tar_cleanup(struct archive *a)
229 {
230         struct tar *tar;
231
232         tar = *(a->pformat_data);
233         archive_string_free(&tar->acl_text);
234         archive_string_free(&tar->entry_name);
235         archive_string_free(&tar->entry_linkname);
236         archive_string_free(&tar->entry_uname);
237         archive_string_free(&tar->entry_gname);
238         archive_string_free(&tar->pax_global);
239         archive_string_free(&tar->pax_header);
240         if (tar->pax_entry != NULL)
241                 free(tar->pax_entry);
242         free(tar);
243         *(a->pformat_data) = NULL;
244         return (ARCHIVE_OK);
245 }
246
247
248 static int
249 archive_read_format_tar_bid(struct archive *a)
250 {
251         int bid;
252         ssize_t bytes_read;
253         const void *h;
254         const struct archive_entry_header_ustar *header;
255
256         /*
257          * If we're already reading a non-tar file, don't
258          * bother to bid.
259          */
260         if (a->archive_format != 0 &&
261             (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
262             ARCHIVE_FORMAT_TAR)
263                 return (0);
264         bid = 0;
265
266         /*
267          * If we're already reading a tar format, start the bid at 1 as
268          * a failsafe.
269          */
270         if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
271             ARCHIVE_FORMAT_TAR)
272                 bid++;
273
274         /* Now let's look at the actual header and see if it matches. */
275         if (a->compression_read_ahead != NULL)
276                 bytes_read = (a->compression_read_ahead)(a, &h, 512);
277         else
278                 bytes_read = 0; /* Empty file. */
279         if (bytes_read < 0)
280                 return (ARCHIVE_FATAL);
281         if (bytes_read == 0  &&  bid > 0) {
282                 /* An archive without a proper end-of-archive marker. */
283                 /* Hold our nose and bid 1 anyway. */
284                 return (1);
285         }
286         if (bytes_read < 512) {
287                 /* If it's a new archive, then just return a zero bid. */
288                 if (bid == 0)
289                         return (0);
290                 /*
291                  * If we already know this is a tar archive,
292                  * then we have a problem.
293                  */
294                 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
295                     "Truncated tar archive");
296                 return (ARCHIVE_FATAL);
297         }
298
299         /* If it's an end-of-archive mark, we can handle it. */
300         if ((*(const char *)h) == 0 && archive_block_is_null(h)) {
301                 /* If it's a known tar file, end-of-archive is definite. */
302                 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
303                     ARCHIVE_FORMAT_TAR)
304                         return (512);
305                 /* Empty archive? */
306                 return (1);
307         }
308
309         /* If it's not an end-of-archive mark, it must have a valid checksum.*/
310         if (!checksum(a, h))
311                 return (0);
312         bid += 48;  /* Checksum is usually 6 octal digits. */
313
314         header = h;
315
316         /* Recognize POSIX formats. */
317         if ((memcmp(header->magic, "ustar\0", 6) == 0)
318             &&(memcmp(header->version, "00", 2)==0))
319                 bid += 56;
320
321         /* Recognize GNU tar format. */
322         if ((memcmp(header->magic, "ustar ", 6) == 0)
323             &&(memcmp(header->version, " \0", 2)==0))
324                 bid += 56;
325
326         /* Type flag must be null, digit or A-Z, a-z. */
327         if (header->typeflag[0] != 0 &&
328             !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
329             !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
330             !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
331                 return (0);
332         bid += 2;  /* 6 bits of variation in an 8-bit field leaves 2 bits. */
333
334         /* Sanity check: Look at first byte of mode field. */
335         switch (255 & (unsigned)header->mode[0]) {
336         case 0: case 255:
337                 /* Base-256 value: No further verification possible! */
338                 break;
339         case ' ': /* Not recommended, but not illegal, either. */
340                 break;
341         case '0': case '1': case '2': case '3':
342         case '4': case '5': case '6': case '7':
343                 /* Octal Value. */
344                 /* TODO: Check format of remainder of this field. */
345                 break;
346         default:
347                 /* Not a valid mode; bail out here. */
348                 return (0);
349         }
350         /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
351
352         return (bid);
353 }
354
355 /*
356  * The function invoked by archive_read_header().  This
357  * just sets up a few things and then calls the internal
358  * tar_read_header() function below.
359  */
360 static int
361 archive_read_format_tar_read_header(struct archive *a,
362     struct archive_entry *entry)
363 {
364         struct stat st;
365         struct tar *tar;
366         const char *p;
367         int r;
368         size_t l;
369
370         memset(&st, 0, sizeof(st));
371         tar = *(a->pformat_data);
372         tar->entry_offset = 0;
373
374         r = tar_read_header(a, tar, entry, &st);
375
376         if (r == ARCHIVE_OK) {
377                 /*
378                  * "Regular" entry with trailing '/' is really
379                  * directory: This is needed for certain old tar
380                  * variants and even for some broken newer ones.
381                  */
382                 p = archive_entry_pathname(entry);
383                 l = strlen(p);
384                 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
385                         st.st_mode &= ~S_IFMT;
386                         st.st_mode |= S_IFDIR;
387                 }
388
389                 /* Copy the final stat data into the entry. */
390                 archive_entry_copy_stat(entry, &st);
391         }
392         return (r);
393 }
394
395 static int
396 archive_read_format_tar_read_data(struct archive *a,
397     const void **buff, size_t *size, off_t *offset)
398 {
399         ssize_t bytes_read;
400         struct tar *tar;
401         struct sparse_block *p;
402
403         tar = *(a->pformat_data);
404         if (tar->entry_bytes_remaining > 0) {
405                 bytes_read = (a->compression_read_ahead)(a, buff, 1);
406                 if (bytes_read <= 0)
407                         return (ARCHIVE_FATAL);
408                 if (bytes_read > tar->entry_bytes_remaining)
409                         bytes_read = tar->entry_bytes_remaining;
410                 while (tar->sparse_list != NULL &&
411                     tar->sparse_list->remaining == 0) {
412                         p = tar->sparse_list;
413                         tar->sparse_list = p->next;
414                         free(p);
415                         if (tar->sparse_list != NULL)
416                                 tar->entry_offset = tar->sparse_list->offset;
417                 }
418                 if (tar->sparse_list != NULL) {
419                         if (tar->sparse_list->remaining < bytes_read)
420                                 bytes_read = tar->sparse_list->remaining;
421                         tar->sparse_list->remaining -= bytes_read;
422                 }
423                 *size = bytes_read;
424                 *offset = tar->entry_offset;
425                 tar->entry_offset += bytes_read;
426                 tar->entry_bytes_remaining -= bytes_read;
427                 (a->compression_read_consume)(a, bytes_read);
428                 return (ARCHIVE_OK);
429         } else {
430                 while (tar->entry_padding > 0) {
431                         bytes_read = (a->compression_read_ahead)(a, buff, 1);
432                         if (bytes_read <= 0)
433                                 return (ARCHIVE_FATAL);
434                         if (bytes_read > tar->entry_padding)
435                                 bytes_read = tar->entry_padding;
436                         (a->compression_read_consume)(a, bytes_read);
437                         tar->entry_padding -= bytes_read;
438                 }
439                 *buff = NULL;
440                 *size = 0;
441                 *offset = tar->entry_offset;
442                 return (ARCHIVE_EOF);
443         }
444 }
445
446 /*
447  * This function recursively interprets all of the headers associated
448  * with a single entry.
449  */
450 static int
451 tar_read_header(struct archive *a, struct tar *tar,
452     struct archive_entry *entry, struct stat *st)
453 {
454         ssize_t bytes;
455         int err;
456         const void *h;
457         const struct archive_entry_header_ustar *header;
458
459         /* Read 512-byte header record */
460         bytes = (a->compression_read_ahead)(a, &h, 512);
461         if (bytes < 512) {
462                 /*
463                  * If we're here, it's becase the _bid function accepted
464                  * this file.  So just call a short read end-of-archive
465                  * and be done with it.
466                  */
467                 return (ARCHIVE_EOF);
468         }
469         (a->compression_read_consume)(a, 512);
470
471         /* Check for end-of-archive mark. */
472         if (((*(const char *)h)==0) && archive_block_is_null(h)) {
473                 /* Try to consume a second all-null record, as well. */
474                 bytes = (a->compression_read_ahead)(a, &h, 512);
475                 if (bytes > 0)
476                         (a->compression_read_consume)(a, bytes);
477                 archive_set_error(a, 0, NULL);
478                 return (ARCHIVE_EOF);
479         }
480
481         /*
482          * Note: If the checksum fails and we return ARCHIVE_RETRY,
483          * then the client is likely to just retry.  This is a very
484          * crude way to search for the next valid header!
485          *
486          * TODO: Improve this by implementing a real header scan.
487          */
488         if (!checksum(a, h)) {
489                 archive_set_error(a, EINVAL, "Damaged tar archive");
490                 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
491         }
492
493         if (++tar->header_recursion_depth > 32) {
494                 archive_set_error(a, EINVAL, "Too many special headers");
495                 return (ARCHIVE_WARN);
496         }
497
498         /* Determine the format variant. */
499         header = h;
500         switch(header->typeflag[0]) {
501         case 'A': /* Solaris tar ACL */
502                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
503                 a->archive_format_name = "Solaris tar";
504                 err = header_Solaris_ACL(a, tar, entry, st, h);
505                 break;
506         case 'g': /* POSIX-standard 'g' header. */
507                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
508                 a->archive_format_name = "POSIX pax interchange format";
509                 err = header_pax_global(a, tar, entry, st, h);
510                 break;
511         case 'K': /* Long link name (GNU tar, others) */
512                 err = header_longlink(a, tar, entry, st, h);
513                 break;
514         case 'L': /* Long filename (GNU tar, others) */
515                 err = header_longname(a, tar, entry, st, h);
516                 break;
517         case 'V': /* GNU volume header */
518                 err = header_volume(a, tar, entry, st, h);
519                 break;
520         case 'X': /* Used by SUN tar; same as 'x'. */
521                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
522                 a->archive_format_name =
523                     "POSIX pax interchange format (Sun variant)";
524                 err = header_pax_extensions(a, tar, entry, st, h);
525                 break;
526         case 'x': /* POSIX-standard 'x' header. */
527                 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
528                 a->archive_format_name = "POSIX pax interchange format";
529                 err = header_pax_extensions(a, tar, entry, st, h);
530                 break;
531         default:
532                 if (memcmp(header->magic, "ustar  \0", 8) == 0) {
533                         a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
534                         a->archive_format_name = "GNU tar format";
535                         err = header_gnutar(a, tar, entry, st, h);
536                 } else if (memcmp(header->magic, "ustar", 5) == 0) {
537                         if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
538                                 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
539                                 a->archive_format_name = "POSIX ustar format";
540                         }
541                         err = header_ustar(a, tar, entry, st, h);
542                 } else {
543                         a->archive_format = ARCHIVE_FORMAT_TAR;
544                         a->archive_format_name = "tar (non-POSIX)";
545                         err = header_old_tar(a, tar, entry, st, h);
546                 }
547         }
548         --tar->header_recursion_depth;
549         return (err);
550 }
551
552 /*
553  * Return true if block checksum is correct.
554  */
555 static int
556 checksum(struct archive *a, const void *h)
557 {
558         const unsigned char *bytes;
559         const struct archive_entry_header_ustar *header;
560         int check, i, sum;
561
562         (void)a; /* UNUSED */
563         bytes = h;
564         header = h;
565
566         /*
567          * Test the checksum.  Note that POSIX specifies _unsigned_
568          * bytes for this calculation.
569          */
570         sum = tar_atol(header->checksum, sizeof(header->checksum));
571         check = 0;
572         for (i = 0; i < 148; i++)
573                 check += (unsigned char)bytes[i];
574         for (; i < 156; i++)
575                 check += 32;
576         for (; i < 512; i++)
577                 check += (unsigned char)bytes[i];
578         if (sum == check)
579                 return (1);
580
581         /*
582          * Repeat test with _signed_ bytes, just in case this archive
583          * was created by an old BSD, Solaris, or HP-UX tar with a
584          * broken checksum calculation.
585          */
586         check = 0;
587         for (i = 0; i < 148; i++)
588                 check += (signed char)bytes[i];
589         for (; i < 156; i++)
590                 check += 32;
591         for (; i < 512; i++)
592                 check += (signed char)bytes[i];
593         if (sum == check)
594                 return (1);
595
596         return (0);
597 }
598
599 /*
600  * Return true if this block contains only nulls.
601  */
602 static int
603 archive_block_is_null(const unsigned char *p)
604 {
605         unsigned i;
606
607         for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
608                 if (*p++)
609                         return (0);
610         return (1);
611 }
612
613 /*
614  * Interpret 'A' Solaris ACL header
615  */
616 static int
617 header_Solaris_ACL(struct archive *a, struct tar *tar,
618     struct archive_entry *entry, struct stat *st, const void *h)
619 {
620         int err, err2;
621         char *p;
622         wchar_t *wp;
623
624         err = read_body_to_string(a, tar, &(tar->acl_text), h);
625         err2 = tar_read_header(a, tar, entry, st);
626         err = err_combine(err, err2);
627
628         /* XXX Ensure p doesn't overrun acl_text */
629
630         /* Skip leading octal number. */
631         /* XXX TODO: Parse the octal number and sanity-check it. */
632         p = tar->acl_text.s;
633         while (*p != '\0')
634                 p++;
635         p++;
636
637         wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
638         if (wp != NULL) {
639                 utf8_decode(wp, p, strlen(p));
640                 err2 = __archive_entry_acl_parse_w(entry, wp,
641                     ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
642                 err = err_combine(err, err2);
643                 free(wp);
644         }
645
646         return (err);
647 }
648
649 /*
650  * Interpret 'K' long linkname header.
651  */
652 static int
653 header_longlink(struct archive *a, struct tar *tar,
654     struct archive_entry *entry, struct stat *st, const void *h)
655 {
656         int err, err2;
657
658         err = read_body_to_string(a, tar, &(tar->longlink), h);
659         err2 = tar_read_header(a, tar, entry, st);
660         if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
661                 /* Set symlink if symlink already set, else hardlink. */
662                 archive_entry_set_link(entry, tar->longlink.s);
663         }
664         return (err_combine(err, err2));
665 }
666
667 /*
668  * Interpret 'L' long filename header.
669  */
670 static int
671 header_longname(struct archive *a, struct tar *tar,
672     struct archive_entry *entry, struct stat *st, const void *h)
673 {
674         int err, err2;
675
676         err = read_body_to_string(a, tar, &(tar->longname), h);
677         /* Read and parse "real" header, then override name. */
678         err2 = tar_read_header(a, tar, entry, st);
679         if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
680                 archive_entry_set_pathname(entry, tar->longname.s);
681         return (err_combine(err, err2));
682 }
683
684
685 /*
686  * Interpret 'V' GNU tar volume header.
687  */
688 static int
689 header_volume(struct archive *a, struct tar *tar,
690     struct archive_entry *entry, struct stat *st, const void *h)
691 {
692         (void)h;
693
694         /* Just skip this and read the next header. */
695         return (tar_read_header(a, tar, entry, st));
696 }
697
698 /*
699  * Read body of an archive entry into an archive_string object.
700  */
701 static int
702 read_body_to_string(struct archive *a, struct tar *tar,
703     struct archive_string *as, const void *h)
704 {
705         off_t size, padded_size;
706         ssize_t bytes_read, bytes_to_copy;
707         const struct archive_entry_header_ustar *header;
708         const void *src;
709         char *dest;
710
711         (void)tar; /* UNUSED */
712         header = h;
713         size  = tar_atol(header->size, sizeof(header->size));
714
715         /* Read the body into the string. */
716         archive_string_ensure(as, size+1);
717         padded_size = (size + 511) & ~ 511;
718         dest = as->s;
719         while (padded_size > 0) {
720                 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
721                 if (bytes_read < 0)
722                         return (ARCHIVE_FATAL);
723                 if (bytes_read > padded_size)
724                         bytes_read = padded_size;
725                 (a->compression_read_consume)(a, bytes_read);
726                 bytes_to_copy = bytes_read;
727                 if ((off_t)bytes_to_copy > size)
728                         bytes_to_copy = (ssize_t)size;
729                 memcpy(dest, src, bytes_to_copy);
730                 dest += bytes_to_copy;
731                 size -= bytes_to_copy;
732                 padded_size -= bytes_read;
733         }
734         *dest = '\0';
735         return (ARCHIVE_OK);
736 }
737
738 /*
739  * Parse out common header elements.
740  *
741  * This would be the same as header_old_tar, except that the
742  * filename is handled slightly differently for old and POSIX
743  * entries  (POSIX entries support a 'prefix').  This factoring
744  * allows header_old_tar and header_ustar
745  * to handle filenames differently, while still putting most of the
746  * common parsing into one place.
747  */
748 static int
749 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
750     struct stat *st, const void *h)
751 {
752         const struct archive_entry_header_ustar *header;
753         char    tartype;
754
755         (void)a; /* UNUSED */
756
757         header = h;
758         if (header->linkname[0])
759                 archive_strncpy(&(tar->entry_linkname), header->linkname,
760                     sizeof(header->linkname));
761         else
762                 archive_string_empty(&(tar->entry_linkname));
763
764         /* Parse out the numeric fields (all are octal) */
765         st->st_mode  = tar_atol(header->mode, sizeof(header->mode));
766         st->st_uid   = tar_atol(header->uid, sizeof(header->uid));
767         st->st_gid   = tar_atol(header->gid, sizeof(header->gid));
768         st->st_size  = tar_atol(header->size, sizeof(header->size));
769         st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
770
771         /* Handle the tar type flag appropriately. */
772         tartype = header->typeflag[0];
773         st->st_mode &= ~S_IFMT;
774
775         switch (tartype) {
776         case '1': /* Hard link */
777                 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
778                 /*
779                  * The following may seem odd, but: Technically, tar
780                  * does not store the file type for a "hard link"
781                  * entry, only the fact that it is a hard link.  So, I
782                  * leave the type zero normally.  But, pax interchange
783                  * format allows hard links to have data, which
784                  * implies that the underlying entry is a regular
785                  * file.
786                  */
787                 if (st->st_size > 0)
788                         st->st_mode |= S_IFREG;
789
790                 /*
791                  * A tricky point: Traditionally, tar readers have
792                  * ignored the size field when reading hardlink
793                  * entries, and some writers put non-zero sizes even
794                  * though the body is empty.  POSIX.1-2001 broke with
795                  * this tradition by permitting hardlink entries to
796                  * store valid bodies in pax interchange format, but
797                  * not in ustar format.  Since there is no hard and
798                  * fast way to distinguish pax interchange from
799                  * earlier archives (the 'x' and 'g' entries are
800                  * optional, after all), we need a heuristic.  Here, I
801                  * use the bid function to test whether or not there's
802                  * a valid header following.  Of course, if we know
803                  * this is pax interchange format, then we must obey
804                  * the size.
805                  *
806                  * This heuristic will only fail for a pax interchange
807                  * archive that is storing hardlink bodies, no pax
808                  * extended attribute entries have yet occurred, and
809                  * we encounter a hardlink entry for a file that is
810                  * itself an uncompressed tar archive.
811                  */
812                 if (st->st_size > 0  &&
813                     a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE  &&
814                     archive_read_format_tar_bid(a) > 50)
815                         st->st_size = 0;
816                 break;
817         case '2': /* Symlink */
818                 st->st_mode |= S_IFLNK;
819                 st->st_size = 0;
820                 archive_entry_set_symlink(entry, tar->entry_linkname.s);
821                 break;
822         case '3': /* Character device */
823                 st->st_mode |= S_IFCHR;
824                 st->st_size = 0;
825                 break;
826         case '4': /* Block device */
827                 st->st_mode |= S_IFBLK;
828                 st->st_size = 0;
829                 break;
830         case '5': /* Dir */
831                 st->st_mode |= S_IFDIR;
832                 st->st_size = 0;
833                 break;
834         case '6': /* FIFO device */
835                 st->st_mode |= S_IFIFO;
836                 st->st_size = 0;
837                 break;
838         case 'D': /* GNU incremental directory type */
839                 /*
840                  * No special handling is actually required here.
841                  * It might be nice someday to preprocess the file list and
842                  * provide it to the client, though.
843                  */
844                 st->st_mode |= S_IFDIR;
845                 break;
846         case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
847                 /*
848                  * As far as I can tell, this is just like a regular file
849                  * entry, except that the contents should be _appended_ to
850                  * the indicated file at the indicated offset.  This may
851                  * require some API work to fully support.
852                  */
853                 break;
854         case 'N': /* Old GNU "long filename" entry. */
855                 /* The body of this entry is a script for renaming
856                  * previously-extracted entries.  Ugh.  It will never
857                  * be supported by libarchive. */
858                 st->st_mode |= S_IFREG;
859                 break;
860         case 'S': /* GNU sparse files */
861                 /*
862                  * Sparse files are really just regular files with
863                  * sparse information in the extended area.
864                  */
865                 /* FALL THROUGH */
866         default: /* Regular file  and non-standard types */
867                 /*
868                  * Per POSIX: non-recognized types should always be
869                  * treated as regular files.
870                  */
871                 st->st_mode |= S_IFREG;
872                 break;
873         }
874         return (0);
875 }
876
877 /*
878  * Parse out header elements for "old-style" tar archives.
879  */
880 static int
881 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
882     struct stat *st, const void *h)
883 {
884         const struct archive_entry_header_ustar *header;
885
886         /* Copy filename over (to ensure null termination). */
887         header = h;
888         archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
889         archive_entry_set_pathname(entry, tar->entry_name.s);
890
891         /* Grab rest of common fields */
892         header_common(a, tar, entry, st, h);
893
894         tar->entry_bytes_remaining = st->st_size;
895         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
896         return (0);
897 }
898
899 /*
900  * Parse a file header for a pax extended archive entry.
901  */
902 static int
903 header_pax_global(struct archive *a, struct tar *tar,
904     struct archive_entry *entry, struct stat *st, const void *h)
905 {
906         int err, err2;
907
908         err = read_body_to_string(a, tar, &(tar->pax_global), h);
909         err2 = tar_read_header(a, tar, entry, st);
910         return (err_combine(err, err2));
911 }
912
913 static int
914 header_pax_extensions(struct archive *a, struct tar *tar,
915     struct archive_entry *entry, struct stat *st, const void *h)
916 {
917         int err, err2;
918
919         read_body_to_string(a, tar, &(tar->pax_header), h);
920
921         /* Parse the next header. */
922         err = tar_read_header(a, tar, entry, st);
923
924         /*
925          * TODO: Parse global/default options into 'entry' struct here
926          * before handling file-specific options.
927          *
928          * This design (parse standard header, then overwrite with pax
929          * extended attribute data) usually works well, but isn't ideal;
930          * it would be better to parse the pax extended attributes first
931          * and then skip any fields in the standard header that were
932          * defined in the pax header.
933          */
934         err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
935         err =  err_combine(err, err2);
936         tar->entry_bytes_remaining = st->st_size;
937         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
938         return (err);
939 }
940
941
942 /*
943  * Parse a file header for a Posix "ustar" archive entry.  This also
944  * handles "pax" or "extended ustar" entries.
945  */
946 static int
947 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
948     struct stat *st, const void *h)
949 {
950         const struct archive_entry_header_ustar *header;
951         struct archive_string *as;
952
953         header = h;
954
955         /* Copy name into an internal buffer to ensure null-termination. */
956         as = &(tar->entry_name);
957         if (header->prefix[0]) {
958                 archive_strncpy(as, header->prefix, sizeof(header->prefix));
959                 if (as->s[archive_strlen(as) - 1] != '/')
960                         archive_strappend_char(as, '/');
961                 archive_strncat(as, header->name, sizeof(header->name));
962         } else
963                 archive_strncpy(as, header->name, sizeof(header->name));
964
965         archive_entry_set_pathname(entry, as->s);
966
967         /* Handle rest of common fields. */
968         header_common(a, tar, entry, st, h);
969
970         /* Handle POSIX ustar fields. */
971         archive_strncpy(&(tar->entry_uname), header->uname,
972             sizeof(header->uname));
973         archive_entry_set_uname(entry, tar->entry_uname.s);
974
975         archive_strncpy(&(tar->entry_gname), header->gname,
976             sizeof(header->gname));
977         archive_entry_set_gname(entry, tar->entry_gname.s);
978
979         /* Parse out device numbers only for char and block specials. */
980         if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
981                 st->st_rdev = makedev(
982                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
983                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
984         }
985
986         tar->entry_bytes_remaining = st->st_size;
987         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
988
989         return (0);
990 }
991
992
993 /*
994  * Parse the pax extended attributes record.
995  *
996  * Returns non-zero if there's an error in the data.
997  */
998 static int
999 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1000     struct stat *st, char *attr)
1001 {
1002         size_t attr_length, l, line_length;
1003         char *line, *p;
1004         wchar_t *key, *wp, *value;
1005         int err, err2;
1006
1007         attr_length = strlen(attr);
1008         err = ARCHIVE_OK;
1009         while (attr_length > 0) {
1010                 /* Parse decimal length field at start of line. */
1011                 line_length = 0;
1012                 l = attr_length;
1013                 line = p = attr; /* Record start of line. */
1014                 while (l>0) {
1015                         if (*p == ' ') {
1016                                 p++;
1017                                 l--;
1018                                 break;
1019                         }
1020                         if (*p < '0' || *p > '9')
1021                                 return (-1);
1022                         line_length *= 10;
1023                         line_length += *p - '0';
1024                         if (line_length > 999999) {
1025                                 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1026                                     "Rejecting pax extended attribute > 1MB");
1027                                 return (ARCHIVE_WARN);
1028                         }
1029                         p++;
1030                         l--;
1031                 }
1032
1033                 if (line_length > attr_length)
1034                         return (0);
1035
1036                 /* Ensure pax_entry buffer is big enough. */
1037                 if (tar->pax_entry_length <= line_length) {
1038                         if (tar->pax_entry_length <= 0)
1039                                 tar->pax_entry_length = 1024;
1040                         while (tar->pax_entry_length <= line_length + 1)
1041                                 tar->pax_entry_length *= 2;
1042
1043                         /* XXX Error handling here */
1044                         tar->pax_entry = realloc(tar->pax_entry,
1045                             tar->pax_entry_length * sizeof(wchar_t));
1046                 }
1047
1048                 /* Decode UTF-8 to wchar_t, null-terminate result. */
1049                 if (utf8_decode(tar->pax_entry, p,
1050                         line_length - (p - attr) - 1)) {
1051                         archive_set_error(a, ARCHIVE_ERRNO_MISC,
1052                            "Invalid UTF8 character in pax extended attribute");
1053                         err = err_combine(err, ARCHIVE_WARN);
1054                 }
1055
1056                 /* Null-terminate 'key' value. */
1057                 key = tar->pax_entry;
1058                 if (key[0] == L'=')
1059                         return (-1);
1060                 wp = wcschr(key, L'=');
1061                 if (wp == NULL) {
1062                         archive_set_error(a, ARCHIVE_ERRNO_MISC,
1063                             "Invalid pax extended attributes");
1064                         return (ARCHIVE_WARN);
1065                 }
1066                 *wp = 0;
1067
1068                 /* Identify null-terminated 'value' portion. */
1069                 value = wp + 1;
1070
1071                 /* Identify this attribute and set it in the entry. */
1072                 err2 = pax_attribute(entry, st, key, value);
1073                 err = err_combine(err, err2);
1074
1075                 /* Skip to next line */
1076                 attr += line_length;
1077                 attr_length -= line_length;
1078         }
1079         return (err);
1080 }
1081
1082
1083
1084 /*
1085  * Parse a single key=value attribute.  key/value pointers are
1086  * assumed to point into reasonably long-lived storage.
1087  *
1088  * Note that POSIX reserves all-lowercase keywords.  Vendor-specific
1089  * extensions should always have keywords of the form "VENDOR.attribute"
1090  * In particular, it's quite feasible to support many different
1091  * vendor extensions here.  I'm using "LIBARCHIVE" for extensions
1092  * unique to this library (currently, there are none).
1093  *
1094  * Investigate other vendor-specific extensions, as well and see if
1095  * any of them look useful.
1096  */
1097 static int
1098 pax_attribute(struct archive_entry *entry, struct stat *st,
1099     wchar_t *key, wchar_t *value)
1100 {
1101         int64_t s;
1102         long n;
1103
1104         switch (key[0]) {
1105         case 'L':
1106                 /* Our extensions */
1107 /* TODO: Handle arbitrary extended attributes... */
1108 /*
1109                 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1110                         archive_entry_set_xxxxxx(entry, value);
1111 */
1112                 break;
1113         case 'S':
1114                 /* We support some keys used by the "star" archiver */
1115                 if (wcscmp(key, L"SCHILY.acl.access")==0)
1116                         __archive_entry_acl_parse_w(entry, value,
1117                             ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1118                 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1119                         __archive_entry_acl_parse_w(entry, value,
1120                             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1121                 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1122                         st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1123                             minor(st->st_rdev));
1124                 else if (wcscmp(key, L"SCHILY.devminor")==0)
1125                         st->st_rdev = makedev(major(st->st_rdev),
1126                             tar_atol10(value, wcslen(value)));
1127                 else if (wcscmp(key, L"SCHILY.fflags")==0)
1128                         archive_entry_copy_fflags_text_w(entry, value);
1129                 else if (wcscmp(key, L"SCHILY.nlink")==0)
1130                         st->st_nlink = tar_atol10(value, wcslen(value));
1131                 break;
1132         case 'a':
1133                 if (wcscmp(key, L"atime")==0) {
1134                         pax_time(value, &s, &n);
1135                         st->st_atime = s;
1136                         ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1137                 }
1138                 break;
1139         case 'c':
1140                 if (wcscmp(key, L"ctime")==0) {
1141                         pax_time(value, &s, &n);
1142                         st->st_ctime = s;
1143                         ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1144                 } else if (wcscmp(key, L"charset")==0) {
1145                         /* TODO: Publish charset information in entry. */
1146                 } else if (wcscmp(key, L"comment")==0) {
1147                         /* TODO: Publish comment in entry. */
1148                 }
1149                 break;
1150         case 'g':
1151                 if (wcscmp(key, L"gid")==0)
1152                         st->st_gid = tar_atol10(value, wcslen(value));
1153                 else if (wcscmp(key, L"gname")==0)
1154                         archive_entry_copy_gname_w(entry, value);
1155                 break;
1156         case 'l':
1157                 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1158                 if (wcscmp(key, L"linkpath")==0) {
1159                         if (archive_entry_hardlink(entry))
1160                                 archive_entry_copy_hardlink_w(entry, value);
1161                         else
1162                                 archive_entry_copy_symlink_w(entry, value);
1163                 }
1164                 break;
1165         case 'm':
1166                 if (wcscmp(key, L"mtime")==0) {
1167                         pax_time(value, &s, &n);
1168                         st->st_mtime = s;
1169                         ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1170                 }
1171                 break;
1172         case 'p':
1173                 if (wcscmp(key, L"path")==0)
1174                         archive_entry_copy_pathname_w(entry, value);
1175                 break;
1176         case 'r':
1177                 /* POSIX has reserved 'realtime.*' */
1178                 break;
1179         case 's':
1180                 /* POSIX has reserved 'security.*' */
1181                 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1182                 if (wcscmp(key, L"size")==0)
1183                         st->st_size = tar_atol10(value, wcslen(value));
1184                 break;
1185         case 'u':
1186                 if (wcscmp(key, L"uid")==0)
1187                         st->st_uid = tar_atol10(value, wcslen(value));
1188                 else if (wcscmp(key, L"uname")==0)
1189                         archive_entry_copy_uname_w(entry, value);
1190                 break;
1191         }
1192         return (0);
1193 }
1194
1195
1196
1197 /*
1198  * parse a decimal time value, which may include a fractional portion
1199  */
1200 static void
1201 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1202 {
1203         char digit;
1204         int64_t s;
1205         unsigned long l;
1206         int sign;
1207         int64_t limit, last_digit_limit;
1208
1209         limit = max_int64 / 10;
1210         last_digit_limit = max_int64 % 10;
1211
1212         s = 0;
1213         sign = 1;
1214         if (*p == '-') {
1215                 sign = -1;
1216                 p++;
1217         }
1218         while (*p >= '0' && *p <= '9') {
1219                 digit = *p - '0';
1220                 if (s > limit ||
1221                     (s == limit && digit > last_digit_limit)) {
1222                         s = max_uint64;
1223                         break;
1224                 }
1225                 s = (s * 10) + digit;
1226                 ++p;
1227         }
1228
1229         *ps = s * sign;
1230
1231         /* Calculate nanoseconds. */
1232         *pn = 0;
1233
1234         if (*p != '.')
1235                 return;
1236
1237         l = 100000000UL;
1238         do {
1239                 ++p;
1240                 if (*p >= '0' && *p <= '9')
1241                         *pn += (*p - '0') * l;
1242                 else
1243                         break;
1244         } while (l /= 10);
1245 }
1246
1247 /*
1248  * Parse GNU tar header
1249  */
1250 static int
1251 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1252     struct stat *st, const void *h)
1253 {
1254         const struct archive_entry_header_gnutar *header;
1255
1256         (void)a;
1257
1258         /*
1259          * GNU header is like POSIX ustar, except 'prefix' is
1260          * replaced with some other fields. This also means the
1261          * filename is stored as in old-style archives.
1262          */
1263
1264         /* Grab fields common to all tar variants. */
1265         header_common(a, tar, entry, st, h);
1266
1267         /* Copy filename over (to ensure null termination). */
1268         header = h;
1269         archive_strncpy(&(tar->entry_name), header->name,
1270             sizeof(header->name));
1271         archive_entry_set_pathname(entry, tar->entry_name.s);
1272
1273         /* Fields common to ustar and GNU */
1274         /* XXX Can the following be factored out since it's common
1275          * to ustar and gnu tar?  Is it okay to move it down into
1276          * header_common, perhaps?  */
1277         archive_strncpy(&(tar->entry_uname),
1278             header->uname, sizeof(header->uname));
1279         archive_entry_set_uname(entry, tar->entry_uname.s);
1280
1281         archive_strncpy(&(tar->entry_gname),
1282             header->gname, sizeof(header->gname));
1283         archive_entry_set_gname(entry, tar->entry_gname.s);
1284
1285         /* Parse out device numbers only for char and block specials */
1286         if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1287                 st->st_rdev = makedev (
1288                     tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1289                     tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1290         else
1291                 st->st_rdev = 0;
1292
1293         tar->entry_bytes_remaining = st->st_size;
1294         tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1295
1296         /* Grab GNU-specific fields. */
1297         st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1298         st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1299         if (header->realsize[0] != 0) {
1300                 st->st_size = tar_atol(header->realsize,
1301                     sizeof(header->realsize));
1302         }
1303
1304         if (header->sparse[0].offset[0] != 0) {
1305                 gnu_read_sparse_data(a, tar, header);
1306         } else {
1307                 if (header->isextended[0] != 0) {
1308                         /* XXX WTF? XXX */
1309                 }
1310         }
1311
1312         return (0);
1313 }
1314
1315 int
1316 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1317     const struct archive_entry_header_gnutar *header)
1318 {
1319         ssize_t bytes_read;
1320         const void *data;
1321         struct extended {
1322                 struct gnu_sparse sparse[21];
1323                 char    isextended[1];
1324                 char    padding[7];
1325         };
1326         const struct extended *ext;
1327
1328         gnu_parse_sparse_data(a, tar, header->sparse, 4);
1329         if (header->isextended[0] == 0)
1330                 return (ARCHIVE_OK);
1331
1332         do {
1333                 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1334                 if (bytes_read < 0)
1335                         return (ARCHIVE_FATAL);
1336                 if (bytes_read < 512) {
1337                         archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1338                             "Truncated tar archive "
1339                             "detected while reading sparse file data");
1340                         return (ARCHIVE_FATAL);
1341                 }
1342                 (a->compression_read_consume)(a, 512);
1343                 ext = (const struct extended *)data;
1344                 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1345         } while (ext->isextended[0] != 0);
1346         if (tar->sparse_list != NULL)
1347                 tar->entry_offset = tar->sparse_list->offset;
1348         return (ARCHIVE_OK);
1349 }
1350
1351 void
1352 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1353     const struct gnu_sparse *sparse, int length)
1354 {
1355         struct sparse_block *last;
1356         struct sparse_block *p;
1357
1358         (void)a; /* UNUSED */
1359
1360         last = tar->sparse_list;
1361         while (last != NULL && last->next != NULL)
1362                 last = last->next;
1363
1364         while (length > 0 && sparse->offset[0] != 0) {
1365                 p = malloc(sizeof(*p));
1366                 memset(p, 0, sizeof(*p));
1367                 if (last != NULL)
1368                         last->next = p;
1369                 else
1370                         tar->sparse_list = p;
1371                 last = p;
1372                 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1373                 p->remaining =
1374                     tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1375                 sparse++;
1376                 length--;
1377         }
1378 }
1379
1380 /*-
1381  * Convert text->integer.
1382  *
1383  * Traditional tar formats (including POSIX) specify base-8 for
1384  * all of the standard numeric fields.  This is a significant limitation
1385  * in practice:
1386  *   = file size is limited to 8GB
1387  *   = rdevmajor and rdevminor are limited to 21 bits
1388  *   = uid/gid are limited to 21 bits
1389  *
1390  * There are two workarounds for this:
1391  *   = pax extended headers, which use variable-length string fields
1392  *   = GNU tar and STAR both allow either base-8 or base-256 in
1393  *      most fields.  The high bit is set to indicate base-256.
1394  *
1395  * On read, this implementation supports both extensions.
1396  */
1397 static int64_t
1398 tar_atol(const char *p, unsigned char_cnt)
1399 {
1400         /*
1401          * Technically, GNU tar considers a field to be in base-256
1402          * only if the first byte is 0xff or 0x80.
1403          */
1404         if (*p & 0x80)
1405                 return (tar_atol256(p, char_cnt));
1406         return (tar_atol8(p, char_cnt));
1407 }
1408
1409 /*
1410  * Note that this implementation does not (and should not!) obey
1411  * locale settings; you cannot simply substitute strtol here, since
1412  * it does obey locale.
1413  */
1414 static int64_t
1415 tar_atol8(const char *p, unsigned char_cnt)
1416 {
1417         int64_t l, limit, last_digit_limit;
1418         int digit, sign, base;
1419
1420         base = 8;
1421         limit = max_int64 / base;
1422         last_digit_limit = max_int64 % base;
1423
1424         while (*p == ' ' || *p == '\t')
1425                 p++;
1426         if (*p == '-') {
1427                 sign = -1;
1428                 p++;
1429         } else
1430                 sign = 1;
1431
1432         l = 0;
1433         digit = *p - '0';
1434         while (digit >= 0 && digit < base  && char_cnt-- > 0) {
1435                 if (l>limit || (l == limit && digit > last_digit_limit)) {
1436                         l = max_uint64; /* Truncate on overflow. */
1437                         break;
1438                 }
1439                 l = (l * base) + digit;
1440                 digit = *++p - '0';
1441         }
1442         return (sign < 0) ? -l : l;
1443 }
1444
1445
1446 /*
1447  * Note that this implementation does not (and should not!) obey
1448  * locale settings; you cannot simply substitute strtol here, since
1449  * it does obey locale.
1450  */
1451 static int64_t
1452 tar_atol10(const wchar_t *p, unsigned char_cnt)
1453 {
1454         int64_t l, limit, last_digit_limit;
1455         int base, digit, sign;
1456
1457         base = 10;
1458         limit = max_int64 / base;
1459         last_digit_limit = max_int64 % base;
1460
1461         while (*p == ' ' || *p == '\t')
1462                 p++;
1463         if (*p == '-') {
1464                 sign = -1;
1465                 p++;
1466         } else
1467                 sign = 1;
1468
1469         l = 0;
1470         digit = *p - '0';
1471         while (digit >= 0 && digit < base  && char_cnt-- > 0) {
1472                 if (l > limit || (l == limit && digit > last_digit_limit)) {
1473                         l = max_uint64; /* Truncate on overflow. */
1474                         break;
1475                 }
1476                 l = (l * base) + digit;
1477                 digit = *++p - '0';
1478         }
1479         return (sign < 0) ? -l : l;
1480 }
1481
1482 /*
1483  * Parse a base-256 integer.  This is just a straight signed binary
1484  * value in big-endian order, except that the high-order bit is
1485  * ignored.  Remember that "int64_t" may or may not be exactly 64
1486  * bits; the implementation here tries to avoid making any assumptions
1487  * about the actual size of an int64_t.  It does assume we're using
1488  * twos-complement arithmetic, though.
1489  */
1490 static int64_t
1491 tar_atol256(const char *_p, unsigned char_cnt)
1492 {
1493         int64_t l, upper_limit, lower_limit;
1494         const unsigned char *p = _p;
1495
1496         upper_limit = max_int64 / 256;
1497         lower_limit = min_int64 / 256;
1498
1499         /* Pad with 1 or 0 bits, depending on sign. */
1500         if ((0x40 & *p) == 0x40)
1501                 l = (int64_t)-1;
1502         else
1503                 l = 0;
1504         l = (l << 6) | (0x3f & *p++);
1505         while (--char_cnt > 0) {
1506                 if (l > upper_limit) {
1507                         l = max_int64; /* Truncate on overflow */
1508                         break;
1509                 } else if (l < lower_limit) {
1510                         l = min_int64;
1511                         break;
1512                 }
1513                 l = (l << 8) | (0xff & (int64_t)*p++);
1514         }
1515         return (l);
1516 }
1517
1518 static int
1519 utf8_decode(wchar_t *dest, const char *src, size_t length)
1520 {
1521         size_t n;
1522         int err;
1523
1524         err = 0;
1525         while(length > 0) {
1526                 n = UTF8_mbrtowc(dest, src, length);
1527                 if (n == 0)
1528                         break;
1529                 if (n > 8) {
1530                         /* Invalid byte encountered; try to keep going. */
1531                         *dest = L'?';
1532                         n = 1;
1533                         err = 1;
1534                 }
1535                 dest++;
1536                 src += n;
1537                 length -= n;
1538         }
1539         *dest++ = L'\0';
1540         return (err);
1541 }
1542
1543 /*
1544  * Copied from FreeBSD libc/locale.
1545  */
1546 static size_t
1547 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1548 {
1549         int ch, i, len, mask;
1550         unsigned long lbound, wch;
1551
1552         if (s == NULL)
1553                 /* Reset to initial shift state (no-op) */
1554                 return (0);
1555         if (n == 0)
1556                 /* Incomplete multibyte sequence */
1557                 return ((size_t)-2);
1558
1559         /*
1560          * Determine the number of octets that make up this character from
1561          * the first octet, and a mask that extracts the interesting bits of
1562          * the first octet.
1563          *
1564          * We also specify a lower bound for the character code to detect
1565          * redundant, non-"shortest form" encodings. For example, the
1566          * sequence C0 80 is _not_ a legal representation of the null
1567          * character. This enforces a 1-to-1 mapping between character
1568          * codes and their multibyte representations.
1569          */
1570         ch = (unsigned char)*s;
1571         if ((ch & 0x80) == 0) {
1572                 mask = 0x7f;
1573                 len = 1;
1574                 lbound = 0;
1575         } else if ((ch & 0xe0) == 0xc0) {
1576                 mask = 0x1f;
1577                 len = 2;
1578                 lbound = 0x80;
1579         } else if ((ch & 0xf0) == 0xe0) {
1580                 mask = 0x0f;
1581                 len = 3;
1582                 lbound = 0x800;
1583         } else if ((ch & 0xf8) == 0xf0) {
1584                 mask = 0x07;
1585                 len = 4;
1586                 lbound = 0x10000;
1587         } else if ((ch & 0xfc) == 0xf8) {
1588                 mask = 0x03;
1589                 len = 5;
1590                 lbound = 0x200000;
1591         } else if ((ch & 0xfc) == 0xfc) {
1592                 mask = 0x01;
1593                 len = 6;
1594                 lbound = 0x4000000;
1595         } else {
1596                 /*
1597                  * Malformed input; input is not UTF-8.
1598                  */
1599                 errno = EILSEQ;
1600                 return ((size_t)-1);
1601         }
1602
1603         if (n < (size_t)len)
1604                 /* Incomplete multibyte sequence */
1605                 return ((size_t)-2);
1606
1607         /*
1608          * Decode the octet sequence representing the character in chunks
1609          * of 6 bits, most significant first.
1610          */
1611         wch = (unsigned char)*s++ & mask;
1612         i = len;
1613         while (--i != 0) {
1614                 if ((*s & 0xc0) != 0x80) {
1615                         /*
1616                          * Malformed input; bad characters in the middle
1617                          * of a character.
1618                          */
1619                         errno = EILSEQ;
1620                         return ((size_t)-1);
1621                 }
1622                 wch <<= 6;
1623                 wch |= *s++ & 0x3f;
1624         }
1625         if (wch < lbound) {
1626                 /*
1627                  * Malformed input; redundant encoding.
1628                  */
1629                 errno = EILSEQ;
1630                 return ((size_t)-1);
1631         }
1632         if (pwc != NULL) {
1633                 /* Assign the value to the output; out-of-range values
1634                  * just get truncated. */
1635                 *pwc = (wchar_t)wch;
1636 #ifdef WCHAR_MAX
1637                 /*
1638                  * If platform has WCHAR_MAX, we can do something
1639                  * more sensible with out-of-range values.
1640                  */
1641                 if (wch >= WCHAR_MAX)
1642                         *pwc = '?';
1643 #endif
1644         }
1645         return (wch == L'\0' ? 0 : len);
1646 }