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.28 2004/10/27 05:15:23 kientzle Exp $");
32 /* #include <stdint.h> */ /* See archive_platform.h */
38 #include "archive_entry.h"
39 #include "archive_private.h"
42 * Layout of POSIX 'ustar' tar header.
44 struct archive_entry_header_ustar {
53 char linkname[100]; /* "old format" header ends here */
54 char magic[6]; /* For POSIX: "ustar\0" */
55 char version[2]; /* For POSIX: "00" */
64 * Structure of GNU tar header
71 struct archive_entry_header_gnutar {
81 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
91 struct gnu_sparse sparse[4];
95 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
101 * Data specific to this format.
103 struct sparse_block {
104 struct sparse_block *next;
110 struct archive_string acl_text;
111 struct archive_string entry_name;
112 struct archive_string entry_linkname;
113 struct archive_string entry_uname;
114 struct archive_string entry_gname;
115 struct archive_string longlink;
116 struct archive_string longname;
117 struct archive_string pax_header;
118 struct archive_string pax_global;
120 size_t pax_entry_length;
121 int header_recursion_depth;
122 off_t entry_bytes_remaining;
125 struct sparse_block *sparse_list;
128 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
129 static int archive_block_is_null(const unsigned char *p);
130 int gnu_read_sparse_data(struct archive *, struct tar *,
131 const struct archive_entry_header_gnutar *header);
132 void gnu_parse_sparse_data(struct archive *, struct tar *,
133 const struct gnu_sparse *sparse, int length);
134 static int header_Solaris_ACL(struct archive *, struct tar *,
135 struct archive_entry *, struct stat *, const void *);
136 static int header_common(struct archive *, struct tar *,
137 struct archive_entry *, struct stat *, const void *);
138 static int header_old_tar(struct archive *, struct tar *,
139 struct archive_entry *, struct stat *, const void *);
140 static int header_pax_extensions(struct archive *, struct tar *,
141 struct archive_entry *, struct stat *, const void *);
142 static int header_pax_global(struct archive *, struct tar *,
143 struct archive_entry *, struct stat *, const void *h);
144 static int header_longlink(struct archive *, struct tar *,
145 struct archive_entry *, struct stat *, const void *h);
146 static int header_longname(struct archive *, struct tar *,
147 struct archive_entry *, struct stat *, const void *h);
148 static int header_volume(struct archive *, struct tar *,
149 struct archive_entry *, struct stat *, const void *h);
150 static int header_ustar(struct archive *, struct tar *,
151 struct archive_entry *, struct stat *, const void *h);
152 static int header_gnutar(struct archive *, struct tar *,
153 struct archive_entry *, struct stat *, const void *h);
154 static int archive_read_format_tar_bid(struct archive *);
155 static int archive_read_format_tar_cleanup(struct archive *);
156 static int archive_read_format_tar_read_data(struct archive *a,
157 const void **buff, size_t *size, off_t *offset);
158 static int archive_read_format_tar_read_header(struct archive *,
159 struct archive_entry *);
160 static int checksum(struct archive *, const void *);
161 static int pax_attribute(struct archive_entry *, struct stat *,
162 wchar_t *key, wchar_t *value);
163 static int pax_header(struct archive *, struct tar *,
164 struct archive_entry *, struct stat *, char *attr);
165 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
166 static int read_body_to_string(struct archive *, struct tar *,
167 struct archive_string *, const void *h);
168 static int64_t tar_atol(const char *, unsigned);
169 static int64_t tar_atol10(const wchar_t *, unsigned);
170 static int64_t tar_atol256(const char *, unsigned);
171 static int64_t tar_atol8(const char *, unsigned);
172 static int tar_read_header(struct archive *, struct tar *,
173 struct archive_entry *, struct stat *);
174 static int utf8_decode(wchar_t *, const char *, size_t length);
177 * ANSI C99 defines constants for these, but not everyone supports
178 * those constants, so I define a couple of static variables here and
179 * compute the values. These calculations should be portable to any
180 * 2s-complement architecture.
183 static const uint64_t max_uint64 = UINT64_MAX;
185 static const uint64_t max_uint64 = ~(uint64_t)0;
188 static const int64_t max_int64 = INT64_MAX;
190 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
193 static const int64_t min_int64 = INT64_MIN;
195 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
199 archive_read_support_format_gnutar(struct archive *a)
201 return (archive_read_support_format_tar(a));
206 archive_read_support_format_tar(struct archive *a)
211 tar = malloc(sizeof(*tar));
212 memset(tar, 0, sizeof(*tar));
214 r = __archive_read_register_format(a, tar,
215 archive_read_format_tar_bid,
216 archive_read_format_tar_read_header,
217 archive_read_format_tar_read_data,
218 archive_read_format_tar_cleanup);
226 archive_read_format_tar_cleanup(struct archive *a)
230 tar = *(a->pformat_data);
231 archive_string_free(&tar->acl_text);
232 archive_string_free(&tar->entry_name);
233 archive_string_free(&tar->entry_linkname);
234 archive_string_free(&tar->entry_uname);
235 archive_string_free(&tar->entry_gname);
236 archive_string_free(&tar->pax_global);
237 archive_string_free(&tar->pax_header);
238 if (tar->pax_entry != NULL)
239 free(tar->pax_entry);
241 *(a->pformat_data) = NULL;
247 archive_read_format_tar_bid(struct archive *a)
252 const struct archive_entry_header_ustar *header;
255 * If we're already reading a non-tar file, don't
258 if (a->archive_format != 0 &&
259 (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
265 * If we're already reading a tar format, start the bid at 1 as
268 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
272 /* Now let's look at the actual header and see if it matches. */
273 if (a->compression_read_ahead != NULL)
274 bytes_read = (a->compression_read_ahead)(a, &h, 512);
276 bytes_read = 0; /* Empty file. */
278 return (ARCHIVE_FATAL);
279 if (bytes_read == 0 && bid > 0) {
280 /* An archive without a proper end-of-archive marker. */
281 /* Hold our nose and bid 1 anyway. */
284 if (bytes_read < 512) {
285 /* If it's a new archive, then just return a zero bid. */
289 * If we already know this is a tar archive,
290 * then we have a problem.
292 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
293 "Truncated tar archive");
294 return (ARCHIVE_FATAL);
297 /* If it's an end-of-archive mark, we can handle it. */
298 if ((*(const char *)h) == 0 && archive_block_is_null(h))
301 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
304 bid += 48; /* Checksum is usually 6 octal digits. */
308 /* Recognize POSIX formats. */
309 if ((memcmp(header->magic, "ustar\0", 6) == 0)
310 &&(memcmp(header->version, "00", 2)==0))
313 /* Recognize GNU tar format. */
314 if ((memcmp(header->magic, "ustar ", 6) == 0)
315 &&(memcmp(header->version, " \0", 2)==0))
318 /* Type flag must be null, digit or A-Z, a-z. */
319 if (header->typeflag[0] != 0 &&
320 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
321 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
322 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
325 /* Sanity check: Look at first byte of mode field. */
326 switch (255 & (unsigned)header->mode[0]) {
328 /* Base-256 value: No further verification possible! */
330 case ' ': /* Not recommended, but not illegal, either. */
332 case '0': case '1': case '2': case '3':
333 case '4': case '5': case '6': case '7':
335 /* TODO: Check format of remainder of this field. */
338 /* Not a valid mode; bail out here. */
341 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
347 * The function invoked by archive_read_header(). This
348 * just sets up a few things and then calls the internal
349 * tar_read_header() function below.
352 archive_read_format_tar_read_header(struct archive *a,
353 struct archive_entry *entry)
361 memset(&st, 0, sizeof(st));
362 tar = *(a->pformat_data);
363 tar->entry_offset = 0;
365 r = tar_read_header(a, tar, entry, &st);
367 if (r == ARCHIVE_OK) {
369 * "Regular" entry with trailing '/' is really
370 * directory: This is needed for certain old tar
371 * variants and even for some broken newer ones.
373 p = archive_entry_pathname(entry);
375 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
376 st.st_mode &= ~S_IFMT;
377 st.st_mode |= S_IFDIR;
380 /* Copy the final stat data into the entry. */
381 archive_entry_copy_stat(entry, &st);
387 archive_read_format_tar_read_data(struct archive *a,
388 const void **buff, size_t *size, off_t *offset)
392 struct sparse_block *p;
394 tar = *(a->pformat_data);
395 if (tar->entry_bytes_remaining > 0) {
396 bytes_read = (a->compression_read_ahead)(a, buff, 1);
398 return (ARCHIVE_FATAL);
399 if (bytes_read > tar->entry_bytes_remaining)
400 bytes_read = tar->entry_bytes_remaining;
401 while (tar->sparse_list != NULL &&
402 tar->sparse_list->remaining == 0) {
403 p = tar->sparse_list;
404 tar->sparse_list = p->next;
406 if (tar->sparse_list != NULL)
407 tar->entry_offset = tar->sparse_list->offset;
409 if (tar->sparse_list != NULL) {
410 if (tar->sparse_list->remaining < bytes_read)
411 bytes_read = tar->sparse_list->remaining;
412 tar->sparse_list->remaining -= bytes_read;
415 *offset = tar->entry_offset;
416 tar->entry_offset += bytes_read;
417 tar->entry_bytes_remaining -= bytes_read;
418 (a->compression_read_consume)(a, bytes_read);
421 while (tar->entry_padding > 0) {
422 bytes_read = (a->compression_read_ahead)(a, buff, 1);
424 return (ARCHIVE_FATAL);
425 if (bytes_read > tar->entry_padding)
426 bytes_read = tar->entry_padding;
427 (a->compression_read_consume)(a, bytes_read);
428 tar->entry_padding -= bytes_read;
432 *offset = tar->entry_offset;
433 return (ARCHIVE_EOF);
438 * This function recursively interprets all of the headers associated
439 * with a single entry.
442 tar_read_header(struct archive *a, struct tar *tar,
443 struct archive_entry *entry, struct stat *st)
448 const struct archive_entry_header_ustar *header;
450 /* Read 512-byte header record */
451 bytes = (a->compression_read_ahead)(a, &h, 512);
454 * If we're here, it's becase the _bid function accepted
455 * this file. So just call a short read end-of-archive
456 * and be done with it.
458 return (ARCHIVE_EOF);
460 (a->compression_read_consume)(a, 512);
462 /* Check for end-of-archive mark. */
463 if (((*(const char *)h)==0) && archive_block_is_null(h)) {
464 /* Try to consume a second all-null record, as well. */
465 bytes = (a->compression_read_ahead)(a, &h, 512);
467 (a->compression_read_consume)(a, bytes);
468 archive_set_error(a, 0, NULL);
469 return (ARCHIVE_EOF);
473 * Note: If the checksum fails and we return ARCHIVE_RETRY,
474 * then the client is likely to just retry. This is a very
475 * crude way to search for the next valid header!
477 * TODO: Improve this by implementing a real header scan.
479 if (!checksum(a, h)) {
480 archive_set_error(a, EINVAL, "Damaged tar archive");
481 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
484 if (++tar->header_recursion_depth > 32) {
485 archive_set_error(a, EINVAL, "Too many special headers");
486 return (ARCHIVE_WARN);
489 /* Determine the format variant. */
491 switch(header->typeflag[0]) {
492 case 'A': /* Solaris tar ACL */
493 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
494 a->archive_format_name = "Solaris tar";
495 err = header_Solaris_ACL(a, tar, entry, st, h);
497 case 'g': /* POSIX-standard 'g' header. */
498 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
499 a->archive_format_name = "POSIX pax interchange format";
500 err = header_pax_global(a, tar, entry, st, h);
502 case 'K': /* Long link name (GNU tar, others) */
503 err = header_longlink(a, tar, entry, st, h);
505 case 'L': /* Long filename (GNU tar, others) */
506 err = header_longname(a, tar, entry, st, h);
508 case 'V': /* GNU volume header */
509 err = header_volume(a, tar, entry, st, h);
511 case 'X': /* Used by SUN tar; same as 'x'. */
512 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
513 a->archive_format_name =
514 "POSIX pax interchange format (Sun variant)";
515 err = header_pax_extensions(a, tar, entry, st, h);
517 case 'x': /* POSIX-standard 'x' header. */
518 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
519 a->archive_format_name = "POSIX pax interchange format";
520 err = header_pax_extensions(a, tar, entry, st, h);
523 if (memcmp(header->magic, "ustar \0", 8) == 0) {
524 a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
525 a->archive_format_name = "GNU tar format";
526 err = header_gnutar(a, tar, entry, st, h);
527 } else if (memcmp(header->magic, "ustar", 5) == 0) {
528 if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
529 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
530 a->archive_format_name = "POSIX ustar format";
532 err = header_ustar(a, tar, entry, st, h);
534 a->archive_format = ARCHIVE_FORMAT_TAR;
535 a->archive_format_name = "tar (non-POSIX)";
536 err = header_old_tar(a, tar, entry, st, h);
539 --tar->header_recursion_depth;
544 * Return true if block checksum is correct.
547 checksum(struct archive *a, const void *h)
549 const unsigned char *bytes;
550 const struct archive_entry_header_ustar *header;
553 (void)a; /* UNUSED */
558 * Test the checksum. Note that POSIX specifies _unsigned_
559 * bytes for this calculation.
561 sum = tar_atol(header->checksum, sizeof(header->checksum));
563 for (i = 0; i < 148; i++)
564 check += (unsigned char)bytes[i];
568 check += (unsigned char)bytes[i];
573 * Repeat test with _signed_ bytes, just in case this archive
574 * was created by an old BSD, Solaris, or HP-UX tar with a
575 * broken checksum calculation.
578 for (i = 0; i < 148; i++)
579 check += (signed char)bytes[i];
583 check += (signed char)bytes[i];
591 * Return true if this block contains only nulls.
594 archive_block_is_null(const unsigned char *p)
598 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
605 * Interpret 'A' Solaris ACL header
608 header_Solaris_ACL(struct archive *a, struct tar *tar,
609 struct archive_entry *entry, struct stat *st, const void *h)
615 err = read_body_to_string(a, tar, &(tar->acl_text), h);
616 err2 = tar_read_header(a, tar, entry, st);
617 err = err_combine(err, err2);
619 /* XXX Ensure p doesn't overrun acl_text */
621 /* Skip leading octal number. */
622 /* XXX TODO: Parse the octal number and sanity-check it. */
628 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
630 utf8_decode(wp, p, strlen(p));
631 err2 = __archive_entry_acl_parse_w(entry, wp,
632 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
633 err = err_combine(err, err2);
641 * Interpret 'K' long linkname header.
644 header_longlink(struct archive *a, struct tar *tar,
645 struct archive_entry *entry, struct stat *st, const void *h)
649 err = read_body_to_string(a, tar, &(tar->longlink), h);
650 err2 = tar_read_header(a, tar, entry, st);
651 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
652 /* Set symlink if symlink already set, else hardlink. */
653 archive_entry_set_link(entry, tar->longlink.s);
655 return (err_combine(err, err2));
659 * Interpret 'L' long filename header.
662 header_longname(struct archive *a, struct tar *tar,
663 struct archive_entry *entry, struct stat *st, const void *h)
667 err = read_body_to_string(a, tar, &(tar->longname), h);
668 /* Read and parse "real" header, then override name. */
669 err2 = tar_read_header(a, tar, entry, st);
670 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
671 archive_entry_set_pathname(entry, tar->longname.s);
672 return (err_combine(err, err2));
677 * Interpret 'V' GNU tar volume header.
680 header_volume(struct archive *a, struct tar *tar,
681 struct archive_entry *entry, struct stat *st, const void *h)
685 /* Just skip this and read the next header. */
686 return (tar_read_header(a, tar, entry, st));
690 * Read body of an archive entry into an archive_string object.
693 read_body_to_string(struct archive *a, struct tar *tar,
694 struct archive_string *as, const void *h)
696 off_t size, padded_size;
697 ssize_t bytes_read, bytes_to_copy;
698 const struct archive_entry_header_ustar *header;
702 (void)tar; /* UNUSED */
704 size = tar_atol(header->size, sizeof(header->size));
706 /* Read the body into the string. */
707 archive_string_ensure(as, size+1);
708 padded_size = (size + 511) & ~ 511;
710 while (padded_size > 0) {
711 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
713 return (ARCHIVE_FATAL);
714 if (bytes_read > padded_size)
715 bytes_read = padded_size;
716 (a->compression_read_consume)(a, bytes_read);
717 bytes_to_copy = bytes_read;
718 if ((off_t)bytes_to_copy > size)
719 bytes_to_copy = (ssize_t)size;
720 memcpy(dest, src, bytes_to_copy);
721 dest += bytes_to_copy;
722 size -= bytes_to_copy;
723 padded_size -= bytes_read;
730 * Parse out common header elements.
732 * This would be the same as header_old_tar, except that the
733 * filename is handled slightly differently for old and POSIX
734 * entries (POSIX entries support a 'prefix'). This factoring
735 * allows header_old_tar and header_ustar
736 * to handle filenames differently, while still putting most of the
737 * common parsing into one place.
740 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
741 struct stat *st, const void *h)
743 const struct archive_entry_header_ustar *header;
746 (void)a; /* UNUSED */
749 if (header->linkname[0])
750 archive_strncpy(&(tar->entry_linkname), header->linkname,
751 sizeof(header->linkname));
753 archive_string_empty(&(tar->entry_linkname));
755 /* Parse out the numeric fields (all are octal) */
756 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
757 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
758 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
759 st->st_size = tar_atol(header->size, sizeof(header->size));
760 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
762 /* Handle the tar type flag appropriately. */
763 tartype = header->typeflag[0];
764 st->st_mode &= ~S_IFMT;
767 case '1': /* Hard link */
768 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
770 * The following may seem odd, but: Technically, tar
771 * does not store the file type for a "hard link"
772 * entry, only the fact that it is a hard link. So, I
773 * leave the type zero normally. But, pax interchange
774 * format allows hard links to have data, which
775 * implies that the underlying entry is a regular
779 st->st_mode |= S_IFREG;
782 * A tricky point: Traditionally, tar readers have
783 * ignored the size field when reading hardlink
784 * entries, and some writers put non-zero sizes even
785 * though the body is empty. POSIX.1-2001 broke with
786 * this tradition by permitting hardlink entries to
787 * store valid bodies in pax interchange format, but
788 * not in ustar format. Since there is no hard and
789 * fast way to distinguish pax interchange from
790 * earlier archives (the 'x' and 'g' entries are
791 * optional, after all), we need a heuristic. Here, I
792 * use the bid function to test whether or not there's
793 * a valid header following. Of course, if we know
794 * this is pax interchange format, then we must obey
797 * This heuristic will only fail for a pax interchange
798 * archive that is storing hardlink bodies, no pax
799 * extended attribute entries have yet occurred, and
800 * we encounter a hardlink entry for a file that is
801 * itself an uncompressed tar archive.
803 if (st->st_size > 0 &&
804 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
805 archive_read_format_tar_bid(a) > 50)
808 case '2': /* Symlink */
809 st->st_mode |= S_IFLNK;
811 archive_entry_set_symlink(entry, tar->entry_linkname.s);
813 case '3': /* Character device */
814 st->st_mode |= S_IFCHR;
817 case '4': /* Block device */
818 st->st_mode |= S_IFBLK;
822 st->st_mode |= S_IFDIR;
825 case '6': /* FIFO device */
826 st->st_mode |= S_IFIFO;
829 case 'D': /* GNU incremental directory type */
831 * No special handling is actually required here.
832 * It might be nice someday to preprocess the file list and
833 * provide it to the client, though.
835 st->st_mode |= S_IFDIR;
837 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
839 * As far as I can tell, this is just like a regular file
840 * entry, except that the contents should be _appended_ to
841 * the indicated file at the indicated offset. This may
842 * require some API work to fully support.
845 case 'N': /* Old GNU "long filename" entry. */
846 /* The body of this entry is a script for renaming
847 * previously-extracted entries. Ugh. It will never
848 * be supported by libarchive. */
849 st->st_mode |= S_IFREG;
851 case 'S': /* GNU sparse files */
853 * Sparse files are really just regular files with
854 * sparse information in the extended area.
857 default: /* Regular file and non-standard types */
859 * Per POSIX: non-recognized types should always be
860 * treated as regular files.
862 st->st_mode |= S_IFREG;
869 * Parse out header elements for "old-style" tar archives.
872 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
873 struct stat *st, const void *h)
875 const struct archive_entry_header_ustar *header;
877 /* Copy filename over (to ensure null termination). */
879 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
880 archive_entry_set_pathname(entry, tar->entry_name.s);
882 /* Grab rest of common fields */
883 header_common(a, tar, entry, st, h);
885 tar->entry_bytes_remaining = st->st_size;
886 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
891 * Parse a file header for a pax extended archive entry.
894 header_pax_global(struct archive *a, struct tar *tar,
895 struct archive_entry *entry, struct stat *st, const void *h)
899 err = read_body_to_string(a, tar, &(tar->pax_global), h);
900 err2 = tar_read_header(a, tar, entry, st);
901 return (err_combine(err, err2));
905 header_pax_extensions(struct archive *a, struct tar *tar,
906 struct archive_entry *entry, struct stat *st, const void *h)
910 read_body_to_string(a, tar, &(tar->pax_header), h);
912 /* Parse the next header. */
913 err = tar_read_header(a, tar, entry, st);
916 * TODO: Parse global/default options into 'entry' struct here
917 * before handling file-specific options.
919 * This design (parse standard header, then overwrite with pax
920 * extended attribute data) usually works well, but isn't ideal;
921 * it would be better to parse the pax extended attributes first
922 * and then skip any fields in the standard header that were
923 * defined in the pax header.
925 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
926 err = err_combine(err, err2);
927 tar->entry_bytes_remaining = st->st_size;
928 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
934 * Parse a file header for a Posix "ustar" archive entry. This also
935 * handles "pax" or "extended ustar" entries.
938 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
939 struct stat *st, const void *h)
941 const struct archive_entry_header_ustar *header;
942 struct archive_string *as;
946 /* Copy name into an internal buffer to ensure null-termination. */
947 as = &(tar->entry_name);
948 if (header->prefix[0]) {
949 archive_strncpy(as, header->prefix, sizeof(header->prefix));
950 if (as->s[archive_strlen(as) - 1] != '/')
951 archive_strappend_char(as, '/');
952 archive_strncat(as, header->name, sizeof(header->name));
954 archive_strncpy(as, header->name, sizeof(header->name));
956 archive_entry_set_pathname(entry, as->s);
958 /* Handle rest of common fields. */
959 header_common(a, tar, entry, st, h);
961 /* Handle POSIX ustar fields. */
962 archive_strncpy(&(tar->entry_uname), header->uname,
963 sizeof(header->uname));
964 archive_entry_set_uname(entry, tar->entry_uname.s);
966 archive_strncpy(&(tar->entry_gname), header->gname,
967 sizeof(header->gname));
968 archive_entry_set_gname(entry, tar->entry_gname.s);
970 /* Parse out device numbers only for char and block specials. */
971 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
972 st->st_rdev = makedev(
973 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
974 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
977 tar->entry_bytes_remaining = st->st_size;
978 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
985 * Parse the pax extended attributes record.
987 * Returns non-zero if there's an error in the data.
990 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
991 struct stat *st, char *attr)
993 size_t attr_length, l, line_length;
995 wchar_t *key, *wp, *value;
998 attr_length = strlen(attr);
1000 while (attr_length > 0) {
1001 /* Parse decimal length field at start of line. */
1004 line = p = attr; /* Record start of line. */
1011 if (*p < '0' || *p > '9')
1014 line_length += *p - '0';
1015 if (line_length > 999999)
1021 if (line_length > attr_length)
1024 /* Ensure pax_entry buffer is big enough. */
1025 if (tar->pax_entry_length <= line_length) {
1026 if (tar->pax_entry_length <= 0)
1027 tar->pax_entry_length = 1024;
1028 while (tar->pax_entry_length <= line_length + 1)
1029 tar->pax_entry_length *= 2;
1031 /* XXX Error handling here */
1032 tar->pax_entry = realloc(tar->pax_entry,
1033 tar->pax_entry_length * sizeof(wchar_t));
1036 /* Decode UTF-8 to wchar_t, null-terminate result. */
1037 if (utf8_decode(tar->pax_entry, p,
1038 line_length - (p - attr) - 1)) {
1039 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1040 "Invalid UTF8 character in pax extended attribute");
1041 err = err_combine(err, ARCHIVE_WARN);
1044 /* Null-terminate 'key' value. */
1045 key = tar->pax_entry;
1048 wp = wcschr(key, L'=');
1050 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1051 "Invalid pax extended attributes");
1052 return (ARCHIVE_WARN);
1056 /* Identify null-terminated 'value' portion. */
1059 /* Identify this attribute and set it in the entry. */
1060 err2 = pax_attribute(entry, st, key, value);
1061 err = err_combine(err, err2);
1063 /* Skip to next line */
1064 attr += line_length;
1065 attr_length -= line_length;
1073 * Parse a single key=value attribute. key/value pointers are
1074 * assumed to point into reasonably long-lived storage.
1076 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1077 * extensions should always have keywords of the form "VENDOR.attribute"
1078 * In particular, it's quite feasible to support many different
1079 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1080 * unique to this library (currently, there are none).
1082 * Investigate other vendor-specific extensions, as well and see if
1083 * any of them look useful.
1086 pax_attribute(struct archive_entry *entry, struct stat *st,
1087 wchar_t *key, wchar_t *value)
1094 /* Our extensions */
1095 /* TODO: Handle arbitrary extended attributes... */
1097 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1098 archive_entry_set_xxxxxx(entry, value);
1102 /* We support some keys used by the "star" archiver */
1103 if (wcscmp(key, L"SCHILY.acl.access")==0)
1104 __archive_entry_acl_parse_w(entry, value,
1105 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1106 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1107 __archive_entry_acl_parse_w(entry, value,
1108 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1109 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1110 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1111 minor(st->st_rdev));
1112 else if (wcscmp(key, L"SCHILY.devminor")==0)
1113 st->st_rdev = makedev(major(st->st_rdev),
1114 tar_atol10(value, wcslen(value)));
1115 else if (wcscmp(key, L"SCHILY.fflags")==0)
1116 archive_entry_copy_fflags_text_w(entry, value);
1117 else if (wcscmp(key, L"SCHILY.nlink")==0)
1118 st->st_nlink = tar_atol10(value, wcslen(value));
1121 if (wcscmp(key, L"atime")==0) {
1122 pax_time(value, &s, &n);
1124 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1128 if (wcscmp(key, L"ctime")==0) {
1129 pax_time(value, &s, &n);
1131 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1132 } else if (wcscmp(key, L"charset")==0) {
1133 /* TODO: Publish charset information in entry. */
1134 } else if (wcscmp(key, L"comment")==0) {
1135 /* TODO: Publish comment in entry. */
1139 if (wcscmp(key, L"gid")==0)
1140 st->st_gid = tar_atol10(value, wcslen(value));
1141 else if (wcscmp(key, L"gname")==0)
1142 archive_entry_copy_gname_w(entry, value);
1145 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1146 if (wcscmp(key, L"linkpath")==0) {
1147 if (archive_entry_hardlink(entry))
1148 archive_entry_copy_hardlink_w(entry, value);
1150 archive_entry_copy_symlink_w(entry, value);
1154 if (wcscmp(key, L"mtime")==0) {
1155 pax_time(value, &s, &n);
1157 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1161 if (wcscmp(key, L"path")==0)
1162 archive_entry_copy_pathname_w(entry, value);
1165 /* POSIX has reserved 'realtime.*' */
1168 /* POSIX has reserved 'security.*' */
1169 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1170 if (wcscmp(key, L"size")==0)
1171 st->st_size = tar_atol10(value, wcslen(value));
1174 if (wcscmp(key, L"uid")==0)
1175 st->st_uid = tar_atol10(value, wcslen(value));
1176 else if (wcscmp(key, L"uname")==0)
1177 archive_entry_copy_uname_w(entry, value);
1186 * parse a decimal time value, which may include a fractional portion
1189 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1195 int64_t limit, last_digit_limit;
1197 limit = max_int64 / 10;
1198 last_digit_limit = max_int64 % 10;
1206 while (*p >= '0' && *p <= '9') {
1209 (s == limit && digit > last_digit_limit)) {
1213 s = (s * 10) + digit;
1219 /* Calculate nanoseconds. */
1228 if (*p >= '0' && *p <= '9')
1229 *pn += (*p - '0') * l;
1236 * Parse GNU tar header
1239 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1240 struct stat *st, const void *h)
1242 const struct archive_entry_header_gnutar *header;
1247 * GNU header is like POSIX ustar, except 'prefix' is
1248 * replaced with some other fields. This also means the
1249 * filename is stored as in old-style archives.
1252 /* Grab fields common to all tar variants. */
1253 header_common(a, tar, entry, st, h);
1255 /* Copy filename over (to ensure null termination). */
1257 archive_strncpy(&(tar->entry_name), header->name,
1258 sizeof(header->name));
1259 archive_entry_set_pathname(entry, tar->entry_name.s);
1261 /* Fields common to ustar and GNU */
1262 /* XXX Can the following be factored out since it's common
1263 * to ustar and gnu tar? Is it okay to move it down into
1264 * header_common, perhaps? */
1265 archive_strncpy(&(tar->entry_uname),
1266 header->uname, sizeof(header->uname));
1267 archive_entry_set_uname(entry, tar->entry_uname.s);
1269 archive_strncpy(&(tar->entry_gname),
1270 header->gname, sizeof(header->gname));
1271 archive_entry_set_gname(entry, tar->entry_gname.s);
1273 /* Parse out device numbers only for char and block specials */
1274 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1275 st->st_rdev = makedev (
1276 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1277 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1281 tar->entry_bytes_remaining = st->st_size;
1282 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1284 /* Grab GNU-specific fields. */
1285 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1286 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1287 if (header->realsize[0] != 0) {
1288 st->st_size = tar_atol(header->realsize,
1289 sizeof(header->realsize));
1292 if (header->sparse[0].offset[0] != 0) {
1293 gnu_read_sparse_data(a, tar, header);
1295 if (header->isextended[0] != 0) {
1304 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1305 const struct archive_entry_header_gnutar *header)
1310 struct gnu_sparse sparse[21];
1314 const struct extended *ext;
1316 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1317 if (header->isextended[0] == 0)
1318 return (ARCHIVE_OK);
1321 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1323 return (ARCHIVE_FATAL);
1324 if (bytes_read < 512) {
1325 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1326 "Truncated tar archive "
1327 "detected while reading sparse file data");
1328 return (ARCHIVE_FATAL);
1330 (a->compression_read_consume)(a, 512);
1331 ext = (const struct extended *)data;
1332 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1333 } while (ext->isextended[0] != 0);
1334 if (tar->sparse_list != NULL)
1335 tar->entry_offset = tar->sparse_list->offset;
1336 return (ARCHIVE_OK);
1340 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1341 const struct gnu_sparse *sparse, int length)
1343 struct sparse_block *last;
1344 struct sparse_block *p;
1346 (void)a; /* UNUSED */
1348 last = tar->sparse_list;
1349 while (last != NULL && last->next != NULL)
1352 while (length > 0 && sparse->offset[0] != 0) {
1353 p = malloc(sizeof(*p));
1354 memset(p, 0, sizeof(*p));
1358 tar->sparse_list = p;
1360 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1362 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1369 * Convert text->integer.
1371 * Traditional tar formats (including POSIX) specify base-8 for
1372 * all of the standard numeric fields. This is a significant limitation
1374 * = file size is limited to 8GB
1375 * = rdevmajor and rdevminor are limited to 21 bits
1376 * = uid/gid are limited to 21 bits
1378 * There are two workarounds for this:
1379 * = pax extended headers, which use variable-length string fields
1380 * = GNU tar and STAR both allow either base-8 or base-256 in
1381 * most fields. The high bit is set to indicate base-256.
1383 * On read, this implementation supports both extensions.
1386 tar_atol(const char *p, unsigned char_cnt)
1389 * Technically, GNU tar considers a field to be in base-256
1390 * only if the first byte is 0xff or 0x80.
1393 return (tar_atol256(p, char_cnt));
1394 return (tar_atol8(p, char_cnt));
1398 * Note that this implementation does not (and should not!) obey
1399 * locale settings; you cannot simply substitute strtol here, since
1400 * it does obey locale.
1403 tar_atol8(const char *p, unsigned char_cnt)
1405 int64_t l, limit, last_digit_limit;
1406 int digit, sign, base;
1409 limit = max_int64 / base;
1410 last_digit_limit = max_int64 % base;
1412 while (*p == ' ' || *p == '\t')
1422 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1423 if (l>limit || (l == limit && digit > last_digit_limit)) {
1424 l = max_uint64; /* Truncate on overflow. */
1427 l = (l * base) + digit;
1430 return (sign < 0) ? -l : l;
1435 * Note that this implementation does not (and should not!) obey
1436 * locale settings; you cannot simply substitute strtol here, since
1437 * it does obey locale.
1440 tar_atol10(const wchar_t *p, unsigned char_cnt)
1442 int64_t l, limit, last_digit_limit;
1443 int base, digit, sign;
1446 limit = max_int64 / base;
1447 last_digit_limit = max_int64 % base;
1449 while (*p == ' ' || *p == '\t')
1459 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1460 if (l > limit || (l == limit && digit > last_digit_limit)) {
1461 l = max_uint64; /* Truncate on overflow. */
1464 l = (l * base) + digit;
1467 return (sign < 0) ? -l : l;
1471 * Parse a base-256 integer. This is just a straight signed binary
1472 * value in big-endian order, except that the high-order bit is
1473 * ignored. Remember that "int64_t" may or may not be exactly 64
1474 * bits; the implementation here tries to avoid making any assumptions
1475 * about the actual size of an int64_t. It does assume we're using
1476 * twos-complement arithmetic, though.
1479 tar_atol256(const char *_p, unsigned char_cnt)
1481 int64_t l, upper_limit, lower_limit;
1482 const unsigned char *p = _p;
1484 upper_limit = max_int64 / 256;
1485 lower_limit = min_int64 / 256;
1487 /* Pad with 1 or 0 bits, depending on sign. */
1488 if ((0x40 & *p) == 0x40)
1492 l = (l << 6) | (0x3f & *p++);
1493 while (--char_cnt > 0) {
1494 if (l > upper_limit) {
1495 l = max_int64; /* Truncate on overflow */
1497 } else if (l < lower_limit) {
1501 l = (l << 8) | (0xff & (int64_t)*p++);
1507 utf8_decode(wchar_t *dest, const char *src, size_t length)
1514 n = UTF8_mbrtowc(dest, src, length);
1518 /* Invalid byte encountered; try to keep going. */
1532 * Copied from FreeBSD libc/locale.
1535 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1537 int ch, i, len, mask;
1538 unsigned long lbound, wch;
1541 /* Reset to initial shift state (no-op) */
1544 /* Incomplete multibyte sequence */
1545 return ((size_t)-2);
1548 * Determine the number of octets that make up this character from
1549 * the first octet, and a mask that extracts the interesting bits of
1552 * We also specify a lower bound for the character code to detect
1553 * redundant, non-"shortest form" encodings. For example, the
1554 * sequence C0 80 is _not_ a legal representation of the null
1555 * character. This enforces a 1-to-1 mapping between character
1556 * codes and their multibyte representations.
1558 ch = (unsigned char)*s;
1559 if ((ch & 0x80) == 0) {
1563 } else if ((ch & 0xe0) == 0xc0) {
1567 } else if ((ch & 0xf0) == 0xe0) {
1571 } else if ((ch & 0xf8) == 0xf0) {
1575 } else if ((ch & 0xfc) == 0xf8) {
1579 } else if ((ch & 0xfc) == 0xfc) {
1585 * Malformed input; input is not UTF-8.
1588 return ((size_t)-1);
1591 if (n < (size_t)len)
1592 /* Incomplete multibyte sequence */
1593 return ((size_t)-2);
1596 * Decode the octet sequence representing the character in chunks
1597 * of 6 bits, most significant first.
1599 wch = (unsigned char)*s++ & mask;
1602 if ((*s & 0xc0) != 0x80) {
1604 * Malformed input; bad characters in the middle
1608 return ((size_t)-1);
1615 * Malformed input; redundant encoding.
1618 return ((size_t)-1);
1621 /* Assign the value to the output; out-of-range values
1622 * just get truncated. */
1623 *pwc = (wchar_t)wch;
1626 * If platform has WCHAR_MAX, we can do something
1627 * more sensible with out-of-range values.
1629 if (wch >= WCHAR_MAX)
1633 return (wch == L'\0' ? 0 : len);