gconvert.c 55.3 KB
Newer Older
1 2 3 4
/* GLIB - Library of useful routines for C programming
 *
 * gconvert.c: Convert between character sets using iconv
 * Copyright Red Hat Inc., 2000
5
 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * 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
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>

Tor Lillqvist's avatar
Tor Lillqvist committed
31
#include "glib.h"
32
#include "gprintfint.h"
33
#include "gthreadprivate.h"
34
#include "gunicode.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 52
#include "galias.h"

53
GQuark 
54
g_convert_error_quark (void)
55
{
56
  return g_quark_from_static_string ("g_convert_error");
57 58
}

59 60 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
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;
}

92 93
G_GNUC_INTERNAL extern const char ** 
_g_charset_get_aliases (const char *canonical_name);
94

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

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

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

	      p++;
	    }
	}

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

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

Havoc Pennington's avatar
Havoc Pennington committed
144 145 146 147 148 149 150 151
/**
 * 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
 * 
152
 * Same as the standard UNIX routine iconv(), but
153
 * may be implemented via libiconv on UNIX flavors that lack
Havoc Pennington's avatar
Havoc Pennington committed
154 155
 * a native implementation.
 *
Owen Taylor's avatar
Owen Taylor committed
156
 * GLib provides g_convert() and g_locale_to_utf8() which are likely
Havoc Pennington's avatar
Havoc Pennington committed
157 158 159 160
 * more convenient than the raw iconv wrappers.
 * 
 * Return value: count of non-reversible conversions, or -1 on error
 **/
161
gsize 
162 163
g_iconv (GIConv   converter,
	 gchar  **inbuf,
164
	 gsize   *inbytes_left,
165
	 gchar  **outbuf,
166
	 gsize   *outbytes_left)
167 168 169 170 171 172
{
  iconv_t cd = (iconv_t)converter;

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

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

  return iconv_close (cd);
}

196

197 198
#ifdef NEED_ICONV_CACHE

199 200 201 202 203 204
#define ICONV_CACHE_SIZE   (16)

struct _iconv_cache_bucket {
  gchar *key;
  guint32 refcount;
  gboolean used;
205
  GIConv cd;
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
};

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.
 *
239 240
 * This assumes ownership of @key.
 *
241 242
 * Returns a pointer to the newly allocated cache bucket.
 **/
243
static struct _iconv_cache_bucket *
244
iconv_cache_bucket_new (gchar *key, GIConv cd)
245 246 247 248
{
  struct _iconv_cache_bucket *bucket;
  
  bucket = g_new (struct _iconv_cache_bucket, 1);
249
  bucket->key = key;
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 333 334 335
  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
336
static GIConv
337
open_converter (const gchar *to_codeset,
338
		const gchar *from_codeset,
339 340
		GError     **error)
{
341
  struct _iconv_cache_bucket *bucket;
342
  gchar *key, *dyn_key, auto_key[80];
343
  GIConv cd;
344
  gsize len_from_codeset, len_to_codeset;
345 346
  
  /* create our key */
347 348 349 350 351 352 353 354 355 356 357 358 359
  len_from_codeset = strlen (from_codeset);
  len_to_codeset = strlen (to_codeset);
  if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
    {
      key = auto_key;
      dyn_key = NULL;
    }
  else
    key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
  memcpy (key, from_codeset, len_from_codeset);
  key[len_from_codeset] = ':';
  strcpy (key + len_from_codeset + 1, to_codeset);

360 361 362 363 364 365 366
  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)
367
    {
368 369
      g_free (dyn_key);

370 371 372
      if (bucket->used)
        {
          cd = g_iconv_open (to_codeset, from_codeset);
373
          if (cd == (GIConv) -1)
374 375
            goto error;
        }
376
      else
377
        {
378 379 380 381
	  /* 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.)
	   */
382
	  gsize inbytes_left = 0;
383
	  gchar *outbuf = NULL;
384
	  gsize outbytes_left = 0;
385
		
386 387 388 389
          cd = bucket->cd;
          bucket->used = TRUE;
          
          /* reset the descriptor */
390
          g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
391 392 393
        }
      
      bucket->refcount++;
394
    }
395 396 397
  else
    {
      cd = g_iconv_open (to_codeset, from_codeset);
398 399 400 401 402
      if (cd == (GIConv) -1) 
	{
	  g_free (dyn_key);
	  goto error;
	}
403 404
      
      iconv_cache_expire_unused ();
405 406

      bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
407 408 409 410 411 412 413 414 415 416 417 418 419
    }
  
  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.  */
420 421 422 423 424 425 426 427 428 429 430
  if (error)
    {
      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,
		     _("Could not open converter from '%s' to '%s'"),
		     from_codeset, to_codeset);
    }
431
  
432
  return cd;
433
}
434

435 436 437 438 439
static int
close_converter (GIConv converter)
{
  struct _iconv_cache_bucket *bucket;
  const gchar *key;
440
  GIConv cd;
441
  
442
  cd = converter;
443
  
444
  if (cd == (GIConv) -1)
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    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;
482 483
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
#else  /* !NEED_ICONV_CACHE */

static GIConv
open_converter (const gchar *to_codeset,
		const gchar *from_codeset,
		GError     **error)
{
  GIConv cd;

  cd = g_iconv_open (to_codeset, from_codeset);

  if (cd == (GIConv) -1)
    {
      /* Something went wrong.  */
      if (error)
	{
	  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,
			 _("Could not open converter from '%s' to '%s'"),
			 from_codeset, to_codeset);
	}
    }
  
  return cd;
}

static int
close_converter (GIConv cd)
{
  if (cd == (GIConv) -1)
    return 0;
  
  return g_iconv_close (cd);  
}

#endif /* NEED_ICONV_CACHE */

525 526 527
/**
 * g_convert_with_iconv:
 * @str:           the string to convert
528 529
 * @len:           the length of the string, or -1 if the string is 
 *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
530 531 532
 * @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.
 *
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
 * Converts a string from one character set to another. 
 * 
 * Note that you should use g_iconv() for streaming 
 * conversions<footnote id="streaming-state">
 *  <para>
 * Despite the fact that @byes_read can return information about partial 
 * characters, the <literal>g_convert_...</literal> functions
 * are not generally suitable for streaming. If the underlying converter 
 * being used maintains internal state, then this won't be preserved 
 * across successive calls to g_convert(), g_convert_with_iconv() or 
 * g_convert_with_fallback(). (An example of this is the GNU C converter 
 * for CP1255 which does not emit a base character until it knows that 
 * the next character is not a mark that could combine with the base 
 * character.)
 *  </para>
 * </footnote>. 
560 561
 *
 * Return value: If the conversion was successful, a newly allocated
562 563
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
 **/
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;
581
  gboolean done = FALSE;
582
  gboolean reset = FALSE;
583 584 585
  
  g_return_val_if_fail (converter != (GIConv) -1, NULL);
     
586 587 588 589 590
  if (len < 0)
    len = strlen (str);

  p = str;
  inbytes_remaining = len;
591
  outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
592
  
593 594 595
  outbytes_remaining = outbuf_size - 1; /* -1 for nul */
  outp = dest = g_malloc (outbuf_size);

596
  while (!done && !have_error)
597
    {
598 599 600 601
      if (reset)
        err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
      else
        err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
602

603
      if (err == (gsize) -1)
604
	{
605 606 607 608
	  switch (errno)
	    {
	    case EINVAL:
	      /* Incomplete text, do not report an error */
609
	      done = TRUE;
610 611 612
	      break;
	    case E2BIG:
	      {
613
		gsize used = outp - dest;
614
		
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
		outbuf_size *= 2;
		dest = g_realloc (dest, outbuf_size);
		
		outp = dest + used;
		outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
	      }
	      break;
	    case EILSEQ:
	      if (error)
		g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
			     _("Invalid byte sequence in conversion input"));
	      have_error = TRUE;
	      break;
	    default:
	      if (error)
		g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
			     _("Error during conversion: %s"),
			     g_strerror (errno));
	      have_error = TRUE;
	      break;
	    }
	}
      else 
	{
639
	  if (!reset)
640 641
	    {
	      /* call g_iconv with NULL inbuf to cleanup shift state */
642
	      reset = TRUE;
643 644 645 646
	      inbytes_remaining = 0;
	    }
	  else
	    done = TRUE;
647 648 649 650 651 652 653
	}
    }

  *outp = '\0';
  
  if (bytes_read)
    *bytes_read = p - str;
654 655 656 657
  else
    {
      if ((p - str) != len) 
	{
658 659
          if (!have_error)
            {
660 661 662
	      if (error)
		g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
			     _("Partial character sequence at end of input"));
663 664
              have_error = TRUE;
            }
665 666
	}
    }
667 668 669 670 671 672 673 674 675 676 677 678 679

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

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

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 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 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
/**
 * g_convert:
 * @str:           the string to convert
 * @len:           the length of the string, or -1 if the string is 
 *                 nul-terminated<footnote id="nul-unsafe">
                     <para>
                       Note that some encodings may allow nul bytes to 
                       occur inside strings. In that case, using -1 for 
                       the @len parameter is unsafe.
                     </para>
                   </footnote>. 
 * @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.
 *                 Even if the conversion was successful, this may be 
 *                 less than @len if there were partial characters
 *                 at the end of the input. If the error
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
 *                 input sequence.
 * @bytes_written: the number of bytes stored in the output buffer (not 
 *                 including the terminating nul).
 * @error:         location to store the error occuring, or %NULL to ignore
 *                 errors. Any of the errors in #GConvertError may occur.
 *
 * Converts a string from one character set to another.
 *
 * Note that you should use g_iconv() for streaming 
 * conversions<footnoteref linkend="streaming-state"/>.
 *
 * Return value: If the conversion was successful, a newly allocated
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
 **/
gchar*
g_convert (const gchar *str,
           gssize       len,  
           const gchar *to_codeset,
           const gchar *from_codeset,
           gsize       *bytes_read, 
	   gsize       *bytes_written, 
	   GError     **error)
{
  gchar *res;
  GIConv cd;

  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);
  
  cd = open_converter (to_codeset, from_codeset, error);

  if (cd == (GIConv) -1)
    {
      if (bytes_read)
        *bytes_read = 0;
      
      if (bytes_written)
        *bytes_written = 0;
      
      return NULL;
    }

  res = g_convert_with_iconv (str, len, cd,
			      bytes_read, bytes_written,
			      error);

  close_converter (cd);

  return res;
}

753 754 755
/**
 * g_convert_with_fallback:
 * @str:          the string to convert
756 757
 * @len:          the length of the string, or -1 if the string is 
 *                nul-terminated<footnoteref linkend="nul-unsafe"/>. 
758 759 760
 * @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
761 762 763 764
 *                present in the target encoding. (The string must be
 *                representable in the target encoding). 
                  If %NULL, characters not in the target encoding will 
                  be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
765 766
 * @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
767
 *                Even if the conversion was successful, this may be 
768
 *                less than @len if there were partial characters
769
 *                at the end of the input.
770
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
771
 *                including the terminating nul).
772 773 774
 * @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
775
 * Converts a string from one character set to another, possibly
776 777 778 779
 * 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
780
 * to @to_codeset in their iconv() functions, 
Owen Taylor's avatar
Owen Taylor committed
781
 * in which case GLib will simply return that approximate conversion.
782
 *
783 784 785
 * Note that you should use g_iconv() for streaming 
 * conversions<footnoteref linkend="streaming-state"/>.
 *
786
 * Return value: If the conversion was successful, a newly allocated
787 788
 *               nul-terminated string, which must be freed with
 *               g_free(). Otherwise %NULL and @error will be set.
789 790 791
 **/
gchar*
g_convert_with_fallback (const gchar *str,
792
			 gssize       len,    
793 794 795
			 const gchar *to_codeset,
			 const gchar *from_codeset,
			 gchar       *fallback,
796 797
			 gsize       *bytes_read,
			 gsize       *bytes_written,
798 799 800 801 802 803 804
			 GError     **error)
{
  gchar *utf8;
  gchar *dest;
  gchar *outp;
  const gchar *insert_str = NULL;
  const gchar *p;
805
  gsize inbytes_remaining;   
806
  const gchar *save_p = NULL;
807 808 809
  gsize save_inbytes = 0;
  gsize outbytes_remaining; 
  gsize err;
810
  GIConv cd;
811
  gsize outbuf_size;
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
  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);

840 841
  local_error = NULL;
  
842 843 844 845
  /* 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);
846
  if (cd == (GIConv) -1)
847 848 849 850 851 852 853 854 855 856 857 858 859
    {
      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)
860
    {
861
      close_converter (cd);
862 863 864 865
      if (bytes_written)
        *bytes_written = 0;
      return NULL;
    }
866 867 868 869 870 871 872 873 874 875

  /* 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;
876 877

  outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
878 879 880 881 882
  outbytes_remaining = outbuf_size - 1; /* -1 for nul */
  outp = dest = g_malloc (outbuf_size);

  while (!done && !have_error)
    {
883
      gsize inbytes_tmp = inbytes_remaining;
884
      err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
885
      inbytes_remaining = inbytes_tmp;
886

887
      if (err == (gsize) -1)
888 889 890 891 892 893 894 895
	{
	  switch (errno)
	    {
	    case EINVAL:
	      g_assert_not_reached();
	      break;
	    case E2BIG:
	      {
896
		gsize used = outp - dest;
897

898 899 900 901 902
		outbuf_size *= 2;
		dest = g_realloc (dest, outbuf_size);
		
		outp = dest + used;
		outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
903 904 905 906 907 908 909 910 911
		
		break;
	      }
	    case EILSEQ:
	      if (save_p)
		{
		  /* Error converting fallback string - fatal
		   */
		  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
912
			       _("Cannot convert fallback '%s' to codeset '%s'"),
913 914 915 916
			       insert_str, to_codeset);
		  have_error = TRUE;
		  break;
		}
917
	      else if (p)
918 919 920 921
		{
		  if (!fallback)
		    { 
		      gunichar ch = g_utf8_get_char (p);
922
		      insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
923 924 925 926 927 928 929 930 931
						    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);
932
		  break;
933
		}
934
	      /* fall thru if p is NULL */
935
	    default:
936
	      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
937
			   _("Error during conversion: %s"),
Owen Taylor's avatar
Owen Taylor committed
938
			   g_strerror (errno));
939 940 941 942 943 944 945 946 947 948 949 950 951 952
	      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;
	    }
953 954 955 956 957 958
	  else if (p)
	    {
	      /* call g_iconv with NULL inbuf to cleanup shift state */
	      p = NULL;
	      inbytes_remaining = 0;
	    }
959 960 961 962 963 964 965 966 967
	  else
	    done = TRUE;
	}
    }

  /* Cleanup
   */
  *outp = '\0';
  
968
  close_converter (cd);
969 970

  if (bytes_written)
971
    *bytes_written = outp - dest;	/* Doesn't include '\0' */
972 973 974 975 976 977 978 979 980 981 982 983 984

  g_free (utf8);

  if (have_error)
    {
      if (save_p && !fallback)
	g_free ((gchar *)insert_str);
      g_free (dest);
      return NULL;
    }
  else
    return dest;
}
985 986 987 988

/*
 * g_locale_to_utf8
 *
989 990 991
 * 
 */

992 993 994 995
static gchar *
strdup_len (const gchar *string,
	    gssize       len,
	    gsize       *bytes_written,
996 997
	    gsize       *bytes_read,
	    GError      **error)
998 999 1000 1001
	 
{
  gsize real_len;

1002
  if (!g_utf8_validate (string, len, NULL))
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    {
      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;
    }
  
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  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);
}

1032 1033
/**
 * g_locale_to_utf8:
Tor Lillqvist's avatar
Tor Lillqvist committed
1034 1035
 * @opsysstring:   a string in the encoding of the current locale. On Windows
 *                 this means the system codepage.
1036
 * @len:           the length of the string, or -1 if the string is
1037
 *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1038 1039
 * @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
1040
 *                 Even if the conversion was successful, this may be 
1041
 *                 less than @len if there were partial characters
1042
 *                 at the end of the input. If the error
1043 1044
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1045
 *                 input sequence.
1046
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1047
 *                 including the terminating nul).
1048
 * @error:         location to store the error occuring, or %NULL to ignore
1049 1050
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
1051 1052
 * Converts a string which is in the encoding used for strings by
 * the C runtime (usually the same as that used by the operating
1053 1054
 * system) in the <link linkend="setlocale">current locale</link> into a
 * UTF-8 string.
1055 1056 1057
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1058
gchar *
1059
g_locale_to_utf8 (const gchar  *opsysstring,
1060 1061 1062
		  gssize        len,            
		  gsize        *bytes_read,    
		  gsize        *bytes_written,
1063
		  GError      **error)
1064
{
1065
  const char *charset;
1066 1067

  if (g_get_charset (&charset))
1068
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1069 1070 1071
  else
    return g_convert (opsysstring, len, 
		      "UTF-8", charset, bytes_read, bytes_written, error);
1072 1073
}

1074 1075 1076 1077
/**
 * g_locale_from_utf8:
 * @utf8string:    a UTF-8 encoded string 
 * @len:           the length of the string, or -1 if the string is
1078
 *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1079 1080
 * @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
1081
 *                 Even if the conversion was successful, this may be 
1082
 *                 less than @len if there were partial characters
1083
 *                 at the end of the input. If the error
1084 1085
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1086
 *                 input sequence.
1087
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1088
 *                 including the terminating nul).
1089
 * @error:         location to store the error occuring, or %NULL to ignore
1090 1091 1092 1093
 *                 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
1094
 * system) in the <link linkend="setlocale">current locale</link>.
1095 1096 1097
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1098
gchar *
1099
g_locale_from_utf8 (const gchar *utf8string,
1100 1101 1102
		    gssize       len,            
		    gsize       *bytes_read,    
		    gsize       *bytes_written,
1103
		    GError     **error)
1104
{
1105
  const gchar *charset;
1106 1107

  if (g_get_charset (&charset))
1108
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1109 1110 1111
  else
    return g_convert (utf8string, len,
		      charset, "UTF-8", bytes_read, bytes_written, error);
1112 1113
}

1114
#ifndef G_PLATFORM_WIN32
1115

1116 1117 1118 1119 1120
typedef struct _GFilenameCharsetCache GFilenameCharsetCache;

struct _GFilenameCharsetCache {
  gboolean is_utf8;
  gchar *charset;
1121
  gchar **filename_charsets;
1122 1123 1124 1125 1126 1127 1128
};

static void
filename_charset_cache_free (gpointer data)
{
  GFilenameCharsetCache *cache = data;
  g_free (cache->charset);
1129
  g_strfreev (cache->filename_charsets);
1130 1131 1132
  g_free (cache);
}

1133
/**
1134 1135
 * g_get_filename_charsets:
 * @charsets: return location for the %NULL-terminated list of encoding names
1136
 *
1137 1138 1139
 * 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
1140
 * representation of a filename, see g_filename_display_name().
1141
 *
1142 1143 1144 1145 1146
 * On Unix, the character sets are determined by consulting the
 * environment variables <envar>G_FILENAME_ENCODING</envar> and
 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
 * used in the GLib API is always UTF-8 and said environment variables
 * have no effect.
1147
 *
1148 1149 1150 1151 1152 1153 1154
 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
 * of character set names. The special token "&commat;locale" is taken to 
 * mean the character set for the <link linkend="setlocale">current 
 * locale</link>. 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
1155 1156 1157
 * set of the current locale is also put in the list of encodings.
 *
 * The returned @charsets belong to GLib and must not be freed.
1158 1159
 *
 * Note that on Unix, regardless of the locale character set or
1160 1161
 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present 
 * on a system might be in any random encoding or just gibberish.
1162
 *
1163 1164 1165
 * Return value: %TRUE if the filename encoding is UTF-8.
 * 
 * Since: 2.6
1166
 */
1167 1168
gboolean
g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1169
{
1170 1171 1172
  static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
  GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
  const gchar *charset;
1173

1174
  if (!cache)
1175
    {
1176 1177 1178 1179 1180 1181 1182 1183 1184
      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;
1185 1186
      gchar *p;
      gint i;
1187

1188
      g_free (cache->charset);
1189
      g_strfreev (cache->filename_charsets);
1190
      cache->charset = g_strdup (charset);
1191 1192
      
      p = getenv ("G_FILENAME_ENCODING");
1193
      if (p != NULL && p[0] != '\0') 
1194
	{
1195 1196
	  cache->filename_charsets = g_strsplit (p, ",", 0);
	  cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1197

1198
	  for (i = 0; cache->filename_charsets[i]; i++)
1199
	    {
1200 1201 1202 1203 1204 1205
	      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);
		}
1206 1207 1208
	    }
	}
      else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1209
	{
1210
	  cache->filename_charsets = g_new0 (gchar *, 2);
1211
	  cache->is_utf8 = g_get_charset (&new_charset);
1212
	  cache->filename_charsets[0] = g_strdup (new_charset);
1213
	}
1214 1215
      else 
	{
1216
	  cache->filename_charsets = g_new0 (gchar *, 3);
1217
	  cache->is_utf8 = TRUE;
1218 1219 1220
	  cache->filename_charsets[0] = g_strdup ("UTF-8");
	  if (!g_get_charset (&new_charset))
	    cache->filename_charsets[1] = g_strdup (new_charset);
1221 1222
	}
    }
1223

1224 1225
  if (filename_charsets)
    *filename_charsets = (const gchar **)cache->filename_charsets;
1226

1227
  return cache->is_utf8;
1228
}
1229

1230
#else /* G_PLATFORM_WIN32 */
1231

1232 1233
gboolean
g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets) 
1234
{
1235
  static const gchar *charsets[] = {
1236 1237 1238 1239
    "UTF-8",
    NULL
  };

1240 1241
#ifdef G_OS_WIN32
  /* On Windows GLib pretends that the filename charset is UTF-8 */
1242 1243 1244
  if (filename_charsets)
    *filename_charsets = charsets;

1245 1246
  return TRUE;
#else
1247 1248
  gboolean result;

1249
  /* Cygwin works like before */
1250 1251 1252 1253 1254 1255
  result = g_get_charset (&(charsets[0]));

  if (filename_charsets)
    *filename_charsets = charsets;

  return result;
1256 1257 1258
#endif
}

1259
#endif /* G_PLATFORM_WIN32 */
1260 1261

static gboolean
1262
get_filename_charset (const gchar **filename_charset)
1263
{
1264 1265 1266 1267
  const gchar **charsets;
  gboolean is_utf8;
  
  is_utf8 = g_get_filename_charsets (&charsets);
1268

1269 1270 1271 1272 1273
  if (filename_charset)
    *filename_charset = charsets[0];
  
  return is_utf8;
}
1274 1275 1276 1277 1278

/* This is called from g_thread_init(). It's used to
 * initialize some static data in a threadsafe way.
 */
void 
1279
_g_convert_thread_init (void)
1280
{
1281
  const gchar **dummy;
1282
  (void) g_get_filename_charsets (&dummy);
1283 1284
}

1285 1286 1287 1288
/**
 * g_filename_to_utf8:
 * @opsysstring:   a string in the encoding for filenames
 * @len:           the length of the string, or -1 if the string is
1289
 *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1290 1291
 * @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
1292
 *                 Even if the conversion was successful, this may be 
1293
 *                 less than @len if there were partial characters
1294
 *                 at the end of the input. If the error
1295 1296
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1297
 *                 input sequence.
1298
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1299
 *                 including the terminating nul).
1300
 * @error:         location to store the error occuring, or %NULL to ignore
1301 1302
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
1303 1304
 * Converts a string which is in the encoding used by GLib for
 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1305 1306
 * for filenames; on other platforms, this function indirectly depends on 
 * the <link linkend="setlocale">current locale</link>.
1307 1308 1309
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1310
gchar*
1311
g_filename_to_utf8 (const gchar *opsysstring, 
1312 1313 1314
		    gssize       len,           
		    gsize       *bytes_read,   
		    gsize       *bytes_written,
1315
		    GError     **error)
1316
{
1317 1318 1319
  const gchar *charset;

  if (get_filename_charset (&charset))
1320
    return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1321 1322 1323
  else
    return g_convert (opsysstring, len, 
		      "UTF-8", charset, bytes_read, bytes_written, error);
1324 1325
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
#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;

1341
  if (g_get_charset (&charset))
1342 1343 1344 1345 1346 1347 1348 1349
    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

1350 1351
/**
 * g_filename_from_utf8:
1352
 * @utf8string:    a UTF-8 encoded string.
1353
 * @len:           the length of the string, or -1 if the string is
1354
 *                 nul-terminated.
1355 1356
 * @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
1357
 *                 Even if the conversion was successful, this may be 
1358
 *                 less than @len if there were partial characters
1359
 *                 at the end of the input. If the error
1360 1361
 *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
 *                 stored will the byte offset after the last valid
1362
 *                 input sequence.
1363
 * @bytes_written: the number of bytes stored in the output buffer (not 
Matthias Clasen's avatar
Matthias Clasen committed
1364
 *                 including the terminating nul).
1365
 * @error:         location to store the error occuring, or %NULL to ignore
1366 1367
 *                 errors. Any of the errors in #GConvertError may occur.
 * 
1368
 * Converts a string from UTF-8 to the encoding GLib uses for
1369 1370 1371
 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
 * on other platforms, this function indirectly depends on the 
 * <link linkend="setlocale">current locale</link>.
1372 1373 1374
 * 
 * Return value: The converted string, or %NULL on an error.
 **/
1375
gchar*
1376
g_filename_from_utf8 (const gchar *utf8string,
1377 1378 1379
		      gssize       len,            
		      gsize       *bytes_read,    
		      gsize       *bytes_written,
1380
		      GError     **error)
1381
{
1382 1383 1384
  const gchar *charset;

  if (get_filename_charset (&charset))
1385
    return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1386 1387 1388
  else
    return g_convert (utf8string, len,
		      charset, "UTF-8", bytes_read, bytes_written, error);
1389
}
1390

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
#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;

1406
  if (g_get_charset (&charset))
1407 1408 1409 1410 1411 1412 1413 1414
    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

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
/* 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 '+'  */
1440
  UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1441 1442 1443 1444 1445
  UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
  UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
} UnsafeCharacterSet;

static const guchar acceptable[96] = {
1446 1447
  /* A table of the ASCII chars from space (32) to DEL (127) */
  /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1448
  0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1449
  /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1450
  0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1451
  /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1452
  0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1453 1454 1455 1456 1457 1458
  /* 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
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
};

static const gchar hex[16] = "0123456789ABCDEF";

/* Note: This escape function works on file: URIs, but if you want to
 * escape something else, please read RFC-2396 */
static gchar *
g_escape_uri_string (const gchar *string, 
		     UnsafeCharacterSet mask)
{
#define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))

  const gchar *p;
  gchar *q;
  gchar *result;
  int c;
  gint unacceptable;
  UnsafeCharacterSet use_mask;
  
  g_return_val_if_fail (mask == UNSAFE_ALL
			|| mask == UNSAFE_ALLOW_PLUS
			|| mask == UNSAFE_PATH
			|| mask == UNSAFE_HOST
			|| mask == UNSAFE_SLASHES, NULL);
  
  unacceptable = 0;
  use_mask = mask;
  for (p = string; *p != '\0'; p++)
    {
1488
      c = (guchar) *p;
1489 1490 1491 1492 1493 1494 1495 1496 1497
      if (!ACCEPTABLE (c)) 
	unacceptable++;
    }
  
  result = g_malloc (p - string + unacceptable * 2 + 1);
  
  use_mask = mask;
  for (q = result, p = string; *p != '\0'; p++)
    {
1498
      c = (guchar) *p;
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
      
      if (!ACCEPTABLE (c))
	{
	  *q++ = '%'; /* means hex coming */
	  *q++ = hex[c >> 4];
	  *q++ = hex[c & 15];
	}
      else
	*q++ = *p;
    }
  
  *q = '\0';
  
  return result;
}


static gchar *
g_escape_file_uri (const gchar *hostname,
		   const gchar *pathname)
{
  char *escaped_hostname = NULL;
  char *escaped_path;
  char *res;

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
#ifdef G_OS_WIN32
  char *p, *backslash;

  /* Turn backslashes into forward slashes. That's what Netscape
   * does, and they are actually more or less equivalent in Windows.
   */
  
  pathname = g_strdup (pathname);
  p = (char *) pathname;
  
  while ((backslash = strchr (p, '\\')) != NULL)
    {
      *backslash = '/';
      p = backslash + 1;
    }
#endif

1541 1542 1543 1544 1545
  if (hostname && *hostname != '\0')
    {
      escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
    }

1546
  escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1547 1548 1549 1550 1551 1552 1553

  res = g_strconcat ("file://",
		     (escaped_hostname) ? escaped_hostname : "",
		     (*escaped_path != '/') ? "/" : "",
		     escaped_path,
		     NULL);

1554 1555 1556 1557
#ifdef G_OS_WIN32
  g_free ((char *) pathname);
#endif

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
  g_free (escaped_hostname);
  g_free (escaped_path);
  
  return res;
}

static int
unescape_character (const char *scanner)
{
  int first_digit;
  int second_digit;

1570
  first_digit = g_ascii_xdigit_value (scanner[0]);
1571 1572 1573
  if (first_digit < 0) 
    return -1;
  
1574
  second_digit = g_ascii_xdigit_value (scanner[1]);
1575 1576 1577 1578 1579 1580