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$");
32 #include <sys/mkdev.h>
34 #ifdef MAJOR_IN_SYSMACROS
35 #include <sys/sysmacros.h>
40 /* #include <stdint.h> */ /* See archive_platform.h */
45 /* Obtain suitable wide-character manipulation functions. */
49 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
52 while(*s1 && diff == 0)
53 diff = (int)*++s1 - (int)*++s2;
56 static size_t wcslen(const wchar_t *s)
66 #include "archive_entry.h"
67 #include "archive_private.h"
70 * Layout of POSIX 'ustar' tar header.
72 struct archive_entry_header_ustar {
81 char linkname[100]; /* "old format" header ends here */
82 char magic[6]; /* For POSIX: "ustar\0" */
83 char version[2]; /* For POSIX: "00" */
92 * Structure of GNU tar header
99 struct archive_entry_header_gnutar {
109 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
119 struct gnu_sparse sparse[4];
123 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
129 * Data specific to this format.
131 struct sparse_block {
132 struct sparse_block *next;
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;
148 size_t pax_entry_length;
149 int header_recursion_depth;
150 off_t entry_bytes_remaining;
153 struct sparse_block *sparse_list;
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);
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.
211 static const uint64_t max_uint64 = UINT64_MAX;
213 static const uint64_t max_uint64 = ~(uint64_t)0;
216 static const int64_t max_int64 = INT64_MAX;
218 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
221 static const int64_t min_int64 = INT64_MIN;
223 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
227 archive_read_support_format_gnutar(struct archive *a)
229 return (archive_read_support_format_tar(a));
234 archive_read_support_format_tar(struct archive *a)
239 tar = malloc(sizeof(*tar));
241 archive_set_error(a, ENOMEM, "Can't allocate tar data");
242 return (ARCHIVE_FATAL);
244 memset(tar, 0, sizeof(*tar));
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,
251 archive_read_format_tar_cleanup);
259 archive_read_format_tar_cleanup(struct archive *a)
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);
274 *(a->pformat_data) = NULL;
280 archive_read_format_tar_bid(struct archive *a)
285 const struct archive_entry_header_ustar *header;
288 * If we're already reading a non-tar file, don't
291 if (a->archive_format != 0 &&
292 (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
298 * If we're already reading a tar format, start the bid at 1 as
301 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
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);
309 bytes_read = 0; /* Empty file. */
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. */
317 if (bytes_read < 512) {
318 /* If it's a new archive, then just return a zero bid. */
322 * If we already know this is a tar archive,
323 * then we have a problem.
325 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
326 "Truncated tar archive");
327 return (ARCHIVE_FATAL);
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) ==
340 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
343 bid += 48; /* Checksum is usually 6 octal digits. */
347 /* Recognize POSIX formats. */
348 if ((memcmp(header->magic, "ustar\0", 6) == 0)
349 &&(memcmp(header->version, "00", 2)==0))
352 /* Recognize GNU tar format. */
353 if ((memcmp(header->magic, "ustar ", 6) == 0)
354 &&(memcmp(header->version, " \0", 2)==0))
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') )
363 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
365 /* Sanity check: Look at first byte of mode field. */
366 switch (255 & (unsigned)header->mode[0]) {
368 /* Base-256 value: No further verification possible! */
370 case ' ': /* Not recommended, but not illegal, either. */
372 case '0': case '1': case '2': case '3':
373 case '4': case '5': case '6': case '7':
375 /* TODO: Check format of remainder of this field. */
378 /* Not a valid mode; bail out here. */
381 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
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.
392 archive_read_format_tar_read_header(struct archive *a,
393 struct archive_entry *entry)
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
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.
409 static int default_inode;
410 static int default_dev;
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) {
427 tar = *(a->pformat_data);
428 tar->entry_offset = 0;
430 r = tar_read_header(a, tar, entry, &st);
432 if (r == ARCHIVE_OK) {
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.
438 p = archive_entry_pathname(entry);
440 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
441 st.st_mode &= ~S_IFMT;
442 st.st_mode |= S_IFDIR;
445 /* Copy the final stat data into the entry. */
446 archive_entry_copy_stat(entry, &st);
452 archive_read_format_tar_read_data(struct archive *a,
453 const void **buff, size_t *size, off_t *offset)
457 struct sparse_block *p;
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;
468 if (tar->sparse_list == NULL) {
469 /* We exhausted the entire sparse list. */
470 tar->entry_bytes_remaining = 0;
474 if (tar->entry_bytes_remaining > 0) {
475 bytes_read = (a->compression_read_ahead)(a, buff, 1);
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;
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);
496 while (tar->entry_padding > 0) {
497 bytes_read = (a->compression_read_ahead)(a, buff, 1);
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;
507 *offset = tar->entry_offset;
508 return (ARCHIVE_EOF);
513 * This function recursively interprets all of the headers associated
514 * with a single entry.
517 tar_read_header(struct archive *a, struct tar *tar,
518 struct archive_entry *entry, struct stat *st)
523 const struct archive_entry_header_ustar *header;
525 /* Read 512-byte header record */
526 bytes = (a->compression_read_ahead)(a, &h, 512);
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.
533 return (ARCHIVE_EOF);
535 (a->compression_read_consume)(a, 512);
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);
542 (a->compression_read_consume)(a, bytes);
543 archive_set_error(a, 0, NULL);
544 return (ARCHIVE_EOF);
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!
552 * TODO: Improve this by implementing a real header scan.
554 if (!checksum(a, h)) {
555 archive_set_error(a, EINVAL, "Damaged tar archive");
556 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
559 if (++tar->header_recursion_depth > 32) {
560 archive_set_error(a, EINVAL, "Too many special headers");
561 return (ARCHIVE_WARN);
564 /* Determine the format variant. */
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);
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);
577 case 'K': /* Long link name (GNU tar, others) */
578 err = header_longlink(a, tar, entry, st, h);
580 case 'L': /* Long filename (GNU tar, others) */
581 err = header_longname(a, tar, entry, st, h);
583 case 'V': /* GNU volume header */
584 err = header_volume(a, tar, entry, st, h);
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);
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);
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";
607 err = header_ustar(a, tar, entry, st, h);
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);
614 --tar->header_recursion_depth;
619 * Return true if block checksum is correct.
622 checksum(struct archive *a, const void *h)
624 const unsigned char *bytes;
625 const struct archive_entry_header_ustar *header;
628 (void)a; /* UNUSED */
633 * Test the checksum. Note that POSIX specifies _unsigned_
634 * bytes for this calculation.
636 sum = tar_atol(header->checksum, sizeof(header->checksum));
638 for (i = 0; i < 148; i++)
639 check += (unsigned char)bytes[i];
643 check += (unsigned char)bytes[i];
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.
653 for (i = 0; i < 148; i++)
654 check += (signed char)bytes[i];
658 check += (signed char)bytes[i];
666 * Return true if this block contains only nulls.
669 archive_block_is_null(const unsigned char *p)
673 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
680 * Interpret 'A' Solaris ACL header
683 header_Solaris_ACL(struct archive *a, struct tar *tar,
684 struct archive_entry *entry, struct stat *st, const void *h)
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);
694 /* XXX Ensure p doesn't overrun acl_text */
696 /* Skip leading octal number. */
697 /* XXX TODO: Parse the octal number and sanity-check it. */
703 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
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);
716 * Interpret 'K' long linkname header.
719 header_longlink(struct archive *a, struct tar *tar,
720 struct archive_entry *entry, struct stat *st, const void *h)
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);
730 return (err_combine(err, err2));
734 * Interpret 'L' long filename header.
737 header_longname(struct archive *a, struct tar *tar,
738 struct archive_entry *entry, struct stat *st, const void *h)
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));
752 * Interpret 'V' GNU tar volume header.
755 header_volume(struct archive *a, struct tar *tar,
756 struct archive_entry *entry, struct stat *st, const void *h)
760 /* Just skip this and read the next header. */
761 return (tar_read_header(a, tar, entry, st));
765 * Read body of an archive entry into an archive_string object.
768 read_body_to_string(struct archive *a, struct tar *tar,
769 struct archive_string *as, const void *h)
771 off_t size, padded_size;
772 ssize_t bytes_read, bytes_to_copy;
773 const struct archive_entry_header_ustar *header;
777 (void)tar; /* UNUSED */
779 size = tar_atol(header->size, sizeof(header->size));
781 /* Read the body into the string. */
782 archive_string_ensure(as, size+1);
783 padded_size = (size + 511) & ~ 511;
785 while (padded_size > 0) {
786 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
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;
805 * Parse out common header elements.
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.
815 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
816 struct stat *st, const void *h)
818 const struct archive_entry_header_ustar *header;
821 (void)a; /* UNUSED */
824 if (header->linkname[0])
825 archive_strncpy(&(tar->entry_linkname), header->linkname,
826 sizeof(header->linkname));
828 archive_string_empty(&(tar->entry_linkname));
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));
837 /* Handle the tar type flag appropriately. */
838 tartype = header->typeflag[0];
839 st->st_mode &= ~S_IFMT;
842 case '1': /* Hard link */
843 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
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
854 st->st_mode |= S_IFREG;
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
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.
878 if (st->st_size > 0 &&
879 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
880 archive_read_format_tar_bid(a) > 50)
883 case '2': /* Symlink */
884 st->st_mode |= S_IFLNK;
886 archive_entry_set_symlink(entry, tar->entry_linkname.s);
888 case '3': /* Character device */
889 st->st_mode |= S_IFCHR;
892 case '4': /* Block device */
893 st->st_mode |= S_IFBLK;
897 st->st_mode |= S_IFDIR;
900 case '6': /* FIFO device */
901 st->st_mode |= S_IFIFO;
904 case 'D': /* GNU incremental directory type */
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.
910 st->st_mode |= S_IFDIR;
912 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
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.
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;
926 case 'S': /* GNU sparse files */
928 * Sparse files are really just regular files with
929 * sparse information in the extended area.
932 default: /* Regular file and non-standard types */
934 * Per POSIX: non-recognized types should always be
935 * treated as regular files.
937 st->st_mode |= S_IFREG;
944 * Parse out header elements for "old-style" tar archives.
947 header_old_tar(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;
952 /* Copy filename over (to ensure null termination). */
954 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
955 archive_entry_set_pathname(entry, tar->entry_name.s);
957 /* Grab rest of common fields */
958 header_common(a, tar, entry, st, h);
960 tar->entry_bytes_remaining = st->st_size;
961 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
966 * Parse a file header for a pax extended archive entry.
969 header_pax_global(struct archive *a, struct tar *tar,
970 struct archive_entry *entry, struct stat *st, const void *h)
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));
980 header_pax_extensions(struct archive *a, struct tar *tar,
981 struct archive_entry *entry, struct stat *st, const void *h)
985 read_body_to_string(a, tar, &(tar->pax_header), h);
987 /* Parse the next header. */
988 err = tar_read_header(a, tar, entry, st);
991 * TODO: Parse global/default options into 'entry' struct here
992 * before handling file-specific options.
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.
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);
1009 * Parse a file header for a Posix "ustar" archive entry. This also
1010 * handles "pax" or "extended ustar" entries.
1013 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1014 struct stat *st, const void *h)
1016 const struct archive_entry_header_ustar *header;
1017 struct archive_string *as;
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));
1029 archive_strncpy(as, header->name, sizeof(header->name));
1031 archive_entry_set_pathname(entry, as->s);
1033 /* Handle rest of common fields. */
1034 header_common(a, tar, entry, st, h);
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);
1041 archive_strncpy(&(tar->entry_gname), header->gname,
1042 sizeof(header->gname));
1043 archive_entry_set_gname(entry, tar->entry_gname.s);
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)));
1052 tar->entry_bytes_remaining = st->st_size;
1053 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1060 * Parse the pax extended attributes record.
1062 * Returns non-zero if there's an error in the data.
1065 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1066 struct stat *st, char *attr)
1068 size_t attr_length, l, line_length;
1070 wchar_t *key, *wp, *value;
1073 attr_length = strlen(attr);
1075 while (attr_length > 0) {
1076 /* Parse decimal length field at start of line. */
1079 line = p = attr; /* Record start of line. */
1086 if (*p < '0' || *p > '9')
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);
1099 if (line_length > attr_length)
1102 /* Ensure pax_entry buffer is big enough. */
1103 if (tar->pax_entry_length <= line_length) {
1104 wchar_t *old_entry = tar->pax_entry;
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;
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) {
1116 archive_set_error(a, ENOMEM,
1118 return (ARCHIVE_FATAL);
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);
1130 /* Null-terminate 'key' value. */
1131 wp = key = tar->pax_entry;
1134 while (*wp && *wp != L'=')
1136 if (*wp == L'\0' || wp == NULL) {
1137 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1138 "Invalid pax extended attributes");
1139 return (ARCHIVE_WARN);
1143 /* Identify null-terminated 'value' portion. */
1146 /* Identify this attribute and set it in the entry. */
1147 err2 = pax_attribute(entry, st, key, value);
1148 err = err_combine(err, err2);
1150 /* Skip to next line */
1151 attr += line_length;
1152 attr_length -= line_length;
1160 * Parse a single key=value attribute. key/value pointers are
1161 * assumed to point into reasonably long-lived storage.
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).
1169 * Investigate other vendor-specific extensions, as well and see if
1170 * any of them look useful.
1173 pax_attribute(struct archive_entry *entry, struct stat *st,
1174 wchar_t *key, wchar_t *value)
1181 /* Our extensions */
1182 /* TODO: Handle arbitrary extended attributes... */
1184 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1185 archive_entry_set_xxxxxx(entry, value);
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));
1208 if (wcscmp(key, L"atime")==0) {
1209 pax_time(value, &s, &n);
1211 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1215 if (wcscmp(key, L"ctime")==0) {
1216 pax_time(value, &s, &n);
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. */
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);
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);
1237 archive_entry_copy_symlink_w(entry, value);
1241 if (wcscmp(key, L"mtime")==0) {
1242 pax_time(value, &s, &n);
1244 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1248 if (wcscmp(key, L"path")==0)
1249 archive_entry_copy_pathname_w(entry, value);
1252 /* POSIX has reserved 'realtime.*' */
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));
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);
1273 * parse a decimal time value, which may include a fractional portion
1276 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1282 int64_t limit, last_digit_limit;
1284 limit = max_int64 / 10;
1285 last_digit_limit = max_int64 % 10;
1293 while (*p >= '0' && *p <= '9') {
1296 (s == limit && digit > last_digit_limit)) {
1300 s = (s * 10) + digit;
1306 /* Calculate nanoseconds. */
1315 if (*p >= '0' && *p <= '9')
1316 *pn += (*p - '0') * l;
1323 * Parse GNU tar header
1326 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1327 struct stat *st, const void *h)
1329 const struct archive_entry_header_gnutar *header;
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.
1339 /* Grab fields common to all tar variants. */
1340 header_common(a, tar, entry, st, h);
1342 /* Copy filename over (to ensure null termination). */
1344 archive_strncpy(&(tar->entry_name), header->name,
1345 sizeof(header->name));
1346 archive_entry_set_pathname(entry, tar->entry_name.s);
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);
1356 archive_strncpy(&(tar->entry_gname),
1357 header->gname, sizeof(header->gname));
1358 archive_entry_set_gname(entry, tar->entry_gname.s);
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)));
1368 tar->entry_bytes_remaining = st->st_size;
1369 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
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));
1379 if (header->sparse[0].offset[0] != 0) {
1380 gnu_read_sparse_data(a, tar, header);
1382 if (header->isextended[0] != 0) {
1391 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1392 const struct archive_entry_header_gnutar *header)
1397 struct gnu_sparse sparse[21];
1401 const struct extended *ext;
1403 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1404 if (header->isextended[0] == 0)
1405 return (ARCHIVE_OK);
1408 bytes_read = (a->compression_read_ahead)(a, &data, 512);
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);
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);
1427 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1428 const struct gnu_sparse *sparse, int length)
1430 struct sparse_block *last;
1431 struct sparse_block *p;
1433 (void)a; /* UNUSED */
1435 last = tar->sparse_list;
1436 while (last != NULL && last->next != NULL)
1439 while (length > 0 && sparse->offset[0] != 0) {
1440 p = malloc(sizeof(*p));
1442 __archive_errx(1, "Out of memory");
1443 memset(p, 0, sizeof(*p));
1447 tar->sparse_list = p;
1449 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1451 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1458 * Convert text->integer.
1460 * Traditional tar formats (including POSIX) specify base-8 for
1461 * all of the standard numeric fields. This is a significant limitation
1463 * = file size is limited to 8GB
1464 * = rdevmajor and rdevminor are limited to 21 bits
1465 * = uid/gid are limited to 21 bits
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.
1472 * On read, this implementation supports both extensions.
1475 tar_atol(const char *p, unsigned char_cnt)
1478 * Technically, GNU tar considers a field to be in base-256
1479 * only if the first byte is 0xff or 0x80.
1482 return (tar_atol256(p, char_cnt));
1483 return (tar_atol8(p, char_cnt));
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.
1492 tar_atol8(const char *p, unsigned char_cnt)
1494 int64_t l, limit, last_digit_limit;
1495 int digit, sign, base;
1498 limit = max_int64 / base;
1499 last_digit_limit = max_int64 % base;
1501 while (*p == ' ' || *p == '\t')
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. */
1516 l = (l * base) + digit;
1519 return (sign < 0) ? -l : l;
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.
1529 tar_atol10(const wchar_t *p, unsigned char_cnt)
1531 int64_t l, limit, last_digit_limit;
1532 int base, digit, sign;
1535 limit = max_int64 / base;
1536 last_digit_limit = max_int64 % base;
1538 while (*p == ' ' || *p == '\t')
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. */
1553 l = (l * base) + digit;
1556 return (sign < 0) ? -l : l;
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.
1568 tar_atol256(const char *_p, unsigned char_cnt)
1570 int64_t l, upper_limit, lower_limit;
1571 const unsigned char *p = (const unsigned char *)_p;
1573 upper_limit = max_int64 / 256;
1574 lower_limit = min_int64 / 256;
1576 /* Pad with 1 or 0 bits, depending on sign. */
1577 if ((0x40 & *p) == 0x40)
1581 l = (l << 6) | (0x3f & *p++);
1582 while (--char_cnt > 0) {
1583 if (l > upper_limit) {
1584 l = max_int64; /* Truncate on overflow */
1586 } else if (l < lower_limit) {
1590 l = (l << 8) | (0xff & (int64_t)*p++);
1596 utf8_decode(wchar_t *dest, const char *src, size_t length)
1603 n = UTF8_mbrtowc(dest, src, length);
1607 /* Invalid byte encountered; try to keep going. */
1621 * Copied from FreeBSD libc/locale.
1624 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1626 int ch, i, len, mask;
1627 unsigned long lbound, wch;
1630 /* Reset to initial shift state (no-op) */
1633 /* Incomplete multibyte sequence */
1634 return ((size_t)-2);
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
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.
1647 ch = (unsigned char)*s;
1648 if ((ch & 0x80) == 0) {
1652 } else if ((ch & 0xe0) == 0xc0) {
1656 } else if ((ch & 0xf0) == 0xe0) {
1660 } else if ((ch & 0xf8) == 0xf0) {
1664 } else if ((ch & 0xfc) == 0xf8) {
1668 } else if ((ch & 0xfc) == 0xfc) {
1674 * Malformed input; input is not UTF-8.
1677 return ((size_t)-1);
1680 if (n < (size_t)len)
1681 /* Incomplete multibyte sequence */
1682 return ((size_t)-2);
1685 * Decode the octet sequence representing the character in chunks
1686 * of 6 bits, most significant first.
1688 wch = (unsigned char)*s++ & mask;
1691 if ((*s & 0xc0) != 0x80) {
1693 * Malformed input; bad characters in the middle
1697 return ((size_t)-1);
1704 * Malformed input; redundant encoding.
1707 return ((size_t)-1);
1710 /* Assign the value to the output; out-of-range values
1711 * just get truncated. */
1712 *pwc = (wchar_t)wch;
1715 * If platform has WCHAR_MAX, we can do something
1716 * more sensible with out-of-range values.
1718 if (wch >= WCHAR_MAX)
1722 return (wch == L'\0' ? 0 : len);