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$");
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 archive_read_support_format_gnutar(struct archive *a)
231 return (archive_read_support_format_tar(a));
236 archive_read_support_format_tar(struct archive *_a)
238 struct archive_read *a = (struct archive_read *)_a;
242 tar = (struct tar *)malloc(sizeof(*tar));
244 archive_set_error(&a->archive, ENOMEM,
245 "Can't allocate tar data");
246 return (ARCHIVE_FATAL);
248 memset(tar, 0, sizeof(*tar));
250 r = __archive_read_register_format(a, tar,
251 archive_read_format_tar_bid,
252 archive_read_format_tar_read_header,
253 archive_read_format_tar_read_data,
254 archive_read_format_tar_skip,
255 archive_read_format_tar_cleanup);
263 archive_read_format_tar_cleanup(struct archive_read *a)
267 tar = (struct tar *)*(a->pformat_data);
268 archive_string_free(&tar->acl_text);
269 archive_string_free(&tar->entry_name);
270 archive_string_free(&tar->entry_linkname);
271 archive_string_free(&tar->entry_uname);
272 archive_string_free(&tar->entry_gname);
273 archive_string_free(&tar->pax_global);
274 archive_string_free(&tar->pax_header);
275 if (tar->pax_entry != NULL)
276 free(tar->pax_entry);
278 *(a->pformat_data) = NULL;
284 archive_read_format_tar_bid(struct archive_read *a)
289 const struct archive_entry_header_ustar *header;
292 * If we're already reading a non-tar file, don't
295 if (a->archive.archive_format != 0 &&
296 (a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
302 * If we're already reading a tar format, start the bid at 1 as
305 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
309 /* Now let's look at the actual header and see if it matches. */
310 if (a->compression_read_ahead != NULL)
311 bytes_read = (a->compression_read_ahead)(a, &h, 512);
313 bytes_read = 0; /* Empty file. */
315 return (ARCHIVE_FATAL);
316 if (bytes_read == 0 && bid > 0) {
317 /* An archive without a proper end-of-archive marker. */
318 /* Hold our nose and bid 1 anyway. */
321 if (bytes_read < 512) {
322 /* If it's a new archive, then just return a zero bid. */
326 * If we already know this is a tar archive,
327 * then we have a problem.
329 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
330 "Truncated tar archive");
331 return (ARCHIVE_FATAL);
334 /* If it's an end-of-archive mark, we can handle it. */
335 if ((*(const char *)h) == 0 && archive_block_is_null((const unsigned char *)h)) {
336 /* If it's a known tar file, end-of-archive is definite. */
337 if ((a->archive.archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
344 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
347 bid += 48; /* Checksum is usually 6 octal digits. */
349 header = (const struct archive_entry_header_ustar *)h;
351 /* Recognize POSIX formats. */
352 if ((memcmp(header->magic, "ustar\0", 6) == 0)
353 &&(memcmp(header->version, "00", 2)==0))
356 /* Recognize GNU tar format. */
357 if ((memcmp(header->magic, "ustar ", 6) == 0)
358 &&(memcmp(header->version, " \0", 2)==0))
361 /* Type flag must be null, digit or A-Z, a-z. */
362 if (header->typeflag[0] != 0 &&
363 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
364 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
365 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
367 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
369 /* Sanity check: Look at first byte of mode field. */
370 switch (255 & (unsigned)header->mode[0]) {
372 /* Base-256 value: No further verification possible! */
374 case ' ': /* Not recommended, but not illegal, either. */
376 case '0': case '1': case '2': case '3':
377 case '4': case '5': case '6': case '7':
379 /* TODO: Check format of remainder of this field. */
382 /* Not a valid mode; bail out here. */
385 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
391 * The function invoked by archive_read_header(). This
392 * just sets up a few things and then calls the internal
393 * tar_read_header() function below.
396 archive_read_format_tar_read_header(struct archive_read *a,
397 struct archive_entry *entry)
400 * When converting tar archives to cpio archives, it is
401 * essential that each distinct file have a distinct inode
402 * number. To simplify this, we keep a static count here to
403 * assign fake dev/inode numbers to each tar entry. Note that
404 * pax format archives may overwrite this with something more
407 * Ideally, we would track every file read from the archive so
408 * that we could assign the same dev/ino pair to hardlinks,
409 * but the memory required to store a complete lookup table is
410 * probably not worthwhile just to support the relatively
411 * obscure tar->cpio conversion case.
413 static int default_inode;
414 static int default_dev;
421 memset(&st, 0, sizeof(st));
422 /* Assign default device/inode values. */
423 st.st_dev = 1 + default_dev; /* Don't use zero. */
424 st.st_ino = ++default_inode; /* Don't use zero. */
425 /* Limit generated st_ino number to 16 bits. */
426 if (default_inode >= 0xffff) {
431 tar = (struct tar *)*(a->pformat_data);
432 tar->entry_offset = 0;
434 r = tar_read_header(a, tar, entry, &st);
436 if (r == ARCHIVE_OK) {
438 * "Regular" entry with trailing '/' is really
439 * directory: This is needed for certain old tar
440 * variants and even for some broken newer ones.
442 p = archive_entry_pathname(entry);
444 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
445 st.st_mode &= ~S_IFMT;
446 st.st_mode |= S_IFDIR;
449 /* Copy the final stat data into the entry. */
450 archive_entry_copy_stat(entry, &st);
456 archive_read_format_tar_read_data(struct archive_read *a,
457 const void **buff, size_t *size, off_t *offset)
461 struct sparse_block *p;
463 tar = (struct tar *)*(a->pformat_data);
464 if (tar->sparse_list != NULL) {
465 /* Remove exhausted entries from sparse list. */
466 while (tar->sparse_list != NULL &&
467 tar->sparse_list->remaining == 0) {
468 p = tar->sparse_list;
469 tar->sparse_list = p->next;
472 if (tar->sparse_list == NULL) {
473 /* We exhausted the entire sparse list. */
474 tar->entry_bytes_remaining = 0;
478 if (tar->entry_bytes_remaining > 0) {
479 bytes_read = (a->compression_read_ahead)(a, buff, 1);
480 if (bytes_read == 0) {
481 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
482 "Truncated tar archive");
483 return (ARCHIVE_FATAL);
486 return (ARCHIVE_FATAL);
487 if (bytes_read > tar->entry_bytes_remaining)
488 bytes_read = tar->entry_bytes_remaining;
489 if (tar->sparse_list != NULL) {
490 /* Don't read more than is available in the
491 * current sparse block. */
492 if (tar->sparse_list->remaining < bytes_read)
493 bytes_read = tar->sparse_list->remaining;
494 tar->entry_offset = tar->sparse_list->offset;
495 tar->sparse_list->remaining -= bytes_read;
496 tar->sparse_list->offset += bytes_read;
499 *offset = tar->entry_offset;
500 tar->entry_offset += bytes_read;
501 tar->entry_bytes_remaining -= bytes_read;
502 (a->compression_read_consume)(a, bytes_read);
505 if ((a->compression_skip)(a, tar->entry_padding) < 0)
506 return (ARCHIVE_FATAL);
507 tar->entry_padding = 0;
510 *offset = tar->entry_offset;
511 return (ARCHIVE_EOF);
516 archive_read_format_tar_skip(struct archive_read *a)
520 struct sparse_block *p;
522 tar = (struct tar *)*(a->pformat_data);
525 * Compression layer skip functions are required to either skip the
526 * length requested or fail, so we can rely upon the entire entry
527 * plus padding being skipped.
529 bytes_skipped = (a->compression_skip)(a, tar->entry_bytes_remaining +
531 if (bytes_skipped < 0)
532 return (ARCHIVE_FATAL);
534 tar->entry_bytes_remaining = 0;
535 tar->entry_padding = 0;
537 /* Free the sparse list. */
538 while (tar->sparse_list != NULL) {
539 p = tar->sparse_list;
540 tar->sparse_list = p->next;
548 * This function recursively interprets all of the headers associated
549 * with a single entry.
552 tar_read_header(struct archive_read *a, struct tar *tar,
553 struct archive_entry *entry, struct stat *st)
558 const struct archive_entry_header_ustar *header;
560 /* Read 512-byte header record */
561 bytes = (a->compression_read_ahead)(a, &h, 512);
564 * If we're here, it's becase the _bid function accepted
565 * this file. So just call a short read end-of-archive
566 * and be done with it.
568 return (ARCHIVE_EOF);
570 (a->compression_read_consume)(a, 512);
572 /* Check for end-of-archive mark. */
573 if (((*(const char *)h)==0) && archive_block_is_null((const unsigned char *)h)) {
574 /* Try to consume a second all-null record, as well. */
575 bytes = (a->compression_read_ahead)(a, &h, 512);
577 (a->compression_read_consume)(a, bytes);
578 archive_set_error(&a->archive, 0, NULL);
579 return (ARCHIVE_EOF);
583 * Note: If the checksum fails and we return ARCHIVE_RETRY,
584 * then the client is likely to just retry. This is a very
585 * crude way to search for the next valid header!
587 * TODO: Improve this by implementing a real header scan.
589 if (!checksum(a, h)) {
590 archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
591 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
594 if (++tar->header_recursion_depth > 32) {
595 archive_set_error(&a->archive, EINVAL, "Too many special headers");
596 return (ARCHIVE_WARN);
599 /* Determine the format variant. */
600 header = (const struct archive_entry_header_ustar *)h;
601 switch(header->typeflag[0]) {
602 case 'A': /* Solaris tar ACL */
603 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
604 a->archive.archive_format_name = "Solaris tar";
605 err = header_Solaris_ACL(a, tar, entry, st, h);
607 case 'g': /* POSIX-standard 'g' header. */
608 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
609 a->archive.archive_format_name = "POSIX pax interchange format";
610 err = header_pax_global(a, tar, entry, st, h);
612 case 'K': /* Long link name (GNU tar, others) */
613 err = header_longlink(a, tar, entry, st, h);
615 case 'L': /* Long filename (GNU tar, others) */
616 err = header_longname(a, tar, entry, st, h);
618 case 'V': /* GNU volume header */
619 err = header_volume(a, tar, entry, st, h);
621 case 'X': /* Used by SUN tar; same as 'x'. */
622 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
623 a->archive.archive_format_name =
624 "POSIX pax interchange format (Sun variant)";
625 err = header_pax_extensions(a, tar, entry, st, h);
627 case 'x': /* POSIX-standard 'x' header. */
628 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
629 a->archive.archive_format_name = "POSIX pax interchange format";
630 err = header_pax_extensions(a, tar, entry, st, h);
633 if (memcmp(header->magic, "ustar \0", 8) == 0) {
634 a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
635 a->archive.archive_format_name = "GNU tar format";
636 err = header_gnutar(a, tar, entry, st, h);
637 } else if (memcmp(header->magic, "ustar", 5) == 0) {
638 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
639 a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
640 a->archive.archive_format_name = "POSIX ustar format";
642 err = header_ustar(a, tar, entry, st, h);
644 a->archive.archive_format = ARCHIVE_FORMAT_TAR;
645 a->archive.archive_format_name = "tar (non-POSIX)";
646 err = header_old_tar(a, tar, entry, st, h);
649 --tar->header_recursion_depth;
654 * Return true if block checksum is correct.
657 checksum(struct archive_read *a, const void *h)
659 const unsigned char *bytes;
660 const struct archive_entry_header_ustar *header;
663 (void)a; /* UNUSED */
664 bytes = (const unsigned char *)h;
665 header = (const struct archive_entry_header_ustar *)h;
668 * Test the checksum. Note that POSIX specifies _unsigned_
669 * bytes for this calculation.
671 sum = tar_atol(header->checksum, sizeof(header->checksum));
673 for (i = 0; i < 148; i++)
674 check += (unsigned char)bytes[i];
678 check += (unsigned char)bytes[i];
683 * Repeat test with _signed_ bytes, just in case this archive
684 * was created by an old BSD, Solaris, or HP-UX tar with a
685 * broken checksum calculation.
688 for (i = 0; i < 148; i++)
689 check += (signed char)bytes[i];
693 check += (signed char)bytes[i];
701 * Return true if this block contains only nulls.
704 archive_block_is_null(const unsigned char *p)
708 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
715 * Interpret 'A' Solaris ACL header
718 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
719 struct archive_entry *entry, struct stat *st, const void *h)
725 err = read_body_to_string(a, tar, &(tar->acl_text), h);
726 err2 = tar_read_header(a, tar, entry, st);
727 err = err_combine(err, err2);
729 /* XXX Ensure p doesn't overrun acl_text */
731 /* Skip leading octal number. */
732 /* XXX TODO: Parse the octal number and sanity-check it. */
738 wp = (wchar_t *)malloc((strlen(p) + 1) * sizeof(wchar_t));
740 utf8_decode(wp, p, strlen(p));
741 err2 = __archive_entry_acl_parse_w(entry, wp,
742 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
743 err = err_combine(err, err2);
751 * Interpret 'K' long linkname header.
754 header_longlink(struct archive_read *a, struct tar *tar,
755 struct archive_entry *entry, struct stat *st, const void *h)
759 err = read_body_to_string(a, tar, &(tar->longlink), h);
760 err2 = tar_read_header(a, tar, entry, st);
761 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
762 /* Set symlink if symlink already set, else hardlink. */
763 archive_entry_set_link(entry, tar->longlink.s);
765 return (err_combine(err, err2));
769 * Interpret 'L' long filename header.
772 header_longname(struct archive_read *a, struct tar *tar,
773 struct archive_entry *entry, struct stat *st, const void *h)
777 err = read_body_to_string(a, tar, &(tar->longname), h);
778 /* Read and parse "real" header, then override name. */
779 err2 = tar_read_header(a, tar, entry, st);
780 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
781 archive_entry_set_pathname(entry, tar->longname.s);
782 return (err_combine(err, err2));
787 * Interpret 'V' GNU tar volume header.
790 header_volume(struct archive_read *a, struct tar *tar,
791 struct archive_entry *entry, struct stat *st, const void *h)
795 /* Just skip this and read the next header. */
796 return (tar_read_header(a, tar, entry, st));
800 * Read body of an archive entry into an archive_string object.
803 read_body_to_string(struct archive_read *a, struct tar *tar,
804 struct archive_string *as, const void *h)
806 off_t size, padded_size;
807 ssize_t bytes_read, bytes_to_copy;
808 const struct archive_entry_header_ustar *header;
812 (void)tar; /* UNUSED */
813 header = (const struct archive_entry_header_ustar *)h;
814 size = tar_atol(header->size, sizeof(header->size));
816 /* Read the body into the string. */
817 archive_string_ensure(as, size+1);
818 padded_size = (size + 511) & ~ 511;
820 while (padded_size > 0) {
821 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
823 return (ARCHIVE_FATAL);
824 if (bytes_read > padded_size)
825 bytes_read = padded_size;
826 (a->compression_read_consume)(a, bytes_read);
827 bytes_to_copy = bytes_read;
828 if ((off_t)bytes_to_copy > size)
829 bytes_to_copy = (ssize_t)size;
830 memcpy(dest, src, bytes_to_copy);
831 dest += bytes_to_copy;
832 size -= bytes_to_copy;
833 padded_size -= bytes_read;
840 * Parse out common header elements.
842 * This would be the same as header_old_tar, except that the
843 * filename is handled slightly differently for old and POSIX
844 * entries (POSIX entries support a 'prefix'). This factoring
845 * allows header_old_tar and header_ustar
846 * to handle filenames differently, while still putting most of the
847 * common parsing into one place.
850 header_common(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
851 struct stat *st, const void *h)
853 const struct archive_entry_header_ustar *header;
856 (void)a; /* UNUSED */
858 header = (const struct archive_entry_header_ustar *)h;
859 if (header->linkname[0])
860 archive_strncpy(&(tar->entry_linkname), header->linkname,
861 sizeof(header->linkname));
863 archive_string_empty(&(tar->entry_linkname));
865 /* Parse out the numeric fields (all are octal) */
866 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
867 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
868 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
869 st->st_size = tar_atol(header->size, sizeof(header->size));
870 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
872 /* Handle the tar type flag appropriately. */
873 tartype = header->typeflag[0];
874 st->st_mode &= ~S_IFMT;
877 case '1': /* Hard link */
878 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
880 * The following may seem odd, but: Technically, tar
881 * does not store the file type for a "hard link"
882 * entry, only the fact that it is a hard link. So, I
883 * leave the type zero normally. But, pax interchange
884 * format allows hard links to have data, which
885 * implies that the underlying entry is a regular
889 st->st_mode |= S_IFREG;
892 * A tricky point: Traditionally, tar readers have
893 * ignored the size field when reading hardlink
894 * entries, and some writers put non-zero sizes even
895 * though the body is empty. POSIX.1-2001 broke with
896 * this tradition by permitting hardlink entries to
897 * store valid bodies in pax interchange format, but
898 * not in ustar format. Since there is no hard and
899 * fast way to distinguish pax interchange from
900 * earlier archives (the 'x' and 'g' entries are
901 * optional, after all), we need a heuristic. Here, I
902 * use the bid function to test whether or not there's
903 * a valid header following. Of course, if we know
904 * this is pax interchange format, then we must obey
907 * This heuristic will only fail for a pax interchange
908 * archive that is storing hardlink bodies, no pax
909 * extended attribute entries have yet occurred, and
910 * we encounter a hardlink entry for a file that is
911 * itself an uncompressed tar archive.
913 if (st->st_size > 0 &&
914 a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
915 archive_read_format_tar_bid(a) > 50)
918 case '2': /* Symlink */
919 st->st_mode |= S_IFLNK;
921 archive_entry_set_symlink(entry, tar->entry_linkname.s);
923 case '3': /* Character device */
924 st->st_mode |= S_IFCHR;
927 case '4': /* Block device */
928 st->st_mode |= S_IFBLK;
932 st->st_mode |= S_IFDIR;
935 case '6': /* FIFO device */
936 st->st_mode |= S_IFIFO;
939 case 'D': /* GNU incremental directory type */
941 * No special handling is actually required here.
942 * It might be nice someday to preprocess the file list and
943 * provide it to the client, though.
945 st->st_mode |= S_IFDIR;
947 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
949 * As far as I can tell, this is just like a regular file
950 * entry, except that the contents should be _appended_ to
951 * the indicated file at the indicated offset. This may
952 * require some API work to fully support.
955 case 'N': /* Old GNU "long filename" entry. */
956 /* The body of this entry is a script for renaming
957 * previously-extracted entries. Ugh. It will never
958 * be supported by libarchive. */
959 st->st_mode |= S_IFREG;
961 case 'S': /* GNU sparse files */
963 * Sparse files are really just regular files with
964 * sparse information in the extended area.
967 default: /* Regular file and non-standard types */
969 * Per POSIX: non-recognized types should always be
970 * treated as regular files.
972 st->st_mode |= S_IFREG;
979 * Parse out header elements for "old-style" tar archives.
982 header_old_tar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
983 struct stat *st, const void *h)
985 const struct archive_entry_header_ustar *header;
987 /* Copy filename over (to ensure null termination). */
988 header = (const struct archive_entry_header_ustar *)h;
989 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
990 archive_entry_set_pathname(entry, tar->entry_name.s);
992 /* Grab rest of common fields */
993 header_common(a, tar, entry, st, h);
995 tar->entry_bytes_remaining = st->st_size;
996 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1001 * Parse a file header for a pax extended archive entry.
1004 header_pax_global(struct archive_read *a, struct tar *tar,
1005 struct archive_entry *entry, struct stat *st, const void *h)
1009 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1010 err2 = tar_read_header(a, tar, entry, st);
1011 return (err_combine(err, err2));
1015 header_pax_extensions(struct archive_read *a, struct tar *tar,
1016 struct archive_entry *entry, struct stat *st, const void *h)
1020 read_body_to_string(a, tar, &(tar->pax_header), h);
1022 /* Parse the next header. */
1023 err = tar_read_header(a, tar, entry, st);
1026 * TODO: Parse global/default options into 'entry' struct here
1027 * before handling file-specific options.
1029 * This design (parse standard header, then overwrite with pax
1030 * extended attribute data) usually works well, but isn't ideal;
1031 * it would be better to parse the pax extended attributes first
1032 * and then skip any fields in the standard header that were
1033 * defined in the pax header.
1035 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1036 err = err_combine(err, err2);
1037 tar->entry_bytes_remaining = st->st_size;
1038 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1044 * Parse a file header for a Posix "ustar" archive entry. This also
1045 * handles "pax" or "extended ustar" entries.
1048 header_ustar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1049 struct stat *st, const void *h)
1051 const struct archive_entry_header_ustar *header;
1052 struct archive_string *as;
1054 header = (const struct archive_entry_header_ustar *)h;
1056 /* Copy name into an internal buffer to ensure null-termination. */
1057 as = &(tar->entry_name);
1058 if (header->prefix[0]) {
1059 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1060 if (as->s[archive_strlen(as) - 1] != '/')
1061 archive_strappend_char(as, '/');
1062 archive_strncat(as, header->name, sizeof(header->name));
1064 archive_strncpy(as, header->name, sizeof(header->name));
1066 archive_entry_set_pathname(entry, as->s);
1068 /* Handle rest of common fields. */
1069 header_common(a, tar, entry, st, h);
1071 /* Handle POSIX ustar fields. */
1072 archive_strncpy(&(tar->entry_uname), header->uname,
1073 sizeof(header->uname));
1074 archive_entry_set_uname(entry, tar->entry_uname.s);
1076 archive_strncpy(&(tar->entry_gname), header->gname,
1077 sizeof(header->gname));
1078 archive_entry_set_gname(entry, tar->entry_gname.s);
1080 /* Parse out device numbers only for char and block specials. */
1081 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1082 st->st_rdev = makedev(
1083 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1084 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1087 tar->entry_bytes_remaining = st->st_size;
1088 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1095 * Parse the pax extended attributes record.
1097 * Returns non-zero if there's an error in the data.
1100 pax_header(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1101 struct stat *st, char *attr)
1103 size_t attr_length, l, line_length;
1105 wchar_t *key, *wp, *value;
1108 attr_length = strlen(attr);
1110 while (attr_length > 0) {
1111 /* Parse decimal length field at start of line. */
1114 line = p = attr; /* Record start of line. */
1121 if (*p < '0' || *p > '9')
1124 line_length += *p - '0';
1125 if (line_length > 999999) {
1126 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1127 "Rejecting pax extended attribute > 1MB");
1128 return (ARCHIVE_WARN);
1134 if (line_length > attr_length)
1137 /* Ensure pax_entry buffer is big enough. */
1138 if (tar->pax_entry_length <= line_length) {
1139 wchar_t *old_entry = tar->pax_entry;
1141 if (tar->pax_entry_length <= 0)
1142 tar->pax_entry_length = 1024;
1143 while (tar->pax_entry_length <= line_length + 1)
1144 tar->pax_entry_length *= 2;
1146 old_entry = tar->pax_entry;
1147 tar->pax_entry = (wchar_t *)realloc(tar->pax_entry,
1148 tar->pax_entry_length * sizeof(wchar_t));
1149 if (tar->pax_entry == NULL) {
1151 archive_set_error(&a->archive, ENOMEM,
1153 return (ARCHIVE_FATAL);
1157 /* Decode UTF-8 to wchar_t, null-terminate result. */
1158 if (utf8_decode(tar->pax_entry, p,
1159 line_length - (p - attr) - 1)) {
1160 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1161 "Invalid UTF8 character in pax extended attribute");
1162 err = err_combine(err, ARCHIVE_WARN);
1165 /* Null-terminate 'key' value. */
1166 wp = key = tar->pax_entry;
1169 while (*wp && *wp != L'=')
1172 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1173 "Invalid pax extended attributes");
1174 return (ARCHIVE_WARN);
1178 /* Identify null-terminated 'value' portion. */
1181 /* Identify this attribute and set it in the entry. */
1182 err2 = pax_attribute(entry, st, key, value);
1183 err = err_combine(err, err2);
1185 /* Skip to next line */
1186 attr += line_length;
1187 attr_length -= line_length;
1193 pax_attribute_xattr(struct archive_entry *entry,
1194 wchar_t *name, wchar_t *value)
1196 char *name_decoded, *name_narrow;
1197 void *value_decoded;
1200 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1205 /* URL-decode name */
1206 name_narrow = wide_to_narrow(name);
1207 if (name_narrow == NULL)
1209 name_decoded = url_decode(name_narrow);
1211 if (name_decoded == NULL)
1214 /* Base-64 decode value */
1215 value_decoded = base64_decode(value, wcslen(value), &value_len);
1216 if (value_decoded == NULL) {
1221 archive_entry_xattr_add_entry(entry, name_decoded,
1222 value_decoded, value_len);
1225 free(value_decoded);
1230 * Parse a single key=value attribute. key/value pointers are
1231 * assumed to point into reasonably long-lived storage.
1233 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1234 * extensions should always have keywords of the form "VENDOR.attribute"
1235 * In particular, it's quite feasible to support many different
1236 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1237 * unique to this library (currently, there are none).
1239 * Investigate other vendor-specific extensions, as well and see if
1240 * any of them look useful.
1243 pax_attribute(struct archive_entry *entry, struct stat *st,
1244 wchar_t *key, wchar_t *value)
1251 /* Our extensions */
1252 /* TODO: Handle arbitrary extended attributes... */
1254 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1255 archive_entry_set_xxxxxx(entry, value);
1257 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1258 pax_attribute_xattr(entry, key, value);
1261 /* We support some keys used by the "star" archiver */
1262 if (wcscmp(key, L"SCHILY.acl.access")==0)
1263 __archive_entry_acl_parse_w(entry, value,
1264 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1265 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1266 __archive_entry_acl_parse_w(entry, value,
1267 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1268 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1269 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1270 minor(st->st_rdev));
1271 else if (wcscmp(key, L"SCHILY.devminor")==0)
1272 st->st_rdev = makedev(major(st->st_rdev),
1273 tar_atol10(value, wcslen(value)));
1274 else if (wcscmp(key, L"SCHILY.fflags")==0)
1275 archive_entry_copy_fflags_text_w(entry, value);
1276 else if (wcscmp(key, L"SCHILY.dev")==0)
1277 st->st_dev = tar_atol10(value, wcslen(value));
1278 else if (wcscmp(key, L"SCHILY.ino")==0)
1279 st->st_ino = tar_atol10(value, wcslen(value));
1280 else if (wcscmp(key, L"SCHILY.nlink")==0)
1281 st->st_nlink = tar_atol10(value, wcslen(value));
1284 if (wcscmp(key, L"atime")==0) {
1285 pax_time(value, &s, &n);
1287 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1291 if (wcscmp(key, L"ctime")==0) {
1292 pax_time(value, &s, &n);
1294 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1295 } else if (wcscmp(key, L"charset")==0) {
1296 /* TODO: Publish charset information in entry. */
1297 } else if (wcscmp(key, L"comment")==0) {
1298 /* TODO: Publish comment in entry. */
1302 if (wcscmp(key, L"gid")==0)
1303 st->st_gid = tar_atol10(value, wcslen(value));
1304 else if (wcscmp(key, L"gname")==0)
1305 archive_entry_copy_gname_w(entry, value);
1308 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1309 if (wcscmp(key, L"linkpath")==0) {
1310 if (archive_entry_hardlink(entry))
1311 archive_entry_copy_hardlink_w(entry, value);
1313 archive_entry_copy_symlink_w(entry, value);
1317 if (wcscmp(key, L"mtime")==0) {
1318 pax_time(value, &s, &n);
1320 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1324 if (wcscmp(key, L"path")==0)
1325 archive_entry_copy_pathname_w(entry, value);
1328 /* POSIX has reserved 'realtime.*' */
1331 /* POSIX has reserved 'security.*' */
1332 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1333 if (wcscmp(key, L"size")==0)
1334 st->st_size = tar_atol10(value, wcslen(value));
1337 if (wcscmp(key, L"uid")==0)
1338 st->st_uid = tar_atol10(value, wcslen(value));
1339 else if (wcscmp(key, L"uname")==0)
1340 archive_entry_copy_uname_w(entry, value);
1349 * parse a decimal time value, which may include a fractional portion
1352 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1358 int64_t limit, last_digit_limit;
1360 limit = INT64_MAX / 10;
1361 last_digit_limit = INT64_MAX % 10;
1369 while (*p >= '0' && *p <= '9') {
1372 (s == limit && digit > last_digit_limit)) {
1376 s = (s * 10) + digit;
1382 /* Calculate nanoseconds. */
1391 if (*p >= '0' && *p <= '9')
1392 *pn += (*p - '0') * l;
1399 * Parse GNU tar header
1402 header_gnutar(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
1403 struct stat *st, const void *h)
1405 const struct archive_entry_header_gnutar *header;
1410 * GNU header is like POSIX ustar, except 'prefix' is
1411 * replaced with some other fields. This also means the
1412 * filename is stored as in old-style archives.
1415 /* Grab fields common to all tar variants. */
1416 header_common(a, tar, entry, st, h);
1418 /* Copy filename over (to ensure null termination). */
1419 header = (const struct archive_entry_header_gnutar *)h;
1420 archive_strncpy(&(tar->entry_name), header->name,
1421 sizeof(header->name));
1422 archive_entry_set_pathname(entry, tar->entry_name.s);
1424 /* Fields common to ustar and GNU */
1425 /* XXX Can the following be factored out since it's common
1426 * to ustar and gnu tar? Is it okay to move it down into
1427 * header_common, perhaps? */
1428 archive_strncpy(&(tar->entry_uname),
1429 header->uname, sizeof(header->uname));
1430 archive_entry_set_uname(entry, tar->entry_uname.s);
1432 archive_strncpy(&(tar->entry_gname),
1433 header->gname, sizeof(header->gname));
1434 archive_entry_set_gname(entry, tar->entry_gname.s);
1436 /* Parse out device numbers only for char and block specials */
1437 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1438 st->st_rdev = makedev (
1439 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1440 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1444 tar->entry_bytes_remaining = st->st_size;
1445 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1447 /* Grab GNU-specific fields. */
1448 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1449 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1450 if (header->realsize[0] != 0) {
1451 st->st_size = tar_atol(header->realsize,
1452 sizeof(header->realsize));
1455 if (header->sparse[0].offset[0] != 0) {
1456 gnu_read_sparse_data(a, tar, header);
1458 if (header->isextended[0] != 0) {
1467 gnu_read_sparse_data(struct archive_read *a, struct tar *tar,
1468 const struct archive_entry_header_gnutar *header)
1473 struct gnu_sparse sparse[21];
1477 const struct extended *ext;
1479 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1480 if (header->isextended[0] == 0)
1481 return (ARCHIVE_OK);
1484 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1486 return (ARCHIVE_FATAL);
1487 if (bytes_read < 512) {
1488 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1489 "Truncated tar archive "
1490 "detected while reading sparse file data");
1491 return (ARCHIVE_FATAL);
1493 (a->compression_read_consume)(a, 512);
1494 ext = (const struct extended *)data;
1495 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1496 } while (ext->isextended[0] != 0);
1497 if (tar->sparse_list != NULL)
1498 tar->entry_offset = tar->sparse_list->offset;
1499 return (ARCHIVE_OK);
1503 gnu_parse_sparse_data(struct archive_read *a, struct tar *tar,
1504 const struct gnu_sparse *sparse, int length)
1506 struct sparse_block *last;
1507 struct sparse_block *p;
1509 (void)a; /* UNUSED */
1511 last = tar->sparse_list;
1512 while (last != NULL && last->next != NULL)
1515 while (length > 0 && sparse->offset[0] != 0) {
1516 p = (struct sparse_block *)malloc(sizeof(*p));
1518 __archive_errx(1, "Out of memory");
1519 memset(p, 0, sizeof(*p));
1523 tar->sparse_list = p;
1525 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1527 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1534 * Convert text->integer.
1536 * Traditional tar formats (including POSIX) specify base-8 for
1537 * all of the standard numeric fields. This is a significant limitation
1539 * = file size is limited to 8GB
1540 * = rdevmajor and rdevminor are limited to 21 bits
1541 * = uid/gid are limited to 21 bits
1543 * There are two workarounds for this:
1544 * = pax extended headers, which use variable-length string fields
1545 * = GNU tar and STAR both allow either base-8 or base-256 in
1546 * most fields. The high bit is set to indicate base-256.
1548 * On read, this implementation supports both extensions.
1551 tar_atol(const char *p, unsigned char_cnt)
1554 * Technically, GNU tar considers a field to be in base-256
1555 * only if the first byte is 0xff or 0x80.
1558 return (tar_atol256(p, char_cnt));
1559 return (tar_atol8(p, char_cnt));
1563 * Note that this implementation does not (and should not!) obey
1564 * locale settings; you cannot simply substitute strtol here, since
1565 * it does obey locale.
1568 tar_atol8(const char *p, unsigned char_cnt)
1570 int64_t l, limit, last_digit_limit;
1571 int digit, sign, base;
1574 limit = INT64_MAX / base;
1575 last_digit_limit = INT64_MAX % base;
1577 while (*p == ' ' || *p == '\t')
1587 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1588 if (l>limit || (l == limit && digit > last_digit_limit)) {
1589 l = UINT64_MAX; /* Truncate on overflow. */
1592 l = (l * base) + digit;
1595 return (sign < 0) ? -l : l;
1600 * Note that this implementation does not (and should not!) obey
1601 * locale settings; you cannot simply substitute strtol here, since
1602 * it does obey locale.
1605 tar_atol10(const wchar_t *p, unsigned char_cnt)
1607 int64_t l, limit, last_digit_limit;
1608 int base, digit, sign;
1611 limit = INT64_MAX / base;
1612 last_digit_limit = INT64_MAX % base;
1614 while (*p == ' ' || *p == '\t')
1624 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1625 if (l > limit || (l == limit && digit > last_digit_limit)) {
1626 l = UINT64_MAX; /* Truncate on overflow. */
1629 l = (l * base) + digit;
1632 return (sign < 0) ? -l : l;
1636 * Parse a base-256 integer. This is just a straight signed binary
1637 * value in big-endian order, except that the high-order bit is
1638 * ignored. Remember that "int64_t" may or may not be exactly 64
1639 * bits; the implementation here tries to avoid making any assumptions
1640 * about the actual size of an int64_t. It does assume we're using
1641 * twos-complement arithmetic, though.
1644 tar_atol256(const char *_p, unsigned char_cnt)
1646 int64_t l, upper_limit, lower_limit;
1647 const unsigned char *p = (const unsigned char *)_p;
1649 upper_limit = INT64_MAX / 256;
1650 lower_limit = INT64_MIN / 256;
1652 /* Pad with 1 or 0 bits, depending on sign. */
1653 if ((0x40 & *p) == 0x40)
1657 l = (l << 6) | (0x3f & *p++);
1658 while (--char_cnt > 0) {
1659 if (l > upper_limit) {
1660 l = INT64_MAX; /* Truncate on overflow */
1662 } else if (l < lower_limit) {
1666 l = (l << 8) | (0xff & (int64_t)*p++);
1672 utf8_decode(wchar_t *dest, const char *src, size_t length)
1678 while (length > 0) {
1679 n = UTF8_mbrtowc(dest, src, length);
1691 * Copied and simplified from FreeBSD libc/locale.
1694 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1696 int ch, i, len, mask;
1699 if (s == NULL || n == 0 || pwc == NULL)
1703 * Determine the number of octets that make up this character from
1704 * the first octet, and a mask that extracts the interesting bits of
1707 ch = (unsigned char)*s;
1708 if ((ch & 0x80) == 0) {
1711 } else if ((ch & 0xe0) == 0xc0) {
1714 } else if ((ch & 0xf0) == 0xe0) {
1717 } else if ((ch & 0xf8) == 0xf0) {
1720 } else if ((ch & 0xfc) == 0xf8) {
1723 } else if ((ch & 0xfe) == 0xfc) {
1727 /* Invalid first byte; convert to '?' */
1732 if (n < (size_t)len) {
1733 /* Invalid first byte; convert to '?' */
1739 * Decode the octet sequence representing the character in chunks
1740 * of 6 bits, most significant first.
1742 wch = (unsigned char)*s++ & mask;
1745 if ((*s & 0xc0) != 0x80) {
1746 /* Invalid intermediate byte; consume one byte and
1755 /* Assign the value to the output; out-of-range values
1756 * just get truncated. */
1757 *pwc = (wchar_t)wch;
1760 * If platform has WCHAR_MAX, we can do something
1761 * more sensible with out-of-range values.
1763 if (wch >= WCHAR_MAX)
1766 /* Return number of bytes input consumed: 0 for end-of-string. */
1767 return (wch == L'\0' ? 0 : len);
1772 * base64_decode - Base64 decode
1774 * This accepts most variations of base-64 encoding, including:
1775 * * with or without line breaks
1776 * * with or without the final group padded with '=' or '_' characters
1777 * (The most economical Base-64 variant does not pad the last group and
1778 * omits line breaks; RFC1341 used for MIME requires both.)
1781 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1783 static const unsigned char digits[64] = {
1784 'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
1785 'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
1786 'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
1787 'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
1788 '4','5','6','7','8','9','+','/' };
1789 static unsigned char decode_table[128];
1792 /* If the decode table is not yet initialized, prepare it. */
1793 if (decode_table[digits[1]] != 1) {
1795 memset(decode_table, 0xff, sizeof(decode_table));
1796 for (i = 0; i < sizeof(digits); i++)
1797 decode_table[digits[i]] = i;
1800 /* Allocate enough space to hold the entire output. */
1801 /* Note that we may not use all of this... */
1802 out = (char *)malloc((len * 3 + 3) / 4);
1810 /* Collect the next group of (up to) four characters. */
1813 while (group_size < 4 && len > 0) {
1814 /* '=' or '_' padding indicates final group. */
1815 if (*src == '=' || *src == '_') {
1819 /* Skip illegal characters (including line breaks) */
1820 if (*src > 127 || *src < 32
1821 || decode_table[*src] == 0xff) {
1827 v |= decode_table[*src++];
1831 /* Align a short group properly. */
1832 v <<= 6 * (4 - group_size);
1833 /* Unpack the group we just collected. */
1834 switch (group_size) {
1835 case 4: d[2] = v & 0xff;
1837 case 3: d[1] = (v >> 8) & 0xff;
1839 case 2: d[0] = (v >> 16) & 0xff;
1841 case 1: /* this is invalid! */
1844 d += group_size * 3 / 4;
1852 * This is a little tricky because the C99 standard wcstombs()
1853 * function returns the number of bytes that were converted,
1854 * not the number that should be converted. As a result,
1855 * we can never accurately size the output buffer (without
1856 * doing a tedious output size calculation in advance).
1857 * This approach (try a conversion, then try again if it fails)
1858 * will almost always succeed on the first try, and is thus
1859 * much faster, at the cost of sometimes requiring multiple
1860 * passes while we expand the buffer.
1863 wide_to_narrow(const wchar_t *wval)
1865 int converted_length;
1866 /* Guess an output buffer size and try the conversion. */
1867 int alloc_length = wcslen(wval) * 3;
1868 char *mbs_val = (char *)malloc(alloc_length + 1);
1869 if (mbs_val == NULL)
1871 converted_length = wcstombs(mbs_val, wval, alloc_length);
1873 /* If we exhausted the buffer, resize and try again. */
1874 while (converted_length >= alloc_length) {
1877 mbs_val = (char *)malloc(alloc_length + 1);
1878 if (mbs_val == NULL)
1880 converted_length = wcstombs(mbs_val, wval, alloc_length);
1883 /* Ensure a trailing null and return the final string. */
1884 mbs_val[alloc_length] = '\0';
1889 url_decode(const char *in)
1894 out = (char *)malloc(strlen(in) + 1);
1897 for (s = in, d = out; *s != '\0'; ) {
1899 /* Try to convert % escape */
1900 int digit1 = tohex(s[1]);
1901 int digit2 = tohex(s[2]);
1902 if (digit1 >= 0 && digit2 >= 0) {
1903 /* Looks good, consume three chars */
1905 /* Convert output */
1906 *d++ = ((digit1 << 4) | digit2);
1909 /* Else fall through and treat '%' as normal char */
1920 if (c >= '0' && c <= '9')
1922 else if (c >= 'A' && c <= 'F')
1923 return (c - 'A' + 10);
1924 else if (c >= 'a' && c <= 'f')
1925 return (c - 'a' + 10);