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$");
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 static int wcscmp(const wchar_t *s1, const wchar_t *s2)
52 while (*s1 && diff == 0)
53 diff = (int)*++s1 - (int)*++s2;
56 static size_t wcslen(const wchar_t *s)
66 #include "archive_entry.h"
67 #include "archive_private.h"
70 * Layout of POSIX 'ustar' tar header.
72 struct archive_entry_header_ustar {
81 char linkname[100]; /* "old format" header ends here */
82 char magic[6]; /* For POSIX: "ustar\0" */
83 char version[2]; /* For POSIX: "00" */
92 * Structure of GNU tar header
99 struct archive_entry_header_gnutar {
109 char magic[8]; /* "ustar \0" (note blank/blank/null at end) */
119 struct gnu_sparse sparse[4];
123 * GNU doesn't use POSIX 'prefix' field; they use the 'L' (longname)
129 * Data specific to this format.
131 struct sparse_block {
132 struct sparse_block *next;
138 struct archive_string acl_text;
139 struct archive_string entry_name;
140 struct archive_string entry_linkname;
141 struct archive_string entry_uname;
142 struct archive_string entry_gname;
143 struct archive_string longlink;
144 struct archive_string longname;
145 struct archive_string pax_header;
146 struct archive_string pax_global;
148 size_t pax_entry_length;
149 int header_recursion_depth;
150 off_t entry_bytes_remaining;
153 struct sparse_block *sparse_list;
156 static size_t UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n);
157 static int archive_block_is_null(const unsigned char *p);
158 static char *base64_decode(const wchar_t *, size_t, size_t *);
159 static int gnu_read_sparse_data(struct archive *, struct tar *,
160 const struct archive_entry_header_gnutar *header);
161 static void gnu_parse_sparse_data(struct archive *, struct tar *,
162 const struct gnu_sparse *sparse, int length);
163 static int header_Solaris_ACL(struct archive *, struct tar *,
164 struct archive_entry *, struct stat *, const void *);
165 static int header_common(struct archive *, struct tar *,
166 struct archive_entry *, struct stat *, const void *);
167 static int header_old_tar(struct archive *, struct tar *,
168 struct archive_entry *, struct stat *, const void *);
169 static int header_pax_extensions(struct archive *, struct tar *,
170 struct archive_entry *, struct stat *, const void *);
171 static int header_pax_global(struct archive *, struct tar *,
172 struct archive_entry *, struct stat *, const void *h);
173 static int header_longlink(struct archive *, struct tar *,
174 struct archive_entry *, struct stat *, const void *h);
175 static int header_longname(struct archive *, struct tar *,
176 struct archive_entry *, struct stat *, const void *h);
177 static int header_volume(struct archive *, struct tar *,
178 struct archive_entry *, struct stat *, const void *h);
179 static int header_ustar(struct archive *, struct tar *,
180 struct archive_entry *, struct stat *, const void *h);
181 static int header_gnutar(struct archive *, struct tar *,
182 struct archive_entry *, struct stat *, const void *h);
183 static int archive_read_format_tar_bid(struct archive *);
184 static int archive_read_format_tar_cleanup(struct archive *);
185 static int archive_read_format_tar_read_data(struct archive *a,
186 const void **buff, size_t *size, off_t *offset);
187 static int archive_read_format_tar_read_header(struct archive *,
188 struct archive_entry *);
189 static int checksum(struct archive *, const void *);
190 static int pax_attribute(struct archive_entry *, struct stat *,
191 wchar_t *key, wchar_t *value);
192 static int pax_header(struct archive *, struct tar *,
193 struct archive_entry *, struct stat *, char *attr);
194 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
195 static int read_body_to_string(struct archive *, struct tar *,
196 struct archive_string *, const void *h);
197 static int64_t tar_atol(const char *, unsigned);
198 static int64_t tar_atol10(const wchar_t *, unsigned);
199 static int64_t tar_atol256(const char *, unsigned);
200 static int64_t tar_atol8(const char *, unsigned);
201 static int tar_read_header(struct archive *, struct tar *,
202 struct archive_entry *, struct stat *);
203 static int tohex(int c);
204 static char *url_decode(const char *);
205 static int utf8_decode(wchar_t *, const char *, size_t length);
206 static char *wide_to_narrow(const wchar_t *wval);
209 * ANSI C99 defines constants for these, but not everyone supports
210 * those constants, so I define a couple of static variables here and
211 * compute the values. These calculations should be portable to any
212 * 2s-complement architecture.
215 static const uint64_t max_uint64 = UINT64_MAX;
217 static const uint64_t max_uint64 = ~(uint64_t)0;
220 static const int64_t max_int64 = INT64_MAX;
222 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
225 static const int64_t min_int64 = INT64_MIN;
227 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
231 archive_read_support_format_gnutar(struct archive *a)
233 return (archive_read_support_format_tar(a));
238 archive_read_support_format_tar(struct archive *a)
243 tar = malloc(sizeof(*tar));
245 archive_set_error(a, ENOMEM, "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,
255 archive_read_format_tar_cleanup);
263 archive_read_format_tar_cleanup(struct archive *a)
267 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 *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_format != 0 &&
296 (a->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_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_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(h)) {
336 /* If it's a known tar file, end-of-archive is definite. */
337 if ((a->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. */
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 *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 = *(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 *a,
457 const void **buff, size_t *size, off_t *offset)
461 struct sparse_block *p;
463 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);
481 return (ARCHIVE_FATAL);
482 if (bytes_read > tar->entry_bytes_remaining)
483 bytes_read = tar->entry_bytes_remaining;
484 if (tar->sparse_list != NULL) {
485 /* Don't read more than is available in the
486 * current sparse block. */
487 if (tar->sparse_list->remaining < bytes_read)
488 bytes_read = tar->sparse_list->remaining;
489 tar->entry_offset = tar->sparse_list->offset;
490 tar->sparse_list->remaining -= bytes_read;
491 tar->sparse_list->offset += bytes_read;
494 *offset = tar->entry_offset;
495 tar->entry_offset += bytes_read;
496 tar->entry_bytes_remaining -= bytes_read;
497 (a->compression_read_consume)(a, bytes_read);
500 while (tar->entry_padding > 0) {
501 bytes_read = (a->compression_read_ahead)(a, buff, 1);
503 return (ARCHIVE_FATAL);
504 if (bytes_read > tar->entry_padding)
505 bytes_read = tar->entry_padding;
506 (a->compression_read_consume)(a, bytes_read);
507 tar->entry_padding -= bytes_read;
511 *offset = tar->entry_offset;
512 return (ARCHIVE_EOF);
517 * This function recursively interprets all of the headers associated
518 * with a single entry.
521 tar_read_header(struct archive *a, struct tar *tar,
522 struct archive_entry *entry, struct stat *st)
527 const struct archive_entry_header_ustar *header;
529 /* Read 512-byte header record */
530 bytes = (a->compression_read_ahead)(a, &h, 512);
533 * If we're here, it's becase the _bid function accepted
534 * this file. So just call a short read end-of-archive
535 * and be done with it.
537 return (ARCHIVE_EOF);
539 (a->compression_read_consume)(a, 512);
541 /* Check for end-of-archive mark. */
542 if (((*(const char *)h)==0) && archive_block_is_null(h)) {
543 /* Try to consume a second all-null record, as well. */
544 bytes = (a->compression_read_ahead)(a, &h, 512);
546 (a->compression_read_consume)(a, bytes);
547 archive_set_error(a, 0, NULL);
548 return (ARCHIVE_EOF);
552 * Note: If the checksum fails and we return ARCHIVE_RETRY,
553 * then the client is likely to just retry. This is a very
554 * crude way to search for the next valid header!
556 * TODO: Improve this by implementing a real header scan.
558 if (!checksum(a, h)) {
559 archive_set_error(a, EINVAL, "Damaged tar archive");
560 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
563 if (++tar->header_recursion_depth > 32) {
564 archive_set_error(a, EINVAL, "Too many special headers");
565 return (ARCHIVE_WARN);
568 /* Determine the format variant. */
570 switch(header->typeflag[0]) {
571 case 'A': /* Solaris tar ACL */
572 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
573 a->archive_format_name = "Solaris tar";
574 err = header_Solaris_ACL(a, tar, entry, st, h);
576 case 'g': /* POSIX-standard 'g' header. */
577 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
578 a->archive_format_name = "POSIX pax interchange format";
579 err = header_pax_global(a, tar, entry, st, h);
581 case 'K': /* Long link name (GNU tar, others) */
582 err = header_longlink(a, tar, entry, st, h);
584 case 'L': /* Long filename (GNU tar, others) */
585 err = header_longname(a, tar, entry, st, h);
587 case 'V': /* GNU volume header */
588 err = header_volume(a, tar, entry, st, h);
590 case 'X': /* Used by SUN tar; same as 'x'. */
591 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
592 a->archive_format_name =
593 "POSIX pax interchange format (Sun variant)";
594 err = header_pax_extensions(a, tar, entry, st, h);
596 case 'x': /* POSIX-standard 'x' header. */
597 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
598 a->archive_format_name = "POSIX pax interchange format";
599 err = header_pax_extensions(a, tar, entry, st, h);
602 if (memcmp(header->magic, "ustar \0", 8) == 0) {
603 a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
604 a->archive_format_name = "GNU tar format";
605 err = header_gnutar(a, tar, entry, st, h);
606 } else if (memcmp(header->magic, "ustar", 5) == 0) {
607 if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
608 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
609 a->archive_format_name = "POSIX ustar format";
611 err = header_ustar(a, tar, entry, st, h);
613 a->archive_format = ARCHIVE_FORMAT_TAR;
614 a->archive_format_name = "tar (non-POSIX)";
615 err = header_old_tar(a, tar, entry, st, h);
618 --tar->header_recursion_depth;
623 * Return true if block checksum is correct.
626 checksum(struct archive *a, const void *h)
628 const unsigned char *bytes;
629 const struct archive_entry_header_ustar *header;
632 (void)a; /* UNUSED */
637 * Test the checksum. Note that POSIX specifies _unsigned_
638 * bytes for this calculation.
640 sum = tar_atol(header->checksum, sizeof(header->checksum));
642 for (i = 0; i < 148; i++)
643 check += (unsigned char)bytes[i];
647 check += (unsigned char)bytes[i];
652 * Repeat test with _signed_ bytes, just in case this archive
653 * was created by an old BSD, Solaris, or HP-UX tar with a
654 * broken checksum calculation.
657 for (i = 0; i < 148; i++)
658 check += (signed char)bytes[i];
662 check += (signed char)bytes[i];
670 * Return true if this block contains only nulls.
673 archive_block_is_null(const unsigned char *p)
677 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
684 * Interpret 'A' Solaris ACL header
687 header_Solaris_ACL(struct archive *a, struct tar *tar,
688 struct archive_entry *entry, struct stat *st, const void *h)
694 err = read_body_to_string(a, tar, &(tar->acl_text), h);
695 err2 = tar_read_header(a, tar, entry, st);
696 err = err_combine(err, err2);
698 /* XXX Ensure p doesn't overrun acl_text */
700 /* Skip leading octal number. */
701 /* XXX TODO: Parse the octal number and sanity-check it. */
707 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
709 utf8_decode(wp, p, strlen(p));
710 err2 = __archive_entry_acl_parse_w(entry, wp,
711 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
712 err = err_combine(err, err2);
720 * Interpret 'K' long linkname header.
723 header_longlink(struct archive *a, struct tar *tar,
724 struct archive_entry *entry, struct stat *st, const void *h)
728 err = read_body_to_string(a, tar, &(tar->longlink), h);
729 err2 = tar_read_header(a, tar, entry, st);
730 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
731 /* Set symlink if symlink already set, else hardlink. */
732 archive_entry_set_link(entry, tar->longlink.s);
734 return (err_combine(err, err2));
738 * Interpret 'L' long filename header.
741 header_longname(struct archive *a, struct tar *tar,
742 struct archive_entry *entry, struct stat *st, const void *h)
746 err = read_body_to_string(a, tar, &(tar->longname), h);
747 /* Read and parse "real" header, then override name. */
748 err2 = tar_read_header(a, tar, entry, st);
749 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
750 archive_entry_set_pathname(entry, tar->longname.s);
751 return (err_combine(err, err2));
756 * Interpret 'V' GNU tar volume header.
759 header_volume(struct archive *a, struct tar *tar,
760 struct archive_entry *entry, struct stat *st, const void *h)
764 /* Just skip this and read the next header. */
765 return (tar_read_header(a, tar, entry, st));
769 * Read body of an archive entry into an archive_string object.
772 read_body_to_string(struct archive *a, struct tar *tar,
773 struct archive_string *as, const void *h)
775 off_t size, padded_size;
776 ssize_t bytes_read, bytes_to_copy;
777 const struct archive_entry_header_ustar *header;
781 (void)tar; /* UNUSED */
783 size = tar_atol(header->size, sizeof(header->size));
785 /* Read the body into the string. */
786 archive_string_ensure(as, size+1);
787 padded_size = (size + 511) & ~ 511;
789 while (padded_size > 0) {
790 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
792 return (ARCHIVE_FATAL);
793 if (bytes_read > padded_size)
794 bytes_read = padded_size;
795 (a->compression_read_consume)(a, bytes_read);
796 bytes_to_copy = bytes_read;
797 if ((off_t)bytes_to_copy > size)
798 bytes_to_copy = (ssize_t)size;
799 memcpy(dest, src, bytes_to_copy);
800 dest += bytes_to_copy;
801 size -= bytes_to_copy;
802 padded_size -= bytes_read;
809 * Parse out common header elements.
811 * This would be the same as header_old_tar, except that the
812 * filename is handled slightly differently for old and POSIX
813 * entries (POSIX entries support a 'prefix'). This factoring
814 * allows header_old_tar and header_ustar
815 * to handle filenames differently, while still putting most of the
816 * common parsing into one place.
819 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
820 struct stat *st, const void *h)
822 const struct archive_entry_header_ustar *header;
825 (void)a; /* UNUSED */
828 if (header->linkname[0])
829 archive_strncpy(&(tar->entry_linkname), header->linkname,
830 sizeof(header->linkname));
832 archive_string_empty(&(tar->entry_linkname));
834 /* Parse out the numeric fields (all are octal) */
835 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
836 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
837 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
838 st->st_size = tar_atol(header->size, sizeof(header->size));
839 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
841 /* Handle the tar type flag appropriately. */
842 tartype = header->typeflag[0];
843 st->st_mode &= ~S_IFMT;
846 case '1': /* Hard link */
847 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
849 * The following may seem odd, but: Technically, tar
850 * does not store the file type for a "hard link"
851 * entry, only the fact that it is a hard link. So, I
852 * leave the type zero normally. But, pax interchange
853 * format allows hard links to have data, which
854 * implies that the underlying entry is a regular
858 st->st_mode |= S_IFREG;
861 * A tricky point: Traditionally, tar readers have
862 * ignored the size field when reading hardlink
863 * entries, and some writers put non-zero sizes even
864 * though the body is empty. POSIX.1-2001 broke with
865 * this tradition by permitting hardlink entries to
866 * store valid bodies in pax interchange format, but
867 * not in ustar format. Since there is no hard and
868 * fast way to distinguish pax interchange from
869 * earlier archives (the 'x' and 'g' entries are
870 * optional, after all), we need a heuristic. Here, I
871 * use the bid function to test whether or not there's
872 * a valid header following. Of course, if we know
873 * this is pax interchange format, then we must obey
876 * This heuristic will only fail for a pax interchange
877 * archive that is storing hardlink bodies, no pax
878 * extended attribute entries have yet occurred, and
879 * we encounter a hardlink entry for a file that is
880 * itself an uncompressed tar archive.
882 if (st->st_size > 0 &&
883 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
884 archive_read_format_tar_bid(a) > 50)
887 case '2': /* Symlink */
888 st->st_mode |= S_IFLNK;
890 archive_entry_set_symlink(entry, tar->entry_linkname.s);
892 case '3': /* Character device */
893 st->st_mode |= S_IFCHR;
896 case '4': /* Block device */
897 st->st_mode |= S_IFBLK;
901 st->st_mode |= S_IFDIR;
904 case '6': /* FIFO device */
905 st->st_mode |= S_IFIFO;
908 case 'D': /* GNU incremental directory type */
910 * No special handling is actually required here.
911 * It might be nice someday to preprocess the file list and
912 * provide it to the client, though.
914 st->st_mode |= S_IFDIR;
916 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
918 * As far as I can tell, this is just like a regular file
919 * entry, except that the contents should be _appended_ to
920 * the indicated file at the indicated offset. This may
921 * require some API work to fully support.
924 case 'N': /* Old GNU "long filename" entry. */
925 /* The body of this entry is a script for renaming
926 * previously-extracted entries. Ugh. It will never
927 * be supported by libarchive. */
928 st->st_mode |= S_IFREG;
930 case 'S': /* GNU sparse files */
932 * Sparse files are really just regular files with
933 * sparse information in the extended area.
936 default: /* Regular file and non-standard types */
938 * Per POSIX: non-recognized types should always be
939 * treated as regular files.
941 st->st_mode |= S_IFREG;
948 * Parse out header elements for "old-style" tar archives.
951 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
952 struct stat *st, const void *h)
954 const struct archive_entry_header_ustar *header;
956 /* Copy filename over (to ensure null termination). */
958 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
959 archive_entry_set_pathname(entry, tar->entry_name.s);
961 /* Grab rest of common fields */
962 header_common(a, tar, entry, st, h);
964 tar->entry_bytes_remaining = st->st_size;
965 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
970 * Parse a file header for a pax extended archive entry.
973 header_pax_global(struct archive *a, struct tar *tar,
974 struct archive_entry *entry, struct stat *st, const void *h)
978 err = read_body_to_string(a, tar, &(tar->pax_global), h);
979 err2 = tar_read_header(a, tar, entry, st);
980 return (err_combine(err, err2));
984 header_pax_extensions(struct archive *a, struct tar *tar,
985 struct archive_entry *entry, struct stat *st, const void *h)
989 read_body_to_string(a, tar, &(tar->pax_header), h);
991 /* Parse the next header. */
992 err = tar_read_header(a, tar, entry, st);
995 * TODO: Parse global/default options into 'entry' struct here
996 * before handling file-specific options.
998 * This design (parse standard header, then overwrite with pax
999 * extended attribute data) usually works well, but isn't ideal;
1000 * it would be better to parse the pax extended attributes first
1001 * and then skip any fields in the standard header that were
1002 * defined in the pax header.
1004 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1005 err = err_combine(err, err2);
1006 tar->entry_bytes_remaining = st->st_size;
1007 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1013 * Parse a file header for a Posix "ustar" archive entry. This also
1014 * handles "pax" or "extended ustar" entries.
1017 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1018 struct stat *st, const void *h)
1020 const struct archive_entry_header_ustar *header;
1021 struct archive_string *as;
1025 /* Copy name into an internal buffer to ensure null-termination. */
1026 as = &(tar->entry_name);
1027 if (header->prefix[0]) {
1028 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1029 if (as->s[archive_strlen(as) - 1] != '/')
1030 archive_strappend_char(as, '/');
1031 archive_strncat(as, header->name, sizeof(header->name));
1033 archive_strncpy(as, header->name, sizeof(header->name));
1035 archive_entry_set_pathname(entry, as->s);
1037 /* Handle rest of common fields. */
1038 header_common(a, tar, entry, st, h);
1040 /* Handle POSIX ustar fields. */
1041 archive_strncpy(&(tar->entry_uname), header->uname,
1042 sizeof(header->uname));
1043 archive_entry_set_uname(entry, tar->entry_uname.s);
1045 archive_strncpy(&(tar->entry_gname), header->gname,
1046 sizeof(header->gname));
1047 archive_entry_set_gname(entry, tar->entry_gname.s);
1049 /* Parse out device numbers only for char and block specials. */
1050 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1051 st->st_rdev = makedev(
1052 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1053 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1056 tar->entry_bytes_remaining = st->st_size;
1057 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1064 * Parse the pax extended attributes record.
1066 * Returns non-zero if there's an error in the data.
1069 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1070 struct stat *st, char *attr)
1072 size_t attr_length, l, line_length;
1074 wchar_t *key, *wp, *value;
1077 attr_length = strlen(attr);
1079 while (attr_length > 0) {
1080 /* Parse decimal length field at start of line. */
1083 line = p = attr; /* Record start of line. */
1090 if (*p < '0' || *p > '9')
1093 line_length += *p - '0';
1094 if (line_length > 999999) {
1095 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1096 "Rejecting pax extended attribute > 1MB");
1097 return (ARCHIVE_WARN);
1103 if (line_length > attr_length)
1106 /* Ensure pax_entry buffer is big enough. */
1107 if (tar->pax_entry_length <= line_length) {
1108 wchar_t *old_entry = tar->pax_entry;
1110 if (tar->pax_entry_length <= 0)
1111 tar->pax_entry_length = 1024;
1112 while (tar->pax_entry_length <= line_length + 1)
1113 tar->pax_entry_length *= 2;
1115 old_entry = tar->pax_entry;
1116 tar->pax_entry = realloc(tar->pax_entry,
1117 tar->pax_entry_length * sizeof(wchar_t));
1118 if (tar->pax_entry == NULL) {
1120 archive_set_error(a, ENOMEM,
1122 return (ARCHIVE_FATAL);
1126 /* Decode UTF-8 to wchar_t, null-terminate result. */
1127 if (utf8_decode(tar->pax_entry, p,
1128 line_length - (p - attr) - 1)) {
1129 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1130 "Invalid UTF8 character in pax extended attribute");
1131 err = err_combine(err, ARCHIVE_WARN);
1134 /* Null-terminate 'key' value. */
1135 wp = key = tar->pax_entry;
1138 while (*wp && *wp != L'=')
1140 if (*wp == L'\0' || wp == NULL) {
1141 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1142 "Invalid pax extended attributes");
1143 return (ARCHIVE_WARN);
1147 /* Identify null-terminated 'value' portion. */
1150 /* Identify this attribute and set it in the entry. */
1151 err2 = pax_attribute(entry, st, key, value);
1152 err = err_combine(err, err2);
1154 /* Skip to next line */
1155 attr += line_length;
1156 attr_length -= line_length;
1162 pax_attribute_xattr(struct archive_entry *entry,
1163 wchar_t *name, wchar_t *value)
1165 char *name_decoded, *name_narrow;
1166 void *value_decoded;
1169 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1174 /* URL-decode name */
1175 name_narrow = wide_to_narrow(name);
1176 if (name_narrow == NULL)
1178 name_decoded = url_decode(name_narrow);
1180 if (name_decoded == NULL)
1183 /* Base-64 decode value */
1184 value_decoded = base64_decode(value, wcslen(value), &value_len);
1185 if (value_decoded == NULL) {
1190 archive_entry_xattr_add_entry(entry, name_decoded,
1191 value_decoded, value_len);
1194 free(value_decoded);
1199 * Parse a single key=value attribute. key/value pointers are
1200 * assumed to point into reasonably long-lived storage.
1202 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1203 * extensions should always have keywords of the form "VENDOR.attribute"
1204 * In particular, it's quite feasible to support many different
1205 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1206 * unique to this library (currently, there are none).
1208 * Investigate other vendor-specific extensions, as well and see if
1209 * any of them look useful.
1212 pax_attribute(struct archive_entry *entry, struct stat *st,
1213 wchar_t *key, wchar_t *value)
1220 /* Our extensions */
1221 /* TODO: Handle arbitrary extended attributes... */
1223 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1224 archive_entry_set_xxxxxx(entry, value);
1226 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1227 pax_attribute_xattr(entry, key, value);
1230 /* We support some keys used by the "star" archiver */
1231 if (wcscmp(key, L"SCHILY.acl.access")==0)
1232 __archive_entry_acl_parse_w(entry, value,
1233 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1234 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1235 __archive_entry_acl_parse_w(entry, value,
1236 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1237 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1238 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1239 minor(st->st_rdev));
1240 else if (wcscmp(key, L"SCHILY.devminor")==0)
1241 st->st_rdev = makedev(major(st->st_rdev),
1242 tar_atol10(value, wcslen(value)));
1243 else if (wcscmp(key, L"SCHILY.fflags")==0)
1244 archive_entry_copy_fflags_text_w(entry, value);
1245 else if (wcscmp(key, L"SCHILY.nlink")==0)
1246 st->st_nlink = tar_atol10(value, wcslen(value));
1249 if (wcscmp(key, L"atime")==0) {
1250 pax_time(value, &s, &n);
1252 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1256 if (wcscmp(key, L"ctime")==0) {
1257 pax_time(value, &s, &n);
1259 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1260 } else if (wcscmp(key, L"charset")==0) {
1261 /* TODO: Publish charset information in entry. */
1262 } else if (wcscmp(key, L"comment")==0) {
1263 /* TODO: Publish comment in entry. */
1267 if (wcscmp(key, L"gid")==0)
1268 st->st_gid = tar_atol10(value, wcslen(value));
1269 else if (wcscmp(key, L"gname")==0)
1270 archive_entry_copy_gname_w(entry, value);
1273 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1274 if (wcscmp(key, L"linkpath")==0) {
1275 if (archive_entry_hardlink(entry))
1276 archive_entry_copy_hardlink_w(entry, value);
1278 archive_entry_copy_symlink_w(entry, value);
1282 if (wcscmp(key, L"mtime")==0) {
1283 pax_time(value, &s, &n);
1285 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1289 if (wcscmp(key, L"path")==0)
1290 archive_entry_copy_pathname_w(entry, value);
1293 /* POSIX has reserved 'realtime.*' */
1296 /* POSIX has reserved 'security.*' */
1297 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1298 if (wcscmp(key, L"size")==0)
1299 st->st_size = tar_atol10(value, wcslen(value));
1302 if (wcscmp(key, L"uid")==0)
1303 st->st_uid = tar_atol10(value, wcslen(value));
1304 else if (wcscmp(key, L"uname")==0)
1305 archive_entry_copy_uname_w(entry, value);
1314 * parse a decimal time value, which may include a fractional portion
1317 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1323 int64_t limit, last_digit_limit;
1325 limit = max_int64 / 10;
1326 last_digit_limit = max_int64 % 10;
1334 while (*p >= '0' && *p <= '9') {
1337 (s == limit && digit > last_digit_limit)) {
1341 s = (s * 10) + digit;
1347 /* Calculate nanoseconds. */
1356 if (*p >= '0' && *p <= '9')
1357 *pn += (*p - '0') * l;
1364 * Parse GNU tar header
1367 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1368 struct stat *st, const void *h)
1370 const struct archive_entry_header_gnutar *header;
1375 * GNU header is like POSIX ustar, except 'prefix' is
1376 * replaced with some other fields. This also means the
1377 * filename is stored as in old-style archives.
1380 /* Grab fields common to all tar variants. */
1381 header_common(a, tar, entry, st, h);
1383 /* Copy filename over (to ensure null termination). */
1385 archive_strncpy(&(tar->entry_name), header->name,
1386 sizeof(header->name));
1387 archive_entry_set_pathname(entry, tar->entry_name.s);
1389 /* Fields common to ustar and GNU */
1390 /* XXX Can the following be factored out since it's common
1391 * to ustar and gnu tar? Is it okay to move it down into
1392 * header_common, perhaps? */
1393 archive_strncpy(&(tar->entry_uname),
1394 header->uname, sizeof(header->uname));
1395 archive_entry_set_uname(entry, tar->entry_uname.s);
1397 archive_strncpy(&(tar->entry_gname),
1398 header->gname, sizeof(header->gname));
1399 archive_entry_set_gname(entry, tar->entry_gname.s);
1401 /* Parse out device numbers only for char and block specials */
1402 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1403 st->st_rdev = makedev (
1404 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1405 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1409 tar->entry_bytes_remaining = st->st_size;
1410 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1412 /* Grab GNU-specific fields. */
1413 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1414 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1415 if (header->realsize[0] != 0) {
1416 st->st_size = tar_atol(header->realsize,
1417 sizeof(header->realsize));
1420 if (header->sparse[0].offset[0] != 0) {
1421 gnu_read_sparse_data(a, tar, header);
1423 if (header->isextended[0] != 0) {
1432 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1433 const struct archive_entry_header_gnutar *header)
1438 struct gnu_sparse sparse[21];
1442 const struct extended *ext;
1444 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1445 if (header->isextended[0] == 0)
1446 return (ARCHIVE_OK);
1449 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1451 return (ARCHIVE_FATAL);
1452 if (bytes_read < 512) {
1453 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1454 "Truncated tar archive "
1455 "detected while reading sparse file data");
1456 return (ARCHIVE_FATAL);
1458 (a->compression_read_consume)(a, 512);
1459 ext = (const struct extended *)data;
1460 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1461 } while (ext->isextended[0] != 0);
1462 if (tar->sparse_list != NULL)
1463 tar->entry_offset = tar->sparse_list->offset;
1464 return (ARCHIVE_OK);
1468 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1469 const struct gnu_sparse *sparse, int length)
1471 struct sparse_block *last;
1472 struct sparse_block *p;
1474 (void)a; /* UNUSED */
1476 last = tar->sparse_list;
1477 while (last != NULL && last->next != NULL)
1480 while (length > 0 && sparse->offset[0] != 0) {
1481 p = malloc(sizeof(*p));
1483 __archive_errx(1, "Out of memory");
1484 memset(p, 0, sizeof(*p));
1488 tar->sparse_list = p;
1490 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1492 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1499 * Convert text->integer.
1501 * Traditional tar formats (including POSIX) specify base-8 for
1502 * all of the standard numeric fields. This is a significant limitation
1504 * = file size is limited to 8GB
1505 * = rdevmajor and rdevminor are limited to 21 bits
1506 * = uid/gid are limited to 21 bits
1508 * There are two workarounds for this:
1509 * = pax extended headers, which use variable-length string fields
1510 * = GNU tar and STAR both allow either base-8 or base-256 in
1511 * most fields. The high bit is set to indicate base-256.
1513 * On read, this implementation supports both extensions.
1516 tar_atol(const char *p, unsigned char_cnt)
1519 * Technically, GNU tar considers a field to be in base-256
1520 * only if the first byte is 0xff or 0x80.
1523 return (tar_atol256(p, char_cnt));
1524 return (tar_atol8(p, char_cnt));
1528 * Note that this implementation does not (and should not!) obey
1529 * locale settings; you cannot simply substitute strtol here, since
1530 * it does obey locale.
1533 tar_atol8(const char *p, unsigned char_cnt)
1535 int64_t l, limit, last_digit_limit;
1536 int digit, sign, base;
1539 limit = max_int64 / base;
1540 last_digit_limit = max_int64 % base;
1542 while (*p == ' ' || *p == '\t')
1552 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1553 if (l>limit || (l == limit && digit > last_digit_limit)) {
1554 l = max_uint64; /* Truncate on overflow. */
1557 l = (l * base) + digit;
1560 return (sign < 0) ? -l : l;
1565 * Note that this implementation does not (and should not!) obey
1566 * locale settings; you cannot simply substitute strtol here, since
1567 * it does obey locale.
1570 tar_atol10(const wchar_t *p, unsigned char_cnt)
1572 int64_t l, limit, last_digit_limit;
1573 int base, digit, sign;
1576 limit = max_int64 / base;
1577 last_digit_limit = max_int64 % base;
1579 while (*p == ' ' || *p == '\t')
1589 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1590 if (l > limit || (l == limit && digit > last_digit_limit)) {
1591 l = max_uint64; /* Truncate on overflow. */
1594 l = (l * base) + digit;
1597 return (sign < 0) ? -l : l;
1601 * Parse a base-256 integer. This is just a straight signed binary
1602 * value in big-endian order, except that the high-order bit is
1603 * ignored. Remember that "int64_t" may or may not be exactly 64
1604 * bits; the implementation here tries to avoid making any assumptions
1605 * about the actual size of an int64_t. It does assume we're using
1606 * twos-complement arithmetic, though.
1609 tar_atol256(const char *_p, unsigned char_cnt)
1611 int64_t l, upper_limit, lower_limit;
1612 const unsigned char *p = (const unsigned char *)_p;
1614 upper_limit = max_int64 / 256;
1615 lower_limit = min_int64 / 256;
1617 /* Pad with 1 or 0 bits, depending on sign. */
1618 if ((0x40 & *p) == 0x40)
1622 l = (l << 6) | (0x3f & *p++);
1623 while (--char_cnt > 0) {
1624 if (l > upper_limit) {
1625 l = max_int64; /* Truncate on overflow */
1627 } else if (l < lower_limit) {
1631 l = (l << 8) | (0xff & (int64_t)*p++);
1637 utf8_decode(wchar_t *dest, const char *src, size_t length)
1643 while (length > 0) {
1644 n = UTF8_mbrtowc(dest, src, length);
1648 /* Invalid byte encountered; try to keep going. */
1662 * Copied from FreeBSD libc/locale.
1665 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1667 int ch, i, len, mask;
1668 unsigned long lbound, wch;
1671 /* Reset to initial shift state (no-op) */
1674 /* Incomplete multibyte sequence */
1675 return ((size_t)-2);
1678 * Determine the number of octets that make up this character from
1679 * the first octet, and a mask that extracts the interesting bits of
1682 * We also specify a lower bound for the character code to detect
1683 * redundant, non-"shortest form" encodings. For example, the
1684 * sequence C0 80 is _not_ a legal representation of the null
1685 * character. This enforces a 1-to-1 mapping between character
1686 * codes and their multibyte representations.
1688 ch = (unsigned char)*s;
1689 if ((ch & 0x80) == 0) {
1693 } else if ((ch & 0xe0) == 0xc0) {
1697 } else if ((ch & 0xf0) == 0xe0) {
1701 } else if ((ch & 0xf8) == 0xf0) {
1705 } else if ((ch & 0xfc) == 0xf8) {
1709 } else if ((ch & 0xfc) == 0xfc) {
1715 * Malformed input; input is not UTF-8.
1718 return ((size_t)-1);
1721 if (n < (size_t)len)
1722 /* Incomplete multibyte sequence */
1723 return ((size_t)-2);
1726 * Decode the octet sequence representing the character in chunks
1727 * of 6 bits, most significant first.
1729 wch = (unsigned char)*s++ & mask;
1732 if ((*s & 0xc0) != 0x80) {
1734 * Malformed input; bad characters in the middle
1738 return ((size_t)-1);
1745 * Malformed input; redundant encoding.
1748 return ((size_t)-1);
1751 /* Assign the value to the output; out-of-range values
1752 * just get truncated. */
1753 *pwc = (wchar_t)wch;
1756 * If platform has WCHAR_MAX, we can do something
1757 * more sensible with out-of-range values.
1759 if (wch >= WCHAR_MAX)
1763 return (wch == L'\0' ? 0 : len);
1768 * base64_decode - Base64 decode
1770 * This accepts most variations of base-64 encoding, including:
1771 * * with or without line breaks
1772 * * with or without the final group padded with '=' or '_' characters
1773 * (The most economical Base-64 variant does not pad the last group and
1774 * omits line breaks; RFC1341 used for MIME requires both.)
1777 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1779 static const unsigned char digits[64] =
1780 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1781 static unsigned char decode_table[128];
1784 /* If the decode table is not yet initialized, prepare it. */
1785 if (decode_table[digits[1]] != 1) {
1787 memset(decode_table, 0xff, sizeof(decode_table));
1788 for (i = 0; i < sizeof(digits); i++)
1789 decode_table[digits[i]] = i;
1792 /* Allocate enough space to hold the entire output. */
1793 /* Note that we may not use all of this... */
1794 out = malloc((len * 3 + 3) / 4);
1802 /* Collect the next group of (up to) four characters. */
1805 while (group_size < 4 && len > 0) {
1806 /* '=' or '_' padding indicates final group. */
1807 if (*src == '=' || *src == '_') {
1811 /* Skip illegal characters (including line breaks) */
1812 if (*src > 127 || *src < 32
1813 || decode_table[*src] == 0xff) {
1819 v |= decode_table[*src++];
1823 /* Align a short group properly. */
1824 v <<= 6 * (4 - group_size);
1825 /* Unpack the group we just collected. */
1826 switch (group_size) {
1827 case 4: d[2] = v & 0xff;
1829 case 3: d[1] = (v >> 8) & 0xff;
1831 case 2: d[0] = (v >> 16) & 0xff;
1833 case 1: /* this is invalid! */
1836 d += group_size * 3 / 4;
1844 * This is a little tricky because the C99 standard wcstombs()
1845 * function returns the number of bytes that were converted,
1846 * not the number that should be converted. As a result,
1847 * we can never accurately size the output buffer (without
1848 * doing a tedious output size calculation in advance).
1849 * This approach (try a conversion, then try again if it fails)
1850 * will almost always succeed on the first try, and is thus
1851 * much faster, at the cost of sometimes requiring multiple
1852 * passes while we expand the buffer.
1855 wide_to_narrow(const wchar_t *wval)
1857 int converted_length;
1858 /* Guess an output buffer size and try the conversion. */
1859 int alloc_length = wcslen(wval) * 3;
1860 char *mbs_val = malloc(alloc_length + 1);
1861 if (mbs_val == NULL)
1863 converted_length = wcstombs(mbs_val, wval, alloc_length);
1865 /* If we exhausted the buffer, resize and try again. */
1866 while (converted_length >= alloc_length) {
1869 mbs_val = malloc(alloc_length + 1);
1870 if (mbs_val == NULL)
1872 converted_length = wcstombs(mbs_val, wval, alloc_length);
1875 /* Ensure a trailing null and return the final string. */
1876 mbs_val[alloc_length] = '\0';
1881 url_decode(const char *in)
1886 out = malloc(strlen(in) + 1);
1889 for (s = in, d = out; *s != '\0'; ) {
1891 /* Try to convert % escape */
1892 int digit1 = tohex(s[1]);
1893 int digit2 = tohex(s[2]);
1894 if (digit1 >= 0 && digit2 >= 0) {
1895 /* Looks good, consume three chars */
1897 /* Convert output */
1898 *d++ = ((digit1 << 4) | digit2);
1901 /* Else fall through and treat '%' as normal char */
1912 if (c >= '0' && c <= '9')
1914 else if (c >= 'A' && c <= 'F')
1915 return (c - 'A' + 10);
1916 else if (c >= 'a' && c <= 'f')
1917 return (c - 'a' + 10);