Coverage Report

Created: 2025-10-12 06:56

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