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.50 2007/03/31 22:59:43 cperciva Exp $");
29 #ifdef HAVE_SYS_STAT_H
33 #include <sys/mkdev.h>
35 #ifdef MAJOR_IN_SYSMACROS
36 #include <sys/sysmacros.h>
43 /* #include <stdint.h> */ /* See archive_platform.h */
54 /* Obtain suitable wide-character manipulation functions. */
58 /* Good enough for equality testing, which is all we need. */
59 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
62 while (*s1 && diff == 0)
63 diff = (int)*++s1 - (int)*++s2;
66 /* Good enough for equality testing, which is all we need. */
67 static int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n)
70 while (*s1 && diff == 0 && n-- > 0)
71 diff = (int)*++s1 - (int)*++s2;
74 static size_t wcslen(const wchar_t *s)
84 #include "archive_entry.h"
85 #include "archive_private.h"
86 #include "archive_read_private.h"
89 * Layout of POSIX 'ustar' tar header.
91 struct archive_entry_header_ustar {
100 char linkname[100]; /* "old format" header ends here */
101 char magic[6]; /* For POSIX: "ustar\0" */
102 char version[2]; /* For POSIX: "00" */
111 * Structure of GNU tar header
118 struct archive_entry_header_gnutar {
128 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
138 struct gnu_sparse sparse[4];
142 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
148 * Data specific to this format.
150 struct sparse_block {
151 struct sparse_block *next;
157 struct archive_string acl_text;
158 struct archive_string entry_name;
159 struct archive_string entry_linkname;
160 struct archive_string entry_uname;
161 struct archive_string entry_gname;
162 struct archive_string longlink;
163 struct archive_string longname;
164 struct archive_string pax_header;
165 struct archive_string pax_global;
167 size_t pax_entry_length;
168 int header_recursion_depth;
169 off_t entry_bytes_remaining;
172 struct sparse_block *sparse_list;
175 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
176 static int archive_block_is_null(const unsigned char *p);
177 static char *base64_decode(const wchar_t *, size_t, size_t *);
178 static int gnu_read_sparse_data(struct archive_read *, struct tar *,
179 const struct archive_entry_header_gnutar *header);
180 static void gnu_parse_sparse_data(struct archive_read *, struct tar *,
181 const struct gnu_sparse *sparse, int length);
182 static int header_Solaris_ACL(struct archive_read *, struct tar *,
183 struct archive_entry *, struct stat *, const void *);
184 static int header_common(struct archive_read *, struct tar *,
185 struct archive_entry *, struct stat *, const void *);
186 static int header_old_tar(struct archive_read *, struct tar *,
187 struct archive_entry *, struct stat *, const void *);
188 static int header_pax_extensions(struct archive_read *, struct tar *,
189 struct archive_entry *, struct stat *, const void *);
190 static int header_pax_global(struct archive_read *, struct tar *,
191 struct archive_entry *, struct stat *, const void *h);
192 static int header_longlink(struct archive_read *, struct tar *,
193 struct archive_entry *, struct stat *, const void *h);
194 static int header_longname(struct archive_read *, struct tar *,
195 struct archive_entry *, struct stat *, const void *h);
196 static int header_volume(struct archive_read *, struct tar *,
197 struct archive_entry *, struct stat *, const void *h);
198 static int header_ustar(struct archive_read *, struct tar *,
199 struct archive_entry *, struct stat *, const void *h);
200 static int header_gnutar(struct archive_read *, struct tar *,
201 struct archive_entry *, struct stat *, const void *h);
202 static int archive_read_format_tar_bid(struct archive_read *);
203 static int archive_read_format_tar_cleanup(struct archive_read *);
204 static int archive_read_format_tar_read_data(struct archive_read *a,
205 const void **buff, size_t *size, off_t *offset);
206 static int archive_read_format_tar_skip(struct archive_read *a);
207 static int archive_read_format_tar_read_header(struct archive_read *,
208 struct archive_entry *);
209 static int checksum(struct archive_read *, const void *);
210 static int pax_attribute(struct archive_entry *, struct stat *,
211 wchar_t *key, wchar_t *value);
212 static int pax_header(struct archive_read *, struct tar *,
213 struct archive_entry *, struct stat *, char *attr);
214 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
215 static int read_body_to_string(struct archive_read *, struct tar *,
216 struct archive_string *, const void *h);
217 static int64_t tar_atol(const char *, unsigned);
218 static int64_t tar_atol10(const wchar_t *, unsigned);
219 static int64_t tar_atol256(const char *, unsigned);
220 static int64_t tar_atol8(const char *, unsigned);
221 static int tar_read_header(struct archive_read *, struct tar *,
222 struct archive_entry *, struct stat *);
223 static int tohex(int c);
224 static char *url_decode(const char *);
225 static int utf8_decode(wchar_t *, const char *, size_t length);
226 static char *wide_to_narrow(const wchar_t *wval);
229 * ANSI C99 defines constants for these, but not everyone supports
230 * those constants, so I define a couple of static variables here and
231 * compute the values. These calculations should be portable to any
232 * 2s-complement architecture.
235 static const uint64_t max_uint64 = UINT64_MAX;
237 static const uint64_t max_uint64 = ~(uint64_t)0;
240 static const int64_t max_int64 = INT64_MAX;
242 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
245 static const int64_t min_int64 = INT64_MIN;
247 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
251 archive_read_support_format_gnutar(struct archive *a)
253 return (archive_read_support_format_tar(a));
258 archive_read_support_format_tar(struct archive *_a)
260 struct archive_read *a = (struct archive_read *)_a;
264 tar = (struct tar *)malloc(sizeof(*tar));
266 archive_set_error(&a->archive, ENOMEM,
267 "Can't allocate tar data");
268 return (ARCHIVE_FATAL);
270 memset(tar, 0, sizeof(*tar));
272 r = __archive_read_register_format(a, tar,
273 archive_read_format_tar_bid,
274 archive_read_format_tar_read_header,
275 archive_read_format_tar_read_data,
276 archive_read_format_tar_skip,
277 archive_read_format_tar_cleanup);
285 archive_read_format_tar_cleanup(struct archive_read *a)
289 tar = (struct tar *)*(a->pformat_data);
290 archive_string_free(&tar->acl_text);
291 archive_string_free(&tar->entry_name);
292 archive_string_free(&tar->entry_linkname);
293 archive_string_free(&tar->entry_uname);
294 archive_string_free(&tar->entry_gname);
295 archive_string_free(&tar->pax_global);
296 archive_string_free(&tar->pax_header);
297 if (tar->pax_entry != NULL)
298 free(tar->pax_entry);
300 *(a->pformat_data) = NULL;
306 archive_read_format_tar_bid(struct archive_read *a)
311 const struct archive_entry_header_ustar *header;
314 * If we're already reading a non-tar file, don't
317 if (a->archive.archive_format != 0 &&
318 (a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
324 * If we're already reading a tar format, start the bid at 1 as
327 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
331 /* Now let's look at the actual header and see if it matches. */
332 if (a->compression_read_ahead != NULL)
333 bytes_read = (a->compression_read_ahead)(a, &h, 512);
335 bytes_read = 0; /* Empty file. */
337 return (ARCHIVE_FATAL);
338 if (bytes_read == 0 && bid > 0) {
339 /* An archive without a proper end-of-archive marker. */
340 /* Hold our nose and bid 1 anyway. */
343 if (bytes_read < 512) {
344 /* If it's a new archive, then just return a zero bid. */
348 * If we already know this is a tar archive,
349 * then we have a problem.
351 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
352 "Truncated tar archive");
353 return (ARCHIVE_FATAL);
356 /* If it's an end-of-archive mark, we can handle it. */
357 if ((*(const char *)h) == 0 && archive_block_is_null((const unsigned char *)h)) {
358 /* If it's a known tar file, end-of-archive is definite. */
359 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
366 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
369 bid += 48; /* Checksum is usually 6 octal digits. */
371 header = (const struct archive_entry_header_ustar *)h;
373 /* Recognize POSIX formats. */
374 if ((memcmp(header->magic, "ustar\0", 6) == 0)
375 &&(memcmp(header->version, "00", 2)==0))
378 /* Recognize GNU tar format. */
379 if ((memcmp(header->magic, "ustar ", 6) == 0)
380 &&(memcmp(header->version, " \0", 2)==0))
383 /* Type flag must be null, digit or A-Z, a-z. */
384 if (header->typeflag[0] != 0 &&
385 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
386 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
387 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
389 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
391 /* Sanity check: Look at first byte of mode field. */
392 switch (255 & (unsigned)header->mode[0]) {
394 /* Base-256 value: No further verification possible! */
396 case ' ': /* Not recommended, but not illegal, either. */
398 case '0': case '1': case '2': case '3':
399 case '4': case '5': case '6': case '7':
401 /* TODO: Check format of remainder of this field. */
404 /* Not a valid mode; bail out here. */
407 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
413 * The function invoked by archive_read_header(). This
414 * just sets up a few things and then calls the internal
415 * tar_read_header() function below.
418 archive_read_format_tar_read_header(struct archive_read *a,
419 struct archive_entry *entry)
422 * When converting tar archives to cpio archives, it is
423 * essential that each distinct file have a distinct inode
424 * number. To simplify this, we keep a static count here to
425 * assign fake dev/inode numbers to each tar entry. Note that
426 * pax format archives may overwrite this with something more
429 * Ideally, we would track every file read from the archive so
430 * that we could assign the same dev/ino pair to hardlinks,
431 * but the memory required to store a complete lookup table is
432 * probably not worthwhile just to support the relatively
433 * obscure tar->cpio conversion case.
435 static int default_inode;
436 static int default_dev;
443 memset(&st, 0, sizeof(st));
444 /* Assign default device/inode values. */
445 st.st_dev = 1 + default_dev; /* Don't use zero. */
446 st.st_ino = ++default_inode; /* Don't use zero. */
447 /* Limit generated st_ino number to 16 bits. */
448 if (default_inode >= 0xffff) {
453 tar = (struct tar *)*(a->pformat_data);
454 tar->entry_offset = 0;
456 r = tar_read_header(a, tar, entry, &st);
458 if (r == ARCHIVE_OK) {
460 * "Regular" entry with trailing '/' is really
461 * directory: This is needed for certain old tar
462 * variants and even for some broken newer ones.
464 p = archive_entry_pathname(entry);
466 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
467 st.st_mode &= ~S_IFMT;
468 st.st_mode |= S_IFDIR;
471 /* Copy the final stat data into the entry. */
472 archive_entry_copy_stat(entry, &st);
478 archive_read_format_tar_read_data(struct archive_read *a,
479 const void **buff, size_t *size, off_t *offset)
483 struct sparse_block *p;
485 tar = (struct tar *)*(a->pformat_data);
486 if (tar->sparse_list != NULL) {
487 /* Remove exhausted entries from sparse list. */
488 while (tar->sparse_list != NULL &&
489 tar->sparse_list->remaining == 0) {
490 p = tar->sparse_list;
491 tar->sparse_list = p->next;
494 if (tar->sparse_list == NULL) {
495 /* We exhausted the entire sparse list. */
496 tar->entry_bytes_remaining = 0;
500 if (tar->entry_bytes_remaining > 0) {
501 bytes_read = (a->compression_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 if (tar->sparse_list != NULL) {
512 /* Don't read more than is available in the
513 * current sparse block. */
514 if (tar->sparse_list->remaining < bytes_read)
515 bytes_read = tar->sparse_list->remaining;
516 tar->entry_offset = tar->sparse_list->offset;
517 tar->sparse_list->remaining -= bytes_read;
518 tar->sparse_list->offset += bytes_read;
521 *offset = tar->entry_offset;
522 tar->entry_offset += bytes_read;
523 tar->entry_bytes_remaining -= bytes_read;
524 (a->compression_read_consume)(a, bytes_read);
527 while (tar->entry_padding > 0) {
528 bytes_read = (a->compression_read_ahead)(a, buff, 1);
530 return (ARCHIVE_FATAL);
531 if (bytes_read > tar->entry_padding)
532 bytes_read = tar->entry_padding;
533 (a->compression_read_consume)(a, bytes_read);
534 tar->entry_padding -= bytes_read;
538 *offset = tar->entry_offset;
539 return (ARCHIVE_EOF);
544 archive_read_format_tar_skip(struct archive_read *a)
548 struct sparse_block *p;
550 tar = (struct tar *)*(a->pformat_data);
553 * Compression layer skip functions are required to either skip the
554 * length requested or fail, so we can rely upon the entire entry
555 * plus padding being skipped.
557 bytes_skipped = (a->compression_skip)(a, tar->entry_bytes_remaining +
559 if (bytes_skipped < 0)
560 return (ARCHIVE_FATAL);
562 tar->entry_bytes_remaining = 0;
563 tar->entry_padding = 0;
565 /* Free the sparse list. */
566 while (tar->sparse_list != NULL) {
567 p = tar->sparse_list;
568 tar->sparse_list = p->next;
576 * This function recursively interprets all of the headers associated
577 * with a single entry.
580 tar_read_header(struct archive_read *a, struct tar *tar,
581 struct archive_entry *entry, struct stat *st)
586 const struct archive_entry_header_ustar *header;
588 /* Read 512-byte header record */
589 bytes = (a->compression_read_ahead)(a, &h, 512);
592 * If we're here, it's becase the _bid function accepted
593 * this file. So just call a short read end-of-archive
594 * and be done with it.
596 return (ARCHIVE_EOF);
598 (a->compression_read_consume)(a, 512);
600 /* Check for end-of-archive mark. */
601 if (((*(const char *)h)==0) && archive_block_is_null((const unsigned char *)h)) {
602 /* Try to consume a second all-null record, as well. */
603 bytes = (a->compression_read_ahead)(a, &h, 512);
605 (a->compression_read_consume)(a, bytes);
606 archive_set_error(&a->archive, 0, NULL);
607 return (ARCHIVE_EOF);
611 * Note: If the checksum fails and we return ARCHIVE_RETRY,
612 * then the client is likely to just retry. This is a very
613 * crude way to search for the next valid header!
615 * TODO: Improve this by implementing a real header scan.
617 if (!checksum(a, h)) {
618 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
619 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
622 if (++tar->header_recursion_depth > 32) {
623 archive_set_error(&a->archive, EINVAL, "Too many special headers");
624 return (ARCHIVE_WARN);
627 /* Determine the format variant. */
628 header = (const struct archive_entry_header_ustar *)h;
629 switch(header->typeflag[0]) {
630 case 'A': /* Solaris tar ACL */
631 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
632 a->archive.archive_format_name = "Solaris tar";
633 err = header_Solaris_ACL(a, tar, entry, st, h);
635 case 'g': /* POSIX-standard 'g' header. */
636 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
637 a->archive.archive_format_name = "POSIX pax interchange format";
638 err = header_pax_global(a, tar, entry, st, h);
640 case 'K': /* Long link name (GNU tar, others) */
641 err = header_longlink(a, tar, entry, st, h);
643 case 'L': /* Long filename (GNU tar, others) */
644 err = header_longname(a, tar, entry, st, h);
646 case 'V': /* GNU volume header */
647 err = header_volume(a, tar, entry, st, h);
649 case 'X': /* Used by SUN tar; same as 'x'. */
650 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
651 a->archive.archive_format_name =
652 "POSIX pax interchange format (Sun variant)";
653 err = header_pax_extensions(a, tar, entry, st, h);
655 case 'x': /* POSIX-standard 'x' header. */
656 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
657 a->archive.archive_format_name = "POSIX pax interchange format";
658 err = header_pax_extensions(a, tar, entry, st, h);
661 if (memcmp(header->magic, "ustar \0", 8) == 0) {
662 a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
663 a->archive.archive_format_name = "GNU tar format";
664 err = header_gnutar(a, tar, entry, st, h);
665 } else if (memcmp(header->magic, "ustar", 5) == 0) {
666 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
667 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
668 a->archive.archive_format_name = "POSIX ustar format";
670 err = header_ustar(a, tar, entry, st, h);
672 a->archive.archive_format = ARCHIVE_FORMAT_TAR;
673 a->archive.archive_format_name = "tar (non-POSIX)";
674 err = header_old_tar(a, tar, entry, st, h);
677 --tar->header_recursion_depth;
682 * Return true if block checksum is correct.
685 checksum(struct archive_read *a, const void *h)
687 const unsigned char *bytes;
688 const struct archive_entry_header_ustar *header;
691 (void)a; /* UNUSED */
692 bytes = (const unsigned char *)h;
693 header = (const struct archive_entry_header_ustar *)h;
696 * Test the checksum. Note that POSIX specifies _unsigned_
697 * bytes for this calculation.
699 sum = tar_atol(header->checksum, sizeof(header->checksum));
701 for (i = 0; i < 148; i++)
702 check += (unsigned char)bytes[i];
706 check += (unsigned char)bytes[i];
711 * Repeat test with _signed_ bytes, just in case this archive
712 * was created by an old BSD, Solaris, or HP-UX tar with a
713 * broken checksum calculation.
716 for (i = 0; i < 148; i++)
717 check += (signed char)bytes[i];
721 check += (signed char)bytes[i];
729 * Return true if this block contains only nulls.
732 archive_block_is_null(const unsigned char *p)
736 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
743 * Interpret 'A' Solaris ACL header
746 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
747 struct archive_entry *entry, struct stat *st, const void *h)
753 err = read_body_to_string(a, tar, &(tar->acl_text), h);
754 err2 = tar_read_header(a, tar, entry, st);
755 err = err_combine(err, err2);
757 /* XXX Ensure p doesn't overrun acl_text */
759 /* Skip leading octal number. */
760 /* XXX TODO: Parse the octal number and sanity-check it. */
766 wp = (wchar_t *)malloc((strlen(p) + 1) * sizeof(wchar_t));
768 utf8_decode(wp, p, strlen(p));
769 err2 = __archive_entry_acl_parse_w(entry, wp,
770 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
771 err = err_combine(err, err2);
779 * Interpret 'K' long linkname header.
782 header_longlink(struct archive_read *a, struct tar *tar,
783 struct archive_entry *entry, struct stat *st, const void *h)
787 err = read_body_to_string(a, tar, &(tar->longlink), h);
788 err2 = tar_read_header(a, tar, entry, st);
789 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
790 /* Set symlink if symlink already set, else hardlink. */
791 archive_entry_set_link(entry, tar->longlink.s);
793 return (err_combine(err, err2));
797 * Interpret 'L' long filename header.
800 header_longname(struct archive_read *a, struct tar *tar,
801 struct archive_entry *entry, struct stat *st, const void *h)
805 err = read_body_to_string(a, tar, &(tar->longname), h);
806 /* Read and parse "real" header, then override name. */
807 err2 = tar_read_header(a, tar, entry, st);
808 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
809 archive_entry_set_pathname(entry, tar->longname.s);
810 return (err_combine(err, err2));
815 * Interpret 'V' GNU tar volume header.
818 header_volume(struct archive_read *a, struct tar *tar,
819 struct archive_entry *entry, struct stat *st, const void *h)
823 /* Just skip this and read the next header. */
824 return (tar_read_header(a, tar, entry, st));
828 * Read body of an archive entry into an archive_string object.
831 read_body_to_string(struct archive_read *a, struct tar *tar,
832 struct archive_string *as, const void *h)
834 off_t size, padded_size;
835 ssize_t bytes_read, bytes_to_copy;
836 const struct archive_entry_header_ustar *header;
840 (void)tar; /* UNUSED */
841 header = (const struct archive_entry_header_ustar *)h;
842 size = tar_atol(header->size, sizeof(header->size));
844 /* Read the body into the string. */
845 archive_string_ensure(as, size+1);
846 padded_size = (size + 511) & ~ 511;
848 while (padded_size > 0) {
849 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
851 return (ARCHIVE_FATAL);
852 if (bytes_read > padded_size)
853 bytes_read = padded_size;
854 (a->compression_read_consume)(a, bytes_read);
855 bytes_to_copy = bytes_read;
856 if ((off_t)bytes_to_copy > size)
857 bytes_to_copy = (ssize_t)size;
858 memcpy(dest, src, bytes_to_copy);
859 dest += bytes_to_copy;
860 size -= bytes_to_copy;
861 padded_size -= bytes_read;
868 * Parse out common header elements.
870 * This would be the same as header_old_tar, except that the
871 * filename is handled slightly differently for old and POSIX
872 * entries (POSIX entries support a 'prefix'). This factoring
873 * allows header_old_tar and header_ustar
874 * to handle filenames differently, while still putting most of the
875 * common parsing into one place.
878 header_common(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
879 struct stat *st, const void *h)
881 const struct archive_entry_header_ustar *header;
884 (void)a; /* UNUSED */
886 header = (const struct archive_entry_header_ustar *)h;
887 if (header->linkname[0])
888 archive_strncpy(&(tar->entry_linkname), header->linkname,
889 sizeof(header->linkname));
891 archive_string_empty(&(tar->entry_linkname));
893 /* Parse out the numeric fields (all are octal) */
894 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
895 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
896 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
897 st->st_size = tar_atol(header->size, sizeof(header->size));
898 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
900 /* Handle the tar type flag appropriately. */
901 tartype = header->typeflag[0];
902 st->st_mode &= ~S_IFMT;
905 case '1': /* Hard link */
906 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
908 * The following may seem odd, but: Technically, tar
909 * does not store the file type for a "hard link"
910 * entry, only the fact that it is a hard link. So, I
911 * leave the type zero normally. But, pax interchange
912 * format allows hard links to have data, which
913 * implies that the underlying entry is a regular
917 st->st_mode |= S_IFREG;
920 * A tricky point: Traditionally, tar readers have
921 * ignored the size field when reading hardlink
922 * entries, and some writers put non-zero sizes even
923 * though the body is empty. POSIX.1-2001 broke with
924 * this tradition by permitting hardlink entries to
925 * store valid bodies in pax interchange format, but
926 * not in ustar format. Since there is no hard and
927 * fast way to distinguish pax interchange from
928 * earlier archives (the 'x' and 'g' entries are
929 * optional, after all), we need a heuristic. Here, I
930 * use the bid function to test whether or not there's
931 * a valid header following. Of course, if we know
932 * this is pax interchange format, then we must obey
935 * This heuristic will only fail for a pax interchange
936 * archive that is storing hardlink bodies, no pax
937 * extended attribute entries have yet occurred, and
938 * we encounter a hardlink entry for a file that is
939 * itself an uncompressed tar archive.
941 if (st->st_size > 0 &&
942 a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
943 archive_read_format_tar_bid(a) > 50)
946 case '2': /* Symlink */
947 st->st_mode |= S_IFLNK;
949 archive_entry_set_symlink(entry, tar->entry_linkname.s);
951 case '3': /* Character device */
952 st->st_mode |= S_IFCHR;
955 case '4': /* Block device */
956 st->st_mode |= S_IFBLK;
960 st->st_mode |= S_IFDIR;
963 case '6': /* FIFO device */
964 st->st_mode |= S_IFIFO;
967 case 'D': /* GNU incremental directory type */
969 * No special handling is actually required here.
970 * It might be nice someday to preprocess the file list and
971 * provide it to the client, though.
973 st->st_mode |= S_IFDIR;
975 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
977 * As far as I can tell, this is just like a regular file
978 * entry, except that the contents should be _appended_ to
979 * the indicated file at the indicated offset. This may
980 * require some API work to fully support.
983 case 'N': /* Old GNU "long filename" entry. */
984 /* The body of this entry is a script for renaming
985 * previously-extracted entries. Ugh. It will never
986 * be supported by libarchive. */
987 st->st_mode |= S_IFREG;
989 case 'S': /* GNU sparse files */
991 * Sparse files are really just regular files with
992 * sparse information in the extended area.
995 default: /* Regular file and non-standard types */
997 * Per POSIX: non-recognized types should always be
998 * treated as regular files.
1000 st->st_mode |= S_IFREG;
1007 * Parse out header elements for "old-style" tar archives.
1010 header_old_tar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1011 struct stat *st, const void *h)
1013 const struct archive_entry_header_ustar *header;
1015 /* Copy filename over (to ensure null termination). */
1016 header = (const struct archive_entry_header_ustar *)h;
1017 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1018 archive_entry_set_pathname(entry, tar->entry_name.s);
1020 /* Grab rest of common fields */
1021 header_common(a, tar, entry, st, h);
1023 tar->entry_bytes_remaining = st->st_size;
1024 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1029 * Parse a file header for a pax extended archive entry.
1032 header_pax_global(struct archive_read *a, struct tar *tar,
1033 struct archive_entry *entry, struct stat *st, const void *h)
1037 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1038 err2 = tar_read_header(a, tar, entry, st);
1039 return (err_combine(err, err2));
1043 header_pax_extensions(struct archive_read *a, struct tar *tar,
1044 struct archive_entry *entry, struct stat *st, const void *h)
1048 read_body_to_string(a, tar, &(tar->pax_header), h);
1050 /* Parse the next header. */
1051 err = tar_read_header(a, tar, entry, st);
1054 * TODO: Parse global/default options into 'entry' struct here
1055 * before handling file-specific options.
1057 * This design (parse standard header, then overwrite with pax
1058 * extended attribute data) usually works well, but isn't ideal;
1059 * it would be better to parse the pax extended attributes first
1060 * and then skip any fields in the standard header that were
1061 * defined in the pax header.
1063 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1064 err = err_combine(err, err2);
1065 tar->entry_bytes_remaining = st->st_size;
1066 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1072 * Parse a file header for a Posix "ustar" archive entry. This also
1073 * handles "pax" or "extended ustar" entries.
1076 header_ustar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1077 struct stat *st, const void *h)
1079 const struct archive_entry_header_ustar *header;
1080 struct archive_string *as;
1082 header = (const struct archive_entry_header_ustar *)h;
1084 /* Copy name into an internal buffer to ensure null-termination. */
1085 as = &(tar->entry_name);
1086 if (header->prefix[0]) {
1087 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1088 if (as->s[archive_strlen(as) - 1] != '/')
1089 archive_strappend_char(as, '/');
1090 archive_strncat(as, header->name, sizeof(header->name));
1092 archive_strncpy(as, header->name, sizeof(header->name));
1094 archive_entry_set_pathname(entry, as->s);
1096 /* Handle rest of common fields. */
1097 header_common(a, tar, entry, st, h);
1099 /* Handle POSIX ustar fields. */
1100 archive_strncpy(&(tar->entry_uname), header->uname,
1101 sizeof(header->uname));
1102 archive_entry_set_uname(entry, tar->entry_uname.s);
1104 archive_strncpy(&(tar->entry_gname), header->gname,
1105 sizeof(header->gname));
1106 archive_entry_set_gname(entry, tar->entry_gname.s);
1108 /* Parse out device numbers only for char and block specials. */
1109 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1110 st->st_rdev = makedev(
1111 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1112 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1115 tar->entry_bytes_remaining = st->st_size;
1116 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1123 * Parse the pax extended attributes record.
1125 * Returns non-zero if there's an error in the data.
1128 pax_header(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1129 struct stat *st, char *attr)
1131 size_t attr_length, l, line_length;
1133 wchar_t *key, *wp, *value;
1136 attr_length = strlen(attr);
1138 while (attr_length > 0) {
1139 /* Parse decimal length field at start of line. */
1142 line = p = attr; /* Record start of line. */
1149 if (*p < '0' || *p > '9')
1152 line_length += *p - '0';
1153 if (line_length > 999999) {
1154 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1155 "Rejecting pax extended attribute > 1MB");
1156 return (ARCHIVE_WARN);
1162 if (line_length > attr_length)
1165 /* Ensure pax_entry buffer is big enough. */
1166 if (tar->pax_entry_length <= line_length) {
1167 wchar_t *old_entry = tar->pax_entry;
1169 if (tar->pax_entry_length <= 0)
1170 tar->pax_entry_length = 1024;
1171 while (tar->pax_entry_length <= line_length + 1)
1172 tar->pax_entry_length *= 2;
1174 old_entry = tar->pax_entry;
1175 tar->pax_entry = (wchar_t *)realloc(tar->pax_entry,
1176 tar->pax_entry_length * sizeof(wchar_t));
1177 if (tar->pax_entry == NULL) {
1179 archive_set_error(&a->archive, ENOMEM,
1181 return (ARCHIVE_FATAL);
1185 /* Decode UTF-8 to wchar_t, null-terminate result. */
1186 if (utf8_decode(tar->pax_entry, p,
1187 line_length - (p - attr) - 1)) {
1188 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1189 "Invalid UTF8 character in pax extended attribute");
1190 err = err_combine(err, ARCHIVE_WARN);
1193 /* Null-terminate 'key' value. */
1194 wp = key = tar->pax_entry;
1197 while (*wp && *wp != L'=')
1199 if (*wp == L'\0' || wp == NULL) {
1200 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1201 "Invalid pax extended attributes");
1202 return (ARCHIVE_WARN);
1206 /* Identify null-terminated 'value' portion. */
1209 /* Identify this attribute and set it in the entry. */
1210 err2 = pax_attribute(entry, st, key, value);
1211 err = err_combine(err, err2);
1213 /* Skip to next line */
1214 attr += line_length;
1215 attr_length -= line_length;
1221 pax_attribute_xattr(struct archive_entry *entry,
1222 wchar_t *name, wchar_t *value)
1224 char *name_decoded, *name_narrow;
1225 void *value_decoded;
1228 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1233 /* URL-decode name */
1234 name_narrow = wide_to_narrow(name);
1235 if (name_narrow == NULL)
1237 name_decoded = url_decode(name_narrow);
1239 if (name_decoded == NULL)
1242 /* Base-64 decode value */
1243 value_decoded = base64_decode(value, wcslen(value), &value_len);
1244 if (value_decoded == NULL) {
1249 archive_entry_xattr_add_entry(entry, name_decoded,
1250 value_decoded, value_len);
1253 free(value_decoded);
1258 * Parse a single key=value attribute. key/value pointers are
1259 * assumed to point into reasonably long-lived storage.
1261 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1262 * extensions should always have keywords of the form "VENDOR.attribute"
1263 * In particular, it's quite feasible to support many different
1264 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1265 * unique to this library (currently, there are none).
1267 * Investigate other vendor-specific extensions, as well and see if
1268 * any of them look useful.
1271 pax_attribute(struct archive_entry *entry, struct stat *st,
1272 wchar_t *key, wchar_t *value)
1279 /* Our extensions */
1280 /* TODO: Handle arbitrary extended attributes... */
1282 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1283 archive_entry_set_xxxxxx(entry, value);
1285 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1286 pax_attribute_xattr(entry, key, value);
1289 /* We support some keys used by the "star" archiver */
1290 if (wcscmp(key, L"SCHILY.acl.access")==0)
1291 __archive_entry_acl_parse_w(entry, value,
1292 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1293 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1294 __archive_entry_acl_parse_w(entry, value,
1295 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1296 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1297 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1298 minor(st->st_rdev));
1299 else if (wcscmp(key, L"SCHILY.devminor")==0)
1300 st->st_rdev = makedev(major(st->st_rdev),
1301 tar_atol10(value, wcslen(value)));
1302 else if (wcscmp(key, L"SCHILY.fflags")==0)
1303 archive_entry_copy_fflags_text_w(entry, value);
1304 else if (wcscmp(key, L"SCHILY.nlink")==0)
1305 st->st_nlink = tar_atol10(value, wcslen(value));
1308 if (wcscmp(key, L"atime")==0) {
1309 pax_time(value, &s, &n);
1311 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1315 if (wcscmp(key, L"ctime")==0) {
1316 pax_time(value, &s, &n);
1318 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1319 } else if (wcscmp(key, L"charset")==0) {
1320 /* TODO: Publish charset information in entry. */
1321 } else if (wcscmp(key, L"comment")==0) {
1322 /* TODO: Publish comment in entry. */
1326 if (wcscmp(key, L"gid")==0)
1327 st->st_gid = tar_atol10(value, wcslen(value));
1328 else if (wcscmp(key, L"gname")==0)
1329 archive_entry_copy_gname_w(entry, value);
1332 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1333 if (wcscmp(key, L"linkpath")==0) {
1334 if (archive_entry_hardlink(entry))
1335 archive_entry_copy_hardlink_w(entry, value);
1337 archive_entry_copy_symlink_w(entry, value);
1341 if (wcscmp(key, L"mtime")==0) {
1342 pax_time(value, &s, &n);
1344 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1348 if (wcscmp(key, L"path")==0)
1349 archive_entry_copy_pathname_w(entry, value);
1352 /* POSIX has reserved 'realtime.*' */
1355 /* POSIX has reserved 'security.*' */
1356 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1357 if (wcscmp(key, L"size")==0)
1358 st->st_size = tar_atol10(value, wcslen(value));
1361 if (wcscmp(key, L"uid")==0)
1362 st->st_uid = tar_atol10(value, wcslen(value));
1363 else if (wcscmp(key, L"uname")==0)
1364 archive_entry_copy_uname_w(entry, value);
1373 * parse a decimal time value, which may include a fractional portion
1376 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1382 int64_t limit, last_digit_limit;
1384 limit = max_int64 / 10;
1385 last_digit_limit = max_int64 % 10;
1393 while (*p >= '0' && *p <= '9') {
1396 (s == limit && digit > last_digit_limit)) {
1400 s = (s * 10) + digit;
1406 /* Calculate nanoseconds. */
1415 if (*p >= '0' && *p <= '9')
1416 *pn += (*p - '0') * l;
1423 * Parse GNU tar header
1426 header_gnutar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1427 struct stat *st, const void *h)
1429 const struct archive_entry_header_gnutar *header;
1434 * GNU header is like POSIX ustar, except 'prefix' is
1435 * replaced with some other fields. This also means the
1436 * filename is stored as in old-style archives.
1439 /* Grab fields common to all tar variants. */
1440 header_common(a, tar, entry, st, h);
1442 /* Copy filename over (to ensure null termination). */
1443 header = (const struct archive_entry_header_gnutar *)h;
1444 archive_strncpy(&(tar->entry_name), header->name,
1445 sizeof(header->name));
1446 archive_entry_set_pathname(entry, tar->entry_name.s);
1448 /* Fields common to ustar and GNU */
1449 /* XXX Can the following be factored out since it's common
1450 * to ustar and gnu tar? Is it okay to move it down into
1451 * header_common, perhaps? */
1452 archive_strncpy(&(tar->entry_uname),
1453 header->uname, sizeof(header->uname));
1454 archive_entry_set_uname(entry, tar->entry_uname.s);
1456 archive_strncpy(&(tar->entry_gname),
1457 header->gname, sizeof(header->gname));
1458 archive_entry_set_gname(entry, tar->entry_gname.s);
1460 /* Parse out device numbers only for char and block specials */
1461 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1462 st->st_rdev = makedev (
1463 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1464 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1468 tar->entry_bytes_remaining = st->st_size;
1469 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1471 /* Grab GNU-specific fields. */
1472 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1473 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1474 if (header->realsize[0] != 0) {
1475 st->st_size = tar_atol(header->realsize,
1476 sizeof(header->realsize));
1479 if (header->sparse[0].offset[0] != 0) {
1480 gnu_read_sparse_data(a, tar, header);
1482 if (header->isextended[0] != 0) {
1491 gnu_read_sparse_data(struct archive_read *a, struct tar *tar,
1492 const struct archive_entry_header_gnutar *header)
1497 struct gnu_sparse sparse[21];
1501 const struct extended *ext;
1503 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1504 if (header->isextended[0] == 0)
1505 return (ARCHIVE_OK);
1508 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1510 return (ARCHIVE_FATAL);
1511 if (bytes_read < 512) {
1512 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1513 "Truncated tar archive "
1514 "detected while reading sparse file data");
1515 return (ARCHIVE_FATAL);
1517 (a->compression_read_consume)(a, 512);
1518 ext = (const struct extended *)data;
1519 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1520 } while (ext->isextended[0] != 0);
1521 if (tar->sparse_list != NULL)
1522 tar->entry_offset = tar->sparse_list->offset;
1523 return (ARCHIVE_OK);
1527 gnu_parse_sparse_data(struct archive_read *a, struct tar *tar,
1528 const struct gnu_sparse *sparse, int length)
1530 struct sparse_block *last;
1531 struct sparse_block *p;
1533 (void)a; /* UNUSED */
1535 last = tar->sparse_list;
1536 while (last != NULL && last->next != NULL)
1539 while (length > 0 && sparse->offset[0] != 0) {
1540 p = (struct sparse_block *)malloc(sizeof(*p));
1542 __archive_errx(1, "Out of memory");
1543 memset(p, 0, sizeof(*p));
1547 tar->sparse_list = p;
1549 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1551 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1558 * Convert text->integer.
1560 * Traditional tar formats (including POSIX) specify base-8 for
1561 * all of the standard numeric fields. This is a significant limitation
1563 * = file size is limited to 8GB
1564 * = rdevmajor and rdevminor are limited to 21 bits
1565 * = uid/gid are limited to 21 bits
1567 * There are two workarounds for this:
1568 * = pax extended headers, which use variable-length string fields
1569 * = GNU tar and STAR both allow either base-8 or base-256 in
1570 * most fields. The high bit is set to indicate base-256.
1572 * On read, this implementation supports both extensions.
1575 tar_atol(const char *p, unsigned char_cnt)
1578 * Technically, GNU tar considers a field to be in base-256
1579 * only if the first byte is 0xff or 0x80.
1582 return (tar_atol256(p, char_cnt));
1583 return (tar_atol8(p, char_cnt));
1587 * Note that this implementation does not (and should not!) obey
1588 * locale settings; you cannot simply substitute strtol here, since
1589 * it does obey locale.
1592 tar_atol8(const char *p, unsigned char_cnt)
1594 int64_t l, limit, last_digit_limit;
1595 int digit, sign, base;
1598 limit = max_int64 / base;
1599 last_digit_limit = max_int64 % base;
1601 while (*p == ' ' || *p == '\t')
1611 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1612 if (l>limit || (l == limit && digit > last_digit_limit)) {
1613 l = max_uint64; /* Truncate on overflow. */
1616 l = (l * base) + digit;
1619 return (sign < 0) ? -l : l;
1624 * Note that this implementation does not (and should not!) obey
1625 * locale settings; you cannot simply substitute strtol here, since
1626 * it does obey locale.
1629 tar_atol10(const wchar_t *p, unsigned char_cnt)
1631 int64_t l, limit, last_digit_limit;
1632 int base, digit, sign;
1635 limit = max_int64 / base;
1636 last_digit_limit = max_int64 % base;
1638 while (*p == ' ' || *p == '\t')
1648 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1649 if (l > limit || (l == limit && digit > last_digit_limit)) {
1650 l = max_uint64; /* Truncate on overflow. */
1653 l = (l * base) + digit;
1656 return (sign < 0) ? -l : l;
1660 * Parse a base-256 integer. This is just a straight signed binary
1661 * value in big-endian order, except that the high-order bit is
1662 * ignored. Remember that "int64_t" may or may not be exactly 64
1663 * bits; the implementation here tries to avoid making any assumptions
1664 * about the actual size of an int64_t. It does assume we're using
1665 * twos-complement arithmetic, though.
1668 tar_atol256(const char *_p, unsigned char_cnt)
1670 int64_t l, upper_limit, lower_limit;
1671 const unsigned char *p = (const unsigned char *)_p;
1673 upper_limit = max_int64 / 256;
1674 lower_limit = min_int64 / 256;
1676 /* Pad with 1 or 0 bits, depending on sign. */
1677 if ((0x40 & *p) == 0x40)
1681 l = (l << 6) | (0x3f & *p++);
1682 while (--char_cnt > 0) {
1683 if (l > upper_limit) {
1684 l = max_int64; /* Truncate on overflow */
1686 } else if (l < lower_limit) {
1690 l = (l << 8) | (0xff & (int64_t)*p++);
1696 utf8_decode(wchar_t *dest, const char *src, size_t length)
1702 while (length > 0) {
1703 n = UTF8_mbrtowc(dest, src, length);
1715 * Copied and simplified from FreeBSD libc/locale.
1718 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1720 int ch, i, len, mask;
1723 if (s == NULL || n == 0 || pwc == NULL)
1727 * Determine the number of octets that make up this character from
1728 * the first octet, and a mask that extracts the interesting bits of
1731 ch = (unsigned char)*s;
1732 if ((ch & 0x80) == 0) {
1735 } else if ((ch & 0xe0) == 0xc0) {
1738 } else if ((ch & 0xf0) == 0xe0) {
1741 } else if ((ch & 0xf8) == 0xf0) {
1744 } else if ((ch & 0xfc) == 0xf8) {
1747 } else if ((ch & 0xfe) == 0xfc) {
1751 /* Invalid first byte; convert to '?' */
1756 if (n < (size_t)len) {
1757 /* Invalid first byte; convert to '?' */
1763 * Decode the octet sequence representing the character in chunks
1764 * of 6 bits, most significant first.
1766 wch = (unsigned char)*s++ & mask;
1769 if ((*s & 0xc0) != 0x80) {
1770 /* Invalid intermediate byte; consume one byte and
1779 /* Assign the value to the output; out-of-range values
1780 * just get truncated. */
1781 *pwc = (wchar_t)wch;
1784 * If platform has WCHAR_MAX, we can do something
1785 * more sensible with out-of-range values.
1787 if (wch >= WCHAR_MAX)
1790 /* Return number of bytes input consumed: 0 for end-of-string. */
1791 return (wch == L'\0' ? 0 : len);
1796 * base64_decode - Base64 decode
1798 * This accepts most variations of base-64 encoding, including:
1799 * * with or without line breaks
1800 * * with or without the final group padded with '=' or '_' characters
1801 * (The most economical Base-64 variant does not pad the last group and
1802 * omits line breaks; RFC1341 used for MIME requires both.)
1805 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1807 static const unsigned char digits[64] = {
1808 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
1809 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
1810 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
1811 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
1812 '4','5','6','7','8','9','+','/' };
1813 static unsigned char decode_table[128];
1816 /* If the decode table is not yet initialized, prepare it. */
1817 if (decode_table[digits[1]] != 1) {
1819 memset(decode_table, 0xff, sizeof(decode_table));
1820 for (i = 0; i < sizeof(digits); i++)
1821 decode_table[digits[i]] = i;
1824 /* Allocate enough space to hold the entire output. */
1825 /* Note that we may not use all of this... */
1826 out = (char *)malloc((len * 3 + 3) / 4);
1834 /* Collect the next group of (up to) four characters. */
1837 while (group_size < 4 && len > 0) {
1838 /* '=' or '_' padding indicates final group. */
1839 if (*src == '=' || *src == '_') {
1843 /* Skip illegal characters (including line breaks) */
1844 if (*src > 127 || *src < 32
1845 || decode_table[*src] == 0xff) {
1851 v |= decode_table[*src++];
1855 /* Align a short group properly. */
1856 v <<= 6 * (4 - group_size);
1857 /* Unpack the group we just collected. */
1858 switch (group_size) {
1859 case 4: d[2] = v & 0xff;
1861 case 3: d[1] = (v >> 8) & 0xff;
1863 case 2: d[0] = (v >> 16) & 0xff;
1865 case 1: /* this is invalid! */
1868 d += group_size * 3 / 4;
1876 * This is a little tricky because the C99 standard wcstombs()
1877 * function returns the number of bytes that were converted,
1878 * not the number that should be converted. As a result,
1879 * we can never accurately size the output buffer (without
1880 * doing a tedious output size calculation in advance).
1881 * This approach (try a conversion, then try again if it fails)
1882 * will almost always succeed on the first try, and is thus
1883 * much faster, at the cost of sometimes requiring multiple
1884 * passes while we expand the buffer.
1887 wide_to_narrow(const wchar_t *wval)
1889 int converted_length;
1890 /* Guess an output buffer size and try the conversion. */
1891 int alloc_length = wcslen(wval) * 3;
1892 char *mbs_val = (char *)malloc(alloc_length + 1);
1893 if (mbs_val == NULL)
1895 converted_length = wcstombs(mbs_val, wval, alloc_length);
1897 /* If we exhausted the buffer, resize and try again. */
1898 while (converted_length >= alloc_length) {
1901 mbs_val = (char *)malloc(alloc_length + 1);
1902 if (mbs_val == NULL)
1904 converted_length = wcstombs(mbs_val, wval, alloc_length);
1907 /* Ensure a trailing null and return the final string. */
1908 mbs_val[alloc_length] = '\0';
1913 url_decode(const char *in)
1918 out = (char *)malloc(strlen(in) + 1);
1921 for (s = in, d = out; *s != '\0'; ) {
1923 /* Try to convert % escape */
1924 int digit1 = tohex(s[1]);
1925 int digit2 = tohex(s[2]);
1926 if (digit1 >= 0 && digit2 >= 0) {
1927 /* Looks good, consume three chars */
1929 /* Convert output */
1930 *d++ = ((digit1 << 4) | digit2);
1933 /* Else fall through and treat '%' as normal char */
1944 if (c >= '0' && c <= '9')
1946 else if (c >= 'A' && c <= 'F')
1947 return (c - 'A' + 10);
1948 else if (c >= 'a' && c <= 'f')
1949 return (c - 'a' + 10);