Coverage Report

Created: 2026-09-14 06:43

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