archive_string.c revision 324417
1228753Smm/*-
2232153Smm * Copyright (c) 2003-2011 Tim Kientzle
3232153Smm * Copyright (c) 2011-2012 Michihiro NAKAJIMA
4228753Smm * All rights reserved.
5228753Smm *
6228753Smm * Redistribution and use in source and binary forms, with or without
7228753Smm * modification, are permitted provided that the following conditions
8228753Smm * are met:
9228753Smm * 1. Redistributions of source code must retain the above copyright
10228753Smm *    notice, this list of conditions and the following disclaimer.
11228753Smm * 2. Redistributions in binary form must reproduce the above copyright
12228753Smm *    notice, this list of conditions and the following disclaimer in the
13228753Smm *    documentation and/or other materials provided with the distribution.
14228753Smm *
15228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16228753Smm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17228753Smm * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18228753Smm * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19228753Smm * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20228753Smm * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21228753Smm * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22228753Smm * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23228753Smm * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24228753Smm * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25228753Smm */
26228753Smm
27228753Smm#include "archive_platform.h"
28228763Smm__FBSDID("$FreeBSD: stable/11/contrib/libarchive/libarchive/archive_string.c 324417 2017-10-08 20:54:53Z mm $");
29228753Smm
30228753Smm/*
31228753Smm * Basic resizable string support, to simplify manipulating arbitrary-sized
32228753Smm * strings while minimizing heap activity.
33232153Smm *
34232153Smm * In particular, the buffer used by a string object is only grown, it
35232153Smm * never shrinks, so you can clear and reuse the same string object
36232153Smm * without incurring additional memory allocations.
37228753Smm */
38228753Smm
39232153Smm#ifdef HAVE_ERRNO_H
40232153Smm#include <errno.h>
41232153Smm#endif
42232153Smm#ifdef HAVE_ICONV_H
43232153Smm#include <iconv.h>
44232153Smm#endif
45232153Smm#ifdef HAVE_LANGINFO_H
46232153Smm#include <langinfo.h>
47232153Smm#endif
48232153Smm#ifdef HAVE_LOCALCHARSET_H
49232153Smm#include <localcharset.h>
50232153Smm#endif
51228753Smm#ifdef HAVE_STDLIB_H
52228753Smm#include <stdlib.h>
53228753Smm#endif
54228753Smm#ifdef HAVE_STRING_H
55228753Smm#include <string.h>
56228753Smm#endif
57228753Smm#ifdef HAVE_WCHAR_H
58228753Smm#include <wchar.h>
59228753Smm#endif
60228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
61228753Smm#include <windows.h>
62232153Smm#include <locale.h>
63228753Smm#endif
64228753Smm
65232153Smm#include "archive_endian.h"
66228753Smm#include "archive_private.h"
67228753Smm#include "archive_string.h"
68232153Smm#include "archive_string_composition.h"
69228753Smm
70232153Smm#if !defined(HAVE_WMEMCPY) && !defined(wmemcpy)
71232153Smm#define wmemcpy(a,b,i)  (wchar_t *)memcpy((a), (b), (i) * sizeof(wchar_t))
72232153Smm#endif
73232153Smm
74299529Smm#if !defined(HAVE_WMEMMOVE) && !defined(wmemmove)
75299529Smm#define wmemmove(a,b,i)  (wchar_t *)memmove((a), (b), (i) * sizeof(wchar_t))
76299529Smm#endif
77299529Smm
78232153Smmstruct archive_string_conv {
79232153Smm	struct archive_string_conv	*next;
80232153Smm	char				*from_charset;
81232153Smm	char				*to_charset;
82232153Smm	unsigned			 from_cp;
83232153Smm	unsigned			 to_cp;
84232153Smm	/* Set 1 if from_charset and to_charset are the same. */
85232153Smm	int				 same;
86232153Smm	int				 flag;
87232153Smm#define SCONV_TO_CHARSET	1	/* MBS is being converted to specified
88232153Smm					 * charset. */
89232153Smm#define SCONV_FROM_CHARSET	(1<<1)	/* MBS is being converted from
90232153Smm					 * specified charset. */
91232153Smm#define SCONV_BEST_EFFORT 	(1<<2)	/* Copy at least ASCII code. */
92232153Smm#define SCONV_WIN_CP	 	(1<<3)	/* Use Windows API for converting
93232153Smm					 * MBS. */
94232153Smm#define SCONV_UTF8_LIBARCHIVE_2 (1<<4)	/* Incorrect UTF-8 made by libarchive
95232153Smm					 * 2.x in the wrong assumption. */
96232153Smm#define SCONV_NORMALIZATION_C	(1<<6)	/* Need normalization to be Form C.
97232153Smm					 * Before UTF-8 characters are actually
98232153Smm					 * processed. */
99232153Smm#define SCONV_NORMALIZATION_D	(1<<7)	/* Need normalization to be Form D.
100232153Smm					 * Before UTF-8 characters are actually
101232153Smm					 * processed.
102232153Smm					 * Currently this only for MAC OS X. */
103232153Smm#define SCONV_TO_UTF8		(1<<8)	/* "to charset" side is UTF-8. */
104232153Smm#define SCONV_FROM_UTF8		(1<<9)	/* "from charset" side is UTF-8. */
105232153Smm#define SCONV_TO_UTF16BE 	(1<<10)	/* "to charset" side is UTF-16BE. */
106232153Smm#define SCONV_FROM_UTF16BE 	(1<<11)	/* "from charset" side is UTF-16BE. */
107232153Smm#define SCONV_TO_UTF16LE 	(1<<12)	/* "to charset" side is UTF-16LE. */
108232153Smm#define SCONV_FROM_UTF16LE 	(1<<13)	/* "from charset" side is UTF-16LE. */
109232153Smm#define SCONV_TO_UTF16		(SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
110232153Smm#define SCONV_FROM_UTF16	(SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
111232153Smm
112232153Smm#if HAVE_ICONV
113232153Smm	iconv_t				 cd;
114232153Smm	iconv_t				 cd_w;/* Use at archive_mstring on
115232153Smm				 	       * Windows. */
116232153Smm#endif
117232153Smm	/* A temporary buffer for normalization. */
118232153Smm	struct archive_string		 utftmp;
119232153Smm	int (*converter[2])(struct archive_string *, const void *, size_t,
120232153Smm	    struct archive_string_conv *);
121232153Smm	int				 nconverter;
122232153Smm};
123232153Smm
124232153Smm#define CP_C_LOCALE	0	/* "C" locale only for this file. */
125232153Smm#define CP_UTF16LE	1200
126232153Smm#define CP_UTF16BE	1201
127232153Smm
128232153Smm#define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
129232153Smm#define IS_LOW_SURROGATE_LA(uc)	 ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
130232153Smm#define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
131232153Smm#define UNICODE_MAX		0x10FFFF
132232153Smm#define UNICODE_R_CHAR		0xFFFD	/* Replacement character. */
133232153Smm/* Set U+FFFD(Replacement character) in UTF-8. */
134299529Smmstatic const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd};
135232153Smm
136232153Smmstatic struct archive_string_conv *find_sconv_object(struct archive *,
137232153Smm	const char *, const char *);
138232153Smmstatic void add_sconv_object(struct archive *, struct archive_string_conv *);
139232153Smmstatic struct archive_string_conv *create_sconv_object(const char *,
140232153Smm	const char *, unsigned, int);
141232153Smmstatic void free_sconv_object(struct archive_string_conv *);
142232153Smmstatic struct archive_string_conv *get_sconv_object(struct archive *,
143232153Smm	const char *, const char *, int);
144232153Smmstatic unsigned make_codepage_from_charset(const char *);
145232153Smmstatic unsigned get_current_codepage(void);
146232153Smmstatic unsigned get_current_oemcp(void);
147232153Smmstatic size_t mbsnbytes(const void *, size_t);
148232153Smmstatic size_t utf16nbytes(const void *, size_t);
149232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
150232153Smmstatic int archive_wstring_append_from_mbs_in_codepage(
151232153Smm    struct archive_wstring *, const char *, size_t,
152232153Smm    struct archive_string_conv *);
153232153Smmstatic int archive_string_append_from_wcs_in_codepage(struct archive_string *,
154232153Smm    const wchar_t *, size_t, struct archive_string_conv *);
155232153Smmstatic int is_big_endian(void);
156232153Smmstatic int strncat_in_codepage(struct archive_string *, const void *,
157232153Smm    size_t, struct archive_string_conv *);
158238856Smmstatic int win_strncat_from_utf16be(struct archive_string *, const void *,
159232153Smm    size_t, struct archive_string_conv *);
160238856Smmstatic int win_strncat_from_utf16le(struct archive_string *, const void *,
161232153Smm    size_t, struct archive_string_conv *);
162238856Smmstatic int win_strncat_to_utf16be(struct archive_string *, const void *,
163232153Smm    size_t, struct archive_string_conv *);
164238856Smmstatic int win_strncat_to_utf16le(struct archive_string *, const void *,
165232153Smm    size_t, struct archive_string_conv *);
166238856Smm#endif
167238856Smmstatic int best_effort_strncat_from_utf16be(struct archive_string *,
168238856Smm    const void *, size_t, struct archive_string_conv *);
169238856Smmstatic int best_effort_strncat_from_utf16le(struct archive_string *,
170238856Smm    const void *, size_t, struct archive_string_conv *);
171238856Smmstatic int best_effort_strncat_to_utf16be(struct archive_string *,
172238856Smm    const void *, size_t, struct archive_string_conv *);
173238856Smmstatic int best_effort_strncat_to_utf16le(struct archive_string *,
174238856Smm    const void *, size_t, struct archive_string_conv *);
175232153Smm#if defined(HAVE_ICONV)
176232153Smmstatic int iconv_strncat_in_locale(struct archive_string *, const void *,
177232153Smm    size_t, struct archive_string_conv *);
178232153Smm#endif
179238856Smmstatic int best_effort_strncat_in_locale(struct archive_string *,
180238856Smm    const void *, size_t, struct archive_string_conv *);
181232153Smmstatic int _utf8_to_unicode(uint32_t *, const char *, size_t);
182232153Smmstatic int utf8_to_unicode(uint32_t *, const char *, size_t);
183232153Smmstatic inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
184232153Smmstatic int cesu8_to_unicode(uint32_t *, const char *, size_t);
185232153Smmstatic size_t unicode_to_utf8(char *, size_t, uint32_t);
186232153Smmstatic int utf16_to_unicode(uint32_t *, const char *, size_t, int);
187232153Smmstatic size_t unicode_to_utf16be(char *, size_t, uint32_t);
188232153Smmstatic size_t unicode_to_utf16le(char *, size_t, uint32_t);
189232153Smmstatic int strncat_from_utf8_libarchive2(struct archive_string *,
190232153Smm    const void *, size_t, struct archive_string_conv *);
191232153Smmstatic int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
192232153Smm    size_t, struct archive_string_conv *);
193232153Smmstatic int archive_string_normalize_C(struct archive_string *, const void *,
194232153Smm    size_t, struct archive_string_conv *);
195232153Smmstatic int archive_string_normalize_D(struct archive_string *, const void *,
196232153Smm    size_t, struct archive_string_conv *);
197232153Smmstatic int archive_string_append_unicode(struct archive_string *,
198232153Smm    const void *, size_t, struct archive_string_conv *);
199232153Smm
200232153Smmstatic struct archive_string *
201232153Smmarchive_string_append(struct archive_string *as, const char *p, size_t s)
202228753Smm{
203232153Smm	if (archive_string_ensure(as, as->length + s + 1) == NULL)
204232153Smm		return (NULL);
205318482Smm	if (s)
206318482Smm		memmove(as->s + as->length, p, s);
207228753Smm	as->length += s;
208232153Smm	as->s[as->length] = 0;
209228753Smm	return (as);
210228753Smm}
211228753Smm
212232153Smmstatic struct archive_wstring *
213232153Smmarchive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
214232153Smm{
215232153Smm	if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
216232153Smm		return (NULL);
217324417Smm	if (s)
218324417Smm		wmemmove(as->s + as->length, p, s);
219232153Smm	as->length += s;
220232153Smm	as->s[as->length] = 0;
221232153Smm	return (as);
222232153Smm}
223232153Smm
224313570Smmstruct archive_string *
225313570Smmarchive_array_append(struct archive_string *as, const char *p, size_t s)
226313570Smm{
227313570Smm	return archive_string_append(as, p, s);
228313570Smm}
229313570Smm
230228753Smmvoid
231232153Smmarchive_string_concat(struct archive_string *dest, struct archive_string *src)
232228753Smm{
233232153Smm	if (archive_string_append(dest, src->s, src->length) == NULL)
234232153Smm		__archive_errx(1, "Out of memory");
235228753Smm}
236228753Smm
237228753Smmvoid
238238856Smmarchive_wstring_concat(struct archive_wstring *dest,
239238856Smm    struct archive_wstring *src)
240228753Smm{
241232153Smm	if (archive_wstring_append(dest, src->s, src->length) == NULL)
242232153Smm		__archive_errx(1, "Out of memory");
243228753Smm}
244228753Smm
245228753Smmvoid
246232153Smmarchive_string_free(struct archive_string *as)
247228753Smm{
248228753Smm	as->length = 0;
249228753Smm	as->buffer_length = 0;
250232153Smm	free(as->s);
251232153Smm	as->s = NULL;
252228753Smm}
253228753Smm
254232153Smmvoid
255232153Smmarchive_wstring_free(struct archive_wstring *as)
256232153Smm{
257232153Smm	as->length = 0;
258232153Smm	as->buffer_length = 0;
259232153Smm	free(as->s);
260232153Smm	as->s = NULL;
261232153Smm}
262232153Smm
263232153Smmstruct archive_wstring *
264232153Smmarchive_wstring_ensure(struct archive_wstring *as, size_t s)
265232153Smm{
266232153Smm	return (struct archive_wstring *)
267232153Smm		archive_string_ensure((struct archive_string *)as,
268232153Smm					s * sizeof(wchar_t));
269232153Smm}
270232153Smm
271228753Smm/* Returns NULL on any allocation failure. */
272228753Smmstruct archive_string *
273232153Smmarchive_string_ensure(struct archive_string *as, size_t s)
274228753Smm{
275232153Smm	char *p;
276232153Smm	size_t new_length;
277232153Smm
278228753Smm	/* If buffer is already big enough, don't reallocate. */
279228753Smm	if (as->s && (s <= as->buffer_length))
280228753Smm		return (as);
281228753Smm
282228753Smm	/*
283228753Smm	 * Growing the buffer at least exponentially ensures that
284228753Smm	 * append operations are always linear in the number of
285228753Smm	 * characters appended.  Using a smaller growth rate for
286228753Smm	 * larger buffers reduces memory waste somewhat at the cost of
287228753Smm	 * a larger constant factor.
288228753Smm	 */
289228753Smm	if (as->buffer_length < 32)
290228753Smm		/* Start with a minimum 32-character buffer. */
291232153Smm		new_length = 32;
292228753Smm	else if (as->buffer_length < 8192)
293228753Smm		/* Buffers under 8k are doubled for speed. */
294232153Smm		new_length = as->buffer_length + as->buffer_length;
295228753Smm	else {
296228753Smm		/* Buffers 8k and over grow by at least 25% each time. */
297232153Smm		new_length = as->buffer_length + as->buffer_length / 4;
298232153Smm		/* Be safe: If size wraps, fail. */
299232153Smm		if (new_length < as->buffer_length) {
300232153Smm			/* On failure, wipe the string and return NULL. */
301232153Smm			archive_string_free(as);
302232153Smm			errno = ENOMEM;/* Make sure errno has ENOMEM. */
303228753Smm			return (NULL);
304228753Smm		}
305228753Smm	}
306228753Smm	/*
307228753Smm	 * The computation above is a lower limit to how much we'll
308228753Smm	 * grow the buffer.  In any case, we have to grow it enough to
309228753Smm	 * hold the request.
310228753Smm	 */
311232153Smm	if (new_length < s)
312232153Smm		new_length = s;
313228753Smm	/* Now we can reallocate the buffer. */
314232153Smm	p = (char *)realloc(as->s, new_length);
315232153Smm	if (p == NULL) {
316232153Smm		/* On failure, wipe the string and return NULL. */
317232153Smm		archive_string_free(as);
318232153Smm		errno = ENOMEM;/* Make sure errno has ENOMEM. */
319228753Smm		return (NULL);
320232153Smm	}
321232153Smm
322232153Smm	as->s = p;
323232153Smm	as->buffer_length = new_length;
324228753Smm	return (as);
325228753Smm}
326228753Smm
327232153Smm/*
328232153Smm * TODO: See if there's a way to avoid scanning
329232153Smm * the source string twice.  Then test to see
330232153Smm * if it actually helps (remember that we're almost
331232153Smm * always called with pretty short arguments, so
332232153Smm * such an optimization might not help).
333232153Smm */
334228753Smmstruct archive_string *
335232153Smmarchive_strncat(struct archive_string *as, const void *_p, size_t n)
336228753Smm{
337228753Smm	size_t s;
338228753Smm	const char *p, *pp;
339228753Smm
340228753Smm	p = (const char *)_p;
341228753Smm
342228753Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
343228753Smm	s = 0;
344228753Smm	pp = p;
345228753Smm	while (s < n && *pp) {
346228753Smm		pp++;
347228753Smm		s++;
348228753Smm	}
349232153Smm	if ((as = archive_string_append(as, p, s)) == NULL)
350232153Smm		__archive_errx(1, "Out of memory");
351232153Smm	return (as);
352228753Smm}
353228753Smm
354232153Smmstruct archive_wstring *
355232153Smmarchive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
356232153Smm{
357232153Smm	size_t s;
358232153Smm	const wchar_t *pp;
359232153Smm
360232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
361232153Smm	s = 0;
362232153Smm	pp = p;
363232153Smm	while (s < n && *pp) {
364232153Smm		pp++;
365232153Smm		s++;
366232153Smm	}
367232153Smm	if ((as = archive_wstring_append(as, p, s)) == NULL)
368232153Smm		__archive_errx(1, "Out of memory");
369232153Smm	return (as);
370232153Smm}
371232153Smm
372228753Smmstruct archive_string *
373232153Smmarchive_strcat(struct archive_string *as, const void *p)
374228753Smm{
375232153Smm	/* strcat is just strncat without an effective limit.
376232153Smm	 * Assert that we'll never get called with a source
377232153Smm	 * string over 16MB.
378232153Smm	 * TODO: Review all uses of strcat in the source
379232153Smm	 * and try to replace them with strncat().
380232153Smm	 */
381232153Smm	return archive_strncat(as, p, 0x1000000);
382228753Smm}
383228753Smm
384232153Smmstruct archive_wstring *
385232153Smmarchive_wstrcat(struct archive_wstring *as, const wchar_t *p)
386232153Smm{
387232153Smm	/* Ditto. */
388232153Smm	return archive_wstrncat(as, p, 0x1000000);
389232153Smm}
390232153Smm
391232153Smmstruct archive_string *
392232153Smmarchive_strappend_char(struct archive_string *as, char c)
393232153Smm{
394232153Smm	if ((as = archive_string_append(as, &c, 1)) == NULL)
395232153Smm		__archive_errx(1, "Out of memory");
396232153Smm	return (as);
397232153Smm}
398232153Smm
399232153Smmstruct archive_wstring *
400232153Smmarchive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
401232153Smm{
402232153Smm	if ((as = archive_wstring_append(as, &c, 1)) == NULL)
403232153Smm		__archive_errx(1, "Out of memory");
404232153Smm	return (as);
405232153Smm}
406232153Smm
407228753Smm/*
408232153Smm * Get the "current character set" name to use with iconv.
409232153Smm * On FreeBSD, the empty character set name "" chooses
410232153Smm * the correct character encoding for the current locale,
411232153Smm * so this isn't necessary.
412232153Smm * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
413232153Smm * on that system, we have to explicitly call nl_langinfo()
414232153Smm * to get the right name.  Not sure about other platforms.
415232153Smm *
416232153Smm * NOTE: GNU libiconv does not recognize the character-set name
417232153Smm * which some platform nl_langinfo(CODESET) returns, so we should
418232153Smm * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
419228753Smm */
420232153Smmstatic const char *
421232153Smmdefault_iconv_charset(const char *charset) {
422232153Smm	if (charset != NULL && charset[0] != '\0')
423232153Smm		return charset;
424232153Smm#if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
425232153Smm	/* locale_charset() is broken on Mac OS */
426232153Smm	return locale_charset();
427232153Smm#elif HAVE_NL_LANGINFO
428232153Smm	return nl_langinfo(CODESET);
429232153Smm#else
430232153Smm	return "";
431232153Smm#endif
432232153Smm}
433232153Smm
434232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
435232153Smm
436232153Smm/*
437232153Smm * Convert MBS to WCS.
438232153Smm * Note: returns -1 if conversion fails.
439232153Smm */
440232153Smmint
441232153Smmarchive_wstring_append_from_mbs(struct archive_wstring *dest,
442232153Smm    const char *p, size_t len)
443228753Smm{
444238856Smm	return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
445232153Smm}
446232153Smm
447232153Smmstatic int
448232153Smmarchive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
449232153Smm    const char *s, size_t length, struct archive_string_conv *sc)
450232153Smm{
451232153Smm	int count, ret = 0;
452232153Smm	UINT from_cp;
453232153Smm
454232153Smm	if (sc != NULL)
455232153Smm		from_cp = sc->from_cp;
456232153Smm	else
457232153Smm		from_cp = get_current_codepage();
458232153Smm
459232153Smm	if (from_cp == CP_C_LOCALE) {
460232153Smm		/*
461232153Smm		 * "C" locale special process.
462232153Smm		 */
463232153Smm		wchar_t *ws;
464232153Smm		const unsigned char *mp;
465232153Smm
466232153Smm		if (NULL == archive_wstring_ensure(dest,
467232153Smm		    dest->length + length + 1))
468232153Smm			return (-1);
469232153Smm
470232153Smm		ws = dest->s + dest->length;
471232153Smm		mp = (const unsigned char *)s;
472232153Smm		count = 0;
473232153Smm		while (count < (int)length && *mp) {
474232153Smm			*ws++ = (wchar_t)*mp++;
475232153Smm			count++;
476232153Smm		}
477238856Smm	} else if (sc != NULL &&
478238856Smm	    (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
479232153Smm		/*
480232153Smm		 * Normalize UTF-8 and UTF-16BE and convert it directly
481232153Smm		 * to UTF-16 as wchar_t.
482232153Smm		 */
483232153Smm		struct archive_string u16;
484232153Smm		int saved_flag = sc->flag;/* save current flag. */
485232153Smm
486232153Smm		if (is_big_endian())
487232153Smm			sc->flag |= SCONV_TO_UTF16BE;
488232153Smm		else
489232153Smm			sc->flag |= SCONV_TO_UTF16LE;
490232153Smm
491232153Smm		if (sc->flag & SCONV_FROM_UTF16) {
492232153Smm			/*
493232153Smm			 *  UTF-16BE/LE NFD ===> UTF-16 NFC
494238856Smm			 *  UTF-16BE/LE NFC ===> UTF-16 NFD
495232153Smm			 */
496248616Smm			count = (int)utf16nbytes(s, length);
497232153Smm		} else {
498232153Smm			/*
499232153Smm			 *  UTF-8 NFD ===> UTF-16 NFC
500238856Smm			 *  UTF-8 NFC ===> UTF-16 NFD
501232153Smm			 */
502248616Smm			count = (int)mbsnbytes(s, length);
503232153Smm		}
504232153Smm		u16.s = (char *)dest->s;
505232153Smm		u16.length = dest->length << 1;;
506232153Smm		u16.buffer_length = dest->buffer_length;
507238856Smm		if (sc->flag & SCONV_NORMALIZATION_C)
508238856Smm			ret = archive_string_normalize_C(&u16, s, count, sc);
509238856Smm		else
510238856Smm			ret = archive_string_normalize_D(&u16, s, count, sc);
511232153Smm		dest->s = (wchar_t *)u16.s;
512232153Smm		dest->length = u16.length >> 1;
513232153Smm		dest->buffer_length = u16.buffer_length;
514232153Smm		sc->flag = saved_flag;/* restore the saved flag. */
515232153Smm		return (ret);
516232153Smm	} else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
517248616Smm		count = (int)utf16nbytes(s, length);
518232153Smm		count >>= 1; /* to be WCS length */
519232153Smm		/* Allocate memory for WCS. */
520232153Smm		if (NULL == archive_wstring_ensure(dest,
521232153Smm		    dest->length + count + 1))
522232153Smm			return (-1);
523238856Smm		wmemcpy(dest->s + dest->length, (const wchar_t *)s, count);
524232153Smm		if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) {
525232153Smm			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
526232153Smm			int b;
527232153Smm			for (b = 0; b < count; b++) {
528232153Smm				uint16_t val = archive_le16dec(u16+b);
529232153Smm				archive_be16enc(u16+b, val);
530232153Smm			}
531232153Smm		} else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) {
532232153Smm			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
533232153Smm			int b;
534232153Smm			for (b = 0; b < count; b++) {
535232153Smm				uint16_t val = archive_be16dec(u16+b);
536232153Smm				archive_le16enc(u16+b, val);
537232153Smm			}
538232153Smm		}
539232153Smm	} else {
540232153Smm		DWORD mbflag;
541238856Smm		size_t buffsize;
542232153Smm
543232153Smm		if (sc == NULL)
544232153Smm			mbflag = 0;
545232153Smm		else if (sc->flag & SCONV_FROM_CHARSET) {
546232153Smm			/* Do not trust the length which comes from
547232153Smm			 * an archive file. */
548232153Smm			length = mbsnbytes(s, length);
549232153Smm			mbflag = 0;
550232153Smm		} else
551232153Smm			mbflag = MB_PRECOMPOSED;
552232153Smm
553238856Smm		buffsize = dest->length + length + 1;
554238856Smm		do {
555238856Smm			/* Allocate memory for WCS. */
556238856Smm			if (NULL == archive_wstring_ensure(dest, buffsize))
557232153Smm				return (-1);
558238856Smm			/* Convert MBS to WCS. */
559238856Smm			count = MultiByteToWideChar(from_cp,
560248616Smm			    mbflag, s, (int)length, dest->s + dest->length,
561248616Smm			    (int)(dest->buffer_length >> 1) -1);
562238856Smm			if (count == 0 &&
563238856Smm			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
564238856Smm				/* Expand the WCS buffer. */
565238856Smm				buffsize = dest->buffer_length << 1;
566238856Smm				continue;
567232153Smm			}
568238856Smm			if (count == 0 && length != 0)
569238856Smm				ret = -1;
570302294Smm			break;
571302294Smm		} while (1);
572232153Smm	}
573232153Smm	dest->length += count;
574232153Smm	dest->s[dest->length] = L'\0';
575232153Smm	return (ret);
576232153Smm}
577232153Smm
578232153Smm#else
579232153Smm
580232153Smm/*
581232153Smm * Convert MBS to WCS.
582232153Smm * Note: returns -1 if conversion fails.
583232153Smm */
584232153Smmint
585232153Smmarchive_wstring_append_from_mbs(struct archive_wstring *dest,
586232153Smm    const char *p, size_t len)
587232153Smm{
588232153Smm	size_t r;
589238856Smm	int ret_val = 0;
590232153Smm	/*
591232153Smm	 * No single byte will be more than one wide character,
592232153Smm	 * so this length estimate will always be big enough.
593232153Smm	 */
594232153Smm	size_t wcs_length = len;
595232153Smm	size_t mbs_length = len;
596232153Smm	const char *mbs = p;
597232153Smm	wchar_t *wcs;
598232153Smm#if HAVE_MBRTOWC
599232153Smm	mbstate_t shift_state;
600232153Smm
601232153Smm	memset(&shift_state, 0, sizeof(shift_state));
602232153Smm#endif
603232153Smm	if (NULL == archive_wstring_ensure(dest, dest->length + wcs_length + 1))
604238856Smm		return (-1);
605232153Smm	wcs = dest->s + dest->length;
606232153Smm	/*
607232153Smm	 * We cannot use mbsrtowcs/mbstowcs here because those may convert
608313570Smm	 * extra MBS when strlen(p) > len and one wide character consists of
609232153Smm	 * multi bytes.
610232153Smm	 */
611238856Smm	while (*mbs && mbs_length > 0) {
612238856Smm		if (wcs_length == 0) {
613238856Smm			dest->length = wcs - dest->s;
614238856Smm			dest->s[dest->length] = L'\0';
615238856Smm			wcs_length = mbs_length;
616238856Smm			if (NULL == archive_wstring_ensure(dest,
617238856Smm			    dest->length + wcs_length + 1))
618238856Smm				return (-1);
619238856Smm			wcs = dest->s + dest->length;
620238856Smm		}
621232153Smm#if HAVE_MBRTOWC
622232153Smm		r = mbrtowc(wcs, mbs, wcs_length, &shift_state);
623232153Smm#else
624232153Smm		r = mbtowc(wcs, mbs, wcs_length);
625232153Smm#endif
626232153Smm		if (r == (size_t)-1 || r == (size_t)-2) {
627238856Smm			ret_val = -1;
628238856Smm			if (errno == EILSEQ) {
629238856Smm				++mbs;
630238856Smm				--mbs_length;
631238856Smm				continue;
632238856Smm			} else
633238856Smm				break;
634232153Smm		}
635232153Smm		if (r == 0 || r > mbs_length)
636232153Smm			break;
637232153Smm		wcs++;
638232153Smm		wcs_length--;
639232153Smm		mbs += r;
640232153Smm		mbs_length -= r;
641232153Smm	}
642232153Smm	dest->length = wcs - dest->s;
643232153Smm	dest->s[dest->length] = L'\0';
644238856Smm	return (ret_val);
645232153Smm}
646232153Smm
647232153Smm#endif
648232153Smm
649232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
650232153Smm
651232153Smm/*
652232153Smm * WCS ==> MBS.
653232153Smm * Note: returns -1 if conversion fails.
654232153Smm *
655232153Smm * Win32 builds use WideCharToMultiByte from the Windows API.
656232153Smm * (Maybe Cygwin should too?  WideCharToMultiByte will know a
657232153Smm * lot more about local character encodings than the wcrtomb()
658232153Smm * wrapper is going to know.)
659232153Smm */
660232153Smmint
661232153Smmarchive_string_append_from_wcs(struct archive_string *as,
662232153Smm    const wchar_t *w, size_t len)
663232153Smm{
664238856Smm	return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
665232153Smm}
666232153Smm
667232153Smmstatic int
668232153Smmarchive_string_append_from_wcs_in_codepage(struct archive_string *as,
669232153Smm    const wchar_t *ws, size_t len, struct archive_string_conv *sc)
670232153Smm{
671232153Smm	BOOL defchar_used, *dp;
672232153Smm	int count, ret = 0;
673232153Smm	UINT to_cp;
674232153Smm	int wslen = (int)len;
675232153Smm
676232153Smm	if (sc != NULL)
677232153Smm		to_cp = sc->to_cp;
678232153Smm	else
679232153Smm		to_cp = get_current_codepage();
680232153Smm
681232153Smm	if (to_cp == CP_C_LOCALE) {
682232153Smm		/*
683232153Smm		 * "C" locale special process.
684232153Smm		 */
685232153Smm		const wchar_t *wp = ws;
686232153Smm		char *p;
687232153Smm
688232153Smm		if (NULL == archive_string_ensure(as,
689232153Smm		    as->length + wslen +1))
690232153Smm			return (-1);
691232153Smm		p = as->s + as->length;
692232153Smm		count = 0;
693232153Smm		defchar_used = 0;
694232153Smm		while (count < wslen && *wp) {
695232153Smm			if (*wp > 255) {
696232153Smm				*p++ = '?';
697232153Smm				wp++;
698232153Smm				defchar_used = 1;
699232153Smm			} else
700232153Smm				*p++ = (char)*wp++;
701232153Smm			count++;
702232153Smm		}
703232153Smm	} else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
704232153Smm		uint16_t *u16;
705232153Smm
706232153Smm		if (NULL ==
707232153Smm		    archive_string_ensure(as, as->length + len * 2 + 2))
708232153Smm			return (-1);
709232153Smm		u16 = (uint16_t *)(as->s + as->length);
710232153Smm		count = 0;
711232153Smm		defchar_used = 0;
712232153Smm		if (sc->flag & SCONV_TO_UTF16BE) {
713232153Smm			while (count < (int)len && *ws) {
714232153Smm				archive_be16enc(u16+count, *ws);
715232153Smm				ws++;
716232153Smm				count++;
717232153Smm			}
718232153Smm		} else {
719232153Smm			while (count < (int)len && *ws) {
720232153Smm				archive_le16enc(u16+count, *ws);
721232153Smm				ws++;
722232153Smm				count++;
723232153Smm			}
724232153Smm		}
725232153Smm		count <<= 1; /* to be byte size */
726232153Smm	} else {
727232153Smm		/* Make sure the MBS buffer has plenty to set. */
728232153Smm		if (NULL ==
729232153Smm		    archive_string_ensure(as, as->length + len * 2 + 1))
730232153Smm			return (-1);
731232153Smm		do {
732232153Smm			defchar_used = 0;
733232153Smm			if (to_cp == CP_UTF8 || sc == NULL)
734232153Smm				dp = NULL;
735232153Smm			else
736232153Smm				dp = &defchar_used;
737232153Smm			count = WideCharToMultiByte(to_cp, 0, ws, wslen,
738248616Smm			    as->s + as->length, (int)as->buffer_length-1, NULL, dp);
739232153Smm			if (count == 0 &&
740232153Smm			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
741232153Smm				/* Expand the MBS buffer and retry. */
742232153Smm				if (NULL == archive_string_ensure(as,
743232153Smm					as->buffer_length + len))
744232153Smm					return (-1);
745232153Smm				continue;
746232153Smm			}
747232153Smm			if (count == 0)
748232153Smm				ret = -1;
749299529Smm			break;
750299529Smm		} while (1);
751232153Smm	}
752232153Smm	as->length += count;
753232153Smm	as->s[as->length] = '\0';
754232153Smm	return (defchar_used?-1:ret);
755232153Smm}
756232153Smm
757232153Smm#elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
758232153Smm
759232153Smm/*
760232153Smm * Translates a wide character string into current locale character set
761232153Smm * and appends to the archive_string.  Note: returns -1 if conversion
762232153Smm * fails.
763232153Smm */
764232153Smmint
765232153Smmarchive_string_append_from_wcs(struct archive_string *as,
766232153Smm    const wchar_t *w, size_t len)
767232153Smm{
768232153Smm	/* We cannot use the standard wcstombs() here because it
769232153Smm	 * cannot tell us how big the output buffer should be.  So
770232153Smm	 * I've built a loop around wcrtomb() or wctomb() that
771232153Smm	 * converts a character at a time and resizes the string as
772232153Smm	 * needed.  We prefer wcrtomb() when it's available because
773232153Smm	 * it's thread-safe. */
774232153Smm	int n, ret_val = 0;
775228753Smm	char *p;
776232153Smm	char *end;
777232153Smm#if HAVE_WCRTOMB
778232153Smm	mbstate_t shift_state;
779228753Smm
780232153Smm	memset(&shift_state, 0, sizeof(shift_state));
781232153Smm#else
782232153Smm	/* Clear the shift state before starting. */
783232153Smm	wctomb(NULL, L'\0');
784232153Smm#endif
785228753Smm	/*
786232153Smm	 * Allocate buffer for MBS.
787232153Smm	 * We need this allocation here since it is possible that
788232153Smm	 * as->s is still NULL.
789228753Smm	 */
790232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
791238856Smm		return (-1);
792232153Smm
793232153Smm	p = as->s + as->length;
794232153Smm	end = as->s + as->buffer_length - MB_CUR_MAX -1;
795232153Smm	while (*w != L'\0' && len > 0) {
796232153Smm		if (p >= end) {
797232153Smm			as->length = p - as->s;
798232153Smm			as->s[as->length] = '\0';
799232153Smm			/* Re-allocate buffer for MBS. */
800232153Smm			if (archive_string_ensure(as,
801232153Smm			    as->length + len * 2 + 1) == NULL)
802238856Smm				return (-1);
803232153Smm			p = as->s + as->length;
804232153Smm			end = as->s + as->buffer_length - MB_CUR_MAX -1;
805228753Smm		}
806232153Smm#if HAVE_WCRTOMB
807232153Smm		n = wcrtomb(p, *w++, &shift_state);
808232153Smm#else
809232153Smm		n = wctomb(p, *w++);
810232153Smm#endif
811232153Smm		if (n == -1) {
812232153Smm			if (errno == EILSEQ) {
813232153Smm				/* Skip an illegal wide char. */
814232153Smm				*p++ = '?';
815232153Smm				ret_val = -1;
816232153Smm			} else {
817232153Smm				ret_val = -1;
818232153Smm				break;
819232153Smm			}
820232153Smm		} else
821232153Smm			p += n;
822232153Smm		len--;
823232153Smm	}
824232153Smm	as->length = p - as->s;
825232153Smm	as->s[as->length] = '\0';
826232153Smm	return (ret_val);
827232153Smm}
828232153Smm
829232153Smm#else /* HAVE_WCTOMB || HAVE_WCRTOMB */
830232153Smm
831232153Smm/*
832232153Smm * TODO: Test if __STDC_ISO_10646__ is defined.
833232153Smm * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
834232153Smm * one character at a time.  If a non-Windows platform doesn't have
835232153Smm * either of these, fall back to the built-in UTF8 conversion.
836232153Smm */
837232153Smmint
838232153Smmarchive_string_append_from_wcs(struct archive_string *as,
839232153Smm    const wchar_t *w, size_t len)
840232153Smm{
841232153Smm	(void)as;/* UNUSED */
842232153Smm	(void)w;/* UNUSED */
843232153Smm	(void)len;/* UNUSED */
844238856Smm	errno = ENOSYS;
845232153Smm	return (-1);
846232153Smm}
847232153Smm
848232153Smm#endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
849232153Smm
850232153Smm/*
851232153Smm * Find a string conversion object by a pair of 'from' charset name
852232153Smm * and 'to' charset name from an archive object.
853232153Smm * Return NULL if not found.
854232153Smm */
855232153Smmstatic struct archive_string_conv *
856232153Smmfind_sconv_object(struct archive *a, const char *fc, const char *tc)
857232153Smm{
858232153Smm	struct archive_string_conv *sc;
859232153Smm
860232153Smm	if (a == NULL)
861232153Smm		return (NULL);
862232153Smm
863232153Smm	for (sc = a->sconv; sc != NULL; sc = sc->next) {
864232153Smm		if (strcmp(sc->from_charset, fc) == 0 &&
865232153Smm		    strcmp(sc->to_charset, tc) == 0)
866232153Smm			break;
867232153Smm	}
868232153Smm	return (sc);
869232153Smm}
870232153Smm
871232153Smm/*
872232153Smm * Register a string object to an archive object.
873232153Smm */
874232153Smmstatic void
875232153Smmadd_sconv_object(struct archive *a, struct archive_string_conv *sc)
876232153Smm{
877232153Smm	struct archive_string_conv **psc;
878232153Smm
879232153Smm	/* Add a new sconv to sconv list. */
880232153Smm	psc = &(a->sconv);
881232153Smm	while (*psc != NULL)
882232153Smm		psc = &((*psc)->next);
883232153Smm	*psc = sc;
884232153Smm}
885232153Smm
886232153Smmstatic void
887232153Smmadd_converter(struct archive_string_conv *sc, int (*converter)
888232153Smm    (struct archive_string *, const void *, size_t,
889232153Smm     struct archive_string_conv *))
890232153Smm{
891232153Smm	if (sc == NULL || sc->nconverter >= 2)
892232153Smm		__archive_errx(1, "Programing error");
893232153Smm	sc->converter[sc->nconverter++] = converter;
894232153Smm}
895232153Smm
896232153Smmstatic void
897232153Smmsetup_converter(struct archive_string_conv *sc)
898232153Smm{
899232153Smm
900232153Smm	/* Reset. */
901232153Smm	sc->nconverter = 0;
902232153Smm
903232153Smm	/*
904232153Smm	 * Perform special sequence for the incorrect UTF-8 filenames
905232153Smm	 * made by libarchive2.x.
906232153Smm	 */
907232153Smm	if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
908232153Smm		add_converter(sc, strncat_from_utf8_libarchive2);
909232153Smm		return;
910232153Smm	}
911232153Smm
912232153Smm	/*
913232153Smm	 * Convert a string to UTF-16BE/LE.
914232153Smm	 */
915232153Smm	if (sc->flag & SCONV_TO_UTF16) {
916232153Smm		/*
917232153Smm		 * If the current locale is UTF-8, we can translate
918232153Smm		 * a UTF-8 string into a UTF-16BE string.
919232153Smm		 */
920232153Smm		if (sc->flag & SCONV_FROM_UTF8) {
921232153Smm			add_converter(sc, archive_string_append_unicode);
922232153Smm			return;
923228753Smm		}
924232153Smm
925232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
926232153Smm		if (sc->flag & SCONV_WIN_CP) {
927232153Smm			if (sc->flag & SCONV_TO_UTF16BE)
928232153Smm				add_converter(sc, win_strncat_to_utf16be);
929232153Smm			else
930232153Smm				add_converter(sc, win_strncat_to_utf16le);
931232153Smm			return;
932232153Smm		}
933232153Smm#endif
934232153Smm
935232153Smm#if defined(HAVE_ICONV)
936232153Smm		if (sc->cd != (iconv_t)-1) {
937232153Smm			add_converter(sc, iconv_strncat_in_locale);
938232153Smm			return;
939232153Smm		}
940232153Smm#endif
941232153Smm
942232153Smm		if (sc->flag & SCONV_BEST_EFFORT) {
943232153Smm			if (sc->flag & SCONV_TO_UTF16BE)
944238856Smm				add_converter(sc,
945238856Smm					best_effort_strncat_to_utf16be);
946232153Smm			else
947238856Smm				add_converter(sc,
948238856Smm					best_effort_strncat_to_utf16le);
949232153Smm		} else
950232153Smm			/* Make sure we have no converter. */
951232153Smm			sc->nconverter = 0;
952232153Smm		return;
953232153Smm	}
954232153Smm
955232153Smm	/*
956232153Smm	 * Convert a string from UTF-16BE/LE.
957232153Smm	 */
958232153Smm	if (sc->flag & SCONV_FROM_UTF16) {
959232153Smm		/*
960232153Smm		 * At least we should normalize a UTF-16BE string.
961232153Smm		 */
962232153Smm		if (sc->flag & SCONV_NORMALIZATION_D)
963232153Smm			add_converter(sc,archive_string_normalize_D);
964238856Smm		else if (sc->flag & SCONV_NORMALIZATION_C)
965232153Smm			add_converter(sc, archive_string_normalize_C);
966232153Smm
967232153Smm		if (sc->flag & SCONV_TO_UTF8) {
968232153Smm			/*
969232153Smm			 * If the current locale is UTF-8, we can translate
970232153Smm			 * a UTF-16BE/LE string into a UTF-8 string directly.
971232153Smm			 */
972232153Smm			if (!(sc->flag &
973232153Smm			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
974232153Smm				add_converter(sc,
975232153Smm				    archive_string_append_unicode);
976232153Smm			return;
977232153Smm		}
978232153Smm
979232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
980232153Smm		if (sc->flag & SCONV_WIN_CP) {
981232153Smm			if (sc->flag & SCONV_FROM_UTF16BE)
982232153Smm				add_converter(sc, win_strncat_from_utf16be);
983232153Smm			else
984232153Smm				add_converter(sc, win_strncat_from_utf16le);
985232153Smm			return;
986232153Smm		}
987232153Smm#endif
988232153Smm
989232153Smm#if defined(HAVE_ICONV)
990232153Smm		if (sc->cd != (iconv_t)-1) {
991232153Smm			add_converter(sc, iconv_strncat_in_locale);
992232153Smm			return;
993232153Smm		}
994232153Smm#endif
995232153Smm
996232153Smm		if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
997232153Smm		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
998232153Smm			add_converter(sc, best_effort_strncat_from_utf16be);
999232153Smm		else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1000232153Smm		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1001232153Smm			add_converter(sc, best_effort_strncat_from_utf16le);
1002232153Smm		else
1003232153Smm			/* Make sure we have no converter. */
1004232153Smm			sc->nconverter = 0;
1005232153Smm		return;
1006232153Smm	}
1007232153Smm
1008232153Smm	if (sc->flag & SCONV_FROM_UTF8) {
1009232153Smm		/*
1010232153Smm		 * At least we should normalize a UTF-8 string.
1011232153Smm		 */
1012232153Smm		if (sc->flag & SCONV_NORMALIZATION_D)
1013232153Smm			add_converter(sc,archive_string_normalize_D);
1014238856Smm		else if (sc->flag & SCONV_NORMALIZATION_C)
1015232153Smm			add_converter(sc, archive_string_normalize_C);
1016232153Smm
1017232153Smm		/*
1018232153Smm		 * Copy UTF-8 string with a check of CESU-8.
1019232153Smm		 * Apparently, iconv does not check surrogate pairs in UTF-8
1020232153Smm		 * when both from-charset and to-charset are UTF-8, and then
1021232153Smm		 * we use our UTF-8 copy code.
1022232153Smm		 */
1023232153Smm		if (sc->flag & SCONV_TO_UTF8) {
1024232153Smm			/*
1025232153Smm			 * If the current locale is UTF-8, we can translate
1026232153Smm			 * a UTF-16BE string into a UTF-8 string directly.
1027232153Smm			 */
1028232153Smm			if (!(sc->flag &
1029232153Smm			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1030232153Smm				add_converter(sc, strncat_from_utf8_to_utf8);
1031232153Smm			return;
1032232153Smm		}
1033232153Smm	}
1034232153Smm
1035232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1036232153Smm	/*
1037232153Smm	 * On Windows we can use Windows API for a string conversion.
1038232153Smm	 */
1039232153Smm	if (sc->flag & SCONV_WIN_CP) {
1040232153Smm		add_converter(sc, strncat_in_codepage);
1041232153Smm		return;
1042232153Smm	}
1043232153Smm#endif
1044232153Smm
1045232153Smm#if HAVE_ICONV
1046232153Smm	if (sc->cd != (iconv_t)-1) {
1047232153Smm		add_converter(sc, iconv_strncat_in_locale);
1048238856Smm		/*
1049238856Smm		 * iconv generally does not support UTF-8-MAC and so
1050238856Smm		 * we have to the output of iconv from NFC to NFD if
1051238856Smm		 * need.
1052238856Smm		 */
1053238856Smm		if ((sc->flag & SCONV_FROM_CHARSET) &&
1054238856Smm		    (sc->flag & SCONV_TO_UTF8)) {
1055238856Smm			if (sc->flag & SCONV_NORMALIZATION_D)
1056238856Smm				add_converter(sc, archive_string_normalize_D);
1057238856Smm		}
1058232153Smm		return;
1059232153Smm	}
1060232153Smm#endif
1061232153Smm
1062232153Smm	/*
1063232153Smm	 * Try conversion in the best effort or no conversion.
1064232153Smm	 */
1065232153Smm	if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
1066232153Smm		add_converter(sc, best_effort_strncat_in_locale);
1067232153Smm	else
1068232153Smm		/* Make sure we have no converter. */
1069232153Smm		sc->nconverter = 0;
1070232153Smm}
1071232153Smm
1072232153Smm/*
1073232153Smm * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
1074232153Smm * and CP932 which are referenced in create_sconv_object().
1075232153Smm */
1076232153Smmstatic const char *
1077232153Smmcanonical_charset_name(const char *charset)
1078232153Smm{
1079232153Smm	char cs[16];
1080232153Smm	char *p;
1081232153Smm	const char *s;
1082232153Smm
1083232153Smm	if (charset == NULL || charset[0] == '\0'
1084232153Smm	    || strlen(charset) > 15)
1085232153Smm		return (charset);
1086232153Smm
1087232153Smm	/* Copy name to uppercase. */
1088232153Smm	p = cs;
1089232153Smm	s = charset;
1090232153Smm	while (*s) {
1091232153Smm		char c = *s++;
1092232153Smm		if (c >= 'a' && c <= 'z')
1093232153Smm			c -= 'a' - 'A';
1094232153Smm		*p++ = c;
1095232153Smm	}
1096232153Smm	*p++ = '\0';
1097232153Smm
1098232153Smm	if (strcmp(cs, "UTF-8") == 0 ||
1099232153Smm	    strcmp(cs, "UTF8") == 0)
1100232153Smm		return ("UTF-8");
1101232153Smm	if (strcmp(cs, "UTF-16BE") == 0 ||
1102232153Smm	    strcmp(cs, "UTF16BE") == 0)
1103232153Smm		return ("UTF-16BE");
1104232153Smm	if (strcmp(cs, "UTF-16LE") == 0 ||
1105232153Smm	    strcmp(cs, "UTF16LE") == 0)
1106232153Smm		return ("UTF-16LE");
1107232153Smm	if (strcmp(cs, "CP932") == 0)
1108232153Smm		return ("CP932");
1109232153Smm	return (charset);
1110232153Smm}
1111232153Smm
1112232153Smm/*
1113232153Smm * Create a string conversion object.
1114232153Smm */
1115232153Smmstatic struct archive_string_conv *
1116232153Smmcreate_sconv_object(const char *fc, const char *tc,
1117232153Smm    unsigned current_codepage, int flag)
1118232153Smm{
1119232153Smm	struct archive_string_conv *sc;
1120232153Smm
1121232153Smm	sc = calloc(1, sizeof(*sc));
1122232153Smm	if (sc == NULL)
1123232153Smm		return (NULL);
1124232153Smm	sc->next = NULL;
1125232153Smm	sc->from_charset = strdup(fc);
1126232153Smm	if (sc->from_charset == NULL) {
1127232153Smm		free(sc);
1128232153Smm		return (NULL);
1129232153Smm	}
1130232153Smm	sc->to_charset = strdup(tc);
1131232153Smm	if (sc->to_charset == NULL) {
1132248616Smm		free(sc->from_charset);
1133232153Smm		free(sc);
1134232153Smm		return (NULL);
1135232153Smm	}
1136232153Smm	archive_string_init(&sc->utftmp);
1137232153Smm
1138232153Smm	if (flag & SCONV_TO_CHARSET) {
1139232153Smm		/*
1140232153Smm		 * Convert characters from the current locale charset to
1141232153Smm		 * a specified charset.
1142232153Smm		 */
1143232153Smm		sc->from_cp = current_codepage;
1144232153Smm		sc->to_cp = make_codepage_from_charset(tc);
1145232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1146232153Smm		if (IsValidCodePage(sc->to_cp))
1147232153Smm			flag |= SCONV_WIN_CP;
1148232153Smm#endif
1149232153Smm	} else if (flag & SCONV_FROM_CHARSET) {
1150232153Smm		/*
1151232153Smm		 * Convert characters from a specified charset to
1152232153Smm		 * the current locale charset.
1153232153Smm		 */
1154232153Smm		sc->to_cp = current_codepage;
1155232153Smm		sc->from_cp = make_codepage_from_charset(fc);
1156232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1157232153Smm		if (IsValidCodePage(sc->from_cp))
1158232153Smm			flag |= SCONV_WIN_CP;
1159232153Smm#endif
1160232153Smm	}
1161232153Smm
1162232153Smm	/*
1163232153Smm	 * Check if "from charset" and "to charset" are the same.
1164232153Smm	 */
1165232153Smm	if (strcmp(fc, tc) == 0 ||
1166232153Smm	    (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
1167232153Smm		sc->same = 1;
1168232153Smm	else
1169232153Smm		sc->same = 0;
1170232153Smm
1171232153Smm	/*
1172232153Smm	 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
1173232153Smm	 */
1174232153Smm	if (strcmp(tc, "UTF-8") == 0)
1175232153Smm		flag |= SCONV_TO_UTF8;
1176232153Smm	else if (strcmp(tc, "UTF-16BE") == 0)
1177232153Smm		flag |= SCONV_TO_UTF16BE;
1178232153Smm	else if (strcmp(tc, "UTF-16LE") == 0)
1179232153Smm		flag |= SCONV_TO_UTF16LE;
1180232153Smm	if (strcmp(fc, "UTF-8") == 0)
1181232153Smm		flag |= SCONV_FROM_UTF8;
1182232153Smm	else if (strcmp(fc, "UTF-16BE") == 0)
1183232153Smm		flag |= SCONV_FROM_UTF16BE;
1184232153Smm	else if (strcmp(fc, "UTF-16LE") == 0)
1185232153Smm		flag |= SCONV_FROM_UTF16LE;
1186232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1187232153Smm	if (sc->to_cp == CP_UTF8)
1188232153Smm		flag |= SCONV_TO_UTF8;
1189232153Smm	else if (sc->to_cp == CP_UTF16BE)
1190232153Smm		flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
1191232153Smm	else if (sc->to_cp == CP_UTF16LE)
1192232153Smm		flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
1193232153Smm	if (sc->from_cp == CP_UTF8)
1194232153Smm		flag |= SCONV_FROM_UTF8;
1195232153Smm	else if (sc->from_cp == CP_UTF16BE)
1196232153Smm		flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
1197232153Smm	else if (sc->from_cp == CP_UTF16LE)
1198232153Smm		flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
1199232153Smm#endif
1200232153Smm
1201232153Smm	/*
1202232153Smm	 * Set a flag for Unicode NFD. Usually iconv cannot correctly
1203232153Smm	 * handle it. So we have to translate NFD characters to NFC ones
1204232153Smm	 * ourselves before iconv handles. Another reason is to prevent
1205232153Smm	 * that the same sight of two filenames, one is NFC and other
1206232153Smm	 * is NFD, would be in its directory.
1207232153Smm	 * On Mac OS X, although its filesystem layer automatically
1208232153Smm	 * convert filenames to NFD, it would be useful for filename
1209232153Smm	 * comparing to find out the same filenames that we normalize
1210232153Smm	 * that to be NFD ourselves.
1211232153Smm	 */
1212232153Smm	if ((flag & SCONV_FROM_CHARSET) &&
1213232153Smm	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
1214232153Smm#if defined(__APPLE__)
1215238856Smm		if (flag & SCONV_TO_UTF8)
1216238856Smm			flag |= SCONV_NORMALIZATION_D;
1217238856Smm		else
1218232153Smm#endif
1219232153Smm			flag |= SCONV_NORMALIZATION_C;
1220232153Smm	}
1221238856Smm#if defined(__APPLE__)
1222238856Smm	/*
1223238856Smm	 * In case writing an archive file, make sure that a filename
1224238856Smm	 * going to be passed to iconv is a Unicode NFC string since
1225238856Smm	 * a filename in HFS Plus filesystem is a Unicode NFD one and
1226238856Smm	 * iconv cannot handle it with "UTF-8" charset. It is simpler
1227238856Smm	 * than a use of "UTF-8-MAC" charset.
1228238856Smm	 */
1229238856Smm	if ((flag & SCONV_TO_CHARSET) &&
1230238856Smm	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1231238856Smm	    !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1232238856Smm		flag |= SCONV_NORMALIZATION_C;
1233238856Smm	/*
1234238856Smm	 * In case reading an archive file. make sure that a filename
1235238856Smm	 * will be passed to users is a Unicode NFD string in order to
1236238856Smm	 * correctly compare the filename with other one which comes
1237238856Smm	 * from HFS Plus filesystem.
1238238856Smm	 */
1239238856Smm	if ((flag & SCONV_FROM_CHARSET) &&
1240238856Smm	   !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1241238856Smm	    (flag & SCONV_TO_UTF8))
1242238856Smm		flag |= SCONV_NORMALIZATION_D;
1243238856Smm#endif
1244232153Smm
1245232153Smm#if defined(HAVE_ICONV)
1246232153Smm	sc->cd_w = (iconv_t)-1;
1247232153Smm	/*
1248232153Smm	 * Create an iconv object.
1249232153Smm	 */
1250232153Smm	if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
1251232153Smm	    (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
1252232153Smm	    (flag & SCONV_WIN_CP)) {
1253232153Smm		/* This case we won't use iconv. */
1254232153Smm		sc->cd = (iconv_t)-1;
1255232153Smm	} else {
1256232153Smm		sc->cd = iconv_open(tc, fc);
1257232153Smm		if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
1258232153Smm			/*
1259313570Smm			 * Unfortunately, all of iconv implements do support
1260232153Smm			 * "CP932" character-set, so we should use "SJIS"
1261232153Smm			 * instead if iconv_open failed.
1262232153Smm			 */
1263232153Smm			if (strcmp(tc, "CP932") == 0)
1264232153Smm				sc->cd = iconv_open("SJIS", fc);
1265232153Smm			else if (strcmp(fc, "CP932") == 0)
1266232153Smm				sc->cd = iconv_open(tc, "SJIS");
1267232153Smm		}
1268232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1269232153Smm		/*
1270232153Smm		 * archive_mstring on Windows directly convert multi-bytes
1271232153Smm		 * into archive_wstring in order not to depend on locale
1272313570Smm		 * so that you can do a I18N programming. This will be
1273232153Smm		 * used only in archive_mstring_copy_mbs_len_l so far.
1274232153Smm		 */
1275232153Smm		if (flag & SCONV_FROM_CHARSET) {
1276232153Smm			sc->cd_w = iconv_open("UTF-8", fc);
1277232153Smm			if (sc->cd_w == (iconv_t)-1 &&
1278232153Smm			    (sc->flag & SCONV_BEST_EFFORT)) {
1279232153Smm				if (strcmp(fc, "CP932") == 0)
1280232153Smm					sc->cd_w = iconv_open("UTF-8", "SJIS");
1281232153Smm			}
1282232153Smm		}
1283232153Smm#endif /* _WIN32 && !__CYGWIN__ */
1284232153Smm	}
1285232153Smm#endif	/* HAVE_ICONV */
1286232153Smm
1287232153Smm	sc->flag = flag;
1288232153Smm
1289232153Smm	/*
1290238856Smm	 * Set up converters.
1291232153Smm	 */
1292232153Smm	setup_converter(sc);
1293232153Smm
1294232153Smm	return (sc);
1295232153Smm}
1296232153Smm
1297232153Smm/*
1298232153Smm * Free a string conversion object.
1299232153Smm */
1300232153Smmstatic void
1301232153Smmfree_sconv_object(struct archive_string_conv *sc)
1302232153Smm{
1303232153Smm	free(sc->from_charset);
1304232153Smm	free(sc->to_charset);
1305232153Smm	archive_string_free(&sc->utftmp);
1306232153Smm#if HAVE_ICONV
1307232153Smm	if (sc->cd != (iconv_t)-1)
1308232153Smm		iconv_close(sc->cd);
1309232153Smm	if (sc->cd_w != (iconv_t)-1)
1310232153Smm		iconv_close(sc->cd_w);
1311232153Smm#endif
1312232153Smm	free(sc);
1313232153Smm}
1314232153Smm
1315232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1316232153Smmstatic unsigned
1317232153Smmmy_atoi(const char *p)
1318232153Smm{
1319232153Smm	unsigned cp;
1320232153Smm
1321232153Smm	cp = 0;
1322232153Smm	while (*p) {
1323232153Smm		if (*p >= '0' && *p <= '9')
1324232153Smm			cp = cp * 10 + (*p - '0');
1325232153Smm		else
1326232153Smm			return (-1);
1327232153Smm		p++;
1328232153Smm	}
1329232153Smm	return (cp);
1330232153Smm}
1331232153Smm
1332232153Smm/*
1333232153Smm * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
1334232153Smm * Return -1 if failed.
1335232153Smm *
1336232153Smm * Note: This translation code may be insufficient.
1337232153Smm */
1338232153Smmstatic struct charset {
1339232153Smm	const char *name;
1340232153Smm	unsigned cp;
1341232153Smm} charsets[] = {
1342232153Smm	/* MUST BE SORTED! */
1343232153Smm	{"ASCII", 1252},
1344232153Smm	{"ASMO-708", 708},
1345232153Smm	{"BIG5", 950},
1346232153Smm	{"CHINESE", 936},
1347232153Smm	{"CP367", 1252},
1348232153Smm	{"CP819", 1252},
1349232153Smm	{"CP1025", 21025},
1350232153Smm	{"DOS-720", 720},
1351232153Smm	{"DOS-862", 862},
1352232153Smm	{"EUC-CN", 51936},
1353232153Smm	{"EUC-JP", 51932},
1354232153Smm	{"EUC-KR", 949},
1355232153Smm	{"EUCCN", 51936},
1356232153Smm	{"EUCJP", 51932},
1357232153Smm	{"EUCKR", 949},
1358232153Smm	{"GB18030", 54936},
1359232153Smm	{"GB2312", 936},
1360232153Smm	{"HEBREW", 1255},
1361232153Smm	{"HZ-GB-2312", 52936},
1362232153Smm	{"IBM273", 20273},
1363232153Smm	{"IBM277", 20277},
1364232153Smm	{"IBM278", 20278},
1365232153Smm	{"IBM280", 20280},
1366232153Smm	{"IBM284", 20284},
1367232153Smm	{"IBM285", 20285},
1368232153Smm	{"IBM290", 20290},
1369232153Smm	{"IBM297", 20297},
1370232153Smm	{"IBM367", 1252},
1371232153Smm	{"IBM420", 20420},
1372232153Smm	{"IBM423", 20423},
1373232153Smm	{"IBM424", 20424},
1374232153Smm	{"IBM819", 1252},
1375232153Smm	{"IBM871", 20871},
1376232153Smm	{"IBM880", 20880},
1377232153Smm	{"IBM905", 20905},
1378232153Smm	{"IBM924", 20924},
1379232153Smm	{"ISO-8859-1", 28591},
1380232153Smm	{"ISO-8859-13", 28603},
1381232153Smm	{"ISO-8859-15", 28605},
1382232153Smm	{"ISO-8859-2", 28592},
1383232153Smm	{"ISO-8859-3", 28593},
1384232153Smm	{"ISO-8859-4", 28594},
1385232153Smm	{"ISO-8859-5", 28595},
1386232153Smm	{"ISO-8859-6", 28596},
1387232153Smm	{"ISO-8859-7", 28597},
1388232153Smm	{"ISO-8859-8", 28598},
1389232153Smm	{"ISO-8859-9", 28599},
1390232153Smm	{"ISO8859-1", 28591},
1391232153Smm	{"ISO8859-13", 28603},
1392232153Smm	{"ISO8859-15", 28605},
1393232153Smm	{"ISO8859-2", 28592},
1394232153Smm	{"ISO8859-3", 28593},
1395232153Smm	{"ISO8859-4", 28594},
1396232153Smm	{"ISO8859-5", 28595},
1397232153Smm	{"ISO8859-6", 28596},
1398232153Smm	{"ISO8859-7", 28597},
1399232153Smm	{"ISO8859-8", 28598},
1400232153Smm	{"ISO8859-9", 28599},
1401232153Smm	{"JOHAB", 1361},
1402232153Smm	{"KOI8-R", 20866},
1403232153Smm	{"KOI8-U", 21866},
1404232153Smm	{"KS_C_5601-1987", 949},
1405232153Smm	{"LATIN1", 1252},
1406232153Smm	{"LATIN2", 28592},
1407232153Smm	{"MACINTOSH", 10000},
1408232153Smm	{"SHIFT-JIS", 932},
1409232153Smm	{"SHIFT_JIS", 932},
1410232153Smm	{"SJIS", 932},
1411232153Smm	{"US", 1252},
1412232153Smm	{"US-ASCII", 1252},
1413232153Smm	{"UTF-16", 1200},
1414232153Smm	{"UTF-16BE", 1201},
1415232153Smm	{"UTF-16LE", 1200},
1416232153Smm	{"UTF-8", CP_UTF8},
1417232153Smm	{"X-EUROPA", 29001},
1418232153Smm	{"X-MAC-ARABIC", 10004},
1419232153Smm	{"X-MAC-CE", 10029},
1420232153Smm	{"X-MAC-CHINESEIMP", 10008},
1421232153Smm	{"X-MAC-CHINESETRAD", 10002},
1422232153Smm	{"X-MAC-CROATIAN", 10082},
1423232153Smm	{"X-MAC-CYRILLIC", 10007},
1424232153Smm	{"X-MAC-GREEK", 10006},
1425232153Smm	{"X-MAC-HEBREW", 10005},
1426232153Smm	{"X-MAC-ICELANDIC", 10079},
1427232153Smm	{"X-MAC-JAPANESE", 10001},
1428232153Smm	{"X-MAC-KOREAN", 10003},
1429232153Smm	{"X-MAC-ROMANIAN", 10010},
1430232153Smm	{"X-MAC-THAI", 10021},
1431232153Smm	{"X-MAC-TURKISH", 10081},
1432232153Smm	{"X-MAC-UKRAINIAN", 10017},
1433232153Smm};
1434232153Smmstatic unsigned
1435232153Smmmake_codepage_from_charset(const char *charset)
1436232153Smm{
1437232153Smm	char cs[16];
1438232153Smm	char *p;
1439232153Smm	unsigned cp;
1440232153Smm	int a, b;
1441232153Smm
1442232153Smm	if (charset == NULL || strlen(charset) > 15)
1443232153Smm		return -1;
1444232153Smm
1445232153Smm	/* Copy name to uppercase. */
1446232153Smm	p = cs;
1447232153Smm	while (*charset) {
1448232153Smm		char c = *charset++;
1449232153Smm		if (c >= 'a' && c <= 'z')
1450232153Smm			c -= 'a' - 'A';
1451232153Smm		*p++ = c;
1452232153Smm	}
1453232153Smm	*p++ = '\0';
1454232153Smm	cp = -1;
1455232153Smm
1456232153Smm	/* Look it up in the table first, so that we can easily
1457232153Smm	 * override CP367, which we map to 1252 instead of 367. */
1458232153Smm	a = 0;
1459232153Smm	b = sizeof(charsets)/sizeof(charsets[0]);
1460232153Smm	while (b > a) {
1461232153Smm		int c = (b + a) / 2;
1462232153Smm		int r = strcmp(charsets[c].name, cs);
1463232153Smm		if (r < 0)
1464232153Smm			a = c + 1;
1465232153Smm		else if (r > 0)
1466232153Smm			b = c;
1467232153Smm		else
1468232153Smm			return charsets[c].cp;
1469232153Smm	}
1470232153Smm
1471232153Smm	/* If it's not in the table, try to parse it. */
1472232153Smm	switch (*cs) {
1473232153Smm	case 'C':
1474232153Smm		if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
1475232153Smm			cp = my_atoi(cs + 2);
1476232153Smm		} else if (strcmp(cs, "CP_ACP") == 0)
1477232153Smm			cp = get_current_codepage();
1478232153Smm		else if (strcmp(cs, "CP_OEMCP") == 0)
1479232153Smm			cp = get_current_oemcp();
1480232153Smm		break;
1481232153Smm	case 'I':
1482232153Smm		if (cs[1] == 'B' && cs[2] == 'M' &&
1483232153Smm		    cs[3] >= '0' && cs[3] <= '9') {
1484232153Smm			cp = my_atoi(cs + 3);
1485232153Smm		}
1486232153Smm		break;
1487232153Smm	case 'W':
1488232153Smm		if (strncmp(cs, "WINDOWS-", 8) == 0) {
1489232153Smm			cp = my_atoi(cs + 8);
1490232153Smm			if (cp != 874 && (cp < 1250 || cp > 1258))
1491232153Smm				cp = -1;/* This may invalid code. */
1492232153Smm		}
1493232153Smm		break;
1494232153Smm	}
1495232153Smm	return (cp);
1496232153Smm}
1497232153Smm
1498232153Smm/*
1499232153Smm * Return ANSI Code Page of current locale set by setlocale().
1500232153Smm */
1501232153Smmstatic unsigned
1502232153Smmget_current_codepage(void)
1503232153Smm{
1504232153Smm	char *locale, *p;
1505232153Smm	unsigned cp;
1506232153Smm
1507232153Smm	locale = setlocale(LC_CTYPE, NULL);
1508232153Smm	if (locale == NULL)
1509232153Smm		return (GetACP());
1510232153Smm	if (locale[0] == 'C' && locale[1] == '\0')
1511232153Smm		return (CP_C_LOCALE);
1512232153Smm	p = strrchr(locale, '.');
1513232153Smm	if (p == NULL)
1514232153Smm		return (GetACP());
1515232153Smm	cp = my_atoi(p+1);
1516232153Smm	if (cp <= 0)
1517232153Smm		return (GetACP());
1518232153Smm	return (cp);
1519232153Smm}
1520232153Smm
1521232153Smm/*
1522232153Smm * Translation table between Locale Name and ACP/OEMCP.
1523232153Smm */
1524232153Smmstatic struct {
1525232153Smm	unsigned acp;
1526232153Smm	unsigned ocp;
1527232153Smm	const char *locale;
1528232153Smm} acp_ocp_map[] = {
1529232153Smm	{  950,  950, "Chinese_Taiwan" },
1530232153Smm	{  936,  936, "Chinese_People's Republic of China" },
1531232153Smm	{  950,  950, "Chinese_Taiwan" },
1532232153Smm	{ 1250,  852, "Czech_Czech Republic" },
1533232153Smm	{ 1252,  850, "Danish_Denmark" },
1534232153Smm	{ 1252,  850, "Dutch_Netherlands" },
1535232153Smm	{ 1252,  850, "Dutch_Belgium" },
1536232153Smm	{ 1252,  437, "English_United States" },
1537232153Smm	{ 1252,  850, "English_Australia" },
1538232153Smm	{ 1252,  850, "English_Canada" },
1539232153Smm	{ 1252,  850, "English_New Zealand" },
1540232153Smm	{ 1252,  850, "English_United Kingdom" },
1541232153Smm	{ 1252,  437, "English_United States" },
1542232153Smm	{ 1252,  850, "Finnish_Finland" },
1543232153Smm	{ 1252,  850, "French_France" },
1544232153Smm	{ 1252,  850, "French_Belgium" },
1545232153Smm	{ 1252,  850, "French_Canada" },
1546232153Smm	{ 1252,  850, "French_Switzerland" },
1547232153Smm	{ 1252,  850, "German_Germany" },
1548232153Smm	{ 1252,  850, "German_Austria" },
1549232153Smm	{ 1252,  850, "German_Switzerland" },
1550232153Smm	{ 1253,  737, "Greek_Greece" },
1551232153Smm	{ 1250,  852, "Hungarian_Hungary" },
1552232153Smm	{ 1252,  850, "Icelandic_Iceland" },
1553232153Smm	{ 1252,  850, "Italian_Italy" },
1554232153Smm	{ 1252,  850, "Italian_Switzerland" },
1555232153Smm	{  932,  932, "Japanese_Japan" },
1556232153Smm	{  949,  949, "Korean_Korea" },
1557232153Smm	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
1558232153Smm	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
1559232153Smm	{ 1252,  850, "Norwegian-Nynorsk_Norway" },
1560232153Smm	{ 1250,  852, "Polish_Poland" },
1561232153Smm	{ 1252,  850, "Portuguese_Portugal" },
1562232153Smm	{ 1252,  850, "Portuguese_Brazil" },
1563232153Smm	{ 1251,  866, "Russian_Russia" },
1564232153Smm	{ 1250,  852, "Slovak_Slovakia" },
1565232153Smm	{ 1252,  850, "Spanish_Spain" },
1566232153Smm	{ 1252,  850, "Spanish_Mexico" },
1567232153Smm	{ 1252,  850, "Spanish_Spain" },
1568232153Smm	{ 1252,  850, "Swedish_Sweden" },
1569232153Smm	{ 1254,  857, "Turkish_Turkey" },
1570232153Smm	{ 0, 0, NULL}
1571232153Smm};
1572232153Smm
1573232153Smm/*
1574232153Smm * Return OEM Code Page of current locale set by setlocale().
1575232153Smm */
1576232153Smmstatic unsigned
1577232153Smmget_current_oemcp(void)
1578232153Smm{
1579232153Smm	int i;
1580232153Smm	char *locale, *p;
1581232153Smm	size_t len;
1582232153Smm
1583232153Smm	locale = setlocale(LC_CTYPE, NULL);
1584232153Smm	if (locale == NULL)
1585232153Smm		return (GetOEMCP());
1586232153Smm	if (locale[0] == 'C' && locale[1] == '\0')
1587232153Smm		return (CP_C_LOCALE);
1588232153Smm
1589232153Smm	p = strrchr(locale, '.');
1590232153Smm	if (p == NULL)
1591232153Smm		return (GetOEMCP());
1592232153Smm	len = p - locale;
1593232153Smm	for (i = 0; acp_ocp_map[i].acp; i++) {
1594232153Smm		if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
1595232153Smm			return (acp_ocp_map[i].ocp);
1596232153Smm	}
1597232153Smm	return (GetOEMCP());
1598232153Smm}
1599232153Smm#else
1600232153Smm
1601232153Smm/*
1602232153Smm * POSIX platform does not use CodePage.
1603232153Smm */
1604232153Smm
1605232153Smmstatic unsigned
1606232153Smmget_current_codepage(void)
1607232153Smm{
1608232153Smm	return (-1);/* Unknown */
1609232153Smm}
1610232153Smmstatic unsigned
1611232153Smmmake_codepage_from_charset(const char *charset)
1612232153Smm{
1613232153Smm	(void)charset; /* UNUSED */
1614232153Smm	return (-1);/* Unknown */
1615232153Smm}
1616232153Smmstatic unsigned
1617232153Smmget_current_oemcp(void)
1618232153Smm{
1619232153Smm	return (-1);/* Unknown */
1620232153Smm}
1621232153Smm
1622232153Smm#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1623232153Smm
1624232153Smm/*
1625232153Smm * Return a string conversion object.
1626232153Smm */
1627232153Smmstatic struct archive_string_conv *
1628232153Smmget_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
1629232153Smm{
1630232153Smm	struct archive_string_conv *sc;
1631232153Smm	unsigned current_codepage;
1632232153Smm
1633232153Smm	/* Check if we have made the sconv object. */
1634232153Smm	sc = find_sconv_object(a, fc, tc);
1635232153Smm	if (sc != NULL)
1636232153Smm		return (sc);
1637232153Smm
1638232153Smm	if (a == NULL)
1639232153Smm		current_codepage = get_current_codepage();
1640232153Smm	else
1641232153Smm		current_codepage = a->current_codepage;
1642232153Smm
1643232153Smm	sc = create_sconv_object(canonical_charset_name(fc),
1644232153Smm	    canonical_charset_name(tc), current_codepage, flag);
1645232153Smm	if (sc == NULL) {
1646232153Smm		if (a != NULL)
1647232153Smm			archive_set_error(a, ENOMEM,
1648232153Smm			    "Could not allocate memory for "
1649232153Smm			    "a string conversion object");
1650232153Smm		return (NULL);
1651232153Smm	}
1652232153Smm
1653232153Smm	/*
1654232153Smm	 * If there is no converter for current string conversion object,
1655232153Smm	 * we cannot handle this conversion.
1656232153Smm	 */
1657232153Smm	if (sc->nconverter == 0) {
1658232153Smm		if (a != NULL) {
1659232153Smm#if HAVE_ICONV
1660232153Smm			archive_set_error(a, ARCHIVE_ERRNO_MISC,
1661232153Smm			    "iconv_open failed : Cannot handle ``%s''",
1662232153Smm			    (flag & SCONV_TO_CHARSET)?tc:fc);
1663232153Smm#else
1664232153Smm			archive_set_error(a, ARCHIVE_ERRNO_MISC,
1665232153Smm			    "A character-set conversion not fully supported "
1666232153Smm			    "on this platform");
1667232153Smm#endif
1668232153Smm		}
1669232153Smm		/* Failed; free a sconv object. */
1670232153Smm		free_sconv_object(sc);
1671232153Smm		return (NULL);
1672232153Smm	}
1673232153Smm
1674232153Smm	/*
1675232153Smm	 * Success!
1676232153Smm	 */
1677232153Smm	if (a != NULL)
1678232153Smm		add_sconv_object(a, sc);
1679232153Smm	return (sc);
1680232153Smm}
1681232153Smm
1682232153Smmstatic const char *
1683232153Smmget_current_charset(struct archive *a)
1684232153Smm{
1685232153Smm	const char *cur_charset;
1686232153Smm
1687232153Smm	if (a == NULL)
1688232153Smm		cur_charset = default_iconv_charset("");
1689232153Smm	else {
1690232153Smm		cur_charset = default_iconv_charset(a->current_code);
1691232153Smm		if (a->current_code == NULL) {
1692232153Smm			a->current_code = strdup(cur_charset);
1693232153Smm			a->current_codepage = get_current_codepage();
1694232153Smm			a->current_oemcp = get_current_oemcp();
1695232153Smm		}
1696232153Smm	}
1697232153Smm	return (cur_charset);
1698232153Smm}
1699232153Smm
1700232153Smm/*
1701232153Smm * Make and Return a string conversion object.
1702232153Smm * Return NULL if the platform does not support the specified conversion
1703232153Smm * and best_effort is 0.
1704232153Smm * If best_effort is set, A string conversion object must be returned
1705232153Smm * unless memory allocation for the object fails, but the conversion
1706232153Smm * might fail when non-ASCII code is found.
1707232153Smm */
1708232153Smmstruct archive_string_conv *
1709232153Smmarchive_string_conversion_to_charset(struct archive *a, const char *charset,
1710232153Smm    int best_effort)
1711232153Smm{
1712232153Smm	int flag = SCONV_TO_CHARSET;
1713232153Smm
1714232153Smm	if (best_effort)
1715232153Smm		flag |= SCONV_BEST_EFFORT;
1716232153Smm	return (get_sconv_object(a, get_current_charset(a), charset, flag));
1717232153Smm}
1718232153Smm
1719232153Smmstruct archive_string_conv *
1720232153Smmarchive_string_conversion_from_charset(struct archive *a, const char *charset,
1721232153Smm    int best_effort)
1722232153Smm{
1723232153Smm	int flag = SCONV_FROM_CHARSET;
1724232153Smm
1725232153Smm	if (best_effort)
1726232153Smm		flag |= SCONV_BEST_EFFORT;
1727232153Smm	return (get_sconv_object(a, charset, get_current_charset(a), flag));
1728232153Smm}
1729232153Smm
1730232153Smm/*
1731232153Smm * archive_string_default_conversion_*_archive() are provided for Windows
1732232153Smm * platform because other archiver application use CP_OEMCP for
1733232153Smm * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
1734232153Smm * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
1735232153Smm * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
1736232153Smm * So we should make a string conversion between CP_ACP and CP_OEMCP
1737313570Smm * for compatibility.
1738232153Smm */
1739232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1740232153Smmstruct archive_string_conv *
1741232153Smmarchive_string_default_conversion_for_read(struct archive *a)
1742232153Smm{
1743232153Smm	const char *cur_charset = get_current_charset(a);
1744232153Smm	char oemcp[16];
1745232153Smm
1746232153Smm	/* NOTE: a check of cur_charset is unneeded but we need
1747232153Smm	 * that get_current_charset() has been surely called at
1748232153Smm	 * this time whatever C compiler optimized. */
1749232153Smm	if (cur_charset != NULL &&
1750232153Smm	    (a->current_codepage == CP_C_LOCALE ||
1751232153Smm	     a->current_codepage == a->current_oemcp))
1752232153Smm		return (NULL);/* no conversion. */
1753232153Smm
1754232153Smm	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1755232153Smm	/* Make sure a null termination must be set. */
1756232153Smm	oemcp[sizeof(oemcp)-1] = '\0';
1757232153Smm	return (get_sconv_object(a, oemcp, cur_charset,
1758232153Smm	    SCONV_FROM_CHARSET));
1759232153Smm}
1760232153Smm
1761232153Smmstruct archive_string_conv *
1762232153Smmarchive_string_default_conversion_for_write(struct archive *a)
1763232153Smm{
1764232153Smm	const char *cur_charset = get_current_charset(a);
1765232153Smm	char oemcp[16];
1766232153Smm
1767232153Smm	/* NOTE: a check of cur_charset is unneeded but we need
1768232153Smm	 * that get_current_charset() has been surely called at
1769232153Smm	 * this time whatever C compiler optimized. */
1770232153Smm	if (cur_charset != NULL &&
1771232153Smm	    (a->current_codepage == CP_C_LOCALE ||
1772232153Smm	     a->current_codepage == a->current_oemcp))
1773232153Smm		return (NULL);/* no conversion. */
1774232153Smm
1775232153Smm	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1776232153Smm	/* Make sure a null termination must be set. */
1777232153Smm	oemcp[sizeof(oemcp)-1] = '\0';
1778232153Smm	return (get_sconv_object(a, cur_charset, oemcp,
1779232153Smm	    SCONV_TO_CHARSET));
1780232153Smm}
1781232153Smm#else
1782232153Smmstruct archive_string_conv *
1783232153Smmarchive_string_default_conversion_for_read(struct archive *a)
1784232153Smm{
1785232153Smm	(void)a; /* UNUSED */
1786232153Smm	return (NULL);
1787232153Smm}
1788232153Smm
1789232153Smmstruct archive_string_conv *
1790232153Smmarchive_string_default_conversion_for_write(struct archive *a)
1791232153Smm{
1792232153Smm	(void)a; /* UNUSED */
1793232153Smm	return (NULL);
1794232153Smm}
1795232153Smm#endif
1796232153Smm
1797232153Smm/*
1798232153Smm * Dispose of all character conversion objects in the archive object.
1799232153Smm */
1800232153Smmvoid
1801232153Smmarchive_string_conversion_free(struct archive *a)
1802232153Smm{
1803232153Smm	struct archive_string_conv *sc;
1804232153Smm	struct archive_string_conv *sc_next;
1805232153Smm
1806232153Smm	for (sc = a->sconv; sc != NULL; sc = sc_next) {
1807232153Smm		sc_next = sc->next;
1808232153Smm		free_sconv_object(sc);
1809232153Smm	}
1810232153Smm	a->sconv = NULL;
1811232153Smm	free(a->current_code);
1812232153Smm	a->current_code = NULL;
1813232153Smm}
1814232153Smm
1815232153Smm/*
1816232153Smm * Return a conversion charset name.
1817232153Smm */
1818232153Smmconst char *
1819232153Smmarchive_string_conversion_charset_name(struct archive_string_conv *sc)
1820232153Smm{
1821232153Smm	if (sc->flag & SCONV_TO_CHARSET)
1822232153Smm		return (sc->to_charset);
1823232153Smm	else
1824232153Smm		return (sc->from_charset);
1825232153Smm}
1826232153Smm
1827232153Smm/*
1828232153Smm * Change the behavior of a string conversion.
1829232153Smm */
1830232153Smmvoid
1831232153Smmarchive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
1832232153Smm{
1833232153Smm	switch (opt) {
1834232153Smm	/*
1835232153Smm	 * A filename in UTF-8 was made with libarchive 2.x in a wrong
1836232153Smm	 * assumption that wchar_t was Unicode.
1837232153Smm	 * This option enables simulating the assumption in order to read
1838311041Smm	 * that filename correctly.
1839232153Smm	 */
1840232153Smm	case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
1841232153Smm#if (defined(_WIN32) && !defined(__CYGWIN__)) \
1842232153Smm	 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
1843232153Smm		/*
1844232153Smm		 * Nothing to do for it since wchar_t on these platforms
1845232153Smm		 * is really Unicode.
1846232153Smm		 */
1847232153Smm		(void)sc; /* UNUSED */
1848232153Smm#else
1849232153Smm		if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
1850232153Smm			sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
1851238856Smm			/* Set up string converters. */
1852232153Smm			setup_converter(sc);
1853232153Smm		}
1854232153Smm#endif
1855232153Smm		break;
1856238856Smm	case SCONV_SET_OPT_NORMALIZATION_C:
1857238856Smm		if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
1858238856Smm			sc->flag |= SCONV_NORMALIZATION_C;
1859238856Smm			sc->flag &= ~SCONV_NORMALIZATION_D;
1860238856Smm			/* Set up string converters. */
1861238856Smm			setup_converter(sc);
1862238856Smm		}
1863238856Smm		break;
1864238856Smm	case SCONV_SET_OPT_NORMALIZATION_D:
1865238856Smm#if defined(HAVE_ICONV)
1866238856Smm		/*
1867238856Smm		 * If iconv will take the string, do not change the
1868238856Smm		 * setting of the normalization.
1869238856Smm		 */
1870238856Smm		if (!(sc->flag & SCONV_WIN_CP) &&
1871238856Smm		     (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1872238856Smm		    !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1873238856Smm			break;
1874238856Smm#endif
1875238856Smm		if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
1876238856Smm			sc->flag |= SCONV_NORMALIZATION_D;
1877238856Smm			sc->flag &= ~SCONV_NORMALIZATION_C;
1878238856Smm			/* Set up string converters. */
1879238856Smm			setup_converter(sc);
1880238856Smm		}
1881238856Smm		break;
1882232153Smm	default:
1883232153Smm		break;
1884232153Smm	}
1885232153Smm}
1886232153Smm
1887232153Smm/*
1888232153Smm *
1889232153Smm * Copy one archive_string to another in locale conversion.
1890232153Smm *
1891238856Smm *	archive_strncat_l();
1892238856Smm *	archive_strncpy_l();
1893232153Smm *
1894232153Smm */
1895232153Smm
1896232153Smmstatic size_t
1897232153Smmmbsnbytes(const void *_p, size_t n)
1898232153Smm{
1899232153Smm	size_t s;
1900232153Smm	const char *p, *pp;
1901232153Smm
1902232153Smm	if (_p == NULL)
1903232153Smm		return (0);
1904232153Smm	p = (const char *)_p;
1905232153Smm
1906232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
1907232153Smm	s = 0;
1908232153Smm	pp = p;
1909232153Smm	while (s < n && *pp) {
1910232153Smm		pp++;
1911232153Smm		s++;
1912232153Smm	}
1913232153Smm	return (s);
1914232153Smm}
1915232153Smm
1916232153Smmstatic size_t
1917232153Smmutf16nbytes(const void *_p, size_t n)
1918232153Smm{
1919232153Smm	size_t s;
1920232153Smm	const char *p, *pp;
1921232153Smm
1922232153Smm	if (_p == NULL)
1923232153Smm		return (0);
1924232153Smm	p = (const char *)_p;
1925232153Smm
1926232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
1927232153Smm	s = 0;
1928232153Smm	pp = p;
1929232153Smm	n >>= 1;
1930232153Smm	while (s < n && (pp[0] || pp[1])) {
1931232153Smm		pp += 2;
1932232153Smm		s++;
1933232153Smm	}
1934232153Smm	return (s<<1);
1935232153Smm}
1936232153Smm
1937232153Smmint
1938238856Smmarchive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
1939232153Smm    struct archive_string_conv *sc)
1940232153Smm{
1941232153Smm	as->length = 0;
1942238856Smm	return (archive_strncat_l(as, _p, n, sc));
1943232153Smm}
1944232153Smm
1945232153Smmint
1946238856Smmarchive_strncat_l(struct archive_string *as, const void *_p, size_t n,
1947232153Smm    struct archive_string_conv *sc)
1948232153Smm{
1949232153Smm	const void *s;
1950311041Smm	size_t length = 0;
1951232153Smm	int i, r = 0, r2;
1952232153Smm
1953311041Smm	if (_p != NULL && n > 0) {
1954311041Smm		if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
1955311041Smm			length = utf16nbytes(_p, n);
1956311041Smm		else
1957311041Smm			length = mbsnbytes(_p, n);
1958311041Smm	}
1959311041Smm
1960232153Smm	/* We must allocate memory even if there is no data for conversion
1961232153Smm	 * or copy. This simulates archive_string_append behavior. */
1962311041Smm	if (length == 0) {
1963232153Smm		int tn = 1;
1964232153Smm		if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
1965232153Smm			tn = 2;
1966232153Smm		if (archive_string_ensure(as, as->length + tn) == NULL)
1967232153Smm			return (-1);
1968232153Smm		as->s[as->length] = 0;
1969232153Smm		if (tn == 2)
1970232153Smm			as->s[as->length+1] = 0;
1971232153Smm		return (0);
1972232153Smm	}
1973232153Smm
1974232153Smm	/*
1975232153Smm	 * If sc is NULL, we just make a copy.
1976232153Smm	 */
1977232153Smm	if (sc == NULL) {
1978232153Smm		if (archive_string_append(as, _p, length) == NULL)
1979232153Smm			return (-1);/* No memory */
1980232153Smm		return (0);
1981232153Smm	}
1982232153Smm
1983232153Smm	s = _p;
1984232153Smm	i = 0;
1985232153Smm	if (sc->nconverter > 1) {
1986232153Smm		sc->utftmp.length = 0;
1987232153Smm		r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
1988232153Smm		if (r2 != 0 && errno == ENOMEM)
1989232153Smm			return (r2);
1990232153Smm		if (r > r2)
1991232153Smm			r = r2;
1992232153Smm		s = sc->utftmp.s;
1993232153Smm		length = sc->utftmp.length;
1994232153Smm		++i;
1995232153Smm	}
1996232153Smm	r2 = sc->converter[i](as, s, length, sc);
1997232153Smm	if (r > r2)
1998232153Smm		r = r2;
1999232153Smm	return (r);
2000232153Smm}
2001232153Smm
2002232153Smm#if HAVE_ICONV
2003232153Smm
2004232153Smm/*
2005311041Smm * Return -1 if conversion fails.
2006232153Smm */
2007232153Smmstatic int
2008232153Smmiconv_strncat_in_locale(struct archive_string *as, const void *_p,
2009232153Smm    size_t length, struct archive_string_conv *sc)
2010232153Smm{
2011248616Smm	ICONV_CONST char *itp;
2012232153Smm	size_t remaining;
2013232153Smm	iconv_t cd;
2014232153Smm	char *outp;
2015232153Smm	size_t avail, bs;
2016232153Smm	int return_value = 0; /* success */
2017232153Smm	int to_size, from_size;
2018232153Smm
2019232153Smm	if (sc->flag & SCONV_TO_UTF16)
2020232153Smm		to_size = 2;
2021232153Smm	else
2022232153Smm		to_size = 1;
2023232153Smm	if (sc->flag & SCONV_FROM_UTF16)
2024232153Smm		from_size = 2;
2025232153Smm	else
2026232153Smm		from_size = 1;
2027232153Smm
2028232153Smm	if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2029232153Smm		return (-1);
2030232153Smm
2031232153Smm	cd = sc->cd;
2032248616Smm	itp = (char *)(uintptr_t)_p;
2033232153Smm	remaining = length;
2034232153Smm	outp = as->s + as->length;
2035232153Smm	avail = as->buffer_length - as->length - to_size;
2036232153Smm	while (remaining >= (size_t)from_size) {
2037248616Smm		size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
2038232153Smm
2039232153Smm		if (result != (size_t)-1)
2040232153Smm			break; /* Conversion completed. */
2041232153Smm
2042232153Smm		if (errno == EILSEQ || errno == EINVAL) {
2043232153Smm			/*
2044232153Smm		 	 * If an output charset is UTF-8 or UTF-16BE/LE,
2045232153Smm			 * unknown character should be U+FFFD
2046232153Smm			 * (replacement character).
2047232153Smm			 */
2048232153Smm			if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2049232153Smm				size_t rbytes;
2050232153Smm				if (sc->flag & SCONV_TO_UTF8)
2051299529Smm					rbytes = sizeof(utf8_replacement_char);
2052232153Smm				else
2053232153Smm					rbytes = 2;
2054232153Smm
2055232153Smm				if (avail < rbytes) {
2056232153Smm					as->length = outp - as->s;
2057232153Smm					bs = as->buffer_length +
2058232153Smm					    (remaining * to_size) + rbytes;
2059232153Smm					if (NULL ==
2060232153Smm					    archive_string_ensure(as, bs))
2061232153Smm						return (-1);
2062232153Smm					outp = as->s + as->length;
2063232153Smm					avail = as->buffer_length
2064232153Smm					    - as->length - to_size;
2065232153Smm				}
2066232153Smm				if (sc->flag & SCONV_TO_UTF8)
2067299529Smm					memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
2068232153Smm				else if (sc->flag & SCONV_TO_UTF16BE)
2069232153Smm					archive_be16enc(outp, UNICODE_R_CHAR);
2070232153Smm				else
2071232153Smm					archive_le16enc(outp, UNICODE_R_CHAR);
2072232153Smm				outp += rbytes;
2073232153Smm				avail -= rbytes;
2074232153Smm			} else {
2075232153Smm				/* Skip the illegal input bytes. */
2076232153Smm				*outp++ = '?';
2077232153Smm				avail--;
2078232153Smm			}
2079248616Smm			itp += from_size;
2080232153Smm			remaining -= from_size;
2081232153Smm			return_value = -1; /* failure */
2082228753Smm		} else {
2083232153Smm			/* E2BIG no output buffer,
2084232153Smm			 * Increase an output buffer.  */
2085232153Smm			as->length = outp - as->s;
2086232153Smm			bs = as->buffer_length + remaining * 2;
2087232153Smm			if (NULL == archive_string_ensure(as, bs))
2088232153Smm				return (-1);
2089232153Smm			outp = as->s + as->length;
2090232153Smm			avail = as->buffer_length - as->length - to_size;
2091228753Smm		}
2092228753Smm	}
2093232153Smm	as->length = outp - as->s;
2094232153Smm	as->s[as->length] = 0;
2095232153Smm	if (to_size == 2)
2096232153Smm		as->s[as->length+1] = 0;
2097232153Smm	return (return_value);
2098228753Smm}
2099228753Smm
2100232153Smm#endif /* HAVE_ICONV */
2101232153Smm
2102232153Smm
2103232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2104232153Smm
2105232153Smm/*
2106232153Smm * Translate a string from a some CodePage to an another CodePage by
2107311041Smm * Windows APIs, and copy the result. Return -1 if conversion fails.
2108232153Smm */
2109228753Smmstatic int
2110232153Smmstrncat_in_codepage(struct archive_string *as,
2111232153Smm    const void *_p, size_t length, struct archive_string_conv *sc)
2112228753Smm{
2113232153Smm	const char *s = (const char *)_p;
2114232153Smm	struct archive_wstring aws;
2115232153Smm	size_t l;
2116232153Smm	int r, saved_flag;
2117228753Smm
2118232153Smm	archive_string_init(&aws);
2119232153Smm	saved_flag = sc->flag;
2120232153Smm	sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2121232153Smm	r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2122232153Smm	sc->flag = saved_flag;
2123232153Smm	if (r != 0) {
2124232153Smm		archive_wstring_free(&aws);
2125232153Smm		if (errno != ENOMEM)
2126232153Smm			archive_string_append(as, s, length);
2127232153Smm		return (-1);
2128232153Smm	}
2129232153Smm
2130232153Smm	l = as->length;
2131232153Smm	r = archive_string_append_from_wcs_in_codepage(
2132232153Smm	    as, aws.s, aws.length, sc);
2133232153Smm	if (r != 0 && errno != ENOMEM && l == as->length)
2134232153Smm		archive_string_append(as, s, length);
2135232153Smm	archive_wstring_free(&aws);
2136232153Smm	return (r);
2137232153Smm}
2138232153Smm
2139232153Smm/*
2140232153Smm * Test whether MBS ==> WCS is okay.
2141232153Smm */
2142232153Smmstatic int
2143232153Smminvalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2144232153Smm{
2145232153Smm	const char *p = (const char *)_p;
2146232153Smm	unsigned codepage;
2147232153Smm	DWORD mbflag = MB_ERR_INVALID_CHARS;
2148232153Smm
2149232153Smm	if (sc->flag & SCONV_FROM_CHARSET)
2150232153Smm		codepage = sc->to_cp;
2151232153Smm	else
2152232153Smm		codepage = sc->from_cp;
2153232153Smm
2154232153Smm	if (codepage == CP_C_LOCALE)
2155232153Smm		return (0);
2156232153Smm	if (codepage != CP_UTF8)
2157232153Smm		mbflag |= MB_PRECOMPOSED;
2158232153Smm
2159248616Smm	if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
2160232153Smm		return (-1); /* Invalid */
2161232153Smm	return (0); /* Okay */
2162232153Smm}
2163232153Smm
2164232153Smm#else
2165232153Smm
2166232153Smm/*
2167232153Smm * Test whether MBS ==> WCS is okay.
2168232153Smm */
2169232153Smmstatic int
2170232153Smminvalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2171232153Smm{
2172232153Smm	const char *p = (const char *)_p;
2173232153Smm	size_t r;
2174232153Smm
2175232153Smm#if HAVE_MBRTOWC
2176232153Smm	mbstate_t shift_state;
2177232153Smm
2178232153Smm	memset(&shift_state, 0, sizeof(shift_state));
2179232153Smm#else
2180232153Smm	/* Clear the shift state before starting. */
2181232153Smm	mbtowc(NULL, NULL, 0);
2182232153Smm#endif
2183232153Smm	while (n) {
2184232153Smm		wchar_t wc;
2185232153Smm
2186232153Smm#if HAVE_MBRTOWC
2187232153Smm		r = mbrtowc(&wc, p, n, &shift_state);
2188232153Smm#else
2189232153Smm		r = mbtowc(&wc, p, n);
2190232153Smm#endif
2191232153Smm		if (r == (size_t)-1 || r == (size_t)-2)
2192232153Smm			return (-1);/* Invalid. */
2193232153Smm		if (r == 0)
2194232153Smm			break;
2195232153Smm		p += r;
2196232153Smm		n -= r;
2197232153Smm	}
2198238856Smm	(void)sc; /* UNUSED */
2199232153Smm	return (0); /* All Okey. */
2200232153Smm}
2201232153Smm
2202232153Smm#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2203232153Smm
2204232153Smm/*
2205232153Smm * Basically returns -1 because we cannot make a conversion of charset
2206232153Smm * without iconv but in some cases this would return 0.
2207232153Smm * Returns 0 if all copied characters are ASCII.
2208232153Smm * Returns 0 if both from-locale and to-locale are the same and those
2209232153Smm * can be WCS with no error.
2210232153Smm */
2211232153Smmstatic int
2212232153Smmbest_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2213232153Smm    size_t length, struct archive_string_conv *sc)
2214232153Smm{
2215232153Smm	size_t remaining;
2216248616Smm	const uint8_t *itp;
2217232153Smm	int return_value = 0; /* success */
2218232153Smm
2219232153Smm	/*
2220232153Smm	 * If both from-locale and to-locale is the same, this makes a copy.
2221232153Smm	 * And then this checks all copied MBS can be WCS if so returns 0.
2222232153Smm	 */
2223232153Smm	if (sc->same) {
2224232153Smm		if (archive_string_append(as, _p, length) == NULL)
2225232153Smm			return (-1);/* No memory */
2226232153Smm		return (invalid_mbs(_p, length, sc));
2227232153Smm	}
2228232153Smm
2229232153Smm	/*
2230232153Smm	 * If a character is ASCII, this just copies it. If not, this
2231313570Smm	 * assigns '?' character instead but in UTF-8 locale this assigns
2232232153Smm	 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2233232153Smm	 * a Replacement Character in Unicode.
2234232153Smm	 */
2235232153Smm
2236232153Smm	remaining = length;
2237248616Smm	itp = (const uint8_t *)_p;
2238248616Smm	while (*itp && remaining > 0) {
2239299529Smm		if (*itp > 127) {
2240299529Smm			// Non-ASCII: Substitute with suitable replacement
2241299529Smm			if (sc->flag & SCONV_TO_UTF8) {
2242299529Smm				if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
2243299529Smm					__archive_errx(1, "Out of memory");
2244299529Smm				}
2245299529Smm			} else {
2246299529Smm				archive_strappend_char(as, '?');
2247232153Smm			}
2248232153Smm			return_value = -1;
2249232153Smm		} else {
2250299529Smm			archive_strappend_char(as, *itp);
2251232153Smm		}
2252299529Smm		++itp;
2253232153Smm	}
2254232153Smm	return (return_value);
2255232153Smm}
2256232153Smm
2257232153Smm
2258232153Smm/*
2259232153Smm * Unicode conversion functions.
2260232153Smm *   - UTF-8 <===> UTF-8 in removing surrogate pairs.
2261232153Smm *   - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2262232153Smm *   - UTF-8 made by libarchive 2.x ===> UTF-8.
2263232153Smm *   - UTF-16BE <===> UTF-8.
2264232153Smm *
2265232153Smm */
2266232153Smm
2267232153Smm/*
2268232153Smm * Utility to convert a single UTF-8 sequence.
2269232153Smm *
2270232153Smm * Usually return used bytes, return used byte in negative value when
2271232153Smm * a unicode character is replaced with U+FFFD.
2272232153Smm * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2273232153Smm * Recommended Practice for Replacement Characters.
2274232153Smm */
2275232153Smmstatic int
2276232153Smm_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2277232153Smm{
2278232153Smm	static const char utf8_count[256] = {
2279232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2280232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2281232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2282232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2283232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2284232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2285232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2286232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2287232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2288232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2289232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2290232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2291232153Smm		 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2292232153Smm		 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2293232153Smm		 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2294232153Smm		 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2295232153Smm	};
2296232153Smm	int ch, i;
2297232153Smm	int cnt;
2298232153Smm	uint32_t wc;
2299232153Smm
2300232153Smm	/* Sanity check. */
2301232153Smm	if (n == 0)
2302232153Smm		return (0);
2303232153Smm	/*
2304228753Smm	 * Decode 1-4 bytes depending on the value of the first byte.
2305228753Smm	 */
2306232153Smm	ch = (unsigned char)*s;
2307232153Smm	if (ch == 0)
2308228753Smm		return (0); /* Standard:  return 0 for end-of-string. */
2309232153Smm	cnt = utf8_count[ch];
2310232153Smm
2311311041Smm	/* Invalid sequence or there are not plenty bytes. */
2312232153Smm	if ((int)n < cnt) {
2313248616Smm		cnt = (int)n;
2314232153Smm		for (i = 1; i < cnt; i++) {
2315232153Smm			if ((s[i] & 0xc0) != 0x80) {
2316232153Smm				cnt = i;
2317232153Smm				break;
2318232153Smm			}
2319232153Smm		}
2320232153Smm		goto invalid_sequence;
2321228753Smm	}
2322232153Smm
2323232153Smm	/* Make a Unicode code point from a single UTF-8 sequence. */
2324232153Smm	switch (cnt) {
2325232153Smm	case 1:	/* 1 byte sequence. */
2326232153Smm		*pwc = ch & 0x7f;
2327232153Smm		return (cnt);
2328232153Smm	case 2:	/* 2 bytes sequence. */
2329232153Smm		if ((s[1] & 0xc0) != 0x80) {
2330232153Smm			cnt = 1;
2331232153Smm			goto invalid_sequence;
2332232153Smm		}
2333232153Smm		*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2334232153Smm		return (cnt);
2335232153Smm	case 3:	/* 3 bytes sequence. */
2336232153Smm		if ((s[1] & 0xc0) != 0x80) {
2337232153Smm			cnt = 1;
2338232153Smm			goto invalid_sequence;
2339232153Smm		}
2340232153Smm		if ((s[2] & 0xc0) != 0x80) {
2341232153Smm			cnt = 2;
2342232153Smm			goto invalid_sequence;
2343232153Smm		}
2344232153Smm		wc = ((ch & 0x0f) << 12)
2345228753Smm		    | ((s[1] & 0x3f) << 6)
2346228753Smm		    | (s[2] & 0x3f);
2347232153Smm		if (wc < 0x800)
2348232153Smm			goto invalid_sequence;/* Overlong sequence. */
2349232153Smm		break;
2350232153Smm	case 4:	/* 4 bytes sequence. */
2351232153Smm		if ((s[1] & 0xc0) != 0x80) {
2352232153Smm			cnt = 1;
2353232153Smm			goto invalid_sequence;
2354232153Smm		}
2355232153Smm		if ((s[2] & 0xc0) != 0x80) {
2356232153Smm			cnt = 2;
2357232153Smm			goto invalid_sequence;
2358232153Smm		}
2359232153Smm		if ((s[3] & 0xc0) != 0x80) {
2360232153Smm			cnt = 3;
2361232153Smm			goto invalid_sequence;
2362232153Smm		}
2363232153Smm		wc = ((ch & 0x07) << 18)
2364228753Smm		    | ((s[1] & 0x3f) << 12)
2365228753Smm		    | ((s[2] & 0x3f) << 6)
2366228753Smm		    | (s[3] & 0x3f);
2367232153Smm		if (wc < 0x10000)
2368232153Smm			goto invalid_sequence;/* Overlong sequence. */
2369232153Smm		break;
2370232153Smm	default: /* Others are all invalid sequence. */
2371232153Smm		if (ch == 0xc0 || ch == 0xc1)
2372232153Smm			cnt = 2;
2373232153Smm		else if (ch >= 0xf5 && ch <= 0xf7)
2374232153Smm			cnt = 4;
2375232153Smm		else if (ch >= 0xf8 && ch <= 0xfb)
2376232153Smm			cnt = 5;
2377232153Smm		else if (ch == 0xfc || ch == 0xfd)
2378232153Smm			cnt = 6;
2379232153Smm		else
2380232153Smm			cnt = 1;
2381232153Smm		if ((int)n < cnt)
2382248616Smm			cnt = (int)n;
2383232153Smm		for (i = 1; i < cnt; i++) {
2384232153Smm			if ((s[i] & 0xc0) != 0x80) {
2385232153Smm				cnt = i;
2386232153Smm				break;
2387232153Smm			}
2388232153Smm		}
2389232153Smm		goto invalid_sequence;
2390232153Smm	}
2391232153Smm
2392311041Smm	/* The code point larger than 0x10FFFF is not legal
2393232153Smm	 * Unicode values. */
2394232153Smm	if (wc > UNICODE_MAX)
2395232153Smm		goto invalid_sequence;
2396232153Smm	/* Correctly gets a Unicode, returns used bytes. */
2397232153Smm	*pwc = wc;
2398232153Smm	return (cnt);
2399232153Smminvalid_sequence:
2400232153Smm	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2401232153Smm	return (cnt * -1);
2402232153Smm}
2403232153Smm
2404232153Smmstatic int
2405232153Smmutf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2406232153Smm{
2407232153Smm	int cnt;
2408232153Smm
2409232153Smm	cnt = _utf8_to_unicode(pwc, s, n);
2410311041Smm	/* Any of Surrogate pair is not legal Unicode values. */
2411232153Smm	if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2412232153Smm		return (-3);
2413232153Smm	return (cnt);
2414232153Smm}
2415232153Smm
2416232153Smmstatic inline uint32_t
2417232153Smmcombine_surrogate_pair(uint32_t uc, uint32_t uc2)
2418232153Smm{
2419232153Smm	uc -= 0xD800;
2420232153Smm	uc *= 0x400;
2421232153Smm	uc += uc2 - 0xDC00;
2422232153Smm	uc += 0x10000;
2423232153Smm	return (uc);
2424232153Smm}
2425232153Smm
2426232153Smm/*
2427232153Smm * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2428232153Smm * removing surrogate pairs.
2429232153Smm *
2430232153Smm * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2431232153Smm *
2432232153Smm * Usually return used bytes, return used byte in negative value when
2433232153Smm * a unicode character is replaced with U+FFFD.
2434232153Smm */
2435232153Smmstatic int
2436232153Smmcesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2437232153Smm{
2438248616Smm	uint32_t wc = 0;
2439232153Smm	int cnt;
2440232153Smm
2441232153Smm	cnt = _utf8_to_unicode(&wc, s, n);
2442232153Smm	if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2443248616Smm		uint32_t wc2 = 0;
2444232153Smm		if (n - 3 < 3) {
2445232153Smm			/* Invalid byte sequence. */
2446232153Smm			goto invalid_sequence;
2447232153Smm		}
2448232153Smm		cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2449232153Smm		if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2450232153Smm			/* Invalid byte sequence. */
2451232153Smm			goto invalid_sequence;
2452232153Smm		}
2453232153Smm		wc = combine_surrogate_pair(wc, wc2);
2454232153Smm		cnt = 6;
2455232153Smm	} else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2456232153Smm		/* Invalid byte sequence. */
2457232153Smm		goto invalid_sequence;
2458232153Smm	}
2459232153Smm	*pwc = wc;
2460232153Smm	return (cnt);
2461232153Smminvalid_sequence:
2462232153Smm	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2463232153Smm	if (cnt > 0)
2464232153Smm		cnt *= -1;
2465232153Smm	return (cnt);
2466232153Smm}
2467232153Smm
2468232153Smm/*
2469232153Smm * Convert a Unicode code point to a single UTF-8 sequence.
2470232153Smm *
2471311041Smm * NOTE:This function does not check if the Unicode is legal or not.
2472232153Smm * Please you definitely check it before calling this.
2473232153Smm */
2474232153Smmstatic size_t
2475232153Smmunicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2476232153Smm{
2477232153Smm	char *_p = p;
2478232153Smm
2479299529Smm	/* Invalid Unicode char maps to Replacement character */
2480299529Smm	if (uc > UNICODE_MAX)
2481299529Smm		uc = UNICODE_R_CHAR;
2482232153Smm	/* Translate code point to UTF8 */
2483232153Smm	if (uc <= 0x7f) {
2484232153Smm		if (remaining == 0)
2485232153Smm			return (0);
2486232153Smm		*p++ = (char)uc;
2487232153Smm	} else if (uc <= 0x7ff) {
2488232153Smm		if (remaining < 2)
2489232153Smm			return (0);
2490232153Smm		*p++ = 0xc0 | ((uc >> 6) & 0x1f);
2491232153Smm		*p++ = 0x80 | (uc & 0x3f);
2492232153Smm	} else if (uc <= 0xffff) {
2493232153Smm		if (remaining < 3)
2494232153Smm			return (0);
2495232153Smm		*p++ = 0xe0 | ((uc >> 12) & 0x0f);
2496232153Smm		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2497232153Smm		*p++ = 0x80 | (uc & 0x3f);
2498299529Smm	} else {
2499232153Smm		if (remaining < 4)
2500232153Smm			return (0);
2501232153Smm		*p++ = 0xf0 | ((uc >> 18) & 0x07);
2502232153Smm		*p++ = 0x80 | ((uc >> 12) & 0x3f);
2503232153Smm		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2504232153Smm		*p++ = 0x80 | (uc & 0x3f);
2505232153Smm	}
2506232153Smm	return (p - _p);
2507232153Smm}
2508232153Smm
2509232153Smmstatic int
2510232153Smmutf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2511232153Smm{
2512232153Smm	return (utf16_to_unicode(pwc, s, n, 1));
2513232153Smm}
2514232153Smm
2515232153Smmstatic int
2516232153Smmutf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2517232153Smm{
2518232153Smm	return (utf16_to_unicode(pwc, s, n, 0));
2519232153Smm}
2520232153Smm
2521232153Smmstatic int
2522232153Smmutf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2523232153Smm{
2524232153Smm	const char *utf16 = s;
2525232153Smm	unsigned uc;
2526232153Smm
2527232153Smm	if (n == 0)
2528232153Smm		return (0);
2529232153Smm	if (n == 1) {
2530232153Smm		/* set the Replacement Character instead. */
2531232153Smm		*pwc = UNICODE_R_CHAR;
2532232153Smm		return (-1);
2533232153Smm	}
2534232153Smm
2535232153Smm	if (be)
2536232153Smm		uc = archive_be16dec(utf16);
2537232153Smm	else
2538232153Smm		uc = archive_le16dec(utf16);
2539232153Smm	utf16 += 2;
2540232153Smm
2541232153Smm	/* If this is a surrogate pair, assemble the full code point.*/
2542232153Smm	if (IS_HIGH_SURROGATE_LA(uc)) {
2543232153Smm		unsigned uc2;
2544232153Smm
2545232153Smm		if (n >= 4) {
2546232153Smm			if (be)
2547232153Smm				uc2 = archive_be16dec(utf16);
2548232153Smm			else
2549232153Smm				uc2 = archive_le16dec(utf16);
2550232153Smm		} else
2551232153Smm			uc2 = 0;
2552232153Smm		if (IS_LOW_SURROGATE_LA(uc2)) {
2553232153Smm			uc = combine_surrogate_pair(uc, uc2);
2554232153Smm			utf16 += 2;
2555232153Smm		} else {
2556232153Smm	 		/* Undescribed code point should be U+FFFD
2557232153Smm		 	* (replacement character). */
2558232153Smm			*pwc = UNICODE_R_CHAR;
2559232153Smm			return (-2);
2560232153Smm		}
2561232153Smm	}
2562232153Smm
2563232153Smm	/*
2564232153Smm	 * Surrogate pair values(0xd800 through 0xdfff) are only
2565313570Smm	 * used by UTF-16, so, after above calculation, the code
2566232153Smm	 * must not be surrogate values, and Unicode has no codes
2567311041Smm	 * larger than 0x10ffff. Thus, those are not legal Unicode
2568232153Smm	 * values.
2569232153Smm	 */
2570232153Smm	if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2571232153Smm	 	/* Undescribed code point should be U+FFFD
2572232153Smm	 	* (replacement character). */
2573232153Smm		*pwc = UNICODE_R_CHAR;
2574232153Smm		return (((int)(utf16 - s)) * -1);
2575232153Smm	}
2576232153Smm	*pwc = uc;
2577232153Smm	return ((int)(utf16 - s));
2578232153Smm}
2579232153Smm
2580232153Smmstatic size_t
2581232153Smmunicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2582232153Smm{
2583232153Smm	char *utf16 = p;
2584232153Smm
2585232153Smm	if (uc > 0xffff) {
2586232153Smm		/* We have a code point that won't fit into a
2587232153Smm		 * wchar_t; convert it to a surrogate pair. */
2588232153Smm		if (remaining < 4)
2589232153Smm			return (0);
2590232153Smm		uc -= 0x10000;
2591232153Smm		archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2592232153Smm		archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2593228753Smm		return (4);
2594232153Smm	} else {
2595232153Smm		if (remaining < 2)
2596232153Smm			return (0);
2597232153Smm		archive_be16enc(utf16, uc);
2598232153Smm		return (2);
2599232153Smm	}
2600228753Smm}
2601228753Smm
2602232153Smmstatic size_t
2603232153Smmunicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2604232153Smm{
2605232153Smm	char *utf16 = p;
2606232153Smm
2607232153Smm	if (uc > 0xffff) {
2608232153Smm		/* We have a code point that won't fit into a
2609232153Smm		 * wchar_t; convert it to a surrogate pair. */
2610232153Smm		if (remaining < 4)
2611232153Smm			return (0);
2612232153Smm		uc -= 0x10000;
2613232153Smm		archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2614232153Smm		archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2615232153Smm		return (4);
2616232153Smm	} else {
2617232153Smm		if (remaining < 2)
2618232153Smm			return (0);
2619232153Smm		archive_le16enc(utf16, uc);
2620232153Smm		return (2);
2621232153Smm	}
2622232153Smm}
2623232153Smm
2624228753Smm/*
2625232153Smm * Copy UTF-8 string in checking surrogate pair.
2626232153Smm * If any surrogate pair are found, it would be canonicalized.
2627228753Smm */
2628232153Smmstatic int
2629238856Smmstrncat_from_utf8_to_utf8(struct archive_string *as, const void *_p,
2630238856Smm    size_t len, struct archive_string_conv *sc)
2631228753Smm{
2632232153Smm	const char *s;
2633232153Smm	char *p, *endp;
2634232153Smm	int n, ret = 0;
2635228753Smm
2636232153Smm	(void)sc; /* UNUSED */
2637232153Smm
2638232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
2639232153Smm		return (-1);
2640232153Smm
2641232153Smm	s = (const char *)_p;
2642232153Smm	p = as->s + as->length;
2643232153Smm	endp = as->s + as->buffer_length -1;
2644232153Smm	do {
2645232153Smm		uint32_t uc;
2646232153Smm		const char *ss = s;
2647232153Smm		size_t w;
2648232153Smm
2649232153Smm		/*
2650232153Smm		 * Forward byte sequence until a conversion of that is needed.
2651232153Smm		 */
2652232153Smm		while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
2653232153Smm			s += n;
2654232153Smm			len -= n;
2655232153Smm		}
2656232153Smm		if (ss < s) {
2657232153Smm			if (p + (s - ss) > endp) {
2658232153Smm				as->length = p - as->s;
2659232153Smm				if (archive_string_ensure(as,
2660232153Smm				    as->buffer_length + len + 1) == NULL)
2661232153Smm					return (-1);
2662232153Smm				p = as->s + as->length;
2663232153Smm				endp = as->s + as->buffer_length -1;
2664232153Smm			}
2665232153Smm
2666232153Smm			memcpy(p, ss, s - ss);
2667232153Smm			p += s - ss;
2668232153Smm		}
2669232153Smm
2670232153Smm		/*
2671232153Smm		 * If n is negative, current byte sequence needs a replacement.
2672232153Smm		 */
2673228753Smm		if (n < 0) {
2674232153Smm			if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2675232153Smm				/* Current byte sequence may be CESU-8. */
2676232153Smm				n = cesu8_to_unicode(&uc, s, len);
2677232153Smm			}
2678228753Smm			if (n < 0) {
2679232153Smm				ret = -1;
2680232153Smm				n *= -1;/* Use a replaced unicode character. */
2681228753Smm			}
2682232153Smm
2683232153Smm			/* Rebuild UTF-8 byte sequence. */
2684232153Smm			while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
2685232153Smm				as->length = p - as->s;
2686232153Smm				if (archive_string_ensure(as,
2687232153Smm				    as->buffer_length + len + 1) == NULL)
2688232153Smm					return (-1);
2689232153Smm				p = as->s + as->length;
2690232153Smm				endp = as->s + as->buffer_length -1;
2691228753Smm			}
2692232153Smm			p += w;
2693232153Smm			s += n;
2694232153Smm			len -= n;
2695228753Smm		}
2696232153Smm	} while (n > 0);
2697232153Smm	as->length = p - as->s;
2698232153Smm	as->s[as->length] = '\0';
2699232153Smm	return (ret);
2700232153Smm}
2701232153Smm
2702232153Smmstatic int
2703232153Smmarchive_string_append_unicode(struct archive_string *as, const void *_p,
2704232153Smm    size_t len, struct archive_string_conv *sc)
2705232153Smm{
2706232153Smm	const char *s;
2707232153Smm	char *p, *endp;
2708232153Smm	uint32_t uc;
2709232153Smm	size_t w;
2710232153Smm	int n, ret = 0, ts, tm;
2711232153Smm	int (*parse)(uint32_t *, const char *, size_t);
2712232153Smm	size_t (*unparse)(char *, size_t, uint32_t);
2713232153Smm
2714232153Smm	if (sc->flag & SCONV_TO_UTF16BE) {
2715232153Smm		unparse = unicode_to_utf16be;
2716232153Smm		ts = 2;
2717232153Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
2718232153Smm		unparse = unicode_to_utf16le;
2719232153Smm		ts = 2;
2720232153Smm	} else if (sc->flag & SCONV_TO_UTF8) {
2721232153Smm		unparse = unicode_to_utf8;
2722232153Smm		ts = 1;
2723232153Smm	} else {
2724232153Smm		/*
2725232153Smm		 * This case is going to be converted to another
2726232153Smm		 * character-set through iconv.
2727232153Smm		 */
2728232153Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
2729232153Smm			unparse = unicode_to_utf16be;
2730232153Smm			ts = 2;
2731232153Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
2732232153Smm			unparse = unicode_to_utf16le;
2733232153Smm			ts = 2;
2734232153Smm		} else {
2735232153Smm			unparse = unicode_to_utf8;
2736232153Smm			ts = 1;
2737232153Smm		}
2738228753Smm	}
2739232153Smm
2740232153Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
2741232153Smm		parse = utf16be_to_unicode;
2742232153Smm		tm = 1;
2743232153Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
2744232153Smm		parse = utf16le_to_unicode;
2745232153Smm		tm = 1;
2746232153Smm	} else {
2747232153Smm		parse = cesu8_to_unicode;
2748232153Smm		tm = ts;
2749232153Smm	}
2750232153Smm
2751232153Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2752232153Smm		return (-1);
2753232153Smm
2754232153Smm	s = (const char *)_p;
2755232153Smm	p = as->s + as->length;
2756232153Smm	endp = as->s + as->buffer_length - ts;
2757232153Smm	while ((n = parse(&uc, s, len)) != 0) {
2758232153Smm		if (n < 0) {
2759232153Smm			/* Use a replaced unicode character. */
2760232153Smm			n *= -1;
2761232153Smm			ret = -1;
2762232153Smm		}
2763232153Smm		s += n;
2764232153Smm		len -= n;
2765232153Smm		while ((w = unparse(p, endp - p, uc)) == 0) {
2766232153Smm			/* There is not enough output buffer so
2767232153Smm			 * we have to expand it. */
2768232153Smm			as->length = p - as->s;
2769232153Smm			if (archive_string_ensure(as,
2770232153Smm			    as->buffer_length + len * tm + ts) == NULL)
2771232153Smm				return (-1);
2772232153Smm			p = as->s + as->length;
2773232153Smm			endp = as->s + as->buffer_length - ts;
2774232153Smm		}
2775232153Smm		p += w;
2776232153Smm	}
2777232153Smm	as->length = p - as->s;
2778232153Smm	as->s[as->length] = '\0';
2779232153Smm	if (ts == 2)
2780232153Smm		as->s[as->length+1] = '\0';
2781232153Smm	return (ret);
2782228753Smm}
2783228753Smm
2784232153Smm/*
2785232153Smm * Following Constants for Hangul compositions this information comes from
2786232153Smm * Unicode Standard Annex #15  http://unicode.org/reports/tr15/
2787232153Smm */
2788232153Smm#define HC_SBASE	0xAC00
2789232153Smm#define HC_LBASE	0x1100
2790232153Smm#define HC_VBASE	0x1161
2791232153Smm#define HC_TBASE	0x11A7
2792232153Smm#define HC_LCOUNT	19
2793232153Smm#define HC_VCOUNT	21
2794232153Smm#define HC_TCOUNT	28
2795232153Smm#define HC_NCOUNT	(HC_VCOUNT * HC_TCOUNT)
2796232153Smm#define HC_SCOUNT	(HC_LCOUNT * HC_NCOUNT)
2797228753Smm
2798232153Smmstatic uint32_t
2799232153Smmget_nfc(uint32_t uc, uint32_t uc2)
2800232153Smm{
2801232153Smm	int t, b;
2802232153Smm
2803232153Smm	t = 0;
2804232153Smm	b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2805232153Smm	while (b >= t) {
2806232153Smm		int m = (t + b) / 2;
2807232153Smm		if (u_composition_table[m].cp1 < uc)
2808232153Smm			t = m + 1;
2809232153Smm		else if (u_composition_table[m].cp1 > uc)
2810232153Smm			b = m - 1;
2811232153Smm		else if (u_composition_table[m].cp2 < uc2)
2812232153Smm			t = m + 1;
2813232153Smm		else if (u_composition_table[m].cp2 > uc2)
2814232153Smm			b = m - 1;
2815232153Smm		else
2816232153Smm			return (u_composition_table[m].nfc);
2817232153Smm	}
2818232153Smm	return (0);
2819232153Smm}
2820232153Smm
2821232153Smm#define FDC_MAX 10	/* The maximum number of Following Decomposable
2822232153Smm			 * Characters. */
2823232153Smm
2824228753Smm/*
2825232153Smm * Update first code point.
2826232153Smm */
2827232153Smm#define UPDATE_UC(new_uc)	do {		\
2828232153Smm	uc = new_uc;				\
2829232153Smm	ucptr = NULL;				\
2830232153Smm} while (0)
2831232153Smm
2832232153Smm/*
2833232153Smm * Replace first code point with second code point.
2834232153Smm */
2835232153Smm#define REPLACE_UC_WITH_UC2() do {		\
2836232153Smm	uc = uc2;				\
2837232153Smm	ucptr = uc2ptr;				\
2838232153Smm	n = n2;					\
2839232153Smm} while (0)
2840232153Smm
2841232153Smm#define EXPAND_BUFFER() do {			\
2842232153Smm	as->length = p - as->s;			\
2843232153Smm	if (archive_string_ensure(as,		\
2844232153Smm	    as->buffer_length + len * tm + ts) == NULL)\
2845232153Smm		return (-1);			\
2846232153Smm	p = as->s + as->length;			\
2847232153Smm	endp = as->s + as->buffer_length - ts;	\
2848232153Smm} while (0)
2849232153Smm
2850232153Smm#define UNPARSE(p, endp, uc)	do {		\
2851232153Smm	while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
2852232153Smm		EXPAND_BUFFER();		\
2853232153Smm	}					\
2854232153Smm	p += w;					\
2855232153Smm} while (0)
2856232153Smm
2857232153Smm/*
2858232153Smm * Write first code point.
2859232153Smm * If the code point has not be changed from its original code,
2860232153Smm * this just copies it from its original buffer pointer.
2861232153Smm * If not, this converts it to UTF-8 byte sequence and copies it.
2862232153Smm */
2863232153Smm#define WRITE_UC()	do {			\
2864232153Smm	if (ucptr) {				\
2865232153Smm		if (p + n > endp)		\
2866232153Smm			EXPAND_BUFFER();	\
2867232153Smm		switch (n) {			\
2868232153Smm		case 4:				\
2869232153Smm			*p++ = *ucptr++;	\
2870232153Smm			/* FALL THROUGH */	\
2871232153Smm		case 3:				\
2872232153Smm			*p++ = *ucptr++;	\
2873232153Smm			/* FALL THROUGH */	\
2874232153Smm		case 2:				\
2875232153Smm			*p++ = *ucptr++;	\
2876232153Smm			/* FALL THROUGH */	\
2877232153Smm		case 1:				\
2878232153Smm			*p++ = *ucptr;		\
2879232153Smm			break;			\
2880232153Smm		}				\
2881232153Smm		ucptr = NULL;			\
2882232153Smm	} else {				\
2883232153Smm		UNPARSE(p, endp, uc);		\
2884232153Smm	}					\
2885232153Smm} while (0)
2886232153Smm
2887232153Smm/*
2888232153Smm * Collect following decomposable code points.
2889232153Smm */
2890232153Smm#define COLLECT_CPS(start)	do {		\
2891232153Smm	int _i;					\
2892232153Smm	for (_i = start; _i < FDC_MAX ; _i++) {	\
2893232153Smm		nx = parse(&ucx[_i], s, len);	\
2894232153Smm		if (nx <= 0)			\
2895232153Smm			break;			\
2896232153Smm		cx = CCC(ucx[_i]);		\
2897232153Smm		if (cl >= cx && cl != 228 && cx != 228)\
2898232153Smm			break;			\
2899232153Smm		s += nx;			\
2900232153Smm		len -= nx;			\
2901232153Smm		cl = cx;			\
2902232153Smm		ccx[_i] = cx;			\
2903232153Smm	}					\
2904232153Smm	if (_i >= FDC_MAX) {			\
2905232153Smm		ret = -1;			\
2906232153Smm		ucx_size = FDC_MAX;		\
2907232153Smm	} else					\
2908232153Smm		ucx_size = _i;			\
2909232153Smm} while (0)
2910232153Smm
2911232153Smm/*
2912232153Smm * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
2913228753Smm *
2914313570Smm * TODO: Convert composition exclusions, which are never converted
2915232153Smm * from NFC,NFD,NFKC and NFKD, to Form C.
2916228753Smm */
2917232153Smmstatic int
2918232153Smmarchive_string_normalize_C(struct archive_string *as, const void *_p,
2919232153Smm    size_t len, struct archive_string_conv *sc)
2920228753Smm{
2921232153Smm	const char *s = (const char *)_p;
2922232153Smm	char *p, *endp;
2923232153Smm	uint32_t uc, uc2;
2924232153Smm	size_t w;
2925232153Smm	int always_replace, n, n2, ret = 0, spair, ts, tm;
2926232153Smm	int (*parse)(uint32_t *, const char *, size_t);
2927232153Smm	size_t (*unparse)(char *, size_t, uint32_t);
2928228753Smm
2929232153Smm	always_replace = 1;
2930232153Smm	ts = 1;/* text size. */
2931232153Smm	if (sc->flag & SCONV_TO_UTF16BE) {
2932232153Smm		unparse = unicode_to_utf16be;
2933232153Smm		ts = 2;
2934232153Smm		if (sc->flag & SCONV_FROM_UTF16BE)
2935232153Smm			always_replace = 0;
2936232153Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
2937232153Smm		unparse = unicode_to_utf16le;
2938232153Smm		ts = 2;
2939232153Smm		if (sc->flag & SCONV_FROM_UTF16LE)
2940232153Smm			always_replace = 0;
2941232153Smm	} else if (sc->flag & SCONV_TO_UTF8) {
2942232153Smm		unparse = unicode_to_utf8;
2943232153Smm		if (sc->flag & SCONV_FROM_UTF8)
2944232153Smm			always_replace = 0;
2945232153Smm	} else {
2946232153Smm		/*
2947232153Smm		 * This case is going to be converted to another
2948232153Smm		 * character-set through iconv.
2949232153Smm		 */
2950232153Smm		always_replace = 0;
2951232153Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
2952232153Smm			unparse = unicode_to_utf16be;
2953232153Smm			ts = 2;
2954232153Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
2955232153Smm			unparse = unicode_to_utf16le;
2956232153Smm			ts = 2;
2957232153Smm		} else {
2958232153Smm			unparse = unicode_to_utf8;
2959232153Smm		}
2960232153Smm	}
2961232153Smm
2962232153Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
2963232153Smm		parse = utf16be_to_unicode;
2964232153Smm		tm = 1;
2965232153Smm		spair = 4;/* surrogate pair size in UTF-16. */
2966232153Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
2967232153Smm		parse = utf16le_to_unicode;
2968232153Smm		tm = 1;
2969232153Smm		spair = 4;/* surrogate pair size in UTF-16. */
2970232153Smm	} else {
2971232153Smm		parse = cesu8_to_unicode;
2972232153Smm		tm = ts;
2973232153Smm		spair = 6;/* surrogate pair size in UTF-8. */
2974232153Smm	}
2975232153Smm
2976232153Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2977232153Smm		return (-1);
2978232153Smm
2979232153Smm	p = as->s + as->length;
2980232153Smm	endp = as->s + as->buffer_length - ts;
2981232153Smm	while ((n = parse(&uc, s, len)) != 0) {
2982232153Smm		const char *ucptr, *uc2ptr;
2983232153Smm
2984232153Smm		if (n < 0) {
2985232153Smm			/* Use a replaced unicode character. */
2986232153Smm			UNPARSE(p, endp, uc);
2987232153Smm			s += n*-1;
2988232153Smm			len -= n*-1;
2989232153Smm			ret = -1;
2990232153Smm			continue;
2991232153Smm		} else if (n == spair || always_replace)
2992232153Smm			/* uc is converted from a surrogate pair.
2993232153Smm			 * this should be treated as a changed code. */
2994232153Smm			ucptr = NULL;
2995232153Smm		else
2996232153Smm			ucptr = s;
2997232153Smm		s += n;
2998232153Smm		len -= n;
2999232153Smm
3000232153Smm		/* Read second code point. */
3001232153Smm		while ((n2 = parse(&uc2, s, len)) > 0) {
3002232153Smm			uint32_t ucx[FDC_MAX];
3003232153Smm			int ccx[FDC_MAX];
3004232153Smm			int cl, cx, i, nx, ucx_size;
3005232153Smm			int LIndex,SIndex;
3006232153Smm			uint32_t nfc;
3007232153Smm
3008232153Smm			if (n2 == spair || always_replace)
3009232153Smm				/* uc2 is converted from a surrogate pair.
3010232153Smm			 	 * this should be treated as a changed code. */
3011232153Smm				uc2ptr = NULL;
3012232153Smm			else
3013232153Smm				uc2ptr = s;
3014232153Smm			s += n2;
3015232153Smm			len -= n2;
3016232153Smm
3017232153Smm			/*
3018232153Smm			 * If current second code point is out of decomposable
3019232153Smm			 * code points, finding compositions is unneeded.
3020232153Smm			 */
3021232153Smm			if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3022232153Smm				WRITE_UC();
3023232153Smm				REPLACE_UC_WITH_UC2();
3024232153Smm				continue;
3025232153Smm			}
3026232153Smm
3027232153Smm			/*
3028232153Smm			 * Try to combine current code points.
3029232153Smm			 */
3030232153Smm			/*
3031232153Smm			 * We have to combine Hangul characters according to
3032232153Smm			 * http://uniicode.org/reports/tr15/#Hangul
3033232153Smm			 */
3034232153Smm			if (0 <= (LIndex = uc - HC_LBASE) &&
3035232153Smm			    LIndex < HC_LCOUNT) {
3036232153Smm				/*
3037232153Smm				 * Hangul Composition.
3038232153Smm				 * 1. Two current code points are L and V.
3039232153Smm				 */
3040232153Smm				int VIndex = uc2 - HC_VBASE;
3041232153Smm				if (0 <= VIndex && VIndex < HC_VCOUNT) {
3042232153Smm					/* Make syllable of form LV. */
3043232153Smm					UPDATE_UC(HC_SBASE +
3044232153Smm					    (LIndex * HC_VCOUNT + VIndex) *
3045232153Smm					     HC_TCOUNT);
3046232153Smm				} else {
3047232153Smm					WRITE_UC();
3048232153Smm					REPLACE_UC_WITH_UC2();
3049232153Smm				}
3050232153Smm				continue;
3051232153Smm			} else if (0 <= (SIndex = uc - HC_SBASE) &&
3052232153Smm			    SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3053232153Smm				/*
3054232153Smm				 * Hangul Composition.
3055232153Smm				 * 2. Two current code points are LV and T.
3056232153Smm				 */
3057232153Smm				int TIndex = uc2 - HC_TBASE;
3058232153Smm				if (0 < TIndex && TIndex < HC_TCOUNT) {
3059232153Smm					/* Make syllable of form LVT. */
3060232153Smm					UPDATE_UC(uc + TIndex);
3061232153Smm				} else {
3062232153Smm					WRITE_UC();
3063232153Smm					REPLACE_UC_WITH_UC2();
3064232153Smm				}
3065232153Smm				continue;
3066232153Smm			} else if ((nfc = get_nfc(uc, uc2)) != 0) {
3067232153Smm				/* A composition to current code points
3068232153Smm				 * is found. */
3069232153Smm				UPDATE_UC(nfc);
3070232153Smm				continue;
3071232153Smm			} else if ((cl = CCC(uc2)) == 0) {
3072232153Smm				/* Clearly 'uc2' the second code point is not
3073232153Smm				 * a decomposable code. */
3074232153Smm				WRITE_UC();
3075232153Smm				REPLACE_UC_WITH_UC2();
3076232153Smm				continue;
3077232153Smm			}
3078232153Smm
3079232153Smm			/*
3080232153Smm			 * Collect following decomposable code points.
3081232153Smm			 */
3082232153Smm			cx = 0;
3083232153Smm			ucx[0] = uc2;
3084232153Smm			ccx[0] = cl;
3085232153Smm			COLLECT_CPS(1);
3086232153Smm
3087232153Smm			/*
3088232153Smm			 * Find a composed code in the collected code points.
3089232153Smm			 */
3090232153Smm			i = 1;
3091232153Smm			while (i < ucx_size) {
3092232153Smm				int j;
3093232153Smm
3094232153Smm				if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3095232153Smm					i++;
3096232153Smm					continue;
3097232153Smm				}
3098232153Smm
3099232153Smm				/*
3100232153Smm				 * nfc is composed of uc and ucx[i].
3101232153Smm				 */
3102232153Smm				UPDATE_UC(nfc);
3103232153Smm
3104232153Smm				/*
3105232153Smm				 * Remove ucx[i] by shifting
3106232153Smm				 * following code points.
3107232153Smm				 */
3108232153Smm				for (j = i; j+1 < ucx_size; j++) {
3109232153Smm					ucx[j] = ucx[j+1];
3110232153Smm					ccx[j] = ccx[j+1];
3111232153Smm				}
3112232153Smm				ucx_size --;
3113232153Smm
3114232153Smm				/*
3115232153Smm				 * Collect following code points blocked
3116232153Smm				 * by ucx[i] the removed code point.
3117232153Smm				 */
3118232153Smm				if (ucx_size > 0 && i == ucx_size &&
3119232153Smm				    nx > 0 && cx == cl) {
3120232153Smm					cl =  ccx[ucx_size-1];
3121232153Smm					COLLECT_CPS(ucx_size);
3122232153Smm				}
3123232153Smm				/*
3124232153Smm				 * Restart finding a composed code with
3125232153Smm				 * the updated uc from the top of the
3126232153Smm				 * collected code points.
3127232153Smm				 */
3128232153Smm				i = 0;
3129232153Smm			}
3130232153Smm
3131232153Smm			/*
3132232153Smm			 * Apparently the current code points are not
3133232153Smm			 * decomposed characters or already composed.
3134232153Smm			 */
3135232153Smm			WRITE_UC();
3136232153Smm			for (i = 0; i < ucx_size; i++)
3137232153Smm				UNPARSE(p, endp, ucx[i]);
3138232153Smm
3139232153Smm			/*
3140232153Smm			 * Flush out remaining canonical combining characters.
3141232153Smm			 */
3142232153Smm			if (nx > 0 && cx == cl && len > 0) {
3143232153Smm				while ((nx = parse(&ucx[0], s, len))
3144232153Smm				    > 0) {
3145232153Smm					cx = CCC(ucx[0]);
3146232153Smm					if (cl > cx)
3147232153Smm						break;
3148232153Smm					s += nx;
3149232153Smm					len -= nx;
3150232153Smm					cl = cx;
3151232153Smm					UNPARSE(p, endp, ucx[0]);
3152232153Smm				}
3153232153Smm			}
3154232153Smm			break;
3155232153Smm		}
3156232153Smm		if (n2 < 0) {
3157232153Smm			WRITE_UC();
3158232153Smm			/* Use a replaced unicode character. */
3159232153Smm			UNPARSE(p, endp, uc2);
3160232153Smm			s += n2*-1;
3161232153Smm			len -= n2*-1;
3162232153Smm			ret = -1;
3163232153Smm			continue;
3164232153Smm		} else if (n2 == 0) {
3165232153Smm			WRITE_UC();
3166232153Smm			break;
3167232153Smm		}
3168232153Smm	}
3169232153Smm	as->length = p - as->s;
3170232153Smm	as->s[as->length] = '\0';
3171232153Smm	if (ts == 2)
3172232153Smm		as->s[as->length+1] = '\0';
3173232153Smm	return (ret);
3174232153Smm}
3175232153Smm
3176238856Smmstatic int
3177238856Smmget_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
3178238856Smm{
3179238856Smm	int t, b;
3180232153Smm
3181238856Smm	/*
3182238856Smm	 * These are not converted to NFD on Mac OS.
3183238856Smm	 */
3184238856Smm	if ((uc >= 0x2000 && uc <= 0x2FFF) ||
3185238856Smm	    (uc >= 0xF900 && uc <= 0xFAFF) ||
3186238856Smm	    (uc >= 0x2F800 && uc <= 0x2FAFF))
3187238856Smm		return (0);
3188238856Smm	/*
3189238856Smm	 * Those code points are not converted to NFD on Mac OS.
3190238856Smm	 * I do not know the reason because it is undocumented.
3191238856Smm	 *   NFC        NFD
3192238856Smm	 *   1109A  ==> 11099 110BA
3193238856Smm	 *   1109C  ==> 1109B 110BA
3194238856Smm	 *   110AB  ==> 110A5 110BA
3195238856Smm	 */
3196238856Smm	if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
3197238856Smm		return (0);
3198238856Smm
3199238856Smm	t = 0;
3200238856Smm	b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
3201238856Smm	while (b >= t) {
3202238856Smm		int m = (t + b) / 2;
3203238856Smm		if (u_decomposition_table[m].nfc < uc)
3204238856Smm			t = m + 1;
3205238856Smm		else if (u_decomposition_table[m].nfc > uc)
3206238856Smm			b = m - 1;
3207238856Smm		else {
3208238856Smm			*cp1 = u_decomposition_table[m].cp1;
3209238856Smm			*cp2 = u_decomposition_table[m].cp2;
3210238856Smm			return (1);
3211238856Smm		}
3212238856Smm	}
3213238856Smm	return (0);
3214238856Smm}
3215238856Smm
3216238856Smm#define REPLACE_UC_WITH(cp) do {		\
3217238856Smm	uc = cp;				\
3218238856Smm	ucptr = NULL;				\
3219238856Smm} while (0)
3220238856Smm
3221232153Smm/*
3222232153Smm * Normalize UTF-8 characters to Form D and copy the result.
3223232153Smm */
3224232153Smmstatic int
3225232153Smmarchive_string_normalize_D(struct archive_string *as, const void *_p,
3226232153Smm    size_t len, struct archive_string_conv *sc)
3227232153Smm{
3228238856Smm	const char *s = (const char *)_p;
3229238856Smm	char *p, *endp;
3230238856Smm	uint32_t uc, uc2;
3231238856Smm	size_t w;
3232238856Smm	int always_replace, n, n2, ret = 0, spair, ts, tm;
3233238856Smm	int (*parse)(uint32_t *, const char *, size_t);
3234238856Smm	size_t (*unparse)(char *, size_t, uint32_t);
3235232153Smm
3236238856Smm	always_replace = 1;
3237238856Smm	ts = 1;/* text size. */
3238238856Smm	if (sc->flag & SCONV_TO_UTF16BE) {
3239238856Smm		unparse = unicode_to_utf16be;
3240238856Smm		ts = 2;
3241238856Smm		if (sc->flag & SCONV_FROM_UTF16BE)
3242238856Smm			always_replace = 0;
3243238856Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
3244238856Smm		unparse = unicode_to_utf16le;
3245238856Smm		ts = 2;
3246238856Smm		if (sc->flag & SCONV_FROM_UTF16LE)
3247238856Smm			always_replace = 0;
3248238856Smm	} else if (sc->flag & SCONV_TO_UTF8) {
3249238856Smm		unparse = unicode_to_utf8;
3250238856Smm		if (sc->flag & SCONV_FROM_UTF8)
3251238856Smm			always_replace = 0;
3252238856Smm	} else {
3253238856Smm		/*
3254238856Smm		 * This case is going to be converted to another
3255238856Smm		 * character-set through iconv.
3256238856Smm		 */
3257238856Smm		always_replace = 0;
3258238856Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
3259238856Smm			unparse = unicode_to_utf16be;
3260238856Smm			ts = 2;
3261238856Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
3262238856Smm			unparse = unicode_to_utf16le;
3263238856Smm			ts = 2;
3264238856Smm		} else {
3265238856Smm			unparse = unicode_to_utf8;
3266238856Smm		}
3267228753Smm	}
3268232153Smm
3269238856Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
3270238856Smm		parse = utf16be_to_unicode;
3271238856Smm		tm = 1;
3272238856Smm		spair = 4;/* surrogate pair size in UTF-16. */
3273238856Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
3274238856Smm		parse = utf16le_to_unicode;
3275238856Smm		tm = 1;
3276238856Smm		spair = 4;/* surrogate pair size in UTF-16. */
3277238856Smm	} else {
3278238856Smm		parse = cesu8_to_unicode;
3279238856Smm		tm = ts;
3280238856Smm		spair = 6;/* surrogate pair size in UTF-8. */
3281238856Smm	}
3282238856Smm
3283238856Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3284232153Smm		return (-1);
3285232153Smm
3286238856Smm	p = as->s + as->length;
3287238856Smm	endp = as->s + as->buffer_length - ts;
3288238856Smm	while ((n = parse(&uc, s, len)) != 0) {
3289238856Smm		const char *ucptr;
3290238856Smm		uint32_t cp1, cp2;
3291238856Smm		int SIndex;
3292238856Smm		struct {
3293238856Smm			uint32_t uc;
3294238856Smm			int ccc;
3295238856Smm		} fdc[FDC_MAX];
3296238856Smm		int fdi, fdj;
3297238856Smm		int ccc;
3298232153Smm
3299238856Smmcheck_first_code:
3300238856Smm		if (n < 0) {
3301238856Smm			/* Use a replaced unicode character. */
3302238856Smm			UNPARSE(p, endp, uc);
3303238856Smm			s += n*-1;
3304238856Smm			len -= n*-1;
3305238856Smm			ret = -1;
3306238856Smm			continue;
3307238856Smm		} else if (n == spair || always_replace)
3308238856Smm			/* uc is converted from a surrogate pair.
3309238856Smm			 * this should be treated as a changed code. */
3310238856Smm			ucptr = NULL;
3311238856Smm		else
3312238856Smm			ucptr = s;
3313238856Smm		s += n;
3314238856Smm		len -= n;
3315232153Smm
3316238856Smm		/* Hangul Decomposition. */
3317238856Smm		if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
3318238856Smm			int L = HC_LBASE + SIndex / HC_NCOUNT;
3319238856Smm			int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
3320238856Smm			int T = HC_TBASE + SIndex % HC_TCOUNT;
3321232153Smm
3322238856Smm			REPLACE_UC_WITH(L);
3323238856Smm			WRITE_UC();
3324238856Smm			REPLACE_UC_WITH(V);
3325238856Smm			WRITE_UC();
3326238856Smm			if (T != HC_TBASE) {
3327238856Smm				REPLACE_UC_WITH(T);
3328238856Smm				WRITE_UC();
3329238856Smm			}
3330238856Smm			continue;
3331238856Smm		}
3332238856Smm		if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
3333238856Smm			WRITE_UC();
3334238856Smm			continue;
3335238856Smm		}
3336232153Smm
3337238856Smm		fdi = 0;
3338238856Smm		while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
3339238856Smm			int k;
3340238856Smm
3341238856Smm			for (k = fdi; k > 0; k--)
3342238856Smm				fdc[k] = fdc[k-1];
3343238856Smm			fdc[0].ccc = CCC(cp2);
3344238856Smm			fdc[0].uc = cp2;
3345238856Smm			fdi++;
3346238856Smm			REPLACE_UC_WITH(cp1);
3347238856Smm		}
3348238856Smm
3349238856Smm		/* Read following code points. */
3350238856Smm		while ((n2 = parse(&uc2, s, len)) > 0 &&
3351238856Smm		    (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
3352238856Smm			int j, k;
3353238856Smm
3354238856Smm			s += n2;
3355238856Smm			len -= n2;
3356238856Smm			for (j = 0; j < fdi; j++) {
3357238856Smm				if (fdc[j].ccc > ccc)
3358238856Smm					break;
3359238856Smm			}
3360238856Smm			if (j < fdi) {
3361238856Smm				for (k = fdi; k > j; k--)
3362238856Smm					fdc[k] = fdc[k-1];
3363238856Smm				fdc[j].ccc = ccc;
3364238856Smm				fdc[j].uc = uc2;
3365238856Smm			} else {
3366238856Smm				fdc[fdi].ccc = ccc;
3367238856Smm				fdc[fdi].uc = uc2;
3368238856Smm			}
3369238856Smm			fdi++;
3370238856Smm		}
3371238856Smm
3372238856Smm		WRITE_UC();
3373238856Smm		for (fdj = 0; fdj < fdi; fdj++) {
3374238856Smm			REPLACE_UC_WITH(fdc[fdj].uc);
3375238856Smm			WRITE_UC();
3376238856Smm		}
3377238856Smm
3378238856Smm		if (n2 == 0)
3379238856Smm			break;
3380238856Smm		REPLACE_UC_WITH(uc2);
3381238856Smm		n = n2;
3382238856Smm		goto check_first_code;
3383232153Smm	}
3384238856Smm	as->length = p - as->s;
3385238856Smm	as->s[as->length] = '\0';
3386238856Smm	if (ts == 2)
3387238856Smm		as->s[as->length+1] = '\0';
3388232153Smm	return (ret);
3389228753Smm}
3390228753Smm
3391228753Smm/*
3392232153Smm * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
3393232153Smm * that WCS is Unicode. It is true for several platforms but some are false.
3394232153Smm * And then people who did not use UTF-8 locale on the non Unicode WCS
3395232153Smm * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3396232153Smm * now cannot get right filename from libarchive 3.x and later since we
3397232153Smm * fixed the wrong assumption and it is incompatible to older its versions.
3398232153Smm * So we provide special option, "compat-2x.x", for resolving it.
3399232153Smm * That option enable the string conversion of libarchive 2.x.
3400228753Smm *
3401232153Smm * Translates the wrong UTF-8 string made by libarchive 2.x into current
3402232153Smm * locale character set and appends to the archive_string.
3403232153Smm * Note: returns -1 if conversion fails.
3404228753Smm */
3405232153Smmstatic int
3406232153Smmstrncat_from_utf8_libarchive2(struct archive_string *as,
3407232153Smm    const void *_p, size_t len, struct archive_string_conv *sc)
3408228753Smm{
3409232153Smm	const char *s;
3410228753Smm	int n;
3411228753Smm	char *p;
3412232153Smm	char *end;
3413232153Smm	uint32_t unicode;
3414228753Smm#if HAVE_WCRTOMB
3415228753Smm	mbstate_t shift_state;
3416228753Smm
3417228753Smm	memset(&shift_state, 0, sizeof(shift_state));
3418228753Smm#else
3419228753Smm	/* Clear the shift state before starting. */
3420228753Smm	wctomb(NULL, L'\0');
3421228753Smm#endif
3422232153Smm	(void)sc; /* UNUSED */
3423228753Smm	/*
3424232153Smm	 * Allocate buffer for MBS.
3425232153Smm	 * We need this allocation here since it is possible that
3426232153Smm	 * as->s is still NULL.
3427228753Smm	 */
3428232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
3429232153Smm		return (-1);
3430232153Smm
3431232153Smm	s = (const char *)_p;
3432232153Smm	p = as->s + as->length;
3433232153Smm	end = as->s + as->buffer_length - MB_CUR_MAX -1;
3434232153Smm	while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3435232153Smm		wchar_t wc;
3436232153Smm
3437232153Smm		if (p >= end) {
3438232153Smm			as->length = p - as->s;
3439232153Smm			/* Re-allocate buffer for MBS. */
3440232153Smm			if (archive_string_ensure(as,
3441232153Smm			    as->length + len * 2 + 1) == NULL)
3442232153Smm				return (-1);
3443232153Smm			p = as->s + as->length;
3444232153Smm			end = as->s + as->buffer_length - MB_CUR_MAX -1;
3445228753Smm		}
3446232153Smm
3447232153Smm		/*
3448313570Smm		 * As libarchive 2.x, translates the UTF-8 characters into
3449232153Smm		 * wide-characters in the assumption that WCS is Unicode.
3450232153Smm		 */
3451232153Smm		if (n < 0) {
3452232153Smm			n *= -1;
3453232153Smm			wc = L'?';
3454232153Smm		} else
3455232153Smm			wc = (wchar_t)unicode;
3456232153Smm
3457232153Smm		s += n;
3458232153Smm		len -= n;
3459232153Smm		/*
3460232153Smm		 * Translates the wide-character into the current locale MBS.
3461232153Smm		 */
3462228753Smm#if HAVE_WCRTOMB
3463248616Smm		n = (int)wcrtomb(p, wc, &shift_state);
3464228753Smm#else
3465248616Smm		n = (int)wctomb(p, wc);
3466228753Smm#endif
3467228753Smm		if (n == -1)
3468232153Smm			return (-1);
3469228753Smm		p += n;
3470228753Smm	}
3471232153Smm	as->length = p - as->s;
3472232153Smm	as->s[as->length] = '\0';
3473232153Smm	return (0);
3474232153Smm}
3475232153Smm
3476232153Smm
3477232153Smm/*
3478232153Smm * Conversion functions between current locale dependent MBS and UTF-16BE.
3479232153Smm *   strncat_from_utf16be() : UTF-16BE --> MBS
3480232153Smm *   strncat_to_utf16be()   : MBS --> UTF16BE
3481232153Smm */
3482232153Smm
3483232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3484232153Smm
3485232153Smm/*
3486232153Smm * Convert a UTF-16BE/LE string to current locale and copy the result.
3487311041Smm * Return -1 if conversion fails.
3488232153Smm */
3489232153Smmstatic int
3490232153Smmwin_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3491232153Smm    struct archive_string_conv *sc, int be)
3492232153Smm{
3493232153Smm	struct archive_string tmp;
3494232153Smm	const char *u16;
3495232153Smm	int ll;
3496232153Smm	BOOL defchar;
3497232153Smm	char *mbs;
3498232153Smm	size_t mbs_size, b;
3499232153Smm	int ret = 0;
3500232153Smm
3501232153Smm	bytes &= ~1;
3502232153Smm	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3503232153Smm		return (-1);
3504232153Smm
3505232153Smm	mbs = as->s + as->length;
3506232153Smm	mbs_size = as->buffer_length - as->length -1;
3507232153Smm
3508232153Smm	if (sc->to_cp == CP_C_LOCALE) {
3509232153Smm		/*
3510232153Smm		 * "C" locale special process.
3511232153Smm		 */
3512232153Smm		u16 = _p;
3513232153Smm		ll = 0;
3514232153Smm		for (b = 0; b < bytes; b += 2) {
3515232153Smm			uint16_t val;
3516232153Smm			if (be)
3517232153Smm				val = archive_be16dec(u16+b);
3518232153Smm			else
3519232153Smm				val = archive_le16dec(u16+b);
3520232153Smm			if (val > 255) {
3521232153Smm				*mbs++ = '?';
3522232153Smm				ret = -1;
3523232153Smm			} else
3524232153Smm				*mbs++ = (char)(val&0xff);
3525232153Smm			ll++;
3526232153Smm		}
3527232153Smm		as->length += ll;
3528232153Smm		as->s[as->length] = '\0';
3529232153Smm		return (ret);
3530232153Smm	}
3531232153Smm
3532232153Smm	archive_string_init(&tmp);
3533232153Smm	if (be) {
3534232153Smm		if (is_big_endian()) {
3535232153Smm			u16 = _p;
3536232153Smm		} else {
3537232153Smm			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3538232153Smm				return (-1);
3539232153Smm			memcpy(tmp.s, _p, bytes);
3540232153Smm			for (b = 0; b < bytes; b += 2) {
3541232153Smm				uint16_t val = archive_be16dec(tmp.s+b);
3542232153Smm				archive_le16enc(tmp.s+b, val);
3543232153Smm			}
3544232153Smm			u16 = tmp.s;
3545232153Smm		}
3546232153Smm	} else {
3547232153Smm		if (!is_big_endian()) {
3548232153Smm			u16 = _p;
3549232153Smm		} else {
3550232153Smm			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3551232153Smm				return (-1);
3552232153Smm			memcpy(tmp.s, _p, bytes);
3553232153Smm			for (b = 0; b < bytes; b += 2) {
3554232153Smm				uint16_t val = archive_le16dec(tmp.s+b);
3555232153Smm				archive_be16enc(tmp.s+b, val);
3556232153Smm			}
3557232153Smm			u16 = tmp.s;
3558232153Smm		}
3559232153Smm	}
3560232153Smm
3561232153Smm	do {
3562232153Smm		defchar = 0;
3563232153Smm		ll = WideCharToMultiByte(sc->to_cp, 0,
3564248616Smm		    (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
3565232153Smm			NULL, &defchar);
3566302294Smm		/* Exit loop if we succeeded */
3567302294Smm		if (ll != 0 ||
3568302294Smm		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3569302294Smm			break;
3570232153Smm		}
3571302294Smm		/* Else expand buffer and loop to try again. */
3572302294Smm		ll = WideCharToMultiByte(sc->to_cp, 0,
3573302294Smm		    (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
3574302294Smm		if (archive_string_ensure(as, ll +1) == NULL)
3575302294Smm			return (-1);
3576302294Smm		mbs = as->s + as->length;
3577302294Smm		mbs_size = as->buffer_length - as->length -1;
3578302294Smm	} while (1);
3579232153Smm	archive_string_free(&tmp);
3580232153Smm	as->length += ll;
3581232153Smm	as->s[as->length] = '\0';
3582232153Smm	if (ll == 0 || defchar)
3583232153Smm		ret = -1;
3584232153Smm	return (ret);
3585232153Smm}
3586232153Smm
3587232153Smmstatic int
3588238856Smmwin_strncat_from_utf16be(struct archive_string *as, const void *_p,
3589238856Smm    size_t bytes, struct archive_string_conv *sc)
3590232153Smm{
3591232153Smm	return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3592232153Smm}
3593232153Smm
3594232153Smmstatic int
3595238856Smmwin_strncat_from_utf16le(struct archive_string *as, const void *_p,
3596238856Smm    size_t bytes, struct archive_string_conv *sc)
3597232153Smm{
3598232153Smm	return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3599232153Smm}
3600232153Smm
3601232153Smmstatic int
3602232153Smmis_big_endian(void)
3603232153Smm{
3604232153Smm	uint16_t d = 1;
3605232153Smm
3606232153Smm	return (archive_be16dec(&d) == 1);
3607232153Smm}
3608232153Smm
3609232153Smm/*
3610232153Smm * Convert a current locale string to UTF-16BE/LE and copy the result.
3611311041Smm * Return -1 if conversion fails.
3612232153Smm */
3613232153Smmstatic int
3614238856Smmwin_strncat_to_utf16(struct archive_string *as16, const void *_p,
3615238856Smm    size_t length, struct archive_string_conv *sc, int bigendian)
3616232153Smm{
3617232153Smm	const char *s = (const char *)_p;
3618232153Smm	char *u16;
3619232153Smm	size_t count, avail;
3620232153Smm
3621232153Smm	if (archive_string_ensure(as16,
3622232153Smm	    as16->length + (length + 1) * 2) == NULL)
3623232153Smm		return (-1);
3624232153Smm
3625232153Smm	u16 = as16->s + as16->length;
3626232153Smm	avail = as16->buffer_length - 2;
3627232153Smm	if (sc->from_cp == CP_C_LOCALE) {
3628232153Smm		/*
3629232153Smm		 * "C" locale special process.
3630232153Smm		 */
3631232153Smm		count = 0;
3632232153Smm		while (count < length && *s) {
3633232153Smm			if (bigendian)
3634232153Smm				archive_be16enc(u16, *s);
3635232153Smm			else
3636232153Smm				archive_le16enc(u16, *s);
3637232153Smm			u16 += 2;
3638232153Smm			s++;
3639232153Smm			count++;
3640232153Smm		}
3641232153Smm		as16->length += count << 1;
3642232153Smm		as16->s[as16->length] = 0;
3643232153Smm		as16->s[as16->length+1] = 0;
3644232153Smm		return (0);
3645232153Smm	}
3646232153Smm	do {
3647232153Smm		count = MultiByteToWideChar(sc->from_cp,
3648248616Smm		    MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
3649302294Smm		/* Exit loop if we succeeded */
3650302294Smm		if (count != 0 ||
3651302294Smm		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3652302294Smm			break;
3653232153Smm		}
3654302294Smm		/* Expand buffer and try again */
3655302294Smm		count = MultiByteToWideChar(sc->from_cp,
3656302294Smm		    MB_PRECOMPOSED, s, (int)length, NULL, 0);
3657302294Smm		if (archive_string_ensure(as16, (count +1) * 2)
3658302294Smm		    == NULL)
3659302294Smm			return (-1);
3660302294Smm		u16 = as16->s + as16->length;
3661302294Smm		avail = as16->buffer_length - 2;
3662302294Smm	} while (1);
3663232153Smm	as16->length += count * 2;
3664232153Smm	as16->s[as16->length] = 0;
3665232153Smm	as16->s[as16->length+1] = 0;
3666232153Smm	if (count == 0)
3667232153Smm		return (-1);
3668232153Smm
3669232153Smm	if (is_big_endian()) {
3670232153Smm		if (!bigendian) {
3671232153Smm			while (count > 0) {
3672232153Smm				uint16_t v = archive_be16dec(u16);
3673232153Smm				archive_le16enc(u16, v);
3674232153Smm				u16 += 2;
3675232153Smm				count--;
3676232153Smm			}
3677232153Smm		}
3678232153Smm	} else {
3679232153Smm		if (bigendian) {
3680232153Smm			while (count > 0) {
3681232153Smm				uint16_t v = archive_le16dec(u16);
3682232153Smm				archive_be16enc(u16, v);
3683232153Smm				u16 += 2;
3684232153Smm				count--;
3685232153Smm			}
3686232153Smm		}
3687232153Smm	}
3688232153Smm	return (0);
3689232153Smm}
3690232153Smm
3691232153Smmstatic int
3692238856Smmwin_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3693238856Smm    size_t length, struct archive_string_conv *sc)
3694232153Smm{
3695232153Smm	return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3696232153Smm}
3697232153Smm
3698232153Smmstatic int
3699238856Smmwin_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3700238856Smm    size_t length, struct archive_string_conv *sc)
3701232153Smm{
3702232153Smm	return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3703232153Smm}
3704232153Smm
3705232153Smm#endif /* _WIN32 && !__CYGWIN__ */
3706232153Smm
3707232153Smm/*
3708232153Smm * Do the best effort for conversions.
3709232153Smm * We cannot handle UTF-16BE character-set without such iconv,
3710232153Smm * but there is a chance if a string consists just ASCII code or
3711232153Smm * a current locale is UTF-8.
3712232153Smm */
3713232153Smm
3714232153Smm/*
3715232153Smm * Convert a UTF-16BE string to current locale and copy the result.
3716311041Smm * Return -1 if conversion fails.
3717232153Smm */
3718232153Smmstatic int
3719232153Smmbest_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3720232153Smm    size_t bytes, struct archive_string_conv *sc, int be)
3721232153Smm{
3722232153Smm	const char *utf16 = (const char *)_p;
3723232153Smm	char *mbs;
3724232153Smm	uint32_t uc;
3725232153Smm	int n, ret;
3726232153Smm
3727232153Smm	(void)sc; /* UNUSED */
3728232153Smm	/*
3729232153Smm	 * Other case, we should do the best effort.
3730232153Smm	 * If all character are ASCII(<0x7f), we can convert it.
3731232153Smm	 * if not , we set a alternative character and return -1.
3732232153Smm	 */
3733232153Smm	ret = 0;
3734232153Smm	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3735232153Smm		return (-1);
3736232153Smm	mbs = as->s + as->length;
3737232153Smm
3738232153Smm	while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3739232153Smm		if (n < 0) {
3740232153Smm			n *= -1;
3741232153Smm			ret =  -1;
3742232153Smm		}
3743232153Smm		bytes -= n;
3744232153Smm		utf16 += n;
3745232153Smm
3746232153Smm		if (uc > 127) {
3747232153Smm			/* We cannot handle it. */
3748232153Smm			*mbs++ = '?';
3749232153Smm			ret =  -1;
3750232153Smm		} else
3751232153Smm			*mbs++ = (char)uc;
3752232153Smm	}
3753232153Smm	as->length = mbs - as->s;
3754232153Smm	as->s[as->length] = '\0';
3755232153Smm	return (ret);
3756232153Smm}
3757232153Smm
3758232153Smmstatic int
3759232153Smmbest_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3760232153Smm    size_t bytes, struct archive_string_conv *sc)
3761232153Smm{
3762232153Smm	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3763232153Smm}
3764232153Smm
3765232153Smmstatic int
3766232153Smmbest_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3767232153Smm    size_t bytes, struct archive_string_conv *sc)
3768232153Smm{
3769232153Smm	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3770232153Smm}
3771232153Smm
3772232153Smm/*
3773232153Smm * Convert a current locale string to UTF-16BE/LE and copy the result.
3774311041Smm * Return -1 if conversion fails.
3775232153Smm */
3776232153Smmstatic int
3777232153Smmbest_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3778232153Smm    size_t length, struct archive_string_conv *sc, int bigendian)
3779232153Smm{
3780232153Smm	const char *s = (const char *)_p;
3781232153Smm	char *utf16;
3782232153Smm	size_t remaining;
3783232153Smm	int ret;
3784232153Smm
3785232153Smm	(void)sc; /* UNUSED */
3786232153Smm	/*
3787232153Smm	 * Other case, we should do the best effort.
3788232153Smm	 * If all character are ASCII(<0x7f), we can convert it.
3789232153Smm	 * if not , we set a alternative character and return -1.
3790232153Smm	 */
3791232153Smm	ret = 0;
3792232153Smm	remaining = length;
3793232153Smm
3794232153Smm	if (archive_string_ensure(as16,
3795232153Smm	    as16->length + (length + 1) * 2) == NULL)
3796232153Smm		return (-1);
3797232153Smm
3798232153Smm	utf16 = as16->s + as16->length;
3799232153Smm	while (remaining--) {
3800232153Smm		unsigned c = *s++;
3801232153Smm		if (c > 127) {
3802232153Smm			/* We cannot handle it. */
3803232153Smm			c = UNICODE_R_CHAR;
3804232153Smm			ret = -1;
3805232153Smm		}
3806232153Smm		if (bigendian)
3807232153Smm			archive_be16enc(utf16, c);
3808232153Smm		else
3809232153Smm			archive_le16enc(utf16, c);
3810232153Smm		utf16 += 2;
3811232153Smm	}
3812232153Smm	as16->length = utf16 - as16->s;
3813232153Smm	as16->s[as16->length] = 0;
3814232153Smm	as16->s[as16->length+1] = 0;
3815232153Smm	return (ret);
3816232153Smm}
3817232153Smm
3818232153Smmstatic int
3819232153Smmbest_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3820232153Smm    size_t length, struct archive_string_conv *sc)
3821232153Smm{
3822232153Smm	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3823232153Smm}
3824232153Smm
3825232153Smmstatic int
3826232153Smmbest_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3827232153Smm    size_t length, struct archive_string_conv *sc)
3828232153Smm{
3829232153Smm	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3830232153Smm}
3831232153Smm
3832232153Smm
3833232153Smm/*
3834232153Smm * Multistring operations.
3835232153Smm */
3836232153Smm
3837232153Smmvoid
3838232153Smmarchive_mstring_clean(struct archive_mstring *aes)
3839232153Smm{
3840232153Smm	archive_wstring_free(&(aes->aes_wcs));
3841232153Smm	archive_string_free(&(aes->aes_mbs));
3842232153Smm	archive_string_free(&(aes->aes_utf8));
3843232153Smm	archive_string_free(&(aes->aes_mbs_in_locale));
3844232153Smm	aes->aes_set = 0;
3845232153Smm}
3846232153Smm
3847232153Smmvoid
3848232153Smmarchive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3849232153Smm{
3850232153Smm	dest->aes_set = src->aes_set;
3851232153Smm	archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3852232153Smm	archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3853232153Smm	archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3854232153Smm}
3855232153Smm
3856232153Smmint
3857232153Smmarchive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3858232153Smm  const char **p)
3859232153Smm{
3860232153Smm	struct archive_string_conv *sc;
3861232153Smm	int r;
3862232153Smm
3863232153Smm	/* If we already have a UTF8 form, return that immediately. */
3864232153Smm	if (aes->aes_set & AES_SET_UTF8) {
3865232153Smm		*p = aes->aes_utf8.s;
3866232153Smm		return (0);
3867232153Smm	}
3868232153Smm
3869232153Smm	*p = NULL;
3870232153Smm	if (aes->aes_set & AES_SET_MBS) {
3871232153Smm		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3872232153Smm		if (sc == NULL)
3873232153Smm			return (-1);/* Couldn't allocate memory for sc. */
3874299529Smm		r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
3875232153Smm		    aes->aes_mbs.length, sc);
3876232153Smm		if (a == NULL)
3877232153Smm			free_sconv_object(sc);
3878232153Smm		if (r == 0) {
3879232153Smm			aes->aes_set |= AES_SET_UTF8;
3880232153Smm			*p = aes->aes_utf8.s;
3881232153Smm			return (0);/* success. */
3882232153Smm		} else
3883232153Smm			return (-1);/* failure. */
3884232153Smm	}
3885232153Smm	return (0);/* success. */
3886232153Smm}
3887232153Smm
3888232153Smmint
3889232153Smmarchive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3890232153Smm    const char **p)
3891232153Smm{
3892232153Smm	int r, ret = 0;
3893232153Smm
3894232153Smm	(void)a; /* UNUSED */
3895232153Smm	/* If we already have an MBS form, return that immediately. */
3896232153Smm	if (aes->aes_set & AES_SET_MBS) {
3897232153Smm		*p = aes->aes_mbs.s;
3898232153Smm		return (ret);
3899232153Smm	}
3900232153Smm
3901232153Smm	*p = NULL;
3902232153Smm	/* If there's a WCS form, try converting with the native locale. */
3903232153Smm	if (aes->aes_set & AES_SET_WCS) {
3904232153Smm		archive_string_empty(&(aes->aes_mbs));
3905232153Smm		r = archive_string_append_from_wcs(&(aes->aes_mbs),
3906232153Smm		    aes->aes_wcs.s, aes->aes_wcs.length);
3907232153Smm		*p = aes->aes_mbs.s;
3908232153Smm		if (r == 0) {
3909232153Smm			aes->aes_set |= AES_SET_MBS;
3910232153Smm			return (ret);
3911232153Smm		} else
3912232153Smm			ret = -1;
3913232153Smm	}
3914232153Smm
3915232153Smm	/*
3916232153Smm	 * Only a UTF-8 form cannot avail because its conversion already
3917232153Smm	 * failed at archive_mstring_update_utf8().
3918232153Smm	 */
3919232153Smm	return (ret);
3920232153Smm}
3921232153Smm
3922232153Smmint
3923232153Smmarchive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
3924232153Smm    const wchar_t **wp)
3925232153Smm{
3926232153Smm	int r, ret = 0;
3927232153Smm
3928232153Smm	(void)a;/* UNUSED */
3929232153Smm	/* Return WCS form if we already have it. */
3930232153Smm	if (aes->aes_set & AES_SET_WCS) {
3931232153Smm		*wp = aes->aes_wcs.s;
3932232153Smm		return (ret);
3933232153Smm	}
3934232153Smm
3935232153Smm	*wp = NULL;
3936232153Smm	/* Try converting MBS to WCS using native locale. */
3937232153Smm	if (aes->aes_set & AES_SET_MBS) {
3938232153Smm		archive_wstring_empty(&(aes->aes_wcs));
3939232153Smm		r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
3940232153Smm		    aes->aes_mbs.s, aes->aes_mbs.length);
3941232153Smm		if (r == 0) {
3942232153Smm			aes->aes_set |= AES_SET_WCS;
3943232153Smm			*wp = aes->aes_wcs.s;
3944232153Smm		} else
3945232153Smm			ret = -1;/* failure. */
3946232153Smm	}
3947232153Smm	return (ret);
3948232153Smm}
3949232153Smm
3950232153Smmint
3951232153Smmarchive_mstring_get_mbs_l(struct archive_mstring *aes,
3952232153Smm    const char **p, size_t *length, struct archive_string_conv *sc)
3953232153Smm{
3954232153Smm	int r, ret = 0;
3955232153Smm
3956232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3957232153Smm	/*
3958313570Smm	 * Internationalization programming on Windows must use Wide
3959232153Smm	 * characters because Windows platform cannot make locale UTF-8.
3960232153Smm	 */
3961232153Smm	if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
3962232153Smm		archive_string_empty(&(aes->aes_mbs_in_locale));
3963232153Smm		r = archive_string_append_from_wcs_in_codepage(
3964232153Smm		    &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
3965232153Smm		    aes->aes_wcs.length, sc);
3966232153Smm		if (r == 0) {
3967232153Smm			*p = aes->aes_mbs_in_locale.s;
3968232153Smm			if (length != NULL)
3969232153Smm				*length = aes->aes_mbs_in_locale.length;
3970232153Smm			return (0);
3971232153Smm		} else if (errno == ENOMEM)
3972232153Smm			return (-1);
3973232153Smm		else
3974232153Smm			ret = -1;
3975232153Smm	}
3976228753Smm#endif
3977232153Smm
3978232153Smm	/* If there is not an MBS form but is a WCS form, try converting
3979232153Smm	 * with the native locale to be used for translating it to specified
3980232153Smm	 * character-set. */
3981232153Smm	if ((aes->aes_set & AES_SET_MBS) == 0 &&
3982232153Smm	    (aes->aes_set & AES_SET_WCS) != 0) {
3983232153Smm		archive_string_empty(&(aes->aes_mbs));
3984232153Smm		r = archive_string_append_from_wcs(&(aes->aes_mbs),
3985232153Smm		    aes->aes_wcs.s, aes->aes_wcs.length);
3986232153Smm		if (r == 0)
3987232153Smm			aes->aes_set |= AES_SET_MBS;
3988232153Smm		else if (errno == ENOMEM)
3989232153Smm			return (-1);
3990232153Smm		else
3991232153Smm			ret = -1;
3992232153Smm	}
3993232153Smm	/* If we already have an MBS form, use it to be translated to
3994232153Smm	 * specified character-set. */
3995232153Smm	if (aes->aes_set & AES_SET_MBS) {
3996232153Smm		if (sc == NULL) {
3997232153Smm			/* Conversion is unneeded. */
3998232153Smm			*p = aes->aes_mbs.s;
3999232153Smm			if (length != NULL)
4000232153Smm				*length = aes->aes_mbs.length;
4001232153Smm			return (0);
4002232153Smm		}
4003238856Smm		ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
4004232153Smm		    aes->aes_mbs.s, aes->aes_mbs.length, sc);
4005232153Smm		*p = aes->aes_mbs_in_locale.s;
4006232153Smm		if (length != NULL)
4007232153Smm			*length = aes->aes_mbs_in_locale.length;
4008232153Smm	} else {
4009232153Smm		*p = NULL;
4010232153Smm		if (length != NULL)
4011232153Smm			*length = 0;
4012232153Smm	}
4013232153Smm	return (ret);
4014228753Smm}
4015228753Smm
4016232153Smmint
4017232153Smmarchive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4018232153Smm{
4019232153Smm	if (mbs == NULL) {
4020232153Smm		aes->aes_set = 0;
4021232153Smm		return (0);
4022232153Smm	}
4023232153Smm	return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4024232153Smm}
4025232153Smm
4026232153Smmint
4027232153Smmarchive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4028232153Smm    size_t len)
4029232153Smm{
4030232153Smm	if (mbs == NULL) {
4031232153Smm		aes->aes_set = 0;
4032232153Smm		return (0);
4033232153Smm	}
4034232153Smm	aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4035232153Smm	archive_strncpy(&(aes->aes_mbs), mbs, len);
4036232153Smm	archive_string_empty(&(aes->aes_utf8));
4037232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4038232153Smm	return (0);
4039232153Smm}
4040232153Smm
4041232153Smmint
4042232153Smmarchive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4043232153Smm{
4044238856Smm	return archive_mstring_copy_wcs_len(aes, wcs,
4045238856Smm				wcs == NULL ? 0 : wcslen(wcs));
4046232153Smm}
4047232153Smm
4048232153Smmint
4049299529Smmarchive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
4050299529Smm{
4051299529Smm  if (utf8 == NULL) {
4052299529Smm    aes->aes_set = 0;
4053299529Smm  }
4054299529Smm  aes->aes_set = AES_SET_UTF8;
4055299529Smm  archive_string_empty(&(aes->aes_mbs));
4056299529Smm  archive_string_empty(&(aes->aes_wcs));
4057299529Smm  archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
4058299529Smm  return (int)strlen(utf8);
4059299529Smm}
4060299529Smm
4061299529Smmint
4062232153Smmarchive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4063232153Smm    size_t len)
4064232153Smm{
4065232153Smm	if (wcs == NULL) {
4066232153Smm		aes->aes_set = 0;
4067232153Smm	}
4068232153Smm	aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4069232153Smm	archive_string_empty(&(aes->aes_mbs));
4070232153Smm	archive_string_empty(&(aes->aes_utf8));
4071232153Smm	archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4072232153Smm	return (0);
4073232153Smm}
4074232153Smm
4075232153Smmint
4076232153Smmarchive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4077232153Smm    const char *mbs, size_t len, struct archive_string_conv *sc)
4078232153Smm{
4079232153Smm	int r;
4080232153Smm
4081232153Smm	if (mbs == NULL) {
4082232153Smm		aes->aes_set = 0;
4083232153Smm		return (0);
4084232153Smm	}
4085232153Smm	archive_string_empty(&(aes->aes_mbs));
4086232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4087232153Smm	archive_string_empty(&(aes->aes_utf8));
4088232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
4089232153Smm	/*
4090313570Smm	 * Internationalization programming on Windows must use Wide
4091232153Smm	 * characters because Windows platform cannot make locale UTF-8.
4092232153Smm	 */
4093232153Smm	if (sc == NULL) {
4094232153Smm		if (archive_string_append(&(aes->aes_mbs),
4095232153Smm			mbs, mbsnbytes(mbs, len)) == NULL) {
4096232153Smm			aes->aes_set = 0;
4097232153Smm			r = -1;
4098232153Smm		} else {
4099232153Smm			aes->aes_set = AES_SET_MBS;
4100232153Smm			r = 0;
4101232153Smm		}
4102232153Smm#if defined(HAVE_ICONV)
4103232153Smm	} else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4104232153Smm		/*
4105232153Smm		 * This case happens only when MultiByteToWideChar() cannot
4106232153Smm		 * handle sc->from_cp, and we have to iconv in order to
4107232153Smm		 * translate character-set to wchar_t,UTF-16.
4108232153Smm		 */
4109232153Smm		iconv_t cd = sc->cd;
4110232153Smm		unsigned from_cp;
4111232153Smm		int flag;
4112232153Smm
4113232153Smm		/*
4114232153Smm		 * Translate multi-bytes from some character-set to UTF-8.
4115232153Smm		 */
4116232153Smm		sc->cd = sc->cd_w;
4117238856Smm		r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
4118232153Smm		sc->cd = cd;
4119232153Smm		if (r != 0) {
4120232153Smm			aes->aes_set = 0;
4121232153Smm			return (r);
4122232153Smm		}
4123232153Smm		aes->aes_set = AES_SET_UTF8;
4124232153Smm
4125232153Smm		/*
4126232153Smm		 * Append the UTF-8 string into wstring.
4127232153Smm		 */
4128232153Smm		flag = sc->flag;
4129232153Smm		sc->flag &= ~(SCONV_NORMALIZATION_C
4130232153Smm				| SCONV_TO_UTF16| SCONV_FROM_UTF16);
4131232153Smm		from_cp = sc->from_cp;
4132232153Smm		sc->from_cp = CP_UTF8;
4133232153Smm		r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4134232153Smm			aes->aes_utf8.s, aes->aes_utf8.length, sc);
4135232153Smm		sc->flag = flag;
4136232153Smm		sc->from_cp = from_cp;
4137232153Smm		if (r == 0)
4138232153Smm			aes->aes_set |= AES_SET_WCS;
4139232153Smm#endif
4140232153Smm	} else {
4141232153Smm		r = archive_wstring_append_from_mbs_in_codepage(
4142232153Smm		    &(aes->aes_wcs), mbs, len, sc);
4143232153Smm		if (r == 0)
4144232153Smm			aes->aes_set = AES_SET_WCS;
4145232153Smm		else
4146232153Smm			aes->aes_set = 0;
4147232153Smm	}
4148232153Smm#else
4149238856Smm	r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
4150232153Smm	if (r == 0)
4151232153Smm		aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4152232153Smm	else
4153232153Smm		aes->aes_set = 0;
4154232153Smm#endif
4155232153Smm	return (r);
4156232153Smm}
4157232153Smm
4158232153Smm/*
4159232153Smm * The 'update' form tries to proactively update all forms of
4160232153Smm * this string (WCS and MBS) and returns an error if any of
4161232153Smm * them fail.  This is used by the 'pax' handler, for instance,
4162232153Smm * to detect and report character-conversion failures early while
4163232153Smm * still allowing clients to get potentially useful values from
4164232153Smm * the more tolerant lazy conversions.  (get_mbs and get_wcs will
4165232153Smm * strive to give the user something useful, so you can get hopefully
4166232153Smm * usable values even if some of the character conversions are failing.)
4167232153Smm */
4168232153Smmint
4169232153Smmarchive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4170232153Smm    const char *utf8)
4171232153Smm{
4172232153Smm	struct archive_string_conv *sc;
4173232153Smm	int r;
4174232153Smm
4175232153Smm	if (utf8 == NULL) {
4176232153Smm		aes->aes_set = 0;
4177232153Smm		return (0); /* Succeeded in clearing everything. */
4178232153Smm	}
4179232153Smm
4180232153Smm	/* Save the UTF8 string. */
4181232153Smm	archive_strcpy(&(aes->aes_utf8), utf8);
4182232153Smm
4183232153Smm	/* Empty the mbs and wcs strings. */
4184232153Smm	archive_string_empty(&(aes->aes_mbs));
4185232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4186232153Smm
4187232153Smm	aes->aes_set = AES_SET_UTF8;	/* Only UTF8 is set now. */
4188232153Smm
4189232153Smm	/* Try converting UTF-8 to MBS, return false on failure. */
4190232153Smm	sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4191232153Smm	if (sc == NULL)
4192232153Smm		return (-1);/* Couldn't allocate memory for sc. */
4193238856Smm	r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
4194232153Smm	if (a == NULL)
4195232153Smm		free_sconv_object(sc);
4196232153Smm	if (r != 0)
4197232153Smm		return (-1);
4198232153Smm	aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4199232153Smm
4200232153Smm	/* Try converting MBS to WCS, return false on failure. */
4201232153Smm	if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4202232153Smm	    aes->aes_mbs.length))
4203232153Smm		return (-1);
4204232153Smm	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4205232153Smm
4206232153Smm	/* All conversions succeeded. */
4207232153Smm	return (0);
4208232153Smm}
4209