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