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