2 * Copyright (c) 2003-2007 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 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "archive_platform.h"
27 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_tar.c,v 1.62 2007/10/24 04:01:31 kientzle Exp $");
33 /* #include <stdint.h> */ /* See archive_platform.h */
41 /* Obtain suitable wide-character manipulation functions. */
45 /* Good enough for equality testing, which is all we need. */
46 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
49 while (*s1 && diff == 0)
50 diff = (int)*++s1 - (int)*++s2;
53 /* Good enough for equality testing, which is all we need. */
54 static int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n)
57 while (*s1 && diff == 0 && n-- > 0)
58 diff = (int)*++s1 - (int)*++s2;
61 static size_t wcslen(const wchar_t *s)
71 #include "archive_entry.h"
72 #include "archive_private.h"
73 #include "archive_read_private.h"
75 #define tar_min(a,b) ((a) < (b) ? (a) : (b))
78 * Layout of POSIX 'ustar' tar header.
80 struct archive_entry_header_ustar {
89 char linkname[100]; /* "old format" header ends here */
90 char magic[6]; /* For POSIX: "ustar\0" */
91 char version[2]; /* For POSIX: "00" */
100 * Structure of GNU tar header
107 struct archive_entry_header_gnutar {
117 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
127 struct gnu_sparse sparse[4];
131 * Old GNU format doesn't use POSIX 'prefix' field; they use
132 * the 'L' (longname) entry instead.
137 * Data specific to this format.
139 struct sparse_block {
140 struct sparse_block *next;
146 struct archive_string acl_text;
147 struct archive_string entry_name;
148 struct archive_string entry_linkname;
149 struct archive_string entry_uname;
150 struct archive_string entry_gname;
151 struct archive_string longlink;
152 struct archive_string longname;
153 struct archive_string pax_header;
154 struct archive_string pax_global;
155 struct archive_string line;
157 size_t pax_entry_length;
158 int header_recursion_depth;
159 off_t entry_bytes_remaining;
163 struct sparse_block *sparse_list;
164 struct sparse_block *sparse_last;
165 int64_t sparse_offset;
166 int64_t sparse_numbytes;
167 int sparse_gnu_major;
168 int sparse_gnu_minor;
169 char sparse_gnu_pending;
172 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
173 static int archive_block_is_null(const unsigned char *p);
174 static char *base64_decode(const wchar_t *, size_t, size_t *);
175 static void gnu_add_sparse_entry(struct tar *,
176 off_t offset, off_t remaining);
177 static void gnu_clear_sparse_list(struct tar *);
178 static int gnu_sparse_old_read(struct archive_read *, struct tar *,
179 const struct archive_entry_header_gnutar *header);
180 static void gnu_sparse_old_parse(struct tar *,
181 const struct gnu_sparse *sparse, int length);
182 static int gnu_sparse_01_parse(struct tar *, const wchar_t *);
183 static ssize_t gnu_sparse_10_read(struct archive_read *, struct tar *);
184 static int header_Solaris_ACL(struct archive_read *, struct tar *,
185 struct archive_entry *, const void *);
186 static int header_common(struct archive_read *, struct tar *,
187 struct archive_entry *, const void *);
188 static int header_old_tar(struct archive_read *, struct tar *,
189 struct archive_entry *, const void *);
190 static int header_pax_extensions(struct archive_read *, struct tar *,
191 struct archive_entry *, const void *);
192 static int header_pax_global(struct archive_read *, struct tar *,
193 struct archive_entry *, const void *h);
194 static int header_longlink(struct archive_read *, struct tar *,
195 struct archive_entry *, const void *h);
196 static int header_longname(struct archive_read *, struct tar *,
197 struct archive_entry *, const void *h);
198 static int header_volume(struct archive_read *, struct tar *,
199 struct archive_entry *, const void *h);
200 static int header_ustar(struct archive_read *, struct tar *,
201 struct archive_entry *, const void *h);
202 static int header_gnutar(struct archive_read *, struct tar *,
203 struct archive_entry *, const void *h);
204 static int archive_read_format_tar_bid(struct archive_read *);
205 static int archive_read_format_tar_cleanup(struct archive_read *);
206 static int archive_read_format_tar_read_data(struct archive_read *a,
207 const void **buff, size_t *size, off_t *offset);
208 static int archive_read_format_tar_skip(struct archive_read *a);
209 static int archive_read_format_tar_read_header(struct archive_read *,
210 struct archive_entry *);
211 static int checksum(struct archive_read *, const void *);
212 static int pax_attribute(struct tar *, struct archive_entry *,
213 wchar_t *key, wchar_t *value);
214 static int pax_header(struct archive_read *, struct tar *,
215 struct archive_entry *, char *attr);
216 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
217 static ssize_t readline(struct archive_read *, struct tar *, const char **,
219 static int read_body_to_string(struct archive_read *, struct tar *,
220 struct archive_string *, const void *h);
221 static int64_t tar_atol(const char *, unsigned);
222 static int64_t tar_atol10(const wchar_t *, unsigned);
223 static int64_t tar_atol256(const char *, unsigned);
224 static int64_t tar_atol8(const char *, unsigned);
225 static int tar_read_header(struct archive_read *, struct tar *,
226 struct archive_entry *);
227 static int tohex(int c);
228 static char *url_decode(const char *);
229 static int utf8_decode(wchar_t *, const char *, size_t length);
230 static char *wide_to_narrow(const wchar_t *wval);
233 archive_read_support_format_gnutar(struct archive *a)
235 return (archive_read_support_format_tar(a));
240 archive_read_support_format_tar(struct archive *_a)
242 struct archive_read *a = (struct archive_read *)_a;
246 tar = (struct tar *)malloc(sizeof(*tar));
248 archive_set_error(&a->archive, ENOMEM,
249 "Can't allocate tar data");
250 return (ARCHIVE_FATAL);
252 memset(tar, 0, sizeof(*tar));
254 r = __archive_read_register_format(a, tar,
255 archive_read_format_tar_bid,
256 archive_read_format_tar_read_header,
257 archive_read_format_tar_read_data,
258 archive_read_format_tar_skip,
259 archive_read_format_tar_cleanup);
267 archive_read_format_tar_cleanup(struct archive_read *a)
271 tar = (struct tar *)(a->format->data);
272 gnu_clear_sparse_list(tar);
273 archive_string_free(&tar->acl_text);
274 archive_string_free(&tar->entry_name);
275 archive_string_free(&tar->entry_linkname);
276 archive_string_free(&tar->entry_uname);
277 archive_string_free(&tar->entry_gname);
278 archive_string_free(&tar->line);
279 archive_string_free(&tar->pax_global);
280 archive_string_free(&tar->pax_header);
281 archive_string_free(&tar->longname);
282 archive_string_free(&tar->longlink);
283 free(tar->pax_entry);
285 (a->format->data) = NULL;
291 archive_read_format_tar_bid(struct archive_read *a)
296 const struct archive_entry_header_ustar *header;
299 * If we're already reading a non-tar file, don't
302 if (a->archive.archive_format != 0 &&
303 (a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
309 * If we're already reading a tar format, start the bid at 1 as
312 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
316 /* Now let's look at the actual header and see if it matches. */
317 if (a->decompressor->read_ahead != NULL)
318 bytes_read = (a->decompressor->read_ahead)(a, &h, 512);
320 bytes_read = 0; /* Empty file. */
322 return (ARCHIVE_FATAL);
323 if (bytes_read < 512)
326 /* If it's an end-of-archive mark, we can handle it. */
327 if ((*(const char *)h) == 0 && archive_block_is_null((const unsigned char *)h)) {
328 /* If it's a known tar file, end-of-archive is definite. */
329 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
336 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
339 bid += 48; /* Checksum is usually 6 octal digits. */
341 header = (const struct archive_entry_header_ustar *)h;
343 /* Recognize POSIX formats. */
344 if ((memcmp(header->magic, "ustar\0", 6) == 0)
345 &&(memcmp(header->version, "00", 2)==0))
348 /* Recognize GNU tar format. */
349 if ((memcmp(header->magic, "ustar ", 6) == 0)
350 &&(memcmp(header->version, " \0", 2)==0))
353 /* Type flag must be null, digit or A-Z, a-z. */
354 if (header->typeflag[0] != 0 &&
355 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
356 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
357 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
359 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
361 /* Sanity check: Look at first byte of mode field. */
362 switch (255 & (unsigned)header->mode[0]) {
364 /* Base-256 value: No further verification possible! */
366 case ' ': /* Not recommended, but not illegal, either. */
368 case '0': case '1': case '2': case '3':
369 case '4': case '5': case '6': case '7':
371 /* TODO: Check format of remainder of this field. */
374 /* Not a valid mode; bail out here. */
377 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
383 * The function invoked by archive_read_header(). This
384 * just sets up a few things and then calls the internal
385 * tar_read_header() function below.
388 archive_read_format_tar_read_header(struct archive_read *a,
389 struct archive_entry *entry)
392 * When converting tar archives to cpio archives, it is
393 * essential that each distinct file have a distinct inode
394 * number. To simplify this, we keep a static count here to
395 * assign fake dev/inode numbers to each tar entry. Note that
396 * pax format archives may overwrite this with something more
399 * Ideally, we would track every file read from the archive so
400 * that we could assign the same dev/ino pair to hardlinks,
401 * but the memory required to store a complete lookup table is
402 * probably not worthwhile just to support the relatively
403 * obscure tar->cpio conversion case.
405 static int default_inode;
406 static int default_dev;
408 struct sparse_block *sp;
413 /* Assign default device/inode values. */
414 archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
415 archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
416 /* Limit generated st_ino number to 16 bits. */
417 if (default_inode >= 0xffff) {
422 tar = (struct tar *)(a->format->data);
423 tar->entry_offset = 0;
424 while (tar->sparse_list != NULL) {
425 sp = tar->sparse_list;
426 tar->sparse_list = sp->next;
429 tar->sparse_last = NULL;
430 tar->realsize = -1; /* Mark this as "unset" */
432 r = tar_read_header(a, tar, entry);
435 * "non-sparse" files are really just sparse files with
438 if (tar->sparse_list == NULL)
439 gnu_add_sparse_entry(tar, 0, tar->entry_bytes_remaining);
441 if (r == ARCHIVE_OK) {
443 * "Regular" entry with trailing '/' is really
444 * directory: This is needed for certain old tar
445 * variants and even for some broken newer ones.
447 p = archive_entry_pathname(entry);
449 if (archive_entry_filetype(entry) == AE_IFREG
451 archive_entry_set_filetype(entry, AE_IFDIR);
457 archive_read_format_tar_read_data(struct archive_read *a,
458 const void **buff, size_t *size, off_t *offset)
462 struct sparse_block *p;
464 tar = (struct tar *)(a->format->data);
466 if (tar->sparse_gnu_pending) {
467 if (tar->sparse_gnu_major == 1 && tar->sparse_gnu_minor == 0) {
468 tar->sparse_gnu_pending = 0;
469 /* Read initial sparse map. */
470 bytes_read = gnu_sparse_10_read(a, tar);
471 tar->entry_bytes_remaining -= bytes_read;
477 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
478 "Unrecognized GNU sparse file format");
479 return (ARCHIVE_WARN);
481 tar->sparse_gnu_pending = 0;
484 /* Remove exhausted entries from sparse list. */
485 while (tar->sparse_list != NULL &&
486 tar->sparse_list->remaining == 0) {
487 p = tar->sparse_list;
488 tar->sparse_list = p->next;
492 /* If we're at end of file, return EOF. */
493 if (tar->sparse_list == NULL || tar->entry_bytes_remaining == 0) {
494 if ((a->decompressor->skip)(a, tar->entry_padding) < 0)
495 return (ARCHIVE_FATAL);
496 tar->entry_padding = 0;
499 *offset = tar->realsize;
500 return (ARCHIVE_EOF);
503 bytes_read = (a->decompressor->read_ahead)(a, buff, 1);
504 if (bytes_read == 0) {
505 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
506 "Truncated tar archive");
507 return (ARCHIVE_FATAL);
510 return (ARCHIVE_FATAL);
511 if (bytes_read > tar->entry_bytes_remaining)
512 bytes_read = tar->entry_bytes_remaining;
513 /* Don't read more than is available in the
514 * current sparse block. */
515 if (tar->sparse_list->remaining < bytes_read)
516 bytes_read = tar->sparse_list->remaining;
518 *offset = tar->sparse_list->offset;
519 tar->sparse_list->remaining -= bytes_read;
520 tar->sparse_list->offset += bytes_read;
521 tar->entry_bytes_remaining -= bytes_read;
522 (a->decompressor->consume)(a, bytes_read);
527 archive_read_format_tar_skip(struct archive_read *a)
532 tar = (struct tar *)(a->format->data);
535 * Compression layer skip functions are required to either skip the
536 * length requested or fail, so we can rely upon the entire entry
537 * plus padding being skipped.
539 bytes_skipped = (a->decompressor->skip)(a, tar->entry_bytes_remaining +
541 if (bytes_skipped < 0)
542 return (ARCHIVE_FATAL);
544 tar->entry_bytes_remaining = 0;
545 tar->entry_padding = 0;
547 /* Free the sparse list. */
548 gnu_clear_sparse_list(tar);
554 * This function recursively interprets all of the headers associated
555 * with a single entry.
558 tar_read_header(struct archive_read *a, struct tar *tar,
559 struct archive_entry *entry)
564 const struct archive_entry_header_ustar *header;
566 /* Read 512-byte header record */
567 bytes = (a->decompressor->read_ahead)(a, &h, 512);
572 * An archive that just ends without a proper
573 * end-of-archive marker. Yes, there are tar programs
574 * that do this; hold our nose and accept it.
576 return (ARCHIVE_EOF);
579 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
580 "Truncated tar archive");
581 return (ARCHIVE_FATAL);
583 (a->decompressor->consume)(a, 512);
586 /* Check for end-of-archive mark. */
587 if (((*(const char *)h)==0) && archive_block_is_null((const unsigned char *)h)) {
588 /* Try to consume a second all-null record, as well. */
589 bytes = (a->decompressor->read_ahead)(a, &h, 512);
591 (a->decompressor->consume)(a, bytes);
592 archive_set_error(&a->archive, 0, NULL);
593 return (ARCHIVE_EOF);
597 * Note: If the checksum fails and we return ARCHIVE_RETRY,
598 * then the client is likely to just retry. This is a very
599 * crude way to search for the next valid header!
601 * TODO: Improve this by implementing a real header scan.
603 if (!checksum(a, h)) {
604 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
605 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
608 if (++tar->header_recursion_depth > 32) {
609 archive_set_error(&a->archive, EINVAL, "Too many special headers");
610 return (ARCHIVE_WARN);
613 /* Determine the format variant. */
614 header = (const struct archive_entry_header_ustar *)h;
615 switch(header->typeflag[0]) {
616 case 'A': /* Solaris tar ACL */
617 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
618 a->archive.archive_format_name = "Solaris tar";
619 err = header_Solaris_ACL(a, tar, entry, h);
621 case 'g': /* POSIX-standard 'g' header. */
622 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
623 a->archive.archive_format_name = "POSIX pax interchange format";
624 err = header_pax_global(a, tar, entry, h);
626 case 'K': /* Long link name (GNU tar, others) */
627 err = header_longlink(a, tar, entry, h);
629 case 'L': /* Long filename (GNU tar, others) */
630 err = header_longname(a, tar, entry, h);
632 case 'V': /* GNU volume header */
633 err = header_volume(a, tar, entry, h);
635 case 'X': /* Used by SUN tar; same as 'x'. */
636 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
637 a->archive.archive_format_name =
638 "POSIX pax interchange format (Sun variant)";
639 err = header_pax_extensions(a, tar, entry, h);
641 case 'x': /* POSIX-standard 'x' header. */
642 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
643 a->archive.archive_format_name = "POSIX pax interchange format";
644 err = header_pax_extensions(a, tar, entry, h);
647 if (memcmp(header->magic, "ustar \0", 8) == 0) {
648 a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
649 a->archive.archive_format_name = "GNU tar format";
650 err = header_gnutar(a, tar, entry, h);
651 } else if (memcmp(header->magic, "ustar", 5) == 0) {
652 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
653 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
654 a->archive.archive_format_name = "POSIX ustar format";
656 err = header_ustar(a, tar, entry, h);
658 a->archive.archive_format = ARCHIVE_FORMAT_TAR;
659 a->archive.archive_format_name = "tar (non-POSIX)";
660 err = header_old_tar(a, tar, entry, h);
663 --tar->header_recursion_depth;
664 /* We return warnings or success as-is. Anything else is fatal. */
665 if (err == ARCHIVE_WARN || err == ARCHIVE_OK)
667 if (err == ARCHIVE_EOF)
668 /* EOF when recursively reading a header is bad. */
669 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
670 return (ARCHIVE_FATAL);
674 * Return true if block checksum is correct.
677 checksum(struct archive_read *a, const void *h)
679 const unsigned char *bytes;
680 const struct archive_entry_header_ustar *header;
683 (void)a; /* UNUSED */
684 bytes = (const unsigned char *)h;
685 header = (const struct archive_entry_header_ustar *)h;
688 * Test the checksum. Note that POSIX specifies _unsigned_
689 * bytes for this calculation.
691 sum = tar_atol(header->checksum, sizeof(header->checksum));
693 for (i = 0; i < 148; i++)
694 check += (unsigned char)bytes[i];
698 check += (unsigned char)bytes[i];
703 * Repeat test with _signed_ bytes, just in case this archive
704 * was created by an old BSD, Solaris, or HP-UX tar with a
705 * broken checksum calculation.
708 for (i = 0; i < 148; i++)
709 check += (signed char)bytes[i];
713 check += (signed char)bytes[i];
721 * Return true if this block contains only nulls.
724 archive_block_is_null(const unsigned char *p)
728 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
735 * Interpret 'A' Solaris ACL header
738 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
739 struct archive_entry *entry, const void *h)
741 const struct archive_entry_header_ustar *header;
748 * read_body_to_string adds a NUL terminator, but we need a little
749 * more to make sure that we don't overrun acl_text later.
751 header = (const struct archive_entry_header_ustar *)h;
752 size = tar_atol(header->size, sizeof(header->size));
753 err = read_body_to_string(a, tar, &(tar->acl_text), h);
754 if (err != ARCHIVE_OK)
756 err = tar_read_header(a, tar, entry);
757 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
760 /* Skip leading octal number. */
761 /* XXX TODO: Parse the octal number and sanity-check it. */
762 p = acl = tar->acl_text.s;
763 while (*p != '\0' && p < acl + size)
767 if (p >= acl + size) {
768 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
769 "Malformed Solaris ACL attribute");
770 return(ARCHIVE_WARN);
773 /* Skip leading octal number. */
777 while (*p != '\0' && p < acl + size)
780 wp = (wchar_t *)malloc((p - acl + 1) * sizeof(wchar_t));
782 archive_set_error(&a->archive, ENOMEM,
783 "Can't allocate work buffer for ACL parsing");
784 return (ARCHIVE_FATAL);
786 utf8_decode(wp, acl, p - acl);
787 err = __archive_entry_acl_parse_w(entry, wp,
788 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
794 * Interpret 'K' long linkname header.
797 header_longlink(struct archive_read *a, struct tar *tar,
798 struct archive_entry *entry, const void *h)
802 err = read_body_to_string(a, tar, &(tar->longlink), h);
803 if (err != ARCHIVE_OK)
805 err = tar_read_header(a, tar, entry);
806 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
808 /* Set symlink if symlink already set, else hardlink. */
809 archive_entry_set_link(entry, tar->longlink.s);
814 * Interpret 'L' long filename header.
817 header_longname(struct archive_read *a, struct tar *tar,
818 struct archive_entry *entry, const void *h)
822 err = read_body_to_string(a, tar, &(tar->longname), h);
823 if (err != ARCHIVE_OK)
825 /* Read and parse "real" header, then override name. */
826 err = tar_read_header(a, tar, entry);
827 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
829 archive_entry_set_pathname(entry, tar->longname.s);
835 * Interpret 'V' GNU tar volume header.
838 header_volume(struct archive_read *a, struct tar *tar,
839 struct archive_entry *entry, const void *h)
843 /* Just skip this and read the next header. */
844 return (tar_read_header(a, tar, entry));
848 * Read body of an archive entry into an archive_string object.
851 read_body_to_string(struct archive_read *a, struct tar *tar,
852 struct archive_string *as, const void *h)
854 off_t size, padded_size;
855 ssize_t bytes_read, bytes_to_copy;
856 const struct archive_entry_header_ustar *header;
860 (void)tar; /* UNUSED */
861 header = (const struct archive_entry_header_ustar *)h;
862 size = tar_atol(header->size, sizeof(header->size));
863 if ((size > 1048576) || (size < 0)) {
864 archive_set_error(&a->archive, EINVAL,
865 "Special header too large");
866 return (ARCHIVE_FATAL);
869 /* Fail if we can't make our buffer big enough. */
870 if (archive_string_ensure(as, size+1) == NULL) {
871 archive_set_error(&a->archive, ENOMEM,
873 return (ARCHIVE_FATAL);
876 /* Read the body into the string. */
877 padded_size = (size + 511) & ~ 511;
879 while (padded_size > 0) {
880 bytes_read = (a->decompressor->read_ahead)(a, &src, padded_size);
882 return (ARCHIVE_EOF);
884 return (ARCHIVE_FATAL);
885 if (bytes_read > padded_size)
886 bytes_read = padded_size;
887 (a->decompressor->consume)(a, bytes_read);
888 bytes_to_copy = bytes_read;
889 if ((off_t)bytes_to_copy > size)
890 bytes_to_copy = (ssize_t)size;
891 memcpy(dest, src, bytes_to_copy);
892 dest += bytes_to_copy;
893 size -= bytes_to_copy;
894 padded_size -= bytes_read;
901 * Parse out common header elements.
903 * This would be the same as header_old_tar, except that the
904 * filename is handled slightly differently for old and POSIX
905 * entries (POSIX entries support a 'prefix'). This factoring
906 * allows header_old_tar and header_ustar
907 * to handle filenames differently, while still putting most of the
908 * common parsing into one place.
911 header_common(struct archive_read *a, struct tar *tar,
912 struct archive_entry *entry, const void *h)
914 const struct archive_entry_header_ustar *header;
917 (void)a; /* UNUSED */
919 header = (const struct archive_entry_header_ustar *)h;
920 if (header->linkname[0])
921 archive_strncpy(&(tar->entry_linkname), header->linkname,
922 sizeof(header->linkname));
924 archive_string_empty(&(tar->entry_linkname));
926 /* Parse out the numeric fields (all are octal) */
927 archive_entry_set_mode(entry, tar_atol(header->mode, sizeof(header->mode)));
928 archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
929 archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
930 tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size));
931 tar->realsize = tar->entry_bytes_remaining;
932 archive_entry_set_size(entry, tar->entry_bytes_remaining);
933 archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
935 /* Handle the tar type flag appropriately. */
936 tartype = header->typeflag[0];
939 case '1': /* Hard link */
940 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
942 * The following may seem odd, but: Technically, tar
943 * does not store the file type for a "hard link"
944 * entry, only the fact that it is a hard link. So, I
945 * leave the type zero normally. But, pax interchange
946 * format allows hard links to have data, which
947 * implies that the underlying entry is a regular
950 if (archive_entry_size(entry) > 0)
951 archive_entry_set_filetype(entry, AE_IFREG);
954 * A tricky point: Traditionally, tar readers have
955 * ignored the size field when reading hardlink
956 * entries, and some writers put non-zero sizes even
957 * though the body is empty. POSIX.1-2001 broke with
958 * this tradition by permitting hardlink entries to
959 * store valid bodies in pax interchange format, but
960 * not in ustar format. Since there is no hard and
961 * fast way to distinguish pax interchange from
962 * earlier archives (the 'x' and 'g' entries are
963 * optional, after all), we need a heuristic. Here, I
964 * use the bid function to test whether or not there's
965 * a valid header following. Of course, if we know
966 * this is pax interchange format, then we must obey
969 * This heuristic will only fail for a pax interchange
970 * archive that is storing hardlink bodies, no pax
971 * extended attribute entries have yet occurred, and
972 * we encounter a hardlink entry for a file that is
973 * itself an uncompressed tar archive.
975 if (archive_entry_size(entry) > 0 &&
976 a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
977 archive_read_format_tar_bid(a) > 50) {
978 archive_entry_set_size(entry, 0);
979 tar->entry_bytes_remaining = 0;
982 case '2': /* Symlink */
983 archive_entry_set_filetype(entry, AE_IFLNK);
984 archive_entry_set_size(entry, 0);
985 tar->entry_bytes_remaining = 0;
986 archive_entry_set_symlink(entry, tar->entry_linkname.s);
988 case '3': /* Character device */
989 archive_entry_set_filetype(entry, AE_IFCHR);
990 archive_entry_set_size(entry, 0);
991 tar->entry_bytes_remaining = 0;
993 case '4': /* Block device */
994 archive_entry_set_filetype(entry, AE_IFBLK);
995 archive_entry_set_size(entry, 0);
996 tar->entry_bytes_remaining = 0;
999 archive_entry_set_filetype(entry, AE_IFDIR);
1000 archive_entry_set_size(entry, 0);
1001 tar->entry_bytes_remaining = 0;
1003 case '6': /* FIFO device */
1004 archive_entry_set_filetype(entry, AE_IFIFO);
1005 archive_entry_set_size(entry, 0);
1006 tar->entry_bytes_remaining = 0;
1008 case 'D': /* GNU incremental directory type */
1010 * No special handling is actually required here.
1011 * It might be nice someday to preprocess the file list and
1012 * provide it to the client, though.
1014 archive_entry_set_filetype(entry, AE_IFDIR);
1016 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1018 * As far as I can tell, this is just like a regular file
1019 * entry, except that the contents should be _appended_ to
1020 * the indicated file at the indicated offset. This may
1021 * require some API work to fully support.
1024 case 'N': /* Old GNU "long filename" entry. */
1025 /* The body of this entry is a script for renaming
1026 * previously-extracted entries. Ugh. It will never
1027 * be supported by libarchive. */
1028 archive_entry_set_filetype(entry, AE_IFREG);
1030 case 'S': /* GNU sparse files */
1032 * Sparse files are really just regular files with
1033 * sparse information in the extended area.
1036 default: /* Regular file and non-standard types */
1038 * Per POSIX: non-recognized types should always be
1039 * treated as regular files.
1041 archive_entry_set_filetype(entry, AE_IFREG);
1048 * Parse out header elements for "old-style" tar archives.
1051 header_old_tar(struct archive_read *a, struct tar *tar,
1052 struct archive_entry *entry, const void *h)
1054 const struct archive_entry_header_ustar *header;
1056 /* Copy filename over (to ensure null termination). */
1057 header = (const struct archive_entry_header_ustar *)h;
1058 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1059 archive_entry_set_pathname(entry, tar->entry_name.s);
1061 /* Grab rest of common fields */
1062 header_common(a, tar, entry, h);
1064 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1069 * Parse a file header for a pax extended archive entry.
1072 header_pax_global(struct archive_read *a, struct tar *tar,
1073 struct archive_entry *entry, const void *h)
1077 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1078 if (err != ARCHIVE_OK)
1080 err = tar_read_header(a, tar, entry);
1085 header_pax_extensions(struct archive_read *a, struct tar *tar,
1086 struct archive_entry *entry, const void *h)
1090 err = read_body_to_string(a, tar, &(tar->pax_header), h);
1091 if (err != ARCHIVE_OK)
1094 /* Parse the next header. */
1095 err = tar_read_header(a, tar, entry);
1096 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1100 * TODO: Parse global/default options into 'entry' struct here
1101 * before handling file-specific options.
1103 * This design (parse standard header, then overwrite with pax
1104 * extended attribute data) usually works well, but isn't ideal;
1105 * it would be better to parse the pax extended attributes first
1106 * and then skip any fields in the standard header that were
1107 * defined in the pax header.
1109 err2 = pax_header(a, tar, entry, tar->pax_header.s);
1110 err = err_combine(err, err2);
1111 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1117 * Parse a file header for a Posix "ustar" archive entry. This also
1118 * handles "pax" or "extended ustar" entries.
1121 header_ustar(struct archive_read *a, struct tar *tar,
1122 struct archive_entry *entry, const void *h)
1124 const struct archive_entry_header_ustar *header;
1125 struct archive_string *as;
1127 header = (const struct archive_entry_header_ustar *)h;
1129 /* Copy name into an internal buffer to ensure null-termination. */
1130 as = &(tar->entry_name);
1131 if (header->prefix[0]) {
1132 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1133 if (as->s[archive_strlen(as) - 1] != '/')
1134 archive_strappend_char(as, '/');
1135 archive_strncat(as, header->name, sizeof(header->name));
1137 archive_strncpy(as, header->name, sizeof(header->name));
1139 archive_entry_set_pathname(entry, as->s);
1141 /* Handle rest of common fields. */
1142 header_common(a, tar, entry, h);
1144 /* Handle POSIX ustar fields. */
1145 archive_strncpy(&(tar->entry_uname), header->uname,
1146 sizeof(header->uname));
1147 archive_entry_set_uname(entry, tar->entry_uname.s);
1149 archive_strncpy(&(tar->entry_gname), header->gname,
1150 sizeof(header->gname));
1151 archive_entry_set_gname(entry, tar->entry_gname.s);
1153 /* Parse out device numbers only for char and block specials. */
1154 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1155 archive_entry_set_rdevmajor(entry,
1156 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1157 archive_entry_set_rdevminor(entry,
1158 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1161 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1168 * Parse the pax extended attributes record.
1170 * Returns non-zero if there's an error in the data.
1173 pax_header(struct archive_read *a, struct tar *tar,
1174 struct archive_entry *entry, char *attr)
1176 size_t attr_length, l, line_length;
1178 wchar_t *key, *wp, *value;
1181 attr_length = strlen(attr);
1183 while (attr_length > 0) {
1184 /* Parse decimal length field at start of line. */
1187 line = p = attr; /* Record start of line. */
1194 if (*p < '0' || *p > '9') {
1195 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1196 "Ignoring malformed pax extended attributes");
1197 return (ARCHIVE_WARN);
1200 line_length += *p - '0';
1201 if (line_length > 999999) {
1202 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1203 "Rejecting pax extended attribute > 1MB");
1204 return (ARCHIVE_WARN);
1211 * Parsed length must be no bigger than available data,
1212 * at least 1, and the last character of the line must
1215 if (line_length > attr_length
1217 || attr[line_length - 1] != '\n')
1219 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1220 "Ignoring malformed pax extended attribute");
1221 return (ARCHIVE_WARN);
1224 /* Ensure pax_entry buffer is big enough. */
1225 if (tar->pax_entry_length <= line_length) {
1226 wchar_t *old_entry = tar->pax_entry;
1228 if (tar->pax_entry_length <= 0)
1229 tar->pax_entry_length = 1024;
1230 while (tar->pax_entry_length <= line_length + 1)
1231 tar->pax_entry_length *= 2;
1233 old_entry = tar->pax_entry;
1234 tar->pax_entry = (wchar_t *)realloc(tar->pax_entry,
1235 tar->pax_entry_length * sizeof(wchar_t));
1236 if (tar->pax_entry == NULL) {
1238 archive_set_error(&a->archive, ENOMEM,
1240 return (ARCHIVE_FATAL);
1244 /* Decode UTF-8 to wchar_t, null-terminate result. */
1245 if (utf8_decode(tar->pax_entry, p,
1246 line_length - (p - attr) - 1)) {
1247 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1248 "Invalid UTF8 character in pax extended attribute");
1249 err = err_combine(err, ARCHIVE_WARN);
1252 /* Null-terminate 'key' value. */
1253 wp = key = tar->pax_entry;
1256 while (*wp && *wp != L'=')
1259 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1260 "Invalid pax extended attributes");
1261 return (ARCHIVE_WARN);
1265 /* Identify null-terminated 'value' portion. */
1268 /* Identify this attribute and set it in the entry. */
1269 err2 = pax_attribute(tar, entry, key, value);
1270 err = err_combine(err, err2);
1272 /* Skip to next line */
1273 attr += line_length;
1274 attr_length -= line_length;
1280 pax_attribute_xattr(struct archive_entry *entry,
1281 wchar_t *name, wchar_t *value)
1283 char *name_decoded, *name_narrow;
1284 void *value_decoded;
1287 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1292 /* URL-decode name */
1293 name_narrow = wide_to_narrow(name);
1294 if (name_narrow == NULL)
1296 name_decoded = url_decode(name_narrow);
1298 if (name_decoded == NULL)
1301 /* Base-64 decode value */
1302 value_decoded = base64_decode(value, wcslen(value), &value_len);
1303 if (value_decoded == NULL) {
1308 archive_entry_xattr_add_entry(entry, name_decoded,
1309 value_decoded, value_len);
1312 free(value_decoded);
1317 * Parse a single key=value attribute. key/value pointers are
1318 * assumed to point into reasonably long-lived storage.
1320 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1321 * extensions should always have keywords of the form "VENDOR.attribute"
1322 * In particular, it's quite feasible to support many different
1323 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1324 * unique to this library.
1326 * Investigate other vendor-specific extensions and see if
1327 * any of them look useful.
1330 pax_attribute(struct tar *tar, struct archive_entry *entry,
1331 wchar_t *key, wchar_t *value)
1338 /* GNU "0.0" sparse pax format. */
1339 if (wcscmp(key, L"GNU.sparse.numblocks") == 0) {
1340 tar->sparse_offset = -1;
1341 tar->sparse_numbytes = -1;
1342 tar->sparse_gnu_major = 0;
1343 tar->sparse_gnu_minor = 0;
1345 if (wcscmp(key, L"GNU.sparse.offset") == 0) {
1346 tar->sparse_offset = tar_atol10(value, wcslen(value));
1347 if (tar->sparse_numbytes != -1) {
1348 gnu_add_sparse_entry(tar,
1349 tar->sparse_offset, tar->sparse_numbytes);
1350 tar->sparse_offset = -1;
1351 tar->sparse_numbytes = -1;
1354 if (wcscmp(key, L"GNU.sparse.numbytes") == 0) {
1355 tar->sparse_numbytes = tar_atol10(value, wcslen(value));
1356 if (tar->sparse_numbytes != -1) {
1357 gnu_add_sparse_entry(tar,
1358 tar->sparse_offset, tar->sparse_numbytes);
1359 tar->sparse_offset = -1;
1360 tar->sparse_numbytes = -1;
1363 if (wcscmp(key, L"GNU.sparse.size") == 0) {
1364 tar->realsize = tar_atol10(value, wcslen(value));
1365 archive_entry_set_size(entry, tar->realsize);
1368 /* GNU "0.1" sparse pax format. */
1369 if (wcscmp(key, L"GNU.sparse.map") == 0) {
1370 tar->sparse_gnu_major = 0;
1371 tar->sparse_gnu_minor = 1;
1372 if (gnu_sparse_01_parse(tar, value) != ARCHIVE_OK)
1373 return (ARCHIVE_WARN);
1376 /* GNU "1.0" sparse pax format */
1377 if (wcscmp(key, L"GNU.sparse.major") == 0) {
1378 tar->sparse_gnu_major = tar_atol10(value, wcslen(value));
1379 tar->sparse_gnu_pending = 1;
1381 if (wcscmp(key, L"GNU.sparse.minor") == 0) {
1382 tar->sparse_gnu_minor = tar_atol10(value, wcslen(value));
1383 tar->sparse_gnu_pending = 1;
1385 if (wcscmp(key, L"GNU.sparse.name") == 0)
1386 archive_entry_copy_pathname_w(entry, value);
1387 if (wcscmp(key, L"GNU.sparse.realsize") == 0) {
1388 tar->realsize = tar_atol10(value, wcslen(value));
1389 archive_entry_set_size(entry, tar->realsize);
1393 /* Our extensions */
1394 /* TODO: Handle arbitrary extended attributes... */
1396 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1397 archive_entry_set_xxxxxx(entry, value);
1399 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1400 pax_attribute_xattr(entry, key, value);
1403 /* We support some keys used by the "star" archiver */
1404 if (wcscmp(key, L"SCHILY.acl.access")==0)
1405 __archive_entry_acl_parse_w(entry, value,
1406 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1407 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1408 __archive_entry_acl_parse_w(entry, value,
1409 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1410 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1411 archive_entry_set_rdevmajor(entry, tar_atol10(value, wcslen(value)));
1412 else if (wcscmp(key, L"SCHILY.devminor")==0)
1413 archive_entry_set_rdevminor(entry, tar_atol10(value, wcslen(value)));
1414 else if (wcscmp(key, L"SCHILY.fflags")==0)
1415 archive_entry_copy_fflags_text_w(entry, value);
1416 else if (wcscmp(key, L"SCHILY.dev")==0)
1417 archive_entry_set_dev(entry, tar_atol10(value, wcslen(value)));
1418 else if (wcscmp(key, L"SCHILY.ino")==0)
1419 archive_entry_set_ino(entry, tar_atol10(value, wcslen(value)));
1420 else if (wcscmp(key, L"SCHILY.nlink")==0)
1421 archive_entry_set_nlink(entry, tar_atol10(value, wcslen(value)));
1422 else if (wcscmp(key, L"SCHILY.realsize")==0) {
1423 tar->realsize = tar_atol10(value, wcslen(value));
1424 archive_entry_set_size(entry, tar->realsize);
1428 if (wcscmp(key, L"atime")==0) {
1429 pax_time(value, &s, &n);
1430 archive_entry_set_atime(entry, s, n);
1434 if (wcscmp(key, L"ctime")==0) {
1435 pax_time(value, &s, &n);
1436 archive_entry_set_ctime(entry, s, n);
1437 } else if (wcscmp(key, L"charset")==0) {
1438 /* TODO: Publish charset information in entry. */
1439 } else if (wcscmp(key, L"comment")==0) {
1440 /* TODO: Publish comment in entry. */
1444 if (wcscmp(key, L"gid")==0)
1445 archive_entry_set_gid(entry, tar_atol10(value, wcslen(value)));
1446 else if (wcscmp(key, L"gname")==0)
1447 archive_entry_copy_gname_w(entry, value);
1450 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1451 if (wcscmp(key, L"linkpath")==0) {
1452 if (archive_entry_hardlink(entry))
1453 archive_entry_copy_hardlink_w(entry, value);
1455 archive_entry_copy_symlink_w(entry, value);
1459 if (wcscmp(key, L"mtime")==0) {
1460 pax_time(value, &s, &n);
1461 archive_entry_set_mtime(entry, s, n);
1465 if (wcscmp(key, L"path")==0)
1466 archive_entry_copy_pathname_w(entry, value);
1469 /* POSIX has reserved 'realtime.*' */
1472 /* POSIX has reserved 'security.*' */
1473 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1474 if (wcscmp(key, L"size")==0) {
1475 /* "size" is the size of the data in the entry. */
1476 tar->entry_bytes_remaining
1477 = tar_atol10(value, wcslen(value));
1479 * But, "size" is not necessarily the size of
1480 * the file on disk; if this is a sparse file,
1481 * the disk size may have already been set from
1482 * GNU.sparse.realsize or GNU.sparse.size or
1483 * an old GNU header field or SCHILY.realsize
1486 if (tar->realsize < 0) {
1487 archive_entry_set_size(entry,
1488 tar->entry_bytes_remaining);
1490 = tar->entry_bytes_remaining;
1495 if (wcscmp(key, L"uid")==0)
1496 archive_entry_set_uid(entry, tar_atol10(value, wcslen(value)));
1497 else if (wcscmp(key, L"uname")==0)
1498 archive_entry_copy_uname_w(entry, value);
1507 * parse a decimal time value, which may include a fractional portion
1510 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1516 int64_t limit, last_digit_limit;
1518 limit = INT64_MAX / 10;
1519 last_digit_limit = INT64_MAX % 10;
1527 while (*p >= '0' && *p <= '9') {
1530 (s == limit && digit > last_digit_limit)) {
1534 s = (s * 10) + digit;
1540 /* Calculate nanoseconds. */
1549 if (*p >= '0' && *p <= '9')
1550 *pn += (*p - '0') * l;
1557 * Parse GNU tar header
1560 header_gnutar(struct archive_read *a, struct tar *tar,
1561 struct archive_entry *entry, const void *h)
1563 const struct archive_entry_header_gnutar *header;
1568 * GNU header is like POSIX ustar, except 'prefix' is
1569 * replaced with some other fields. This also means the
1570 * filename is stored as in old-style archives.
1573 /* Grab fields common to all tar variants. */
1574 header_common(a, tar, entry, h);
1576 /* Copy filename over (to ensure null termination). */
1577 header = (const struct archive_entry_header_gnutar *)h;
1578 archive_strncpy(&(tar->entry_name), header->name,
1579 sizeof(header->name));
1580 archive_entry_set_pathname(entry, tar->entry_name.s);
1582 /* Fields common to ustar and GNU */
1583 /* XXX Can the following be factored out since it's common
1584 * to ustar and gnu tar? Is it okay to move it down into
1585 * header_common, perhaps? */
1586 archive_strncpy(&(tar->entry_uname),
1587 header->uname, sizeof(header->uname));
1588 archive_entry_set_uname(entry, tar->entry_uname.s);
1590 archive_strncpy(&(tar->entry_gname),
1591 header->gname, sizeof(header->gname));
1592 archive_entry_set_gname(entry, tar->entry_gname.s);
1594 /* Parse out device numbers only for char and block specials */
1595 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1596 archive_entry_set_rdevmajor(entry,
1597 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1598 archive_entry_set_rdevminor(entry,
1599 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1601 archive_entry_set_rdev(entry, 0);
1603 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1605 /* Grab GNU-specific fields. */
1606 archive_entry_set_atime(entry,
1607 tar_atol(header->atime, sizeof(header->atime)), 0);
1608 archive_entry_set_ctime(entry,
1609 tar_atol(header->ctime, sizeof(header->ctime)), 0);
1610 if (header->realsize[0] != 0) {
1612 = tar_atol(header->realsize, sizeof(header->realsize));
1613 archive_entry_set_size(entry, tar->realsize);
1616 if (header->sparse[0].offset[0] != 0) {
1617 gnu_sparse_old_read(a, tar, header);
1619 if (header->isextended[0] != 0) {
1628 gnu_add_sparse_entry(struct tar *tar, off_t offset, off_t remaining)
1630 struct sparse_block *p;
1632 p = (struct sparse_block *)malloc(sizeof(*p));
1634 __archive_errx(1, "Out of memory");
1635 memset(p, 0, sizeof(*p));
1636 if (tar->sparse_last != NULL)
1637 tar->sparse_last->next = p;
1639 tar->sparse_list = p;
1640 tar->sparse_last = p;
1642 p->remaining = remaining;
1646 gnu_clear_sparse_list(struct tar *tar)
1648 struct sparse_block *p;
1650 while (tar->sparse_list != NULL) {
1651 p = tar->sparse_list;
1652 tar->sparse_list = p->next;
1655 tar->sparse_last = NULL;
1659 * GNU tar old-format sparse data.
1661 * GNU old-format sparse data is stored in a fixed-field
1662 * format. Offset/size values are 11-byte octal fields (same
1663 * format as 'size' field in ustart header). These are
1664 * stored in the header, allocating subsequent header blocks
1665 * as needed. Extending the header in this way is a pretty
1666 * severe POSIX violation; this design has earned GNU tar a
1671 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
1672 const struct archive_entry_header_gnutar *header)
1677 struct gnu_sparse sparse[21];
1681 const struct extended *ext;
1683 gnu_sparse_old_parse(tar, header->sparse, 4);
1684 if (header->isextended[0] == 0)
1685 return (ARCHIVE_OK);
1688 bytes_read = (a->decompressor->read_ahead)(a, &data, 512);
1690 return (ARCHIVE_FATAL);
1691 if (bytes_read < 512) {
1692 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1693 "Truncated tar archive "
1694 "detected while reading sparse file data");
1695 return (ARCHIVE_FATAL);
1697 (a->decompressor->consume)(a, 512);
1698 ext = (const struct extended *)data;
1699 gnu_sparse_old_parse(tar, ext->sparse, 21);
1700 } while (ext->isextended[0] != 0);
1701 if (tar->sparse_list != NULL)
1702 tar->entry_offset = tar->sparse_list->offset;
1703 return (ARCHIVE_OK);
1707 gnu_sparse_old_parse(struct tar *tar,
1708 const struct gnu_sparse *sparse, int length)
1710 while (length > 0 && sparse->offset[0] != 0) {
1711 gnu_add_sparse_entry(tar,
1712 tar_atol(sparse->offset, sizeof(sparse->offset)),
1713 tar_atol(sparse->numbytes, sizeof(sparse->numbytes)));
1720 * GNU tar sparse format 0.0
1722 * Beginning with GNU tar 1.15, sparse files are stored using
1723 * information in the pax extended header. The GNU tar maintainers
1724 * have gone through a number of variations in the process of working
1725 * out this scheme; furtunately, they're all numbered.
1727 * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
1728 * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
1729 * store offset/size for each block. The repeated instances of these
1730 * latter fields violate the pax specification (which frowns on
1731 * duplicate keys), so this format was quickly replaced.
1735 * GNU tar sparse format 0.1
1737 * This version replaced the offset/numbytes attributes with
1738 * a single "map" attribute that stored a list of integers. This
1739 * format had two problems: First, the "map" attribute could be very
1740 * long, which caused problems for some implementations. More
1741 * importantly, the sparse data was lost when extracted by archivers
1742 * that didn't recognize this extension.
1746 gnu_sparse_01_parse(struct tar *tar, const wchar_t *p)
1749 off_t offset = -1, size = -1;
1753 while (*e != '\0' && *e != ',') {
1754 if (*e < '0' || *e > '9')
1755 return (ARCHIVE_WARN);
1759 offset = tar_atol10(p, e - p);
1761 return (ARCHIVE_WARN);
1763 size = tar_atol10(p, e - p);
1765 return (ARCHIVE_WARN);
1766 gnu_add_sparse_entry(tar, offset, size);
1770 return (ARCHIVE_OK);
1776 * GNU tar sparse format 1.0
1778 * The idea: The offset/size data is stored as a series of base-10
1779 * ASCII numbers prepended to the file data, so that dearchivers that
1780 * don't support this format will extract the block map along with the
1781 * data and a separate post-process can restore the sparseness.
1783 * Unfortunately, GNU tar 1.16 adds bogus padding to the end of the
1784 * entry that depends on the size of the map; this means we have to
1785 * parse the sparse map when we read the header (otherwise, entry_skip
1786 * will fail). This is why sparse_10_read is called from read_header
1787 * above, instead of at the beginning of read_data, where it "should"
1790 * This variant also replaced GNU.sparse.size with GNU.sparse.realsize
1791 * and introduced the GNU.sparse.major/GNU.sparse.minor attributes.
1795 * Read the next line from the input, and parse it as a decimal
1796 * integer followed by '\n'. Returns positive integer value or
1797 * negative on error.
1800 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
1803 int64_t l, limit, last_digit_limit;
1809 limit = INT64_MAX / base;
1810 last_digit_limit = INT64_MAX % base;
1813 * Skip any lines starting with '#'; GNU tar specs
1814 * don't require this, but they should.
1817 bytes_read = readline(a, tar, &p, tar_min(*remaining, 100));
1818 if (bytes_read <= 0)
1819 return (ARCHIVE_FATAL);
1820 *remaining -= bytes_read;
1821 } while (p[0] == '#');
1824 while (bytes_read > 0) {
1827 if (*p < '0' || *p >= '0' + base)
1828 return (ARCHIVE_WARN);
1830 if (l > limit || (l == limit && digit > last_digit_limit))
1831 l = UINT64_MAX; /* Truncate on overflow. */
1833 l = (l * base) + digit;
1837 /* TODO: Error message. */
1838 return (ARCHIVE_WARN);
1842 * Returns length (in bytes) of the sparse data description
1846 gnu_sparse_10_read(struct archive_read *a, struct tar *tar)
1848 ssize_t remaining, bytes_read;
1850 off_t offset, size, to_skip;
1852 /* Clear out the existing sparse list. */
1853 gnu_clear_sparse_list(tar);
1855 remaining = tar->entry_bytes_remaining;
1857 /* Parse entries. */
1858 entries = gnu_sparse_10_atol(a, tar, &remaining);
1860 return (ARCHIVE_FATAL);
1861 /* Parse the individual entries. */
1862 while (entries-- > 0) {
1863 /* Parse offset/size */
1864 offset = gnu_sparse_10_atol(a, tar, &remaining);
1866 return (ARCHIVE_FATAL);
1867 size = gnu_sparse_10_atol(a, tar, &remaining);
1869 return (ARCHIVE_FATAL);
1870 /* Add a new sparse entry. */
1871 gnu_add_sparse_entry(tar, offset, size);
1873 /* Skip rest of block... */
1874 bytes_read = tar->entry_bytes_remaining - remaining;
1875 to_skip = 0x1ff & -bytes_read;
1876 if (to_skip != (a->decompressor->skip)(a, to_skip))
1877 return (ARCHIVE_FATAL);
1878 return (bytes_read + to_skip);
1882 * Convert text->integer.
1884 * Traditional tar formats (including POSIX) specify base-8 for
1885 * all of the standard numeric fields. This is a significant limitation
1887 * = file size is limited to 8GB
1888 * = rdevmajor and rdevminor are limited to 21 bits
1889 * = uid/gid are limited to 21 bits
1891 * There are two workarounds for this:
1892 * = pax extended headers, which use variable-length string fields
1893 * = GNU tar and STAR both allow either base-8 or base-256 in
1894 * most fields. The high bit is set to indicate base-256.
1896 * On read, this implementation supports both extensions.
1899 tar_atol(const char *p, unsigned char_cnt)
1902 * Technically, GNU tar considers a field to be in base-256
1903 * only if the first byte is 0xff or 0x80.
1906 return (tar_atol256(p, char_cnt));
1907 return (tar_atol8(p, char_cnt));
1911 * Note that this implementation does not (and should not!) obey
1912 * locale settings; you cannot simply substitute strtol here, since
1913 * it does obey locale.
1916 tar_atol8(const char *p, unsigned char_cnt)
1918 int64_t l, limit, last_digit_limit;
1919 int digit, sign, base;
1922 limit = INT64_MAX / base;
1923 last_digit_limit = INT64_MAX % base;
1925 while (*p == ' ' || *p == '\t')
1935 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1936 if (l>limit || (l == limit && digit > last_digit_limit)) {
1937 l = UINT64_MAX; /* Truncate on overflow. */
1940 l = (l * base) + digit;
1943 return (sign < 0) ? -l : l;
1947 * Note that this implementation does not (and should not!) obey
1948 * locale settings; you cannot simply substitute strtol here, since
1949 * it does obey locale.
1952 tar_atol10(const wchar_t *p, unsigned char_cnt)
1954 int64_t l, limit, last_digit_limit;
1955 int base, digit, sign;
1958 limit = INT64_MAX / base;
1959 last_digit_limit = INT64_MAX % base;
1961 while (*p == ' ' || *p == '\t')
1971 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1972 if (l > limit || (l == limit && digit > last_digit_limit)) {
1973 l = UINT64_MAX; /* Truncate on overflow. */
1976 l = (l * base) + digit;
1979 return (sign < 0) ? -l : l;
1983 * Parse a base-256 integer. This is just a straight signed binary
1984 * value in big-endian order, except that the high-order bit is
1985 * ignored. Remember that "int64_t" may or may not be exactly 64
1986 * bits; the implementation here tries to avoid making any assumptions
1987 * about the actual size of an int64_t. It does assume we're using
1988 * twos-complement arithmetic, though.
1991 tar_atol256(const char *_p, unsigned char_cnt)
1993 int64_t l, upper_limit, lower_limit;
1994 const unsigned char *p = (const unsigned char *)_p;
1996 upper_limit = INT64_MAX / 256;
1997 lower_limit = INT64_MIN / 256;
1999 /* Pad with 1 or 0 bits, depending on sign. */
2000 if ((0x40 & *p) == 0x40)
2004 l = (l << 6) | (0x3f & *p++);
2005 while (--char_cnt > 0) {
2006 if (l > upper_limit) {
2007 l = INT64_MAX; /* Truncate on overflow */
2009 } else if (l < lower_limit) {
2013 l = (l << 8) | (0xff & (int64_t)*p++);
2019 * Returns length of line (including trailing newline)
2020 * or negative on error. 'start' argument is updated to
2021 * point to first character of line. This avoids copying
2025 readline(struct archive_read *a, struct tar *tar, const char **start,
2029 ssize_t total_size = 0;
2034 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2035 if (bytes_read <= 0)
2036 return (ARCHIVE_FATAL);
2037 s = t; /* Start of line? */
2038 p = memchr(t, '\n', bytes_read);
2039 /* If we found '\n' in the read buffer, return pointer to that. */
2041 bytes_read = 1 + ((const char *)p) - s;
2042 if (bytes_read > limit) {
2043 archive_set_error(&a->archive,
2044 ARCHIVE_ERRNO_FILE_FORMAT,
2046 return (ARCHIVE_FATAL);
2048 (a->decompressor->consume)(a, bytes_read);
2050 return (bytes_read);
2052 /* Otherwise, we need to accumulate in a line buffer. */
2054 if (total_size + bytes_read > limit) {
2055 archive_set_error(&a->archive,
2056 ARCHIVE_ERRNO_FILE_FORMAT,
2058 return (ARCHIVE_FATAL);
2060 if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
2061 archive_set_error(&a->archive, ENOMEM,
2062 "Can't allocate working buffer");
2063 return (ARCHIVE_FATAL);
2065 memcpy(tar->line.s + total_size, t, bytes_read);
2066 (a->decompressor->consume)(a, bytes_read);
2067 total_size += bytes_read;
2068 /* If we found '\n', clean up and return. */
2070 *start = tar->line.s;
2071 return (total_size);
2073 /* Read some more. */
2074 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2075 if (bytes_read <= 0)
2076 return (ARCHIVE_FATAL);
2077 s = t; /* Start of line? */
2078 p = memchr(t, '\n', bytes_read);
2079 /* If we found '\n', trim the read. */
2081 bytes_read = 1 + ((const char *)p) - s;
2087 utf8_decode(wchar_t *dest, const char *src, size_t length)
2093 while (length > 0) {
2094 n = UTF8_mbrtowc(dest, src, length);
2106 * Copied and simplified from FreeBSD libc/locale.
2109 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
2111 int ch, i, len, mask;
2114 if (s == NULL || n == 0 || pwc == NULL)
2118 * Determine the number of octets that make up this character from
2119 * the first octet, and a mask that extracts the interesting bits of
2122 ch = (unsigned char)*s;
2123 if ((ch & 0x80) == 0) {
2126 } else if ((ch & 0xe0) == 0xc0) {
2129 } else if ((ch & 0xf0) == 0xe0) {
2132 } else if ((ch & 0xf8) == 0xf0) {
2135 } else if ((ch & 0xfc) == 0xf8) {
2138 } else if ((ch & 0xfe) == 0xfc) {
2142 /* Invalid first byte; convert to '?' */
2147 if (n < (size_t)len) {
2148 /* Invalid first byte; convert to '?' */
2154 * Decode the octet sequence representing the character in chunks
2155 * of 6 bits, most significant first.
2157 wch = (unsigned char)*s++ & mask;
2160 if ((*s & 0xc0) != 0x80) {
2161 /* Invalid intermediate byte; consume one byte and
2170 /* Assign the value to the output; out-of-range values
2171 * just get truncated. */
2172 *pwc = (wchar_t)wch;
2175 * If platform has WCHAR_MAX, we can do something
2176 * more sensible with out-of-range values.
2178 if (wch >= WCHAR_MAX)
2181 /* Return number of bytes input consumed: 0 for end-of-string. */
2182 return (wch == L'\0' ? 0 : len);
2187 * base64_decode - Base64 decode
2189 * This accepts most variations of base-64 encoding, including:
2190 * * with or without line breaks
2191 * * with or without the final group padded with '=' or '_' characters
2192 * (The most economical Base-64 variant does not pad the last group and
2193 * omits line breaks; RFC1341 used for MIME requires both.)
2196 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
2198 static const unsigned char digits[64] = {
2199 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
2200 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
2201 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
2202 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
2203 '4','5','6','7','8','9','+','/' };
2204 static unsigned char decode_table[128];
2207 /* If the decode table is not yet initialized, prepare it. */
2208 if (decode_table[digits[1]] != 1) {
2210 memset(decode_table, 0xff, sizeof(decode_table));
2211 for (i = 0; i < sizeof(digits); i++)
2212 decode_table[digits[i]] = i;
2215 /* Allocate enough space to hold the entire output. */
2216 /* Note that we may not use all of this... */
2217 out = (char *)malloc((len * 3 + 3) / 4);
2225 /* Collect the next group of (up to) four characters. */
2228 while (group_size < 4 && len > 0) {
2229 /* '=' or '_' padding indicates final group. */
2230 if (*src == '=' || *src == '_') {
2234 /* Skip illegal characters (including line breaks) */
2235 if (*src > 127 || *src < 32
2236 || decode_table[*src] == 0xff) {
2242 v |= decode_table[*src++];
2246 /* Align a short group properly. */
2247 v <<= 6 * (4 - group_size);
2248 /* Unpack the group we just collected. */
2249 switch (group_size) {
2250 case 4: d[2] = v & 0xff;
2252 case 3: d[1] = (v >> 8) & 0xff;
2254 case 2: d[0] = (v >> 16) & 0xff;
2256 case 1: /* this is invalid! */
2259 d += group_size * 3 / 4;
2267 * This is a little tricky because the C99 standard wcstombs()
2268 * function returns the number of bytes that were converted,
2269 * not the number that should be converted. As a result,
2270 * we can never accurately size the output buffer (without
2271 * doing a tedious output size calculation in advance).
2272 * This approach (try a conversion, then try again if it fails)
2273 * will almost always succeed on the first try, and is thus
2274 * much faster, at the cost of sometimes requiring multiple
2275 * passes while we expand the buffer.
2278 wide_to_narrow(const wchar_t *wval)
2280 int converted_length;
2281 /* Guess an output buffer size and try the conversion. */
2282 int alloc_length = wcslen(wval) * 3;
2283 char *mbs_val = (char *)malloc(alloc_length + 1);
2284 if (mbs_val == NULL)
2286 converted_length = wcstombs(mbs_val, wval, alloc_length);
2288 /* If we exhausted the buffer, resize and try again. */
2289 while (converted_length >= alloc_length) {
2292 mbs_val = (char *)malloc(alloc_length + 1);
2293 if (mbs_val == NULL)
2295 converted_length = wcstombs(mbs_val, wval, alloc_length);
2298 /* Ensure a trailing null and return the final string. */
2299 mbs_val[alloc_length] = '\0';
2304 url_decode(const char *in)
2309 out = (char *)malloc(strlen(in) + 1);
2312 for (s = in, d = out; *s != '\0'; ) {
2314 /* Try to convert % escape */
2315 int digit1 = tohex(s[1]);
2316 int digit2 = tohex(s[2]);
2317 if (digit1 >= 0 && digit2 >= 0) {
2318 /* Looks good, consume three chars */
2320 /* Convert output */
2321 *d++ = ((digit1 << 4) | digit2);
2324 /* Else fall through and treat '%' as normal char */
2335 if (c >= '0' && c <= '9')
2337 else if (c >= 'A' && c <= 'F')
2338 return (c - 'A' + 10);
2339 else if (c >= 'a' && c <= 'f')
2340 return (c - 'a' + 10);