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