1 /* GLIB - Library of useful routines for C programming
3 * gconvert.c: Convert between character sets using iconv
4 * Copyright Red Hat Inc., 2000
5 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
33 #include "gprintfint.h"
34 #include "gthreadinit.h"
36 #ifdef G_PLATFORM_WIN32
44 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
45 #error GNU libiconv in use but included iconv.h not from libiconv
47 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
48 #error GNU libiconv not in use but included iconv.h is from libiconv
52 g_convert_error_quark (void)
56 quark = g_quark_from_static_string ("g_convert_error");
62 try_conversion (const char *to_codeset,
63 const char *from_codeset,
66 *cd = iconv_open (to_codeset, from_codeset);
68 if (*cd == (iconv_t)-1 && errno == EINVAL)
75 try_to_aliases (const char **to_aliases,
76 const char *from_codeset,
81 const char **p = to_aliases;
84 if (try_conversion (*p, from_codeset, cd))
94 extern const char **_g_charset_get_aliases (const char *canonical_name) G_GNUC_INTERNAL;
98 * @to_codeset: destination codeset
99 * @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
103 * a native implementation.
105 * GLib provides g_convert() and g_locale_to_utf8() which are likely
106 * more convenient than the raw iconv wrappers.
108 * Return value: a "conversion descriptor", or (GIConv)-1 if
109 * opening the converter failed.
112 g_iconv_open (const gchar *to_codeset,
113 const gchar *from_codeset)
117 if (!try_conversion (to_codeset, from_codeset, &cd))
119 const char **to_aliases = _g_charset_get_aliases (to_codeset);
120 const char **from_aliases = _g_charset_get_aliases (from_codeset);
124 const char **p = from_aliases;
127 if (try_conversion (to_codeset, *p, &cd))
130 if (try_to_aliases (to_aliases, *p, &cd))
137 if (try_to_aliases (to_aliases, from_codeset, &cd))
142 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
147 * @converter: conversion descriptor from g_iconv_open()
148 * @inbuf: bytes to convert
149 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
150 * @outbuf: converted output bytes
151 * @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
155 * a native implementation.
157 * GLib provides g_convert() and g_locale_to_utf8() which are likely
158 * more convenient than the raw iconv wrappers.
160 * Return value: count of non-reversible conversions, or -1 on error
163 g_iconv (GIConv converter,
167 gsize *outbytes_left)
169 iconv_t cd = (iconv_t)converter;
171 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
176 * @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
180 * a native implementation. Should be called to clean up
181 * the conversion descriptor from g_iconv_open() when
182 * you are done converting things.
184 * GLib provides g_convert() and g_locale_to_utf8() which are likely
185 * more convenient than the raw iconv wrappers.
187 * Return value: -1 on error, 0 on success
190 g_iconv_close (GIConv converter)
192 iconv_t cd = (iconv_t)converter;
194 return iconv_close (cd);
198 #define ICONV_CACHE_SIZE (16)
200 struct _iconv_cache_bucket {
207 static GList *iconv_cache_list;
208 static GHashTable *iconv_cache;
209 static GHashTable *iconv_open_hash;
210 static guint iconv_cache_size = 0;
211 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
213 /* caller *must* hold the iconv_cache_lock */
215 iconv_cache_init (void)
217 static gboolean initialized = FALSE;
222 iconv_cache_list = NULL;
223 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
224 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
231 * iconv_cache_bucket_new:
233 * @cd: iconv descriptor
235 * Creates a new cache bucket, inserts it into the cache and
236 * increments the cache size.
238 * 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)
243 struct _iconv_cache_bucket *bucket;
245 bucket = g_new (struct _iconv_cache_bucket, 1);
246 bucket->key = g_strdup (key);
247 bucket->refcount = 1;
251 g_hash_table_insert (iconv_cache, bucket->key, bucket);
253 /* FIXME: if we sorted the list so items with few refcounts were
254 first, then we could expire them faster in iconv_cache_expire_unused () */
255 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
264 * iconv_cache_bucket_expire:
265 * @node: cache bucket's node
266 * @bucket: cache bucket
268 * Expires a single cache bucket @bucket. This should only ever be
269 * called on a bucket that currently has no used iconv descriptors
272 * @node is not a required argument. If @node is not supplied, we
273 * search for it ourselves.
276 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
278 g_hash_table_remove (iconv_cache, bucket->key);
281 node = g_list_find (iconv_cache_list, bucket);
283 g_assert (node != NULL);
287 node->prev->next = node->next;
289 node->next->prev = node->prev;
293 iconv_cache_list = node->next;
295 node->next->prev = NULL;
298 g_list_free_1 (node);
300 g_free (bucket->key);
301 g_iconv_close (bucket->cd);
309 * iconv_cache_expire_unused:
311 * Expires as many unused cache buckets as it needs to in order to get
312 * the total number of buckets < ICONV_CACHE_SIZE.
315 iconv_cache_expire_unused (void)
317 struct _iconv_cache_bucket *bucket;
320 node = iconv_cache_list;
321 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
326 if (bucket->refcount == 0)
327 iconv_cache_bucket_expire (node, bucket);
334 open_converter (const gchar *to_codeset,
335 const gchar *from_codeset,
338 struct _iconv_cache_bucket *bucket;
343 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
344 _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
346 G_LOCK (iconv_cache_lock);
348 /* make sure the cache has been initialized */
351 bucket = g_hash_table_lookup (iconv_cache, key);
356 cd = g_iconv_open (to_codeset, from_codeset);
357 if (cd == (GIConv) -1)
362 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
363 * NULL for anything but inbuf; work around that. (NULL outbuf
364 * or NULL *outbuf is allowed by Unix98.)
366 gsize inbytes_left = 0;
367 gchar *outbuf = NULL;
368 gsize outbytes_left = 0;
373 /* reset the descriptor */
374 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
381 cd = g_iconv_open (to_codeset, from_codeset);
382 if (cd == (GIConv) -1)
385 iconv_cache_expire_unused ();
387 bucket = iconv_cache_bucket_new (key, cd);
390 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
392 G_UNLOCK (iconv_cache_lock);
398 G_UNLOCK (iconv_cache_lock);
400 /* Something went wrong. */
402 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
403 _("Conversion from character set '%s' to '%s' is not supported"),
404 from_codeset, to_codeset);
406 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
407 _("Could not open converter from '%s' to '%s'"),
408 from_codeset, to_codeset);
414 close_converter (GIConv converter)
416 struct _iconv_cache_bucket *bucket;
422 if (cd == (GIConv) -1)
425 G_LOCK (iconv_cache_lock);
427 key = g_hash_table_lookup (iconv_open_hash, cd);
430 g_hash_table_remove (iconv_open_hash, cd);
432 bucket = g_hash_table_lookup (iconv_cache, key);
437 if (cd == bucket->cd)
438 bucket->used = FALSE;
442 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
444 /* expire this cache bucket */
445 iconv_cache_bucket_expire (NULL, bucket);
450 G_UNLOCK (iconv_cache_lock);
452 g_warning ("This iconv context wasn't opened using open_converter");
454 return g_iconv_close (converter);
457 G_UNLOCK (iconv_cache_lock);
465 * @str: the string to convert
466 * @len: the length of the string
467 * @to_codeset: name of character set into which to convert @str
468 * @from_codeset: character set of @str.
469 * @bytes_read: location to store the number of bytes in the
470 * input string that were successfully converted, or %NULL.
471 * Even if the conversion was successful, this may be
472 * less than @len if there were partial characters
473 * at the end of the input. If the error
474 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
475 * stored will the byte offset after the last valid
477 * @bytes_written: the number of bytes stored in the output buffer (not
478 * including the terminating nul).
479 * @error: location to store the error occuring, or %NULL to ignore
480 * errors. Any of the errors in #GConvertError may occur.
482 * Converts a string from one character set to another.
484 * Return value: If the conversion was successful, a newly allocated
485 * nul-terminated string, which must be freed with
486 * g_free(). Otherwise %NULL and @error will be set.
489 g_convert (const gchar *str,
491 const gchar *to_codeset,
492 const gchar *from_codeset,
494 gsize *bytes_written,
500 g_return_val_if_fail (str != NULL, NULL);
501 g_return_val_if_fail (to_codeset != NULL, NULL);
502 g_return_val_if_fail (from_codeset != NULL, NULL);
504 cd = open_converter (to_codeset, from_codeset, error);
506 if (cd == (GIConv) -1)
517 res = g_convert_with_iconv (str, len, cd,
518 bytes_read, bytes_written,
521 close_converter (cd);
527 * g_convert_with_iconv:
528 * @str: the string to convert
529 * @len: the length of the string
530 * @converter: conversion descriptor from g_iconv_open()
531 * @bytes_read: location to store the number of bytes in the
532 * input string that were successfully converted, or %NULL.
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 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
537 * stored will the byte offset after the last valid
539 * @bytes_written: the number of bytes stored in the output buffer (not
540 * including the terminating nul).
541 * @error: location to store the error occuring, or %NULL to ignore
542 * errors. Any of the errors in #GConvertError may occur.
544 * Converts a string from one character set to another.
546 * Return value: If the conversion was successful, a newly allocated
547 * nul-terminated string, which must be freed with
548 * g_free(). Otherwise %NULL and @error will be set.
551 g_convert_with_iconv (const gchar *str,
555 gsize *bytes_written,
561 gsize inbytes_remaining;
562 gsize outbytes_remaining;
565 gboolean have_error = FALSE;
567 g_return_val_if_fail (str != NULL, NULL);
568 g_return_val_if_fail (converter != (GIConv) -1, NULL);
574 inbytes_remaining = len;
575 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
577 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
578 outp = dest = g_malloc (outbuf_size);
582 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
584 if (err == (size_t) -1)
589 /* Incomplete text, do not report an error */
593 size_t used = outp - dest;
596 dest = g_realloc (dest, outbuf_size);
599 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
604 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
605 _("Invalid byte sequence in conversion input"));
609 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
610 _("Error during conversion: %s"),
620 *bytes_read = p - str;
623 if ((p - str) != len)
627 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
628 _("Partial character sequence at end of input"));
635 *bytes_written = outp - dest; /* Doesn't include '\0' */
647 * g_convert_with_fallback:
648 * @str: the string to convert
649 * @len: the length of the string
650 * @to_codeset: name of character set into which to convert @str
651 * @from_codeset: character set of @str.
652 * @fallback: UTF-8 string to use in place of character not
653 * present in the target encoding. (This must be
654 * in the target encoding), if %NULL, characters
655 * not in the target encoding will be represented
656 * as Unicode escapes \uxxxx or \Uxxxxyyyy.
657 * @bytes_read: location to store the number of bytes in the
658 * input string that were successfully converted, or %NULL.
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
663 * including the terminating nul).
664 * @error: location to store the error occuring, or %NULL to ignore
665 * errors. Any of the errors in #GConvertError may occur.
667 * Converts a string from one character set to another, possibly
668 * including fallback sequences for characters not representable
669 * in the output. Note that it is not guaranteed that the specification
670 * for the fallback sequences in @fallback will be honored. Some
671 * systems may do a approximate conversion from @from_codeset
672 * to @to_codeset in their iconv() functions,
673 * in which case GLib will simply return that approximate conversion.
675 * Return value: If the conversion was successful, a newly allocated
676 * nul-terminated string, which must be freed with
677 * g_free(). Otherwise %NULL and @error will be set.
680 g_convert_with_fallback (const gchar *str,
682 const gchar *to_codeset,
683 const gchar *from_codeset,
686 gsize *bytes_written,
692 const gchar *insert_str = NULL;
694 gsize inbytes_remaining;
695 const gchar *save_p = NULL;
696 gsize save_inbytes = 0;
697 gsize outbytes_remaining;
701 gboolean have_error = FALSE;
702 gboolean done = FALSE;
704 GError *local_error = NULL;
706 g_return_val_if_fail (str != NULL, NULL);
707 g_return_val_if_fail (to_codeset != NULL, NULL);
708 g_return_val_if_fail (from_codeset != NULL, NULL);
713 /* Try an exact conversion; we only proceed if this fails
714 * due to an illegal sequence in the input string.
716 dest = g_convert (str, len, to_codeset, from_codeset,
717 bytes_read, bytes_written, &local_error);
721 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
723 g_propagate_error (error, local_error);
727 g_error_free (local_error);
731 /* No go; to proceed, we need a converter from "UTF-8" to
732 * to_codeset, and the string as UTF-8.
734 cd = open_converter (to_codeset, "UTF-8", error);
735 if (cd == (GIConv) -1)
746 utf8 = g_convert (str, len, "UTF-8", from_codeset,
747 bytes_read, &inbytes_remaining, error);
750 close_converter (cd);
756 /* Now the heart of the code. We loop through the UTF-8 string, and
757 * whenever we hit an offending character, we form fallback, convert
758 * the fallback to the target codeset, and then go back to
759 * converting the original string after finishing with the fallback.
761 * The variables save_p and save_inbytes store the input state
762 * for the original string while we are converting the fallback
766 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
767 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
768 outp = dest = g_malloc (outbuf_size);
770 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;
776 if (err == (size_t) -1)
781 g_assert_not_reached();
785 size_t used = outp - dest;
788 dest = g_realloc (dest, outbuf_size);
791 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
798 /* Error converting fallback string - fatal
800 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
801 _("Cannot convert fallback '%s' to codeset '%s'"),
802 insert_str, to_codeset);
810 gunichar ch = g_utf8_get_char (p);
811 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
815 insert_str = fallback;
817 save_p = g_utf8_next_char (p);
818 save_inbytes = inbytes_remaining - (save_p - p);
820 inbytes_remaining = strlen (p);
824 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
825 _("Error during conversion: %s"),
836 g_free ((gchar *)insert_str);
838 inbytes_remaining = save_inbytes;
850 close_converter (cd);
853 *bytes_written = outp - dest; /* Doesn't include '\0' */
859 if (save_p && !fallback)
860 g_free ((gchar *)insert_str);
875 strdup_len (const gchar *string,
877 gsize *bytes_written,
884 if (!g_utf8_validate (string, len, NULL))
891 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
892 _("Invalid byte sequence in conversion input"));
897 real_len = strlen (string);
902 while (real_len < len && string[real_len])
907 *bytes_read = real_len;
909 *bytes_written = real_len;
911 return g_strndup (string, real_len);
916 * @opsysstring: a string in the encoding of the current locale
917 * @len: the length of the string, or -1 if the string is
919 * @bytes_read: location to store the number of bytes in the
920 * input string that were successfully converted, or %NULL.
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 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
925 * stored will the byte offset after the last valid
927 * @bytes_written: the number of bytes stored in the output buffer (not
928 * including the terminating nul).
929 * @error: location to store the error occuring, or %NULL to ignore
930 * errors. Any of the errors in #GConvertError may occur.
932 * Converts a string which is in the encoding used for strings by
933 * the C runtime (usually the same as that used by the operating
934 * system) in the current locale into a UTF-8 string.
936 * Return value: The converted string, or %NULL on an error.
939 g_locale_to_utf8 (const gchar *opsysstring,
942 gsize *bytes_written,
947 if (g_get_charset (&charset))
948 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
950 return g_convert (opsysstring, len,
951 "UTF-8", charset, bytes_read, bytes_written, error);
955 * g_locale_from_utf8:
956 * @utf8string: a UTF-8 encoded string
957 * @len: the length of the string, or -1 if the string is
959 * @bytes_read: location to store the number of bytes in the
960 * input string that were successfully converted, or %NULL.
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 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
965 * stored will the byte offset after the last valid
967 * @bytes_written: the number of bytes stored in the output buffer (not
968 * including the terminating nul).
969 * @error: location to store the error occuring, or %NULL to ignore
970 * errors. Any of the errors in #GConvertError may occur.
972 * Converts a string from UTF-8 to the encoding used for strings by
973 * the C runtime (usually the same as that used by the operating
974 * system) in the current locale.
976 * Return value: The converted string, or %NULL on an error.
979 g_locale_from_utf8 (const gchar *utf8string,
982 gsize *bytes_written,
985 const gchar *charset;
987 if (g_get_charset (&charset))
988 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
990 return g_convert (utf8string, len,
991 charset, "UTF-8", bytes_read, bytes_written, error);
994 #ifndef G_PLATFORM_WIN32
996 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
998 struct _GFilenameCharsetCache {
1001 gchar *filename_charset;
1005 filename_charset_cache_free (gpointer data)
1007 GFilenameCharsetCache *cache = data;
1008 g_free (cache->charset);
1009 g_free (cache->filename_charset);
1014 * get_filename_charset:
1015 * @charset: return location for the name of the filename encoding
1017 * Determines the preferred character set used for filenames by
1018 * consulting the environment variables G_FILENAME_ENCODING and
1019 * G_BROKEN_FILENAMES.
1021 * G_FILENAME_ENCODING may be set to a comma-separated list of character
1022 * set names. The special token "@locale" is taken to mean the character set
1023 * for the current locale. The first character set from the list is taken
1024 * as the filename encoding.
1025 * If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the
1026 * character set of the current locale is taken as the filename encoding.
1028 * The returned @charset belongs to GLib and must not be freed.
1030 * Note that on Unix, regardless of the locale character set or
1031 * G_FILENAME_ENCODING value, the actual file names present on a
1032 * system might be in any random encoding or just gibberish.
1034 * Return value: %TRUE
1035 * if the charset used for filename is UTF-8.
1038 get_filename_charset (const gchar **filename_charset)
1040 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1041 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1042 const gchar *charset;
1046 cache = g_new0 (GFilenameCharsetCache, 1);
1047 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1050 g_get_charset (&charset);
1052 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1054 const gchar *new_charset;
1057 g_free (cache->charset);
1058 g_free (cache->filename_charset);
1059 cache->charset = g_strdup (charset);
1061 p = getenv ("G_FILENAME_ENCODING");
1064 q = strchr (p, ',');
1068 if (strncmp ("@locale", p, q - p) == 0)
1070 cache->is_utf8 = g_get_charset (&new_charset);
1071 cache->filename_charset = g_strdup (new_charset);
1075 cache->filename_charset = g_strndup (p, q - p);
1076 cache->is_utf8 = (strcmp (cache->filename_charset, "UTF-8") == 0);
1079 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1081 cache->is_utf8 = g_get_charset (&new_charset);
1082 cache->filename_charset = g_strdup (new_charset);
1086 cache->filename_charset = g_strdup ("UTF-8");
1087 cache->is_utf8 = TRUE;
1091 if (filename_charset)
1092 *filename_charset = cache->filename_charset;
1094 return cache->is_utf8;
1097 #else /* G_PLATFORM_WIN32 */
1100 get_filename_charset (const gchar **filename_charset)
1103 /* On Windows GLib pretends that the filename charset is UTF-8 */
1104 if (filename_charset)
1105 *filename_charset = "UTF-8";
1108 /* Cygwin works like before */
1109 g_get_charset (filename_charset);
1117 old_get_filename_charset (const gchar **filename_charset)
1119 g_get_charset (filename_charset);
1125 #endif /* G_PLATFORM_WIN32 */
1127 /* This is called from g_thread_init(). It's used to
1128 * initialize some static data in a threadsafe way.
1131 _g_convert_thread_init (void)
1134 (void) get_filename_charset (&dummy);
1138 * g_filename_to_utf8:
1139 * @opsysstring: a string in the encoding for filenames
1140 * @len: the length of the string, or -1 if the string is
1142 * @bytes_read: location to store the number of bytes in the
1143 * input string that were successfully converted, or %NULL.
1144 * Even if the conversion was successful, this may be
1145 * less than @len if there were partial characters
1146 * at the end of the input. If the error
1147 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1148 * stored will the byte offset after the last valid
1150 * @bytes_written: the number of bytes stored in the output buffer (not
1151 * including the terminating nul).
1152 * @error: location to store the error occuring, or %NULL to ignore
1153 * errors. Any of the errors in #GConvertError may occur.
1155 * Converts a string which is in the encoding used for filenames
1156 * into a UTF-8 string.
1158 * Return value: The converted string, or %NULL on an error.
1161 g_filename_to_utf8 (const gchar *opsysstring,
1164 gsize *bytes_written,
1167 const gchar *charset;
1169 if (get_filename_charset (&charset))
1170 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1172 return g_convert (opsysstring, len,
1173 "UTF-8", charset, bytes_read, bytes_written, error);
1178 #undef g_filename_to_utf8
1180 /* Binary compatibility version. Not for newly compiled code. */
1183 g_filename_to_utf8 (const gchar *opsysstring,
1186 gsize *bytes_written,
1189 const gchar *charset;
1191 if (old_get_filename_charset (&charset))
1192 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1194 return g_convert (opsysstring, len,
1195 "UTF-8", charset, bytes_read, bytes_written, error);
1201 * g_filename_from_utf8:
1202 * @utf8string: a UTF-8 encoded string.
1203 * @len: the length of the string, or -1 if the string is
1205 * @bytes_read: location to store the number of bytes in the
1206 * input string that were successfully converted, or %NULL.
1207 * Even if the conversion was successful, this may be
1208 * less than @len if there were partial characters
1209 * at the end of the input. If the error
1210 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1211 * stored will the byte offset after the last valid
1213 * @bytes_written: the number of bytes stored in the output buffer (not
1214 * including the terminating nul).
1215 * @error: location to store the error occuring, or %NULL to ignore
1216 * errors. Any of the errors in #GConvertError may occur.
1218 * Converts a string from UTF-8 to the encoding used for filenames.
1220 * Return value: The converted string, or %NULL on an error.
1223 g_filename_from_utf8 (const gchar *utf8string,
1226 gsize *bytes_written,
1229 const gchar *charset;
1231 if (get_filename_charset (&charset))
1232 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1234 return g_convert (utf8string, len,
1235 charset, "UTF-8", bytes_read, bytes_written, error);
1240 #undef g_filename_from_utf8
1242 /* Binary compatibility version. Not for newly compiled code. */
1245 g_filename_from_utf8 (const gchar *utf8string,
1248 gsize *bytes_written,
1251 const gchar *charset;
1253 if (old_get_filename_charset (&charset))
1254 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1256 return g_convert (utf8string, len,
1257 charset, "UTF-8", bytes_read, bytes_written, error);
1262 /* Test of haystack has the needle prefix, comparing case
1263 * insensitive. haystack may be UTF-8, but needle must
1264 * contain only ascii. */
1266 has_case_prefix (const gchar *haystack, const gchar *needle)
1270 /* Eat one character at a time. */
1275 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1285 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1286 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1287 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1288 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1289 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1290 } UnsafeCharacterSet;
1292 static const guchar acceptable[96] = {
1293 /* A table of the ASCII chars from space (32) to DEL (127) */
1294 /* ! " # $ % & ' ( ) * + , - . / */
1295 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1296 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1297 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1298 /* @ A B C D E F G H I J K L M N O */
1299 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1300 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1301 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1302 /* ` a b c d e f g h i j k l m n o */
1303 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1304 /* p q r s t u v w x y z { | } ~ DEL */
1305 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1308 static const gchar hex[16] = "0123456789ABCDEF";
1310 /* Note: This escape function works on file: URIs, but if you want to
1311 * escape something else, please read RFC-2396 */
1313 g_escape_uri_string (const gchar *string,
1314 UnsafeCharacterSet mask)
1316 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1323 UnsafeCharacterSet use_mask;
1325 g_return_val_if_fail (mask == UNSAFE_ALL
1326 || mask == UNSAFE_ALLOW_PLUS
1327 || mask == UNSAFE_PATH
1328 || mask == UNSAFE_HOST
1329 || mask == UNSAFE_SLASHES, NULL);
1333 for (p = string; *p != '\0'; p++)
1336 if (!ACCEPTABLE (c))
1340 result = g_malloc (p - string + unacceptable * 2 + 1);
1343 for (q = result, p = string; *p != '\0'; p++)
1347 if (!ACCEPTABLE (c))
1349 *q++ = '%'; /* means hex coming */
1364 g_escape_file_uri (const gchar *hostname,
1365 const gchar *pathname)
1367 char *escaped_hostname = NULL;
1372 char *p, *backslash;
1374 /* Turn backslashes into forward slashes. That's what Netscape
1375 * does, and they are actually more or less equivalent in Windows.
1378 pathname = g_strdup (pathname);
1379 p = (char *) pathname;
1381 while ((backslash = strchr (p, '\\')) != NULL)
1388 if (hostname && *hostname != '\0')
1390 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1393 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1395 res = g_strconcat ("file://",
1396 (escaped_hostname) ? escaped_hostname : "",
1397 (*escaped_path != '/') ? "/" : "",
1402 g_free ((char *) pathname);
1405 g_free (escaped_hostname);
1406 g_free (escaped_path);
1412 unescape_character (const char *scanner)
1417 first_digit = g_ascii_xdigit_value (scanner[0]);
1418 if (first_digit < 0)
1421 second_digit = g_ascii_xdigit_value (scanner[1]);
1422 if (second_digit < 0)
1425 return (first_digit << 4) | second_digit;
1429 g_unescape_uri_string (const char *escaped,
1431 const char *illegal_escaped_characters,
1432 gboolean ascii_must_not_be_escaped)
1434 const gchar *in, *in_end;
1435 gchar *out, *result;
1438 if (escaped == NULL)
1442 len = strlen (escaped);
1444 result = g_malloc (len + 1);
1447 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1453 /* catch partial escape sequences past the end of the substring */
1454 if (in + 3 > in_end)
1457 c = unescape_character (in + 1);
1459 /* catch bad escape sequences and NUL characters */
1463 /* catch escaped ASCII */
1464 if (ascii_must_not_be_escaped && c <= 0x7F)
1467 /* catch other illegal escaped characters */
1468 if (strchr (illegal_escaped_characters, c) != NULL)
1477 g_assert (out - result <= len);
1490 is_asciialphanum (gunichar c)
1492 return c <= 0x7F && g_ascii_isalnum (c);
1496 is_asciialpha (gunichar c)
1498 return c <= 0x7F && g_ascii_isalpha (c);
1501 /* allows an empty string */
1503 hostname_validate (const char *hostname)
1506 gunichar c, first_char, last_char;
1513 /* read in a label */
1514 c = g_utf8_get_char (p);
1515 p = g_utf8_next_char (p);
1516 if (!is_asciialphanum (c))
1522 c = g_utf8_get_char (p);
1523 p = g_utf8_next_char (p);
1525 while (is_asciialphanum (c) || c == '-');
1526 if (last_char == '-')
1529 /* if that was the last label, check that it was a toplabel */
1530 if (c == '\0' || (c == '.' && *p == '\0'))
1531 return is_asciialpha (first_char);
1538 * g_filename_from_uri:
1539 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1540 * @hostname: Location to store hostname for the URI, or %NULL.
1541 * If there is no hostname in the URI, %NULL will be
1542 * stored in this location.
1543 * @error: location to store the error occuring, or %NULL to ignore
1544 * errors. Any of the errors in #GConvertError may occur.
1546 * Converts an escaped ASCII-encoded URI to a local filename in the
1547 * encoding used for filenames.
1549 * Return value: a newly-allocated string holding the resulting
1550 * filename, or %NULL on an error.
1553 g_filename_from_uri (const gchar *uri,
1557 const char *path_part;
1558 const char *host_part;
1559 char *unescaped_hostname;
1570 if (!has_case_prefix (uri, "file:/"))
1572 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1573 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1578 path_part = uri + strlen ("file:");
1580 if (strchr (path_part, '#') != NULL)
1582 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1583 _("The local file URI '%s' may not include a '#'"),
1588 if (has_case_prefix (path_part, "///"))
1590 else if (has_case_prefix (path_part, "//"))
1593 host_part = path_part;
1595 path_part = strchr (path_part, '/');
1597 if (path_part == NULL)
1599 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1600 _("The URI '%s' is invalid"),
1605 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1607 if (unescaped_hostname == NULL ||
1608 !hostname_validate (unescaped_hostname))
1610 g_free (unescaped_hostname);
1611 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1612 _("The hostname of the URI '%s' is invalid"),
1618 *hostname = unescaped_hostname;
1620 g_free (unescaped_hostname);
1623 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1625 if (filename == NULL)
1627 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1628 _("The URI '%s' contains invalidly escaped characters"),
1635 /* Drop localhost */
1636 if (hostname && *hostname != NULL &&
1637 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1643 /* Turn slashes into backslashes, because that's the canonical spelling */
1645 while ((slash = strchr (p, '/')) != NULL)
1651 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1652 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1653 * the filename from the drive letter.
1655 if (g_ascii_isalpha (filename[1]))
1657 if (filename[2] == ':')
1659 else if (filename[2] == '|')
1667 result = g_strdup (filename + offs);
1674 * g_filename_to_uri:
1675 * @filename: an absolute filename specified in the encoding
1676 * used for filenames by the operating system.
1677 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1678 * @error: location to store the error occuring, or %NULL to ignore
1679 * errors. Any of the errors in #GConvertError may occur.
1681 * Converts an absolute filename to an escaped ASCII-encoded URI.
1683 * Return value: a newly-allocated string holding the resulting
1684 * URI, or %NULL on an error.
1687 g_filename_to_uri (const gchar *filename,
1688 const gchar *hostname,
1693 g_return_val_if_fail (filename != NULL, NULL);
1695 if (!g_path_is_absolute (filename))
1697 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1698 _("The pathname '%s' is not an absolute path"),
1704 !(g_utf8_validate (hostname, -1, NULL)
1705 && hostname_validate (hostname)))
1707 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1708 _("Invalid hostname"));
1713 /* Don't use localhost unnecessarily */
1714 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1718 escaped_uri = g_escape_file_uri (hostname, filename);
1724 * g_uri_list_extract_uris:
1725 * @uri_list: an URI list
1727 * Splits an URI list conforming to the text/uri-list
1728 * mime type defined in RFC 2483 into individual URIs,
1729 * discarding any comments. The URIs are not validated.
1731 * Returns: a newly allocated %NULL-terminated list of
1732 * strings holding the individual URIs. The array should
1733 * be freed with g_strfreev().
1738 g_uri_list_extract_uris (const gchar *uri_list)
1749 /* We don't actually try to validate the URI according to RFC
1750 * 2396, or even check for allowed characters - we just ignore
1751 * comments and trim whitespace off the ends. We also
1752 * allow LF delimination as well as the specified CRLF.
1754 * We do allow comments like specified in RFC 2483.
1760 while (g_ascii_isspace (*p))
1764 while (*q && (*q != '\n') && (*q != '\r'))
1770 while (q > p && g_ascii_isspace (*q))
1775 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1780 p = strchr (p, '\n');
1785 result = g_new (gchar *, n_uris + 1);
1787 result[n_uris--] = 0;
1788 for (u = uris; u; u = u->next)
1789 result[n_uris--] = u->data;
1791 g_slist_free (uris);