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 /* 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_read_header(struct archive *,
197 struct archive_entry *);
198 static int checksum(struct archive *, const void *);
199 static int pax_attribute(struct archive_entry *, struct stat *,
200 wchar_t *key, wchar_t *value);
201 static int pax_header(struct archive *, struct tar *,
202 struct archive_entry *, struct stat *, char *attr);
203 static void pax_time(const wchar_t *, int64_t *sec, long *nanos);
204 static int read_body_to_string(struct archive *, struct tar *,
205 struct archive_string *, const void *h);
206 static int64_t tar_atol(const char *, unsigned);
207 static int64_t tar_atol10(const wchar_t *, unsigned);
208 static int64_t tar_atol256(const char *, unsigned);
209 static int64_t tar_atol8(const char *, unsigned);
210 static int tar_read_header(struct archive *, struct tar *,
211 struct archive_entry *, struct stat *);
212 static int tohex(int c);
213 static char *url_decode(const char *);
214 static int utf8_decode(wchar_t *, const char *, size_t length);
215 static char *wide_to_narrow(const wchar_t *wval);
218 * ANSI C99 defines constants for these, but not everyone supports
219 * those constants, so I define a couple of static variables here and
220 * compute the values. These calculations should be portable to any
221 * 2s-complement architecture.
224 static const uint64_t max_uint64 = UINT64_MAX;
226 static const uint64_t max_uint64 = ~(uint64_t)0;
229 static const int64_t max_int64 = INT64_MAX;
231 static const int64_t max_int64 = (int64_t)((~(uint64_t)0) >> 1);
234 static const int64_t min_int64 = INT64_MIN;
236 static const int64_t min_int64 = (int64_t)(~((~(uint64_t)0) >> 1));
240 archive_read_support_format_gnutar(struct archive *a)
242 return (archive_read_support_format_tar(a));
247 archive_read_support_format_tar(struct archive *a)
252 tar = malloc(sizeof(*tar));
254 archive_set_error(a, ENOMEM, "Can't allocate tar data");
255 return (ARCHIVE_FATAL);
257 memset(tar, 0, sizeof(*tar));
259 r = __archive_read_register_format(a, tar,
260 archive_read_format_tar_bid,
261 archive_read_format_tar_read_header,
262 archive_read_format_tar_read_data,
264 archive_read_format_tar_cleanup);
272 archive_read_format_tar_cleanup(struct archive *a)
276 tar = *(a->pformat_data);
277 archive_string_free(&tar->acl_text);
278 archive_string_free(&tar->entry_name);
279 archive_string_free(&tar->entry_linkname);
280 archive_string_free(&tar->entry_uname);
281 archive_string_free(&tar->entry_gname);
282 archive_string_free(&tar->pax_global);
283 archive_string_free(&tar->pax_header);
284 if (tar->pax_entry != NULL)
285 free(tar->pax_entry);
287 *(a->pformat_data) = NULL;
293 archive_read_format_tar_bid(struct archive *a)
298 const struct archive_entry_header_ustar *header;
301 * If we're already reading a non-tar file, don't
304 if (a->archive_format != 0 &&
305 (a->archive_format & ARCHIVE_FORMAT_BASE_MASK) !=
311 * If we're already reading a tar format, start the bid at 1 as
314 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
318 /* Now let's look at the actual header and see if it matches. */
319 if (a->compression_read_ahead != NULL)
320 bytes_read = (a->compression_read_ahead)(a, &h, 512);
322 bytes_read = 0; /* Empty file. */
324 return (ARCHIVE_FATAL);
325 if (bytes_read == 0 && bid > 0) {
326 /* An archive without a proper end-of-archive marker. */
327 /* Hold our nose and bid 1 anyway. */
330 if (bytes_read < 512) {
331 /* If it's a new archive, then just return a zero bid. */
335 * If we already know this is a tar archive,
336 * then we have a problem.
338 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
339 "Truncated tar archive");
340 return (ARCHIVE_FATAL);
343 /* If it's an end-of-archive mark, we can handle it. */
344 if ((*(const char *)h) == 0 && archive_block_is_null(h)) {
345 /* If it's a known tar file, end-of-archive is definite. */
346 if ((a->archive_format & ARCHIVE_FORMAT_BASE_MASK) ==
353 /* If it's not an end-of-archive mark, it must have a valid checksum.*/
356 bid += 48; /* Checksum is usually 6 octal digits. */
360 /* Recognize POSIX formats. */
361 if ((memcmp(header->magic, "ustar\0", 6) == 0)
362 &&(memcmp(header->version, "00", 2)==0))
365 /* Recognize GNU tar format. */
366 if ((memcmp(header->magic, "ustar ", 6) == 0)
367 &&(memcmp(header->version, " \0", 2)==0))
370 /* Type flag must be null, digit or A-Z, a-z. */
371 if (header->typeflag[0] != 0 &&
372 !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
373 !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
374 !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
376 bid += 2; /* 6 bits of variation in an 8-bit field leaves 2 bits. */
378 /* Sanity check: Look at first byte of mode field. */
379 switch (255 & (unsigned)header->mode[0]) {
381 /* Base-256 value: No further verification possible! */
383 case ' ': /* Not recommended, but not illegal, either. */
385 case '0': case '1': case '2': case '3':
386 case '4': case '5': case '6': case '7':
388 /* TODO: Check format of remainder of this field. */
391 /* Not a valid mode; bail out here. */
394 /* TODO: Sanity test uid/gid/size/mtime/rdevmajor/rdevminor fields. */
400 * The function invoked by archive_read_header(). This
401 * just sets up a few things and then calls the internal
402 * tar_read_header() function below.
405 archive_read_format_tar_read_header(struct archive *a,
406 struct archive_entry *entry)
409 * When converting tar archives to cpio archives, it is
410 * essential that each distinct file have a distinct inode
411 * number. To simplify this, we keep a static count here to
412 * assign fake dev/inode numbers to each tar entry. Note that
413 * pax format archives may overwrite this with something more
416 * Ideally, we would track every file read from the archive so
417 * that we could assign the same dev/ino pair to hardlinks,
418 * but the memory required to store a complete lookup table is
419 * probably not worthwhile just to support the relatively
420 * obscure tar->cpio conversion case.
422 static int default_inode;
423 static int default_dev;
430 memset(&st, 0, sizeof(st));
431 /* Assign default device/inode values. */
432 st.st_dev = 1 + default_dev; /* Don't use zero. */
433 st.st_ino = ++default_inode; /* Don't use zero. */
434 /* Limit generated st_ino number to 16 bits. */
435 if (default_inode >= 0xffff) {
440 tar = *(a->pformat_data);
441 tar->entry_offset = 0;
443 r = tar_read_header(a, tar, entry, &st);
445 if (r == ARCHIVE_OK) {
447 * "Regular" entry with trailing '/' is really
448 * directory: This is needed for certain old tar
449 * variants and even for some broken newer ones.
451 p = archive_entry_pathname(entry);
453 if (S_ISREG(st.st_mode) && p[l-1] == '/') {
454 st.st_mode &= ~S_IFMT;
455 st.st_mode |= S_IFDIR;
458 /* Copy the final stat data into the entry. */
459 archive_entry_copy_stat(entry, &st);
465 archive_read_format_tar_read_data(struct archive *a,
466 const void **buff, size_t *size, off_t *offset)
470 struct sparse_block *p;
472 tar = *(a->pformat_data);
473 if (tar->sparse_list != NULL) {
474 /* Remove exhausted entries from sparse list. */
475 while (tar->sparse_list != NULL &&
476 tar->sparse_list->remaining == 0) {
477 p = tar->sparse_list;
478 tar->sparse_list = p->next;
481 if (tar->sparse_list == NULL) {
482 /* We exhausted the entire sparse list. */
483 tar->entry_bytes_remaining = 0;
487 if (tar->entry_bytes_remaining > 0) {
488 bytes_read = (a->compression_read_ahead)(a, buff, 1);
490 return (ARCHIVE_FATAL);
491 if (bytes_read > tar->entry_bytes_remaining)
492 bytes_read = tar->entry_bytes_remaining;
493 if (tar->sparse_list != NULL) {
494 /* Don't read more than is available in the
495 * current sparse block. */
496 if (tar->sparse_list->remaining < bytes_read)
497 bytes_read = tar->sparse_list->remaining;
498 tar->entry_offset = tar->sparse_list->offset;
499 tar->sparse_list->remaining -= bytes_read;
500 tar->sparse_list->offset += bytes_read;
503 *offset = tar->entry_offset;
504 tar->entry_offset += bytes_read;
505 tar->entry_bytes_remaining -= bytes_read;
506 (a->compression_read_consume)(a, bytes_read);
509 while (tar->entry_padding > 0) {
510 bytes_read = (a->compression_read_ahead)(a, buff, 1);
512 return (ARCHIVE_FATAL);
513 if (bytes_read > tar->entry_padding)
514 bytes_read = tar->entry_padding;
515 (a->compression_read_consume)(a, bytes_read);
516 tar->entry_padding -= bytes_read;
520 *offset = tar->entry_offset;
521 return (ARCHIVE_EOF);
526 * This function recursively interprets all of the headers associated
527 * with a single entry.
530 tar_read_header(struct archive *a, struct tar *tar,
531 struct archive_entry *entry, struct stat *st)
536 const struct archive_entry_header_ustar *header;
538 /* Read 512-byte header record */
539 bytes = (a->compression_read_ahead)(a, &h, 512);
542 * If we're here, it's becase the _bid function accepted
543 * this file. So just call a short read end-of-archive
544 * and be done with it.
546 return (ARCHIVE_EOF);
548 (a->compression_read_consume)(a, 512);
550 /* Check for end-of-archive mark. */
551 if (((*(const char *)h)==0) && archive_block_is_null(h)) {
552 /* Try to consume a second all-null record, as well. */
553 bytes = (a->compression_read_ahead)(a, &h, 512);
555 (a->compression_read_consume)(a, bytes);
556 archive_set_error(a, 0, NULL);
557 return (ARCHIVE_EOF);
561 * Note: If the checksum fails and we return ARCHIVE_RETRY,
562 * then the client is likely to just retry. This is a very
563 * crude way to search for the next valid header!
565 * TODO: Improve this by implementing a real header scan.
567 if (!checksum(a, h)) {
568 archive_set_error(a, EINVAL, "Damaged tar archive");
569 return (ARCHIVE_RETRY); /* Retryable: Invalid header */
572 if (++tar->header_recursion_depth > 32) {
573 archive_set_error(a, EINVAL, "Too many special headers");
574 return (ARCHIVE_WARN);
577 /* Determine the format variant. */
579 switch(header->typeflag[0]) {
580 case 'A': /* Solaris tar ACL */
581 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
582 a->archive_format_name = "Solaris tar";
583 err = header_Solaris_ACL(a, tar, entry, st, h);
585 case 'g': /* POSIX-standard 'g' header. */
586 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
587 a->archive_format_name = "POSIX pax interchange format";
588 err = header_pax_global(a, tar, entry, st, h);
590 case 'K': /* Long link name (GNU tar, others) */
591 err = header_longlink(a, tar, entry, st, h);
593 case 'L': /* Long filename (GNU tar, others) */
594 err = header_longname(a, tar, entry, st, h);
596 case 'V': /* GNU volume header */
597 err = header_volume(a, tar, entry, st, h);
599 case 'X': /* Used by SUN tar; same as 'x'. */
600 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
601 a->archive_format_name =
602 "POSIX pax interchange format (Sun variant)";
603 err = header_pax_extensions(a, tar, entry, st, h);
605 case 'x': /* POSIX-standard 'x' header. */
606 a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
607 a->archive_format_name = "POSIX pax interchange format";
608 err = header_pax_extensions(a, tar, entry, st, h);
611 if (memcmp(header->magic, "ustar \0", 8) == 0) {
612 a->archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
613 a->archive_format_name = "GNU tar format";
614 err = header_gnutar(a, tar, entry, st, h);
615 } else if (memcmp(header->magic, "ustar", 5) == 0) {
616 if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
617 a->archive_format = ARCHIVE_FORMAT_TAR_USTAR;
618 a->archive_format_name = "POSIX ustar format";
620 err = header_ustar(a, tar, entry, st, h);
622 a->archive_format = ARCHIVE_FORMAT_TAR;
623 a->archive_format_name = "tar (non-POSIX)";
624 err = header_old_tar(a, tar, entry, st, h);
627 --tar->header_recursion_depth;
632 * Return true if block checksum is correct.
635 checksum(struct archive *a, const void *h)
637 const unsigned char *bytes;
638 const struct archive_entry_header_ustar *header;
641 (void)a; /* UNUSED */
646 * Test the checksum. Note that POSIX specifies _unsigned_
647 * bytes for this calculation.
649 sum = tar_atol(header->checksum, sizeof(header->checksum));
651 for (i = 0; i < 148; i++)
652 check += (unsigned char)bytes[i];
656 check += (unsigned char)bytes[i];
661 * Repeat test with _signed_ bytes, just in case this archive
662 * was created by an old BSD, Solaris, or HP-UX tar with a
663 * broken checksum calculation.
666 for (i = 0; i < 148; i++)
667 check += (signed char)bytes[i];
671 check += (signed char)bytes[i];
679 * Return true if this block contains only nulls.
682 archive_block_is_null(const unsigned char *p)
686 for (i = 0; i < ARCHIVE_BYTES_PER_RECORD / sizeof(*p); i++)
693 * Interpret 'A' Solaris ACL header
696 header_Solaris_ACL(struct archive *a, struct tar *tar,
697 struct archive_entry *entry, struct stat *st, const void *h)
703 err = read_body_to_string(a, tar, &(tar->acl_text), h);
704 err2 = tar_read_header(a, tar, entry, st);
705 err = err_combine(err, err2);
707 /* XXX Ensure p doesn't overrun acl_text */
709 /* Skip leading octal number. */
710 /* XXX TODO: Parse the octal number and sanity-check it. */
716 wp = malloc((strlen(p) + 1) * sizeof(wchar_t));
718 utf8_decode(wp, p, strlen(p));
719 err2 = __archive_entry_acl_parse_w(entry, wp,
720 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
721 err = err_combine(err, err2);
729 * Interpret 'K' long linkname header.
732 header_longlink(struct archive *a, struct tar *tar,
733 struct archive_entry *entry, struct stat *st, const void *h)
737 err = read_body_to_string(a, tar, &(tar->longlink), h);
738 err2 = tar_read_header(a, tar, entry, st);
739 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK) {
740 /* Set symlink if symlink already set, else hardlink. */
741 archive_entry_set_link(entry, tar->longlink.s);
743 return (err_combine(err, err2));
747 * Interpret 'L' long filename header.
750 header_longname(struct archive *a, struct tar *tar,
751 struct archive_entry *entry, struct stat *st, const void *h)
755 err = read_body_to_string(a, tar, &(tar->longname), h);
756 /* Read and parse "real" header, then override name. */
757 err2 = tar_read_header(a, tar, entry, st);
758 if (err == ARCHIVE_OK && err2 == ARCHIVE_OK)
759 archive_entry_set_pathname(entry, tar->longname.s);
760 return (err_combine(err, err2));
765 * Interpret 'V' GNU tar volume header.
768 header_volume(struct archive *a, struct tar *tar,
769 struct archive_entry *entry, struct stat *st, const void *h)
773 /* Just skip this and read the next header. */
774 return (tar_read_header(a, tar, entry, st));
778 * Read body of an archive entry into an archive_string object.
781 read_body_to_string(struct archive *a, struct tar *tar,
782 struct archive_string *as, const void *h)
784 off_t size, padded_size;
785 ssize_t bytes_read, bytes_to_copy;
786 const struct archive_entry_header_ustar *header;
790 (void)tar; /* UNUSED */
792 size = tar_atol(header->size, sizeof(header->size));
794 /* Read the body into the string. */
795 archive_string_ensure(as, size+1);
796 padded_size = (size + 511) & ~ 511;
798 while (padded_size > 0) {
799 bytes_read = (a->compression_read_ahead)(a, &src, padded_size);
801 return (ARCHIVE_FATAL);
802 if (bytes_read > padded_size)
803 bytes_read = padded_size;
804 (a->compression_read_consume)(a, bytes_read);
805 bytes_to_copy = bytes_read;
806 if ((off_t)bytes_to_copy > size)
807 bytes_to_copy = (ssize_t)size;
808 memcpy(dest, src, bytes_to_copy);
809 dest += bytes_to_copy;
810 size -= bytes_to_copy;
811 padded_size -= bytes_read;
818 * Parse out common header elements.
820 * This would be the same as header_old_tar, except that the
821 * filename is handled slightly differently for old and POSIX
822 * entries (POSIX entries support a 'prefix'). This factoring
823 * allows header_old_tar and header_ustar
824 * to handle filenames differently, while still putting most of the
825 * common parsing into one place.
828 header_common(struct archive *a, struct tar *tar, struct archive_entry *entry,
829 struct stat *st, const void *h)
831 const struct archive_entry_header_ustar *header;
834 (void)a; /* UNUSED */
837 if (header->linkname[0])
838 archive_strncpy(&(tar->entry_linkname), header->linkname,
839 sizeof(header->linkname));
841 archive_string_empty(&(tar->entry_linkname));
843 /* Parse out the numeric fields (all are octal) */
844 st->st_mode = tar_atol(header->mode, sizeof(header->mode));
845 st->st_uid = tar_atol(header->uid, sizeof(header->uid));
846 st->st_gid = tar_atol(header->gid, sizeof(header->gid));
847 st->st_size = tar_atol(header->size, sizeof(header->size));
848 st->st_mtime = tar_atol(header->mtime, sizeof(header->mtime));
850 /* Handle the tar type flag appropriately. */
851 tartype = header->typeflag[0];
852 st->st_mode &= ~S_IFMT;
855 case '1': /* Hard link */
856 archive_entry_set_hardlink(entry, tar->entry_linkname.s);
858 * The following may seem odd, but: Technically, tar
859 * does not store the file type for a "hard link"
860 * entry, only the fact that it is a hard link. So, I
861 * leave the type zero normally. But, pax interchange
862 * format allows hard links to have data, which
863 * implies that the underlying entry is a regular
867 st->st_mode |= S_IFREG;
870 * A tricky point: Traditionally, tar readers have
871 * ignored the size field when reading hardlink
872 * entries, and some writers put non-zero sizes even
873 * though the body is empty. POSIX.1-2001 broke with
874 * this tradition by permitting hardlink entries to
875 * store valid bodies in pax interchange format, but
876 * not in ustar format. Since there is no hard and
877 * fast way to distinguish pax interchange from
878 * earlier archives (the 'x' and 'g' entries are
879 * optional, after all), we need a heuristic. Here, I
880 * use the bid function to test whether or not there's
881 * a valid header following. Of course, if we know
882 * this is pax interchange format, then we must obey
885 * This heuristic will only fail for a pax interchange
886 * archive that is storing hardlink bodies, no pax
887 * extended attribute entries have yet occurred, and
888 * we encounter a hardlink entry for a file that is
889 * itself an uncompressed tar archive.
891 if (st->st_size > 0 &&
892 a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
893 archive_read_format_tar_bid(a) > 50)
896 case '2': /* Symlink */
897 st->st_mode |= S_IFLNK;
899 archive_entry_set_symlink(entry, tar->entry_linkname.s);
901 case '3': /* Character device */
902 st->st_mode |= S_IFCHR;
905 case '4': /* Block device */
906 st->st_mode |= S_IFBLK;
910 st->st_mode |= S_IFDIR;
913 case '6': /* FIFO device */
914 st->st_mode |= S_IFIFO;
917 case 'D': /* GNU incremental directory type */
919 * No special handling is actually required here.
920 * It might be nice someday to preprocess the file list and
921 * provide it to the client, though.
923 st->st_mode |= S_IFDIR;
925 case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
927 * As far as I can tell, this is just like a regular file
928 * entry, except that the contents should be _appended_ to
929 * the indicated file at the indicated offset. This may
930 * require some API work to fully support.
933 case 'N': /* Old GNU "long filename" entry. */
934 /* The body of this entry is a script for renaming
935 * previously-extracted entries. Ugh. It will never
936 * be supported by libarchive. */
937 st->st_mode |= S_IFREG;
939 case 'S': /* GNU sparse files */
941 * Sparse files are really just regular files with
942 * sparse information in the extended area.
945 default: /* Regular file and non-standard types */
947 * Per POSIX: non-recognized types should always be
948 * treated as regular files.
950 st->st_mode |= S_IFREG;
957 * Parse out header elements for "old-style" tar archives.
960 header_old_tar(struct archive *a, struct tar *tar, struct archive_entry *entry,
961 struct stat *st, const void *h)
963 const struct archive_entry_header_ustar *header;
965 /* Copy filename over (to ensure null termination). */
967 archive_strncpy(&(tar->entry_name), header->name, sizeof(header->name));
968 archive_entry_set_pathname(entry, tar->entry_name.s);
970 /* Grab rest of common fields */
971 header_common(a, tar, entry, st, h);
973 tar->entry_bytes_remaining = st->st_size;
974 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
979 * Parse a file header for a pax extended archive entry.
982 header_pax_global(struct archive *a, struct tar *tar,
983 struct archive_entry *entry, struct stat *st, const void *h)
987 err = read_body_to_string(a, tar, &(tar->pax_global), h);
988 err2 = tar_read_header(a, tar, entry, st);
989 return (err_combine(err, err2));
993 header_pax_extensions(struct archive *a, struct tar *tar,
994 struct archive_entry *entry, struct stat *st, const void *h)
998 read_body_to_string(a, tar, &(tar->pax_header), h);
1000 /* Parse the next header. */
1001 err = tar_read_header(a, tar, entry, st);
1004 * TODO: Parse global/default options into 'entry' struct here
1005 * before handling file-specific options.
1007 * This design (parse standard header, then overwrite with pax
1008 * extended attribute data) usually works well, but isn't ideal;
1009 * it would be better to parse the pax extended attributes first
1010 * and then skip any fields in the standard header that were
1011 * defined in the pax header.
1013 err2 = pax_header(a, tar, entry, st, tar->pax_header.s);
1014 err = err_combine(err, err2);
1015 tar->entry_bytes_remaining = st->st_size;
1016 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1022 * Parse a file header for a Posix "ustar" archive entry. This also
1023 * handles "pax" or "extended ustar" entries.
1026 header_ustar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1027 struct stat *st, const void *h)
1029 const struct archive_entry_header_ustar *header;
1030 struct archive_string *as;
1034 /* Copy name into an internal buffer to ensure null-termination. */
1035 as = &(tar->entry_name);
1036 if (header->prefix[0]) {
1037 archive_strncpy(as, header->prefix, sizeof(header->prefix));
1038 if (as->s[archive_strlen(as) - 1] != '/')
1039 archive_strappend_char(as, '/');
1040 archive_strncat(as, header->name, sizeof(header->name));
1042 archive_strncpy(as, header->name, sizeof(header->name));
1044 archive_entry_set_pathname(entry, as->s);
1046 /* Handle rest of common fields. */
1047 header_common(a, tar, entry, st, h);
1049 /* Handle POSIX ustar fields. */
1050 archive_strncpy(&(tar->entry_uname), header->uname,
1051 sizeof(header->uname));
1052 archive_entry_set_uname(entry, tar->entry_uname.s);
1054 archive_strncpy(&(tar->entry_gname), header->gname,
1055 sizeof(header->gname));
1056 archive_entry_set_gname(entry, tar->entry_gname.s);
1058 /* Parse out device numbers only for char and block specials. */
1059 if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1060 st->st_rdev = makedev(
1061 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1062 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1065 tar->entry_bytes_remaining = st->st_size;
1066 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1073 * Parse the pax extended attributes record.
1075 * Returns non-zero if there's an error in the data.
1078 pax_header(struct archive *a, struct tar *tar, struct archive_entry *entry,
1079 struct stat *st, char *attr)
1081 size_t attr_length, l, line_length;
1083 wchar_t *key, *wp, *value;
1086 attr_length = strlen(attr);
1088 while (attr_length > 0) {
1089 /* Parse decimal length field at start of line. */
1092 line = p = attr; /* Record start of line. */
1099 if (*p < '0' || *p > '9')
1102 line_length += *p - '0';
1103 if (line_length > 999999) {
1104 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1105 "Rejecting pax extended attribute > 1MB");
1106 return (ARCHIVE_WARN);
1112 if (line_length > attr_length)
1115 /* Ensure pax_entry buffer is big enough. */
1116 if (tar->pax_entry_length <= line_length) {
1117 wchar_t *old_entry = tar->pax_entry;
1119 if (tar->pax_entry_length <= 0)
1120 tar->pax_entry_length = 1024;
1121 while (tar->pax_entry_length <= line_length + 1)
1122 tar->pax_entry_length *= 2;
1124 old_entry = tar->pax_entry;
1125 tar->pax_entry = realloc(tar->pax_entry,
1126 tar->pax_entry_length * sizeof(wchar_t));
1127 if (tar->pax_entry == NULL) {
1129 archive_set_error(a, ENOMEM,
1131 return (ARCHIVE_FATAL);
1135 /* Decode UTF-8 to wchar_t, null-terminate result. */
1136 if (utf8_decode(tar->pax_entry, p,
1137 line_length - (p - attr) - 1)) {
1138 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1139 "Invalid UTF8 character in pax extended attribute");
1140 err = err_combine(err, ARCHIVE_WARN);
1143 /* Null-terminate 'key' value. */
1144 wp = key = tar->pax_entry;
1147 while (*wp && *wp != L'=')
1149 if (*wp == L'\0' || wp == NULL) {
1150 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1151 "Invalid pax extended attributes");
1152 return (ARCHIVE_WARN);
1156 /* Identify null-terminated 'value' portion. */
1159 /* Identify this attribute and set it in the entry. */
1160 err2 = pax_attribute(entry, st, key, value);
1161 err = err_combine(err, err2);
1163 /* Skip to next line */
1164 attr += line_length;
1165 attr_length -= line_length;
1171 pax_attribute_xattr(struct archive_entry *entry,
1172 wchar_t *name, wchar_t *value)
1174 char *name_decoded, *name_narrow;
1175 void *value_decoded;
1178 if (wcslen(name) < 18 || (wcsncmp(name, L"LIBARCHIVE.xattr.", 17)) != 0)
1183 /* URL-decode name */
1184 name_narrow = wide_to_narrow(name);
1185 if (name_narrow == NULL)
1187 name_decoded = url_decode(name_narrow);
1189 if (name_decoded == NULL)
1192 /* Base-64 decode value */
1193 value_decoded = base64_decode(value, wcslen(value), &value_len);
1194 if (value_decoded == NULL) {
1199 archive_entry_xattr_add_entry(entry, name_decoded,
1200 value_decoded, value_len);
1203 free(value_decoded);
1208 * Parse a single key=value attribute. key/value pointers are
1209 * assumed to point into reasonably long-lived storage.
1211 * Note that POSIX reserves all-lowercase keywords. Vendor-specific
1212 * extensions should always have keywords of the form "VENDOR.attribute"
1213 * In particular, it's quite feasible to support many different
1214 * vendor extensions here. I'm using "LIBARCHIVE" for extensions
1215 * unique to this library (currently, there are none).
1217 * Investigate other vendor-specific extensions, as well and see if
1218 * any of them look useful.
1221 pax_attribute(struct archive_entry *entry, struct stat *st,
1222 wchar_t *key, wchar_t *value)
1229 /* Our extensions */
1230 /* TODO: Handle arbitrary extended attributes... */
1232 if (strcmp(key, "LIBARCHIVE.xxxxxxx")==0)
1233 archive_entry_set_xxxxxx(entry, value);
1235 if (wcsncmp(key, L"LIBARCHIVE.xattr.", 17)==0)
1236 pax_attribute_xattr(entry, key, value);
1239 /* We support some keys used by the "star" archiver */
1240 if (wcscmp(key, L"SCHILY.acl.access")==0)
1241 __archive_entry_acl_parse_w(entry, value,
1242 ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1243 else if (wcscmp(key, L"SCHILY.acl.default")==0)
1244 __archive_entry_acl_parse_w(entry, value,
1245 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1246 else if (wcscmp(key, L"SCHILY.devmajor")==0)
1247 st->st_rdev = makedev(tar_atol10(value, wcslen(value)),
1248 minor(st->st_rdev));
1249 else if (wcscmp(key, L"SCHILY.devminor")==0)
1250 st->st_rdev = makedev(major(st->st_rdev),
1251 tar_atol10(value, wcslen(value)));
1252 else if (wcscmp(key, L"SCHILY.fflags")==0)
1253 archive_entry_copy_fflags_text_w(entry, value);
1254 else if (wcscmp(key, L"SCHILY.nlink")==0)
1255 st->st_nlink = tar_atol10(value, wcslen(value));
1258 if (wcscmp(key, L"atime")==0) {
1259 pax_time(value, &s, &n);
1261 ARCHIVE_STAT_SET_ATIME_NANOS(st, n);
1265 if (wcscmp(key, L"ctime")==0) {
1266 pax_time(value, &s, &n);
1268 ARCHIVE_STAT_SET_CTIME_NANOS(st, n);
1269 } else if (wcscmp(key, L"charset")==0) {
1270 /* TODO: Publish charset information in entry. */
1271 } else if (wcscmp(key, L"comment")==0) {
1272 /* TODO: Publish comment in entry. */
1276 if (wcscmp(key, L"gid")==0)
1277 st->st_gid = tar_atol10(value, wcslen(value));
1278 else if (wcscmp(key, L"gname")==0)
1279 archive_entry_copy_gname_w(entry, value);
1282 /* pax interchange doesn't distinguish hardlink vs. symlink. */
1283 if (wcscmp(key, L"linkpath")==0) {
1284 if (archive_entry_hardlink(entry))
1285 archive_entry_copy_hardlink_w(entry, value);
1287 archive_entry_copy_symlink_w(entry, value);
1291 if (wcscmp(key, L"mtime")==0) {
1292 pax_time(value, &s, &n);
1294 ARCHIVE_STAT_SET_MTIME_NANOS(st, n);
1298 if (wcscmp(key, L"path")==0)
1299 archive_entry_copy_pathname_w(entry, value);
1302 /* POSIX has reserved 'realtime.*' */
1305 /* POSIX has reserved 'security.*' */
1306 /* Someday: if (wcscmp(key, L"security.acl")==0) { ... } */
1307 if (wcscmp(key, L"size")==0)
1308 st->st_size = tar_atol10(value, wcslen(value));
1311 if (wcscmp(key, L"uid")==0)
1312 st->st_uid = tar_atol10(value, wcslen(value));
1313 else if (wcscmp(key, L"uname")==0)
1314 archive_entry_copy_uname_w(entry, value);
1323 * parse a decimal time value, which may include a fractional portion
1326 pax_time(const wchar_t *p, int64_t *ps, long *pn)
1332 int64_t limit, last_digit_limit;
1334 limit = max_int64 / 10;
1335 last_digit_limit = max_int64 % 10;
1343 while (*p >= '0' && *p <= '9') {
1346 (s == limit && digit > last_digit_limit)) {
1350 s = (s * 10) + digit;
1356 /* Calculate nanoseconds. */
1365 if (*p >= '0' && *p <= '9')
1366 *pn += (*p - '0') * l;
1373 * Parse GNU tar header
1376 header_gnutar(struct archive *a, struct tar *tar, struct archive_entry *entry,
1377 struct stat *st, const void *h)
1379 const struct archive_entry_header_gnutar *header;
1384 * GNU header is like POSIX ustar, except 'prefix' is
1385 * replaced with some other fields. This also means the
1386 * filename is stored as in old-style archives.
1389 /* Grab fields common to all tar variants. */
1390 header_common(a, tar, entry, st, h);
1392 /* Copy filename over (to ensure null termination). */
1394 archive_strncpy(&(tar->entry_name), header->name,
1395 sizeof(header->name));
1396 archive_entry_set_pathname(entry, tar->entry_name.s);
1398 /* Fields common to ustar and GNU */
1399 /* XXX Can the following be factored out since it's common
1400 * to ustar and gnu tar? Is it okay to move it down into
1401 * header_common, perhaps? */
1402 archive_strncpy(&(tar->entry_uname),
1403 header->uname, sizeof(header->uname));
1404 archive_entry_set_uname(entry, tar->entry_uname.s);
1406 archive_strncpy(&(tar->entry_gname),
1407 header->gname, sizeof(header->gname));
1408 archive_entry_set_gname(entry, tar->entry_gname.s);
1410 /* Parse out device numbers only for char and block specials */
1411 if (header->typeflag[0] == '3' || header->typeflag[0] == '4')
1412 st->st_rdev = makedev (
1413 tar_atol(header->rdevmajor, sizeof(header->rdevmajor)),
1414 tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1418 tar->entry_bytes_remaining = st->st_size;
1419 tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1421 /* Grab GNU-specific fields. */
1422 st->st_atime = tar_atol(header->atime, sizeof(header->atime));
1423 st->st_ctime = tar_atol(header->ctime, sizeof(header->ctime));
1424 if (header->realsize[0] != 0) {
1425 st->st_size = tar_atol(header->realsize,
1426 sizeof(header->realsize));
1429 if (header->sparse[0].offset[0] != 0) {
1430 gnu_read_sparse_data(a, tar, header);
1432 if (header->isextended[0] != 0) {
1441 gnu_read_sparse_data(struct archive *a, struct tar *tar,
1442 const struct archive_entry_header_gnutar *header)
1447 struct gnu_sparse sparse[21];
1451 const struct extended *ext;
1453 gnu_parse_sparse_data(a, tar, header->sparse, 4);
1454 if (header->isextended[0] == 0)
1455 return (ARCHIVE_OK);
1458 bytes_read = (a->compression_read_ahead)(a, &data, 512);
1460 return (ARCHIVE_FATAL);
1461 if (bytes_read < 512) {
1462 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1463 "Truncated tar archive "
1464 "detected while reading sparse file data");
1465 return (ARCHIVE_FATAL);
1467 (a->compression_read_consume)(a, 512);
1468 ext = (const struct extended *)data;
1469 gnu_parse_sparse_data(a, tar, ext->sparse, 21);
1470 } while (ext->isextended[0] != 0);
1471 if (tar->sparse_list != NULL)
1472 tar->entry_offset = tar->sparse_list->offset;
1473 return (ARCHIVE_OK);
1477 gnu_parse_sparse_data(struct archive *a, struct tar *tar,
1478 const struct gnu_sparse *sparse, int length)
1480 struct sparse_block *last;
1481 struct sparse_block *p;
1483 (void)a; /* UNUSED */
1485 last = tar->sparse_list;
1486 while (last != NULL && last->next != NULL)
1489 while (length > 0 && sparse->offset[0] != 0) {
1490 p = malloc(sizeof(*p));
1492 __archive_errx(1, "Out of memory");
1493 memset(p, 0, sizeof(*p));
1497 tar->sparse_list = p;
1499 p->offset = tar_atol(sparse->offset, sizeof(sparse->offset));
1501 tar_atol(sparse->numbytes, sizeof(sparse->numbytes));
1508 * Convert text->integer.
1510 * Traditional tar formats (including POSIX) specify base-8 for
1511 * all of the standard numeric fields. This is a significant limitation
1513 * = file size is limited to 8GB
1514 * = rdevmajor and rdevminor are limited to 21 bits
1515 * = uid/gid are limited to 21 bits
1517 * There are two workarounds for this:
1518 * = pax extended headers, which use variable-length string fields
1519 * = GNU tar and STAR both allow either base-8 or base-256 in
1520 * most fields. The high bit is set to indicate base-256.
1522 * On read, this implementation supports both extensions.
1525 tar_atol(const char *p, unsigned char_cnt)
1528 * Technically, GNU tar considers a field to be in base-256
1529 * only if the first byte is 0xff or 0x80.
1532 return (tar_atol256(p, char_cnt));
1533 return (tar_atol8(p, char_cnt));
1537 * Note that this implementation does not (and should not!) obey
1538 * locale settings; you cannot simply substitute strtol here, since
1539 * it does obey locale.
1542 tar_atol8(const char *p, unsigned char_cnt)
1544 int64_t l, limit, last_digit_limit;
1545 int digit, sign, base;
1548 limit = max_int64 / base;
1549 last_digit_limit = max_int64 % base;
1551 while (*p == ' ' || *p == '\t')
1561 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1562 if (l>limit || (l == limit && digit > last_digit_limit)) {
1563 l = max_uint64; /* Truncate on overflow. */
1566 l = (l * base) + digit;
1569 return (sign < 0) ? -l : l;
1574 * Note that this implementation does not (and should not!) obey
1575 * locale settings; you cannot simply substitute strtol here, since
1576 * it does obey locale.
1579 tar_atol10(const wchar_t *p, unsigned char_cnt)
1581 int64_t l, limit, last_digit_limit;
1582 int base, digit, sign;
1585 limit = max_int64 / base;
1586 last_digit_limit = max_int64 % base;
1588 while (*p == ' ' || *p == '\t')
1598 while (digit >= 0 && digit < base && char_cnt-- > 0) {
1599 if (l > limit || (l == limit && digit > last_digit_limit)) {
1600 l = max_uint64; /* Truncate on overflow. */
1603 l = (l * base) + digit;
1606 return (sign < 0) ? -l : l;
1610 * Parse a base-256 integer. This is just a straight signed binary
1611 * value in big-endian order, except that the high-order bit is
1612 * ignored. Remember that "int64_t" may or may not be exactly 64
1613 * bits; the implementation here tries to avoid making any assumptions
1614 * about the actual size of an int64_t. It does assume we're using
1615 * twos-complement arithmetic, though.
1618 tar_atol256(const char *_p, unsigned char_cnt)
1620 int64_t l, upper_limit, lower_limit;
1621 const unsigned char *p = (const unsigned char *)_p;
1623 upper_limit = max_int64 / 256;
1624 lower_limit = min_int64 / 256;
1626 /* Pad with 1 or 0 bits, depending on sign. */
1627 if ((0x40 & *p) == 0x40)
1631 l = (l << 6) | (0x3f & *p++);
1632 while (--char_cnt > 0) {
1633 if (l > upper_limit) {
1634 l = max_int64; /* Truncate on overflow */
1636 } else if (l < lower_limit) {
1640 l = (l << 8) | (0xff & (int64_t)*p++);
1646 utf8_decode(wchar_t *dest, const char *src, size_t length)
1652 while (length > 0) {
1653 n = UTF8_mbrtowc(dest, src, length);
1665 * Copied and simplified from FreeBSD libc/locale.
1668 UTF8_mbrtowc(wchar_t *pwc, const char *s, size_t n)
1670 int ch, i, len, mask;
1673 if (s == NULL || n == 0 || pwc == NULL)
1677 * Determine the number of octets that make up this character from
1678 * the first octet, and a mask that extracts the interesting bits of
1681 ch = (unsigned char)*s;
1682 if ((ch & 0x80) == 0) {
1685 } else if ((ch & 0xe0) == 0xc0) {
1688 } else if ((ch & 0xf0) == 0xe0) {
1691 } else if ((ch & 0xf8) == 0xf0) {
1694 } else if ((ch & 0xfc) == 0xf8) {
1697 } else if ((ch & 0xfe) == 0xfc) {
1701 /* Invalid first byte; convert to '?' */
1706 if (n < (size_t)len) {
1707 /* Invalid first byte; convert to '?' */
1713 * Decode the octet sequence representing the character in chunks
1714 * of 6 bits, most significant first.
1716 wch = (unsigned char)*s++ & mask;
1719 if ((*s & 0xc0) != 0x80) {
1720 /* Invalid intermediate byte; consume one byte and
1729 /* Assign the value to the output; out-of-range values
1730 * just get truncated. */
1731 *pwc = (wchar_t)wch;
1734 * If platform has WCHAR_MAX, we can do something
1735 * more sensible with out-of-range values.
1737 if (wch >= WCHAR_MAX)
1740 /* Return number of bytes input consumed: 0 for end-of-string. */
1741 return (wch == L'\0' ? 0 : len);
1746 * base64_decode - Base64 decode
1748 * This accepts most variations of base-64 encoding, including:
1749 * * with or without line breaks
1750 * * with or without the final group padded with '=' or '_' characters
1751 * (The most economical Base-64 variant does not pad the last group and
1752 * omits line breaks; RFC1341 used for MIME requires both.)
1755 base64_decode(const wchar_t *src, size_t len, size_t *out_len)
1757 static const unsigned char digits[64] =
1758 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1759 static unsigned char decode_table[128];
1762 /* If the decode table is not yet initialized, prepare it. */
1763 if (decode_table[digits[1]] != 1) {
1765 memset(decode_table, 0xff, sizeof(decode_table));
1766 for (i = 0; i < sizeof(digits); i++)
1767 decode_table[digits[i]] = i;
1770 /* Allocate enough space to hold the entire output. */
1771 /* Note that we may not use all of this... */
1772 out = malloc((len * 3 + 3) / 4);
1780 /* Collect the next group of (up to) four characters. */
1783 while (group_size < 4 && len > 0) {
1784 /* '=' or '_' padding indicates final group. */
1785 if (*src == '=' || *src == '_') {
1789 /* Skip illegal characters (including line breaks) */
1790 if (*src > 127 || *src < 32
1791 || decode_table[*src] == 0xff) {
1797 v |= decode_table[*src++];
1801 /* Align a short group properly. */
1802 v <<= 6 * (4 - group_size);
1803 /* Unpack the group we just collected. */
1804 switch (group_size) {
1805 case 4: d[2] = v & 0xff;
1807 case 3: d[1] = (v >> 8) & 0xff;
1809 case 2: d[0] = (v >> 16) & 0xff;
1811 case 1: /* this is invalid! */
1814 d += group_size * 3 / 4;
1822 * This is a little tricky because the C99 standard wcstombs()
1823 * function returns the number of bytes that were converted,
1824 * not the number that should be converted. As a result,
1825 * we can never accurately size the output buffer (without
1826 * doing a tedious output size calculation in advance).
1827 * This approach (try a conversion, then try again if it fails)
1828 * will almost always succeed on the first try, and is thus
1829 * much faster, at the cost of sometimes requiring multiple
1830 * passes while we expand the buffer.
1833 wide_to_narrow(const wchar_t *wval)
1835 int converted_length;
1836 /* Guess an output buffer size and try the conversion. */
1837 int alloc_length = wcslen(wval) * 3;
1838 char *mbs_val = malloc(alloc_length + 1);
1839 if (mbs_val == NULL)
1841 converted_length = wcstombs(mbs_val, wval, alloc_length);
1843 /* If we exhausted the buffer, resize and try again. */
1844 while (converted_length >= alloc_length) {
1847 mbs_val = malloc(alloc_length + 1);
1848 if (mbs_val == NULL)
1850 converted_length = wcstombs(mbs_val, wval, alloc_length);
1853 /* Ensure a trailing null and return the final string. */
1854 mbs_val[alloc_length] = '\0';
1859 url_decode(const char *in)
1864 out = malloc(strlen(in) + 1);
1867 for (s = in, d = out; *s != '\0'; ) {
1869 /* Try to convert % escape */
1870 int digit1 = tohex(s[1]);
1871 int digit2 = tohex(s[2]);
1872 if (digit1 >= 0 && digit2 >= 0) {
1873 /* Looks good, consume three chars */
1875 /* Convert output */
1876 *d++ = ((digit1 << 4) | digit2);
1879 /* Else fall through and treat '%' as normal char */
1890 if (c >= '0' && c <= '9')
1892 else if (c >= 'A' && c <= 'F')
1893 return (c - 'A' + 10);
1894 else if (c >= 'a' && c <= 'f')
1895 return (c - 'a' + 10);