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