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