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