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