Coverage Report

Created: 2026-04-29 07:01

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