Home | History | Annotate | Line # | Download | only in libarchive
      1 /*-
      2  * Copyright (c) 2003-2011 Tim Kientzle
      3  * Copyright (c) 2011-2012 Michihiro NAKAJIMA
      4  * All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      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.
     14  *
     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.
     25  */
     26 
     27 #include "archive_platform.h"
     28 
     29 /*
     30  * Basic resizable string support, to simplify manipulating arbitrary-sized
     31  * strings while minimizing heap activity.
     32  *
     33  * In particular, the buffer used by a string object is only grown, it
     34  * never shrinks, so you can clear and reuse the same string object
     35  * without incurring additional memory allocations.
     36  */
     37 
     38 #ifdef HAVE_ERRNO_H
     39 #include <errno.h>
     40 #endif
     41 #ifdef HAVE_ICONV_H
     42 #include <iconv.h>
     43 #endif
     44 #ifdef HAVE_LANGINFO_H
     45 #include <langinfo.h>
     46 #endif
     47 #ifdef HAVE_LOCALCHARSET_H
     48 #include <localcharset.h>
     49 #endif
     50 #ifdef HAVE_STDLIB_H
     51 #include <stdlib.h>
     52 #endif
     53 #ifdef HAVE_STRING_H
     54 #include <string.h>
     55 #endif
     56 #ifdef HAVE_WCHAR_H
     57 #include <wchar.h>
     58 #endif
     59 #if defined(_WIN32) && !defined(__CYGWIN__)
     60 #include <windows.h>
     61 #include <locale.h>
     62 #endif
     63 
     64 #include "archive_endian.h"
     65 #include "archive_private.h"
     66 #include "archive_string.h"
     67 #include "archive_string_composition.h"
     68 
     69 #if !defined(HAVE_WMEMCPY) && !defined(wmemcpy)
     70 #define wmemcpy(a,b,i)  (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t))
     71 #endif
     72 
     73 #if !defined(HAVE_WMEMMOVE) && !defined(wmemmove)
     74 #define wmemmove(a,b,i)  (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t))
     75 #endif
     76 
     77 #undef max
     78 #define max(a, b)       ((a)>(b)?(a):(b))
     79 
     80 struct archive_string_conv {
     81 	struct archive_string_conv	*next;
     82 	char				*from_charset;
     83 	char				*to_charset;
     84 	unsigned			 from_cp;
     85 	unsigned			 to_cp;
     86 	/* Set 1 if from_charset and to_charset are the same. */
     87 	int				 same;
     88 	int				 flag;
     89 #define SCONV_TO_CHARSET	1	/* MBS is being converted to specified
     90 					 * charset. */
     91 #define SCONV_FROM_CHARSET	(1<<1)	/* MBS is being converted from
     92 					 * specified charset. */
     93 #define SCONV_BEST_EFFORT 	(1<<2)	/* Copy at least ASCII code. */
     94 #define SCONV_WIN_CP	 	(1<<3)	/* Use Windows API for converting
     95 					 * MBS. */
     96 #define SCONV_UTF8_LIBARCHIVE_2 (1<<4)	/* Incorrect UTF-8 made by libarchive
     97 					 * 2.x in the wrong assumption. */
     98 #define SCONV_NORMALIZATION_C	(1<<6)	/* Need normalization to be Form C.
     99 					 * Before UTF-8 characters are actually
    100 					 * processed. */
    101 #define SCONV_NORMALIZATION_D	(1<<7)	/* Need normalization to be Form D.
    102 					 * Before UTF-8 characters are actually
    103 					 * processed.
    104 					 * Currently this only for MAC OS X. */
    105 #define SCONV_TO_UTF8		(1<<8)	/* "to charset" side is UTF-8. */
    106 #define SCONV_FROM_UTF8		(1<<9)	/* "from charset" side is UTF-8. */
    107 #define SCONV_TO_UTF16BE 	(1<<10)	/* "to charset" side is UTF-16BE. */
    108 #define SCONV_FROM_UTF16BE 	(1<<11)	/* "from charset" side is UTF-16BE. */
    109 #define SCONV_TO_UTF16LE 	(1<<12)	/* "to charset" side is UTF-16LE. */
    110 #define SCONV_FROM_UTF16LE 	(1<<13)	/* "from charset" side is UTF-16LE. */
    111 #define SCONV_TO_UTF16		(SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
    112 #define SCONV_FROM_UTF16	(SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
    113 
    114 #if HAVE_ICONV
    115 	iconv_t				 cd;
    116 	iconv_t				 cd_w;/* Use at archive_mstring on
    117 				 	       * Windows. */
    118 #endif
    119 	/* A temporary buffer for normalization. */
    120 	struct archive_string		 utftmp;
    121 	int (*converter[2])(struct archive_string *, const void *, size_t,
    122 	    struct archive_string_conv *);
    123 	int				 nconverter;
    124 };
    125 
    126 #define CP_C_LOCALE	0	/* "C" locale only for this file. */
    127 #define CP_UTF16LE	1200
    128 #define CP_UTF16BE	1201
    129 
    130 #define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
    131 #define IS_LOW_SURROGATE_LA(uc)	 ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
    132 #define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
    133 #define UNICODE_MAX		0x10FFFF
    134 #define UNICODE_R_CHAR		0xFFFD	/* Replacement character. */
    135 /* Set U+FFFD(Replacement character) in UTF-8. */
    136 static const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd};
    137 
    138 static struct archive_string_conv *find_sconv_object(struct archive *,
    139 	const char *, const char *);
    140 static void add_sconv_object(struct archive *, struct archive_string_conv *);
    141 static struct archive_string_conv *create_sconv_object(const char *,
    142 	const char *, unsigned, int);
    143 static void free_sconv_object(struct archive_string_conv *);
    144 static struct archive_string_conv *get_sconv_object(struct archive *,
    145 	const char *, const char *, int);
    146 static unsigned make_codepage_from_charset(const char *);
    147 static unsigned get_current_codepage(void);
    148 static unsigned get_current_oemcp(void);
    149 static size_t mbsnbytes(const void *, size_t);
    150 static size_t utf16nbytes(const void *, size_t);
    151 #if defined(_WIN32) && !defined(__CYGWIN__)
    152 static int archive_wstring_append_from_mbs_in_codepage(
    153     struct archive_wstring *, const char *, size_t,
    154     struct archive_string_conv *);
    155 static int archive_string_append_from_wcs_in_codepage(struct archive_string *,
    156     const wchar_t *, size_t, struct archive_string_conv *);
    157 static int strncat_in_codepage(struct archive_string *, const void *,
    158     size_t, struct archive_string_conv *);
    159 static int win_strncat_from_utf16be(struct archive_string *, const void *,
    160     size_t, struct archive_string_conv *);
    161 static int win_strncat_from_utf16le(struct archive_string *, const void *,
    162     size_t, struct archive_string_conv *);
    163 static int win_strncat_to_utf16be(struct archive_string *, const void *,
    164     size_t, struct archive_string_conv *);
    165 static int win_strncat_to_utf16le(struct archive_string *, const void *,
    166     size_t, struct archive_string_conv *);
    167 #endif
    168 static int best_effort_strncat_from_utf16be(struct archive_string *,
    169     const void *, size_t, struct archive_string_conv *);
    170 static int best_effort_strncat_from_utf16le(struct archive_string *,
    171     const void *, size_t, struct archive_string_conv *);
    172 static int best_effort_strncat_to_utf16be(struct archive_string *,
    173     const void *, size_t, struct archive_string_conv *);
    174 static int best_effort_strncat_to_utf16le(struct archive_string *,
    175     const void *, size_t, struct archive_string_conv *);
    176 #if defined(HAVE_ICONV)
    177 static int iconv_strncat_in_locale(struct archive_string *, const void *,
    178     size_t, struct archive_string_conv *);
    179 #endif
    180 static int best_effort_strncat_in_locale(struct archive_string *,
    181     const void *, size_t, struct archive_string_conv *);
    182 static int _utf8_to_unicode(uint32_t *, const char *, size_t);
    183 static int utf8_to_unicode(uint32_t *, const char *, size_t);
    184 static inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
    185 static int cesu8_to_unicode(uint32_t *, const char *, size_t);
    186 static size_t unicode_to_utf8(char *, size_t, uint32_t);
    187 static int utf16_to_unicode(uint32_t *, const char *, size_t, int);
    188 static size_t unicode_to_utf16be(char *, size_t, uint32_t);
    189 static size_t unicode_to_utf16le(char *, size_t, uint32_t);
    190 static int strncat_from_utf8_libarchive2(struct archive_string *,
    191     const void *, size_t, struct archive_string_conv *);
    192 static int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
    193     size_t, struct archive_string_conv *);
    194 static int archive_string_normalize_C(struct archive_string *, const void *,
    195     size_t, struct archive_string_conv *);
    196 static int archive_string_normalize_D(struct archive_string *, const void *,
    197     size_t, struct archive_string_conv *);
    198 static int archive_string_append_unicode(struct archive_string *,
    199     const void *, size_t, struct archive_string_conv *);
    200 
    201 #if defined __LITTLE_ENDIAN__
    202   #define IS_BIG_ENDIAN 0
    203 #elif defined __BIG_ENDIAN__
    204   #define IS_BIG_ENDIAN 1
    205 #elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
    206   #define IS_BIG_ENDIAN 0
    207 #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
    208   #define IS_BIG_ENDIAN 1
    209 #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || defined(_M_ARM64))
    210   #define IS_BIG_ENDIAN 0
    211 #else
    212 // Detect endianness at runtime.
    213 static int
    214 is_big_endian(void)
    215 {
    216 	uint16_t d = 1;
    217 
    218 	return (archive_be16dec(&d) == 1);
    219 }
    220 
    221 #define IS_BIG_ENDIAN is_big_endian()
    222 #endif
    223 
    224 static struct archive_string *
    225 archive_string_append(struct archive_string *as, const char *p, size_t s)
    226 {
    227 	if (archive_string_ensure(as, as->length + s + 1) == NULL)
    228 		return (NULL);
    229 	if (s)
    230 		memmove(as->s + as->length, p, s);
    231 	as->length += s;
    232 	as->s[as->length] = 0;
    233 	return (as);
    234 }
    235 
    236 static struct archive_wstring *
    237 archive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
    238 {
    239 	if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
    240 		return (NULL);
    241 	if (s)
    242 		wmemmove(as->s + as->length, p, s);
    243 	as->length += s;
    244 	as->s[as->length] = 0;
    245 	return (as);
    246 }
    247 
    248 struct archive_string *
    249 archive_array_append(struct archive_string *as, const char *p, size_t s)
    250 {
    251 	return archive_string_append(as, p, s);
    252 }
    253 
    254 void
    255 archive_string_concat(struct archive_string *dest, struct archive_string *src)
    256 {
    257 	if (archive_string_append(dest, src->s, src->length) == NULL)
    258 		__archive_errx(1, "Out of memory");
    259 }
    260 
    261 void
    262 archive_wstring_concat(struct archive_wstring *dest,
    263     struct archive_wstring *src)
    264 {
    265 	if (archive_wstring_append(dest, src->s, src->length) == NULL)
    266 		__archive_errx(1, "Out of memory");
    267 }
    268 
    269 void
    270 archive_string_free(struct archive_string *as)
    271 {
    272 	as->length = 0;
    273 	as->buffer_length = 0;
    274 	free(as->s);
    275 	as->s = NULL;
    276 }
    277 
    278 void
    279 archive_wstring_free(struct archive_wstring *as)
    280 {
    281 	as->length = 0;
    282 	as->buffer_length = 0;
    283 	free(as->s);
    284 	as->s = NULL;
    285 }
    286 
    287 struct archive_wstring *
    288 archive_wstring_ensure(struct archive_wstring *as, size_t s)
    289 {
    290 	return (struct archive_wstring *)
    291 		archive_string_ensure((struct archive_string *)as,
    292 					s * sizeof(wchar_t));
    293 }
    294 
    295 /* Returns NULL on any allocation failure. */
    296 struct archive_string *
    297 archive_string_ensure(struct archive_string *as, size_t s)
    298 {
    299 	char *p;
    300 	size_t new_length;
    301 
    302 	/* If buffer is already big enough, don't reallocate. */
    303 	if (as->s && (s <= as->buffer_length))
    304 		return (as);
    305 
    306 	/*
    307 	 * Growing the buffer at least exponentially ensures that
    308 	 * append operations are always linear in the number of
    309 	 * characters appended.  Using a smaller growth rate for
    310 	 * larger buffers reduces memory waste somewhat at the cost of
    311 	 * a larger constant factor.
    312 	 */
    313 	if (as->buffer_length < 32)
    314 		/* Start with a minimum 32-character buffer. */
    315 		new_length = 32;
    316 	else if (as->buffer_length < 8192)
    317 		/* Buffers under 8k are doubled for speed. */
    318 		new_length = as->buffer_length + as->buffer_length;
    319 	else {
    320 		/* Buffers 8k and over grow by at least 25% each time. */
    321 		new_length = as->buffer_length + as->buffer_length / 4;
    322 		/* Be safe: If size wraps, fail. */
    323 		if (new_length < as->buffer_length) {
    324 			/* On failure, wipe the string and return NULL. */
    325 			archive_string_free(as);
    326 			errno = ENOMEM;/* Make sure errno has ENOMEM. */
    327 			return (NULL);
    328 		}
    329 	}
    330 	/*
    331 	 * The computation above is a lower limit to how much we'll
    332 	 * grow the buffer.  In any case, we have to grow it enough to
    333 	 * hold the request.
    334 	 */
    335 	if (new_length < s)
    336 		new_length = s;
    337 	/* Now we can reallocate the buffer. */
    338 	p = realloc(as->s, new_length);
    339 	if (p == NULL) {
    340 		/* On failure, wipe the string and return NULL. */
    341 		archive_string_free(as);
    342 		errno = ENOMEM;/* Make sure errno has ENOMEM. */
    343 		return (NULL);
    344 	}
    345 
    346 	as->s = p;
    347 	as->buffer_length = new_length;
    348 	return (as);
    349 }
    350 
    351 /*
    352  * TODO: See if there's a way to avoid scanning
    353  * the source string twice.  Then test to see
    354  * if it actually helps (remember that we're almost
    355  * always called with pretty short arguments, so
    356  * such an optimization might not help).
    357  */
    358 struct archive_string *
    359 archive_strncat(struct archive_string *as, const void *_p, size_t n)
    360 {
    361 	size_t s;
    362 	const char *p, *pp;
    363 
    364 	p = (const char *)_p;
    365 
    366 	/* Like strlen(p), except won't examine positions beyond p[n]. */
    367 	s = 0;
    368 	pp = p;
    369 	while (s < n && *pp) {
    370 		pp++;
    371 		s++;
    372 	}
    373 	if ((as = archive_string_append(as, p, s)) == NULL)
    374 		__archive_errx(1, "Out of memory");
    375 	return (as);
    376 }
    377 
    378 struct archive_wstring *
    379 archive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
    380 {
    381 	size_t s;
    382 	const wchar_t *pp;
    383 
    384 	/* Like strlen(p), except won't examine positions beyond p[n]. */
    385 	s = 0;
    386 	pp = p;
    387 	while (s < n && *pp) {
    388 		pp++;
    389 		s++;
    390 	}
    391 	if ((as = archive_wstring_append(as, p, s)) == NULL)
    392 		__archive_errx(1, "Out of memory");
    393 	return (as);
    394 }
    395 
    396 struct archive_string *
    397 archive_strcat(struct archive_string *as, const void *p)
    398 {
    399 	/* strcat is just strncat without an effective limit.
    400 	 * Assert that we'll never get called with a source
    401 	 * string over 16MB.
    402 	 * TODO: Review all uses of strcat in the source
    403 	 * and try to replace them with strncat().
    404 	 */
    405 	return archive_strncat(as, p, 0x1000000);
    406 }
    407 
    408 struct archive_wstring *
    409 archive_wstrcat(struct archive_wstring *as, const wchar_t *p)
    410 {
    411 	/* Ditto. */
    412 	return archive_wstrncat(as, p, 0x1000000);
    413 }
    414 
    415 struct archive_string *
    416 archive_strappend_char(struct archive_string *as, char c)
    417 {
    418 	if ((as = archive_string_append(as, &c, 1)) == NULL)
    419 		__archive_errx(1, "Out of memory");
    420 	return (as);
    421 }
    422 
    423 struct archive_wstring *
    424 archive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
    425 {
    426 	if ((as = archive_wstring_append(as, &c, 1)) == NULL)
    427 		__archive_errx(1, "Out of memory");
    428 	return (as);
    429 }
    430 
    431 /*
    432  * Get the "current character set" name to use with iconv.
    433  * On FreeBSD, the empty character set name "" chooses
    434  * the correct character encoding for the current locale,
    435  * so this isn't necessary.
    436  * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
    437  * on that system, we have to explicitly call nl_langinfo()
    438  * to get the right name.  Not sure about other platforms.
    439  *
    440  * NOTE: GNU libiconv does not recognize the character-set name
    441  * which some platform nl_langinfo(CODESET) returns, so we should
    442  * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
    443  */
    444 static const char *
    445 default_iconv_charset(const char *charset) {
    446 	if (charset != NULL && charset[0] != '\0')
    447 		return charset;
    448 #if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
    449 	/* locale_charset() is broken on Mac OS */
    450 	return locale_charset();
    451 #elif HAVE_NL_LANGINFO
    452 	return nl_langinfo(CODESET);
    453 #else
    454 	return "";
    455 #endif
    456 }
    457 
    458 #if defined(_WIN32) && !defined(__CYGWIN__)
    459 
    460 /*
    461  * Convert MBS to WCS.
    462  * Note: returns -1 if conversion fails.
    463  */
    464 int
    465 archive_wstring_append_from_mbs(struct archive_wstring *dest,
    466     const char *p, size_t len)
    467 {
    468 	return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
    469 }
    470 
    471 static int
    472 archive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
    473     const char *s, size_t length, struct archive_string_conv *sc)
    474 {
    475 	int ret = 0;
    476 	size_t count;
    477 	UINT from_cp;
    478 
    479 	if (sc != NULL)
    480 		from_cp = sc->from_cp;
    481 	else
    482 		from_cp = get_current_codepage();
    483 
    484 	if (from_cp == CP_C_LOCALE) {
    485 		/*
    486 		 * "C" locale special processing.
    487 		 */
    488 		wchar_t *ws;
    489 		const unsigned char *mp;
    490 
    491 		if (NULL == archive_wstring_ensure(dest,
    492 		    dest->length + length + 1))
    493 			return (-1);
    494 
    495 		ws = dest->s + dest->length;
    496 		mp = (const unsigned char *)s;
    497 		count = 0;
    498 		while (count < length && *mp) {
    499 			*ws++ = (wchar_t)*mp++;
    500 			count++;
    501 		}
    502 	} else if (sc != NULL &&
    503 	    (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
    504 		/*
    505 		 * Normalize UTF-8 and UTF-16BE and convert it directly
    506 		 * to UTF-16 as wchar_t.
    507 		 */
    508 		struct archive_string u16;
    509 		int saved_flag = sc->flag;/* save current flag. */
    510 
    511 		if (IS_BIG_ENDIAN)
    512 			sc->flag |= SCONV_TO_UTF16BE;
    513 		else
    514 			sc->flag |= SCONV_TO_UTF16LE;
    515 
    516 		if (sc->flag & SCONV_FROM_UTF16) {
    517 			/*
    518 			 *  UTF-16BE/LE NFD ===> UTF-16 NFC
    519 			 *  UTF-16BE/LE NFC ===> UTF-16 NFD
    520 			 */
    521 			count = utf16nbytes(s, length);
    522 		} else {
    523 			/*
    524 			 *  UTF-8 NFD ===> UTF-16 NFC
    525 			 *  UTF-8 NFC ===> UTF-16 NFD
    526 			 */
    527 			count = mbsnbytes(s, length);
    528 		}
    529 		u16.s = (char *)dest->s;
    530 		u16.length = dest->length << 1;
    531 		u16.buffer_length = dest->buffer_length;
    532 		if (sc->flag & SCONV_NORMALIZATION_C)
    533 			ret = archive_string_normalize_C(&u16, s, count, sc);
    534 		else
    535 			ret = archive_string_normalize_D(&u16, s, count, sc);
    536 		dest->s = (wchar_t *)u16.s;
    537 		dest->length = u16.length >> 1;
    538 		dest->buffer_length = u16.buffer_length;
    539 		sc->flag = saved_flag;/* restore the saved flag. */
    540 		return (ret);
    541 	} else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
    542 		count = utf16nbytes(s, length);
    543 		count >>= 1; /* to be WCS length */
    544 		/* Allocate memory for WCS. */
    545 		if (NULL == archive_wstring_ensure(dest,
    546 		    dest->length + count + 1))
    547 			return (-1);
    548 		wmemcpy(dest->s + dest->length, (const wchar_t *)s, count);
    549 		if ((sc->flag & SCONV_FROM_UTF16BE) && !IS_BIG_ENDIAN) {
    550 			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
    551 			size_t b;
    552 			for (b = 0; b < count; b++) {
    553 				uint16_t val = archive_le16dec(u16+b);
    554 				archive_be16enc(u16+b, val);
    555 			}
    556 		} else if ((sc->flag & SCONV_FROM_UTF16LE) && IS_BIG_ENDIAN) {
    557 			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
    558 			size_t b;
    559 			for (b = 0; b < count; b++) {
    560 				uint16_t val = archive_be16dec(u16+b);
    561 				archive_le16enc(u16+b, val);
    562 			}
    563 		}
    564 	} else {
    565 		DWORD mbflag;
    566 		size_t buffsize;
    567 
    568 		if (sc == NULL)
    569 			mbflag = 0;
    570 		else if (sc->flag & SCONV_FROM_CHARSET) {
    571 			/* Do not trust the length which comes from
    572 			 * an archive file. */
    573 			length = mbsnbytes(s, length);
    574 			mbflag = 0;
    575 		} else
    576 			mbflag = MB_PRECOMPOSED;
    577 
    578 		mbflag |= MB_ERR_INVALID_CHARS;
    579 
    580 		buffsize = dest->length + length + 1;
    581 		do {
    582 			int r;
    583 
    584 			/* MultiByteToWideChar is limited to int. */
    585 			if (length > (size_t)INT_MAX ||
    586 				(dest->buffer_length >> 1) > (size_t)INT_MAX)
    587 				return (-1);
    588 			/* Allocate memory for WCS. */
    589 			if (NULL == archive_wstring_ensure(dest, buffsize))
    590 				return (-1);
    591 			/* Convert MBS to WCS. */
    592 			r = MultiByteToWideChar(from_cp,
    593 			    mbflag, s, (int)length, dest->s + dest->length,
    594 			    (int)(dest->buffer_length >> 1) -1);
    595 			if (r == 0 &&
    596 			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
    597 				/* Expand the WCS buffer. */
    598 				buffsize = dest->buffer_length << 1;
    599 				continue;
    600 			}
    601 			if (r == 0 && length != 0)
    602 				ret = -1;
    603 			count = (size_t)r;
    604 			break;
    605 		} while (1);
    606 	}
    607 	dest->length += count;
    608 	dest->s[dest->length] = L'\0';
    609 	return (ret);
    610 }
    611 
    612 #else
    613 
    614 /*
    615  * Convert MBS to WCS.
    616  * Note: returns -1 if conversion fails.
    617  */
    618 int
    619 archive_wstring_append_from_mbs(struct archive_wstring *dest,
    620     const char *p, size_t len)
    621 {
    622 	size_t r;
    623 	int ret_val = 0;
    624 	/*
    625 	 * No single byte will be more than one wide character,
    626 	 * so this length estimate will always be big enough.
    627 	 */
    628 	// size_t wcs_length = len;
    629 	size_t mbs_length = len;
    630 	const char *mbs = p;
    631 	wchar_t *wcs;
    632 #if HAVE_MBRTOWC
    633 	mbstate_t shift_state;
    634 
    635 	memset(&shift_state, 0, sizeof(shift_state));
    636 #endif
    637 	/*
    638 	 * As we decided to have wcs_length == mbs_length == len
    639 	 * we can use len here instead of wcs_length
    640 	 */
    641 	if (NULL == archive_wstring_ensure(dest, dest->length + len + 1))
    642 		return (-1);
    643 	wcs = dest->s + dest->length;
    644 	/*
    645 	 * We cannot use mbsrtowcs/mbstowcs here because those may convert
    646 	 * extra MBS when strlen(p) > len and one wide character consists of
    647 	 * multi bytes.
    648 	 */
    649 	while (*mbs && mbs_length > 0) {
    650 		/*
    651 		 * The buffer we allocated is always big enough.
    652 		 * Keep this code path in a comment if we decide to choose
    653 		 * smaller wcs_length in the future
    654 		 */
    655 /*
    656 		if (wcs_length == 0) {
    657 			dest->length = wcs - dest->s;
    658 			dest->s[dest->length] = L'\0';
    659 			wcs_length = mbs_length;
    660 			if (NULL == archive_wstring_ensure(dest,
    661 			    dest->length + wcs_length + 1))
    662 				return (-1);
    663 			wcs = dest->s + dest->length;
    664 		}
    665 */
    666 #if HAVE_MBRTOWC
    667 		r = mbrtowc(wcs, mbs, mbs_length, &shift_state);
    668 #else
    669 		r = mbtowc(wcs, mbs, mbs_length);
    670 #endif
    671 		if (r == (size_t)-1 || r == (size_t)-2) {
    672 			ret_val = -1;
    673 			break;
    674 		}
    675 		if (r == 0 || r > mbs_length)
    676 			break;
    677 		wcs++;
    678 		// wcs_length--;
    679 		mbs += r;
    680 		mbs_length -= r;
    681 	}
    682 	dest->length = wcs - dest->s;
    683 	dest->s[dest->length] = L'\0';
    684 	return (ret_val);
    685 }
    686 
    687 #endif
    688 
    689 #if defined(_WIN32) && !defined(__CYGWIN__)
    690 
    691 /*
    692  * WCS ==> MBS.
    693  * Note: returns -1 if conversion fails.
    694  *
    695  * Win32 builds use WideCharToMultiByte from the Windows API.
    696  * (Maybe Cygwin should too?  WideCharToMultiByte will know a
    697  * lot more about local character encodings than the wcrtomb()
    698  * wrapper is going to know.)
    699  */
    700 int
    701 archive_string_append_from_wcs(struct archive_string *as,
    702     const wchar_t *w, size_t len)
    703 {
    704 	return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
    705 }
    706 
    707 static int
    708 archive_string_append_from_wcs_in_codepage(struct archive_string *as,
    709     const wchar_t *ws, size_t len, struct archive_string_conv *sc)
    710 {
    711 	BOOL defchar_used, *dp;
    712 	int ret = 0;
    713 	UINT to_cp;
    714 	size_t count, wslen = len;
    715 
    716 	if (sc != NULL)
    717 		to_cp = sc->to_cp;
    718 	else
    719 		to_cp = get_current_codepage();
    720 
    721 	if (to_cp == CP_C_LOCALE) {
    722 		/*
    723 		 * "C" locale special processing.
    724 		 */
    725 		const wchar_t *wp = ws;
    726 		char *p;
    727 
    728 		if (NULL == archive_string_ensure(as,
    729 		    as->length + wslen +1))
    730 			return (-1);
    731 		p = as->s + as->length;
    732 		count = 0;
    733 		defchar_used = 0;
    734 		while (count < wslen && *wp) {
    735 			if (*wp > 255) {
    736 				*p++ = '?';
    737 				wp++;
    738 				defchar_used = 1;
    739 			} else
    740 				*p++ = (char)*wp++;
    741 			count++;
    742 		}
    743 	} else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
    744 		uint16_t *u16;
    745 
    746 		if (NULL ==
    747 		    archive_string_ensure(as, as->length + len * 2 + 2))
    748 			return (-1);
    749 		u16 = (uint16_t *)(as->s + as->length);
    750 		count = 0;
    751 		defchar_used = 0;
    752 		if (sc->flag & SCONV_TO_UTF16BE) {
    753 			while (count < len && *ws) {
    754 				archive_be16enc(u16+count, *ws);
    755 				ws++;
    756 				count++;
    757 			}
    758 		} else {
    759 			while (count < len && *ws) {
    760 				archive_le16enc(u16+count, *ws);
    761 				ws++;
    762 				count++;
    763 			}
    764 		}
    765 		count <<= 1; /* to be byte size */
    766 	} else {
    767 		/* Make sure the MBS buffer has plenty to set. */
    768 		if (NULL ==
    769 		    archive_string_ensure(as, as->length + len * 2 + 1))
    770 			return (-1);
    771 		do {
    772 			int r;
    773 
    774 			defchar_used = 0;
    775 			if (to_cp == CP_UTF8)
    776 				dp = NULL;
    777 			else
    778 				dp = &defchar_used;
    779 			/* WideCharToMultiByte is limited to int. */
    780 			if (as->buffer_length - as->length - 1 > (size_t)INT_MAX ||
    781 				wslen > (size_t)INT_MAX)
    782 				return (-1);
    783 			r = WideCharToMultiByte(to_cp, 0, ws, (int)wslen,
    784 			    as->s + as->length,
    785 			    (int)(as->buffer_length - as->length - 1), NULL, dp);
    786 			if (r == 0 &&
    787 			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
    788 				/* Expand the MBS buffer and retry. */
    789 				if (NULL == archive_string_ensure(as,
    790 					as->buffer_length + len))
    791 					return (-1);
    792 				continue;
    793 			}
    794 			if (r == 0)
    795 				ret = -1;
    796 			count = (size_t)r;
    797 			break;
    798 		} while (1);
    799 	}
    800 	as->length += count;
    801 	as->s[as->length] = '\0';
    802 	return (defchar_used?-1:ret);
    803 }
    804 
    805 #elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
    806 
    807 /*
    808  * Translates a wide character string into current locale character set
    809  * and appends to the archive_string.  Note: returns -1 if conversion
    810  * fails.
    811  */
    812 int
    813 archive_string_append_from_wcs(struct archive_string *as,
    814     const wchar_t *w, size_t len)
    815 {
    816 	/* We cannot use the standard wcstombs() here because it
    817 	 * cannot tell us how big the output buffer should be.  So
    818 	 * I've built a loop around wcrtomb() or wctomb() that
    819 	 * converts a character at a time and resizes the string as
    820 	 * needed.  We prefer wcrtomb() when it's available because
    821 	 * it's thread-safe. */
    822 	int n, ret_val = 0;
    823 	char *p;
    824 	char *end;
    825 #if HAVE_WCRTOMB
    826 	mbstate_t shift_state;
    827 
    828 	memset(&shift_state, 0, sizeof(shift_state));
    829 #else
    830 	/* Clear the shift state before starting. */
    831 	wctomb(NULL, L'\0');
    832 #endif
    833 	/*
    834 	 * Allocate buffer for MBS.
    835 	 * We need this allocation here since it is possible that
    836 	 * as->s is still NULL.
    837 	 */
    838 	if (archive_string_ensure(as, as->length + len + 1) == NULL)
    839 		return (-1);
    840 
    841 	p = as->s + as->length;
    842 	end = as->s + as->buffer_length - MB_CUR_MAX -1;
    843 	while (*w != L'\0' && len > 0) {
    844 		if (p >= end) {
    845 			as->length = p - as->s;
    846 			as->s[as->length] = '\0';
    847 			/* Re-allocate buffer for MBS. */
    848 			if (archive_string_ensure(as,
    849 			    as->length + max(len * 2,
    850 			    (size_t)MB_CUR_MAX) + 1) == NULL)
    851 				return (-1);
    852 			p = as->s + as->length;
    853 			end = as->s + as->buffer_length - MB_CUR_MAX -1;
    854 		}
    855 #if HAVE_WCRTOMB
    856 		n = wcrtomb(p, *w++, &shift_state);
    857 #else
    858 		n = wctomb(p, *w++);
    859 #endif
    860 		if (n == -1) {
    861 			if (errno == EILSEQ) {
    862 				/* Skip an illegal wide char. */
    863 				*p++ = '?';
    864 				ret_val = -1;
    865 			} else {
    866 				ret_val = -1;
    867 				break;
    868 			}
    869 		} else
    870 			p += n;
    871 		len--;
    872 	}
    873 	as->length = p - as->s;
    874 	as->s[as->length] = '\0';
    875 	return (ret_val);
    876 }
    877 
    878 #else /* HAVE_WCTOMB || HAVE_WCRTOMB */
    879 
    880 /*
    881  * TODO: Test if __STDC_ISO_10646__ is defined.
    882  * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
    883  * one character at a time.  If a non-Windows platform doesn't have
    884  * either of these, fall back to the built-in UTF8 conversion.
    885  */
    886 int
    887 archive_string_append_from_wcs(struct archive_string *as,
    888     const wchar_t *w, size_t len)
    889 {
    890 	(void)as;/* UNUSED */
    891 	(void)w;/* UNUSED */
    892 	(void)len;/* UNUSED */
    893 	errno = ENOSYS;
    894 	return (-1);
    895 }
    896 
    897 #endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
    898 
    899 /*
    900  * Find a string conversion object by a pair of 'from' charset name
    901  * and 'to' charset name from an archive object.
    902  * Return NULL if not found.
    903  */
    904 static struct archive_string_conv *
    905 find_sconv_object(struct archive *a, const char *fc, const char *tc)
    906 {
    907 	struct archive_string_conv *sc;
    908 
    909 	if (a == NULL)
    910 		return (NULL);
    911 
    912 	for (sc = a->sconv; sc != NULL; sc = sc->next) {
    913 		if (strcmp(sc->from_charset, fc) == 0 &&
    914 		    strcmp(sc->to_charset, tc) == 0)
    915 			break;
    916 	}
    917 	return (sc);
    918 }
    919 
    920 /*
    921  * Register a string object to an archive object.
    922  */
    923 static void
    924 add_sconv_object(struct archive *a, struct archive_string_conv *sc)
    925 {
    926 	struct archive_string_conv **psc;
    927 
    928 	/* Add a new sconv to sconv list. */
    929 	psc = &(a->sconv);
    930 	while (*psc != NULL)
    931 		psc = &((*psc)->next);
    932 	*psc = sc;
    933 }
    934 
    935 static void
    936 add_converter(struct archive_string_conv *sc, int (*converter)
    937     (struct archive_string *, const void *, size_t,
    938      struct archive_string_conv *))
    939 {
    940 	if (sc == NULL || sc->nconverter >= 2)
    941 		__archive_errx(1, "Programming error");
    942 	sc->converter[sc->nconverter++] = converter;
    943 }
    944 
    945 static void
    946 setup_converter(struct archive_string_conv *sc)
    947 {
    948 
    949 	/* Reset. */
    950 	sc->nconverter = 0;
    951 
    952 	/*
    953 	 * Perform special sequence for the incorrect UTF-8 filenames
    954 	 * made by libarchive2.x.
    955 	 */
    956 	if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
    957 		add_converter(sc, strncat_from_utf8_libarchive2);
    958 		return;
    959 	}
    960 
    961 	/*
    962 	 * Convert a string to UTF-16BE/LE.
    963 	 */
    964 	if (sc->flag & SCONV_TO_UTF16) {
    965 		/*
    966 		 * If the current locale is UTF-8, we can translate
    967 		 * a UTF-8 string into a UTF-16BE string.
    968 		 */
    969 		if (sc->flag & SCONV_FROM_UTF8) {
    970 			add_converter(sc, archive_string_append_unicode);
    971 			return;
    972 		}
    973 
    974 #if defined(_WIN32) && !defined(__CYGWIN__)
    975 		if (sc->flag & SCONV_WIN_CP) {
    976 			if (sc->flag & SCONV_TO_UTF16BE)
    977 				add_converter(sc, win_strncat_to_utf16be);
    978 			else
    979 				add_converter(sc, win_strncat_to_utf16le);
    980 			return;
    981 		}
    982 #endif
    983 
    984 #if defined(HAVE_ICONV)
    985 		if (sc->cd != (iconv_t)-1) {
    986 			add_converter(sc, iconv_strncat_in_locale);
    987 			return;
    988 		}
    989 #endif
    990 
    991 		if (sc->flag & SCONV_BEST_EFFORT) {
    992 			if (sc->flag & SCONV_TO_UTF16BE)
    993 				add_converter(sc,
    994 					best_effort_strncat_to_utf16be);
    995 			else
    996 				add_converter(sc,
    997 					best_effort_strncat_to_utf16le);
    998 		} else
    999 			/* Make sure we have no converter. */
   1000 			sc->nconverter = 0;
   1001 		return;
   1002 	}
   1003 
   1004 	/*
   1005 	 * Convert a string from UTF-16BE/LE.
   1006 	 */
   1007 	if (sc->flag & SCONV_FROM_UTF16) {
   1008 		/*
   1009 		 * At least we should normalize a UTF-16BE string.
   1010 		 */
   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);
   1015 
   1016 		if (sc->flag & SCONV_TO_UTF8) {
   1017 			/*
   1018 			 * If the current locale is UTF-8, we can translate
   1019 			 * a UTF-16BE/LE string into a UTF-8 string directly.
   1020 			 */
   1021 			if (!(sc->flag &
   1022 			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
   1023 				add_converter(sc,
   1024 				    archive_string_append_unicode);
   1025 			return;
   1026 		}
   1027 
   1028 #if defined(_WIN32) && !defined(__CYGWIN__)
   1029 		if (sc->flag & SCONV_WIN_CP) {
   1030 			if (sc->flag & SCONV_FROM_UTF16BE)
   1031 				add_converter(sc, win_strncat_from_utf16be);
   1032 			else
   1033 				add_converter(sc, win_strncat_from_utf16le);
   1034 			return;
   1035 		}
   1036 #endif
   1037 
   1038 #if defined(HAVE_ICONV)
   1039 		if (sc->cd != (iconv_t)-1) {
   1040 			add_converter(sc, iconv_strncat_in_locale);
   1041 			return;
   1042 		}
   1043 #endif
   1044 
   1045 		if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
   1046 		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
   1047 			add_converter(sc, best_effort_strncat_from_utf16be);
   1048 		else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
   1049 		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
   1050 			add_converter(sc, best_effort_strncat_from_utf16le);
   1051 		else
   1052 			/* Make sure we have no converter. */
   1053 			sc->nconverter = 0;
   1054 		return;
   1055 	}
   1056 
   1057 	if (sc->flag & SCONV_FROM_UTF8) {
   1058 		/*
   1059 		 * At least we should normalize a UTF-8 string.
   1060 		 */
   1061 		if (sc->flag & SCONV_NORMALIZATION_D)
   1062 			add_converter(sc,archive_string_normalize_D);
   1063 		else if (sc->flag & SCONV_NORMALIZATION_C)
   1064 			add_converter(sc, archive_string_normalize_C);
   1065 
   1066 		/*
   1067 		 * Copy UTF-8 string with a check of CESU-8.
   1068 		 * Apparently, iconv does not check surrogate pairs in UTF-8
   1069 		 * when both from-charset and to-charset are UTF-8, and then
   1070 		 * we use our UTF-8 copy code.
   1071 		 */
   1072 		if (sc->flag & SCONV_TO_UTF8) {
   1073 			/*
   1074 			 * If the current locale is UTF-8, we can translate
   1075 			 * a UTF-16BE string into a UTF-8 string directly.
   1076 			 */
   1077 			if (!(sc->flag &
   1078 			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
   1079 				add_converter(sc, strncat_from_utf8_to_utf8);
   1080 			return;
   1081 		}
   1082 	}
   1083 
   1084 #if defined(_WIN32) && !defined(__CYGWIN__)
   1085 	/*
   1086 	 * On Windows we can use Windows API for a string conversion.
   1087 	 */
   1088 	if (sc->flag & SCONV_WIN_CP) {
   1089 		add_converter(sc, strncat_in_codepage);
   1090 		return;
   1091 	}
   1092 #endif
   1093 
   1094 #if HAVE_ICONV
   1095 	if (sc->cd != (iconv_t)-1) {
   1096 		add_converter(sc, iconv_strncat_in_locale);
   1097 		/*
   1098 		 * iconv generally does not support UTF-8-MAC and so
   1099 		 * we have to the output of iconv from NFC to NFD if
   1100 		 * need.
   1101 		 */
   1102 		if ((sc->flag & SCONV_FROM_CHARSET) &&
   1103 		    (sc->flag & SCONV_TO_UTF8)) {
   1104 			if (sc->flag & SCONV_NORMALIZATION_D)
   1105 				add_converter(sc, archive_string_normalize_D);
   1106 		}
   1107 		return;
   1108 	}
   1109 #endif
   1110 
   1111 	/*
   1112 	 * Try conversion in the best effort or no conversion.
   1113 	 */
   1114 	if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
   1115 		add_converter(sc, best_effort_strncat_in_locale);
   1116 	else
   1117 		/* Make sure we have no converter. */
   1118 		sc->nconverter = 0;
   1119 }
   1120 
   1121 /*
   1122  * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
   1123  * and CP932 which are referenced in create_sconv_object().
   1124  */
   1125 static const char *
   1126 canonical_charset_name(const char *charset)
   1127 {
   1128 	char cs[16];
   1129 	char *p;
   1130 	const char *s;
   1131 
   1132 	if (charset == NULL || charset[0] == '\0'
   1133 	    || strlen(charset) > 15)
   1134 		return (charset);
   1135 
   1136 	/* Copy name to uppercase. */
   1137 	p = cs;
   1138 	s = charset;
   1139 	while (*s) {
   1140 		char c = *s++;
   1141 		if (c >= 'a' && c <= 'z')
   1142 			c -= 'a' - 'A';
   1143 		*p++ = c;
   1144 	}
   1145 	*p++ = '\0';
   1146 
   1147 	if (strcmp(cs, "UTF-8") == 0 ||
   1148 	    strcmp(cs, "UTF8") == 0)
   1149 		return ("UTF-8");
   1150 	if (strcmp(cs, "UTF-16BE") == 0 ||
   1151 	    strcmp(cs, "UTF16BE") == 0)
   1152 		return ("UTF-16BE");
   1153 	if (strcmp(cs, "UTF-16LE") == 0 ||
   1154 	    strcmp(cs, "UTF16LE") == 0)
   1155 		return ("UTF-16LE");
   1156 	if (strcmp(cs, "CP932") == 0)
   1157 		return ("CP932");
   1158 	return (charset);
   1159 }
   1160 
   1161 /*
   1162  * Create a string conversion object.
   1163  */
   1164 static struct archive_string_conv *
   1165 create_sconv_object(const char *fc, const char *tc,
   1166     unsigned current_codepage, int flag)
   1167 {
   1168 	struct archive_string_conv *sc;
   1169 
   1170 	sc = calloc(1, sizeof(*sc));
   1171 	if (sc == NULL)
   1172 		return (NULL);
   1173 	sc->next = NULL;
   1174 	sc->from_charset = strdup(fc);
   1175 	if (sc->from_charset == NULL) {
   1176 		free(sc);
   1177 		return (NULL);
   1178 	}
   1179 	sc->to_charset = strdup(tc);
   1180 	if (sc->to_charset == NULL) {
   1181 		free(sc->from_charset);
   1182 		free(sc);
   1183 		return (NULL);
   1184 	}
   1185 	archive_string_init(&sc->utftmp);
   1186 
   1187 	if (flag & SCONV_TO_CHARSET) {
   1188 		/*
   1189 		 * Convert characters from the current locale charset to
   1190 		 * a specified charset.
   1191 		 */
   1192 		sc->from_cp = current_codepage;
   1193 		sc->to_cp = make_codepage_from_charset(tc);
   1194 #if defined(_WIN32) && !defined(__CYGWIN__)
   1195 		if (IsValidCodePage(sc->to_cp))
   1196 			flag |= SCONV_WIN_CP;
   1197 #endif
   1198 	} else if (flag & SCONV_FROM_CHARSET) {
   1199 		/*
   1200 		 * Convert characters from a specified charset to
   1201 		 * the current locale charset.
   1202 		 */
   1203 		sc->to_cp = current_codepage;
   1204 		sc->from_cp = make_codepage_from_charset(fc);
   1205 #if defined(_WIN32) && !defined(__CYGWIN__)
   1206 		if (IsValidCodePage(sc->from_cp))
   1207 			flag |= SCONV_WIN_CP;
   1208 #endif
   1209 	}
   1210 
   1211 	/*
   1212 	 * Check if "from charset" and "to charset" are the same.
   1213 	 */
   1214 	if (strcmp(fc, tc) == 0 ||
   1215 	    (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
   1216 		sc->same = 1;
   1217 	else
   1218 		sc->same = 0;
   1219 
   1220 	/*
   1221 	 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
   1222 	 */
   1223 	if (strcmp(tc, "UTF-8") == 0)
   1224 		flag |= SCONV_TO_UTF8;
   1225 	else if (strcmp(tc, "UTF-16BE") == 0)
   1226 		flag |= SCONV_TO_UTF16BE;
   1227 	else if (strcmp(tc, "UTF-16LE") == 0)
   1228 		flag |= SCONV_TO_UTF16LE;
   1229 	if (strcmp(fc, "UTF-8") == 0)
   1230 		flag |= SCONV_FROM_UTF8;
   1231 	else if (strcmp(fc, "UTF-16BE") == 0)
   1232 		flag |= SCONV_FROM_UTF16BE;
   1233 	else if (strcmp(fc, "UTF-16LE") == 0)
   1234 		flag |= SCONV_FROM_UTF16LE;
   1235 #if defined(_WIN32) && !defined(__CYGWIN__)
   1236 	if (sc->to_cp == CP_UTF8)
   1237 		flag |= SCONV_TO_UTF8;
   1238 	else if (sc->to_cp == CP_UTF16BE)
   1239 		flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
   1240 	else if (sc->to_cp == CP_UTF16LE)
   1241 		flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
   1242 	if (sc->from_cp == CP_UTF8)
   1243 		flag |= SCONV_FROM_UTF8;
   1244 	else if (sc->from_cp == CP_UTF16BE)
   1245 		flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
   1246 	else if (sc->from_cp == CP_UTF16LE)
   1247 		flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
   1248 #endif
   1249 
   1250 	/*
   1251 	 * Set a flag for Unicode NFD. Usually iconv cannot correctly
   1252 	 * handle it. So we have to translate NFD characters to NFC ones
   1253 	 * ourselves before iconv handles. Another reason is to prevent
   1254 	 * that the same sight of two filenames, one is NFC and other
   1255 	 * is NFD, would be in its directory.
   1256 	 * On Mac OS X, although its filesystem layer automatically
   1257 	 * convert filenames to NFD, it would be useful for filename
   1258 	 * comparing to find out the same filenames that we normalize
   1259 	 * that to be NFD ourselves.
   1260 	 */
   1261 	if ((flag & SCONV_FROM_CHARSET) &&
   1262 	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
   1263 #if defined(__APPLE__)
   1264 		if (flag & SCONV_TO_UTF8)
   1265 			flag |= SCONV_NORMALIZATION_D;
   1266 		else
   1267 #endif
   1268 			flag |= SCONV_NORMALIZATION_C;
   1269 	}
   1270 #if defined(__APPLE__)
   1271 	/*
   1272 	 * In case writing an archive file, make sure that a filename
   1273 	 * going to be passed to iconv is a Unicode NFC string since
   1274 	 * a filename in HFS Plus filesystem is a Unicode NFD one and
   1275 	 * iconv cannot handle it with "UTF-8" charset. It is simpler
   1276 	 * than a use of "UTF-8-MAC" charset.
   1277 	 */
   1278 	if ((flag & SCONV_TO_CHARSET) &&
   1279 	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
   1280 	    !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
   1281 		flag |= SCONV_NORMALIZATION_C;
   1282 	/*
   1283 	 * In case reading an archive file. make sure that a filename
   1284 	 * will be passed to users is a Unicode NFD string in order to
   1285 	 * correctly compare the filename with other one which comes
   1286 	 * from HFS Plus filesystem.
   1287 	 */
   1288 	if ((flag & SCONV_FROM_CHARSET) &&
   1289 	   !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
   1290 	    (flag & SCONV_TO_UTF8))
   1291 		flag |= SCONV_NORMALIZATION_D;
   1292 #endif
   1293 
   1294 #if defined(HAVE_ICONV)
   1295 	sc->cd_w = (iconv_t)-1;
   1296 	/*
   1297 	 * Create an iconv object.
   1298 	 */
   1299 	if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
   1300 	    (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
   1301 	    (flag & SCONV_WIN_CP)) {
   1302 		/* This case we won't use iconv. */
   1303 		sc->cd = (iconv_t)-1;
   1304 	} else {
   1305 		sc->cd = iconv_open(tc, fc);
   1306 		if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
   1307 			/*
   1308 			 * Unfortunately, all of iconv implements do support
   1309 			 * "CP932" character-set, so we should use "SJIS"
   1310 			 * instead if iconv_open failed.
   1311 			 */
   1312 			if (strcmp(tc, "CP932") == 0)
   1313 				sc->cd = iconv_open("SJIS", fc);
   1314 			else if (strcmp(fc, "CP932") == 0)
   1315 				sc->cd = iconv_open(tc, "SJIS");
   1316 		}
   1317 #if defined(_WIN32) && !defined(__CYGWIN__)
   1318 		/*
   1319 		 * archive_mstring on Windows directly convert multi-bytes
   1320 		 * into archive_wstring in order not to depend on locale
   1321 		 * so that you can do a I18N programming. This will be
   1322 		 * used only in archive_mstring_copy_mbs_len_l so far.
   1323 		 */
   1324 		if (flag & SCONV_FROM_CHARSET) {
   1325 			sc->cd_w = iconv_open("UTF-8", fc);
   1326 			if (sc->cd_w == (iconv_t)-1 &&
   1327 			    (sc->flag & SCONV_BEST_EFFORT)) {
   1328 				if (strcmp(fc, "CP932") == 0)
   1329 					sc->cd_w = iconv_open("UTF-8", "SJIS");
   1330 			}
   1331 		}
   1332 #endif /* _WIN32 && !__CYGWIN__ */
   1333 	}
   1334 #endif	/* HAVE_ICONV */
   1335 
   1336 	sc->flag = flag;
   1337 
   1338 	/*
   1339 	 * Set up converters.
   1340 	 */
   1341 	setup_converter(sc);
   1342 
   1343 	return (sc);
   1344 }
   1345 
   1346 /*
   1347  * Free a string conversion object.
   1348  */
   1349 static void
   1350 free_sconv_object(struct archive_string_conv *sc)
   1351 {
   1352 	free(sc->from_charset);
   1353 	free(sc->to_charset);
   1354 	archive_string_free(&sc->utftmp);
   1355 #if HAVE_ICONV
   1356 	if (sc->cd != (iconv_t)-1)
   1357 		iconv_close(sc->cd);
   1358 	if (sc->cd_w != (iconv_t)-1)
   1359 		iconv_close(sc->cd_w);
   1360 #endif
   1361 	free(sc);
   1362 }
   1363 
   1364 #if defined(_WIN32) && !defined(__CYGWIN__)
   1365 # if defined(WINAPI_FAMILY_PARTITION) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
   1366 #  define GetOEMCP() CP_OEMCP
   1367 # endif
   1368 
   1369 static unsigned
   1370 my_atoi(const char *p)
   1371 {
   1372 	unsigned cp;
   1373 
   1374 	cp = 0;
   1375 	while (*p) {
   1376 		if (*p >= '0' && *p <= '9')
   1377 			cp = cp * 10 + (*p - '0');
   1378 		else
   1379 			return (-1);
   1380 		p++;
   1381 	}
   1382 	return (cp);
   1383 }
   1384 
   1385 /*
   1386  * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
   1387  * Return -1 if failed.
   1388  *
   1389  * Note: This translation code may be insufficient.
   1390  */
   1391 static struct charset {
   1392 	const char *name;
   1393 	unsigned cp;
   1394 } charsets[] = {
   1395 	/* MUST BE SORTED! */
   1396 	{"ASCII", 1252},
   1397 	{"ASMO-708", 708},
   1398 	{"BIG5", 950},
   1399 	{"CHINESE", 936},
   1400 	{"CP367", 1252},
   1401 	{"CP819", 1252},
   1402 	{"CP1025", 21025},
   1403 	{"DOS-720", 720},
   1404 	{"DOS-862", 862},
   1405 	{"EUC-CN", 51936},
   1406 	{"EUC-JP", 51932},
   1407 	{"EUC-KR", 949},
   1408 	{"EUCCN", 51936},
   1409 	{"EUCJP", 51932},
   1410 	{"EUCKR", 949},
   1411 	{"GB18030", 54936},
   1412 	{"GB2312", 936},
   1413 	{"HEBREW", 1255},
   1414 	{"HZ-GB-2312", 52936},
   1415 	{"IBM273", 20273},
   1416 	{"IBM277", 20277},
   1417 	{"IBM278", 20278},
   1418 	{"IBM280", 20280},
   1419 	{"IBM284", 20284},
   1420 	{"IBM285", 20285},
   1421 	{"IBM290", 20290},
   1422 	{"IBM297", 20297},
   1423 	{"IBM367", 1252},
   1424 	{"IBM420", 20420},
   1425 	{"IBM423", 20423},
   1426 	{"IBM424", 20424},
   1427 	{"IBM819", 1252},
   1428 	{"IBM871", 20871},
   1429 	{"IBM880", 20880},
   1430 	{"IBM905", 20905},
   1431 	{"IBM924", 20924},
   1432 	{"ISO-8859-1", 28591},
   1433 	{"ISO-8859-13", 28603},
   1434 	{"ISO-8859-15", 28605},
   1435 	{"ISO-8859-2", 28592},
   1436 	{"ISO-8859-3", 28593},
   1437 	{"ISO-8859-4", 28594},
   1438 	{"ISO-8859-5", 28595},
   1439 	{"ISO-8859-6", 28596},
   1440 	{"ISO-8859-7", 28597},
   1441 	{"ISO-8859-8", 28598},
   1442 	{"ISO-8859-9", 28599},
   1443 	{"ISO8859-1", 28591},
   1444 	{"ISO8859-13", 28603},
   1445 	{"ISO8859-15", 28605},
   1446 	{"ISO8859-2", 28592},
   1447 	{"ISO8859-3", 28593},
   1448 	{"ISO8859-4", 28594},
   1449 	{"ISO8859-5", 28595},
   1450 	{"ISO8859-6", 28596},
   1451 	{"ISO8859-7", 28597},
   1452 	{"ISO8859-8", 28598},
   1453 	{"ISO8859-9", 28599},
   1454 	{"JOHAB", 1361},
   1455 	{"KOI8-R", 20866},
   1456 	{"KOI8-U", 21866},
   1457 	{"KS_C_5601-1987", 949},
   1458 	{"LATIN1", 1252},
   1459 	{"LATIN2", 28592},
   1460 	{"MACINTOSH", 10000},
   1461 	{"SHIFT-JIS", 932},
   1462 	{"SHIFT_JIS", 932},
   1463 	{"SJIS", 932},
   1464 	{"US", 1252},
   1465 	{"US-ASCII", 1252},
   1466 	{"UTF-16", 1200},
   1467 	{"UTF-16BE", 1201},
   1468 	{"UTF-16LE", 1200},
   1469 	{"UTF-8", CP_UTF8},
   1470 	{"X-EUROPA", 29001},
   1471 	{"X-MAC-ARABIC", 10004},
   1472 	{"X-MAC-CE", 10029},
   1473 	{"X-MAC-CHINESEIMP", 10008},
   1474 	{"X-MAC-CHINESETRAD", 10002},
   1475 	{"X-MAC-CROATIAN", 10082},
   1476 	{"X-MAC-CYRILLIC", 10007},
   1477 	{"X-MAC-GREEK", 10006},
   1478 	{"X-MAC-HEBREW", 10005},
   1479 	{"X-MAC-ICELANDIC", 10079},
   1480 	{"X-MAC-JAPANESE", 10001},
   1481 	{"X-MAC-KOREAN", 10003},
   1482 	{"X-MAC-ROMANIAN", 10010},
   1483 	{"X-MAC-THAI", 10021},
   1484 	{"X-MAC-TURKISH", 10081},
   1485 	{"X-MAC-UKRAINIAN", 10017},
   1486 };
   1487 static unsigned
   1488 make_codepage_from_charset(const char *charset)
   1489 {
   1490 	char cs[16];
   1491 	char *p;
   1492 	unsigned cp;
   1493 	int a, b;
   1494 
   1495 	if (charset == NULL || strlen(charset) > 15)
   1496 		return -1;
   1497 
   1498 	/* Copy name to uppercase. */
   1499 	p = cs;
   1500 	while (*charset) {
   1501 		char c = *charset++;
   1502 		if (c >= 'a' && c <= 'z')
   1503 			c -= 'a' - 'A';
   1504 		*p++ = c;
   1505 	}
   1506 	*p++ = '\0';
   1507 	cp = -1;
   1508 
   1509 	/* Look it up in the table first, so that we can easily
   1510 	 * override CP367, which we map to 1252 instead of 367. */
   1511 	a = 0;
   1512 	b = sizeof(charsets)/sizeof(charsets[0]);
   1513 	while (b > a) {
   1514 		int c = (b + a) / 2;
   1515 		int r = strcmp(charsets[c].name, cs);
   1516 		if (r < 0)
   1517 			a = c + 1;
   1518 		else if (r > 0)
   1519 			b = c;
   1520 		else
   1521 			return charsets[c].cp;
   1522 	}
   1523 
   1524 	/* If it's not in the table, try to parse it. */
   1525 	switch (*cs) {
   1526 	case 'C':
   1527 		if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
   1528 			cp = my_atoi(cs + 2);
   1529 		} else if (strcmp(cs, "CP_ACP") == 0)
   1530 			cp = get_current_codepage();
   1531 		else if (strcmp(cs, "CP_OEMCP") == 0)
   1532 			cp = get_current_oemcp();
   1533 		break;
   1534 	case 'I':
   1535 		if (cs[1] == 'B' && cs[2] == 'M' &&
   1536 		    cs[3] >= '0' && cs[3] <= '9') {
   1537 			cp = my_atoi(cs + 3);
   1538 		}
   1539 		break;
   1540 	case 'W':
   1541 		if (strncmp(cs, "WINDOWS-", 8) == 0) {
   1542 			cp = my_atoi(cs + 8);
   1543 			if (cp != 874 && (cp < 1250 || cp > 1258))
   1544 				cp = -1;/* This may invalid code. */
   1545 		}
   1546 		break;
   1547 	}
   1548 	return (cp);
   1549 }
   1550 
   1551 /*
   1552  * Return ANSI Code Page of current locale set by setlocale().
   1553  */
   1554 static unsigned
   1555 get_current_codepage(void)
   1556 {
   1557 	char *locale, *p;
   1558 	unsigned cp;
   1559 
   1560 	locale = setlocale(LC_CTYPE, NULL);
   1561 	if (locale == NULL)
   1562 		return (GetACP());
   1563 	if (locale[0] == 'C' && locale[1] == '\0')
   1564 		return (CP_C_LOCALE);
   1565 	p = strrchr(locale, '.');
   1566 	if (p == NULL)
   1567 		return (GetACP());
   1568 	if ((strcmp(p+1, "utf8") == 0) || (strcmp(p+1, "UTF-8") == 0))
   1569 		return CP_UTF8;
   1570 	cp = my_atoi(p+1);
   1571 	if ((int)cp <= 0)
   1572 		return (GetACP());
   1573 	return (cp);
   1574 }
   1575 
   1576 /*
   1577  * Translation table between Locale Name and ACP/OEMCP.
   1578  */
   1579 static struct {
   1580 	unsigned acp;
   1581 	unsigned ocp;
   1582 	const char *locale;
   1583 } acp_ocp_map[] = {
   1584 	{  950,  950, "Chinese_Taiwan" },
   1585 	{  936,  936, "Chinese_People's Republic of China" },
   1586 	{  950,  950, "Chinese_Taiwan" },
   1587 	{ 1250,  852, "Czech_Czech Republic" },
   1588 	{ 1252,  850, "Danish_Denmark" },
   1589 	{ 1252,  850, "Dutch_Netherlands" },
   1590 	{ 1252,  850, "Dutch_Belgium" },
   1591 	{ 1252,  437, "English_United States" },
   1592 	{ 1252,  850, "English_Australia" },
   1593 	{ 1252,  850, "English_Canada" },
   1594 	{ 1252,  850, "English_New Zealand" },
   1595 	{ 1252,  850, "English_United Kingdom" },
   1596 	{ 1252,  437, "English_United States" },
   1597 	{ 1252,  850, "Finnish_Finland" },
   1598 	{ 1252,  850, "French_France" },
   1599 	{ 1252,  850, "French_Belgium" },
   1600 	{ 1252,  850, "French_Canada" },
   1601 	{ 1252,  850, "French_Switzerland" },
   1602 	{ 1252,  850, "German_Germany" },
   1603 	{ 1252,  850, "German_Austria" },
   1604 	{ 1252,  850, "German_Switzerland" },
   1605 	{ 1253,  737, "Greek_Greece" },
   1606 	{ 1250,  852, "Hungarian_Hungary" },
   1607 	{ 1252,  850, "Icelandic_Iceland" },
   1608 	{ 1252,  850, "Italian_Italy" },
   1609 	{ 1252,  850, "Italian_Switzerland" },
   1610 	{  932,  932, "Japanese_Japan" },
   1611 	{  949,  949, "Korean_Korea" },
   1612 	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
   1613 	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
   1614 	{ 1252,  850, "Norwegian-Nynorsk_Norway" },
   1615 	{ 1250,  852, "Polish_Poland" },
   1616 	{ 1252,  850, "Portuguese_Portugal" },
   1617 	{ 1252,  850, "Portuguese_Brazil" },
   1618 	{ 1251,  866, "Russian_Russia" },
   1619 	{ 1250,  852, "Slovak_Slovakia" },
   1620 	{ 1252,  850, "Spanish_Spain" },
   1621 	{ 1252,  850, "Spanish_Mexico" },
   1622 	{ 1252,  850, "Spanish_Spain" },
   1623 	{ 1252,  850, "Swedish_Sweden" },
   1624 	{ 1254,  857, "Turkish_Turkey" },
   1625 	{ 0, 0, NULL}
   1626 };
   1627 
   1628 /*
   1629  * Return OEM Code Page of current locale set by setlocale().
   1630  */
   1631 static unsigned
   1632 get_current_oemcp(void)
   1633 {
   1634 	int i;
   1635 	char *locale, *p;
   1636 	size_t len;
   1637 
   1638 	locale = setlocale(LC_CTYPE, NULL);
   1639 	if (locale == NULL)
   1640 		return (GetOEMCP());
   1641 	if (locale[0] == 'C' && locale[1] == '\0')
   1642 		return (CP_C_LOCALE);
   1643 
   1644 	p = strrchr(locale, '.');
   1645 	if (p == NULL)
   1646 		return (GetOEMCP());
   1647 	len = p - locale;
   1648 	for (i = 0; acp_ocp_map[i].acp; i++) {
   1649 		if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
   1650 			return (acp_ocp_map[i].ocp);
   1651 	}
   1652 	return (GetOEMCP());
   1653 }
   1654 #else
   1655 
   1656 /*
   1657  * POSIX platform does not use CodePage.
   1658  */
   1659 
   1660 static unsigned
   1661 get_current_codepage(void)
   1662 {
   1663 	return (-1);/* Unknown */
   1664 }
   1665 static unsigned
   1666 make_codepage_from_charset(const char *charset)
   1667 {
   1668 	(void)charset; /* UNUSED */
   1669 	return (-1);/* Unknown */
   1670 }
   1671 static unsigned
   1672 get_current_oemcp(void)
   1673 {
   1674 	return (-1);/* Unknown */
   1675 }
   1676 
   1677 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
   1678 
   1679 /*
   1680  * Return a string conversion object.
   1681  */
   1682 static struct archive_string_conv *
   1683 get_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
   1684 {
   1685 	struct archive_string_conv *sc;
   1686 	unsigned current_codepage;
   1687 
   1688 	/* Check if we have made the sconv object. */
   1689 	sc = find_sconv_object(a, fc, tc);
   1690 	if (sc != NULL)
   1691 		return (sc);
   1692 
   1693 	if (a == NULL)
   1694 		current_codepage = get_current_codepage();
   1695 	else
   1696 		current_codepage = a->current_codepage;
   1697 
   1698 	sc = create_sconv_object(canonical_charset_name(fc),
   1699 	    canonical_charset_name(tc), current_codepage, flag);
   1700 	if (sc == NULL) {
   1701 		if (a != NULL)
   1702 			archive_set_error(a, ENOMEM,
   1703 			    "Could not allocate memory for "
   1704 			    "a string conversion object");
   1705 		return (NULL);
   1706 	}
   1707 
   1708 	/*
   1709 	 * If there is no converter for current string conversion object,
   1710 	 * we cannot handle this conversion.
   1711 	 */
   1712 	if (sc->nconverter == 0) {
   1713 		if (a != NULL) {
   1714 #if HAVE_ICONV
   1715 			archive_set_error(a, ARCHIVE_ERRNO_MISC,
   1716 			    "iconv_open failed: Cannot handle ``%s''",
   1717 			    (flag & SCONV_TO_CHARSET)?tc:fc);
   1718 #else
   1719 			archive_set_error(a, ARCHIVE_ERRNO_MISC,
   1720 			    "A character-set conversion not fully supported "
   1721 			    "on this platform");
   1722 #endif
   1723 		}
   1724 		/* Failed; free a sconv object. */
   1725 		free_sconv_object(sc);
   1726 		return (NULL);
   1727 	}
   1728 
   1729 	/*
   1730 	 * Success!
   1731 	 */
   1732 	if (a != NULL)
   1733 		add_sconv_object(a, sc);
   1734 	return (sc);
   1735 }
   1736 
   1737 static const char *
   1738 get_current_charset(struct archive *a)
   1739 {
   1740 	const char *cur_charset;
   1741 
   1742 	if (a == NULL)
   1743 		cur_charset = default_iconv_charset("");
   1744 	else {
   1745 		cur_charset = default_iconv_charset(a->current_code);
   1746 		if (a->current_code == NULL) {
   1747 			a->current_code = strdup(cur_charset);
   1748 			a->current_codepage = get_current_codepage();
   1749 			a->current_oemcp = get_current_oemcp();
   1750 		}
   1751 	}
   1752 	return (cur_charset);
   1753 }
   1754 
   1755 /*
   1756  * Make and Return a string conversion object.
   1757  * Return NULL if the platform does not support the specified conversion
   1758  * and best_effort is 0.
   1759  * If best_effort is set, A string conversion object must be returned
   1760  * unless memory allocation for the object fails, but the conversion
   1761  * might fail when non-ASCII code is found.
   1762  */
   1763 struct archive_string_conv *
   1764 archive_string_conversion_to_charset(struct archive *a, const char *charset,
   1765     int best_effort)
   1766 {
   1767 	int flag = SCONV_TO_CHARSET;
   1768 
   1769 	if (best_effort)
   1770 		flag |= SCONV_BEST_EFFORT;
   1771 	return (get_sconv_object(a, get_current_charset(a), charset, flag));
   1772 }
   1773 
   1774 struct archive_string_conv *
   1775 archive_string_conversion_from_charset(struct archive *a, const char *charset,
   1776     int best_effort)
   1777 {
   1778 	int flag = SCONV_FROM_CHARSET;
   1779 
   1780 	if (best_effort)
   1781 		flag |= SCONV_BEST_EFFORT;
   1782 	return (get_sconv_object(a, charset, get_current_charset(a), flag));
   1783 }
   1784 
   1785 /*
   1786  * archive_string_default_conversion_*_archive() are provided for Windows
   1787  * platform because other archiver application use CP_OEMCP for
   1788  * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
   1789  * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
   1790  * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
   1791  * So we should make a string conversion between CP_ACP and CP_OEMCP
   1792  * for compatibility.
   1793  */
   1794 #if defined(_WIN32) && !defined(__CYGWIN__)
   1795 struct archive_string_conv *
   1796 archive_string_default_conversion_for_read(struct archive *a)
   1797 {
   1798 	const char *cur_charset = get_current_charset(a);
   1799 	char oemcp[16];
   1800 
   1801 	/* NOTE: a check of cur_charset is unneeded but we need
   1802 	 * that get_current_charset() has been surely called at
   1803 	 * this time whatever C compiler optimized. */
   1804 	if (cur_charset != NULL &&
   1805 	    (a->current_codepage == CP_C_LOCALE ||
   1806 	     a->current_codepage == a->current_oemcp))
   1807 		return (NULL);/* no conversion. */
   1808 
   1809 	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
   1810 	/* Make sure a null termination must be set. */
   1811 	oemcp[sizeof(oemcp)-1] = '\0';
   1812 	return (get_sconv_object(a, oemcp, cur_charset,
   1813 	    SCONV_FROM_CHARSET));
   1814 }
   1815 
   1816 struct archive_string_conv *
   1817 archive_string_default_conversion_for_write(struct archive *a)
   1818 {
   1819 	const char *cur_charset = get_current_charset(a);
   1820 	char oemcp[16];
   1821 
   1822 	/* NOTE: a check of cur_charset is unneeded but we need
   1823 	 * that get_current_charset() has been surely called at
   1824 	 * this time whatever C compiler optimized. */
   1825 	if (cur_charset != NULL &&
   1826 	    (a->current_codepage == CP_C_LOCALE ||
   1827 	     a->current_codepage == a->current_oemcp))
   1828 		return (NULL);/* no conversion. */
   1829 
   1830 	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
   1831 	/* Make sure a null termination must be set. */
   1832 	oemcp[sizeof(oemcp)-1] = '\0';
   1833 	return (get_sconv_object(a, cur_charset, oemcp,
   1834 	    SCONV_TO_CHARSET));
   1835 }
   1836 #else
   1837 struct archive_string_conv *
   1838 archive_string_default_conversion_for_read(struct archive *a)
   1839 {
   1840 	(void)a; /* UNUSED */
   1841 	return (NULL);
   1842 }
   1843 
   1844 struct archive_string_conv *
   1845 archive_string_default_conversion_for_write(struct archive *a)
   1846 {
   1847 	(void)a; /* UNUSED */
   1848 	return (NULL);
   1849 }
   1850 #endif
   1851 
   1852 /*
   1853  * Dispose of all character conversion objects in the archive object.
   1854  */
   1855 void
   1856 archive_string_conversion_free(struct archive *a)
   1857 {
   1858 	struct archive_string_conv *sc;
   1859 	struct archive_string_conv *sc_next;
   1860 
   1861 	for (sc = a->sconv; sc != NULL; sc = sc_next) {
   1862 		sc_next = sc->next;
   1863 		free_sconv_object(sc);
   1864 	}
   1865 	a->sconv = NULL;
   1866 	free(a->current_code);
   1867 	a->current_code = NULL;
   1868 }
   1869 
   1870 /*
   1871  * Return a conversion charset name.
   1872  */
   1873 const char *
   1874 archive_string_conversion_charset_name(struct archive_string_conv *sc)
   1875 {
   1876 	if (sc == NULL) {
   1877 		return "current locale";
   1878 	}
   1879 	if (sc->flag & SCONV_TO_CHARSET)
   1880 		return (sc->to_charset);
   1881 	else
   1882 		return (sc->from_charset);
   1883 }
   1884 
   1885 /*
   1886  * Change the behavior of a string conversion.
   1887  */
   1888 void
   1889 archive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
   1890 {
   1891 	switch (opt) {
   1892 	/*
   1893 	 * A filename in UTF-8 was made with libarchive 2.x in a wrong
   1894 	 * assumption that wchar_t was Unicode.
   1895 	 * This option enables simulating the assumption in order to read
   1896 	 * that filename correctly.
   1897 	 */
   1898 	case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
   1899 #if (defined(_WIN32) && !defined(__CYGWIN__)) \
   1900 	 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
   1901 		/*
   1902 		 * Nothing to do for it since wchar_t on these platforms
   1903 		 * is really Unicode.
   1904 		 */
   1905 		(void)sc; /* UNUSED */
   1906 #else
   1907 		if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
   1908 			sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
   1909 			/* Set up string converters. */
   1910 			setup_converter(sc);
   1911 		}
   1912 #endif
   1913 		break;
   1914 	case SCONV_SET_OPT_NORMALIZATION_C:
   1915 		if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
   1916 			sc->flag |= SCONV_NORMALIZATION_C;
   1917 			sc->flag &= ~SCONV_NORMALIZATION_D;
   1918 			/* Set up string converters. */
   1919 			setup_converter(sc);
   1920 		}
   1921 		break;
   1922 	case SCONV_SET_OPT_NORMALIZATION_D:
   1923 #if defined(HAVE_ICONV)
   1924 		/*
   1925 		 * If iconv will take the string, do not change the
   1926 		 * setting of the normalization.
   1927 		 */
   1928 		if (!(sc->flag & SCONV_WIN_CP) &&
   1929 		     (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
   1930 		    !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
   1931 			break;
   1932 #endif
   1933 		if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
   1934 			sc->flag |= SCONV_NORMALIZATION_D;
   1935 			sc->flag &= ~SCONV_NORMALIZATION_C;
   1936 			/* Set up string converters. */
   1937 			setup_converter(sc);
   1938 		}
   1939 		break;
   1940 	default:
   1941 		break;
   1942 	}
   1943 }
   1944 
   1945 /*
   1946  *
   1947  * Copy one archive_string to another in locale conversion.
   1948  *
   1949  *	archive_strncat_l();
   1950  *	archive_strncpy_l();
   1951  *
   1952  */
   1953 
   1954 static size_t
   1955 mbsnbytes(const void *_p, size_t n)
   1956 {
   1957 	size_t s;
   1958 	const char *p, *pp;
   1959 
   1960 	if (_p == NULL)
   1961 		return (0);
   1962 	p = (const char *)_p;
   1963 
   1964 	/* Like strlen(p), except won't examine positions beyond p[n]. */
   1965 	s = 0;
   1966 	pp = p;
   1967 	while (s < n && *pp) {
   1968 		pp++;
   1969 		s++;
   1970 	}
   1971 	return (s);
   1972 }
   1973 
   1974 static size_t
   1975 utf16nbytes(const void *_p, size_t n)
   1976 {
   1977 	size_t s;
   1978 	const char *p, *pp;
   1979 
   1980 	if (_p == NULL)
   1981 		return (0);
   1982 	p = (const char *)_p;
   1983 
   1984 	/* Like strlen(p), except won't examine positions beyond p[n]. */
   1985 	s = 0;
   1986 	pp = p;
   1987 	n >>= 1;
   1988 	while (s < n && (pp[0] || pp[1])) {
   1989 		pp += 2;
   1990 		s++;
   1991 	}
   1992 	return (s<<1);
   1993 }
   1994 
   1995 int
   1996 archive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
   1997     struct archive_string_conv *sc)
   1998 {
   1999 	as->length = 0;
   2000 	return (archive_strncat_l(as, _p, n, sc));
   2001 }
   2002 
   2003 int
   2004 archive_strncat_l(struct archive_string *as, const void *_p, size_t n,
   2005     struct archive_string_conv *sc)
   2006 {
   2007 	const void *s;
   2008 	size_t length = 0;
   2009 	int i, r = 0, r2;
   2010 
   2011 	if (_p != NULL && n > 0) {
   2012 		if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
   2013 			length = utf16nbytes(_p, n);
   2014 		else
   2015 			length = mbsnbytes(_p, n);
   2016 	}
   2017 
   2018 	/* We must allocate memory even if there is no data for conversion
   2019 	 * or copy. This simulates archive_string_append behavior. */
   2020 	if (length == 0) {
   2021 		size_t tn = 1;
   2022 		if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
   2023 			tn = 2;
   2024 		if (archive_string_ensure(as, as->length + tn) == NULL)
   2025 			return (-1);
   2026 		as->s[as->length] = 0;
   2027 		if (tn == 2)
   2028 			as->s[as->length+1] = 0;
   2029 		return (0);
   2030 	}
   2031 
   2032 	/*
   2033 	 * If sc is NULL, we just make a copy.
   2034 	 */
   2035 	if (sc == NULL) {
   2036 		if (archive_string_append(as, _p, length) == NULL)
   2037 			return (-1);/* No memory */
   2038 		return (0);
   2039 	}
   2040 
   2041 	s = _p;
   2042 	i = 0;
   2043 	if (sc->nconverter > 1) {
   2044 		sc->utftmp.length = 0;
   2045 		r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
   2046 		if (r2 != 0 && errno == ENOMEM)
   2047 			return (r2);
   2048 		if (r > r2)
   2049 			r = r2;
   2050 		s = sc->utftmp.s;
   2051 		length = sc->utftmp.length;
   2052 		++i;
   2053 	}
   2054 	r2 = sc->converter[i](as, s, length, sc);
   2055 	if (r > r2)
   2056 		r = r2;
   2057 	return (r);
   2058 }
   2059 
   2060 struct archive_string *
   2061 archive_string_dirname(struct archive_string *as)
   2062 {
   2063 	/* strip trailing separators */
   2064 	while (as->length > 1 && as->s[as->length - 1] == '/')
   2065 		as->length--;
   2066 	/* strip final component */
   2067 	while (as->length > 0 && as->s[as->length - 1] != '/')
   2068 		as->length--;
   2069 	/* empty path -> cwd */
   2070 	if (as->length == 0)
   2071 		return (archive_strcat(as, "."));
   2072 	/* strip separator(s) */
   2073 	while (as->length > 1 && as->s[as->length - 1] == '/')
   2074 		as->length--;
   2075 	/* terminate */
   2076 	as->s[as->length] = '\0';
   2077 	return (as);
   2078 }
   2079 
   2080 #if HAVE_ICONV
   2081 
   2082 /*
   2083  * Return -1 if conversion fails.
   2084  */
   2085 static int
   2086 iconv_strncat_in_locale(struct archive_string *as, const void *_p,
   2087     size_t length, struct archive_string_conv *sc)
   2088 {
   2089 	ICONV_CONST char *itp;
   2090 	size_t remaining;
   2091 	iconv_t cd;
   2092 	char *outp;
   2093 	size_t avail, bs;
   2094 	int return_value = 0; /* success */
   2095 	size_t to_size, from_size;
   2096 
   2097 	if (sc->flag & SCONV_TO_UTF16)
   2098 		to_size = 2;
   2099 	else
   2100 		to_size = 1;
   2101 	if (sc->flag & SCONV_FROM_UTF16)
   2102 		from_size = 2;
   2103 	else
   2104 		from_size = 1;
   2105 
   2106 	if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
   2107 		return (-1);
   2108 
   2109 	cd = sc->cd;
   2110 	itp = (char *)(uintptr_t)_p;
   2111 	remaining = length;
   2112 	outp = as->s + as->length;
   2113 	avail = as->buffer_length - as->length - to_size;
   2114 	while (remaining >= from_size) {
   2115 		size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
   2116 
   2117 		if (result != (size_t)-1)
   2118 			break; /* Conversion completed. */
   2119 
   2120 		if (errno == EILSEQ || errno == EINVAL) {
   2121 			/*
   2122 		 	 * If an output charset is UTF-8 or UTF-16BE/LE,
   2123 			 * unknown character should be U+FFFD
   2124 			 * (replacement character).
   2125 			 */
   2126 			if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
   2127 				size_t rbytes;
   2128 				if (sc->flag & SCONV_TO_UTF8)
   2129 					rbytes = sizeof(utf8_replacement_char);
   2130 				else
   2131 					rbytes = 2;
   2132 
   2133 				if (avail < rbytes) {
   2134 					as->length = outp - as->s;
   2135 					bs = as->buffer_length +
   2136 					    (remaining * to_size) + rbytes;
   2137 					if (NULL ==
   2138 					    archive_string_ensure(as, bs))
   2139 						return (-1);
   2140 					outp = as->s + as->length;
   2141 					avail = as->buffer_length
   2142 					    - as->length - to_size;
   2143 				}
   2144 				if (sc->flag & SCONV_TO_UTF8)
   2145 					memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
   2146 				else if (sc->flag & SCONV_TO_UTF16BE)
   2147 					archive_be16enc(outp, UNICODE_R_CHAR);
   2148 				else
   2149 					archive_le16enc(outp, UNICODE_R_CHAR);
   2150 				outp += rbytes;
   2151 				avail -= rbytes;
   2152 			} else {
   2153 				/* Skip the illegal input bytes. */
   2154 				*outp++ = '?';
   2155 				avail--;
   2156 			}
   2157 			itp += from_size;
   2158 			remaining -= from_size;
   2159 			return_value = -1; /* failure */
   2160 		} else {
   2161 			/* E2BIG no output buffer,
   2162 			 * Increase an output buffer.  */
   2163 			as->length = outp - as->s;
   2164 			bs = as->buffer_length + remaining * 2;
   2165 			if (NULL == archive_string_ensure(as, bs))
   2166 				return (-1);
   2167 			outp = as->s + as->length;
   2168 			avail = as->buffer_length - as->length - to_size;
   2169 		}
   2170 	}
   2171 	as->length = outp - as->s;
   2172 	as->s[as->length] = 0;
   2173 	if (to_size == 2)
   2174 		as->s[as->length+1] = 0;
   2175 	return (return_value);
   2176 }
   2177 
   2178 #endif /* HAVE_ICONV */
   2179 
   2180 
   2181 #if defined(_WIN32) && !defined(__CYGWIN__)
   2182 
   2183 /*
   2184  * Translate a string from a some CodePage to an another CodePage by
   2185  * Windows APIs, and copy the result. Return -1 if conversion fails.
   2186  */
   2187 static int
   2188 strncat_in_codepage(struct archive_string *as,
   2189     const void *_p, size_t length, struct archive_string_conv *sc)
   2190 {
   2191 	const char *s = (const char *)_p;
   2192 	struct archive_wstring aws;
   2193 	size_t l;
   2194 	int r, saved_flag;
   2195 
   2196 	archive_string_init(&aws);
   2197 	saved_flag = sc->flag;
   2198 	sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
   2199 	r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
   2200 	sc->flag = saved_flag;
   2201 	if (r != 0) {
   2202 		archive_wstring_free(&aws);
   2203 		if (errno != ENOMEM)
   2204 			archive_string_append(as, s, length);
   2205 		return (-1);
   2206 	}
   2207 
   2208 	l = as->length;
   2209 	r = archive_string_append_from_wcs_in_codepage(
   2210 	    as, aws.s, aws.length, sc);
   2211 	if (r != 0 && errno != ENOMEM && l == as->length)
   2212 		archive_string_append(as, s, length);
   2213 	archive_wstring_free(&aws);
   2214 	return (r);
   2215 }
   2216 
   2217 /*
   2218  * Test whether MBS ==> WCS is okay.
   2219  */
   2220 static int
   2221 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
   2222 {
   2223 	const char *p = (const char *)_p;
   2224 	unsigned codepage;
   2225 	DWORD mbflag = MB_ERR_INVALID_CHARS;
   2226 
   2227 	if (sc->flag & SCONV_FROM_CHARSET)
   2228 		codepage = sc->to_cp;
   2229 	else
   2230 		codepage = sc->from_cp;
   2231 
   2232 	if (codepage == CP_C_LOCALE)
   2233 		return (0);
   2234 	if (codepage != CP_UTF8)
   2235 		mbflag |= MB_PRECOMPOSED;
   2236 
   2237 	if (n > (size_t)INT_MAX)
   2238 		return (-1); /* Invalid */
   2239 	if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
   2240 		return (-1); /* Invalid */
   2241 	return (0); /* Okay */
   2242 }
   2243 
   2244 #else
   2245 
   2246 /*
   2247  * Test whether MBS ==> WCS is okay.
   2248  */
   2249 static int
   2250 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
   2251 {
   2252 	const char *p = (const char *)_p;
   2253 	size_t r;
   2254 
   2255 #if HAVE_MBRTOWC
   2256 	mbstate_t shift_state;
   2257 
   2258 	memset(&shift_state, 0, sizeof(shift_state));
   2259 #else
   2260 	/* Clear the shift state before starting. */
   2261 	mbtowc(NULL, NULL, 0);
   2262 #endif
   2263 	while (n) {
   2264 		wchar_t wc;
   2265 
   2266 #if HAVE_MBRTOWC
   2267 		r = mbrtowc(&wc, p, n, &shift_state);
   2268 #else
   2269 		r = mbtowc(&wc, p, n);
   2270 #endif
   2271 		if (r == (size_t)-1 || r == (size_t)-2)
   2272 			return (-1);/* Invalid. */
   2273 		if (r == 0)
   2274 			break;
   2275 		p += r;
   2276 		n -= r;
   2277 	}
   2278 	(void)sc; /* UNUSED */
   2279 	return (0); /* All Okey. */
   2280 }
   2281 
   2282 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
   2283 
   2284 /*
   2285  * Basically returns -1 because we cannot make a conversion of charset
   2286  * without iconv but in some cases this would return 0.
   2287  * Returns 0 if all copied characters are ASCII.
   2288  * Returns 0 if both from-locale and to-locale are the same and those
   2289  * can be WCS with no error.
   2290  */
   2291 static int
   2292 best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
   2293     size_t length, struct archive_string_conv *sc)
   2294 {
   2295 	size_t remaining;
   2296 	const uint8_t *itp;
   2297 	int return_value = 0; /* success */
   2298 
   2299 	/*
   2300 	 * If both from-locale and to-locale is the same, this makes a copy.
   2301 	 * And then this checks all copied MBS can be WCS if so returns 0.
   2302 	 */
   2303 	if (sc->same) {
   2304 		if (archive_string_append(as, _p, length) == NULL)
   2305 			return (-1);/* No memory */
   2306 		return (invalid_mbs(_p, length, sc));
   2307 	}
   2308 
   2309 	/*
   2310 	 * If a character is ASCII, this just copies it. If not, this
   2311 	 * assigns '?' character instead but in UTF-8 locale this assigns
   2312 	 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
   2313 	 * a Replacement Character in Unicode.
   2314 	 */
   2315 
   2316 	remaining = length;
   2317 	itp = (const uint8_t *)_p;
   2318 	while (*itp && remaining > 0) {
   2319 		if (*itp > 127) {
   2320 			// Non-ASCII: Substitute with suitable replacement
   2321 			if (sc->flag & SCONV_TO_UTF8) {
   2322 				if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
   2323 					__archive_errx(1, "Out of memory");
   2324 				}
   2325 			} else {
   2326 				archive_strappend_char(as, '?');
   2327 			}
   2328 			return_value = -1;
   2329 		} else {
   2330 			archive_strappend_char(as, *itp);
   2331 		}
   2332 		++itp;
   2333 	}
   2334 	return (return_value);
   2335 }
   2336 
   2337 
   2338 /*
   2339  * Unicode conversion functions.
   2340  *   - UTF-8 <===> UTF-8 in removing surrogate pairs.
   2341  *   - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
   2342  *   - UTF-8 made by libarchive 2.x ===> UTF-8.
   2343  *   - UTF-16BE <===> UTF-8.
   2344  *
   2345  */
   2346 
   2347 /*
   2348  * Utility to convert a single UTF-8 sequence.
   2349  *
   2350  * Usually return used bytes, return used byte in negative value when
   2351  * a unicode character is replaced with U+FFFD.
   2352  * See also http://unicode.org/review/pr-121.html Public Review Issue #121
   2353  * Recommended Practice for Replacement Characters.
   2354  */
   2355 static int
   2356 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
   2357 {
   2358 	static const char utf8_count[256] = {
   2359 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
   2360 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
   2361 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
   2362 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
   2363 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
   2364 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
   2365 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
   2366 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
   2367 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
   2368 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
   2369 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
   2370 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
   2371 		 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
   2372 		 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
   2373 		 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
   2374 		 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
   2375 	};
   2376 	int ch, i;
   2377 	int cnt;
   2378 	uint32_t wc;
   2379 
   2380 	/* Sanity check. */
   2381 	if (n == 0)
   2382 		return (0);
   2383 	/*
   2384 	 * Decode 1-4 bytes depending on the value of the first byte.
   2385 	 */
   2386 	ch = (unsigned char)*s;
   2387 	if (ch == 0)
   2388 		return (0); /* Standard:  return 0 for end-of-string. */
   2389 	cnt = utf8_count[ch];
   2390 
   2391 	/* Invalid sequence or there are not plenty bytes. */
   2392 	if (n < (size_t)cnt) {
   2393 		cnt = (int)n;
   2394 		for (i = 1; i < cnt; i++) {
   2395 			if ((s[i] & 0xc0) != 0x80) {
   2396 				cnt = i;
   2397 				break;
   2398 			}
   2399 		}
   2400 		goto invalid_sequence;
   2401 	}
   2402 
   2403 	/* Make a Unicode code point from a single UTF-8 sequence. */
   2404 	switch (cnt) {
   2405 	case 1:	/* 1 byte sequence. */
   2406 		*pwc = ch & 0x7f;
   2407 		return (cnt);
   2408 	case 2:	/* 2 bytes sequence. */
   2409 		if ((s[1] & 0xc0) != 0x80) {
   2410 			cnt = 1;
   2411 			goto invalid_sequence;
   2412 		}
   2413 		*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
   2414 		return (cnt);
   2415 	case 3:	/* 3 bytes sequence. */
   2416 		if ((s[1] & 0xc0) != 0x80) {
   2417 			cnt = 1;
   2418 			goto invalid_sequence;
   2419 		}
   2420 		if ((s[2] & 0xc0) != 0x80) {
   2421 			cnt = 2;
   2422 			goto invalid_sequence;
   2423 		}
   2424 		wc = ((ch & 0x0f) << 12)
   2425 		    | ((s[1] & 0x3f) << 6)
   2426 		    | (s[2] & 0x3f);
   2427 		if (wc < 0x800)
   2428 			goto invalid_sequence;/* Overlong sequence. */
   2429 		break;
   2430 	case 4:	/* 4 bytes sequence. */
   2431 		if ((s[1] & 0xc0) != 0x80) {
   2432 			cnt = 1;
   2433 			goto invalid_sequence;
   2434 		}
   2435 		if ((s[2] & 0xc0) != 0x80) {
   2436 			cnt = 2;
   2437 			goto invalid_sequence;
   2438 		}
   2439 		if ((s[3] & 0xc0) != 0x80) {
   2440 			cnt = 3;
   2441 			goto invalid_sequence;
   2442 		}
   2443 		wc = ((ch & 0x07) << 18)
   2444 		    | ((s[1] & 0x3f) << 12)
   2445 		    | ((s[2] & 0x3f) << 6)
   2446 		    | (s[3] & 0x3f);
   2447 		if (wc < 0x10000)
   2448 			goto invalid_sequence;/* Overlong sequence. */
   2449 		break;
   2450 	default: /* Others are all invalid sequence. */
   2451 		if (ch == 0xc0 || ch == 0xc1)
   2452 			cnt = 2;
   2453 		else if (ch >= 0xf5 && ch <= 0xf7)
   2454 			cnt = 4;
   2455 		else if (ch >= 0xf8 && ch <= 0xfb)
   2456 			cnt = 5;
   2457 		else if (ch == 0xfc || ch == 0xfd)
   2458 			cnt = 6;
   2459 		else
   2460 			cnt = 1;
   2461 		if (n < (size_t)cnt)
   2462 			cnt = (int)n;
   2463 		for (i = 1; i < cnt; i++) {
   2464 			if ((s[i] & 0xc0) != 0x80) {
   2465 				cnt = i;
   2466 				break;
   2467 			}
   2468 		}
   2469 		goto invalid_sequence;
   2470 	}
   2471 
   2472 	/* The code point larger than 0x10FFFF is not legal
   2473 	 * Unicode values. */
   2474 	if (wc > UNICODE_MAX)
   2475 		goto invalid_sequence;
   2476 	/* Correctly gets a Unicode, returns used bytes. */
   2477 	*pwc = wc;
   2478 	return (cnt);
   2479 invalid_sequence:
   2480 	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
   2481 	return (cnt * -1);
   2482 }
   2483 
   2484 static int
   2485 utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
   2486 {
   2487 	int cnt;
   2488 
   2489 	cnt = _utf8_to_unicode(pwc, s, n);
   2490 	/* Any of Surrogate pair is not legal Unicode values. */
   2491 	if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
   2492 		return (-3);
   2493 	return (cnt);
   2494 }
   2495 
   2496 static inline uint32_t
   2497 combine_surrogate_pair(uint32_t uc, uint32_t uc2)
   2498 {
   2499 	uc -= 0xD800;
   2500 	uc *= 0x400;
   2501 	uc += uc2 - 0xDC00;
   2502 	uc += 0x10000;
   2503 	return (uc);
   2504 }
   2505 
   2506 /*
   2507  * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
   2508  * removing surrogate pairs.
   2509  *
   2510  * CESU-8: The Compatibility Encoding Scheme for UTF-16.
   2511  *
   2512  * Usually return used bytes, return used byte in negative value when
   2513  * a unicode character is replaced with U+FFFD.
   2514  */
   2515 static int
   2516 cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
   2517 {
   2518 	uint32_t wc = 0;
   2519 	int cnt;
   2520 
   2521 	cnt = _utf8_to_unicode(&wc, s, n);
   2522 	if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
   2523 		uint32_t wc2 = 0;
   2524 		if (n - 3 < 3) {
   2525 			/* Invalid byte sequence. */
   2526 			goto invalid_sequence;
   2527 		}
   2528 		cnt = _utf8_to_unicode(&wc2, s+3, n-3);
   2529 		if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
   2530 			/* Invalid byte sequence. */
   2531 			goto invalid_sequence;
   2532 		}
   2533 		wc = combine_surrogate_pair(wc, wc2);
   2534 		cnt = 6;
   2535 	} else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
   2536 		/* Invalid byte sequence. */
   2537 		goto invalid_sequence;
   2538 	}
   2539 	*pwc = wc;
   2540 	return (cnt);
   2541 invalid_sequence:
   2542 	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
   2543 	if (cnt > 0)
   2544 		cnt *= -1;
   2545 	return (cnt);
   2546 }
   2547 
   2548 /*
   2549  * Convert a Unicode code point to a single UTF-8 sequence.
   2550  *
   2551  * NOTE:This function does not check if the Unicode is legal or not.
   2552  * Please you definitely check it before calling this.
   2553  */
   2554 static size_t
   2555 unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
   2556 {
   2557 	char *_p = p;
   2558 
   2559 	/* Invalid Unicode char maps to Replacement character */
   2560 	if (uc > UNICODE_MAX)
   2561 		uc = UNICODE_R_CHAR;
   2562 	/* Translate code point to UTF8 */
   2563 	if (uc <= 0x7f) {
   2564 		if (remaining == 0)
   2565 			return (0);
   2566 		*p++ = (char)uc;
   2567 	} else if (uc <= 0x7ff) {
   2568 		if (remaining < 2)
   2569 			return (0);
   2570 		*p++ = 0xc0 | ((uc >> 6) & 0x1f);
   2571 		*p++ = 0x80 | (uc & 0x3f);
   2572 	} else if (uc <= 0xffff) {
   2573 		if (remaining < 3)
   2574 			return (0);
   2575 		*p++ = 0xe0 | ((uc >> 12) & 0x0f);
   2576 		*p++ = 0x80 | ((uc >> 6) & 0x3f);
   2577 		*p++ = 0x80 | (uc & 0x3f);
   2578 	} else {
   2579 		if (remaining < 4)
   2580 			return (0);
   2581 		*p++ = 0xf0 | ((uc >> 18) & 0x07);
   2582 		*p++ = 0x80 | ((uc >> 12) & 0x3f);
   2583 		*p++ = 0x80 | ((uc >> 6) & 0x3f);
   2584 		*p++ = 0x80 | (uc & 0x3f);
   2585 	}
   2586 	return (p - _p);
   2587 }
   2588 
   2589 static int
   2590 utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
   2591 {
   2592 	return (utf16_to_unicode(pwc, s, n, 1));
   2593 }
   2594 
   2595 static int
   2596 utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
   2597 {
   2598 	return (utf16_to_unicode(pwc, s, n, 0));
   2599 }
   2600 
   2601 static int
   2602 utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
   2603 {
   2604 	const char *utf16 = s;
   2605 	unsigned uc;
   2606 
   2607 	if (n == 0)
   2608 		return (0);
   2609 	if (n == 1) {
   2610 		/* set the Replacement Character instead. */
   2611 		*pwc = UNICODE_R_CHAR;
   2612 		return (-1);
   2613 	}
   2614 
   2615 	if (be)
   2616 		uc = archive_be16dec(utf16);
   2617 	else
   2618 		uc = archive_le16dec(utf16);
   2619 	utf16 += 2;
   2620 
   2621 	/* If this is a surrogate pair, assemble the full code point.*/
   2622 	if (IS_HIGH_SURROGATE_LA(uc)) {
   2623 		unsigned uc2;
   2624 
   2625 		if (n >= 4) {
   2626 			if (be)
   2627 				uc2 = archive_be16dec(utf16);
   2628 			else
   2629 				uc2 = archive_le16dec(utf16);
   2630 		} else
   2631 			uc2 = 0;
   2632 		if (IS_LOW_SURROGATE_LA(uc2)) {
   2633 			uc = combine_surrogate_pair(uc, uc2);
   2634 			utf16 += 2;
   2635 		} else {
   2636 	 		/* Undescribed code point should be U+FFFD
   2637 		 	* (replacement character). */
   2638 			*pwc = UNICODE_R_CHAR;
   2639 			return (-2);
   2640 		}
   2641 	}
   2642 
   2643 	/*
   2644 	 * Surrogate pair values(0xd800 through 0xdfff) are only
   2645 	 * used by UTF-16, so, after above calculation, the code
   2646 	 * must not be surrogate values, and Unicode has no codes
   2647 	 * larger than 0x10ffff. Thus, those are not legal Unicode
   2648 	 * values.
   2649 	 */
   2650 	if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
   2651 	 	/* Undescribed code point should be U+FFFD
   2652 	 	* (replacement character). */
   2653 		*pwc = UNICODE_R_CHAR;
   2654 		return (((int)(utf16 - s)) * -1);
   2655 	}
   2656 	*pwc = uc;
   2657 	return ((int)(utf16 - s));
   2658 }
   2659 
   2660 static size_t
   2661 unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
   2662 {
   2663 	char *utf16 = p;
   2664 
   2665 	if (uc > 0xffff) {
   2666 		/* We have a code point that won't fit into a
   2667 		 * wchar_t; convert it to a surrogate pair. */
   2668 		if (remaining < 4)
   2669 			return (0);
   2670 		uc -= 0x10000;
   2671 		archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
   2672 		archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
   2673 		return (4);
   2674 	} else {
   2675 		if (remaining < 2)
   2676 			return (0);
   2677 		archive_be16enc(utf16, (uint16_t)uc);
   2678 		return (2);
   2679 	}
   2680 }
   2681 
   2682 static size_t
   2683 unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
   2684 {
   2685 	char *utf16 = p;
   2686 
   2687 	if (uc > 0xffff) {
   2688 		/* We have a code point that won't fit into a
   2689 		 * wchar_t; convert it to a surrogate pair. */
   2690 		if (remaining < 4)
   2691 			return (0);
   2692 		uc -= 0x10000;
   2693 		archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
   2694 		archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
   2695 		return (4);
   2696 	} else {
   2697 		if (remaining < 2)
   2698 			return (0);
   2699 		archive_le16enc(utf16, (uint16_t)uc);
   2700 		return (2);
   2701 	}
   2702 }
   2703 
   2704 /*
   2705  * Append new UTF-8 string to existing UTF-8 string.
   2706  * Existing string is assumed to already be in proper form;
   2707  * the new string will have invalid sequences replaced and
   2708  * surrogate pairs canonicalized.
   2709  */
   2710 static int
   2711 strncat_from_utf8_to_utf8(struct archive_string *as, const void *_src,
   2712     size_t len, struct archive_string_conv *sc)
   2713 {
   2714 	int ret = 0;
   2715 	const char *src = _src;
   2716 	(void)sc; /* UNUSED */
   2717 
   2718 	/* Pre-extend the destination */
   2719 	if (archive_string_ensure(as, as->length + len + 1) == NULL)
   2720 		return (-1);
   2721 
   2722 	/* Invariant: src points to the first UTF8 byte that hasn't
   2723 	 * been copied to the destination `as`. */
   2724 	for (;;) {
   2725 		int n;
   2726 		uint32_t uc;
   2727 		const char *e = src;
   2728 
   2729 		/* Skip UTF-8 sequences until we reach end-of-string or
   2730 		 * a code point that needs conversion. */
   2731 		while ((n = utf8_to_unicode(&uc, e, len)) > 0) {
   2732 			e += n;
   2733 			len -= n;
   2734 		}
   2735 		/* Copy the part that doesn't need conversion */
   2736 		if (e > src) {
   2737 			if (archive_string_append(as, src, e - src) == NULL)
   2738 				return (-1);
   2739 			src = e;
   2740 		}
   2741 
   2742 		if (n == 0) {
   2743 			/* We reached end-of-string */
   2744 			return (ret);
   2745 		} else {
   2746 			/* Next code point needs conversion */
   2747 			char t[4];
   2748 			size_t w;
   2749 
   2750 			/* Try decoding a surrogate pair */
   2751 			if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
   2752 				n = cesu8_to_unicode(&uc, src, len);
   2753 			}
   2754 			/* Not a (valid) surrogate, so use a replacement char */
   2755 			if (n < 0) {
   2756 				ret = -1; /* Return -1 if we used any replacement */
   2757 				n *= -1;
   2758 			}
   2759 			/* Consume converted code point */
   2760 			src += n;
   2761 			len -= n;
   2762 			/* Convert and append new UTF-8 sequence. */
   2763 			w = unicode_to_utf8(t, sizeof(t), uc);
   2764 			if (archive_string_append(as, t, w) == NULL)
   2765 				return (-1);
   2766 		}
   2767 	}
   2768 }
   2769 
   2770 static int
   2771 archive_string_append_unicode(struct archive_string *as, const void *_p,
   2772     size_t len, struct archive_string_conv *sc)
   2773 {
   2774 	const char *s;
   2775 	char *p, *endp;
   2776 	uint32_t uc;
   2777 	size_t w;
   2778 	size_t ts, tm;
   2779 	int n, ret = 0;
   2780 	int (*parse)(uint32_t *, const char *, size_t);
   2781 	size_t (*unparse)(char *, size_t, uint32_t);
   2782 
   2783 	if (sc->flag & SCONV_TO_UTF16BE) {
   2784 		unparse = unicode_to_utf16be;
   2785 		ts = 2;
   2786 	} else if (sc->flag & SCONV_TO_UTF16LE) {
   2787 		unparse = unicode_to_utf16le;
   2788 		ts = 2;
   2789 	} else if (sc->flag & SCONV_TO_UTF8) {
   2790 		unparse = unicode_to_utf8;
   2791 		ts = 1;
   2792 	} else {
   2793 		/*
   2794 		 * This case is going to be converted to another
   2795 		 * character-set through iconv.
   2796 		 */
   2797 		if (sc->flag & SCONV_FROM_UTF16BE) {
   2798 			unparse = unicode_to_utf16be;
   2799 			ts = 2;
   2800 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
   2801 			unparse = unicode_to_utf16le;
   2802 			ts = 2;
   2803 		} else {
   2804 			unparse = unicode_to_utf8;
   2805 			ts = 1;
   2806 		}
   2807 	}
   2808 
   2809 	if (sc->flag & SCONV_FROM_UTF16BE) {
   2810 		parse = utf16be_to_unicode;
   2811 		tm = 1;
   2812 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
   2813 		parse = utf16le_to_unicode;
   2814 		tm = 1;
   2815 	} else {
   2816 		parse = cesu8_to_unicode;
   2817 		tm = ts;
   2818 	}
   2819 
   2820 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
   2821 		return (-1);
   2822 
   2823 	s = (const char *)_p;
   2824 	p = as->s + as->length;
   2825 	endp = as->s + as->buffer_length - ts;
   2826 	while ((n = parse(&uc, s, len)) != 0) {
   2827 		if (n < 0) {
   2828 			/* Use a replaced unicode character. */
   2829 			n *= -1;
   2830 			ret = -1;
   2831 		}
   2832 		s += n;
   2833 		len -= n;
   2834 		while ((w = unparse(p, endp - p, uc)) == 0) {
   2835 			/* There is not enough output buffer so
   2836 			 * we have to expand it. */
   2837 			as->length = p - as->s;
   2838 			if (archive_string_ensure(as,
   2839 			    as->buffer_length + len * tm + ts) == NULL)
   2840 				return (-1);
   2841 			p = as->s + as->length;
   2842 			endp = as->s + as->buffer_length - ts;
   2843 		}
   2844 		p += w;
   2845 	}
   2846 	as->length = p - as->s;
   2847 	as->s[as->length] = '\0';
   2848 	if (ts == 2)
   2849 		as->s[as->length+1] = '\0';
   2850 	return (ret);
   2851 }
   2852 
   2853 /*
   2854  * Following Constants for Hangul compositions this information comes from
   2855  * Unicode Standard Annex #15  http://unicode.org/reports/tr15/
   2856  */
   2857 #define HC_SBASE	0xAC00
   2858 #define HC_LBASE	0x1100
   2859 #define HC_VBASE	0x1161
   2860 #define HC_TBASE	0x11A7
   2861 #define HC_LCOUNT	19
   2862 #define HC_VCOUNT	21
   2863 #define HC_TCOUNT	28
   2864 #define HC_NCOUNT	(HC_VCOUNT * HC_TCOUNT)
   2865 #define HC_SCOUNT	(HC_LCOUNT * HC_NCOUNT)
   2866 
   2867 static uint32_t
   2868 get_nfc(uint32_t uc, uint32_t uc2)
   2869 {
   2870 	int t, b;
   2871 
   2872 	t = 0;
   2873 	b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
   2874 	while (b >= t) {
   2875 		int m = (t + b) / 2;
   2876 		if (u_composition_table[m].cp1 < uc)
   2877 			t = m + 1;
   2878 		else if (u_composition_table[m].cp1 > uc)
   2879 			b = m - 1;
   2880 		else if (u_composition_table[m].cp2 < uc2)
   2881 			t = m + 1;
   2882 		else if (u_composition_table[m].cp2 > uc2)
   2883 			b = m - 1;
   2884 		else
   2885 			return (u_composition_table[m].nfc);
   2886 	}
   2887 	return (0);
   2888 }
   2889 
   2890 #define FDC_MAX 10	/* The maximum number of Following Decomposable
   2891 			 * Characters. */
   2892 
   2893 /*
   2894  * Update first code point.
   2895  */
   2896 #define UPDATE_UC(new_uc)	do {		\
   2897 	uc = new_uc;				\
   2898 	ucptr = NULL;				\
   2899 } while (0)
   2900 
   2901 /*
   2902  * Replace first code point with second code point.
   2903  */
   2904 #define REPLACE_UC_WITH_UC2() do {		\
   2905 	uc = uc2;				\
   2906 	ucptr = uc2ptr;				\
   2907 	n = n2;					\
   2908 } while (0)
   2909 
   2910 #define EXPAND_BUFFER() do {			\
   2911 	as->length = p - as->s;			\
   2912 	if (archive_string_ensure(as,		\
   2913 	    as->buffer_length + len * tm + ts) == NULL)\
   2914 		return (-1);			\
   2915 	p = as->s + as->length;			\
   2916 	endp = as->s + as->buffer_length - ts;	\
   2917 } while (0)
   2918 
   2919 #define UNPARSE(p, endp, uc)	do {		\
   2920 	while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
   2921 		EXPAND_BUFFER();		\
   2922 	}					\
   2923 	p += w;					\
   2924 } while (0)
   2925 
   2926 /*
   2927  * Write first code point.
   2928  * If the code point has not be changed from its original code,
   2929  * this just copies it from its original buffer pointer.
   2930  * If not, this converts it to UTF-8 byte sequence and copies it.
   2931  */
   2932 #define WRITE_UC()	do {			\
   2933 	if (ucptr) {				\
   2934 		if (p + n > endp)		\
   2935 			EXPAND_BUFFER();	\
   2936 		switch (n) {			\
   2937 		case 4:				\
   2938 			*p++ = *ucptr++;	\
   2939 			/* FALL THROUGH */	\
   2940 		case 3:				\
   2941 			*p++ = *ucptr++;	\
   2942 			/* FALL THROUGH */	\
   2943 		case 2:				\
   2944 			*p++ = *ucptr++;	\
   2945 			/* FALL THROUGH */	\
   2946 		case 1:				\
   2947 			*p++ = *ucptr;		\
   2948 			break;			\
   2949 		}				\
   2950 		ucptr = NULL;			\
   2951 	} else {				\
   2952 		UNPARSE(p, endp, uc);		\
   2953 	}					\
   2954 } while (0)
   2955 
   2956 /*
   2957  * Collect following decomposable code points.
   2958  */
   2959 #define COLLECT_CPS(start)	do {		\
   2960 	int _i;					\
   2961 	for (_i = start; _i < FDC_MAX ; _i++) {	\
   2962 		nx = parse(&ucx[_i], s, len);	\
   2963 		if (nx <= 0)			\
   2964 			break;			\
   2965 		cx = CCC(ucx[_i]);		\
   2966 		if (cl >= cx && cl != 228 && cx != 228)\
   2967 			break;			\
   2968 		s += nx;			\
   2969 		len -= nx;			\
   2970 		cl = cx;			\
   2971 		ccx[_i] = cx;			\
   2972 	}					\
   2973 	if (_i >= FDC_MAX) {			\
   2974 		ret = -1;			\
   2975 		ucx_size = FDC_MAX;		\
   2976 	} else					\
   2977 		ucx_size = _i;			\
   2978 } while (0)
   2979 
   2980 /*
   2981  * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
   2982  *
   2983  * TODO: Convert composition exclusions, which are never converted
   2984  * from NFC,NFD,NFKC and NFKD, to Form C.
   2985  */
   2986 static int
   2987 archive_string_normalize_C(struct archive_string *as, const void *_p,
   2988     size_t len, struct archive_string_conv *sc)
   2989 {
   2990 	const char *s = (const char *)_p;
   2991 	char *p, *endp;
   2992 	uint32_t uc, uc2;
   2993 	size_t w;
   2994 	int always_replace, n, n2, ret = 0, spair, ts, tm;
   2995 	int (*parse)(uint32_t *, const char *, size_t);
   2996 	size_t (*unparse)(char *, size_t, uint32_t);
   2997 
   2998 	always_replace = 1;
   2999 	ts = 1;/* text size. */
   3000 	if (sc->flag & SCONV_TO_UTF16BE) {
   3001 		unparse = unicode_to_utf16be;
   3002 		ts = 2;
   3003 		if (sc->flag & SCONV_FROM_UTF16BE)
   3004 			always_replace = 0;
   3005 	} else if (sc->flag & SCONV_TO_UTF16LE) {
   3006 		unparse = unicode_to_utf16le;
   3007 		ts = 2;
   3008 		if (sc->flag & SCONV_FROM_UTF16LE)
   3009 			always_replace = 0;
   3010 	} else if (sc->flag & SCONV_TO_UTF8) {
   3011 		unparse = unicode_to_utf8;
   3012 		if (sc->flag & SCONV_FROM_UTF8)
   3013 			always_replace = 0;
   3014 	} else {
   3015 		/*
   3016 		 * This case is going to be converted to another
   3017 		 * character-set through iconv.
   3018 		 */
   3019 		always_replace = 0;
   3020 		if (sc->flag & SCONV_FROM_UTF16BE) {
   3021 			unparse = unicode_to_utf16be;
   3022 			ts = 2;
   3023 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
   3024 			unparse = unicode_to_utf16le;
   3025 			ts = 2;
   3026 		} else {
   3027 			unparse = unicode_to_utf8;
   3028 		}
   3029 	}
   3030 
   3031 	if (sc->flag & SCONV_FROM_UTF16BE) {
   3032 		parse = utf16be_to_unicode;
   3033 		tm = 1;
   3034 		spair = 4;/* surrogate pair size in UTF-16. */
   3035 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
   3036 		parse = utf16le_to_unicode;
   3037 		tm = 1;
   3038 		spair = 4;/* surrogate pair size in UTF-16. */
   3039 	} else {
   3040 		parse = cesu8_to_unicode;
   3041 		tm = ts;
   3042 		spair = 6;/* surrogate pair size in UTF-8. */
   3043 	}
   3044 
   3045 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
   3046 		return (-1);
   3047 
   3048 	p = as->s + as->length;
   3049 	endp = as->s + as->buffer_length - ts;
   3050 	while ((n = parse(&uc, s, len)) != 0) {
   3051 		const char *ucptr, *uc2ptr;
   3052 
   3053 		if (n < 0) {
   3054 			/* Use a replaced unicode character. */
   3055 			UNPARSE(p, endp, uc);
   3056 			s += n*-1;
   3057 			len -= n*-1;
   3058 			ret = -1;
   3059 			continue;
   3060 		} else if (n == spair || always_replace)
   3061 			/* uc is converted from a surrogate pair.
   3062 			 * this should be treated as a changed code. */
   3063 			ucptr = NULL;
   3064 		else
   3065 			ucptr = s;
   3066 		s += n;
   3067 		len -= n;
   3068 
   3069 		/* Read second code point. */
   3070 		while ((n2 = parse(&uc2, s, len)) > 0) {
   3071 			uint32_t ucx[FDC_MAX];
   3072 			int ccx[FDC_MAX];
   3073 			int cl, cx, i, nx, ucx_size;
   3074 			int LIndex,SIndex;
   3075 			uint32_t nfc;
   3076 
   3077 			if (n2 == spair || always_replace)
   3078 				/* uc2 is converted from a surrogate pair.
   3079 			 	 * this should be treated as a changed code. */
   3080 				uc2ptr = NULL;
   3081 			else
   3082 				uc2ptr = s;
   3083 			s += n2;
   3084 			len -= n2;
   3085 
   3086 			/*
   3087 			 * If current second code point is out of decomposable
   3088 			 * code points, finding compositions is unneeded.
   3089 			 */
   3090 			if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
   3091 				WRITE_UC();
   3092 				REPLACE_UC_WITH_UC2();
   3093 				continue;
   3094 			}
   3095 
   3096 			/*
   3097 			 * Try to combine current code points.
   3098 			 */
   3099 			/*
   3100 			 * We have to combine Hangul characters according to
   3101 			 * http://uniicode.org/reports/tr15/#Hangul
   3102 			 */
   3103 			if (0 <= (LIndex = uc - HC_LBASE) &&
   3104 			    LIndex < HC_LCOUNT) {
   3105 				/*
   3106 				 * Hangul Composition.
   3107 				 * 1. Two current code points are L and V.
   3108 				 */
   3109 				int VIndex = uc2 - HC_VBASE;
   3110 				if (0 <= VIndex && VIndex < HC_VCOUNT) {
   3111 					/* Make syllable of form LV. */
   3112 					UPDATE_UC(HC_SBASE +
   3113 					    (LIndex * HC_VCOUNT + VIndex) *
   3114 					     HC_TCOUNT);
   3115 				} else {
   3116 					WRITE_UC();
   3117 					REPLACE_UC_WITH_UC2();
   3118 				}
   3119 				continue;
   3120 			} else if (0 <= (SIndex = uc - HC_SBASE) &&
   3121 			    SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
   3122 				/*
   3123 				 * Hangul Composition.
   3124 				 * 2. Two current code points are LV and T.
   3125 				 */
   3126 				int TIndex = uc2 - HC_TBASE;
   3127 				if (0 < TIndex && TIndex < HC_TCOUNT) {
   3128 					/* Make syllable of form LVT. */
   3129 					UPDATE_UC(uc + TIndex);
   3130 				} else {
   3131 					WRITE_UC();
   3132 					REPLACE_UC_WITH_UC2();
   3133 				}
   3134 				continue;
   3135 			} else if ((nfc = get_nfc(uc, uc2)) != 0) {
   3136 				/* A composition to current code points
   3137 				 * is found. */
   3138 				UPDATE_UC(nfc);
   3139 				continue;
   3140 			} else if ((cl = CCC(uc2)) == 0) {
   3141 				/* Clearly 'uc2' the second code point is not
   3142 				 * a decomposable code. */
   3143 				WRITE_UC();
   3144 				REPLACE_UC_WITH_UC2();
   3145 				continue;
   3146 			}
   3147 
   3148 			/*
   3149 			 * Collect following decomposable code points.
   3150 			 */
   3151 			cx = 0;
   3152 			ucx[0] = uc2;
   3153 			ccx[0] = cl;
   3154 			COLLECT_CPS(1);
   3155 
   3156 			/*
   3157 			 * Find a composed code in the collected code points.
   3158 			 */
   3159 			i = 1;
   3160 			while (i < ucx_size) {
   3161 				int j;
   3162 
   3163 				if ((nfc = get_nfc(uc, ucx[i])) == 0) {
   3164 					i++;
   3165 					continue;
   3166 				}
   3167 
   3168 				/*
   3169 				 * nfc is composed of uc and ucx[i].
   3170 				 */
   3171 				UPDATE_UC(nfc);
   3172 
   3173 				/*
   3174 				 * Remove ucx[i] by shifting
   3175 				 * following code points.
   3176 				 */
   3177 				for (j = i; j+1 < ucx_size; j++) {
   3178 					ucx[j] = ucx[j+1];
   3179 					ccx[j] = ccx[j+1];
   3180 				}
   3181 				ucx_size --;
   3182 
   3183 				/*
   3184 				 * Collect following code points blocked
   3185 				 * by ucx[i] the removed code point.
   3186 				 */
   3187 				if (ucx_size > 0 && i == ucx_size &&
   3188 				    nx > 0 && cx == cl) {
   3189 					cl =  ccx[ucx_size-1];
   3190 					COLLECT_CPS(ucx_size);
   3191 				}
   3192 				/*
   3193 				 * Restart finding a composed code with
   3194 				 * the updated uc from the top of the
   3195 				 * collected code points.
   3196 				 */
   3197 				i = 0;
   3198 			}
   3199 
   3200 			/*
   3201 			 * Apparently the current code points are not
   3202 			 * decomposed characters or already composed.
   3203 			 */
   3204 			WRITE_UC();
   3205 			for (i = 0; i < ucx_size; i++)
   3206 				UNPARSE(p, endp, ucx[i]);
   3207 
   3208 			/*
   3209 			 * Flush out remaining canonical combining characters.
   3210 			 */
   3211 			if (nx > 0 && cx == cl && len > 0) {
   3212 				while ((nx = parse(&ucx[0], s, len))
   3213 				    > 0) {
   3214 					cx = CCC(ucx[0]);
   3215 					if (cl > cx)
   3216 						break;
   3217 					s += nx;
   3218 					len -= nx;
   3219 					cl = cx;
   3220 					UNPARSE(p, endp, ucx[0]);
   3221 				}
   3222 			}
   3223 			break;
   3224 		}
   3225 		if (n2 < 0) {
   3226 			WRITE_UC();
   3227 			/* Use a replaced unicode character. */
   3228 			UNPARSE(p, endp, uc2);
   3229 			s += n2*-1;
   3230 			len -= n2*-1;
   3231 			ret = -1;
   3232 			continue;
   3233 		} else if (n2 == 0) {
   3234 			WRITE_UC();
   3235 			break;
   3236 		}
   3237 	}
   3238 	as->length = p - as->s;
   3239 	as->s[as->length] = '\0';
   3240 	if (ts == 2)
   3241 		as->s[as->length+1] = '\0';
   3242 	return (ret);
   3243 }
   3244 
   3245 static int
   3246 get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
   3247 {
   3248 	int t, b;
   3249 
   3250 	/*
   3251 	 * These are not converted to NFD on Mac OS.
   3252 	 */
   3253 	if ((uc >= 0x2000 && uc <= 0x2FFF) ||
   3254 	    (uc >= 0xF900 && uc <= 0xFAFF) ||
   3255 	    (uc >= 0x2F800 && uc <= 0x2FAFF))
   3256 		return (0);
   3257 	/*
   3258 	 * Those code points are not converted to NFD on Mac OS.
   3259 	 * I do not know the reason because it is undocumented.
   3260 	 *   NFC        NFD
   3261 	 *   1109A  ==> 11099 110BA
   3262 	 *   1109C  ==> 1109B 110BA
   3263 	 *   110AB  ==> 110A5 110BA
   3264 	 */
   3265 	if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
   3266 		return (0);
   3267 
   3268 	t = 0;
   3269 	b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
   3270 	while (b >= t) {
   3271 		int m = (t + b) / 2;
   3272 		if (u_decomposition_table[m].nfc < uc)
   3273 			t = m + 1;
   3274 		else if (u_decomposition_table[m].nfc > uc)
   3275 			b = m - 1;
   3276 		else {
   3277 			*cp1 = u_decomposition_table[m].cp1;
   3278 			*cp2 = u_decomposition_table[m].cp2;
   3279 			return (1);
   3280 		}
   3281 	}
   3282 	return (0);
   3283 }
   3284 
   3285 #define REPLACE_UC_WITH(cp) do {		\
   3286 	uc = cp;				\
   3287 	ucptr = NULL;				\
   3288 } while (0)
   3289 
   3290 /*
   3291  * Normalize UTF-8 characters to Form D and copy the result.
   3292  */
   3293 static int
   3294 archive_string_normalize_D(struct archive_string *as, const void *_p,
   3295     size_t len, struct archive_string_conv *sc)
   3296 {
   3297 	const char *s = (const char *)_p;
   3298 	char *p, *endp;
   3299 	uint32_t uc, uc2;
   3300 	size_t w;
   3301 	int always_replace, n, n2, ret = 0, spair, ts, tm;
   3302 	int (*parse)(uint32_t *, const char *, size_t);
   3303 	size_t (*unparse)(char *, size_t, uint32_t);
   3304 
   3305 	always_replace = 1;
   3306 	ts = 1;/* text size. */
   3307 	if (sc->flag & SCONV_TO_UTF16BE) {
   3308 		unparse = unicode_to_utf16be;
   3309 		ts = 2;
   3310 		if (sc->flag & SCONV_FROM_UTF16BE)
   3311 			always_replace = 0;
   3312 	} else if (sc->flag & SCONV_TO_UTF16LE) {
   3313 		unparse = unicode_to_utf16le;
   3314 		ts = 2;
   3315 		if (sc->flag & SCONV_FROM_UTF16LE)
   3316 			always_replace = 0;
   3317 	} else if (sc->flag & SCONV_TO_UTF8) {
   3318 		unparse = unicode_to_utf8;
   3319 		if (sc->flag & SCONV_FROM_UTF8)
   3320 			always_replace = 0;
   3321 	} else {
   3322 		/*
   3323 		 * This case is going to be converted to another
   3324 		 * character-set through iconv.
   3325 		 */
   3326 		always_replace = 0;
   3327 		if (sc->flag & SCONV_FROM_UTF16BE) {
   3328 			unparse = unicode_to_utf16be;
   3329 			ts = 2;
   3330 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
   3331 			unparse = unicode_to_utf16le;
   3332 			ts = 2;
   3333 		} else {
   3334 			unparse = unicode_to_utf8;
   3335 		}
   3336 	}
   3337 
   3338 	if (sc->flag & SCONV_FROM_UTF16BE) {
   3339 		parse = utf16be_to_unicode;
   3340 		tm = 1;
   3341 		spair = 4;/* surrogate pair size in UTF-16. */
   3342 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
   3343 		parse = utf16le_to_unicode;
   3344 		tm = 1;
   3345 		spair = 4;/* surrogate pair size in UTF-16. */
   3346 	} else {
   3347 		parse = cesu8_to_unicode;
   3348 		tm = ts;
   3349 		spair = 6;/* surrogate pair size in UTF-8. */
   3350 	}
   3351 
   3352 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
   3353 		return (-1);
   3354 
   3355 	p = as->s + as->length;
   3356 	endp = as->s + as->buffer_length - ts;
   3357 	while ((n = parse(&uc, s, len)) != 0) {
   3358 		const char *ucptr;
   3359 		uint32_t cp1, cp2;
   3360 		int SIndex;
   3361 		struct {
   3362 			uint32_t uc;
   3363 			int ccc;
   3364 		} fdc[FDC_MAX];
   3365 		int fdi, fdj;
   3366 		int ccc;
   3367 
   3368 check_first_code:
   3369 		if (n < 0) {
   3370 			/* Use a replaced unicode character. */
   3371 			UNPARSE(p, endp, uc);
   3372 			s += n*-1;
   3373 			len -= n*-1;
   3374 			ret = -1;
   3375 			continue;
   3376 		} else if (n == spair || always_replace)
   3377 			/* uc is converted from a surrogate pair.
   3378 			 * this should be treated as a changed code. */
   3379 			ucptr = NULL;
   3380 		else
   3381 			ucptr = s;
   3382 		s += n;
   3383 		len -= n;
   3384 
   3385 		/* Hangul Decomposition. */
   3386 		if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
   3387 			int L = HC_LBASE + SIndex / HC_NCOUNT;
   3388 			int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
   3389 			int T = HC_TBASE + SIndex % HC_TCOUNT;
   3390 
   3391 			REPLACE_UC_WITH(L);
   3392 			WRITE_UC();
   3393 			REPLACE_UC_WITH(V);
   3394 			WRITE_UC();
   3395 			if (T != HC_TBASE) {
   3396 				REPLACE_UC_WITH(T);
   3397 				WRITE_UC();
   3398 			}
   3399 			continue;
   3400 		}
   3401 		if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
   3402 			WRITE_UC();
   3403 			continue;
   3404 		}
   3405 
   3406 		fdi = 0;
   3407 		while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
   3408 			int k;
   3409 
   3410 			for (k = fdi; k > 0; k--)
   3411 				fdc[k] = fdc[k-1];
   3412 			fdc[0].ccc = CCC(cp2);
   3413 			fdc[0].uc = cp2;
   3414 			fdi++;
   3415 			REPLACE_UC_WITH(cp1);
   3416 		}
   3417 
   3418 		/* Read following code points. */
   3419 		while ((n2 = parse(&uc2, s, len)) > 0 &&
   3420 		    (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
   3421 			int j, k;
   3422 
   3423 			s += n2;
   3424 			len -= n2;
   3425 			for (j = 0; j < fdi; j++) {
   3426 				if (fdc[j].ccc > ccc)
   3427 					break;
   3428 			}
   3429 			if (j < fdi) {
   3430 				for (k = fdi; k > j; k--)
   3431 					fdc[k] = fdc[k-1];
   3432 				fdc[j].ccc = ccc;
   3433 				fdc[j].uc = uc2;
   3434 			} else {
   3435 				fdc[fdi].ccc = ccc;
   3436 				fdc[fdi].uc = uc2;
   3437 			}
   3438 			fdi++;
   3439 		}
   3440 
   3441 		WRITE_UC();
   3442 		for (fdj = 0; fdj < fdi; fdj++) {
   3443 			REPLACE_UC_WITH(fdc[fdj].uc);
   3444 			WRITE_UC();
   3445 		}
   3446 
   3447 		if (n2 == 0)
   3448 			break;
   3449 		REPLACE_UC_WITH(uc2);
   3450 		n = n2;
   3451 		goto check_first_code;
   3452 	}
   3453 	as->length = p - as->s;
   3454 	as->s[as->length] = '\0';
   3455 	if (ts == 2)
   3456 		as->s[as->length+1] = '\0';
   3457 	return (ret);
   3458 }
   3459 
   3460 /*
   3461  * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
   3462  * that WCS is Unicode. It is true for several platforms but some are false.
   3463  * And then people who did not use UTF-8 locale on the non Unicode WCS
   3464  * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
   3465  * now cannot get right filename from libarchive 3.x and later since we
   3466  * fixed the wrong assumption and it is incompatible to older its versions.
   3467  * So we provide special option, "compat-2x.x", for resolving it.
   3468  * That option enable the string conversion of libarchive 2.x.
   3469  *
   3470  * Translates the wrong UTF-8 string made by libarchive 2.x into current
   3471  * locale character set and appends to the archive_string.
   3472  * Note: returns -1 if conversion fails.
   3473  */
   3474 static int
   3475 strncat_from_utf8_libarchive2(struct archive_string *as,
   3476     const void *_p, size_t len, struct archive_string_conv *sc)
   3477 {
   3478 	const char *s;
   3479 	int n;
   3480 	char *p;
   3481 	char *end;
   3482 	uint32_t unicode;
   3483 #if HAVE_WCRTOMB
   3484 	mbstate_t shift_state;
   3485 
   3486 	memset(&shift_state, 0, sizeof(shift_state));
   3487 #else
   3488 	/* Clear the shift state before starting. */
   3489 	wctomb(NULL, L'\0');
   3490 #endif
   3491 	(void)sc; /* UNUSED */
   3492 	/*
   3493 	 * Allocate buffer for MBS.
   3494 	 * We need this allocation here since it is possible that
   3495 	 * as->s is still NULL.
   3496 	 */
   3497 	if (archive_string_ensure(as, as->length + len + 1) == NULL)
   3498 		return (-1);
   3499 
   3500 	s = (const char *)_p;
   3501 	p = as->s + as->length;
   3502 	end = as->s + as->buffer_length - MB_CUR_MAX -1;
   3503 	while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
   3504 		wchar_t wc;
   3505 
   3506 		if (p >= end) {
   3507 			as->length = p - as->s;
   3508 			/* Re-allocate buffer for MBS. */
   3509 			if (archive_string_ensure(as,
   3510 			    as->length + max(len * 2,
   3511 			    (size_t)MB_CUR_MAX) + 1) == NULL)
   3512 				return (-1);
   3513 			p = as->s + as->length;
   3514 			end = as->s + as->buffer_length - MB_CUR_MAX -1;
   3515 		}
   3516 
   3517 		/*
   3518 		 * As libarchive 2.x, translates the UTF-8 characters into
   3519 		 * wide-characters in the assumption that WCS is Unicode.
   3520 		 */
   3521 		if (n < 0) {
   3522 			n *= -1;
   3523 			wc = L'?';
   3524 		} else
   3525 			wc = (wchar_t)unicode;
   3526 
   3527 		s += n;
   3528 		len -= n;
   3529 		/*
   3530 		 * Translates the wide-character into the current locale MBS.
   3531 		 */
   3532 #if HAVE_WCRTOMB
   3533 		n = (int)wcrtomb(p, wc, &shift_state);
   3534 #else
   3535 		n = (int)wctomb(p, wc);
   3536 #endif
   3537 		if (n == -1)
   3538 			return (-1);
   3539 		p += n;
   3540 	}
   3541 	as->length = p - as->s;
   3542 	as->s[as->length] = '\0';
   3543 	return (0);
   3544 }
   3545 
   3546 
   3547 /*
   3548  * Conversion functions between current locale dependent MBS and UTF-16BE.
   3549  *   strncat_from_utf16be() : UTF-16BE --> MBS
   3550  *   strncat_to_utf16be()   : MBS --> UTF16BE
   3551  */
   3552 
   3553 #if defined(_WIN32) && !defined(__CYGWIN__)
   3554 
   3555 /*
   3556  * Convert a UTF-16BE/LE string to current locale and copy the result.
   3557  * Return -1 if conversion fails.
   3558  */
   3559 static int
   3560 win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
   3561     struct archive_string_conv *sc, int be)
   3562 {
   3563 	struct archive_string tmp;
   3564 	const char *u16;
   3565 	BOOL defchar;
   3566 	char *mbs;
   3567 	size_t mbs_size, b, ll;
   3568 	int ret = 0;
   3569 
   3570 	bytes &= ~1;
   3571 	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
   3572 		return (-1);
   3573 
   3574 	mbs = as->s + as->length;
   3575 	mbs_size = as->buffer_length - as->length -1;
   3576 
   3577 	if (sc->to_cp == CP_C_LOCALE) {
   3578 		/*
   3579 		 * "C" locale special processing.
   3580 		 */
   3581 		u16 = _p;
   3582 		ll = 0;
   3583 		for (b = 0; b < bytes; b += 2) {
   3584 			uint16_t val;
   3585 			if (be)
   3586 				val = archive_be16dec(u16+b);
   3587 			else
   3588 				val = archive_le16dec(u16+b);
   3589 			if (val > 255) {
   3590 				*mbs++ = '?';
   3591 				ret = -1;
   3592 			} else
   3593 				*mbs++ = (char)(val&0xff);
   3594 			ll++;
   3595 		}
   3596 		as->length += ll;
   3597 		as->s[as->length] = '\0';
   3598 		return (ret);
   3599 	}
   3600 
   3601 	archive_string_init(&tmp);
   3602 	if (be) {
   3603 		if (IS_BIG_ENDIAN) {
   3604 			u16 = _p;
   3605 		} else {
   3606 			if (archive_string_ensure(&tmp, bytes+2) == NULL)
   3607 				return (-1);
   3608 			memcpy(tmp.s, _p, bytes);
   3609 			for (b = 0; b < bytes; b += 2) {
   3610 				uint16_t val = archive_be16dec(tmp.s+b);
   3611 				archive_le16enc(tmp.s+b, val);
   3612 			}
   3613 			u16 = tmp.s;
   3614 		}
   3615 	} else {
   3616 		if (!IS_BIG_ENDIAN) {
   3617 			u16 = _p;
   3618 		} else {
   3619 			if (archive_string_ensure(&tmp, bytes+2) == NULL)
   3620 				return (-1);
   3621 			memcpy(tmp.s, _p, bytes);
   3622 			for (b = 0; b < bytes; b += 2) {
   3623 				uint16_t val = archive_le16dec(tmp.s+b);
   3624 				archive_be16enc(tmp.s+b, val);
   3625 			}
   3626 			u16 = tmp.s;
   3627 		}
   3628 	}
   3629 
   3630 	do {
   3631 		int r;
   3632 		defchar = 0;
   3633 		/* WideCharToMultiByte is limited to int. */
   3634 		if (bytes > (size_t)INT_MAX || mbs_size > (size_t)INT_MAX)
   3635 			return (-1);
   3636 		r = WideCharToMultiByte(sc->to_cp, 0,
   3637 		    (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
   3638 			NULL, &defchar);
   3639 		/* Exit loop if we succeeded */
   3640 		if (r != 0 ||
   3641 		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
   3642 			ll = (size_t)r;
   3643 			break;
   3644 		}
   3645 		/* Else expand buffer and loop to try again. */
   3646 		r = WideCharToMultiByte(sc->to_cp, 0,
   3647 		    (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
   3648 		ll = (size_t)r;
   3649 		if (archive_string_ensure(as, ll +1) == NULL)
   3650 			return (-1);
   3651 		mbs = as->s + as->length;
   3652 		mbs_size = as->buffer_length - as->length -1;
   3653 	} while (1);
   3654 	archive_string_free(&tmp);
   3655 	as->length += ll;
   3656 	as->s[as->length] = '\0';
   3657 	if (ll == 0 || defchar)
   3658 		ret = -1;
   3659 	return (ret);
   3660 }
   3661 
   3662 static int
   3663 win_strncat_from_utf16be(struct archive_string *as, const void *_p,
   3664     size_t bytes, struct archive_string_conv *sc)
   3665 {
   3666 	return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
   3667 }
   3668 
   3669 static int
   3670 win_strncat_from_utf16le(struct archive_string *as, const void *_p,
   3671     size_t bytes, struct archive_string_conv *sc)
   3672 {
   3673 	return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
   3674 }
   3675 
   3676 /*
   3677  * Convert a current locale string to UTF-16BE/LE and copy the result.
   3678  * Return -1 if conversion fails.
   3679  */
   3680 static int
   3681 win_strncat_to_utf16(struct archive_string *as16, const void *_p,
   3682     size_t length, struct archive_string_conv *sc, int bigendian)
   3683 {
   3684 	const char *s = (const char *)_p;
   3685 	char *u16;
   3686 	size_t count, avail;
   3687 
   3688 	if (archive_string_ensure(as16,
   3689 	    as16->length + (length + 1) * 2) == NULL)
   3690 		return (-1);
   3691 
   3692 	u16 = as16->s + as16->length;
   3693 	avail = as16->buffer_length - 2;
   3694 	if (sc->from_cp == CP_C_LOCALE) {
   3695 		/*
   3696 		 * "C" locale special processing.
   3697 		 */
   3698 		count = 0;
   3699 		while (count < length && *s) {
   3700 			if (bigendian)
   3701 				archive_be16enc(u16, *s);
   3702 			else
   3703 				archive_le16enc(u16, *s);
   3704 			u16 += 2;
   3705 			s++;
   3706 			count++;
   3707 		}
   3708 		as16->length += count << 1;
   3709 		as16->s[as16->length] = 0;
   3710 		as16->s[as16->length+1] = 0;
   3711 		return (0);
   3712 	}
   3713 	do {
   3714 		int r;
   3715 		if (length > (size_t)INT_MAX || (avail >> 1) > (size_t)INT_MAX)
   3716 			return (-1);
   3717 		r = MultiByteToWideChar(sc->from_cp,
   3718 		    MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
   3719 		/* Exit loop if we succeeded */
   3720 		if (r != 0 ||
   3721 		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
   3722 			count = (size_t)r;
   3723 			break;
   3724 		}
   3725 		/* Expand buffer and try again */
   3726 		r = MultiByteToWideChar(sc->from_cp,
   3727 		    MB_PRECOMPOSED, s, (int)length, NULL, 0);
   3728 		count = (size_t)r;
   3729 		if (archive_string_ensure(as16, (count +1) * 2)
   3730 		    == NULL)
   3731 			return (-1);
   3732 		u16 = as16->s + as16->length;
   3733 		avail = as16->buffer_length - 2;
   3734 	} while (1);
   3735 	as16->length += count * 2;
   3736 	as16->s[as16->length] = 0;
   3737 	as16->s[as16->length+1] = 0;
   3738 	if (count == 0)
   3739 		return (-1);
   3740 
   3741 	if (IS_BIG_ENDIAN) {
   3742 		if (!bigendian) {
   3743 			while (count > 0) {
   3744 				uint16_t v = archive_be16dec(u16);
   3745 				archive_le16enc(u16, v);
   3746 				u16 += 2;
   3747 				count--;
   3748 			}
   3749 		}
   3750 	} else {
   3751 		if (bigendian) {
   3752 			while (count > 0) {
   3753 				uint16_t v = archive_le16dec(u16);
   3754 				archive_be16enc(u16, v);
   3755 				u16 += 2;
   3756 				count--;
   3757 			}
   3758 		}
   3759 	}
   3760 	return (0);
   3761 }
   3762 
   3763 static int
   3764 win_strncat_to_utf16be(struct archive_string *as16, const void *_p,
   3765     size_t length, struct archive_string_conv *sc)
   3766 {
   3767 	return (win_strncat_to_utf16(as16, _p, length, sc, 1));
   3768 }
   3769 
   3770 static int
   3771 win_strncat_to_utf16le(struct archive_string *as16, const void *_p,
   3772     size_t length, struct archive_string_conv *sc)
   3773 {
   3774 	return (win_strncat_to_utf16(as16, _p, length, sc, 0));
   3775 }
   3776 
   3777 #endif /* _WIN32 && !__CYGWIN__ */
   3778 
   3779 /*
   3780  * Do the best effort for conversions.
   3781  * We cannot handle UTF-16BE character-set without such iconv,
   3782  * but there is a chance if a string consists just ASCII code or
   3783  * a current locale is UTF-8.
   3784  */
   3785 
   3786 /*
   3787  * Convert a UTF-16BE string to current locale and copy the result.
   3788  * Return -1 if conversion fails.
   3789  */
   3790 static int
   3791 best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
   3792     size_t bytes, struct archive_string_conv *sc, int be)
   3793 {
   3794 	const char *utf16 = (const char *)_p;
   3795 	char *mbs;
   3796 	uint32_t uc;
   3797 	int n, ret;
   3798 
   3799 	(void)sc; /* UNUSED */
   3800 	/*
   3801 	 * Other case, we should do the best effort.
   3802 	 * If all character are ASCII(<0x7f), we can convert it.
   3803 	 * if not , we set a alternative character and return -1.
   3804 	 */
   3805 	ret = 0;
   3806 	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
   3807 		return (-1);
   3808 	mbs = as->s + as->length;
   3809 
   3810 	while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
   3811 		if (n < 0) {
   3812 			n *= -1;
   3813 			ret =  -1;
   3814 		}
   3815 		bytes -= n;
   3816 		utf16 += n;
   3817 
   3818 		if (uc > 127) {
   3819 			/* We cannot handle it. */
   3820 			*mbs++ = '?';
   3821 			ret =  -1;
   3822 		} else
   3823 			*mbs++ = (char)uc;
   3824 	}
   3825 	as->length = mbs - as->s;
   3826 	as->s[as->length] = '\0';
   3827 	return (ret);
   3828 }
   3829 
   3830 static int
   3831 best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
   3832     size_t bytes, struct archive_string_conv *sc)
   3833 {
   3834 	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
   3835 }
   3836 
   3837 static int
   3838 best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
   3839     size_t bytes, struct archive_string_conv *sc)
   3840 {
   3841 	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
   3842 }
   3843 
   3844 /*
   3845  * Convert a current locale string to UTF-16BE/LE and copy the result.
   3846  * Return -1 if conversion fails.
   3847  */
   3848 static int
   3849 best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
   3850     size_t length, struct archive_string_conv *sc, int bigendian)
   3851 {
   3852 	const char *s = (const char *)_p;
   3853 	char *utf16;
   3854 	size_t remaining;
   3855 	int ret;
   3856 
   3857 	(void)sc; /* UNUSED */
   3858 	/*
   3859 	 * Other case, we should do the best effort.
   3860 	 * If all character are ASCII(<0x7f), we can convert it.
   3861 	 * if not , we set a alternative character and return -1.
   3862 	 */
   3863 	ret = 0;
   3864 	remaining = length;
   3865 
   3866 	if (archive_string_ensure(as16,
   3867 	    as16->length + (length + 1) * 2) == NULL)
   3868 		return (-1);
   3869 
   3870 	utf16 = as16->s + as16->length;
   3871 	while (remaining--) {
   3872 		unsigned c = *s++;
   3873 		if (c > 127) {
   3874 			/* We cannot handle it. */
   3875 			c = UNICODE_R_CHAR;
   3876 			ret = -1;
   3877 		}
   3878 		if (bigendian)
   3879 			archive_be16enc(utf16, (uint16_t)c);
   3880 		else
   3881 			archive_le16enc(utf16, (uint16_t)c);
   3882 		utf16 += 2;
   3883 	}
   3884 	as16->length = utf16 - as16->s;
   3885 	as16->s[as16->length] = 0;
   3886 	as16->s[as16->length+1] = 0;
   3887 	return (ret);
   3888 }
   3889 
   3890 static int
   3891 best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
   3892     size_t length, struct archive_string_conv *sc)
   3893 {
   3894 	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
   3895 }
   3896 
   3897 static int
   3898 best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
   3899     size_t length, struct archive_string_conv *sc)
   3900 {
   3901 	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
   3902 }
   3903 
   3904 
   3905 /*
   3906  * Multistring operations.
   3907  */
   3908 
   3909 void
   3910 archive_mstring_clean(struct archive_mstring *aes)
   3911 {
   3912 	archive_wstring_free(&(aes->aes_wcs));
   3913 	archive_string_free(&(aes->aes_mbs));
   3914 	archive_string_free(&(aes->aes_utf8));
   3915 	archive_string_free(&(aes->aes_mbs_in_locale));
   3916 	aes->aes_set = 0;
   3917 }
   3918 
   3919 void
   3920 archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
   3921 {
   3922 	dest->aes_set = src->aes_set;
   3923 	archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
   3924 	archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
   3925 	archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
   3926 }
   3927 
   3928 int
   3929 archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
   3930   const char **p)
   3931 {
   3932 	struct archive_string_conv *sc;
   3933 	int r;
   3934 
   3935 	/* If we already have a UTF8 form, return that immediately. */
   3936 	if (aes->aes_set & AES_SET_UTF8) {
   3937 		*p = aes->aes_utf8.s;
   3938 		return (0);
   3939 	}
   3940 
   3941 	*p = NULL;
   3942 #if defined(_WIN32) && !defined(__CYGWIN__)
   3943 	/*
   3944 	 * On Windows, first try converting from WCS because (1) there's no
   3945 	 * guarantee that the conversion to MBS will succeed, e.g. when using
   3946 	 * CP_ACP, and (2) that's more efficient than converting to MBS, just to
   3947 	 * convert back to WCS again before finally converting to UTF-8
   3948 	 */
   3949 	if ((aes->aes_set & AES_SET_WCS) != 0) {
   3950 		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
   3951 		if (sc == NULL)
   3952 			return (-1);/* Couldn't allocate memory for sc. */
   3953 		archive_string_empty(&(aes->aes_utf8));
   3954 		r = archive_string_append_from_wcs_in_codepage(&(aes->aes_utf8),
   3955 			aes->aes_wcs.s, aes->aes_wcs.length, sc);
   3956 		if (a == NULL)
   3957 			free_sconv_object(sc);
   3958 		if (r == 0) {
   3959 			aes->aes_set |= AES_SET_UTF8;
   3960 			*p = aes->aes_utf8.s;
   3961 			return (0);/* success. */
   3962 		} else
   3963 			return (-1);/* failure. */
   3964 	}
   3965 #endif
   3966 	/* Try converting WCS to MBS first if MBS does not exist yet. */
   3967 	if ((aes->aes_set & AES_SET_MBS) == 0) {
   3968 		const char *pm; /* unused */
   3969 		archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
   3970 	}
   3971 	if (aes->aes_set & AES_SET_MBS) {
   3972 		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
   3973 		if (sc == NULL)
   3974 			return (-1);/* Couldn't allocate memory for sc. */
   3975 		r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
   3976 		    aes->aes_mbs.length, sc);
   3977 		if (a == NULL)
   3978 			free_sconv_object(sc);
   3979 		if (r == 0) {
   3980 			aes->aes_set |= AES_SET_UTF8;
   3981 			*p = aes->aes_utf8.s;
   3982 			return (0);/* success. */
   3983 		} else
   3984 			return (-1);/* failure. */
   3985 	}
   3986 	return (0);/* success. */
   3987 }
   3988 
   3989 int
   3990 archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
   3991     const char **p)
   3992 {
   3993 	struct archive_string_conv *sc;
   3994 	int r, ret = 0;
   3995 
   3996 	/* If we already have an MBS form, return that immediately. */
   3997 	if (aes->aes_set & AES_SET_MBS) {
   3998 		*p = aes->aes_mbs.s;
   3999 		return (ret);
   4000 	}
   4001 
   4002 	*p = NULL;
   4003 	/* If there's a WCS form, try converting with the native locale. */
   4004 	if (aes->aes_set & AES_SET_WCS) {
   4005 		archive_string_empty(&(aes->aes_mbs));
   4006 		r = archive_string_append_from_wcs(&(aes->aes_mbs),
   4007 		    aes->aes_wcs.s, aes->aes_wcs.length);
   4008 		*p = aes->aes_mbs.s;
   4009 		if (r == 0) {
   4010 			aes->aes_set |= AES_SET_MBS;
   4011 			return (ret);
   4012 		} else
   4013 			ret = -1;
   4014 	}
   4015 
   4016 	/* If there's a UTF-8 form, try converting with the native locale. */
   4017 	if (aes->aes_set & AES_SET_UTF8) {
   4018 		archive_string_empty(&(aes->aes_mbs));
   4019 		sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
   4020 		if (sc == NULL)
   4021 			return (-1);/* Couldn't allocate memory for sc. */
   4022 		r = archive_strncpy_l(&(aes->aes_mbs),
   4023 			aes->aes_utf8.s, aes->aes_utf8.length, sc);
   4024 		if (a == NULL)
   4025 			free_sconv_object(sc);
   4026 		*p = aes->aes_mbs.s;
   4027 		if (r == 0) {
   4028 			aes->aes_set |= AES_SET_MBS;
   4029 			ret = 0;/* success; overwrite previous error. */
   4030 		} else
   4031 			ret = -1;/* failure. */
   4032 	}
   4033 	return (ret);
   4034 }
   4035 
   4036 int
   4037 archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
   4038     const wchar_t **wp)
   4039 {
   4040 	int r, ret = 0;
   4041 
   4042 	(void)a;/* UNUSED */
   4043 	/* Return WCS form if we already have it. */
   4044 	if (aes->aes_set & AES_SET_WCS) {
   4045 		*wp = aes->aes_wcs.s;
   4046 		return (ret);
   4047 	}
   4048 
   4049 	*wp = NULL;
   4050 #if defined(_WIN32) && !defined(__CYGWIN__)
   4051 	/*
   4052 	 * On Windows, prefer converting from UTF-8 directly to WCS because:
   4053 	 * (1) there's no guarantee that the string can be represented in MBS (e.g.
   4054 	 * with CP_ACP), and (2) in order to convert from UTF-8 to MBS, we're going
   4055 	 * to need to convert from UTF-8 to WCS anyway and its wasteful to throw
   4056 	 * away that intermediate result
   4057 	 */
   4058 	if (aes->aes_set & AES_SET_UTF8) {
   4059 		struct archive_string_conv *sc;
   4060 
   4061 		sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
   4062 		if (sc != NULL) {
   4063 			archive_wstring_empty((&aes->aes_wcs));
   4064 			r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
   4065 			    aes->aes_utf8.s, aes->aes_utf8.length, sc);
   4066 			if (a == NULL)
   4067 				free_sconv_object(sc);
   4068 			if (r == 0) {
   4069 				aes->aes_set |= AES_SET_WCS;
   4070 				*wp = aes->aes_wcs.s;
   4071 				return (0);
   4072 			}
   4073 		}
   4074 	}
   4075 #endif
   4076 	/* Try converting UTF8 to MBS first if MBS does not exist yet. */
   4077 	if ((aes->aes_set & AES_SET_MBS) == 0) {
   4078 		const char *p; /* unused */
   4079 		archive_mstring_get_mbs(a, aes, &p); /* ignore errors, we'll handle it later */
   4080 	}
   4081 	/* Try converting MBS to WCS using native locale. */
   4082 	if (aes->aes_set & AES_SET_MBS) {
   4083 		archive_wstring_empty(&(aes->aes_wcs));
   4084 		r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
   4085 		    aes->aes_mbs.s, aes->aes_mbs.length);
   4086 		if (r == 0) {
   4087 			aes->aes_set |= AES_SET_WCS;
   4088 			*wp = aes->aes_wcs.s;
   4089 		} else
   4090 			ret = -1;/* failure. */
   4091 	}
   4092 	return (ret);
   4093 }
   4094 
   4095 int
   4096 archive_mstring_get_mbs_l(struct archive *a, struct archive_mstring *aes,
   4097     const char **p, size_t *length, struct archive_string_conv *sc)
   4098 {
   4099 	int ret = 0;
   4100 #if defined(_WIN32) && !defined(__CYGWIN__)
   4101 	int r;
   4102 
   4103 	/*
   4104 	 * Internationalization programming on Windows must use Wide
   4105 	 * characters because Windows platform cannot make locale UTF-8.
   4106 	 */
   4107 	if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
   4108 		archive_string_empty(&(aes->aes_mbs_in_locale));
   4109 		r = archive_string_append_from_wcs_in_codepage(
   4110 		    &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
   4111 		    aes->aes_wcs.length, sc);
   4112 		if (r == 0) {
   4113 			*p = aes->aes_mbs_in_locale.s;
   4114 			if (length != NULL)
   4115 				*length = aes->aes_mbs_in_locale.length;
   4116 			return (0);
   4117 		} else if (errno == ENOMEM)
   4118 			return (-1);
   4119 		else
   4120 			ret = -1;
   4121 	}
   4122 #endif
   4123 
   4124 	/* If there is not an MBS form but there is a WCS or UTF8 form, try converting
   4125 	 * with the native locale to be used for translating it to specified
   4126 	 * character-set. */
   4127 	if ((aes->aes_set & AES_SET_MBS) == 0) {
   4128 		const char *pm; /* unused */
   4129 		if (archive_mstring_get_mbs(a, aes, &pm) != 0) {
   4130 			/* We have another form, but failed to convert it to
   4131 			 * the native locale.  Transitively, we've failed to
   4132 			 * convert it to the specified character set. */
   4133 			ret = -1;
   4134 		}
   4135 	}
   4136 	/* If we already have an MBS form, use it to be translated to
   4137 	 * specified character-set. */
   4138 	if (aes->aes_set & AES_SET_MBS) {
   4139 		if (sc == NULL) {
   4140 			/* Conversion is unneeded. */
   4141 			*p = aes->aes_mbs.s;
   4142 			if (length != NULL)
   4143 				*length = aes->aes_mbs.length;
   4144 			return (0);
   4145 		}
   4146 		ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
   4147 		    aes->aes_mbs.s, aes->aes_mbs.length, sc);
   4148 		*p = aes->aes_mbs_in_locale.s;
   4149 		if (length != NULL)
   4150 			*length = aes->aes_mbs_in_locale.length;
   4151 	} else {
   4152 		/* Either we have no string in any form,
   4153 		 * or conversion failed and set 'ret != 0'.  */
   4154 		*p = NULL;
   4155 		if (length != NULL)
   4156 			*length = 0;
   4157 	}
   4158 	return (ret);
   4159 }
   4160 
   4161 int
   4162 archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
   4163 {
   4164 	if (mbs == NULL) {
   4165 		aes->aes_set = 0;
   4166 		return (0);
   4167 	}
   4168 	return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
   4169 }
   4170 
   4171 int
   4172 archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
   4173     size_t len)
   4174 {
   4175 	if (mbs == NULL) {
   4176 		aes->aes_set = 0;
   4177 		return (0);
   4178 	}
   4179 	aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
   4180 	archive_strncpy(&(aes->aes_mbs), mbs, len);
   4181 	archive_string_empty(&(aes->aes_utf8));
   4182 	archive_wstring_empty(&(aes->aes_wcs));
   4183 	return (0);
   4184 }
   4185 
   4186 int
   4187 archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
   4188 {
   4189 	return archive_mstring_copy_wcs_len(aes, wcs,
   4190 				wcs == NULL ? 0 : wcslen(wcs));
   4191 }
   4192 
   4193 int
   4194 archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
   4195 {
   4196   if (utf8 == NULL) {
   4197     aes->aes_set = 0;
   4198     return (0);
   4199   }
   4200   aes->aes_set = AES_SET_UTF8;
   4201   archive_string_empty(&(aes->aes_mbs));
   4202   archive_string_empty(&(aes->aes_wcs));
   4203   archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
   4204   return (int)strlen(utf8);
   4205 }
   4206 
   4207 int
   4208 archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
   4209     size_t len)
   4210 {
   4211 	if (wcs == NULL) {
   4212 		aes->aes_set = 0;
   4213 		return (0);
   4214 	}
   4215 	aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
   4216 	archive_string_empty(&(aes->aes_mbs));
   4217 	archive_string_empty(&(aes->aes_utf8));
   4218 	archive_wstrncpy(&(aes->aes_wcs), wcs, len);
   4219 	return (0);
   4220 }
   4221 
   4222 int
   4223 archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
   4224     const char *mbs, size_t len, struct archive_string_conv *sc)
   4225 {
   4226 	int r;
   4227 
   4228 	if (mbs == NULL) {
   4229 		aes->aes_set = 0;
   4230 		return (0);
   4231 	}
   4232 	archive_string_empty(&(aes->aes_mbs));
   4233 	archive_wstring_empty(&(aes->aes_wcs));
   4234 	archive_string_empty(&(aes->aes_utf8));
   4235 #if defined(_WIN32) && !defined(__CYGWIN__)
   4236 	/*
   4237 	 * Internationalization programming on Windows must use Wide
   4238 	 * characters because Windows platform cannot make locale UTF-8.
   4239 	 */
   4240 	if (sc == NULL) {
   4241 		if (archive_string_append(&(aes->aes_mbs),
   4242 			mbs, mbsnbytes(mbs, len)) == NULL) {
   4243 			aes->aes_set = 0;
   4244 			r = -1;
   4245 		} else {
   4246 			aes->aes_set = AES_SET_MBS;
   4247 			r = 0;
   4248 		}
   4249 #if defined(HAVE_ICONV)
   4250 	} else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
   4251 		/*
   4252 		 * This case happens only when MultiByteToWideChar() cannot
   4253 		 * handle sc->from_cp, and we have to iconv in order to
   4254 		 * translate character-set to wchar_t,UTF-16.
   4255 		 */
   4256 		iconv_t cd = sc->cd;
   4257 		unsigned from_cp;
   4258 		int flag;
   4259 
   4260 		/*
   4261 		 * Translate multi-bytes from some character-set to UTF-8.
   4262 		 */
   4263 		sc->cd = sc->cd_w;
   4264 		r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
   4265 		sc->cd = cd;
   4266 		if (r != 0) {
   4267 			aes->aes_set = 0;
   4268 			return (r);
   4269 		}
   4270 		aes->aes_set = AES_SET_UTF8;
   4271 
   4272 		/*
   4273 		 * Append the UTF-8 string into wstring.
   4274 		 */
   4275 		flag = sc->flag;
   4276 		sc->flag &= ~(SCONV_NORMALIZATION_C
   4277 				| SCONV_TO_UTF16| SCONV_FROM_UTF16);
   4278 		from_cp = sc->from_cp;
   4279 		sc->from_cp = CP_UTF8;
   4280 		r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
   4281 			aes->aes_utf8.s, aes->aes_utf8.length, sc);
   4282 		sc->flag = flag;
   4283 		sc->from_cp = from_cp;
   4284 		if (r == 0)
   4285 			aes->aes_set |= AES_SET_WCS;
   4286 #endif
   4287 	} else {
   4288 		r = archive_wstring_append_from_mbs_in_codepage(
   4289 		    &(aes->aes_wcs), mbs, len, sc);
   4290 		if (r == 0)
   4291 			aes->aes_set = AES_SET_WCS;
   4292 		else
   4293 			aes->aes_set = 0;
   4294 	}
   4295 #else
   4296 	r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
   4297 	if (r == 0)
   4298 		aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
   4299 	else
   4300 		aes->aes_set = 0;
   4301 #endif
   4302 	return (r);
   4303 }
   4304 
   4305 /*
   4306  * The 'update' form tries to proactively update all forms of
   4307  * this string (WCS and MBS) and returns an error if any of
   4308  * them fail.  This is used by the 'pax' handler, for instance,
   4309  * to detect and report character-conversion failures early while
   4310  * still allowing clients to get potentially useful values from
   4311  * the more tolerant lazy conversions.  (get_mbs and get_wcs will
   4312  * strive to give the user something useful, so you can get hopefully
   4313  * usable values even if some of the character conversions are failing.)
   4314  */
   4315 int
   4316 archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
   4317     const char *utf8)
   4318 {
   4319 	struct archive_string_conv *sc;
   4320 	int r;
   4321 
   4322 	if (utf8 == NULL) {
   4323 		aes->aes_set = 0;
   4324 		return (0); /* Succeeded in clearing everything. */
   4325 	}
   4326 
   4327 	/* Save the UTF8 string. */
   4328 	archive_strcpy(&(aes->aes_utf8), utf8);
   4329 
   4330 	/* Empty the mbs and wcs strings. */
   4331 	archive_string_empty(&(aes->aes_mbs));
   4332 	archive_wstring_empty(&(aes->aes_wcs));
   4333 
   4334 	aes->aes_set = AES_SET_UTF8;	/* Only UTF8 is set now. */
   4335 
   4336 	sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
   4337 	if (sc == NULL)
   4338 		return (-1);/* Couldn't allocate memory for sc. */
   4339 
   4340 #if defined(_WIN32) && !defined(__CYGWIN__)
   4341 	/* On Windows, there's no good way to convert from UTF8 -> MBS directly, so
   4342 	 * prefer to first convert to WCS as (1) it's wasteful to throw away the
   4343 	 * intermediate result, and (2) WCS will still be set even if we fail to
   4344 	 * convert to MBS (e.g. with ACP that can't represent the characters) */
   4345 	r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
   4346 		aes->aes_utf8.s, aes->aes_utf8.length, sc);
   4347 
   4348 	if (a == NULL)
   4349 		free_sconv_object(sc);
   4350 	if (r != 0)
   4351 		return (-1); /* This will guarantee we can't convert to MBS */
   4352 	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS; /* Both UTF8 and WCS set. */
   4353 
   4354 	/* Try converting WCS to MBS, return false on failure. */
   4355 	if (archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s,
   4356 	    aes->aes_wcs.length))
   4357 		return (-1);
   4358 #else
   4359 	/* Try converting UTF-8 to MBS, return false on failure. */
   4360 	r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
   4361 
   4362 	if (a == NULL)
   4363 		free_sconv_object(sc);
   4364 	if (r != 0)
   4365 		return (-1);
   4366 	aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
   4367 
   4368 	/* Try converting MBS to WCS, return false on failure. */
   4369 	if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
   4370 	    aes->aes_mbs.length))
   4371 		return (-1);
   4372 #endif
   4373 
   4374 	/* All conversions succeeded. */
   4375 	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
   4376 
   4377 	return (0);
   4378 }
   4379