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