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.61 2007/08/18 21:53:25 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 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
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 free(tar->pax_entry);
283 (a->format->data) = NULL;
289 archive_read_format_tar_bid(struct archive_read *a)
294 const struct archive_entry_header_ustar *header;
297 * If we're already reading a non-tar file, don't
300 if (a->archive.archive_format != 0 &&
301 (a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
307 * If we're already reading a tar format, start the bid at 1 as
310 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
314 /* Now let's look at the actual header and see if it matches. */
315 if (a->decompressor->read_ahead != NULL)
316 bytes_read = (a->decompressor->read_ahead)(a, &h, 512);
318 bytes_read = 0; /* Empty file. */
320 return (ARCHIVE_FATAL);
321 if (bytes_read == 0 && bid > 0) {
322 /* An archive without a proper end-of-archive marker. */
323 /* Hold our nose and bid 1 anyway. */
326 if (bytes_read < 512) {
327 /* If it's a new archive, then just return a zero bid. */
331 * If we already know this is a tar archive,
332 * then we have a problem.
334 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
335 "Truncated tar archive");
336 return (ARCHIVE_FATAL);
339 /* If it's an end-of-archive mark, we can handle it. */
340 if ((*(const char *)h) == 0 && archive_block_is_null((const unsigned char *)h)) {
341 /* If it's a known tar file, end-of-archive is definite. */
342 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
349 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
352 bid += 48; /* Checksum is usually 6 octal digits. */
354 header = (const struct archive_entry_header_ustar *)h;
356 /* Recognize POSIX formats. */
357 if ((memcmp(header->magic, "ustar\0", 6) == 0)
358 &&(memcmp(header->version, "00", 2)==0))
361 /* Recognize GNU tar format. */
362 if ((memcmp(header->magic, "ustar ", 6) == 0)
363 &&(memcmp(header->version, " \0", 2)==0))
366 /* Type flag must be null, digit or A-Z, a-z. */
367 if (header->typeflag[0] != 0 &&
368 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
369 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
370 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
372 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
374 /* Sanity check: Look at first byte of mode field. */
375 switch (255 & (unsigned)header->mode[0]) {
377 /* Base-256 value: No further verification possible! */
379 case ' ': /* Not recommended, but not illegal, either. */
381 case '0': case '1': case '2': case '3':
382 case '4': case '5': case '6': case '7':
384 /* TODO: Check format of remainder of this field. */
387 /* Not a valid mode; bail out here. */
390 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
396 * The function invoked by archive_read_header(). This
397 * just sets up a few things and then calls the internal
398 * tar_read_header() function below.
401 archive_read_format_tar_read_header(struct archive_read *a,
402 struct archive_entry *entry)
405 * When converting tar archives to cpio archives, it is
406 * essential that each distinct file have a distinct inode
407 * number. To simplify this, we keep a static count here to
408 * assign fake dev/inode numbers to each tar entry. Note that
409 * pax format archives may overwrite this with something more
412 * Ideally, we would track every file read from the archive so
413 * that we could assign the same dev/ino pair to hardlinks,
414 * but the memory required to store a complete lookup table is
415 * probably not worthwhile just to support the relatively
416 * obscure tar->cpio conversion case.
418 static int default_inode;
419 static int default_dev;
421 struct sparse_block *sp;
426 /* Assign default device/inode values. */
427 archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
428 archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
429 /* Limit generated st_ino number to 16 bits. */
430 if (default_inode >= 0xffff) {
435 tar = (struct tar *)(a->format->data);
436 tar->entry_offset = 0;
437 while (tar->sparse_list != NULL) {
438 sp = tar->sparse_list;
439 tar->sparse_list = sp->next;
442 tar->sparse_last = NULL;
444 r = tar_read_header(a, tar, entry);
447 * "non-sparse" files are really just sparse files with
450 if (tar->sparse_list == NULL)
451 gnu_add_sparse_entry(tar, 0, tar->entry_bytes_remaining);
453 tar->realsize = archive_entry_size(entry);
455 if (r == ARCHIVE_OK) {
457 * "Regular" entry with trailing '/' is really
458 * directory: This is needed for certain old tar
459 * variants and even for some broken newer ones.
461 p = archive_entry_pathname(entry);
463 if (archive_entry_filetype(entry) == AE_IFREG
465 archive_entry_set_filetype(entry, AE_IFDIR);
471 archive_read_format_tar_read_data(struct archive_read *a,
472 const void **buff, size_t *size, off_t *offset)
476 struct sparse_block *p;
478 tar = (struct tar *)(a->format->data);
480 if (tar->sparse_gnu_pending) {
481 if (tar->sparse_gnu_major == 1 && tar->sparse_gnu_minor == 0) {
482 tar->sparse_gnu_pending = 0;
483 /* Read initial sparse map. */
484 bytes_read = gnu_sparse_10_read(a, tar);
485 tar->entry_bytes_remaining -= bytes_read;
491 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
492 "Unrecognized GNU sparse file format");
493 return (ARCHIVE_WARN);
495 tar->sparse_gnu_pending = 0;
498 /* Remove exhausted entries from sparse list. */
499 while (tar->sparse_list != NULL &&
500 tar->sparse_list->remaining == 0) {
501 p = tar->sparse_list;
502 tar->sparse_list = p->next;
506 /* If we're at end of file, return EOF. */
507 if (tar->sparse_list == NULL || tar->entry_bytes_remaining == 0) {
508 if ((a->decompressor->skip)(a, tar->entry_padding) < 0)
509 return (ARCHIVE_FATAL);
510 tar->entry_padding = 0;
513 *offset = tar->realsize;
514 return (ARCHIVE_EOF);
517 bytes_read = (a->decompressor->read_ahead)(a, buff, 1);
518 if (bytes_read == 0) {
519 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
520 "Truncated tar archive");
521 return (ARCHIVE_FATAL);
524 return (ARCHIVE_FATAL);
525 if (bytes_read > tar->entry_bytes_remaining)
526 bytes_read = tar->entry_bytes_remaining;
527 /* Don't read more than is available in the
528 * current sparse block. */
529 if (tar->sparse_list->remaining < bytes_read)
530 bytes_read = tar->sparse_list->remaining;
532 *offset = tar->sparse_list->offset;
533 tar->sparse_list->remaining -= bytes_read;
534 tar->sparse_list->offset += bytes_read;
535 tar->entry_bytes_remaining -= bytes_read;
536 (a->decompressor->consume)(a, bytes_read);
541 archive_read_format_tar_skip(struct archive_read *a)
546 tar = (struct tar *)(a->format->data);
549 * Compression layer skip functions are required to either skip the
550 * length requested or fail, so we can rely upon the entire entry
551 * plus padding being skipped.
553 bytes_skipped = (a->decompressor->skip)(a, tar->entry_bytes_remaining +
555 if (bytes_skipped < 0)
556 return (ARCHIVE_FATAL);
558 tar->entry_bytes_remaining = 0;
559 tar->entry_padding = 0;
561 /* Free the sparse list. */
562 gnu_clear_sparse_list(tar);
568 * This function recursively interprets all of the headers associated
569 * with a single entry.
572 tar_read_header(struct archive_read *a, struct tar *tar,
573 struct archive_entry *entry)
578 const struct archive_entry_header_ustar *header;
580 /* Read 512-byte header record */
581 bytes = (a->decompressor->read_ahead)(a, &h, 512);
584 * If we're here, it's becase the _bid function accepted
585 * this file. So just call a short read end-of-archive
586 * and be done with it.
588 return (ARCHIVE_EOF);
590 (a->decompressor->consume)(a, 512);
592 /* Check for end-of-archive mark. */
593 if (((*(const char *)h)==0) && archive_block_is_null((const unsigned char *)h)) {
594 /* Try to consume a second all-null record, as well. */
595 bytes = (a->decompressor->read_ahead)(a, &h, 512);
597 (a->decompressor->consume)(a, bytes);
598 archive_set_error(&a->archive, 0, NULL);
599 return (ARCHIVE_EOF);
603 * Note: If the checksum fails and we return ARCHIVE_RETRY,
604 * then the client is likely to just retry. This is a very
605 * crude way to search for the next valid header!
607 * TODO: Improve this by implementing a real header scan.
609 if (!checksum(a, h)) {
610 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
611 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
614 if (++tar->header_recursion_depth > 32) {
615 archive_set_error(&a->archive, EINVAL, "Too many special headers");
616 return (ARCHIVE_WARN);
619 /* Determine the format variant. */
620 header = (const struct archive_entry_header_ustar *)h;
621 switch(header->typeflag[0]) {
622 case 'A': /* Solaris tar ACL */
623 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
624 a->archive.archive_format_name = "Solaris tar";
625 err = header_Solaris_ACL(a, tar, entry, h);
627 case 'g': /* POSIX-standard 'g' header. */
628 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
629 a->archive.archive_format_name = "POSIX pax interchange format";
630 err = header_pax_global(a, tar, entry, h);
632 case 'K': /* Long link name (GNU tar, others) */
633 err = header_longlink(a, tar, entry, h);
635 case 'L': /* Long filename (GNU tar, others) */
636 err = header_longname(a, tar, entry, h);
638 case 'V': /* GNU volume header */
639 err = header_volume(a, tar, entry, h);
641 case 'X': /* Used by SUN tar; same as 'x'. */
642 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
643 a->archive.archive_format_name =
644 "POSIX pax interchange format (Sun variant)";
645 err = header_pax_extensions(a, tar, entry, h);
647 case 'x': /* POSIX-standard 'x' header. */
648 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
649 a->archive.archive_format_name = "POSIX pax interchange format";
650 err = header_pax_extensions(a, tar, entry, h);
653 if (memcmp(header->magic, "ustar \0", 8) == 0) {
654 a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
655 a->archive.archive_format_name = "GNU tar format";
656 err = header_gnutar(a, tar, entry, h);
657 } else if (memcmp(header->magic, "ustar", 5) == 0) {
658 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
659 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
660 a->archive.archive_format_name = "POSIX ustar format";
662 err = header_ustar(a, tar, entry, h);
664 a->archive.archive_format = ARCHIVE_FORMAT_TAR;
665 a->archive.archive_format_name = "tar (non-POSIX)";
666 err = header_old_tar(a, tar, entry, h);
669 --tar->header_recursion_depth;
670 /* We return warnings or success as-is. Anything else is fatal. */
671 if (err == ARCHIVE_WARN || err == ARCHIVE_OK)
673 if (err == ARCHIVE_EOF)
674 /* EOF when recursively reading a header is bad. */
675 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
676 return (ARCHIVE_FATAL);
680 * Return true if block checksum is correct.
683 checksum(struct archive_read *a, const void *h)
685 const unsigned char *bytes;
686 const struct archive_entry_header_ustar *header;
689 (void)a; /* UNUSED */
690 bytes = (const unsigned char *)h;
691 header = (const struct archive_entry_header_ustar *)h;
694 * Test the checksum. Note that POSIX specifies _unsigned_
695 * bytes for this calculation.
697 sum = tar_atol(header->checksum, sizeof(header->checksum));
699 for (i = 0; i < 148; i++)
700 check += (unsigned char)bytes[i];
704 check += (unsigned char)bytes[i];
709 * Repeat test with _signed_ bytes, just in case this archive
710 * was created by an old BSD, Solaris, or HP-UX tar with a
711 * broken checksum calculation.
714 for (i = 0; i < 148; i++)
715 check += (signed char)bytes[i];
719 check += (signed char)bytes[i];
727 * Return true if this block contains only nulls.
730 archive_block_is_null(const unsigned char *p)
734 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
741 * Interpret 'A' Solaris ACL header
744 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
745 struct archive_entry *entry, const void *h)
747 const struct archive_entry_header_ustar *header;
754 * read_body_to_string adds a NUL terminator, but we need a little
755 * more to make sure that we don't overrun acl_text later.
757 header = (const struct archive_entry_header_ustar *)h;
758 size = tar_atol(header->size, sizeof(header->size));
759 err = read_body_to_string(a, tar, &(tar->acl_text), h);
760 if (err != ARCHIVE_OK)
762 err = tar_read_header(a, tar, entry);
763 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
766 /* Skip leading octal number. */
767 /* XXX TODO: Parse the octal number and sanity-check it. */
768 p = acl = tar->acl_text.s;
769 while (*p != '\0' && p < acl + size)
773 if (p >= acl + size) {
774 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
775 "Malformed Solaris ACL attribute");
776 return(ARCHIVE_WARN);
779 /* Skip leading octal number. */
783 while (*p != '\0' && p < acl + size)
786 wp = (wchar_t *)malloc((p - acl + 1) * sizeof(wchar_t));
788 archive_set_error(&a->archive, ENOMEM,
789 "Can't allocate work buffer for ACL parsing");
790 return (ARCHIVE_FATAL);
792 utf8_decode(wp, acl, p - acl);
793 err = __archive_entry_acl_parse_w(entry, wp,
794 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
800 * Interpret 'K' long linkname header.
803 header_longlink(struct archive_read *a, struct tar *tar,
804 struct archive_entry *entry, const void *h)
808 err = read_body_to_string(a, tar, &(tar->longlink), h);
809 if (err != ARCHIVE_OK)
811 err = tar_read_header(a, tar, entry);
812 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
814 /* Set symlink if symlink already set, else hardlink. */
815 archive_entry_set_link(entry, tar->longlink.s);
820 * Interpret 'L' long filename header.
823 header_longname(struct archive_read *a, struct tar *tar,
824 struct archive_entry *entry, const void *h)
828 err = read_body_to_string(a, tar, &(tar->longname), h);
829 if (err != ARCHIVE_OK)
831 /* Read and parse "real" header, then override name. */
832 err = tar_read_header(a, tar, entry);
833 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
835 archive_entry_set_pathname(entry, tar->longname.s);
841 * Interpret 'V' GNU tar volume header.
844 header_volume(struct archive_read *a, struct tar *tar,
845 struct archive_entry *entry, const void *h)
849 /* Just skip this and read the next header. */
850 return (tar_read_header(a, tar, entry));
854 * Read body of an archive entry into an archive_string object.
857 read_body_to_string(struct archive_read *a, struct tar *tar,
858 struct archive_string *as, const void *h)
860 off_t size, padded_size;
861 ssize_t bytes_read, bytes_to_copy;
862 const struct archive_entry_header_ustar *header;
866 (void)tar; /* UNUSED */
867 header = (const struct archive_entry_header_ustar *)h;
868 size = tar_atol(header->size, sizeof(header->size));
869 if ((size > 1048576) || (size < 0)) {
870 archive_set_error(&a->archive, EINVAL,
871 "Special header too large");
872 return (ARCHIVE_FATAL);
875 /* Fail if we can't make our buffer big enough. */
876 if (archive_string_ensure(as, size+1) == NULL) {
877 archive_set_error(&a->archive, ENOMEM,
879 return (ARCHIVE_FATAL);
882 /* Read the body into the string. */
883 padded_size = (size + 511) & ~ 511;
885 while (padded_size > 0) {
886 bytes_read = (a->decompressor->read_ahead)(a, &src, padded_size);
888 return (ARCHIVE_EOF);
890 return (ARCHIVE_FATAL);
891 if (bytes_read > padded_size)
892 bytes_read = padded_size;
893 (a->decompressor->consume)(a, bytes_read);
894 bytes_to_copy = bytes_read;
895 if ((off_t)bytes_to_copy > size)
896 bytes_to_copy = (ssize_t)size;
897 memcpy(dest, src, bytes_to_copy);
898 dest += bytes_to_copy;
899 size -= bytes_to_copy;
900 padded_size -= bytes_read;
907 * Parse out common header elements.
909 * This would be the same as header_old_tar, except that the
910 * filename is handled slightly differently for old and POSIX
911 * entries (POSIX entries support a 'prefix'). This factoring
912 * allows header_old_tar and header_ustar
913 * to handle filenames differently, while still putting most of the
914 * common parsing into one place.
917 header_common(struct archive_read *a, struct tar *tar,
918 struct archive_entry *entry, const void *h)
920 const struct archive_entry_header_ustar *header;
923 (void)a; /* UNUSED */
925 header = (const struct archive_entry_header_ustar *)h;
926 if (header->linkname[0])
927 archive_strncpy(&(tar->entry_linkname), header->linkname,
928 sizeof(header->linkname));
930 archive_string_empty(&(tar->entry_linkname));
932 /* Parse out the numeric fields (all are octal) */
933 archive_entry_set_mode(entry, tar_atol(header->mode, sizeof(header->mode)));
934 archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
935 archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
936 tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size));
937 archive_entry_set_size(entry, tar->entry_bytes_remaining);
938 archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
940 /* Handle the tar type flag appropriately. */
941 tartype = header->typeflag[0];
944 case '1': /* Hard link */
945 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
947 * The following may seem odd, but: Technically, tar
948 * does not store the file type for a "hard link"
949 * entry, only the fact that it is a hard link. So, I
950 * leave the type zero normally. But, pax interchange
951 * format allows hard links to have data, which
952 * implies that the underlying entry is a regular
955 if (archive_entry_size(entry) > 0)
956 archive_entry_set_filetype(entry, AE_IFREG);
959 * A tricky point: Traditionally, tar readers have
960 * ignored the size field when reading hardlink
961 * entries, and some writers put non-zero sizes even
962 * though the body is empty. POSIX.1-2001 broke with
963 * this tradition by permitting hardlink entries to
964 * store valid bodies in pax interchange format, but
965 * not in ustar format. Since there is no hard and
966 * fast way to distinguish pax interchange from
967 * earlier archives (the 'x' and 'g' entries are
968 * optional, after all), we need a heuristic. Here, I
969 * use the bid function to test whether or not there's
970 * a valid header following. Of course, if we know
971 * this is pax interchange format, then we must obey
974 * This heuristic will only fail for a pax interchange
975 * archive that is storing hardlink bodies, no pax
976 * extended attribute entries have yet occurred, and
977 * we encounter a hardlink entry for a file that is
978 * itself an uncompressed tar archive.
980 if (archive_entry_size(entry) > 0 &&
981 a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
982 archive_read_format_tar_bid(a) > 50) {
983 archive_entry_set_size(entry, 0);
984 tar->entry_bytes_remaining = 0;
987 case '2': /* Symlink */
988 archive_entry_set_filetype(entry, AE_IFLNK);
989 archive_entry_set_size(entry, 0);
990 tar->entry_bytes_remaining = 0;
991 archive_entry_set_symlink(entry, tar->entry_linkname.s);
993 case '3': /* Character device */
994 archive_entry_set_filetype(entry, AE_IFCHR);
995 archive_entry_set_size(entry, 0);
996 tar->entry_bytes_remaining = 0;
998 case '4': /* Block device */
999 archive_entry_set_filetype(entry, AE_IFBLK);
1000 archive_entry_set_size(entry, 0);
1001 tar->entry_bytes_remaining = 0;
1004 archive_entry_set_filetype(entry, AE_IFDIR);
1005 archive_entry_set_size(entry, 0);
1006 tar->entry_bytes_remaining = 0;
1008 case '6': /* FIFO device */
1009 archive_entry_set_filetype(entry, AE_IFIFO);
1010 archive_entry_set_size(entry, 0);
1011 tar->entry_bytes_remaining = 0;
1013 case 'D': /* GNU incremental directory type */
1015 * No special handling is actually required here.
1016 * It might be nice someday to preprocess the file list and
1017 * provide it to the client, though.
1019 archive_entry_set_filetype(entry, AE_IFDIR);
1021 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1023 * As far as I can tell, this is just like a regular file
1024 * entry, except that the contents should be _appended_ to
1025 * the indicated file at the indicated offset. This may
1026 * require some API work to fully support.
1029 case 'N': /* Old GNU "long filename" entry. */
1030 /* The body of this entry is a script for renaming
1031 * previously-extracted entries. Ugh. It will never
1032 * be supported by libarchive. */
1033 archive_entry_set_filetype(entry, AE_IFREG);
1035 case 'S': /* GNU sparse files */
1037 * Sparse files are really just regular files with
1038 * sparse information in the extended area.
1041 default: /* Regular file and non-standard types */
1043 * Per POSIX: non-recognized types should always be
1044 * treated as regular files.
1046 archive_entry_set_filetype(entry, AE_IFREG);
1053 * Parse out header elements for "old-style" tar archives.
1056 header_old_tar(struct archive_read *a, struct tar *tar,
1057 struct archive_entry *entry, const void *h)
1059 const struct archive_entry_header_ustar *header;
1061 /* Copy filename over (to ensure null termination). */
1062 header = (const struct archive_entry_header_ustar *)h;
1063 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1064 archive_entry_set_pathname(entry, tar->entry_name.s);
1066 /* Grab rest of common fields */
1067 header_common(a, tar, entry, h);
1069 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1074 * Parse a file header for a pax extended archive entry.
1077 header_pax_global(struct archive_read *a, struct tar *tar,
1078 struct archive_entry *entry, const void *h)
1082 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1083 if (err != ARCHIVE_OK)
1085 err = tar_read_header(a, tar, entry);
1090 header_pax_extensions(struct archive_read *a, struct tar *tar,
1091 struct archive_entry *entry, const void *h)
1095 err = read_body_to_string(a, tar, &(tar->pax_header), h);
1096 if (err != ARCHIVE_OK)
1099 /* Parse the next header. */
1100 err = tar_read_header(a, tar, entry);
1101 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1105 * TODO: Parse global/default options into 'entry' struct here
1106 * before handling file-specific options.
1108 * This design (parse standard header, then overwrite with pax
1109 * extended attribute data) usually works well, but isn't ideal;
1110 * it would be better to parse the pax extended attributes first
1111 * and then skip any fields in the standard header that were
1112 * defined in the pax header.
1114 err2 = pax_header(a, tar, entry, tar->pax_header.s);
1115 err = err_combine(err, err2);
1116 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1122 * Parse a file header for a Posix "ustar" archive entry. This also
1123 * handles "pax" or "extended ustar" entries.
1126 header_ustar(struct archive_read *a, struct tar *tar,
1127 struct archive_entry *entry, const void *h)
1129 const struct archive_entry_header_ustar *header;
1130 struct archive_string *as;
1132 header = (const struct archive_entry_header_ustar *)h;
1134 /* Copy name into an internal buffer to ensure null-termination. */
1135 as = &(tar->entry_name);
1136 if (header->prefix[0]) {
1137 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1138 if (as->s[archive_strlen(as) - 1] != '/')
1139 archive_strappend_char(as, '/');
1140 archive_strncat(as, header->name, sizeof(header->name));
1142 archive_strncpy(as, header->name, sizeof(header->name));
1144 archive_entry_set_pathname(entry, as->s);
1146 /* Handle rest of common fields. */
1147 header_common(a, tar, entry, h);
1149 /* Handle POSIX ustar fields. */
1150 archive_strncpy(&(tar->entry_uname), header->uname,
1151 sizeof(header->uname));
1152 archive_entry_set_uname(entry, tar->entry_uname.s);
1154 archive_strncpy(&(tar->entry_gname), header->gname,
1155 sizeof(header->gname));
1156 archive_entry_set_gname(entry, tar->entry_gname.s);
1158 /* Parse out device numbers only for char and block specials. */
1159 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1160 archive_entry_set_rdevmajor(entry,
1161 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1162 archive_entry_set_rdevminor(entry,
1163 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1166 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1173 * Parse the pax extended attributes record.
1175 * Returns non-zero if there's an error in the data.
1178 pax_header(struct archive_read *a, struct tar *tar,
1179 struct archive_entry *entry, char *attr)
1181 size_t attr_length, l, line_length;
1183 wchar_t *key, *wp, *value;
1186 attr_length = strlen(attr);
1188 while (attr_length > 0) {
1189 /* Parse decimal length field at start of line. */
1192 line = p = attr; /* Record start of line. */
1199 if (*p < '0' || *p > '9') {
1200 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1201 "Ignoring malformed pax extended attributes");
1202 return (ARCHIVE_WARN);
1205 line_length += *p - '0';
1206 if (line_length > 999999) {
1207 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1208 "Rejecting pax extended attribute > 1MB");
1209 return (ARCHIVE_WARN);
1216 * Parsed length must be no bigger than available data,
1217 * at least 1, and the last character of the line must
1220 if (line_length > attr_length
1222 || attr[line_length - 1] != '\n')
1224 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1225 "Ignoring malformed pax extended attribute");
1226 return (ARCHIVE_WARN);
1229 /* Ensure pax_entry buffer is big enough. */
1230 if (tar->pax_entry_length <= line_length) {
1231 wchar_t *old_entry = tar->pax_entry;
1233 if (tar->pax_entry_length <= 0)
1234 tar->pax_entry_length = 1024;
1235 while (tar->pax_entry_length <= line_length + 1)
1236 tar->pax_entry_length *= 2;
1238 old_entry = tar->pax_entry;
1239 tar->pax_entry = (wchar_t *)realloc(tar->pax_entry,
1240 tar->pax_entry_length * sizeof(wchar_t));
1241 if (tar->pax_entry == NULL) {
1243 archive_set_error(&a->archive, ENOMEM,
1245 return (ARCHIVE_FATAL);
1249 /* Decode UTF-8 to wchar_t, null-terminate result. */
1250 if (utf8_decode(tar->pax_entry, p,
1251 line_length - (p - attr) - 1)) {
1252 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1253 "Invalid UTF8 character in pax extended attribute");
1254 err = err_combine(err, ARCHIVE_WARN);
1257 /* Null-terminate 'key' value. */
1258 wp = key = tar->pax_entry;
1261 while (*wp && *wp != L'=')
1264 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1265 "Invalid pax extended attributes");
1266 return (ARCHIVE_WARN);
1270 /* Identify null-terminated 'value' portion. */
1273 /* Identify this attribute and set it in the entry. */
1274 err2 = pax_attribute(tar, entry, key, value);
1275 err = err_combine(err, err2);
1277 /* Skip to next line */
1278 attr += line_length;
1279 attr_length -= line_length;
1285 pax_attribute_xattr(struct archive_entry *entry,
1286 wchar_t *name, wchar_t *value)
1288 char *name_decoded, *name_narrow;
1289 void *value_decoded;
1292 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1297 /* URL-decode name */
1298 name_narrow = wide_to_narrow(name);
1299 if (name_narrow == NULL)
1301 name_decoded = url_decode(name_narrow);
1303 if (name_decoded == NULL)
1306 /* Base-64 decode value */
1307 value_decoded = base64_decode(value, wcslen(value), &value_len);
1308 if (value_decoded == NULL) {
1313 archive_entry_xattr_add_entry(entry, name_decoded,
1314 value_decoded, value_len);
1317 free(value_decoded);
1322 * Parse a single key=value attribute. key/value pointers are
1323 * assumed to point into reasonably long-lived storage.
1325 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1326 * extensions should always have keywords of the form "VENDOR.attribute"
1327 * In particular, it's quite feasible to support many different
1328 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1329 * unique to this library.
1331 * Investigate other vendor-specific extensions and see if
1332 * any of them look useful.
1335 pax_attribute(struct tar *tar, struct archive_entry *entry,
1336 wchar_t *key, wchar_t *value)
1343 /* GNU "0.0" sparse pax format. */
1344 if (wcscmp(key, L"GNU.sparse.numblocks") == 0) {
1345 tar->sparse_offset = -1;
1346 tar->sparse_numbytes = -1;
1347 tar->sparse_gnu_major = 0;
1348 tar->sparse_gnu_minor = 0;
1350 if (wcscmp(key, L"GNU.sparse.offset") == 0) {
1351 tar->sparse_offset = tar_atol10(value, wcslen(value));
1352 if (tar->sparse_numbytes != -1) {
1353 gnu_add_sparse_entry(tar,
1354 tar->sparse_offset, tar->sparse_numbytes);
1355 tar->sparse_offset = -1;
1356 tar->sparse_numbytes = -1;
1359 if (wcscmp(key, L"GNU.sparse.numbytes") == 0) {
1360 tar->sparse_numbytes = tar_atol10(value, wcslen(value));
1361 if (tar->sparse_numbytes != -1) {
1362 gnu_add_sparse_entry(tar,
1363 tar->sparse_offset, tar->sparse_numbytes);
1364 tar->sparse_offset = -1;
1365 tar->sparse_numbytes = -1;
1368 if (wcscmp(key, L"GNU.sparse.size") == 0)
1369 archive_entry_set_size(entry,
1370 tar_atol10(value, wcslen(value)));
1372 /* GNU "0.1" sparse pax format. */
1373 if (wcscmp(key, L"GNU.sparse.map") == 0) {
1374 tar->sparse_gnu_major = 0;
1375 tar->sparse_gnu_minor = 1;
1376 if (gnu_sparse_01_parse(tar, value) != ARCHIVE_OK)
1377 return (ARCHIVE_WARN);
1380 /* GNU "1.0" sparse pax format */
1381 if (wcscmp(key, L"GNU.sparse.major") == 0) {
1382 tar->sparse_gnu_major = tar_atol10(value, wcslen(value));
1383 tar->sparse_gnu_pending = 1;
1385 if (wcscmp(key, L"GNU.sparse.minor") == 0) {
1386 tar->sparse_gnu_minor = tar_atol10(value, wcslen(value));
1387 tar->sparse_gnu_pending = 1;
1389 if (wcscmp(key, L"GNU.sparse.name") == 0)
1390 archive_entry_copy_pathname_w(entry, value);
1391 if (wcscmp(key, L"GNU.sparse.realsize") == 0)
1392 archive_entry_set_size(entry,
1393 tar_atol10(value, wcslen(value)));
1396 /* Our extensions */
1397 /* TODO: Handle arbitrary extended attributes... */
1399 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1400 archive_entry_set_xxxxxx(entry, value);
1402 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1403 pax_attribute_xattr(entry, key, value);
1406 /* We support some keys used by the "star" archiver */
1407 if (wcscmp(key, L"SCHILY.acl.access")==0)
1408 __archive_entry_acl_parse_w(entry, value,
1409 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1410 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1411 __archive_entry_acl_parse_w(entry, value,
1412 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1413 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1414 archive_entry_set_rdevmajor(entry, tar_atol10(value, wcslen(value)));
1415 else if (wcscmp(key, L"SCHILY.devminor")==0)
1416 archive_entry_set_rdevminor(entry, tar_atol10(value, wcslen(value)));
1417 else if (wcscmp(key, L"SCHILY.fflags")==0)
1418 archive_entry_copy_fflags_text_w(entry, value);
1419 else if (wcscmp(key, L"SCHILY.dev")==0)
1420 archive_entry_set_dev(entry, tar_atol10(value, wcslen(value)));
1421 else if (wcscmp(key, L"SCHILY.ino")==0)
1422 archive_entry_set_ino(entry, tar_atol10(value, wcslen(value)));
1423 else if (wcscmp(key, L"SCHILY.nlink")==0)
1424 archive_entry_set_nlink(entry, tar_atol10(value, wcslen(value)));
1427 if (wcscmp(key, L"atime")==0) {
1428 pax_time(value, &s, &n);
1429 archive_entry_set_atime(entry, s, n);
1433 if (wcscmp(key, L"ctime")==0) {
1434 pax_time(value, &s, &n);
1435 archive_entry_set_ctime(entry, s, n);
1436 } else if (wcscmp(key, L"charset")==0) {
1437 /* TODO: Publish charset information in entry. */
1438 } else if (wcscmp(key, L"comment")==0) {
1439 /* TODO: Publish comment in entry. */
1443 if (wcscmp(key, L"gid")==0)
1444 archive_entry_set_gid(entry, tar_atol10(value, wcslen(value)));
1445 else if (wcscmp(key, L"gname")==0)
1446 archive_entry_copy_gname_w(entry, value);
1449 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1450 if (wcscmp(key, L"linkpath")==0) {
1451 if (archive_entry_hardlink(entry))
1452 archive_entry_copy_hardlink_w(entry, value);
1454 archive_entry_copy_symlink_w(entry, value);
1458 if (wcscmp(key, L"mtime")==0) {
1459 pax_time(value, &s, &n);
1460 archive_entry_set_mtime(entry, s, n);
1464 if (wcscmp(key, L"path")==0)
1465 archive_entry_copy_pathname_w(entry, value);
1468 /* POSIX has reserved 'realtime.*' */
1471 /* POSIX has reserved 'security.*' */
1472 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1473 if (wcscmp(key, L"size")==0) {
1474 tar->entry_bytes_remaining = tar_atol10(value, wcslen(value));
1475 archive_entry_set_size(entry, tar->entry_bytes_remaining);
1477 tar->entry_bytes_remaining = 0;
1481 if (wcscmp(key, L"uid")==0)
1482 archive_entry_set_uid(entry, tar_atol10(value, wcslen(value)));
1483 else if (wcscmp(key, L"uname")==0)
1484 archive_entry_copy_uname_w(entry, value);
1493 * parse a decimal time value, which may include a fractional portion
1496 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1502 int64_t limit, last_digit_limit;
1504 limit = INT64_MAX / 10;
1505 last_digit_limit = INT64_MAX % 10;
1513 while (*p >= '0' && *p <= '9') {
1516 (s == limit && digit > last_digit_limit)) {
1520 s = (s * 10) + digit;
1526 /* Calculate nanoseconds. */
1535 if (*p >= '0' && *p <= '9')
1536 *pn += (*p - '0') * l;
1543 * Parse GNU tar header
1546 header_gnutar(struct archive_read *a, struct tar *tar,
1547 struct archive_entry *entry, const void *h)
1549 const struct archive_entry_header_gnutar *header;
1554 * GNU header is like POSIX ustar, except 'prefix' is
1555 * replaced with some other fields. This also means the
1556 * filename is stored as in old-style archives.
1559 /* Grab fields common to all tar variants. */
1560 header_common(a, tar, entry, h);
1562 /* Copy filename over (to ensure null termination). */
1563 header = (const struct archive_entry_header_gnutar *)h;
1564 archive_strncpy(&(tar->entry_name), header->name,
1565 sizeof(header->name));
1566 archive_entry_set_pathname(entry, tar->entry_name.s);
1568 /* Fields common to ustar and GNU */
1569 /* XXX Can the following be factored out since it's common
1570 * to ustar and gnu tar? Is it okay to move it down into
1571 * header_common, perhaps? */
1572 archive_strncpy(&(tar->entry_uname),
1573 header->uname, sizeof(header->uname));
1574 archive_entry_set_uname(entry, tar->entry_uname.s);
1576 archive_strncpy(&(tar->entry_gname),
1577 header->gname, sizeof(header->gname));
1578 archive_entry_set_gname(entry, tar->entry_gname.s);
1580 /* Parse out device numbers only for char and block specials */
1581 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1582 archive_entry_set_rdevmajor(entry,
1583 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1584 archive_entry_set_rdevminor(entry,
1585 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1587 archive_entry_set_rdev(entry, 0);
1589 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1591 /* Grab GNU-specific fields. */
1592 archive_entry_set_atime(entry,
1593 tar_atol(header->atime, sizeof(header->atime)), 0);
1594 archive_entry_set_ctime(entry,
1595 tar_atol(header->ctime, sizeof(header->ctime)), 0);
1596 if (header->realsize[0] != 0) {
1597 archive_entry_set_size(entry,
1598 tar_atol(header->realsize, sizeof(header->realsize)));
1601 if (header->sparse[0].offset[0] != 0) {
1602 gnu_sparse_old_read(a, tar, header);
1604 if (header->isextended[0] != 0) {
1613 gnu_add_sparse_entry(struct tar *tar, off_t offset, off_t remaining)
1615 struct sparse_block *p;
1617 p = (struct sparse_block *)malloc(sizeof(*p));
1619 __archive_errx(1, "Out of memory");
1620 memset(p, 0, sizeof(*p));
1621 if (tar->sparse_last != NULL)
1622 tar->sparse_last->next = p;
1624 tar->sparse_list = p;
1625 tar->sparse_last = p;
1627 p->remaining = remaining;
1631 gnu_clear_sparse_list(struct tar *tar)
1633 struct sparse_block *p;
1635 while (tar->sparse_list != NULL) {
1636 p = tar->sparse_list;
1637 tar->sparse_list = p->next;
1640 tar->sparse_last = NULL;
1644 * GNU tar old-format sparse data.
1646 * GNU old-format sparse data is stored in a fixed-field
1647 * format. Offset/size values are 11-byte octal fields (same
1648 * format as 'size' field in ustart header). These are
1649 * stored in the header, allocating subsequent header blocks
1650 * as needed. Extending the header in this way is a pretty
1651 * severe POSIX violation; this design has earned GNU tar a
1656 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
1657 const struct archive_entry_header_gnutar *header)
1662 struct gnu_sparse sparse[21];
1666 const struct extended *ext;
1668 gnu_sparse_old_parse(tar, header->sparse, 4);
1669 if (header->isextended[0] == 0)
1670 return (ARCHIVE_OK);
1673 bytes_read = (a->decompressor->read_ahead)(a, &data, 512);
1675 return (ARCHIVE_FATAL);
1676 if (bytes_read < 512) {
1677 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1678 "Truncated tar archive "
1679 "detected while reading sparse file data");
1680 return (ARCHIVE_FATAL);
1682 (a->decompressor->consume)(a, 512);
1683 ext = (const struct extended *)data;
1684 gnu_sparse_old_parse(tar, ext->sparse, 21);
1685 } while (ext->isextended[0] != 0);
1686 if (tar->sparse_list != NULL)
1687 tar->entry_offset = tar->sparse_list->offset;
1688 return (ARCHIVE_OK);
1692 gnu_sparse_old_parse(struct tar *tar,
1693 const struct gnu_sparse *sparse, int length)
1695 while (length > 0 && sparse->offset[0] != 0) {
1696 gnu_add_sparse_entry(tar,
1697 tar_atol(sparse->offset, sizeof(sparse->offset)),
1698 tar_atol(sparse->numbytes, sizeof(sparse->numbytes)));
1705 * GNU tar sparse format 0.0
1707 * Beginning with GNU tar 1.15, sparse files are stored using
1708 * information in the pax extended header. The GNU tar maintainers
1709 * have gone through a number of variations in the process of working
1710 * out this scheme; furtunately, they're all numbered.
1712 * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
1713 * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
1714 * store offset/size for each block. The repeated instances of these
1715 * latter fields violate the pax specification (which frowns on
1716 * duplicate keys), so this format was quickly replaced.
1720 * GNU tar sparse format 0.1
1722 * This version replaced the offset/numbytes attributes with
1723 * a single "map" attribute that stored a list of integers. This
1724 * format had two problems: First, the "map" attribute could be very
1725 * long, which caused problems for some implementations. More
1726 * importantly, the sparse data was lost when extracted by archivers
1727 * that didn't recognize this extension.
1731 gnu_sparse_01_parse(struct tar *tar, const wchar_t *p)
1734 off_t offset = -1, size = -1;
1738 while (*e != '\0' && *e != ',') {
1739 if (*e < '0' || *e > '9')
1740 return (ARCHIVE_WARN);
1744 offset = tar_atol10(p, e - p);
1746 return (ARCHIVE_WARN);
1748 size = tar_atol10(p, e - p);
1750 return (ARCHIVE_WARN);
1751 gnu_add_sparse_entry(tar, offset, size);
1755 return (ARCHIVE_OK);
1761 * GNU tar sparse format 1.0
1763 * The idea: The offset/size data is stored as a series of base-10
1764 * ASCII numbers prepended to the file data, so that dearchivers that
1765 * don't support this format will extract the block map along with the
1766 * data and a separate post-process can restore the sparseness.
1768 * Unfortunately, GNU tar 1.16 adds bogus padding to the end of the
1769 * entry that depends on the size of the map; this means we have to
1770 * parse the sparse map when we read the header (otherwise, entry_skip
1771 * will fail). This is why sparse_10_read is called from read_header
1772 * above, instead of at the beginning of read_data, where it "should"
1775 * This variant also replaced GNU.sparse.size with GNU.sparse.realsize
1776 * and introduced the GNU.sparse.major/GNU.sparse.minor attributes.
1780 * Read the next line from the input, and parse it as a decimal
1781 * integer followed by '\n'. Returns positive integer value or
1782 * negative on error.
1785 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
1788 int64_t l, limit, last_digit_limit;
1794 limit = INT64_MAX / base;
1795 last_digit_limit = INT64_MAX % base;
1798 * Skip any lines starting with '#'; GNU tar specs
1799 * don't require this, but they should.
1802 bytes_read = readline(a, tar, &p, tar_min(*remaining, 100));
1803 if (bytes_read <= 0)
1804 return (ARCHIVE_FATAL);
1805 *remaining -= bytes_read;
1806 } while (p[0] == '#');
1809 while (bytes_read > 0) {
1812 if (*p < '0' || *p >= '0' + base)
1813 return (ARCHIVE_WARN);
1815 if (l > limit || (l == limit && digit > last_digit_limit))
1816 l = UINT64_MAX; /* Truncate on overflow. */
1818 l = (l * base) + digit;
1822 /* TODO: Error message. */
1823 return (ARCHIVE_WARN);
1827 * Returns length (in bytes) of the sparse data description
1831 gnu_sparse_10_read(struct archive_read *a, struct tar *tar)
1833 ssize_t remaining, bytes_read;
1835 off_t offset, size, to_skip;
1837 /* Clear out the existing sparse list. */
1838 gnu_clear_sparse_list(tar);
1840 remaining = tar->entry_bytes_remaining;
1842 /* Parse entries. */
1843 entries = gnu_sparse_10_atol(a, tar, &remaining);
1845 return (ARCHIVE_FATAL);
1846 /* Parse the individual entries. */
1847 while (entries-- > 0) {
1848 /* Parse offset/size */
1849 offset = gnu_sparse_10_atol(a, tar, &remaining);
1851 return (ARCHIVE_FATAL);
1852 size = gnu_sparse_10_atol(a, tar, &remaining);
1854 return (ARCHIVE_FATAL);
1855 /* Add a new sparse entry. */
1856 gnu_add_sparse_entry(tar, offset, size);
1858 /* Skip rest of block... */
1859 bytes_read = tar->entry_bytes_remaining - remaining;
1860 to_skip = 0x1ff & -bytes_read;
1861 if (to_skip != (a->decompressor->skip)(a, to_skip))
1862 return (ARCHIVE_FATAL);
1863 return (bytes_read + to_skip);
1867 * Convert text->integer.
1869 * Traditional tar formats (including POSIX) specify base-8 for
1870 * all of the standard numeric fields. This is a significant limitation
1872 * = file size is limited to 8GB
1873 * = rdevmajor and rdevminor are limited to 21 bits
1874 * = uid/gid are limited to 21 bits
1876 * There are two workarounds for this:
1877 * = pax extended headers, which use variable-length string fields
1878 * = GNU tar and STAR both allow either base-8 or base-256 in
1879 * most fields. The high bit is set to indicate base-256.
1881 * On read, this implementation supports both extensions.
1884 tar_atol(const char *p, unsigned char_cnt)
1887 * Technically, GNU tar considers a field to be in base-256
1888 * only if the first byte is 0xff or 0x80.
1891 return (tar_atol256(p, char_cnt));
1892 return (tar_atol8(p, char_cnt));
1896 * Note that this implementation does not (and should not!) obey
1897 * locale settings; you cannot simply substitute strtol here, since
1898 * it does obey locale.
1901 tar_atol8(const char *p, unsigned char_cnt)
1903 int64_t l, limit, last_digit_limit;
1904 int digit, sign, base;
1907 limit = INT64_MAX / base;
1908 last_digit_limit = INT64_MAX % base;
1910 while (*p == ' ' || *p == '\t')
1920 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1921 if (l>limit || (l == limit && digit > last_digit_limit)) {
1922 l = UINT64_MAX; /* Truncate on overflow. */
1925 l = (l * base) + digit;
1928 return (sign < 0) ? -l : l;
1932 * Note that this implementation does not (and should not!) obey
1933 * locale settings; you cannot simply substitute strtol here, since
1934 * it does obey locale.
1937 tar_atol10(const wchar_t *p, unsigned char_cnt)
1939 int64_t l, limit, last_digit_limit;
1940 int base, digit, sign;
1943 limit = INT64_MAX / base;
1944 last_digit_limit = INT64_MAX % base;
1946 while (*p == ' ' || *p == '\t')
1956 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1957 if (l > limit || (l == limit && digit > last_digit_limit)) {
1958 l = UINT64_MAX; /* Truncate on overflow. */
1961 l = (l * base) + digit;
1964 return (sign < 0) ? -l : l;
1968 * Parse a base-256 integer. This is just a straight signed binary
1969 * value in big-endian order, except that the high-order bit is
1970 * ignored. Remember that "int64_t" may or may not be exactly 64
1971 * bits; the implementation here tries to avoid making any assumptions
1972 * about the actual size of an int64_t. It does assume we're using
1973 * twos-complement arithmetic, though.
1976 tar_atol256(const char *_p, unsigned char_cnt)
1978 int64_t l, upper_limit, lower_limit;
1979 const unsigned char *p = (const unsigned char *)_p;
1981 upper_limit = INT64_MAX / 256;
1982 lower_limit = INT64_MIN / 256;
1984 /* Pad with 1 or 0 bits, depending on sign. */
1985 if ((0x40 & *p) == 0x40)
1989 l = (l << 6) | (0x3f & *p++);
1990 while (--char_cnt > 0) {
1991 if (l > upper_limit) {
1992 l = INT64_MAX; /* Truncate on overflow */
1994 } else if (l < lower_limit) {
1998 l = (l << 8) | (0xff & (int64_t)*p++);
2004 * Returns length of line (including trailing newline)
2005 * or negative on error. 'start' argument is updated to
2006 * point to first character of line. This avoids copying
2010 readline(struct archive_read *a, struct tar *tar, const char **start,
2014 ssize_t total_size = 0;
2019 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2020 if (bytes_read <= 0)
2021 return (ARCHIVE_FATAL);
2022 s = t; /* Start of line? */
2023 p = memchr(t, '\n', bytes_read);
2024 /* If we found '\n' in the read buffer, return pointer to that. */
2026 bytes_read = 1 + ((const char *)p) - s;
2027 if (bytes_read > limit) {
2028 archive_set_error(&a->archive,
2029 ARCHIVE_ERRNO_FILE_FORMAT,
2031 return (ARCHIVE_FATAL);
2033 (a->decompressor->consume)(a, bytes_read);
2035 return (bytes_read);
2037 /* Otherwise, we need to accumulate in a line buffer. */
2039 if (total_size + bytes_read > limit) {
2040 archive_set_error(&a->archive,
2041 ARCHIVE_ERRNO_FILE_FORMAT,
2043 return (ARCHIVE_FATAL);
2045 if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
2046 archive_set_error(&a->archive, ENOMEM,
2047 "Can't allocate working buffer");
2048 return (ARCHIVE_FATAL);
2050 memcpy(tar->line.s + total_size, t, bytes_read);
2051 (a->decompressor->consume)(a, bytes_read);
2052 total_size += bytes_read;
2053 /* If we found '\n', clean up and return. */
2055 *start = tar->line.s;
2056 return (total_size);
2058 /* Read some more. */
2059 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2060 if (bytes_read <= 0)
2061 return (ARCHIVE_FATAL);
2062 s = t; /* Start of line? */
2063 p = memchr(t, '\n', bytes_read);
2064 /* If we found '\n', trim the read. */
2066 bytes_read = 1 + ((const char *)p) - s;
2072 utf8_decode(wchar_t *dest, const char *src, size_t length)
2078 while (length > 0) {
2079 n = UTF8_mbrtowc(dest, src, length);
2091 * Copied and simplified from FreeBSD libc/locale.
2094 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
2096 int ch, i, len, mask;
2099 if (s == NULL || n == 0 || pwc == NULL)
2103 * Determine the number of octets that make up this character from
2104 * the first octet, and a mask that extracts the interesting bits of
2107 ch = (unsigned char)*s;
2108 if ((ch & 0x80) == 0) {
2111 } else if ((ch & 0xe0) == 0xc0) {
2114 } else if ((ch & 0xf0) == 0xe0) {
2117 } else if ((ch & 0xf8) == 0xf0) {
2120 } else if ((ch & 0xfc) == 0xf8) {
2123 } else if ((ch & 0xfe) == 0xfc) {
2127 /* Invalid first byte; convert to '?' */
2132 if (n < (size_t)len) {
2133 /* Invalid first byte; convert to '?' */
2139 * Decode the octet sequence representing the character in chunks
2140 * of 6 bits, most significant first.
2142 wch = (unsigned char)*s++ & mask;
2145 if ((*s & 0xc0) != 0x80) {
2146 /* Invalid intermediate byte; consume one byte and
2155 /* Assign the value to the output; out-of-range values
2156 * just get truncated. */
2157 *pwc = (wchar_t)wch;
2160 * If platform has WCHAR_MAX, we can do something
2161 * more sensible with out-of-range values.
2163 if (wch >= WCHAR_MAX)
2166 /* Return number of bytes input consumed: 0 for end-of-string. */
2167 return (wch == L'\0' ? 0 : len);
2172 * base64_decode - Base64 decode
2174 * This accepts most variations of base-64 encoding, including:
2175 * * with or without line breaks
2176 * * with or without the final group padded with '=' or '_' characters
2177 * (The most economical Base-64 variant does not pad the last group and
2178 * omits line breaks; RFC1341 used for MIME requires both.)
2181 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
2183 static const unsigned char digits[64] = {
2184 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
2185 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
2186 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
2187 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
2188 '4','5','6','7','8','9','+','/' };
2189 static unsigned char decode_table[128];
2192 /* If the decode table is not yet initialized, prepare it. */
2193 if (decode_table[digits[1]] != 1) {
2195 memset(decode_table, 0xff, sizeof(decode_table));
2196 for (i = 0; i < sizeof(digits); i++)
2197 decode_table[digits[i]] = i;
2200 /* Allocate enough space to hold the entire output. */
2201 /* Note that we may not use all of this... */
2202 out = (char *)malloc((len * 3 + 3) / 4);
2210 /* Collect the next group of (up to) four characters. */
2213 while (group_size < 4 && len > 0) {
2214 /* '=' or '_' padding indicates final group. */
2215 if (*src == '=' || *src == '_') {
2219 /* Skip illegal characters (including line breaks) */
2220 if (*src > 127 || *src < 32
2221 || decode_table[*src] == 0xff) {
2227 v |= decode_table[*src++];
2231 /* Align a short group properly. */
2232 v <<= 6 * (4 - group_size);
2233 /* Unpack the group we just collected. */
2234 switch (group_size) {
2235 case 4: d[2] = v & 0xff;
2237 case 3: d[1] = (v >> 8) & 0xff;
2239 case 2: d[0] = (v >> 16) & 0xff;
2241 case 1: /* this is invalid! */
2244 d += group_size * 3 / 4;
2252 * This is a little tricky because the C99 standard wcstombs()
2253 * function returns the number of bytes that were converted,
2254 * not the number that should be converted. As a result,
2255 * we can never accurately size the output buffer (without
2256 * doing a tedious output size calculation in advance).
2257 * This approach (try a conversion, then try again if it fails)
2258 * will almost always succeed on the first try, and is thus
2259 * much faster, at the cost of sometimes requiring multiple
2260 * passes while we expand the buffer.
2263 wide_to_narrow(const wchar_t *wval)
2265 int converted_length;
2266 /* Guess an output buffer size and try the conversion. */
2267 int alloc_length = wcslen(wval) * 3;
2268 char *mbs_val = (char *)malloc(alloc_length + 1);
2269 if (mbs_val == NULL)
2271 converted_length = wcstombs(mbs_val, wval, alloc_length);
2273 /* If we exhausted the buffer, resize and try again. */
2274 while (converted_length >= alloc_length) {
2277 mbs_val = (char *)malloc(alloc_length + 1);
2278 if (mbs_val == NULL)
2280 converted_length = wcstombs(mbs_val, wval, alloc_length);
2283 /* Ensure a trailing null and return the final string. */
2284 mbs_val[alloc_length] = '\0';
2289 url_decode(const char *in)
2294 out = (char *)malloc(strlen(in) + 1);
2297 for (s = in, d = out; *s != '\0'; ) {
2299 /* Try to convert % escape */
2300 int digit1 = tohex(s[1]);
2301 int digit2 = tohex(s[2]);
2302 if (digit1 >= 0 && digit2 >= 0) {
2303 /* Looks good, consume three chars */
2305 /* Convert output */
2306 *d++ = ((digit1 << 4) | digit2);
2309 /* Else fall through and treat '%' as normal char */
2320 if (c >= '0' && c <= '9')
2322 else if (c >= 'A' && c <= 'F')
2323 return (c - 'A' + 10);
2324 else if (c >= 'a' && c <= 'f')
2325 return (c - 'a' + 10);