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 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 < 512)
324 /* If it's an end-of-archive mark, we can handle it. */
325 if ((*(const char *)h) == 0 && archive_block_is_null((const unsigned char *)h)) {
326 /* If it's a known tar file, end-of-archive is definite. */
327 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
334 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
337 bid += 48; /* Checksum is usually 6 octal digits. */
339 header = (const struct archive_entry_header_ustar *)h;
341 /* Recognize POSIX formats. */
342 if ((memcmp(header->magic, "ustar\0", 6) == 0)
343 &&(memcmp(header->version, "00", 2)==0))
346 /* Recognize GNU tar format. */
347 if ((memcmp(header->magic, "ustar ", 6) == 0)
348 &&(memcmp(header->version, " \0", 2)==0))
351 /* Type flag must be null, digit or A-Z, a-z. */
352 if (header->typeflag[0] != 0 &&
353 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
354 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
355 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
357 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
359 /* Sanity check: Look at first byte of mode field. */
360 switch (255 & (unsigned)header->mode[0]) {
362 /* Base-256 value: No further verification possible! */
364 case ' ': /* Not recommended, but not illegal, either. */
366 case '0': case '1': case '2': case '3':
367 case '4': case '5': case '6': case '7':
369 /* TODO: Check format of remainder of this field. */
372 /* Not a valid mode; bail out here. */
375 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
381 * The function invoked by archive_read_header(). This
382 * just sets up a few things and then calls the internal
383 * tar_read_header() function below.
386 archive_read_format_tar_read_header(struct archive_read *a,
387 struct archive_entry *entry)
390 * When converting tar archives to cpio archives, it is
391 * essential that each distinct file have a distinct inode
392 * number. To simplify this, we keep a static count here to
393 * assign fake dev/inode numbers to each tar entry. Note that
394 * pax format archives may overwrite this with something more
397 * Ideally, we would track every file read from the archive so
398 * that we could assign the same dev/ino pair to hardlinks,
399 * but the memory required to store a complete lookup table is
400 * probably not worthwhile just to support the relatively
401 * obscure tar->cpio conversion case.
403 static int default_inode;
404 static int default_dev;
406 struct sparse_block *sp;
411 /* Assign default device/inode values. */
412 archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
413 archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
414 /* Limit generated st_ino number to 16 bits. */
415 if (default_inode >= 0xffff) {
420 tar = (struct tar *)(a->format->data);
421 tar->entry_offset = 0;
422 while (tar->sparse_list != NULL) {
423 sp = tar->sparse_list;
424 tar->sparse_list = sp->next;
427 tar->sparse_last = NULL;
428 tar->realsize = -1; /* Mark this as "unset" */
430 r = tar_read_header(a, tar, entry);
433 * "non-sparse" files are really just sparse files with
436 if (tar->sparse_list == NULL)
437 gnu_add_sparse_entry(tar, 0, tar->entry_bytes_remaining);
439 if (r == ARCHIVE_OK) {
441 * "Regular" entry with trailing '/' is really
442 * directory: This is needed for certain old tar
443 * variants and even for some broken newer ones.
445 p = archive_entry_pathname(entry);
447 if (archive_entry_filetype(entry) == AE_IFREG
449 archive_entry_set_filetype(entry, AE_IFDIR);
455 archive_read_format_tar_read_data(struct archive_read *a,
456 const void **buff, size_t *size, off_t *offset)
460 struct sparse_block *p;
462 tar = (struct tar *)(a->format->data);
464 if (tar->sparse_gnu_pending) {
465 if (tar->sparse_gnu_major == 1 && tar->sparse_gnu_minor == 0) {
466 tar->sparse_gnu_pending = 0;
467 /* Read initial sparse map. */
468 bytes_read = gnu_sparse_10_read(a, tar);
469 tar->entry_bytes_remaining -= bytes_read;
475 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
476 "Unrecognized GNU sparse file format");
477 return (ARCHIVE_WARN);
479 tar->sparse_gnu_pending = 0;
482 /* Remove exhausted entries from sparse list. */
483 while (tar->sparse_list != NULL &&
484 tar->sparse_list->remaining == 0) {
485 p = tar->sparse_list;
486 tar->sparse_list = p->next;
490 /* If we're at end of file, return EOF. */
491 if (tar->sparse_list == NULL || tar->entry_bytes_remaining == 0) {
492 if ((a->decompressor->skip)(a, tar->entry_padding) < 0)
493 return (ARCHIVE_FATAL);
494 tar->entry_padding = 0;
497 *offset = tar->realsize;
498 return (ARCHIVE_EOF);
501 bytes_read = (a->decompressor->read_ahead)(a, buff, 1);
502 if (bytes_read == 0) {
503 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
504 "Truncated tar archive");
505 return (ARCHIVE_FATAL);
508 return (ARCHIVE_FATAL);
509 if (bytes_read > tar->entry_bytes_remaining)
510 bytes_read = tar->entry_bytes_remaining;
511 /* Don't read more than is available in the
512 * current sparse block. */
513 if (tar->sparse_list->remaining < bytes_read)
514 bytes_read = tar->sparse_list->remaining;
516 *offset = tar->sparse_list->offset;
517 tar->sparse_list->remaining -= bytes_read;
518 tar->sparse_list->offset += bytes_read;
519 tar->entry_bytes_remaining -= bytes_read;
520 (a->decompressor->consume)(a, bytes_read);
525 archive_read_format_tar_skip(struct archive_read *a)
530 tar = (struct tar *)(a->format->data);
533 * Compression layer skip functions are required to either skip the
534 * length requested or fail, so we can rely upon the entire entry
535 * plus padding being skipped.
537 bytes_skipped = (a->decompressor->skip)(a, tar->entry_bytes_remaining +
539 if (bytes_skipped < 0)
540 return (ARCHIVE_FATAL);
542 tar->entry_bytes_remaining = 0;
543 tar->entry_padding = 0;
545 /* Free the sparse list. */
546 gnu_clear_sparse_list(tar);
552 * This function recursively interprets all of the headers associated
553 * with a single entry.
556 tar_read_header(struct archive_read *a, struct tar *tar,
557 struct archive_entry *entry)
562 const struct archive_entry_header_ustar *header;
564 /* Read 512-byte header record */
565 bytes = (a->decompressor->read_ahead)(a, &h, 512);
570 * An archive that just ends without a proper
571 * end-of-archive marker. Yes, there are tar programs
572 * that do this; hold our nose and accept it.
574 return (ARCHIVE_EOF);
577 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
578 "Truncated tar archive");
579 return (ARCHIVE_FATAL);
581 (a->decompressor->consume)(a, 512);
584 /* Check for end-of-archive mark. */
585 if (((*(const char *)h)==0) && archive_block_is_null((const unsigned char *)h)) {
586 /* Try to consume a second all-null record, as well. */
587 bytes = (a->decompressor->read_ahead)(a, &h, 512);
589 (a->decompressor->consume)(a, bytes);
590 archive_set_error(&a->archive, 0, NULL);
591 return (ARCHIVE_EOF);
595 * Note: If the checksum fails and we return ARCHIVE_RETRY,
596 * then the client is likely to just retry. This is a very
597 * crude way to search for the next valid header!
599 * TODO: Improve this by implementing a real header scan.
601 if (!checksum(a, h)) {
602 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
603 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
606 if (++tar->header_recursion_depth > 32) {
607 archive_set_error(&a->archive, EINVAL, "Too many special headers");
608 return (ARCHIVE_WARN);
611 /* Determine the format variant. */
612 header = (const struct archive_entry_header_ustar *)h;
613 switch(header->typeflag[0]) {
614 case 'A': /* Solaris tar ACL */
615 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
616 a->archive.archive_format_name = "Solaris tar";
617 err = header_Solaris_ACL(a, tar, entry, h);
619 case 'g': /* POSIX-standard 'g' header. */
620 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
621 a->archive.archive_format_name = "POSIX pax interchange format";
622 err = header_pax_global(a, tar, entry, h);
624 case 'K': /* Long link name (GNU tar, others) */
625 err = header_longlink(a, tar, entry, h);
627 case 'L': /* Long filename (GNU tar, others) */
628 err = header_longname(a, tar, entry, h);
630 case 'V': /* GNU volume header */
631 err = header_volume(a, tar, entry, h);
633 case 'X': /* Used by SUN tar; same as 'x'. */
634 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
635 a->archive.archive_format_name =
636 "POSIX pax interchange format (Sun variant)";
637 err = header_pax_extensions(a, tar, entry, h);
639 case 'x': /* POSIX-standard 'x' header. */
640 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
641 a->archive.archive_format_name = "POSIX pax interchange format";
642 err = header_pax_extensions(a, tar, entry, h);
645 if (memcmp(header->magic, "ustar \0", 8) == 0) {
646 a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
647 a->archive.archive_format_name = "GNU tar format";
648 err = header_gnutar(a, tar, entry, h);
649 } else if (memcmp(header->magic, "ustar", 5) == 0) {
650 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
651 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
652 a->archive.archive_format_name = "POSIX ustar format";
654 err = header_ustar(a, tar, entry, h);
656 a->archive.archive_format = ARCHIVE_FORMAT_TAR;
657 a->archive.archive_format_name = "tar (non-POSIX)";
658 err = header_old_tar(a, tar, entry, h);
661 --tar->header_recursion_depth;
662 /* We return warnings or success as-is. Anything else is fatal. */
663 if (err == ARCHIVE_WARN || err == ARCHIVE_OK)
665 if (err == ARCHIVE_EOF)
666 /* EOF when recursively reading a header is bad. */
667 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
668 return (ARCHIVE_FATAL);
672 * Return true if block checksum is correct.
675 checksum(struct archive_read *a, const void *h)
677 const unsigned char *bytes;
678 const struct archive_entry_header_ustar *header;
681 (void)a; /* UNUSED */
682 bytes = (const unsigned char *)h;
683 header = (const struct archive_entry_header_ustar *)h;
686 * Test the checksum. Note that POSIX specifies _unsigned_
687 * bytes for this calculation.
689 sum = tar_atol(header->checksum, sizeof(header->checksum));
691 for (i = 0; i < 148; i++)
692 check += (unsigned char)bytes[i];
696 check += (unsigned char)bytes[i];
701 * Repeat test with _signed_ bytes, just in case this archive
702 * was created by an old BSD, Solaris, or HP-UX tar with a
703 * broken checksum calculation.
706 for (i = 0; i < 148; i++)
707 check += (signed char)bytes[i];
711 check += (signed char)bytes[i];
719 * Return true if this block contains only nulls.
722 archive_block_is_null(const unsigned char *p)
726 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
733 * Interpret 'A' Solaris ACL header
736 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
737 struct archive_entry *entry, const void *h)
739 const struct archive_entry_header_ustar *header;
746 * read_body_to_string adds a NUL terminator, but we need a little
747 * more to make sure that we don't overrun acl_text later.
749 header = (const struct archive_entry_header_ustar *)h;
750 size = tar_atol(header->size, sizeof(header->size));
751 err = read_body_to_string(a, tar, &(tar->acl_text), h);
752 if (err != ARCHIVE_OK)
754 err = tar_read_header(a, tar, entry);
755 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
758 /* Skip leading octal number. */
759 /* XXX TODO: Parse the octal number and sanity-check it. */
760 p = acl = tar->acl_text.s;
761 while (*p != '\0' && p < acl + size)
765 if (p >= acl + size) {
766 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
767 "Malformed Solaris ACL attribute");
768 return(ARCHIVE_WARN);
771 /* Skip leading octal number. */
775 while (*p != '\0' && p < acl + size)
778 wp = (wchar_t *)malloc((p - acl + 1) * sizeof(wchar_t));
780 archive_set_error(&a->archive, ENOMEM,
781 "Can't allocate work buffer for ACL parsing");
782 return (ARCHIVE_FATAL);
784 utf8_decode(wp, acl, p - acl);
785 err = __archive_entry_acl_parse_w(entry, wp,
786 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
792 * Interpret 'K' long linkname header.
795 header_longlink(struct archive_read *a, struct tar *tar,
796 struct archive_entry *entry, const void *h)
800 err = read_body_to_string(a, tar, &(tar->longlink), h);
801 if (err != ARCHIVE_OK)
803 err = tar_read_header(a, tar, entry);
804 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
806 /* Set symlink if symlink already set, else hardlink. */
807 archive_entry_set_link(entry, tar->longlink.s);
812 * Interpret 'L' long filename header.
815 header_longname(struct archive_read *a, struct tar *tar,
816 struct archive_entry *entry, const void *h)
820 err = read_body_to_string(a, tar, &(tar->longname), h);
821 if (err != ARCHIVE_OK)
823 /* Read and parse "real" header, then override name. */
824 err = tar_read_header(a, tar, entry);
825 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
827 archive_entry_set_pathname(entry, tar->longname.s);
833 * Interpret 'V' GNU tar volume header.
836 header_volume(struct archive_read *a, struct tar *tar,
837 struct archive_entry *entry, const void *h)
841 /* Just skip this and read the next header. */
842 return (tar_read_header(a, tar, entry));
846 * Read body of an archive entry into an archive_string object.
849 read_body_to_string(struct archive_read *a, struct tar *tar,
850 struct archive_string *as, const void *h)
852 off_t size, padded_size;
853 ssize_t bytes_read, bytes_to_copy;
854 const struct archive_entry_header_ustar *header;
858 (void)tar; /* UNUSED */
859 header = (const struct archive_entry_header_ustar *)h;
860 size = tar_atol(header->size, sizeof(header->size));
861 if ((size > 1048576) || (size < 0)) {
862 archive_set_error(&a->archive, EINVAL,
863 "Special header too large");
864 return (ARCHIVE_FATAL);
867 /* Fail if we can't make our buffer big enough. */
868 if (archive_string_ensure(as, size+1) == NULL) {
869 archive_set_error(&a->archive, ENOMEM,
871 return (ARCHIVE_FATAL);
874 /* Read the body into the string. */
875 padded_size = (size + 511) & ~ 511;
877 while (padded_size > 0) {
878 bytes_read = (a->decompressor->read_ahead)(a, &src, padded_size);
880 return (ARCHIVE_EOF);
882 return (ARCHIVE_FATAL);
883 if (bytes_read > padded_size)
884 bytes_read = padded_size;
885 (a->decompressor->consume)(a, bytes_read);
886 bytes_to_copy = bytes_read;
887 if ((off_t)bytes_to_copy > size)
888 bytes_to_copy = (ssize_t)size;
889 memcpy(dest, src, bytes_to_copy);
890 dest += bytes_to_copy;
891 size -= bytes_to_copy;
892 padded_size -= bytes_read;
899 * Parse out common header elements.
901 * This would be the same as header_old_tar, except that the
902 * filename is handled slightly differently for old and POSIX
903 * entries (POSIX entries support a 'prefix'). This factoring
904 * allows header_old_tar and header_ustar
905 * to handle filenames differently, while still putting most of the
906 * common parsing into one place.
909 header_common(struct archive_read *a, struct tar *tar,
910 struct archive_entry *entry, const void *h)
912 const struct archive_entry_header_ustar *header;
915 (void)a; /* UNUSED */
917 header = (const struct archive_entry_header_ustar *)h;
918 if (header->linkname[0])
919 archive_strncpy(&(tar->entry_linkname), header->linkname,
920 sizeof(header->linkname));
922 archive_string_empty(&(tar->entry_linkname));
924 /* Parse out the numeric fields (all are octal) */
925 archive_entry_set_mode(entry, tar_atol(header->mode, sizeof(header->mode)));
926 archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
927 archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
928 tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size));
929 tar->realsize = tar->entry_bytes_remaining;
930 archive_entry_set_size(entry, tar->entry_bytes_remaining);
931 archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
933 /* Handle the tar type flag appropriately. */
934 tartype = header->typeflag[0];
937 case '1': /* Hard link */
938 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
940 * The following may seem odd, but: Technically, tar
941 * does not store the file type for a "hard link"
942 * entry, only the fact that it is a hard link. So, I
943 * leave the type zero normally. But, pax interchange
944 * format allows hard links to have data, which
945 * implies that the underlying entry is a regular
948 if (archive_entry_size(entry) > 0)
949 archive_entry_set_filetype(entry, AE_IFREG);
952 * A tricky point: Traditionally, tar readers have
953 * ignored the size field when reading hardlink
954 * entries, and some writers put non-zero sizes even
955 * though the body is empty. POSIX.1-2001 broke with
956 * this tradition by permitting hardlink entries to
957 * store valid bodies in pax interchange format, but
958 * not in ustar format. Since there is no hard and
959 * fast way to distinguish pax interchange from
960 * earlier archives (the 'x' and 'g' entries are
961 * optional, after all), we need a heuristic. Here, I
962 * use the bid function to test whether or not there's
963 * a valid header following. Of course, if we know
964 * this is pax interchange format, then we must obey
967 * This heuristic will only fail for a pax interchange
968 * archive that is storing hardlink bodies, no pax
969 * extended attribute entries have yet occurred, and
970 * we encounter a hardlink entry for a file that is
971 * itself an uncompressed tar archive.
973 if (archive_entry_size(entry) > 0 &&
974 a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
975 archive_read_format_tar_bid(a) > 50) {
976 archive_entry_set_size(entry, 0);
977 tar->entry_bytes_remaining = 0;
980 case '2': /* Symlink */
981 archive_entry_set_filetype(entry, AE_IFLNK);
982 archive_entry_set_size(entry, 0);
983 tar->entry_bytes_remaining = 0;
984 archive_entry_set_symlink(entry, tar->entry_linkname.s);
986 case '3': /* Character device */
987 archive_entry_set_filetype(entry, AE_IFCHR);
988 archive_entry_set_size(entry, 0);
989 tar->entry_bytes_remaining = 0;
991 case '4': /* Block device */
992 archive_entry_set_filetype(entry, AE_IFBLK);
993 archive_entry_set_size(entry, 0);
994 tar->entry_bytes_remaining = 0;
997 archive_entry_set_filetype(entry, AE_IFDIR);
998 archive_entry_set_size(entry, 0);
999 tar->entry_bytes_remaining = 0;
1001 case '6': /* FIFO device */
1002 archive_entry_set_filetype(entry, AE_IFIFO);
1003 archive_entry_set_size(entry, 0);
1004 tar->entry_bytes_remaining = 0;
1006 case 'D': /* GNU incremental directory type */
1008 * No special handling is actually required here.
1009 * It might be nice someday to preprocess the file list and
1010 * provide it to the client, though.
1012 archive_entry_set_filetype(entry, AE_IFDIR);
1014 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1016 * As far as I can tell, this is just like a regular file
1017 * entry, except that the contents should be _appended_ to
1018 * the indicated file at the indicated offset. This may
1019 * require some API work to fully support.
1022 case 'N': /* Old GNU "long filename" entry. */
1023 /* The body of this entry is a script for renaming
1024 * previously-extracted entries. Ugh. It will never
1025 * be supported by libarchive. */
1026 archive_entry_set_filetype(entry, AE_IFREG);
1028 case 'S': /* GNU sparse files */
1030 * Sparse files are really just regular files with
1031 * sparse information in the extended area.
1034 default: /* Regular file and non-standard types */
1036 * Per POSIX: non-recognized types should always be
1037 * treated as regular files.
1039 archive_entry_set_filetype(entry, AE_IFREG);
1046 * Parse out header elements for "old-style" tar archives.
1049 header_old_tar(struct archive_read *a, struct tar *tar,
1050 struct archive_entry *entry, const void *h)
1052 const struct archive_entry_header_ustar *header;
1054 /* Copy filename over (to ensure null termination). */
1055 header = (const struct archive_entry_header_ustar *)h;
1056 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1057 archive_entry_set_pathname(entry, tar->entry_name.s);
1059 /* Grab rest of common fields */
1060 header_common(a, tar, entry, h);
1062 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1067 * Parse a file header for a pax extended archive entry.
1070 header_pax_global(struct archive_read *a, struct tar *tar,
1071 struct archive_entry *entry, const void *h)
1075 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1076 if (err != ARCHIVE_OK)
1078 err = tar_read_header(a, tar, entry);
1083 header_pax_extensions(struct archive_read *a, struct tar *tar,
1084 struct archive_entry *entry, const void *h)
1088 err = read_body_to_string(a, tar, &(tar->pax_header), h);
1089 if (err != ARCHIVE_OK)
1092 /* Parse the next header. */
1093 err = tar_read_header(a, tar, entry);
1094 if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1098 * TODO: Parse global/default options into 'entry' struct here
1099 * before handling file-specific options.
1101 * This design (parse standard header, then overwrite with pax
1102 * extended attribute data) usually works well, but isn't ideal;
1103 * it would be better to parse the pax extended attributes first
1104 * and then skip any fields in the standard header that were
1105 * defined in the pax header.
1107 err2 = pax_header(a, tar, entry, tar->pax_header.s);
1108 err = err_combine(err, err2);
1109 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1115 * Parse a file header for a Posix "ustar" archive entry. This also
1116 * handles "pax" or "extended ustar" entries.
1119 header_ustar(struct archive_read *a, struct tar *tar,
1120 struct archive_entry *entry, const void *h)
1122 const struct archive_entry_header_ustar *header;
1123 struct archive_string *as;
1125 header = (const struct archive_entry_header_ustar *)h;
1127 /* Copy name into an internal buffer to ensure null-termination. */
1128 as = &(tar->entry_name);
1129 if (header->prefix[0]) {
1130 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1131 if (as->s[archive_strlen(as) - 1] != '/')
1132 archive_strappend_char(as, '/');
1133 archive_strncat(as, header->name, sizeof(header->name));
1135 archive_strncpy(as, header->name, sizeof(header->name));
1137 archive_entry_set_pathname(entry, as->s);
1139 /* Handle rest of common fields. */
1140 header_common(a, tar, entry, h);
1142 /* Handle POSIX ustar fields. */
1143 archive_strncpy(&(tar->entry_uname), header->uname,
1144 sizeof(header->uname));
1145 archive_entry_set_uname(entry, tar->entry_uname.s);
1147 archive_strncpy(&(tar->entry_gname), header->gname,
1148 sizeof(header->gname));
1149 archive_entry_set_gname(entry, tar->entry_gname.s);
1151 /* Parse out device numbers only for char and block specials. */
1152 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1153 archive_entry_set_rdevmajor(entry,
1154 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1155 archive_entry_set_rdevminor(entry,
1156 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1159 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1166 * Parse the pax extended attributes record.
1168 * Returns non-zero if there's an error in the data.
1171 pax_header(struct archive_read *a, struct tar *tar,
1172 struct archive_entry *entry, char *attr)
1174 size_t attr_length, l, line_length;
1176 wchar_t *key, *wp, *value;
1179 attr_length = strlen(attr);
1181 while (attr_length > 0) {
1182 /* Parse decimal length field at start of line. */
1185 line = p = attr; /* Record start of line. */
1192 if (*p < '0' || *p > '9') {
1193 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1194 "Ignoring malformed pax extended attributes");
1195 return (ARCHIVE_WARN);
1198 line_length += *p - '0';
1199 if (line_length > 999999) {
1200 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1201 "Rejecting pax extended attribute > 1MB");
1202 return (ARCHIVE_WARN);
1209 * Parsed length must be no bigger than available data,
1210 * at least 1, and the last character of the line must
1213 if (line_length > attr_length
1215 || attr[line_length - 1] != '\n')
1217 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1218 "Ignoring malformed pax extended attribute");
1219 return (ARCHIVE_WARN);
1222 /* Ensure pax_entry buffer is big enough. */
1223 if (tar->pax_entry_length <= line_length) {
1224 wchar_t *old_entry = tar->pax_entry;
1226 if (tar->pax_entry_length <= 0)
1227 tar->pax_entry_length = 1024;
1228 while (tar->pax_entry_length <= line_length + 1)
1229 tar->pax_entry_length *= 2;
1231 old_entry = tar->pax_entry;
1232 tar->pax_entry = (wchar_t *)realloc(tar->pax_entry,
1233 tar->pax_entry_length * sizeof(wchar_t));
1234 if (tar->pax_entry == NULL) {
1236 archive_set_error(&a->archive, ENOMEM,
1238 return (ARCHIVE_FATAL);
1242 /* Decode UTF-8 to wchar_t, null-terminate result. */
1243 if (utf8_decode(tar->pax_entry, p,
1244 line_length - (p - attr) - 1)) {
1245 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1246 "Invalid UTF8 character in pax extended attribute");
1247 err = err_combine(err, ARCHIVE_WARN);
1250 /* Null-terminate 'key' value. */
1251 wp = key = tar->pax_entry;
1254 while (*wp && *wp != L'=')
1257 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1258 "Invalid pax extended attributes");
1259 return (ARCHIVE_WARN);
1263 /* Identify null-terminated 'value' portion. */
1266 /* Identify this attribute and set it in the entry. */
1267 err2 = pax_attribute(tar, entry, key, value);
1268 err = err_combine(err, err2);
1270 /* Skip to next line */
1271 attr += line_length;
1272 attr_length -= line_length;
1278 pax_attribute_xattr(struct archive_entry *entry,
1279 wchar_t *name, wchar_t *value)
1281 char *name_decoded, *name_narrow;
1282 void *value_decoded;
1285 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1290 /* URL-decode name */
1291 name_narrow = wide_to_narrow(name);
1292 if (name_narrow == NULL)
1294 name_decoded = url_decode(name_narrow);
1296 if (name_decoded == NULL)
1299 /* Base-64 decode value */
1300 value_decoded = base64_decode(value, wcslen(value), &value_len);
1301 if (value_decoded == NULL) {
1306 archive_entry_xattr_add_entry(entry, name_decoded,
1307 value_decoded, value_len);
1310 free(value_decoded);
1315 * Parse a single key=value attribute. key/value pointers are
1316 * assumed to point into reasonably long-lived storage.
1318 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1319 * extensions should always have keywords of the form "VENDOR.attribute"
1320 * In particular, it's quite feasible to support many different
1321 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1322 * unique to this library.
1324 * Investigate other vendor-specific extensions and see if
1325 * any of them look useful.
1328 pax_attribute(struct tar *tar, struct archive_entry *entry,
1329 wchar_t *key, wchar_t *value)
1336 /* GNU "0.0" sparse pax format. */
1337 if (wcscmp(key, L"GNU.sparse.numblocks") == 0) {
1338 tar->sparse_offset = -1;
1339 tar->sparse_numbytes = -1;
1340 tar->sparse_gnu_major = 0;
1341 tar->sparse_gnu_minor = 0;
1343 if (wcscmp(key, L"GNU.sparse.offset") == 0) {
1344 tar->sparse_offset = tar_atol10(value, wcslen(value));
1345 if (tar->sparse_numbytes != -1) {
1346 gnu_add_sparse_entry(tar,
1347 tar->sparse_offset, tar->sparse_numbytes);
1348 tar->sparse_offset = -1;
1349 tar->sparse_numbytes = -1;
1352 if (wcscmp(key, L"GNU.sparse.numbytes") == 0) {
1353 tar->sparse_numbytes = tar_atol10(value, wcslen(value));
1354 if (tar->sparse_numbytes != -1) {
1355 gnu_add_sparse_entry(tar,
1356 tar->sparse_offset, tar->sparse_numbytes);
1357 tar->sparse_offset = -1;
1358 tar->sparse_numbytes = -1;
1361 if (wcscmp(key, L"GNU.sparse.size") == 0) {
1362 tar->realsize = tar_atol10(value, wcslen(value));
1363 archive_entry_set_size(entry, tar->realsize);
1366 /* GNU "0.1" sparse pax format. */
1367 if (wcscmp(key, L"GNU.sparse.map") == 0) {
1368 tar->sparse_gnu_major = 0;
1369 tar->sparse_gnu_minor = 1;
1370 if (gnu_sparse_01_parse(tar, value) != ARCHIVE_OK)
1371 return (ARCHIVE_WARN);
1374 /* GNU "1.0" sparse pax format */
1375 if (wcscmp(key, L"GNU.sparse.major") == 0) {
1376 tar->sparse_gnu_major = tar_atol10(value, wcslen(value));
1377 tar->sparse_gnu_pending = 1;
1379 if (wcscmp(key, L"GNU.sparse.minor") == 0) {
1380 tar->sparse_gnu_minor = tar_atol10(value, wcslen(value));
1381 tar->sparse_gnu_pending = 1;
1383 if (wcscmp(key, L"GNU.sparse.name") == 0)
1384 archive_entry_copy_pathname_w(entry, value);
1385 if (wcscmp(key, L"GNU.sparse.realsize") == 0) {
1386 tar->realsize = tar_atol10(value, wcslen(value));
1387 archive_entry_set_size(entry, tar->realsize);
1391 /* Our extensions */
1392 /* TODO: Handle arbitrary extended attributes... */
1394 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1395 archive_entry_set_xxxxxx(entry, value);
1397 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1398 pax_attribute_xattr(entry, key, value);
1401 /* We support some keys used by the "star" archiver */
1402 if (wcscmp(key, L"SCHILY.acl.access")==0)
1403 __archive_entry_acl_parse_w(entry, value,
1404 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1405 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1406 __archive_entry_acl_parse_w(entry, value,
1407 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1408 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1409 archive_entry_set_rdevmajor(entry, tar_atol10(value, wcslen(value)));
1410 else if (wcscmp(key, L"SCHILY.devminor")==0)
1411 archive_entry_set_rdevminor(entry, tar_atol10(value, wcslen(value)));
1412 else if (wcscmp(key, L"SCHILY.fflags")==0)
1413 archive_entry_copy_fflags_text_w(entry, value);
1414 else if (wcscmp(key, L"SCHILY.dev")==0)
1415 archive_entry_set_dev(entry, tar_atol10(value, wcslen(value)));
1416 else if (wcscmp(key, L"SCHILY.ino")==0)
1417 archive_entry_set_ino(entry, tar_atol10(value, wcslen(value)));
1418 else if (wcscmp(key, L"SCHILY.nlink")==0)
1419 archive_entry_set_nlink(entry, tar_atol10(value, wcslen(value)));
1420 else if (wcscmp(key, L"SCHILY.realsize")==0) {
1421 tar->realsize = tar_atol10(value, wcslen(value));
1422 archive_entry_set_size(entry, tar->realsize);
1426 if (wcscmp(key, L"atime")==0) {
1427 pax_time(value, &s, &n);
1428 archive_entry_set_atime(entry, s, n);
1432 if (wcscmp(key, L"ctime")==0) {
1433 pax_time(value, &s, &n);
1434 archive_entry_set_ctime(entry, s, n);
1435 } else if (wcscmp(key, L"charset")==0) {
1436 /* TODO: Publish charset information in entry. */
1437 } else if (wcscmp(key, L"comment")==0) {
1438 /* TODO: Publish comment in entry. */
1442 if (wcscmp(key, L"gid")==0)
1443 archive_entry_set_gid(entry, tar_atol10(value, wcslen(value)));
1444 else if (wcscmp(key, L"gname")==0)
1445 archive_entry_copy_gname_w(entry, value);
1448 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1449 if (wcscmp(key, L"linkpath")==0) {
1450 if (archive_entry_hardlink(entry))
1451 archive_entry_copy_hardlink_w(entry, value);
1453 archive_entry_copy_symlink_w(entry, value);
1457 if (wcscmp(key, L"mtime")==0) {
1458 pax_time(value, &s, &n);
1459 archive_entry_set_mtime(entry, s, n);
1463 if (wcscmp(key, L"path")==0)
1464 archive_entry_copy_pathname_w(entry, value);
1467 /* POSIX has reserved 'realtime.*' */
1470 /* POSIX has reserved 'security.*' */
1471 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1472 if (wcscmp(key, L"size")==0) {
1473 /* "size" is the size of the data in the entry. */
1474 tar->entry_bytes_remaining
1475 = tar_atol10(value, wcslen(value));
1477 * But, "size" is not necessarily the size of
1478 * the file on disk; if this is a sparse file,
1479 * the disk size may have already been set from
1480 * GNU.sparse.realsize or GNU.sparse.size or
1481 * an old GNU header field or SCHILY.realsize
1484 if (tar->realsize < 0) {
1485 archive_entry_set_size(entry,
1486 tar->entry_bytes_remaining);
1488 = tar->entry_bytes_remaining;
1493 if (wcscmp(key, L"uid")==0)
1494 archive_entry_set_uid(entry, tar_atol10(value, wcslen(value)));
1495 else if (wcscmp(key, L"uname")==0)
1496 archive_entry_copy_uname_w(entry, value);
1505 * parse a decimal time value, which may include a fractional portion
1508 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1514 int64_t limit, last_digit_limit;
1516 limit = INT64_MAX / 10;
1517 last_digit_limit = INT64_MAX % 10;
1525 while (*p >= '0' && *p <= '9') {
1528 (s == limit && digit > last_digit_limit)) {
1532 s = (s * 10) + digit;
1538 /* Calculate nanoseconds. */
1547 if (*p >= '0' && *p <= '9')
1548 *pn += (*p - '0') * l;
1555 * Parse GNU tar header
1558 header_gnutar(struct archive_read *a, struct tar *tar,
1559 struct archive_entry *entry, const void *h)
1561 const struct archive_entry_header_gnutar *header;
1566 * GNU header is like POSIX ustar, except 'prefix' is
1567 * replaced with some other fields. This also means the
1568 * filename is stored as in old-style archives.
1571 /* Grab fields common to all tar variants. */
1572 header_common(a, tar, entry, h);
1574 /* Copy filename over (to ensure null termination). */
1575 header = (const struct archive_entry_header_gnutar *)h;
1576 archive_strncpy(&(tar->entry_name), header->name,
1577 sizeof(header->name));
1578 archive_entry_set_pathname(entry, tar->entry_name.s);
1580 /* Fields common to ustar and GNU */
1581 /* XXX Can the following be factored out since it's common
1582 * to ustar and gnu tar? Is it okay to move it down into
1583 * header_common, perhaps? */
1584 archive_strncpy(&(tar->entry_uname),
1585 header->uname, sizeof(header->uname));
1586 archive_entry_set_uname(entry, tar->entry_uname.s);
1588 archive_strncpy(&(tar->entry_gname),
1589 header->gname, sizeof(header->gname));
1590 archive_entry_set_gname(entry, tar->entry_gname.s);
1592 /* Parse out device numbers only for char and block specials */
1593 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1594 archive_entry_set_rdevmajor(entry,
1595 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1596 archive_entry_set_rdevminor(entry,
1597 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1599 archive_entry_set_rdev(entry, 0);
1601 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1603 /* Grab GNU-specific fields. */
1604 archive_entry_set_atime(entry,
1605 tar_atol(header->atime, sizeof(header->atime)), 0);
1606 archive_entry_set_ctime(entry,
1607 tar_atol(header->ctime, sizeof(header->ctime)), 0);
1608 if (header->realsize[0] != 0) {
1610 = tar_atol(header->realsize, sizeof(header->realsize));
1611 archive_entry_set_size(entry, tar->realsize);
1614 if (header->sparse[0].offset[0] != 0) {
1615 gnu_sparse_old_read(a, tar, header);
1617 if (header->isextended[0] != 0) {
1626 gnu_add_sparse_entry(struct tar *tar, off_t offset, off_t remaining)
1628 struct sparse_block *p;
1630 p = (struct sparse_block *)malloc(sizeof(*p));
1632 __archive_errx(1, "Out of memory");
1633 memset(p, 0, sizeof(*p));
1634 if (tar->sparse_last != NULL)
1635 tar->sparse_last->next = p;
1637 tar->sparse_list = p;
1638 tar->sparse_last = p;
1640 p->remaining = remaining;
1644 gnu_clear_sparse_list(struct tar *tar)
1646 struct sparse_block *p;
1648 while (tar->sparse_list != NULL) {
1649 p = tar->sparse_list;
1650 tar->sparse_list = p->next;
1653 tar->sparse_last = NULL;
1657 * GNU tar old-format sparse data.
1659 * GNU old-format sparse data is stored in a fixed-field
1660 * format. Offset/size values are 11-byte octal fields (same
1661 * format as 'size' field in ustart header). These are
1662 * stored in the header, allocating subsequent header blocks
1663 * as needed. Extending the header in this way is a pretty
1664 * severe POSIX violation; this design has earned GNU tar a
1669 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
1670 const struct archive_entry_header_gnutar *header)
1675 struct gnu_sparse sparse[21];
1679 const struct extended *ext;
1681 gnu_sparse_old_parse(tar, header->sparse, 4);
1682 if (header->isextended[0] == 0)
1683 return (ARCHIVE_OK);
1686 bytes_read = (a->decompressor->read_ahead)(a, &data, 512);
1688 return (ARCHIVE_FATAL);
1689 if (bytes_read < 512) {
1690 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1691 "Truncated tar archive "
1692 "detected while reading sparse file data");
1693 return (ARCHIVE_FATAL);
1695 (a->decompressor->consume)(a, 512);
1696 ext = (const struct extended *)data;
1697 gnu_sparse_old_parse(tar, ext->sparse, 21);
1698 } while (ext->isextended[0] != 0);
1699 if (tar->sparse_list != NULL)
1700 tar->entry_offset = tar->sparse_list->offset;
1701 return (ARCHIVE_OK);
1705 gnu_sparse_old_parse(struct tar *tar,
1706 const struct gnu_sparse *sparse, int length)
1708 while (length > 0 && sparse->offset[0] != 0) {
1709 gnu_add_sparse_entry(tar,
1710 tar_atol(sparse->offset, sizeof(sparse->offset)),
1711 tar_atol(sparse->numbytes, sizeof(sparse->numbytes)));
1718 * GNU tar sparse format 0.0
1720 * Beginning with GNU tar 1.15, sparse files are stored using
1721 * information in the pax extended header. The GNU tar maintainers
1722 * have gone through a number of variations in the process of working
1723 * out this scheme; furtunately, they're all numbered.
1725 * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
1726 * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
1727 * store offset/size for each block. The repeated instances of these
1728 * latter fields violate the pax specification (which frowns on
1729 * duplicate keys), so this format was quickly replaced.
1733 * GNU tar sparse format 0.1
1735 * This version replaced the offset/numbytes attributes with
1736 * a single "map" attribute that stored a list of integers. This
1737 * format had two problems: First, the "map" attribute could be very
1738 * long, which caused problems for some implementations. More
1739 * importantly, the sparse data was lost when extracted by archivers
1740 * that didn't recognize this extension.
1744 gnu_sparse_01_parse(struct tar *tar, const wchar_t *p)
1747 off_t offset = -1, size = -1;
1751 while (*e != '\0' && *e != ',') {
1752 if (*e < '0' || *e > '9')
1753 return (ARCHIVE_WARN);
1757 offset = tar_atol10(p, e - p);
1759 return (ARCHIVE_WARN);
1761 size = tar_atol10(p, e - p);
1763 return (ARCHIVE_WARN);
1764 gnu_add_sparse_entry(tar, offset, size);
1768 return (ARCHIVE_OK);
1774 * GNU tar sparse format 1.0
1776 * The idea: The offset/size data is stored as a series of base-10
1777 * ASCII numbers prepended to the file data, so that dearchivers that
1778 * don't support this format will extract the block map along with the
1779 * data and a separate post-process can restore the sparseness.
1781 * Unfortunately, GNU tar 1.16 adds bogus padding to the end of the
1782 * entry that depends on the size of the map; this means we have to
1783 * parse the sparse map when we read the header (otherwise, entry_skip
1784 * will fail). This is why sparse_10_read is called from read_header
1785 * above, instead of at the beginning of read_data, where it "should"
1788 * This variant also replaced GNU.sparse.size with GNU.sparse.realsize
1789 * and introduced the GNU.sparse.major/GNU.sparse.minor attributes.
1793 * Read the next line from the input, and parse it as a decimal
1794 * integer followed by '\n'. Returns positive integer value or
1795 * negative on error.
1798 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
1801 int64_t l, limit, last_digit_limit;
1807 limit = INT64_MAX / base;
1808 last_digit_limit = INT64_MAX % base;
1811 * Skip any lines starting with '#'; GNU tar specs
1812 * don't require this, but they should.
1815 bytes_read = readline(a, tar, &p, tar_min(*remaining, 100));
1816 if (bytes_read <= 0)
1817 return (ARCHIVE_FATAL);
1818 *remaining -= bytes_read;
1819 } while (p[0] == '#');
1822 while (bytes_read > 0) {
1825 if (*p < '0' || *p >= '0' + base)
1826 return (ARCHIVE_WARN);
1828 if (l > limit || (l == limit && digit > last_digit_limit))
1829 l = UINT64_MAX; /* Truncate on overflow. */
1831 l = (l * base) + digit;
1835 /* TODO: Error message. */
1836 return (ARCHIVE_WARN);
1840 * Returns length (in bytes) of the sparse data description
1844 gnu_sparse_10_read(struct archive_read *a, struct tar *tar)
1846 ssize_t remaining, bytes_read;
1848 off_t offset, size, to_skip;
1850 /* Clear out the existing sparse list. */
1851 gnu_clear_sparse_list(tar);
1853 remaining = tar->entry_bytes_remaining;
1855 /* Parse entries. */
1856 entries = gnu_sparse_10_atol(a, tar, &remaining);
1858 return (ARCHIVE_FATAL);
1859 /* Parse the individual entries. */
1860 while (entries-- > 0) {
1861 /* Parse offset/size */
1862 offset = gnu_sparse_10_atol(a, tar, &remaining);
1864 return (ARCHIVE_FATAL);
1865 size = gnu_sparse_10_atol(a, tar, &remaining);
1867 return (ARCHIVE_FATAL);
1868 /* Add a new sparse entry. */
1869 gnu_add_sparse_entry(tar, offset, size);
1871 /* Skip rest of block... */
1872 bytes_read = tar->entry_bytes_remaining - remaining;
1873 to_skip = 0x1ff & -bytes_read;
1874 if (to_skip != (a->decompressor->skip)(a, to_skip))
1875 return (ARCHIVE_FATAL);
1876 return (bytes_read + to_skip);
1880 * Convert text->integer.
1882 * Traditional tar formats (including POSIX) specify base-8 for
1883 * all of the standard numeric fields. This is a significant limitation
1885 * = file size is limited to 8GB
1886 * = rdevmajor and rdevminor are limited to 21 bits
1887 * = uid/gid are limited to 21 bits
1889 * There are two workarounds for this:
1890 * = pax extended headers, which use variable-length string fields
1891 * = GNU tar and STAR both allow either base-8 or base-256 in
1892 * most fields. The high bit is set to indicate base-256.
1894 * On read, this implementation supports both extensions.
1897 tar_atol(const char *p, unsigned char_cnt)
1900 * Technically, GNU tar considers a field to be in base-256
1901 * only if the first byte is 0xff or 0x80.
1904 return (tar_atol256(p, char_cnt));
1905 return (tar_atol8(p, char_cnt));
1909 * Note that this implementation does not (and should not!) obey
1910 * locale settings; you cannot simply substitute strtol here, since
1911 * it does obey locale.
1914 tar_atol8(const char *p, unsigned char_cnt)
1916 int64_t l, limit, last_digit_limit;
1917 int digit, sign, base;
1920 limit = INT64_MAX / base;
1921 last_digit_limit = INT64_MAX % base;
1923 while (*p == ' ' || *p == '\t')
1933 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1934 if (l>limit || (l == limit && digit > last_digit_limit)) {
1935 l = UINT64_MAX; /* Truncate on overflow. */
1938 l = (l * base) + digit;
1941 return (sign < 0) ? -l : l;
1945 * Note that this implementation does not (and should not!) obey
1946 * locale settings; you cannot simply substitute strtol here, since
1947 * it does obey locale.
1950 tar_atol10(const wchar_t *p, unsigned char_cnt)
1952 int64_t l, limit, last_digit_limit;
1953 int base, digit, sign;
1956 limit = INT64_MAX / base;
1957 last_digit_limit = INT64_MAX % base;
1959 while (*p == ' ' || *p == '\t')
1969 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1970 if (l > limit || (l == limit && digit > last_digit_limit)) {
1971 l = UINT64_MAX; /* Truncate on overflow. */
1974 l = (l * base) + digit;
1977 return (sign < 0) ? -l : l;
1981 * Parse a base-256 integer. This is just a straight signed binary
1982 * value in big-endian order, except that the high-order bit is
1983 * ignored. Remember that "int64_t" may or may not be exactly 64
1984 * bits; the implementation here tries to avoid making any assumptions
1985 * about the actual size of an int64_t. It does assume we're using
1986 * twos-complement arithmetic, though.
1989 tar_atol256(const char *_p, unsigned char_cnt)
1991 int64_t l, upper_limit, lower_limit;
1992 const unsigned char *p = (const unsigned char *)_p;
1994 upper_limit = INT64_MAX / 256;
1995 lower_limit = INT64_MIN / 256;
1997 /* Pad with 1 or 0 bits, depending on sign. */
1998 if ((0x40 & *p) == 0x40)
2002 l = (l << 6) | (0x3f & *p++);
2003 while (--char_cnt > 0) {
2004 if (l > upper_limit) {
2005 l = INT64_MAX; /* Truncate on overflow */
2007 } else if (l < lower_limit) {
2011 l = (l << 8) | (0xff & (int64_t)*p++);
2017 * Returns length of line (including trailing newline)
2018 * or negative on error. 'start' argument is updated to
2019 * point to first character of line. This avoids copying
2023 readline(struct archive_read *a, struct tar *tar, const char **start,
2027 ssize_t total_size = 0;
2032 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2033 if (bytes_read <= 0)
2034 return (ARCHIVE_FATAL);
2035 s = t; /* Start of line? */
2036 p = memchr(t, '\n', bytes_read);
2037 /* If we found '\n' in the read buffer, return pointer to that. */
2039 bytes_read = 1 + ((const char *)p) - s;
2040 if (bytes_read > limit) {
2041 archive_set_error(&a->archive,
2042 ARCHIVE_ERRNO_FILE_FORMAT,
2044 return (ARCHIVE_FATAL);
2046 (a->decompressor->consume)(a, bytes_read);
2048 return (bytes_read);
2050 /* Otherwise, we need to accumulate in a line buffer. */
2052 if (total_size + bytes_read > limit) {
2053 archive_set_error(&a->archive,
2054 ARCHIVE_ERRNO_FILE_FORMAT,
2056 return (ARCHIVE_FATAL);
2058 if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
2059 archive_set_error(&a->archive, ENOMEM,
2060 "Can't allocate working buffer");
2061 return (ARCHIVE_FATAL);
2063 memcpy(tar->line.s + total_size, t, bytes_read);
2064 (a->decompressor->consume)(a, bytes_read);
2065 total_size += bytes_read;
2066 /* If we found '\n', clean up and return. */
2068 *start = tar->line.s;
2069 return (total_size);
2071 /* Read some more. */
2072 bytes_read = (a->decompressor->read_ahead)(a, &t, 1);
2073 if (bytes_read <= 0)
2074 return (ARCHIVE_FATAL);
2075 s = t; /* Start of line? */
2076 p = memchr(t, '\n', bytes_read);
2077 /* If we found '\n', trim the read. */
2079 bytes_read = 1 + ((const char *)p) - s;
2085 utf8_decode(wchar_t *dest, const char *src, size_t length)
2091 while (length > 0) {
2092 n = UTF8_mbrtowc(dest, src, length);
2104 * Copied and simplified from FreeBSD libc/locale.
2107 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
2109 int ch, i, len, mask;
2112 if (s == NULL || n == 0 || pwc == NULL)
2116 * Determine the number of octets that make up this character from
2117 * the first octet, and a mask that extracts the interesting bits of
2120 ch = (unsigned char)*s;
2121 if ((ch & 0x80) == 0) {
2124 } else if ((ch & 0xe0) == 0xc0) {
2127 } else if ((ch & 0xf0) == 0xe0) {
2130 } else if ((ch & 0xf8) == 0xf0) {
2133 } else if ((ch & 0xfc) == 0xf8) {
2136 } else if ((ch & 0xfe) == 0xfc) {
2140 /* Invalid first byte; convert to '?' */
2145 if (n < (size_t)len) {
2146 /* Invalid first byte; convert to '?' */
2152 * Decode the octet sequence representing the character in chunks
2153 * of 6 bits, most significant first.
2155 wch = (unsigned char)*s++ & mask;
2158 if ((*s & 0xc0) != 0x80) {
2159 /* Invalid intermediate byte; consume one byte and
2168 /* Assign the value to the output; out-of-range values
2169 * just get truncated. */
2170 *pwc = (wchar_t)wch;
2173 * If platform has WCHAR_MAX, we can do something
2174 * more sensible with out-of-range values.
2176 if (wch >= WCHAR_MAX)
2179 /* Return number of bytes input consumed: 0 for end-of-string. */
2180 return (wch == L'\0' ? 0 : len);
2185 * base64_decode - Base64 decode
2187 * This accepts most variations of base-64 encoding, including:
2188 * * with or without line breaks
2189 * * with or without the final group padded with '=' or '_' characters
2190 * (The most economical Base-64 variant does not pad the last group and
2191 * omits line breaks; RFC1341 used for MIME requires both.)
2194 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
2196 static const unsigned char digits[64] = {
2197 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
2198 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
2199 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
2200 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
2201 '4','5','6','7','8','9','+','/' };
2202 static unsigned char decode_table[128];
2205 /* If the decode table is not yet initialized, prepare it. */
2206 if (decode_table[digits[1]] != 1) {
2208 memset(decode_table, 0xff, sizeof(decode_table));
2209 for (i = 0; i < sizeof(digits); i++)
2210 decode_table[digits[i]] = i;
2213 /* Allocate enough space to hold the entire output. */
2214 /* Note that we may not use all of this... */
2215 out = (char *)malloc((len * 3 + 3) / 4);
2223 /* Collect the next group of (up to) four characters. */
2226 while (group_size < 4 && len > 0) {
2227 /* '=' or '_' padding indicates final group. */
2228 if (*src == '=' || *src == '_') {
2232 /* Skip illegal characters (including line breaks) */
2233 if (*src > 127 || *src < 32
2234 || decode_table[*src] == 0xff) {
2240 v |= decode_table[*src++];
2244 /* Align a short group properly. */
2245 v <<= 6 * (4 - group_size);
2246 /* Unpack the group we just collected. */
2247 switch (group_size) {
2248 case 4: d[2] = v & 0xff;
2250 case 3: d[1] = (v >> 8) & 0xff;
2252 case 2: d[0] = (v >> 16) & 0xff;
2254 case 1: /* this is invalid! */
2257 d += group_size * 3 / 4;
2265 * This is a little tricky because the C99 standard wcstombs()
2266 * function returns the number of bytes that were converted,
2267 * not the number that should be converted. As a result,
2268 * we can never accurately size the output buffer (without
2269 * doing a tedious output size calculation in advance).
2270 * This approach (try a conversion, then try again if it fails)
2271 * will almost always succeed on the first try, and is thus
2272 * much faster, at the cost of sometimes requiring multiple
2273 * passes while we expand the buffer.
2276 wide_to_narrow(const wchar_t *wval)
2278 int converted_length;
2279 /* Guess an output buffer size and try the conversion. */
2280 int alloc_length = wcslen(wval) * 3;
2281 char *mbs_val = (char *)malloc(alloc_length + 1);
2282 if (mbs_val == NULL)
2284 converted_length = wcstombs(mbs_val, wval, alloc_length);
2286 /* If we exhausted the buffer, resize and try again. */
2287 while (converted_length >= alloc_length) {
2290 mbs_val = (char *)malloc(alloc_length + 1);
2291 if (mbs_val == NULL)
2293 converted_length = wcstombs(mbs_val, wval, alloc_length);
2296 /* Ensure a trailing null and return the final string. */
2297 mbs_val[alloc_length] = '\0';
2302 url_decode(const char *in)
2307 out = (char *)malloc(strlen(in) + 1);
2310 for (s = in, d = out; *s != '\0'; ) {
2312 /* Try to convert % escape */
2313 int digit1 = tohex(s[1]);
2314 int digit2 = tohex(s[2]);
2315 if (digit1 >= 0 && digit2 >= 0) {
2316 /* Looks good, consume three chars */
2318 /* Convert output */
2319 *d++ = ((digit1 << 4) | digit2);
2322 /* Else fall through and treat '%' as normal char */
2333 if (c >= '0' && c <= '9')
2335 else if (c >= 'A' && c <= 'F')
2336 return (c - 'A' + 10);
2337 else if (c >= 'a' && c <= 'f')
2338 return (c - 'a' + 10);