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 368707 2020-12-16 22:25:20Z 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
78358088Smm#undef max
79358088Smm#define max(a, b)       ((a)>(b)?(a):(b))
80358088Smm
81232153Smmstruct archive_string_conv {
82232153Smm	struct archive_string_conv	*next;
83232153Smm	char				*from_charset;
84232153Smm	char				*to_charset;
85232153Smm	unsigned			 from_cp;
86232153Smm	unsigned			 to_cp;
87232153Smm	/* Set 1 if from_charset and to_charset are the same. */
88232153Smm	int				 same;
89232153Smm	int				 flag;
90232153Smm#define SCONV_TO_CHARSET	1	/* MBS is being converted to specified
91232153Smm					 * charset. */
92232153Smm#define SCONV_FROM_CHARSET	(1<<1)	/* MBS is being converted from
93232153Smm					 * specified charset. */
94232153Smm#define SCONV_BEST_EFFORT 	(1<<2)	/* Copy at least ASCII code. */
95232153Smm#define SCONV_WIN_CP	 	(1<<3)	/* Use Windows API for converting
96232153Smm					 * MBS. */
97232153Smm#define SCONV_UTF8_LIBARCHIVE_2 (1<<4)	/* Incorrect UTF-8 made by libarchive
98232153Smm					 * 2.x in the wrong assumption. */
99232153Smm#define SCONV_NORMALIZATION_C	(1<<6)	/* Need normalization to be Form C.
100232153Smm					 * Before UTF-8 characters are actually
101232153Smm					 * processed. */
102232153Smm#define SCONV_NORMALIZATION_D	(1<<7)	/* Need normalization to be Form D.
103232153Smm					 * Before UTF-8 characters are actually
104232153Smm					 * processed.
105232153Smm					 * Currently this only for MAC OS X. */
106232153Smm#define SCONV_TO_UTF8		(1<<8)	/* "to charset" side is UTF-8. */
107232153Smm#define SCONV_FROM_UTF8		(1<<9)	/* "from charset" side is UTF-8. */
108232153Smm#define SCONV_TO_UTF16BE 	(1<<10)	/* "to charset" side is UTF-16BE. */
109232153Smm#define SCONV_FROM_UTF16BE 	(1<<11)	/* "from charset" side is UTF-16BE. */
110232153Smm#define SCONV_TO_UTF16LE 	(1<<12)	/* "to charset" side is UTF-16LE. */
111232153Smm#define SCONV_FROM_UTF16LE 	(1<<13)	/* "from charset" side is UTF-16LE. */
112232153Smm#define SCONV_TO_UTF16		(SCONV_TO_UTF16BE | SCONV_TO_UTF16LE)
113232153Smm#define SCONV_FROM_UTF16	(SCONV_FROM_UTF16BE | SCONV_FROM_UTF16LE)
114232153Smm
115232153Smm#if HAVE_ICONV
116232153Smm	iconv_t				 cd;
117232153Smm	iconv_t				 cd_w;/* Use at archive_mstring on
118232153Smm				 	       * Windows. */
119232153Smm#endif
120232153Smm	/* A temporary buffer for normalization. */
121232153Smm	struct archive_string		 utftmp;
122232153Smm	int (*converter[2])(struct archive_string *, const void *, size_t,
123232153Smm	    struct archive_string_conv *);
124232153Smm	int				 nconverter;
125232153Smm};
126232153Smm
127232153Smm#define CP_C_LOCALE	0	/* "C" locale only for this file. */
128232153Smm#define CP_UTF16LE	1200
129232153Smm#define CP_UTF16BE	1201
130232153Smm
131232153Smm#define IS_HIGH_SURROGATE_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDBFF)
132232153Smm#define IS_LOW_SURROGATE_LA(uc)	 ((uc) >= 0xDC00 && (uc) <= 0xDFFF)
133232153Smm#define IS_SURROGATE_PAIR_LA(uc) ((uc) >= 0xD800 && (uc) <= 0xDFFF)
134232153Smm#define UNICODE_MAX		0x10FFFF
135232153Smm#define UNICODE_R_CHAR		0xFFFD	/* Replacement character. */
136232153Smm/* Set U+FFFD(Replacement character) in UTF-8. */
137299529Smmstatic const char utf8_replacement_char[] = {0xef, 0xbf, 0xbd};
138232153Smm
139232153Smmstatic struct archive_string_conv *find_sconv_object(struct archive *,
140232153Smm	const char *, const char *);
141232153Smmstatic void add_sconv_object(struct archive *, struct archive_string_conv *);
142232153Smmstatic struct archive_string_conv *create_sconv_object(const char *,
143232153Smm	const char *, unsigned, int);
144232153Smmstatic void free_sconv_object(struct archive_string_conv *);
145232153Smmstatic struct archive_string_conv *get_sconv_object(struct archive *,
146232153Smm	const char *, const char *, int);
147232153Smmstatic unsigned make_codepage_from_charset(const char *);
148232153Smmstatic unsigned get_current_codepage(void);
149232153Smmstatic unsigned get_current_oemcp(void);
150232153Smmstatic size_t mbsnbytes(const void *, size_t);
151232153Smmstatic size_t utf16nbytes(const void *, size_t);
152232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
153232153Smmstatic int archive_wstring_append_from_mbs_in_codepage(
154232153Smm    struct archive_wstring *, const char *, size_t,
155232153Smm    struct archive_string_conv *);
156232153Smmstatic int archive_string_append_from_wcs_in_codepage(struct archive_string *,
157232153Smm    const wchar_t *, size_t, struct archive_string_conv *);
158232153Smmstatic int is_big_endian(void);
159232153Smmstatic int strncat_in_codepage(struct archive_string *, const void *,
160232153Smm    size_t, struct archive_string_conv *);
161238856Smmstatic int win_strncat_from_utf16be(struct archive_string *, const void *,
162232153Smm    size_t, struct archive_string_conv *);
163238856Smmstatic int win_strncat_from_utf16le(struct archive_string *, const void *,
164232153Smm    size_t, struct archive_string_conv *);
165238856Smmstatic int win_strncat_to_utf16be(struct archive_string *, const void *,
166232153Smm    size_t, struct archive_string_conv *);
167238856Smmstatic int win_strncat_to_utf16le(struct archive_string *, const void *,
168232153Smm    size_t, struct archive_string_conv *);
169238856Smm#endif
170238856Smmstatic int best_effort_strncat_from_utf16be(struct archive_string *,
171238856Smm    const void *, size_t, struct archive_string_conv *);
172238856Smmstatic int best_effort_strncat_from_utf16le(struct archive_string *,
173238856Smm    const void *, size_t, struct archive_string_conv *);
174238856Smmstatic int best_effort_strncat_to_utf16be(struct archive_string *,
175238856Smm    const void *, size_t, struct archive_string_conv *);
176238856Smmstatic int best_effort_strncat_to_utf16le(struct archive_string *,
177238856Smm    const void *, size_t, struct archive_string_conv *);
178232153Smm#if defined(HAVE_ICONV)
179232153Smmstatic int iconv_strncat_in_locale(struct archive_string *, const void *,
180232153Smm    size_t, struct archive_string_conv *);
181232153Smm#endif
182238856Smmstatic int best_effort_strncat_in_locale(struct archive_string *,
183238856Smm    const void *, size_t, struct archive_string_conv *);
184232153Smmstatic int _utf8_to_unicode(uint32_t *, const char *, size_t);
185232153Smmstatic int utf8_to_unicode(uint32_t *, const char *, size_t);
186232153Smmstatic inline uint32_t combine_surrogate_pair(uint32_t, uint32_t);
187232153Smmstatic int cesu8_to_unicode(uint32_t *, const char *, size_t);
188232153Smmstatic size_t unicode_to_utf8(char *, size_t, uint32_t);
189232153Smmstatic int utf16_to_unicode(uint32_t *, const char *, size_t, int);
190232153Smmstatic size_t unicode_to_utf16be(char *, size_t, uint32_t);
191232153Smmstatic size_t unicode_to_utf16le(char *, size_t, uint32_t);
192232153Smmstatic int strncat_from_utf8_libarchive2(struct archive_string *,
193232153Smm    const void *, size_t, struct archive_string_conv *);
194232153Smmstatic int strncat_from_utf8_to_utf8(struct archive_string *, const void *,
195232153Smm    size_t, struct archive_string_conv *);
196232153Smmstatic int archive_string_normalize_C(struct archive_string *, const void *,
197232153Smm    size_t, struct archive_string_conv *);
198232153Smmstatic int archive_string_normalize_D(struct archive_string *, const void *,
199232153Smm    size_t, struct archive_string_conv *);
200232153Smmstatic int archive_string_append_unicode(struct archive_string *,
201232153Smm    const void *, size_t, struct archive_string_conv *);
202232153Smm
203232153Smmstatic struct archive_string *
204232153Smmarchive_string_append(struct archive_string *as, const char *p, size_t s)
205228753Smm{
206232153Smm	if (archive_string_ensure(as, as->length + s + 1) == NULL)
207232153Smm		return (NULL);
208318482Smm	if (s)
209318482Smm		memmove(as->s + as->length, p, s);
210228753Smm	as->length += s;
211232153Smm	as->s[as->length] = 0;
212228753Smm	return (as);
213228753Smm}
214228753Smm
215232153Smmstatic struct archive_wstring *
216232153Smmarchive_wstring_append(struct archive_wstring *as, const wchar_t *p, size_t s)
217232153Smm{
218232153Smm	if (archive_wstring_ensure(as, as->length + s + 1) == NULL)
219232153Smm		return (NULL);
220324417Smm	if (s)
221324417Smm		wmemmove(as->s + as->length, p, s);
222232153Smm	as->length += s;
223232153Smm	as->s[as->length] = 0;
224232153Smm	return (as);
225232153Smm}
226232153Smm
227313570Smmstruct archive_string *
228313570Smmarchive_array_append(struct archive_string *as, const char *p, size_t s)
229313570Smm{
230313570Smm	return archive_string_append(as, p, s);
231313570Smm}
232313570Smm
233228753Smmvoid
234232153Smmarchive_string_concat(struct archive_string *dest, struct archive_string *src)
235228753Smm{
236232153Smm	if (archive_string_append(dest, src->s, src->length) == NULL)
237232153Smm		__archive_errx(1, "Out of memory");
238228753Smm}
239228753Smm
240228753Smmvoid
241238856Smmarchive_wstring_concat(struct archive_wstring *dest,
242238856Smm    struct archive_wstring *src)
243228753Smm{
244232153Smm	if (archive_wstring_append(dest, src->s, src->length) == NULL)
245232153Smm		__archive_errx(1, "Out of memory");
246228753Smm}
247228753Smm
248228753Smmvoid
249232153Smmarchive_string_free(struct archive_string *as)
250228753Smm{
251228753Smm	as->length = 0;
252228753Smm	as->buffer_length = 0;
253232153Smm	free(as->s);
254232153Smm	as->s = NULL;
255228753Smm}
256228753Smm
257232153Smmvoid
258232153Smmarchive_wstring_free(struct archive_wstring *as)
259232153Smm{
260232153Smm	as->length = 0;
261232153Smm	as->buffer_length = 0;
262232153Smm	free(as->s);
263232153Smm	as->s = NULL;
264232153Smm}
265232153Smm
266232153Smmstruct archive_wstring *
267232153Smmarchive_wstring_ensure(struct archive_wstring *as, size_t s)
268232153Smm{
269232153Smm	return (struct archive_wstring *)
270232153Smm		archive_string_ensure((struct archive_string *)as,
271232153Smm					s * sizeof(wchar_t));
272232153Smm}
273232153Smm
274228753Smm/* Returns NULL on any allocation failure. */
275228753Smmstruct archive_string *
276232153Smmarchive_string_ensure(struct archive_string *as, size_t s)
277228753Smm{
278232153Smm	char *p;
279232153Smm	size_t new_length;
280232153Smm
281228753Smm	/* If buffer is already big enough, don't reallocate. */
282228753Smm	if (as->s && (s <= as->buffer_length))
283228753Smm		return (as);
284228753Smm
285228753Smm	/*
286228753Smm	 * Growing the buffer at least exponentially ensures that
287228753Smm	 * append operations are always linear in the number of
288228753Smm	 * characters appended.  Using a smaller growth rate for
289228753Smm	 * larger buffers reduces memory waste somewhat at the cost of
290228753Smm	 * a larger constant factor.
291228753Smm	 */
292228753Smm	if (as->buffer_length < 32)
293228753Smm		/* Start with a minimum 32-character buffer. */
294232153Smm		new_length = 32;
295228753Smm	else if (as->buffer_length < 8192)
296228753Smm		/* Buffers under 8k are doubled for speed. */
297232153Smm		new_length = as->buffer_length + as->buffer_length;
298228753Smm	else {
299228753Smm		/* Buffers 8k and over grow by at least 25% each time. */
300232153Smm		new_length = as->buffer_length + as->buffer_length / 4;
301232153Smm		/* Be safe: If size wraps, fail. */
302232153Smm		if (new_length < as->buffer_length) {
303232153Smm			/* On failure, wipe the string and return NULL. */
304232153Smm			archive_string_free(as);
305232153Smm			errno = ENOMEM;/* Make sure errno has ENOMEM. */
306228753Smm			return (NULL);
307228753Smm		}
308228753Smm	}
309228753Smm	/*
310228753Smm	 * The computation above is a lower limit to how much we'll
311228753Smm	 * grow the buffer.  In any case, we have to grow it enough to
312228753Smm	 * hold the request.
313228753Smm	 */
314232153Smm	if (new_length < s)
315232153Smm		new_length = s;
316228753Smm	/* Now we can reallocate the buffer. */
317232153Smm	p = (char *)realloc(as->s, new_length);
318232153Smm	if (p == NULL) {
319232153Smm		/* On failure, wipe the string and return NULL. */
320232153Smm		archive_string_free(as);
321232153Smm		errno = ENOMEM;/* Make sure errno has ENOMEM. */
322228753Smm		return (NULL);
323232153Smm	}
324232153Smm
325232153Smm	as->s = p;
326232153Smm	as->buffer_length = new_length;
327228753Smm	return (as);
328228753Smm}
329228753Smm
330232153Smm/*
331232153Smm * TODO: See if there's a way to avoid scanning
332232153Smm * the source string twice.  Then test to see
333232153Smm * if it actually helps (remember that we're almost
334232153Smm * always called with pretty short arguments, so
335232153Smm * such an optimization might not help).
336232153Smm */
337228753Smmstruct archive_string *
338232153Smmarchive_strncat(struct archive_string *as, const void *_p, size_t n)
339228753Smm{
340228753Smm	size_t s;
341228753Smm	const char *p, *pp;
342228753Smm
343228753Smm	p = (const char *)_p;
344228753Smm
345228753Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
346228753Smm	s = 0;
347228753Smm	pp = p;
348228753Smm	while (s < n && *pp) {
349228753Smm		pp++;
350228753Smm		s++;
351228753Smm	}
352232153Smm	if ((as = archive_string_append(as, p, s)) == NULL)
353232153Smm		__archive_errx(1, "Out of memory");
354232153Smm	return (as);
355228753Smm}
356228753Smm
357232153Smmstruct archive_wstring *
358232153Smmarchive_wstrncat(struct archive_wstring *as, const wchar_t *p, size_t n)
359232153Smm{
360232153Smm	size_t s;
361232153Smm	const wchar_t *pp;
362232153Smm
363232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
364232153Smm	s = 0;
365232153Smm	pp = p;
366232153Smm	while (s < n && *pp) {
367232153Smm		pp++;
368232153Smm		s++;
369232153Smm	}
370232153Smm	if ((as = archive_wstring_append(as, p, s)) == NULL)
371232153Smm		__archive_errx(1, "Out of memory");
372232153Smm	return (as);
373232153Smm}
374232153Smm
375228753Smmstruct archive_string *
376232153Smmarchive_strcat(struct archive_string *as, const void *p)
377228753Smm{
378232153Smm	/* strcat is just strncat without an effective limit.
379232153Smm	 * Assert that we'll never get called with a source
380232153Smm	 * string over 16MB.
381232153Smm	 * TODO: Review all uses of strcat in the source
382232153Smm	 * and try to replace them with strncat().
383232153Smm	 */
384232153Smm	return archive_strncat(as, p, 0x1000000);
385228753Smm}
386228753Smm
387232153Smmstruct archive_wstring *
388232153Smmarchive_wstrcat(struct archive_wstring *as, const wchar_t *p)
389232153Smm{
390232153Smm	/* Ditto. */
391232153Smm	return archive_wstrncat(as, p, 0x1000000);
392232153Smm}
393232153Smm
394232153Smmstruct archive_string *
395232153Smmarchive_strappend_char(struct archive_string *as, char c)
396232153Smm{
397232153Smm	if ((as = archive_string_append(as, &c, 1)) == NULL)
398232153Smm		__archive_errx(1, "Out of memory");
399232153Smm	return (as);
400232153Smm}
401232153Smm
402232153Smmstruct archive_wstring *
403232153Smmarchive_wstrappend_wchar(struct archive_wstring *as, wchar_t c)
404232153Smm{
405232153Smm	if ((as = archive_wstring_append(as, &c, 1)) == NULL)
406232153Smm		__archive_errx(1, "Out of memory");
407232153Smm	return (as);
408232153Smm}
409232153Smm
410228753Smm/*
411232153Smm * Get the "current character set" name to use with iconv.
412232153Smm * On FreeBSD, the empty character set name "" chooses
413232153Smm * the correct character encoding for the current locale,
414232153Smm * so this isn't necessary.
415232153Smm * But iconv on Mac OS 10.6 doesn't seem to handle this correctly;
416232153Smm * on that system, we have to explicitly call nl_langinfo()
417232153Smm * to get the right name.  Not sure about other platforms.
418232153Smm *
419232153Smm * NOTE: GNU libiconv does not recognize the character-set name
420232153Smm * which some platform nl_langinfo(CODESET) returns, so we should
421232153Smm * use locale_charset() instead of nl_langinfo(CODESET) for GNU libiconv.
422228753Smm */
423232153Smmstatic const char *
424232153Smmdefault_iconv_charset(const char *charset) {
425232153Smm	if (charset != NULL && charset[0] != '\0')
426232153Smm		return charset;
427232153Smm#if HAVE_LOCALE_CHARSET && !defined(__APPLE__)
428232153Smm	/* locale_charset() is broken on Mac OS */
429232153Smm	return locale_charset();
430232153Smm#elif HAVE_NL_LANGINFO
431232153Smm	return nl_langinfo(CODESET);
432232153Smm#else
433232153Smm	return "";
434232153Smm#endif
435232153Smm}
436232153Smm
437232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
438232153Smm
439232153Smm/*
440232153Smm * Convert MBS to WCS.
441232153Smm * Note: returns -1 if conversion fails.
442232153Smm */
443232153Smmint
444232153Smmarchive_wstring_append_from_mbs(struct archive_wstring *dest,
445232153Smm    const char *p, size_t len)
446228753Smm{
447238856Smm	return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL);
448232153Smm}
449232153Smm
450232153Smmstatic int
451232153Smmarchive_wstring_append_from_mbs_in_codepage(struct archive_wstring *dest,
452232153Smm    const char *s, size_t length, struct archive_string_conv *sc)
453232153Smm{
454232153Smm	int count, ret = 0;
455232153Smm	UINT from_cp;
456232153Smm
457232153Smm	if (sc != NULL)
458232153Smm		from_cp = sc->from_cp;
459232153Smm	else
460232153Smm		from_cp = get_current_codepage();
461232153Smm
462232153Smm	if (from_cp == CP_C_LOCALE) {
463232153Smm		/*
464353376Smm		 * "C" locale special processing.
465232153Smm		 */
466232153Smm		wchar_t *ws;
467232153Smm		const unsigned char *mp;
468232153Smm
469232153Smm		if (NULL == archive_wstring_ensure(dest,
470232153Smm		    dest->length + length + 1))
471232153Smm			return (-1);
472232153Smm
473232153Smm		ws = dest->s + dest->length;
474232153Smm		mp = (const unsigned char *)s;
475232153Smm		count = 0;
476232153Smm		while (count < (int)length && *mp) {
477232153Smm			*ws++ = (wchar_t)*mp++;
478232153Smm			count++;
479232153Smm		}
480238856Smm	} else if (sc != NULL &&
481238856Smm	    (sc->flag & (SCONV_NORMALIZATION_C | SCONV_NORMALIZATION_D))) {
482232153Smm		/*
483232153Smm		 * Normalize UTF-8 and UTF-16BE and convert it directly
484232153Smm		 * to UTF-16 as wchar_t.
485232153Smm		 */
486232153Smm		struct archive_string u16;
487232153Smm		int saved_flag = sc->flag;/* save current flag. */
488232153Smm
489232153Smm		if (is_big_endian())
490232153Smm			sc->flag |= SCONV_TO_UTF16BE;
491232153Smm		else
492232153Smm			sc->flag |= SCONV_TO_UTF16LE;
493232153Smm
494232153Smm		if (sc->flag & SCONV_FROM_UTF16) {
495232153Smm			/*
496232153Smm			 *  UTF-16BE/LE NFD ===> UTF-16 NFC
497238856Smm			 *  UTF-16BE/LE NFC ===> UTF-16 NFD
498232153Smm			 */
499248616Smm			count = (int)utf16nbytes(s, length);
500232153Smm		} else {
501232153Smm			/*
502232153Smm			 *  UTF-8 NFD ===> UTF-16 NFC
503238856Smm			 *  UTF-8 NFC ===> UTF-16 NFD
504232153Smm			 */
505248616Smm			count = (int)mbsnbytes(s, length);
506232153Smm		}
507232153Smm		u16.s = (char *)dest->s;
508232153Smm		u16.length = dest->length << 1;;
509232153Smm		u16.buffer_length = dest->buffer_length;
510238856Smm		if (sc->flag & SCONV_NORMALIZATION_C)
511238856Smm			ret = archive_string_normalize_C(&u16, s, count, sc);
512238856Smm		else
513238856Smm			ret = archive_string_normalize_D(&u16, s, count, sc);
514232153Smm		dest->s = (wchar_t *)u16.s;
515232153Smm		dest->length = u16.length >> 1;
516232153Smm		dest->buffer_length = u16.buffer_length;
517232153Smm		sc->flag = saved_flag;/* restore the saved flag. */
518232153Smm		return (ret);
519232153Smm	} else if (sc != NULL && (sc->flag & SCONV_FROM_UTF16)) {
520248616Smm		count = (int)utf16nbytes(s, length);
521232153Smm		count >>= 1; /* to be WCS length */
522232153Smm		/* Allocate memory for WCS. */
523232153Smm		if (NULL == archive_wstring_ensure(dest,
524232153Smm		    dest->length + count + 1))
525232153Smm			return (-1);
526238856Smm		wmemcpy(dest->s + dest->length, (const wchar_t *)s, count);
527232153Smm		if ((sc->flag & SCONV_FROM_UTF16BE) && !is_big_endian()) {
528232153Smm			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
529232153Smm			int b;
530232153Smm			for (b = 0; b < count; b++) {
531232153Smm				uint16_t val = archive_le16dec(u16+b);
532232153Smm				archive_be16enc(u16+b, val);
533232153Smm			}
534232153Smm		} else if ((sc->flag & SCONV_FROM_UTF16LE) && is_big_endian()) {
535232153Smm			uint16_t *u16 = (uint16_t *)(dest->s + dest->length);
536232153Smm			int b;
537232153Smm			for (b = 0; b < count; b++) {
538232153Smm				uint16_t val = archive_be16dec(u16+b);
539232153Smm				archive_le16enc(u16+b, val);
540232153Smm			}
541232153Smm		}
542232153Smm	} else {
543232153Smm		DWORD mbflag;
544238856Smm		size_t buffsize;
545232153Smm
546232153Smm		if (sc == NULL)
547232153Smm			mbflag = 0;
548232153Smm		else if (sc->flag & SCONV_FROM_CHARSET) {
549232153Smm			/* Do not trust the length which comes from
550232153Smm			 * an archive file. */
551232153Smm			length = mbsnbytes(s, length);
552232153Smm			mbflag = 0;
553232153Smm		} else
554232153Smm			mbflag = MB_PRECOMPOSED;
555232153Smm
556238856Smm		buffsize = dest->length + length + 1;
557238856Smm		do {
558238856Smm			/* Allocate memory for WCS. */
559238856Smm			if (NULL == archive_wstring_ensure(dest, buffsize))
560232153Smm				return (-1);
561238856Smm			/* Convert MBS to WCS. */
562238856Smm			count = MultiByteToWideChar(from_cp,
563248616Smm			    mbflag, s, (int)length, dest->s + dest->length,
564248616Smm			    (int)(dest->buffer_length >> 1) -1);
565238856Smm			if (count == 0 &&
566238856Smm			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
567238856Smm				/* Expand the WCS buffer. */
568238856Smm				buffsize = dest->buffer_length << 1;
569238856Smm				continue;
570232153Smm			}
571238856Smm			if (count == 0 && length != 0)
572238856Smm				ret = -1;
573302294Smm			break;
574302294Smm		} while (1);
575232153Smm	}
576232153Smm	dest->length += count;
577232153Smm	dest->s[dest->length] = L'\0';
578232153Smm	return (ret);
579232153Smm}
580232153Smm
581232153Smm#else
582232153Smm
583232153Smm/*
584232153Smm * Convert MBS to WCS.
585232153Smm * Note: returns -1 if conversion fails.
586232153Smm */
587232153Smmint
588232153Smmarchive_wstring_append_from_mbs(struct archive_wstring *dest,
589232153Smm    const char *p, size_t len)
590232153Smm{
591232153Smm	size_t r;
592238856Smm	int ret_val = 0;
593232153Smm	/*
594232153Smm	 * No single byte will be more than one wide character,
595232153Smm	 * so this length estimate will always be big enough.
596232153Smm	 */
597358088Smm	// size_t wcs_length = len;
598232153Smm	size_t mbs_length = len;
599232153Smm	const char *mbs = p;
600232153Smm	wchar_t *wcs;
601232153Smm#if HAVE_MBRTOWC
602232153Smm	mbstate_t shift_state;
603232153Smm
604232153Smm	memset(&shift_state, 0, sizeof(shift_state));
605232153Smm#endif
606358088Smm	/*
607358088Smm	 * As we decided to have wcs_length == mbs_length == len
608358088Smm	 * we can use len here instead of wcs_length
609358088Smm	 */
610358088Smm	if (NULL == archive_wstring_ensure(dest, dest->length + len + 1))
611238856Smm		return (-1);
612232153Smm	wcs = dest->s + dest->length;
613232153Smm	/*
614232153Smm	 * We cannot use mbsrtowcs/mbstowcs here because those may convert
615313570Smm	 * extra MBS when strlen(p) > len and one wide character consists of
616232153Smm	 * multi bytes.
617232153Smm	 */
618238856Smm	while (*mbs && mbs_length > 0) {
619358088Smm		/*
620358088Smm		 * The buffer we allocated is always big enough.
621358088Smm		 * Keep this code path in a comment if we decide to choose
622358088Smm		 * smaller wcs_length in the future
623358088Smm		 */
624358088Smm/*
625238856Smm		if (wcs_length == 0) {
626238856Smm			dest->length = wcs - dest->s;
627238856Smm			dest->s[dest->length] = L'\0';
628238856Smm			wcs_length = mbs_length;
629238856Smm			if (NULL == archive_wstring_ensure(dest,
630238856Smm			    dest->length + wcs_length + 1))
631238856Smm				return (-1);
632238856Smm			wcs = dest->s + dest->length;
633238856Smm		}
634358088Smm*/
635232153Smm#if HAVE_MBRTOWC
636358088Smm		r = mbrtowc(wcs, mbs, mbs_length, &shift_state);
637232153Smm#else
638358088Smm		r = mbtowc(wcs, mbs, mbs_length);
639232153Smm#endif
640232153Smm		if (r == (size_t)-1 || r == (size_t)-2) {
641238856Smm			ret_val = -1;
642358088Smm			break;
643232153Smm		}
644232153Smm		if (r == 0 || r > mbs_length)
645232153Smm			break;
646232153Smm		wcs++;
647358088Smm		// wcs_length--;
648232153Smm		mbs += r;
649232153Smm		mbs_length -= r;
650232153Smm	}
651232153Smm	dest->length = wcs - dest->s;
652232153Smm	dest->s[dest->length] = L'\0';
653238856Smm	return (ret_val);
654232153Smm}
655232153Smm
656232153Smm#endif
657232153Smm
658232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
659232153Smm
660232153Smm/*
661232153Smm * WCS ==> MBS.
662232153Smm * Note: returns -1 if conversion fails.
663232153Smm *
664232153Smm * Win32 builds use WideCharToMultiByte from the Windows API.
665232153Smm * (Maybe Cygwin should too?  WideCharToMultiByte will know a
666232153Smm * lot more about local character encodings than the wcrtomb()
667232153Smm * wrapper is going to know.)
668232153Smm */
669232153Smmint
670232153Smmarchive_string_append_from_wcs(struct archive_string *as,
671232153Smm    const wchar_t *w, size_t len)
672232153Smm{
673238856Smm	return archive_string_append_from_wcs_in_codepage(as, w, len, NULL);
674232153Smm}
675232153Smm
676232153Smmstatic int
677232153Smmarchive_string_append_from_wcs_in_codepage(struct archive_string *as,
678232153Smm    const wchar_t *ws, size_t len, struct archive_string_conv *sc)
679232153Smm{
680232153Smm	BOOL defchar_used, *dp;
681232153Smm	int count, ret = 0;
682232153Smm	UINT to_cp;
683232153Smm	int wslen = (int)len;
684232153Smm
685232153Smm	if (sc != NULL)
686232153Smm		to_cp = sc->to_cp;
687232153Smm	else
688232153Smm		to_cp = get_current_codepage();
689232153Smm
690232153Smm	if (to_cp == CP_C_LOCALE) {
691232153Smm		/*
692353376Smm		 * "C" locale special processing.
693232153Smm		 */
694232153Smm		const wchar_t *wp = ws;
695232153Smm		char *p;
696232153Smm
697232153Smm		if (NULL == archive_string_ensure(as,
698232153Smm		    as->length + wslen +1))
699232153Smm			return (-1);
700232153Smm		p = as->s + as->length;
701232153Smm		count = 0;
702232153Smm		defchar_used = 0;
703232153Smm		while (count < wslen && *wp) {
704232153Smm			if (*wp > 255) {
705232153Smm				*p++ = '?';
706232153Smm				wp++;
707232153Smm				defchar_used = 1;
708232153Smm			} else
709232153Smm				*p++ = (char)*wp++;
710232153Smm			count++;
711232153Smm		}
712232153Smm	} else if (sc != NULL && (sc->flag & SCONV_TO_UTF16)) {
713232153Smm		uint16_t *u16;
714232153Smm
715232153Smm		if (NULL ==
716232153Smm		    archive_string_ensure(as, as->length + len * 2 + 2))
717232153Smm			return (-1);
718232153Smm		u16 = (uint16_t *)(as->s + as->length);
719232153Smm		count = 0;
720232153Smm		defchar_used = 0;
721232153Smm		if (sc->flag & SCONV_TO_UTF16BE) {
722232153Smm			while (count < (int)len && *ws) {
723232153Smm				archive_be16enc(u16+count, *ws);
724232153Smm				ws++;
725232153Smm				count++;
726232153Smm			}
727232153Smm		} else {
728232153Smm			while (count < (int)len && *ws) {
729232153Smm				archive_le16enc(u16+count, *ws);
730232153Smm				ws++;
731232153Smm				count++;
732232153Smm			}
733232153Smm		}
734232153Smm		count <<= 1; /* to be byte size */
735232153Smm	} else {
736232153Smm		/* Make sure the MBS buffer has plenty to set. */
737232153Smm		if (NULL ==
738232153Smm		    archive_string_ensure(as, as->length + len * 2 + 1))
739232153Smm			return (-1);
740232153Smm		do {
741232153Smm			defchar_used = 0;
742232153Smm			if (to_cp == CP_UTF8 || sc == NULL)
743232153Smm				dp = NULL;
744232153Smm			else
745232153Smm				dp = &defchar_used;
746232153Smm			count = WideCharToMultiByte(to_cp, 0, ws, wslen,
747358088Smm			    as->s + as->length,
748358088Smm			    (int)as->buffer_length - as->length - 1, NULL, dp);
749232153Smm			if (count == 0 &&
750232153Smm			    GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
751232153Smm				/* Expand the MBS buffer and retry. */
752232153Smm				if (NULL == archive_string_ensure(as,
753232153Smm					as->buffer_length + len))
754232153Smm					return (-1);
755232153Smm				continue;
756232153Smm			}
757232153Smm			if (count == 0)
758232153Smm				ret = -1;
759299529Smm			break;
760299529Smm		} while (1);
761232153Smm	}
762232153Smm	as->length += count;
763232153Smm	as->s[as->length] = '\0';
764232153Smm	return (defchar_used?-1:ret);
765232153Smm}
766232153Smm
767232153Smm#elif defined(HAVE_WCTOMB) || defined(HAVE_WCRTOMB)
768232153Smm
769232153Smm/*
770232153Smm * Translates a wide character string into current locale character set
771232153Smm * and appends to the archive_string.  Note: returns -1 if conversion
772232153Smm * fails.
773232153Smm */
774232153Smmint
775232153Smmarchive_string_append_from_wcs(struct archive_string *as,
776232153Smm    const wchar_t *w, size_t len)
777232153Smm{
778232153Smm	/* We cannot use the standard wcstombs() here because it
779232153Smm	 * cannot tell us how big the output buffer should be.  So
780232153Smm	 * I've built a loop around wcrtomb() or wctomb() that
781232153Smm	 * converts a character at a time and resizes the string as
782232153Smm	 * needed.  We prefer wcrtomb() when it's available because
783232153Smm	 * it's thread-safe. */
784232153Smm	int n, ret_val = 0;
785228753Smm	char *p;
786232153Smm	char *end;
787232153Smm#if HAVE_WCRTOMB
788232153Smm	mbstate_t shift_state;
789228753Smm
790232153Smm	memset(&shift_state, 0, sizeof(shift_state));
791232153Smm#else
792232153Smm	/* Clear the shift state before starting. */
793232153Smm	wctomb(NULL, L'\0');
794232153Smm#endif
795228753Smm	/*
796232153Smm	 * Allocate buffer for MBS.
797232153Smm	 * We need this allocation here since it is possible that
798232153Smm	 * as->s is still NULL.
799228753Smm	 */
800232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
801238856Smm		return (-1);
802232153Smm
803232153Smm	p = as->s + as->length;
804232153Smm	end = as->s + as->buffer_length - MB_CUR_MAX -1;
805232153Smm	while (*w != L'\0' && len > 0) {
806232153Smm		if (p >= end) {
807232153Smm			as->length = p - as->s;
808232153Smm			as->s[as->length] = '\0';
809232153Smm			/* Re-allocate buffer for MBS. */
810232153Smm			if (archive_string_ensure(as,
811358088Smm			    as->length + max(len * 2,
812358088Smm			    (size_t)MB_CUR_MAX) + 1) == NULL)
813238856Smm				return (-1);
814232153Smm			p = as->s + as->length;
815232153Smm			end = as->s + as->buffer_length - MB_CUR_MAX -1;
816228753Smm		}
817232153Smm#if HAVE_WCRTOMB
818232153Smm		n = wcrtomb(p, *w++, &shift_state);
819232153Smm#else
820232153Smm		n = wctomb(p, *w++);
821232153Smm#endif
822232153Smm		if (n == -1) {
823232153Smm			if (errno == EILSEQ) {
824232153Smm				/* Skip an illegal wide char. */
825232153Smm				*p++ = '?';
826232153Smm				ret_val = -1;
827232153Smm			} else {
828232153Smm				ret_val = -1;
829232153Smm				break;
830232153Smm			}
831232153Smm		} else
832232153Smm			p += n;
833232153Smm		len--;
834232153Smm	}
835232153Smm	as->length = p - as->s;
836232153Smm	as->s[as->length] = '\0';
837232153Smm	return (ret_val);
838232153Smm}
839232153Smm
840232153Smm#else /* HAVE_WCTOMB || HAVE_WCRTOMB */
841232153Smm
842232153Smm/*
843232153Smm * TODO: Test if __STDC_ISO_10646__ is defined.
844232153Smm * Non-Windows uses ISO C wcrtomb() or wctomb() to perform the conversion
845232153Smm * one character at a time.  If a non-Windows platform doesn't have
846232153Smm * either of these, fall back to the built-in UTF8 conversion.
847232153Smm */
848232153Smmint
849232153Smmarchive_string_append_from_wcs(struct archive_string *as,
850232153Smm    const wchar_t *w, size_t len)
851232153Smm{
852232153Smm	(void)as;/* UNUSED */
853232153Smm	(void)w;/* UNUSED */
854232153Smm	(void)len;/* UNUSED */
855238856Smm	errno = ENOSYS;
856232153Smm	return (-1);
857232153Smm}
858232153Smm
859232153Smm#endif /* HAVE_WCTOMB || HAVE_WCRTOMB */
860232153Smm
861232153Smm/*
862232153Smm * Find a string conversion object by a pair of 'from' charset name
863232153Smm * and 'to' charset name from an archive object.
864232153Smm * Return NULL if not found.
865232153Smm */
866232153Smmstatic struct archive_string_conv *
867232153Smmfind_sconv_object(struct archive *a, const char *fc, const char *tc)
868232153Smm{
869232153Smm	struct archive_string_conv *sc;
870232153Smm
871232153Smm	if (a == NULL)
872232153Smm		return (NULL);
873232153Smm
874232153Smm	for (sc = a->sconv; sc != NULL; sc = sc->next) {
875232153Smm		if (strcmp(sc->from_charset, fc) == 0 &&
876232153Smm		    strcmp(sc->to_charset, tc) == 0)
877232153Smm			break;
878232153Smm	}
879232153Smm	return (sc);
880232153Smm}
881232153Smm
882232153Smm/*
883232153Smm * Register a string object to an archive object.
884232153Smm */
885232153Smmstatic void
886232153Smmadd_sconv_object(struct archive *a, struct archive_string_conv *sc)
887232153Smm{
888232153Smm	struct archive_string_conv **psc;
889232153Smm
890232153Smm	/* Add a new sconv to sconv list. */
891232153Smm	psc = &(a->sconv);
892232153Smm	while (*psc != NULL)
893232153Smm		psc = &((*psc)->next);
894232153Smm	*psc = sc;
895232153Smm}
896232153Smm
897232153Smmstatic void
898232153Smmadd_converter(struct archive_string_conv *sc, int (*converter)
899232153Smm    (struct archive_string *, const void *, size_t,
900232153Smm     struct archive_string_conv *))
901232153Smm{
902232153Smm	if (sc == NULL || sc->nconverter >= 2)
903353376Smm		__archive_errx(1, "Programming error");
904232153Smm	sc->converter[sc->nconverter++] = converter;
905232153Smm}
906232153Smm
907232153Smmstatic void
908232153Smmsetup_converter(struct archive_string_conv *sc)
909232153Smm{
910232153Smm
911232153Smm	/* Reset. */
912232153Smm	sc->nconverter = 0;
913232153Smm
914232153Smm	/*
915232153Smm	 * Perform special sequence for the incorrect UTF-8 filenames
916232153Smm	 * made by libarchive2.x.
917232153Smm	 */
918232153Smm	if (sc->flag & SCONV_UTF8_LIBARCHIVE_2) {
919232153Smm		add_converter(sc, strncat_from_utf8_libarchive2);
920232153Smm		return;
921232153Smm	}
922232153Smm
923232153Smm	/*
924232153Smm	 * Convert a string to UTF-16BE/LE.
925232153Smm	 */
926232153Smm	if (sc->flag & SCONV_TO_UTF16) {
927232153Smm		/*
928232153Smm		 * If the current locale is UTF-8, we can translate
929232153Smm		 * a UTF-8 string into a UTF-16BE string.
930232153Smm		 */
931232153Smm		if (sc->flag & SCONV_FROM_UTF8) {
932232153Smm			add_converter(sc, archive_string_append_unicode);
933232153Smm			return;
934228753Smm		}
935232153Smm
936232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
937232153Smm		if (sc->flag & SCONV_WIN_CP) {
938232153Smm			if (sc->flag & SCONV_TO_UTF16BE)
939232153Smm				add_converter(sc, win_strncat_to_utf16be);
940232153Smm			else
941232153Smm				add_converter(sc, win_strncat_to_utf16le);
942232153Smm			return;
943232153Smm		}
944232153Smm#endif
945232153Smm
946232153Smm#if defined(HAVE_ICONV)
947232153Smm		if (sc->cd != (iconv_t)-1) {
948232153Smm			add_converter(sc, iconv_strncat_in_locale);
949232153Smm			return;
950232153Smm		}
951232153Smm#endif
952232153Smm
953232153Smm		if (sc->flag & SCONV_BEST_EFFORT) {
954232153Smm			if (sc->flag & SCONV_TO_UTF16BE)
955238856Smm				add_converter(sc,
956238856Smm					best_effort_strncat_to_utf16be);
957232153Smm			else
958238856Smm				add_converter(sc,
959238856Smm					best_effort_strncat_to_utf16le);
960232153Smm		} else
961232153Smm			/* Make sure we have no converter. */
962232153Smm			sc->nconverter = 0;
963232153Smm		return;
964232153Smm	}
965232153Smm
966232153Smm	/*
967232153Smm	 * Convert a string from UTF-16BE/LE.
968232153Smm	 */
969232153Smm	if (sc->flag & SCONV_FROM_UTF16) {
970232153Smm		/*
971232153Smm		 * At least we should normalize a UTF-16BE string.
972232153Smm		 */
973232153Smm		if (sc->flag & SCONV_NORMALIZATION_D)
974232153Smm			add_converter(sc,archive_string_normalize_D);
975238856Smm		else if (sc->flag & SCONV_NORMALIZATION_C)
976232153Smm			add_converter(sc, archive_string_normalize_C);
977232153Smm
978232153Smm		if (sc->flag & SCONV_TO_UTF8) {
979232153Smm			/*
980232153Smm			 * If the current locale is UTF-8, we can translate
981232153Smm			 * a UTF-16BE/LE string into a UTF-8 string directly.
982232153Smm			 */
983232153Smm			if (!(sc->flag &
984232153Smm			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
985232153Smm				add_converter(sc,
986232153Smm				    archive_string_append_unicode);
987232153Smm			return;
988232153Smm		}
989232153Smm
990232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
991232153Smm		if (sc->flag & SCONV_WIN_CP) {
992232153Smm			if (sc->flag & SCONV_FROM_UTF16BE)
993232153Smm				add_converter(sc, win_strncat_from_utf16be);
994232153Smm			else
995232153Smm				add_converter(sc, win_strncat_from_utf16le);
996232153Smm			return;
997232153Smm		}
998232153Smm#endif
999232153Smm
1000232153Smm#if defined(HAVE_ICONV)
1001232153Smm		if (sc->cd != (iconv_t)-1) {
1002232153Smm			add_converter(sc, iconv_strncat_in_locale);
1003232153Smm			return;
1004232153Smm		}
1005232153Smm#endif
1006232153Smm
1007232153Smm		if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
1008232153Smm		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16BE))
1009232153Smm			add_converter(sc, best_effort_strncat_from_utf16be);
1010232153Smm		else if ((sc->flag & (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1011232153Smm		    == (SCONV_BEST_EFFORT | SCONV_FROM_UTF16LE))
1012232153Smm			add_converter(sc, best_effort_strncat_from_utf16le);
1013232153Smm		else
1014232153Smm			/* Make sure we have no converter. */
1015232153Smm			sc->nconverter = 0;
1016232153Smm		return;
1017232153Smm	}
1018232153Smm
1019232153Smm	if (sc->flag & SCONV_FROM_UTF8) {
1020232153Smm		/*
1021232153Smm		 * At least we should normalize a UTF-8 string.
1022232153Smm		 */
1023232153Smm		if (sc->flag & SCONV_NORMALIZATION_D)
1024232153Smm			add_converter(sc,archive_string_normalize_D);
1025238856Smm		else if (sc->flag & SCONV_NORMALIZATION_C)
1026232153Smm			add_converter(sc, archive_string_normalize_C);
1027232153Smm
1028232153Smm		/*
1029232153Smm		 * Copy UTF-8 string with a check of CESU-8.
1030232153Smm		 * Apparently, iconv does not check surrogate pairs in UTF-8
1031232153Smm		 * when both from-charset and to-charset are UTF-8, and then
1032232153Smm		 * we use our UTF-8 copy code.
1033232153Smm		 */
1034232153Smm		if (sc->flag & SCONV_TO_UTF8) {
1035232153Smm			/*
1036232153Smm			 * If the current locale is UTF-8, we can translate
1037232153Smm			 * a UTF-16BE string into a UTF-8 string directly.
1038232153Smm			 */
1039232153Smm			if (!(sc->flag &
1040232153Smm			    (SCONV_NORMALIZATION_D |SCONV_NORMALIZATION_C)))
1041232153Smm				add_converter(sc, strncat_from_utf8_to_utf8);
1042232153Smm			return;
1043232153Smm		}
1044232153Smm	}
1045232153Smm
1046232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1047232153Smm	/*
1048232153Smm	 * On Windows we can use Windows API for a string conversion.
1049232153Smm	 */
1050232153Smm	if (sc->flag & SCONV_WIN_CP) {
1051232153Smm		add_converter(sc, strncat_in_codepage);
1052232153Smm		return;
1053232153Smm	}
1054232153Smm#endif
1055232153Smm
1056232153Smm#if HAVE_ICONV
1057232153Smm	if (sc->cd != (iconv_t)-1) {
1058232153Smm		add_converter(sc, iconv_strncat_in_locale);
1059238856Smm		/*
1060238856Smm		 * iconv generally does not support UTF-8-MAC and so
1061238856Smm		 * we have to the output of iconv from NFC to NFD if
1062238856Smm		 * need.
1063238856Smm		 */
1064238856Smm		if ((sc->flag & SCONV_FROM_CHARSET) &&
1065238856Smm		    (sc->flag & SCONV_TO_UTF8)) {
1066238856Smm			if (sc->flag & SCONV_NORMALIZATION_D)
1067238856Smm				add_converter(sc, archive_string_normalize_D);
1068238856Smm		}
1069232153Smm		return;
1070232153Smm	}
1071232153Smm#endif
1072232153Smm
1073232153Smm	/*
1074232153Smm	 * Try conversion in the best effort or no conversion.
1075232153Smm	 */
1076232153Smm	if ((sc->flag & SCONV_BEST_EFFORT) || sc->same)
1077232153Smm		add_converter(sc, best_effort_strncat_in_locale);
1078232153Smm	else
1079232153Smm		/* Make sure we have no converter. */
1080232153Smm		sc->nconverter = 0;
1081232153Smm}
1082232153Smm
1083232153Smm/*
1084232153Smm * Return canonicalized charset-name but this supports just UTF-8, UTF-16BE
1085232153Smm * and CP932 which are referenced in create_sconv_object().
1086232153Smm */
1087232153Smmstatic const char *
1088232153Smmcanonical_charset_name(const char *charset)
1089232153Smm{
1090232153Smm	char cs[16];
1091232153Smm	char *p;
1092232153Smm	const char *s;
1093232153Smm
1094232153Smm	if (charset == NULL || charset[0] == '\0'
1095232153Smm	    || strlen(charset) > 15)
1096232153Smm		return (charset);
1097232153Smm
1098232153Smm	/* Copy name to uppercase. */
1099232153Smm	p = cs;
1100232153Smm	s = charset;
1101232153Smm	while (*s) {
1102232153Smm		char c = *s++;
1103232153Smm		if (c >= 'a' && c <= 'z')
1104232153Smm			c -= 'a' - 'A';
1105232153Smm		*p++ = c;
1106232153Smm	}
1107232153Smm	*p++ = '\0';
1108232153Smm
1109232153Smm	if (strcmp(cs, "UTF-8") == 0 ||
1110232153Smm	    strcmp(cs, "UTF8") == 0)
1111232153Smm		return ("UTF-8");
1112232153Smm	if (strcmp(cs, "UTF-16BE") == 0 ||
1113232153Smm	    strcmp(cs, "UTF16BE") == 0)
1114232153Smm		return ("UTF-16BE");
1115232153Smm	if (strcmp(cs, "UTF-16LE") == 0 ||
1116232153Smm	    strcmp(cs, "UTF16LE") == 0)
1117232153Smm		return ("UTF-16LE");
1118232153Smm	if (strcmp(cs, "CP932") == 0)
1119232153Smm		return ("CP932");
1120232153Smm	return (charset);
1121232153Smm}
1122232153Smm
1123232153Smm/*
1124232153Smm * Create a string conversion object.
1125232153Smm */
1126232153Smmstatic struct archive_string_conv *
1127232153Smmcreate_sconv_object(const char *fc, const char *tc,
1128232153Smm    unsigned current_codepage, int flag)
1129232153Smm{
1130232153Smm	struct archive_string_conv *sc;
1131232153Smm
1132232153Smm	sc = calloc(1, sizeof(*sc));
1133232153Smm	if (sc == NULL)
1134232153Smm		return (NULL);
1135232153Smm	sc->next = NULL;
1136232153Smm	sc->from_charset = strdup(fc);
1137232153Smm	if (sc->from_charset == NULL) {
1138232153Smm		free(sc);
1139232153Smm		return (NULL);
1140232153Smm	}
1141232153Smm	sc->to_charset = strdup(tc);
1142232153Smm	if (sc->to_charset == NULL) {
1143248616Smm		free(sc->from_charset);
1144232153Smm		free(sc);
1145232153Smm		return (NULL);
1146232153Smm	}
1147232153Smm	archive_string_init(&sc->utftmp);
1148232153Smm
1149232153Smm	if (flag & SCONV_TO_CHARSET) {
1150232153Smm		/*
1151232153Smm		 * Convert characters from the current locale charset to
1152232153Smm		 * a specified charset.
1153232153Smm		 */
1154232153Smm		sc->from_cp = current_codepage;
1155232153Smm		sc->to_cp = make_codepage_from_charset(tc);
1156232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1157232153Smm		if (IsValidCodePage(sc->to_cp))
1158232153Smm			flag |= SCONV_WIN_CP;
1159232153Smm#endif
1160232153Smm	} else if (flag & SCONV_FROM_CHARSET) {
1161232153Smm		/*
1162232153Smm		 * Convert characters from a specified charset to
1163232153Smm		 * the current locale charset.
1164232153Smm		 */
1165232153Smm		sc->to_cp = current_codepage;
1166232153Smm		sc->from_cp = make_codepage_from_charset(fc);
1167232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1168232153Smm		if (IsValidCodePage(sc->from_cp))
1169232153Smm			flag |= SCONV_WIN_CP;
1170232153Smm#endif
1171232153Smm	}
1172232153Smm
1173232153Smm	/*
1174232153Smm	 * Check if "from charset" and "to charset" are the same.
1175232153Smm	 */
1176232153Smm	if (strcmp(fc, tc) == 0 ||
1177232153Smm	    (sc->from_cp != (unsigned)-1 && sc->from_cp == sc->to_cp))
1178232153Smm		sc->same = 1;
1179232153Smm	else
1180232153Smm		sc->same = 0;
1181232153Smm
1182232153Smm	/*
1183232153Smm	 * Mark if "from charset" or "to charset" are UTF-8 or UTF-16BE/LE.
1184232153Smm	 */
1185232153Smm	if (strcmp(tc, "UTF-8") == 0)
1186232153Smm		flag |= SCONV_TO_UTF8;
1187232153Smm	else if (strcmp(tc, "UTF-16BE") == 0)
1188232153Smm		flag |= SCONV_TO_UTF16BE;
1189232153Smm	else if (strcmp(tc, "UTF-16LE") == 0)
1190232153Smm		flag |= SCONV_TO_UTF16LE;
1191232153Smm	if (strcmp(fc, "UTF-8") == 0)
1192232153Smm		flag |= SCONV_FROM_UTF8;
1193232153Smm	else if (strcmp(fc, "UTF-16BE") == 0)
1194232153Smm		flag |= SCONV_FROM_UTF16BE;
1195232153Smm	else if (strcmp(fc, "UTF-16LE") == 0)
1196232153Smm		flag |= SCONV_FROM_UTF16LE;
1197232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1198232153Smm	if (sc->to_cp == CP_UTF8)
1199232153Smm		flag |= SCONV_TO_UTF8;
1200232153Smm	else if (sc->to_cp == CP_UTF16BE)
1201232153Smm		flag |= SCONV_TO_UTF16BE | SCONV_WIN_CP;
1202232153Smm	else if (sc->to_cp == CP_UTF16LE)
1203232153Smm		flag |= SCONV_TO_UTF16LE | SCONV_WIN_CP;
1204232153Smm	if (sc->from_cp == CP_UTF8)
1205232153Smm		flag |= SCONV_FROM_UTF8;
1206232153Smm	else if (sc->from_cp == CP_UTF16BE)
1207232153Smm		flag |= SCONV_FROM_UTF16BE | SCONV_WIN_CP;
1208232153Smm	else if (sc->from_cp == CP_UTF16LE)
1209232153Smm		flag |= SCONV_FROM_UTF16LE | SCONV_WIN_CP;
1210232153Smm#endif
1211232153Smm
1212232153Smm	/*
1213232153Smm	 * Set a flag for Unicode NFD. Usually iconv cannot correctly
1214232153Smm	 * handle it. So we have to translate NFD characters to NFC ones
1215232153Smm	 * ourselves before iconv handles. Another reason is to prevent
1216232153Smm	 * that the same sight of two filenames, one is NFC and other
1217232153Smm	 * is NFD, would be in its directory.
1218232153Smm	 * On Mac OS X, although its filesystem layer automatically
1219232153Smm	 * convert filenames to NFD, it would be useful for filename
1220232153Smm	 * comparing to find out the same filenames that we normalize
1221232153Smm	 * that to be NFD ourselves.
1222232153Smm	 */
1223232153Smm	if ((flag & SCONV_FROM_CHARSET) &&
1224232153Smm	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8))) {
1225232153Smm#if defined(__APPLE__)
1226238856Smm		if (flag & SCONV_TO_UTF8)
1227238856Smm			flag |= SCONV_NORMALIZATION_D;
1228238856Smm		else
1229232153Smm#endif
1230232153Smm			flag |= SCONV_NORMALIZATION_C;
1231232153Smm	}
1232238856Smm#if defined(__APPLE__)
1233238856Smm	/*
1234238856Smm	 * In case writing an archive file, make sure that a filename
1235238856Smm	 * going to be passed to iconv is a Unicode NFC string since
1236238856Smm	 * a filename in HFS Plus filesystem is a Unicode NFD one and
1237238856Smm	 * iconv cannot handle it with "UTF-8" charset. It is simpler
1238238856Smm	 * than a use of "UTF-8-MAC" charset.
1239238856Smm	 */
1240238856Smm	if ((flag & SCONV_TO_CHARSET) &&
1241238856Smm	    (flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1242238856Smm	    !(flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1243238856Smm		flag |= SCONV_NORMALIZATION_C;
1244238856Smm	/*
1245238856Smm	 * In case reading an archive file. make sure that a filename
1246238856Smm	 * will be passed to users is a Unicode NFD string in order to
1247238856Smm	 * correctly compare the filename with other one which comes
1248238856Smm	 * from HFS Plus filesystem.
1249238856Smm	 */
1250238856Smm	if ((flag & SCONV_FROM_CHARSET) &&
1251238856Smm	   !(flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1252238856Smm	    (flag & SCONV_TO_UTF8))
1253238856Smm		flag |= SCONV_NORMALIZATION_D;
1254238856Smm#endif
1255232153Smm
1256232153Smm#if defined(HAVE_ICONV)
1257232153Smm	sc->cd_w = (iconv_t)-1;
1258232153Smm	/*
1259232153Smm	 * Create an iconv object.
1260232153Smm	 */
1261232153Smm	if (((flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) &&
1262232153Smm	    (flag & (SCONV_FROM_UTF8 | SCONV_FROM_UTF16))) ||
1263232153Smm	    (flag & SCONV_WIN_CP)) {
1264232153Smm		/* This case we won't use iconv. */
1265232153Smm		sc->cd = (iconv_t)-1;
1266232153Smm	} else {
1267232153Smm		sc->cd = iconv_open(tc, fc);
1268232153Smm		if (sc->cd == (iconv_t)-1 && (sc->flag & SCONV_BEST_EFFORT)) {
1269232153Smm			/*
1270313570Smm			 * Unfortunately, all of iconv implements do support
1271232153Smm			 * "CP932" character-set, so we should use "SJIS"
1272232153Smm			 * instead if iconv_open failed.
1273232153Smm			 */
1274232153Smm			if (strcmp(tc, "CP932") == 0)
1275232153Smm				sc->cd = iconv_open("SJIS", fc);
1276232153Smm			else if (strcmp(fc, "CP932") == 0)
1277232153Smm				sc->cd = iconv_open(tc, "SJIS");
1278232153Smm		}
1279232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1280232153Smm		/*
1281232153Smm		 * archive_mstring on Windows directly convert multi-bytes
1282232153Smm		 * into archive_wstring in order not to depend on locale
1283313570Smm		 * so that you can do a I18N programming. This will be
1284232153Smm		 * used only in archive_mstring_copy_mbs_len_l so far.
1285232153Smm		 */
1286232153Smm		if (flag & SCONV_FROM_CHARSET) {
1287232153Smm			sc->cd_w = iconv_open("UTF-8", fc);
1288232153Smm			if (sc->cd_w == (iconv_t)-1 &&
1289232153Smm			    (sc->flag & SCONV_BEST_EFFORT)) {
1290232153Smm				if (strcmp(fc, "CP932") == 0)
1291232153Smm					sc->cd_w = iconv_open("UTF-8", "SJIS");
1292232153Smm			}
1293232153Smm		}
1294232153Smm#endif /* _WIN32 && !__CYGWIN__ */
1295232153Smm	}
1296232153Smm#endif	/* HAVE_ICONV */
1297232153Smm
1298232153Smm	sc->flag = flag;
1299232153Smm
1300232153Smm	/*
1301238856Smm	 * Set up converters.
1302232153Smm	 */
1303232153Smm	setup_converter(sc);
1304232153Smm
1305232153Smm	return (sc);
1306232153Smm}
1307232153Smm
1308232153Smm/*
1309232153Smm * Free a string conversion object.
1310232153Smm */
1311232153Smmstatic void
1312232153Smmfree_sconv_object(struct archive_string_conv *sc)
1313232153Smm{
1314232153Smm	free(sc->from_charset);
1315232153Smm	free(sc->to_charset);
1316232153Smm	archive_string_free(&sc->utftmp);
1317232153Smm#if HAVE_ICONV
1318232153Smm	if (sc->cd != (iconv_t)-1)
1319232153Smm		iconv_close(sc->cd);
1320232153Smm	if (sc->cd_w != (iconv_t)-1)
1321232153Smm		iconv_close(sc->cd_w);
1322232153Smm#endif
1323232153Smm	free(sc);
1324232153Smm}
1325232153Smm
1326232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1327232153Smmstatic unsigned
1328232153Smmmy_atoi(const char *p)
1329232153Smm{
1330232153Smm	unsigned cp;
1331232153Smm
1332232153Smm	cp = 0;
1333232153Smm	while (*p) {
1334232153Smm		if (*p >= '0' && *p <= '9')
1335232153Smm			cp = cp * 10 + (*p - '0');
1336232153Smm		else
1337232153Smm			return (-1);
1338232153Smm		p++;
1339232153Smm	}
1340232153Smm	return (cp);
1341232153Smm}
1342232153Smm
1343232153Smm/*
1344232153Smm * Translate Charset name (as used by iconv) into CodePage (as used by Windows)
1345232153Smm * Return -1 if failed.
1346232153Smm *
1347232153Smm * Note: This translation code may be insufficient.
1348232153Smm */
1349232153Smmstatic struct charset {
1350232153Smm	const char *name;
1351232153Smm	unsigned cp;
1352232153Smm} charsets[] = {
1353232153Smm	/* MUST BE SORTED! */
1354232153Smm	{"ASCII", 1252},
1355232153Smm	{"ASMO-708", 708},
1356232153Smm	{"BIG5", 950},
1357232153Smm	{"CHINESE", 936},
1358232153Smm	{"CP367", 1252},
1359232153Smm	{"CP819", 1252},
1360232153Smm	{"CP1025", 21025},
1361232153Smm	{"DOS-720", 720},
1362232153Smm	{"DOS-862", 862},
1363232153Smm	{"EUC-CN", 51936},
1364232153Smm	{"EUC-JP", 51932},
1365232153Smm	{"EUC-KR", 949},
1366232153Smm	{"EUCCN", 51936},
1367232153Smm	{"EUCJP", 51932},
1368232153Smm	{"EUCKR", 949},
1369232153Smm	{"GB18030", 54936},
1370232153Smm	{"GB2312", 936},
1371232153Smm	{"HEBREW", 1255},
1372232153Smm	{"HZ-GB-2312", 52936},
1373232153Smm	{"IBM273", 20273},
1374232153Smm	{"IBM277", 20277},
1375232153Smm	{"IBM278", 20278},
1376232153Smm	{"IBM280", 20280},
1377232153Smm	{"IBM284", 20284},
1378232153Smm	{"IBM285", 20285},
1379232153Smm	{"IBM290", 20290},
1380232153Smm	{"IBM297", 20297},
1381232153Smm	{"IBM367", 1252},
1382232153Smm	{"IBM420", 20420},
1383232153Smm	{"IBM423", 20423},
1384232153Smm	{"IBM424", 20424},
1385232153Smm	{"IBM819", 1252},
1386232153Smm	{"IBM871", 20871},
1387232153Smm	{"IBM880", 20880},
1388232153Smm	{"IBM905", 20905},
1389232153Smm	{"IBM924", 20924},
1390232153Smm	{"ISO-8859-1", 28591},
1391232153Smm	{"ISO-8859-13", 28603},
1392232153Smm	{"ISO-8859-15", 28605},
1393232153Smm	{"ISO-8859-2", 28592},
1394232153Smm	{"ISO-8859-3", 28593},
1395232153Smm	{"ISO-8859-4", 28594},
1396232153Smm	{"ISO-8859-5", 28595},
1397232153Smm	{"ISO-8859-6", 28596},
1398232153Smm	{"ISO-8859-7", 28597},
1399232153Smm	{"ISO-8859-8", 28598},
1400232153Smm	{"ISO-8859-9", 28599},
1401232153Smm	{"ISO8859-1", 28591},
1402232153Smm	{"ISO8859-13", 28603},
1403232153Smm	{"ISO8859-15", 28605},
1404232153Smm	{"ISO8859-2", 28592},
1405232153Smm	{"ISO8859-3", 28593},
1406232153Smm	{"ISO8859-4", 28594},
1407232153Smm	{"ISO8859-5", 28595},
1408232153Smm	{"ISO8859-6", 28596},
1409232153Smm	{"ISO8859-7", 28597},
1410232153Smm	{"ISO8859-8", 28598},
1411232153Smm	{"ISO8859-9", 28599},
1412232153Smm	{"JOHAB", 1361},
1413232153Smm	{"KOI8-R", 20866},
1414232153Smm	{"KOI8-U", 21866},
1415232153Smm	{"KS_C_5601-1987", 949},
1416232153Smm	{"LATIN1", 1252},
1417232153Smm	{"LATIN2", 28592},
1418232153Smm	{"MACINTOSH", 10000},
1419232153Smm	{"SHIFT-JIS", 932},
1420232153Smm	{"SHIFT_JIS", 932},
1421232153Smm	{"SJIS", 932},
1422232153Smm	{"US", 1252},
1423232153Smm	{"US-ASCII", 1252},
1424232153Smm	{"UTF-16", 1200},
1425232153Smm	{"UTF-16BE", 1201},
1426232153Smm	{"UTF-16LE", 1200},
1427232153Smm	{"UTF-8", CP_UTF8},
1428232153Smm	{"X-EUROPA", 29001},
1429232153Smm	{"X-MAC-ARABIC", 10004},
1430232153Smm	{"X-MAC-CE", 10029},
1431232153Smm	{"X-MAC-CHINESEIMP", 10008},
1432232153Smm	{"X-MAC-CHINESETRAD", 10002},
1433232153Smm	{"X-MAC-CROATIAN", 10082},
1434232153Smm	{"X-MAC-CYRILLIC", 10007},
1435232153Smm	{"X-MAC-GREEK", 10006},
1436232153Smm	{"X-MAC-HEBREW", 10005},
1437232153Smm	{"X-MAC-ICELANDIC", 10079},
1438232153Smm	{"X-MAC-JAPANESE", 10001},
1439232153Smm	{"X-MAC-KOREAN", 10003},
1440232153Smm	{"X-MAC-ROMANIAN", 10010},
1441232153Smm	{"X-MAC-THAI", 10021},
1442232153Smm	{"X-MAC-TURKISH", 10081},
1443232153Smm	{"X-MAC-UKRAINIAN", 10017},
1444232153Smm};
1445232153Smmstatic unsigned
1446232153Smmmake_codepage_from_charset(const char *charset)
1447232153Smm{
1448232153Smm	char cs[16];
1449232153Smm	char *p;
1450232153Smm	unsigned cp;
1451232153Smm	int a, b;
1452232153Smm
1453232153Smm	if (charset == NULL || strlen(charset) > 15)
1454232153Smm		return -1;
1455232153Smm
1456232153Smm	/* Copy name to uppercase. */
1457232153Smm	p = cs;
1458232153Smm	while (*charset) {
1459232153Smm		char c = *charset++;
1460232153Smm		if (c >= 'a' && c <= 'z')
1461232153Smm			c -= 'a' - 'A';
1462232153Smm		*p++ = c;
1463232153Smm	}
1464232153Smm	*p++ = '\0';
1465232153Smm	cp = -1;
1466232153Smm
1467232153Smm	/* Look it up in the table first, so that we can easily
1468232153Smm	 * override CP367, which we map to 1252 instead of 367. */
1469232153Smm	a = 0;
1470232153Smm	b = sizeof(charsets)/sizeof(charsets[0]);
1471232153Smm	while (b > a) {
1472232153Smm		int c = (b + a) / 2;
1473232153Smm		int r = strcmp(charsets[c].name, cs);
1474232153Smm		if (r < 0)
1475232153Smm			a = c + 1;
1476232153Smm		else if (r > 0)
1477232153Smm			b = c;
1478232153Smm		else
1479232153Smm			return charsets[c].cp;
1480232153Smm	}
1481232153Smm
1482232153Smm	/* If it's not in the table, try to parse it. */
1483232153Smm	switch (*cs) {
1484232153Smm	case 'C':
1485232153Smm		if (cs[1] == 'P' && cs[2] >= '0' && cs[2] <= '9') {
1486232153Smm			cp = my_atoi(cs + 2);
1487232153Smm		} else if (strcmp(cs, "CP_ACP") == 0)
1488232153Smm			cp = get_current_codepage();
1489232153Smm		else if (strcmp(cs, "CP_OEMCP") == 0)
1490232153Smm			cp = get_current_oemcp();
1491232153Smm		break;
1492232153Smm	case 'I':
1493232153Smm		if (cs[1] == 'B' && cs[2] == 'M' &&
1494232153Smm		    cs[3] >= '0' && cs[3] <= '9') {
1495232153Smm			cp = my_atoi(cs + 3);
1496232153Smm		}
1497232153Smm		break;
1498232153Smm	case 'W':
1499232153Smm		if (strncmp(cs, "WINDOWS-", 8) == 0) {
1500232153Smm			cp = my_atoi(cs + 8);
1501232153Smm			if (cp != 874 && (cp < 1250 || cp > 1258))
1502232153Smm				cp = -1;/* This may invalid code. */
1503232153Smm		}
1504232153Smm		break;
1505232153Smm	}
1506232153Smm	return (cp);
1507232153Smm}
1508232153Smm
1509232153Smm/*
1510232153Smm * Return ANSI Code Page of current locale set by setlocale().
1511232153Smm */
1512232153Smmstatic unsigned
1513232153Smmget_current_codepage(void)
1514232153Smm{
1515232153Smm	char *locale, *p;
1516232153Smm	unsigned cp;
1517232153Smm
1518232153Smm	locale = setlocale(LC_CTYPE, NULL);
1519232153Smm	if (locale == NULL)
1520232153Smm		return (GetACP());
1521232153Smm	if (locale[0] == 'C' && locale[1] == '\0')
1522232153Smm		return (CP_C_LOCALE);
1523232153Smm	p = strrchr(locale, '.');
1524232153Smm	if (p == NULL)
1525232153Smm		return (GetACP());
1526346104Smm	if (strcmp(p+1, "utf8") == 0)
1527346104Smm		return CP_UTF8;
1528232153Smm	cp = my_atoi(p+1);
1529346104Smm	if ((int)cp <= 0)
1530232153Smm		return (GetACP());
1531232153Smm	return (cp);
1532232153Smm}
1533232153Smm
1534232153Smm/*
1535232153Smm * Translation table between Locale Name and ACP/OEMCP.
1536232153Smm */
1537232153Smmstatic struct {
1538232153Smm	unsigned acp;
1539232153Smm	unsigned ocp;
1540232153Smm	const char *locale;
1541232153Smm} acp_ocp_map[] = {
1542232153Smm	{  950,  950, "Chinese_Taiwan" },
1543232153Smm	{  936,  936, "Chinese_People's Republic of China" },
1544232153Smm	{  950,  950, "Chinese_Taiwan" },
1545232153Smm	{ 1250,  852, "Czech_Czech Republic" },
1546232153Smm	{ 1252,  850, "Danish_Denmark" },
1547232153Smm	{ 1252,  850, "Dutch_Netherlands" },
1548232153Smm	{ 1252,  850, "Dutch_Belgium" },
1549232153Smm	{ 1252,  437, "English_United States" },
1550232153Smm	{ 1252,  850, "English_Australia" },
1551232153Smm	{ 1252,  850, "English_Canada" },
1552232153Smm	{ 1252,  850, "English_New Zealand" },
1553232153Smm	{ 1252,  850, "English_United Kingdom" },
1554232153Smm	{ 1252,  437, "English_United States" },
1555232153Smm	{ 1252,  850, "Finnish_Finland" },
1556232153Smm	{ 1252,  850, "French_France" },
1557232153Smm	{ 1252,  850, "French_Belgium" },
1558232153Smm	{ 1252,  850, "French_Canada" },
1559232153Smm	{ 1252,  850, "French_Switzerland" },
1560232153Smm	{ 1252,  850, "German_Germany" },
1561232153Smm	{ 1252,  850, "German_Austria" },
1562232153Smm	{ 1252,  850, "German_Switzerland" },
1563232153Smm	{ 1253,  737, "Greek_Greece" },
1564232153Smm	{ 1250,  852, "Hungarian_Hungary" },
1565232153Smm	{ 1252,  850, "Icelandic_Iceland" },
1566232153Smm	{ 1252,  850, "Italian_Italy" },
1567232153Smm	{ 1252,  850, "Italian_Switzerland" },
1568232153Smm	{  932,  932, "Japanese_Japan" },
1569232153Smm	{  949,  949, "Korean_Korea" },
1570232153Smm	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
1571232153Smm	{ 1252,  850, "Norwegian (BokmOl)_Norway" },
1572232153Smm	{ 1252,  850, "Norwegian-Nynorsk_Norway" },
1573232153Smm	{ 1250,  852, "Polish_Poland" },
1574232153Smm	{ 1252,  850, "Portuguese_Portugal" },
1575232153Smm	{ 1252,  850, "Portuguese_Brazil" },
1576232153Smm	{ 1251,  866, "Russian_Russia" },
1577232153Smm	{ 1250,  852, "Slovak_Slovakia" },
1578232153Smm	{ 1252,  850, "Spanish_Spain" },
1579232153Smm	{ 1252,  850, "Spanish_Mexico" },
1580232153Smm	{ 1252,  850, "Spanish_Spain" },
1581232153Smm	{ 1252,  850, "Swedish_Sweden" },
1582232153Smm	{ 1254,  857, "Turkish_Turkey" },
1583232153Smm	{ 0, 0, NULL}
1584232153Smm};
1585232153Smm
1586232153Smm/*
1587232153Smm * Return OEM Code Page of current locale set by setlocale().
1588232153Smm */
1589232153Smmstatic unsigned
1590232153Smmget_current_oemcp(void)
1591232153Smm{
1592232153Smm	int i;
1593232153Smm	char *locale, *p;
1594232153Smm	size_t len;
1595232153Smm
1596232153Smm	locale = setlocale(LC_CTYPE, NULL);
1597232153Smm	if (locale == NULL)
1598232153Smm		return (GetOEMCP());
1599232153Smm	if (locale[0] == 'C' && locale[1] == '\0')
1600232153Smm		return (CP_C_LOCALE);
1601232153Smm
1602232153Smm	p = strrchr(locale, '.');
1603232153Smm	if (p == NULL)
1604232153Smm		return (GetOEMCP());
1605232153Smm	len = p - locale;
1606232153Smm	for (i = 0; acp_ocp_map[i].acp; i++) {
1607232153Smm		if (strncmp(acp_ocp_map[i].locale, locale, len) == 0)
1608232153Smm			return (acp_ocp_map[i].ocp);
1609232153Smm	}
1610232153Smm	return (GetOEMCP());
1611232153Smm}
1612232153Smm#else
1613232153Smm
1614232153Smm/*
1615232153Smm * POSIX platform does not use CodePage.
1616232153Smm */
1617232153Smm
1618232153Smmstatic unsigned
1619232153Smmget_current_codepage(void)
1620232153Smm{
1621232153Smm	return (-1);/* Unknown */
1622232153Smm}
1623232153Smmstatic unsigned
1624232153Smmmake_codepage_from_charset(const char *charset)
1625232153Smm{
1626232153Smm	(void)charset; /* UNUSED */
1627232153Smm	return (-1);/* Unknown */
1628232153Smm}
1629232153Smmstatic unsigned
1630232153Smmget_current_oemcp(void)
1631232153Smm{
1632232153Smm	return (-1);/* Unknown */
1633232153Smm}
1634232153Smm
1635232153Smm#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
1636232153Smm
1637232153Smm/*
1638232153Smm * Return a string conversion object.
1639232153Smm */
1640232153Smmstatic struct archive_string_conv *
1641232153Smmget_sconv_object(struct archive *a, const char *fc, const char *tc, int flag)
1642232153Smm{
1643232153Smm	struct archive_string_conv *sc;
1644232153Smm	unsigned current_codepage;
1645232153Smm
1646232153Smm	/* Check if we have made the sconv object. */
1647232153Smm	sc = find_sconv_object(a, fc, tc);
1648232153Smm	if (sc != NULL)
1649232153Smm		return (sc);
1650232153Smm
1651232153Smm	if (a == NULL)
1652232153Smm		current_codepage = get_current_codepage();
1653232153Smm	else
1654232153Smm		current_codepage = a->current_codepage;
1655232153Smm
1656232153Smm	sc = create_sconv_object(canonical_charset_name(fc),
1657232153Smm	    canonical_charset_name(tc), current_codepage, flag);
1658232153Smm	if (sc == NULL) {
1659232153Smm		if (a != NULL)
1660232153Smm			archive_set_error(a, ENOMEM,
1661232153Smm			    "Could not allocate memory for "
1662232153Smm			    "a string conversion object");
1663232153Smm		return (NULL);
1664232153Smm	}
1665232153Smm
1666232153Smm	/*
1667232153Smm	 * If there is no converter for current string conversion object,
1668232153Smm	 * we cannot handle this conversion.
1669232153Smm	 */
1670232153Smm	if (sc->nconverter == 0) {
1671232153Smm		if (a != NULL) {
1672232153Smm#if HAVE_ICONV
1673232153Smm			archive_set_error(a, ARCHIVE_ERRNO_MISC,
1674232153Smm			    "iconv_open failed : Cannot handle ``%s''",
1675232153Smm			    (flag & SCONV_TO_CHARSET)?tc:fc);
1676232153Smm#else
1677232153Smm			archive_set_error(a, ARCHIVE_ERRNO_MISC,
1678232153Smm			    "A character-set conversion not fully supported "
1679232153Smm			    "on this platform");
1680232153Smm#endif
1681232153Smm		}
1682232153Smm		/* Failed; free a sconv object. */
1683232153Smm		free_sconv_object(sc);
1684232153Smm		return (NULL);
1685232153Smm	}
1686232153Smm
1687232153Smm	/*
1688232153Smm	 * Success!
1689232153Smm	 */
1690232153Smm	if (a != NULL)
1691232153Smm		add_sconv_object(a, sc);
1692232153Smm	return (sc);
1693232153Smm}
1694232153Smm
1695232153Smmstatic const char *
1696232153Smmget_current_charset(struct archive *a)
1697232153Smm{
1698232153Smm	const char *cur_charset;
1699232153Smm
1700232153Smm	if (a == NULL)
1701232153Smm		cur_charset = default_iconv_charset("");
1702232153Smm	else {
1703232153Smm		cur_charset = default_iconv_charset(a->current_code);
1704232153Smm		if (a->current_code == NULL) {
1705232153Smm			a->current_code = strdup(cur_charset);
1706232153Smm			a->current_codepage = get_current_codepage();
1707232153Smm			a->current_oemcp = get_current_oemcp();
1708232153Smm		}
1709232153Smm	}
1710232153Smm	return (cur_charset);
1711232153Smm}
1712232153Smm
1713232153Smm/*
1714232153Smm * Make and Return a string conversion object.
1715232153Smm * Return NULL if the platform does not support the specified conversion
1716232153Smm * and best_effort is 0.
1717232153Smm * If best_effort is set, A string conversion object must be returned
1718232153Smm * unless memory allocation for the object fails, but the conversion
1719232153Smm * might fail when non-ASCII code is found.
1720232153Smm */
1721232153Smmstruct archive_string_conv *
1722232153Smmarchive_string_conversion_to_charset(struct archive *a, const char *charset,
1723232153Smm    int best_effort)
1724232153Smm{
1725232153Smm	int flag = SCONV_TO_CHARSET;
1726232153Smm
1727232153Smm	if (best_effort)
1728232153Smm		flag |= SCONV_BEST_EFFORT;
1729232153Smm	return (get_sconv_object(a, get_current_charset(a), charset, flag));
1730232153Smm}
1731232153Smm
1732232153Smmstruct archive_string_conv *
1733232153Smmarchive_string_conversion_from_charset(struct archive *a, const char *charset,
1734232153Smm    int best_effort)
1735232153Smm{
1736232153Smm	int flag = SCONV_FROM_CHARSET;
1737232153Smm
1738232153Smm	if (best_effort)
1739232153Smm		flag |= SCONV_BEST_EFFORT;
1740232153Smm	return (get_sconv_object(a, charset, get_current_charset(a), flag));
1741232153Smm}
1742232153Smm
1743232153Smm/*
1744232153Smm * archive_string_default_conversion_*_archive() are provided for Windows
1745232153Smm * platform because other archiver application use CP_OEMCP for
1746232153Smm * MultiByteToWideChar() and WideCharToMultiByte() for the filenames
1747232153Smm * in tar or zip files. But mbstowcs/wcstombs(CRT) usually use CP_ACP
1748232153Smm * unless you use setlocale(LC_ALL, ".OCP")(specify CP_OEMCP).
1749232153Smm * So we should make a string conversion between CP_ACP and CP_OEMCP
1750313570Smm * for compatibility.
1751232153Smm */
1752232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1753232153Smmstruct archive_string_conv *
1754232153Smmarchive_string_default_conversion_for_read(struct archive *a)
1755232153Smm{
1756232153Smm	const char *cur_charset = get_current_charset(a);
1757232153Smm	char oemcp[16];
1758232153Smm
1759232153Smm	/* NOTE: a check of cur_charset is unneeded but we need
1760232153Smm	 * that get_current_charset() has been surely called at
1761232153Smm	 * this time whatever C compiler optimized. */
1762232153Smm	if (cur_charset != NULL &&
1763232153Smm	    (a->current_codepage == CP_C_LOCALE ||
1764232153Smm	     a->current_codepage == a->current_oemcp))
1765232153Smm		return (NULL);/* no conversion. */
1766232153Smm
1767232153Smm	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1768232153Smm	/* Make sure a null termination must be set. */
1769232153Smm	oemcp[sizeof(oemcp)-1] = '\0';
1770232153Smm	return (get_sconv_object(a, oemcp, cur_charset,
1771232153Smm	    SCONV_FROM_CHARSET));
1772232153Smm}
1773232153Smm
1774232153Smmstruct archive_string_conv *
1775232153Smmarchive_string_default_conversion_for_write(struct archive *a)
1776232153Smm{
1777232153Smm	const char *cur_charset = get_current_charset(a);
1778232153Smm	char oemcp[16];
1779232153Smm
1780232153Smm	/* NOTE: a check of cur_charset is unneeded but we need
1781232153Smm	 * that get_current_charset() has been surely called at
1782232153Smm	 * this time whatever C compiler optimized. */
1783232153Smm	if (cur_charset != NULL &&
1784232153Smm	    (a->current_codepage == CP_C_LOCALE ||
1785232153Smm	     a->current_codepage == a->current_oemcp))
1786232153Smm		return (NULL);/* no conversion. */
1787232153Smm
1788232153Smm	_snprintf(oemcp, sizeof(oemcp)-1, "CP%d", a->current_oemcp);
1789232153Smm	/* Make sure a null termination must be set. */
1790232153Smm	oemcp[sizeof(oemcp)-1] = '\0';
1791232153Smm	return (get_sconv_object(a, cur_charset, oemcp,
1792232153Smm	    SCONV_TO_CHARSET));
1793232153Smm}
1794232153Smm#else
1795232153Smmstruct archive_string_conv *
1796232153Smmarchive_string_default_conversion_for_read(struct archive *a)
1797232153Smm{
1798232153Smm	(void)a; /* UNUSED */
1799232153Smm	return (NULL);
1800232153Smm}
1801232153Smm
1802232153Smmstruct archive_string_conv *
1803232153Smmarchive_string_default_conversion_for_write(struct archive *a)
1804232153Smm{
1805232153Smm	(void)a; /* UNUSED */
1806232153Smm	return (NULL);
1807232153Smm}
1808232153Smm#endif
1809232153Smm
1810232153Smm/*
1811232153Smm * Dispose of all character conversion objects in the archive object.
1812232153Smm */
1813232153Smmvoid
1814232153Smmarchive_string_conversion_free(struct archive *a)
1815232153Smm{
1816232153Smm	struct archive_string_conv *sc;
1817232153Smm	struct archive_string_conv *sc_next;
1818232153Smm
1819232153Smm	for (sc = a->sconv; sc != NULL; sc = sc_next) {
1820232153Smm		sc_next = sc->next;
1821232153Smm		free_sconv_object(sc);
1822232153Smm	}
1823232153Smm	a->sconv = NULL;
1824232153Smm	free(a->current_code);
1825232153Smm	a->current_code = NULL;
1826232153Smm}
1827232153Smm
1828232153Smm/*
1829232153Smm * Return a conversion charset name.
1830232153Smm */
1831232153Smmconst char *
1832232153Smmarchive_string_conversion_charset_name(struct archive_string_conv *sc)
1833232153Smm{
1834232153Smm	if (sc->flag & SCONV_TO_CHARSET)
1835232153Smm		return (sc->to_charset);
1836232153Smm	else
1837232153Smm		return (sc->from_charset);
1838232153Smm}
1839232153Smm
1840232153Smm/*
1841232153Smm * Change the behavior of a string conversion.
1842232153Smm */
1843232153Smmvoid
1844232153Smmarchive_string_conversion_set_opt(struct archive_string_conv *sc, int opt)
1845232153Smm{
1846232153Smm	switch (opt) {
1847232153Smm	/*
1848232153Smm	 * A filename in UTF-8 was made with libarchive 2.x in a wrong
1849232153Smm	 * assumption that wchar_t was Unicode.
1850232153Smm	 * This option enables simulating the assumption in order to read
1851311041Smm	 * that filename correctly.
1852232153Smm	 */
1853232153Smm	case SCONV_SET_OPT_UTF8_LIBARCHIVE2X:
1854232153Smm#if (defined(_WIN32) && !defined(__CYGWIN__)) \
1855232153Smm	 || defined(__STDC_ISO_10646__) || defined(__APPLE__)
1856232153Smm		/*
1857232153Smm		 * Nothing to do for it since wchar_t on these platforms
1858232153Smm		 * is really Unicode.
1859232153Smm		 */
1860232153Smm		(void)sc; /* UNUSED */
1861232153Smm#else
1862232153Smm		if ((sc->flag & SCONV_UTF8_LIBARCHIVE_2) == 0) {
1863232153Smm			sc->flag |= SCONV_UTF8_LIBARCHIVE_2;
1864238856Smm			/* Set up string converters. */
1865232153Smm			setup_converter(sc);
1866232153Smm		}
1867232153Smm#endif
1868232153Smm		break;
1869238856Smm	case SCONV_SET_OPT_NORMALIZATION_C:
1870238856Smm		if ((sc->flag & SCONV_NORMALIZATION_C) == 0) {
1871238856Smm			sc->flag |= SCONV_NORMALIZATION_C;
1872238856Smm			sc->flag &= ~SCONV_NORMALIZATION_D;
1873238856Smm			/* Set up string converters. */
1874238856Smm			setup_converter(sc);
1875238856Smm		}
1876238856Smm		break;
1877238856Smm	case SCONV_SET_OPT_NORMALIZATION_D:
1878238856Smm#if defined(HAVE_ICONV)
1879238856Smm		/*
1880238856Smm		 * If iconv will take the string, do not change the
1881238856Smm		 * setting of the normalization.
1882238856Smm		 */
1883238856Smm		if (!(sc->flag & SCONV_WIN_CP) &&
1884238856Smm		     (sc->flag & (SCONV_FROM_UTF16 | SCONV_FROM_UTF8)) &&
1885238856Smm		    !(sc->flag & (SCONV_TO_UTF16 | SCONV_TO_UTF8)))
1886238856Smm			break;
1887238856Smm#endif
1888238856Smm		if ((sc->flag & SCONV_NORMALIZATION_D) == 0) {
1889238856Smm			sc->flag |= SCONV_NORMALIZATION_D;
1890238856Smm			sc->flag &= ~SCONV_NORMALIZATION_C;
1891238856Smm			/* Set up string converters. */
1892238856Smm			setup_converter(sc);
1893238856Smm		}
1894238856Smm		break;
1895232153Smm	default:
1896232153Smm		break;
1897232153Smm	}
1898232153Smm}
1899232153Smm
1900232153Smm/*
1901232153Smm *
1902232153Smm * Copy one archive_string to another in locale conversion.
1903232153Smm *
1904238856Smm *	archive_strncat_l();
1905238856Smm *	archive_strncpy_l();
1906232153Smm *
1907232153Smm */
1908232153Smm
1909232153Smmstatic size_t
1910232153Smmmbsnbytes(const void *_p, size_t n)
1911232153Smm{
1912232153Smm	size_t s;
1913232153Smm	const char *p, *pp;
1914232153Smm
1915232153Smm	if (_p == NULL)
1916232153Smm		return (0);
1917232153Smm	p = (const char *)_p;
1918232153Smm
1919232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
1920232153Smm	s = 0;
1921232153Smm	pp = p;
1922232153Smm	while (s < n && *pp) {
1923232153Smm		pp++;
1924232153Smm		s++;
1925232153Smm	}
1926232153Smm	return (s);
1927232153Smm}
1928232153Smm
1929232153Smmstatic size_t
1930232153Smmutf16nbytes(const void *_p, size_t n)
1931232153Smm{
1932232153Smm	size_t s;
1933232153Smm	const char *p, *pp;
1934232153Smm
1935232153Smm	if (_p == NULL)
1936232153Smm		return (0);
1937232153Smm	p = (const char *)_p;
1938232153Smm
1939232153Smm	/* Like strlen(p), except won't examine positions beyond p[n]. */
1940232153Smm	s = 0;
1941232153Smm	pp = p;
1942232153Smm	n >>= 1;
1943232153Smm	while (s < n && (pp[0] || pp[1])) {
1944232153Smm		pp += 2;
1945232153Smm		s++;
1946232153Smm	}
1947232153Smm	return (s<<1);
1948232153Smm}
1949232153Smm
1950232153Smmint
1951238856Smmarchive_strncpy_l(struct archive_string *as, const void *_p, size_t n,
1952232153Smm    struct archive_string_conv *sc)
1953232153Smm{
1954232153Smm	as->length = 0;
1955238856Smm	return (archive_strncat_l(as, _p, n, sc));
1956232153Smm}
1957232153Smm
1958232153Smmint
1959238856Smmarchive_strncat_l(struct archive_string *as, const void *_p, size_t n,
1960232153Smm    struct archive_string_conv *sc)
1961232153Smm{
1962232153Smm	const void *s;
1963311041Smm	size_t length = 0;
1964232153Smm	int i, r = 0, r2;
1965232153Smm
1966311041Smm	if (_p != NULL && n > 0) {
1967311041Smm		if (sc != NULL && (sc->flag & SCONV_FROM_UTF16))
1968311041Smm			length = utf16nbytes(_p, n);
1969311041Smm		else
1970311041Smm			length = mbsnbytes(_p, n);
1971311041Smm	}
1972311041Smm
1973232153Smm	/* We must allocate memory even if there is no data for conversion
1974232153Smm	 * or copy. This simulates archive_string_append behavior. */
1975311041Smm	if (length == 0) {
1976232153Smm		int tn = 1;
1977232153Smm		if (sc != NULL && (sc->flag & SCONV_TO_UTF16))
1978232153Smm			tn = 2;
1979232153Smm		if (archive_string_ensure(as, as->length + tn) == NULL)
1980232153Smm			return (-1);
1981232153Smm		as->s[as->length] = 0;
1982232153Smm		if (tn == 2)
1983232153Smm			as->s[as->length+1] = 0;
1984232153Smm		return (0);
1985232153Smm	}
1986232153Smm
1987232153Smm	/*
1988232153Smm	 * If sc is NULL, we just make a copy.
1989232153Smm	 */
1990232153Smm	if (sc == NULL) {
1991232153Smm		if (archive_string_append(as, _p, length) == NULL)
1992232153Smm			return (-1);/* No memory */
1993232153Smm		return (0);
1994232153Smm	}
1995232153Smm
1996232153Smm	s = _p;
1997232153Smm	i = 0;
1998232153Smm	if (sc->nconverter > 1) {
1999232153Smm		sc->utftmp.length = 0;
2000232153Smm		r2 = sc->converter[0](&(sc->utftmp), s, length, sc);
2001232153Smm		if (r2 != 0 && errno == ENOMEM)
2002232153Smm			return (r2);
2003232153Smm		if (r > r2)
2004232153Smm			r = r2;
2005232153Smm		s = sc->utftmp.s;
2006232153Smm		length = sc->utftmp.length;
2007232153Smm		++i;
2008232153Smm	}
2009232153Smm	r2 = sc->converter[i](as, s, length, sc);
2010232153Smm	if (r > r2)
2011232153Smm		r = r2;
2012232153Smm	return (r);
2013232153Smm}
2014232153Smm
2015232153Smm#if HAVE_ICONV
2016232153Smm
2017232153Smm/*
2018311041Smm * Return -1 if conversion fails.
2019232153Smm */
2020232153Smmstatic int
2021232153Smmiconv_strncat_in_locale(struct archive_string *as, const void *_p,
2022232153Smm    size_t length, struct archive_string_conv *sc)
2023232153Smm{
2024248616Smm	ICONV_CONST char *itp;
2025232153Smm	size_t remaining;
2026232153Smm	iconv_t cd;
2027232153Smm	char *outp;
2028232153Smm	size_t avail, bs;
2029232153Smm	int return_value = 0; /* success */
2030232153Smm	int to_size, from_size;
2031232153Smm
2032232153Smm	if (sc->flag & SCONV_TO_UTF16)
2033232153Smm		to_size = 2;
2034232153Smm	else
2035232153Smm		to_size = 1;
2036232153Smm	if (sc->flag & SCONV_FROM_UTF16)
2037232153Smm		from_size = 2;
2038232153Smm	else
2039232153Smm		from_size = 1;
2040232153Smm
2041232153Smm	if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2042232153Smm		return (-1);
2043232153Smm
2044232153Smm	cd = sc->cd;
2045248616Smm	itp = (char *)(uintptr_t)_p;
2046232153Smm	remaining = length;
2047232153Smm	outp = as->s + as->length;
2048232153Smm	avail = as->buffer_length - as->length - to_size;
2049232153Smm	while (remaining >= (size_t)from_size) {
2050248616Smm		size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
2051232153Smm
2052232153Smm		if (result != (size_t)-1)
2053232153Smm			break; /* Conversion completed. */
2054232153Smm
2055232153Smm		if (errno == EILSEQ || errno == EINVAL) {
2056232153Smm			/*
2057232153Smm		 	 * If an output charset is UTF-8 or UTF-16BE/LE,
2058232153Smm			 * unknown character should be U+FFFD
2059232153Smm			 * (replacement character).
2060232153Smm			 */
2061232153Smm			if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2062232153Smm				size_t rbytes;
2063232153Smm				if (sc->flag & SCONV_TO_UTF8)
2064299529Smm					rbytes = sizeof(utf8_replacement_char);
2065232153Smm				else
2066232153Smm					rbytes = 2;
2067232153Smm
2068232153Smm				if (avail < rbytes) {
2069232153Smm					as->length = outp - as->s;
2070232153Smm					bs = as->buffer_length +
2071232153Smm					    (remaining * to_size) + rbytes;
2072232153Smm					if (NULL ==
2073232153Smm					    archive_string_ensure(as, bs))
2074232153Smm						return (-1);
2075232153Smm					outp = as->s + as->length;
2076232153Smm					avail = as->buffer_length
2077232153Smm					    - as->length - to_size;
2078232153Smm				}
2079232153Smm				if (sc->flag & SCONV_TO_UTF8)
2080299529Smm					memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
2081232153Smm				else if (sc->flag & SCONV_TO_UTF16BE)
2082232153Smm					archive_be16enc(outp, UNICODE_R_CHAR);
2083232153Smm				else
2084232153Smm					archive_le16enc(outp, UNICODE_R_CHAR);
2085232153Smm				outp += rbytes;
2086232153Smm				avail -= rbytes;
2087232153Smm			} else {
2088232153Smm				/* Skip the illegal input bytes. */
2089232153Smm				*outp++ = '?';
2090232153Smm				avail--;
2091232153Smm			}
2092248616Smm			itp += from_size;
2093232153Smm			remaining -= from_size;
2094232153Smm			return_value = -1; /* failure */
2095228753Smm		} else {
2096232153Smm			/* E2BIG no output buffer,
2097232153Smm			 * Increase an output buffer.  */
2098232153Smm			as->length = outp - as->s;
2099232153Smm			bs = as->buffer_length + remaining * 2;
2100232153Smm			if (NULL == archive_string_ensure(as, bs))
2101232153Smm				return (-1);
2102232153Smm			outp = as->s + as->length;
2103232153Smm			avail = as->buffer_length - as->length - to_size;
2104228753Smm		}
2105228753Smm	}
2106232153Smm	as->length = outp - as->s;
2107232153Smm	as->s[as->length] = 0;
2108232153Smm	if (to_size == 2)
2109232153Smm		as->s[as->length+1] = 0;
2110232153Smm	return (return_value);
2111228753Smm}
2112228753Smm
2113232153Smm#endif /* HAVE_ICONV */
2114232153Smm
2115232153Smm
2116232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
2117232153Smm
2118232153Smm/*
2119232153Smm * Translate a string from a some CodePage to an another CodePage by
2120311041Smm * Windows APIs, and copy the result. Return -1 if conversion fails.
2121232153Smm */
2122228753Smmstatic int
2123232153Smmstrncat_in_codepage(struct archive_string *as,
2124232153Smm    const void *_p, size_t length, struct archive_string_conv *sc)
2125228753Smm{
2126232153Smm	const char *s = (const char *)_p;
2127232153Smm	struct archive_wstring aws;
2128232153Smm	size_t l;
2129232153Smm	int r, saved_flag;
2130228753Smm
2131232153Smm	archive_string_init(&aws);
2132232153Smm	saved_flag = sc->flag;
2133232153Smm	sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2134232153Smm	r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2135232153Smm	sc->flag = saved_flag;
2136232153Smm	if (r != 0) {
2137232153Smm		archive_wstring_free(&aws);
2138232153Smm		if (errno != ENOMEM)
2139232153Smm			archive_string_append(as, s, length);
2140232153Smm		return (-1);
2141232153Smm	}
2142232153Smm
2143232153Smm	l = as->length;
2144232153Smm	r = archive_string_append_from_wcs_in_codepage(
2145232153Smm	    as, aws.s, aws.length, sc);
2146232153Smm	if (r != 0 && errno != ENOMEM && l == as->length)
2147232153Smm		archive_string_append(as, s, length);
2148232153Smm	archive_wstring_free(&aws);
2149232153Smm	return (r);
2150232153Smm}
2151232153Smm
2152232153Smm/*
2153232153Smm * Test whether MBS ==> WCS is okay.
2154232153Smm */
2155232153Smmstatic int
2156232153Smminvalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2157232153Smm{
2158232153Smm	const char *p = (const char *)_p;
2159232153Smm	unsigned codepage;
2160232153Smm	DWORD mbflag = MB_ERR_INVALID_CHARS;
2161232153Smm
2162232153Smm	if (sc->flag & SCONV_FROM_CHARSET)
2163232153Smm		codepage = sc->to_cp;
2164232153Smm	else
2165232153Smm		codepage = sc->from_cp;
2166232153Smm
2167232153Smm	if (codepage == CP_C_LOCALE)
2168232153Smm		return (0);
2169232153Smm	if (codepage != CP_UTF8)
2170232153Smm		mbflag |= MB_PRECOMPOSED;
2171232153Smm
2172248616Smm	if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
2173232153Smm		return (-1); /* Invalid */
2174232153Smm	return (0); /* Okay */
2175232153Smm}
2176232153Smm
2177232153Smm#else
2178232153Smm
2179232153Smm/*
2180232153Smm * Test whether MBS ==> WCS is okay.
2181232153Smm */
2182232153Smmstatic int
2183232153Smminvalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2184232153Smm{
2185232153Smm	const char *p = (const char *)_p;
2186232153Smm	size_t r;
2187232153Smm
2188232153Smm#if HAVE_MBRTOWC
2189232153Smm	mbstate_t shift_state;
2190232153Smm
2191232153Smm	memset(&shift_state, 0, sizeof(shift_state));
2192232153Smm#else
2193232153Smm	/* Clear the shift state before starting. */
2194232153Smm	mbtowc(NULL, NULL, 0);
2195232153Smm#endif
2196232153Smm	while (n) {
2197232153Smm		wchar_t wc;
2198232153Smm
2199232153Smm#if HAVE_MBRTOWC
2200232153Smm		r = mbrtowc(&wc, p, n, &shift_state);
2201232153Smm#else
2202232153Smm		r = mbtowc(&wc, p, n);
2203232153Smm#endif
2204232153Smm		if (r == (size_t)-1 || r == (size_t)-2)
2205232153Smm			return (-1);/* Invalid. */
2206232153Smm		if (r == 0)
2207232153Smm			break;
2208232153Smm		p += r;
2209232153Smm		n -= r;
2210232153Smm	}
2211238856Smm	(void)sc; /* UNUSED */
2212232153Smm	return (0); /* All Okey. */
2213232153Smm}
2214232153Smm
2215232153Smm#endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2216232153Smm
2217232153Smm/*
2218232153Smm * Basically returns -1 because we cannot make a conversion of charset
2219232153Smm * without iconv but in some cases this would return 0.
2220232153Smm * Returns 0 if all copied characters are ASCII.
2221232153Smm * Returns 0 if both from-locale and to-locale are the same and those
2222232153Smm * can be WCS with no error.
2223232153Smm */
2224232153Smmstatic int
2225232153Smmbest_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2226232153Smm    size_t length, struct archive_string_conv *sc)
2227232153Smm{
2228232153Smm	size_t remaining;
2229248616Smm	const uint8_t *itp;
2230232153Smm	int return_value = 0; /* success */
2231232153Smm
2232232153Smm	/*
2233232153Smm	 * If both from-locale and to-locale is the same, this makes a copy.
2234232153Smm	 * And then this checks all copied MBS can be WCS if so returns 0.
2235232153Smm	 */
2236232153Smm	if (sc->same) {
2237232153Smm		if (archive_string_append(as, _p, length) == NULL)
2238232153Smm			return (-1);/* No memory */
2239232153Smm		return (invalid_mbs(_p, length, sc));
2240232153Smm	}
2241232153Smm
2242232153Smm	/*
2243232153Smm	 * If a character is ASCII, this just copies it. If not, this
2244313570Smm	 * assigns '?' character instead but in UTF-8 locale this assigns
2245232153Smm	 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2246232153Smm	 * a Replacement Character in Unicode.
2247232153Smm	 */
2248232153Smm
2249232153Smm	remaining = length;
2250248616Smm	itp = (const uint8_t *)_p;
2251248616Smm	while (*itp && remaining > 0) {
2252299529Smm		if (*itp > 127) {
2253299529Smm			// Non-ASCII: Substitute with suitable replacement
2254299529Smm			if (sc->flag & SCONV_TO_UTF8) {
2255299529Smm				if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
2256299529Smm					__archive_errx(1, "Out of memory");
2257299529Smm				}
2258299529Smm			} else {
2259299529Smm				archive_strappend_char(as, '?');
2260232153Smm			}
2261232153Smm			return_value = -1;
2262232153Smm		} else {
2263299529Smm			archive_strappend_char(as, *itp);
2264232153Smm		}
2265299529Smm		++itp;
2266232153Smm	}
2267232153Smm	return (return_value);
2268232153Smm}
2269232153Smm
2270232153Smm
2271232153Smm/*
2272232153Smm * Unicode conversion functions.
2273232153Smm *   - UTF-8 <===> UTF-8 in removing surrogate pairs.
2274232153Smm *   - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2275232153Smm *   - UTF-8 made by libarchive 2.x ===> UTF-8.
2276232153Smm *   - UTF-16BE <===> UTF-8.
2277232153Smm *
2278232153Smm */
2279232153Smm
2280232153Smm/*
2281232153Smm * Utility to convert a single UTF-8 sequence.
2282232153Smm *
2283232153Smm * Usually return used bytes, return used byte in negative value when
2284232153Smm * a unicode character is replaced with U+FFFD.
2285232153Smm * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2286232153Smm * Recommended Practice for Replacement Characters.
2287232153Smm */
2288232153Smmstatic int
2289232153Smm_utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2290232153Smm{
2291232153Smm	static const char utf8_count[256] = {
2292232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2293232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2294232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2295232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2296232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2297232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2298232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2299232153Smm		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2300232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2301232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2302232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2303232153Smm		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2304232153Smm		 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2305232153Smm		 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2306232153Smm		 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2307232153Smm		 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2308232153Smm	};
2309232153Smm	int ch, i;
2310232153Smm	int cnt;
2311232153Smm	uint32_t wc;
2312232153Smm
2313232153Smm	/* Sanity check. */
2314232153Smm	if (n == 0)
2315232153Smm		return (0);
2316232153Smm	/*
2317228753Smm	 * Decode 1-4 bytes depending on the value of the first byte.
2318228753Smm	 */
2319232153Smm	ch = (unsigned char)*s;
2320232153Smm	if (ch == 0)
2321228753Smm		return (0); /* Standard:  return 0 for end-of-string. */
2322232153Smm	cnt = utf8_count[ch];
2323232153Smm
2324311041Smm	/* Invalid sequence or there are not plenty bytes. */
2325232153Smm	if ((int)n < cnt) {
2326248616Smm		cnt = (int)n;
2327232153Smm		for (i = 1; i < cnt; i++) {
2328232153Smm			if ((s[i] & 0xc0) != 0x80) {
2329232153Smm				cnt = i;
2330232153Smm				break;
2331232153Smm			}
2332232153Smm		}
2333232153Smm		goto invalid_sequence;
2334228753Smm	}
2335232153Smm
2336232153Smm	/* Make a Unicode code point from a single UTF-8 sequence. */
2337232153Smm	switch (cnt) {
2338232153Smm	case 1:	/* 1 byte sequence. */
2339232153Smm		*pwc = ch & 0x7f;
2340232153Smm		return (cnt);
2341232153Smm	case 2:	/* 2 bytes sequence. */
2342232153Smm		if ((s[1] & 0xc0) != 0x80) {
2343232153Smm			cnt = 1;
2344232153Smm			goto invalid_sequence;
2345232153Smm		}
2346232153Smm		*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2347232153Smm		return (cnt);
2348232153Smm	case 3:	/* 3 bytes sequence. */
2349232153Smm		if ((s[1] & 0xc0) != 0x80) {
2350232153Smm			cnt = 1;
2351232153Smm			goto invalid_sequence;
2352232153Smm		}
2353232153Smm		if ((s[2] & 0xc0) != 0x80) {
2354232153Smm			cnt = 2;
2355232153Smm			goto invalid_sequence;
2356232153Smm		}
2357232153Smm		wc = ((ch & 0x0f) << 12)
2358228753Smm		    | ((s[1] & 0x3f) << 6)
2359228753Smm		    | (s[2] & 0x3f);
2360232153Smm		if (wc < 0x800)
2361232153Smm			goto invalid_sequence;/* Overlong sequence. */
2362232153Smm		break;
2363232153Smm	case 4:	/* 4 bytes sequence. */
2364232153Smm		if ((s[1] & 0xc0) != 0x80) {
2365232153Smm			cnt = 1;
2366232153Smm			goto invalid_sequence;
2367232153Smm		}
2368232153Smm		if ((s[2] & 0xc0) != 0x80) {
2369232153Smm			cnt = 2;
2370232153Smm			goto invalid_sequence;
2371232153Smm		}
2372232153Smm		if ((s[3] & 0xc0) != 0x80) {
2373232153Smm			cnt = 3;
2374232153Smm			goto invalid_sequence;
2375232153Smm		}
2376232153Smm		wc = ((ch & 0x07) << 18)
2377228753Smm		    | ((s[1] & 0x3f) << 12)
2378228753Smm		    | ((s[2] & 0x3f) << 6)
2379228753Smm		    | (s[3] & 0x3f);
2380232153Smm		if (wc < 0x10000)
2381232153Smm			goto invalid_sequence;/* Overlong sequence. */
2382232153Smm		break;
2383232153Smm	default: /* Others are all invalid sequence. */
2384232153Smm		if (ch == 0xc0 || ch == 0xc1)
2385232153Smm			cnt = 2;
2386232153Smm		else if (ch >= 0xf5 && ch <= 0xf7)
2387232153Smm			cnt = 4;
2388232153Smm		else if (ch >= 0xf8 && ch <= 0xfb)
2389232153Smm			cnt = 5;
2390232153Smm		else if (ch == 0xfc || ch == 0xfd)
2391232153Smm			cnt = 6;
2392232153Smm		else
2393232153Smm			cnt = 1;
2394232153Smm		if ((int)n < cnt)
2395248616Smm			cnt = (int)n;
2396232153Smm		for (i = 1; i < cnt; i++) {
2397232153Smm			if ((s[i] & 0xc0) != 0x80) {
2398232153Smm				cnt = i;
2399232153Smm				break;
2400232153Smm			}
2401232153Smm		}
2402232153Smm		goto invalid_sequence;
2403232153Smm	}
2404232153Smm
2405311041Smm	/* The code point larger than 0x10FFFF is not legal
2406232153Smm	 * Unicode values. */
2407232153Smm	if (wc > UNICODE_MAX)
2408232153Smm		goto invalid_sequence;
2409232153Smm	/* Correctly gets a Unicode, returns used bytes. */
2410232153Smm	*pwc = wc;
2411232153Smm	return (cnt);
2412232153Smminvalid_sequence:
2413232153Smm	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2414232153Smm	return (cnt * -1);
2415232153Smm}
2416232153Smm
2417232153Smmstatic int
2418232153Smmutf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2419232153Smm{
2420232153Smm	int cnt;
2421232153Smm
2422232153Smm	cnt = _utf8_to_unicode(pwc, s, n);
2423311041Smm	/* Any of Surrogate pair is not legal Unicode values. */
2424232153Smm	if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2425232153Smm		return (-3);
2426232153Smm	return (cnt);
2427232153Smm}
2428232153Smm
2429232153Smmstatic inline uint32_t
2430232153Smmcombine_surrogate_pair(uint32_t uc, uint32_t uc2)
2431232153Smm{
2432232153Smm	uc -= 0xD800;
2433232153Smm	uc *= 0x400;
2434232153Smm	uc += uc2 - 0xDC00;
2435232153Smm	uc += 0x10000;
2436232153Smm	return (uc);
2437232153Smm}
2438232153Smm
2439232153Smm/*
2440232153Smm * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2441232153Smm * removing surrogate pairs.
2442232153Smm *
2443232153Smm * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2444232153Smm *
2445232153Smm * Usually return used bytes, return used byte in negative value when
2446232153Smm * a unicode character is replaced with U+FFFD.
2447232153Smm */
2448232153Smmstatic int
2449232153Smmcesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2450232153Smm{
2451248616Smm	uint32_t wc = 0;
2452232153Smm	int cnt;
2453232153Smm
2454232153Smm	cnt = _utf8_to_unicode(&wc, s, n);
2455232153Smm	if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2456248616Smm		uint32_t wc2 = 0;
2457232153Smm		if (n - 3 < 3) {
2458232153Smm			/* Invalid byte sequence. */
2459232153Smm			goto invalid_sequence;
2460232153Smm		}
2461232153Smm		cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2462232153Smm		if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2463232153Smm			/* Invalid byte sequence. */
2464232153Smm			goto invalid_sequence;
2465232153Smm		}
2466232153Smm		wc = combine_surrogate_pair(wc, wc2);
2467232153Smm		cnt = 6;
2468232153Smm	} else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2469232153Smm		/* Invalid byte sequence. */
2470232153Smm		goto invalid_sequence;
2471232153Smm	}
2472232153Smm	*pwc = wc;
2473232153Smm	return (cnt);
2474232153Smminvalid_sequence:
2475232153Smm	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2476232153Smm	if (cnt > 0)
2477232153Smm		cnt *= -1;
2478232153Smm	return (cnt);
2479232153Smm}
2480232153Smm
2481232153Smm/*
2482232153Smm * Convert a Unicode code point to a single UTF-8 sequence.
2483232153Smm *
2484311041Smm * NOTE:This function does not check if the Unicode is legal or not.
2485232153Smm * Please you definitely check it before calling this.
2486232153Smm */
2487232153Smmstatic size_t
2488232153Smmunicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2489232153Smm{
2490232153Smm	char *_p = p;
2491232153Smm
2492299529Smm	/* Invalid Unicode char maps to Replacement character */
2493299529Smm	if (uc > UNICODE_MAX)
2494299529Smm		uc = UNICODE_R_CHAR;
2495232153Smm	/* Translate code point to UTF8 */
2496232153Smm	if (uc <= 0x7f) {
2497232153Smm		if (remaining == 0)
2498232153Smm			return (0);
2499232153Smm		*p++ = (char)uc;
2500232153Smm	} else if (uc <= 0x7ff) {
2501232153Smm		if (remaining < 2)
2502232153Smm			return (0);
2503232153Smm		*p++ = 0xc0 | ((uc >> 6) & 0x1f);
2504232153Smm		*p++ = 0x80 | (uc & 0x3f);
2505232153Smm	} else if (uc <= 0xffff) {
2506232153Smm		if (remaining < 3)
2507232153Smm			return (0);
2508232153Smm		*p++ = 0xe0 | ((uc >> 12) & 0x0f);
2509232153Smm		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2510232153Smm		*p++ = 0x80 | (uc & 0x3f);
2511299529Smm	} else {
2512232153Smm		if (remaining < 4)
2513232153Smm			return (0);
2514232153Smm		*p++ = 0xf0 | ((uc >> 18) & 0x07);
2515232153Smm		*p++ = 0x80 | ((uc >> 12) & 0x3f);
2516232153Smm		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2517232153Smm		*p++ = 0x80 | (uc & 0x3f);
2518232153Smm	}
2519232153Smm	return (p - _p);
2520232153Smm}
2521232153Smm
2522232153Smmstatic int
2523232153Smmutf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2524232153Smm{
2525232153Smm	return (utf16_to_unicode(pwc, s, n, 1));
2526232153Smm}
2527232153Smm
2528232153Smmstatic int
2529232153Smmutf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2530232153Smm{
2531232153Smm	return (utf16_to_unicode(pwc, s, n, 0));
2532232153Smm}
2533232153Smm
2534232153Smmstatic int
2535232153Smmutf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2536232153Smm{
2537232153Smm	const char *utf16 = s;
2538232153Smm	unsigned uc;
2539232153Smm
2540232153Smm	if (n == 0)
2541232153Smm		return (0);
2542232153Smm	if (n == 1) {
2543232153Smm		/* set the Replacement Character instead. */
2544232153Smm		*pwc = UNICODE_R_CHAR;
2545232153Smm		return (-1);
2546232153Smm	}
2547232153Smm
2548232153Smm	if (be)
2549232153Smm		uc = archive_be16dec(utf16);
2550232153Smm	else
2551232153Smm		uc = archive_le16dec(utf16);
2552232153Smm	utf16 += 2;
2553232153Smm
2554232153Smm	/* If this is a surrogate pair, assemble the full code point.*/
2555232153Smm	if (IS_HIGH_SURROGATE_LA(uc)) {
2556232153Smm		unsigned uc2;
2557232153Smm
2558232153Smm		if (n >= 4) {
2559232153Smm			if (be)
2560232153Smm				uc2 = archive_be16dec(utf16);
2561232153Smm			else
2562232153Smm				uc2 = archive_le16dec(utf16);
2563232153Smm		} else
2564232153Smm			uc2 = 0;
2565232153Smm		if (IS_LOW_SURROGATE_LA(uc2)) {
2566232153Smm			uc = combine_surrogate_pair(uc, uc2);
2567232153Smm			utf16 += 2;
2568232153Smm		} else {
2569232153Smm	 		/* Undescribed code point should be U+FFFD
2570232153Smm		 	* (replacement character). */
2571232153Smm			*pwc = UNICODE_R_CHAR;
2572232153Smm			return (-2);
2573232153Smm		}
2574232153Smm	}
2575232153Smm
2576232153Smm	/*
2577232153Smm	 * Surrogate pair values(0xd800 through 0xdfff) are only
2578313570Smm	 * used by UTF-16, so, after above calculation, the code
2579232153Smm	 * must not be surrogate values, and Unicode has no codes
2580311041Smm	 * larger than 0x10ffff. Thus, those are not legal Unicode
2581232153Smm	 * values.
2582232153Smm	 */
2583232153Smm	if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2584232153Smm	 	/* Undescribed code point should be U+FFFD
2585232153Smm	 	* (replacement character). */
2586232153Smm		*pwc = UNICODE_R_CHAR;
2587232153Smm		return (((int)(utf16 - s)) * -1);
2588232153Smm	}
2589232153Smm	*pwc = uc;
2590232153Smm	return ((int)(utf16 - s));
2591232153Smm}
2592232153Smm
2593232153Smmstatic size_t
2594232153Smmunicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2595232153Smm{
2596232153Smm	char *utf16 = p;
2597232153Smm
2598232153Smm	if (uc > 0xffff) {
2599232153Smm		/* We have a code point that won't fit into a
2600232153Smm		 * wchar_t; convert it to a surrogate pair. */
2601232153Smm		if (remaining < 4)
2602232153Smm			return (0);
2603232153Smm		uc -= 0x10000;
2604232153Smm		archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2605232153Smm		archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2606228753Smm		return (4);
2607232153Smm	} else {
2608232153Smm		if (remaining < 2)
2609232153Smm			return (0);
2610232153Smm		archive_be16enc(utf16, uc);
2611232153Smm		return (2);
2612232153Smm	}
2613228753Smm}
2614228753Smm
2615232153Smmstatic size_t
2616232153Smmunicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2617232153Smm{
2618232153Smm	char *utf16 = p;
2619232153Smm
2620232153Smm	if (uc > 0xffff) {
2621232153Smm		/* We have a code point that won't fit into a
2622232153Smm		 * wchar_t; convert it to a surrogate pair. */
2623232153Smm		if (remaining < 4)
2624232153Smm			return (0);
2625232153Smm		uc -= 0x10000;
2626232153Smm		archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2627232153Smm		archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2628232153Smm		return (4);
2629232153Smm	} else {
2630232153Smm		if (remaining < 2)
2631232153Smm			return (0);
2632232153Smm		archive_le16enc(utf16, uc);
2633232153Smm		return (2);
2634232153Smm	}
2635232153Smm}
2636232153Smm
2637228753Smm/*
2638232153Smm * Copy UTF-8 string in checking surrogate pair.
2639232153Smm * If any surrogate pair are found, it would be canonicalized.
2640228753Smm */
2641232153Smmstatic int
2642238856Smmstrncat_from_utf8_to_utf8(struct archive_string *as, const void *_p,
2643238856Smm    size_t len, struct archive_string_conv *sc)
2644228753Smm{
2645232153Smm	const char *s;
2646232153Smm	char *p, *endp;
2647232153Smm	int n, ret = 0;
2648228753Smm
2649232153Smm	(void)sc; /* UNUSED */
2650232153Smm
2651232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
2652232153Smm		return (-1);
2653232153Smm
2654232153Smm	s = (const char *)_p;
2655232153Smm	p = as->s + as->length;
2656232153Smm	endp = as->s + as->buffer_length -1;
2657232153Smm	do {
2658232153Smm		uint32_t uc;
2659232153Smm		const char *ss = s;
2660232153Smm		size_t w;
2661232153Smm
2662232153Smm		/*
2663232153Smm		 * Forward byte sequence until a conversion of that is needed.
2664232153Smm		 */
2665232153Smm		while ((n = utf8_to_unicode(&uc, s, len)) > 0) {
2666232153Smm			s += n;
2667232153Smm			len -= n;
2668232153Smm		}
2669232153Smm		if (ss < s) {
2670232153Smm			if (p + (s - ss) > endp) {
2671232153Smm				as->length = p - as->s;
2672232153Smm				if (archive_string_ensure(as,
2673232153Smm				    as->buffer_length + len + 1) == NULL)
2674232153Smm					return (-1);
2675232153Smm				p = as->s + as->length;
2676232153Smm				endp = as->s + as->buffer_length -1;
2677232153Smm			}
2678232153Smm
2679232153Smm			memcpy(p, ss, s - ss);
2680232153Smm			p += s - ss;
2681232153Smm		}
2682232153Smm
2683232153Smm		/*
2684232153Smm		 * If n is negative, current byte sequence needs a replacement.
2685232153Smm		 */
2686228753Smm		if (n < 0) {
2687232153Smm			if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2688232153Smm				/* Current byte sequence may be CESU-8. */
2689232153Smm				n = cesu8_to_unicode(&uc, s, len);
2690232153Smm			}
2691228753Smm			if (n < 0) {
2692232153Smm				ret = -1;
2693232153Smm				n *= -1;/* Use a replaced unicode character. */
2694228753Smm			}
2695232153Smm
2696232153Smm			/* Rebuild UTF-8 byte sequence. */
2697232153Smm			while ((w = unicode_to_utf8(p, endp - p, uc)) == 0) {
2698232153Smm				as->length = p - as->s;
2699232153Smm				if (archive_string_ensure(as,
2700232153Smm				    as->buffer_length + len + 1) == NULL)
2701232153Smm					return (-1);
2702232153Smm				p = as->s + as->length;
2703232153Smm				endp = as->s + as->buffer_length -1;
2704228753Smm			}
2705232153Smm			p += w;
2706232153Smm			s += n;
2707232153Smm			len -= n;
2708228753Smm		}
2709232153Smm	} while (n > 0);
2710232153Smm	as->length = p - as->s;
2711232153Smm	as->s[as->length] = '\0';
2712232153Smm	return (ret);
2713232153Smm}
2714232153Smm
2715232153Smmstatic int
2716232153Smmarchive_string_append_unicode(struct archive_string *as, const void *_p,
2717232153Smm    size_t len, struct archive_string_conv *sc)
2718232153Smm{
2719232153Smm	const char *s;
2720232153Smm	char *p, *endp;
2721232153Smm	uint32_t uc;
2722232153Smm	size_t w;
2723232153Smm	int n, ret = 0, ts, tm;
2724232153Smm	int (*parse)(uint32_t *, const char *, size_t);
2725232153Smm	size_t (*unparse)(char *, size_t, uint32_t);
2726232153Smm
2727232153Smm	if (sc->flag & SCONV_TO_UTF16BE) {
2728232153Smm		unparse = unicode_to_utf16be;
2729232153Smm		ts = 2;
2730232153Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
2731232153Smm		unparse = unicode_to_utf16le;
2732232153Smm		ts = 2;
2733232153Smm	} else if (sc->flag & SCONV_TO_UTF8) {
2734232153Smm		unparse = unicode_to_utf8;
2735232153Smm		ts = 1;
2736232153Smm	} else {
2737232153Smm		/*
2738232153Smm		 * This case is going to be converted to another
2739232153Smm		 * character-set through iconv.
2740232153Smm		 */
2741232153Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
2742232153Smm			unparse = unicode_to_utf16be;
2743232153Smm			ts = 2;
2744232153Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
2745232153Smm			unparse = unicode_to_utf16le;
2746232153Smm			ts = 2;
2747232153Smm		} else {
2748232153Smm			unparse = unicode_to_utf8;
2749232153Smm			ts = 1;
2750232153Smm		}
2751228753Smm	}
2752232153Smm
2753232153Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
2754232153Smm		parse = utf16be_to_unicode;
2755232153Smm		tm = 1;
2756232153Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
2757232153Smm		parse = utf16le_to_unicode;
2758232153Smm		tm = 1;
2759232153Smm	} else {
2760232153Smm		parse = cesu8_to_unicode;
2761232153Smm		tm = ts;
2762232153Smm	}
2763232153Smm
2764232153Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2765232153Smm		return (-1);
2766232153Smm
2767232153Smm	s = (const char *)_p;
2768232153Smm	p = as->s + as->length;
2769232153Smm	endp = as->s + as->buffer_length - ts;
2770232153Smm	while ((n = parse(&uc, s, len)) != 0) {
2771232153Smm		if (n < 0) {
2772232153Smm			/* Use a replaced unicode character. */
2773232153Smm			n *= -1;
2774232153Smm			ret = -1;
2775232153Smm		}
2776232153Smm		s += n;
2777232153Smm		len -= n;
2778232153Smm		while ((w = unparse(p, endp - p, uc)) == 0) {
2779232153Smm			/* There is not enough output buffer so
2780232153Smm			 * we have to expand it. */
2781232153Smm			as->length = p - as->s;
2782232153Smm			if (archive_string_ensure(as,
2783232153Smm			    as->buffer_length + len * tm + ts) == NULL)
2784232153Smm				return (-1);
2785232153Smm			p = as->s + as->length;
2786232153Smm			endp = as->s + as->buffer_length - ts;
2787232153Smm		}
2788232153Smm		p += w;
2789232153Smm	}
2790232153Smm	as->length = p - as->s;
2791232153Smm	as->s[as->length] = '\0';
2792232153Smm	if (ts == 2)
2793232153Smm		as->s[as->length+1] = '\0';
2794232153Smm	return (ret);
2795228753Smm}
2796228753Smm
2797232153Smm/*
2798232153Smm * Following Constants for Hangul compositions this information comes from
2799232153Smm * Unicode Standard Annex #15  http://unicode.org/reports/tr15/
2800232153Smm */
2801232153Smm#define HC_SBASE	0xAC00
2802232153Smm#define HC_LBASE	0x1100
2803232153Smm#define HC_VBASE	0x1161
2804232153Smm#define HC_TBASE	0x11A7
2805232153Smm#define HC_LCOUNT	19
2806232153Smm#define HC_VCOUNT	21
2807232153Smm#define HC_TCOUNT	28
2808232153Smm#define HC_NCOUNT	(HC_VCOUNT * HC_TCOUNT)
2809232153Smm#define HC_SCOUNT	(HC_LCOUNT * HC_NCOUNT)
2810228753Smm
2811232153Smmstatic uint32_t
2812232153Smmget_nfc(uint32_t uc, uint32_t uc2)
2813232153Smm{
2814232153Smm	int t, b;
2815232153Smm
2816232153Smm	t = 0;
2817232153Smm	b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2818232153Smm	while (b >= t) {
2819232153Smm		int m = (t + b) / 2;
2820232153Smm		if (u_composition_table[m].cp1 < uc)
2821232153Smm			t = m + 1;
2822232153Smm		else if (u_composition_table[m].cp1 > uc)
2823232153Smm			b = m - 1;
2824232153Smm		else if (u_composition_table[m].cp2 < uc2)
2825232153Smm			t = m + 1;
2826232153Smm		else if (u_composition_table[m].cp2 > uc2)
2827232153Smm			b = m - 1;
2828232153Smm		else
2829232153Smm			return (u_composition_table[m].nfc);
2830232153Smm	}
2831232153Smm	return (0);
2832232153Smm}
2833232153Smm
2834232153Smm#define FDC_MAX 10	/* The maximum number of Following Decomposable
2835232153Smm			 * Characters. */
2836232153Smm
2837228753Smm/*
2838232153Smm * Update first code point.
2839232153Smm */
2840232153Smm#define UPDATE_UC(new_uc)	do {		\
2841232153Smm	uc = new_uc;				\
2842232153Smm	ucptr = NULL;				\
2843232153Smm} while (0)
2844232153Smm
2845232153Smm/*
2846232153Smm * Replace first code point with second code point.
2847232153Smm */
2848232153Smm#define REPLACE_UC_WITH_UC2() do {		\
2849232153Smm	uc = uc2;				\
2850232153Smm	ucptr = uc2ptr;				\
2851232153Smm	n = n2;					\
2852232153Smm} while (0)
2853232153Smm
2854232153Smm#define EXPAND_BUFFER() do {			\
2855232153Smm	as->length = p - as->s;			\
2856232153Smm	if (archive_string_ensure(as,		\
2857232153Smm	    as->buffer_length + len * tm + ts) == NULL)\
2858232153Smm		return (-1);			\
2859232153Smm	p = as->s + as->length;			\
2860232153Smm	endp = as->s + as->buffer_length - ts;	\
2861232153Smm} while (0)
2862232153Smm
2863232153Smm#define UNPARSE(p, endp, uc)	do {		\
2864232153Smm	while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
2865232153Smm		EXPAND_BUFFER();		\
2866232153Smm	}					\
2867232153Smm	p += w;					\
2868232153Smm} while (0)
2869232153Smm
2870232153Smm/*
2871232153Smm * Write first code point.
2872232153Smm * If the code point has not be changed from its original code,
2873232153Smm * this just copies it from its original buffer pointer.
2874232153Smm * If not, this converts it to UTF-8 byte sequence and copies it.
2875232153Smm */
2876232153Smm#define WRITE_UC()	do {			\
2877232153Smm	if (ucptr) {				\
2878232153Smm		if (p + n > endp)		\
2879232153Smm			EXPAND_BUFFER();	\
2880232153Smm		switch (n) {			\
2881232153Smm		case 4:				\
2882232153Smm			*p++ = *ucptr++;	\
2883232153Smm			/* FALL THROUGH */	\
2884232153Smm		case 3:				\
2885232153Smm			*p++ = *ucptr++;	\
2886232153Smm			/* FALL THROUGH */	\
2887232153Smm		case 2:				\
2888232153Smm			*p++ = *ucptr++;	\
2889232153Smm			/* FALL THROUGH */	\
2890232153Smm		case 1:				\
2891232153Smm			*p++ = *ucptr;		\
2892232153Smm			break;			\
2893232153Smm		}				\
2894232153Smm		ucptr = NULL;			\
2895232153Smm	} else {				\
2896232153Smm		UNPARSE(p, endp, uc);		\
2897232153Smm	}					\
2898232153Smm} while (0)
2899232153Smm
2900232153Smm/*
2901232153Smm * Collect following decomposable code points.
2902232153Smm */
2903232153Smm#define COLLECT_CPS(start)	do {		\
2904232153Smm	int _i;					\
2905232153Smm	for (_i = start; _i < FDC_MAX ; _i++) {	\
2906232153Smm		nx = parse(&ucx[_i], s, len);	\
2907232153Smm		if (nx <= 0)			\
2908232153Smm			break;			\
2909232153Smm		cx = CCC(ucx[_i]);		\
2910232153Smm		if (cl >= cx && cl != 228 && cx != 228)\
2911232153Smm			break;			\
2912232153Smm		s += nx;			\
2913232153Smm		len -= nx;			\
2914232153Smm		cl = cx;			\
2915232153Smm		ccx[_i] = cx;			\
2916232153Smm	}					\
2917232153Smm	if (_i >= FDC_MAX) {			\
2918232153Smm		ret = -1;			\
2919232153Smm		ucx_size = FDC_MAX;		\
2920232153Smm	} else					\
2921232153Smm		ucx_size = _i;			\
2922232153Smm} while (0)
2923232153Smm
2924232153Smm/*
2925232153Smm * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
2926228753Smm *
2927313570Smm * TODO: Convert composition exclusions, which are never converted
2928232153Smm * from NFC,NFD,NFKC and NFKD, to Form C.
2929228753Smm */
2930232153Smmstatic int
2931232153Smmarchive_string_normalize_C(struct archive_string *as, const void *_p,
2932232153Smm    size_t len, struct archive_string_conv *sc)
2933228753Smm{
2934232153Smm	const char *s = (const char *)_p;
2935232153Smm	char *p, *endp;
2936232153Smm	uint32_t uc, uc2;
2937232153Smm	size_t w;
2938232153Smm	int always_replace, n, n2, ret = 0, spair, ts, tm;
2939232153Smm	int (*parse)(uint32_t *, const char *, size_t);
2940232153Smm	size_t (*unparse)(char *, size_t, uint32_t);
2941228753Smm
2942232153Smm	always_replace = 1;
2943232153Smm	ts = 1;/* text size. */
2944232153Smm	if (sc->flag & SCONV_TO_UTF16BE) {
2945232153Smm		unparse = unicode_to_utf16be;
2946232153Smm		ts = 2;
2947232153Smm		if (sc->flag & SCONV_FROM_UTF16BE)
2948232153Smm			always_replace = 0;
2949232153Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
2950232153Smm		unparse = unicode_to_utf16le;
2951232153Smm		ts = 2;
2952232153Smm		if (sc->flag & SCONV_FROM_UTF16LE)
2953232153Smm			always_replace = 0;
2954232153Smm	} else if (sc->flag & SCONV_TO_UTF8) {
2955232153Smm		unparse = unicode_to_utf8;
2956232153Smm		if (sc->flag & SCONV_FROM_UTF8)
2957232153Smm			always_replace = 0;
2958232153Smm	} else {
2959232153Smm		/*
2960232153Smm		 * This case is going to be converted to another
2961232153Smm		 * character-set through iconv.
2962232153Smm		 */
2963232153Smm		always_replace = 0;
2964232153Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
2965232153Smm			unparse = unicode_to_utf16be;
2966232153Smm			ts = 2;
2967232153Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
2968232153Smm			unparse = unicode_to_utf16le;
2969232153Smm			ts = 2;
2970232153Smm		} else {
2971232153Smm			unparse = unicode_to_utf8;
2972232153Smm		}
2973232153Smm	}
2974232153Smm
2975232153Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
2976232153Smm		parse = utf16be_to_unicode;
2977232153Smm		tm = 1;
2978232153Smm		spair = 4;/* surrogate pair size in UTF-16. */
2979232153Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
2980232153Smm		parse = utf16le_to_unicode;
2981232153Smm		tm = 1;
2982232153Smm		spair = 4;/* surrogate pair size in UTF-16. */
2983232153Smm	} else {
2984232153Smm		parse = cesu8_to_unicode;
2985232153Smm		tm = ts;
2986232153Smm		spair = 6;/* surrogate pair size in UTF-8. */
2987232153Smm	}
2988232153Smm
2989232153Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2990232153Smm		return (-1);
2991232153Smm
2992232153Smm	p = as->s + as->length;
2993232153Smm	endp = as->s + as->buffer_length - ts;
2994232153Smm	while ((n = parse(&uc, s, len)) != 0) {
2995232153Smm		const char *ucptr, *uc2ptr;
2996232153Smm
2997232153Smm		if (n < 0) {
2998232153Smm			/* Use a replaced unicode character. */
2999232153Smm			UNPARSE(p, endp, uc);
3000232153Smm			s += n*-1;
3001232153Smm			len -= n*-1;
3002232153Smm			ret = -1;
3003232153Smm			continue;
3004232153Smm		} else if (n == spair || always_replace)
3005232153Smm			/* uc is converted from a surrogate pair.
3006232153Smm			 * this should be treated as a changed code. */
3007232153Smm			ucptr = NULL;
3008232153Smm		else
3009232153Smm			ucptr = s;
3010232153Smm		s += n;
3011232153Smm		len -= n;
3012232153Smm
3013232153Smm		/* Read second code point. */
3014232153Smm		while ((n2 = parse(&uc2, s, len)) > 0) {
3015232153Smm			uint32_t ucx[FDC_MAX];
3016232153Smm			int ccx[FDC_MAX];
3017232153Smm			int cl, cx, i, nx, ucx_size;
3018232153Smm			int LIndex,SIndex;
3019232153Smm			uint32_t nfc;
3020232153Smm
3021232153Smm			if (n2 == spair || always_replace)
3022232153Smm				/* uc2 is converted from a surrogate pair.
3023232153Smm			 	 * this should be treated as a changed code. */
3024232153Smm				uc2ptr = NULL;
3025232153Smm			else
3026232153Smm				uc2ptr = s;
3027232153Smm			s += n2;
3028232153Smm			len -= n2;
3029232153Smm
3030232153Smm			/*
3031232153Smm			 * If current second code point is out of decomposable
3032232153Smm			 * code points, finding compositions is unneeded.
3033232153Smm			 */
3034232153Smm			if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3035232153Smm				WRITE_UC();
3036232153Smm				REPLACE_UC_WITH_UC2();
3037232153Smm				continue;
3038232153Smm			}
3039232153Smm
3040232153Smm			/*
3041232153Smm			 * Try to combine current code points.
3042232153Smm			 */
3043232153Smm			/*
3044232153Smm			 * We have to combine Hangul characters according to
3045232153Smm			 * http://uniicode.org/reports/tr15/#Hangul
3046232153Smm			 */
3047232153Smm			if (0 <= (LIndex = uc - HC_LBASE) &&
3048232153Smm			    LIndex < HC_LCOUNT) {
3049232153Smm				/*
3050232153Smm				 * Hangul Composition.
3051232153Smm				 * 1. Two current code points are L and V.
3052232153Smm				 */
3053232153Smm				int VIndex = uc2 - HC_VBASE;
3054232153Smm				if (0 <= VIndex && VIndex < HC_VCOUNT) {
3055232153Smm					/* Make syllable of form LV. */
3056232153Smm					UPDATE_UC(HC_SBASE +
3057232153Smm					    (LIndex * HC_VCOUNT + VIndex) *
3058232153Smm					     HC_TCOUNT);
3059232153Smm				} else {
3060232153Smm					WRITE_UC();
3061232153Smm					REPLACE_UC_WITH_UC2();
3062232153Smm				}
3063232153Smm				continue;
3064232153Smm			} else if (0 <= (SIndex = uc - HC_SBASE) &&
3065232153Smm			    SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3066232153Smm				/*
3067232153Smm				 * Hangul Composition.
3068232153Smm				 * 2. Two current code points are LV and T.
3069232153Smm				 */
3070232153Smm				int TIndex = uc2 - HC_TBASE;
3071232153Smm				if (0 < TIndex && TIndex < HC_TCOUNT) {
3072232153Smm					/* Make syllable of form LVT. */
3073232153Smm					UPDATE_UC(uc + TIndex);
3074232153Smm				} else {
3075232153Smm					WRITE_UC();
3076232153Smm					REPLACE_UC_WITH_UC2();
3077232153Smm				}
3078232153Smm				continue;
3079232153Smm			} else if ((nfc = get_nfc(uc, uc2)) != 0) {
3080232153Smm				/* A composition to current code points
3081232153Smm				 * is found. */
3082232153Smm				UPDATE_UC(nfc);
3083232153Smm				continue;
3084232153Smm			} else if ((cl = CCC(uc2)) == 0) {
3085232153Smm				/* Clearly 'uc2' the second code point is not
3086232153Smm				 * a decomposable code. */
3087232153Smm				WRITE_UC();
3088232153Smm				REPLACE_UC_WITH_UC2();
3089232153Smm				continue;
3090232153Smm			}
3091232153Smm
3092232153Smm			/*
3093232153Smm			 * Collect following decomposable code points.
3094232153Smm			 */
3095232153Smm			cx = 0;
3096232153Smm			ucx[0] = uc2;
3097232153Smm			ccx[0] = cl;
3098232153Smm			COLLECT_CPS(1);
3099232153Smm
3100232153Smm			/*
3101232153Smm			 * Find a composed code in the collected code points.
3102232153Smm			 */
3103232153Smm			i = 1;
3104232153Smm			while (i < ucx_size) {
3105232153Smm				int j;
3106232153Smm
3107232153Smm				if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3108232153Smm					i++;
3109232153Smm					continue;
3110232153Smm				}
3111232153Smm
3112232153Smm				/*
3113232153Smm				 * nfc is composed of uc and ucx[i].
3114232153Smm				 */
3115232153Smm				UPDATE_UC(nfc);
3116232153Smm
3117232153Smm				/*
3118232153Smm				 * Remove ucx[i] by shifting
3119232153Smm				 * following code points.
3120232153Smm				 */
3121232153Smm				for (j = i; j+1 < ucx_size; j++) {
3122232153Smm					ucx[j] = ucx[j+1];
3123232153Smm					ccx[j] = ccx[j+1];
3124232153Smm				}
3125232153Smm				ucx_size --;
3126232153Smm
3127232153Smm				/*
3128232153Smm				 * Collect following code points blocked
3129232153Smm				 * by ucx[i] the removed code point.
3130232153Smm				 */
3131232153Smm				if (ucx_size > 0 && i == ucx_size &&
3132232153Smm				    nx > 0 && cx == cl) {
3133232153Smm					cl =  ccx[ucx_size-1];
3134232153Smm					COLLECT_CPS(ucx_size);
3135232153Smm				}
3136232153Smm				/*
3137232153Smm				 * Restart finding a composed code with
3138232153Smm				 * the updated uc from the top of the
3139232153Smm				 * collected code points.
3140232153Smm				 */
3141232153Smm				i = 0;
3142232153Smm			}
3143232153Smm
3144232153Smm			/*
3145232153Smm			 * Apparently the current code points are not
3146232153Smm			 * decomposed characters or already composed.
3147232153Smm			 */
3148232153Smm			WRITE_UC();
3149232153Smm			for (i = 0; i < ucx_size; i++)
3150232153Smm				UNPARSE(p, endp, ucx[i]);
3151232153Smm
3152232153Smm			/*
3153232153Smm			 * Flush out remaining canonical combining characters.
3154232153Smm			 */
3155232153Smm			if (nx > 0 && cx == cl && len > 0) {
3156232153Smm				while ((nx = parse(&ucx[0], s, len))
3157232153Smm				    > 0) {
3158232153Smm					cx = CCC(ucx[0]);
3159232153Smm					if (cl > cx)
3160232153Smm						break;
3161232153Smm					s += nx;
3162232153Smm					len -= nx;
3163232153Smm					cl = cx;
3164232153Smm					UNPARSE(p, endp, ucx[0]);
3165232153Smm				}
3166232153Smm			}
3167232153Smm			break;
3168232153Smm		}
3169232153Smm		if (n2 < 0) {
3170232153Smm			WRITE_UC();
3171232153Smm			/* Use a replaced unicode character. */
3172232153Smm			UNPARSE(p, endp, uc2);
3173232153Smm			s += n2*-1;
3174232153Smm			len -= n2*-1;
3175232153Smm			ret = -1;
3176232153Smm			continue;
3177232153Smm		} else if (n2 == 0) {
3178232153Smm			WRITE_UC();
3179232153Smm			break;
3180232153Smm		}
3181232153Smm	}
3182232153Smm	as->length = p - as->s;
3183232153Smm	as->s[as->length] = '\0';
3184232153Smm	if (ts == 2)
3185232153Smm		as->s[as->length+1] = '\0';
3186232153Smm	return (ret);
3187232153Smm}
3188232153Smm
3189238856Smmstatic int
3190238856Smmget_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
3191238856Smm{
3192238856Smm	int t, b;
3193232153Smm
3194238856Smm	/*
3195238856Smm	 * These are not converted to NFD on Mac OS.
3196238856Smm	 */
3197238856Smm	if ((uc >= 0x2000 && uc <= 0x2FFF) ||
3198238856Smm	    (uc >= 0xF900 && uc <= 0xFAFF) ||
3199238856Smm	    (uc >= 0x2F800 && uc <= 0x2FAFF))
3200238856Smm		return (0);
3201238856Smm	/*
3202238856Smm	 * Those code points are not converted to NFD on Mac OS.
3203238856Smm	 * I do not know the reason because it is undocumented.
3204238856Smm	 *   NFC        NFD
3205238856Smm	 *   1109A  ==> 11099 110BA
3206238856Smm	 *   1109C  ==> 1109B 110BA
3207238856Smm	 *   110AB  ==> 110A5 110BA
3208238856Smm	 */
3209238856Smm	if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
3210238856Smm		return (0);
3211238856Smm
3212238856Smm	t = 0;
3213238856Smm	b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
3214238856Smm	while (b >= t) {
3215238856Smm		int m = (t + b) / 2;
3216238856Smm		if (u_decomposition_table[m].nfc < uc)
3217238856Smm			t = m + 1;
3218238856Smm		else if (u_decomposition_table[m].nfc > uc)
3219238856Smm			b = m - 1;
3220238856Smm		else {
3221238856Smm			*cp1 = u_decomposition_table[m].cp1;
3222238856Smm			*cp2 = u_decomposition_table[m].cp2;
3223238856Smm			return (1);
3224238856Smm		}
3225238856Smm	}
3226238856Smm	return (0);
3227238856Smm}
3228238856Smm
3229238856Smm#define REPLACE_UC_WITH(cp) do {		\
3230238856Smm	uc = cp;				\
3231238856Smm	ucptr = NULL;				\
3232238856Smm} while (0)
3233238856Smm
3234232153Smm/*
3235232153Smm * Normalize UTF-8 characters to Form D and copy the result.
3236232153Smm */
3237232153Smmstatic int
3238232153Smmarchive_string_normalize_D(struct archive_string *as, const void *_p,
3239232153Smm    size_t len, struct archive_string_conv *sc)
3240232153Smm{
3241238856Smm	const char *s = (const char *)_p;
3242238856Smm	char *p, *endp;
3243238856Smm	uint32_t uc, uc2;
3244238856Smm	size_t w;
3245238856Smm	int always_replace, n, n2, ret = 0, spair, ts, tm;
3246238856Smm	int (*parse)(uint32_t *, const char *, size_t);
3247238856Smm	size_t (*unparse)(char *, size_t, uint32_t);
3248232153Smm
3249238856Smm	always_replace = 1;
3250238856Smm	ts = 1;/* text size. */
3251238856Smm	if (sc->flag & SCONV_TO_UTF16BE) {
3252238856Smm		unparse = unicode_to_utf16be;
3253238856Smm		ts = 2;
3254238856Smm		if (sc->flag & SCONV_FROM_UTF16BE)
3255238856Smm			always_replace = 0;
3256238856Smm	} else if (sc->flag & SCONV_TO_UTF16LE) {
3257238856Smm		unparse = unicode_to_utf16le;
3258238856Smm		ts = 2;
3259238856Smm		if (sc->flag & SCONV_FROM_UTF16LE)
3260238856Smm			always_replace = 0;
3261238856Smm	} else if (sc->flag & SCONV_TO_UTF8) {
3262238856Smm		unparse = unicode_to_utf8;
3263238856Smm		if (sc->flag & SCONV_FROM_UTF8)
3264238856Smm			always_replace = 0;
3265238856Smm	} else {
3266238856Smm		/*
3267238856Smm		 * This case is going to be converted to another
3268238856Smm		 * character-set through iconv.
3269238856Smm		 */
3270238856Smm		always_replace = 0;
3271238856Smm		if (sc->flag & SCONV_FROM_UTF16BE) {
3272238856Smm			unparse = unicode_to_utf16be;
3273238856Smm			ts = 2;
3274238856Smm		} else if (sc->flag & SCONV_FROM_UTF16LE) {
3275238856Smm			unparse = unicode_to_utf16le;
3276238856Smm			ts = 2;
3277238856Smm		} else {
3278238856Smm			unparse = unicode_to_utf8;
3279238856Smm		}
3280228753Smm	}
3281232153Smm
3282238856Smm	if (sc->flag & SCONV_FROM_UTF16BE) {
3283238856Smm		parse = utf16be_to_unicode;
3284238856Smm		tm = 1;
3285238856Smm		spair = 4;/* surrogate pair size in UTF-16. */
3286238856Smm	} else if (sc->flag & SCONV_FROM_UTF16LE) {
3287238856Smm		parse = utf16le_to_unicode;
3288238856Smm		tm = 1;
3289238856Smm		spair = 4;/* surrogate pair size in UTF-16. */
3290238856Smm	} else {
3291238856Smm		parse = cesu8_to_unicode;
3292238856Smm		tm = ts;
3293238856Smm		spair = 6;/* surrogate pair size in UTF-8. */
3294238856Smm	}
3295238856Smm
3296238856Smm	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3297232153Smm		return (-1);
3298232153Smm
3299238856Smm	p = as->s + as->length;
3300238856Smm	endp = as->s + as->buffer_length - ts;
3301238856Smm	while ((n = parse(&uc, s, len)) != 0) {
3302238856Smm		const char *ucptr;
3303238856Smm		uint32_t cp1, cp2;
3304238856Smm		int SIndex;
3305238856Smm		struct {
3306238856Smm			uint32_t uc;
3307238856Smm			int ccc;
3308238856Smm		} fdc[FDC_MAX];
3309238856Smm		int fdi, fdj;
3310238856Smm		int ccc;
3311232153Smm
3312238856Smmcheck_first_code:
3313238856Smm		if (n < 0) {
3314238856Smm			/* Use a replaced unicode character. */
3315238856Smm			UNPARSE(p, endp, uc);
3316238856Smm			s += n*-1;
3317238856Smm			len -= n*-1;
3318238856Smm			ret = -1;
3319238856Smm			continue;
3320238856Smm		} else if (n == spair || always_replace)
3321238856Smm			/* uc is converted from a surrogate pair.
3322238856Smm			 * this should be treated as a changed code. */
3323238856Smm			ucptr = NULL;
3324238856Smm		else
3325238856Smm			ucptr = s;
3326238856Smm		s += n;
3327238856Smm		len -= n;
3328232153Smm
3329238856Smm		/* Hangul Decomposition. */
3330238856Smm		if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
3331238856Smm			int L = HC_LBASE + SIndex / HC_NCOUNT;
3332238856Smm			int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
3333238856Smm			int T = HC_TBASE + SIndex % HC_TCOUNT;
3334232153Smm
3335238856Smm			REPLACE_UC_WITH(L);
3336238856Smm			WRITE_UC();
3337238856Smm			REPLACE_UC_WITH(V);
3338238856Smm			WRITE_UC();
3339238856Smm			if (T != HC_TBASE) {
3340238856Smm				REPLACE_UC_WITH(T);
3341238856Smm				WRITE_UC();
3342238856Smm			}
3343238856Smm			continue;
3344238856Smm		}
3345238856Smm		if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
3346238856Smm			WRITE_UC();
3347238856Smm			continue;
3348238856Smm		}
3349232153Smm
3350238856Smm		fdi = 0;
3351238856Smm		while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
3352238856Smm			int k;
3353238856Smm
3354238856Smm			for (k = fdi; k > 0; k--)
3355238856Smm				fdc[k] = fdc[k-1];
3356238856Smm			fdc[0].ccc = CCC(cp2);
3357238856Smm			fdc[0].uc = cp2;
3358238856Smm			fdi++;
3359238856Smm			REPLACE_UC_WITH(cp1);
3360238856Smm		}
3361238856Smm
3362238856Smm		/* Read following code points. */
3363238856Smm		while ((n2 = parse(&uc2, s, len)) > 0 &&
3364238856Smm		    (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
3365238856Smm			int j, k;
3366238856Smm
3367238856Smm			s += n2;
3368238856Smm			len -= n2;
3369238856Smm			for (j = 0; j < fdi; j++) {
3370238856Smm				if (fdc[j].ccc > ccc)
3371238856Smm					break;
3372238856Smm			}
3373238856Smm			if (j < fdi) {
3374238856Smm				for (k = fdi; k > j; k--)
3375238856Smm					fdc[k] = fdc[k-1];
3376238856Smm				fdc[j].ccc = ccc;
3377238856Smm				fdc[j].uc = uc2;
3378238856Smm			} else {
3379238856Smm				fdc[fdi].ccc = ccc;
3380238856Smm				fdc[fdi].uc = uc2;
3381238856Smm			}
3382238856Smm			fdi++;
3383238856Smm		}
3384238856Smm
3385238856Smm		WRITE_UC();
3386238856Smm		for (fdj = 0; fdj < fdi; fdj++) {
3387238856Smm			REPLACE_UC_WITH(fdc[fdj].uc);
3388238856Smm			WRITE_UC();
3389238856Smm		}
3390238856Smm
3391238856Smm		if (n2 == 0)
3392238856Smm			break;
3393238856Smm		REPLACE_UC_WITH(uc2);
3394238856Smm		n = n2;
3395238856Smm		goto check_first_code;
3396232153Smm	}
3397238856Smm	as->length = p - as->s;
3398238856Smm	as->s[as->length] = '\0';
3399238856Smm	if (ts == 2)
3400238856Smm		as->s[as->length+1] = '\0';
3401232153Smm	return (ret);
3402228753Smm}
3403228753Smm
3404228753Smm/*
3405232153Smm * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
3406232153Smm * that WCS is Unicode. It is true for several platforms but some are false.
3407232153Smm * And then people who did not use UTF-8 locale on the non Unicode WCS
3408232153Smm * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3409232153Smm * now cannot get right filename from libarchive 3.x and later since we
3410232153Smm * fixed the wrong assumption and it is incompatible to older its versions.
3411232153Smm * So we provide special option, "compat-2x.x", for resolving it.
3412232153Smm * That option enable the string conversion of libarchive 2.x.
3413228753Smm *
3414232153Smm * Translates the wrong UTF-8 string made by libarchive 2.x into current
3415232153Smm * locale character set and appends to the archive_string.
3416232153Smm * Note: returns -1 if conversion fails.
3417228753Smm */
3418232153Smmstatic int
3419232153Smmstrncat_from_utf8_libarchive2(struct archive_string *as,
3420232153Smm    const void *_p, size_t len, struct archive_string_conv *sc)
3421228753Smm{
3422232153Smm	const char *s;
3423228753Smm	int n;
3424228753Smm	char *p;
3425232153Smm	char *end;
3426232153Smm	uint32_t unicode;
3427228753Smm#if HAVE_WCRTOMB
3428228753Smm	mbstate_t shift_state;
3429228753Smm
3430228753Smm	memset(&shift_state, 0, sizeof(shift_state));
3431228753Smm#else
3432228753Smm	/* Clear the shift state before starting. */
3433228753Smm	wctomb(NULL, L'\0');
3434228753Smm#endif
3435232153Smm	(void)sc; /* UNUSED */
3436228753Smm	/*
3437232153Smm	 * Allocate buffer for MBS.
3438232153Smm	 * We need this allocation here since it is possible that
3439232153Smm	 * as->s is still NULL.
3440228753Smm	 */
3441232153Smm	if (archive_string_ensure(as, as->length + len + 1) == NULL)
3442232153Smm		return (-1);
3443232153Smm
3444232153Smm	s = (const char *)_p;
3445232153Smm	p = as->s + as->length;
3446232153Smm	end = as->s + as->buffer_length - MB_CUR_MAX -1;
3447232153Smm	while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3448232153Smm		wchar_t wc;
3449232153Smm
3450232153Smm		if (p >= end) {
3451232153Smm			as->length = p - as->s;
3452232153Smm			/* Re-allocate buffer for MBS. */
3453232153Smm			if (archive_string_ensure(as,
3454358088Smm			    as->length + max(len * 2,
3455358088Smm			    (size_t)MB_CUR_MAX) + 1) == NULL)
3456232153Smm				return (-1);
3457232153Smm			p = as->s + as->length;
3458232153Smm			end = as->s + as->buffer_length - MB_CUR_MAX -1;
3459228753Smm		}
3460232153Smm
3461232153Smm		/*
3462313570Smm		 * As libarchive 2.x, translates the UTF-8 characters into
3463232153Smm		 * wide-characters in the assumption that WCS is Unicode.
3464232153Smm		 */
3465232153Smm		if (n < 0) {
3466232153Smm			n *= -1;
3467232153Smm			wc = L'?';
3468232153Smm		} else
3469232153Smm			wc = (wchar_t)unicode;
3470232153Smm
3471232153Smm		s += n;
3472232153Smm		len -= n;
3473232153Smm		/*
3474232153Smm		 * Translates the wide-character into the current locale MBS.
3475232153Smm		 */
3476228753Smm#if HAVE_WCRTOMB
3477248616Smm		n = (int)wcrtomb(p, wc, &shift_state);
3478228753Smm#else
3479248616Smm		n = (int)wctomb(p, wc);
3480228753Smm#endif
3481228753Smm		if (n == -1)
3482232153Smm			return (-1);
3483228753Smm		p += n;
3484228753Smm	}
3485232153Smm	as->length = p - as->s;
3486232153Smm	as->s[as->length] = '\0';
3487232153Smm	return (0);
3488232153Smm}
3489232153Smm
3490232153Smm
3491232153Smm/*
3492232153Smm * Conversion functions between current locale dependent MBS and UTF-16BE.
3493232153Smm *   strncat_from_utf16be() : UTF-16BE --> MBS
3494232153Smm *   strncat_to_utf16be()   : MBS --> UTF16BE
3495232153Smm */
3496232153Smm
3497232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3498232153Smm
3499232153Smm/*
3500232153Smm * Convert a UTF-16BE/LE string to current locale and copy the result.
3501311041Smm * Return -1 if conversion fails.
3502232153Smm */
3503232153Smmstatic int
3504232153Smmwin_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3505232153Smm    struct archive_string_conv *sc, int be)
3506232153Smm{
3507232153Smm	struct archive_string tmp;
3508232153Smm	const char *u16;
3509232153Smm	int ll;
3510232153Smm	BOOL defchar;
3511232153Smm	char *mbs;
3512232153Smm	size_t mbs_size, b;
3513232153Smm	int ret = 0;
3514232153Smm
3515232153Smm	bytes &= ~1;
3516232153Smm	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3517232153Smm		return (-1);
3518232153Smm
3519232153Smm	mbs = as->s + as->length;
3520232153Smm	mbs_size = as->buffer_length - as->length -1;
3521232153Smm
3522232153Smm	if (sc->to_cp == CP_C_LOCALE) {
3523232153Smm		/*
3524232153Smm		 * "C" locale special process.
3525232153Smm		 */
3526232153Smm		u16 = _p;
3527232153Smm		ll = 0;
3528232153Smm		for (b = 0; b < bytes; b += 2) {
3529232153Smm			uint16_t val;
3530232153Smm			if (be)
3531232153Smm				val = archive_be16dec(u16+b);
3532232153Smm			else
3533232153Smm				val = archive_le16dec(u16+b);
3534232153Smm			if (val > 255) {
3535232153Smm				*mbs++ = '?';
3536232153Smm				ret = -1;
3537232153Smm			} else
3538232153Smm				*mbs++ = (char)(val&0xff);
3539232153Smm			ll++;
3540232153Smm		}
3541232153Smm		as->length += ll;
3542232153Smm		as->s[as->length] = '\0';
3543232153Smm		return (ret);
3544232153Smm	}
3545232153Smm
3546232153Smm	archive_string_init(&tmp);
3547232153Smm	if (be) {
3548232153Smm		if (is_big_endian()) {
3549232153Smm			u16 = _p;
3550232153Smm		} else {
3551232153Smm			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3552232153Smm				return (-1);
3553232153Smm			memcpy(tmp.s, _p, bytes);
3554232153Smm			for (b = 0; b < bytes; b += 2) {
3555232153Smm				uint16_t val = archive_be16dec(tmp.s+b);
3556232153Smm				archive_le16enc(tmp.s+b, val);
3557232153Smm			}
3558232153Smm			u16 = tmp.s;
3559232153Smm		}
3560232153Smm	} else {
3561232153Smm		if (!is_big_endian()) {
3562232153Smm			u16 = _p;
3563232153Smm		} else {
3564232153Smm			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3565232153Smm				return (-1);
3566232153Smm			memcpy(tmp.s, _p, bytes);
3567232153Smm			for (b = 0; b < bytes; b += 2) {
3568232153Smm				uint16_t val = archive_le16dec(tmp.s+b);
3569232153Smm				archive_be16enc(tmp.s+b, val);
3570232153Smm			}
3571232153Smm			u16 = tmp.s;
3572232153Smm		}
3573232153Smm	}
3574232153Smm
3575232153Smm	do {
3576232153Smm		defchar = 0;
3577232153Smm		ll = WideCharToMultiByte(sc->to_cp, 0,
3578248616Smm		    (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
3579232153Smm			NULL, &defchar);
3580302294Smm		/* Exit loop if we succeeded */
3581302294Smm		if (ll != 0 ||
3582302294Smm		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3583302294Smm			break;
3584232153Smm		}
3585302294Smm		/* Else expand buffer and loop to try again. */
3586302294Smm		ll = WideCharToMultiByte(sc->to_cp, 0,
3587302294Smm		    (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
3588302294Smm		if (archive_string_ensure(as, ll +1) == NULL)
3589302294Smm			return (-1);
3590302294Smm		mbs = as->s + as->length;
3591302294Smm		mbs_size = as->buffer_length - as->length -1;
3592302294Smm	} while (1);
3593232153Smm	archive_string_free(&tmp);
3594232153Smm	as->length += ll;
3595232153Smm	as->s[as->length] = '\0';
3596232153Smm	if (ll == 0 || defchar)
3597232153Smm		ret = -1;
3598232153Smm	return (ret);
3599232153Smm}
3600232153Smm
3601232153Smmstatic int
3602238856Smmwin_strncat_from_utf16be(struct archive_string *as, const void *_p,
3603238856Smm    size_t bytes, struct archive_string_conv *sc)
3604232153Smm{
3605232153Smm	return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3606232153Smm}
3607232153Smm
3608232153Smmstatic int
3609238856Smmwin_strncat_from_utf16le(struct archive_string *as, const void *_p,
3610238856Smm    size_t bytes, struct archive_string_conv *sc)
3611232153Smm{
3612232153Smm	return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3613232153Smm}
3614232153Smm
3615232153Smmstatic int
3616232153Smmis_big_endian(void)
3617232153Smm{
3618232153Smm	uint16_t d = 1;
3619232153Smm
3620232153Smm	return (archive_be16dec(&d) == 1);
3621232153Smm}
3622232153Smm
3623232153Smm/*
3624232153Smm * Convert a current locale string to UTF-16BE/LE and copy the result.
3625311041Smm * Return -1 if conversion fails.
3626232153Smm */
3627232153Smmstatic int
3628238856Smmwin_strncat_to_utf16(struct archive_string *as16, const void *_p,
3629238856Smm    size_t length, struct archive_string_conv *sc, int bigendian)
3630232153Smm{
3631232153Smm	const char *s = (const char *)_p;
3632232153Smm	char *u16;
3633232153Smm	size_t count, avail;
3634232153Smm
3635232153Smm	if (archive_string_ensure(as16,
3636232153Smm	    as16->length + (length + 1) * 2) == NULL)
3637232153Smm		return (-1);
3638232153Smm
3639232153Smm	u16 = as16->s + as16->length;
3640232153Smm	avail = as16->buffer_length - 2;
3641232153Smm	if (sc->from_cp == CP_C_LOCALE) {
3642232153Smm		/*
3643232153Smm		 * "C" locale special process.
3644232153Smm		 */
3645232153Smm		count = 0;
3646232153Smm		while (count < length && *s) {
3647232153Smm			if (bigendian)
3648232153Smm				archive_be16enc(u16, *s);
3649232153Smm			else
3650232153Smm				archive_le16enc(u16, *s);
3651232153Smm			u16 += 2;
3652232153Smm			s++;
3653232153Smm			count++;
3654232153Smm		}
3655232153Smm		as16->length += count << 1;
3656232153Smm		as16->s[as16->length] = 0;
3657232153Smm		as16->s[as16->length+1] = 0;
3658232153Smm		return (0);
3659232153Smm	}
3660232153Smm	do {
3661232153Smm		count = MultiByteToWideChar(sc->from_cp,
3662248616Smm		    MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
3663302294Smm		/* Exit loop if we succeeded */
3664302294Smm		if (count != 0 ||
3665302294Smm		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3666302294Smm			break;
3667232153Smm		}
3668302294Smm		/* Expand buffer and try again */
3669302294Smm		count = MultiByteToWideChar(sc->from_cp,
3670302294Smm		    MB_PRECOMPOSED, s, (int)length, NULL, 0);
3671302294Smm		if (archive_string_ensure(as16, (count +1) * 2)
3672302294Smm		    == NULL)
3673302294Smm			return (-1);
3674302294Smm		u16 = as16->s + as16->length;
3675302294Smm		avail = as16->buffer_length - 2;
3676302294Smm	} while (1);
3677232153Smm	as16->length += count * 2;
3678232153Smm	as16->s[as16->length] = 0;
3679232153Smm	as16->s[as16->length+1] = 0;
3680232153Smm	if (count == 0)
3681232153Smm		return (-1);
3682232153Smm
3683232153Smm	if (is_big_endian()) {
3684232153Smm		if (!bigendian) {
3685232153Smm			while (count > 0) {
3686232153Smm				uint16_t v = archive_be16dec(u16);
3687232153Smm				archive_le16enc(u16, v);
3688232153Smm				u16 += 2;
3689232153Smm				count--;
3690232153Smm			}
3691232153Smm		}
3692232153Smm	} else {
3693232153Smm		if (bigendian) {
3694232153Smm			while (count > 0) {
3695232153Smm				uint16_t v = archive_le16dec(u16);
3696232153Smm				archive_be16enc(u16, v);
3697232153Smm				u16 += 2;
3698232153Smm				count--;
3699232153Smm			}
3700232153Smm		}
3701232153Smm	}
3702232153Smm	return (0);
3703232153Smm}
3704232153Smm
3705232153Smmstatic int
3706238856Smmwin_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3707238856Smm    size_t length, struct archive_string_conv *sc)
3708232153Smm{
3709232153Smm	return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3710232153Smm}
3711232153Smm
3712232153Smmstatic int
3713238856Smmwin_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3714238856Smm    size_t length, struct archive_string_conv *sc)
3715232153Smm{
3716232153Smm	return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3717232153Smm}
3718232153Smm
3719232153Smm#endif /* _WIN32 && !__CYGWIN__ */
3720232153Smm
3721232153Smm/*
3722232153Smm * Do the best effort for conversions.
3723232153Smm * We cannot handle UTF-16BE character-set without such iconv,
3724232153Smm * but there is a chance if a string consists just ASCII code or
3725232153Smm * a current locale is UTF-8.
3726232153Smm */
3727232153Smm
3728232153Smm/*
3729232153Smm * Convert a UTF-16BE string to current locale and copy the result.
3730311041Smm * Return -1 if conversion fails.
3731232153Smm */
3732232153Smmstatic int
3733232153Smmbest_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3734232153Smm    size_t bytes, struct archive_string_conv *sc, int be)
3735232153Smm{
3736232153Smm	const char *utf16 = (const char *)_p;
3737232153Smm	char *mbs;
3738232153Smm	uint32_t uc;
3739232153Smm	int n, ret;
3740232153Smm
3741232153Smm	(void)sc; /* UNUSED */
3742232153Smm	/*
3743232153Smm	 * Other case, we should do the best effort.
3744232153Smm	 * If all character are ASCII(<0x7f), we can convert it.
3745232153Smm	 * if not , we set a alternative character and return -1.
3746232153Smm	 */
3747232153Smm	ret = 0;
3748232153Smm	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3749232153Smm		return (-1);
3750232153Smm	mbs = as->s + as->length;
3751232153Smm
3752232153Smm	while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3753232153Smm		if (n < 0) {
3754232153Smm			n *= -1;
3755232153Smm			ret =  -1;
3756232153Smm		}
3757232153Smm		bytes -= n;
3758232153Smm		utf16 += n;
3759232153Smm
3760232153Smm		if (uc > 127) {
3761232153Smm			/* We cannot handle it. */
3762232153Smm			*mbs++ = '?';
3763232153Smm			ret =  -1;
3764232153Smm		} else
3765232153Smm			*mbs++ = (char)uc;
3766232153Smm	}
3767232153Smm	as->length = mbs - as->s;
3768232153Smm	as->s[as->length] = '\0';
3769232153Smm	return (ret);
3770232153Smm}
3771232153Smm
3772232153Smmstatic int
3773232153Smmbest_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3774232153Smm    size_t bytes, struct archive_string_conv *sc)
3775232153Smm{
3776232153Smm	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3777232153Smm}
3778232153Smm
3779232153Smmstatic int
3780232153Smmbest_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3781232153Smm    size_t bytes, struct archive_string_conv *sc)
3782232153Smm{
3783232153Smm	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3784232153Smm}
3785232153Smm
3786232153Smm/*
3787232153Smm * Convert a current locale string to UTF-16BE/LE and copy the result.
3788311041Smm * Return -1 if conversion fails.
3789232153Smm */
3790232153Smmstatic int
3791232153Smmbest_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3792232153Smm    size_t length, struct archive_string_conv *sc, int bigendian)
3793232153Smm{
3794232153Smm	const char *s = (const char *)_p;
3795232153Smm	char *utf16;
3796232153Smm	size_t remaining;
3797232153Smm	int ret;
3798232153Smm
3799232153Smm	(void)sc; /* UNUSED */
3800232153Smm	/*
3801232153Smm	 * Other case, we should do the best effort.
3802232153Smm	 * If all character are ASCII(<0x7f), we can convert it.
3803232153Smm	 * if not , we set a alternative character and return -1.
3804232153Smm	 */
3805232153Smm	ret = 0;
3806232153Smm	remaining = length;
3807232153Smm
3808232153Smm	if (archive_string_ensure(as16,
3809232153Smm	    as16->length + (length + 1) * 2) == NULL)
3810232153Smm		return (-1);
3811232153Smm
3812232153Smm	utf16 = as16->s + as16->length;
3813232153Smm	while (remaining--) {
3814232153Smm		unsigned c = *s++;
3815232153Smm		if (c > 127) {
3816232153Smm			/* We cannot handle it. */
3817232153Smm			c = UNICODE_R_CHAR;
3818232153Smm			ret = -1;
3819232153Smm		}
3820232153Smm		if (bigendian)
3821232153Smm			archive_be16enc(utf16, c);
3822232153Smm		else
3823232153Smm			archive_le16enc(utf16, c);
3824232153Smm		utf16 += 2;
3825232153Smm	}
3826232153Smm	as16->length = utf16 - as16->s;
3827232153Smm	as16->s[as16->length] = 0;
3828232153Smm	as16->s[as16->length+1] = 0;
3829232153Smm	return (ret);
3830232153Smm}
3831232153Smm
3832232153Smmstatic int
3833232153Smmbest_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3834232153Smm    size_t length, struct archive_string_conv *sc)
3835232153Smm{
3836232153Smm	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3837232153Smm}
3838232153Smm
3839232153Smmstatic int
3840232153Smmbest_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3841232153Smm    size_t length, struct archive_string_conv *sc)
3842232153Smm{
3843232153Smm	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3844232153Smm}
3845232153Smm
3846232153Smm
3847232153Smm/*
3848232153Smm * Multistring operations.
3849232153Smm */
3850232153Smm
3851232153Smmvoid
3852232153Smmarchive_mstring_clean(struct archive_mstring *aes)
3853232153Smm{
3854232153Smm	archive_wstring_free(&(aes->aes_wcs));
3855232153Smm	archive_string_free(&(aes->aes_mbs));
3856232153Smm	archive_string_free(&(aes->aes_utf8));
3857232153Smm	archive_string_free(&(aes->aes_mbs_in_locale));
3858232153Smm	aes->aes_set = 0;
3859232153Smm}
3860232153Smm
3861232153Smmvoid
3862232153Smmarchive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3863232153Smm{
3864232153Smm	dest->aes_set = src->aes_set;
3865232153Smm	archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3866232153Smm	archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3867232153Smm	archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3868232153Smm}
3869232153Smm
3870232153Smmint
3871232153Smmarchive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3872232153Smm  const char **p)
3873232153Smm{
3874232153Smm	struct archive_string_conv *sc;
3875232153Smm	int r;
3876232153Smm
3877232153Smm	/* If we already have a UTF8 form, return that immediately. */
3878232153Smm	if (aes->aes_set & AES_SET_UTF8) {
3879232153Smm		*p = aes->aes_utf8.s;
3880232153Smm		return (0);
3881232153Smm	}
3882232153Smm
3883232153Smm	*p = NULL;
3884368707Smm	/* Try converting WCS to MBS first if MBS does not exist yet. */
3885368707Smm	if ((aes->aes_set & AES_SET_MBS) == 0) {
3886368707Smm		const char *pm; /* unused */
3887368707Smm		archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
3888368707Smm	}
3889232153Smm	if (aes->aes_set & AES_SET_MBS) {
3890232153Smm		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3891232153Smm		if (sc == NULL)
3892232153Smm			return (-1);/* Couldn't allocate memory for sc. */
3893299529Smm		r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
3894232153Smm		    aes->aes_mbs.length, sc);
3895232153Smm		if (a == NULL)
3896232153Smm			free_sconv_object(sc);
3897232153Smm		if (r == 0) {
3898232153Smm			aes->aes_set |= AES_SET_UTF8;
3899232153Smm			*p = aes->aes_utf8.s;
3900232153Smm			return (0);/* success. */
3901232153Smm		} else
3902232153Smm			return (-1);/* failure. */
3903232153Smm	}
3904232153Smm	return (0);/* success. */
3905232153Smm}
3906232153Smm
3907232153Smmint
3908232153Smmarchive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3909232153Smm    const char **p)
3910232153Smm{
3911368707Smm	struct archive_string_conv *sc;
3912232153Smm	int r, ret = 0;
3913232153Smm
3914232153Smm	/* If we already have an MBS form, return that immediately. */
3915232153Smm	if (aes->aes_set & AES_SET_MBS) {
3916232153Smm		*p = aes->aes_mbs.s;
3917232153Smm		return (ret);
3918232153Smm	}
3919232153Smm
3920232153Smm	*p = NULL;
3921232153Smm	/* If there's a WCS form, try converting with the native locale. */
3922232153Smm	if (aes->aes_set & AES_SET_WCS) {
3923232153Smm		archive_string_empty(&(aes->aes_mbs));
3924232153Smm		r = archive_string_append_from_wcs(&(aes->aes_mbs),
3925232153Smm		    aes->aes_wcs.s, aes->aes_wcs.length);
3926232153Smm		*p = aes->aes_mbs.s;
3927232153Smm		if (r == 0) {
3928232153Smm			aes->aes_set |= AES_SET_MBS;
3929232153Smm			return (ret);
3930232153Smm		} else
3931232153Smm			ret = -1;
3932232153Smm	}
3933232153Smm
3934368707Smm	/* If there's a UTF-8 form, try converting with the native locale. */
3935368707Smm	if (aes->aes_set & AES_SET_UTF8) {
3936368707Smm		archive_string_empty(&(aes->aes_mbs));
3937368707Smm		sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
3938368707Smm		if (sc == NULL)
3939368707Smm			return (-1);/* Couldn't allocate memory for sc. */
3940368707Smm		r = archive_strncpy_l(&(aes->aes_mbs),
3941368707Smm			aes->aes_utf8.s, aes->aes_utf8.length, sc);
3942368707Smm		if (a == NULL)
3943368707Smm			free_sconv_object(sc);
3944368707Smm		*p = aes->aes_mbs.s;
3945368707Smm		if (r == 0) {
3946368707Smm			aes->aes_set |= AES_SET_MBS;
3947368707Smm			ret = 0;/* success; overwrite previous error. */
3948368707Smm		} else
3949368707Smm			ret = -1;/* failure. */
3950368707Smm	}
3951232153Smm	return (ret);
3952232153Smm}
3953232153Smm
3954232153Smmint
3955232153Smmarchive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
3956232153Smm    const wchar_t **wp)
3957232153Smm{
3958232153Smm	int r, ret = 0;
3959232153Smm
3960232153Smm	(void)a;/* UNUSED */
3961232153Smm	/* Return WCS form if we already have it. */
3962232153Smm	if (aes->aes_set & AES_SET_WCS) {
3963232153Smm		*wp = aes->aes_wcs.s;
3964232153Smm		return (ret);
3965232153Smm	}
3966232153Smm
3967232153Smm	*wp = NULL;
3968368707Smm	/* Try converting UTF8 to MBS first if MBS does not exist yet. */
3969368707Smm	if ((aes->aes_set & AES_SET_MBS) == 0) {
3970368707Smm		const char *p; /* unused */
3971368707Smm		archive_mstring_get_mbs(a, aes, &p); /* ignore errors, we'll handle it later */
3972368707Smm	}
3973232153Smm	/* Try converting MBS to WCS using native locale. */
3974232153Smm	if (aes->aes_set & AES_SET_MBS) {
3975232153Smm		archive_wstring_empty(&(aes->aes_wcs));
3976232153Smm		r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
3977232153Smm		    aes->aes_mbs.s, aes->aes_mbs.length);
3978232153Smm		if (r == 0) {
3979232153Smm			aes->aes_set |= AES_SET_WCS;
3980232153Smm			*wp = aes->aes_wcs.s;
3981232153Smm		} else
3982232153Smm			ret = -1;/* failure. */
3983232153Smm	}
3984232153Smm	return (ret);
3985232153Smm}
3986232153Smm
3987232153Smmint
3988368707Smmarchive_mstring_get_mbs_l(struct archive *a, struct archive_mstring *aes,
3989232153Smm    const char **p, size_t *length, struct archive_string_conv *sc)
3990232153Smm{
3991232153Smm	int r, ret = 0;
3992232153Smm
3993368707Smm	(void)r; /* UNUSED */
3994232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
3995232153Smm	/*
3996313570Smm	 * Internationalization programming on Windows must use Wide
3997232153Smm	 * characters because Windows platform cannot make locale UTF-8.
3998232153Smm	 */
3999232153Smm	if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
4000232153Smm		archive_string_empty(&(aes->aes_mbs_in_locale));
4001232153Smm		r = archive_string_append_from_wcs_in_codepage(
4002232153Smm		    &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
4003232153Smm		    aes->aes_wcs.length, sc);
4004232153Smm		if (r == 0) {
4005232153Smm			*p = aes->aes_mbs_in_locale.s;
4006232153Smm			if (length != NULL)
4007232153Smm				*length = aes->aes_mbs_in_locale.length;
4008232153Smm			return (0);
4009232153Smm		} else if (errno == ENOMEM)
4010232153Smm			return (-1);
4011232153Smm		else
4012232153Smm			ret = -1;
4013232153Smm	}
4014228753Smm#endif
4015232153Smm
4016368707Smm	/* If there is not an MBS form but there is a WCS or UTF8 form, try converting
4017232153Smm	 * with the native locale to be used for translating it to specified
4018232153Smm	 * character-set. */
4019368707Smm	if ((aes->aes_set & AES_SET_MBS) == 0) {
4020368707Smm		const char *pm; /* unused */
4021368707Smm		archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
4022232153Smm	}
4023232153Smm	/* If we already have an MBS form, use it to be translated to
4024232153Smm	 * specified character-set. */
4025232153Smm	if (aes->aes_set & AES_SET_MBS) {
4026232153Smm		if (sc == NULL) {
4027232153Smm			/* Conversion is unneeded. */
4028232153Smm			*p = aes->aes_mbs.s;
4029232153Smm			if (length != NULL)
4030232153Smm				*length = aes->aes_mbs.length;
4031232153Smm			return (0);
4032232153Smm		}
4033238856Smm		ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
4034232153Smm		    aes->aes_mbs.s, aes->aes_mbs.length, sc);
4035232153Smm		*p = aes->aes_mbs_in_locale.s;
4036232153Smm		if (length != NULL)
4037232153Smm			*length = aes->aes_mbs_in_locale.length;
4038232153Smm	} else {
4039232153Smm		*p = NULL;
4040232153Smm		if (length != NULL)
4041232153Smm			*length = 0;
4042232153Smm	}
4043232153Smm	return (ret);
4044228753Smm}
4045228753Smm
4046232153Smmint
4047232153Smmarchive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4048232153Smm{
4049232153Smm	if (mbs == NULL) {
4050232153Smm		aes->aes_set = 0;
4051232153Smm		return (0);
4052232153Smm	}
4053232153Smm	return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4054232153Smm}
4055232153Smm
4056232153Smmint
4057232153Smmarchive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4058232153Smm    size_t len)
4059232153Smm{
4060232153Smm	if (mbs == NULL) {
4061232153Smm		aes->aes_set = 0;
4062232153Smm		return (0);
4063232153Smm	}
4064232153Smm	aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4065232153Smm	archive_strncpy(&(aes->aes_mbs), mbs, len);
4066232153Smm	archive_string_empty(&(aes->aes_utf8));
4067232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4068232153Smm	return (0);
4069232153Smm}
4070232153Smm
4071232153Smmint
4072232153Smmarchive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4073232153Smm{
4074238856Smm	return archive_mstring_copy_wcs_len(aes, wcs,
4075238856Smm				wcs == NULL ? 0 : wcslen(wcs));
4076232153Smm}
4077232153Smm
4078232153Smmint
4079299529Smmarchive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
4080299529Smm{
4081299529Smm  if (utf8 == NULL) {
4082299529Smm    aes->aes_set = 0;
4083346104Smm    return (0);
4084299529Smm  }
4085299529Smm  aes->aes_set = AES_SET_UTF8;
4086299529Smm  archive_string_empty(&(aes->aes_mbs));
4087299529Smm  archive_string_empty(&(aes->aes_wcs));
4088299529Smm  archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
4089299529Smm  return (int)strlen(utf8);
4090299529Smm}
4091299529Smm
4092299529Smmint
4093232153Smmarchive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4094232153Smm    size_t len)
4095232153Smm{
4096232153Smm	if (wcs == NULL) {
4097232153Smm		aes->aes_set = 0;
4098346104Smm		return (0);
4099232153Smm	}
4100232153Smm	aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4101232153Smm	archive_string_empty(&(aes->aes_mbs));
4102232153Smm	archive_string_empty(&(aes->aes_utf8));
4103232153Smm	archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4104232153Smm	return (0);
4105232153Smm}
4106232153Smm
4107232153Smmint
4108232153Smmarchive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4109232153Smm    const char *mbs, size_t len, struct archive_string_conv *sc)
4110232153Smm{
4111232153Smm	int r;
4112232153Smm
4113232153Smm	if (mbs == NULL) {
4114232153Smm		aes->aes_set = 0;
4115232153Smm		return (0);
4116232153Smm	}
4117232153Smm	archive_string_empty(&(aes->aes_mbs));
4118232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4119232153Smm	archive_string_empty(&(aes->aes_utf8));
4120232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
4121232153Smm	/*
4122313570Smm	 * Internationalization programming on Windows must use Wide
4123232153Smm	 * characters because Windows platform cannot make locale UTF-8.
4124232153Smm	 */
4125232153Smm	if (sc == NULL) {
4126232153Smm		if (archive_string_append(&(aes->aes_mbs),
4127232153Smm			mbs, mbsnbytes(mbs, len)) == NULL) {
4128232153Smm			aes->aes_set = 0;
4129232153Smm			r = -1;
4130232153Smm		} else {
4131232153Smm			aes->aes_set = AES_SET_MBS;
4132232153Smm			r = 0;
4133232153Smm		}
4134232153Smm#if defined(HAVE_ICONV)
4135232153Smm	} else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4136232153Smm		/*
4137232153Smm		 * This case happens only when MultiByteToWideChar() cannot
4138232153Smm		 * handle sc->from_cp, and we have to iconv in order to
4139232153Smm		 * translate character-set to wchar_t,UTF-16.
4140232153Smm		 */
4141232153Smm		iconv_t cd = sc->cd;
4142232153Smm		unsigned from_cp;
4143232153Smm		int flag;
4144232153Smm
4145232153Smm		/*
4146232153Smm		 * Translate multi-bytes from some character-set to UTF-8.
4147232153Smm		 */
4148232153Smm		sc->cd = sc->cd_w;
4149238856Smm		r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
4150232153Smm		sc->cd = cd;
4151232153Smm		if (r != 0) {
4152232153Smm			aes->aes_set = 0;
4153232153Smm			return (r);
4154232153Smm		}
4155232153Smm		aes->aes_set = AES_SET_UTF8;
4156232153Smm
4157232153Smm		/*
4158232153Smm		 * Append the UTF-8 string into wstring.
4159232153Smm		 */
4160232153Smm		flag = sc->flag;
4161232153Smm		sc->flag &= ~(SCONV_NORMALIZATION_C
4162232153Smm				| SCONV_TO_UTF16| SCONV_FROM_UTF16);
4163232153Smm		from_cp = sc->from_cp;
4164232153Smm		sc->from_cp = CP_UTF8;
4165232153Smm		r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4166232153Smm			aes->aes_utf8.s, aes->aes_utf8.length, sc);
4167232153Smm		sc->flag = flag;
4168232153Smm		sc->from_cp = from_cp;
4169232153Smm		if (r == 0)
4170232153Smm			aes->aes_set |= AES_SET_WCS;
4171232153Smm#endif
4172232153Smm	} else {
4173232153Smm		r = archive_wstring_append_from_mbs_in_codepage(
4174232153Smm		    &(aes->aes_wcs), mbs, len, sc);
4175232153Smm		if (r == 0)
4176232153Smm			aes->aes_set = AES_SET_WCS;
4177232153Smm		else
4178232153Smm			aes->aes_set = 0;
4179232153Smm	}
4180232153Smm#else
4181238856Smm	r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
4182232153Smm	if (r == 0)
4183232153Smm		aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4184232153Smm	else
4185232153Smm		aes->aes_set = 0;
4186232153Smm#endif
4187232153Smm	return (r);
4188232153Smm}
4189232153Smm
4190232153Smm/*
4191232153Smm * The 'update' form tries to proactively update all forms of
4192232153Smm * this string (WCS and MBS) and returns an error if any of
4193232153Smm * them fail.  This is used by the 'pax' handler, for instance,
4194232153Smm * to detect and report character-conversion failures early while
4195232153Smm * still allowing clients to get potentially useful values from
4196232153Smm * the more tolerant lazy conversions.  (get_mbs and get_wcs will
4197232153Smm * strive to give the user something useful, so you can get hopefully
4198232153Smm * usable values even if some of the character conversions are failing.)
4199232153Smm */
4200232153Smmint
4201232153Smmarchive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4202232153Smm    const char *utf8)
4203232153Smm{
4204232153Smm	struct archive_string_conv *sc;
4205232153Smm	int r;
4206232153Smm
4207232153Smm	if (utf8 == NULL) {
4208232153Smm		aes->aes_set = 0;
4209232153Smm		return (0); /* Succeeded in clearing everything. */
4210232153Smm	}
4211232153Smm
4212232153Smm	/* Save the UTF8 string. */
4213232153Smm	archive_strcpy(&(aes->aes_utf8), utf8);
4214232153Smm
4215232153Smm	/* Empty the mbs and wcs strings. */
4216232153Smm	archive_string_empty(&(aes->aes_mbs));
4217232153Smm	archive_wstring_empty(&(aes->aes_wcs));
4218232153Smm
4219232153Smm	aes->aes_set = AES_SET_UTF8;	/* Only UTF8 is set now. */
4220232153Smm
4221232153Smm	/* Try converting UTF-8 to MBS, return false on failure. */
4222232153Smm	sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4223232153Smm	if (sc == NULL)
4224232153Smm		return (-1);/* Couldn't allocate memory for sc. */
4225238856Smm	r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
4226232153Smm	if (a == NULL)
4227232153Smm		free_sconv_object(sc);
4228232153Smm	if (r != 0)
4229232153Smm		return (-1);
4230232153Smm	aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4231232153Smm
4232232153Smm	/* Try converting MBS to WCS, return false on failure. */
4233232153Smm	if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4234232153Smm	    aes->aes_mbs.length))
4235232153Smm		return (-1);
4236232153Smm	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4237232153Smm
4238232153Smm	/* All conversions succeeded. */
4239232153Smm	return (0);
4240232153Smm}
4241