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