2 * Copyright (c) 2003-2011 Tim Kientzle
3 * Copyright (c) 2011-2012 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$");
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__)
65 #include "archive_endian.h"
66 #include "archive_private.h"
67 #include "archive_string.h"
68 #include "archive_string_composition.h"
70 #if !defined(HAVE_WMEMCPY) && !defined(wmemcpy)
71 #define wmemcpy(a,b,i) (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t))
74 #if !defined(HAVE_WMEMMOVE) && !defined(wmemmove)
75 #define wmemmove(a,b,i) (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t))
78 struct archive_string_conv {
79 struct archive_string_conv *next;
84 /* Set 1 if from_charset and to_charset are the same. */
87 #define SCONV_TO_CHARSET 1 /* MBS is being converted to specified
89 #define SCONV_FROM_CHARSET (1<<1) /* MBS is being converted from
90 * specified charset. */
91 #define SCONV_BEST_EFFORT (1<<2) /* Copy at least ASCII code. */
92 #define SCONV_WIN_CP (1<<3) /* Use Windows API for converting
94 #define SCONV_UTF8_LIBARCHIVE_2 (1<<4) /* Incorrect UTF-8 made by libarchive
95 * 2.x in the wrong assumption. */
96 #define SCONV_NORMALIZATION_C (1<<6) /* Need normalization to be Form C.
97 * Before UTF-8 characters are actually
99 #define SCONV_NORMALIZATION_D (1<<7) /* Need normalization to be Form D.
100 * Before UTF-8 characters are actually
102 * Currently this only for MAC OS X. */
103 #define SCONV_TO_UTF8 (1<<8) /* "to charset" side is UTF-8. */
104 #define SCONV_FROM_UTF8 (1<<9) /* "from charset" side is UTF-8. */
105 #define SCONV_TO_UTF16BE (1<<10) /* "to charset" side is UTF-16BE. */
106 #define SCONV_FROM_UTF16BE (1<<11) /* "from charset" side is UTF-16BE. */
107 #define SCONV_TO_UTF16LE (1<<12) /* "to charset" side is UTF-16LE. */
108 #define SCONV_FROM_UTF16LE (1<<13) /* "from charset" side is UTF-16LE. */
109 #define SCONV_TO_UTF16 (SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
110 #define SCONV_FROM_UTF16 (SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
114 iconv_t cd_w;/* Use at archive_mstring on
117 /* A temporary buffer for normalization. */
118 struct archive_string utftmp;
119 int (*converter[2])(struct archive_string *, const void *, size_t,
120 struct archive_string_conv *);
124 #define CP_C_LOCALE 0 /* "C" locale only for this file. */
125 #define CP_UTF16LE 1200
126 #define CP_UTF16BE 1201
128 #define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
129 #define IS_LOW_SURROGATE_LA(uc) ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
130 #define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
131 #define UNICODE_MAX 0x10FFFF
132 #define UNICODE_R_CHAR 0xFFFD /* Replacement character. */
133 /* Set U+FFFD(Replacement character) in UTF-8. */
134 static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd};
136 static struct archive_string_conv *find_sconv_object(struct archive *,
137 const char *, const char *);
138 static void add_sconv_object(struct archive *, struct archive_string_conv *);
139 static struct archive_string_conv *create_sconv_object(const char *,
140 const char *, unsigned, int);
141 static void free_sconv_object(struct archive_string_conv *);
142 static struct archive_string_conv *get_sconv_object(struct archive *,
143 const char *, const char *, int);
144 static unsigned make_codepage_from_charset(const char *);
145 static unsigned get_current_codepage(void);
146 static unsigned get_current_oemcp(void);
147 static size_t mbsnbytes(const void *, size_t);
148 static size_t utf16nbytes(const void *, size_t);
149 #if defined(_WIN32) && !defined(__CYGWIN__)
150 static int archive_wstring_append_from_mbs_in_codepage(
151 struct archive_wstring *, const char *, size_t,
152 struct archive_string_conv *);
153 static int archive_string_append_from_wcs_in_codepage(struct archive_string *,
154 const wchar_t *, size_t, struct archive_string_conv *);
155 static int is_big_endian(void);
156 static int strncat_in_codepage(struct archive_string *, const void *,
157 size_t, struct archive_string_conv *);
158 static int win_strncat_from_utf16be(struct archive_string *, const void *,
159 size_t, struct archive_string_conv *);
160 static int win_strncat_from_utf16le(struct archive_string *, const void *,
161 size_t, struct archive_string_conv *);
162 static int win_strncat_to_utf16be(struct archive_string *, const void *,
163 size_t, struct archive_string_conv *);
164 static int win_strncat_to_utf16le(struct archive_string *, const void *,
165 size_t, struct archive_string_conv *);
167 static int best_effort_strncat_from_utf16be(struct archive_string *,
168 const void *, size_t, struct archive_string_conv *);
169 static int best_effort_strncat_from_utf16le(struct archive_string *,
170 const void *, size_t, struct archive_string_conv *);
171 static int best_effort_strncat_to_utf16be(struct archive_string *,
172 const void *, size_t, struct archive_string_conv *);
173 static int best_effort_strncat_to_utf16le(struct archive_string *,
174 const void *, size_t, struct archive_string_conv *);
175 #if defined(HAVE_ICONV)
176 static int iconv_strncat_in_locale(struct archive_string *, const void *,
177 size_t, struct archive_string_conv *);
179 static int best_effort_strncat_in_locale(struct archive_string *,
180 const void *, size_t, struct archive_string_conv *);
181 static int _utf8_to_unicode(uint32_t *, const char *, size_t);
182 static int utf8_to_unicode(uint32_t *, const char *, size_t);
183 static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
184 static int cesu8_to_unicode(uint32_t *, const char *, size_t);
185 static size_t unicode_to_utf8(char *, size_t, uint32_t);
186 static int utf16_to_unicode(uint32_t *, const char *, size_t, int);
187 static size_t unicode_to_utf16be(char *, size_t, uint32_t);
188 static size_t unicode_to_utf16le(char *, size_t, uint32_t);
189 static int strncat_from_utf8_libarchive2(struct archive_string *,
190 const void *, size_t, struct archive_string_conv *);
191 static int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
192 size_t, struct archive_string_conv *);
193 static int archive_string_normalize_C(struct archive_string *, const void *,
194 size_t, struct archive_string_conv *);
195 static int archive_string_normalize_D(struct archive_string *, const void *,
196 size_t, struct archive_string_conv *);
197 static int archive_string_append_unicode(struct archive_string *,
198 const void *, size_t, struct archive_string_conv *);
200 static struct archive_string *
201 archive_string_append(struct archive_string *as, const char *p, size_t s)
203 if (archive_string_ensure(as, as->length + s + 1) == NULL)
206 memmove(as->s + as->length, p, s);
208 as->s[as->length] = 0;
212 static struct archive_wstring *
213 archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
215 if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
218 wmemmove(as->s + as->length, p, s);
220 as->s[as->length] = 0;
224 struct archive_string *
225 archive_array_append(struct archive_string *as, const char *p, size_t s)
227 return archive_string_append(as, p, s);
231 archive_string_concat(struct archive_string *dest, struct archive_string *src)
233 if (archive_string_append(dest, src->s, src->length) == NULL)
234 __archive_errx(1, "Out of memory");
238 archive_wstring_concat(struct archive_wstring *dest,
239 struct archive_wstring *src)
241 if (archive_wstring_append(dest, src->s, src->length) == NULL)
242 __archive_errx(1, "Out of memory");
246 archive_string_free(struct archive_string *as)
249 as->buffer_length = 0;
255 archive_wstring_free(struct archive_wstring *as)
258 as->buffer_length = 0;
263 struct archive_wstring *
264 archive_wstring_ensure(struct archive_wstring *as, size_t s)
266 return (struct archive_wstring *)
267 archive_string_ensure((struct archive_string *)as,
268 s * sizeof(wchar_t));
271 /* Returns NULL on any allocation failure. */
272 struct archive_string *
273 archive_string_ensure(struct archive_string *as, size_t s)
278 /* If buffer is already big enough, don't reallocate. */
279 if (as->s && (s <= as->buffer_length))
283 * Growing the buffer at least exponentially ensures that
284 * append operations are always linear in the number of
285 * characters appended. Using a smaller growth rate for
286 * larger buffers reduces memory waste somewhat at the cost of
287 * a larger constant factor.
289 if (as->buffer_length < 32)
290 /* Start with a minimum 32-character buffer. */
292 else if (as->buffer_length < 8192)
293 /* Buffers under 8k are doubled for speed. */
294 new_length = as->buffer_length + as->buffer_length;
296 /* Buffers 8k and over grow by at least 25% each time. */
297 new_length = as->buffer_length + as->buffer_length / 4;
298 /* Be safe: If size wraps, fail. */
299 if (new_length < as->buffer_length) {
300 /* On failure, wipe the string and return NULL. */
301 archive_string_free(as);
302 errno = ENOMEM;/* Make sure errno has ENOMEM. */
307 * The computation above is a lower limit to how much we'll
308 * grow the buffer. In any case, we have to grow it enough to
313 /* Now we can reallocate the buffer. */
314 p = (char *)realloc(as->s, new_length);
316 /* On failure, wipe the string and return NULL. */
317 archive_string_free(as);
318 errno = ENOMEM;/* Make sure errno has ENOMEM. */
323 as->buffer_length = new_length;
328 * TODO: See if there's a way to avoid scanning
329 * the source string twice. Then test to see
330 * if it actually helps (remember that we're almost
331 * always called with pretty short arguments, so
332 * such an optimization might not help).
334 struct archive_string *
335 archive_strncat(struct archive_string *as, const void *_p, size_t n)
340 p = (const char *)_p;
342 /* Like strlen(p), except won't examine positions beyond p[n]. */
345 while (s < n && *pp) {
349 if ((as = archive_string_append(as, p, s)) == NULL)
350 __archive_errx(1, "Out of memory");
354 struct archive_wstring *
355 archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
360 /* Like strlen(p), except won't examine positions beyond p[n]. */
363 while (s < n && *pp) {
367 if ((as = archive_wstring_append(as, p, s)) == NULL)
368 __archive_errx(1, "Out of memory");
372 struct archive_string *
373 archive_strcat(struct archive_string *as, const void *p)
375 /* strcat is just strncat without an effective limit.
376 * Assert that we'll never get called with a source
378 * TODO: Review all uses of strcat in the source
379 * and try to replace them with strncat().
381 return archive_strncat(as, p, 0x1000000);
384 struct archive_wstring *
385 archive_wstrcat(struct archive_wstring *as, const wchar_t *p)
388 return archive_wstrncat(as, p, 0x1000000);
391 struct archive_string *
392 archive_strappend_char(struct archive_string *as, char c)
394 if ((as = archive_string_append(as, &c, 1)) == NULL)
395 __archive_errx(1, "Out of memory");
399 struct archive_wstring *
400 archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
402 if ((as = archive_wstring_append(as, &c, 1)) == NULL)
403 __archive_errx(1, "Out of memory");
408 * Get the "current character set" name to use with iconv.
409 * On FreeBSD, the empty character set name "" chooses
410 * the correct character encoding for the current locale,
411 * so this isn't necessary.
412 * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
413 * on that system, we have to explicitly call nl_langinfo()
414 * to get the right name. Not sure about other platforms.
416 * NOTE: GNU libiconv does not recognize the character-set name
417 * which some platform nl_langinfo(CODESET) returns, so we should
418 * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
421 default_iconv_charset(const char *charset) {
422 if (charset != NULL && charset[0] != '\0')
424 #if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
425 /* locale_charset() is broken on Mac OS */
426 return locale_charset();
427 #elif HAVE_NL_LANGINFO
428 return nl_langinfo(CODESET);
434 #if defined(_WIN32) && !defined(__CYGWIN__)
437 * Convert MBS to WCS.
438 * Note: returns -1 if conversion fails.
441 archive_wstring_append_from_mbs(struct archive_wstring *dest,
442 const char *p, size_t len)
444 return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
448 archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
449 const char *s, size_t length, struct archive_string_conv *sc)
455 from_cp = sc->from_cp;
457 from_cp = get_current_codepage();
459 if (from_cp == CP_C_LOCALE) {
461 * "C" locale special process.
464 const unsigned char *mp;
466 if (NULL == archive_wstring_ensure(dest,
467 dest->length + length + 1))
470 ws = dest->s + dest->length;
471 mp = (const unsigned char *)s;
473 while (count < (int)length && *mp) {
474 *ws++ = (wchar_t)*mp++;
477 } else if (sc != NULL &&
478 (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
480 * Normalize UTF-8 and UTF-16BE and convert it directly
481 * to UTF-16 as wchar_t.
483 struct archive_string u16;
484 int saved_flag = sc->flag;/* save current flag. */
487 sc->flag |= SCONV_TO_UTF16BE;
489 sc->flag |= SCONV_TO_UTF16LE;
491 if (sc->flag & SCONV_FROM_UTF16) {
493 * UTF-16BE/LE NFD ===> UTF-16 NFC
494 * UTF-16BE/LE NFC ===> UTF-16 NFD
496 count = (int)utf16nbytes(s, length);
499 * UTF-8 NFD ===> UTF-16 NFC
500 * UTF-8 NFC ===> UTF-16 NFD
502 count = (int)mbsnbytes(s, length);
504 u16.s = (char *)dest->s;
505 u16.length = dest->length << 1;;
506 u16.buffer_length = dest->buffer_length;
507 if (sc->flag & SCONV_NORMALIZATION_C)
508 ret = archive_string_normalize_C(&u16, s, count, sc);
510 ret = archive_string_normalize_D(&u16, s, count, sc);
511 dest->s = (wchar_t *)u16.s;
512 dest->length = u16.length >> 1;
513 dest->buffer_length = u16.buffer_length;
514 sc->flag = saved_flag;/* restore the saved flag. */
516 } else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
517 count = (int)utf16nbytes(s, length);
518 count >>= 1; /* to be WCS length */
519 /* Allocate memory for WCS. */
520 if (NULL == archive_wstring_ensure(dest,
521 dest->length + count + 1))
523 wmemcpy(dest->s + dest->length, (const wchar_t *)s, count);
524 if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) {
525 uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
527 for (b = 0; b < count; b++) {
528 uint16_t val = archive_le16dec(u16+b);
529 archive_be16enc(u16+b, val);
531 } else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) {
532 uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
534 for (b = 0; b < count; b++) {
535 uint16_t val = archive_be16dec(u16+b);
536 archive_le16enc(u16+b, val);
545 else if (sc->flag & SCONV_FROM_CHARSET) {
546 /* Do not trust the length which comes from
547 * an archive file. */
548 length = mbsnbytes(s, length);
551 mbflag = MB_PRECOMPOSED;
553 buffsize = dest->length + length + 1;
555 /* Allocate memory for WCS. */
556 if (NULL == archive_wstring_ensure(dest, buffsize))
558 /* Convert MBS to WCS. */
559 count = MultiByteToWideChar(from_cp,
560 mbflag, s, (int)length, dest->s + dest->length,
561 (int)(dest->buffer_length >> 1) -1);
563 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
564 /* Expand the WCS buffer. */
565 buffsize = dest->buffer_length << 1;
568 if (count == 0 && length != 0)
573 dest->length += count;
574 dest->s[dest->length] = L'\0';
581 * Convert MBS to WCS.
582 * Note: returns -1 if conversion fails.
585 archive_wstring_append_from_mbs(struct archive_wstring *dest,
586 const char *p, size_t len)
591 * No single byte will be more than one wide character,
592 * so this length estimate will always be big enough.
594 size_t wcs_length = len;
595 size_t mbs_length = len;
599 mbstate_t shift_state;
601 memset(&shift_state, 0, sizeof(shift_state));
603 if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))
605 wcs = dest->s + dest->length;
607 * We cannot use mbsrtowcs/mbstowcs here because those may convert
608 * extra MBS when strlen(p) > len and one wide character consists of
611 while (*mbs && mbs_length > 0) {
612 if (wcs_length == 0) {
613 dest->length = wcs - dest->s;
614 dest->s[dest->length] = L'\0';
615 wcs_length = mbs_length;
616 if (NULL == archive_wstring_ensure(dest,
617 dest->length + wcs_length + 1))
619 wcs = dest->s + dest->length;
622 r = mbrtowc(wcs, mbs, wcs_length, &shift_state);
624 r = mbtowc(wcs, mbs, wcs_length);
626 if (r == (size_t)-1 || r == (size_t)-2) {
628 if (errno == EILSEQ) {
635 if (r == 0 || r > mbs_length)
642 dest->length = wcs - dest->s;
643 dest->s[dest->length] = L'\0';
649 #if defined(_WIN32) && !defined(__CYGWIN__)
653 * Note: returns -1 if conversion fails.
655 * Win32 builds use WideCharToMultiByte from the Windows API.
656 * (Maybe Cygwin should too? WideCharToMultiByte will know a
657 * lot more about local character encodings than the wcrtomb()
658 * wrapper is going to know.)
661 archive_string_append_from_wcs(struct archive_string *as,
662 const wchar_t *w, size_t len)
664 return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
668 archive_string_append_from_wcs_in_codepage(struct archive_string *as,
669 const wchar_t *ws, size_t len, struct archive_string_conv *sc)
671 BOOL defchar_used, *dp;
674 int wslen = (int)len;
679 to_cp = get_current_codepage();
681 if (to_cp == CP_C_LOCALE) {
683 * "C" locale special process.
685 const wchar_t *wp = ws;
688 if (NULL == archive_string_ensure(as,
689 as->length + wslen +1))
691 p = as->s + as->length;
694 while (count < wslen && *wp) {
703 } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
707 archive_string_ensure(as, as->length + len * 2 + 2))
709 u16 = (uint16_t *)(as->s + as->length);
712 if (sc->flag & SCONV_TO_UTF16BE) {
713 while (count < (int)len && *ws) {
714 archive_be16enc(u16+count, *ws);
719 while (count < (int)len && *ws) {
720 archive_le16enc(u16+count, *ws);
725 count <<= 1; /* to be byte size */
727 /* Make sure the MBS buffer has plenty to set. */
729 archive_string_ensure(as, as->length + len * 2 + 1))
733 if (to_cp == CP_UTF8 || sc == NULL)
737 count = WideCharToMultiByte(to_cp, 0, ws, wslen,
738 as->s + as->length, (int)as->buffer_length-1, NULL, dp);
740 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
741 /* Expand the MBS buffer and retry. */
742 if (NULL == archive_string_ensure(as,
743 as->buffer_length + len))
753 as->s[as->length] = '\0';
754 return (defchar_used?-1:ret);
757 #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
760 * Translates a wide character string into current locale character set
761 * and appends to the archive_string. Note: returns -1 if conversion
765 archive_string_append_from_wcs(struct archive_string *as,
766 const wchar_t *w, size_t len)
768 /* We cannot use the standard wcstombs() here because it
769 * cannot tell us how big the output buffer should be. So
770 * I've built a loop around wcrtomb() or wctomb() that
771 * converts a character at a time and resizes the string as
772 * needed. We prefer wcrtomb() when it's available because
773 * it's thread-safe. */
778 mbstate_t shift_state;
780 memset(&shift_state, 0, sizeof(shift_state));
782 /* Clear the shift state before starting. */
786 * Allocate buffer for MBS.
787 * We need this allocation here since it is possible that
788 * as->s is still NULL.
790 if (archive_string_ensure(as, as->length + len + 1) == NULL)
793 p = as->s + as->length;
794 end = as->s + as->buffer_length - MB_CUR_MAX -1;
795 while (*w != L'\0' && len > 0) {
797 as->length = p - as->s;
798 as->s[as->length] = '\0';
799 /* Re-allocate buffer for MBS. */
800 if (archive_string_ensure(as,
801 as->length + len * 2 + 1) == NULL)
803 p = as->s + as->length;
804 end = as->s + as->buffer_length - MB_CUR_MAX -1;
807 n = wcrtomb(p, *w++, &shift_state);
812 if (errno == EILSEQ) {
813 /* Skip an illegal wide char. */
824 as->length = p - as->s;
825 as->s[as->length] = '\0';
829 #else /* HAVE_WCTOMB || HAVE_WCRTOMB */
832 * TODO: Test if __STDC_ISO_10646__ is defined.
833 * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
834 * one character at a time. If a non-Windows platform doesn't have
835 * either of these, fall back to the built-in UTF8 conversion.
838 archive_string_append_from_wcs(struct archive_string *as,
839 const wchar_t *w, size_t len)
841 (void)as;/* UNUSED */
843 (void)len;/* UNUSED */
848 #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
851 * Find a string conversion object by a pair of 'from' charset name
852 * and 'to' charset name from an archive object.
853 * Return NULL if not found.
855 static struct archive_string_conv *
856 find_sconv_object(struct archive *a, const char *fc, const char *tc)
858 struct archive_string_conv *sc;
863 for (sc = a->sconv; sc != NULL; sc = sc->next) {
864 if (strcmp(sc->from_charset, fc) == 0 &&
865 strcmp(sc->to_charset, tc) == 0)
872 * Register a string object to an archive object.
875 add_sconv_object(struct archive *a, struct archive_string_conv *sc)
877 struct archive_string_conv **psc;
879 /* Add a new sconv to sconv list. */
882 psc = &((*psc)->next);
887 add_converter(struct archive_string_conv *sc, int (*converter)
888 (struct archive_string *, const void *, size_t,
889 struct archive_string_conv *))
891 if (sc == NULL || sc->nconverter >= 2)
892 __archive_errx(1, "Programing error");
893 sc->converter[sc->nconverter++] = converter;
897 setup_converter(struct archive_string_conv *sc)
904 * Perform special sequence for the incorrect UTF-8 filenames
905 * made by libarchive2.x.
907 if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
908 add_converter(sc, strncat_from_utf8_libarchive2);
913 * Convert a string to UTF-16BE/LE.
915 if (sc->flag & SCONV_TO_UTF16) {
917 * If the current locale is UTF-8, we can translate
918 * a UTF-8 string into a UTF-16BE string.
920 if (sc->flag & SCONV_FROM_UTF8) {
921 add_converter(sc, archive_string_append_unicode);
925 #if defined(_WIN32) && !defined(__CYGWIN__)
926 if (sc->flag & SCONV_WIN_CP) {
927 if (sc->flag & SCONV_TO_UTF16BE)
928 add_converter(sc, win_strncat_to_utf16be);
930 add_converter(sc, win_strncat_to_utf16le);
935 #if defined(HAVE_ICONV)
936 if (sc->cd != (iconv_t)-1) {
937 add_converter(sc, iconv_strncat_in_locale);
942 if (sc->flag & SCONV_BEST_EFFORT) {
943 if (sc->flag & SCONV_TO_UTF16BE)
945 best_effort_strncat_to_utf16be);
948 best_effort_strncat_to_utf16le);
950 /* Make sure we have no converter. */
956 * Convert a string from UTF-16BE/LE.
958 if (sc->flag & SCONV_FROM_UTF16) {
960 * At least we should normalize a UTF-16BE string.
962 if (sc->flag & SCONV_NORMALIZATION_D)
963 add_converter(sc,archive_string_normalize_D);
964 else if (sc->flag & SCONV_NORMALIZATION_C)
965 add_converter(sc, archive_string_normalize_C);
967 if (sc->flag & SCONV_TO_UTF8) {
969 * If the current locale is UTF-8, we can translate
970 * a UTF-16BE/LE string into a UTF-8 string directly.
973 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
975 archive_string_append_unicode);
979 #if defined(_WIN32) && !defined(__CYGWIN__)
980 if (sc->flag & SCONV_WIN_CP) {
981 if (sc->flag & SCONV_FROM_UTF16BE)
982 add_converter(sc, win_strncat_from_utf16be);
984 add_converter(sc, win_strncat_from_utf16le);
989 #if defined(HAVE_ICONV)
990 if (sc->cd != (iconv_t)-1) {
991 add_converter(sc, iconv_strncat_in_locale);
996 if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
997 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
998 add_converter(sc, best_effort_strncat_from_utf16be);
999 else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1000 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1001 add_converter(sc, best_effort_strncat_from_utf16le);
1003 /* Make sure we have no converter. */
1008 if (sc->flag & SCONV_FROM_UTF8) {
1010 * At least we should normalize a UTF-8 string.
1012 if (sc->flag & SCONV_NORMALIZATION_D)
1013 add_converter(sc,archive_string_normalize_D);
1014 else if (sc->flag & SCONV_NORMALIZATION_C)
1015 add_converter(sc, archive_string_normalize_C);
1018 * Copy UTF-8 string with a check of CESU-8.
1019 * Apparently, iconv does not check surrogate pairs in UTF-8
1020 * when both from-charset and to-charset are UTF-8, and then
1021 * we use our UTF-8 copy code.
1023 if (sc->flag & SCONV_TO_UTF8) {
1025 * If the current locale is UTF-8, we can translate
1026 * a UTF-16BE string into a UTF-8 string directly.
1029 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1030 add_converter(sc, strncat_from_utf8_to_utf8);
1035 #if defined(_WIN32) && !defined(__CYGWIN__)
1037 * On Windows we can use Windows API for a string conversion.
1039 if (sc->flag & SCONV_WIN_CP) {
1040 add_converter(sc, strncat_in_codepage);
1046 if (sc->cd != (iconv_t)-1) {
1047 add_converter(sc, iconv_strncat_in_locale);
1049 * iconv generally does not support UTF-8-MAC and so
1050 * we have to the output of iconv from NFC to NFD if
1053 if ((sc->flag & SCONV_FROM_CHARSET) &&
1054 (sc->flag & SCONV_TO_UTF8)) {
1055 if (sc->flag & SCONV_NORMALIZATION_D)
1056 add_converter(sc, archive_string_normalize_D);
1063 * Try conversion in the best effort or no conversion.
1065 if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
1066 add_converter(sc, best_effort_strncat_in_locale);
1068 /* Make sure we have no converter. */
1073 * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
1074 * and CP932 which are referenced in create_sconv_object().
1077 canonical_charset_name(const char *charset)
1083 if (charset == NULL || charset[0] == '\0'
1084 || strlen(charset) > 15)
1087 /* Copy name to uppercase. */
1092 if (c >= 'a' && c <= 'z')
1098 if (strcmp(cs, "UTF-8") == 0 ||
1099 strcmp(cs, "UTF8") == 0)
1101 if (strcmp(cs, "UTF-16BE") == 0 ||
1102 strcmp(cs, "UTF16BE") == 0)
1103 return ("UTF-16BE");
1104 if (strcmp(cs, "UTF-16LE") == 0 ||
1105 strcmp(cs, "UTF16LE") == 0)
1106 return ("UTF-16LE");
1107 if (strcmp(cs, "CP932") == 0)
1113 * Create a string conversion object.
1115 static struct archive_string_conv *
1116 create_sconv_object(const char *fc, const char *tc,
1117 unsigned current_codepage, int flag)
1119 struct archive_string_conv *sc;
1121 sc = calloc(1, sizeof(*sc));
1125 sc->from_charset = strdup(fc);
1126 if (sc->from_charset == NULL) {
1130 sc->to_charset = strdup(tc);
1131 if (sc->to_charset == NULL) {
1132 free(sc->from_charset);
1136 archive_string_init(&sc->utftmp);
1138 if (flag & SCONV_TO_CHARSET) {
1140 * Convert characters from the current locale charset to
1141 * a specified charset.
1143 sc->from_cp = current_codepage;
1144 sc->to_cp = make_codepage_from_charset(tc);
1145 #if defined(_WIN32) && !defined(__CYGWIN__)
1146 if (IsValidCodePage(sc->to_cp))
1147 flag |= SCONV_WIN_CP;
1149 } else if (flag & SCONV_FROM_CHARSET) {
1151 * Convert characters from a specified charset to
1152 * the current locale charset.
1154 sc->to_cp = current_codepage;
1155 sc->from_cp = make_codepage_from_charset(fc);
1156 #if defined(_WIN32) && !defined(__CYGWIN__)
1157 if (IsValidCodePage(sc->from_cp))
1158 flag |= SCONV_WIN_CP;
1163 * Check if "from charset" and "to charset" are the same.
1165 if (strcmp(fc, tc) == 0 ||
1166 (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
1172 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
1174 if (strcmp(tc, "UTF-8") == 0)
1175 flag |= SCONV_TO_UTF8;
1176 else if (strcmp(tc, "UTF-16BE") == 0)
1177 flag |= SCONV_TO_UTF16BE;
1178 else if (strcmp(tc, "UTF-16LE") == 0)
1179 flag |= SCONV_TO_UTF16LE;
1180 if (strcmp(fc, "UTF-8") == 0)
1181 flag |= SCONV_FROM_UTF8;
1182 else if (strcmp(fc, "UTF-16BE") == 0)
1183 flag |= SCONV_FROM_UTF16BE;
1184 else if (strcmp(fc, "UTF-16LE") == 0)
1185 flag |= SCONV_FROM_UTF16LE;
1186 #if defined(_WIN32) && !defined(__CYGWIN__)
1187 if (sc->to_cp == CP_UTF8)
1188 flag |= SCONV_TO_UTF8;
1189 else if (sc->to_cp == CP_UTF16BE)
1190 flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
1191 else if (sc->to_cp == CP_UTF16LE)
1192 flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
1193 if (sc->from_cp == CP_UTF8)
1194 flag |= SCONV_FROM_UTF8;
1195 else if (sc->from_cp == CP_UTF16BE)
1196 flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
1197 else if (sc->from_cp == CP_UTF16LE)
1198 flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
1202 * Set a flag for Unicode NFD. Usually iconv cannot correctly
1203 * handle it. So we have to translate NFD characters to NFC ones
1204 * ourselves before iconv handles. Another reason is to prevent
1205 * that the same sight of two filenames, one is NFC and other
1206 * is NFD, would be in its directory.
1207 * On Mac OS X, although its filesystem layer automatically
1208 * convert filenames to NFD, it would be useful for filename
1209 * comparing to find out the same filenames that we normalize
1210 * that to be NFD ourselves.
1212 if ((flag & SCONV_FROM_CHARSET) &&
1213 (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
1214 #if defined(__APPLE__)
1215 if (flag & SCONV_TO_UTF8)
1216 flag |= SCONV_NORMALIZATION_D;
1219 flag |= SCONV_NORMALIZATION_C;
1221 #if defined(__APPLE__)
1223 * In case writing an archive file, make sure that a filename
1224 * going to be passed to iconv is a Unicode NFC string since
1225 * a filename in HFS Plus filesystem is a Unicode NFD one and
1226 * iconv cannot handle it with "UTF-8" charset. It is simpler
1227 * than a use of "UTF-8-MAC" charset.
1229 if ((flag & SCONV_TO_CHARSET) &&
1230 (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1231 !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1232 flag |= SCONV_NORMALIZATION_C;
1234 * In case reading an archive file. make sure that a filename
1235 * will be passed to users is a Unicode NFD string in order to
1236 * correctly compare the filename with other one which comes
1237 * from HFS Plus filesystem.
1239 if ((flag & SCONV_FROM_CHARSET) &&
1240 !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1241 (flag & SCONV_TO_UTF8))
1242 flag |= SCONV_NORMALIZATION_D;
1245 #if defined(HAVE_ICONV)
1246 sc->cd_w = (iconv_t)-1;
1248 * Create an iconv object.
1250 if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
1251 (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
1252 (flag & SCONV_WIN_CP)) {
1253 /* This case we won't use iconv. */
1254 sc->cd = (iconv_t)-1;
1256 sc->cd = iconv_open(tc, fc);
1257 if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
1259 * Unfortunately, all of iconv implements do support
1260 * "CP932" character-set, so we should use "SJIS"
1261 * instead if iconv_open failed.
1263 if (strcmp(tc, "CP932") == 0)
1264 sc->cd = iconv_open("SJIS", fc);
1265 else if (strcmp(fc, "CP932") == 0)
1266 sc->cd = iconv_open(tc, "SJIS");
1268 #if defined(_WIN32) && !defined(__CYGWIN__)
1270 * archive_mstring on Windows directly convert multi-bytes
1271 * into archive_wstring in order not to depend on locale
1272 * so that you can do a I18N programming. This will be
1273 * used only in archive_mstring_copy_mbs_len_l so far.
1275 if (flag & SCONV_FROM_CHARSET) {
1276 sc->cd_w = iconv_open("UTF-8", fc);
1277 if (sc->cd_w == (iconv_t)-1 &&
1278 (sc->flag & SCONV_BEST_EFFORT)) {
1279 if (strcmp(fc, "CP932") == 0)
1280 sc->cd_w = iconv_open("UTF-8", "SJIS");
1283 #endif /* _WIN32 && !__CYGWIN__ */
1285 #endif /* HAVE_ICONV */
1290 * Set up converters.
1292 setup_converter(sc);
1298 * Free a string conversion object.
1301 free_sconv_object(struct archive_string_conv *sc)
1303 free(sc->from_charset);
1304 free(sc->to_charset);
1305 archive_string_free(&sc->utftmp);
1307 if (sc->cd != (iconv_t)-1)
1308 iconv_close(sc->cd);
1309 if (sc->cd_w != (iconv_t)-1)
1310 iconv_close(sc->cd_w);
1315 #if defined(_WIN32) && !defined(__CYGWIN__)
1317 my_atoi(const char *p)
1323 if (*p >= '0' && *p <= '9')
1324 cp = cp * 10 + (*p - '0');
1333 * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
1334 * Return -1 if failed.
1336 * Note: This translation code may be insufficient.
1338 static struct charset {
1342 /* MUST BE SORTED! */
1361 {"HZ-GB-2312", 52936},
1379 {"ISO-8859-1", 28591},
1380 {"ISO-8859-13", 28603},
1381 {"ISO-8859-15", 28605},
1382 {"ISO-8859-2", 28592},
1383 {"ISO-8859-3", 28593},
1384 {"ISO-8859-4", 28594},
1385 {"ISO-8859-5", 28595},
1386 {"ISO-8859-6", 28596},
1387 {"ISO-8859-7", 28597},
1388 {"ISO-8859-8", 28598},
1389 {"ISO-8859-9", 28599},
1390 {"ISO8859-1", 28591},
1391 {"ISO8859-13", 28603},
1392 {"ISO8859-15", 28605},
1393 {"ISO8859-2", 28592},
1394 {"ISO8859-3", 28593},
1395 {"ISO8859-4", 28594},
1396 {"ISO8859-5", 28595},
1397 {"ISO8859-6", 28596},
1398 {"ISO8859-7", 28597},
1399 {"ISO8859-8", 28598},
1400 {"ISO8859-9", 28599},
1404 {"KS_C_5601-1987", 949},
1407 {"MACINTOSH", 10000},
1417 {"X-EUROPA", 29001},
1418 {"X-MAC-ARABIC", 10004},
1419 {"X-MAC-CE", 10029},
1420 {"X-MAC-CHINESEIMP", 10008},
1421 {"X-MAC-CHINESETRAD", 10002},
1422 {"X-MAC-CROATIAN", 10082},
1423 {"X-MAC-CYRILLIC", 10007},
1424 {"X-MAC-GREEK", 10006},
1425 {"X-MAC-HEBREW", 10005},
1426 {"X-MAC-ICELANDIC", 10079},
1427 {"X-MAC-JAPANESE", 10001},
1428 {"X-MAC-KOREAN", 10003},
1429 {"X-MAC-ROMANIAN", 10010},
1430 {"X-MAC-THAI", 10021},
1431 {"X-MAC-TURKISH", 10081},
1432 {"X-MAC-UKRAINIAN", 10017},
1435 make_codepage_from_charset(const char *charset)
1442 if (charset == NULL || strlen(charset) > 15)
1445 /* Copy name to uppercase. */
1448 char c = *charset++;
1449 if (c >= 'a' && c <= 'z')
1456 /* Look it up in the table first, so that we can easily
1457 * override CP367, which we map to 1252 instead of 367. */
1459 b = sizeof(charsets)/sizeof(charsets[0]);
1461 int c = (b + a) / 2;
1462 int r = strcmp(charsets[c].name, cs);
1468 return charsets[c].cp;
1471 /* If it's not in the table, try to parse it. */
1474 if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
1475 cp = my_atoi(cs + 2);
1476 } else if (strcmp(cs, "CP_ACP") == 0)
1477 cp = get_current_codepage();
1478 else if (strcmp(cs, "CP_OEMCP") == 0)
1479 cp = get_current_oemcp();
1482 if (cs[1] == 'B' && cs[2] == 'M' &&
1483 cs[3] >= '0' && cs[3] <= '9') {
1484 cp = my_atoi(cs + 3);
1488 if (strncmp(cs, "WINDOWS-", 8) == 0) {
1489 cp = my_atoi(cs + 8);
1490 if (cp != 874 && (cp < 1250 || cp > 1258))
1491 cp = -1;/* This may invalid code. */
1499 * Return ANSI Code Page of current locale set by setlocale().
1502 get_current_codepage(void)
1507 locale = setlocale(LC_CTYPE, NULL);
1510 if (locale[0] == 'C' && locale[1] == '\0')
1511 return (CP_C_LOCALE);
1512 p = strrchr(locale, '.');
1522 * Translation table between Locale Name and ACP/OEMCP.
1529 { 950, 950, "Chinese_Taiwan" },
1530 { 936, 936, "Chinese_People's Republic of China" },
1531 { 950, 950, "Chinese_Taiwan" },
1532 { 1250, 852, "Czech_Czech Republic" },
1533 { 1252, 850, "Danish_Denmark" },
1534 { 1252, 850, "Dutch_Netherlands" },
1535 { 1252, 850, "Dutch_Belgium" },
1536 { 1252, 437, "English_United States" },
1537 { 1252, 850, "English_Australia" },
1538 { 1252, 850, "English_Canada" },
1539 { 1252, 850, "English_New Zealand" },
1540 { 1252, 850, "English_United Kingdom" },
1541 { 1252, 437, "English_United States" },
1542 { 1252, 850, "Finnish_Finland" },
1543 { 1252, 850, "French_France" },
1544 { 1252, 850, "French_Belgium" },
1545 { 1252, 850, "French_Canada" },
1546 { 1252, 850, "French_Switzerland" },
1547 { 1252, 850, "German_Germany" },
1548 { 1252, 850, "German_Austria" },
1549 { 1252, 850, "German_Switzerland" },
1550 { 1253, 737, "Greek_Greece" },
1551 { 1250, 852, "Hungarian_Hungary" },
1552 { 1252, 850, "Icelandic_Iceland" },
1553 { 1252, 850, "Italian_Italy" },
1554 { 1252, 850, "Italian_Switzerland" },
1555 { 932, 932, "Japanese_Japan" },
1556 { 949, 949, "Korean_Korea" },
1557 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1558 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1559 { 1252, 850, "Norwegian-Nynorsk_Norway" },
1560 { 1250, 852, "Polish_Poland" },
1561 { 1252, 850, "Portuguese_Portugal" },
1562 { 1252, 850, "Portuguese_Brazil" },
1563 { 1251, 866, "Russian_Russia" },
1564 { 1250, 852, "Slovak_Slovakia" },
1565 { 1252, 850, "Spanish_Spain" },
1566 { 1252, 850, "Spanish_Mexico" },
1567 { 1252, 850, "Spanish_Spain" },
1568 { 1252, 850, "Swedish_Sweden" },
1569 { 1254, 857, "Turkish_Turkey" },
1574 * Return OEM Code Page of current locale set by setlocale().
1577 get_current_oemcp(void)
1583 locale = setlocale(LC_CTYPE, NULL);
1585 return (GetOEMCP());
1586 if (locale[0] == 'C' && locale[1] == '\0')
1587 return (CP_C_LOCALE);
1589 p = strrchr(locale, '.');
1591 return (GetOEMCP());
1593 for (i = 0; acp_ocp_map[i].acp; i++) {
1594 if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
1595 return (acp_ocp_map[i].ocp);
1597 return (GetOEMCP());
1602 * POSIX platform does not use CodePage.
1606 get_current_codepage(void)
1608 return (-1);/* Unknown */
1611 make_codepage_from_charset(const char *charset)
1613 (void)charset; /* UNUSED */
1614 return (-1);/* Unknown */
1617 get_current_oemcp(void)
1619 return (-1);/* Unknown */
1622 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1625 * Return a string conversion object.
1627 static struct archive_string_conv *
1628 get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
1630 struct archive_string_conv *sc;
1631 unsigned current_codepage;
1633 /* Check if we have made the sconv object. */
1634 sc = find_sconv_object(a, fc, tc);
1639 current_codepage = get_current_codepage();
1641 current_codepage = a->current_codepage;
1643 sc = create_sconv_object(canonical_charset_name(fc),
1644 canonical_charset_name(tc), current_codepage, flag);
1647 archive_set_error(a, ENOMEM,
1648 "Could not allocate memory for "
1649 "a string conversion object");
1654 * If there is no converter for current string conversion object,
1655 * we cannot handle this conversion.
1657 if (sc->nconverter == 0) {
1660 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1661 "iconv_open failed : Cannot handle ``%s''",
1662 (flag & SCONV_TO_CHARSET)?tc:fc);
1664 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1665 "A character-set conversion not fully supported "
1666 "on this platform");
1669 /* Failed; free a sconv object. */
1670 free_sconv_object(sc);
1678 add_sconv_object(a, sc);
1683 get_current_charset(struct archive *a)
1685 const char *cur_charset;
1688 cur_charset = default_iconv_charset("");
1690 cur_charset = default_iconv_charset(a->current_code);
1691 if (a->current_code == NULL) {
1692 a->current_code = strdup(cur_charset);
1693 a->current_codepage = get_current_codepage();
1694 a->current_oemcp = get_current_oemcp();
1697 return (cur_charset);
1701 * Make and Return a string conversion object.
1702 * Return NULL if the platform does not support the specified conversion
1703 * and best_effort is 0.
1704 * If best_effort is set, A string conversion object must be returned
1705 * unless memory allocation for the object fails, but the conversion
1706 * might fail when non-ASCII code is found.
1708 struct archive_string_conv *
1709 archive_string_conversion_to_charset(struct archive *a, const char *charset,
1712 int flag = SCONV_TO_CHARSET;
1715 flag |= SCONV_BEST_EFFORT;
1716 return (get_sconv_object(a, get_current_charset(a), charset, flag));
1719 struct archive_string_conv *
1720 archive_string_conversion_from_charset(struct archive *a, const char *charset,
1723 int flag = SCONV_FROM_CHARSET;
1726 flag |= SCONV_BEST_EFFORT;
1727 return (get_sconv_object(a, charset, get_current_charset(a), flag));
1731 * archive_string_default_conversion_*_archive() are provided for Windows
1732 * platform because other archiver application use CP_OEMCP for
1733 * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
1734 * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
1735 * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
1736 * So we should make a string conversion between CP_ACP and CP_OEMCP
1737 * for compatibility.
1739 #if defined(_WIN32) && !defined(__CYGWIN__)
1740 struct archive_string_conv *
1741 archive_string_default_conversion_for_read(struct archive *a)
1743 const char *cur_charset = get_current_charset(a);
1746 /* NOTE: a check of cur_charset is unneeded but we need
1747 * that get_current_charset() has been surely called at
1748 * this time whatever C compiler optimized. */
1749 if (cur_charset != NULL &&
1750 (a->current_codepage == CP_C_LOCALE ||
1751 a->current_codepage == a->current_oemcp))
1752 return (NULL);/* no conversion. */
1754 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1755 /* Make sure a null termination must be set. */
1756 oemcp[sizeof(oemcp)-1] = '\0';
1757 return (get_sconv_object(a, oemcp, cur_charset,
1758 SCONV_FROM_CHARSET));
1761 struct archive_string_conv *
1762 archive_string_default_conversion_for_write(struct archive *a)
1764 const char *cur_charset = get_current_charset(a);
1767 /* NOTE: a check of cur_charset is unneeded but we need
1768 * that get_current_charset() has been surely called at
1769 * this time whatever C compiler optimized. */
1770 if (cur_charset != NULL &&
1771 (a->current_codepage == CP_C_LOCALE ||
1772 a->current_codepage == a->current_oemcp))
1773 return (NULL);/* no conversion. */
1775 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1776 /* Make sure a null termination must be set. */
1777 oemcp[sizeof(oemcp)-1] = '\0';
1778 return (get_sconv_object(a, cur_charset, oemcp,
1782 struct archive_string_conv *
1783 archive_string_default_conversion_for_read(struct archive *a)
1785 (void)a; /* UNUSED */
1789 struct archive_string_conv *
1790 archive_string_default_conversion_for_write(struct archive *a)
1792 (void)a; /* UNUSED */
1798 * Dispose of all character conversion objects in the archive object.
1801 archive_string_conversion_free(struct archive *a)
1803 struct archive_string_conv *sc;
1804 struct archive_string_conv *sc_next;
1806 for (sc = a->sconv; sc != NULL; sc = sc_next) {
1808 free_sconv_object(sc);
1811 free(a->current_code);
1812 a->current_code = NULL;
1816 * Return a conversion charset name.
1819 archive_string_conversion_charset_name(struct archive_string_conv *sc)
1821 if (sc->flag & SCONV_TO_CHARSET)
1822 return (sc->to_charset);
1824 return (sc->from_charset);
1828 * Change the behavior of a string conversion.
1831 archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
1835 * A filename in UTF-8 was made with libarchive 2.x in a wrong
1836 * assumption that wchar_t was Unicode.
1837 * This option enables simulating the assumption in order to read
1838 * that filename correctly.
1840 case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
1841 #if (defined(_WIN32) && !defined(__CYGWIN__)) \
1842 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
1844 * Nothing to do for it since wchar_t on these platforms
1845 * is really Unicode.
1847 (void)sc; /* UNUSED */
1849 if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
1850 sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
1851 /* Set up string converters. */
1852 setup_converter(sc);
1856 case SCONV_SET_OPT_NORMALIZATION_C:
1857 if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
1858 sc->flag |= SCONV_NORMALIZATION_C;
1859 sc->flag &= ~SCONV_NORMALIZATION_D;
1860 /* Set up string converters. */
1861 setup_converter(sc);
1864 case SCONV_SET_OPT_NORMALIZATION_D:
1865 #if defined(HAVE_ICONV)
1867 * If iconv will take the string, do not change the
1868 * setting of the normalization.
1870 if (!(sc->flag & SCONV_WIN_CP) &&
1871 (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1872 !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1875 if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
1876 sc->flag |= SCONV_NORMALIZATION_D;
1877 sc->flag &= ~SCONV_NORMALIZATION_C;
1878 /* Set up string converters. */
1879 setup_converter(sc);
1889 * Copy one archive_string to another in locale conversion.
1891 * archive_strncat_l();
1892 * archive_strncpy_l();
1897 mbsnbytes(const void *_p, size_t n)
1904 p = (const char *)_p;
1906 /* Like strlen(p), except won't examine positions beyond p[n]. */
1909 while (s < n && *pp) {
1917 utf16nbytes(const void *_p, size_t n)
1924 p = (const char *)_p;
1926 /* Like strlen(p), except won't examine positions beyond p[n]. */
1930 while (s < n && (pp[0] || pp[1])) {
1938 archive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
1939 struct archive_string_conv *sc)
1942 return (archive_strncat_l(as, _p, n, sc));
1946 archive_strncat_l(struct archive_string *as, const void *_p, size_t n,
1947 struct archive_string_conv *sc)
1953 if (_p != NULL && n > 0) {
1954 if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
1955 length = utf16nbytes(_p, n);
1957 length = mbsnbytes(_p, n);
1960 /* We must allocate memory even if there is no data for conversion
1961 * or copy. This simulates archive_string_append behavior. */
1964 if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
1966 if (archive_string_ensure(as, as->length + tn) == NULL)
1968 as->s[as->length] = 0;
1970 as->s[as->length+1] = 0;
1975 * If sc is NULL, we just make a copy.
1978 if (archive_string_append(as, _p, length) == NULL)
1979 return (-1);/* No memory */
1985 if (sc->nconverter > 1) {
1986 sc->utftmp.length = 0;
1987 r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
1988 if (r2 != 0 && errno == ENOMEM)
1993 length = sc->utftmp.length;
1996 r2 = sc->converter[i](as, s, length, sc);
2005 * Return -1 if conversion fails.
2008 iconv_strncat_in_locale(struct archive_string *as, const void *_p,
2009 size_t length, struct archive_string_conv *sc)
2011 ICONV_CONST char *itp;
2016 int return_value = 0; /* success */
2017 int to_size, from_size;
2019 if (sc->flag & SCONV_TO_UTF16)
2023 if (sc->flag & SCONV_FROM_UTF16)
2028 if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2032 itp = (char *)(uintptr_t)_p;
2034 outp = as->s + as->length;
2035 avail = as->buffer_length - as->length - to_size;
2036 while (remaining >= (size_t)from_size) {
2037 size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
2039 if (result != (size_t)-1)
2040 break; /* Conversion completed. */
2042 if (errno == EILSEQ || errno == EINVAL) {
2044 * If an output charset is UTF-8 or UTF-16BE/LE,
2045 * unknown character should be U+FFFD
2046 * (replacement character).
2048 if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2050 if (sc->flag & SCONV_TO_UTF8)
2051 rbytes = sizeof(utf8_replacement_char);
2055 if (avail < rbytes) {
2056 as->length = outp - as->s;
2057 bs = as->buffer_length +
2058 (remaining * to_size) + rbytes;
2060 archive_string_ensure(as, bs))
2062 outp = as->s + as->length;
2063 avail = as->buffer_length
2064 - as->length - to_size;
2066 if (sc->flag & SCONV_TO_UTF8)
2067 memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
2068 else if (sc->flag & SCONV_TO_UTF16BE)
2069 archive_be16enc(outp, UNICODE_R_CHAR);
2071 archive_le16enc(outp, UNICODE_R_CHAR);
2075 /* Skip the illegal input bytes. */
2080 remaining -= from_size;
2081 return_value = -1; /* failure */
2083 /* E2BIG no output buffer,
2084 * Increase an output buffer. */
2085 as->length = outp - as->s;
2086 bs = as->buffer_length + remaining * 2;
2087 if (NULL == archive_string_ensure(as, bs))
2089 outp = as->s + as->length;
2090 avail = as->buffer_length - as->length - to_size;
2093 as->length = outp - as->s;
2094 as->s[as->length] = 0;
2096 as->s[as->length+1] = 0;
2097 return (return_value);
2100 #endif /* HAVE_ICONV */
2103 #if defined(_WIN32) && !defined(__CYGWIN__)
2106 * Translate a string from a some CodePage to an another CodePage by
2107 * Windows APIs, and copy the result. Return -1 if conversion fails.
2110 strncat_in_codepage(struct archive_string *as,
2111 const void *_p, size_t length, struct archive_string_conv *sc)
2113 const char *s = (const char *)_p;
2114 struct archive_wstring aws;
2118 archive_string_init(&aws);
2119 saved_flag = sc->flag;
2120 sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2121 r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2122 sc->flag = saved_flag;
2124 archive_wstring_free(&aws);
2125 if (errno != ENOMEM)
2126 archive_string_append(as, s, length);
2131 r = archive_string_append_from_wcs_in_codepage(
2132 as, aws.s, aws.length, sc);
2133 if (r != 0 && errno != ENOMEM && l == as->length)
2134 archive_string_append(as, s, length);
2135 archive_wstring_free(&aws);
2140 * Test whether MBS ==> WCS is okay.
2143 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2145 const char *p = (const char *)_p;
2147 DWORD mbflag = MB_ERR_INVALID_CHARS;
2149 if (sc->flag & SCONV_FROM_CHARSET)
2150 codepage = sc->to_cp;
2152 codepage = sc->from_cp;
2154 if (codepage == CP_C_LOCALE)
2156 if (codepage != CP_UTF8)
2157 mbflag |= MB_PRECOMPOSED;
2159 if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
2160 return (-1); /* Invalid */
2161 return (0); /* Okay */
2167 * Test whether MBS ==> WCS is okay.
2170 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2172 const char *p = (const char *)_p;
2176 mbstate_t shift_state;
2178 memset(&shift_state, 0, sizeof(shift_state));
2180 /* Clear the shift state before starting. */
2181 mbtowc(NULL, NULL, 0);
2187 r = mbrtowc(&wc, p, n, &shift_state);
2189 r = mbtowc(&wc, p, n);
2191 if (r == (size_t)-1 || r == (size_t)-2)
2192 return (-1);/* Invalid. */
2198 (void)sc; /* UNUSED */
2199 return (0); /* All Okey. */
2202 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2205 * Basically returns -1 because we cannot make a conversion of charset
2206 * without iconv but in some cases this would return 0.
2207 * Returns 0 if all copied characters are ASCII.
2208 * Returns 0 if both from-locale and to-locale are the same and those
2209 * can be WCS with no error.
2212 best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2213 size_t length, struct archive_string_conv *sc)
2217 int return_value = 0; /* success */
2220 * If both from-locale and to-locale is the same, this makes a copy.
2221 * And then this checks all copied MBS can be WCS if so returns 0.
2224 if (archive_string_append(as, _p, length) == NULL)
2225 return (-1);/* No memory */
2226 return (invalid_mbs(_p, length, sc));
2230 * If a character is ASCII, this just copies it. If not, this
2231 * assigns '?' character instead but in UTF-8 locale this assigns
2232 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2233 * a Replacement Character in Unicode.
2237 itp = (const uint8_t *)_p;
2238 while (*itp && remaining > 0) {
2240 // Non-ASCII: Substitute with suitable replacement
2241 if (sc->flag & SCONV_TO_UTF8) {
2242 if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
2243 __archive_errx(1, "Out of memory");
2246 archive_strappend_char(as, '?');
2250 archive_strappend_char(as, *itp);
2254 return (return_value);
2259 * Unicode conversion functions.
2260 * - UTF-8 <===> UTF-8 in removing surrogate pairs.
2261 * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2262 * - UTF-8 made by libarchive 2.x ===> UTF-8.
2263 * - UTF-16BE <===> UTF-8.
2268 * Utility to convert a single UTF-8 sequence.
2270 * Usually return used bytes, return used byte in negative value when
2271 * a unicode character is replaced with U+FFFD.
2272 * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2273 * Recommended Practice for Replacement Characters.
2276 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2278 static const char utf8_count[256] = {
2279 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2280 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2281 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2282 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2283 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2284 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2285 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2286 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2287 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2288 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2289 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2290 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2291 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2292 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2293 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2294 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2304 * Decode 1-4 bytes depending on the value of the first byte.
2306 ch = (unsigned char)*s;
2308 return (0); /* Standard: return 0 for end-of-string. */
2309 cnt = utf8_count[ch];
2311 /* Invalid sequence or there are not plenty bytes. */
2314 for (i = 1; i < cnt; i++) {
2315 if ((s[i] & 0xc0) != 0x80) {
2320 goto invalid_sequence;
2323 /* Make a Unicode code point from a single UTF-8 sequence. */
2325 case 1: /* 1 byte sequence. */
2328 case 2: /* 2 bytes sequence. */
2329 if ((s[1] & 0xc0) != 0x80) {
2331 goto invalid_sequence;
2333 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2335 case 3: /* 3 bytes sequence. */
2336 if ((s[1] & 0xc0) != 0x80) {
2338 goto invalid_sequence;
2340 if ((s[2] & 0xc0) != 0x80) {
2342 goto invalid_sequence;
2344 wc = ((ch & 0x0f) << 12)
2345 | ((s[1] & 0x3f) << 6)
2348 goto invalid_sequence;/* Overlong sequence. */
2350 case 4: /* 4 bytes sequence. */
2351 if ((s[1] & 0xc0) != 0x80) {
2353 goto invalid_sequence;
2355 if ((s[2] & 0xc0) != 0x80) {
2357 goto invalid_sequence;
2359 if ((s[3] & 0xc0) != 0x80) {
2361 goto invalid_sequence;
2363 wc = ((ch & 0x07) << 18)
2364 | ((s[1] & 0x3f) << 12)
2365 | ((s[2] & 0x3f) << 6)
2368 goto invalid_sequence;/* Overlong sequence. */
2370 default: /* Others are all invalid sequence. */
2371 if (ch == 0xc0 || ch == 0xc1)
2373 else if (ch >= 0xf5 && ch <= 0xf7)
2375 else if (ch >= 0xf8 && ch <= 0xfb)
2377 else if (ch == 0xfc || ch == 0xfd)
2383 for (i = 1; i < cnt; i++) {
2384 if ((s[i] & 0xc0) != 0x80) {
2389 goto invalid_sequence;
2392 /* The code point larger than 0x10FFFF is not legal
2393 * Unicode values. */
2394 if (wc > UNICODE_MAX)
2395 goto invalid_sequence;
2396 /* Correctly gets a Unicode, returns used bytes. */
2400 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2405 utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2409 cnt = _utf8_to_unicode(pwc, s, n);
2410 /* Any of Surrogate pair is not legal Unicode values. */
2411 if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2416 static inline uint32_t
2417 combine_surrogate_pair(uint32_t uc, uint32_t uc2)
2427 * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2428 * removing surrogate pairs.
2430 * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2432 * Usually return used bytes, return used byte in negative value when
2433 * a unicode character is replaced with U+FFFD.
2436 cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2441 cnt = _utf8_to_unicode(&wc, s, n);
2442 if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2445 /* Invalid byte sequence. */
2446 goto invalid_sequence;
2448 cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2449 if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2450 /* Invalid byte sequence. */
2451 goto invalid_sequence;
2453 wc = combine_surrogate_pair(wc, wc2);
2455 } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2456 /* Invalid byte sequence. */
2457 goto invalid_sequence;
2462 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2469 * Convert a Unicode code point to a single UTF-8 sequence.
2471 * NOTE:This function does not check if the Unicode is legal or not.
2472 * Please you definitely check it before calling this.
2475 unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2479 /* Invalid Unicode char maps to Replacement character */
2480 if (uc > UNICODE_MAX)
2481 uc = UNICODE_R_CHAR;
2482 /* Translate code point to UTF8 */
2487 } else if (uc <= 0x7ff) {
2490 *p++ = 0xc0 | ((uc >> 6) & 0x1f);
2491 *p++ = 0x80 | (uc & 0x3f);
2492 } else if (uc <= 0xffff) {
2495 *p++ = 0xe0 | ((uc >> 12) & 0x0f);
2496 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2497 *p++ = 0x80 | (uc & 0x3f);
2501 *p++ = 0xf0 | ((uc >> 18) & 0x07);
2502 *p++ = 0x80 | ((uc >> 12) & 0x3f);
2503 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2504 *p++ = 0x80 | (uc & 0x3f);
2510 utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2512 return (utf16_to_unicode(pwc, s, n, 1));
2516 utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2518 return (utf16_to_unicode(pwc, s, n, 0));
2522 utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2524 const char *utf16 = s;
2530 /* set the Replacement Character instead. */
2531 *pwc = UNICODE_R_CHAR;
2536 uc = archive_be16dec(utf16);
2538 uc = archive_le16dec(utf16);
2541 /* If this is a surrogate pair, assemble the full code point.*/
2542 if (IS_HIGH_SURROGATE_LA(uc)) {
2547 uc2 = archive_be16dec(utf16);
2549 uc2 = archive_le16dec(utf16);
2552 if (IS_LOW_SURROGATE_LA(uc2)) {
2553 uc = combine_surrogate_pair(uc, uc2);
2556 /* Undescribed code point should be U+FFFD
2557 * (replacement character). */
2558 *pwc = UNICODE_R_CHAR;
2564 * Surrogate pair values(0xd800 through 0xdfff) are only
2565 * used by UTF-16, so, after above calculation, the code
2566 * must not be surrogate values, and Unicode has no codes
2567 * larger than 0x10ffff. Thus, those are not legal Unicode
2570 if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2571 /* Undescribed code point should be U+FFFD
2572 * (replacement character). */
2573 *pwc = UNICODE_R_CHAR;
2574 return (((int)(utf16 - s)) * -1);
2577 return ((int)(utf16 - s));
2581 unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2586 /* We have a code point that won't fit into a
2587 * wchar_t; convert it to a surrogate pair. */
2591 archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2592 archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2597 archive_be16enc(utf16, uc);
2603 unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2608 /* We have a code point that won't fit into a
2609 * wchar_t; convert it to a surrogate pair. */
2613 archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2614 archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2619 archive_le16enc(utf16, uc);
2625 * Copy UTF-8 string in checking surrogate pair.
2626 * If any surrogate pair are found, it would be canonicalized.
2629 strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p,
2630 size_t len, struct archive_string_conv *sc)
2636 (void)sc; /* UNUSED */
2638 if (archive_string_ensure(as, as->length + len + 1) == NULL)
2641 s = (const char *)_p;
2642 p = as->s + as->length;
2643 endp = as->s + as->buffer_length -1;
2650 * Forward byte sequence until a conversion of that is needed.
2652 while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
2657 if (p + (s - ss) > endp) {
2658 as->length = p - as->s;
2659 if (archive_string_ensure(as,
2660 as->buffer_length + len + 1) == NULL)
2662 p = as->s + as->length;
2663 endp = as->s + as->buffer_length -1;
2666 memcpy(p, ss, s - ss);
2671 * If n is negative, current byte sequence needs a replacement.
2674 if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2675 /* Current byte sequence may be CESU-8. */
2676 n = cesu8_to_unicode(&uc, s, len);
2680 n *= -1;/* Use a replaced unicode character. */
2683 /* Rebuild UTF-8 byte sequence. */
2684 while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
2685 as->length = p - as->s;
2686 if (archive_string_ensure(as,
2687 as->buffer_length + len + 1) == NULL)
2689 p = as->s + as->length;
2690 endp = as->s + as->buffer_length -1;
2697 as->length = p - as->s;
2698 as->s[as->length] = '\0';
2703 archive_string_append_unicode(struct archive_string *as, const void *_p,
2704 size_t len, struct archive_string_conv *sc)
2710 int n, ret = 0, ts, tm;
2711 int (*parse)(uint32_t *, const char *, size_t);
2712 size_t (*unparse)(char *, size_t, uint32_t);
2714 if (sc->flag & SCONV_TO_UTF16BE) {
2715 unparse = unicode_to_utf16be;
2717 } else if (sc->flag & SCONV_TO_UTF16LE) {
2718 unparse = unicode_to_utf16le;
2720 } else if (sc->flag & SCONV_TO_UTF8) {
2721 unparse = unicode_to_utf8;
2725 * This case is going to be converted to another
2726 * character-set through iconv.
2728 if (sc->flag & SCONV_FROM_UTF16BE) {
2729 unparse = unicode_to_utf16be;
2731 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2732 unparse = unicode_to_utf16le;
2735 unparse = unicode_to_utf8;
2740 if (sc->flag & SCONV_FROM_UTF16BE) {
2741 parse = utf16be_to_unicode;
2743 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2744 parse = utf16le_to_unicode;
2747 parse = cesu8_to_unicode;
2751 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2754 s = (const char *)_p;
2755 p = as->s + as->length;
2756 endp = as->s + as->buffer_length - ts;
2757 while ((n = parse(&uc, s, len)) != 0) {
2759 /* Use a replaced unicode character. */
2765 while ((w = unparse(p, endp - p, uc)) == 0) {
2766 /* There is not enough output buffer so
2767 * we have to expand it. */
2768 as->length = p - as->s;
2769 if (archive_string_ensure(as,
2770 as->buffer_length + len * tm + ts) == NULL)
2772 p = as->s + as->length;
2773 endp = as->s + as->buffer_length - ts;
2777 as->length = p - as->s;
2778 as->s[as->length] = '\0';
2780 as->s[as->length+1] = '\0';
2785 * Following Constants for Hangul compositions this information comes from
2786 * Unicode Standard Annex #15 http://unicode.org/reports/tr15/
2788 #define HC_SBASE 0xAC00
2789 #define HC_LBASE 0x1100
2790 #define HC_VBASE 0x1161
2791 #define HC_TBASE 0x11A7
2792 #define HC_LCOUNT 19
2793 #define HC_VCOUNT 21
2794 #define HC_TCOUNT 28
2795 #define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT)
2796 #define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT)
2799 get_nfc(uint32_t uc, uint32_t uc2)
2804 b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2806 int m = (t + b) / 2;
2807 if (u_composition_table[m].cp1 < uc)
2809 else if (u_composition_table[m].cp1 > uc)
2811 else if (u_composition_table[m].cp2 < uc2)
2813 else if (u_composition_table[m].cp2 > uc2)
2816 return (u_composition_table[m].nfc);
2821 #define FDC_MAX 10 /* The maximum number of Following Decomposable
2825 * Update first code point.
2827 #define UPDATE_UC(new_uc) do { \
2833 * Replace first code point with second code point.
2835 #define REPLACE_UC_WITH_UC2() do { \
2841 #define EXPAND_BUFFER() do { \
2842 as->length = p - as->s; \
2843 if (archive_string_ensure(as, \
2844 as->buffer_length + len * tm + ts) == NULL)\
2846 p = as->s + as->length; \
2847 endp = as->s + as->buffer_length - ts; \
2850 #define UNPARSE(p, endp, uc) do { \
2851 while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
2858 * Write first code point.
2859 * If the code point has not be changed from its original code,
2860 * this just copies it from its original buffer pointer.
2861 * If not, this converts it to UTF-8 byte sequence and copies it.
2863 #define WRITE_UC() do { \
2870 /* FALL THROUGH */ \
2873 /* FALL THROUGH */ \
2876 /* FALL THROUGH */ \
2883 UNPARSE(p, endp, uc); \
2888 * Collect following decomposable code points.
2890 #define COLLECT_CPS(start) do { \
2892 for (_i = start; _i < FDC_MAX ; _i++) { \
2893 nx = parse(&ucx[_i], s, len); \
2896 cx = CCC(ucx[_i]); \
2897 if (cl >= cx && cl != 228 && cx != 228)\
2904 if (_i >= FDC_MAX) { \
2906 ucx_size = FDC_MAX; \
2912 * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
2914 * TODO: Convert composition exclusions, which are never converted
2915 * from NFC,NFD,NFKC and NFKD, to Form C.
2918 archive_string_normalize_C(struct archive_string *as, const void *_p,
2919 size_t len, struct archive_string_conv *sc)
2921 const char *s = (const char *)_p;
2925 int always_replace, n, n2, ret = 0, spair, ts, tm;
2926 int (*parse)(uint32_t *, const char *, size_t);
2927 size_t (*unparse)(char *, size_t, uint32_t);
2930 ts = 1;/* text size. */
2931 if (sc->flag & SCONV_TO_UTF16BE) {
2932 unparse = unicode_to_utf16be;
2934 if (sc->flag & SCONV_FROM_UTF16BE)
2936 } else if (sc->flag & SCONV_TO_UTF16LE) {
2937 unparse = unicode_to_utf16le;
2939 if (sc->flag & SCONV_FROM_UTF16LE)
2941 } else if (sc->flag & SCONV_TO_UTF8) {
2942 unparse = unicode_to_utf8;
2943 if (sc->flag & SCONV_FROM_UTF8)
2947 * This case is going to be converted to another
2948 * character-set through iconv.
2951 if (sc->flag & SCONV_FROM_UTF16BE) {
2952 unparse = unicode_to_utf16be;
2954 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2955 unparse = unicode_to_utf16le;
2958 unparse = unicode_to_utf8;
2962 if (sc->flag & SCONV_FROM_UTF16BE) {
2963 parse = utf16be_to_unicode;
2965 spair = 4;/* surrogate pair size in UTF-16. */
2966 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2967 parse = utf16le_to_unicode;
2969 spair = 4;/* surrogate pair size in UTF-16. */
2971 parse = cesu8_to_unicode;
2973 spair = 6;/* surrogate pair size in UTF-8. */
2976 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2979 p = as->s + as->length;
2980 endp = as->s + as->buffer_length - ts;
2981 while ((n = parse(&uc, s, len)) != 0) {
2982 const char *ucptr, *uc2ptr;
2985 /* Use a replaced unicode character. */
2986 UNPARSE(p, endp, uc);
2991 } else if (n == spair || always_replace)
2992 /* uc is converted from a surrogate pair.
2993 * this should be treated as a changed code. */
3000 /* Read second code point. */
3001 while ((n2 = parse(&uc2, s, len)) > 0) {
3002 uint32_t ucx[FDC_MAX];
3004 int cl, cx, i, nx, ucx_size;
3008 if (n2 == spair || always_replace)
3009 /* uc2 is converted from a surrogate pair.
3010 * this should be treated as a changed code. */
3018 * If current second code point is out of decomposable
3019 * code points, finding compositions is unneeded.
3021 if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3023 REPLACE_UC_WITH_UC2();
3028 * Try to combine current code points.
3031 * We have to combine Hangul characters according to
3032 * http://uniicode.org/reports/tr15/#Hangul
3034 if (0 <= (LIndex = uc - HC_LBASE) &&
3035 LIndex < HC_LCOUNT) {
3037 * Hangul Composition.
3038 * 1. Two current code points are L and V.
3040 int VIndex = uc2 - HC_VBASE;
3041 if (0 <= VIndex && VIndex < HC_VCOUNT) {
3042 /* Make syllable of form LV. */
3043 UPDATE_UC(HC_SBASE +
3044 (LIndex * HC_VCOUNT + VIndex) *
3048 REPLACE_UC_WITH_UC2();
3051 } else if (0 <= (SIndex = uc - HC_SBASE) &&
3052 SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3054 * Hangul Composition.
3055 * 2. Two current code points are LV and T.
3057 int TIndex = uc2 - HC_TBASE;
3058 if (0 < TIndex && TIndex < HC_TCOUNT) {
3059 /* Make syllable of form LVT. */
3060 UPDATE_UC(uc + TIndex);
3063 REPLACE_UC_WITH_UC2();
3066 } else if ((nfc = get_nfc(uc, uc2)) != 0) {
3067 /* A composition to current code points
3071 } else if ((cl = CCC(uc2)) == 0) {
3072 /* Clearly 'uc2' the second code point is not
3073 * a decomposable code. */
3075 REPLACE_UC_WITH_UC2();
3080 * Collect following decomposable code points.
3088 * Find a composed code in the collected code points.
3091 while (i < ucx_size) {
3094 if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3100 * nfc is composed of uc and ucx[i].
3105 * Remove ucx[i] by shifting
3106 * following code points.
3108 for (j = i; j+1 < ucx_size; j++) {
3115 * Collect following code points blocked
3116 * by ucx[i] the removed code point.
3118 if (ucx_size > 0 && i == ucx_size &&
3119 nx > 0 && cx == cl) {
3120 cl = ccx[ucx_size-1];
3121 COLLECT_CPS(ucx_size);
3124 * Restart finding a composed code with
3125 * the updated uc from the top of the
3126 * collected code points.
3132 * Apparently the current code points are not
3133 * decomposed characters or already composed.
3136 for (i = 0; i < ucx_size; i++)
3137 UNPARSE(p, endp, ucx[i]);
3140 * Flush out remaining canonical combining characters.
3142 if (nx > 0 && cx == cl && len > 0) {
3143 while ((nx = parse(&ucx[0], s, len))
3151 UNPARSE(p, endp, ucx[0]);
3158 /* Use a replaced unicode character. */
3159 UNPARSE(p, endp, uc2);
3164 } else if (n2 == 0) {
3169 as->length = p - as->s;
3170 as->s[as->length] = '\0';
3172 as->s[as->length+1] = '\0';
3177 get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
3182 * These are not converted to NFD on Mac OS.
3184 if ((uc >= 0x2000 && uc <= 0x2FFF) ||
3185 (uc >= 0xF900 && uc <= 0xFAFF) ||
3186 (uc >= 0x2F800 && uc <= 0x2FAFF))
3189 * Those code points are not converted to NFD on Mac OS.
3190 * I do not know the reason because it is undocumented.
3192 * 1109A ==> 11099 110BA
3193 * 1109C ==> 1109B 110BA
3194 * 110AB ==> 110A5 110BA
3196 if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
3200 b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
3202 int m = (t + b) / 2;
3203 if (u_decomposition_table[m].nfc < uc)
3205 else if (u_decomposition_table[m].nfc > uc)
3208 *cp1 = u_decomposition_table[m].cp1;
3209 *cp2 = u_decomposition_table[m].cp2;
3216 #define REPLACE_UC_WITH(cp) do { \
3222 * Normalize UTF-8 characters to Form D and copy the result.
3225 archive_string_normalize_D(struct archive_string *as, const void *_p,
3226 size_t len, struct archive_string_conv *sc)
3228 const char *s = (const char *)_p;
3232 int always_replace, n, n2, ret = 0, spair, ts, tm;
3233 int (*parse)(uint32_t *, const char *, size_t);
3234 size_t (*unparse)(char *, size_t, uint32_t);
3237 ts = 1;/* text size. */
3238 if (sc->flag & SCONV_TO_UTF16BE) {
3239 unparse = unicode_to_utf16be;
3241 if (sc->flag & SCONV_FROM_UTF16BE)
3243 } else if (sc->flag & SCONV_TO_UTF16LE) {
3244 unparse = unicode_to_utf16le;
3246 if (sc->flag & SCONV_FROM_UTF16LE)
3248 } else if (sc->flag & SCONV_TO_UTF8) {
3249 unparse = unicode_to_utf8;
3250 if (sc->flag & SCONV_FROM_UTF8)
3254 * This case is going to be converted to another
3255 * character-set through iconv.
3258 if (sc->flag & SCONV_FROM_UTF16BE) {
3259 unparse = unicode_to_utf16be;
3261 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3262 unparse = unicode_to_utf16le;
3265 unparse = unicode_to_utf8;
3269 if (sc->flag & SCONV_FROM_UTF16BE) {
3270 parse = utf16be_to_unicode;
3272 spair = 4;/* surrogate pair size in UTF-16. */
3273 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3274 parse = utf16le_to_unicode;
3276 spair = 4;/* surrogate pair size in UTF-16. */
3278 parse = cesu8_to_unicode;
3280 spair = 6;/* surrogate pair size in UTF-8. */
3283 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3286 p = as->s + as->length;
3287 endp = as->s + as->buffer_length - ts;
3288 while ((n = parse(&uc, s, len)) != 0) {
3301 /* Use a replaced unicode character. */
3302 UNPARSE(p, endp, uc);
3307 } else if (n == spair || always_replace)
3308 /* uc is converted from a surrogate pair.
3309 * this should be treated as a changed code. */
3316 /* Hangul Decomposition. */
3317 if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
3318 int L = HC_LBASE + SIndex / HC_NCOUNT;
3319 int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
3320 int T = HC_TBASE + SIndex % HC_TCOUNT;
3326 if (T != HC_TBASE) {
3332 if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
3338 while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
3341 for (k = fdi; k > 0; k--)
3343 fdc[0].ccc = CCC(cp2);
3346 REPLACE_UC_WITH(cp1);
3349 /* Read following code points. */
3350 while ((n2 = parse(&uc2, s, len)) > 0 &&
3351 (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
3356 for (j = 0; j < fdi; j++) {
3357 if (fdc[j].ccc > ccc)
3361 for (k = fdi; k > j; k--)
3373 for (fdj = 0; fdj < fdi; fdj++) {
3374 REPLACE_UC_WITH(fdc[fdj].uc);
3380 REPLACE_UC_WITH(uc2);
3382 goto check_first_code;
3384 as->length = p - as->s;
3385 as->s[as->length] = '\0';
3387 as->s[as->length+1] = '\0';
3392 * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
3393 * that WCS is Unicode. It is true for several platforms but some are false.
3394 * And then people who did not use UTF-8 locale on the non Unicode WCS
3395 * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3396 * now cannot get right filename from libarchive 3.x and later since we
3397 * fixed the wrong assumption and it is incompatible to older its versions.
3398 * So we provide special option, "compat-2x.x", for resolving it.
3399 * That option enable the string conversion of libarchive 2.x.
3401 * Translates the wrong UTF-8 string made by libarchive 2.x into current
3402 * locale character set and appends to the archive_string.
3403 * Note: returns -1 if conversion fails.
3406 strncat_from_utf8_libarchive2(struct archive_string *as,
3407 const void *_p, size_t len, struct archive_string_conv *sc)
3415 mbstate_t shift_state;
3417 memset(&shift_state, 0, sizeof(shift_state));
3419 /* Clear the shift state before starting. */
3420 wctomb(NULL, L'\0');
3422 (void)sc; /* UNUSED */
3424 * Allocate buffer for MBS.
3425 * We need this allocation here since it is possible that
3426 * as->s is still NULL.
3428 if (archive_string_ensure(as, as->length + len + 1) == NULL)
3431 s = (const char *)_p;
3432 p = as->s + as->length;
3433 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3434 while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3438 as->length = p - as->s;
3439 /* Re-allocate buffer for MBS. */
3440 if (archive_string_ensure(as,
3441 as->length + len * 2 + 1) == NULL)
3443 p = as->s + as->length;
3444 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3448 * As libarchive 2.x, translates the UTF-8 characters into
3449 * wide-characters in the assumption that WCS is Unicode.
3455 wc = (wchar_t)unicode;
3460 * Translates the wide-character into the current locale MBS.
3463 n = (int)wcrtomb(p, wc, &shift_state);
3465 n = (int)wctomb(p, wc);
3471 as->length = p - as->s;
3472 as->s[as->length] = '\0';
3478 * Conversion functions between current locale dependent MBS and UTF-16BE.
3479 * strncat_from_utf16be() : UTF-16BE --> MBS
3480 * strncat_to_utf16be() : MBS --> UTF16BE
3483 #if defined(_WIN32) && !defined(__CYGWIN__)
3486 * Convert a UTF-16BE/LE string to current locale and copy the result.
3487 * Return -1 if conversion fails.
3490 win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3491 struct archive_string_conv *sc, int be)
3493 struct archive_string tmp;
3502 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3505 mbs = as->s + as->length;
3506 mbs_size = as->buffer_length - as->length -1;
3508 if (sc->to_cp == CP_C_LOCALE) {
3510 * "C" locale special process.
3514 for (b = 0; b < bytes; b += 2) {
3517 val = archive_be16dec(u16+b);
3519 val = archive_le16dec(u16+b);
3524 *mbs++ = (char)(val&0xff);
3528 as->s[as->length] = '\0';
3532 archive_string_init(&tmp);
3534 if (is_big_endian()) {
3537 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3539 memcpy(tmp.s, _p, bytes);
3540 for (b = 0; b < bytes; b += 2) {
3541 uint16_t val = archive_be16dec(tmp.s+b);
3542 archive_le16enc(tmp.s+b, val);
3547 if (!is_big_endian()) {
3550 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3552 memcpy(tmp.s, _p, bytes);
3553 for (b = 0; b < bytes; b += 2) {
3554 uint16_t val = archive_le16dec(tmp.s+b);
3555 archive_be16enc(tmp.s+b, val);
3563 ll = WideCharToMultiByte(sc->to_cp, 0,
3564 (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
3566 /* Exit loop if we succeeded */
3568 GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3571 /* Else expand buffer and loop to try again. */
3572 ll = WideCharToMultiByte(sc->to_cp, 0,
3573 (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
3574 if (archive_string_ensure(as, ll +1) == NULL)
3576 mbs = as->s + as->length;
3577 mbs_size = as->buffer_length - as->length -1;
3579 archive_string_free(&tmp);
3581 as->s[as->length] = '\0';
3582 if (ll == 0 || defchar)
3588 win_strncat_from_utf16be(struct archive_string *as, const void *_p,
3589 size_t bytes, struct archive_string_conv *sc)
3591 return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3595 win_strncat_from_utf16le(struct archive_string *as, const void *_p,
3596 size_t bytes, struct archive_string_conv *sc)
3598 return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3606 return (archive_be16dec(&d) == 1);
3610 * Convert a current locale string to UTF-16BE/LE and copy the result.
3611 * Return -1 if conversion fails.
3614 win_strncat_to_utf16(struct archive_string *as16, const void *_p,
3615 size_t length, struct archive_string_conv *sc, int bigendian)
3617 const char *s = (const char *)_p;
3619 size_t count, avail;
3621 if (archive_string_ensure(as16,
3622 as16->length + (length + 1) * 2) == NULL)
3625 u16 = as16->s + as16->length;
3626 avail = as16->buffer_length - 2;
3627 if (sc->from_cp == CP_C_LOCALE) {
3629 * "C" locale special process.
3632 while (count < length && *s) {
3634 archive_be16enc(u16, *s);
3636 archive_le16enc(u16, *s);
3641 as16->length += count << 1;
3642 as16->s[as16->length] = 0;
3643 as16->s[as16->length+1] = 0;
3647 count = MultiByteToWideChar(sc->from_cp,
3648 MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
3649 /* Exit loop if we succeeded */
3651 GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3654 /* Expand buffer and try again */
3655 count = MultiByteToWideChar(sc->from_cp,
3656 MB_PRECOMPOSED, s, (int)length, NULL, 0);
3657 if (archive_string_ensure(as16, (count +1) * 2)
3660 u16 = as16->s + as16->length;
3661 avail = as16->buffer_length - 2;
3663 as16->length += count * 2;
3664 as16->s[as16->length] = 0;
3665 as16->s[as16->length+1] = 0;
3669 if (is_big_endian()) {
3672 uint16_t v = archive_be16dec(u16);
3673 archive_le16enc(u16, v);
3681 uint16_t v = archive_le16dec(u16);
3682 archive_be16enc(u16, v);
3692 win_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3693 size_t length, struct archive_string_conv *sc)
3695 return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3699 win_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3700 size_t length, struct archive_string_conv *sc)
3702 return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3705 #endif /* _WIN32 && !__CYGWIN__ */
3708 * Do the best effort for conversions.
3709 * We cannot handle UTF-16BE character-set without such iconv,
3710 * but there is a chance if a string consists just ASCII code or
3711 * a current locale is UTF-8.
3715 * Convert a UTF-16BE string to current locale and copy the result.
3716 * Return -1 if conversion fails.
3719 best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3720 size_t bytes, struct archive_string_conv *sc, int be)
3722 const char *utf16 = (const char *)_p;
3727 (void)sc; /* UNUSED */
3729 * Other case, we should do the best effort.
3730 * If all character are ASCII(<0x7f), we can convert it.
3731 * if not , we set a alternative character and return -1.
3734 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3736 mbs = as->s + as->length;
3738 while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3747 /* We cannot handle it. */
3753 as->length = mbs - as->s;
3754 as->s[as->length] = '\0';
3759 best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3760 size_t bytes, struct archive_string_conv *sc)
3762 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3766 best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3767 size_t bytes, struct archive_string_conv *sc)
3769 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3773 * Convert a current locale string to UTF-16BE/LE and copy the result.
3774 * Return -1 if conversion fails.
3777 best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3778 size_t length, struct archive_string_conv *sc, int bigendian)
3780 const char *s = (const char *)_p;
3785 (void)sc; /* UNUSED */
3787 * Other case, we should do the best effort.
3788 * If all character are ASCII(<0x7f), we can convert it.
3789 * if not , we set a alternative character and return -1.
3794 if (archive_string_ensure(as16,
3795 as16->length + (length + 1) * 2) == NULL)
3798 utf16 = as16->s + as16->length;
3799 while (remaining--) {
3802 /* We cannot handle it. */
3807 archive_be16enc(utf16, c);
3809 archive_le16enc(utf16, c);
3812 as16->length = utf16 - as16->s;
3813 as16->s[as16->length] = 0;
3814 as16->s[as16->length+1] = 0;
3819 best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3820 size_t length, struct archive_string_conv *sc)
3822 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3826 best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3827 size_t length, struct archive_string_conv *sc)
3829 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3834 * Multistring operations.
3838 archive_mstring_clean(struct archive_mstring *aes)
3840 archive_wstring_free(&(aes->aes_wcs));
3841 archive_string_free(&(aes->aes_mbs));
3842 archive_string_free(&(aes->aes_utf8));
3843 archive_string_free(&(aes->aes_mbs_in_locale));
3848 archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3850 dest->aes_set = src->aes_set;
3851 archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3852 archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3853 archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3857 archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3860 struct archive_string_conv *sc;
3863 /* If we already have a UTF8 form, return that immediately. */
3864 if (aes->aes_set & AES_SET_UTF8) {
3865 *p = aes->aes_utf8.s;
3870 if (aes->aes_set & AES_SET_MBS) {
3871 sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3873 return (-1);/* Couldn't allocate memory for sc. */
3874 r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
3875 aes->aes_mbs.length, sc);
3877 free_sconv_object(sc);
3879 aes->aes_set |= AES_SET_UTF8;
3880 *p = aes->aes_utf8.s;
3881 return (0);/* success. */
3883 return (-1);/* failure. */
3885 return (0);/* success. */
3889 archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3894 (void)a; /* UNUSED */
3895 /* If we already have an MBS form, return that immediately. */
3896 if (aes->aes_set & AES_SET_MBS) {
3897 *p = aes->aes_mbs.s;
3902 /* If there's a WCS form, try converting with the native locale. */
3903 if (aes->aes_set & AES_SET_WCS) {
3904 archive_string_empty(&(aes->aes_mbs));
3905 r = archive_string_append_from_wcs(&(aes->aes_mbs),
3906 aes->aes_wcs.s, aes->aes_wcs.length);
3907 *p = aes->aes_mbs.s;
3909 aes->aes_set |= AES_SET_MBS;
3916 * Only a UTF-8 form cannot avail because its conversion already
3917 * failed at archive_mstring_update_utf8().
3923 archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
3928 (void)a;/* UNUSED */
3929 /* Return WCS form if we already have it. */
3930 if (aes->aes_set & AES_SET_WCS) {
3931 *wp = aes->aes_wcs.s;
3936 /* Try converting MBS to WCS using native locale. */
3937 if (aes->aes_set & AES_SET_MBS) {
3938 archive_wstring_empty(&(aes->aes_wcs));
3939 r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
3940 aes->aes_mbs.s, aes->aes_mbs.length);
3942 aes->aes_set |= AES_SET_WCS;
3943 *wp = aes->aes_wcs.s;
3945 ret = -1;/* failure. */
3951 archive_mstring_get_mbs_l(struct archive_mstring *aes,
3952 const char **p, size_t *length, struct archive_string_conv *sc)
3956 #if defined(_WIN32) && !defined(__CYGWIN__)
3958 * Internationalization programming on Windows must use Wide
3959 * characters because Windows platform cannot make locale UTF-8.
3961 if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
3962 archive_string_empty(&(aes->aes_mbs_in_locale));
3963 r = archive_string_append_from_wcs_in_codepage(
3964 &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
3965 aes->aes_wcs.length, sc);
3967 *p = aes->aes_mbs_in_locale.s;
3969 *length = aes->aes_mbs_in_locale.length;
3971 } else if (errno == ENOMEM)
3978 /* If there is not an MBS form but is a WCS form, try converting
3979 * with the native locale to be used for translating it to specified
3981 if ((aes->aes_set & AES_SET_MBS) == 0 &&
3982 (aes->aes_set & AES_SET_WCS) != 0) {
3983 archive_string_empty(&(aes->aes_mbs));
3984 r = archive_string_append_from_wcs(&(aes->aes_mbs),
3985 aes->aes_wcs.s, aes->aes_wcs.length);
3987 aes->aes_set |= AES_SET_MBS;
3988 else if (errno == ENOMEM)
3993 /* If we already have an MBS form, use it to be translated to
3994 * specified character-set. */
3995 if (aes->aes_set & AES_SET_MBS) {
3997 /* Conversion is unneeded. */
3998 *p = aes->aes_mbs.s;
4000 *length = aes->aes_mbs.length;
4003 ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
4004 aes->aes_mbs.s, aes->aes_mbs.length, sc);
4005 *p = aes->aes_mbs_in_locale.s;
4007 *length = aes->aes_mbs_in_locale.length;
4017 archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4023 return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4027 archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4034 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4035 archive_strncpy(&(aes->aes_mbs), mbs, len);
4036 archive_string_empty(&(aes->aes_utf8));
4037 archive_wstring_empty(&(aes->aes_wcs));
4042 archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4044 return archive_mstring_copy_wcs_len(aes, wcs,
4045 wcs == NULL ? 0 : wcslen(wcs));
4049 archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
4054 aes->aes_set = AES_SET_UTF8;
4055 archive_string_empty(&(aes->aes_mbs));
4056 archive_string_empty(&(aes->aes_wcs));
4057 archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
4058 return (int)strlen(utf8);
4062 archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4068 aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4069 archive_string_empty(&(aes->aes_mbs));
4070 archive_string_empty(&(aes->aes_utf8));
4071 archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4076 archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4077 const char *mbs, size_t len, struct archive_string_conv *sc)
4085 archive_string_empty(&(aes->aes_mbs));
4086 archive_wstring_empty(&(aes->aes_wcs));
4087 archive_string_empty(&(aes->aes_utf8));
4088 #if defined(_WIN32) && !defined(__CYGWIN__)
4090 * Internationalization programming on Windows must use Wide
4091 * characters because Windows platform cannot make locale UTF-8.
4094 if (archive_string_append(&(aes->aes_mbs),
4095 mbs, mbsnbytes(mbs, len)) == NULL) {
4099 aes->aes_set = AES_SET_MBS;
4102 #if defined(HAVE_ICONV)
4103 } else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4105 * This case happens only when MultiByteToWideChar() cannot
4106 * handle sc->from_cp, and we have to iconv in order to
4107 * translate character-set to wchar_t,UTF-16.
4109 iconv_t cd = sc->cd;
4114 * Translate multi-bytes from some character-set to UTF-8.
4117 r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
4123 aes->aes_set = AES_SET_UTF8;
4126 * Append the UTF-8 string into wstring.
4129 sc->flag &= ~(SCONV_NORMALIZATION_C
4130 | SCONV_TO_UTF16| SCONV_FROM_UTF16);
4131 from_cp = sc->from_cp;
4132 sc->from_cp = CP_UTF8;
4133 r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4134 aes->aes_utf8.s, aes->aes_utf8.length, sc);
4136 sc->from_cp = from_cp;
4138 aes->aes_set |= AES_SET_WCS;
4141 r = archive_wstring_append_from_mbs_in_codepage(
4142 &(aes->aes_wcs), mbs, len, sc);
4144 aes->aes_set = AES_SET_WCS;
4149 r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
4151 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4159 * The 'update' form tries to proactively update all forms of
4160 * this string (WCS and MBS) and returns an error if any of
4161 * them fail. This is used by the 'pax' handler, for instance,
4162 * to detect and report character-conversion failures early while
4163 * still allowing clients to get potentially useful values from
4164 * the more tolerant lazy conversions. (get_mbs and get_wcs will
4165 * strive to give the user something useful, so you can get hopefully
4166 * usable values even if some of the character conversions are failing.)
4169 archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4172 struct archive_string_conv *sc;
4177 return (0); /* Succeeded in clearing everything. */
4180 /* Save the UTF8 string. */
4181 archive_strcpy(&(aes->aes_utf8), utf8);
4183 /* Empty the mbs and wcs strings. */
4184 archive_string_empty(&(aes->aes_mbs));
4185 archive_wstring_empty(&(aes->aes_wcs));
4187 aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */
4189 /* Try converting UTF-8 to MBS, return false on failure. */
4190 sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4192 return (-1);/* Couldn't allocate memory for sc. */
4193 r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
4195 free_sconv_object(sc);
4198 aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4200 /* Try converting MBS to WCS, return false on failure. */
4201 if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4202 aes->aes_mbs.length))
4204 aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4206 /* All conversions succeeded. */