2 * Copyright (c) 2003-2004 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_tar.c,v 1.32 2005/04/06 04:19:30 kientzle Exp $");
32 /* #include <stdint.h> */ /* See archive_platform.h */
39 #include "archive_entry.h"
40 #include "archive_private.h"
43 * Layout of POSIX 'ustar' tar header.
45 struct archive_entry_header_ustar {
54 char linkname[100]; /* "old format" header ends here */
55 char magic[6]; /* For POSIX: "ustar\0" */
56 char version[2]; /* For POSIX: "00" */
65 * Structure of GNU tar header
72 struct archive_entry_header_gnutar {
82 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
92 struct gnu_sparse sparse[4];
96 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
102 * Data specific to this format.
104 struct sparse_block {
105 struct sparse_block *next;
111 struct archive_string acl_text;
112 struct archive_string entry_name;
113 struct archive_string entry_linkname;
114 struct archive_string entry_uname;
115 struct archive_string entry_gname;
116 struct archive_string longlink;
117 struct archive_string longname;
118 struct archive_string pax_header;
119 struct archive_string pax_global;
121 size_t pax_entry_length;
122 int header_recursion_depth;
123 off_t entry_bytes_remaining;
126 struct sparse_block *sparse_list;
129 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
130 static int archive_block_is_null(const unsigned char *p);
131 int gnu_read_sparse_data(struct archive *, struct tar *,
132 const struct archive_entry_header_gnutar *header);
133 void gnu_parse_sparse_data(struct archive *, struct tar *,
134 const struct gnu_sparse *sparse, int length);
135 static int header_Solaris_ACL(struct archive *, struct tar *,
136 struct archive_entry *, struct stat *, const void *);
137 static int header_common(struct archive *, struct tar *,
138 struct archive_entry *, struct stat *, const void *);
139 static int header_old_tar(struct archive *, struct tar *,
140 struct archive_entry *, struct stat *, const void *);
141 static int header_pax_extensions(struct archive *, struct tar *,
142 struct archive_entry *, struct stat *, const void *);
143 static int header_pax_global(struct archive *, struct tar *,
144 struct archive_entry *, struct stat *, const void *h);
145 static int header_longlink(struct archive *, struct tar *,
146 struct archive_entry *, struct stat *, const void *h);
147 static int header_longname(struct archive *, struct tar *,
148 struct archive_entry *, struct stat *, const void *h);
149 static int header_volume(struct archive *, struct tar *,
150 struct archive_entry *, struct stat *, const void *h);
151 static int header_ustar(struct archive *, struct tar *,
152 struct archive_entry *, struct stat *, const void *h);
153 static int header_gnutar(struct archive *, struct tar *,
154 struct archive_entry *, struct stat *, const void *h);
155 static int archive_read_format_tar_bid(struct archive *);
156 static int archive_read_format_tar_cleanup(struct archive *);
157 static int archive_read_format_tar_read_data(struct archive *a,
158 const void **buff, size_t *size, off_t *offset);
159 static int archive_read_format_tar_read_header(struct archive *,
160 struct archive_entry *);
161 static int checksum(struct archive *, const void *);
162 static int pax_attribute(struct archive_entry *, struct stat *,
163 wchar_t *key, wchar_t *value);
164 static int pax_header(struct archive *, struct tar *,
165 struct archive_entry *, struct stat *, char *attr);
166 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
167 static int read_body_to_string(struct archive *, struct tar *,
168 struct archive_string *, const void *h);
169 static int64_t tar_atol(const char *, unsigned);
170 static int64_t tar_atol10(const wchar_t *, unsigned);
171 static int64_t tar_atol256(const char *, unsigned);
172 static int64_t tar_atol8(const char *, unsigned);
173 static int tar_read_header(struct archive *, struct tar *,
174 struct archive_entry *, struct stat *);
175 static int utf8_decode(wchar_t *, const char *, size_t length);
178 * ANSI C99 defines constants for these, but not everyone supports
179 * those constants, so I define a couple of static variables here and
180 * compute the values. These calculations should be portable to any
181 * 2s-complement architecture.
184 static const uint64_t max_uint64 = UINT64_MAX;
186 static const uint64_t max_uint64 = ~(uint64_t)0;
189 static const int64_t max_int64 = INT64_MAX;
191 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
194 static const int64_t min_int64 = INT64_MIN;
196 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
200 archive_read_support_format_gnutar(struct archive *a)
202 return (archive_read_support_format_tar(a));
207 archive_read_support_format_tar(struct archive *a)
212 tar = malloc(sizeof(*tar));
213 memset(tar, 0, sizeof(*tar));
215 r = __archive_read_register_format(a, tar,
216 archive_read_format_tar_bid,
217 archive_read_format_tar_read_header,
218 archive_read_format_tar_read_data,
220 archive_read_format_tar_cleanup);
228 archive_read_format_tar_cleanup(struct archive *a)
232 tar = *(a->pformat_data);
233 archive_string_free(&tar->acl_text);
234 archive_string_free(&tar->entry_name);
235 archive_string_free(&tar->entry_linkname);
236 archive_string_free(&tar->entry_uname);
237 archive_string_free(&tar->entry_gname);
238 archive_string_free(&tar->pax_global);
239 archive_string_free(&tar->pax_header);
240 if (tar->pax_entry != NULL)
241 free(tar->pax_entry);
243 *(a->pformat_data) = NULL;
249 archive_read_format_tar_bid(struct archive *a)
254 const struct archive_entry_header_ustar *header;
257 * If we're already reading a non-tar file, don't
260 if (a->archive_format != 0 &&
261 (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
267 * If we're already reading a tar format, start the bid at 1 as
270 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
274 /* Now let's look at the actual header and see if it matches. */
275 if (a->compression_read_ahead != NULL)
276 bytes_read = (a->compression_read_ahead)(a, &h, 512);
278 bytes_read = 0; /* Empty file. */
280 return (ARCHIVE_FATAL);
281 if (bytes_read == 0 && bid > 0) {
282 /* An archive without a proper end-of-archive marker. */
283 /* Hold our nose and bid 1 anyway. */
286 if (bytes_read < 512) {
287 /* If it's a new archive, then just return a zero bid. */
291 * If we already know this is a tar archive,
292 * then we have a problem.
294 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
295 "Truncated tar archive");
296 return (ARCHIVE_FATAL);
299 /* If it's an end-of-archive mark, we can handle it. */
300 if ((*(const char *)h) == 0 && archive_block_is_null(h)) {
301 /* If it's a known tar file, end-of-archive is definite. */
302 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
309 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
312 bid += 48; /* Checksum is usually 6 octal digits. */
316 /* Recognize POSIX formats. */
317 if ((memcmp(header->magic, "ustar\0", 6) == 0)
318 &&(memcmp(header->version, "00", 2)==0))
321 /* Recognize GNU tar format. */
322 if ((memcmp(header->magic, "ustar ", 6) == 0)
323 &&(memcmp(header->version, " \0", 2)==0))
326 /* Type flag must be null, digit or A-Z, a-z. */
327 if (header->typeflag[0] != 0 &&
328 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
329 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
330 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
332 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
334 /* Sanity check: Look at first byte of mode field. */
335 switch (255 & (unsigned)header->mode[0]) {
337 /* Base-256 value: No further verification possible! */
339 case ' ': /* Not recommended, but not illegal, either. */
341 case '0': case '1': case '2': case '3':
342 case '4': case '5': case '6': case '7':
344 /* TODO: Check format of remainder of this field. */
347 /* Not a valid mode; bail out here. */
350 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
356 * The function invoked by archive_read_header(). This
357 * just sets up a few things and then calls the internal
358 * tar_read_header() function below.
361 archive_read_format_tar_read_header(struct archive *a,
362 struct archive_entry *entry)
370 memset(&st, 0, sizeof(st));
371 tar = *(a->pformat_data);
372 tar->entry_offset = 0;
374 r = tar_read_header(a, tar, entry, &st);
376 if (r == ARCHIVE_OK) {
378 * "Regular" entry with trailing '/' is really
379 * directory: This is needed for certain old tar
380 * variants and even for some broken newer ones.
382 p = archive_entry_pathname(entry);
384 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
385 st.st_mode &= ~S_IFMT;
386 st.st_mode |= S_IFDIR;
389 /* Copy the final stat data into the entry. */
390 archive_entry_copy_stat(entry, &st);
396 archive_read_format_tar_read_data(struct archive *a,
397 const void **buff, size_t *size, off_t *offset)
401 struct sparse_block *p;
403 tar = *(a->pformat_data);
404 if (tar->entry_bytes_remaining > 0) {
405 bytes_read = (a->compression_read_ahead)(a, buff, 1);
407 return (ARCHIVE_FATAL);
408 if (bytes_read > tar->entry_bytes_remaining)
409 bytes_read = tar->entry_bytes_remaining;
410 while (tar->sparse_list != NULL &&
411 tar->sparse_list->remaining == 0) {
412 p = tar->sparse_list;
413 tar->sparse_list = p->next;
415 if (tar->sparse_list != NULL)
416 tar->entry_offset = tar->sparse_list->offset;
418 if (tar->sparse_list != NULL) {
419 if (tar->sparse_list->remaining < bytes_read)
420 bytes_read = tar->sparse_list->remaining;
421 tar->sparse_list->remaining -= bytes_read;
424 *offset = tar->entry_offset;
425 tar->entry_offset += bytes_read;
426 tar->entry_bytes_remaining -= bytes_read;
427 (a->compression_read_consume)(a, bytes_read);
430 while (tar->entry_padding > 0) {
431 bytes_read = (a->compression_read_ahead)(a, buff, 1);
433 return (ARCHIVE_FATAL);
434 if (bytes_read > tar->entry_padding)
435 bytes_read = tar->entry_padding;
436 (a->compression_read_consume)(a, bytes_read);
437 tar->entry_padding -= bytes_read;
441 *offset = tar->entry_offset;
442 return (ARCHIVE_EOF);
447 * This function recursively interprets all of the headers associated
448 * with a single entry.
451 tar_read_header(struct archive *a, struct tar *tar,
452 struct archive_entry *entry, struct stat *st)
457 const struct archive_entry_header_ustar *header;
459 /* Read 512-byte header record */
460 bytes = (a->compression_read_ahead)(a, &h, 512);
463 * If we're here, it's becase the _bid function accepted
464 * this file. So just call a short read end-of-archive
465 * and be done with it.
467 return (ARCHIVE_EOF);
469 (a->compression_read_consume)(a, 512);
471 /* Check for end-of-archive mark. */
472 if (((*(const char *)h)==0) && archive_block_is_null(h)) {
473 /* Try to consume a second all-null record, as well. */
474 bytes = (a->compression_read_ahead)(a, &h, 512);
476 (a->compression_read_consume)(a, bytes);
477 archive_set_error(a, 0, NULL);
478 return (ARCHIVE_EOF);
482 * Note: If the checksum fails and we return ARCHIVE_RETRY,
483 * then the client is likely to just retry. This is a very
484 * crude way to search for the next valid header!
486 * TODO: Improve this by implementing a real header scan.
488 if (!checksum(a, h)) {
489 archive_set_error(a, EINVAL, "Damaged tar archive");
490 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
493 if (++tar->header_recursion_depth > 32) {
494 archive_set_error(a, EINVAL, "Too many special headers");
495 return (ARCHIVE_WARN);
498 /* Determine the format variant. */
500 switch(header->typeflag[0]) {
501 case 'A': /* Solaris tar ACL */
502 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
503 a->archive_format_name = "Solaris tar";
504 err = header_Solaris_ACL(a, tar, entry, st, h);
506 case 'g': /* POSIX-standard 'g' header. */
507 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
508 a->archive_format_name = "POSIX pax interchange format";
509 err = header_pax_global(a, tar, entry, st, h);
511 case 'K': /* Long link name (GNU tar, others) */
512 err = header_longlink(a, tar, entry, st, h);
514 case 'L': /* Long filename (GNU tar, others) */
515 err = header_longname(a, tar, entry, st, h);
517 case 'V': /* GNU volume header */
518 err = header_volume(a, tar, entry, st, h);
520 case 'X': /* Used by SUN tar; same as 'x'. */
521 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
522 a->archive_format_name =
523 "POSIX pax interchange format (Sun variant)";
524 err = header_pax_extensions(a, tar, entry, st, h);
526 case 'x': /* POSIX-standard 'x' header. */
527 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
528 a->archive_format_name = "POSIX pax interchange format";
529 err = header_pax_extensions(a, tar, entry, st, h);
532 if (memcmp(header->magic, "ustar \0", 8) == 0) {
533 a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
534 a->archive_format_name = "GNU tar format";
535 err = header_gnutar(a, tar, entry, st, h);
536 } else if (memcmp(header->magic, "ustar", 5) == 0) {
537 if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
538 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
539 a->archive_format_name = "POSIX ustar format";
541 err = header_ustar(a, tar, entry, st, h);
543 a->archive_format = ARCHIVE_FORMAT_TAR;
544 a->archive_format_name = "tar (non-POSIX)";
545 err = header_old_tar(a, tar, entry, st, h);
548 --tar->header_recursion_depth;
553 * Return true if block checksum is correct.
556 checksum(struct archive *a, const void *h)
558 const unsigned char *bytes;
559 const struct archive_entry_header_ustar *header;
562 (void)a; /* UNUSED */
567 * Test the checksum. Note that POSIX specifies _unsigned_
568 * bytes for this calculation.
570 sum = tar_atol(header->checksum, sizeof(header->checksum));
572 for (i = 0; i < 148; i++)
573 check += (unsigned char)bytes[i];
577 check += (unsigned char)bytes[i];
582 * Repeat test with _signed_ bytes, just in case this archive
583 * was created by an old BSD, Solaris, or HP-UX tar with a
584 * broken checksum calculation.
587 for (i = 0; i < 148; i++)
588 check += (signed char)bytes[i];
592 check += (signed char)bytes[i];
600 * Return true if this block contains only nulls.
603 archive_block_is_null(const unsigned char *p)
607 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
614 * Interpret 'A' Solaris ACL header
617 header_Solaris_ACL(struct archive *a, struct tar *tar,
618 struct archive_entry *entry, struct stat *st, const void *h)
624 err = read_body_to_string(a, tar, &(tar->acl_text), h);
625 err2 = tar_read_header(a, tar, entry, st);
626 err = err_combine(err, err2);
628 /* XXX Ensure p doesn't overrun acl_text */
630 /* Skip leading octal number. */
631 /* XXX TODO: Parse the octal number and sanity-check it. */
637 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
639 utf8_decode(wp, p, strlen(p));
640 err2 = __archive_entry_acl_parse_w(entry, wp,
641 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
642 err = err_combine(err, err2);
650 * Interpret 'K' long linkname header.
653 header_longlink(struct archive *a, struct tar *tar,
654 struct archive_entry *entry, struct stat *st, const void *h)
658 err = read_body_to_string(a, tar, &(tar->longlink), h);
659 err2 = tar_read_header(a, tar, entry, st);
660 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
661 /* Set symlink if symlink already set, else hardlink. */
662 archive_entry_set_link(entry, tar->longlink.s);
664 return (err_combine(err, err2));
668 * Interpret 'L' long filename header.
671 header_longname(struct archive *a, struct tar *tar,
672 struct archive_entry *entry, struct stat *st, const void *h)
676 err = read_body_to_string(a, tar, &(tar->longname), h);
677 /* Read and parse "real" header, then override name. */
678 err2 = tar_read_header(a, tar, entry, st);
679 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
680 archive_entry_set_pathname(entry, tar->longname.s);
681 return (err_combine(err, err2));
686 * Interpret 'V' GNU tar volume header.
689 header_volume(struct archive *a, struct tar *tar,
690 struct archive_entry *entry, struct stat *st, const void *h)
694 /* Just skip this and read the next header. */
695 return (tar_read_header(a, tar, entry, st));
699 * Read body of an archive entry into an archive_string object.
702 read_body_to_string(struct archive *a, struct tar *tar,
703 struct archive_string *as, const void *h)
705 off_t size, padded_size;
706 ssize_t bytes_read, bytes_to_copy;
707 const struct archive_entry_header_ustar *header;
711 (void)tar; /* UNUSED */
713 size = tar_atol(header->size, sizeof(header->size));
715 /* Read the body into the string. */
716 archive_string_ensure(as, size+1);
717 padded_size = (size + 511) & ~ 511;
719 while (padded_size > 0) {
720 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
722 return (ARCHIVE_FATAL);
723 if (bytes_read > padded_size)
724 bytes_read = padded_size;
725 (a->compression_read_consume)(a, bytes_read);
726 bytes_to_copy = bytes_read;
727 if ((off_t)bytes_to_copy > size)
728 bytes_to_copy = (ssize_t)size;
729 memcpy(dest, src, bytes_to_copy);
730 dest += bytes_to_copy;
731 size -= bytes_to_copy;
732 padded_size -= bytes_read;
739 * Parse out common header elements.
741 * This would be the same as header_old_tar, except that the
742 * filename is handled slightly differently for old and POSIX
743 * entries (POSIX entries support a 'prefix'). This factoring
744 * allows header_old_tar and header_ustar
745 * to handle filenames differently, while still putting most of the
746 * common parsing into one place.
749 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
750 struct stat *st, const void *h)
752 const struct archive_entry_header_ustar *header;
755 (void)a; /* UNUSED */
758 if (header->linkname[0])
759 archive_strncpy(&(tar->entry_linkname), header->linkname,
760 sizeof(header->linkname));
762 archive_string_empty(&(tar->entry_linkname));
764 /* Parse out the numeric fields (all are octal) */
765 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
766 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
767 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
768 st->st_size = tar_atol(header->size, sizeof(header->size));
769 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
771 /* Handle the tar type flag appropriately. */
772 tartype = header->typeflag[0];
773 st->st_mode &= ~S_IFMT;
776 case '1': /* Hard link */
777 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
779 * The following may seem odd, but: Technically, tar
780 * does not store the file type for a "hard link"
781 * entry, only the fact that it is a hard link. So, I
782 * leave the type zero normally. But, pax interchange
783 * format allows hard links to have data, which
784 * implies that the underlying entry is a regular
788 st->st_mode |= S_IFREG;
791 * A tricky point: Traditionally, tar readers have
792 * ignored the size field when reading hardlink
793 * entries, and some writers put non-zero sizes even
794 * though the body is empty. POSIX.1-2001 broke with
795 * this tradition by permitting hardlink entries to
796 * store valid bodies in pax interchange format, but
797 * not in ustar format. Since there is no hard and
798 * fast way to distinguish pax interchange from
799 * earlier archives (the 'x' and 'g' entries are
800 * optional, after all), we need a heuristic. Here, I
801 * use the bid function to test whether or not there's
802 * a valid header following. Of course, if we know
803 * this is pax interchange format, then we must obey
806 * This heuristic will only fail for a pax interchange
807 * archive that is storing hardlink bodies, no pax
808 * extended attribute entries have yet occurred, and
809 * we encounter a hardlink entry for a file that is
810 * itself an uncompressed tar archive.
812 if (st->st_size > 0 &&
813 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
814 archive_read_format_tar_bid(a) > 50)
817 case '2': /* Symlink */
818 st->st_mode |= S_IFLNK;
820 archive_entry_set_symlink(entry, tar->entry_linkname.s);
822 case '3': /* Character device */
823 st->st_mode |= S_IFCHR;
826 case '4': /* Block device */
827 st->st_mode |= S_IFBLK;
831 st->st_mode |= S_IFDIR;
834 case '6': /* FIFO device */
835 st->st_mode |= S_IFIFO;
838 case 'D': /* GNU incremental directory type */
840 * No special handling is actually required here.
841 * It might be nice someday to preprocess the file list and
842 * provide it to the client, though.
844 st->st_mode |= S_IFDIR;
846 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
848 * As far as I can tell, this is just like a regular file
849 * entry, except that the contents should be _appended_ to
850 * the indicated file at the indicated offset. This may
851 * require some API work to fully support.
854 case 'N': /* Old GNU "long filename" entry. */
855 /* The body of this entry is a script for renaming
856 * previously-extracted entries. Ugh. It will never
857 * be supported by libarchive. */
858 st->st_mode |= S_IFREG;
860 case 'S': /* GNU sparse files */
862 * Sparse files are really just regular files with
863 * sparse information in the extended area.
866 default: /* Regular file and non-standard types */
868 * Per POSIX: non-recognized types should always be
869 * treated as regular files.
871 st->st_mode |= S_IFREG;
878 * Parse out header elements for "old-style" tar archives.
881 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
882 struct stat *st, const void *h)
884 const struct archive_entry_header_ustar *header;
886 /* Copy filename over (to ensure null termination). */
888 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
889 archive_entry_set_pathname(entry, tar->entry_name.s);
891 /* Grab rest of common fields */
892 header_common(a, tar, entry, st, h);
894 tar->entry_bytes_remaining = st->st_size;
895 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
900 * Parse a file header for a pax extended archive entry.
903 header_pax_global(struct archive *a, struct tar *tar,
904 struct archive_entry *entry, struct stat *st, const void *h)
908 err = read_body_to_string(a, tar, &(tar->pax_global), h);
909 err2 = tar_read_header(a, tar, entry, st);
910 return (err_combine(err, err2));
914 header_pax_extensions(struct archive *a, struct tar *tar,
915 struct archive_entry *entry, struct stat *st, const void *h)
919 read_body_to_string(a, tar, &(tar->pax_header), h);
921 /* Parse the next header. */
922 err = tar_read_header(a, tar, entry, st);
925 * TODO: Parse global/default options into 'entry' struct here
926 * before handling file-specific options.
928 * This design (parse standard header, then overwrite with pax
929 * extended attribute data) usually works well, but isn't ideal;
930 * it would be better to parse the pax extended attributes first
931 * and then skip any fields in the standard header that were
932 * defined in the pax header.
934 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
935 err = err_combine(err, err2);
936 tar->entry_bytes_remaining = st->st_size;
937 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
943 * Parse a file header for a Posix "ustar" archive entry. This also
944 * handles "pax" or "extended ustar" entries.
947 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
948 struct stat *st, const void *h)
950 const struct archive_entry_header_ustar *header;
951 struct archive_string *as;
955 /* Copy name into an internal buffer to ensure null-termination. */
956 as = &(tar->entry_name);
957 if (header->prefix[0]) {
958 archive_strncpy(as, header->prefix, sizeof(header->prefix));
959 if (as->s[archive_strlen(as) - 1] != '/')
960 archive_strappend_char(as, '/');
961 archive_strncat(as, header->name, sizeof(header->name));
963 archive_strncpy(as, header->name, sizeof(header->name));
965 archive_entry_set_pathname(entry, as->s);
967 /* Handle rest of common fields. */
968 header_common(a, tar, entry, st, h);
970 /* Handle POSIX ustar fields. */
971 archive_strncpy(&(tar->entry_uname), header->uname,
972 sizeof(header->uname));
973 archive_entry_set_uname(entry, tar->entry_uname.s);
975 archive_strncpy(&(tar->entry_gname), header->gname,
976 sizeof(header->gname));
977 archive_entry_set_gname(entry, tar->entry_gname.s);
979 /* Parse out device numbers only for char and block specials. */
980 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
981 st->st_rdev = makedev(
982 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
983 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
986 tar->entry_bytes_remaining = st->st_size;
987 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
994 * Parse the pax extended attributes record.
996 * Returns non-zero if there's an error in the data.
999 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1000 struct stat *st, char *attr)
1002 size_t attr_length, l, line_length;
1004 wchar_t *key, *wp, *value;
1007 attr_length = strlen(attr);
1009 while (attr_length > 0) {
1010 /* Parse decimal length field at start of line. */
1013 line = p = attr; /* Record start of line. */
1020 if (*p < '0' || *p > '9')
1023 line_length += *p - '0';
1024 if (line_length > 999999) {
1025 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1026 "Rejecting pax extended attribute > 1MB");
1027 return (ARCHIVE_WARN);
1033 if (line_length > attr_length)
1036 /* Ensure pax_entry buffer is big enough. */
1037 if (tar->pax_entry_length <= line_length) {
1038 if (tar->pax_entry_length <= 0)
1039 tar->pax_entry_length = 1024;
1040 while (tar->pax_entry_length <= line_length + 1)
1041 tar->pax_entry_length *= 2;
1043 /* XXX Error handling here */
1044 tar->pax_entry = realloc(tar->pax_entry,
1045 tar->pax_entry_length * sizeof(wchar_t));
1048 /* Decode UTF-8 to wchar_t, null-terminate result. */
1049 if (utf8_decode(tar->pax_entry, p,
1050 line_length - (p - attr) - 1)) {
1051 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1052 "Invalid UTF8 character in pax extended attribute");
1053 err = err_combine(err, ARCHIVE_WARN);
1056 /* Null-terminate 'key' value. */
1057 key = tar->pax_entry;
1060 wp = wcschr(key, L'=');
1062 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1063 "Invalid pax extended attributes");
1064 return (ARCHIVE_WARN);
1068 /* Identify null-terminated 'value' portion. */
1071 /* Identify this attribute and set it in the entry. */
1072 err2 = pax_attribute(entry, st, key, value);
1073 err = err_combine(err, err2);
1075 /* Skip to next line */
1076 attr += line_length;
1077 attr_length -= line_length;
1085 * Parse a single key=value attribute. key/value pointers are
1086 * assumed to point into reasonably long-lived storage.
1088 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1089 * extensions should always have keywords of the form "VENDOR.attribute"
1090 * In particular, it's quite feasible to support many different
1091 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1092 * unique to this library (currently, there are none).
1094 * Investigate other vendor-specific extensions, as well and see if
1095 * any of them look useful.
1098 pax_attribute(struct archive_entry *entry, struct stat *st,
1099 wchar_t *key, wchar_t *value)
1106 /* Our extensions */
1107 /* TODO: Handle arbitrary extended attributes... */
1109 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1110 archive_entry_set_xxxxxx(entry, value);
1114 /* We support some keys used by the "star" archiver */
1115 if (wcscmp(key, L"SCHILY.acl.access")==0)
1116 __archive_entry_acl_parse_w(entry, value,
1117 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1118 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1119 __archive_entry_acl_parse_w(entry, value,
1120 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1121 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1122 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1123 minor(st->st_rdev));
1124 else if (wcscmp(key, L"SCHILY.devminor")==0)
1125 st->st_rdev = makedev(major(st->st_rdev),
1126 tar_atol10(value, wcslen(value)));
1127 else if (wcscmp(key, L"SCHILY.fflags")==0)
1128 archive_entry_copy_fflags_text_w(entry, value);
1129 else if (wcscmp(key, L"SCHILY.nlink")==0)
1130 st->st_nlink = tar_atol10(value, wcslen(value));
1133 if (wcscmp(key, L"atime")==0) {
1134 pax_time(value, &s, &n);
1136 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1140 if (wcscmp(key, L"ctime")==0) {
1141 pax_time(value, &s, &n);
1143 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1144 } else if (wcscmp(key, L"charset")==0) {
1145 /* TODO: Publish charset information in entry. */
1146 } else if (wcscmp(key, L"comment")==0) {
1147 /* TODO: Publish comment in entry. */
1151 if (wcscmp(key, L"gid")==0)
1152 st->st_gid = tar_atol10(value, wcslen(value));
1153 else if (wcscmp(key, L"gname")==0)
1154 archive_entry_copy_gname_w(entry, value);
1157 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1158 if (wcscmp(key, L"linkpath")==0) {
1159 if (archive_entry_hardlink(entry))
1160 archive_entry_copy_hardlink_w(entry, value);
1162 archive_entry_copy_symlink_w(entry, value);
1166 if (wcscmp(key, L"mtime")==0) {
1167 pax_time(value, &s, &n);
1169 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1173 if (wcscmp(key, L"path")==0)
1174 archive_entry_copy_pathname_w(entry, value);
1177 /* POSIX has reserved 'realtime.*' */
1180 /* POSIX has reserved 'security.*' */
1181 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1182 if (wcscmp(key, L"size")==0)
1183 st->st_size = tar_atol10(value, wcslen(value));
1186 if (wcscmp(key, L"uid")==0)
1187 st->st_uid = tar_atol10(value, wcslen(value));
1188 else if (wcscmp(key, L"uname")==0)
1189 archive_entry_copy_uname_w(entry, value);
1198 * parse a decimal time value, which may include a fractional portion
1201 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1207 int64_t limit, last_digit_limit;
1209 limit = max_int64 / 10;
1210 last_digit_limit = max_int64 % 10;
1218 while (*p >= '0' && *p <= '9') {
1221 (s == limit && digit > last_digit_limit)) {
1225 s = (s * 10) + digit;
1231 /* Calculate nanoseconds. */
1240 if (*p >= '0' && *p <= '9')
1241 *pn += (*p - '0') * l;
1248 * Parse GNU tar header
1251 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1252 struct stat *st, const void *h)
1254 const struct archive_entry_header_gnutar *header;
1259 * GNU header is like POSIX ustar, except 'prefix' is
1260 * replaced with some other fields. This also means the
1261 * filename is stored as in old-style archives.
1264 /* Grab fields common to all tar variants. */
1265 header_common(a, tar, entry, st, h);
1267 /* Copy filename over (to ensure null termination). */
1269 archive_strncpy(&(tar->entry_name), header->name,
1270 sizeof(header->name));
1271 archive_entry_set_pathname(entry, tar->entry_name.s);
1273 /* Fields common to ustar and GNU */
1274 /* XXX Can the following be factored out since it's common
1275 * to ustar and gnu tar? Is it okay to move it down into
1276 * header_common, perhaps? */
1277 archive_strncpy(&(tar->entry_uname),
1278 header->uname, sizeof(header->uname));
1279 archive_entry_set_uname(entry, tar->entry_uname.s);
1281 archive_strncpy(&(tar->entry_gname),
1282 header->gname, sizeof(header->gname));
1283 archive_entry_set_gname(entry, tar->entry_gname.s);
1285 /* Parse out device numbers only for char and block specials */
1286 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1287 st->st_rdev = makedev (
1288 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1289 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1293 tar->entry_bytes_remaining = st->st_size;
1294 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1296 /* Grab GNU-specific fields. */
1297 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1298 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1299 if (header->realsize[0] != 0) {
1300 st->st_size = tar_atol(header->realsize,
1301 sizeof(header->realsize));
1304 if (header->sparse[0].offset[0] != 0) {
1305 gnu_read_sparse_data(a, tar, header);
1307 if (header->isextended[0] != 0) {
1316 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1317 const struct archive_entry_header_gnutar *header)
1322 struct gnu_sparse sparse[21];
1326 const struct extended *ext;
1328 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1329 if (header->isextended[0] == 0)
1330 return (ARCHIVE_OK);
1333 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1335 return (ARCHIVE_FATAL);
1336 if (bytes_read < 512) {
1337 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1338 "Truncated tar archive "
1339 "detected while reading sparse file data");
1340 return (ARCHIVE_FATAL);
1342 (a->compression_read_consume)(a, 512);
1343 ext = (const struct extended *)data;
1344 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1345 } while (ext->isextended[0] != 0);
1346 if (tar->sparse_list != NULL)
1347 tar->entry_offset = tar->sparse_list->offset;
1348 return (ARCHIVE_OK);
1352 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1353 const struct gnu_sparse *sparse, int length)
1355 struct sparse_block *last;
1356 struct sparse_block *p;
1358 (void)a; /* UNUSED */
1360 last = tar->sparse_list;
1361 while (last != NULL && last->next != NULL)
1364 while (length > 0 && sparse->offset[0] != 0) {
1365 p = malloc(sizeof(*p));
1366 memset(p, 0, sizeof(*p));
1370 tar->sparse_list = p;
1372 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1374 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1381 * Convert text->integer.
1383 * Traditional tar formats (including POSIX) specify base-8 for
1384 * all of the standard numeric fields. This is a significant limitation
1386 * = file size is limited to 8GB
1387 * = rdevmajor and rdevminor are limited to 21 bits
1388 * = uid/gid are limited to 21 bits
1390 * There are two workarounds for this:
1391 * = pax extended headers, which use variable-length string fields
1392 * = GNU tar and STAR both allow either base-8 or base-256 in
1393 * most fields. The high bit is set to indicate base-256.
1395 * On read, this implementation supports both extensions.
1398 tar_atol(const char *p, unsigned char_cnt)
1401 * Technically, GNU tar considers a field to be in base-256
1402 * only if the first byte is 0xff or 0x80.
1405 return (tar_atol256(p, char_cnt));
1406 return (tar_atol8(p, char_cnt));
1410 * Note that this implementation does not (and should not!) obey
1411 * locale settings; you cannot simply substitute strtol here, since
1412 * it does obey locale.
1415 tar_atol8(const char *p, unsigned char_cnt)
1417 int64_t l, limit, last_digit_limit;
1418 int digit, sign, base;
1421 limit = max_int64 / base;
1422 last_digit_limit = max_int64 % base;
1424 while (*p == ' ' || *p == '\t')
1434 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1435 if (l>limit || (l == limit && digit > last_digit_limit)) {
1436 l = max_uint64; /* Truncate on overflow. */
1439 l = (l * base) + digit;
1442 return (sign < 0) ? -l : l;
1447 * Note that this implementation does not (and should not!) obey
1448 * locale settings; you cannot simply substitute strtol here, since
1449 * it does obey locale.
1452 tar_atol10(const wchar_t *p, unsigned char_cnt)
1454 int64_t l, limit, last_digit_limit;
1455 int base, digit, sign;
1458 limit = max_int64 / base;
1459 last_digit_limit = max_int64 % base;
1461 while (*p == ' ' || *p == '\t')
1471 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1472 if (l > limit || (l == limit && digit > last_digit_limit)) {
1473 l = max_uint64; /* Truncate on overflow. */
1476 l = (l * base) + digit;
1479 return (sign < 0) ? -l : l;
1483 * Parse a base-256 integer. This is just a straight signed binary
1484 * value in big-endian order, except that the high-order bit is
1485 * ignored. Remember that "int64_t" may or may not be exactly 64
1486 * bits; the implementation here tries to avoid making any assumptions
1487 * about the actual size of an int64_t. It does assume we're using
1488 * twos-complement arithmetic, though.
1491 tar_atol256(const char *_p, unsigned char_cnt)
1493 int64_t l, upper_limit, lower_limit;
1494 const unsigned char *p = _p;
1496 upper_limit = max_int64 / 256;
1497 lower_limit = min_int64 / 256;
1499 /* Pad with 1 or 0 bits, depending on sign. */
1500 if ((0x40 & *p) == 0x40)
1504 l = (l << 6) | (0x3f & *p++);
1505 while (--char_cnt > 0) {
1506 if (l > upper_limit) {
1507 l = max_int64; /* Truncate on overflow */
1509 } else if (l < lower_limit) {
1513 l = (l << 8) | (0xff & (int64_t)*p++);
1519 utf8_decode(wchar_t *dest, const char *src, size_t length)
1526 n = UTF8_mbrtowc(dest, src, length);
1530 /* Invalid byte encountered; try to keep going. */
1544 * Copied from FreeBSD libc/locale.
1547 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1549 int ch, i, len, mask;
1550 unsigned long lbound, wch;
1553 /* Reset to initial shift state (no-op) */
1556 /* Incomplete multibyte sequence */
1557 return ((size_t)-2);
1560 * Determine the number of octets that make up this character from
1561 * the first octet, and a mask that extracts the interesting bits of
1564 * We also specify a lower bound for the character code to detect
1565 * redundant, non-"shortest form" encodings. For example, the
1566 * sequence C0 80 is _not_ a legal representation of the null
1567 * character. This enforces a 1-to-1 mapping between character
1568 * codes and their multibyte representations.
1570 ch = (unsigned char)*s;
1571 if ((ch & 0x80) == 0) {
1575 } else if ((ch & 0xe0) == 0xc0) {
1579 } else if ((ch & 0xf0) == 0xe0) {
1583 } else if ((ch & 0xf8) == 0xf0) {
1587 } else if ((ch & 0xfc) == 0xf8) {
1591 } else if ((ch & 0xfc) == 0xfc) {
1597 * Malformed input; input is not UTF-8.
1600 return ((size_t)-1);
1603 if (n < (size_t)len)
1604 /* Incomplete multibyte sequence */
1605 return ((size_t)-2);
1608 * Decode the octet sequence representing the character in chunks
1609 * of 6 bits, most significant first.
1611 wch = (unsigned char)*s++ & mask;
1614 if ((*s & 0xc0) != 0x80) {
1616 * Malformed input; bad characters in the middle
1620 return ((size_t)-1);
1627 * Malformed input; redundant encoding.
1630 return ((size_t)-1);
1633 /* Assign the value to the output; out-of-range values
1634 * just get truncated. */
1635 *pwc = (wchar_t)wch;
1638 * If platform has WCHAR_MAX, we can do something
1639 * more sensible with out-of-range values.
1641 if (wch >= WCHAR_MAX)
1645 return (wch == L'\0' ? 0 : len);