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