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)
217 wmemmove(as->s + as->length, p, s);
219 as->s[as->length] = 0;
223 struct archive_string *
224 archive_array_append(struct archive_string *as, const char *p, size_t s)
226 return archive_string_append(as, p, s);
230 archive_string_concat(struct archive_string *dest, struct archive_string *src)
232 if (archive_string_append(dest, src->s, src->length) == NULL)
233 __archive_errx(1, "Out of memory");
237 archive_wstring_concat(struct archive_wstring *dest,
238 struct archive_wstring *src)
240 if (archive_wstring_append(dest, src->s, src->length) == NULL)
241 __archive_errx(1, "Out of memory");
245 archive_string_free(struct archive_string *as)
248 as->buffer_length = 0;
254 archive_wstring_free(struct archive_wstring *as)
257 as->buffer_length = 0;
262 struct archive_wstring *
263 archive_wstring_ensure(struct archive_wstring *as, size_t s)
265 return (struct archive_wstring *)
266 archive_string_ensure((struct archive_string *)as,
267 s * sizeof(wchar_t));
270 /* Returns NULL on any allocation failure. */
271 struct archive_string *
272 archive_string_ensure(struct archive_string *as, size_t s)
277 /* If buffer is already big enough, don't reallocate. */
278 if (as->s && (s <= as->buffer_length))
282 * Growing the buffer at least exponentially ensures that
283 * append operations are always linear in the number of
284 * characters appended. Using a smaller growth rate for
285 * larger buffers reduces memory waste somewhat at the cost of
286 * a larger constant factor.
288 if (as->buffer_length < 32)
289 /* Start with a minimum 32-character buffer. */
291 else if (as->buffer_length < 8192)
292 /* Buffers under 8k are doubled for speed. */
293 new_length = as->buffer_length + as->buffer_length;
295 /* Buffers 8k and over grow by at least 25% each time. */
296 new_length = as->buffer_length + as->buffer_length / 4;
297 /* Be safe: If size wraps, fail. */
298 if (new_length < as->buffer_length) {
299 /* On failure, wipe the string and return NULL. */
300 archive_string_free(as);
301 errno = ENOMEM;/* Make sure errno has ENOMEM. */
306 * The computation above is a lower limit to how much we'll
307 * grow the buffer. In any case, we have to grow it enough to
312 /* Now we can reallocate the buffer. */
313 p = (char *)realloc(as->s, new_length);
315 /* On failure, wipe the string and return NULL. */
316 archive_string_free(as);
317 errno = ENOMEM;/* Make sure errno has ENOMEM. */
322 as->buffer_length = new_length;
327 * TODO: See if there's a way to avoid scanning
328 * the source string twice. Then test to see
329 * if it actually helps (remember that we're almost
330 * always called with pretty short arguments, so
331 * such an optimization might not help).
333 struct archive_string *
334 archive_strncat(struct archive_string *as, const void *_p, size_t n)
339 p = (const char *)_p;
341 /* Like strlen(p), except won't examine positions beyond p[n]. */
344 while (s < n && *pp) {
348 if ((as = archive_string_append(as, p, s)) == NULL)
349 __archive_errx(1, "Out of memory");
353 struct archive_wstring *
354 archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
359 /* Like strlen(p), except won't examine positions beyond p[n]. */
362 while (s < n && *pp) {
366 if ((as = archive_wstring_append(as, p, s)) == NULL)
367 __archive_errx(1, "Out of memory");
371 struct archive_string *
372 archive_strcat(struct archive_string *as, const void *p)
374 /* strcat is just strncat without an effective limit.
375 * Assert that we'll never get called with a source
377 * TODO: Review all uses of strcat in the source
378 * and try to replace them with strncat().
380 return archive_strncat(as, p, 0x1000000);
383 struct archive_wstring *
384 archive_wstrcat(struct archive_wstring *as, const wchar_t *p)
387 return archive_wstrncat(as, p, 0x1000000);
390 struct archive_string *
391 archive_strappend_char(struct archive_string *as, char c)
393 if ((as = archive_string_append(as, &c, 1)) == NULL)
394 __archive_errx(1, "Out of memory");
398 struct archive_wstring *
399 archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
401 if ((as = archive_wstring_append(as, &c, 1)) == NULL)
402 __archive_errx(1, "Out of memory");
407 * Get the "current character set" name to use with iconv.
408 * On FreeBSD, the empty character set name "" chooses
409 * the correct character encoding for the current locale,
410 * so this isn't necessary.
411 * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
412 * on that system, we have to explicitly call nl_langinfo()
413 * to get the right name. Not sure about other platforms.
415 * NOTE: GNU libiconv does not recognize the character-set name
416 * which some platform nl_langinfo(CODESET) returns, so we should
417 * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
420 default_iconv_charset(const char *charset) {
421 if (charset != NULL && charset[0] != '\0')
423 #if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
424 /* locale_charset() is broken on Mac OS */
425 return locale_charset();
426 #elif HAVE_NL_LANGINFO
427 return nl_langinfo(CODESET);
433 #if defined(_WIN32) && !defined(__CYGWIN__)
436 * Convert MBS to WCS.
437 * Note: returns -1 if conversion fails.
440 archive_wstring_append_from_mbs(struct archive_wstring *dest,
441 const char *p, size_t len)
443 return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
447 archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
448 const char *s, size_t length, struct archive_string_conv *sc)
454 from_cp = sc->from_cp;
456 from_cp = get_current_codepage();
458 if (from_cp == CP_C_LOCALE) {
460 * "C" locale special process.
463 const unsigned char *mp;
465 if (NULL == archive_wstring_ensure(dest,
466 dest->length + length + 1))
469 ws = dest->s + dest->length;
470 mp = (const unsigned char *)s;
472 while (count < (int)length && *mp) {
473 *ws++ = (wchar_t)*mp++;
476 } else if (sc != NULL &&
477 (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
479 * Normalize UTF-8 and UTF-16BE and convert it directly
480 * to UTF-16 as wchar_t.
482 struct archive_string u16;
483 int saved_flag = sc->flag;/* save current flag. */
486 sc->flag |= SCONV_TO_UTF16BE;
488 sc->flag |= SCONV_TO_UTF16LE;
490 if (sc->flag & SCONV_FROM_UTF16) {
492 * UTF-16BE/LE NFD ===> UTF-16 NFC
493 * UTF-16BE/LE NFC ===> UTF-16 NFD
495 count = (int)utf16nbytes(s, length);
498 * UTF-8 NFD ===> UTF-16 NFC
499 * UTF-8 NFC ===> UTF-16 NFD
501 count = (int)mbsnbytes(s, length);
503 u16.s = (char *)dest->s;
504 u16.length = dest->length << 1;;
505 u16.buffer_length = dest->buffer_length;
506 if (sc->flag & SCONV_NORMALIZATION_C)
507 ret = archive_string_normalize_C(&u16, s, count, sc);
509 ret = archive_string_normalize_D(&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 = (int)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, (const 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);
544 else if (sc->flag & SCONV_FROM_CHARSET) {
545 /* Do not trust the length which comes from
546 * an archive file. */
547 length = mbsnbytes(s, length);
550 mbflag = MB_PRECOMPOSED;
552 buffsize = dest->length + length + 1;
554 /* Allocate memory for WCS. */
555 if (NULL == archive_wstring_ensure(dest, buffsize))
557 /* Convert MBS to WCS. */
558 count = MultiByteToWideChar(from_cp,
559 mbflag, s, (int)length, dest->s + dest->length,
560 (int)(dest->buffer_length >> 1) -1);
562 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
563 /* Expand the WCS buffer. */
564 buffsize = dest->buffer_length << 1;
567 if (count == 0 && length != 0)
572 dest->length += count;
573 dest->s[dest->length] = L'\0';
580 * Convert MBS to WCS.
581 * Note: returns -1 if conversion fails.
584 archive_wstring_append_from_mbs(struct archive_wstring *dest,
585 const char *p, size_t len)
590 * No single byte will be more than one wide character,
591 * so this length estimate will always be big enough.
593 size_t wcs_length = len;
594 size_t mbs_length = len;
598 mbstate_t shift_state;
600 memset(&shift_state, 0, sizeof(shift_state));
602 if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))
604 wcs = dest->s + dest->length;
606 * We cannot use mbsrtowcs/mbstowcs here because those may convert
607 * extra MBS when strlen(p) > len and one wide character consists of
610 while (*mbs && mbs_length > 0) {
611 if (wcs_length == 0) {
612 dest->length = wcs - dest->s;
613 dest->s[dest->length] = L'\0';
614 wcs_length = mbs_length;
615 if (NULL == archive_wstring_ensure(dest,
616 dest->length + wcs_length + 1))
618 wcs = dest->s + dest->length;
621 r = mbrtowc(wcs, mbs, wcs_length, &shift_state);
623 r = mbtowc(wcs, mbs, wcs_length);
625 if (r == (size_t)-1 || r == (size_t)-2) {
627 if (errno == EILSEQ) {
634 if (r == 0 || r > mbs_length)
641 dest->length = wcs - dest->s;
642 dest->s[dest->length] = L'\0';
648 #if defined(_WIN32) && !defined(__CYGWIN__)
652 * Note: returns -1 if conversion fails.
654 * Win32 builds use WideCharToMultiByte from the Windows API.
655 * (Maybe Cygwin should too? WideCharToMultiByte will know a
656 * lot more about local character encodings than the wcrtomb()
657 * wrapper is going to know.)
660 archive_string_append_from_wcs(struct archive_string *as,
661 const wchar_t *w, size_t len)
663 return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
667 archive_string_append_from_wcs_in_codepage(struct archive_string *as,
668 const wchar_t *ws, size_t len, struct archive_string_conv *sc)
670 BOOL defchar_used, *dp;
673 int wslen = (int)len;
678 to_cp = get_current_codepage();
680 if (to_cp == CP_C_LOCALE) {
682 * "C" locale special process.
684 const wchar_t *wp = ws;
687 if (NULL == archive_string_ensure(as,
688 as->length + wslen +1))
690 p = as->s + as->length;
693 while (count < wslen && *wp) {
702 } else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
706 archive_string_ensure(as, as->length + len * 2 + 2))
708 u16 = (uint16_t *)(as->s + as->length);
711 if (sc->flag & SCONV_TO_UTF16BE) {
712 while (count < (int)len && *ws) {
713 archive_be16enc(u16+count, *ws);
718 while (count < (int)len && *ws) {
719 archive_le16enc(u16+count, *ws);
724 count <<= 1; /* to be byte size */
726 /* Make sure the MBS buffer has plenty to set. */
728 archive_string_ensure(as, as->length + len * 2 + 1))
732 if (to_cp == CP_UTF8 || sc == NULL)
736 count = WideCharToMultiByte(to_cp, 0, ws, wslen,
737 as->s + as->length, (int)as->buffer_length-1, NULL, dp);
739 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
740 /* Expand the MBS buffer and retry. */
741 if (NULL == archive_string_ensure(as,
742 as->buffer_length + len))
752 as->s[as->length] = '\0';
753 return (defchar_used?-1:ret);
756 #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
759 * Translates a wide character string into current locale character set
760 * and appends to the archive_string. Note: returns -1 if conversion
764 archive_string_append_from_wcs(struct archive_string *as,
765 const wchar_t *w, size_t len)
767 /* We cannot use the standard wcstombs() here because it
768 * cannot tell us how big the output buffer should be. So
769 * I've built a loop around wcrtomb() or wctomb() that
770 * converts a character at a time and resizes the string as
771 * needed. We prefer wcrtomb() when it's available because
772 * it's thread-safe. */
777 mbstate_t shift_state;
779 memset(&shift_state, 0, sizeof(shift_state));
781 /* Clear the shift state before starting. */
785 * Allocate buffer for MBS.
786 * We need this allocation here since it is possible that
787 * as->s is still NULL.
789 if (archive_string_ensure(as, as->length + len + 1) == NULL)
792 p = as->s + as->length;
793 end = as->s + as->buffer_length - MB_CUR_MAX -1;
794 while (*w != L'\0' && len > 0) {
796 as->length = p - as->s;
797 as->s[as->length] = '\0';
798 /* Re-allocate buffer for MBS. */
799 if (archive_string_ensure(as,
800 as->length + len * 2 + 1) == NULL)
802 p = as->s + as->length;
803 end = as->s + as->buffer_length - MB_CUR_MAX -1;
806 n = wcrtomb(p, *w++, &shift_state);
811 if (errno == EILSEQ) {
812 /* Skip an illegal wide char. */
823 as->length = p - as->s;
824 as->s[as->length] = '\0';
828 #else /* HAVE_WCTOMB || HAVE_WCRTOMB */
831 * TODO: Test if __STDC_ISO_10646__ is defined.
832 * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
833 * one character at a time. If a non-Windows platform doesn't have
834 * either of these, fall back to the built-in UTF8 conversion.
837 archive_string_append_from_wcs(struct archive_string *as,
838 const wchar_t *w, size_t len)
840 (void)as;/* UNUSED */
842 (void)len;/* UNUSED */
847 #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
850 * Find a string conversion object by a pair of 'from' charset name
851 * and 'to' charset name from an archive object.
852 * Return NULL if not found.
854 static struct archive_string_conv *
855 find_sconv_object(struct archive *a, const char *fc, const char *tc)
857 struct archive_string_conv *sc;
862 for (sc = a->sconv; sc != NULL; sc = sc->next) {
863 if (strcmp(sc->from_charset, fc) == 0 &&
864 strcmp(sc->to_charset, tc) == 0)
871 * Register a string object to an archive object.
874 add_sconv_object(struct archive *a, struct archive_string_conv *sc)
876 struct archive_string_conv **psc;
878 /* Add a new sconv to sconv list. */
881 psc = &((*psc)->next);
886 add_converter(struct archive_string_conv *sc, int (*converter)
887 (struct archive_string *, const void *, size_t,
888 struct archive_string_conv *))
890 if (sc == NULL || sc->nconverter >= 2)
891 __archive_errx(1, "Programing error");
892 sc->converter[sc->nconverter++] = converter;
896 setup_converter(struct archive_string_conv *sc)
903 * Perform special sequence for the incorrect UTF-8 filenames
904 * made by libarchive2.x.
906 if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
907 add_converter(sc, strncat_from_utf8_libarchive2);
912 * Convert a string to UTF-16BE/LE.
914 if (sc->flag & SCONV_TO_UTF16) {
916 * If the current locale is UTF-8, we can translate
917 * a UTF-8 string into a UTF-16BE string.
919 if (sc->flag & SCONV_FROM_UTF8) {
920 add_converter(sc, archive_string_append_unicode);
924 #if defined(_WIN32) && !defined(__CYGWIN__)
925 if (sc->flag & SCONV_WIN_CP) {
926 if (sc->flag & SCONV_TO_UTF16BE)
927 add_converter(sc, win_strncat_to_utf16be);
929 add_converter(sc, win_strncat_to_utf16le);
934 #if defined(HAVE_ICONV)
935 if (sc->cd != (iconv_t)-1) {
936 add_converter(sc, iconv_strncat_in_locale);
941 if (sc->flag & SCONV_BEST_EFFORT) {
942 if (sc->flag & SCONV_TO_UTF16BE)
944 best_effort_strncat_to_utf16be);
947 best_effort_strncat_to_utf16le);
949 /* Make sure we have no converter. */
955 * Convert a string from UTF-16BE/LE.
957 if (sc->flag & SCONV_FROM_UTF16) {
959 * At least we should normalize a UTF-16BE string.
961 if (sc->flag & SCONV_NORMALIZATION_D)
962 add_converter(sc,archive_string_normalize_D);
963 else if (sc->flag & SCONV_NORMALIZATION_C)
964 add_converter(sc, archive_string_normalize_C);
966 if (sc->flag & SCONV_TO_UTF8) {
968 * If the current locale is UTF-8, we can translate
969 * a UTF-16BE/LE string into a UTF-8 string directly.
972 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
974 archive_string_append_unicode);
978 #if defined(_WIN32) && !defined(__CYGWIN__)
979 if (sc->flag & SCONV_WIN_CP) {
980 if (sc->flag & SCONV_FROM_UTF16BE)
981 add_converter(sc, win_strncat_from_utf16be);
983 add_converter(sc, win_strncat_from_utf16le);
988 #if defined(HAVE_ICONV)
989 if (sc->cd != (iconv_t)-1) {
990 add_converter(sc, iconv_strncat_in_locale);
995 if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
996 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
997 add_converter(sc, best_effort_strncat_from_utf16be);
998 else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
999 == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1000 add_converter(sc, best_effort_strncat_from_utf16le);
1002 /* Make sure we have no converter. */
1007 if (sc->flag & SCONV_FROM_UTF8) {
1009 * At least we should normalize a UTF-8 string.
1011 if (sc->flag & SCONV_NORMALIZATION_D)
1012 add_converter(sc,archive_string_normalize_D);
1013 else if (sc->flag & SCONV_NORMALIZATION_C)
1014 add_converter(sc, archive_string_normalize_C);
1017 * Copy UTF-8 string with a check of CESU-8.
1018 * Apparently, iconv does not check surrogate pairs in UTF-8
1019 * when both from-charset and to-charset are UTF-8, and then
1020 * we use our UTF-8 copy code.
1022 if (sc->flag & SCONV_TO_UTF8) {
1024 * If the current locale is UTF-8, we can translate
1025 * a UTF-16BE string into a UTF-8 string directly.
1028 (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1029 add_converter(sc, strncat_from_utf8_to_utf8);
1034 #if defined(_WIN32) && !defined(__CYGWIN__)
1036 * On Windows we can use Windows API for a string conversion.
1038 if (sc->flag & SCONV_WIN_CP) {
1039 add_converter(sc, strncat_in_codepage);
1045 if (sc->cd != (iconv_t)-1) {
1046 add_converter(sc, iconv_strncat_in_locale);
1048 * iconv generally does not support UTF-8-MAC and so
1049 * we have to the output of iconv from NFC to NFD if
1052 if ((sc->flag & SCONV_FROM_CHARSET) &&
1053 (sc->flag & SCONV_TO_UTF8)) {
1054 if (sc->flag & SCONV_NORMALIZATION_D)
1055 add_converter(sc, archive_string_normalize_D);
1062 * Try conversion in the best effort or no conversion.
1064 if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
1065 add_converter(sc, best_effort_strncat_in_locale);
1067 /* Make sure we have no converter. */
1072 * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
1073 * and CP932 which are referenced in create_sconv_object().
1076 canonical_charset_name(const char *charset)
1082 if (charset == NULL || charset[0] == '\0'
1083 || strlen(charset) > 15)
1086 /* Copy name to uppercase. */
1091 if (c >= 'a' && c <= 'z')
1097 if (strcmp(cs, "UTF-8") == 0 ||
1098 strcmp(cs, "UTF8") == 0)
1100 if (strcmp(cs, "UTF-16BE") == 0 ||
1101 strcmp(cs, "UTF16BE") == 0)
1102 return ("UTF-16BE");
1103 if (strcmp(cs, "UTF-16LE") == 0 ||
1104 strcmp(cs, "UTF16LE") == 0)
1105 return ("UTF-16LE");
1106 if (strcmp(cs, "CP932") == 0)
1112 * Create a string conversion object.
1114 static struct archive_string_conv *
1115 create_sconv_object(const char *fc, const char *tc,
1116 unsigned current_codepage, int flag)
1118 struct archive_string_conv *sc;
1120 sc = calloc(1, sizeof(*sc));
1124 sc->from_charset = strdup(fc);
1125 if (sc->from_charset == NULL) {
1129 sc->to_charset = strdup(tc);
1130 if (sc->to_charset == NULL) {
1131 free(sc->from_charset);
1135 archive_string_init(&sc->utftmp);
1137 if (flag & SCONV_TO_CHARSET) {
1139 * Convert characters from the current locale charset to
1140 * a specified charset.
1142 sc->from_cp = current_codepage;
1143 sc->to_cp = make_codepage_from_charset(tc);
1144 #if defined(_WIN32) && !defined(__CYGWIN__)
1145 if (IsValidCodePage(sc->to_cp))
1146 flag |= SCONV_WIN_CP;
1148 } else if (flag & SCONV_FROM_CHARSET) {
1150 * Convert characters from a specified charset to
1151 * the current locale charset.
1153 sc->to_cp = current_codepage;
1154 sc->from_cp = make_codepage_from_charset(fc);
1155 #if defined(_WIN32) && !defined(__CYGWIN__)
1156 if (IsValidCodePage(sc->from_cp))
1157 flag |= SCONV_WIN_CP;
1162 * Check if "from charset" and "to charset" are the same.
1164 if (strcmp(fc, tc) == 0 ||
1165 (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
1171 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
1173 if (strcmp(tc, "UTF-8") == 0)
1174 flag |= SCONV_TO_UTF8;
1175 else if (strcmp(tc, "UTF-16BE") == 0)
1176 flag |= SCONV_TO_UTF16BE;
1177 else if (strcmp(tc, "UTF-16LE") == 0)
1178 flag |= SCONV_TO_UTF16LE;
1179 if (strcmp(fc, "UTF-8") == 0)
1180 flag |= SCONV_FROM_UTF8;
1181 else if (strcmp(fc, "UTF-16BE") == 0)
1182 flag |= SCONV_FROM_UTF16BE;
1183 else if (strcmp(fc, "UTF-16LE") == 0)
1184 flag |= SCONV_FROM_UTF16LE;
1185 #if defined(_WIN32) && !defined(__CYGWIN__)
1186 if (sc->to_cp == CP_UTF8)
1187 flag |= SCONV_TO_UTF8;
1188 else if (sc->to_cp == CP_UTF16BE)
1189 flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
1190 else if (sc->to_cp == CP_UTF16LE)
1191 flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
1192 if (sc->from_cp == CP_UTF8)
1193 flag |= SCONV_FROM_UTF8;
1194 else if (sc->from_cp == CP_UTF16BE)
1195 flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
1196 else if (sc->from_cp == CP_UTF16LE)
1197 flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
1201 * Set a flag for Unicode NFD. Usually iconv cannot correctly
1202 * handle it. So we have to translate NFD characters to NFC ones
1203 * ourselves before iconv handles. Another reason is to prevent
1204 * that the same sight of two filenames, one is NFC and other
1205 * is NFD, would be in its directory.
1206 * On Mac OS X, although its filesystem layer automatically
1207 * convert filenames to NFD, it would be useful for filename
1208 * comparing to find out the same filenames that we normalize
1209 * that to be NFD ourselves.
1211 if ((flag & SCONV_FROM_CHARSET) &&
1212 (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
1213 #if defined(__APPLE__)
1214 if (flag & SCONV_TO_UTF8)
1215 flag |= SCONV_NORMALIZATION_D;
1218 flag |= SCONV_NORMALIZATION_C;
1220 #if defined(__APPLE__)
1222 * In case writing an archive file, make sure that a filename
1223 * going to be passed to iconv is a Unicode NFC string since
1224 * a filename in HFS Plus filesystem is a Unicode NFD one and
1225 * iconv cannot handle it with "UTF-8" charset. It is simpler
1226 * than a use of "UTF-8-MAC" charset.
1228 if ((flag & SCONV_TO_CHARSET) &&
1229 (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1230 !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1231 flag |= SCONV_NORMALIZATION_C;
1233 * In case reading an archive file. make sure that a filename
1234 * will be passed to users is a Unicode NFD string in order to
1235 * correctly compare the filename with other one which comes
1236 * from HFS Plus filesystem.
1238 if ((flag & SCONV_FROM_CHARSET) &&
1239 !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1240 (flag & SCONV_TO_UTF8))
1241 flag |= SCONV_NORMALIZATION_D;
1244 #if defined(HAVE_ICONV)
1245 sc->cd_w = (iconv_t)-1;
1247 * Create an iconv object.
1249 if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
1250 (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
1251 (flag & SCONV_WIN_CP)) {
1252 /* This case we won't use iconv. */
1253 sc->cd = (iconv_t)-1;
1255 sc->cd = iconv_open(tc, fc);
1256 if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
1258 * Unfortunately, all of iconv implements do support
1259 * "CP932" character-set, so we should use "SJIS"
1260 * instead if iconv_open failed.
1262 if (strcmp(tc, "CP932") == 0)
1263 sc->cd = iconv_open("SJIS", fc);
1264 else if (strcmp(fc, "CP932") == 0)
1265 sc->cd = iconv_open(tc, "SJIS");
1267 #if defined(_WIN32) && !defined(__CYGWIN__)
1269 * archive_mstring on Windows directly convert multi-bytes
1270 * into archive_wstring in order not to depend on locale
1271 * so that you can do a I18N programming. This will be
1272 * used only in archive_mstring_copy_mbs_len_l so far.
1274 if (flag & SCONV_FROM_CHARSET) {
1275 sc->cd_w = iconv_open("UTF-8", fc);
1276 if (sc->cd_w == (iconv_t)-1 &&
1277 (sc->flag & SCONV_BEST_EFFORT)) {
1278 if (strcmp(fc, "CP932") == 0)
1279 sc->cd_w = iconv_open("UTF-8", "SJIS");
1282 #endif /* _WIN32 && !__CYGWIN__ */
1284 #endif /* HAVE_ICONV */
1289 * Set up converters.
1291 setup_converter(sc);
1297 * Free a string conversion object.
1300 free_sconv_object(struct archive_string_conv *sc)
1302 free(sc->from_charset);
1303 free(sc->to_charset);
1304 archive_string_free(&sc->utftmp);
1306 if (sc->cd != (iconv_t)-1)
1307 iconv_close(sc->cd);
1308 if (sc->cd_w != (iconv_t)-1)
1309 iconv_close(sc->cd_w);
1314 #if defined(_WIN32) && !defined(__CYGWIN__)
1316 my_atoi(const char *p)
1322 if (*p >= '0' && *p <= '9')
1323 cp = cp * 10 + (*p - '0');
1332 * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
1333 * Return -1 if failed.
1335 * Note: This translation code may be insufficient.
1337 static struct charset {
1341 /* MUST BE SORTED! */
1360 {"HZ-GB-2312", 52936},
1378 {"ISO-8859-1", 28591},
1379 {"ISO-8859-13", 28603},
1380 {"ISO-8859-15", 28605},
1381 {"ISO-8859-2", 28592},
1382 {"ISO-8859-3", 28593},
1383 {"ISO-8859-4", 28594},
1384 {"ISO-8859-5", 28595},
1385 {"ISO-8859-6", 28596},
1386 {"ISO-8859-7", 28597},
1387 {"ISO-8859-8", 28598},
1388 {"ISO-8859-9", 28599},
1389 {"ISO8859-1", 28591},
1390 {"ISO8859-13", 28603},
1391 {"ISO8859-15", 28605},
1392 {"ISO8859-2", 28592},
1393 {"ISO8859-3", 28593},
1394 {"ISO8859-4", 28594},
1395 {"ISO8859-5", 28595},
1396 {"ISO8859-6", 28596},
1397 {"ISO8859-7", 28597},
1398 {"ISO8859-8", 28598},
1399 {"ISO8859-9", 28599},
1403 {"KS_C_5601-1987", 949},
1406 {"MACINTOSH", 10000},
1416 {"X-EUROPA", 29001},
1417 {"X-MAC-ARABIC", 10004},
1418 {"X-MAC-CE", 10029},
1419 {"X-MAC-CHINESEIMP", 10008},
1420 {"X-MAC-CHINESETRAD", 10002},
1421 {"X-MAC-CROATIAN", 10082},
1422 {"X-MAC-CYRILLIC", 10007},
1423 {"X-MAC-GREEK", 10006},
1424 {"X-MAC-HEBREW", 10005},
1425 {"X-MAC-ICELANDIC", 10079},
1426 {"X-MAC-JAPANESE", 10001},
1427 {"X-MAC-KOREAN", 10003},
1428 {"X-MAC-ROMANIAN", 10010},
1429 {"X-MAC-THAI", 10021},
1430 {"X-MAC-TURKISH", 10081},
1431 {"X-MAC-UKRAINIAN", 10017},
1434 make_codepage_from_charset(const char *charset)
1441 if (charset == NULL || strlen(charset) > 15)
1444 /* Copy name to uppercase. */
1447 char c = *charset++;
1448 if (c >= 'a' && c <= 'z')
1455 /* Look it up in the table first, so that we can easily
1456 * override CP367, which we map to 1252 instead of 367. */
1458 b = sizeof(charsets)/sizeof(charsets[0]);
1460 int c = (b + a) / 2;
1461 int r = strcmp(charsets[c].name, cs);
1467 return charsets[c].cp;
1470 /* If it's not in the table, try to parse it. */
1473 if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
1474 cp = my_atoi(cs + 2);
1475 } else if (strcmp(cs, "CP_ACP") == 0)
1476 cp = get_current_codepage();
1477 else if (strcmp(cs, "CP_OEMCP") == 0)
1478 cp = get_current_oemcp();
1481 if (cs[1] == 'B' && cs[2] == 'M' &&
1482 cs[3] >= '0' && cs[3] <= '9') {
1483 cp = my_atoi(cs + 3);
1487 if (strncmp(cs, "WINDOWS-", 8) == 0) {
1488 cp = my_atoi(cs + 8);
1489 if (cp != 874 && (cp < 1250 || cp > 1258))
1490 cp = -1;/* This may invalid code. */
1498 * Return ANSI Code Page of current locale set by setlocale().
1501 get_current_codepage(void)
1506 locale = setlocale(LC_CTYPE, NULL);
1509 if (locale[0] == 'C' && locale[1] == '\0')
1510 return (CP_C_LOCALE);
1511 p = strrchr(locale, '.');
1521 * Translation table between Locale Name and ACP/OEMCP.
1528 { 950, 950, "Chinese_Taiwan" },
1529 { 936, 936, "Chinese_People's Republic of China" },
1530 { 950, 950, "Chinese_Taiwan" },
1531 { 1250, 852, "Czech_Czech Republic" },
1532 { 1252, 850, "Danish_Denmark" },
1533 { 1252, 850, "Dutch_Netherlands" },
1534 { 1252, 850, "Dutch_Belgium" },
1535 { 1252, 437, "English_United States" },
1536 { 1252, 850, "English_Australia" },
1537 { 1252, 850, "English_Canada" },
1538 { 1252, 850, "English_New Zealand" },
1539 { 1252, 850, "English_United Kingdom" },
1540 { 1252, 437, "English_United States" },
1541 { 1252, 850, "Finnish_Finland" },
1542 { 1252, 850, "French_France" },
1543 { 1252, 850, "French_Belgium" },
1544 { 1252, 850, "French_Canada" },
1545 { 1252, 850, "French_Switzerland" },
1546 { 1252, 850, "German_Germany" },
1547 { 1252, 850, "German_Austria" },
1548 { 1252, 850, "German_Switzerland" },
1549 { 1253, 737, "Greek_Greece" },
1550 { 1250, 852, "Hungarian_Hungary" },
1551 { 1252, 850, "Icelandic_Iceland" },
1552 { 1252, 850, "Italian_Italy" },
1553 { 1252, 850, "Italian_Switzerland" },
1554 { 932, 932, "Japanese_Japan" },
1555 { 949, 949, "Korean_Korea" },
1556 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1557 { 1252, 850, "Norwegian (BokmOl)_Norway" },
1558 { 1252, 850, "Norwegian-Nynorsk_Norway" },
1559 { 1250, 852, "Polish_Poland" },
1560 { 1252, 850, "Portuguese_Portugal" },
1561 { 1252, 850, "Portuguese_Brazil" },
1562 { 1251, 866, "Russian_Russia" },
1563 { 1250, 852, "Slovak_Slovakia" },
1564 { 1252, 850, "Spanish_Spain" },
1565 { 1252, 850, "Spanish_Mexico" },
1566 { 1252, 850, "Spanish_Spain" },
1567 { 1252, 850, "Swedish_Sweden" },
1568 { 1254, 857, "Turkish_Turkey" },
1573 * Return OEM Code Page of current locale set by setlocale().
1576 get_current_oemcp(void)
1582 locale = setlocale(LC_CTYPE, NULL);
1584 return (GetOEMCP());
1585 if (locale[0] == 'C' && locale[1] == '\0')
1586 return (CP_C_LOCALE);
1588 p = strrchr(locale, '.');
1590 return (GetOEMCP());
1592 for (i = 0; acp_ocp_map[i].acp; i++) {
1593 if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
1594 return (acp_ocp_map[i].ocp);
1596 return (GetOEMCP());
1601 * POSIX platform does not use CodePage.
1605 get_current_codepage(void)
1607 return (-1);/* Unknown */
1610 make_codepage_from_charset(const char *charset)
1612 (void)charset; /* UNUSED */
1613 return (-1);/* Unknown */
1616 get_current_oemcp(void)
1618 return (-1);/* Unknown */
1621 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1624 * Return a string conversion object.
1626 static struct archive_string_conv *
1627 get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
1629 struct archive_string_conv *sc;
1630 unsigned current_codepage;
1632 /* Check if we have made the sconv object. */
1633 sc = find_sconv_object(a, fc, tc);
1638 current_codepage = get_current_codepage();
1640 current_codepage = a->current_codepage;
1642 sc = create_sconv_object(canonical_charset_name(fc),
1643 canonical_charset_name(tc), current_codepage, flag);
1646 archive_set_error(a, ENOMEM,
1647 "Could not allocate memory for "
1648 "a string conversion object");
1653 * If there is no converter for current string conversion object,
1654 * we cannot handle this conversion.
1656 if (sc->nconverter == 0) {
1659 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1660 "iconv_open failed : Cannot handle ``%s''",
1661 (flag & SCONV_TO_CHARSET)?tc:fc);
1663 archive_set_error(a, ARCHIVE_ERRNO_MISC,
1664 "A character-set conversion not fully supported "
1665 "on this platform");
1668 /* Failed; free a sconv object. */
1669 free_sconv_object(sc);
1677 add_sconv_object(a, sc);
1682 get_current_charset(struct archive *a)
1684 const char *cur_charset;
1687 cur_charset = default_iconv_charset("");
1689 cur_charset = default_iconv_charset(a->current_code);
1690 if (a->current_code == NULL) {
1691 a->current_code = strdup(cur_charset);
1692 a->current_codepage = get_current_codepage();
1693 a->current_oemcp = get_current_oemcp();
1696 return (cur_charset);
1700 * Make and Return a string conversion object.
1701 * Return NULL if the platform does not support the specified conversion
1702 * and best_effort is 0.
1703 * If best_effort is set, A string conversion object must be returned
1704 * unless memory allocation for the object fails, but the conversion
1705 * might fail when non-ASCII code is found.
1707 struct archive_string_conv *
1708 archive_string_conversion_to_charset(struct archive *a, const char *charset,
1711 int flag = SCONV_TO_CHARSET;
1714 flag |= SCONV_BEST_EFFORT;
1715 return (get_sconv_object(a, get_current_charset(a), charset, flag));
1718 struct archive_string_conv *
1719 archive_string_conversion_from_charset(struct archive *a, const char *charset,
1722 int flag = SCONV_FROM_CHARSET;
1725 flag |= SCONV_BEST_EFFORT;
1726 return (get_sconv_object(a, charset, get_current_charset(a), flag));
1730 * archive_string_default_conversion_*_archive() are provided for Windows
1731 * platform because other archiver application use CP_OEMCP for
1732 * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
1733 * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
1734 * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
1735 * So we should make a string conversion between CP_ACP and CP_OEMCP
1736 * for compatibility.
1738 #if defined(_WIN32) && !defined(__CYGWIN__)
1739 struct archive_string_conv *
1740 archive_string_default_conversion_for_read(struct archive *a)
1742 const char *cur_charset = get_current_charset(a);
1745 /* NOTE: a check of cur_charset is unneeded but we need
1746 * that get_current_charset() has been surely called at
1747 * this time whatever C compiler optimized. */
1748 if (cur_charset != NULL &&
1749 (a->current_codepage == CP_C_LOCALE ||
1750 a->current_codepage == a->current_oemcp))
1751 return (NULL);/* no conversion. */
1753 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1754 /* Make sure a null termination must be set. */
1755 oemcp[sizeof(oemcp)-1] = '\0';
1756 return (get_sconv_object(a, oemcp, cur_charset,
1757 SCONV_FROM_CHARSET));
1760 struct archive_string_conv *
1761 archive_string_default_conversion_for_write(struct archive *a)
1763 const char *cur_charset = get_current_charset(a);
1766 /* NOTE: a check of cur_charset is unneeded but we need
1767 * that get_current_charset() has been surely called at
1768 * this time whatever C compiler optimized. */
1769 if (cur_charset != NULL &&
1770 (a->current_codepage == CP_C_LOCALE ||
1771 a->current_codepage == a->current_oemcp))
1772 return (NULL);/* no conversion. */
1774 _snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1775 /* Make sure a null termination must be set. */
1776 oemcp[sizeof(oemcp)-1] = '\0';
1777 return (get_sconv_object(a, cur_charset, oemcp,
1781 struct archive_string_conv *
1782 archive_string_default_conversion_for_read(struct archive *a)
1784 (void)a; /* UNUSED */
1788 struct archive_string_conv *
1789 archive_string_default_conversion_for_write(struct archive *a)
1791 (void)a; /* UNUSED */
1797 * Dispose of all character conversion objects in the archive object.
1800 archive_string_conversion_free(struct archive *a)
1802 struct archive_string_conv *sc;
1803 struct archive_string_conv *sc_next;
1805 for (sc = a->sconv; sc != NULL; sc = sc_next) {
1807 free_sconv_object(sc);
1810 free(a->current_code);
1811 a->current_code = NULL;
1815 * Return a conversion charset name.
1818 archive_string_conversion_charset_name(struct archive_string_conv *sc)
1820 if (sc->flag & SCONV_TO_CHARSET)
1821 return (sc->to_charset);
1823 return (sc->from_charset);
1827 * Change the behavior of a string conversion.
1830 archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
1834 * A filename in UTF-8 was made with libarchive 2.x in a wrong
1835 * assumption that wchar_t was Unicode.
1836 * This option enables simulating the assumption in order to read
1837 * that filename correctly.
1839 case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
1840 #if (defined(_WIN32) && !defined(__CYGWIN__)) \
1841 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
1843 * Nothing to do for it since wchar_t on these platforms
1844 * is really Unicode.
1846 (void)sc; /* UNUSED */
1848 if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
1849 sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
1850 /* Set up string converters. */
1851 setup_converter(sc);
1855 case SCONV_SET_OPT_NORMALIZATION_C:
1856 if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
1857 sc->flag |= SCONV_NORMALIZATION_C;
1858 sc->flag &= ~SCONV_NORMALIZATION_D;
1859 /* Set up string converters. */
1860 setup_converter(sc);
1863 case SCONV_SET_OPT_NORMALIZATION_D:
1864 #if defined(HAVE_ICONV)
1866 * If iconv will take the string, do not change the
1867 * setting of the normalization.
1869 if (!(sc->flag & SCONV_WIN_CP) &&
1870 (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1871 !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1874 if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
1875 sc->flag |= SCONV_NORMALIZATION_D;
1876 sc->flag &= ~SCONV_NORMALIZATION_C;
1877 /* Set up string converters. */
1878 setup_converter(sc);
1888 * Copy one archive_string to another in locale conversion.
1890 * archive_strncat_l();
1891 * archive_strncpy_l();
1896 mbsnbytes(const void *_p, size_t n)
1903 p = (const char *)_p;
1905 /* Like strlen(p), except won't examine positions beyond p[n]. */
1908 while (s < n && *pp) {
1916 utf16nbytes(const void *_p, size_t n)
1923 p = (const char *)_p;
1925 /* Like strlen(p), except won't examine positions beyond p[n]. */
1929 while (s < n && (pp[0] || pp[1])) {
1937 archive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
1938 struct archive_string_conv *sc)
1941 return (archive_strncat_l(as, _p, n, sc));
1945 archive_strncat_l(struct archive_string *as, const void *_p, size_t n,
1946 struct archive_string_conv *sc)
1952 if (_p != NULL && n > 0) {
1953 if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
1954 length = utf16nbytes(_p, n);
1956 length = mbsnbytes(_p, n);
1959 /* We must allocate memory even if there is no data for conversion
1960 * or copy. This simulates archive_string_append behavior. */
1963 if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
1965 if (archive_string_ensure(as, as->length + tn) == NULL)
1967 as->s[as->length] = 0;
1969 as->s[as->length+1] = 0;
1974 * If sc is NULL, we just make a copy.
1977 if (archive_string_append(as, _p, length) == NULL)
1978 return (-1);/* No memory */
1984 if (sc->nconverter > 1) {
1985 sc->utftmp.length = 0;
1986 r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
1987 if (r2 != 0 && errno == ENOMEM)
1992 length = sc->utftmp.length;
1995 r2 = sc->converter[i](as, s, length, sc);
2004 * Return -1 if conversion fails.
2007 iconv_strncat_in_locale(struct archive_string *as, const void *_p,
2008 size_t length, struct archive_string_conv *sc)
2010 ICONV_CONST char *itp;
2015 int return_value = 0; /* success */
2016 int to_size, from_size;
2018 if (sc->flag & SCONV_TO_UTF16)
2022 if (sc->flag & SCONV_FROM_UTF16)
2027 if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2031 itp = (char *)(uintptr_t)_p;
2033 outp = as->s + as->length;
2034 avail = as->buffer_length - as->length - to_size;
2035 while (remaining >= (size_t)from_size) {
2036 size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
2038 if (result != (size_t)-1)
2039 break; /* Conversion completed. */
2041 if (errno == EILSEQ || errno == EINVAL) {
2043 * If an output charset is UTF-8 or UTF-16BE/LE,
2044 * unknown character should be U+FFFD
2045 * (replacement character).
2047 if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2049 if (sc->flag & SCONV_TO_UTF8)
2050 rbytes = sizeof(utf8_replacement_char);
2054 if (avail < rbytes) {
2055 as->length = outp - as->s;
2056 bs = as->buffer_length +
2057 (remaining * to_size) + rbytes;
2059 archive_string_ensure(as, bs))
2061 outp = as->s + as->length;
2062 avail = as->buffer_length
2063 - as->length - to_size;
2065 if (sc->flag & SCONV_TO_UTF8)
2066 memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
2067 else if (sc->flag & SCONV_TO_UTF16BE)
2068 archive_be16enc(outp, UNICODE_R_CHAR);
2070 archive_le16enc(outp, UNICODE_R_CHAR);
2074 /* Skip the illegal input bytes. */
2079 remaining -= from_size;
2080 return_value = -1; /* failure */
2082 /* E2BIG no output buffer,
2083 * Increase an output buffer. */
2084 as->length = outp - as->s;
2085 bs = as->buffer_length + remaining * 2;
2086 if (NULL == archive_string_ensure(as, bs))
2088 outp = as->s + as->length;
2089 avail = as->buffer_length - as->length - to_size;
2092 as->length = outp - as->s;
2093 as->s[as->length] = 0;
2095 as->s[as->length+1] = 0;
2096 return (return_value);
2099 #endif /* HAVE_ICONV */
2102 #if defined(_WIN32) && !defined(__CYGWIN__)
2105 * Translate a string from a some CodePage to an another CodePage by
2106 * Windows APIs, and copy the result. Return -1 if conversion fails.
2109 strncat_in_codepage(struct archive_string *as,
2110 const void *_p, size_t length, struct archive_string_conv *sc)
2112 const char *s = (const char *)_p;
2113 struct archive_wstring aws;
2117 archive_string_init(&aws);
2118 saved_flag = sc->flag;
2119 sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2120 r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2121 sc->flag = saved_flag;
2123 archive_wstring_free(&aws);
2124 if (errno != ENOMEM)
2125 archive_string_append(as, s, length);
2130 r = archive_string_append_from_wcs_in_codepage(
2131 as, aws.s, aws.length, sc);
2132 if (r != 0 && errno != ENOMEM && l == as->length)
2133 archive_string_append(as, s, length);
2134 archive_wstring_free(&aws);
2139 * Test whether MBS ==> WCS is okay.
2142 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2144 const char *p = (const char *)_p;
2146 DWORD mbflag = MB_ERR_INVALID_CHARS;
2148 if (sc->flag & SCONV_FROM_CHARSET)
2149 codepage = sc->to_cp;
2151 codepage = sc->from_cp;
2153 if (codepage == CP_C_LOCALE)
2155 if (codepage != CP_UTF8)
2156 mbflag |= MB_PRECOMPOSED;
2158 if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
2159 return (-1); /* Invalid */
2160 return (0); /* Okay */
2166 * Test whether MBS ==> WCS is okay.
2169 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2171 const char *p = (const char *)_p;
2175 mbstate_t shift_state;
2177 memset(&shift_state, 0, sizeof(shift_state));
2179 /* Clear the shift state before starting. */
2180 mbtowc(NULL, NULL, 0);
2186 r = mbrtowc(&wc, p, n, &shift_state);
2188 r = mbtowc(&wc, p, n);
2190 if (r == (size_t)-1 || r == (size_t)-2)
2191 return (-1);/* Invalid. */
2197 (void)sc; /* UNUSED */
2198 return (0); /* All Okey. */
2201 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2204 * Basically returns -1 because we cannot make a conversion of charset
2205 * without iconv but in some cases this would return 0.
2206 * Returns 0 if all copied characters are ASCII.
2207 * Returns 0 if both from-locale and to-locale are the same and those
2208 * can be WCS with no error.
2211 best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2212 size_t length, struct archive_string_conv *sc)
2216 int return_value = 0; /* success */
2219 * If both from-locale and to-locale is the same, this makes a copy.
2220 * And then this checks all copied MBS can be WCS if so returns 0.
2223 if (archive_string_append(as, _p, length) == NULL)
2224 return (-1);/* No memory */
2225 return (invalid_mbs(_p, length, sc));
2229 * If a character is ASCII, this just copies it. If not, this
2230 * assigns '?' character instead but in UTF-8 locale this assigns
2231 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2232 * a Replacement Character in Unicode.
2236 itp = (const uint8_t *)_p;
2237 while (*itp && remaining > 0) {
2239 // Non-ASCII: Substitute with suitable replacement
2240 if (sc->flag & SCONV_TO_UTF8) {
2241 if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
2242 __archive_errx(1, "Out of memory");
2245 archive_strappend_char(as, '?');
2249 archive_strappend_char(as, *itp);
2253 return (return_value);
2258 * Unicode conversion functions.
2259 * - UTF-8 <===> UTF-8 in removing surrogate pairs.
2260 * - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2261 * - UTF-8 made by libarchive 2.x ===> UTF-8.
2262 * - UTF-16BE <===> UTF-8.
2267 * Utility to convert a single UTF-8 sequence.
2269 * Usually return used bytes, return used byte in negative value when
2270 * a unicode character is replaced with U+FFFD.
2271 * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2272 * Recommended Practice for Replacement Characters.
2275 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2277 static const char utf8_count[256] = {
2278 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2279 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2280 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2281 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2282 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2283 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2284 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2285 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2286 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2287 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2288 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2289 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2290 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2291 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2292 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2293 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2303 * Decode 1-4 bytes depending on the value of the first byte.
2305 ch = (unsigned char)*s;
2307 return (0); /* Standard: return 0 for end-of-string. */
2308 cnt = utf8_count[ch];
2310 /* Invalid sequence or there are not plenty bytes. */
2313 for (i = 1; i < cnt; i++) {
2314 if ((s[i] & 0xc0) != 0x80) {
2319 goto invalid_sequence;
2322 /* Make a Unicode code point from a single UTF-8 sequence. */
2324 case 1: /* 1 byte sequence. */
2327 case 2: /* 2 bytes sequence. */
2328 if ((s[1] & 0xc0) != 0x80) {
2330 goto invalid_sequence;
2332 *pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2334 case 3: /* 3 bytes sequence. */
2335 if ((s[1] & 0xc0) != 0x80) {
2337 goto invalid_sequence;
2339 if ((s[2] & 0xc0) != 0x80) {
2341 goto invalid_sequence;
2343 wc = ((ch & 0x0f) << 12)
2344 | ((s[1] & 0x3f) << 6)
2347 goto invalid_sequence;/* Overlong sequence. */
2349 case 4: /* 4 bytes sequence. */
2350 if ((s[1] & 0xc0) != 0x80) {
2352 goto invalid_sequence;
2354 if ((s[2] & 0xc0) != 0x80) {
2356 goto invalid_sequence;
2358 if ((s[3] & 0xc0) != 0x80) {
2360 goto invalid_sequence;
2362 wc = ((ch & 0x07) << 18)
2363 | ((s[1] & 0x3f) << 12)
2364 | ((s[2] & 0x3f) << 6)
2367 goto invalid_sequence;/* Overlong sequence. */
2369 default: /* Others are all invalid sequence. */
2370 if (ch == 0xc0 || ch == 0xc1)
2372 else if (ch >= 0xf5 && ch <= 0xf7)
2374 else if (ch >= 0xf8 && ch <= 0xfb)
2376 else if (ch == 0xfc || ch == 0xfd)
2382 for (i = 1; i < cnt; i++) {
2383 if ((s[i] & 0xc0) != 0x80) {
2388 goto invalid_sequence;
2391 /* The code point larger than 0x10FFFF is not legal
2392 * Unicode values. */
2393 if (wc > UNICODE_MAX)
2394 goto invalid_sequence;
2395 /* Correctly gets a Unicode, returns used bytes. */
2399 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2404 utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2408 cnt = _utf8_to_unicode(pwc, s, n);
2409 /* Any of Surrogate pair is not legal Unicode values. */
2410 if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2415 static inline uint32_t
2416 combine_surrogate_pair(uint32_t uc, uint32_t uc2)
2426 * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2427 * removing surrogate pairs.
2429 * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2431 * Usually return used bytes, return used byte in negative value when
2432 * a unicode character is replaced with U+FFFD.
2435 cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2440 cnt = _utf8_to_unicode(&wc, s, n);
2441 if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2444 /* Invalid byte sequence. */
2445 goto invalid_sequence;
2447 cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2448 if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2449 /* Invalid byte sequence. */
2450 goto invalid_sequence;
2452 wc = combine_surrogate_pair(wc, wc2);
2454 } else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2455 /* Invalid byte sequence. */
2456 goto invalid_sequence;
2461 *pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2468 * Convert a Unicode code point to a single UTF-8 sequence.
2470 * NOTE:This function does not check if the Unicode is legal or not.
2471 * Please you definitely check it before calling this.
2474 unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2478 /* Invalid Unicode char maps to Replacement character */
2479 if (uc > UNICODE_MAX)
2480 uc = UNICODE_R_CHAR;
2481 /* Translate code point to UTF8 */
2486 } else if (uc <= 0x7ff) {
2489 *p++ = 0xc0 | ((uc >> 6) & 0x1f);
2490 *p++ = 0x80 | (uc & 0x3f);
2491 } else if (uc <= 0xffff) {
2494 *p++ = 0xe0 | ((uc >> 12) & 0x0f);
2495 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2496 *p++ = 0x80 | (uc & 0x3f);
2500 *p++ = 0xf0 | ((uc >> 18) & 0x07);
2501 *p++ = 0x80 | ((uc >> 12) & 0x3f);
2502 *p++ = 0x80 | ((uc >> 6) & 0x3f);
2503 *p++ = 0x80 | (uc & 0x3f);
2509 utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2511 return (utf16_to_unicode(pwc, s, n, 1));
2515 utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2517 return (utf16_to_unicode(pwc, s, n, 0));
2521 utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2523 const char *utf16 = s;
2529 /* set the Replacement Character instead. */
2530 *pwc = UNICODE_R_CHAR;
2535 uc = archive_be16dec(utf16);
2537 uc = archive_le16dec(utf16);
2540 /* If this is a surrogate pair, assemble the full code point.*/
2541 if (IS_HIGH_SURROGATE_LA(uc)) {
2546 uc2 = archive_be16dec(utf16);
2548 uc2 = archive_le16dec(utf16);
2551 if (IS_LOW_SURROGATE_LA(uc2)) {
2552 uc = combine_surrogate_pair(uc, uc2);
2555 /* Undescribed code point should be U+FFFD
2556 * (replacement character). */
2557 *pwc = UNICODE_R_CHAR;
2563 * Surrogate pair values(0xd800 through 0xdfff) are only
2564 * used by UTF-16, so, after above calculation, the code
2565 * must not be surrogate values, and Unicode has no codes
2566 * larger than 0x10ffff. Thus, those are not legal Unicode
2569 if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2570 /* Undescribed code point should be U+FFFD
2571 * (replacement character). */
2572 *pwc = UNICODE_R_CHAR;
2573 return (((int)(utf16 - s)) * -1);
2576 return ((int)(utf16 - s));
2580 unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2585 /* We have a code point that won't fit into a
2586 * wchar_t; convert it to a surrogate pair. */
2590 archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2591 archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2596 archive_be16enc(utf16, uc);
2602 unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2607 /* We have a code point that won't fit into a
2608 * wchar_t; convert it to a surrogate pair. */
2612 archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2613 archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2618 archive_le16enc(utf16, uc);
2624 * Copy UTF-8 string in checking surrogate pair.
2625 * If any surrogate pair are found, it would be canonicalized.
2628 strncat_from_utf8_to_utf8(struct archive_string *as, const void *_p,
2629 size_t len, struct archive_string_conv *sc)
2635 (void)sc; /* UNUSED */
2637 if (archive_string_ensure(as, as->length + len + 1) == NULL)
2640 s = (const char *)_p;
2641 p = as->s + as->length;
2642 endp = as->s + as->buffer_length -1;
2649 * Forward byte sequence until a conversion of that is needed.
2651 while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
2656 if (p + (s - ss) > endp) {
2657 as->length = p - as->s;
2658 if (archive_string_ensure(as,
2659 as->buffer_length + len + 1) == NULL)
2661 p = as->s + as->length;
2662 endp = as->s + as->buffer_length -1;
2665 memcpy(p, ss, s - ss);
2670 * If n is negative, current byte sequence needs a replacement.
2673 if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2674 /* Current byte sequence may be CESU-8. */
2675 n = cesu8_to_unicode(&uc, s, len);
2679 n *= -1;/* Use a replaced unicode character. */
2682 /* Rebuild UTF-8 byte sequence. */
2683 while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
2684 as->length = p - as->s;
2685 if (archive_string_ensure(as,
2686 as->buffer_length + len + 1) == NULL)
2688 p = as->s + as->length;
2689 endp = as->s + as->buffer_length -1;
2696 as->length = p - as->s;
2697 as->s[as->length] = '\0';
2702 archive_string_append_unicode(struct archive_string *as, const void *_p,
2703 size_t len, struct archive_string_conv *sc)
2709 int n, ret = 0, ts, tm;
2710 int (*parse)(uint32_t *, const char *, size_t);
2711 size_t (*unparse)(char *, size_t, uint32_t);
2713 if (sc->flag & SCONV_TO_UTF16BE) {
2714 unparse = unicode_to_utf16be;
2716 } else if (sc->flag & SCONV_TO_UTF16LE) {
2717 unparse = unicode_to_utf16le;
2719 } else if (sc->flag & SCONV_TO_UTF8) {
2720 unparse = unicode_to_utf8;
2724 * This case is going to be converted to another
2725 * character-set through iconv.
2727 if (sc->flag & SCONV_FROM_UTF16BE) {
2728 unparse = unicode_to_utf16be;
2730 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2731 unparse = unicode_to_utf16le;
2734 unparse = unicode_to_utf8;
2739 if (sc->flag & SCONV_FROM_UTF16BE) {
2740 parse = utf16be_to_unicode;
2742 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2743 parse = utf16le_to_unicode;
2746 parse = cesu8_to_unicode;
2750 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2753 s = (const char *)_p;
2754 p = as->s + as->length;
2755 endp = as->s + as->buffer_length - ts;
2756 while ((n = parse(&uc, s, len)) != 0) {
2758 /* Use a replaced unicode character. */
2764 while ((w = unparse(p, endp - p, uc)) == 0) {
2765 /* There is not enough output buffer so
2766 * we have to expand it. */
2767 as->length = p - as->s;
2768 if (archive_string_ensure(as,
2769 as->buffer_length + len * tm + ts) == NULL)
2771 p = as->s + as->length;
2772 endp = as->s + as->buffer_length - ts;
2776 as->length = p - as->s;
2777 as->s[as->length] = '\0';
2779 as->s[as->length+1] = '\0';
2784 * Following Constants for Hangul compositions this information comes from
2785 * Unicode Standard Annex #15 http://unicode.org/reports/tr15/
2787 #define HC_SBASE 0xAC00
2788 #define HC_LBASE 0x1100
2789 #define HC_VBASE 0x1161
2790 #define HC_TBASE 0x11A7
2791 #define HC_LCOUNT 19
2792 #define HC_VCOUNT 21
2793 #define HC_TCOUNT 28
2794 #define HC_NCOUNT (HC_VCOUNT * HC_TCOUNT)
2795 #define HC_SCOUNT (HC_LCOUNT * HC_NCOUNT)
2798 get_nfc(uint32_t uc, uint32_t uc2)
2803 b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2805 int m = (t + b) / 2;
2806 if (u_composition_table[m].cp1 < uc)
2808 else if (u_composition_table[m].cp1 > uc)
2810 else if (u_composition_table[m].cp2 < uc2)
2812 else if (u_composition_table[m].cp2 > uc2)
2815 return (u_composition_table[m].nfc);
2820 #define FDC_MAX 10 /* The maximum number of Following Decomposable
2824 * Update first code point.
2826 #define UPDATE_UC(new_uc) do { \
2832 * Replace first code point with second code point.
2834 #define REPLACE_UC_WITH_UC2() do { \
2840 #define EXPAND_BUFFER() do { \
2841 as->length = p - as->s; \
2842 if (archive_string_ensure(as, \
2843 as->buffer_length + len * tm + ts) == NULL)\
2845 p = as->s + as->length; \
2846 endp = as->s + as->buffer_length - ts; \
2849 #define UNPARSE(p, endp, uc) do { \
2850 while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
2857 * Write first code point.
2858 * If the code point has not be changed from its original code,
2859 * this just copies it from its original buffer pointer.
2860 * If not, this converts it to UTF-8 byte sequence and copies it.
2862 #define WRITE_UC() do { \
2869 /* FALL THROUGH */ \
2872 /* FALL THROUGH */ \
2875 /* FALL THROUGH */ \
2882 UNPARSE(p, endp, uc); \
2887 * Collect following decomposable code points.
2889 #define COLLECT_CPS(start) do { \
2891 for (_i = start; _i < FDC_MAX ; _i++) { \
2892 nx = parse(&ucx[_i], s, len); \
2895 cx = CCC(ucx[_i]); \
2896 if (cl >= cx && cl != 228 && cx != 228)\
2903 if (_i >= FDC_MAX) { \
2905 ucx_size = FDC_MAX; \
2911 * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
2913 * TODO: Convert composition exclusions, which are never converted
2914 * from NFC,NFD,NFKC and NFKD, to Form C.
2917 archive_string_normalize_C(struct archive_string *as, const void *_p,
2918 size_t len, struct archive_string_conv *sc)
2920 const char *s = (const char *)_p;
2924 int always_replace, n, n2, ret = 0, spair, ts, tm;
2925 int (*parse)(uint32_t *, const char *, size_t);
2926 size_t (*unparse)(char *, size_t, uint32_t);
2929 ts = 1;/* text size. */
2930 if (sc->flag & SCONV_TO_UTF16BE) {
2931 unparse = unicode_to_utf16be;
2933 if (sc->flag & SCONV_FROM_UTF16BE)
2935 } else if (sc->flag & SCONV_TO_UTF16LE) {
2936 unparse = unicode_to_utf16le;
2938 if (sc->flag & SCONV_FROM_UTF16LE)
2940 } else if (sc->flag & SCONV_TO_UTF8) {
2941 unparse = unicode_to_utf8;
2942 if (sc->flag & SCONV_FROM_UTF8)
2946 * This case is going to be converted to another
2947 * character-set through iconv.
2950 if (sc->flag & SCONV_FROM_UTF16BE) {
2951 unparse = unicode_to_utf16be;
2953 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2954 unparse = unicode_to_utf16le;
2957 unparse = unicode_to_utf8;
2961 if (sc->flag & SCONV_FROM_UTF16BE) {
2962 parse = utf16be_to_unicode;
2964 spair = 4;/* surrogate pair size in UTF-16. */
2965 } else if (sc->flag & SCONV_FROM_UTF16LE) {
2966 parse = utf16le_to_unicode;
2968 spair = 4;/* surrogate pair size in UTF-16. */
2970 parse = cesu8_to_unicode;
2972 spair = 6;/* surrogate pair size in UTF-8. */
2975 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2978 p = as->s + as->length;
2979 endp = as->s + as->buffer_length - ts;
2980 while ((n = parse(&uc, s, len)) != 0) {
2981 const char *ucptr, *uc2ptr;
2984 /* Use a replaced unicode character. */
2985 UNPARSE(p, endp, uc);
2990 } else if (n == spair || always_replace)
2991 /* uc is converted from a surrogate pair.
2992 * this should be treated as a changed code. */
2999 /* Read second code point. */
3000 while ((n2 = parse(&uc2, s, len)) > 0) {
3001 uint32_t ucx[FDC_MAX];
3003 int cl, cx, i, nx, ucx_size;
3007 if (n2 == spair || always_replace)
3008 /* uc2 is converted from a surrogate pair.
3009 * this should be treated as a changed code. */
3017 * If current second code point is out of decomposable
3018 * code points, finding compositions is unneeded.
3020 if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3022 REPLACE_UC_WITH_UC2();
3027 * Try to combine current code points.
3030 * We have to combine Hangul characters according to
3031 * http://uniicode.org/reports/tr15/#Hangul
3033 if (0 <= (LIndex = uc - HC_LBASE) &&
3034 LIndex < HC_LCOUNT) {
3036 * Hangul Composition.
3037 * 1. Two current code points are L and V.
3039 int VIndex = uc2 - HC_VBASE;
3040 if (0 <= VIndex && VIndex < HC_VCOUNT) {
3041 /* Make syllable of form LV. */
3042 UPDATE_UC(HC_SBASE +
3043 (LIndex * HC_VCOUNT + VIndex) *
3047 REPLACE_UC_WITH_UC2();
3050 } else if (0 <= (SIndex = uc - HC_SBASE) &&
3051 SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3053 * Hangul Composition.
3054 * 2. Two current code points are LV and T.
3056 int TIndex = uc2 - HC_TBASE;
3057 if (0 < TIndex && TIndex < HC_TCOUNT) {
3058 /* Make syllable of form LVT. */
3059 UPDATE_UC(uc + TIndex);
3062 REPLACE_UC_WITH_UC2();
3065 } else if ((nfc = get_nfc(uc, uc2)) != 0) {
3066 /* A composition to current code points
3070 } else if ((cl = CCC(uc2)) == 0) {
3071 /* Clearly 'uc2' the second code point is not
3072 * a decomposable code. */
3074 REPLACE_UC_WITH_UC2();
3079 * Collect following decomposable code points.
3087 * Find a composed code in the collected code points.
3090 while (i < ucx_size) {
3093 if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3099 * nfc is composed of uc and ucx[i].
3104 * Remove ucx[i] by shifting
3105 * following code points.
3107 for (j = i; j+1 < ucx_size; j++) {
3114 * Collect following code points blocked
3115 * by ucx[i] the removed code point.
3117 if (ucx_size > 0 && i == ucx_size &&
3118 nx > 0 && cx == cl) {
3119 cl = ccx[ucx_size-1];
3120 COLLECT_CPS(ucx_size);
3123 * Restart finding a composed code with
3124 * the updated uc from the top of the
3125 * collected code points.
3131 * Apparently the current code points are not
3132 * decomposed characters or already composed.
3135 for (i = 0; i < ucx_size; i++)
3136 UNPARSE(p, endp, ucx[i]);
3139 * Flush out remaining canonical combining characters.
3141 if (nx > 0 && cx == cl && len > 0) {
3142 while ((nx = parse(&ucx[0], s, len))
3150 UNPARSE(p, endp, ucx[0]);
3157 /* Use a replaced unicode character. */
3158 UNPARSE(p, endp, uc2);
3163 } else if (n2 == 0) {
3168 as->length = p - as->s;
3169 as->s[as->length] = '\0';
3171 as->s[as->length+1] = '\0';
3176 get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
3181 * These are not converted to NFD on Mac OS.
3183 if ((uc >= 0x2000 && uc <= 0x2FFF) ||
3184 (uc >= 0xF900 && uc <= 0xFAFF) ||
3185 (uc >= 0x2F800 && uc <= 0x2FAFF))
3188 * Those code points are not converted to NFD on Mac OS.
3189 * I do not know the reason because it is undocumented.
3191 * 1109A ==> 11099 110BA
3192 * 1109C ==> 1109B 110BA
3193 * 110AB ==> 110A5 110BA
3195 if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
3199 b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
3201 int m = (t + b) / 2;
3202 if (u_decomposition_table[m].nfc < uc)
3204 else if (u_decomposition_table[m].nfc > uc)
3207 *cp1 = u_decomposition_table[m].cp1;
3208 *cp2 = u_decomposition_table[m].cp2;
3215 #define REPLACE_UC_WITH(cp) do { \
3221 * Normalize UTF-8 characters to Form D and copy the result.
3224 archive_string_normalize_D(struct archive_string *as, const void *_p,
3225 size_t len, struct archive_string_conv *sc)
3227 const char *s = (const char *)_p;
3231 int always_replace, n, n2, ret = 0, spair, ts, tm;
3232 int (*parse)(uint32_t *, const char *, size_t);
3233 size_t (*unparse)(char *, size_t, uint32_t);
3236 ts = 1;/* text size. */
3237 if (sc->flag & SCONV_TO_UTF16BE) {
3238 unparse = unicode_to_utf16be;
3240 if (sc->flag & SCONV_FROM_UTF16BE)
3242 } else if (sc->flag & SCONV_TO_UTF16LE) {
3243 unparse = unicode_to_utf16le;
3245 if (sc->flag & SCONV_FROM_UTF16LE)
3247 } else if (sc->flag & SCONV_TO_UTF8) {
3248 unparse = unicode_to_utf8;
3249 if (sc->flag & SCONV_FROM_UTF8)
3253 * This case is going to be converted to another
3254 * character-set through iconv.
3257 if (sc->flag & SCONV_FROM_UTF16BE) {
3258 unparse = unicode_to_utf16be;
3260 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3261 unparse = unicode_to_utf16le;
3264 unparse = unicode_to_utf8;
3268 if (sc->flag & SCONV_FROM_UTF16BE) {
3269 parse = utf16be_to_unicode;
3271 spair = 4;/* surrogate pair size in UTF-16. */
3272 } else if (sc->flag & SCONV_FROM_UTF16LE) {
3273 parse = utf16le_to_unicode;
3275 spair = 4;/* surrogate pair size in UTF-16. */
3277 parse = cesu8_to_unicode;
3279 spair = 6;/* surrogate pair size in UTF-8. */
3282 if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3285 p = as->s + as->length;
3286 endp = as->s + as->buffer_length - ts;
3287 while ((n = parse(&uc, s, len)) != 0) {
3300 /* Use a replaced unicode character. */
3301 UNPARSE(p, endp, uc);
3306 } else if (n == spair || always_replace)
3307 /* uc is converted from a surrogate pair.
3308 * this should be treated as a changed code. */
3315 /* Hangul Decomposition. */
3316 if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
3317 int L = HC_LBASE + SIndex / HC_NCOUNT;
3318 int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
3319 int T = HC_TBASE + SIndex % HC_TCOUNT;
3325 if (T != HC_TBASE) {
3331 if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
3337 while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
3340 for (k = fdi; k > 0; k--)
3342 fdc[0].ccc = CCC(cp2);
3345 REPLACE_UC_WITH(cp1);
3348 /* Read following code points. */
3349 while ((n2 = parse(&uc2, s, len)) > 0 &&
3350 (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
3355 for (j = 0; j < fdi; j++) {
3356 if (fdc[j].ccc > ccc)
3360 for (k = fdi; k > j; k--)
3372 for (fdj = 0; fdj < fdi; fdj++) {
3373 REPLACE_UC_WITH(fdc[fdj].uc);
3379 REPLACE_UC_WITH(uc2);
3381 goto check_first_code;
3383 as->length = p - as->s;
3384 as->s[as->length] = '\0';
3386 as->s[as->length+1] = '\0';
3391 * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
3392 * that WCS is Unicode. It is true for several platforms but some are false.
3393 * And then people who did not use UTF-8 locale on the non Unicode WCS
3394 * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3395 * now cannot get right filename from libarchive 3.x and later since we
3396 * fixed the wrong assumption and it is incompatible to older its versions.
3397 * So we provide special option, "compat-2x.x", for resolving it.
3398 * That option enable the string conversion of libarchive 2.x.
3400 * Translates the wrong UTF-8 string made by libarchive 2.x into current
3401 * locale character set and appends to the archive_string.
3402 * Note: returns -1 if conversion fails.
3405 strncat_from_utf8_libarchive2(struct archive_string *as,
3406 const void *_p, size_t len, struct archive_string_conv *sc)
3414 mbstate_t shift_state;
3416 memset(&shift_state, 0, sizeof(shift_state));
3418 /* Clear the shift state before starting. */
3419 wctomb(NULL, L'\0');
3421 (void)sc; /* UNUSED */
3423 * Allocate buffer for MBS.
3424 * We need this allocation here since it is possible that
3425 * as->s is still NULL.
3427 if (archive_string_ensure(as, as->length + len + 1) == NULL)
3430 s = (const char *)_p;
3431 p = as->s + as->length;
3432 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3433 while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3437 as->length = p - as->s;
3438 /* Re-allocate buffer for MBS. */
3439 if (archive_string_ensure(as,
3440 as->length + len * 2 + 1) == NULL)
3442 p = as->s + as->length;
3443 end = as->s + as->buffer_length - MB_CUR_MAX -1;
3447 * As libarchive 2.x, translates the UTF-8 characters into
3448 * wide-characters in the assumption that WCS is Unicode.
3454 wc = (wchar_t)unicode;
3459 * Translates the wide-character into the current locale MBS.
3462 n = (int)wcrtomb(p, wc, &shift_state);
3464 n = (int)wctomb(p, wc);
3470 as->length = p - as->s;
3471 as->s[as->length] = '\0';
3477 * Conversion functions between current locale dependent MBS and UTF-16BE.
3478 * strncat_from_utf16be() : UTF-16BE --> MBS
3479 * strncat_to_utf16be() : MBS --> UTF16BE
3482 #if defined(_WIN32) && !defined(__CYGWIN__)
3485 * Convert a UTF-16BE/LE string to current locale and copy the result.
3486 * Return -1 if conversion fails.
3489 win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3490 struct archive_string_conv *sc, int be)
3492 struct archive_string tmp;
3501 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3504 mbs = as->s + as->length;
3505 mbs_size = as->buffer_length - as->length -1;
3507 if (sc->to_cp == CP_C_LOCALE) {
3509 * "C" locale special process.
3513 for (b = 0; b < bytes; b += 2) {
3516 val = archive_be16dec(u16+b);
3518 val = archive_le16dec(u16+b);
3523 *mbs++ = (char)(val&0xff);
3527 as->s[as->length] = '\0';
3531 archive_string_init(&tmp);
3533 if (is_big_endian()) {
3536 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3538 memcpy(tmp.s, _p, bytes);
3539 for (b = 0; b < bytes; b += 2) {
3540 uint16_t val = archive_be16dec(tmp.s+b);
3541 archive_le16enc(tmp.s+b, val);
3546 if (!is_big_endian()) {
3549 if (archive_string_ensure(&tmp, bytes+2) == NULL)
3551 memcpy(tmp.s, _p, bytes);
3552 for (b = 0; b < bytes; b += 2) {
3553 uint16_t val = archive_le16dec(tmp.s+b);
3554 archive_be16enc(tmp.s+b, val);
3562 ll = WideCharToMultiByte(sc->to_cp, 0,
3563 (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
3565 /* Exit loop if we succeeded */
3567 GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3570 /* Else expand buffer and loop to try again. */
3571 ll = WideCharToMultiByte(sc->to_cp, 0,
3572 (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
3573 if (archive_string_ensure(as, ll +1) == NULL)
3575 mbs = as->s + as->length;
3576 mbs_size = as->buffer_length - as->length -1;
3578 archive_string_free(&tmp);
3580 as->s[as->length] = '\0';
3581 if (ll == 0 || defchar)
3587 win_strncat_from_utf16be(struct archive_string *as, const void *_p,
3588 size_t bytes, struct archive_string_conv *sc)
3590 return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3594 win_strncat_from_utf16le(struct archive_string *as, const void *_p,
3595 size_t bytes, struct archive_string_conv *sc)
3597 return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3605 return (archive_be16dec(&d) == 1);
3609 * Convert a current locale string to UTF-16BE/LE and copy the result.
3610 * Return -1 if conversion fails.
3613 win_strncat_to_utf16(struct archive_string *as16, const void *_p,
3614 size_t length, struct archive_string_conv *sc, int bigendian)
3616 const char *s = (const char *)_p;
3618 size_t count, avail;
3620 if (archive_string_ensure(as16,
3621 as16->length + (length + 1) * 2) == NULL)
3624 u16 = as16->s + as16->length;
3625 avail = as16->buffer_length - 2;
3626 if (sc->from_cp == CP_C_LOCALE) {
3628 * "C" locale special process.
3631 while (count < length && *s) {
3633 archive_be16enc(u16, *s);
3635 archive_le16enc(u16, *s);
3640 as16->length += count << 1;
3641 as16->s[as16->length] = 0;
3642 as16->s[as16->length+1] = 0;
3646 count = MultiByteToWideChar(sc->from_cp,
3647 MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
3648 /* Exit loop if we succeeded */
3650 GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3653 /* Expand buffer and try again */
3654 count = MultiByteToWideChar(sc->from_cp,
3655 MB_PRECOMPOSED, s, (int)length, NULL, 0);
3656 if (archive_string_ensure(as16, (count +1) * 2)
3659 u16 = as16->s + as16->length;
3660 avail = as16->buffer_length - 2;
3662 as16->length += count * 2;
3663 as16->s[as16->length] = 0;
3664 as16->s[as16->length+1] = 0;
3668 if (is_big_endian()) {
3671 uint16_t v = archive_be16dec(u16);
3672 archive_le16enc(u16, v);
3680 uint16_t v = archive_le16dec(u16);
3681 archive_be16enc(u16, v);
3691 win_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3692 size_t length, struct archive_string_conv *sc)
3694 return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3698 win_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3699 size_t length, struct archive_string_conv *sc)
3701 return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3704 #endif /* _WIN32 && !__CYGWIN__ */
3707 * Do the best effort for conversions.
3708 * We cannot handle UTF-16BE character-set without such iconv,
3709 * but there is a chance if a string consists just ASCII code or
3710 * a current locale is UTF-8.
3714 * Convert a UTF-16BE string to current locale and copy the result.
3715 * Return -1 if conversion fails.
3718 best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3719 size_t bytes, struct archive_string_conv *sc, int be)
3721 const char *utf16 = (const char *)_p;
3726 (void)sc; /* UNUSED */
3728 * Other case, we should do the best effort.
3729 * If all character are ASCII(<0x7f), we can convert it.
3730 * if not , we set a alternative character and return -1.
3733 if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3735 mbs = as->s + as->length;
3737 while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3746 /* We cannot handle it. */
3752 as->length = mbs - as->s;
3753 as->s[as->length] = '\0';
3758 best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3759 size_t bytes, struct archive_string_conv *sc)
3761 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3765 best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3766 size_t bytes, struct archive_string_conv *sc)
3768 return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3772 * Convert a current locale string to UTF-16BE/LE and copy the result.
3773 * Return -1 if conversion fails.
3776 best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3777 size_t length, struct archive_string_conv *sc, int bigendian)
3779 const char *s = (const char *)_p;
3784 (void)sc; /* UNUSED */
3786 * Other case, we should do the best effort.
3787 * If all character are ASCII(<0x7f), we can convert it.
3788 * if not , we set a alternative character and return -1.
3793 if (archive_string_ensure(as16,
3794 as16->length + (length + 1) * 2) == NULL)
3797 utf16 = as16->s + as16->length;
3798 while (remaining--) {
3801 /* We cannot handle it. */
3806 archive_be16enc(utf16, c);
3808 archive_le16enc(utf16, c);
3811 as16->length = utf16 - as16->s;
3812 as16->s[as16->length] = 0;
3813 as16->s[as16->length+1] = 0;
3818 best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3819 size_t length, struct archive_string_conv *sc)
3821 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3825 best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3826 size_t length, struct archive_string_conv *sc)
3828 return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3833 * Multistring operations.
3837 archive_mstring_clean(struct archive_mstring *aes)
3839 archive_wstring_free(&(aes->aes_wcs));
3840 archive_string_free(&(aes->aes_mbs));
3841 archive_string_free(&(aes->aes_utf8));
3842 archive_string_free(&(aes->aes_mbs_in_locale));
3847 archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3849 dest->aes_set = src->aes_set;
3850 archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3851 archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3852 archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3856 archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3859 struct archive_string_conv *sc;
3862 /* If we already have a UTF8 form, return that immediately. */
3863 if (aes->aes_set & AES_SET_UTF8) {
3864 *p = aes->aes_utf8.s;
3869 if (aes->aes_set & AES_SET_MBS) {
3870 sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3872 return (-1);/* Couldn't allocate memory for sc. */
3873 r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
3874 aes->aes_mbs.length, sc);
3876 free_sconv_object(sc);
3878 aes->aes_set |= AES_SET_UTF8;
3879 *p = aes->aes_utf8.s;
3880 return (0);/* success. */
3882 return (-1);/* failure. */
3884 return (0);/* success. */
3888 archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3893 (void)a; /* UNUSED */
3894 /* If we already have an MBS form, return that immediately. */
3895 if (aes->aes_set & AES_SET_MBS) {
3896 *p = aes->aes_mbs.s;
3901 /* If there's a WCS form, try converting with the native locale. */
3902 if (aes->aes_set & AES_SET_WCS) {
3903 archive_string_empty(&(aes->aes_mbs));
3904 r = archive_string_append_from_wcs(&(aes->aes_mbs),
3905 aes->aes_wcs.s, aes->aes_wcs.length);
3906 *p = aes->aes_mbs.s;
3908 aes->aes_set |= AES_SET_MBS;
3915 * Only a UTF-8 form cannot avail because its conversion already
3916 * failed at archive_mstring_update_utf8().
3922 archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
3927 (void)a;/* UNUSED */
3928 /* Return WCS form if we already have it. */
3929 if (aes->aes_set & AES_SET_WCS) {
3930 *wp = aes->aes_wcs.s;
3935 /* Try converting MBS to WCS using native locale. */
3936 if (aes->aes_set & AES_SET_MBS) {
3937 archive_wstring_empty(&(aes->aes_wcs));
3938 r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
3939 aes->aes_mbs.s, aes->aes_mbs.length);
3941 aes->aes_set |= AES_SET_WCS;
3942 *wp = aes->aes_wcs.s;
3944 ret = -1;/* failure. */
3950 archive_mstring_get_mbs_l(struct archive_mstring *aes,
3951 const char **p, size_t *length, struct archive_string_conv *sc)
3955 #if defined(_WIN32) && !defined(__CYGWIN__)
3957 * Internationalization programming on Windows must use Wide
3958 * characters because Windows platform cannot make locale UTF-8.
3960 if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
3961 archive_string_empty(&(aes->aes_mbs_in_locale));
3962 r = archive_string_append_from_wcs_in_codepage(
3963 &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
3964 aes->aes_wcs.length, sc);
3966 *p = aes->aes_mbs_in_locale.s;
3968 *length = aes->aes_mbs_in_locale.length;
3970 } else if (errno == ENOMEM)
3977 /* If there is not an MBS form but is a WCS form, try converting
3978 * with the native locale to be used for translating it to specified
3980 if ((aes->aes_set & AES_SET_MBS) == 0 &&
3981 (aes->aes_set & AES_SET_WCS) != 0) {
3982 archive_string_empty(&(aes->aes_mbs));
3983 r = archive_string_append_from_wcs(&(aes->aes_mbs),
3984 aes->aes_wcs.s, aes->aes_wcs.length);
3986 aes->aes_set |= AES_SET_MBS;
3987 else if (errno == ENOMEM)
3992 /* If we already have an MBS form, use it to be translated to
3993 * specified character-set. */
3994 if (aes->aes_set & AES_SET_MBS) {
3996 /* Conversion is unneeded. */
3997 *p = aes->aes_mbs.s;
3999 *length = aes->aes_mbs.length;
4002 ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
4003 aes->aes_mbs.s, aes->aes_mbs.length, sc);
4004 *p = aes->aes_mbs_in_locale.s;
4006 *length = aes->aes_mbs_in_locale.length;
4016 archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4022 return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4026 archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4033 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4034 archive_strncpy(&(aes->aes_mbs), mbs, len);
4035 archive_string_empty(&(aes->aes_utf8));
4036 archive_wstring_empty(&(aes->aes_wcs));
4041 archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4043 return archive_mstring_copy_wcs_len(aes, wcs,
4044 wcs == NULL ? 0 : wcslen(wcs));
4048 archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
4053 aes->aes_set = AES_SET_UTF8;
4054 archive_string_empty(&(aes->aes_mbs));
4055 archive_string_empty(&(aes->aes_wcs));
4056 archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
4057 return (int)strlen(utf8);
4061 archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4067 aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4068 archive_string_empty(&(aes->aes_mbs));
4069 archive_string_empty(&(aes->aes_utf8));
4070 archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4075 archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4076 const char *mbs, size_t len, struct archive_string_conv *sc)
4084 archive_string_empty(&(aes->aes_mbs));
4085 archive_wstring_empty(&(aes->aes_wcs));
4086 archive_string_empty(&(aes->aes_utf8));
4087 #if defined(_WIN32) && !defined(__CYGWIN__)
4089 * Internationalization programming on Windows must use Wide
4090 * characters because Windows platform cannot make locale UTF-8.
4093 if (archive_string_append(&(aes->aes_mbs),
4094 mbs, mbsnbytes(mbs, len)) == NULL) {
4098 aes->aes_set = AES_SET_MBS;
4101 #if defined(HAVE_ICONV)
4102 } else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4104 * This case happens only when MultiByteToWideChar() cannot
4105 * handle sc->from_cp, and we have to iconv in order to
4106 * translate character-set to wchar_t,UTF-16.
4108 iconv_t cd = sc->cd;
4113 * Translate multi-bytes from some character-set to UTF-8.
4116 r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
4122 aes->aes_set = AES_SET_UTF8;
4125 * Append the UTF-8 string into wstring.
4128 sc->flag &= ~(SCONV_NORMALIZATION_C
4129 | SCONV_TO_UTF16| SCONV_FROM_UTF16);
4130 from_cp = sc->from_cp;
4131 sc->from_cp = CP_UTF8;
4132 r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4133 aes->aes_utf8.s, aes->aes_utf8.length, sc);
4135 sc->from_cp = from_cp;
4137 aes->aes_set |= AES_SET_WCS;
4140 r = archive_wstring_append_from_mbs_in_codepage(
4141 &(aes->aes_wcs), mbs, len, sc);
4143 aes->aes_set = AES_SET_WCS;
4148 r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
4150 aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4158 * The 'update' form tries to proactively update all forms of
4159 * this string (WCS and MBS) and returns an error if any of
4160 * them fail. This is used by the 'pax' handler, for instance,
4161 * to detect and report character-conversion failures early while
4162 * still allowing clients to get potentially useful values from
4163 * the more tolerant lazy conversions. (get_mbs and get_wcs will
4164 * strive to give the user something useful, so you can get hopefully
4165 * usable values even if some of the character conversions are failing.)
4168 archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4171 struct archive_string_conv *sc;
4176 return (0); /* Succeeded in clearing everything. */
4179 /* Save the UTF8 string. */
4180 archive_strcpy(&(aes->aes_utf8), utf8);
4182 /* Empty the mbs and wcs strings. */
4183 archive_string_empty(&(aes->aes_mbs));
4184 archive_wstring_empty(&(aes->aes_wcs));
4186 aes->aes_set = AES_SET_UTF8; /* Only UTF8 is set now. */
4188 /* Try converting UTF-8 to MBS, return false on failure. */
4189 sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4191 return (-1);/* Couldn't allocate memory for sc. */
4192 r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
4194 free_sconv_object(sc);
4197 aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4199 /* Try converting MBS to WCS, return false on failure. */
4200 if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4201 aes->aes_mbs.length))
4203 aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4205 /* All conversions succeeded. */