Coverage Report

Created: 2025-12-05 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libunistring/lib/striconveh.c
Line
Count
Source
1
/* Character set conversion with error handling.
2
   Copyright (C) 2001-2025 Free Software Foundation, Inc.
3
   Written by Bruno Haible and Simon Josefsson.
4
5
   This file is free software: you can redistribute it and/or modify
6
   it under the terms of the GNU Lesser General Public License as
7
   published by the Free Software Foundation; either version 2.1 of the
8
   License, or (at your option) any later version.
9
10
   This file is distributed in the hope that it will be useful,
11
   but WITHOUT ANY WARRANTY; without even the implied warranty of
12
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
   GNU Lesser General Public License for more details.
14
15
   You should have received a copy of the GNU Lesser General Public License
16
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
17
18
#include <config.h>
19
20
/* Specification.  */
21
#include "striconveh.h"
22
23
#include <errno.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#if HAVE_ICONV
28
# include <iconv.h>
29
# include "unistr.h"
30
#endif
31
32
#include "c-strcase.h"
33
#include "c-strcaseeq.h"
34
35
#ifndef SIZE_MAX
36
# define SIZE_MAX ((size_t) -1)
37
#endif
38
39
40
#if HAVE_ICONV
41
42
/* The caller must provide an iconveh_t, not just an iconv_t, because when a
43
   conversion error occurs, we may have to determine the Unicode representation
44
   of the inconvertible character.  */
45
46
int
47
iconveh_open (const char *to_codeset, const char *from_codeset, iconveh_t *cdp)
48
0
{
49
0
  iconv_t cd;
50
0
  iconv_t cd1;
51
0
  iconv_t cd2;
52
53
0
  cd = iconv_open (to_codeset, from_codeset);
54
55
0
  if (STRCASEEQ (from_codeset, "UTF-8", 'U','T','F','-','8',0,0,0,0))
56
0
    cd1 = (iconv_t)(-1);
57
0
  else
58
0
    {
59
0
      cd1 = iconv_open ("UTF-8", from_codeset);
60
0
      if (cd1 == (iconv_t)(-1))
61
0
        {
62
0
          int saved_errno = errno;
63
0
          if (cd != (iconv_t)(-1))
64
0
            iconv_close (cd);
65
0
          errno = saved_errno;
66
0
          return -1;
67
0
        }
68
0
    }
69
70
0
  if (STRCASEEQ (to_codeset, "UTF-8", 'U','T','F','-','8',0,0,0,0)
71
0
# if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \
72
0
      && !defined __UCLIBC__) \
73
0
     || _LIBICONV_VERSION >= 0x0105 \
74
0
     || defined ICONV_SET_TRANSLITERATE
75
0
      || c_strcasecmp (to_codeset, "UTF-8//TRANSLIT") == 0
76
0
# endif
77
0
     )
78
0
    cd2 = (iconv_t)(-1);
79
0
  else
80
0
    {
81
0
      cd2 = iconv_open (to_codeset, "UTF-8");
82
0
      if (cd2 == (iconv_t)(-1))
83
0
        {
84
0
          int saved_errno = errno;
85
0
          if (cd1 != (iconv_t)(-1))
86
0
            iconv_close (cd1);
87
0
          if (cd != (iconv_t)(-1))
88
0
            iconv_close (cd);
89
0
          errno = saved_errno;
90
0
          return -1;
91
0
        }
92
0
    }
93
94
0
  cdp->cd = cd;
95
0
  cdp->cd1 = cd1;
96
0
  cdp->cd2 = cd2;
97
0
  return 0;
98
0
}
99
100
int
101
iconveh_close (const iconveh_t *cd)
102
0
{
103
0
  if (cd->cd2 != (iconv_t)(-1) && iconv_close (cd->cd2) < 0)
104
0
    {
105
      /* Return -1, but preserve the errno from iconv_close.  */
106
0
      int saved_errno = errno;
107
0
      if (cd->cd1 != (iconv_t)(-1))
108
0
        iconv_close (cd->cd1);
109
0
      if (cd->cd != (iconv_t)(-1))
110
0
        iconv_close (cd->cd);
111
0
      errno = saved_errno;
112
0
      return -1;
113
0
    }
114
0
  if (cd->cd1 != (iconv_t)(-1) && iconv_close (cd->cd1) < 0)
115
0
    {
116
      /* Return -1, but preserve the errno from iconv_close.  */
117
0
      int saved_errno = errno;
118
0
      if (cd->cd != (iconv_t)(-1))
119
0
        iconv_close (cd->cd);
120
0
      errno = saved_errno;
121
0
      return -1;
122
0
    }
123
0
  if (cd->cd != (iconv_t)(-1) && iconv_close (cd->cd) < 0)
124
0
    return -1;
125
0
  return 0;
126
0
}
127
128
/* iconv_carefully is like iconv, except that it stops as soon as it encounters
129
   a conversion error, and it returns in *INCREMENTED a boolean telling whether
130
   it has incremented the input pointers past the error location.  */
131
# if !(defined _LIBICONV_VERSION && !(_LIBICONV_VERSION == 0x10b && defined __APPLE__)) \
132
     && !(defined __GLIBC__ && !defined __UCLIBC__)
133
/* NetBSD iconv() inserts a question mark if it cannot convert.
134
   Only GNU libiconv (excluding the bastard Apple iconv) and GNU libc are
135
   known to prefer to fail rather than doing a lossy conversion.  */
136
static size_t
137
iconv_carefully (iconv_t cd,
138
                 const char **inbuf, size_t *inbytesleft,
139
                 char **outbuf, size_t *outbytesleft,
140
                 bool *incremented)
141
{
142
  const char *inptr = *inbuf;
143
  const char *inptr_end = inptr + *inbytesleft;
144
  char *outptr = *outbuf;
145
  size_t outsize = *outbytesleft;
146
  const char *inptr_before;
147
  size_t res;
148
149
  do
150
    {
151
      inptr_before = inptr;
152
      res = (size_t)(-1);
153
154
      for (size_t insize = 1; inptr + insize <= inptr_end; insize++)
155
        {
156
          res = iconv (cd,
157
                       (ICONV_CONST char **) &inptr, &insize,
158
                       &outptr, &outsize);
159
          if (!(res == (size_t)(-1) && errno == EINVAL))
160
            break;
161
          /* iconv can eat up a shift sequence but give EINVAL while attempting
162
             to convert the first character.  E.g. libiconv does this.  */
163
          if (inptr > inptr_before)
164
            {
165
              res = 0;
166
              break;
167
            }
168
        }
169
170
      if (res == 0)
171
        {
172
          *outbuf = outptr;
173
          *outbytesleft = outsize;
174
        }
175
    }
176
  while (res == 0 && inptr < inptr_end);
177
178
  *inbuf = inptr;
179
  *inbytesleft = inptr_end - inptr;
180
  if (res != (size_t)(-1) && res > 0)
181
    {
182
      /* iconv() has already incremented INPTR.  We cannot go back to a
183
         previous INPTR, otherwise the state inside CD would become invalid,
184
         if FROM_CODESET is a stateful encoding.  So, tell the caller that
185
         *INBUF has already been incremented.  */
186
      *incremented = (inptr > inptr_before);
187
      errno = EILSEQ;
188
      return (size_t)(-1);
189
    }
190
  else
191
    {
192
      *incremented = false;
193
      return res;
194
    }
195
}
196
# else
197
#  define iconv_carefully(cd, inbuf, inbytesleft, outbuf, outbytesleft, incremented) \
198
0
     (*(incremented) = false, \
199
0
      iconv (cd, (ICONV_CONST char **) (inbuf), inbytesleft, outbuf, outbytesleft))
200
# endif
201
202
/* iconv_carefully_1 is like iconv_carefully, except that it stops after
203
   converting one character or one shift sequence.  */
204
static size_t
205
iconv_carefully_1 (iconv_t cd,
206
                   const char **inbuf, size_t *inbytesleft,
207
                   char **outbuf, size_t *outbytesleft,
208
                   bool *incremented)
209
0
{
210
0
  const char *inptr_before = *inbuf;
211
0
  const char *inptr = inptr_before;
212
0
  const char *inptr_end = inptr_before + *inbytesleft;
213
0
  char *outptr = *outbuf;
214
0
  size_t outsize = *outbytesleft;
215
0
  size_t res = (size_t)(-1);
216
217
0
  for (size_t insize = 1; inptr_before + insize <= inptr_end; insize++)
218
0
    {
219
0
      inptr = inptr_before;
220
0
      res = iconv (cd,
221
0
                   (ICONV_CONST char **) &inptr, &insize,
222
0
                   &outptr, &outsize);
223
0
      if (!(res == (size_t)(-1) && errno == EINVAL))
224
0
        break;
225
      /* iconv can eat up a shift sequence but give EINVAL while attempting
226
         to convert the first character.  E.g. libiconv does this.  */
227
0
      if (inptr > inptr_before)
228
0
        {
229
0
          res = 0;
230
0
          break;
231
0
        }
232
0
    }
233
234
0
  *inbuf = inptr;
235
0
  *inbytesleft = inptr_end - inptr;
236
# if !(defined _LIBICONV_VERSION && !(_LIBICONV_VERSION == 0x10b && defined __APPLE__)) \
237
     && !(defined __GLIBC__ && !defined __UCLIBC__)
238
  /* NetBSD iconv() inserts a question mark if it cannot convert.
239
     Only GNU libiconv (excluding the bastard Apple iconv) and GNU libc are
240
     known to prefer to fail rather than doing a lossy conversion.  */
241
  if (res != (size_t)(-1) && res > 0)
242
    {
243
      /* iconv() has already incremented INPTR.  We cannot go back to a
244
         previous INPTR, otherwise the state inside CD would become invalid,
245
         if FROM_CODESET is a stateful encoding.  So, tell the caller that
246
         *INBUF has already been incremented.  */
247
      *incremented = (inptr > inptr_before);
248
      errno = EILSEQ;
249
      return (size_t)(-1);
250
    }
251
# endif
252
253
0
  if (res != (size_t)(-1))
254
0
    {
255
0
      *outbuf = outptr;
256
0
      *outbytesleft = outsize;
257
0
    }
258
0
  *incremented = false;
259
0
  return res;
260
0
}
261
262
/* utf8conv_carefully is like iconv, except that
263
     - it converts from UTF-8 to UTF-8,
264
     - it stops as soon as it encounters a conversion error, and it returns
265
       in *INCREMENTED a boolean telling whether it has incremented the input
266
       pointers past the error location,
267
     - if one_character_only is true, it stops after converting one
268
       character.  */
269
static size_t
270
utf8conv_carefully (bool one_character_only,
271
                    const char **inbuf, size_t *inbytesleft,
272
                    char **outbuf, size_t *outbytesleft,
273
                    bool *incremented)
274
0
{
275
0
  const char *inptr = *inbuf;
276
0
  size_t insize = *inbytesleft;
277
0
  char *outptr = *outbuf;
278
0
  size_t outsize = *outbytesleft;
279
0
  size_t res;
280
281
0
  res = 0;
282
0
  do
283
0
    {
284
0
      ucs4_t uc;
285
0
      int n;
286
0
      int m;
287
288
0
      n = u8_mbtoucr (&uc, (const uint8_t *) inptr, insize);
289
0
      if (n < 0)
290
0
        {
291
0
          errno = (n == -2 ? EINVAL : EILSEQ);
292
0
          n = u8_mbtouc (&uc, (const uint8_t *) inptr, insize);
293
0
          inptr += n;
294
0
          insize -= n;
295
0
          res = (size_t)(-1);
296
0
          *incremented = true;
297
0
          break;
298
0
        }
299
0
      if (outsize == 0)
300
0
        {
301
0
          errno = E2BIG;
302
0
          res = (size_t)(-1);
303
0
          *incremented = false;
304
0
          break;
305
0
        }
306
0
      m = u8_uctomb ((uint8_t *) outptr, uc, outsize);
307
0
      if (m == -2)
308
0
        {
309
0
          errno = E2BIG;
310
0
          res = (size_t)(-1);
311
0
          *incremented = false;
312
0
          break;
313
0
        }
314
0
      inptr += n;
315
0
      insize -= n;
316
0
      if (m == -1)
317
0
        {
318
0
          errno = EILSEQ;
319
0
          res = (size_t)(-1);
320
0
          *incremented = true;
321
0
          break;
322
0
        }
323
0
      outptr += m;
324
0
      outsize -= m;
325
0
    }
326
0
  while (!one_character_only && insize > 0);
327
328
0
  *inbuf = inptr;
329
0
  *inbytesleft = insize;
330
0
  *outbuf = outptr;
331
0
  *outbytesleft = outsize;
332
0
  return res;
333
0
}
334
335
static int
336
mem_cd_iconveh_internal (const char *src, size_t srclen,
337
                         iconv_t cd, iconv_t cd1, iconv_t cd2,
338
                         enum iconv_ilseq_handler handler,
339
                         size_t extra_alloc,
340
                         size_t *offsets,
341
                         char **resultp, size_t *lengthp)
342
0
{
343
  /* When a conversion error occurs, we cannot start using CD1 and CD2 at
344
     this point: FROM_CODESET may be a stateful encoding like ISO-2022-KR.
345
     Instead, we have to start afresh from the beginning of SRC.  */
346
  /* Use a temporary buffer, so that for small strings, a single malloc()
347
     call will be sufficient.  */
348
0
# define tmpbufsize 4096
349
  /* The alignment is needed when converting e.g. to glibc's WCHAR_T or
350
     libiconv's UCS-4-INTERNAL encoding.  */
351
0
  union { unsigned int align; char buf[tmpbufsize]; } tmp;
352
0
# define tmpbuf tmp.buf
353
354
0
  char *initial_result;
355
0
  char *result;
356
0
  size_t allocated;
357
0
  size_t length;
358
0
  size_t last_length = (size_t)(-1); /* only needed if offsets != NULL */
359
360
0
  if (*resultp != NULL && *lengthp >= sizeof (tmpbuf))
361
0
    {
362
0
      initial_result = *resultp;
363
0
      allocated = *lengthp;
364
0
    }
365
0
  else
366
0
    {
367
0
      initial_result = tmpbuf;
368
0
      allocated = sizeof (tmpbuf);
369
0
    }
370
0
  result = initial_result;
371
372
  /* Test whether a direct conversion is possible at all.  */
373
0
  if (cd == (iconv_t)(-1))
374
0
    goto indirectly;
375
376
0
  if (offsets != NULL)
377
0
    {
378
0
      for (size_t i = 0; i < srclen; i++)
379
0
        offsets[i] = (size_t)(-1);
380
381
0
      last_length = (size_t)(-1);
382
0
    }
383
0
  length = 0;
384
385
  /* First, try a direct conversion, and see whether a conversion error
386
     occurs at all.  */
387
0
  {
388
0
    const char *inptr = src;
389
0
    size_t insize = srclen;
390
391
    /* Set to the initial state.  */
392
0
    iconv (cd, NULL, NULL, NULL, NULL);
393
394
0
    while (insize > 0)
395
0
      {
396
0
        char *outptr = result + length;
397
0
        size_t outsize = allocated - extra_alloc - length;
398
0
        bool incremented;
399
0
        size_t res;
400
0
        bool grow;
401
402
0
        if (offsets != NULL)
403
0
          {
404
0
            if (length != last_length) /* ensure that offset[] be increasing */
405
0
              {
406
0
                offsets[inptr - src] = length;
407
0
                last_length = length;
408
0
              }
409
0
            res = iconv_carefully_1 (cd,
410
0
                                     &inptr, &insize,
411
0
                                     &outptr, &outsize,
412
0
                                     &incremented);
413
0
          }
414
0
        else
415
          /* Use iconv_carefully instead of iconv here, because:
416
             - If TO_CODESET is UTF-8, we can do the error handling in this
417
               loop, no need for a second loop,
418
             - With iconv() implementations other than GNU libiconv and GNU
419
               libc, if we use iconv() in a big swoop, checking for an E2BIG
420
               return, we lose the number of irreversible conversions.  */
421
0
          res = iconv_carefully (cd,
422
0
                                 &inptr, &insize,
423
0
                                 &outptr, &outsize,
424
0
                                 &incremented);
425
426
0
        length = outptr - result;
427
0
        grow = (length + extra_alloc > allocated / 2);
428
0
        if (res == (size_t)(-1))
429
0
          {
430
0
            if (errno == E2BIG)
431
0
              grow = true;
432
0
            else if (errno == EINVAL)
433
0
              break;
434
0
            else if (errno == EILSEQ && handler != iconveh_error)
435
0
              {
436
0
                if (cd2 == (iconv_t)(-1))
437
0
                  {
438
                    /* TO_CODESET is UTF-8.  */
439
                    /* Error handling can produce up to 1 or 3 bytes of
440
                       output.  */
441
0
                    size_t extra_need =
442
0
                      (handler == iconveh_replacement_character ? 3 : 1);
443
0
                    if (length + extra_need + extra_alloc > allocated)
444
0
                      {
445
0
                        char *memory;
446
447
0
                        allocated = 2 * allocated;
448
0
                        if (length + extra_need + extra_alloc > allocated)
449
0
                          allocated = 2 * allocated;
450
0
                        if (length + extra_need + extra_alloc > allocated)
451
0
                          abort ();
452
0
                        if (result == initial_result)
453
0
                          memory = (char *) malloc (allocated);
454
0
                        else
455
0
                          memory = (char *) realloc (result, allocated);
456
0
                        if (memory == NULL)
457
0
                          {
458
0
                            if (result != initial_result)
459
0
                              free (result);
460
0
                            errno = ENOMEM;
461
0
                            return -1;
462
0
                          }
463
0
                        if (result == initial_result)
464
0
                          memcpy (memory, initial_result, length);
465
0
                        result = memory;
466
0
                        grow = false;
467
0
                      }
468
                    /* The input is invalid in FROM_CODESET.  Eat up one byte
469
                       and emit a replacement character or a question mark.  */
470
0
                    if (!incremented)
471
0
                      {
472
0
                        if (insize == 0)
473
0
                          abort ();
474
0
                        inptr++;
475
0
                        insize--;
476
0
                      }
477
0
                    if (handler == iconveh_replacement_character)
478
0
                      {
479
                        /* U+FFFD in UTF-8 encoding.  */
480
0
                        result[length+0] = '\357';
481
0
                        result[length+1] = '\277';
482
0
                        result[length+2] = '\275';
483
0
                        length += 3;
484
0
                      }
485
0
                    else
486
0
                      {
487
0
                        result[length] = '?';
488
0
                        length++;
489
0
                      }
490
0
                  }
491
0
                else
492
0
                  goto indirectly;
493
0
              }
494
0
            else
495
0
              {
496
0
                if (result != initial_result)
497
0
                  free (result);
498
0
                return -1;
499
0
              }
500
0
          }
501
0
        if (insize == 0)
502
0
          break;
503
0
        if (grow)
504
0
          {
505
0
            char *memory;
506
507
0
            allocated = 2 * allocated;
508
0
            if (result == initial_result)
509
0
              memory = (char *) malloc (allocated);
510
0
            else
511
0
              memory = (char *) realloc (result, allocated);
512
0
            if (memory == NULL)
513
0
              {
514
0
                if (result != initial_result)
515
0
                  free (result);
516
0
                errno = ENOMEM;
517
0
                return -1;
518
0
              }
519
0
            if (result == initial_result)
520
0
              memcpy (memory, initial_result, length);
521
0
            result = memory;
522
0
          }
523
0
      }
524
0
  }
525
526
  /* Now get the conversion state back to the initial state.
527
     But avoid glibc-2.1 bug and Solaris 2.7 bug.  */
528
0
#if defined _LIBICONV_VERSION \
529
0
    || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
530
0
         || defined __sun)
531
0
  for (;;)
532
0
    {
533
0
      char *outptr = result + length;
534
0
      size_t outsize = allocated - extra_alloc - length;
535
0
      size_t res;
536
537
0
      res = iconv (cd, NULL, NULL, &outptr, &outsize);
538
0
      length = outptr - result;
539
0
      if (res == (size_t)(-1))
540
0
        {
541
0
          if (errno == E2BIG)
542
0
            {
543
0
              char *memory;
544
545
0
              allocated = 2 * allocated;
546
0
              if (result == initial_result)
547
0
                memory = (char *) malloc (allocated);
548
0
              else
549
0
                memory = (char *) realloc (result, allocated);
550
0
              if (memory == NULL)
551
0
                {
552
0
                  if (result != initial_result)
553
0
                    free (result);
554
0
                  errno = ENOMEM;
555
0
                  return -1;
556
0
                }
557
0
              if (result == initial_result)
558
0
                memcpy (memory, initial_result, length);
559
0
              result = memory;
560
0
            }
561
0
          else
562
0
            {
563
0
              if (result != initial_result)
564
0
                free (result);
565
0
              return -1;
566
0
            }
567
0
        }
568
0
      else
569
0
        break;
570
0
    }
571
0
#endif
572
573
  /* The direct conversion succeeded.  */
574
0
  goto done;
575
576
0
 indirectly:
577
  /* The direct conversion failed.
578
     Use a conversion through UTF-8.  */
579
0
  if (offsets != NULL)
580
0
    {
581
0
      for (size_t i = 0; i < srclen; i++)
582
0
        offsets[i] = (size_t)(-1);
583
584
0
      last_length = (size_t)(-1);
585
0
    }
586
0
  length = 0;
587
0
  {
588
0
    const bool slowly = (offsets != NULL || handler == iconveh_error);
589
0
# define utf8bufsize 4096 /* may also be smaller or larger than tmpbufsize */
590
0
    char utf8buf[utf8bufsize + 3];
591
0
    size_t utf8len = 0;
592
0
    const char *in1ptr = src;
593
0
    size_t in1size = srclen;
594
0
    bool do_final_flush1 = true;
595
0
    bool do_final_flush2 = true;
596
597
    /* Set to the initial state.  */
598
0
    if (cd1 != (iconv_t)(-1))
599
0
      iconv (cd1, NULL, NULL, NULL, NULL);
600
0
    if (cd2 != (iconv_t)(-1))
601
0
      iconv (cd2, NULL, NULL, NULL, NULL);
602
603
0
    while (in1size > 0 || do_final_flush1 || utf8len > 0 || do_final_flush2)
604
0
      {
605
0
        char *out1ptr = utf8buf + utf8len;
606
0
        size_t out1size = utf8bufsize - utf8len;
607
0
        bool incremented1;
608
0
        size_t res1;
609
0
        int errno1;
610
611
        /* Conversion step 1: from FROM_CODESET to UTF-8.  */
612
0
        if (in1size > 0)
613
0
          {
614
0
            if (offsets != NULL
615
0
                && length != last_length) /* ensure that offset[] be increasing */
616
0
              {
617
0
                offsets[in1ptr - src] = length;
618
0
                last_length = length;
619
0
              }
620
0
            if (cd1 != (iconv_t)(-1))
621
0
              {
622
0
                if (slowly)
623
0
                  res1 = iconv_carefully_1 (cd1,
624
0
                                            &in1ptr, &in1size,
625
0
                                            &out1ptr, &out1size,
626
0
                                            &incremented1);
627
0
                else
628
0
                  res1 = iconv_carefully (cd1,
629
0
                                          &in1ptr, &in1size,
630
0
                                          &out1ptr, &out1size,
631
0
                                          &incremented1);
632
0
              }
633
0
            else
634
0
              {
635
                /* FROM_CODESET is UTF-8.  */
636
0
                res1 = utf8conv_carefully (slowly,
637
0
                                           &in1ptr, &in1size,
638
0
                                           &out1ptr, &out1size,
639
0
                                           &incremented1);
640
0
              }
641
0
          }
642
0
        else if (do_final_flush1)
643
0
          {
644
            /* Now get the conversion state of CD1 back to the initial state.
645
               But avoid glibc-2.1 bug and Solaris 2.7 bug.  */
646
0
# if defined _LIBICONV_VERSION \
647
0
     || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
648
0
          || defined __sun)
649
0
            if (cd1 != (iconv_t)(-1))
650
0
              res1 = iconv (cd1, NULL, NULL, &out1ptr, &out1size);
651
0
            else
652
0
# endif
653
0
              res1 = 0;
654
0
            do_final_flush1 = false;
655
0
            incremented1 = true;
656
0
          }
657
0
        else
658
0
          {
659
0
            res1 = 0;
660
0
            incremented1 = true;
661
0
          }
662
0
        if (res1 == (size_t)(-1)
663
0
            && !(errno == E2BIG || errno == EINVAL || errno == EILSEQ))
664
0
          {
665
0
            if (result != initial_result)
666
0
              free (result);
667
0
            return -1;
668
0
          }
669
0
        if (res1 == (size_t)(-1)
670
0
            && errno == EILSEQ && handler != iconveh_error)
671
0
          {
672
            /* The input is invalid in FROM_CODESET.  Eat up one byte and
673
               emit a U+FFFD character or a question mark.  Room for this
674
               character was allocated at the end of utf8buf.  */
675
0
            if (!incremented1)
676
0
              {
677
0
                if (in1size == 0)
678
0
                  abort ();
679
0
                in1ptr++;
680
0
                in1size--;
681
0
              }
682
0
            if (handler == iconveh_replacement_character)
683
0
              {
684
                /* U+FFFD in UTF-8 encoding.  */
685
0
                out1ptr[0] = '\357';
686
0
                out1ptr[1] = '\277';
687
0
                out1ptr[2] = '\275';
688
0
                out1ptr += 3;
689
0
              }
690
0
            else
691
0
              *out1ptr++ = '?';
692
0
            res1 = 0;
693
0
          }
694
0
        errno1 = errno;
695
0
        utf8len = out1ptr - utf8buf;
696
697
0
        if (offsets != NULL
698
0
            || in1size == 0
699
0
            || utf8len > utf8bufsize / 2
700
0
            || (res1 == (size_t)(-1) && errno1 == E2BIG))
701
0
          {
702
            /* Conversion step 2: from UTF-8 to TO_CODESET.  */
703
0
            const char *in2ptr = utf8buf;
704
0
            size_t in2size = utf8len;
705
706
0
            while (in2size > 0
707
0
                   || (in1size == 0 && !do_final_flush1 && do_final_flush2))
708
0
              {
709
0
                char *out2ptr = result + length;
710
0
                size_t out2size = allocated - extra_alloc - length;
711
0
                bool incremented2;
712
0
                size_t res2;
713
0
                bool grow;
714
715
0
                if (in2size > 0)
716
0
                  {
717
0
                    if (cd2 != (iconv_t)(-1))
718
0
                      res2 = iconv_carefully (cd2,
719
0
                                              &in2ptr, &in2size,
720
0
                                              &out2ptr, &out2size,
721
0
                                              &incremented2);
722
0
                    else
723
                      /* TO_CODESET is UTF-8.  */
724
0
                      res2 = utf8conv_carefully (false,
725
0
                                                 &in2ptr, &in2size,
726
0
                                                 &out2ptr, &out2size,
727
0
                                                 &incremented2);
728
0
                  }
729
0
                else /* in1size == 0 && !do_final_flush1
730
                        && in2size == 0 && do_final_flush2 */
731
0
                  {
732
                    /* Now get the conversion state of CD1 back to the initial
733
                       state.  But avoid glibc-2.1 bug and Solaris 2.7 bug.  */
734
0
# if defined _LIBICONV_VERSION \
735
0
     || !(((__GLIBC__ == 2 && __GLIBC_MINOR__ <= 1) && !defined __UCLIBC__) \
736
0
          || defined __sun)
737
0
                    if (cd2 != (iconv_t)(-1))
738
0
                      res2 = iconv (cd2, NULL, NULL, &out2ptr, &out2size);
739
0
                    else
740
0
# endif
741
0
                      res2 = 0;
742
0
                    do_final_flush2 = false;
743
0
                    incremented2 = true;
744
0
                  }
745
746
0
                length = out2ptr - result;
747
0
                grow = (length + extra_alloc > allocated / 2);
748
0
                if (res2 == (size_t)(-1))
749
0
                  {
750
0
                    if (errno == E2BIG)
751
0
                      grow = true;
752
0
                    else if (errno == EINVAL)
753
0
                      break;
754
0
                    else if (errno == EILSEQ && handler != iconveh_error)
755
0
                      {
756
                        /* Error handling can produce up to 10 bytes of UTF-8
757
                           output.  But TO_CODESET may be UCS-2, UTF-16 or
758
                           UCS-4, so use CD2 here as well.  */
759
0
                        char scratchbuf[10];
760
0
                        size_t scratchlen;
761
0
                        ucs4_t uc;
762
0
                        const char *inptr;
763
0
                        size_t insize;
764
0
                        size_t res;
765
766
0
                        if (incremented2)
767
0
                          {
768
0
                            if (u8_prev (&uc, (const uint8_t *) in2ptr,
769
0
                                         (const uint8_t *) utf8buf)
770
0
                                == NULL)
771
0
                              abort ();
772
0
                          }
773
0
                        else
774
0
                          {
775
0
                            int n;
776
0
                            if (in2size == 0)
777
0
                              abort ();
778
0
                            n = u8_mbtouc_unsafe (&uc, (const uint8_t *) in2ptr,
779
0
                                                  in2size);
780
0
                            in2ptr += n;
781
0
                            in2size -= n;
782
0
                          }
783
784
0
                        if (handler == iconveh_escape_sequence)
785
0
                          {
786
0
                            static char const hex[16] _GL_ATTRIBUTE_NONSTRING =
787
0
                              "0123456789ABCDEF";
788
0
                            scratchlen = 0;
789
0
                            scratchbuf[scratchlen++] = '\\';
790
0
                            if (uc < 0x10000)
791
0
                              scratchbuf[scratchlen++] = 'u';
792
0
                            else
793
0
                              {
794
0
                                scratchbuf[scratchlen++] = 'U';
795
0
                                scratchbuf[scratchlen++] = hex[(uc>>28) & 15];
796
0
                                scratchbuf[scratchlen++] = hex[(uc>>24) & 15];
797
0
                                scratchbuf[scratchlen++] = hex[(uc>>20) & 15];
798
0
                                scratchbuf[scratchlen++] = hex[(uc>>16) & 15];
799
0
                              }
800
0
                            scratchbuf[scratchlen++] = hex[(uc>>12) & 15];
801
0
                            scratchbuf[scratchlen++] = hex[(uc>>8) & 15];
802
0
                            scratchbuf[scratchlen++] = hex[(uc>>4) & 15];
803
0
                            scratchbuf[scratchlen++] = hex[uc & 15];
804
0
                          }
805
0
                        else if (handler == iconveh_replacement_character)
806
0
                          {
807
                            /* U+FFFD in UTF-8 encoding.  */
808
0
                            scratchbuf[0] = '\357';
809
0
                            scratchbuf[1] = '\277';
810
0
                            scratchbuf[2] = '\275';
811
0
                            scratchlen = 3;
812
0
                          }
813
0
                        else
814
0
                          {
815
0
                            scratchbuf[0] = '?';
816
0
                            scratchlen = 1;
817
0
                          }
818
819
0
                        inptr = scratchbuf;
820
0
                        insize = scratchlen;
821
0
                        if (cd2 != (iconv_t)(-1))
822
0
                          {
823
0
                            char *out2ptr_try = out2ptr;
824
0
                            size_t out2size_try = out2size;
825
0
                            res = iconv (cd2,
826
0
                                         (ICONV_CONST char **) &inptr, &insize,
827
0
                                         &out2ptr_try, &out2size_try);
828
0
                            if (handler == iconveh_replacement_character
829
0
                                && (res == (size_t)(-1)
830
0
                                    ? errno == EILSEQ
831
                                    /* FreeBSD iconv(), NetBSD iconv(), and
832
                                       Solaris 11 iconv() insert a '?' if they
833
                                       cannot convert.  This is what we want.
834
                                       But musl libc iconv() inserts a '*' if it
835
                                       cannot convert.  */
836
0
                                    : (res > 0
837
0
                                       && !(out2ptr_try - out2ptr == 1
838
0
                                            && *out2ptr == '?'))))
839
0
                              {
840
                                /* The iconv() call failed.
841
                                   U+FFFD can't be converted to TO_CODESET.
842
                                   Use '?' instead.  */
843
0
                                scratchbuf[0] = '?';
844
0
                                scratchlen = 1;
845
0
                                inptr = scratchbuf;
846
0
                                insize = scratchlen;
847
0
                                res = iconv (cd2,
848
0
                                             (ICONV_CONST char **) &inptr, &insize,
849
0
                                             &out2ptr, &out2size);
850
0
                              }
851
0
                            else
852
0
                              {
853
                                /* Accept the results of the iconv() call.  */
854
0
                                out2ptr = out2ptr_try;
855
0
                                out2size = out2size_try;
856
0
                                res = 0;
857
0
                              }
858
0
                          }
859
0
                        else
860
0
                          {
861
                            /* TO_CODESET is UTF-8.  */
862
0
                            if (out2size >= insize)
863
0
                              {
864
0
                                memcpy (out2ptr, inptr, insize);
865
0
                                out2ptr += insize;
866
0
                                out2size -= insize;
867
0
                                inptr += insize;
868
0
                                insize = 0;
869
0
                                res = 0;
870
0
                              }
871
0
                            else
872
0
                              {
873
0
                                errno = E2BIG;
874
0
                                res = (size_t)(-1);
875
0
                              }
876
0
                          }
877
0
                        length = out2ptr - result;
878
0
                        if (res == (size_t)(-1) && errno == E2BIG)
879
0
                          {
880
0
                            char *memory;
881
882
0
                            allocated = 2 * allocated;
883
0
                            if (length + 1 + extra_alloc > allocated)
884
0
                              abort ();
885
0
                            if (result == initial_result)
886
0
                              memory = (char *) malloc (allocated);
887
0
                            else
888
0
                              memory = (char *) realloc (result, allocated);
889
0
                            if (memory == NULL)
890
0
                              {
891
0
                                if (result != initial_result)
892
0
                                  free (result);
893
0
                                errno = ENOMEM;
894
0
                                return -1;
895
0
                              }
896
0
                            if (result == initial_result)
897
0
                              memcpy (memory, initial_result, length);
898
0
                            result = memory;
899
0
                            grow = false;
900
901
0
                            out2ptr = result + length;
902
0
                            out2size = allocated - extra_alloc - length;
903
0
                            if (cd2 != (iconv_t)(-1))
904
0
                              res = iconv (cd2,
905
0
                                           (ICONV_CONST char **) &inptr,
906
0
                                           &insize,
907
0
                                           &out2ptr, &out2size);
908
0
                            else
909
0
                              {
910
                                /* TO_CODESET is UTF-8.  */
911
0
                                if (!(out2size >= insize))
912
0
                                  abort ();
913
0
                                memcpy (out2ptr, inptr, insize);
914
0
                                out2ptr += insize;
915
0
                                out2size -= insize;
916
0
                                inptr += insize;
917
0
                                insize = 0;
918
0
                                res = 0;
919
0
                              }
920
0
                            length = out2ptr - result;
921
0
                          }
922
# if !(defined _LIBICONV_VERSION && !(_LIBICONV_VERSION == 0x10b && defined __APPLE__)) \
923
     && !(defined __GLIBC__ && !defined __UCLIBC__)
924
                        /* FreeBSD iconv(), NetBSD iconv(), and Solaris 11
925
                           iconv() insert a '?' if they cannot convert.
926
                           musl libc iconv() inserts a '*' if it cannot convert.
927
                           Only GNU libiconv (excluding the bastard Apple iconv)
928
                           and GNU libc are known to prefer to fail rather than
929
                           doing a lossy conversion.  */
930
                        if (res != (size_t)(-1) && res > 0)
931
                          {
932
                            errno = EILSEQ;
933
                            res = (size_t)(-1);
934
                          }
935
# endif
936
0
                        if (res == (size_t)(-1))
937
0
                          {
938
                            /* Failure converting the ASCII replacement.  */
939
0
                            if (result != initial_result)
940
0
                              free (result);
941
0
                            return -1;
942
0
                          }
943
0
                      }
944
0
                    else
945
0
                      {
946
0
                        if (result != initial_result)
947
0
                          free (result);
948
0
                        return -1;
949
0
                      }
950
0
                  }
951
0
                if (!(in2size > 0
952
0
                      || (in1size == 0 && !do_final_flush1 && do_final_flush2)))
953
0
                  break;
954
0
                if (grow)
955
0
                  {
956
0
                    char *memory;
957
958
0
                    allocated = 2 * allocated;
959
0
                    if (result == initial_result)
960
0
                      memory = (char *) malloc (allocated);
961
0
                    else
962
0
                      memory = (char *) realloc (result, allocated);
963
0
                    if (memory == NULL)
964
0
                      {
965
0
                        if (result != initial_result)
966
0
                          free (result);
967
0
                        errno = ENOMEM;
968
0
                        return -1;
969
0
                      }
970
0
                    if (result == initial_result)
971
0
                      memcpy (memory, initial_result, length);
972
0
                    result = memory;
973
0
                  }
974
0
              }
975
976
            /* Move the remaining bytes to the beginning of utf8buf.  */
977
0
            if (in2size > 0)
978
0
              memmove (utf8buf, in2ptr, in2size);
979
0
            utf8len = in2size;
980
0
          }
981
982
0
        if (res1 == (size_t)(-1))
983
0
          {
984
0
            if (errno1 == EINVAL)
985
0
              in1size = 0;
986
0
            else if (errno1 == EILSEQ)
987
0
              {
988
0
                if (result != initial_result)
989
0
                  free (result);
990
0
                errno = errno1;
991
0
                return -1;
992
0
              }
993
0
          }
994
0
      }
995
0
# undef utf8bufsize
996
0
  }
997
998
0
 done:
999
  /* Now the final memory allocation.  */
1000
0
  if (result == tmpbuf)
1001
0
    {
1002
0
      size_t memsize = length + extra_alloc;
1003
1004
0
      if (*resultp != NULL && *lengthp >= memsize)
1005
0
        result = *resultp;
1006
0
      else
1007
0
        {
1008
0
          char *memory;
1009
1010
0
          memory = (char *) malloc (memsize > 0 ? memsize : 1);
1011
0
          if (memory != NULL)
1012
0
            result = memory;
1013
0
          else
1014
0
            {
1015
0
              errno = ENOMEM;
1016
0
              return -1;
1017
0
            }
1018
0
        }
1019
0
      memcpy (result, tmpbuf, length);
1020
0
    }
1021
0
  else if (result != *resultp && length + extra_alloc < allocated)
1022
0
    {
1023
      /* Shrink the allocated memory if possible.  */
1024
0
      size_t memsize = length + extra_alloc;
1025
0
      char *memory;
1026
1027
0
      memory = (char *) realloc (result, memsize > 0 ? memsize : 1);
1028
0
      if (memory != NULL)
1029
0
        result = memory;
1030
0
    }
1031
0
  *resultp = result;
1032
0
  *lengthp = length;
1033
0
  return 0;
1034
0
# undef tmpbuf
1035
0
# undef tmpbufsize
1036
0
}
1037
1038
int
1039
mem_cd_iconveh (const char *src, size_t srclen,
1040
                const iconveh_t *cd,
1041
                enum iconv_ilseq_handler handler,
1042
                size_t *offsets,
1043
                char **resultp, size_t *lengthp)
1044
0
{
1045
0
  return mem_cd_iconveh_internal (src, srclen, cd->cd, cd->cd1, cd->cd2,
1046
0
                                  handler, 0, offsets, resultp, lengthp);
1047
0
}
1048
1049
char *
1050
str_cd_iconveh (const char *src,
1051
                const iconveh_t *cd,
1052
                enum iconv_ilseq_handler handler)
1053
0
{
1054
  /* For most encodings, a trailing NUL byte in the input will be converted
1055
     to a trailing NUL byte in the output.  But not for UTF-7.  So that this
1056
     function is usable for UTF-7, we have to exclude the NUL byte from the
1057
     conversion and add it by hand afterwards.  */
1058
0
  char *result = NULL;
1059
0
  size_t length = 0;
1060
0
  int retval = mem_cd_iconveh_internal (src, strlen (src),
1061
0
                                        cd->cd, cd->cd1, cd->cd2, handler, 1,
1062
0
                                        NULL, &result, &length);
1063
1064
0
  if (retval < 0)
1065
0
    {
1066
0
      free (result);
1067
0
      return NULL;
1068
0
    }
1069
1070
  /* Add the terminating NUL byte.  */
1071
0
  result[length] = '\0';
1072
1073
0
  return result;
1074
0
}
1075
1076
#endif
1077
1078
int
1079
mem_iconveh (const char *src, size_t srclen,
1080
             const char *from_codeset, const char *to_codeset,
1081
             enum iconv_ilseq_handler handler,
1082
             size_t *offsets,
1083
             char **resultp, size_t *lengthp)
1084
0
{
1085
0
  if (srclen == 0)
1086
0
    {
1087
      /* Nothing to convert.  */
1088
0
      *lengthp = 0;
1089
0
      return 0;
1090
0
    }
1091
0
  else if (offsets == NULL && c_strcasecmp (from_codeset, to_codeset) == 0)
1092
0
    {
1093
0
      char *result;
1094
1095
0
      if (*resultp != NULL && *lengthp >= srclen)
1096
0
        result = *resultp;
1097
0
      else
1098
0
        {
1099
0
          result = (char *) malloc (srclen);
1100
0
          if (result == NULL)
1101
0
            {
1102
0
              errno = ENOMEM;
1103
0
              return -1;
1104
0
            }
1105
0
        }
1106
0
      memcpy (result, src, srclen);
1107
0
      *resultp = result;
1108
0
      *lengthp = srclen;
1109
0
      return 0;
1110
0
    }
1111
0
  else
1112
0
    {
1113
0
#if HAVE_ICONV
1114
0
      iconveh_t cd;
1115
0
      char *result;
1116
0
      size_t length;
1117
0
      int retval;
1118
1119
0
      if (iconveh_open (to_codeset, from_codeset, &cd) < 0)
1120
0
        return -1;
1121
1122
0
      result = *resultp;
1123
0
      length = *lengthp;
1124
0
      retval = mem_cd_iconveh (src, srclen, &cd, handler, offsets,
1125
0
                               &result, &length);
1126
1127
0
      if (retval < 0)
1128
0
        {
1129
          /* Close cd, but preserve the errno from str_cd_iconv.  */
1130
0
          int saved_errno = errno;
1131
0
          iconveh_close (&cd);
1132
0
          errno = saved_errno;
1133
0
        }
1134
0
      else
1135
0
        {
1136
0
          if (iconveh_close (&cd) < 0)
1137
0
            {
1138
0
              if (result != *resultp)
1139
0
                free (result);
1140
0
              return -1;
1141
0
            }
1142
0
          *resultp = result;
1143
0
          *lengthp = length;
1144
0
        }
1145
0
      return retval;
1146
#else
1147
      /* This is a different error code than if iconv_open existed but didn't
1148
         support from_codeset and to_codeset, so that the caller can emit
1149
         an error message such as
1150
           "iconv() is not supported. Installing GNU libiconv and
1151
            then reinstalling this package would fix this."  */
1152
      errno = ENOSYS;
1153
      return -1;
1154
#endif
1155
0
    }
1156
0
}
1157
1158
char *
1159
str_iconveh (const char *src,
1160
             const char *from_codeset, const char *to_codeset,
1161
             enum iconv_ilseq_handler handler)
1162
0
{
1163
0
  if (*src == '\0' || c_strcasecmp (from_codeset, to_codeset) == 0)
1164
0
    {
1165
0
      char *result = strdup (src);
1166
1167
0
      if (result == NULL)
1168
0
        errno = ENOMEM;
1169
0
      return result;
1170
0
    }
1171
0
  else
1172
0
    {
1173
0
#if HAVE_ICONV
1174
0
      iconveh_t cd;
1175
0
      char *result;
1176
1177
0
      if (iconveh_open (to_codeset, from_codeset, &cd) < 0)
1178
0
        return NULL;
1179
1180
0
      result = str_cd_iconveh (src, &cd, handler);
1181
1182
0
      if (result == NULL)
1183
0
        {
1184
          /* Close cd, but preserve the errno from str_cd_iconv.  */
1185
0
          int saved_errno = errno;
1186
0
          iconveh_close (&cd);
1187
0
          errno = saved_errno;
1188
0
        }
1189
0
      else
1190
0
        {
1191
0
          if (iconveh_close (&cd) < 0)
1192
0
            {
1193
0
              free (result);
1194
0
              return NULL;
1195
0
            }
1196
0
        }
1197
0
      return result;
1198
#else
1199
      /* This is a different error code than if iconv_open existed but didn't
1200
         support from_codeset and to_codeset, so that the caller can emit
1201
         an error message such as
1202
           "iconv() is not supported. Installing GNU libiconv and
1203
            then reinstalling this package would fix this."  */
1204
      errno = ENOSYS;
1205
      return NULL;
1206
#endif
1207
0
    }
1208
0
}