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