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.
32 #include "gprintfint.h"
33 #include "gthreadprivate.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
54 g_convert_error_quark (void)
56 return g_quark_from_static_string ("g_convert_error");
60 try_conversion (const char *to_codeset,
61 const char *from_codeset,
64 *cd = iconv_open (to_codeset, from_codeset);
66 if (*cd == (iconv_t)-1 && errno == EINVAL)
73 try_to_aliases (const char **to_aliases,
74 const char *from_codeset,
79 const char **p = to_aliases;
82 if (try_conversion (*p, from_codeset, cd))
92 extern const char ** G_GNUC_INTERNAL _g_charset_get_aliases (const char *canonical_name);
96 * @to_codeset: destination codeset
97 * @from_codeset: source codeset
99 * Same as the standard UNIX routine iconv_open(), but
100 * may be implemented via libiconv on UNIX flavors that lack
101 * a native implementation.
103 * GLib provides g_convert() and g_locale_to_utf8() which are likely
104 * more convenient than the raw iconv wrappers.
106 * Return value: a "conversion descriptor", or (GIConv)-1 if
107 * opening the converter failed.
110 g_iconv_open (const gchar *to_codeset,
111 const gchar *from_codeset)
115 if (!try_conversion (to_codeset, from_codeset, &cd))
117 const char **to_aliases = _g_charset_get_aliases (to_codeset);
118 const char **from_aliases = _g_charset_get_aliases (from_codeset);
122 const char **p = from_aliases;
125 if (try_conversion (to_codeset, *p, &cd))
128 if (try_to_aliases (to_aliases, *p, &cd))
135 if (try_to_aliases (to_aliases, from_codeset, &cd))
140 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
145 * @converter: conversion descriptor from g_iconv_open()
146 * @inbuf: bytes to convert
147 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
148 * @outbuf: converted output bytes
149 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
151 * Same as the standard UNIX routine iconv(), but
152 * may be implemented via libiconv on UNIX flavors that lack
153 * a native implementation.
155 * GLib provides g_convert() and g_locale_to_utf8() which are likely
156 * more convenient than the raw iconv wrappers.
158 * Return value: count of non-reversible conversions, or -1 on error
161 g_iconv (GIConv converter,
165 gsize *outbytes_left)
167 iconv_t cd = (iconv_t)converter;
169 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
174 * @converter: a conversion descriptor from g_iconv_open()
176 * Same as the standard UNIX routine iconv_close(), but
177 * may be implemented via libiconv on UNIX flavors that lack
178 * a native implementation. Should be called to clean up
179 * the conversion descriptor from g_iconv_open() when
180 * you are done converting things.
182 * GLib provides g_convert() and g_locale_to_utf8() which are likely
183 * more convenient than the raw iconv wrappers.
185 * Return value: -1 on error, 0 on success
188 g_iconv_close (GIConv converter)
190 iconv_t cd = (iconv_t)converter;
192 return iconv_close (cd);
196 #ifdef NEED_ICONV_CACHE
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 * This assumes ownership of @key.
240 * Returns a pointer to the newly allocated cache bucket.
242 static struct _iconv_cache_bucket *
243 iconv_cache_bucket_new (gchar *key, GIConv cd)
245 struct _iconv_cache_bucket *bucket;
247 bucket = g_new (struct _iconv_cache_bucket, 1);
249 bucket->refcount = 1;
253 g_hash_table_insert (iconv_cache, bucket->key, bucket);
255 /* FIXME: if we sorted the list so items with few refcounts were
256 first, then we could expire them faster in iconv_cache_expire_unused () */
257 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
266 * iconv_cache_bucket_expire:
267 * @node: cache bucket's node
268 * @bucket: cache bucket
270 * Expires a single cache bucket @bucket. This should only ever be
271 * called on a bucket that currently has no used iconv descriptors
274 * @node is not a required argument. If @node is not supplied, we
275 * search for it ourselves.
278 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
280 g_hash_table_remove (iconv_cache, bucket->key);
283 node = g_list_find (iconv_cache_list, bucket);
285 g_assert (node != NULL);
289 node->prev->next = node->next;
291 node->next->prev = node->prev;
295 iconv_cache_list = node->next;
297 node->next->prev = NULL;
300 g_list_free_1 (node);
302 g_free (bucket->key);
303 g_iconv_close (bucket->cd);
311 * iconv_cache_expire_unused:
313 * Expires as many unused cache buckets as it needs to in order to get
314 * the total number of buckets < ICONV_CACHE_SIZE.
317 iconv_cache_expire_unused (void)
319 struct _iconv_cache_bucket *bucket;
322 node = iconv_cache_list;
323 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
328 if (bucket->refcount == 0)
329 iconv_cache_bucket_expire (node, bucket);
336 open_converter (const gchar *to_codeset,
337 const gchar *from_codeset,
340 struct _iconv_cache_bucket *bucket;
341 gchar *key, *dyn_key, auto_key[80];
343 gsize len_from_codeset, len_to_codeset;
346 len_from_codeset = strlen (from_codeset);
347 len_to_codeset = strlen (to_codeset);
348 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
354 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
355 memcpy (key, from_codeset, len_from_codeset);
356 key[len_from_codeset] = ':';
357 strcpy (key + len_from_codeset + 1, to_codeset);
359 G_LOCK (iconv_cache_lock);
361 /* make sure the cache has been initialized */
364 bucket = g_hash_table_lookup (iconv_cache, key);
371 cd = g_iconv_open (to_codeset, from_codeset);
372 if (cd == (GIConv) -1)
377 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
378 * NULL for anything but inbuf; work around that. (NULL outbuf
379 * or NULL *outbuf is allowed by Unix98.)
381 gsize inbytes_left = 0;
382 gchar *outbuf = NULL;
383 gsize outbytes_left = 0;
388 /* reset the descriptor */
389 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
396 cd = g_iconv_open (to_codeset, from_codeset);
397 if (cd == (GIConv) -1)
403 iconv_cache_expire_unused ();
405 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
408 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
410 G_UNLOCK (iconv_cache_lock);
416 G_UNLOCK (iconv_cache_lock);
418 /* Something went wrong. */
422 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
423 _("Conversion from character set '%s' to '%s' is not supported"),
424 from_codeset, to_codeset);
426 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
427 _("Could not open converter from '%s' to '%s'"),
428 from_codeset, to_codeset);
435 close_converter (GIConv converter)
437 struct _iconv_cache_bucket *bucket;
443 if (cd == (GIConv) -1)
446 G_LOCK (iconv_cache_lock);
448 key = g_hash_table_lookup (iconv_open_hash, cd);
451 g_hash_table_remove (iconv_open_hash, cd);
453 bucket = g_hash_table_lookup (iconv_cache, key);
458 if (cd == bucket->cd)
459 bucket->used = FALSE;
463 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
465 /* expire this cache bucket */
466 iconv_cache_bucket_expire (NULL, bucket);
471 G_UNLOCK (iconv_cache_lock);
473 g_warning ("This iconv context wasn't opened using open_converter");
475 return g_iconv_close (converter);
478 G_UNLOCK (iconv_cache_lock);
483 #else /* !NEED_ICONV_CACHE */
486 open_converter (const gchar *to_codeset,
487 const gchar *from_codeset,
492 cd = g_iconv_open (to_codeset, from_codeset);
494 if (cd == (GIConv) -1)
496 /* Something went wrong. */
500 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
501 _("Conversion from character set '%s' to '%s' is not supported"),
502 from_codeset, to_codeset);
504 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
505 _("Could not open converter from '%s' to '%s'"),
506 from_codeset, to_codeset);
514 close_converter (GIConv cd)
516 if (cd == (GIConv) -1)
519 return g_iconv_close (cd);
522 #endif /* NEED_ICONV_CACHE */
525 * g_convert_with_iconv:
526 * @str: the string to convert
527 * @len: the length of the string, or -1 if the string is
528 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
529 * @converter: conversion descriptor from g_iconv_open()
530 * @bytes_read: location to store the number of bytes in the
531 * input string that were successfully converted, or %NULL.
532 * Even if the conversion was successful, this may be
533 * less than @len if there were partial characters
534 * at the end of the input. If the error
535 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
536 * stored will the byte offset after the last valid
538 * @bytes_written: the number of bytes stored in the output buffer (not
539 * including the terminating nul).
540 * @error: location to store the error occuring, or %NULL to ignore
541 * errors. Any of the errors in #GConvertError may occur.
543 * Converts a string from one character set to another.
545 * Note that you should use g_iconv() for streaming
546 * conversions<footnote id="streaming-state">
548 * Despite the fact that @byes_read can return information about partial
549 * characters, the <literal>g_convert_...</literal> functions
550 * are not generally suitable for streaming. If the underlying converter
551 * being used maintains internal state, then this won't be preserved
552 * across successive calls to g_convert(), g_convert_with_iconv() or
553 * g_convert_with_fallback(). (An example of this is the GNU C converter
554 * for CP1255 which does not emit a base character until it knows that
555 * the next character is not a mark that could combine with the base
560 * Return value: If the conversion was successful, a newly allocated
561 * nul-terminated string, which must be freed with
562 * g_free(). Otherwise %NULL and @error will be set.
565 g_convert_with_iconv (const gchar *str,
569 gsize *bytes_written,
575 const gchar *shift_p = NULL;
576 gsize inbytes_remaining;
577 gsize outbytes_remaining;
580 gboolean have_error = FALSE;
581 gboolean done = FALSE;
583 g_return_val_if_fail (converter != (GIConv) -1, NULL);
589 inbytes_remaining = len;
590 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
592 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
593 outp = dest = g_malloc (outbuf_size);
595 while (!done && !have_error)
597 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
599 if (err == (size_t) -1)
604 /* Incomplete text, do not report an error */
609 size_t used = outp - dest;
612 dest = g_realloc (dest, outbuf_size);
615 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
620 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
621 _("Invalid byte sequence in conversion input"));
626 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
627 _("Error during conversion: %s"),
637 /* call g_iconv with NULL inbuf to cleanup shift state */
640 inbytes_remaining = 0;
653 *bytes_read = p - str;
656 if ((p - str) != len)
661 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
662 _("Partial character sequence at end of input"));
669 *bytes_written = outp - dest; /* Doesn't include '\0' */
682 * @str: the string to convert
683 * @len: the length of the string, or -1 if the string is
684 * nul-terminated<footnote id="nul-unsafe">
686 Note that some encodings may allow nul bytes to
687 occur inside strings. In that case, using -1 for
688 the @len parameter is unsafe.
691 * @to_codeset: name of character set into which to convert @str
692 * @from_codeset: character set of @str.
693 * @bytes_read: location to store the number of bytes in the
694 * input string that were successfully converted, or %NULL.
695 * Even if the conversion was successful, this may be
696 * less than @len if there were partial characters
697 * at the end of the input. If the error
698 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
699 * stored will the byte offset after the last valid
701 * @bytes_written: the number of bytes stored in the output buffer (not
702 * including the terminating nul).
703 * @error: location to store the error occuring, or %NULL to ignore
704 * errors. Any of the errors in #GConvertError may occur.
706 * Converts a string from one character set to another.
708 * Note that you should use g_iconv() for streaming
709 * conversions<footnoteref linkend="streaming-state"/>.
711 * Return value: If the conversion was successful, a newly allocated
712 * nul-terminated string, which must be freed with
713 * g_free(). Otherwise %NULL and @error will be set.
716 g_convert (const gchar *str,
718 const gchar *to_codeset,
719 const gchar *from_codeset,
721 gsize *bytes_written,
727 g_return_val_if_fail (str != NULL, NULL);
728 g_return_val_if_fail (to_codeset != NULL, NULL);
729 g_return_val_if_fail (from_codeset != NULL, NULL);
731 cd = open_converter (to_codeset, from_codeset, error);
733 if (cd == (GIConv) -1)
744 res = g_convert_with_iconv (str, len, cd,
745 bytes_read, bytes_written,
748 close_converter (cd);
754 * g_convert_with_fallback:
755 * @str: the string to convert
756 * @len: the length of the string, or -1 if the string is
757 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
758 * @to_codeset: name of character set into which to convert @str
759 * @from_codeset: character set of @str.
760 * @fallback: UTF-8 string to use in place of character not
761 * present in the target encoding. (The string must be
762 * representable in the target encoding).
763 If %NULL, characters not in the target encoding will
764 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
765 * @bytes_read: location to store the number of bytes in the
766 * input string that were successfully converted, or %NULL.
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
771 * including the terminating nul).
772 * @error: location to store the error occuring, or %NULL to ignore
773 * errors. Any of the errors in #GConvertError may occur.
775 * Converts a string from one character set to another, possibly
776 * including fallback sequences for characters not representable
777 * in the output. Note that it is not guaranteed that the specification
778 * for the fallback sequences in @fallback will be honored. Some
779 * systems may do a approximate conversion from @from_codeset
780 * to @to_codeset in their iconv() functions,
781 * in which case GLib will simply return that approximate conversion.
783 * Note that you should use g_iconv() for streaming
784 * conversions<footnoteref linkend="streaming-state"/>.
786 * Return value: If the conversion was successful, a newly allocated
787 * nul-terminated string, which must be freed with
788 * g_free(). Otherwise %NULL and @error will be set.
791 g_convert_with_fallback (const gchar *str,
793 const gchar *to_codeset,
794 const gchar *from_codeset,
797 gsize *bytes_written,
803 const gchar *insert_str = NULL;
805 gsize inbytes_remaining;
806 const gchar *save_p = NULL;
807 gsize save_inbytes = 0;
808 gsize outbytes_remaining;
812 gboolean have_error = FALSE;
813 gboolean done = FALSE;
815 GError *local_error = NULL;
817 g_return_val_if_fail (str != NULL, NULL);
818 g_return_val_if_fail (to_codeset != NULL, NULL);
819 g_return_val_if_fail (from_codeset != NULL, NULL);
824 /* Try an exact conversion; we only proceed if this fails
825 * due to an illegal sequence in the input string.
827 dest = g_convert (str, len, to_codeset, from_codeset,
828 bytes_read, bytes_written, &local_error);
832 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
834 g_propagate_error (error, local_error);
838 g_error_free (local_error);
842 /* No go; to proceed, we need a converter from "UTF-8" to
843 * to_codeset, and the string as UTF-8.
845 cd = open_converter (to_codeset, "UTF-8", error);
846 if (cd == (GIConv) -1)
857 utf8 = g_convert (str, len, "UTF-8", from_codeset,
858 bytes_read, &inbytes_remaining, error);
861 close_converter (cd);
867 /* Now the heart of the code. We loop through the UTF-8 string, and
868 * whenever we hit an offending character, we form fallback, convert
869 * the fallback to the target codeset, and then go back to
870 * converting the original string after finishing with the fallback.
872 * The variables save_p and save_inbytes store the input state
873 * for the original string while we are converting the fallback
877 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
878 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
879 outp = dest = g_malloc (outbuf_size);
881 while (!done && !have_error)
883 size_t inbytes_tmp = inbytes_remaining;
884 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
885 inbytes_remaining = inbytes_tmp;
887 if (err == (size_t) -1)
892 g_assert_not_reached();
896 size_t used = outp - dest;
899 dest = g_realloc (dest, outbuf_size);
902 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
909 /* Error converting fallback string - fatal
911 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
912 _("Cannot convert fallback '%s' to codeset '%s'"),
913 insert_str, to_codeset);
921 gunichar ch = g_utf8_get_char (p);
922 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
926 insert_str = fallback;
928 save_p = g_utf8_next_char (p);
929 save_inbytes = inbytes_remaining - (save_p - p);
931 inbytes_remaining = strlen (p);
934 /* fall thru if p is NULL */
936 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
937 _("Error during conversion: %s"),
948 g_free ((gchar *)insert_str);
950 inbytes_remaining = save_inbytes;
955 /* call g_iconv with NULL inbuf to cleanup shift state */
957 inbytes_remaining = 0;
968 close_converter (cd);
971 *bytes_written = outp - dest; /* Doesn't include '\0' */
977 if (save_p && !fallback)
978 g_free ((gchar *)insert_str);
993 strdup_len (const gchar *string,
995 gsize *bytes_written,
1002 if (!g_utf8_validate (string, len, NULL))
1009 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1010 _("Invalid byte sequence in conversion input"));
1015 real_len = strlen (string);
1020 while (real_len < len && string[real_len])
1025 *bytes_read = real_len;
1027 *bytes_written = real_len;
1029 return g_strndup (string, real_len);
1034 * @opsysstring: a string in the encoding of the current locale. On Windows
1035 * 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 * @bytes_read: location to store the number of bytes in the
1039 * input string that were successfully converted, or %NULL.
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 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1044 * stored will the byte offset after the last valid
1046 * @bytes_written: the number of bytes stored in the output buffer (not
1047 * including the terminating nul).
1048 * @error: location to store the error occuring, or %NULL to ignore
1049 * errors. Any of the errors in #GConvertError may occur.
1051 * Converts a string which is in the encoding used for strings by
1052 * the C runtime (usually the same as that used by the operating
1053 * system) in the current locale into a UTF-8 string.
1055 * Return value: The converted string, or %NULL on an error.
1058 g_locale_to_utf8 (const gchar *opsysstring,
1061 gsize *bytes_written,
1064 const char *charset;
1066 if (g_get_charset (&charset))
1067 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1069 return g_convert (opsysstring, len,
1070 "UTF-8", charset, bytes_read, bytes_written, error);
1074 * g_locale_from_utf8:
1075 * @utf8string: a UTF-8 encoded string
1076 * @len: the length of the string, or -1 if the string is
1077 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1078 * @bytes_read: location to store the number of bytes in the
1079 * input string that were successfully converted, or %NULL.
1080 * Even if the conversion was successful, this may be
1081 * less than @len if there were partial characters
1082 * at the end of the input. If the error
1083 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1084 * stored will the byte offset after the last valid
1086 * @bytes_written: the number of bytes stored in the output buffer (not
1087 * including the terminating nul).
1088 * @error: location to store the error occuring, or %NULL to ignore
1089 * errors. Any of the errors in #GConvertError may occur.
1091 * Converts a string from UTF-8 to the encoding used for strings by
1092 * the C runtime (usually the same as that used by the operating
1093 * system) in the current locale.
1095 * Return value: The converted string, or %NULL on an error.
1098 g_locale_from_utf8 (const gchar *utf8string,
1101 gsize *bytes_written,
1104 const gchar *charset;
1106 if (g_get_charset (&charset))
1107 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1109 return g_convert (utf8string, len,
1110 charset, "UTF-8", bytes_read, bytes_written, error);
1113 #ifndef G_PLATFORM_WIN32
1115 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1117 struct _GFilenameCharsetCache {
1120 gchar **filename_charsets;
1124 filename_charset_cache_free (gpointer data)
1126 GFilenameCharsetCache *cache = data;
1127 g_free (cache->charset);
1128 g_strfreev (cache->filename_charsets);
1133 * g_get_filename_charsets:
1134 * @charsets: return location for the %NULL-terminated list of encoding names
1136 * Determines the preferred character sets used for filenames.
1137 * The first character set from the @charsets is the filename encoding, the
1138 * subsequent character sets are used when trying to generate a displayable
1139 * representation of a filename, see g_filename_display_name().
1141 * On Unix, the character sets are determined by consulting the
1142 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1143 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1144 * used in the GLib API is always UTF-8 and said environment variables
1147 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1148 * of character set names. The special token "@locale" is taken to mean the
1149 * character set for the current locale. If <envar>G_FILENAME_ENCODING</envar>
1150 * is not set, but <envar>G_BROKEN_FILENAMES</envar> is, the character set of
1151 * the current locale is taken as the filename encoding. If neither environment
1152 * variable is set, UTF-8 is taken as the filename encoding, but the character
1153 * set of the current locale is also put in the list of encodings.
1155 * The returned @charsets belong to GLib and must not be freed.
1157 * Note that on Unix, regardless of the locale character set or
1158 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present on a
1159 * system might be in any random encoding or just gibberish.
1161 * Return value: %TRUE if the filename encoding is UTF-8.
1166 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1168 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1169 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1170 const gchar *charset;
1174 cache = g_new0 (GFilenameCharsetCache, 1);
1175 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1178 g_get_charset (&charset);
1180 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1182 const gchar *new_charset;
1186 g_free (cache->charset);
1187 g_strfreev (cache->filename_charsets);
1188 cache->charset = g_strdup (charset);
1190 p = getenv ("G_FILENAME_ENCODING");
1191 if (p != NULL && p[0] != '\0')
1193 cache->filename_charsets = g_strsplit (p, ",", 0);
1194 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1196 for (i = 0; cache->filename_charsets[i]; i++)
1198 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1200 g_get_charset (&new_charset);
1201 g_free (cache->filename_charsets[i]);
1202 cache->filename_charsets[i] = g_strdup (new_charset);
1206 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1208 cache->filename_charsets = g_new0 (gchar *, 2);
1209 cache->is_utf8 = g_get_charset (&new_charset);
1210 cache->filename_charsets[0] = g_strdup (new_charset);
1214 cache->filename_charsets = g_new0 (gchar *, 3);
1215 cache->is_utf8 = TRUE;
1216 cache->filename_charsets[0] = g_strdup ("UTF-8");
1217 if (!g_get_charset (&new_charset))
1218 cache->filename_charsets[1] = g_strdup (new_charset);
1222 if (filename_charsets)
1223 *filename_charsets = (const gchar **)cache->filename_charsets;
1225 return cache->is_utf8;
1228 #else /* G_PLATFORM_WIN32 */
1231 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1233 static const gchar *charsets[] = {
1239 /* On Windows GLib pretends that the filename charset is UTF-8 */
1240 if (filename_charsets)
1241 *filename_charsets = charsets;
1247 /* Cygwin works like before */
1248 result = g_get_charset (&(charsets[0]));
1250 if (filename_charsets)
1251 *filename_charsets = charsets;
1257 #endif /* G_PLATFORM_WIN32 */
1260 get_filename_charset (const gchar **filename_charset)
1262 const gchar **charsets;
1265 is_utf8 = g_get_filename_charsets (&charsets);
1267 if (filename_charset)
1268 *filename_charset = charsets[0];
1273 /* This is called from g_thread_init(). It's used to
1274 * initialize some static data in a threadsafe way.
1277 _g_convert_thread_init (void)
1279 const gchar **dummy;
1280 (void) g_get_filename_charsets (&dummy);
1284 * g_filename_to_utf8:
1285 * @opsysstring: a string in the encoding for filenames
1286 * @len: the length of the string, or -1 if the string is
1287 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1288 * @bytes_read: location to store the number of bytes in the
1289 * input string that were successfully converted, or %NULL.
1290 * Even if the conversion was successful, this may be
1291 * less than @len if there were partial characters
1292 * at the end of the input. If the error
1293 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1294 * stored will the byte offset after the last valid
1296 * @bytes_written: the number of bytes stored in the output buffer (not
1297 * including the terminating nul).
1298 * @error: location to store the error occuring, or %NULL to ignore
1299 * errors. Any of the errors in #GConvertError may occur.
1301 * Converts a string which is in the encoding used by GLib for
1302 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1305 * Return value: The converted string, or %NULL on an error.
1308 g_filename_to_utf8 (const gchar *opsysstring,
1311 gsize *bytes_written,
1314 const gchar *charset;
1316 if (get_filename_charset (&charset))
1317 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1319 return g_convert (opsysstring, len,
1320 "UTF-8", charset, bytes_read, bytes_written, error);
1325 #undef g_filename_to_utf8
1327 /* Binary compatibility version. Not for newly compiled code. */
1330 g_filename_to_utf8 (const gchar *opsysstring,
1333 gsize *bytes_written,
1336 const gchar *charset;
1338 if (g_get_charset (&charset))
1339 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1341 return g_convert (opsysstring, len,
1342 "UTF-8", charset, bytes_read, bytes_written, error);
1348 * g_filename_from_utf8:
1349 * @utf8string: a UTF-8 encoded string.
1350 * @len: the length of the string, or -1 if the string is
1352 * @bytes_read: location to store the number of bytes in the
1353 * input string that were successfully converted, or %NULL.
1354 * Even if the conversion was successful, this may be
1355 * less than @len if there were partial characters
1356 * at the end of the input. If the error
1357 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1358 * stored will the byte offset after the last valid
1360 * @bytes_written: the number of bytes stored in the output buffer (not
1361 * including the terminating nul).
1362 * @error: location to store the error occuring, or %NULL to ignore
1363 * errors. Any of the errors in #GConvertError may occur.
1365 * Converts a string from UTF-8 to the encoding GLib uses for
1366 * filenames. Note that on Windows GLib uses UTF-8 for filenames.
1368 * Return value: The converted string, or %NULL on an error.
1371 g_filename_from_utf8 (const gchar *utf8string,
1374 gsize *bytes_written,
1377 const gchar *charset;
1379 if (get_filename_charset (&charset))
1380 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1382 return g_convert (utf8string, len,
1383 charset, "UTF-8", bytes_read, bytes_written, error);
1388 #undef g_filename_from_utf8
1390 /* Binary compatibility version. Not for newly compiled code. */
1393 g_filename_from_utf8 (const gchar *utf8string,
1396 gsize *bytes_written,
1399 const gchar *charset;
1401 if (g_get_charset (&charset))
1402 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1404 return g_convert (utf8string, len,
1405 charset, "UTF-8", bytes_read, bytes_written, error);
1410 /* Test of haystack has the needle prefix, comparing case
1411 * insensitive. haystack may be UTF-8, but needle must
1412 * contain only ascii. */
1414 has_case_prefix (const gchar *haystack, const gchar *needle)
1418 /* Eat one character at a time. */
1423 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1433 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1434 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1435 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1436 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1437 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1438 } UnsafeCharacterSet;
1440 static const guchar acceptable[96] = {
1441 /* A table of the ASCII chars from space (32) to DEL (127) */
1442 /* ! " # $ % & ' ( ) * + , - . / */
1443 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1444 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1445 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1446 /* @ A B C D E F G H I J K L M N O */
1447 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1448 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1449 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1450 /* ` a b c d e f g h i j k l m n o */
1451 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1452 /* p q r s t u v w x y z { | } ~ DEL */
1453 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1456 static const gchar hex[16] = "0123456789ABCDEF";
1458 /* Note: This escape function works on file: URIs, but if you want to
1459 * escape something else, please read RFC-2396 */
1461 g_escape_uri_string (const gchar *string,
1462 UnsafeCharacterSet mask)
1464 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1471 UnsafeCharacterSet use_mask;
1473 g_return_val_if_fail (mask == UNSAFE_ALL
1474 || mask == UNSAFE_ALLOW_PLUS
1475 || mask == UNSAFE_PATH
1476 || mask == UNSAFE_HOST
1477 || mask == UNSAFE_SLASHES, NULL);
1481 for (p = string; *p != '\0'; p++)
1484 if (!ACCEPTABLE (c))
1488 result = g_malloc (p - string + unacceptable * 2 + 1);
1491 for (q = result, p = string; *p != '\0'; p++)
1495 if (!ACCEPTABLE (c))
1497 *q++ = '%'; /* means hex coming */
1512 g_escape_file_uri (const gchar *hostname,
1513 const gchar *pathname)
1515 char *escaped_hostname = NULL;
1520 char *p, *backslash;
1522 /* Turn backslashes into forward slashes. That's what Netscape
1523 * does, and they are actually more or less equivalent in Windows.
1526 pathname = g_strdup (pathname);
1527 p = (char *) pathname;
1529 while ((backslash = strchr (p, '\\')) != NULL)
1536 if (hostname && *hostname != '\0')
1538 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1541 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1543 res = g_strconcat ("file://",
1544 (escaped_hostname) ? escaped_hostname : "",
1545 (*escaped_path != '/') ? "/" : "",
1550 g_free ((char *) pathname);
1553 g_free (escaped_hostname);
1554 g_free (escaped_path);
1560 unescape_character (const char *scanner)
1565 first_digit = g_ascii_xdigit_value (scanner[0]);
1566 if (first_digit < 0)
1569 second_digit = g_ascii_xdigit_value (scanner[1]);
1570 if (second_digit < 0)
1573 return (first_digit << 4) | second_digit;
1577 g_unescape_uri_string (const char *escaped,
1579 const char *illegal_escaped_characters,
1580 gboolean ascii_must_not_be_escaped)
1582 const gchar *in, *in_end;
1583 gchar *out, *result;
1586 if (escaped == NULL)
1590 len = strlen (escaped);
1592 result = g_malloc (len + 1);
1595 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1601 /* catch partial escape sequences past the end of the substring */
1602 if (in + 3 > in_end)
1605 c = unescape_character (in + 1);
1607 /* catch bad escape sequences and NUL characters */
1611 /* catch escaped ASCII */
1612 if (ascii_must_not_be_escaped && c <= 0x7F)
1615 /* catch other illegal escaped characters */
1616 if (strchr (illegal_escaped_characters, c) != NULL)
1625 g_assert (out - result <= len);
1638 is_asciialphanum (gunichar c)
1640 return c <= 0x7F && g_ascii_isalnum (c);
1644 is_asciialpha (gunichar c)
1646 return c <= 0x7F && g_ascii_isalpha (c);
1649 /* allows an empty string */
1651 hostname_validate (const char *hostname)
1654 gunichar c, first_char, last_char;
1661 /* read in a label */
1662 c = g_utf8_get_char (p);
1663 p = g_utf8_next_char (p);
1664 if (!is_asciialphanum (c))
1670 c = g_utf8_get_char (p);
1671 p = g_utf8_next_char (p);
1673 while (is_asciialphanum (c) || c == '-');
1674 if (last_char == '-')
1677 /* if that was the last label, check that it was a toplabel */
1678 if (c == '\0' || (c == '.' && *p == '\0'))
1679 return is_asciialpha (first_char);
1686 * g_filename_from_uri:
1687 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1688 * @hostname: Location to store hostname for the URI, or %NULL.
1689 * If there is no hostname in the URI, %NULL will be
1690 * stored in this location.
1691 * @error: location to store the error occuring, or %NULL to ignore
1692 * errors. Any of the errors in #GConvertError may occur.
1694 * Converts an escaped ASCII-encoded URI to a local filename in the
1695 * encoding used for filenames.
1697 * Return value: a newly-allocated string holding the resulting
1698 * filename, or %NULL on an error.
1701 g_filename_from_uri (const gchar *uri,
1705 const char *path_part;
1706 const char *host_part;
1707 char *unescaped_hostname;
1718 if (!has_case_prefix (uri, "file:/"))
1720 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1721 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1726 path_part = uri + strlen ("file:");
1728 if (strchr (path_part, '#') != NULL)
1730 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1731 _("The local file URI '%s' may not include a '#'"),
1736 if (has_case_prefix (path_part, "///"))
1738 else if (has_case_prefix (path_part, "//"))
1741 host_part = path_part;
1743 path_part = strchr (path_part, '/');
1745 if (path_part == NULL)
1747 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1748 _("The URI '%s' is invalid"),
1753 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1755 if (unescaped_hostname == NULL ||
1756 !hostname_validate (unescaped_hostname))
1758 g_free (unescaped_hostname);
1759 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1760 _("The hostname of the URI '%s' is invalid"),
1766 *hostname = unescaped_hostname;
1768 g_free (unescaped_hostname);
1771 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1773 if (filename == NULL)
1775 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1776 _("The URI '%s' contains invalidly escaped characters"),
1783 /* Drop localhost */
1784 if (hostname && *hostname != NULL &&
1785 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1791 /* Turn slashes into backslashes, because that's the canonical spelling */
1793 while ((slash = strchr (p, '/')) != NULL)
1799 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1800 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1801 * the filename from the drive letter.
1803 if (g_ascii_isalpha (filename[1]))
1805 if (filename[2] == ':')
1807 else if (filename[2] == '|')
1815 result = g_strdup (filename + offs);
1823 #undef g_filename_from_uri
1826 g_filename_from_uri (const gchar *uri,
1830 gchar *utf8_filename;
1831 gchar *retval = NULL;
1833 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1836 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1837 g_free (utf8_filename);
1845 * g_filename_to_uri:
1846 * @filename: an absolute filename specified in the GLib file name encoding,
1847 * which is the on-disk file name bytes on Unix, and UTF-8 on
1849 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1850 * @error: location to store the error occuring, or %NULL to ignore
1851 * errors. Any of the errors in #GConvertError may occur.
1853 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1854 * component following Section 3.3. of RFC 2396.
1856 * Return value: a newly-allocated string holding the resulting
1857 * URI, or %NULL on an error.
1860 g_filename_to_uri (const gchar *filename,
1861 const gchar *hostname,
1866 g_return_val_if_fail (filename != NULL, NULL);
1868 if (!g_path_is_absolute (filename))
1870 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1871 _("The pathname '%s' is not an absolute path"),
1877 !(g_utf8_validate (hostname, -1, NULL)
1878 && hostname_validate (hostname)))
1880 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1881 _("Invalid hostname"));
1886 /* Don't use localhost unnecessarily */
1887 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1891 escaped_uri = g_escape_file_uri (hostname, filename);
1898 #undef g_filename_to_uri
1901 g_filename_to_uri (const gchar *filename,
1902 const gchar *hostname,
1905 gchar *utf8_filename;
1906 gchar *retval = NULL;
1908 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1912 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1913 g_free (utf8_filename);
1922 * g_uri_list_extract_uris:
1923 * @uri_list: an URI list
1925 * Splits an URI list conforming to the text/uri-list
1926 * mime type defined in RFC 2483 into individual URIs,
1927 * discarding any comments. The URIs are not validated.
1929 * Returns: a newly allocated %NULL-terminated list of
1930 * strings holding the individual URIs. The array should
1931 * be freed with g_strfreev().
1936 g_uri_list_extract_uris (const gchar *uri_list)
1947 /* We don't actually try to validate the URI according to RFC
1948 * 2396, or even check for allowed characters - we just ignore
1949 * comments and trim whitespace off the ends. We also
1950 * allow LF delimination as well as the specified CRLF.
1952 * We do allow comments like specified in RFC 2483.
1958 while (g_ascii_isspace (*p))
1962 while (*q && (*q != '\n') && (*q != '\r'))
1968 while (q > p && g_ascii_isspace (*q))
1973 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1978 p = strchr (p, '\n');
1983 result = g_new (gchar *, n_uris + 1);
1985 result[n_uris--] = NULL;
1986 for (u = uris; u; u = u->next)
1987 result[n_uris--] = u->data;
1989 g_slist_free (uris);
1995 * g_filename_display_basename:
1996 * @filename: an absolute pathname in the GLib file name encoding
1998 * Returns the display basename for the particular filename, guaranteed
1999 * to be valid UTF-8. The display name might not be identical to the filename,
2000 * for instance there might be problems converting it to UTF-8, and some files
2001 * can be translated in the display.
2003 * If GLib can not make sense of the encoding of @filename, as a last resort it
2004 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2005 * You can search the result for the UTF-8 encoding of this character (which is
2006 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2009 * You must pass the whole absolute pathname to this functions so that
2010 * translation of well known locations can be done.
2012 * This function is preferred over g_filename_display_name() if you know the
2013 * whole path, as it allows translation.
2015 * Return value: a newly allocated string containing
2016 * a rendition of the basename of the filename in valid UTF-8
2021 g_filename_display_basename (const gchar *filename)
2026 g_return_val_if_fail (filename != NULL, NULL);
2028 basename = g_path_get_basename (filename);
2029 display_name = g_filename_display_name (basename);
2031 return display_name;
2035 * g_filename_display_name:
2036 * @filename: a pathname hopefully in the GLib file name encoding
2038 * Converts a filename into a valid UTF-8 string. The conversion is
2039 * not necessarily reversible, so you should keep the original around
2040 * and use the return value of this function only for display purposes.
2041 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2042 * even if the filename actually isn't in the GLib file name encoding.
2044 * If GLib can not make sense of the encoding of @filename, as a last resort it
2045 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2046 * You can search the result for the UTF-8 encoding of this character (which is
2047 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2050 * If you know the whole pathname of the file you should use
2051 * g_filename_display_basename(), since that allows location-based
2052 * translation of filenames.
2054 * Return value: a newly allocated string containing
2055 * a rendition of the filename in valid UTF-8
2060 g_filename_display_name (const gchar *filename)
2063 const gchar **charsets;
2064 gchar *display_name = NULL;
2067 is_utf8 = g_get_filename_charsets (&charsets);
2071 if (g_utf8_validate (filename, -1, NULL))
2072 display_name = g_strdup (filename);
2077 /* Try to convert from the filename charsets to UTF-8.
2078 * Skip the first charset if it is UTF-8.
2080 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2082 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2090 /* if all conversions failed, we replace invalid UTF-8
2091 * by a question mark
2094 display_name = _g_utf8_make_valid (filename);
2096 return display_name;
2099 #define __G_CONVERT_C__
2100 #include "galiasdef.c"