2 * Copyright (c) 2003-2011 Tim Kientzle
3 * Copyright (c) 2011 Michihiro NAKAJIMA
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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: head/lib/libarchive/archive_string.c 201095 2009-12-28 02:33:22Z kientzle $");
31 * Basic resizable string support, to simplify manipulating arbitrary-sized
32 * strings while minimizing heap activity.
34 * In particular, the buffer used by a string object is only grown, it
35 * never shrinks, so you can clear and reuse the same string object
36 * without incurring additional memory allocations.
45 #ifdef HAVE_LANGINFO_H
48 #ifdef HAVE_LOCALCHARSET_H
49 #include <localcharset.h>
60 #if defined(_WIN32) && !defined(__CYGWIN__)
64 #if defined(__APPLE__)
65 #include <CoreServices/CoreServices.h>
68 #include "archive_endian.h"
69 #include "archive_private.h"
70 #include "archive_string.h"
71 #include "archive_string_composition.h"
73 #if !defined(HAVE_WMEMCPY) && !defined(wmemcpy)
74 #define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t))
77 struct archive_string_conv {
78 struct archive_string_conv *next;
83 /* Set 1 if from_charset and to_charset are the same. */
86 #define SCONV_TO_CHARSET 1 /* MBS is being converted to specified
88 #define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from
89 * specified charset. */
90 #define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */
91 #define SCONV_WIN_CP (1<<3) /* Use Windows API for converting
93 #define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive
94 * 2.x in the wrong assumption. */
95 #define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C.
96 * Before UTF-8 characters are actually
98 #define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D.
99 * Before UTF-8 characters are actually
101 * Currently this only for MAC OS X. */
102 #define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */
103 #define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */
104 #define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */
105 #define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */
106 #define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */
107 #define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */
108 #define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
109 #define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
113 iconv_t cd_w;/* Use at archive_mstring on
116 /* A temporary buffer for normalization. */
117 struct archive_string utftmp;
118 #if defined(__APPLE__)
119 UnicodeToTextInfo uniInfo;
120 struct archive_string utf16nfc;
121 struct archive_string utf16nfd;
123 int (*converter[2])(struct archive_string *, const void *, size_t,
124 struct archive_string_conv *);
128 #define CP_C_LOCALE 0 /* "C" locale only for this file. */
129 #define CP_UTF16LE 1200
130 #define CP_UTF16BE 1201
132 #define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
133 #define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
134 #define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
135 #define UNICODE_MAX 0x10FFFF
136 #define UNICODE_R_CHAR 0xFFFD /* Replacement character. */
137 /* Set U+FFFD(Replacement character) in UTF-8. */
138 #define UTF8_SET_R_CHAR(outp) do { \
143 #define UTF8_R_CHAR_SIZE 3
145 static struct archive_string_conv *find_sconv_object(struct archive *,
146 const char *, const char *);
147 static void add_sconv_object(struct archive *, struct archive_string_conv *);
148 static struct archive_string_conv *create_sconv_object(const char *,
149 const char *, unsigned, int);
150 static void free_sconv_object(struct archive_string_conv *);
151 static struct archive_string_conv *get_sconv_object(struct archive *,
152 const char *, const char *, int);
153 static unsigned make_codepage_from_charset(const char *);
154 static unsigned get_current_codepage(void);
155 static unsigned get_current_oemcp(void);
156 static size_t mbsnbytes(const void *, size_t);
157 static size_t utf16nbytes(const void *, size_t);
158 #if defined(_WIN32) && !defined(__CYGWIN__)
159 static int archive_wstring_append_from_mbs_in_codepage(
160 struct archive_wstring *, const char *, size_t,
161 struct archive_string_conv *);
162 static int archive_string_append_from_wcs_in_codepage(struct archive_string *,
163 const wchar_t *, size_t, struct archive_string_conv *);
164 static int is_big_endian(void);
165 static int strncat_in_codepage(struct archive_string *, const void *,
166 size_t, struct archive_string_conv *);
167 static int win_strncat_from_utf16be(struct archive_string *, const void *, size_t,
168 struct archive_string_conv *);
169 static int win_strncat_from_utf16le(struct archive_string *, const void *, size_t,
170 struct archive_string_conv *);
171 static int win_strncat_to_utf16be(struct archive_string *, const void *, size_t,
172 struct archive_string_conv *);
173 static int win_strncat_to_utf16le(struct archive_string *, const void *, size_t,
174 struct archive_string_conv *);
176 static int best_effort_strncat_from_utf16be(struct archive_string *, const void *,
177 size_t, struct archive_string_conv *);
178 static int best_effort_strncat_from_utf16le(struct archive_string *, const void *,
179 size_t, struct archive_string_conv *);
180 static int best_effort_strncat_to_utf16be(struct archive_string *, const void *,
181 size_t, struct archive_string_conv *);
182 static int best_effort_strncat_to_utf16le(struct archive_string *, const void *,
183 size_t, struct archive_string_conv *);
184 #if defined(HAVE_ICONV)
185 static int iconv_strncat_in_locale(struct archive_string *, const void *,
186 size_t, struct archive_string_conv *);
188 static int best_effort_strncat_in_locale(struct archive_string *, const void *,
189 size_t, struct archive_string_conv *);
190 static int _utf8_to_unicode(uint32_t *, const char *, size_t);
191 static int utf8_to_unicode(uint32_t *, const char *, size_t);
192 static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
193 static int cesu8_to_unicode(uint32_t *, const char *, size_t);
194 static size_t unicode_to_utf8(char *, size_t, uint32_t);
195 static int utf16_to_unicode(uint32_t *, const char *, size_t, int);
196 static size_t unicode_to_utf16be(char *, size_t, uint32_t);
197 static size_t unicode_to_utf16le(char *, size_t, uint32_t);
198 static int strncat_from_utf8_libarchive2(struct archive_string *,
199 const void *, size_t, struct archive_string_conv *);
200 static int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
201 size_t, struct archive_string_conv *);
202 static int archive_string_normalize_C(struct archive_string *, const void *,
203 size_t, struct archive_string_conv *);
204 #if defined(__APPLE__)
205 static int archive_string_normalize_D(struct archive_string *, const void *,
206 size_t, struct archive_string_conv *);
208 static int archive_string_append_unicode(struct archive_string *,
209 const void *, size_t, struct archive_string_conv *);
211 static struct archive_string *
212 archive_string_append(struct archive_string *as, const char *p, size_t s)
214 if (archive_string_ensure(as, as->length + s + 1) == NULL)
216 memcpy(as->s + as->length, p, s);
218 as->s[as->length] = 0;
222 static struct archive_wstring *
223 archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
225 if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
227 wmemcpy(as->s + as->length, p, s);
229 as->s[as->length] = 0;
234 archive_string_concat(struct archive_string *dest, struct archive_string *src)
236 if (archive_string_append(dest, src->s, src->length) == NULL)
237 __archive_errx(1, "Out of memory");
241 archive_wstring_concat(struct archive_wstring *dest, struct archive_wstring *src)
243 if (archive_wstring_append(dest, src->s, src->length) == NULL)
244 __archive_errx(1, "Out of memory");
248 archive_string_free(struct archive_string *as)
251 as->buffer_length = 0;
257 archive_wstring_free(struct archive_wstring *as)
260 as->buffer_length = 0;
265 struct archive_wstring *
266 archive_wstring_ensure(struct archive_wstring *as, size_t s)
268 return (struct archive_wstring *)
269 archive_string_ensure((struct archive_string *)as,
270 s * sizeof(wchar_t));
273 /* Returns NULL on any allocation failure. */
274 struct archive_string *
275 archive_string_ensure(struct archive_string *as, size_t s)
280 /* If buffer is already big enough, don't reallocate. */
281 if (as->s && (s <= as->buffer_length))
285 * Growing the buffer at least exponentially ensures that
286 * append operations are always linear in the number of
287 * characters appended. Using a smaller growth rate for
288 * larger buffers reduces memory waste somewhat at the cost of
289 * a larger constant factor.
291 if (as->buffer_length < 32)
292 /* Start with a minimum 32-character buffer. */
294 else if (as->buffer_length < 8192)
295 /* Buffers under 8k are doubled for speed. */
296 new_length = as->buffer_length + as->buffer_length;
298 /* Buffers 8k and over grow by at least 25% each time. */
299 new_length = as->buffer_length + as->buffer_length / 4;
300 /* Be safe: If size wraps, fail. */
301 if (new_length < as->buffer_length) {
302 /* On failure, wipe the string and return NULL. */
303 archive_string_free(as);
304 errno = ENOMEM;/* Make sure errno has ENOMEM. */
309 * The computation above is a lower limit to how much we'll
310 * grow the buffer. In any case, we have to grow it enough to
315 /* Now we can reallocate the buffer. */
316 p = (char *)realloc(as->s, new_length);
318 /* On failure, wipe the string and return NULL. */
319 archive_string_free(as);
320 errno = ENOMEM;/* Make sure errno has ENOMEM. */
325 as->buffer_length = new_length;
330 * TODO: See if there's a way to avoid scanning
331 * the source string twice. Then test to see
332 * if it actually helps (remember that we're almost
333 * always called with pretty short arguments, so
334 * such an optimization might not help).
336 struct archive_string *
337 archive_strncat(struct archive_string *as, const void *_p, size_t n)
342 p = (const char *)_p;
344 /* Like strlen(p), except won't examine positions beyond p[n]. */
347 while (s < n && *pp) {
351 if ((as = archive_string_append(as, p, s)) == NULL)
352 __archive_errx(1, "Out of memory");
356 struct archive_wstring *
357 archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
362 /* Like strlen(p), except won't examine positions beyond p[n]. */
365 while (s < n && *pp) {
369 if ((as = archive_wstring_append(as, p, s)) == NULL)
370 __archive_errx(1, "Out of memory");
374 struct archive_string *
375 archive_strcat(struct archive_string *as, const void *p)
377 /* strcat is just strncat without an effective limit.
378 * Assert that we'll never get called with a source
380 * TODO: Review all uses of strcat in the source
381 * and try to replace them with strncat().
383 return archive_strncat(as, p, 0x1000000);
386 struct archive_wstring *
387 archive_wstrcat(struct archive_wstring *as, const wchar_t *p)
390 return archive_wstrncat(as, p, 0x1000000);
393 struct archive_string *
394 archive_strappend_char(struct archive_string *as, char c)
396 if ((as = archive_string_append(as, &c, 1)) == NULL)
397 __archive_errx(1, "Out of memory");
401 struct archive_wstring *
402 archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
404 if ((as = archive_wstring_append(as, &c, 1)) == NULL)
405 __archive_errx(1, "Out of memory");
410 * Get the "current character set" name to use with iconv.
411 * On FreeBSD, the empty character set name "" chooses
412 * the correct character encoding for the current locale,
413 * so this isn't necessary.
414 * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
415 * on that system, we have to explicitly call nl_langinfo()
416 * to get the right name. Not sure about other platforms.
418 * NOTE: GNU libiconv does not recognize the character-set name
419 * which some platform nl_langinfo(CODESET) returns, so we should
420 * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
423 default_iconv_charset(const char *charset) {
424 if (charset != NULL && charset[0] != '\0')
426 #if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
427 /* locale_charset() is broken on Mac OS */
428 return locale_charset();
429 #elif HAVE_NL_LANGINFO
430 return nl_langinfo(CODESET);
436 #if defined(_WIN32) && !defined(__CYGWIN__)
439 * Convert MBS to WCS.
440 * Note: returns -1 if conversion fails.
443 archive_wstring_append_from_mbs(struct archive_wstring *dest,
444 const char *p, size_t len)
446 int r = archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
447 if (r != 0 && errno == ENOMEM)
448 __archive_errx(1, "No memory");
453 archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
454 const char *s, size_t length, struct archive_string_conv *sc)
460 from_cp = sc->from_cp;
462 from_cp = get_current_codepage();
464 if (from_cp == CP_C_LOCALE) {
466 * "C" locale special process.
469 const unsigned char *mp;
471 if (NULL == archive_wstring_ensure(dest,
472 dest->length + length + 1))
475 ws = dest->s + dest->length;
476 mp = (const unsigned char *)s;
478 while (count < (int)length && *mp) {
479 *ws++ = (wchar_t)*mp++;
482 } else if (sc != NULL && (sc->flag & SCONV_NORMALIZATION_C)) {
484 * Normalize UTF-8 and UTF-16BE and convert it directly
485 * to UTF-16 as wchar_t.
487 struct archive_string u16;
488 int saved_flag = sc->flag;/* save current flag. */
491 sc->flag |= SCONV_TO_UTF16BE;
493 sc->flag |= SCONV_TO_UTF16LE;
495 if (sc->flag & SCONV_FROM_UTF16) {
497 * UTF-16BE/LE NFD ===> UTF-16 NFC
499 count = utf16nbytes(s, length);
502 * UTF-8 NFD ===> UTF-16 NFC
504 count = mbsnbytes(s, length);
506 u16.s = (char *)dest->s;
507 u16.length = dest->length << 1;;
508 u16.buffer_length = dest->buffer_length;
509 ret = archive_string_normalize_C(&u16, s, count, sc);
510 dest->s = (wchar_t *)u16.s;
511 dest->length = u16.length >> 1;
512 dest->buffer_length = u16.buffer_length;
513 sc->flag = saved_flag;/* restore the saved flag. */
515 } else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
516 count = utf16nbytes(s, length);
517 count >>= 1; /* to be WCS length */
518 /* Allocate memory for WCS. */
519 if (NULL == archive_wstring_ensure(dest,
520 dest->length + count + 1))
522 wmemcpy(dest->s + dest->length, (wchar_t *)s, count);
523 if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) {
524 uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
526 for (b = 0; b < count; b++) {
527 uint16_t val = archive_le16dec(u16+b);
528 archive_be16enc(u16+b, val);
530 } else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) {
531 uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
533 for (b = 0; b < count; b++) {
534 uint16_t val = archive_be16dec(u16+b);
535 archive_le16enc(u16+b, val);
543 else if (sc->flag & SCONV_FROM_CHARSET) {
544 /* Do not trust the length which comes from
545 * an archive file. */
546 length = mbsnbytes(s, length);
549 mbflag = MB_PRECOMPOSED;
553 * We do not need to convert any characters but make
554 * sure `dest' has a valid buffer(no NULL pointer).
556 if (NULL == archive_wstring_ensure(dest,
559 dest->s[dest->length] = L'\0';
564 * Count how many bytes are needed for WCS.
566 count = MultiByteToWideChar(from_cp,
567 mbflag, s, length, NULL, 0);
569 if (dest->s == NULL) {
570 if (NULL == archive_wstring_ensure(dest,
574 dest->s[dest->length] = L'\0';
577 /* Allocate memory for WCS. */
578 if (NULL == archive_wstring_ensure(dest,
579 dest->length + count + 1))
581 /* Convert MBS to WCS. */
582 count = MultiByteToWideChar(from_cp,
583 mbflag, s, length, dest->s + dest->length, count);
587 dest->length += count;
588 dest->s[dest->length] = L'\0';
592 #elif defined(HAVE_MBSNRTOWCS)
595 * Convert MBS to WCS.
596 * Note: returns -1 if conversion fails.
599 archive_wstring_append_from_mbs(struct archive_wstring *dest,
600 const char *p, size_t len)
604 * No single byte will be more than one wide character,
605 * so this length estimate will always be big enough.
607 size_t wcs_length = len;
608 size_t mbs_length = len;
611 mbstate_t shift_state;
613 memset(&shift_state, 0, sizeof(shift_state));
614 if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))
616 "No memory for archive_wstring_append_from_mbs()");
617 wcs = dest->s + dest->length;
618 r = mbsnrtowcs(wcs, &mbs, mbs_length, wcs_length, &shift_state);
619 if (r != (size_t)-1) {
621 dest->s[dest->length] = L'\0';
624 dest->s[dest->length] = L'\0';
631 * Convert MBS to WCS.
632 * Note: returns -1 if conversion fails.
635 archive_wstring_append_from_mbs(struct archive_wstring *dest,
636 const char *p, size_t len)
640 * No single byte will be more than one wide character,
641 * so this length estimate will always be big enough.
643 size_t wcs_length = len;
644 size_t mbs_length = len;
648 mbstate_t shift_state;
650 memset(&shift_state, 0, sizeof(shift_state));
652 if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))
654 "No memory for archive_wstring_append_from_mbs()");
655 wcs = dest->s + dest->length;
657 * We cannot use mbsrtowcs/mbstowcs here because those may convert
658 * extra MBS when strlen(p) > len and one wide character consis of
661 while (wcs_length > 0 && *mbs && mbs_length > 0) {
663 r = mbrtowc(wcs, mbs, wcs_length, &shift_state);
665 r = mbtowc(wcs, mbs, wcs_length);
667 if (r == (size_t)-1 || r == (size_t)-2) {
668 dest->s[dest->length] = L'\0';
671 if (r == 0 || r > mbs_length)
678 dest->length = wcs - dest->s;
679 dest->s[dest->length] = L'\0';
685 #if defined(_WIN32) && !defined(__CYGWIN__)
689 * Note: returns -1 if conversion fails.
691 * Win32 builds use WideCharToMultiByte from the Windows API.
692 * (Maybe Cygwin should too? WideCharToMultiByte will know a
693 * lot more about local character encodings than the wcrtomb()
694 * wrapper is going to know.)
697 archive_string_append_from_wcs(struct archive_string *as,
698 const wchar_t *w, size_t len)
700 int r = archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
701 if (r != 0 && errno == ENOMEM)
702 __archive_errx(1, "No memory");
707 archive_string_append_from_wcs_in_codepage(struct archive_string *as,
708 const wchar_t *ws, size_t len, struct archive_string_conv *sc)
710 BOOL defchar_used, *dp;
713 int wslen = (int)len;
718 to_cp = get_current_codepage();
720 if (to_cp == CP_C_LOCALE) {
722 * "C" locale special process.
724 const wchar_t *wp = ws;
727 if (NULL == archive_string_ensure(as,
728 as->length + wslen +1))
730 p = as->s + as->length;
733 while (count < wslen && *wp) {
742 } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
746 archive_string_ensure(as, as->length + len * 2 + 2))
748 u16 = (uint16_t *)(as->s + as->length);
751 if (sc->flag & SCONV_TO_UTF16BE) {
752 while (count < (int)len && *ws) {
753 archive_be16enc(u16+count, *ws);
758 while (count < (int)len && *ws) {
759 archive_le16enc(u16+count, *ws);
764 count <<= 1; /* to be byte size */
766 /* Make sure the MBS buffer has plenty to set. */
768 archive_string_ensure(as, as->length + len * 2 + 1))
772 if (to_cp == CP_UTF8 || sc == NULL)
776 count = WideCharToMultiByte(to_cp, 0, ws, wslen,
777 as->s + as->length, as->buffer_length-1, NULL, dp);
779 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
780 /* Expand the MBS buffer and retry. */
781 if (NULL == archive_string_ensure(as,
782 as->buffer_length + len))
791 as->s[as->length] = '\0';
792 return (defchar_used?-1:ret);
795 #elif defined(HAVE_WCSNRTOMBS)
798 * Translates a wide character string into current locale character set
799 * and appends to the archive_string. Note: returns -1 if conversion
803 archive_string_append_from_wcs(struct archive_string *as,
804 const wchar_t *w, size_t len)
806 mbstate_t shift_state;
807 size_t r, ndest, nwc;
809 const wchar_t *wp, *wpp;
815 /* Initialize the shift state. */
816 memset(&shift_state, 0, sizeof(shift_state));
818 /* Allocate buffer for MBS. */
819 if (archive_string_ensure(as, as->length + ndest + 1) == NULL)
820 __archive_errx(1, "Out of memory");
822 dest = as->s + as->length;
824 r = wcsnrtombs(dest, &wp, nwc,
825 as->buffer_length - as->length -1,
827 if (r == (size_t)-1) {
828 if (errno == EILSEQ) {
829 /* Retry conversion just for safe WCS. */
830 size_t xwc = wp - wpp;
832 r = wcsnrtombs(dest, &wp, xwc,
833 as->buffer_length - as->length -1,
836 /* This would not happen. */
840 /* Skip an illegal wide char. */
841 as->s[as->length++] = '?';
852 if (wp == NULL || (wp - wpp) >= nwc)
854 /* Get a remaining WCS lenth. */
857 /* All wide characters are translated to MBS. */
858 as->s[as->length] = '\0';
862 #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
865 * Translates a wide character string into current locale character set
866 * and appends to the archive_string. Note: returns -1 if conversion
870 archive_string_append_from_wcs(struct archive_string *as,
871 const wchar_t *w, size_t len)
873 /* We cannot use the standard wcstombs() here because it
874 * cannot tell us how big the output buffer should be. So
875 * I've built a loop around wcrtomb() or wctomb() that
876 * converts a character at a time and resizes the string as
877 * needed. We prefer wcrtomb() when it's available because
878 * it's thread-safe. */
883 mbstate_t shift_state;
885 memset(&shift_state, 0, sizeof(shift_state));
887 /* Clear the shift state before starting. */
891 * Allocate buffer for MBS.
892 * We need this allocation here since it is possible that
893 * as->s is still NULL.
895 if (archive_string_ensure(as, as->length + len + 1) == NULL)
896 __archive_errx(1, "Out of memory");
898 p = as->s + as->length;
899 end = as->s + as->buffer_length - MB_CUR_MAX -1;
900 while (*w != L'\0' && len > 0) {
902 as->length = p - as->s;
903 as->s[as->length] = '\0';
904 /* Re-allocate buffer for MBS. */
905 if (archive_string_ensure(as,
906 as->length + len * 2 + 1) == NULL)
907 __archive_errx(1, "Out of memory");
908 p = as->s + as->length;
909 end = as->s + as->buffer_length - MB_CUR_MAX -1;
912 n = wcrtomb(p, *w++, &shift_state);
917 if (errno == EILSEQ) {
918 /* Skip an illegal wide char. */
929 as->length = p - as->s;
930 as->s[as->length] = '\0';
934 #else /* HAVE_WCTOMB || HAVE_WCRTOMB */
937 * TODO: Test if __STDC_ISO_10646__ is defined.
938 * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
939 * one character at a time. If a non-Windows platform doesn't have
940 * either of these, fall back to the built-in UTF8 conversion.
943 archive_string_append_from_wcs(struct archive_string *as,
944 const wchar_t *w, size_t len)
946 (void)as;/* UNUSED */
948 (void)len;/* UNUSED */
952 #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
955 * Find a string conversion object by a pair of 'from' charset name
956 * and 'to' charset name from an archive object.
957 * Return NULL if not found.
959 static struct archive_string_conv *
960 find_sconv_object(struct archive *a, const char *fc, const char *tc)
962 struct archive_string_conv *sc;
967 for (sc = a->sconv; sc != NULL; sc = sc->next) {
968 if (strcmp(sc->from_charset, fc) == 0 &&
969 strcmp(sc->to_charset, tc) == 0)
976 * Register a string object to an archive object.
979 add_sconv_object(struct archive *a, struct archive_string_conv *sc)
981 struct archive_string_conv **psc;
983 /* Add a new sconv to sconv list. */
986 psc = &((*psc)->next);
990 #if defined(__APPLE__)
993 createUniInfo(struct archive_string_conv *sconv)
998 map.unicodeEncoding = CreateTextEncoding(kTextEncodingUnicodeDefault,
999 kUnicodeNoSubset, kUnicode16BitFormat);
1000 map.otherEncoding = CreateTextEncoding(kTextEncodingUnicodeDefault,
1001 kUnicodeHFSPlusDecompVariant, kUnicode16BitFormat);
1002 map.mappingVersion = kUnicodeUseLatestMapping;
1004 sconv->uniInfo = NULL;
1005 err = CreateUnicodeToTextInfo(&map, &(sconv->uniInfo));
1006 return ((err == noErr)? 0: -1);
1009 #endif /* __APPLE__ */
1012 add_converter(struct archive_string_conv *sc, int (*converter)
1013 (struct archive_string *, const void *, size_t,
1014 struct archive_string_conv *))
1016 if (sc == NULL || sc->nconverter >= 2)
1017 __archive_errx(1, "Programing error");
1018 sc->converter[sc->nconverter++] = converter;
1022 setup_converter(struct archive_string_conv *sc)
1029 * Perform special sequence for the incorrect UTF-8 filenames
1030 * made by libarchive2.x.
1032 if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
1033 add_converter(sc, strncat_from_utf8_libarchive2);
1038 * Convert a string to UTF-16BE/LE.
1040 if (sc->flag & SCONV_TO_UTF16) {
1042 * If the current locale is UTF-8, we can translate
1043 * a UTF-8 string into a UTF-16BE string.
1045 if (sc->flag & SCONV_FROM_UTF8) {
1046 add_converter(sc, archive_string_append_unicode);
1050 #if defined(_WIN32) && !defined(__CYGWIN__)
1051 if (sc->flag & SCONV_WIN_CP) {
1052 if (sc->flag & SCONV_TO_UTF16BE)
1053 add_converter(sc, win_strncat_to_utf16be);
1055 add_converter(sc, win_strncat_to_utf16le);
1060 #if defined(HAVE_ICONV)
1061 if (sc->cd != (iconv_t)-1) {
1062 add_converter(sc, iconv_strncat_in_locale);
1067 if (sc->flag & SCONV_BEST_EFFORT) {
1068 if (sc->flag & SCONV_TO_UTF16BE)
1069 add_converter(sc, best_effort_strncat_to_utf16be);
1071 add_converter(sc, best_effort_strncat_to_utf16le);
1073 /* Make sure we have no converter. */
1079 * Convert a string from UTF-16BE/LE.
1081 if (sc->flag & SCONV_FROM_UTF16) {
1083 * At least we should normalize a UTF-16BE string.
1085 #if defined(__APPLE__)
1086 if (sc->flag & SCONV_NORMALIZATION_D)
1087 add_converter(sc,archive_string_normalize_D);
1090 if (sc->flag & SCONV_NORMALIZATION_C)
1091 add_converter(sc, archive_string_normalize_C);
1093 if (sc->flag & SCONV_TO_UTF8) {
1095 * If the current locale is UTF-8, we can translate
1096 * a UTF-16BE/LE string into a UTF-8 string directly.
1099 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1101 archive_string_append_unicode);
1105 #if defined(_WIN32) && !defined(__CYGWIN__)
1106 if (sc->flag & SCONV_WIN_CP) {
1107 if (sc->flag & SCONV_FROM_UTF16BE)
1108 add_converter(sc, win_strncat_from_utf16be);
1110 add_converter(sc, win_strncat_from_utf16le);
1115 #if defined(HAVE_ICONV)
1116 if (sc->cd != (iconv_t)-1) {
1117 add_converter(sc, iconv_strncat_in_locale);
1122 if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
1123 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
1124 add_converter(sc, best_effort_strncat_from_utf16be);
1125 else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1126 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1127 add_converter(sc, best_effort_strncat_from_utf16le);
1129 /* Make sure we have no converter. */
1134 if (sc->flag & SCONV_FROM_UTF8) {
1136 * At least we should normalize a UTF-8 string.
1138 #if defined(__APPLE__)
1139 if (sc->flag & SCONV_NORMALIZATION_D)
1140 add_converter(sc,archive_string_normalize_D);
1143 if (sc->flag & SCONV_NORMALIZATION_C)
1144 add_converter(sc, archive_string_normalize_C);
1147 * Copy UTF-8 string with a check of CESU-8.
1148 * Apparently, iconv does not check surrogate pairs in UTF-8
1149 * when both from-charset and to-charset are UTF-8, and then
1150 * we use our UTF-8 copy code.
1152 if (sc->flag & SCONV_TO_UTF8) {
1154 * If the current locale is UTF-8, we can translate
1155 * a UTF-16BE string into a UTF-8 string directly.
1158 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1159 add_converter(sc, strncat_from_utf8_to_utf8);
1164 #if defined(_WIN32) && !defined(__CYGWIN__)
1166 * On Windows we can use Windows API for a string conversion.
1168 if (sc->flag & SCONV_WIN_CP) {
1169 add_converter(sc, strncat_in_codepage);
1175 if (sc->cd != (iconv_t)-1) {
1176 add_converter(sc, iconv_strncat_in_locale);
1182 * Try conversion in the best effort or no conversion.
1184 if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
1185 add_converter(sc, best_effort_strncat_in_locale);
1187 /* Make sure we have no converter. */
1192 * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
1193 * and CP932 which are referenced in create_sconv_object().
1196 canonical_charset_name(const char *charset)
1202 if (charset == NULL || charset[0] == '\0'
1203 || strlen(charset) > 15)
1206 /* Copy name to uppercase. */
1211 if (c >= 'a' && c <= 'z')
1217 if (strcmp(cs, "UTF-8") == 0 ||
1218 strcmp(cs, "UTF8") == 0)
1220 if (strcmp(cs, "UTF-16BE") == 0 ||
1221 strcmp(cs, "UTF16BE") == 0)
1222 return ("UTF-16BE");
1223 if (strcmp(cs, "UTF-16LE") == 0 ||
1224 strcmp(cs, "UTF16LE") == 0)
1225 return ("UTF-16LE");
1226 if (strcmp(cs, "CP932") == 0)
1232 * Create a string conversion object.
1234 static struct archive_string_conv *
1235 create_sconv_object(const char *fc, const char *tc,
1236 unsigned current_codepage, int flag)
1238 struct archive_string_conv *sc;
1240 sc = calloc(1, sizeof(*sc));
1244 sc->from_charset = strdup(fc);
1245 if (sc->from_charset == NULL) {
1249 sc->to_charset = strdup(tc);
1250 if (sc->to_charset == NULL) {
1252 free(sc->from_charset);
1255 archive_string_init(&sc->utftmp);
1256 #if defined(__APPLE__)
1257 archive_string_init(&sc->utf16nfc);
1258 archive_string_init(&sc->utf16nfd);
1261 if (flag & SCONV_TO_CHARSET) {
1263 * Convert characters from the current locale charset to
1264 * a specified charset.
1266 sc->from_cp = current_codepage;
1267 sc->to_cp = make_codepage_from_charset(tc);
1268 #if defined(_WIN32) && !defined(__CYGWIN__)
1269 if (IsValidCodePage(sc->to_cp))
1270 flag |= SCONV_WIN_CP;
1272 } else if (flag & SCONV_FROM_CHARSET) {
1274 * Convert characters from a specified charset to
1275 * the current locale charset.
1277 sc->to_cp = current_codepage;
1278 sc->from_cp = make_codepage_from_charset(fc);
1279 #if defined(_WIN32) && !defined(__CYGWIN__)
1280 if (IsValidCodePage(sc->from_cp))
1281 flag |= SCONV_WIN_CP;
1286 * Check if "from charset" and "to charset" are the same.
1288 if (strcmp(fc, tc) == 0 ||
1289 (sc->from_cp != -1 && sc->from_cp == sc->to_cp))
1295 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
1297 if (strcmp(tc, "UTF-8") == 0)
1298 flag |= SCONV_TO_UTF8;
1299 else if (strcmp(tc, "UTF-16BE") == 0)
1300 flag |= SCONV_TO_UTF16BE;
1301 else if (strcmp(tc, "UTF-16LE") == 0)
1302 flag |= SCONV_TO_UTF16LE;
1303 if (strcmp(fc, "UTF-8") == 0)
1304 flag |= SCONV_FROM_UTF8;
1305 else if (strcmp(fc, "UTF-16BE") == 0)
1306 flag |= SCONV_FROM_UTF16BE;
1307 else if (strcmp(fc, "UTF-16LE") == 0)
1308 flag |= SCONV_FROM_UTF16LE;
1309 #if defined(_WIN32) && !defined(__CYGWIN__)
1310 if (sc->to_cp == CP_UTF8)
1311 flag |= SCONV_TO_UTF8;
1312 else if (sc->to_cp == CP_UTF16BE)
1313 flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
1314 else if (sc->to_cp == CP_UTF16LE)
1315 flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
1316 if (sc->from_cp == CP_UTF8)
1317 flag |= SCONV_FROM_UTF8;
1318 else if (sc->from_cp == CP_UTF16BE)
1319 flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
1320 else if (sc->from_cp == CP_UTF16LE)
1321 flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
1325 * Set a flag for Unicode NFD. Usually iconv cannot correctly
1326 * handle it. So we have to translate NFD characters to NFC ones
1327 * ourselves before iconv handles. Another reason is to prevent
1328 * that the same sight of two filenames, one is NFC and other
1329 * is NFD, would be in its directory.
1330 * On Mac OS X, although its filesystem layer automatically
1331 * convert filenames to NFD, it would be useful for filename
1332 * comparing to find out the same filenames that we normalize
1333 * that to be NFD ourselves.
1335 if ((flag & SCONV_FROM_CHARSET) &&
1336 (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
1337 #if defined(__APPLE__)
1338 if (flag & SCONV_TO_UTF8) {
1339 if (createUniInfo(sc) == 0)
1340 flag |= SCONV_NORMALIZATION_D;
1343 flag |= SCONV_NORMALIZATION_C;
1346 #if defined(HAVE_ICONV)
1347 sc->cd_w = (iconv_t)-1;
1349 * Create an iconv object.
1351 if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
1352 (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
1353 (flag & SCONV_WIN_CP)) {
1354 /* This case we won't use iconv. */
1355 sc->cd = (iconv_t)-1;
1356 #if defined(__APPLE__)
1357 } else if ((flag & SCONV_FROM_CHARSET) && (flag & SCONV_TO_UTF8)) {
1359 * In case reading an archive file.
1360 * Translate non-Unicode filenames in an archive file to
1361 * UTF-8-MAC filenames.
1363 sc->cd = iconv_open("UTF-8-MAC", fc);
1364 if (sc->cd == (iconv_t)-1) {
1365 if ((sc->flag & SCONV_BEST_EFFORT) &&
1366 strcmp(fc, "CP932") == 0) {
1367 sc->cd = iconv_open("UTF-8-MAC", "SJIS");
1368 if (sc->cd == (iconv_t)-1) {
1369 sc->cd = iconv_open(tc, fc);
1370 if (sc->cd == (iconv_t)-1)
1371 sc->cd = iconv_open(tc, "SJIS");
1374 sc->cd = iconv_open(tc, fc);
1376 } else if ((flag & SCONV_TO_CHARSET) && (flag & SCONV_FROM_UTF8)) {
1378 * In case writing an archive file.
1379 * Translate UTF-8-MAC filenames in HFS Plus to non-Unicode
1382 sc->cd = iconv_open(tc, "UTF-8-MAC");
1383 if (sc->cd == (iconv_t)-1) {
1384 if ((sc->flag & SCONV_BEST_EFFORT) &&
1385 strcmp(tc, "CP932") == 0) {
1386 sc->cd = iconv_open("SJIS", "UTF-8-MAC");
1387 if (sc->cd == (iconv_t)-1) {
1388 sc->cd = iconv_open(tc, fc);
1389 if (sc->cd == (iconv_t)-1)
1390 sc->cd = iconv_open("SJIS", fc);
1393 sc->cd = iconv_open(tc, fc);
1397 sc->cd = iconv_open(tc, fc);
1398 if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
1400 * Unfortunaly, all of iconv implements do support
1401 * "CP932" character-set, so we should use "SJIS"
1402 * instead if iconv_open failed.
1404 if (strcmp(tc, "CP932") == 0)
1405 sc->cd = iconv_open("SJIS", fc);
1406 else if (strcmp(fc, "CP932") == 0)
1407 sc->cd = iconv_open(tc, "SJIS");
1409 #if defined(_WIN32) && !defined(__CYGWIN__)
1411 * archive_mstring on Windows directly convert multi-bytes
1412 * into archive_wstring in order not to depend on locale
1413 * so that you can do a I18N programing. This will be
1414 * used only in archive_mstring_copy_mbs_len_l so far.
1416 if (flag & SCONV_FROM_CHARSET) {
1417 sc->cd_w = iconv_open("UTF-8", fc);
1418 if (sc->cd_w == (iconv_t)-1 &&
1419 (sc->flag & SCONV_BEST_EFFORT)) {
1420 if (strcmp(fc, "CP932") == 0)
1421 sc->cd_w = iconv_open("UTF-8", "SJIS");
1424 #endif /* _WIN32 && !__CYGWIN__ */
1426 #endif /* HAVE_ICONV */
1433 setup_converter(sc);
1439 * Free a string conversion object.
1442 free_sconv_object(struct archive_string_conv *sc)
1444 free(sc->from_charset);
1445 free(sc->to_charset);
1446 archive_string_free(&sc->utftmp);
1448 if (sc->cd != (iconv_t)-1)
1449 iconv_close(sc->cd);
1450 if (sc->cd_w != (iconv_t)-1)
1451 iconv_close(sc->cd_w);
1453 #if defined(__APPLE__)
1454 archive_string_free(&sc->utf16nfc);
1455 archive_string_free(&sc->utf16nfd);
1456 if (sc->uniInfo != NULL)
1457 DisposeUnicodeToTextInfo(&(sc->uniInfo));
1462 #if defined(_WIN32) && !defined(__CYGWIN__)
1464 my_atoi(const char *p)
1470 if (*p >= '0' && *p <= '9')
1471 cp = cp * 10 + (*p - '0');
1480 * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
1481 * Return -1 if failed.
1483 * Note: This translation code may be insufficient.
1485 static struct charset {
1489 /* MUST BE SORTED! */
1508 {"HZ-GB-2312", 52936},
1526 {"ISO-8859-1", 28591},
1527 {"ISO-8859-13", 28603},
1528 {"ISO-8859-15", 28605},
1529 {"ISO-8859-2", 28592},
1530 {"ISO-8859-3", 28593},
1531 {"ISO-8859-4", 28594},
1532 {"ISO-8859-5", 28595},
1533 {"ISO-8859-6", 28596},
1534 {"ISO-8859-7", 28597},
1535 {"ISO-8859-8", 28598},
1536 {"ISO-8859-9", 28599},
1537 {"ISO8859-1", 28591},
1538 {"ISO8859-13", 28603},
1539 {"ISO8859-15", 28605},
1540 {"ISO8859-2", 28592},
1541 {"ISO8859-3", 28593},
1542 {"ISO8859-4", 28594},
1543 {"ISO8859-5", 28595},
1544 {"ISO8859-6", 28596},
1545 {"ISO8859-7", 28597},
1546 {"ISO8859-8", 28598},
1547 {"ISO8859-9", 28599},
1551 {"KS_C_5601-1987", 949},
1554 {"MACINTOSH", 10000},
1564 {"X-EUROPA", 29001},
1565 {"X-MAC-ARABIC", 10004},
1566 {"X-MAC-CE", 10029},
1567 {"X-MAC-CHINESEIMP", 10008},
1568 {"X-MAC-CHINESETRAD", 10002},
1569 {"X-MAC-CROATIAN", 10082},
1570 {"X-MAC-CYRILLIC", 10007},
1571 {"X-MAC-GREEK", 10006},
1572 {"X-MAC-HEBREW", 10005},
1573 {"X-MAC-ICELANDIC", 10079},
1574 {"X-MAC-JAPANESE", 10001},
1575 {"X-MAC-KOREAN", 10003},
1576 {"X-MAC-ROMANIAN", 10010},
1577 {"X-MAC-THAI", 10021},
1578 {"X-MAC-TURKISH", 10081},
1579 {"X-MAC-UKRAINIAN", 10017},
1582 make_codepage_from_charset(const char *charset)
1589 if (charset == NULL || strlen(charset) > 15)
1592 /* Copy name to uppercase. */
1595 char c = *charset++;
1596 if (c >= 'a' && c <= 'z')
1603 /* Look it up in the table first, so that we can easily
1604 * override CP367, which we map to 1252 instead of 367. */
1606 b = sizeof(charsets)/sizeof(charsets[0]);
1608 int c = (b + a) / 2;
1609 int r = strcmp(charsets[c].name, cs);
1615 return charsets[c].cp;
1618 /* If it's not in the table, try to parse it. */
1621 if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
1622 cp = my_atoi(cs + 2);
1623 } else if (strcmp(cs, "CP_ACP") == 0)
1624 cp = get_current_codepage();
1625 else if (strcmp(cs, "CP_OEMCP") == 0)
1626 cp = get_current_oemcp();
1629 if (cs[1] == 'B' && cs[2] == 'M' &&
1630 cs[3] >= '0' && cs[3] <= '9') {
1631 cp = my_atoi(cs + 3);
1635 if (strncmp(cs, "WINDOWS-", 8) == 0) {
1636 cp = my_atoi(cs + 8);
1637 if (cp != 874 && (cp < 1250 || cp > 1258))
1638 cp = -1;/* This may invalid code. */
1646 * Return ANSI Code Page of current locale set by setlocale().
1649 get_current_codepage()
1654 locale = setlocale(LC_CTYPE, NULL);
1657 if (locale[0] == 'C' && locale[1] == '\0')
1658 return (CP_C_LOCALE);
1659 p = strrchr(locale, '.');
1669 * Translation table between Locale Name and ACP/OEMCP.
1676 { 950, 950, "Chinese_Taiwan" },
1677 { 936, 936, "Chinese_People's Republic of China" },
1678 { 950, 950, "Chinese_Taiwan" },
1679 { 1250, 852, "Czech_Czech Republic" },
1680 { 1252, 850, "Danish_Denmark" },
1681 { 1252, 850, "Dutch_Netherlands" },
1682 { 1252, 850, "Dutch_Belgium" },
1683 { 1252, 437, "English_United States" },
1684 { 1252, 850, "English_Australia" },
1685 { 1252, 850, "English_Canada" },
1686 { 1252, 850, "English_New Zealand" },
1687 { 1252, 850, "English_United Kingdom" },
1688 { 1252, 437, "English_United States" },
1689 { 1252, 850, "Finnish_Finland" },
1690 { 1252, 850, "French_France" },
1691 { 1252, 850, "French_Belgium" },
1692 { 1252, 850, "French_Canada" },
1693 { 1252, 850, "French_Switzerland" },
1694 { 1252, 850, "German_Germany" },
1695 { 1252, 850, "German_Austria" },
1696 { 1252, 850, "German_Switzerland" },
1697 { 1253, 737, "Greek_Greece" },
1698 { 1250, 852, "Hungarian_Hungary" },
1699 { 1252, 850, "Icelandic_Iceland" },
1700 { 1252, 850, "Italian_Italy" },
1701 { 1252, 850, "Italian_Switzerland" },
1702 { 932, 932, "Japanese_Japan" },
1703 { 949, 949, "Korean_Korea" },
1704 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1705 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1706 { 1252, 850, "Norwegian-Nynorsk_Norway" },
1707 { 1250, 852, "Polish_Poland" },
1708 { 1252, 850, "Portuguese_Portugal" },
1709 { 1252, 850, "Portuguese_Brazil" },
1710 { 1251, 866, "Russian_Russia" },
1711 { 1250, 852, "Slovak_Slovakia" },
1712 { 1252, 850, "Spanish_Spain" },
1713 { 1252, 850, "Spanish_Mexico" },
1714 { 1252, 850, "Spanish_Spain" },
1715 { 1252, 850, "Swedish_Sweden" },
1716 { 1254, 857, "Turkish_Turkey" },
1721 * Return OEM Code Page of current locale set by setlocale().
1730 locale = setlocale(LC_CTYPE, NULL);
1732 return (GetOEMCP());
1733 if (locale[0] == 'C' && locale[1] == '\0')
1734 return (CP_C_LOCALE);
1736 p = strrchr(locale, '.');
1738 return (GetOEMCP());
1740 for (i = 0; acp_ocp_map[i].acp; i++) {
1741 if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
1742 return (acp_ocp_map[i].ocp);
1744 return (GetOEMCP());
1749 * POSIX platform does not use CodePage.
1753 get_current_codepage()
1755 return (-1);/* Unknown */
1758 make_codepage_from_charset(const char *charset)
1760 (void)charset; /* UNUSED */
1761 return (-1);/* Unknown */
1766 return (-1);/* Unknown */
1769 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1772 * Return a string conversion object.
1774 static struct archive_string_conv *
1775 get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
1777 struct archive_string_conv *sc;
1778 unsigned current_codepage;
1780 /* Check if we have made the sconv object. */
1781 sc = find_sconv_object(a, fc, tc);
1786 current_codepage = get_current_codepage();
1788 current_codepage = a->current_codepage;
1790 sc = create_sconv_object(canonical_charset_name(fc),
1791 canonical_charset_name(tc), current_codepage, flag);
1794 archive_set_error(a, ENOMEM,
1795 "Could not allocate memory for "
1796 "a string conversion object");
1801 * If there is no converter for current string conversion object,
1802 * we cannot handle this conversion.
1804 if (sc->nconverter == 0) {
1807 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1808 "iconv_open failed : Cannot handle ``%s''",
1809 (flag & SCONV_TO_CHARSET)?tc:fc);
1811 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1812 "A character-set conversion not fully supported "
1813 "on this platform");
1816 /* Failed; free a sconv object. */
1817 free_sconv_object(sc);
1825 add_sconv_object(a, sc);
1830 get_current_charset(struct archive *a)
1832 const char *cur_charset;
1835 cur_charset = default_iconv_charset("");
1837 cur_charset = default_iconv_charset(a->current_code);
1838 if (a->current_code == NULL) {
1839 a->current_code = strdup(cur_charset);
1840 a->current_codepage = get_current_codepage();
1841 a->current_oemcp = get_current_oemcp();
1844 return (cur_charset);
1848 * Make and Return a string conversion object.
1849 * Return NULL if the platform does not support the specified conversion
1850 * and best_effort is 0.
1851 * If best_effort is set, A string conversion object must be returned
1852 * unless memory allocation for the object fails, but the conversion
1853 * might fail when non-ASCII code is found.
1855 struct archive_string_conv *
1856 archive_string_conversion_to_charset(struct archive *a, const char *charset,
1859 int flag = SCONV_TO_CHARSET;
1862 flag |= SCONV_BEST_EFFORT;
1863 return (get_sconv_object(a, get_current_charset(a), charset, flag));
1866 struct archive_string_conv *
1867 archive_string_conversion_from_charset(struct archive *a, const char *charset,
1870 int flag = SCONV_FROM_CHARSET;
1873 flag |= SCONV_BEST_EFFORT;
1874 return (get_sconv_object(a, charset, get_current_charset(a), flag));
1878 * archive_string_default_conversion_*_archive() are provided for Windows
1879 * platform because other archiver application use CP_OEMCP for
1880 * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
1881 * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
1882 * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
1883 * So we should make a string conversion between CP_ACP and CP_OEMCP
1884 * for compatibillty.
1886 #if defined(_WIN32) && !defined(__CYGWIN__)
1887 struct archive_string_conv *
1888 archive_string_default_conversion_for_read(struct archive *a)
1890 const char *cur_charset = get_current_charset(a);
1893 /* NOTE: a check of cur_charset is unneeded but we need
1894 * that get_current_charset() has been surely called at
1895 * this time whatever C compiler optimized. */
1896 if (cur_charset != NULL &&
1897 (a->current_codepage == CP_C_LOCALE ||
1898 a->current_codepage == a->current_oemcp))
1899 return (NULL);/* no conversion. */
1901 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1902 /* Make sure a null termination must be set. */
1903 oemcp[sizeof(oemcp)-1] = '\0';
1904 return (get_sconv_object(a, oemcp, cur_charset,
1905 SCONV_FROM_CHARSET));
1908 struct archive_string_conv *
1909 archive_string_default_conversion_for_write(struct archive *a)
1911 const char *cur_charset = get_current_charset(a);
1914 /* NOTE: a check of cur_charset is unneeded but we need
1915 * that get_current_charset() has been surely called at
1916 * this time whatever C compiler optimized. */
1917 if (cur_charset != NULL &&
1918 (a->current_codepage == CP_C_LOCALE ||
1919 a->current_codepage == a->current_oemcp))
1920 return (NULL);/* no conversion. */
1922 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1923 /* Make sure a null termination must be set. */
1924 oemcp[sizeof(oemcp)-1] = '\0';
1925 return (get_sconv_object(a, cur_charset, oemcp,
1929 struct archive_string_conv *
1930 archive_string_default_conversion_for_read(struct archive *a)
1932 (void)a; /* UNUSED */
1936 struct archive_string_conv *
1937 archive_string_default_conversion_for_write(struct archive *a)
1939 (void)a; /* UNUSED */
1945 * Dispose of all character conversion objects in the archive object.
1948 archive_string_conversion_free(struct archive *a)
1950 struct archive_string_conv *sc;
1951 struct archive_string_conv *sc_next;
1953 for (sc = a->sconv; sc != NULL; sc = sc_next) {
1955 free_sconv_object(sc);
1958 free(a->current_code);
1959 a->current_code = NULL;
1963 * Return a conversion charset name.
1966 archive_string_conversion_charset_name(struct archive_string_conv *sc)
1968 if (sc->flag & SCONV_TO_CHARSET)
1969 return (sc->to_charset);
1971 return (sc->from_charset);
1975 * Change the behavior of a string conversion.
1978 archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
1982 * A filename in UTF-8 was made with libarchive 2.x in a wrong
1983 * assumption that wchar_t was Unicode.
1984 * This option enables simulating the assumption in order to read
1985 * that filname correctly.
1987 case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
1988 #if (defined(_WIN32) && !defined(__CYGWIN__)) \
1989 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
1991 * Nothing to do for it since wchar_t on these platforms
1992 * is really Unicode.
1994 (void)sc; /* UNUSED */
1996 if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
1997 sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
1998 /* Re-setup string converters. */
1999 setup_converter(sc);
2010 * Copy one archive_string to another in locale conversion.
2012 * archive_strncpy_in_locale();
2013 * archive_strcpy_in_locale();
2018 mbsnbytes(const void *_p, size_t n)
2025 p = (const char *)_p;
2027 /* Like strlen(p), except won't examine positions beyond p[n]. */
2030 while (s < n && *pp) {
2038 utf16nbytes(const void *_p, size_t n)
2045 p = (const char *)_p;
2047 /* Like strlen(p), except won't examine positions beyond p[n]. */
2051 while (s < n && (pp[0] || pp[1])) {
2059 archive_strncpy_in_locale(struct archive_string *as, const void *_p, size_t n,
2060 struct archive_string_conv *sc)
2063 return (archive_strncat_in_locale(as, _p, n, sc));
2067 archive_strncat_in_locale(struct archive_string *as, const void *_p, size_t n,
2068 struct archive_string_conv *sc)
2074 /* We must allocate memory even if there is no data for conversion
2075 * or copy. This simulates archive_string_append behavior. */
2076 if (_p == NULL || n == 0) {
2078 if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
2080 if (archive_string_ensure(as, as->length + tn) == NULL)
2082 as->s[as->length] = 0;
2084 as->s[as->length+1] = 0;
2089 * If sc is NULL, we just make a copy.
2092 length = mbsnbytes(_p, n);
2093 if (archive_string_append(as, _p, length) == NULL)
2094 return (-1);/* No memory */
2098 if (sc->flag & SCONV_FROM_UTF16)
2099 length = utf16nbytes(_p, n);
2101 length = mbsnbytes(_p, n);
2104 if (sc->nconverter > 1) {
2105 sc->utftmp.length = 0;
2106 r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
2107 if (r2 != 0 && errno == ENOMEM)
2112 length = sc->utftmp.length;
2115 r2 = sc->converter[i](as, s, length, sc);
2124 * Return -1 if conversion failes.
2127 iconv_strncat_in_locale(struct archive_string *as, const void *_p,
2128 size_t length, struct archive_string_conv *sc)
2130 ICONV_CONST char *inp;
2135 int return_value = 0; /* success */
2136 int to_size, from_size;
2138 if (sc->flag & SCONV_TO_UTF16)
2142 if (sc->flag & SCONV_FROM_UTF16)
2147 if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2151 inp = (char *)(uintptr_t)_p;
2153 outp = as->s + as->length;
2154 avail = as->buffer_length - as->length - to_size;
2155 while (remaining >= (size_t)from_size) {
2156 size_t result = iconv(cd, &inp, &remaining, &outp, &avail);
2158 if (result != (size_t)-1)
2159 break; /* Conversion completed. */
2161 if (errno == EILSEQ || errno == EINVAL) {
2163 * If an output charset is UTF-8 or UTF-16BE/LE,
2164 * unknown character should be U+FFFD
2165 * (replacement character).
2167 if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2169 if (sc->flag & SCONV_TO_UTF8)
2170 rbytes = UTF8_R_CHAR_SIZE;
2174 if (avail < rbytes) {
2175 as->length = outp - as->s;
2176 bs = as->buffer_length +
2177 (remaining * to_size) + rbytes;
2179 archive_string_ensure(as, bs))
2181 outp = as->s + as->length;
2182 avail = as->buffer_length
2183 - as->length - to_size;
2185 if (sc->flag & SCONV_TO_UTF8)
2186 UTF8_SET_R_CHAR(outp);
2187 else if (sc->flag & SCONV_TO_UTF16BE)
2188 archive_be16enc(outp, UNICODE_R_CHAR);
2190 archive_le16enc(outp, UNICODE_R_CHAR);
2194 /* Skip the illegal input bytes. */
2199 remaining -= from_size;
2200 return_value = -1; /* failure */
2202 /* E2BIG no output buffer,
2203 * Increase an output buffer. */
2204 as->length = outp - as->s;
2205 bs = as->buffer_length + remaining * 2;
2206 if (NULL == archive_string_ensure(as, bs))
2208 outp = as->s + as->length;
2209 avail = as->buffer_length - as->length - to_size;
2212 as->length = outp - as->s;
2213 as->s[as->length] = 0;
2215 as->s[as->length+1] = 0;
2216 return (return_value);
2219 #endif /* HAVE_ICONV */
2222 #if defined(_WIN32) && !defined(__CYGWIN__)
2225 * Translate a string from a some CodePage to an another CodePage by
2226 * Windows APIs, and copy the result. Return -1 if conversion failes.
2229 strncat_in_codepage(struct archive_string *as,
2230 const void *_p, size_t length, struct archive_string_conv *sc)
2232 const char *s = (const char *)_p;
2233 struct archive_wstring aws;
2237 archive_string_init(&aws);
2238 saved_flag = sc->flag;
2239 sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2240 r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2241 sc->flag = saved_flag;
2243 archive_wstring_free(&aws);
2244 if (errno != ENOMEM)
2245 archive_string_append(as, s, length);
2250 r = archive_string_append_from_wcs_in_codepage(
2251 as, aws.s, aws.length, sc);
2252 if (r != 0 && errno != ENOMEM && l == as->length)
2253 archive_string_append(as, s, length);
2254 archive_wstring_free(&aws);
2259 * Test whether MBS ==> WCS is okay.
2262 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2264 const char *p = (const char *)_p;
2266 DWORD mbflag = MB_ERR_INVALID_CHARS;
2268 if (sc->flag & SCONV_FROM_CHARSET)
2269 codepage = sc->to_cp;
2271 codepage = sc->from_cp;
2273 if (codepage == CP_C_LOCALE)
2275 if (codepage != CP_UTF8)
2276 mbflag |= MB_PRECOMPOSED;
2278 if (MultiByteToWideChar(codepage, mbflag, p, n, NULL, 0) == 0)
2279 return (-1); /* Invalid */
2280 return (0); /* Okay */
2286 * Test whether MBS ==> WCS is okay.
2289 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2291 const char *p = (const char *)_p;
2294 (void)sc; /* UNUSED */
2296 mbstate_t shift_state;
2298 memset(&shift_state, 0, sizeof(shift_state));
2300 /* Clear the shift state before starting. */
2301 mbtowc(NULL, NULL, 0);
2307 r = mbrtowc(&wc, p, n, &shift_state);
2309 r = mbtowc(&wc, p, n);
2311 if (r == (size_t)-1 || r == (size_t)-2)
2312 return (-1);/* Invalid. */
2318 return (0); /* All Okey. */
2321 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2324 * Basically returns -1 because we cannot make a conversion of charset
2325 * without iconv but in some cases this would return 0.
2326 * Returns 0 if all copied characters are ASCII.
2327 * Returns 0 if both from-locale and to-locale are the same and those
2328 * can be WCS with no error.
2331 best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2332 size_t length, struct archive_string_conv *sc)
2338 int return_value = 0; /* success */
2341 * If both from-locale and to-locale is the same, this makes a copy.
2342 * And then this checks all copied MBS can be WCS if so returns 0.
2345 if (archive_string_append(as, _p, length) == NULL)
2346 return (-1);/* No memory */
2347 return (invalid_mbs(_p, length, sc));
2351 * If a character is ASCII, this just copies it. If not, this
2352 * assigns '?' charater instead but in UTF-8 locale this assigns
2353 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2354 * a Replacement Character in Unicode.
2356 if (archive_string_ensure(as, as->length + length + 1) == NULL)
2360 inp = (const char *)_p;
2361 outp = as->s + as->length;
2362 avail = as->buffer_length - as->length -1;
2363 while (*inp && remaining > 0) {
2364 if (*inp < 0 && (sc->flag & SCONV_TO_UTF8)) {
2365 if (avail < UTF8_R_CHAR_SIZE) {
2366 as->length = outp - as->s;
2367 if (NULL == archive_string_ensure(as,
2368 as->buffer_length + remaining +
2371 outp = as->s + as->length;
2372 avail = as->buffer_length - as->length -1;
2375 * When coping a string in UTF-8, unknown character
2376 * should be U+FFFD (replacement character).
2378 UTF8_SET_R_CHAR(outp);
2379 outp += UTF8_R_CHAR_SIZE;
2380 avail -= UTF8_R_CHAR_SIZE;
2384 } else if (*inp < 0) {
2394 as->length = outp - as->s;
2395 as->s[as->length] = '\0';
2396 return (return_value);
2401 * Unicode conversion functions.
2402 * - UTF-8 <===> UTF-8 in removing surrogate pairs.
2403 * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2404 * - UTF-8 made by libarchive 2.x ===> UTF-8.
2405 * - UTF-16BE <===> UTF-8.
2410 * Utility to convert a single UTF-8 sequence.
2412 * Usually return used bytes, return used byte in negative value when
2413 * a unicode character is replaced with U+FFFD.
2414 * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2415 * Recommended Practice for Replacement Characters.
2418 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2420 static const char utf8_count[256] = {
2421 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2422 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2423 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2424 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2425 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2426 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2427 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2428 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2429 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2430 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2431 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2432 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2433 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2434 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2435 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2436 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2446 * Decode 1-4 bytes depending on the value of the first byte.
2448 ch = (unsigned char)*s;
2450 return (0); /* Standard: return 0 for end-of-string. */
2451 cnt = utf8_count[ch];
2453 /* Invalide sequence or there are not plenty bytes. */
2456 for (i = 1; i < cnt; i++) {
2457 if ((s[i] & 0xc0) != 0x80) {
2462 goto invalid_sequence;
2465 /* Make a Unicode code point from a single UTF-8 sequence. */
2467 case 1: /* 1 byte sequence. */
2470 case 2: /* 2 bytes sequence. */
2471 if ((s[1] & 0xc0) != 0x80) {
2473 goto invalid_sequence;
2475 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2477 case 3: /* 3 bytes sequence. */
2478 if ((s[1] & 0xc0) != 0x80) {
2480 goto invalid_sequence;
2482 if ((s[2] & 0xc0) != 0x80) {
2484 goto invalid_sequence;
2486 wc = ((ch & 0x0f) << 12)
2487 | ((s[1] & 0x3f) << 6)
2490 goto invalid_sequence;/* Overlong sequence. */
2492 case 4: /* 4 bytes sequence. */
2493 if ((s[1] & 0xc0) != 0x80) {
2495 goto invalid_sequence;
2497 if ((s[2] & 0xc0) != 0x80) {
2499 goto invalid_sequence;
2501 if ((s[3] & 0xc0) != 0x80) {
2503 goto invalid_sequence;
2505 wc = ((ch & 0x07) << 18)
2506 | ((s[1] & 0x3f) << 12)
2507 | ((s[2] & 0x3f) << 6)
2510 goto invalid_sequence;/* Overlong sequence. */
2512 default: /* Others are all invalid sequence. */
2513 if (ch == 0xc0 || ch == 0xc1)
2515 else if (ch >= 0xf5 && ch <= 0xf7)
2517 else if (ch >= 0xf8 && ch <= 0xfb)
2519 else if (ch == 0xfc || ch == 0xfd)
2525 for (i = 1; i < cnt; i++) {
2526 if ((s[i] & 0xc0) != 0x80) {
2531 goto invalid_sequence;
2534 /* The code point larger than 0x10FFFF is not leagal
2535 * Unicode values. */
2536 if (wc > UNICODE_MAX)
2537 goto invalid_sequence;
2538 /* Correctly gets a Unicode, returns used bytes. */
2542 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2547 utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2551 cnt = _utf8_to_unicode(pwc, s, n);
2552 /* Any of Surrogate pair is not leagal Unicode values. */
2553 if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2558 static inline uint32_t
2559 combine_surrogate_pair(uint32_t uc, uint32_t uc2)
2569 * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2570 * removing surrogate pairs.
2572 * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2574 * Usually return used bytes, return used byte in negative value when
2575 * a unicode character is replaced with U+FFFD.
2578 cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2583 cnt = _utf8_to_unicode(&wc, s, n);
2584 if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2586 /* Invalid byte sequence. */
2587 goto invalid_sequence;
2589 cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2590 if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2591 /* Invalid byte sequence. */
2592 goto invalid_sequence;
2594 wc = combine_surrogate_pair(wc, wc2);
2596 } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2597 /* Invalid byte sequence. */
2598 goto invalid_sequence;
2603 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2610 * Convert a Unicode code point to a single UTF-8 sequence.
2612 * NOTE:This function does not check if the Unicode is leagal or not.
2613 * Please you definitely check it before calling this.
2616 unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2620 /* Translate code point to UTF8 */
2625 } else if (uc <= 0x7ff) {
2628 *p++ = 0xc0 | ((uc >> 6) & 0x1f);
2629 *p++ = 0x80 | (uc & 0x3f);
2630 } else if (uc <= 0xffff) {
2633 *p++ = 0xe0 | ((uc >> 12) & 0x0f);
2634 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2635 *p++ = 0x80 | (uc & 0x3f);
2636 } else if (uc <= UNICODE_MAX) {
2639 *p++ = 0xf0 | ((uc >> 18) & 0x07);
2640 *p++ = 0x80 | ((uc >> 12) & 0x3f);
2641 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2642 *p++ = 0x80 | (uc & 0x3f);
2645 * Undescribed code point should be U+FFFD
2646 * (replacement character).
2648 if (remaining < UTF8_R_CHAR_SIZE)
2651 p += UTF8_R_CHAR_SIZE;
2657 utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2659 return (utf16_to_unicode(pwc, s, n, 1));
2663 utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2665 return (utf16_to_unicode(pwc, s, n, 0));
2669 utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2671 const char *utf16 = s;
2677 /* set the Replacement Character instead. */
2678 *pwc = UNICODE_R_CHAR;
2683 uc = archive_be16dec(utf16);
2685 uc = archive_le16dec(utf16);
2688 /* If this is a surrogate pair, assemble the full code point.*/
2689 if (IS_HIGH_SURROGATE_LA(uc)) {
2694 uc2 = archive_be16dec(utf16);
2696 uc2 = archive_le16dec(utf16);
2699 if (IS_LOW_SURROGATE_LA(uc2)) {
2700 uc = combine_surrogate_pair(uc, uc2);
2703 /* Undescribed code point should be U+FFFD
2704 * (replacement character). */
2705 *pwc = UNICODE_R_CHAR;
2711 * Surrogate pair values(0xd800 through 0xdfff) are only
2712 * used by UTF-16, so, after above culculation, the code
2713 * must not be surrogate values, and Unicode has no codes
2714 * larger than 0x10ffff. Thus, those are not leagal Unicode
2717 if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2718 /* Undescribed code point should be U+FFFD
2719 * (replacement character). */
2720 *pwc = UNICODE_R_CHAR;
2721 return (((int)(utf16 - s)) * -1);
2724 return ((int)(utf16 - s));
2728 unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2733 /* We have a code point that won't fit into a
2734 * wchar_t; convert it to a surrogate pair. */
2738 archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2739 archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2744 archive_be16enc(utf16, uc);
2750 unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2755 /* We have a code point that won't fit into a
2756 * wchar_t; convert it to a surrogate pair. */
2760 archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2761 archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2766 archive_le16enc(utf16, uc);
2772 * Copy UTF-8 string in checking surrogate pair.
2773 * If any surrogate pair are found, it would be canonicalized.
2776 strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p, size_t len,
2777 struct archive_string_conv *sc)
2783 (void)sc; /* UNUSED */
2785 if (archive_string_ensure(as, as->length + len + 1) == NULL)
2788 s = (const char *)_p;
2789 p = as->s + as->length;
2790 endp = as->s + as->buffer_length -1;
2797 * Forward byte sequence until a conversion of that is needed.
2799 while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
2804 if (p + (s - ss) > endp) {
2805 as->length = p - as->s;
2806 if (archive_string_ensure(as,
2807 as->buffer_length + len + 1) == NULL)
2809 p = as->s + as->length;
2810 endp = as->s + as->buffer_length -1;
2813 memcpy(p, ss, s - ss);
2818 * If n is negative, current byte sequence needs a replacement.
2821 if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2822 /* Current byte sequence may be CESU-8. */
2823 n = cesu8_to_unicode(&uc, s, len);
2827 n *= -1;/* Use a replaced unicode character. */
2830 /* Rebuild UTF-8 byte sequence. */
2831 while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
2832 as->length = p - as->s;
2833 if (archive_string_ensure(as,
2834 as->buffer_length + len + 1) == NULL)
2836 p = as->s + as->length;
2837 endp = as->s + as->buffer_length -1;
2844 as->length = p - as->s;
2845 as->s[as->length] = '\0';
2850 archive_string_append_unicode(struct archive_string *as, const void *_p,
2851 size_t len, struct archive_string_conv *sc)
2857 int n, ret = 0, ts, tm;
2858 int (*parse)(uint32_t *, const char *, size_t);
2859 size_t (*unparse)(char *, size_t, uint32_t);
2861 if (sc->flag & SCONV_TO_UTF16BE) {
2862 unparse = unicode_to_utf16be;
2864 } else if (sc->flag & SCONV_TO_UTF16LE) {
2865 unparse = unicode_to_utf16le;
2867 } else if (sc->flag & SCONV_TO_UTF8) {
2868 unparse = unicode_to_utf8;
2872 * This case is going to be converted to another
2873 * character-set through iconv.
2875 if (sc->flag & SCONV_FROM_UTF16BE) {
2876 unparse = unicode_to_utf16be;
2878 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2879 unparse = unicode_to_utf16le;
2882 unparse = unicode_to_utf8;
2887 if (sc->flag & SCONV_FROM_UTF16BE) {
2888 parse = utf16be_to_unicode;
2890 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2891 parse = utf16le_to_unicode;
2894 parse = cesu8_to_unicode;
2898 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2901 s = (const char *)_p;
2902 p = as->s + as->length;
2903 endp = as->s + as->buffer_length - ts;
2904 while ((n = parse(&uc, s, len)) != 0) {
2906 /* Use a replaced unicode character. */
2912 while ((w = unparse(p, endp - p, uc)) == 0) {
2913 /* There is not enough output buffer so
2914 * we have to expand it. */
2915 as->length = p - as->s;
2916 if (archive_string_ensure(as,
2917 as->buffer_length + len * tm + ts) == NULL)
2919 p = as->s + as->length;
2920 endp = as->s + as->buffer_length - ts;
2924 as->length = p - as->s;
2925 as->s[as->length] = '\0';
2927 as->s[as->length+1] = '\0';
2932 * Following Constants for Hangul compositions this information comes from
2933 * Unicode Standard Annex #15 http://unicode.org/reports/tr15/
2935 #define HC_SBASE 0xAC00
2936 #define HC_LBASE 0x1100
2937 #define HC_VBASE 0x1161
2938 #define HC_TBASE 0x11A7
2939 #define HC_LCOUNT 19
2940 #define HC_VCOUNT 21
2941 #define HC_TCOUNT 28
2942 #define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT)
2943 #define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT)
2946 get_nfc(uint32_t uc, uint32_t uc2)
2951 b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2953 int m = (t + b) / 2;
2954 if (u_composition_table[m].cp1 < uc)
2956 else if (u_composition_table[m].cp1 > uc)
2958 else if (u_composition_table[m].cp2 < uc2)
2960 else if (u_composition_table[m].cp2 > uc2)
2963 return (u_composition_table[m].nfc);
2968 #define FDC_MAX 10 /* The maximum number of Following Decomposable
2972 * Update first code point.
2974 #define UPDATE_UC(new_uc) do { \
2980 * Replace first code point with second code point.
2982 #define REPLACE_UC_WITH_UC2() do { \
2988 #define EXPAND_BUFFER() do { \
2989 as->length = p - as->s; \
2990 if (archive_string_ensure(as, \
2991 as->buffer_length + len * tm + ts) == NULL)\
2993 p = as->s + as->length; \
2994 endp = as->s + as->buffer_length - ts; \
2997 #define UNPARSE(p, endp, uc) do { \
2998 while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
3005 * Write first code point.
3006 * If the code point has not be changed from its original code,
3007 * this just copies it from its original buffer pointer.
3008 * If not, this converts it to UTF-8 byte sequence and copies it.
3010 #define WRITE_UC() do { \
3017 /* FALL THROUGH */ \
3020 /* FALL THROUGH */ \
3023 /* FALL THROUGH */ \
3030 UNPARSE(p, endp, uc); \
3035 * Collect following decomposable code points.
3037 #define COLLECT_CPS(start) do { \
3039 for (_i = start; _i < FDC_MAX ; _i++) { \
3040 nx = parse(&ucx[_i], s, len); \
3043 cx = CCC(ucx[_i]); \
3044 if (cl >= cx && cl != 228 && cx != 228)\
3051 if (_i >= FDC_MAX) { \
3053 ucx_size = FDC_MAX; \
3059 * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
3061 * TODO: Convert composition exclusions,which are never converted
3062 * from NFC,NFD,NFKC and NFKD, to Form C.
3065 archive_string_normalize_C(struct archive_string *as, const void *_p,
3066 size_t len, struct archive_string_conv *sc)
3068 const char *s = (const char *)_p;
3072 int always_replace, n, n2, ret = 0, spair, ts, tm;
3073 int (*parse)(uint32_t *, const char *, size_t);
3074 size_t (*unparse)(char *, size_t, uint32_t);
3077 ts = 1;/* text size. */
3078 if (sc->flag & SCONV_TO_UTF16BE) {
3079 unparse = unicode_to_utf16be;
3081 if (sc->flag & SCONV_FROM_UTF16BE)
3083 } else if (sc->flag & SCONV_TO_UTF16LE) {
3084 unparse = unicode_to_utf16le;
3086 if (sc->flag & SCONV_FROM_UTF16LE)
3088 } else if (sc->flag & SCONV_TO_UTF8) {
3089 unparse = unicode_to_utf8;
3090 if (sc->flag & SCONV_FROM_UTF8)
3094 * This case is going to be converted to another
3095 * character-set through iconv.
3098 if (sc->flag & SCONV_FROM_UTF16BE) {
3099 unparse = unicode_to_utf16be;
3101 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3102 unparse = unicode_to_utf16le;
3105 unparse = unicode_to_utf8;
3109 if (sc->flag & SCONV_FROM_UTF16BE) {
3110 parse = utf16be_to_unicode;
3112 spair = 4;/* surrogate pair size in UTF-16. */
3113 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3114 parse = utf16le_to_unicode;
3116 spair = 4;/* surrogate pair size in UTF-16. */
3118 parse = cesu8_to_unicode;
3120 spair = 6;/* surrogate pair size in UTF-8. */
3123 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3126 p = as->s + as->length;
3127 endp = as->s + as->buffer_length - ts;
3128 while ((n = parse(&uc, s, len)) != 0) {
3129 const char *ucptr, *uc2ptr;
3132 /* Use a replaced unicode character. */
3133 UNPARSE(p, endp, uc);
3138 } else if (n == spair || always_replace)
3139 /* uc is converted from a surrogate pair.
3140 * this should be treated as a changed code. */
3147 /* Read second code point. */
3148 while ((n2 = parse(&uc2, s, len)) > 0) {
3149 uint32_t ucx[FDC_MAX];
3151 int cl, cx, i, nx, ucx_size;
3155 if (n2 == spair || always_replace)
3156 /* uc2 is converted from a surrogate pair.
3157 * this should be treated as a changed code. */
3165 * If current second code point is out of decomposable
3166 * code points, finding compositions is unneeded.
3168 if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3170 REPLACE_UC_WITH_UC2();
3175 * Try to combine current code points.
3178 * We have to combine Hangul characters according to
3179 * http://uniicode.org/reports/tr15/#Hangul
3181 if (0 <= (LIndex = uc - HC_LBASE) &&
3182 LIndex < HC_LCOUNT) {
3184 * Hangul Composition.
3185 * 1. Two current code points are L and V.
3187 int VIndex = uc2 - HC_VBASE;
3188 if (0 <= VIndex && VIndex < HC_VCOUNT) {
3189 /* Make syllable of form LV. */
3190 UPDATE_UC(HC_SBASE +
3191 (LIndex * HC_VCOUNT + VIndex) *
3195 REPLACE_UC_WITH_UC2();
3198 } else if (0 <= (SIndex = uc - HC_SBASE) &&
3199 SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3201 * Hangul Composition.
3202 * 2. Two current code points are LV and T.
3204 int TIndex = uc2 - HC_TBASE;
3205 if (0 < TIndex && TIndex < HC_TCOUNT) {
3206 /* Make syllable of form LVT. */
3207 UPDATE_UC(uc + TIndex);
3210 REPLACE_UC_WITH_UC2();
3213 } else if ((nfc = get_nfc(uc, uc2)) != 0) {
3214 /* A composition to current code points
3218 } else if ((cl = CCC(uc2)) == 0) {
3219 /* Clearly 'uc2' the second code point is not
3220 * a decomposable code. */
3222 REPLACE_UC_WITH_UC2();
3227 * Collect following decomposable code points.
3235 * Find a composed code in the collected code points.
3238 while (i < ucx_size) {
3241 if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3247 * nfc is composed of uc and ucx[i].
3252 * Remove ucx[i] by shifting
3253 * follwoing code points.
3255 for (j = i; j+1 < ucx_size; j++) {
3262 * Collect following code points blocked
3263 * by ucx[i] the removed code point.
3265 if (ucx_size > 0 && i == ucx_size &&
3266 nx > 0 && cx == cl) {
3267 cl = ccx[ucx_size-1];
3268 COLLECT_CPS(ucx_size);
3271 * Restart finding a composed code with
3272 * the updated uc from the top of the
3273 * collected code points.
3279 * Apparently the current code points are not
3280 * decomposed characters or already composed.
3283 for (i = 0; i < ucx_size; i++)
3284 UNPARSE(p, endp, ucx[i]);
3287 * Flush out remaining canonical combining characters.
3289 if (nx > 0 && cx == cl && len > 0) {
3290 while ((nx = parse(&ucx[0], s, len))
3298 UNPARSE(p, endp, ucx[0]);
3305 /* Use a replaced unicode character. */
3306 UNPARSE(p, endp, uc2);
3311 } else if (n2 == 0) {
3316 as->length = p - as->s;
3317 as->s[as->length] = '\0';
3319 as->s[as->length+1] = '\0';
3323 #if defined(__APPLE__)
3326 * Normalize UTF-8 characters to Form D and copy the result.
3329 archive_string_normalize_D(struct archive_string *as, const void *_p,
3330 size_t len, struct archive_string_conv *sc)
3335 ByteCount inCount, outCount;
3336 ByteCount inAvail, outAvail;
3338 int ret, saved_flag;
3341 * Convert the current string to UTF-16LE for normalization.
3342 * The character-set of the current string must be UTF-16BE or
3345 archive_string_empty(&(sc->utf16nfc));
3346 saved_flag = sc->flag;/* save a flag. */
3347 sc->flag &= ~(SCONV_TO_UTF16BE | SCONV_TO_UTF8);
3348 sc->flag |= SCONV_TO_UTF16LE;
3349 ret = archive_string_append_unicode(&(sc->utf16nfc), _p, len, sc);
3350 sc->flag = saved_flag;/* restore the saved flag */
3351 if (archive_strlen(&(sc->utf16nfc)) == 0) {
3352 if (archive_string_ensure(as, as->length + 1) == NULL)
3358 * Normalize an NFC string to be an NFD(HFS Plus version).
3360 newsize = sc->utf16nfc.length + 2;
3361 if (archive_string_ensure(&(sc->utf16nfd), newsize) == NULL)
3364 inp = (UniChar *)sc->utf16nfc.s;
3365 inAvail = archive_strlen(&(sc->utf16nfc));
3366 sc->utf16nfd.length = 0;
3367 outp = sc->utf16nfd.s;
3368 outAvail = sc->utf16nfd.buffer_length -2;
3371 /* Reinitialize all state information. */
3372 if (ResetUnicodeToTextInfo(sc->uniInfo) != noErr)
3373 goto return_no_changed_data;
3375 inCount = outCount = 0;
3376 err = ConvertFromUnicodeToText(sc->uniInfo,
3378 kUnicodeDefaultDirectionMask, 0, NULL, NULL, NULL,
3379 outAvail, &inCount, &outCount, outp);
3382 sc->utf16nfd.length = outCount;
3383 sc->utf16nfd.s[sc->utf16nfd.length] = 0;
3384 sc->utf16nfd.s[sc->utf16nfd.length+1] = 0;
3385 } else if (err == kTECOutputBufferFullStatus) {
3386 newsize = inAvail - inCount;
3387 if (newsize > inAvail)
3389 newsize += sc->utf16nfd.buffer_length + 2;
3390 if (archive_string_ensure(&(sc->utf16nfd), newsize)
3393 outp = sc->utf16nfd.s;
3394 outAvail = sc->utf16nfd.buffer_length -2;
3396 goto return_no_changed_data;
3397 } while (err == kTECOutputBufferFullStatus);
3400 * If there is a next-step conversion, we should convert
3401 * a UTF-16LE(NFD) string back to the original Unicode type.
3403 saved_flag = sc->flag;/* save a flag. */
3405 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE | SCONV_TO_UTF8))) {
3407 * This case is going to be converted to another
3408 * character-set through iconv.
3410 if (sc->flag & SCONV_FROM_UTF16BE)
3411 sc->flag |= SCONV_TO_UTF16BE;
3412 else if (sc->flag & SCONV_FROM_UTF16LE)
3413 sc->flag |= SCONV_TO_UTF16LE;
3415 sc->flag |= SCONV_TO_UTF8;
3417 sc->flag &= ~(SCONV_FROM_UTF16BE | SCONV_FROM_UTF8);
3418 sc->flag |= SCONV_FROM_UTF16LE;
3419 if (archive_string_append_unicode(as, sc->utf16nfd.s,
3420 sc->utf16nfd.length, sc) != 0)
3422 sc->flag = saved_flag;/* restore the saved flag */
3425 return_no_changed_data:
3427 * Something conversion error happend, so we return a no normalized
3428 * string with an error.
3430 (void)archive_string_append_unicode(as, _p, len, sc);
3434 #endif /* __APPLE__ */
3437 * libarchive 2.x made incorrect UTF-8 strings in the wrong assumuption
3438 * that WCS is Unicode. it is true for servel platforms but some are false.
3439 * And then people who did not use UTF-8 locale on the non Unicode WCS
3440 * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3441 * now cannot get right filename from libarchive 3.x and later since we
3442 * fixed the wrong assumption and it is incompatible to older its versions.
3443 * So we provide special option, "compat-2x.x", for resolving it.
3444 * That option enable the string conversion of libarchive 2.x.
3446 * Translates the wrong UTF-8 string made by libarchive 2.x into current
3447 * locale character set and appends to the archive_string.
3448 * Note: returns -1 if conversion fails.
3451 strncat_from_utf8_libarchive2(struct archive_string *as,
3452 const void *_p, size_t len, struct archive_string_conv *sc)
3460 mbstate_t shift_state;
3462 memset(&shift_state, 0, sizeof(shift_state));
3464 /* Clear the shift state before starting. */
3465 wctomb(NULL, L'\0');
3467 (void)sc; /* UNUSED */
3469 * Allocate buffer for MBS.
3470 * We need this allocation here since it is possible that
3471 * as->s is still NULL.
3473 if (archive_string_ensure(as, as->length + len + 1) == NULL)
3476 s = (const char *)_p;
3477 p = as->s + as->length;
3478 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3479 while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3483 as->length = p - as->s;
3484 /* Re-allocate buffer for MBS. */
3485 if (archive_string_ensure(as,
3486 as->length + len * 2 + 1) == NULL)
3488 p = as->s + as->length;
3489 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3493 * As libarchie 2.x, translates the UTF-8 characters into
3494 * wide-characters in the assumption that WCS is Unicode.
3500 wc = (wchar_t)unicode;
3505 * Translates the wide-character into the current locale MBS.
3508 n = wcrtomb(p, wc, &shift_state);
3516 as->length = p - as->s;
3517 as->s[as->length] = '\0';
3523 * Conversion functions between current locale dependent MBS and UTF-16BE.
3524 * strncat_from_utf16be() : UTF-16BE --> MBS
3525 * strncat_to_utf16be() : MBS --> UTF16BE
3528 #if defined(_WIN32) && !defined(__CYGWIN__)
3531 * Convert a UTF-16BE/LE string to current locale and copy the result.
3532 * Return -1 if conversion failes.
3535 win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3536 struct archive_string_conv *sc, int be)
3538 struct archive_string tmp;
3547 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3550 mbs = as->s + as->length;
3551 mbs_size = as->buffer_length - as->length -1;
3553 if (sc->to_cp == CP_C_LOCALE) {
3555 * "C" locale special process.
3559 for (b = 0; b < bytes; b += 2) {
3562 val = archive_be16dec(u16+b);
3564 val = archive_le16dec(u16+b);
3569 *mbs++ = (char)(val&0xff);
3573 as->s[as->length] = '\0';
3577 archive_string_init(&tmp);
3579 if (is_big_endian()) {
3582 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3584 memcpy(tmp.s, _p, bytes);
3585 for (b = 0; b < bytes; b += 2) {
3586 uint16_t val = archive_be16dec(tmp.s+b);
3587 archive_le16enc(tmp.s+b, val);
3592 if (!is_big_endian()) {
3595 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3597 memcpy(tmp.s, _p, bytes);
3598 for (b = 0; b < bytes; b += 2) {
3599 uint16_t val = archive_le16dec(tmp.s+b);
3600 archive_be16enc(tmp.s+b, val);
3608 ll = WideCharToMultiByte(sc->to_cp, 0,
3609 (LPCWSTR)u16, bytes>>1, mbs, mbs_size,
3612 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
3613 /* Need more buffer for MBS. */
3614 ll = WideCharToMultiByte(sc->to_cp, 0,
3615 (LPCWSTR)u16, bytes, NULL, 0, NULL, NULL);
3616 if (archive_string_ensure(as, ll +1) == NULL)
3618 mbs = as->s + as->length;
3619 mbs_size = as->buffer_length - as->length -1;
3623 archive_string_free(&tmp);
3625 as->s[as->length] = '\0';
3626 if (ll == 0 || defchar)
3632 win_strncat_from_utf16be(struct archive_string *as, const void *_p, size_t bytes,
3633 struct archive_string_conv *sc)
3635 return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3639 win_strncat_from_utf16le(struct archive_string *as, const void *_p, size_t bytes,
3640 struct archive_string_conv *sc)
3642 return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3650 return (archive_be16dec(&d) == 1);
3654 * Convert a current locale string to UTF-16BE/LE and copy the result.
3655 * Return -1 if conversion failes.
3658 win_strncat_to_utf16(struct archive_string *as16, const void *_p, size_t length,
3659 struct archive_string_conv *sc, int bigendian)
3661 const char *s = (const char *)_p;
3663 size_t count, avail;
3665 if (archive_string_ensure(as16,
3666 as16->length + (length + 1) * 2) == NULL)
3669 u16 = as16->s + as16->length;
3670 avail = as16->buffer_length - 2;
3671 if (sc->from_cp == CP_C_LOCALE) {
3673 * "C" locale special process.
3676 while (count < length && *s) {
3678 archive_be16enc(u16, *s);
3680 archive_le16enc(u16, *s);
3685 as16->length += count << 1;
3686 as16->s[as16->length] = 0;
3687 as16->s[as16->length+1] = 0;
3691 count = MultiByteToWideChar(sc->from_cp,
3692 MB_PRECOMPOSED, s, length, (LPWSTR)u16, (int)avail>>1);
3694 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
3695 /* Need more buffer for UTF-16 string */
3696 count = MultiByteToWideChar(sc->from_cp,
3697 MB_PRECOMPOSED, s, length, NULL, 0);
3698 if (archive_string_ensure(as16, (count +1) * 2)
3701 u16 = as16->s + as16->length;
3702 avail = as16->buffer_length - 2;
3706 as16->length += count * 2;
3707 as16->s[as16->length] = 0;
3708 as16->s[as16->length+1] = 0;
3712 if (is_big_endian()) {
3715 uint16_t v = archive_be16dec(u16);
3716 archive_le16enc(u16, v);
3724 uint16_t v = archive_le16dec(u16);
3725 archive_be16enc(u16, v);
3735 win_strncat_to_utf16be(struct archive_string *as16, const void *_p, size_t length,
3736 struct archive_string_conv *sc)
3738 return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3742 win_strncat_to_utf16le(struct archive_string *as16, const void *_p, size_t length,
3743 struct archive_string_conv *sc)
3745 return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3748 #endif /* _WIN32 && !__CYGWIN__ */
3751 * Do the best effort for conversions.
3752 * We cannot handle UTF-16BE character-set without such iconv,
3753 * but there is a chance if a string consists just ASCII code or
3754 * a current locale is UTF-8.
3758 * Convert a UTF-16BE string to current locale and copy the result.
3759 * Return -1 if conversion failes.
3762 best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3763 size_t bytes, struct archive_string_conv *sc, int be)
3765 const char *utf16 = (const char *)_p;
3770 (void)sc; /* UNUSED */
3772 * Other case, we should do the best effort.
3773 * If all character are ASCII(<0x7f), we can convert it.
3774 * if not , we set a alternative character and return -1.
3777 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3779 mbs = as->s + as->length;
3781 while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3790 /* We cannot handle it. */
3796 as->length = mbs - as->s;
3797 as->s[as->length] = '\0';
3802 best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3803 size_t bytes, struct archive_string_conv *sc)
3805 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3809 best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3810 size_t bytes, struct archive_string_conv *sc)
3812 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3816 * Convert a current locale string to UTF-16BE/LE and copy the result.
3817 * Return -1 if conversion failes.
3820 best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3821 size_t length, struct archive_string_conv *sc, int bigendian)
3823 const char *s = (const char *)_p;
3828 (void)sc; /* UNUSED */
3830 * Other case, we should do the best effort.
3831 * If all character are ASCII(<0x7f), we can convert it.
3832 * if not , we set a alternative character and return -1.
3837 if (archive_string_ensure(as16,
3838 as16->length + (length + 1) * 2) == NULL)
3841 utf16 = as16->s + as16->length;
3842 while (remaining--) {
3845 /* We cannot handle it. */
3850 archive_be16enc(utf16, c);
3852 archive_le16enc(utf16, c);
3855 as16->length = utf16 - as16->s;
3856 as16->s[as16->length] = 0;
3857 as16->s[as16->length+1] = 0;
3862 best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3863 size_t length, struct archive_string_conv *sc)
3865 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3869 best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3870 size_t length, struct archive_string_conv *sc)
3872 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3877 * Multistring operations.
3881 archive_mstring_clean(struct archive_mstring *aes)
3883 archive_wstring_free(&(aes->aes_wcs));
3884 archive_string_free(&(aes->aes_mbs));
3885 archive_string_free(&(aes->aes_utf8));
3886 archive_string_free(&(aes->aes_mbs_in_locale));
3891 archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3893 dest->aes_set = src->aes_set;
3894 archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3895 archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3896 archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3900 archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3903 struct archive_string_conv *sc;
3906 /* If we already have a UTF8 form, return that immediately. */
3907 if (aes->aes_set & AES_SET_UTF8) {
3908 *p = aes->aes_utf8.s;
3913 if (aes->aes_set & AES_SET_MBS) {
3914 sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3916 return (-1);/* Couldn't allocate memory for sc. */
3917 r = archive_strncpy_in_locale(&(aes->aes_mbs), aes->aes_mbs.s,
3918 aes->aes_mbs.length, sc);
3920 free_sconv_object(sc);
3922 aes->aes_set |= AES_SET_UTF8;
3923 *p = aes->aes_utf8.s;
3924 return (0);/* success. */
3926 return (-1);/* failure. */
3928 return (0);/* success. */
3932 archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3937 (void)a; /* UNUSED */
3938 /* If we already have an MBS form, return that immediately. */
3939 if (aes->aes_set & AES_SET_MBS) {
3940 *p = aes->aes_mbs.s;
3945 /* If there's a WCS form, try converting with the native locale. */
3946 if (aes->aes_set & AES_SET_WCS) {
3947 archive_string_empty(&(aes->aes_mbs));
3948 r = archive_string_append_from_wcs(&(aes->aes_mbs),
3949 aes->aes_wcs.s, aes->aes_wcs.length);
3950 *p = aes->aes_mbs.s;
3952 aes->aes_set |= AES_SET_MBS;
3959 * Only a UTF-8 form cannot avail because its conversion already
3960 * failed at archive_mstring_update_utf8().
3966 archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
3971 (void)a;/* UNUSED */
3972 /* Return WCS form if we already have it. */
3973 if (aes->aes_set & AES_SET_WCS) {
3974 *wp = aes->aes_wcs.s;
3979 /* Try converting MBS to WCS using native locale. */
3980 if (aes->aes_set & AES_SET_MBS) {
3981 archive_wstring_empty(&(aes->aes_wcs));
3982 r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
3983 aes->aes_mbs.s, aes->aes_mbs.length);
3985 aes->aes_set |= AES_SET_WCS;
3986 *wp = aes->aes_wcs.s;
3988 ret = -1;/* failure. */
3994 archive_mstring_get_mbs_l(struct archive_mstring *aes,
3995 const char **p, size_t *length, struct archive_string_conv *sc)
3999 #if defined(_WIN32) && !defined(__CYGWIN__)
4001 * Internationalization programing on Windows must use Wide
4002 * characters because Windows platform cannot make locale UTF-8.
4004 if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
4005 archive_string_empty(&(aes->aes_mbs_in_locale));
4006 r = archive_string_append_from_wcs_in_codepage(
4007 &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
4008 aes->aes_wcs.length, sc);
4010 *p = aes->aes_mbs_in_locale.s;
4012 *length = aes->aes_mbs_in_locale.length;
4014 } else if (errno == ENOMEM)
4021 /* If there is not an MBS form but is a WCS form, try converting
4022 * with the native locale to be used for translating it to specified
4024 if ((aes->aes_set & AES_SET_MBS) == 0 &&
4025 (aes->aes_set & AES_SET_WCS) != 0) {
4026 archive_string_empty(&(aes->aes_mbs));
4027 r = archive_string_append_from_wcs(&(aes->aes_mbs),
4028 aes->aes_wcs.s, aes->aes_wcs.length);
4030 aes->aes_set |= AES_SET_MBS;
4031 else if (errno == ENOMEM)
4036 /* If we already have an MBS form, use it to be translated to
4037 * specified character-set. */
4038 if (aes->aes_set & AES_SET_MBS) {
4040 /* Conversion is unneeded. */
4041 *p = aes->aes_mbs.s;
4043 *length = aes->aes_mbs.length;
4046 ret = archive_strncpy_in_locale(&(aes->aes_mbs_in_locale),
4047 aes->aes_mbs.s, aes->aes_mbs.length, sc);
4048 *p = aes->aes_mbs_in_locale.s;
4050 *length = aes->aes_mbs_in_locale.length;
4060 archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4066 return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4070 archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4077 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4078 archive_strncpy(&(aes->aes_mbs), mbs, len);
4079 archive_string_empty(&(aes->aes_utf8));
4080 archive_wstring_empty(&(aes->aes_wcs));
4085 archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4087 return archive_mstring_copy_wcs_len(aes, wcs, wcs == NULL ? 0 : wcslen(wcs));
4091 archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4097 aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4098 archive_string_empty(&(aes->aes_mbs));
4099 archive_string_empty(&(aes->aes_utf8));
4100 archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4105 archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4106 const char *mbs, size_t len, struct archive_string_conv *sc)
4114 archive_string_empty(&(aes->aes_mbs));
4115 archive_wstring_empty(&(aes->aes_wcs));
4116 archive_string_empty(&(aes->aes_utf8));
4117 #if defined(_WIN32) && !defined(__CYGWIN__)
4119 * Internationalization programing on Windows must use Wide
4120 * characters because Windows platform cannot make locale UTF-8.
4123 if (archive_string_append(&(aes->aes_mbs),
4124 mbs, mbsnbytes(mbs, len)) == NULL) {
4128 aes->aes_set = AES_SET_MBS;
4131 #if defined(HAVE_ICONV)
4132 } else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4134 * This case happens only when MultiByteToWideChar() cannot
4135 * handle sc->from_cp, and we have to iconv in order to
4136 * translate character-set to wchar_t,UTF-16.
4138 iconv_t cd = sc->cd;
4143 * Translate multi-bytes from some character-set to UTF-8.
4146 r = archive_strncpy_in_locale(&(aes->aes_utf8), mbs, len, sc);
4152 aes->aes_set = AES_SET_UTF8;
4155 * Append the UTF-8 string into wstring.
4158 sc->flag &= ~(SCONV_NORMALIZATION_C
4159 | SCONV_TO_UTF16| SCONV_FROM_UTF16);
4160 from_cp = sc->from_cp;
4161 sc->from_cp = CP_UTF8;
4162 r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4163 aes->aes_utf8.s, aes->aes_utf8.length, sc);
4165 sc->from_cp = from_cp;
4167 aes->aes_set |= AES_SET_WCS;
4170 r = archive_wstring_append_from_mbs_in_codepage(
4171 &(aes->aes_wcs), mbs, len, sc);
4173 aes->aes_set = AES_SET_WCS;
4178 r = archive_strncpy_in_locale(&(aes->aes_mbs), mbs, len, sc);
4180 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4188 * The 'update' form tries to proactively update all forms of
4189 * this string (WCS and MBS) and returns an error if any of
4190 * them fail. This is used by the 'pax' handler, for instance,
4191 * to detect and report character-conversion failures early while
4192 * still allowing clients to get potentially useful values from
4193 * the more tolerant lazy conversions. (get_mbs and get_wcs will
4194 * strive to give the user something useful, so you can get hopefully
4195 * usable values even if some of the character conversions are failing.)
4198 archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4201 struct archive_string_conv *sc;
4206 return (0); /* Succeeded in clearing everything. */
4209 /* Save the UTF8 string. */
4210 archive_strcpy(&(aes->aes_utf8), utf8);
4212 /* Empty the mbs and wcs strings. */
4213 archive_string_empty(&(aes->aes_mbs));
4214 archive_wstring_empty(&(aes->aes_wcs));
4216 aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */
4218 /* Try converting UTF-8 to MBS, return false on failure. */
4219 sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4221 return (-1);/* Couldn't allocate memory for sc. */
4222 r = archive_strcpy_in_locale(&(aes->aes_mbs), utf8, sc);
4224 free_sconv_object(sc);
4227 aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4229 /* Try converting MBS to WCS, return false on failure. */
4230 if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4231 aes->aes_mbs.length))
4233 aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4235 /* All conversions succeeded. */