2 * Copyright (c) 2003-2006 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 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_tar.c,v 1.43 2006/09/05 05:59:46 kientzle Exp $");
32 #include <sys/mkdev.h>
34 #ifdef MAJOR_IN_SYSMACROS
35 #include <sys/sysmacros.h>
40 /* #include <stdint.h> */ /* See archive_platform.h */
45 /* Obtain suitable wide-character manipulation functions. */
49 /* Good enough for equality testing, which is all we need. */
50 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
53 while (*s1 && diff == 0)
54 diff = (int)*++s1 - (int)*++s2;
57 /* Good enough for equality testing, which is all we need. */
58 static int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n)
61 while (*s1 && diff == 0 && n-- > 0)
62 diff = (int)*++s1 - (int)*++s2;
65 static size_t wcslen(const wchar_t *s)
75 #include "archive_entry.h"
76 #include "archive_private.h"
79 * Layout of POSIX 'ustar' tar header.
81 struct archive_entry_header_ustar {
90 char linkname[100]; /* "old format" header ends here */
91 char magic[6]; /* For POSIX: "ustar\0" */
92 char version[2]; /* For POSIX: "00" */
101 * Structure of GNU tar header
108 struct archive_entry_header_gnutar {
118 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
128 struct gnu_sparse sparse[4];
132 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
138 * Data specific to this format.
140 struct sparse_block {
141 struct sparse_block *next;
147 struct archive_string acl_text;
148 struct archive_string entry_name;
149 struct archive_string entry_linkname;
150 struct archive_string entry_uname;
151 struct archive_string entry_gname;
152 struct archive_string longlink;
153 struct archive_string longname;
154 struct archive_string pax_header;
155 struct archive_string pax_global;
157 size_t pax_entry_length;
158 int header_recursion_depth;
159 off_t entry_bytes_remaining;
162 struct sparse_block *sparse_list;
165 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
166 static int archive_block_is_null(const unsigned char *p);
167 static char *base64_decode(const wchar_t *, size_t, size_t *);
168 static int gnu_read_sparse_data(struct archive *, struct tar *,
169 const struct archive_entry_header_gnutar *header);
170 static void gnu_parse_sparse_data(struct archive *, struct tar *,
171 const struct gnu_sparse *sparse, int length);
172 static int header_Solaris_ACL(struct archive *, struct tar *,
173 struct archive_entry *, struct stat *, const void *);
174 static int header_common(struct archive *, struct tar *,
175 struct archive_entry *, struct stat *, const void *);
176 static int header_old_tar(struct archive *, struct tar *,
177 struct archive_entry *, struct stat *, const void *);
178 static int header_pax_extensions(struct archive *, struct tar *,
179 struct archive_entry *, struct stat *, const void *);
180 static int header_pax_global(struct archive *, struct tar *,
181 struct archive_entry *, struct stat *, const void *h);
182 static int header_longlink(struct archive *, struct tar *,
183 struct archive_entry *, struct stat *, const void *h);
184 static int header_longname(struct archive *, struct tar *,
185 struct archive_entry *, struct stat *, const void *h);
186 static int header_volume(struct archive *, struct tar *,
187 struct archive_entry *, struct stat *, const void *h);
188 static int header_ustar(struct archive *, struct tar *,
189 struct archive_entry *, struct stat *, const void *h);
190 static int header_gnutar(struct archive *, struct tar *,
191 struct archive_entry *, struct stat *, const void *h);
192 static int archive_read_format_tar_bid(struct archive *);
193 static int archive_read_format_tar_cleanup(struct archive *);
194 static int archive_read_format_tar_read_data(struct archive *a,
195 const void **buff, size_t *size, off_t *offset);
196 static int archive_read_format_tar_skip(struct archive *a);
197 static int archive_read_format_tar_read_header(struct archive *,
198 struct archive_entry *);
199 static int checksum(struct archive *, const void *);
200 static int pax_attribute(struct archive_entry *, struct stat *,
201 wchar_t *key, wchar_t *value);
202 static int pax_header(struct archive *, struct tar *,
203 struct archive_entry *, struct stat *, char *attr);
204 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
205 static int read_body_to_string(struct archive *, struct tar *,
206 struct archive_string *, const void *h);
207 static int64_t tar_atol(const char *, unsigned);
208 static int64_t tar_atol10(const wchar_t *, unsigned);
209 static int64_t tar_atol256(const char *, unsigned);
210 static int64_t tar_atol8(const char *, unsigned);
211 static int tar_read_header(struct archive *, struct tar *,
212 struct archive_entry *, struct stat *);
213 static int tohex(int c);
214 static char *url_decode(const char *);
215 static int utf8_decode(wchar_t *, const char *, size_t length);
216 static char *wide_to_narrow(const wchar_t *wval);
219 * ANSI C99 defines constants for these, but not everyone supports
220 * those constants, so I define a couple of static variables here and
221 * compute the values. These calculations should be portable to any
222 * 2s-complement architecture.
225 static const uint64_t max_uint64 = UINT64_MAX;
227 static const uint64_t max_uint64 = ~(uint64_t)0;
230 static const int64_t max_int64 = INT64_MAX;
232 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
235 static const int64_t min_int64 = INT64_MIN;
237 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
241 archive_read_support_format_gnutar(struct archive *a)
243 return (archive_read_support_format_tar(a));
248 archive_read_support_format_tar(struct archive *a)
253 tar = malloc(sizeof(*tar));
255 archive_set_error(a, ENOMEM, "Can't allocate tar data");
256 return (ARCHIVE_FATAL);
258 memset(tar, 0, sizeof(*tar));
260 r = __archive_read_register_format(a, tar,
261 archive_read_format_tar_bid,
262 archive_read_format_tar_read_header,
263 archive_read_format_tar_read_data,
264 archive_read_format_tar_skip,
265 archive_read_format_tar_cleanup);
273 archive_read_format_tar_cleanup(struct archive *a)
277 tar = *(a->pformat_data);
278 archive_string_free(&tar->acl_text);
279 archive_string_free(&tar->entry_name);
280 archive_string_free(&tar->entry_linkname);
281 archive_string_free(&tar->entry_uname);
282 archive_string_free(&tar->entry_gname);
283 archive_string_free(&tar->pax_global);
284 archive_string_free(&tar->pax_header);
285 if (tar->pax_entry != NULL)
286 free(tar->pax_entry);
288 *(a->pformat_data) = NULL;
294 archive_read_format_tar_bid(struct archive *a)
299 const struct archive_entry_header_ustar *header;
302 * If we're already reading a non-tar file, don't
305 if (a->archive_format != 0 &&
306 (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
312 * If we're already reading a tar format, start the bid at 1 as
315 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
319 /* Now let's look at the actual header and see if it matches. */
320 if (a->compression_read_ahead != NULL)
321 bytes_read = (a->compression_read_ahead)(a, &h, 512);
323 bytes_read = 0; /* Empty file. */
325 return (ARCHIVE_FATAL);
326 if (bytes_read == 0 && bid > 0) {
327 /* An archive without a proper end-of-archive marker. */
328 /* Hold our nose and bid 1 anyway. */
331 if (bytes_read < 512) {
332 /* If it's a new archive, then just return a zero bid. */
336 * If we already know this is a tar archive,
337 * then we have a problem.
339 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
340 "Truncated tar archive");
341 return (ARCHIVE_FATAL);
344 /* If it's an end-of-archive mark, we can handle it. */
345 if ((*(const char *)h) == 0 && archive_block_is_null(h)) {
346 /* If it's a known tar file, end-of-archive is definite. */
347 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
354 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
357 bid += 48; /* Checksum is usually 6 octal digits. */
361 /* Recognize POSIX formats. */
362 if ((memcmp(header->magic, "ustar\0", 6) == 0)
363 &&(memcmp(header->version, "00", 2)==0))
366 /* Recognize GNU tar format. */
367 if ((memcmp(header->magic, "ustar ", 6) == 0)
368 &&(memcmp(header->version, " \0", 2)==0))
371 /* Type flag must be null, digit or A-Z, a-z. */
372 if (header->typeflag[0] != 0 &&
373 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
374 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
375 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
377 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
379 /* Sanity check: Look at first byte of mode field. */
380 switch (255 & (unsigned)header->mode[0]) {
382 /* Base-256 value: No further verification possible! */
384 case ' ': /* Not recommended, but not illegal, either. */
386 case '0': case '1': case '2': case '3':
387 case '4': case '5': case '6': case '7':
389 /* TODO: Check format of remainder of this field. */
392 /* Not a valid mode; bail out here. */
395 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
401 * The function invoked by archive_read_header(). This
402 * just sets up a few things and then calls the internal
403 * tar_read_header() function below.
406 archive_read_format_tar_read_header(struct archive *a,
407 struct archive_entry *entry)
410 * When converting tar archives to cpio archives, it is
411 * essential that each distinct file have a distinct inode
412 * number. To simplify this, we keep a static count here to
413 * assign fake dev/inode numbers to each tar entry. Note that
414 * pax format archives may overwrite this with something more
417 * Ideally, we would track every file read from the archive so
418 * that we could assign the same dev/ino pair to hardlinks,
419 * but the memory required to store a complete lookup table is
420 * probably not worthwhile just to support the relatively
421 * obscure tar->cpio conversion case.
423 static int default_inode;
424 static int default_dev;
431 memset(&st, 0, sizeof(st));
432 /* Assign default device/inode values. */
433 st.st_dev = 1 + default_dev; /* Don't use zero. */
434 st.st_ino = ++default_inode; /* Don't use zero. */
435 /* Limit generated st_ino number to 16 bits. */
436 if (default_inode >= 0xffff) {
441 tar = *(a->pformat_data);
442 tar->entry_offset = 0;
444 r = tar_read_header(a, tar, entry, &st);
446 if (r == ARCHIVE_OK) {
448 * "Regular" entry with trailing '/' is really
449 * directory: This is needed for certain old tar
450 * variants and even for some broken newer ones.
452 p = archive_entry_pathname(entry);
454 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
455 st.st_mode &= ~S_IFMT;
456 st.st_mode |= S_IFDIR;
459 /* Copy the final stat data into the entry. */
460 archive_entry_copy_stat(entry, &st);
466 archive_read_format_tar_read_data(struct archive *a,
467 const void **buff, size_t *size, off_t *offset)
471 struct sparse_block *p;
473 tar = *(a->pformat_data);
474 if (tar->sparse_list != NULL) {
475 /* Remove exhausted entries from sparse list. */
476 while (tar->sparse_list != NULL &&
477 tar->sparse_list->remaining == 0) {
478 p = tar->sparse_list;
479 tar->sparse_list = p->next;
482 if (tar->sparse_list == NULL) {
483 /* We exhausted the entire sparse list. */
484 tar->entry_bytes_remaining = 0;
488 if (tar->entry_bytes_remaining > 0) {
489 bytes_read = (a->compression_read_ahead)(a, buff, 1);
491 return (ARCHIVE_FATAL);
492 if (bytes_read > tar->entry_bytes_remaining)
493 bytes_read = tar->entry_bytes_remaining;
494 if (tar->sparse_list != NULL) {
495 /* Don't read more than is available in the
496 * current sparse block. */
497 if (tar->sparse_list->remaining < bytes_read)
498 bytes_read = tar->sparse_list->remaining;
499 tar->entry_offset = tar->sparse_list->offset;
500 tar->sparse_list->remaining -= bytes_read;
501 tar->sparse_list->offset += bytes_read;
504 *offset = tar->entry_offset;
505 tar->entry_offset += bytes_read;
506 tar->entry_bytes_remaining -= bytes_read;
507 (a->compression_read_consume)(a, bytes_read);
510 while (tar->entry_padding > 0) {
511 bytes_read = (a->compression_read_ahead)(a, buff, 1);
513 return (ARCHIVE_FATAL);
514 if (bytes_read > tar->entry_padding)
515 bytes_read = tar->entry_padding;
516 (a->compression_read_consume)(a, bytes_read);
517 tar->entry_padding -= bytes_read;
521 *offset = tar->entry_offset;
522 return (ARCHIVE_EOF);
527 archive_read_format_tar_skip(struct archive *a)
529 ssize_t bytes_skipped;
531 struct sparse_block *p;
533 const void *b; /* dummy variables */
538 tar = *(a->pformat_data);
539 if (a->compression_skip == NULL) {
540 while (r == ARCHIVE_OK)
541 r = archive_read_format_tar_read_data(a, &b, &s, &o);
544 bytes_skipped = (a->compression_skip)(a, tar->entry_bytes_remaining);
545 if (bytes_skipped < 0)
546 return (ARCHIVE_FATAL);
547 /* same code as above in _tar_read_data() */
548 tar->entry_bytes_remaining -= bytes_skipped;
549 while (tar->sparse_list != NULL &&
550 tar->sparse_list->remaining == 0) {
551 p = tar->sparse_list;
552 tar->sparse_list = p->next;
554 if (tar->sparse_list != NULL)
555 tar->entry_offset = tar->sparse_list->offset;
557 if (tar->sparse_list != NULL) {
558 if (tar->sparse_list->remaining < bytes_skipped)
559 bytes_skipped = tar->sparse_list->remaining;
560 tar->sparse_list->remaining -= bytes_skipped;
562 tar->entry_offset += bytes_skipped;
563 tar->entry_bytes_remaining -= bytes_skipped;
564 /* Reuse padding code above. */
565 while (r == ARCHIVE_OK)
566 r = archive_read_format_tar_read_data(a, &b, &s, &o);
571 * This function recursively interprets all of the headers associated
572 * with a single entry.
575 tar_read_header(struct archive *a, struct tar *tar,
576 struct archive_entry *entry, struct stat *st)
581 const struct archive_entry_header_ustar *header;
583 /* Read 512-byte header record */
584 bytes = (a->compression_read_ahead)(a, &h, 512);
587 * If we're here, it's becase the _bid function accepted
588 * this file. So just call a short read end-of-archive
589 * and be done with it.
591 return (ARCHIVE_EOF);
593 (a->compression_read_consume)(a, 512);
595 /* Check for end-of-archive mark. */
596 if (((*(const char *)h)==0) && archive_block_is_null(h)) {
597 /* Try to consume a second all-null record, as well. */
598 bytes = (a->compression_read_ahead)(a, &h, 512);
600 (a->compression_read_consume)(a, bytes);
601 archive_set_error(a, 0, NULL);
602 return (ARCHIVE_EOF);
606 * Note: If the checksum fails and we return ARCHIVE_RETRY,
607 * then the client is likely to just retry. This is a very
608 * crude way to search for the next valid header!
610 * TODO: Improve this by implementing a real header scan.
612 if (!checksum(a, h)) {
613 archive_set_error(a, EINVAL, "Damaged tar archive");
614 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
617 if (++tar->header_recursion_depth > 32) {
618 archive_set_error(a, EINVAL, "Too many special headers");
619 return (ARCHIVE_WARN);
622 /* Determine the format variant. */
624 switch(header->typeflag[0]) {
625 case 'A': /* Solaris tar ACL */
626 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
627 a->archive_format_name = "Solaris tar";
628 err = header_Solaris_ACL(a, tar, entry, st, h);
630 case 'g': /* POSIX-standard 'g' header. */
631 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
632 a->archive_format_name = "POSIX pax interchange format";
633 err = header_pax_global(a, tar, entry, st, h);
635 case 'K': /* Long link name (GNU tar, others) */
636 err = header_longlink(a, tar, entry, st, h);
638 case 'L': /* Long filename (GNU tar, others) */
639 err = header_longname(a, tar, entry, st, h);
641 case 'V': /* GNU volume header */
642 err = header_volume(a, tar, entry, st, h);
644 case 'X': /* Used by SUN tar; same as 'x'. */
645 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
646 a->archive_format_name =
647 "POSIX pax interchange format (Sun variant)";
648 err = header_pax_extensions(a, tar, entry, st, h);
650 case 'x': /* POSIX-standard 'x' header. */
651 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
652 a->archive_format_name = "POSIX pax interchange format";
653 err = header_pax_extensions(a, tar, entry, st, h);
656 if (memcmp(header->magic, "ustar \0", 8) == 0) {
657 a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
658 a->archive_format_name = "GNU tar format";
659 err = header_gnutar(a, tar, entry, st, h);
660 } else if (memcmp(header->magic, "ustar", 5) == 0) {
661 if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
662 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
663 a->archive_format_name = "POSIX ustar format";
665 err = header_ustar(a, tar, entry, st, h);
667 a->archive_format = ARCHIVE_FORMAT_TAR;
668 a->archive_format_name = "tar (non-POSIX)";
669 err = header_old_tar(a, tar, entry, st, h);
672 --tar->header_recursion_depth;
677 * Return true if block checksum is correct.
680 checksum(struct archive *a, const void *h)
682 const unsigned char *bytes;
683 const struct archive_entry_header_ustar *header;
686 (void)a; /* UNUSED */
691 * Test the checksum. Note that POSIX specifies _unsigned_
692 * bytes for this calculation.
694 sum = tar_atol(header->checksum, sizeof(header->checksum));
696 for (i = 0; i < 148; i++)
697 check += (unsigned char)bytes[i];
701 check += (unsigned char)bytes[i];
706 * Repeat test with _signed_ bytes, just in case this archive
707 * was created by an old BSD, Solaris, or HP-UX tar with a
708 * broken checksum calculation.
711 for (i = 0; i < 148; i++)
712 check += (signed char)bytes[i];
716 check += (signed char)bytes[i];
724 * Return true if this block contains only nulls.
727 archive_block_is_null(const unsigned char *p)
731 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
738 * Interpret 'A' Solaris ACL header
741 header_Solaris_ACL(struct archive *a, struct tar *tar,
742 struct archive_entry *entry, struct stat *st, const void *h)
748 err = read_body_to_string(a, tar, &(tar->acl_text), h);
749 err2 = tar_read_header(a, tar, entry, st);
750 err = err_combine(err, err2);
752 /* XXX Ensure p doesn't overrun acl_text */
754 /* Skip leading octal number. */
755 /* XXX TODO: Parse the octal number and sanity-check it. */
761 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
763 utf8_decode(wp, p, strlen(p));
764 err2 = __archive_entry_acl_parse_w(entry, wp,
765 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
766 err = err_combine(err, err2);
774 * Interpret 'K' long linkname header.
777 header_longlink(struct archive *a, struct tar *tar,
778 struct archive_entry *entry, struct stat *st, const void *h)
782 err = read_body_to_string(a, tar, &(tar->longlink), h);
783 err2 = tar_read_header(a, tar, entry, st);
784 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
785 /* Set symlink if symlink already set, else hardlink. */
786 archive_entry_set_link(entry, tar->longlink.s);
788 return (err_combine(err, err2));
792 * Interpret 'L' long filename header.
795 header_longname(struct archive *a, struct tar *tar,
796 struct archive_entry *entry, struct stat *st, const void *h)
800 err = read_body_to_string(a, tar, &(tar->longname), h);
801 /* Read and parse "real" header, then override name. */
802 err2 = tar_read_header(a, tar, entry, st);
803 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
804 archive_entry_set_pathname(entry, tar->longname.s);
805 return (err_combine(err, err2));
810 * Interpret 'V' GNU tar volume header.
813 header_volume(struct archive *a, struct tar *tar,
814 struct archive_entry *entry, struct stat *st, const void *h)
818 /* Just skip this and read the next header. */
819 return (tar_read_header(a, tar, entry, st));
823 * Read body of an archive entry into an archive_string object.
826 read_body_to_string(struct archive *a, struct tar *tar,
827 struct archive_string *as, const void *h)
829 off_t size, padded_size;
830 ssize_t bytes_read, bytes_to_copy;
831 const struct archive_entry_header_ustar *header;
835 (void)tar; /* UNUSED */
837 size = tar_atol(header->size, sizeof(header->size));
839 /* Read the body into the string. */
840 archive_string_ensure(as, size+1);
841 padded_size = (size + 511) & ~ 511;
843 while (padded_size > 0) {
844 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
846 return (ARCHIVE_FATAL);
847 if (bytes_read > padded_size)
848 bytes_read = padded_size;
849 (a->compression_read_consume)(a, bytes_read);
850 bytes_to_copy = bytes_read;
851 if ((off_t)bytes_to_copy > size)
852 bytes_to_copy = (ssize_t)size;
853 memcpy(dest, src, bytes_to_copy);
854 dest += bytes_to_copy;
855 size -= bytes_to_copy;
856 padded_size -= bytes_read;
863 * Parse out common header elements.
865 * This would be the same as header_old_tar, except that the
866 * filename is handled slightly differently for old and POSIX
867 * entries (POSIX entries support a 'prefix'). This factoring
868 * allows header_old_tar and header_ustar
869 * to handle filenames differently, while still putting most of the
870 * common parsing into one place.
873 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
874 struct stat *st, const void *h)
876 const struct archive_entry_header_ustar *header;
879 (void)a; /* UNUSED */
882 if (header->linkname[0])
883 archive_strncpy(&(tar->entry_linkname), header->linkname,
884 sizeof(header->linkname));
886 archive_string_empty(&(tar->entry_linkname));
888 /* Parse out the numeric fields (all are octal) */
889 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
890 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
891 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
892 st->st_size = tar_atol(header->size, sizeof(header->size));
893 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
895 /* Handle the tar type flag appropriately. */
896 tartype = header->typeflag[0];
897 st->st_mode &= ~S_IFMT;
900 case '1': /* Hard link */
901 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
903 * The following may seem odd, but: Technically, tar
904 * does not store the file type for a "hard link"
905 * entry, only the fact that it is a hard link. So, I
906 * leave the type zero normally. But, pax interchange
907 * format allows hard links to have data, which
908 * implies that the underlying entry is a regular
912 st->st_mode |= S_IFREG;
915 * A tricky point: Traditionally, tar readers have
916 * ignored the size field when reading hardlink
917 * entries, and some writers put non-zero sizes even
918 * though the body is empty. POSIX.1-2001 broke with
919 * this tradition by permitting hardlink entries to
920 * store valid bodies in pax interchange format, but
921 * not in ustar format. Since there is no hard and
922 * fast way to distinguish pax interchange from
923 * earlier archives (the 'x' and 'g' entries are
924 * optional, after all), we need a heuristic. Here, I
925 * use the bid function to test whether or not there's
926 * a valid header following. Of course, if we know
927 * this is pax interchange format, then we must obey
930 * This heuristic will only fail for a pax interchange
931 * archive that is storing hardlink bodies, no pax
932 * extended attribute entries have yet occurred, and
933 * we encounter a hardlink entry for a file that is
934 * itself an uncompressed tar archive.
936 if (st->st_size > 0 &&
937 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
938 archive_read_format_tar_bid(a) > 50)
941 case '2': /* Symlink */
942 st->st_mode |= S_IFLNK;
944 archive_entry_set_symlink(entry, tar->entry_linkname.s);
946 case '3': /* Character device */
947 st->st_mode |= S_IFCHR;
950 case '4': /* Block device */
951 st->st_mode |= S_IFBLK;
955 st->st_mode |= S_IFDIR;
958 case '6': /* FIFO device */
959 st->st_mode |= S_IFIFO;
962 case 'D': /* GNU incremental directory type */
964 * No special handling is actually required here.
965 * It might be nice someday to preprocess the file list and
966 * provide it to the client, though.
968 st->st_mode |= S_IFDIR;
970 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
972 * As far as I can tell, this is just like a regular file
973 * entry, except that the contents should be _appended_ to
974 * the indicated file at the indicated offset. This may
975 * require some API work to fully support.
978 case 'N': /* Old GNU "long filename" entry. */
979 /* The body of this entry is a script for renaming
980 * previously-extracted entries. Ugh. It will never
981 * be supported by libarchive. */
982 st->st_mode |= S_IFREG;
984 case 'S': /* GNU sparse files */
986 * Sparse files are really just regular files with
987 * sparse information in the extended area.
990 default: /* Regular file and non-standard types */
992 * Per POSIX: non-recognized types should always be
993 * treated as regular files.
995 st->st_mode |= S_IFREG;
1002 * Parse out header elements for "old-style" tar archives.
1005 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1006 struct stat *st, const void *h)
1008 const struct archive_entry_header_ustar *header;
1010 /* Copy filename over (to ensure null termination). */
1012 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
1013 archive_entry_set_pathname(entry, tar->entry_name.s);
1015 /* Grab rest of common fields */
1016 header_common(a, tar, entry, st, h);
1018 tar->entry_bytes_remaining = st->st_size;
1019 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1024 * Parse a file header for a pax extended archive entry.
1027 header_pax_global(struct archive *a, struct tar *tar,
1028 struct archive_entry *entry, struct stat *st, const void *h)
1032 err = read_body_to_string(a, tar, &(tar->pax_global), h);
1033 err2 = tar_read_header(a, tar, entry, st);
1034 return (err_combine(err, err2));
1038 header_pax_extensions(struct archive *a, struct tar *tar,
1039 struct archive_entry *entry, struct stat *st, const void *h)
1043 read_body_to_string(a, tar, &(tar->pax_header), h);
1045 /* Parse the next header. */
1046 err = tar_read_header(a, tar, entry, st);
1049 * TODO: Parse global/default options into 'entry' struct here
1050 * before handling file-specific options.
1052 * This design (parse standard header, then overwrite with pax
1053 * extended attribute data) usually works well, but isn't ideal;
1054 * it would be better to parse the pax extended attributes first
1055 * and then skip any fields in the standard header that were
1056 * defined in the pax header.
1058 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1059 err = err_combine(err, err2);
1060 tar->entry_bytes_remaining = st->st_size;
1061 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1067 * Parse a file header for a Posix "ustar" archive entry. This also
1068 * handles "pax" or "extended ustar" entries.
1071 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1072 struct stat *st, const void *h)
1074 const struct archive_entry_header_ustar *header;
1075 struct archive_string *as;
1079 /* Copy name into an internal buffer to ensure null-termination. */
1080 as = &(tar->entry_name);
1081 if (header->prefix[0]) {
1082 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1083 if (as->s[archive_strlen(as) - 1] != '/')
1084 archive_strappend_char(as, '/');
1085 archive_strncat(as, header->name, sizeof(header->name));
1087 archive_strncpy(as, header->name, sizeof(header->name));
1089 archive_entry_set_pathname(entry, as->s);
1091 /* Handle rest of common fields. */
1092 header_common(a, tar, entry, st, h);
1094 /* Handle POSIX ustar fields. */
1095 archive_strncpy(&(tar->entry_uname), header->uname,
1096 sizeof(header->uname));
1097 archive_entry_set_uname(entry, tar->entry_uname.s);
1099 archive_strncpy(&(tar->entry_gname), header->gname,
1100 sizeof(header->gname));
1101 archive_entry_set_gname(entry, tar->entry_gname.s);
1103 /* Parse out device numbers only for char and block specials. */
1104 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1105 st->st_rdev = makedev(
1106 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1107 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1110 tar->entry_bytes_remaining = st->st_size;
1111 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1118 * Parse the pax extended attributes record.
1120 * Returns non-zero if there's an error in the data.
1123 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1124 struct stat *st, char *attr)
1126 size_t attr_length, l, line_length;
1128 wchar_t *key, *wp, *value;
1131 attr_length = strlen(attr);
1133 while (attr_length > 0) {
1134 /* Parse decimal length field at start of line. */
1137 line = p = attr; /* Record start of line. */
1144 if (*p < '0' || *p > '9')
1147 line_length += *p - '0';
1148 if (line_length > 999999) {
1149 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1150 "Rejecting pax extended attribute > 1MB");
1151 return (ARCHIVE_WARN);
1157 if (line_length > attr_length)
1160 /* Ensure pax_entry buffer is big enough. */
1161 if (tar->pax_entry_length <= line_length) {
1162 wchar_t *old_entry = tar->pax_entry;
1164 if (tar->pax_entry_length <= 0)
1165 tar->pax_entry_length = 1024;
1166 while (tar->pax_entry_length <= line_length + 1)
1167 tar->pax_entry_length *= 2;
1169 old_entry = tar->pax_entry;
1170 tar->pax_entry = realloc(tar->pax_entry,
1171 tar->pax_entry_length * sizeof(wchar_t));
1172 if (tar->pax_entry == NULL) {
1174 archive_set_error(a, ENOMEM,
1176 return (ARCHIVE_FATAL);
1180 /* Decode UTF-8 to wchar_t, null-terminate result. */
1181 if (utf8_decode(tar->pax_entry, p,
1182 line_length - (p - attr) - 1)) {
1183 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1184 "Invalid UTF8 character in pax extended attribute");
1185 err = err_combine(err, ARCHIVE_WARN);
1188 /* Null-terminate 'key' value. */
1189 wp = key = tar->pax_entry;
1192 while (*wp && *wp != L'=')
1194 if (*wp == L'\0' || wp == NULL) {
1195 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1196 "Invalid pax extended attributes");
1197 return (ARCHIVE_WARN);
1201 /* Identify null-terminated 'value' portion. */
1204 /* Identify this attribute and set it in the entry. */
1205 err2 = pax_attribute(entry, st, key, value);
1206 err = err_combine(err, err2);
1208 /* Skip to next line */
1209 attr += line_length;
1210 attr_length -= line_length;
1216 pax_attribute_xattr(struct archive_entry *entry,
1217 wchar_t *name, wchar_t *value)
1219 char *name_decoded, *name_narrow;
1220 void *value_decoded;
1223 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1228 /* URL-decode name */
1229 name_narrow = wide_to_narrow(name);
1230 if (name_narrow == NULL)
1232 name_decoded = url_decode(name_narrow);
1234 if (name_decoded == NULL)
1237 /* Base-64 decode value */
1238 value_decoded = base64_decode(value, wcslen(value), &value_len);
1239 if (value_decoded == NULL) {
1244 archive_entry_xattr_add_entry(entry, name_decoded,
1245 value_decoded, value_len);
1248 free(value_decoded);
1253 * Parse a single key=value attribute. key/value pointers are
1254 * assumed to point into reasonably long-lived storage.
1256 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1257 * extensions should always have keywords of the form "VENDOR.attribute"
1258 * In particular, it's quite feasible to support many different
1259 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1260 * unique to this library (currently, there are none).
1262 * Investigate other vendor-specific extensions, as well and see if
1263 * any of them look useful.
1266 pax_attribute(struct archive_entry *entry, struct stat *st,
1267 wchar_t *key, wchar_t *value)
1274 /* Our extensions */
1275 /* TODO: Handle arbitrary extended attributes... */
1277 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1278 archive_entry_set_xxxxxx(entry, value);
1280 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1281 pax_attribute_xattr(entry, key, value);
1284 /* We support some keys used by the "star" archiver */
1285 if (wcscmp(key, L"SCHILY.acl.access")==0)
1286 __archive_entry_acl_parse_w(entry, value,
1287 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1288 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1289 __archive_entry_acl_parse_w(entry, value,
1290 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1291 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1292 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1293 minor(st->st_rdev));
1294 else if (wcscmp(key, L"SCHILY.devminor")==0)
1295 st->st_rdev = makedev(major(st->st_rdev),
1296 tar_atol10(value, wcslen(value)));
1297 else if (wcscmp(key, L"SCHILY.fflags")==0)
1298 archive_entry_copy_fflags_text_w(entry, value);
1299 else if (wcscmp(key, L"SCHILY.nlink")==0)
1300 st->st_nlink = tar_atol10(value, wcslen(value));
1303 if (wcscmp(key, L"atime")==0) {
1304 pax_time(value, &s, &n);
1306 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1310 if (wcscmp(key, L"ctime")==0) {
1311 pax_time(value, &s, &n);
1313 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1314 } else if (wcscmp(key, L"charset")==0) {
1315 /* TODO: Publish charset information in entry. */
1316 } else if (wcscmp(key, L"comment")==0) {
1317 /* TODO: Publish comment in entry. */
1321 if (wcscmp(key, L"gid")==0)
1322 st->st_gid = tar_atol10(value, wcslen(value));
1323 else if (wcscmp(key, L"gname")==0)
1324 archive_entry_copy_gname_w(entry, value);
1327 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1328 if (wcscmp(key, L"linkpath")==0) {
1329 if (archive_entry_hardlink(entry))
1330 archive_entry_copy_hardlink_w(entry, value);
1332 archive_entry_copy_symlink_w(entry, value);
1336 if (wcscmp(key, L"mtime")==0) {
1337 pax_time(value, &s, &n);
1339 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1343 if (wcscmp(key, L"path")==0)
1344 archive_entry_copy_pathname_w(entry, value);
1347 /* POSIX has reserved 'realtime.*' */
1350 /* POSIX has reserved 'security.*' */
1351 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1352 if (wcscmp(key, L"size")==0)
1353 st->st_size = tar_atol10(value, wcslen(value));
1356 if (wcscmp(key, L"uid")==0)
1357 st->st_uid = tar_atol10(value, wcslen(value));
1358 else if (wcscmp(key, L"uname")==0)
1359 archive_entry_copy_uname_w(entry, value);
1368 * parse a decimal time value, which may include a fractional portion
1371 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1377 int64_t limit, last_digit_limit;
1379 limit = max_int64 / 10;
1380 last_digit_limit = max_int64 % 10;
1388 while (*p >= '0' && *p <= '9') {
1391 (s == limit && digit > last_digit_limit)) {
1395 s = (s * 10) + digit;
1401 /* Calculate nanoseconds. */
1410 if (*p >= '0' && *p <= '9')
1411 *pn += (*p - '0') * l;
1418 * Parse GNU tar header
1421 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1422 struct stat *st, const void *h)
1424 const struct archive_entry_header_gnutar *header;
1429 * GNU header is like POSIX ustar, except 'prefix' is
1430 * replaced with some other fields. This also means the
1431 * filename is stored as in old-style archives.
1434 /* Grab fields common to all tar variants. */
1435 header_common(a, tar, entry, st, h);
1437 /* Copy filename over (to ensure null termination). */
1439 archive_strncpy(&(tar->entry_name), header->name,
1440 sizeof(header->name));
1441 archive_entry_set_pathname(entry, tar->entry_name.s);
1443 /* Fields common to ustar and GNU */
1444 /* XXX Can the following be factored out since it's common
1445 * to ustar and gnu tar? Is it okay to move it down into
1446 * header_common, perhaps? */
1447 archive_strncpy(&(tar->entry_uname),
1448 header->uname, sizeof(header->uname));
1449 archive_entry_set_uname(entry, tar->entry_uname.s);
1451 archive_strncpy(&(tar->entry_gname),
1452 header->gname, sizeof(header->gname));
1453 archive_entry_set_gname(entry, tar->entry_gname.s);
1455 /* Parse out device numbers only for char and block specials */
1456 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1457 st->st_rdev = makedev (
1458 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1459 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1463 tar->entry_bytes_remaining = st->st_size;
1464 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1466 /* Grab GNU-specific fields. */
1467 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1468 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1469 if (header->realsize[0] != 0) {
1470 st->st_size = tar_atol(header->realsize,
1471 sizeof(header->realsize));
1474 if (header->sparse[0].offset[0] != 0) {
1475 gnu_read_sparse_data(a, tar, header);
1477 if (header->isextended[0] != 0) {
1486 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1487 const struct archive_entry_header_gnutar *header)
1492 struct gnu_sparse sparse[21];
1496 const struct extended *ext;
1498 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1499 if (header->isextended[0] == 0)
1500 return (ARCHIVE_OK);
1503 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1505 return (ARCHIVE_FATAL);
1506 if (bytes_read < 512) {
1507 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1508 "Truncated tar archive "
1509 "detected while reading sparse file data");
1510 return (ARCHIVE_FATAL);
1512 (a->compression_read_consume)(a, 512);
1513 ext = (const struct extended *)data;
1514 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1515 } while (ext->isextended[0] != 0);
1516 if (tar->sparse_list != NULL)
1517 tar->entry_offset = tar->sparse_list->offset;
1518 return (ARCHIVE_OK);
1522 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1523 const struct gnu_sparse *sparse, int length)
1525 struct sparse_block *last;
1526 struct sparse_block *p;
1528 (void)a; /* UNUSED */
1530 last = tar->sparse_list;
1531 while (last != NULL && last->next != NULL)
1534 while (length > 0 && sparse->offset[0] != 0) {
1535 p = malloc(sizeof(*p));
1537 __archive_errx(1, "Out of memory");
1538 memset(p, 0, sizeof(*p));
1542 tar->sparse_list = p;
1544 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1546 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1553 * Convert text->integer.
1555 * Traditional tar formats (including POSIX) specify base-8 for
1556 * all of the standard numeric fields. This is a significant limitation
1558 * = file size is limited to 8GB
1559 * = rdevmajor and rdevminor are limited to 21 bits
1560 * = uid/gid are limited to 21 bits
1562 * There are two workarounds for this:
1563 * = pax extended headers, which use variable-length string fields
1564 * = GNU tar and STAR both allow either base-8 or base-256 in
1565 * most fields. The high bit is set to indicate base-256.
1567 * On read, this implementation supports both extensions.
1570 tar_atol(const char *p, unsigned char_cnt)
1573 * Technically, GNU tar considers a field to be in base-256
1574 * only if the first byte is 0xff or 0x80.
1577 return (tar_atol256(p, char_cnt));
1578 return (tar_atol8(p, char_cnt));
1582 * Note that this implementation does not (and should not!) obey
1583 * locale settings; you cannot simply substitute strtol here, since
1584 * it does obey locale.
1587 tar_atol8(const char *p, unsigned char_cnt)
1589 int64_t l, limit, last_digit_limit;
1590 int digit, sign, base;
1593 limit = max_int64 / base;
1594 last_digit_limit = max_int64 % base;
1596 while (*p == ' ' || *p == '\t')
1606 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1607 if (l>limit || (l == limit && digit > last_digit_limit)) {
1608 l = max_uint64; /* Truncate on overflow. */
1611 l = (l * base) + digit;
1614 return (sign < 0) ? -l : l;
1619 * Note that this implementation does not (and should not!) obey
1620 * locale settings; you cannot simply substitute strtol here, since
1621 * it does obey locale.
1624 tar_atol10(const wchar_t *p, unsigned char_cnt)
1626 int64_t l, limit, last_digit_limit;
1627 int base, digit, sign;
1630 limit = max_int64 / base;
1631 last_digit_limit = max_int64 % base;
1633 while (*p == ' ' || *p == '\t')
1643 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1644 if (l > limit || (l == limit && digit > last_digit_limit)) {
1645 l = max_uint64; /* Truncate on overflow. */
1648 l = (l * base) + digit;
1651 return (sign < 0) ? -l : l;
1655 * Parse a base-256 integer. This is just a straight signed binary
1656 * value in big-endian order, except that the high-order bit is
1657 * ignored. Remember that "int64_t" may or may not be exactly 64
1658 * bits; the implementation here tries to avoid making any assumptions
1659 * about the actual size of an int64_t. It does assume we're using
1660 * twos-complement arithmetic, though.
1663 tar_atol256(const char *_p, unsigned char_cnt)
1665 int64_t l, upper_limit, lower_limit;
1666 const unsigned char *p = (const unsigned char *)_p;
1668 upper_limit = max_int64 / 256;
1669 lower_limit = min_int64 / 256;
1671 /* Pad with 1 or 0 bits, depending on sign. */
1672 if ((0x40 & *p) == 0x40)
1676 l = (l << 6) | (0x3f & *p++);
1677 while (--char_cnt > 0) {
1678 if (l > upper_limit) {
1679 l = max_int64; /* Truncate on overflow */
1681 } else if (l < lower_limit) {
1685 l = (l << 8) | (0xff & (int64_t)*p++);
1691 utf8_decode(wchar_t *dest, const char *src, size_t length)
1697 while (length > 0) {
1698 n = UTF8_mbrtowc(dest, src, length);
1710 * Copied and simplified from FreeBSD libc/locale.
1713 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1715 int ch, i, len, mask;
1718 if (s == NULL || n == 0 || pwc == NULL)
1722 * Determine the number of octets that make up this character from
1723 * the first octet, and a mask that extracts the interesting bits of
1726 ch = (unsigned char)*s;
1727 if ((ch & 0x80) == 0) {
1730 } else if ((ch & 0xe0) == 0xc0) {
1733 } else if ((ch & 0xf0) == 0xe0) {
1736 } else if ((ch & 0xf8) == 0xf0) {
1739 } else if ((ch & 0xfc) == 0xf8) {
1742 } else if ((ch & 0xfe) == 0xfc) {
1746 /* Invalid first byte; convert to '?' */
1751 if (n < (size_t)len) {
1752 /* Invalid first byte; convert to '?' */
1758 * Decode the octet sequence representing the character in chunks
1759 * of 6 bits, most significant first.
1761 wch = (unsigned char)*s++ & mask;
1764 if ((*s & 0xc0) != 0x80) {
1765 /* Invalid intermediate byte; consume one byte and
1774 /* Assign the value to the output; out-of-range values
1775 * just get truncated. */
1776 *pwc = (wchar_t)wch;
1779 * If platform has WCHAR_MAX, we can do something
1780 * more sensible with out-of-range values.
1782 if (wch >= WCHAR_MAX)
1785 /* Return number of bytes input consumed: 0 for end-of-string. */
1786 return (wch == L'\0' ? 0 : len);
1791 * base64_decode - Base64 decode
1793 * This accepts most variations of base-64 encoding, including:
1794 * * with or without line breaks
1795 * * with or without the final group padded with '=' or '_' characters
1796 * (The most economical Base-64 variant does not pad the last group and
1797 * omits line breaks; RFC1341 used for MIME requires both.)
1800 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1802 static const unsigned char digits[64] =
1803 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1804 static unsigned char decode_table[128];
1807 /* If the decode table is not yet initialized, prepare it. */
1808 if (decode_table[digits[1]] != 1) {
1810 memset(decode_table, 0xff, sizeof(decode_table));
1811 for (i = 0; i < sizeof(digits); i++)
1812 decode_table[digits[i]] = i;
1815 /* Allocate enough space to hold the entire output. */
1816 /* Note that we may not use all of this... */
1817 out = malloc((len * 3 + 3) / 4);
1825 /* Collect the next group of (up to) four characters. */
1828 while (group_size < 4 && len > 0) {
1829 /* '=' or '_' padding indicates final group. */
1830 if (*src == '=' || *src == '_') {
1834 /* Skip illegal characters (including line breaks) */
1835 if (*src > 127 || *src < 32
1836 || decode_table[*src] == 0xff) {
1842 v |= decode_table[*src++];
1846 /* Align a short group properly. */
1847 v <<= 6 * (4 - group_size);
1848 /* Unpack the group we just collected. */
1849 switch (group_size) {
1850 case 4: d[2] = v & 0xff;
1852 case 3: d[1] = (v >> 8) & 0xff;
1854 case 2: d[0] = (v >> 16) & 0xff;
1856 case 1: /* this is invalid! */
1859 d += group_size * 3 / 4;
1867 * This is a little tricky because the C99 standard wcstombs()
1868 * function returns the number of bytes that were converted,
1869 * not the number that should be converted. As a result,
1870 * we can never accurately size the output buffer (without
1871 * doing a tedious output size calculation in advance).
1872 * This approach (try a conversion, then try again if it fails)
1873 * will almost always succeed on the first try, and is thus
1874 * much faster, at the cost of sometimes requiring multiple
1875 * passes while we expand the buffer.
1878 wide_to_narrow(const wchar_t *wval)
1880 int converted_length;
1881 /* Guess an output buffer size and try the conversion. */
1882 int alloc_length = wcslen(wval) * 3;
1883 char *mbs_val = malloc(alloc_length + 1);
1884 if (mbs_val == NULL)
1886 converted_length = wcstombs(mbs_val, wval, alloc_length);
1888 /* If we exhausted the buffer, resize and try again. */
1889 while (converted_length >= alloc_length) {
1892 mbs_val = malloc(alloc_length + 1);
1893 if (mbs_val == NULL)
1895 converted_length = wcstombs(mbs_val, wval, alloc_length);
1898 /* Ensure a trailing null and return the final string. */
1899 mbs_val[alloc_length] = '\0';
1904 url_decode(const char *in)
1909 out = malloc(strlen(in) + 1);
1912 for (s = in, d = out; *s != '\0'; ) {
1914 /* Try to convert % escape */
1915 int digit1 = tohex(s[1]);
1916 int digit2 = tohex(s[2]);
1917 if (digit1 >= 0 && digit2 >= 0) {
1918 /* Looks good, consume three chars */
1920 /* Convert output */
1921 *d++ = ((digit1 << 4) | digit2);
1924 /* Else fall through and treat '%' as normal char */
1935 if (c >= '0' && c <= '9')
1937 else if (c >= 'A' && c <= 'F')
1938 return (c - 'A' + 10);
1939 else if (c >= 'a' && c <= 'f')
1940 return (c - 'a' + 10);