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