gconvert.c 49.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* GLIB - Library of useful routines for C programming
 *
 * gconvert.c: Convert between character sets using iconv
 * Copyright Red Hat Inc., 2000
 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

23
#include "config.h"
Owen Taylor's avatar
1.3.14  
Owen Taylor committed
24

25 26
#include <iconv.h>
#include <errno.h>
27
#include <stdio.h>
28
#include <string.h>
29 30
#include <stdlib.h>

31
#include "galias.h"
Tor Lillqvist's avatar
Tor Lillqvist committed
32
#include "glib.h"
33
#include "gprintfint.h"
34
#include "gthreadinit.h"
Tor Lillqvist's avatar
Tor Lillqvist committed
35

36 37
#ifdef G_PLATFORM_WIN32
#define STRICT
38
#include <windows.h>
39
#undef STRICT
40
#endif
41

Owen Taylor's avatar
Owen Taylor committed
42
#include "glibintl.h"
43

44 45
#if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
#error GNU libiconv in use but included iconv.h not from libiconv
46
#endif
47 48
#if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
#error GNU libiconv not in use but included iconv.h is from libiconv
49 50
#endif

51
GQuark 
52
g_convert_error_quark (void)
53 54 55 56
{
  static GQuark quark;
  if (!quark)
    quark = g_quark_from_static_string ("g_convert_error");
57

58 59 60
  return quark;
}

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
static gboolean
try_conversion (const char *to_codeset,
		const char *from_codeset,
		iconv_t    *cd)
{
  *cd = iconv_open (to_codeset, from_codeset);

  if (*cd == (iconv_t)-1 && errno == EINVAL)
    return FALSE;
  else
    return TRUE;
}

static gboolean
try_to_aliases (const char **to_aliases,
		const char  *from_codeset,
		iconv_t     *cd)
{
  if (to_aliases)
    {
      const char **p = to_aliases;
      while (*p)
	{
	  if (try_conversion (*p, from_codeset, cd))
	    return TRUE;

	  p++;
	}
    }

  return FALSE;
}

94
extern const char **_g_charset_get_aliases (const char *canonical_name) G_GNUC_INTERNAL;
95

Havoc Pennington's avatar
docs  
Havoc Pennington committed
96 97 98 99 100
/**
 * g_iconv_open:
 * @to_codeset: destination codeset
 * @from_codeset: source codeset
 * 
101
 * Same as the standard UNIX routine iconv_open(), but
102
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
docs  
Havoc Pennington committed
103 104
 * a native implementation.
 * 
Owen Taylor's avatar
Owen Taylor committed
105
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
docs  
Havoc Pennington committed
106 107
 * more convenient than the raw iconv wrappers.
 * 
108 109
 * Return value: a "conversion descriptor", or (GIConv)-1 if
 *  opening the converter failed.
Havoc Pennington's avatar
docs  
Havoc Pennington committed
110
 **/
111 112 113 114
GIConv
g_iconv_open (const gchar  *to_codeset,
	      const gchar  *from_codeset)
{
115
  iconv_t cd;
116
  
117 118 119
  if (!try_conversion (to_codeset, from_codeset, &cd))
    {
      const char **to_aliases = _g_charset_get_aliases (to_codeset);
120
      const char **from_aliases = _g_charset_get_aliases (from_codeset);
121 122 123 124 125 126 127

      if (from_aliases)
	{
	  const char **p = from_aliases;
	  while (*p)
	    {
	      if (try_conversion (to_codeset, *p, &cd))
128
		goto out;
129 130

	      if (try_to_aliases (to_aliases, *p, &cd))
131
		goto out;
132 133 134 135 136 137

	      p++;
	    }
	}

      if (try_to_aliases (to_aliases, from_codeset, &cd))
138
	goto out;
139 140
    }

141
 out:
142
  return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
143 144
}

Havoc Pennington's avatar
docs  
Havoc Pennington committed
145 146 147 148 149 150 151 152
/**
 * g_iconv:
 * @converter: conversion descriptor from g_iconv_open()
 * @inbuf: bytes to convert
 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
 * @outbuf: converted output bytes
 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
 * 
153
 * Same as the standard UNIX routine iconv(), but
154
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
docs  
Havoc Pennington committed
155 156
 * a native implementation.
 *
Owen Taylor's avatar
Owen Taylor committed
157
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
docs  
Havoc Pennington committed
158 159 160 161
 * more convenient than the raw iconv wrappers.
 * 
 * Return value: count of non-reversible conversions, or -1 on error
 **/
162 163 164
size_t 
g_iconv (GIConv   converter,
	 gchar  **inbuf,
165
	 gsize   *inbytes_left,
166
	 gchar  **outbuf,
167
	 gsize   *outbytes_left)
168 169 170 171 172 173
{
  iconv_t cd = (iconv_t)converter;

  return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
}

Havoc Pennington's avatar
docs  
Havoc Pennington committed
174 175 176 177
/**
 * g_iconv_close:
 * @converter: a conversion descriptor from g_iconv_open()
 *
178
 * Same as the standard UNIX routine iconv_close(), but
179
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
docs  
Havoc Pennington committed
180
 * a native implementation. Should be called to clean up
Matthias Clasen's avatar
Matthias Clasen committed
181
 * the conversion descriptor from g_iconv_open() when
Havoc Pennington's avatar
docs  
Havoc Pennington committed
182 183
 * you are done converting things.
 *
Owen Taylor's avatar
Owen Taylor committed
184
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
docs  
Havoc Pennington committed
185 186 187 188
 * more convenient than the raw iconv wrappers.
 * 
 * Return value: -1 on error, 0 on success
 **/
189 190 191 192 193 194 195 196
gint
g_iconv_close (GIConv converter)
{
  iconv_t cd = (iconv_t)converter;

  return iconv_close (cd);
}

197 198 199 200 201 202 203

#define ICONV_CACHE_SIZE   (16)

struct _iconv_cache_bucket {
  gchar *key;
  guint32 refcount;
  gboolean used;
204
  GIConv cd;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
};

static GList *iconv_cache_list;
static GHashTable *iconv_cache;
static GHashTable *iconv_open_hash;
static guint iconv_cache_size = 0;
G_LOCK_DEFINE_STATIC (iconv_cache_lock);

/* caller *must* hold the iconv_cache_lock */
static void
iconv_cache_init (void)
{
  static gboolean initialized = FALSE;
  
  if (initialized)
    return;
  
  iconv_cache_list = NULL;
  iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
  iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
  
  initialized = TRUE;
}


/**
 * iconv_cache_bucket_new:
 * @key: cache key
 * @cd: iconv descriptor
 *
 * Creates a new cache bucket, inserts it into the cache and
 * increments the cache size.
 *
 * Returns a pointer to the newly allocated cache bucket.
 **/
240
static struct _iconv_cache_bucket *
241
iconv_cache_bucket_new (const gchar *key, GIConv cd)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
{
  struct _iconv_cache_bucket *bucket;
  
  bucket = g_new (struct _iconv_cache_bucket, 1);
  bucket->key = g_strdup (key);
  bucket->refcount = 1;
  bucket->used = TRUE;
  bucket->cd = cd;
  
  g_hash_table_insert (iconv_cache, bucket->key, bucket);
  
  /* FIXME: if we sorted the list so items with few refcounts were
     first, then we could expire them faster in iconv_cache_expire_unused () */
  iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
  
  iconv_cache_size++;
  
  return bucket;
}


/**
 * iconv_cache_bucket_expire:
 * @node: cache bucket's node
 * @bucket: cache bucket
 *
 * Expires a single cache bucket @bucket. This should only ever be
 * called on a bucket that currently has no used iconv descriptors
 * open.
 *
 * @node is not a required argument. If @node is not supplied, we
 * search for it ourselves.
 **/
static void
iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
{
  g_hash_table_remove (iconv_cache, bucket->key);
  
  if (node == NULL)
    node = g_list_find (iconv_cache_list, bucket);
  
  g_assert (node != NULL);
  
  if (node->prev)
    {
      node->prev->next = node->next;
      if (node->next)
        node->next->prev = node->prev;
    }
  else
    {
      iconv_cache_list = node->next;
      if (node->next)
        node->next->prev = NULL;
    }
  
  g_list_free_1 (node);
  
  g_free (bucket->key);
  g_iconv_close (bucket->cd);
  g_free (bucket);
  
  iconv_cache_size--;
}


/**
 * iconv_cache_expire_unused:
 *
 * Expires as many unused cache buckets as it needs to in order to get
 * the total number of buckets < ICONV_CACHE_SIZE.
 **/
static void
iconv_cache_expire_unused (void)
{
  struct _iconv_cache_bucket *bucket;
  GList *node, *next;
  
  node = iconv_cache_list;
  while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
    {
      next = node->next;
      
      bucket = node->data;
      if (bucket->refcount == 0)
        iconv_cache_bucket_expire (node, bucket);
      
      node = next;
    }
}

Havoc Pennington's avatar
Havoc Pennington committed
333
static GIConv
334
open_converter (const gchar *to_codeset,
335
		const gchar *from_codeset,
336 337
		GError     **error)
{
338 339 340 341 342 343
  struct _iconv_cache_bucket *bucket;
  gchar *key;
  GIConv cd;
  
  /* create our key */
  key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
344
  _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
345 346 347 348 349 350 351 352
  
  G_LOCK (iconv_cache_lock);
  
  /* make sure the cache has been initialized */
  iconv_cache_init ();
  
  bucket = g_hash_table_lookup (iconv_cache, key);
  if (bucket)
353
    {
354 355 356
      if (bucket->used)
        {
          cd = g_iconv_open (to_codeset, from_codeset);
357
          if (cd == (GIConv) -1)
358 359
            goto error;
        }
360
      else
361
        {
362 363 364 365
	  /* Apparently iconv on Solaris <= 7 segfaults if you pass in
	   * NULL for anything but inbuf; work around that. (NULL outbuf
	   * or NULL *outbuf is allowed by Unix98.)
	   */
366
	  gsize inbytes_left = 0;
367
	  gchar *outbuf = NULL;
368
	  gsize outbytes_left = 0;
369
		
370 371 372 373
          cd = bucket->cd;
          bucket->used = TRUE;
          
          /* reset the descriptor */
374
          g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
375 376 377
        }
      
      bucket->refcount++;
378
    }
379 380 381
  else
    {
      cd = g_iconv_open (to_codeset, from_codeset);
382
      if (cd == (GIConv) -1)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        goto error;
      
      iconv_cache_expire_unused ();
      
      bucket = iconv_cache_bucket_new (key, cd);
    }
  
  g_hash_table_insert (iconv_open_hash, cd, bucket->key);
  
  G_UNLOCK (iconv_cache_lock);
  
  return cd;
  
 error:
  
  G_UNLOCK (iconv_cache_lock);
  
  /* Something went wrong.  */
  if (errno == EINVAL)
    g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
		 _("Conversion from character set '%s' to '%s' is not supported"),
		 from_codeset, to_codeset);
  else
    g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
407 408
		 _("Could not open converter from '%s' to '%s'"),
		 from_codeset, to_codeset);
409
  
410
  return cd;
411
}
412

413 414 415 416 417
static int
close_converter (GIConv converter)
{
  struct _iconv_cache_bucket *bucket;
  const gchar *key;
418
  GIConv cd;
419
  
420
  cd = converter;
421
  
422
  if (cd == (GIConv) -1)
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    return 0;
  
  G_LOCK (iconv_cache_lock);
  
  key = g_hash_table_lookup (iconv_open_hash, cd);
  if (key)
    {
      g_hash_table_remove (iconv_open_hash, cd);
      
      bucket = g_hash_table_lookup (iconv_cache, key);
      g_assert (bucket);
      
      bucket->refcount--;
      
      if (cd == bucket->cd)
        bucket->used = FALSE;
      else
        g_iconv_close (cd);
      
      if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
        {
          /* expire this cache bucket */
          iconv_cache_bucket_expire (NULL, bucket);
        }
    }
  else
    {
      G_UNLOCK (iconv_cache_lock);
      
      g_warning ("This iconv context wasn't opened using open_converter");
      
      return g_iconv_close (converter);
    }
  
  G_UNLOCK (iconv_cache_lock);
  
  return 0;
460 461
}

462

463 464
/**
 * g_convert:
465 466 467 468 469 470
 * @str:           the string to convert
 * @len:           the length of the string
 * @to_codeset:    name of character set into which to convert @str
 * @from_codeset:  character set of @str.
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
471 472
 *                 Even if the conversion was successful, this may be 
 *                 less than @len if there were partial characters
473
 *                 at the end of the input. If the error
474 475
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
476
 *                 input sequence.
477
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
478
 *                 including the terminating nul).
479 480
 * @error:         location to store the error occuring, or %NULL to ignore
 *                 errors. Any of the errors in #GConvertError may occur.
481
 *
Matthias Clasen's avatar
Matthias Clasen committed
482
 * Converts a string from one character set to another.
483 484
 *
 * Return value: If the conversion was successful, a newly allocated
485 486
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
487 488 489
 **/
gchar*
g_convert (const gchar *str,
490
           gssize       len,  
491 492
           const gchar *to_codeset,
           const gchar *from_codeset,
493 494
           gsize       *bytes_read, 
	   gsize       *bytes_written, 
495 496
	   GError     **error)
{
497
  gchar *res;
498
  GIConv cd;
499 500 501 502
  
  g_return_val_if_fail (str != NULL, NULL);
  g_return_val_if_fail (to_codeset != NULL, NULL);
  g_return_val_if_fail (from_codeset != NULL, NULL);
503
  
504 505
  cd = open_converter (to_codeset, from_codeset, error);

506
  if (cd == (GIConv) -1)
507 508 509 510 511 512 513 514 515 516
    {
      if (bytes_read)
        *bytes_read = 0;
      
      if (bytes_written)
        *bytes_written = 0;
      
      return NULL;
    }

517 518 519 520
  res = g_convert_with_iconv (str, len, cd,
			      bytes_read, bytes_written,
			      error);
  
521
  close_converter (cd);
522 523 524 525 526 527 528 529 530 531 532

  return res;
}

/**
 * g_convert_with_iconv:
 * @str:           the string to convert
 * @len:           the length of the string
 * @converter:     conversion descriptor from g_iconv_open()
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
533
 *                 Even if the conversion was successful, this may be 
534
 *                 less than @len if there were partial characters
535
 *                 at the end of the input. If the error
536 537
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
538
 *                 input sequence.
539
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
540
 *                 including the terminating nul).
541 542 543
 * @error:         location to store the error occuring, or %NULL to ignore
 *                 errors. Any of the errors in #GConvertError may occur.
 *
Matthias Clasen's avatar
Matthias Clasen committed
544
 * Converts a string from one character set to another.
545 546
 *
 * Return value: If the conversion was successful, a newly allocated
547 548
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
 **/
gchar*
g_convert_with_iconv (const gchar *str,
		      gssize       len,
		      GIConv       converter,
		      gsize       *bytes_read, 
		      gsize       *bytes_written, 
		      GError     **error)
{
  gchar *dest;
  gchar *outp;
  const gchar *p;
  gsize inbytes_remaining;
  gsize outbytes_remaining;
  gsize err;
  gsize outbuf_size;
  gboolean have_error = FALSE;
  
  g_return_val_if_fail (str != NULL, NULL);
  g_return_val_if_fail (converter != (GIConv) -1, NULL);
     
570 571 572 573 574
  if (len < 0)
    len = strlen (str);

  p = str;
  inbytes_remaining = len;
575
  outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
576
  
577 578 579 580 581
  outbytes_remaining = outbuf_size - 1; /* -1 for nul */
  outp = dest = g_malloc (outbuf_size);

 again:
  
582
  err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
583 584 585 586 587 588 589 590 591 592 593 594

  if (err == (size_t) -1)
    {
      switch (errno)
	{
	case EINVAL:
	  /* Incomplete text, do not report an error */
	  break;
	case E2BIG:
	  {
	    size_t used = outp - dest;

595 596
	    outbuf_size *= 2;
	    dest = g_realloc (dest, outbuf_size);
597
		
598 599
	    outp = dest + used;
	    outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
600 601 602 603 604

	    goto again;
	  }
	case EILSEQ:
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
605
		       _("Invalid byte sequence in conversion input"));
606 607 608
	  have_error = TRUE;
	  break;
	default:
609
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
610
		       _("Error during conversion: %s"),
Owen Taylor's avatar
Owen Taylor committed
611
		       g_strerror (errno));
612 613 614 615 616 617 618 619 620
	  have_error = TRUE;
	  break;
	}
    }

  *outp = '\0';
  
  if (bytes_read)
    *bytes_read = p - str;
621 622 623 624
  else
    {
      if ((p - str) != len) 
	{
Havoc Pennington's avatar
Havoc Pennington committed
625 626 627 628 629 630
          if (!have_error)
            {
              g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
                           _("Partial character sequence at end of input"));
              have_error = TRUE;
            }
631 632
	}
    }
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655

  if (bytes_written)
    *bytes_written = outp - dest;	/* Doesn't include '\0' */

  if (have_error)
    {
      g_free (dest);
      return NULL;
    }
  else
    return dest;
}

/**
 * g_convert_with_fallback:
 * @str:          the string to convert
 * @len:          the length of the string
 * @to_codeset:   name of character set into which to convert @str
 * @from_codeset: character set of @str.
 * @fallback:     UTF-8 string to use in place of character not
 *                present in the target encoding. (This must be
 *                in the target encoding), if %NULL, characters
 *                not in the target encoding will be represented
656
 *                as Unicode escapes \uxxxx or \Uxxxxyyyy.
657 658
 * @bytes_read:   location to store the number of bytes in the
 *                input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
659
 *                Even if the conversion was successful, this may be 
660
 *                less than @len if there were partial characters
661
 *                at the end of the input.
662
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
663
 *                including the terminating nul).
664 665 666
 * @error:        location to store the error occuring, or %NULL to ignore
 *                errors. Any of the errors in #GConvertError may occur.
 *
Matthias Clasen's avatar
Matthias Clasen committed
667
 * Converts a string from one character set to another, possibly
668 669 670 671
 * including fallback sequences for characters not representable
 * in the output. Note that it is not guaranteed that the specification
 * for the fallback sequences in @fallback will be honored. Some
 * systems may do a approximate conversion from @from_codeset
672
 * to @to_codeset in their iconv() functions, 
Owen Taylor's avatar
Owen Taylor committed
673
 * in which case GLib will simply return that approximate conversion.
674 675
 *
 * Return value: If the conversion was successful, a newly allocated
676 677
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
678 679 680
 **/
gchar*
g_convert_with_fallback (const gchar *str,
681
			 gssize       len,    
682 683 684
			 const gchar *to_codeset,
			 const gchar *from_codeset,
			 gchar       *fallback,
685 686
			 gsize       *bytes_read,
			 gsize       *bytes_written,
687 688 689 690 691 692 693
			 GError     **error)
{
  gchar *utf8;
  gchar *dest;
  gchar *outp;
  const gchar *insert_str = NULL;
  const gchar *p;
694
  gsize inbytes_remaining;   
695
  const gchar *save_p = NULL;
696 697 698
  gsize save_inbytes = 0;
  gsize outbytes_remaining; 
  gsize err;
699
  GIConv cd;
700
  gsize outbuf_size;
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
  gboolean have_error = FALSE;
  gboolean done = FALSE;

  GError *local_error = NULL;
  
  g_return_val_if_fail (str != NULL, NULL);
  g_return_val_if_fail (to_codeset != NULL, NULL);
  g_return_val_if_fail (from_codeset != NULL, NULL);
     
  if (len < 0)
    len = strlen (str);
  
  /* Try an exact conversion; we only proceed if this fails
   * due to an illegal sequence in the input string.
   */
  dest = g_convert (str, len, to_codeset, from_codeset, 
		    bytes_read, bytes_written, &local_error);
  if (!local_error)
    return dest;

  if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
    {
      g_propagate_error (error, local_error);
      return NULL;
    }
  else
    g_error_free (local_error);

Havoc Pennington's avatar
Havoc Pennington committed
729 730
  local_error = NULL;
  
731 732 733 734
  /* No go; to proceed, we need a converter from "UTF-8" to
   * to_codeset, and the string as UTF-8.
   */
  cd = open_converter (to_codeset, "UTF-8", error);
735
  if (cd == (GIConv) -1)
736 737 738 739 740 741 742 743 744 745 746 747 748
    {
      if (bytes_read)
        *bytes_read = 0;
      
      if (bytes_written)
        *bytes_written = 0;
      
      return NULL;
    }

  utf8 = g_convert (str, len, "UTF-8", from_codeset, 
		    bytes_read, &inbytes_remaining, error);
  if (!utf8)
749
    {
750
      close_converter (cd);
751 752 753 754
      if (bytes_written)
        *bytes_written = 0;
      return NULL;
    }
755 756 757 758 759 760 761 762 763 764

  /* Now the heart of the code. We loop through the UTF-8 string, and
   * whenever we hit an offending character, we form fallback, convert
   * the fallback to the target codeset, and then go back to
   * converting the original string after finishing with the fallback.
   *
   * The variables save_p and save_inbytes store the input state
   * for the original string while we are converting the fallback
   */
  p = utf8;
765 766

  outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
767 768 769 770 771
  outbytes_remaining = outbuf_size - 1; /* -1 for nul */
  outp = dest = g_malloc (outbuf_size);

  while (!done && !have_error)
    {
772
      size_t inbytes_tmp = inbytes_remaining;
773
      err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
774
      inbytes_remaining = inbytes_tmp;
775 776 777 778 779 780 781 782 783 784 785

      if (err == (size_t) -1)
	{
	  switch (errno)
	    {
	    case EINVAL:
	      g_assert_not_reached();
	      break;
	    case E2BIG:
	      {
		size_t used = outp - dest;
786

787 788 789 790 791
		outbuf_size *= 2;
		dest = g_realloc (dest, outbuf_size);
		
		outp = dest + used;
		outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
792 793 794 795 796 797 798 799 800
		
		break;
	      }
	    case EILSEQ:
	      if (save_p)
		{
		  /* Error converting fallback string - fatal
		   */
		  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
801
			       _("Cannot convert fallback '%s' to codeset '%s'"),
802 803 804 805 806 807 808 809 810
			       insert_str, to_codeset);
		  have_error = TRUE;
		  break;
		}
	      else
		{
		  if (!fallback)
		    { 
		      gunichar ch = g_utf8_get_char (p);
811
		      insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
812 813 814 815 816 817 818 819 820 821 822 823
						    ch);
		    }
		  else
		    insert_str = fallback;
		  
		  save_p = g_utf8_next_char (p);
		  save_inbytes = inbytes_remaining - (save_p - p);
		  p = insert_str;
		  inbytes_remaining = strlen (p);
		}
	      break;
	    default:
824
	      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
825
			   _("Error during conversion: %s"),
Owen Taylor's avatar
Owen Taylor committed
826
			   g_strerror (errno));
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
	      have_error = TRUE;
	      break;
	    }
	}
      else
	{
	  if (save_p)
	    {
	      if (!fallback)
		g_free ((gchar *)insert_str);
	      p = save_p;
	      inbytes_remaining = save_inbytes;
	      save_p = NULL;
	    }
	  else
	    done = TRUE;
	}
    }

  /* Cleanup
   */
  *outp = '\0';
  
850
  close_converter (cd);
851 852

  if (bytes_written)
853
    *bytes_written = outp - dest;	/* Doesn't include '\0' */
854 855 856 857 858 859 860 861 862 863 864 865 866

  g_free (utf8);

  if (have_error)
    {
      if (save_p && !fallback)
	g_free ((gchar *)insert_str);
      g_free (dest);
      return NULL;
    }
  else
    return dest;
}
867 868 869 870

/*
 * g_locale_to_utf8
 *
871 872 873
 * 
 */

874 875 876 877
static gchar *
strdup_len (const gchar *string,
	    gssize       len,
	    gsize       *bytes_written,
878 879
	    gsize       *bytes_read,
	    GError      **error)
880 881 882 883
	 
{
  gsize real_len;

884
  if (!g_utf8_validate (string, len, NULL))
885 886 887 888 889 890 891 892 893 894 895
    {
      if (bytes_read)
	*bytes_read = 0;
      if (bytes_written)
	*bytes_written = 0;

      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
		   _("Invalid byte sequence in conversion input"));
      return NULL;
    }
  
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  if (len < 0)
    real_len = strlen (string);
  else
    {
      real_len = 0;
      
      while (real_len < len && string[real_len])
	real_len++;
    }
  
  if (bytes_read)
    *bytes_read = real_len;
  if (bytes_written)
    *bytes_written = real_len;

  return g_strndup (string, real_len);
}

914 915 916 917
/**
 * g_locale_to_utf8:
 * @opsysstring:   a string in the encoding of the current locale
 * @len:           the length of the string, or -1 if the string is
918
 *                 nul-terminated.
919 920
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
921
 *                 Even if the conversion was successful, this may be 
922
 *                 less than @len if there were partial characters
923
 *                 at the end of the input. If the error
924 925
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
926
 *                 input sequence.
927
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
928
 *                 including the terminating nul).
929
 * @error:         location to store the error occuring, or %NULL to ignore
930 931
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
932 933 934
 * Converts a string which is in the encoding used for strings by
 * the C runtime (usually the same as that used by the operating
 * system) in the current locale into a UTF-8 string.
935 936 937
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
938
gchar *
939
g_locale_to_utf8 (const gchar  *opsysstring,
940 941 942
		  gssize        len,            
		  gsize        *bytes_read,    
		  gsize        *bytes_written,
943
		  GError      **error)
944
{
945
  const char *charset;
946 947

  if (g_get_charset (&charset))
948
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
949 950 951
  else
    return g_convert (opsysstring, len, 
		      "UTF-8", charset, bytes_read, bytes_written, error);
952 953
}

954 955 956 957
/**
 * g_locale_from_utf8:
 * @utf8string:    a UTF-8 encoded string 
 * @len:           the length of the string, or -1 if the string is
958
 *                 nul-terminated.
959 960
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
961
 *                 Even if the conversion was successful, this may be 
962
 *                 less than @len if there were partial characters
963
 *                 at the end of the input. If the error
964 965
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
966
 *                 input sequence.
967
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
968
 *                 including the terminating nul).
969
 * @error:         location to store the error occuring, or %NULL to ignore
970 971 972 973 974 975 976 977
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
 * Converts a string from UTF-8 to the encoding used for strings by
 * the C runtime (usually the same as that used by the operating
 * system) in the current locale.
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
978
gchar *
979
g_locale_from_utf8 (const gchar *utf8string,
980 981 982
		    gssize       len,            
		    gsize       *bytes_read,    
		    gsize       *bytes_written,
983
		    GError     **error)
984
{
985
  const gchar *charset;
986 987

  if (g_get_charset (&charset))
988
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
989 990 991
  else
    return g_convert (utf8string, len,
		      charset, "UTF-8", bytes_read, bytes_written, error);
992 993
}

994
#ifndef G_PLATFORM_WIN32
995

996 997 998 999 1000
typedef struct _GFilenameCharsetCache GFilenameCharsetCache;

struct _GFilenameCharsetCache {
  gboolean is_utf8;
  gchar *charset;
1001
  gchar **filename_charsets;
1002 1003 1004 1005 1006 1007 1008
};

static void
filename_charset_cache_free (gpointer data)
{
  GFilenameCharsetCache *cache = data;
  g_free (cache->charset);
1009
  g_strfreev (cache->filename_charsets);
1010 1011 1012
  g_free (cache);
}

Matthias Clasen's avatar
Matthias Clasen committed
1013
/**
1014 1015
 * g_get_filename_charsets:
 * @charsets: return location for the %NULL-terminated list of encoding names
1016
 *
1017 1018 1019
 * Determines the preferred character sets used for filenames.
 * The first character set from the @charsets is the filename encoding, the
 * subsequent character sets are used when trying to generate a displayable
Tor Lillqvist's avatar
Tor Lillqvist committed
1020
 * representation of a filename, see g_filename_display_name().
1021
 *
1022 1023
 * The character sets are determined by consulting the environment variables 
 * <envar>G_FILENAME_ENCODING</envar> and <envar>G_BROKEN_FILENAMES</envar>.
1024
 *
1025 1026 1027 1028 1029 1030 1031 1032 1033
 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
 * of character set names. The special token "@locale" is taken to mean the 
 * character set for the current locale. If <envar>G_FILENAME_ENCODING</envar> 
 * is not set, but <envar>G_BROKEN_FILENAMES</envar> is, the character set of 
 * the current locale is taken as the filename encoding. If neither environment
 * variable is set, UTF-8 is taken as the filename encoding, but the character
 * set of the current locale is also put in the list of encodings.
 *
 * The returned @charsets belong to GLib and must not be freed.
1034 1035
 *
 * Note that on Unix, regardless of the locale character set or
1036
 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present on a
1037 1038
 * system might be in any random encoding or just gibberish.
 *
1039 1040 1041
 * Return value: %TRUE if the filename encoding is UTF-8.
 * 
 * Since: 2.6
1042
 */
1043 1044
gboolean
g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1045
{
1046 1047 1048
  static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
  GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
  const gchar *charset;
1049

1050
  if (!cache)
1051
    {
1052 1053 1054 1055 1056 1057 1058 1059 1060
      cache = g_new0 (GFilenameCharsetCache, 1);
      g_static_private_set (&cache_private, cache, filename_charset_cache_free);
    }

  g_get_charset (&charset);

  if (!(cache->charset && strcmp (cache->charset, charset) == 0))
    {
      const gchar *new_charset;
1061 1062
      gchar *p;
      gint i;
1063

1064
      g_free (cache->charset);
1065
      g_strfreev (cache->filename_charsets);
1066
      cache->charset = g_strdup (charset);
1067 1068 1069 1070
      
      p = getenv ("G_FILENAME_ENCODING");
      if (p != NULL) 
	{
1071 1072
	  cache->filename_charsets = g_strsplit (p, ",", 0);
	  cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1073

1074
	  for (i = 0; cache->filename_charsets[i]; i++)
1075
	    {
1076 1077 1078 1079 1080 1081
	      if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
		{
		  g_get_charset (&new_charset);
		  g_free (cache->filename_charsets[i]);
		  cache->filename_charsets[i] = g_strdup (new_charset);
		}
1082 1083 1084
	    }
	}
      else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1085
	{
1086
	  cache->filename_charsets = g_new0 (gchar *, 2);
1087
	  cache->is_utf8 = g_get_charset (&new_charset);
1088
	  cache->filename_charsets[0] = g_strdup (new_charset);
1089
	}
1090 1091
      else 
	{
1092
	  cache->filename_charsets = g_new0 (gchar *, 3);
1093
	  cache->is_utf8 = TRUE;
1094 1095 1096
	  cache->filename_charsets[0] = g_strdup ("UTF-8");
	  if (!g_get_charset (&new_charset))
	    cache->filename_charsets[1] = g_strdup (new_charset);
1097 1098
	}
    }
1099

1100 1101
  if (filename_charsets)
    *filename_charsets = (const gchar **)cache->filename_charsets;
1102

1103
  return cache->is_utf8;
1104
}
1105

1106
#else /* G_PLATFORM_WIN32 */
1107

1108 1109
gboolean
g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets) 
1110
{
1111 1112 1113 1114 1115
  static gchar *charsets[] = {
    "UTF-8",
    NULL
  };

1116 1117
#ifdef G_OS_WIN32
  /* On Windows GLib pretends that the filename charset is UTF-8 */
1118 1119 1120
  if (filename_charsets)
    *filename_charsets = charsets;

1121 1122
  return TRUE;
#else
1123 1124
  gboolean result;

1125
  /* Cygwin works like before */
1126 1127 1128 1129 1130 1131
  result = g_get_charset (&(charsets[0]));

  if (filename_charsets)
    *filename_charsets = charsets;

  return result;
1132 1133 1134
#endif
}

1135
#endif /* G_PLATFORM_WIN32 */
1136 1137

static gboolean
1138
get_filename_charset (const gchar **filename_charset)
1139
{
1140 1141 1142 1143
  const gchar **charsets;
  gboolean is_utf8;
  
  is_utf8 = g_get_filename_charsets (&charsets);
1144

1145 1146 1147 1148 1149
  if (filename_charset)
    *filename_charset = charsets[0];
  
  return is_utf8;
}
1150 1151 1152 1153 1154

/* This is called from g_thread_init(). It's used to
 * initialize some static data in a threadsafe way.
 */
void 
1155
_g_convert_thread_init (void)
1156
{
1157
  const gchar **dummy;
Matthias Clasen's avatar
Matthias Clasen committed
1158
  (void) g_get_filename_charsets (&dummy);
1159 1160
}

1161 1162 1163 1164
/**
 * g_filename_to_utf8:
 * @opsysstring:   a string in the encoding for filenames
 * @len:           the length of the string, or -1 if the string is
1165
 *                 nul-terminated.
1166 1167
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
1168
 *                 Even if the conversion was successful, this may be 
1169
 *                 less than @len if there were partial characters
1170
 *                 at the end of the input. If the error
1171 1172
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1173
 *                 input sequence.
1174
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1175
 *                 including the terminating nul).
1176
 * @error:         location to store the error occuring, or %NULL to ignore
1177 1178 1179 1180 1181 1182 1183
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
 * Converts a string which is in the encoding used for filenames
 * into a UTF-8 string.
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1184
gchar*
1185
g_filename_to_utf8 (const gchar *opsysstring, 
1186 1187 1188
		    gssize       len,           
		    gsize       *bytes_read,   
		    gsize       *bytes_written,
1189
		    GError     **error)
1190
{
1191 1192 1193
  const gchar *charset;

  if (get_filename_charset (&charset))
1194
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1195 1196 1197
  else
    return g_convert (opsysstring, len, 
		      "UTF-8", charset, bytes_read, bytes_written, error);
1198 1199
}

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
#ifdef G_OS_WIN32

#undef g_filename_to_utf8

/* Binary compatibility version. Not for newly compiled code. */

gchar*
g_filename_to_utf8 (const gchar *opsysstring, 
		    gssize       len,           
		    gsize       *bytes_read,   
		    gsize       *bytes_written,
		    GError     **error)
{
  const gchar *charset;

1215
  if (g_get_charset (&charset))
1216 1217 1218 1219 1220 1221 1222 1223
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
  else
    return g_convert (opsysstring, len, 
		      "UTF-8", charset, bytes_read, bytes_written, error);
}

#endif

1224 1225
/**
 * g_filename_from_utf8:
1226
 * @utf8string:    a UTF-8 encoded string.
1227
 * @len:           the length of the string, or -1 if the string is
1228
 *                 nul-terminated.
1229 1230
 * @bytes_read:    location to store the number of bytes in the
 *                 input string that were successfully converted, or %NULL.
Matthias Clasen's avatar
Matthias Clasen committed
1231
 *                 Even if the conversion was successful, this may be 
1232
 *                 less than @len if there were partial characters
1233
 *                 at the end of the input. If the error
1234 1235
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1236
 *                 input sequence.
1237
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1238
 *                 including the terminating nul).
1239
 * @error:         location to store the error occuring, or %NULL to ignore
1240 1241 1242 1243 1244 1245
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
 * Converts a string from UTF-8 to the encoding used for filenames.
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1246
gchar*
1247
g_filename_from_utf8 (const gchar *utf8string,
1248 1249 1250
		      gssize       len,            
		      gsize       *bytes_read,    
		      gsize       *bytes_written,
1251
		      GError     **error)
1252
{
1253 1254 1255
  const gchar *charset;

  if (get_filename_charset (&charset))
1256
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1257 1258 1259
  else
    return g_convert (utf8string, len,
		      charset, "UTF-8", bytes_read, bytes_written, error);
1260
}
1261

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
#ifdef G_OS_WIN32

#undef g_filename_from_utf8

/* Binary compatibility version. Not for newly compiled code. */

gchar*
g_filename_from_utf8 (const gchar *utf8string,
		      gssize       len,            
		      gsize       *bytes_read,    
		      gsize       *bytes_written,
		      GError     **error)
{
  const gchar *charset;

1277
  if (g_get_charset (&charset))
1278 1279 1280 1281 1282 1283 1284 1285
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
  else
    return g_convert (utf8string, len,
		      charset, "UTF-8", bytes_read, bytes_written, error);
}

#endif

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
/* Test of haystack has the needle prefix, comparing case
 * insensitive. haystack may be UTF-8, but needle must
 * contain only ascii. */
static gboolean
has_case_prefix (const gchar *haystack, const gchar *needle)
{
  const gchar *h, *n;
  
  /* Eat one character at a time. */
  h = haystack;
  n = needle;

  while (*n && *h &&
	 g_ascii_tolower (*n) == g_ascii_tolower (*h))
    {
      n++;
      h++;
    }
  
  return *n == '\0';
}

typedef enum {
  UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
  UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1311
  UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1312 1313 1314 1315 1316
  UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
  UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
} UnsafeCharacterSet;

static const guchar acceptable[96] = {
1317 1318
  /* A table of the ASCII chars from space (32) to DEL (127) */
  /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1319
  0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1320
  /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1321
  0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1322
  /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1323
  0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1324 1325 1326 1327 1328 1329
  /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
  0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
  /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
  0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
  /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
  0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20