xref: /freebsd/contrib/libarchive/libarchive/archive_string.c (revision 007679a138089676aadc9a712277f4004403b905)
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 		size_t 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 struct archive_string *
archive_string_dirname(struct archive_string * as)2058 archive_string_dirname(struct archive_string *as)
2059 {
2060 	/* strip trailing separators */
2061 	while (as->length > 1 && as->s[as->length - 1] == '/')
2062 		as->length--;
2063 	/* strip final component */
2064 	while (as->length > 0 && as->s[as->length - 1] != '/')
2065 		as->length--;
2066 	/* empty path -> cwd */
2067 	if (as->length == 0)
2068 		return (archive_strcat(as, "."));
2069 	/* strip separator(s) */
2070 	while (as->length > 1 && as->s[as->length - 1] == '/')
2071 		as->length--;
2072 	/* terminate */
2073 	as->s[as->length] = '\0';
2074 	return (as);
2075 }
2076 
2077 #if HAVE_ICONV
2078 
2079 /*
2080  * Return -1 if conversion fails.
2081  */
2082 static int
iconv_strncat_in_locale(struct archive_string * as,const void * _p,size_t length,struct archive_string_conv * sc)2083 iconv_strncat_in_locale(struct archive_string *as, const void *_p,
2084     size_t length, struct archive_string_conv *sc)
2085 {
2086 	ICONV_CONST char *itp;
2087 	size_t remaining;
2088 	iconv_t cd;
2089 	char *outp;
2090 	size_t avail, bs;
2091 	int return_value = 0; /* success */
2092 	size_t to_size, from_size;
2093 
2094 	if (sc->flag & SCONV_TO_UTF16)
2095 		to_size = 2;
2096 	else
2097 		to_size = 1;
2098 	if (sc->flag & SCONV_FROM_UTF16)
2099 		from_size = 2;
2100 	else
2101 		from_size = 1;
2102 
2103 	if (archive_string_ensure(as, as->length + length*2+to_size) == NULL)
2104 		return (-1);
2105 
2106 	cd = sc->cd;
2107 	itp = (char *)(uintptr_t)_p;
2108 	remaining = length;
2109 	outp = as->s + as->length;
2110 	avail = as->buffer_length - as->length - to_size;
2111 	while (remaining >= from_size) {
2112 		size_t result = iconv(cd, &itp, &remaining, &outp, &avail);
2113 
2114 		if (result != (size_t)-1)
2115 			break; /* Conversion completed. */
2116 
2117 		if (errno == EILSEQ || errno == EINVAL) {
2118 			/*
2119 		 	 * If an output charset is UTF-8 or UTF-16BE/LE,
2120 			 * unknown character should be U+FFFD
2121 			 * (replacement character).
2122 			 */
2123 			if (sc->flag & (SCONV_TO_UTF8 | SCONV_TO_UTF16)) {
2124 				size_t rbytes;
2125 				if (sc->flag & SCONV_TO_UTF8)
2126 					rbytes = sizeof(utf8_replacement_char);
2127 				else
2128 					rbytes = 2;
2129 
2130 				if (avail < rbytes) {
2131 					as->length = outp - as->s;
2132 					bs = as->buffer_length +
2133 					    (remaining * to_size) + rbytes;
2134 					if (NULL ==
2135 					    archive_string_ensure(as, bs))
2136 						return (-1);
2137 					outp = as->s + as->length;
2138 					avail = as->buffer_length
2139 					    - as->length - to_size;
2140 				}
2141 				if (sc->flag & SCONV_TO_UTF8)
2142 					memcpy(outp, utf8_replacement_char, sizeof(utf8_replacement_char));
2143 				else if (sc->flag & SCONV_TO_UTF16BE)
2144 					archive_be16enc(outp, UNICODE_R_CHAR);
2145 				else
2146 					archive_le16enc(outp, UNICODE_R_CHAR);
2147 				outp += rbytes;
2148 				avail -= rbytes;
2149 			} else {
2150 				/* Skip the illegal input bytes. */
2151 				*outp++ = '?';
2152 				avail--;
2153 			}
2154 			itp += from_size;
2155 			remaining -= from_size;
2156 			return_value = -1; /* failure */
2157 		} else {
2158 			/* E2BIG no output buffer,
2159 			 * Increase an output buffer.  */
2160 			as->length = outp - as->s;
2161 			bs = as->buffer_length + remaining * 2;
2162 			if (NULL == archive_string_ensure(as, bs))
2163 				return (-1);
2164 			outp = as->s + as->length;
2165 			avail = as->buffer_length - as->length - to_size;
2166 		}
2167 	}
2168 	as->length = outp - as->s;
2169 	as->s[as->length] = 0;
2170 	if (to_size == 2)
2171 		as->s[as->length+1] = 0;
2172 	return (return_value);
2173 }
2174 
2175 #endif /* HAVE_ICONV */
2176 
2177 
2178 #if defined(_WIN32) && !defined(__CYGWIN__)
2179 
2180 /*
2181  * Translate a string from a some CodePage to an another CodePage by
2182  * Windows APIs, and copy the result. Return -1 if conversion fails.
2183  */
2184 static int
strncat_in_codepage(struct archive_string * as,const void * _p,size_t length,struct archive_string_conv * sc)2185 strncat_in_codepage(struct archive_string *as,
2186     const void *_p, size_t length, struct archive_string_conv *sc)
2187 {
2188 	const char *s = (const char *)_p;
2189 	struct archive_wstring aws;
2190 	size_t l;
2191 	int r, saved_flag;
2192 
2193 	archive_string_init(&aws);
2194 	saved_flag = sc->flag;
2195 	sc->flag &= ~(SCONV_NORMALIZATION_D | SCONV_NORMALIZATION_C);
2196 	r = archive_wstring_append_from_mbs_in_codepage(&aws, s, length, sc);
2197 	sc->flag = saved_flag;
2198 	if (r != 0) {
2199 		archive_wstring_free(&aws);
2200 		if (errno != ENOMEM)
2201 			archive_string_append(as, s, length);
2202 		return (-1);
2203 	}
2204 
2205 	l = as->length;
2206 	r = archive_string_append_from_wcs_in_codepage(
2207 	    as, aws.s, aws.length, sc);
2208 	if (r != 0 && errno != ENOMEM && l == as->length)
2209 		archive_string_append(as, s, length);
2210 	archive_wstring_free(&aws);
2211 	return (r);
2212 }
2213 
2214 /*
2215  * Test whether MBS ==> WCS is okay.
2216  */
2217 static int
invalid_mbs(const void * _p,size_t n,struct archive_string_conv * sc)2218 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2219 {
2220 	const char *p = (const char *)_p;
2221 	unsigned codepage;
2222 	DWORD mbflag = MB_ERR_INVALID_CHARS;
2223 
2224 	if (sc->flag & SCONV_FROM_CHARSET)
2225 		codepage = sc->to_cp;
2226 	else
2227 		codepage = sc->from_cp;
2228 
2229 	if (codepage == CP_C_LOCALE)
2230 		return (0);
2231 	if (codepage != CP_UTF8)
2232 		mbflag |= MB_PRECOMPOSED;
2233 
2234 	if (n > (size_t)INT_MAX)
2235 		return (-1); /* Invalid */
2236 	if (MultiByteToWideChar(codepage, mbflag, p, (int)n, NULL, 0) == 0)
2237 		return (-1); /* Invalid */
2238 	return (0); /* Okay */
2239 }
2240 
2241 #else
2242 
2243 /*
2244  * Test whether MBS ==> WCS is okay.
2245  */
2246 static int
invalid_mbs(const void * _p,size_t n,struct archive_string_conv * sc)2247 invalid_mbs(const void *_p, size_t n, struct archive_string_conv *sc)
2248 {
2249 	const char *p = (const char *)_p;
2250 	size_t r;
2251 
2252 #if HAVE_MBRTOWC
2253 	mbstate_t shift_state;
2254 
2255 	memset(&shift_state, 0, sizeof(shift_state));
2256 #else
2257 	/* Clear the shift state before starting. */
2258 	mbtowc(NULL, NULL, 0);
2259 #endif
2260 	while (n) {
2261 		wchar_t wc;
2262 
2263 #if HAVE_MBRTOWC
2264 		r = mbrtowc(&wc, p, n, &shift_state);
2265 #else
2266 		r = mbtowc(&wc, p, n);
2267 #endif
2268 		if (r == (size_t)-1 || r == (size_t)-2)
2269 			return (-1);/* Invalid. */
2270 		if (r == 0)
2271 			break;
2272 		p += r;
2273 		n -= r;
2274 	}
2275 	(void)sc; /* UNUSED */
2276 	return (0); /* All Okey. */
2277 }
2278 
2279 #endif /* defined(_WIN32) && !defined(__CYGWIN__) */
2280 
2281 /*
2282  * Basically returns -1 because we cannot make a conversion of charset
2283  * without iconv but in some cases this would return 0.
2284  * Returns 0 if all copied characters are ASCII.
2285  * Returns 0 if both from-locale and to-locale are the same and those
2286  * can be WCS with no error.
2287  */
2288 static int
best_effort_strncat_in_locale(struct archive_string * as,const void * _p,size_t length,struct archive_string_conv * sc)2289 best_effort_strncat_in_locale(struct archive_string *as, const void *_p,
2290     size_t length, struct archive_string_conv *sc)
2291 {
2292 	size_t remaining;
2293 	const uint8_t *itp;
2294 	int return_value = 0; /* success */
2295 
2296 	/*
2297 	 * If both from-locale and to-locale is the same, this makes a copy.
2298 	 * And then this checks all copied MBS can be WCS if so returns 0.
2299 	 */
2300 	if (sc->same) {
2301 		if (archive_string_append(as, _p, length) == NULL)
2302 			return (-1);/* No memory */
2303 		return (invalid_mbs(_p, length, sc));
2304 	}
2305 
2306 	/*
2307 	 * If a character is ASCII, this just copies it. If not, this
2308 	 * assigns '?' character instead but in UTF-8 locale this assigns
2309 	 * byte sequence 0xEF 0xBD 0xBD, which are code point U+FFFD,
2310 	 * a Replacement Character in Unicode.
2311 	 */
2312 
2313 	remaining = length;
2314 	itp = (const uint8_t *)_p;
2315 	while (*itp && remaining > 0) {
2316 		if (*itp > 127) {
2317 			// Non-ASCII: Substitute with suitable replacement
2318 			if (sc->flag & SCONV_TO_UTF8) {
2319 				if (archive_string_append(as, utf8_replacement_char, sizeof(utf8_replacement_char)) == NULL) {
2320 					__archive_errx(1, "Out of memory");
2321 				}
2322 			} else {
2323 				archive_strappend_char(as, '?');
2324 			}
2325 			return_value = -1;
2326 		} else {
2327 			archive_strappend_char(as, *itp);
2328 		}
2329 		++itp;
2330 	}
2331 	return (return_value);
2332 }
2333 
2334 
2335 /*
2336  * Unicode conversion functions.
2337  *   - UTF-8 <===> UTF-8 in removing surrogate pairs.
2338  *   - UTF-8 NFD ===> UTF-8 NFC in removing surrogate pairs.
2339  *   - UTF-8 made by libarchive 2.x ===> UTF-8.
2340  *   - UTF-16BE <===> UTF-8.
2341  *
2342  */
2343 
2344 /*
2345  * Utility to convert a single UTF-8 sequence.
2346  *
2347  * Usually return used bytes, return used byte in negative value when
2348  * a unicode character is replaced with U+FFFD.
2349  * See also http://unicode.org/review/pr-121.html Public Review Issue #121
2350  * Recommended Practice for Replacement Characters.
2351  */
2352 static int
_utf8_to_unicode(uint32_t * pwc,const char * s,size_t n)2353 _utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2354 {
2355 	static const char utf8_count[256] = {
2356 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 00 - 0F */
2357 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 10 - 1F */
2358 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20 - 2F */
2359 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30 - 3F */
2360 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40 - 4F */
2361 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 50 - 5F */
2362 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60 - 6F */
2363 		 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 70 - 7F */
2364 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 80 - 8F */
2365 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 90 - 9F */
2366 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* A0 - AF */
2367 		 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* B0 - BF */
2368 		 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* C0 - CF */
2369 		 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/* D0 - DF */
2370 		 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,/* E0 - EF */
2371 		 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
2372 	};
2373 	int ch, i;
2374 	int cnt;
2375 	uint32_t wc;
2376 
2377 	/* Sanity check. */
2378 	if (n == 0)
2379 		return (0);
2380 	/*
2381 	 * Decode 1-4 bytes depending on the value of the first byte.
2382 	 */
2383 	ch = (unsigned char)*s;
2384 	if (ch == 0)
2385 		return (0); /* Standard:  return 0 for end-of-string. */
2386 	cnt = utf8_count[ch];
2387 
2388 	/* Invalid sequence or there are not plenty bytes. */
2389 	if (n < (size_t)cnt) {
2390 		cnt = (int)n;
2391 		for (i = 1; i < cnt; i++) {
2392 			if ((s[i] & 0xc0) != 0x80) {
2393 				cnt = i;
2394 				break;
2395 			}
2396 		}
2397 		goto invalid_sequence;
2398 	}
2399 
2400 	/* Make a Unicode code point from a single UTF-8 sequence. */
2401 	switch (cnt) {
2402 	case 1:	/* 1 byte sequence. */
2403 		*pwc = ch & 0x7f;
2404 		return (cnt);
2405 	case 2:	/* 2 bytes sequence. */
2406 		if ((s[1] & 0xc0) != 0x80) {
2407 			cnt = 1;
2408 			goto invalid_sequence;
2409 		}
2410 		*pwc = ((ch & 0x1f) << 6) | (s[1] & 0x3f);
2411 		return (cnt);
2412 	case 3:	/* 3 bytes sequence. */
2413 		if ((s[1] & 0xc0) != 0x80) {
2414 			cnt = 1;
2415 			goto invalid_sequence;
2416 		}
2417 		if ((s[2] & 0xc0) != 0x80) {
2418 			cnt = 2;
2419 			goto invalid_sequence;
2420 		}
2421 		wc = ((ch & 0x0f) << 12)
2422 		    | ((s[1] & 0x3f) << 6)
2423 		    | (s[2] & 0x3f);
2424 		if (wc < 0x800)
2425 			goto invalid_sequence;/* Overlong sequence. */
2426 		break;
2427 	case 4:	/* 4 bytes sequence. */
2428 		if ((s[1] & 0xc0) != 0x80) {
2429 			cnt = 1;
2430 			goto invalid_sequence;
2431 		}
2432 		if ((s[2] & 0xc0) != 0x80) {
2433 			cnt = 2;
2434 			goto invalid_sequence;
2435 		}
2436 		if ((s[3] & 0xc0) != 0x80) {
2437 			cnt = 3;
2438 			goto invalid_sequence;
2439 		}
2440 		wc = ((ch & 0x07) << 18)
2441 		    | ((s[1] & 0x3f) << 12)
2442 		    | ((s[2] & 0x3f) << 6)
2443 		    | (s[3] & 0x3f);
2444 		if (wc < 0x10000)
2445 			goto invalid_sequence;/* Overlong sequence. */
2446 		break;
2447 	default: /* Others are all invalid sequence. */
2448 		if (ch == 0xc0 || ch == 0xc1)
2449 			cnt = 2;
2450 		else if (ch >= 0xf5 && ch <= 0xf7)
2451 			cnt = 4;
2452 		else if (ch >= 0xf8 && ch <= 0xfb)
2453 			cnt = 5;
2454 		else if (ch == 0xfc || ch == 0xfd)
2455 			cnt = 6;
2456 		else
2457 			cnt = 1;
2458 		if (n < (size_t)cnt)
2459 			cnt = (int)n;
2460 		for (i = 1; i < cnt; i++) {
2461 			if ((s[i] & 0xc0) != 0x80) {
2462 				cnt = i;
2463 				break;
2464 			}
2465 		}
2466 		goto invalid_sequence;
2467 	}
2468 
2469 	/* The code point larger than 0x10FFFF is not legal
2470 	 * Unicode values. */
2471 	if (wc > UNICODE_MAX)
2472 		goto invalid_sequence;
2473 	/* Correctly gets a Unicode, returns used bytes. */
2474 	*pwc = wc;
2475 	return (cnt);
2476 invalid_sequence:
2477 	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2478 	return (cnt * -1);
2479 }
2480 
2481 static int
utf8_to_unicode(uint32_t * pwc,const char * s,size_t n)2482 utf8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2483 {
2484 	int cnt;
2485 
2486 	cnt = _utf8_to_unicode(pwc, s, n);
2487 	/* Any of Surrogate pair is not legal Unicode values. */
2488 	if (cnt == 3 && IS_SURROGATE_PAIR_LA(*pwc))
2489 		return (-3);
2490 	return (cnt);
2491 }
2492 
2493 static inline uint32_t
combine_surrogate_pair(uint32_t uc,uint32_t uc2)2494 combine_surrogate_pair(uint32_t uc, uint32_t uc2)
2495 {
2496 	uc -= 0xD800;
2497 	uc *= 0x400;
2498 	uc += uc2 - 0xDC00;
2499 	uc += 0x10000;
2500 	return (uc);
2501 }
2502 
2503 /*
2504  * Convert a single UTF-8/CESU-8 sequence to a Unicode code point in
2505  * removing surrogate pairs.
2506  *
2507  * CESU-8: The Compatibility Encoding Scheme for UTF-16.
2508  *
2509  * Usually return used bytes, return used byte in negative value when
2510  * a unicode character is replaced with U+FFFD.
2511  */
2512 static int
cesu8_to_unicode(uint32_t * pwc,const char * s,size_t n)2513 cesu8_to_unicode(uint32_t *pwc, const char *s, size_t n)
2514 {
2515 	uint32_t wc = 0;
2516 	int cnt;
2517 
2518 	cnt = _utf8_to_unicode(&wc, s, n);
2519 	if (cnt == 3 && IS_HIGH_SURROGATE_LA(wc)) {
2520 		uint32_t wc2 = 0;
2521 		if (n - 3 < 3) {
2522 			/* Invalid byte sequence. */
2523 			goto invalid_sequence;
2524 		}
2525 		cnt = _utf8_to_unicode(&wc2, s+3, n-3);
2526 		if (cnt != 3 || !IS_LOW_SURROGATE_LA(wc2)) {
2527 			/* Invalid byte sequence. */
2528 			goto invalid_sequence;
2529 		}
2530 		wc = combine_surrogate_pair(wc, wc2);
2531 		cnt = 6;
2532 	} else if (cnt == 3 && IS_LOW_SURROGATE_LA(wc)) {
2533 		/* Invalid byte sequence. */
2534 		goto invalid_sequence;
2535 	}
2536 	*pwc = wc;
2537 	return (cnt);
2538 invalid_sequence:
2539 	*pwc = UNICODE_R_CHAR;/* set the Replacement Character instead. */
2540 	if (cnt > 0)
2541 		cnt *= -1;
2542 	return (cnt);
2543 }
2544 
2545 /*
2546  * Convert a Unicode code point to a single UTF-8 sequence.
2547  *
2548  * NOTE:This function does not check if the Unicode is legal or not.
2549  * Please you definitely check it before calling this.
2550  */
2551 static size_t
unicode_to_utf8(char * p,size_t remaining,uint32_t uc)2552 unicode_to_utf8(char *p, size_t remaining, uint32_t uc)
2553 {
2554 	char *_p = p;
2555 
2556 	/* Invalid Unicode char maps to Replacement character */
2557 	if (uc > UNICODE_MAX)
2558 		uc = UNICODE_R_CHAR;
2559 	/* Translate code point to UTF8 */
2560 	if (uc <= 0x7f) {
2561 		if (remaining == 0)
2562 			return (0);
2563 		*p++ = (char)uc;
2564 	} else if (uc <= 0x7ff) {
2565 		if (remaining < 2)
2566 			return (0);
2567 		*p++ = 0xc0 | ((uc >> 6) & 0x1f);
2568 		*p++ = 0x80 | (uc & 0x3f);
2569 	} else if (uc <= 0xffff) {
2570 		if (remaining < 3)
2571 			return (0);
2572 		*p++ = 0xe0 | ((uc >> 12) & 0x0f);
2573 		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2574 		*p++ = 0x80 | (uc & 0x3f);
2575 	} else {
2576 		if (remaining < 4)
2577 			return (0);
2578 		*p++ = 0xf0 | ((uc >> 18) & 0x07);
2579 		*p++ = 0x80 | ((uc >> 12) & 0x3f);
2580 		*p++ = 0x80 | ((uc >> 6) & 0x3f);
2581 		*p++ = 0x80 | (uc & 0x3f);
2582 	}
2583 	return (p - _p);
2584 }
2585 
2586 static int
utf16be_to_unicode(uint32_t * pwc,const char * s,size_t n)2587 utf16be_to_unicode(uint32_t *pwc, const char *s, size_t n)
2588 {
2589 	return (utf16_to_unicode(pwc, s, n, 1));
2590 }
2591 
2592 static int
utf16le_to_unicode(uint32_t * pwc,const char * s,size_t n)2593 utf16le_to_unicode(uint32_t *pwc, const char *s, size_t n)
2594 {
2595 	return (utf16_to_unicode(pwc, s, n, 0));
2596 }
2597 
2598 static int
utf16_to_unicode(uint32_t * pwc,const char * s,size_t n,int be)2599 utf16_to_unicode(uint32_t *pwc, const char *s, size_t n, int be)
2600 {
2601 	const char *utf16 = s;
2602 	unsigned uc;
2603 
2604 	if (n == 0)
2605 		return (0);
2606 	if (n == 1) {
2607 		/* set the Replacement Character instead. */
2608 		*pwc = UNICODE_R_CHAR;
2609 		return (-1);
2610 	}
2611 
2612 	if (be)
2613 		uc = archive_be16dec(utf16);
2614 	else
2615 		uc = archive_le16dec(utf16);
2616 	utf16 += 2;
2617 
2618 	/* If this is a surrogate pair, assemble the full code point.*/
2619 	if (IS_HIGH_SURROGATE_LA(uc)) {
2620 		unsigned uc2;
2621 
2622 		if (n >= 4) {
2623 			if (be)
2624 				uc2 = archive_be16dec(utf16);
2625 			else
2626 				uc2 = archive_le16dec(utf16);
2627 		} else
2628 			uc2 = 0;
2629 		if (IS_LOW_SURROGATE_LA(uc2)) {
2630 			uc = combine_surrogate_pair(uc, uc2);
2631 			utf16 += 2;
2632 		} else {
2633 	 		/* Undescribed code point should be U+FFFD
2634 		 	* (replacement character). */
2635 			*pwc = UNICODE_R_CHAR;
2636 			return (-2);
2637 		}
2638 	}
2639 
2640 	/*
2641 	 * Surrogate pair values(0xd800 through 0xdfff) are only
2642 	 * used by UTF-16, so, after above calculation, the code
2643 	 * must not be surrogate values, and Unicode has no codes
2644 	 * larger than 0x10ffff. Thus, those are not legal Unicode
2645 	 * values.
2646 	 */
2647 	if (IS_SURROGATE_PAIR_LA(uc) || uc > UNICODE_MAX) {
2648 	 	/* Undescribed code point should be U+FFFD
2649 	 	* (replacement character). */
2650 		*pwc = UNICODE_R_CHAR;
2651 		return (((int)(utf16 - s)) * -1);
2652 	}
2653 	*pwc = uc;
2654 	return ((int)(utf16 - s));
2655 }
2656 
2657 static size_t
unicode_to_utf16be(char * p,size_t remaining,uint32_t uc)2658 unicode_to_utf16be(char *p, size_t remaining, uint32_t uc)
2659 {
2660 	char *utf16 = p;
2661 
2662 	if (uc > 0xffff) {
2663 		/* We have a code point that won't fit into a
2664 		 * wchar_t; convert it to a surrogate pair. */
2665 		if (remaining < 4)
2666 			return (0);
2667 		uc -= 0x10000;
2668 		archive_be16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2669 		archive_be16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2670 		return (4);
2671 	} else {
2672 		if (remaining < 2)
2673 			return (0);
2674 		archive_be16enc(utf16, (uint16_t)uc);
2675 		return (2);
2676 	}
2677 }
2678 
2679 static size_t
unicode_to_utf16le(char * p,size_t remaining,uint32_t uc)2680 unicode_to_utf16le(char *p, size_t remaining, uint32_t uc)
2681 {
2682 	char *utf16 = p;
2683 
2684 	if (uc > 0xffff) {
2685 		/* We have a code point that won't fit into a
2686 		 * wchar_t; convert it to a surrogate pair. */
2687 		if (remaining < 4)
2688 			return (0);
2689 		uc -= 0x10000;
2690 		archive_le16enc(utf16, ((uc >> 10) & 0x3ff) + 0xD800);
2691 		archive_le16enc(utf16+2, (uc & 0x3ff) + 0xDC00);
2692 		return (4);
2693 	} else {
2694 		if (remaining < 2)
2695 			return (0);
2696 		archive_le16enc(utf16, (uint16_t)uc);
2697 		return (2);
2698 	}
2699 }
2700 
2701 /*
2702  * Append new UTF-8 string to existing UTF-8 string.
2703  * Existing string is assumed to already be in proper form;
2704  * the new string will have invalid sequences replaced and
2705  * surrogate pairs canonicalized.
2706  */
2707 static int
strncat_from_utf8_to_utf8(struct archive_string * as,const void * _src,size_t len,struct archive_string_conv * sc)2708 strncat_from_utf8_to_utf8(struct archive_string *as, const void *_src,
2709     size_t len, struct archive_string_conv *sc)
2710 {
2711 	int ret = 0;
2712 	const char *src = _src;
2713 	(void)sc; /* UNUSED */
2714 
2715 	/* Pre-extend the destination */
2716 	if (archive_string_ensure(as, as->length + len + 1) == NULL)
2717 		return (-1);
2718 
2719 	/* Invariant: src points to the first UTF8 byte that hasn't
2720 	 * been copied to the destination `as`. */
2721 	for (;;) {
2722 		int n;
2723 		uint32_t uc;
2724 		const char *e = src;
2725 
2726 		/* Skip UTF-8 sequences until we reach end-of-string or
2727 		 * a code point that needs conversion. */
2728 		while ((n = utf8_to_unicode(&uc, e, len)) > 0) {
2729 			e += n;
2730 			len -= n;
2731 		}
2732 		/* Copy the part that doesn't need conversion */
2733 		if (e > src) {
2734 			if (archive_string_append(as, src, e - src) == NULL)
2735 				return (-1);
2736 			src = e;
2737 		}
2738 
2739 		if (n == 0) {
2740 			/* We reached end-of-string */
2741 			return (ret);
2742 		} else {
2743 			/* Next code point needs conversion */
2744 			char t[4];
2745 			size_t w;
2746 
2747 			/* Try decoding a surrogate pair */
2748 			if (n == -3 && IS_SURROGATE_PAIR_LA(uc)) {
2749 				n = cesu8_to_unicode(&uc, src, len);
2750 			}
2751 			/* Not a (valid) surrogate, so use a replacement char */
2752 			if (n < 0) {
2753 				ret = -1; /* Return -1 if we used any replacement */
2754 				n *= -1;
2755 			}
2756 			/* Consume converted code point */
2757 			src += n;
2758 			len -= n;
2759 			/* Convert and append new UTF-8 sequence. */
2760 			w = unicode_to_utf8(t, sizeof(t), uc);
2761 			if (archive_string_append(as, t, w) == NULL)
2762 				return (-1);
2763 		}
2764 	}
2765 }
2766 
2767 static int
archive_string_append_unicode(struct archive_string * as,const void * _p,size_t len,struct archive_string_conv * sc)2768 archive_string_append_unicode(struct archive_string *as, const void *_p,
2769     size_t len, struct archive_string_conv *sc)
2770 {
2771 	const char *s;
2772 	char *p, *endp;
2773 	uint32_t uc;
2774 	size_t w;
2775 	size_t ts, tm;
2776 	int n, ret = 0;
2777 	int (*parse)(uint32_t *, const char *, size_t);
2778 	size_t (*unparse)(char *, size_t, uint32_t);
2779 
2780 	if (sc->flag & SCONV_TO_UTF16BE) {
2781 		unparse = unicode_to_utf16be;
2782 		ts = 2;
2783 	} else if (sc->flag & SCONV_TO_UTF16LE) {
2784 		unparse = unicode_to_utf16le;
2785 		ts = 2;
2786 	} else if (sc->flag & SCONV_TO_UTF8) {
2787 		unparse = unicode_to_utf8;
2788 		ts = 1;
2789 	} else {
2790 		/*
2791 		 * This case is going to be converted to another
2792 		 * character-set through iconv.
2793 		 */
2794 		if (sc->flag & SCONV_FROM_UTF16BE) {
2795 			unparse = unicode_to_utf16be;
2796 			ts = 2;
2797 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
2798 			unparse = unicode_to_utf16le;
2799 			ts = 2;
2800 		} else {
2801 			unparse = unicode_to_utf8;
2802 			ts = 1;
2803 		}
2804 	}
2805 
2806 	if (sc->flag & SCONV_FROM_UTF16BE) {
2807 		parse = utf16be_to_unicode;
2808 		tm = 1;
2809 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
2810 		parse = utf16le_to_unicode;
2811 		tm = 1;
2812 	} else {
2813 		parse = cesu8_to_unicode;
2814 		tm = ts;
2815 	}
2816 
2817 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
2818 		return (-1);
2819 
2820 	s = (const char *)_p;
2821 	p = as->s + as->length;
2822 	endp = as->s + as->buffer_length - ts;
2823 	while ((n = parse(&uc, s, len)) != 0) {
2824 		if (n < 0) {
2825 			/* Use a replaced unicode character. */
2826 			n *= -1;
2827 			ret = -1;
2828 		}
2829 		s += n;
2830 		len -= n;
2831 		while ((w = unparse(p, endp - p, uc)) == 0) {
2832 			/* There is not enough output buffer so
2833 			 * we have to expand it. */
2834 			as->length = p - as->s;
2835 			if (archive_string_ensure(as,
2836 			    as->buffer_length + len * tm + ts) == NULL)
2837 				return (-1);
2838 			p = as->s + as->length;
2839 			endp = as->s + as->buffer_length - ts;
2840 		}
2841 		p += w;
2842 	}
2843 	as->length = p - as->s;
2844 	as->s[as->length] = '\0';
2845 	if (ts == 2)
2846 		as->s[as->length+1] = '\0';
2847 	return (ret);
2848 }
2849 
2850 /*
2851  * Following Constants for Hangul compositions this information comes from
2852  * Unicode Standard Annex #15  http://unicode.org/reports/tr15/
2853  */
2854 #define HC_SBASE	0xAC00
2855 #define HC_LBASE	0x1100
2856 #define HC_VBASE	0x1161
2857 #define HC_TBASE	0x11A7
2858 #define HC_LCOUNT	19
2859 #define HC_VCOUNT	21
2860 #define HC_TCOUNT	28
2861 #define HC_NCOUNT	(HC_VCOUNT * HC_TCOUNT)
2862 #define HC_SCOUNT	(HC_LCOUNT * HC_NCOUNT)
2863 
2864 static uint32_t
get_nfc(uint32_t uc,uint32_t uc2)2865 get_nfc(uint32_t uc, uint32_t uc2)
2866 {
2867 	int t, b;
2868 
2869 	t = 0;
2870 	b = sizeof(u_composition_table)/sizeof(u_composition_table[0]) -1;
2871 	while (b >= t) {
2872 		int m = (t + b) / 2;
2873 		if (u_composition_table[m].cp1 < uc)
2874 			t = m + 1;
2875 		else if (u_composition_table[m].cp1 > uc)
2876 			b = m - 1;
2877 		else if (u_composition_table[m].cp2 < uc2)
2878 			t = m + 1;
2879 		else if (u_composition_table[m].cp2 > uc2)
2880 			b = m - 1;
2881 		else
2882 			return (u_composition_table[m].nfc);
2883 	}
2884 	return (0);
2885 }
2886 
2887 #define FDC_MAX 10	/* The maximum number of Following Decomposable
2888 			 * Characters. */
2889 
2890 /*
2891  * Update first code point.
2892  */
2893 #define UPDATE_UC(new_uc)	do {		\
2894 	uc = new_uc;				\
2895 	ucptr = NULL;				\
2896 } while (0)
2897 
2898 /*
2899  * Replace first code point with second code point.
2900  */
2901 #define REPLACE_UC_WITH_UC2() do {		\
2902 	uc = uc2;				\
2903 	ucptr = uc2ptr;				\
2904 	n = n2;					\
2905 } while (0)
2906 
2907 #define EXPAND_BUFFER() do {			\
2908 	as->length = p - as->s;			\
2909 	if (archive_string_ensure(as,		\
2910 	    as->buffer_length + len * tm + ts) == NULL)\
2911 		return (-1);			\
2912 	p = as->s + as->length;			\
2913 	endp = as->s + as->buffer_length - ts;	\
2914 } while (0)
2915 
2916 #define UNPARSE(p, endp, uc)	do {		\
2917 	while ((w = unparse(p, (endp) - (p), uc)) == 0) {\
2918 		EXPAND_BUFFER();		\
2919 	}					\
2920 	p += w;					\
2921 } while (0)
2922 
2923 /*
2924  * Write first code point.
2925  * If the code point has not be changed from its original code,
2926  * this just copies it from its original buffer pointer.
2927  * If not, this converts it to UTF-8 byte sequence and copies it.
2928  */
2929 #define WRITE_UC()	do {			\
2930 	if (ucptr) {				\
2931 		if (p + n > endp)		\
2932 			EXPAND_BUFFER();	\
2933 		switch (n) {			\
2934 		case 4:				\
2935 			*p++ = *ucptr++;	\
2936 			/* FALL THROUGH */	\
2937 		case 3:				\
2938 			*p++ = *ucptr++;	\
2939 			/* FALL THROUGH */	\
2940 		case 2:				\
2941 			*p++ = *ucptr++;	\
2942 			/* FALL THROUGH */	\
2943 		case 1:				\
2944 			*p++ = *ucptr;		\
2945 			break;			\
2946 		}				\
2947 		ucptr = NULL;			\
2948 	} else {				\
2949 		UNPARSE(p, endp, uc);		\
2950 	}					\
2951 } while (0)
2952 
2953 /*
2954  * Collect following decomposable code points.
2955  */
2956 #define COLLECT_CPS(start)	do {		\
2957 	int _i;					\
2958 	for (_i = start; _i < FDC_MAX ; _i++) {	\
2959 		nx = parse(&ucx[_i], s, len);	\
2960 		if (nx <= 0)			\
2961 			break;			\
2962 		cx = CCC(ucx[_i]);		\
2963 		if (cl >= cx && cl != 228 && cx != 228)\
2964 			break;			\
2965 		s += nx;			\
2966 		len -= nx;			\
2967 		cl = cx;			\
2968 		ccx[_i] = cx;			\
2969 	}					\
2970 	if (_i >= FDC_MAX) {			\
2971 		ret = -1;			\
2972 		ucx_size = FDC_MAX;		\
2973 	} else					\
2974 		ucx_size = _i;			\
2975 } while (0)
2976 
2977 /*
2978  * Normalize UTF-8/UTF-16BE characters to Form C and copy the result.
2979  *
2980  * TODO: Convert composition exclusions, which are never converted
2981  * from NFC,NFD,NFKC and NFKD, to Form C.
2982  */
2983 static int
archive_string_normalize_C(struct archive_string * as,const void * _p,size_t len,struct archive_string_conv * sc)2984 archive_string_normalize_C(struct archive_string *as, const void *_p,
2985     size_t len, struct archive_string_conv *sc)
2986 {
2987 	const char *s = (const char *)_p;
2988 	char *p, *endp;
2989 	uint32_t uc, uc2;
2990 	size_t w;
2991 	int always_replace, n, n2, ret = 0, spair, ts, tm;
2992 	int (*parse)(uint32_t *, const char *, size_t);
2993 	size_t (*unparse)(char *, size_t, uint32_t);
2994 
2995 	always_replace = 1;
2996 	ts = 1;/* text size. */
2997 	if (sc->flag & SCONV_TO_UTF16BE) {
2998 		unparse = unicode_to_utf16be;
2999 		ts = 2;
3000 		if (sc->flag & SCONV_FROM_UTF16BE)
3001 			always_replace = 0;
3002 	} else if (sc->flag & SCONV_TO_UTF16LE) {
3003 		unparse = unicode_to_utf16le;
3004 		ts = 2;
3005 		if (sc->flag & SCONV_FROM_UTF16LE)
3006 			always_replace = 0;
3007 	} else if (sc->flag & SCONV_TO_UTF8) {
3008 		unparse = unicode_to_utf8;
3009 		if (sc->flag & SCONV_FROM_UTF8)
3010 			always_replace = 0;
3011 	} else {
3012 		/*
3013 		 * This case is going to be converted to another
3014 		 * character-set through iconv.
3015 		 */
3016 		always_replace = 0;
3017 		if (sc->flag & SCONV_FROM_UTF16BE) {
3018 			unparse = unicode_to_utf16be;
3019 			ts = 2;
3020 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
3021 			unparse = unicode_to_utf16le;
3022 			ts = 2;
3023 		} else {
3024 			unparse = unicode_to_utf8;
3025 		}
3026 	}
3027 
3028 	if (sc->flag & SCONV_FROM_UTF16BE) {
3029 		parse = utf16be_to_unicode;
3030 		tm = 1;
3031 		spair = 4;/* surrogate pair size in UTF-16. */
3032 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
3033 		parse = utf16le_to_unicode;
3034 		tm = 1;
3035 		spair = 4;/* surrogate pair size in UTF-16. */
3036 	} else {
3037 		parse = cesu8_to_unicode;
3038 		tm = ts;
3039 		spair = 6;/* surrogate pair size in UTF-8. */
3040 	}
3041 
3042 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3043 		return (-1);
3044 
3045 	p = as->s + as->length;
3046 	endp = as->s + as->buffer_length - ts;
3047 	while ((n = parse(&uc, s, len)) != 0) {
3048 		const char *ucptr, *uc2ptr;
3049 
3050 		if (n < 0) {
3051 			/* Use a replaced unicode character. */
3052 			UNPARSE(p, endp, uc);
3053 			s += n*-1;
3054 			len -= n*-1;
3055 			ret = -1;
3056 			continue;
3057 		} else if (n == spair || always_replace)
3058 			/* uc is converted from a surrogate pair.
3059 			 * this should be treated as a changed code. */
3060 			ucptr = NULL;
3061 		else
3062 			ucptr = s;
3063 		s += n;
3064 		len -= n;
3065 
3066 		/* Read second code point. */
3067 		while ((n2 = parse(&uc2, s, len)) > 0) {
3068 			uint32_t ucx[FDC_MAX];
3069 			int ccx[FDC_MAX];
3070 			int cl, cx, i, nx, ucx_size;
3071 			int LIndex,SIndex;
3072 			uint32_t nfc;
3073 
3074 			if (n2 == spair || always_replace)
3075 				/* uc2 is converted from a surrogate pair.
3076 			 	 * this should be treated as a changed code. */
3077 				uc2ptr = NULL;
3078 			else
3079 				uc2ptr = s;
3080 			s += n2;
3081 			len -= n2;
3082 
3083 			/*
3084 			 * If current second code point is out of decomposable
3085 			 * code points, finding compositions is unneeded.
3086 			 */
3087 			if (!IS_DECOMPOSABLE_BLOCK(uc2)) {
3088 				WRITE_UC();
3089 				REPLACE_UC_WITH_UC2();
3090 				continue;
3091 			}
3092 
3093 			/*
3094 			 * Try to combine current code points.
3095 			 */
3096 			/*
3097 			 * We have to combine Hangul characters according to
3098 			 * http://uniicode.org/reports/tr15/#Hangul
3099 			 */
3100 			if (0 <= (LIndex = uc - HC_LBASE) &&
3101 			    LIndex < HC_LCOUNT) {
3102 				/*
3103 				 * Hangul Composition.
3104 				 * 1. Two current code points are L and V.
3105 				 */
3106 				int VIndex = uc2 - HC_VBASE;
3107 				if (0 <= VIndex && VIndex < HC_VCOUNT) {
3108 					/* Make syllable of form LV. */
3109 					UPDATE_UC(HC_SBASE +
3110 					    (LIndex * HC_VCOUNT + VIndex) *
3111 					     HC_TCOUNT);
3112 				} else {
3113 					WRITE_UC();
3114 					REPLACE_UC_WITH_UC2();
3115 				}
3116 				continue;
3117 			} else if (0 <= (SIndex = uc - HC_SBASE) &&
3118 			    SIndex < HC_SCOUNT && (SIndex % HC_TCOUNT) == 0) {
3119 				/*
3120 				 * Hangul Composition.
3121 				 * 2. Two current code points are LV and T.
3122 				 */
3123 				int TIndex = uc2 - HC_TBASE;
3124 				if (0 < TIndex && TIndex < HC_TCOUNT) {
3125 					/* Make syllable of form LVT. */
3126 					UPDATE_UC(uc + TIndex);
3127 				} else {
3128 					WRITE_UC();
3129 					REPLACE_UC_WITH_UC2();
3130 				}
3131 				continue;
3132 			} else if ((nfc = get_nfc(uc, uc2)) != 0) {
3133 				/* A composition to current code points
3134 				 * is found. */
3135 				UPDATE_UC(nfc);
3136 				continue;
3137 			} else if ((cl = CCC(uc2)) == 0) {
3138 				/* Clearly 'uc2' the second code point is not
3139 				 * a decomposable code. */
3140 				WRITE_UC();
3141 				REPLACE_UC_WITH_UC2();
3142 				continue;
3143 			}
3144 
3145 			/*
3146 			 * Collect following decomposable code points.
3147 			 */
3148 			cx = 0;
3149 			ucx[0] = uc2;
3150 			ccx[0] = cl;
3151 			COLLECT_CPS(1);
3152 
3153 			/*
3154 			 * Find a composed code in the collected code points.
3155 			 */
3156 			i = 1;
3157 			while (i < ucx_size) {
3158 				int j;
3159 
3160 				if ((nfc = get_nfc(uc, ucx[i])) == 0) {
3161 					i++;
3162 					continue;
3163 				}
3164 
3165 				/*
3166 				 * nfc is composed of uc and ucx[i].
3167 				 */
3168 				UPDATE_UC(nfc);
3169 
3170 				/*
3171 				 * Remove ucx[i] by shifting
3172 				 * following code points.
3173 				 */
3174 				for (j = i; j+1 < ucx_size; j++) {
3175 					ucx[j] = ucx[j+1];
3176 					ccx[j] = ccx[j+1];
3177 				}
3178 				ucx_size --;
3179 
3180 				/*
3181 				 * Collect following code points blocked
3182 				 * by ucx[i] the removed code point.
3183 				 */
3184 				if (ucx_size > 0 && i == ucx_size &&
3185 				    nx > 0 && cx == cl) {
3186 					cl =  ccx[ucx_size-1];
3187 					COLLECT_CPS(ucx_size);
3188 				}
3189 				/*
3190 				 * Restart finding a composed code with
3191 				 * the updated uc from the top of the
3192 				 * collected code points.
3193 				 */
3194 				i = 0;
3195 			}
3196 
3197 			/*
3198 			 * Apparently the current code points are not
3199 			 * decomposed characters or already composed.
3200 			 */
3201 			WRITE_UC();
3202 			for (i = 0; i < ucx_size; i++)
3203 				UNPARSE(p, endp, ucx[i]);
3204 
3205 			/*
3206 			 * Flush out remaining canonical combining characters.
3207 			 */
3208 			if (nx > 0 && cx == cl && len > 0) {
3209 				while ((nx = parse(&ucx[0], s, len))
3210 				    > 0) {
3211 					cx = CCC(ucx[0]);
3212 					if (cl > cx)
3213 						break;
3214 					s += nx;
3215 					len -= nx;
3216 					cl = cx;
3217 					UNPARSE(p, endp, ucx[0]);
3218 				}
3219 			}
3220 			break;
3221 		}
3222 		if (n2 < 0) {
3223 			WRITE_UC();
3224 			/* Use a replaced unicode character. */
3225 			UNPARSE(p, endp, uc2);
3226 			s += n2*-1;
3227 			len -= n2*-1;
3228 			ret = -1;
3229 			continue;
3230 		} else if (n2 == 0) {
3231 			WRITE_UC();
3232 			break;
3233 		}
3234 	}
3235 	as->length = p - as->s;
3236 	as->s[as->length] = '\0';
3237 	if (ts == 2)
3238 		as->s[as->length+1] = '\0';
3239 	return (ret);
3240 }
3241 
3242 static int
get_nfd(uint32_t * cp1,uint32_t * cp2,uint32_t uc)3243 get_nfd(uint32_t *cp1, uint32_t *cp2, uint32_t uc)
3244 {
3245 	int t, b;
3246 
3247 	/*
3248 	 * These are not converted to NFD on Mac OS.
3249 	 */
3250 	if ((uc >= 0x2000 && uc <= 0x2FFF) ||
3251 	    (uc >= 0xF900 && uc <= 0xFAFF) ||
3252 	    (uc >= 0x2F800 && uc <= 0x2FAFF))
3253 		return (0);
3254 	/*
3255 	 * Those code points are not converted to NFD on Mac OS.
3256 	 * I do not know the reason because it is undocumented.
3257 	 *   NFC        NFD
3258 	 *   1109A  ==> 11099 110BA
3259 	 *   1109C  ==> 1109B 110BA
3260 	 *   110AB  ==> 110A5 110BA
3261 	 */
3262 	if (uc == 0x1109A || uc == 0x1109C || uc == 0x110AB)
3263 		return (0);
3264 
3265 	t = 0;
3266 	b = sizeof(u_decomposition_table)/sizeof(u_decomposition_table[0]) -1;
3267 	while (b >= t) {
3268 		int m = (t + b) / 2;
3269 		if (u_decomposition_table[m].nfc < uc)
3270 			t = m + 1;
3271 		else if (u_decomposition_table[m].nfc > uc)
3272 			b = m - 1;
3273 		else {
3274 			*cp1 = u_decomposition_table[m].cp1;
3275 			*cp2 = u_decomposition_table[m].cp2;
3276 			return (1);
3277 		}
3278 	}
3279 	return (0);
3280 }
3281 
3282 #define REPLACE_UC_WITH(cp) do {		\
3283 	uc = cp;				\
3284 	ucptr = NULL;				\
3285 } while (0)
3286 
3287 /*
3288  * Normalize UTF-8 characters to Form D and copy the result.
3289  */
3290 static int
archive_string_normalize_D(struct archive_string * as,const void * _p,size_t len,struct archive_string_conv * sc)3291 archive_string_normalize_D(struct archive_string *as, const void *_p,
3292     size_t len, struct archive_string_conv *sc)
3293 {
3294 	const char *s = (const char *)_p;
3295 	char *p, *endp;
3296 	uint32_t uc, uc2;
3297 	size_t w;
3298 	int always_replace, n, n2, ret = 0, spair, ts, tm;
3299 	int (*parse)(uint32_t *, const char *, size_t);
3300 	size_t (*unparse)(char *, size_t, uint32_t);
3301 
3302 	always_replace = 1;
3303 	ts = 1;/* text size. */
3304 	if (sc->flag & SCONV_TO_UTF16BE) {
3305 		unparse = unicode_to_utf16be;
3306 		ts = 2;
3307 		if (sc->flag & SCONV_FROM_UTF16BE)
3308 			always_replace = 0;
3309 	} else if (sc->flag & SCONV_TO_UTF16LE) {
3310 		unparse = unicode_to_utf16le;
3311 		ts = 2;
3312 		if (sc->flag & SCONV_FROM_UTF16LE)
3313 			always_replace = 0;
3314 	} else if (sc->flag & SCONV_TO_UTF8) {
3315 		unparse = unicode_to_utf8;
3316 		if (sc->flag & SCONV_FROM_UTF8)
3317 			always_replace = 0;
3318 	} else {
3319 		/*
3320 		 * This case is going to be converted to another
3321 		 * character-set through iconv.
3322 		 */
3323 		always_replace = 0;
3324 		if (sc->flag & SCONV_FROM_UTF16BE) {
3325 			unparse = unicode_to_utf16be;
3326 			ts = 2;
3327 		} else if (sc->flag & SCONV_FROM_UTF16LE) {
3328 			unparse = unicode_to_utf16le;
3329 			ts = 2;
3330 		} else {
3331 			unparse = unicode_to_utf8;
3332 		}
3333 	}
3334 
3335 	if (sc->flag & SCONV_FROM_UTF16BE) {
3336 		parse = utf16be_to_unicode;
3337 		tm = 1;
3338 		spair = 4;/* surrogate pair size in UTF-16. */
3339 	} else if (sc->flag & SCONV_FROM_UTF16LE) {
3340 		parse = utf16le_to_unicode;
3341 		tm = 1;
3342 		spair = 4;/* surrogate pair size in UTF-16. */
3343 	} else {
3344 		parse = cesu8_to_unicode;
3345 		tm = ts;
3346 		spair = 6;/* surrogate pair size in UTF-8. */
3347 	}
3348 
3349 	if (archive_string_ensure(as, as->length + len * tm + ts) == NULL)
3350 		return (-1);
3351 
3352 	p = as->s + as->length;
3353 	endp = as->s + as->buffer_length - ts;
3354 	while ((n = parse(&uc, s, len)) != 0) {
3355 		const char *ucptr;
3356 		uint32_t cp1, cp2;
3357 		int SIndex;
3358 		struct {
3359 			uint32_t uc;
3360 			int ccc;
3361 		} fdc[FDC_MAX];
3362 		int fdi, fdj;
3363 		int ccc;
3364 
3365 check_first_code:
3366 		if (n < 0) {
3367 			/* Use a replaced unicode character. */
3368 			UNPARSE(p, endp, uc);
3369 			s += n*-1;
3370 			len -= n*-1;
3371 			ret = -1;
3372 			continue;
3373 		} else if (n == spair || always_replace)
3374 			/* uc is converted from a surrogate pair.
3375 			 * this should be treated as a changed code. */
3376 			ucptr = NULL;
3377 		else
3378 			ucptr = s;
3379 		s += n;
3380 		len -= n;
3381 
3382 		/* Hangul Decomposition. */
3383 		if ((SIndex = uc - HC_SBASE) >= 0 && SIndex < HC_SCOUNT) {
3384 			int L = HC_LBASE + SIndex / HC_NCOUNT;
3385 			int V = HC_VBASE + (SIndex % HC_NCOUNT) / HC_TCOUNT;
3386 			int T = HC_TBASE + SIndex % HC_TCOUNT;
3387 
3388 			REPLACE_UC_WITH(L);
3389 			WRITE_UC();
3390 			REPLACE_UC_WITH(V);
3391 			WRITE_UC();
3392 			if (T != HC_TBASE) {
3393 				REPLACE_UC_WITH(T);
3394 				WRITE_UC();
3395 			}
3396 			continue;
3397 		}
3398 		if (IS_DECOMPOSABLE_BLOCK(uc) && CCC(uc) != 0) {
3399 			WRITE_UC();
3400 			continue;
3401 		}
3402 
3403 		fdi = 0;
3404 		while (get_nfd(&cp1, &cp2, uc) && fdi < FDC_MAX) {
3405 			int k;
3406 
3407 			for (k = fdi; k > 0; k--)
3408 				fdc[k] = fdc[k-1];
3409 			fdc[0].ccc = CCC(cp2);
3410 			fdc[0].uc = cp2;
3411 			fdi++;
3412 			REPLACE_UC_WITH(cp1);
3413 		}
3414 
3415 		/* Read following code points. */
3416 		while ((n2 = parse(&uc2, s, len)) > 0 &&
3417 		    (ccc = CCC(uc2)) != 0 && fdi < FDC_MAX) {
3418 			int j, k;
3419 
3420 			s += n2;
3421 			len -= n2;
3422 			for (j = 0; j < fdi; j++) {
3423 				if (fdc[j].ccc > ccc)
3424 					break;
3425 			}
3426 			if (j < fdi) {
3427 				for (k = fdi; k > j; k--)
3428 					fdc[k] = fdc[k-1];
3429 				fdc[j].ccc = ccc;
3430 				fdc[j].uc = uc2;
3431 			} else {
3432 				fdc[fdi].ccc = ccc;
3433 				fdc[fdi].uc = uc2;
3434 			}
3435 			fdi++;
3436 		}
3437 
3438 		WRITE_UC();
3439 		for (fdj = 0; fdj < fdi; fdj++) {
3440 			REPLACE_UC_WITH(fdc[fdj].uc);
3441 			WRITE_UC();
3442 		}
3443 
3444 		if (n2 == 0)
3445 			break;
3446 		REPLACE_UC_WITH(uc2);
3447 		n = n2;
3448 		goto check_first_code;
3449 	}
3450 	as->length = p - as->s;
3451 	as->s[as->length] = '\0';
3452 	if (ts == 2)
3453 		as->s[as->length+1] = '\0';
3454 	return (ret);
3455 }
3456 
3457 /*
3458  * libarchive 2.x made incorrect UTF-8 strings in the wrong assumption
3459  * that WCS is Unicode. It is true for several platforms but some are false.
3460  * And then people who did not use UTF-8 locale on the non Unicode WCS
3461  * platform and made a tar file with libarchive(mostly bsdtar) 2.x. Those
3462  * now cannot get right filename from libarchive 3.x and later since we
3463  * fixed the wrong assumption and it is incompatible to older its versions.
3464  * So we provide special option, "compat-2x.x", for resolving it.
3465  * That option enable the string conversion of libarchive 2.x.
3466  *
3467  * Translates the wrong UTF-8 string made by libarchive 2.x into current
3468  * locale character set and appends to the archive_string.
3469  * Note: returns -1 if conversion fails.
3470  */
3471 static int
strncat_from_utf8_libarchive2(struct archive_string * as,const void * _p,size_t len,struct archive_string_conv * sc)3472 strncat_from_utf8_libarchive2(struct archive_string *as,
3473     const void *_p, size_t len, struct archive_string_conv *sc)
3474 {
3475 	const char *s;
3476 	int n;
3477 	char *p;
3478 	char *end;
3479 	uint32_t unicode;
3480 #if HAVE_WCRTOMB
3481 	mbstate_t shift_state;
3482 
3483 	memset(&shift_state, 0, sizeof(shift_state));
3484 #else
3485 	/* Clear the shift state before starting. */
3486 	wctomb(NULL, L'\0');
3487 #endif
3488 	(void)sc; /* UNUSED */
3489 	/*
3490 	 * Allocate buffer for MBS.
3491 	 * We need this allocation here since it is possible that
3492 	 * as->s is still NULL.
3493 	 */
3494 	if (archive_string_ensure(as, as->length + len + 1) == NULL)
3495 		return (-1);
3496 
3497 	s = (const char *)_p;
3498 	p = as->s + as->length;
3499 	end = as->s + as->buffer_length - MB_CUR_MAX -1;
3500 	while ((n = _utf8_to_unicode(&unicode, s, len)) != 0) {
3501 		wchar_t wc;
3502 
3503 		if (p >= end) {
3504 			as->length = p - as->s;
3505 			/* Re-allocate buffer for MBS. */
3506 			if (archive_string_ensure(as,
3507 			    as->length + max(len * 2,
3508 			    (size_t)MB_CUR_MAX) + 1) == NULL)
3509 				return (-1);
3510 			p = as->s + as->length;
3511 			end = as->s + as->buffer_length - MB_CUR_MAX -1;
3512 		}
3513 
3514 		/*
3515 		 * As libarchive 2.x, translates the UTF-8 characters into
3516 		 * wide-characters in the assumption that WCS is Unicode.
3517 		 */
3518 		if (n < 0) {
3519 			n *= -1;
3520 			wc = L'?';
3521 		} else
3522 			wc = (wchar_t)unicode;
3523 
3524 		s += n;
3525 		len -= n;
3526 		/*
3527 		 * Translates the wide-character into the current locale MBS.
3528 		 */
3529 #if HAVE_WCRTOMB
3530 		n = (int)wcrtomb(p, wc, &shift_state);
3531 #else
3532 		n = (int)wctomb(p, wc);
3533 #endif
3534 		if (n == -1)
3535 			return (-1);
3536 		p += n;
3537 	}
3538 	as->length = p - as->s;
3539 	as->s[as->length] = '\0';
3540 	return (0);
3541 }
3542 
3543 
3544 /*
3545  * Conversion functions between current locale dependent MBS and UTF-16BE.
3546  *   strncat_from_utf16be() : UTF-16BE --> MBS
3547  *   strncat_to_utf16be()   : MBS --> UTF16BE
3548  */
3549 
3550 #if defined(_WIN32) && !defined(__CYGWIN__)
3551 
3552 /*
3553  * Convert a UTF-16BE/LE string to current locale and copy the result.
3554  * Return -1 if conversion fails.
3555  */
3556 static int
win_strncat_from_utf16(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc,int be)3557 win_strncat_from_utf16(struct archive_string *as, const void *_p, size_t bytes,
3558     struct archive_string_conv *sc, int be)
3559 {
3560 	struct archive_string tmp;
3561 	const char *u16;
3562 	BOOL defchar;
3563 	char *mbs;
3564 	size_t mbs_size, b, ll;
3565 	int ret = 0;
3566 
3567 	bytes &= ~1;
3568 	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3569 		return (-1);
3570 
3571 	mbs = as->s + as->length;
3572 	mbs_size = as->buffer_length - as->length -1;
3573 
3574 	if (sc->to_cp == CP_C_LOCALE) {
3575 		/*
3576 		 * "C" locale special process.
3577 		 */
3578 		u16 = _p;
3579 		ll = 0;
3580 		for (b = 0; b < bytes; b += 2) {
3581 			uint16_t val;
3582 			if (be)
3583 				val = archive_be16dec(u16+b);
3584 			else
3585 				val = archive_le16dec(u16+b);
3586 			if (val > 255) {
3587 				*mbs++ = '?';
3588 				ret = -1;
3589 			} else
3590 				*mbs++ = (char)(val&0xff);
3591 			ll++;
3592 		}
3593 		as->length += ll;
3594 		as->s[as->length] = '\0';
3595 		return (ret);
3596 	}
3597 
3598 	archive_string_init(&tmp);
3599 	if (be) {
3600 		if (IS_BIG_ENDIAN) {
3601 			u16 = _p;
3602 		} else {
3603 			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3604 				return (-1);
3605 			memcpy(tmp.s, _p, bytes);
3606 			for (b = 0; b < bytes; b += 2) {
3607 				uint16_t val = archive_be16dec(tmp.s+b);
3608 				archive_le16enc(tmp.s+b, val);
3609 			}
3610 			u16 = tmp.s;
3611 		}
3612 	} else {
3613 		if (!IS_BIG_ENDIAN) {
3614 			u16 = _p;
3615 		} else {
3616 			if (archive_string_ensure(&tmp, bytes+2) == NULL)
3617 				return (-1);
3618 			memcpy(tmp.s, _p, bytes);
3619 			for (b = 0; b < bytes; b += 2) {
3620 				uint16_t val = archive_le16dec(tmp.s+b);
3621 				archive_be16enc(tmp.s+b, val);
3622 			}
3623 			u16 = tmp.s;
3624 		}
3625 	}
3626 
3627 	do {
3628 		int r;
3629 		defchar = 0;
3630 		/* WideCharToMultiByte is limited to int. */
3631 		if (bytes > (size_t)INT_MAX || mbs_size > (size_t)INT_MAX)
3632 			return (-1);
3633 		r = WideCharToMultiByte(sc->to_cp, 0,
3634 		    (LPCWSTR)u16, (int)bytes>>1, mbs, (int)mbs_size,
3635 			NULL, &defchar);
3636 		/* Exit loop if we succeeded */
3637 		if (r != 0 ||
3638 		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3639 			ll = (size_t)r;
3640 			break;
3641 		}
3642 		/* Else expand buffer and loop to try again. */
3643 		r = WideCharToMultiByte(sc->to_cp, 0,
3644 		    (LPCWSTR)u16, (int)bytes, NULL, 0, NULL, NULL);
3645 		ll = (size_t)r;
3646 		if (archive_string_ensure(as, ll +1) == NULL)
3647 			return (-1);
3648 		mbs = as->s + as->length;
3649 		mbs_size = as->buffer_length - as->length -1;
3650 	} while (1);
3651 	archive_string_free(&tmp);
3652 	as->length += ll;
3653 	as->s[as->length] = '\0';
3654 	if (ll == 0 || defchar)
3655 		ret = -1;
3656 	return (ret);
3657 }
3658 
3659 static int
win_strncat_from_utf16be(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc)3660 win_strncat_from_utf16be(struct archive_string *as, const void *_p,
3661     size_t bytes, struct archive_string_conv *sc)
3662 {
3663 	return (win_strncat_from_utf16(as, _p, bytes, sc, 1));
3664 }
3665 
3666 static int
win_strncat_from_utf16le(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc)3667 win_strncat_from_utf16le(struct archive_string *as, const void *_p,
3668     size_t bytes, struct archive_string_conv *sc)
3669 {
3670 	return (win_strncat_from_utf16(as, _p, bytes, sc, 0));
3671 }
3672 
3673 /*
3674  * Convert a current locale string to UTF-16BE/LE and copy the result.
3675  * Return -1 if conversion fails.
3676  */
3677 static int
win_strncat_to_utf16(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc,int bigendian)3678 win_strncat_to_utf16(struct archive_string *as16, const void *_p,
3679     size_t length, struct archive_string_conv *sc, int bigendian)
3680 {
3681 	const char *s = (const char *)_p;
3682 	char *u16;
3683 	size_t count, avail;
3684 
3685 	if (archive_string_ensure(as16,
3686 	    as16->length + (length + 1) * 2) == NULL)
3687 		return (-1);
3688 
3689 	u16 = as16->s + as16->length;
3690 	avail = as16->buffer_length - 2;
3691 	if (sc->from_cp == CP_C_LOCALE) {
3692 		/*
3693 		 * "C" locale special process.
3694 		 */
3695 		count = 0;
3696 		while (count < length && *s) {
3697 			if (bigendian)
3698 				archive_be16enc(u16, *s);
3699 			else
3700 				archive_le16enc(u16, *s);
3701 			u16 += 2;
3702 			s++;
3703 			count++;
3704 		}
3705 		as16->length += count << 1;
3706 		as16->s[as16->length] = 0;
3707 		as16->s[as16->length+1] = 0;
3708 		return (0);
3709 	}
3710 	do {
3711 		int r;
3712 		if (length > (size_t)INT_MAX || (avail >> 1) > (size_t)INT_MAX)
3713 			return (-1);
3714 		r = MultiByteToWideChar(sc->from_cp,
3715 		    MB_PRECOMPOSED, s, (int)length, (LPWSTR)u16, (int)avail>>1);
3716 		/* Exit loop if we succeeded */
3717 		if (r != 0 ||
3718 		    GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
3719 			count = (size_t)r;
3720 			break;
3721 		}
3722 		/* Expand buffer and try again */
3723 		r = MultiByteToWideChar(sc->from_cp,
3724 		    MB_PRECOMPOSED, s, (int)length, NULL, 0);
3725 		count = (size_t)r;
3726 		if (archive_string_ensure(as16, (count +1) * 2)
3727 		    == NULL)
3728 			return (-1);
3729 		u16 = as16->s + as16->length;
3730 		avail = as16->buffer_length - 2;
3731 	} while (1);
3732 	as16->length += count * 2;
3733 	as16->s[as16->length] = 0;
3734 	as16->s[as16->length+1] = 0;
3735 	if (count == 0)
3736 		return (-1);
3737 
3738 	if (IS_BIG_ENDIAN) {
3739 		if (!bigendian) {
3740 			while (count > 0) {
3741 				uint16_t v = archive_be16dec(u16);
3742 				archive_le16enc(u16, v);
3743 				u16 += 2;
3744 				count--;
3745 			}
3746 		}
3747 	} else {
3748 		if (bigendian) {
3749 			while (count > 0) {
3750 				uint16_t v = archive_le16dec(u16);
3751 				archive_be16enc(u16, v);
3752 				u16 += 2;
3753 				count--;
3754 			}
3755 		}
3756 	}
3757 	return (0);
3758 }
3759 
3760 static int
win_strncat_to_utf16be(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc)3761 win_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3762     size_t length, struct archive_string_conv *sc)
3763 {
3764 	return (win_strncat_to_utf16(as16, _p, length, sc, 1));
3765 }
3766 
3767 static int
win_strncat_to_utf16le(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc)3768 win_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3769     size_t length, struct archive_string_conv *sc)
3770 {
3771 	return (win_strncat_to_utf16(as16, _p, length, sc, 0));
3772 }
3773 
3774 #endif /* _WIN32 && !__CYGWIN__ */
3775 
3776 /*
3777  * Do the best effort for conversions.
3778  * We cannot handle UTF-16BE character-set without such iconv,
3779  * but there is a chance if a string consists just ASCII code or
3780  * a current locale is UTF-8.
3781  */
3782 
3783 /*
3784  * Convert a UTF-16BE string to current locale and copy the result.
3785  * Return -1 if conversion fails.
3786  */
3787 static int
best_effort_strncat_from_utf16(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc,int be)3788 best_effort_strncat_from_utf16(struct archive_string *as, const void *_p,
3789     size_t bytes, struct archive_string_conv *sc, int be)
3790 {
3791 	const char *utf16 = (const char *)_p;
3792 	char *mbs;
3793 	uint32_t uc;
3794 	int n, ret;
3795 
3796 	(void)sc; /* UNUSED */
3797 	/*
3798 	 * Other case, we should do the best effort.
3799 	 * If all character are ASCII(<0x7f), we can convert it.
3800 	 * if not , we set a alternative character and return -1.
3801 	 */
3802 	ret = 0;
3803 	if (archive_string_ensure(as, as->length + bytes +1) == NULL)
3804 		return (-1);
3805 	mbs = as->s + as->length;
3806 
3807 	while ((n = utf16_to_unicode(&uc, utf16, bytes, be)) != 0) {
3808 		if (n < 0) {
3809 			n *= -1;
3810 			ret =  -1;
3811 		}
3812 		bytes -= n;
3813 		utf16 += n;
3814 
3815 		if (uc > 127) {
3816 			/* We cannot handle it. */
3817 			*mbs++ = '?';
3818 			ret =  -1;
3819 		} else
3820 			*mbs++ = (char)uc;
3821 	}
3822 	as->length = mbs - as->s;
3823 	as->s[as->length] = '\0';
3824 	return (ret);
3825 }
3826 
3827 static int
best_effort_strncat_from_utf16be(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc)3828 best_effort_strncat_from_utf16be(struct archive_string *as, const void *_p,
3829     size_t bytes, struct archive_string_conv *sc)
3830 {
3831 	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 1));
3832 }
3833 
3834 static int
best_effort_strncat_from_utf16le(struct archive_string * as,const void * _p,size_t bytes,struct archive_string_conv * sc)3835 best_effort_strncat_from_utf16le(struct archive_string *as, const void *_p,
3836     size_t bytes, struct archive_string_conv *sc)
3837 {
3838 	return (best_effort_strncat_from_utf16(as, _p, bytes, sc, 0));
3839 }
3840 
3841 /*
3842  * Convert a current locale string to UTF-16BE/LE and copy the result.
3843  * Return -1 if conversion fails.
3844  */
3845 static int
best_effort_strncat_to_utf16(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc,int bigendian)3846 best_effort_strncat_to_utf16(struct archive_string *as16, const void *_p,
3847     size_t length, struct archive_string_conv *sc, int bigendian)
3848 {
3849 	const char *s = (const char *)_p;
3850 	char *utf16;
3851 	size_t remaining;
3852 	int ret;
3853 
3854 	(void)sc; /* UNUSED */
3855 	/*
3856 	 * Other case, we should do the best effort.
3857 	 * If all character are ASCII(<0x7f), we can convert it.
3858 	 * if not , we set a alternative character and return -1.
3859 	 */
3860 	ret = 0;
3861 	remaining = length;
3862 
3863 	if (archive_string_ensure(as16,
3864 	    as16->length + (length + 1) * 2) == NULL)
3865 		return (-1);
3866 
3867 	utf16 = as16->s + as16->length;
3868 	while (remaining--) {
3869 		unsigned c = *s++;
3870 		if (c > 127) {
3871 			/* We cannot handle it. */
3872 			c = UNICODE_R_CHAR;
3873 			ret = -1;
3874 		}
3875 		if (bigendian)
3876 			archive_be16enc(utf16, (uint16_t)c);
3877 		else
3878 			archive_le16enc(utf16, (uint16_t)c);
3879 		utf16 += 2;
3880 	}
3881 	as16->length = utf16 - as16->s;
3882 	as16->s[as16->length] = 0;
3883 	as16->s[as16->length+1] = 0;
3884 	return (ret);
3885 }
3886 
3887 static int
best_effort_strncat_to_utf16be(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc)3888 best_effort_strncat_to_utf16be(struct archive_string *as16, const void *_p,
3889     size_t length, struct archive_string_conv *sc)
3890 {
3891 	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 1));
3892 }
3893 
3894 static int
best_effort_strncat_to_utf16le(struct archive_string * as16,const void * _p,size_t length,struct archive_string_conv * sc)3895 best_effort_strncat_to_utf16le(struct archive_string *as16, const void *_p,
3896     size_t length, struct archive_string_conv *sc)
3897 {
3898 	return (best_effort_strncat_to_utf16(as16, _p, length, sc, 0));
3899 }
3900 
3901 
3902 /*
3903  * Multistring operations.
3904  */
3905 
3906 void
archive_mstring_clean(struct archive_mstring * aes)3907 archive_mstring_clean(struct archive_mstring *aes)
3908 {
3909 	archive_wstring_free(&(aes->aes_wcs));
3910 	archive_string_free(&(aes->aes_mbs));
3911 	archive_string_free(&(aes->aes_utf8));
3912 	archive_string_free(&(aes->aes_mbs_in_locale));
3913 	aes->aes_set = 0;
3914 }
3915 
3916 void
archive_mstring_copy(struct archive_mstring * dest,struct archive_mstring * src)3917 archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *src)
3918 {
3919 	dest->aes_set = src->aes_set;
3920 	archive_string_copy(&(dest->aes_mbs), &(src->aes_mbs));
3921 	archive_string_copy(&(dest->aes_utf8), &(src->aes_utf8));
3922 	archive_wstring_copy(&(dest->aes_wcs), &(src->aes_wcs));
3923 }
3924 
3925 int
archive_mstring_get_utf8(struct archive * a,struct archive_mstring * aes,const char ** p)3926 archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
3927   const char **p)
3928 {
3929 	struct archive_string_conv *sc;
3930 	int r;
3931 
3932 	/* If we already have a UTF8 form, return that immediately. */
3933 	if (aes->aes_set & AES_SET_UTF8) {
3934 		*p = aes->aes_utf8.s;
3935 		return (0);
3936 	}
3937 
3938 	*p = NULL;
3939 #if defined(_WIN32) && !defined(__CYGWIN__)
3940 	/*
3941 	 * On Windows, first try converting from WCS because (1) there's no
3942 	 * guarantee that the conversion to MBS will succeed, e.g. when using
3943 	 * CP_ACP, and (2) that's more efficient than converting to MBS, just to
3944 	 * convert back to WCS again before finally converting to UTF-8
3945 	 */
3946 	if ((aes->aes_set & AES_SET_WCS) != 0) {
3947 		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3948 		if (sc == NULL)
3949 			return (-1);/* Couldn't allocate memory for sc. */
3950 		archive_string_empty(&(aes->aes_utf8));
3951 		r = archive_string_append_from_wcs_in_codepage(&(aes->aes_utf8),
3952 			aes->aes_wcs.s, aes->aes_wcs.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 #endif
3963 	/* Try converting WCS to MBS first if MBS does not exist yet. */
3964 	if ((aes->aes_set & AES_SET_MBS) == 0) {
3965 		const char *pm; /* unused */
3966 		archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
3967 	}
3968 	if (aes->aes_set & AES_SET_MBS) {
3969 		sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
3970 		if (sc == NULL)
3971 			return (-1);/* Couldn't allocate memory for sc. */
3972 		r = archive_strncpy_l(&(aes->aes_utf8), aes->aes_mbs.s,
3973 		    aes->aes_mbs.length, sc);
3974 		if (a == NULL)
3975 			free_sconv_object(sc);
3976 		if (r == 0) {
3977 			aes->aes_set |= AES_SET_UTF8;
3978 			*p = aes->aes_utf8.s;
3979 			return (0);/* success. */
3980 		} else
3981 			return (-1);/* failure. */
3982 	}
3983 	return (0);/* success. */
3984 }
3985 
3986 int
archive_mstring_get_mbs(struct archive * a,struct archive_mstring * aes,const char ** p)3987 archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
3988     const char **p)
3989 {
3990 	struct archive_string_conv *sc;
3991 	int r, ret = 0;
3992 
3993 	/* If we already have an MBS form, return that immediately. */
3994 	if (aes->aes_set & AES_SET_MBS) {
3995 		*p = aes->aes_mbs.s;
3996 		return (ret);
3997 	}
3998 
3999 	*p = NULL;
4000 	/* If there's a WCS form, try converting with the native locale. */
4001 	if (aes->aes_set & AES_SET_WCS) {
4002 		archive_string_empty(&(aes->aes_mbs));
4003 		r = archive_string_append_from_wcs(&(aes->aes_mbs),
4004 		    aes->aes_wcs.s, aes->aes_wcs.length);
4005 		*p = aes->aes_mbs.s;
4006 		if (r == 0) {
4007 			aes->aes_set |= AES_SET_MBS;
4008 			return (ret);
4009 		} else
4010 			ret = -1;
4011 	}
4012 
4013 	/* If there's a UTF-8 form, try converting with the native locale. */
4014 	if (aes->aes_set & AES_SET_UTF8) {
4015 		archive_string_empty(&(aes->aes_mbs));
4016 		sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4017 		if (sc == NULL)
4018 			return (-1);/* Couldn't allocate memory for sc. */
4019 		r = archive_strncpy_l(&(aes->aes_mbs),
4020 			aes->aes_utf8.s, aes->aes_utf8.length, sc);
4021 		if (a == NULL)
4022 			free_sconv_object(sc);
4023 		*p = aes->aes_mbs.s;
4024 		if (r == 0) {
4025 			aes->aes_set |= AES_SET_MBS;
4026 			ret = 0;/* success; overwrite previous error. */
4027 		} else
4028 			ret = -1;/* failure. */
4029 	}
4030 	return (ret);
4031 }
4032 
4033 int
archive_mstring_get_wcs(struct archive * a,struct archive_mstring * aes,const wchar_t ** wp)4034 archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
4035     const wchar_t **wp)
4036 {
4037 	int r, ret = 0;
4038 
4039 	(void)a;/* UNUSED */
4040 	/* Return WCS form if we already have it. */
4041 	if (aes->aes_set & AES_SET_WCS) {
4042 		*wp = aes->aes_wcs.s;
4043 		return (ret);
4044 	}
4045 
4046 	*wp = NULL;
4047 #if defined(_WIN32) && !defined(__CYGWIN__)
4048 	/*
4049 	 * On Windows, prefer converting from UTF-8 directly to WCS because:
4050 	 * (1) there's no guarantee that the string can be represented in MBS (e.g.
4051 	 * with CP_ACP), and (2) in order to convert from UTF-8 to MBS, we're going
4052 	 * to need to convert from UTF-8 to WCS anyway and its wasteful to throw
4053 	 * away that intermediate result
4054 	 */
4055 	if (aes->aes_set & AES_SET_UTF8) {
4056 		struct archive_string_conv *sc;
4057 
4058 		sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4059 		if (sc != NULL) {
4060 			archive_wstring_empty((&aes->aes_wcs));
4061 			r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4062 			    aes->aes_utf8.s, aes->aes_utf8.length, sc);
4063 			if (a == NULL)
4064 				free_sconv_object(sc);
4065 			if (r == 0) {
4066 				aes->aes_set |= AES_SET_WCS;
4067 				*wp = aes->aes_wcs.s;
4068 				return (0);
4069 			}
4070 		}
4071 	}
4072 #endif
4073 	/* Try converting UTF8 to MBS first if MBS does not exist yet. */
4074 	if ((aes->aes_set & AES_SET_MBS) == 0) {
4075 		const char *p; /* unused */
4076 		archive_mstring_get_mbs(a, aes, &p); /* ignore errors, we'll handle it later */
4077 	}
4078 	/* Try converting MBS to WCS using native locale. */
4079 	if (aes->aes_set & AES_SET_MBS) {
4080 		archive_wstring_empty(&(aes->aes_wcs));
4081 		r = archive_wstring_append_from_mbs(&(aes->aes_wcs),
4082 		    aes->aes_mbs.s, aes->aes_mbs.length);
4083 		if (r == 0) {
4084 			aes->aes_set |= AES_SET_WCS;
4085 			*wp = aes->aes_wcs.s;
4086 		} else
4087 			ret = -1;/* failure. */
4088 	}
4089 	return (ret);
4090 }
4091 
4092 int
archive_mstring_get_mbs_l(struct archive * a,struct archive_mstring * aes,const char ** p,size_t * length,struct archive_string_conv * sc)4093 archive_mstring_get_mbs_l(struct archive *a, struct archive_mstring *aes,
4094     const char **p, size_t *length, struct archive_string_conv *sc)
4095 {
4096 	int ret = 0;
4097 #if defined(_WIN32) && !defined(__CYGWIN__)
4098 	int r;
4099 
4100 	/*
4101 	 * Internationalization programming on Windows must use Wide
4102 	 * characters because Windows platform cannot make locale UTF-8.
4103 	 */
4104 	if (sc != NULL && (aes->aes_set & AES_SET_WCS) != 0) {
4105 		archive_string_empty(&(aes->aes_mbs_in_locale));
4106 		r = archive_string_append_from_wcs_in_codepage(
4107 		    &(aes->aes_mbs_in_locale), aes->aes_wcs.s,
4108 		    aes->aes_wcs.length, sc);
4109 		if (r == 0) {
4110 			*p = aes->aes_mbs_in_locale.s;
4111 			if (length != NULL)
4112 				*length = aes->aes_mbs_in_locale.length;
4113 			return (0);
4114 		} else if (errno == ENOMEM)
4115 			return (-1);
4116 		else
4117 			ret = -1;
4118 	}
4119 #endif
4120 
4121 	/* If there is not an MBS form but there is a WCS or UTF8 form, try converting
4122 	 * with the native locale to be used for translating it to specified
4123 	 * character-set. */
4124 	if ((aes->aes_set & AES_SET_MBS) == 0) {
4125 		const char *pm; /* unused */
4126 		archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
4127 	}
4128 	/* If we already have an MBS form, use it to be translated to
4129 	 * specified character-set. */
4130 	if (aes->aes_set & AES_SET_MBS) {
4131 		if (sc == NULL) {
4132 			/* Conversion is unneeded. */
4133 			*p = aes->aes_mbs.s;
4134 			if (length != NULL)
4135 				*length = aes->aes_mbs.length;
4136 			return (0);
4137 		}
4138 		ret = archive_strncpy_l(&(aes->aes_mbs_in_locale),
4139 		    aes->aes_mbs.s, aes->aes_mbs.length, sc);
4140 		*p = aes->aes_mbs_in_locale.s;
4141 		if (length != NULL)
4142 			*length = aes->aes_mbs_in_locale.length;
4143 	} else {
4144 		*p = NULL;
4145 		if (length != NULL)
4146 			*length = 0;
4147 	}
4148 	return (ret);
4149 }
4150 
4151 int
archive_mstring_copy_mbs(struct archive_mstring * aes,const char * mbs)4152 archive_mstring_copy_mbs(struct archive_mstring *aes, const char *mbs)
4153 {
4154 	if (mbs == NULL) {
4155 		aes->aes_set = 0;
4156 		return (0);
4157 	}
4158 	return (archive_mstring_copy_mbs_len(aes, mbs, strlen(mbs)));
4159 }
4160 
4161 int
archive_mstring_copy_mbs_len(struct archive_mstring * aes,const char * mbs,size_t len)4162 archive_mstring_copy_mbs_len(struct archive_mstring *aes, const char *mbs,
4163     size_t len)
4164 {
4165 	if (mbs == NULL) {
4166 		aes->aes_set = 0;
4167 		return (0);
4168 	}
4169 	aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4170 	archive_strncpy(&(aes->aes_mbs), mbs, len);
4171 	archive_string_empty(&(aes->aes_utf8));
4172 	archive_wstring_empty(&(aes->aes_wcs));
4173 	return (0);
4174 }
4175 
4176 int
archive_mstring_copy_wcs(struct archive_mstring * aes,const wchar_t * wcs)4177 archive_mstring_copy_wcs(struct archive_mstring *aes, const wchar_t *wcs)
4178 {
4179 	return archive_mstring_copy_wcs_len(aes, wcs,
4180 				wcs == NULL ? 0 : wcslen(wcs));
4181 }
4182 
4183 int
archive_mstring_copy_utf8(struct archive_mstring * aes,const char * utf8)4184 archive_mstring_copy_utf8(struct archive_mstring *aes, const char *utf8)
4185 {
4186   if (utf8 == NULL) {
4187     aes->aes_set = 0;
4188     return (0);
4189   }
4190   aes->aes_set = AES_SET_UTF8;
4191   archive_string_empty(&(aes->aes_mbs));
4192   archive_string_empty(&(aes->aes_wcs));
4193   archive_strncpy(&(aes->aes_utf8), utf8, strlen(utf8));
4194   return (int)strlen(utf8);
4195 }
4196 
4197 int
archive_mstring_copy_wcs_len(struct archive_mstring * aes,const wchar_t * wcs,size_t len)4198 archive_mstring_copy_wcs_len(struct archive_mstring *aes, const wchar_t *wcs,
4199     size_t len)
4200 {
4201 	if (wcs == NULL) {
4202 		aes->aes_set = 0;
4203 		return (0);
4204 	}
4205 	aes->aes_set = AES_SET_WCS; /* Only WCS form set. */
4206 	archive_string_empty(&(aes->aes_mbs));
4207 	archive_string_empty(&(aes->aes_utf8));
4208 	archive_wstrncpy(&(aes->aes_wcs), wcs, len);
4209 	return (0);
4210 }
4211 
4212 int
archive_mstring_copy_mbs_len_l(struct archive_mstring * aes,const char * mbs,size_t len,struct archive_string_conv * sc)4213 archive_mstring_copy_mbs_len_l(struct archive_mstring *aes,
4214     const char *mbs, size_t len, struct archive_string_conv *sc)
4215 {
4216 	int r;
4217 
4218 	if (mbs == NULL) {
4219 		aes->aes_set = 0;
4220 		return (0);
4221 	}
4222 	archive_string_empty(&(aes->aes_mbs));
4223 	archive_wstring_empty(&(aes->aes_wcs));
4224 	archive_string_empty(&(aes->aes_utf8));
4225 #if defined(_WIN32) && !defined(__CYGWIN__)
4226 	/*
4227 	 * Internationalization programming on Windows must use Wide
4228 	 * characters because Windows platform cannot make locale UTF-8.
4229 	 */
4230 	if (sc == NULL) {
4231 		if (archive_string_append(&(aes->aes_mbs),
4232 			mbs, mbsnbytes(mbs, len)) == NULL) {
4233 			aes->aes_set = 0;
4234 			r = -1;
4235 		} else {
4236 			aes->aes_set = AES_SET_MBS;
4237 			r = 0;
4238 		}
4239 #if defined(HAVE_ICONV)
4240 	} else if (sc != NULL && sc->cd_w != (iconv_t)-1) {
4241 		/*
4242 		 * This case happens only when MultiByteToWideChar() cannot
4243 		 * handle sc->from_cp, and we have to iconv in order to
4244 		 * translate character-set to wchar_t,UTF-16.
4245 		 */
4246 		iconv_t cd = sc->cd;
4247 		unsigned from_cp;
4248 		int flag;
4249 
4250 		/*
4251 		 * Translate multi-bytes from some character-set to UTF-8.
4252 		 */
4253 		sc->cd = sc->cd_w;
4254 		r = archive_strncpy_l(&(aes->aes_utf8), mbs, len, sc);
4255 		sc->cd = cd;
4256 		if (r != 0) {
4257 			aes->aes_set = 0;
4258 			return (r);
4259 		}
4260 		aes->aes_set = AES_SET_UTF8;
4261 
4262 		/*
4263 		 * Append the UTF-8 string into wstring.
4264 		 */
4265 		flag = sc->flag;
4266 		sc->flag &= ~(SCONV_NORMALIZATION_C
4267 				| SCONV_TO_UTF16| SCONV_FROM_UTF16);
4268 		from_cp = sc->from_cp;
4269 		sc->from_cp = CP_UTF8;
4270 		r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4271 			aes->aes_utf8.s, aes->aes_utf8.length, sc);
4272 		sc->flag = flag;
4273 		sc->from_cp = from_cp;
4274 		if (r == 0)
4275 			aes->aes_set |= AES_SET_WCS;
4276 #endif
4277 	} else {
4278 		r = archive_wstring_append_from_mbs_in_codepage(
4279 		    &(aes->aes_wcs), mbs, len, sc);
4280 		if (r == 0)
4281 			aes->aes_set = AES_SET_WCS;
4282 		else
4283 			aes->aes_set = 0;
4284 	}
4285 #else
4286 	r = archive_strncpy_l(&(aes->aes_mbs), mbs, len, sc);
4287 	if (r == 0)
4288 		aes->aes_set = AES_SET_MBS; /* Only MBS form is set now. */
4289 	else
4290 		aes->aes_set = 0;
4291 #endif
4292 	return (r);
4293 }
4294 
4295 /*
4296  * The 'update' form tries to proactively update all forms of
4297  * this string (WCS and MBS) and returns an error if any of
4298  * them fail.  This is used by the 'pax' handler, for instance,
4299  * to detect and report character-conversion failures early while
4300  * still allowing clients to get potentially useful values from
4301  * the more tolerant lazy conversions.  (get_mbs and get_wcs will
4302  * strive to give the user something useful, so you can get hopefully
4303  * usable values even if some of the character conversions are failing.)
4304  */
4305 int
archive_mstring_update_utf8(struct archive * a,struct archive_mstring * aes,const char * utf8)4306 archive_mstring_update_utf8(struct archive *a, struct archive_mstring *aes,
4307     const char *utf8)
4308 {
4309 	struct archive_string_conv *sc;
4310 	int r;
4311 
4312 	if (utf8 == NULL) {
4313 		aes->aes_set = 0;
4314 		return (0); /* Succeeded in clearing everything. */
4315 	}
4316 
4317 	/* Save the UTF8 string. */
4318 	archive_strcpy(&(aes->aes_utf8), utf8);
4319 
4320 	/* Empty the mbs and wcs strings. */
4321 	archive_string_empty(&(aes->aes_mbs));
4322 	archive_wstring_empty(&(aes->aes_wcs));
4323 
4324 	aes->aes_set = AES_SET_UTF8;	/* Only UTF8 is set now. */
4325 
4326 	sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
4327 	if (sc == NULL)
4328 		return (-1);/* Couldn't allocate memory for sc. */
4329 
4330 #if defined(_WIN32) && !defined(__CYGWIN__)
4331 	/* On Windows, there's no good way to convert from UTF8 -> MBS directly, so
4332 	 * prefer to first convert to WCS as (1) it's wasteful to throw away the
4333 	 * intermediate result, and (2) WCS will still be set even if we fail to
4334 	 * convert to MBS (e.g. with ACP that can't represent the characters) */
4335 	r = archive_wstring_append_from_mbs_in_codepage(&(aes->aes_wcs),
4336 		aes->aes_utf8.s, aes->aes_utf8.length, sc);
4337 
4338 	if (a == NULL)
4339 		free_sconv_object(sc);
4340 	if (r != 0)
4341 		return (-1); /* This will guarantee we can't convert to MBS */
4342 	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS; /* Both UTF8 and WCS set. */
4343 
4344 	/* Try converting WCS to MBS, return false on failure. */
4345 	if (archive_string_append_from_wcs(&(aes->aes_mbs), aes->aes_wcs.s,
4346 	    aes->aes_wcs.length))
4347 		return (-1);
4348 #else
4349 	/* Try converting UTF-8 to MBS, return false on failure. */
4350 	r = archive_strcpy_l(&(aes->aes_mbs), utf8, sc);
4351 
4352 	if (a == NULL)
4353 		free_sconv_object(sc);
4354 	if (r != 0)
4355 		return (-1);
4356 	aes->aes_set = AES_SET_UTF8 | AES_SET_MBS; /* Both UTF8 and MBS set. */
4357 
4358 	/* Try converting MBS to WCS, return false on failure. */
4359 	if (archive_wstring_append_from_mbs(&(aes->aes_wcs), aes->aes_mbs.s,
4360 	    aes->aes_mbs.length))
4361 		return (-1);
4362 #endif
4363 
4364 	/* All conversions succeeded. */
4365 	aes->aes_set = AES_SET_UTF8 | AES_SET_WCS | AES_SET_MBS;
4366 
4367 	return (0);
4368 }
4369