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.
35 #include "gprintfint.h"
36 #include "gthreadprivate.h"
39 #ifdef G_PLATFORM_WIN32
47 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
48 #error GNU libiconv in use but included iconv.h not from libiconv
50 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
51 #error GNU libiconv not in use but included iconv.h is from libiconv
57 #include "win_iconv.c"
61 g_convert_error_quark (void)
63 return g_quark_from_static_string ("g_convert_error");
67 try_conversion (const char *to_codeset,
68 const char *from_codeset,
71 *cd = iconv_open (to_codeset, from_codeset);
73 if (*cd == (iconv_t)-1 && errno == EINVAL)
80 try_to_aliases (const char **to_aliases,
81 const char *from_codeset,
86 const char **p = to_aliases;
89 if (try_conversion (*p, from_codeset, cd))
99 G_GNUC_INTERNAL extern const char **
100 _g_charset_get_aliases (const char *canonical_name);
104 * @to_codeset: destination codeset
105 * @from_codeset: source codeset
107 * Same as the standard UNIX routine iconv_open(), but
108 * may be implemented via libiconv on UNIX flavors that lack
109 * a native implementation.
111 * GLib provides g_convert() and g_locale_to_utf8() which are likely
112 * more convenient than the raw iconv wrappers.
114 * Return value: a "conversion descriptor", or (GIConv)-1 if
115 * opening the converter failed.
118 g_iconv_open (const gchar *to_codeset,
119 const gchar *from_codeset)
123 if (!try_conversion (to_codeset, from_codeset, &cd))
125 const char **to_aliases = _g_charset_get_aliases (to_codeset);
126 const char **from_aliases = _g_charset_get_aliases (from_codeset);
130 const char **p = from_aliases;
133 if (try_conversion (to_codeset, *p, &cd))
136 if (try_to_aliases (to_aliases, *p, &cd))
143 if (try_to_aliases (to_aliases, from_codeset, &cd))
148 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
153 * @converter: conversion descriptor from g_iconv_open()
154 * @inbuf: bytes to convert
155 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
156 * @outbuf: converted output bytes
157 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
159 * Same as the standard UNIX routine iconv(), but
160 * may be implemented via libiconv on UNIX flavors that lack
161 * a native implementation.
163 * GLib provides g_convert() and g_locale_to_utf8() which are likely
164 * more convenient than the raw iconv wrappers.
166 * Return value: count of non-reversible conversions, or -1 on error
169 g_iconv (GIConv converter,
173 gsize *outbytes_left)
175 iconv_t cd = (iconv_t)converter;
177 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
182 * @converter: a conversion descriptor from g_iconv_open()
184 * Same as the standard UNIX routine iconv_close(), but
185 * may be implemented via libiconv on UNIX flavors that lack
186 * a native implementation. Should be called to clean up
187 * the conversion descriptor from g_iconv_open() when
188 * you are done converting things.
190 * GLib provides g_convert() and g_locale_to_utf8() which are likely
191 * more convenient than the raw iconv wrappers.
193 * Return value: -1 on error, 0 on success
196 g_iconv_close (GIConv converter)
198 iconv_t cd = (iconv_t)converter;
200 return iconv_close (cd);
204 #ifdef NEED_ICONV_CACHE
206 #define ICONV_CACHE_SIZE (16)
208 struct _iconv_cache_bucket {
215 static GList *iconv_cache_list;
216 static GHashTable *iconv_cache;
217 static GHashTable *iconv_open_hash;
218 static guint iconv_cache_size = 0;
219 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
221 /* caller *must* hold the iconv_cache_lock */
223 iconv_cache_init (void)
225 static gboolean initialized = FALSE;
230 iconv_cache_list = NULL;
231 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
232 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
239 * iconv_cache_bucket_new:
241 * @cd: iconv descriptor
243 * Creates a new cache bucket, inserts it into the cache and
244 * increments the cache size.
246 * This assumes ownership of @key.
248 * Returns a pointer to the newly allocated cache bucket.
250 static struct _iconv_cache_bucket *
251 iconv_cache_bucket_new (gchar *key, GIConv cd)
253 struct _iconv_cache_bucket *bucket;
255 bucket = g_new (struct _iconv_cache_bucket, 1);
257 bucket->refcount = 1;
261 g_hash_table_insert (iconv_cache, bucket->key, bucket);
263 /* FIXME: if we sorted the list so items with few refcounts were
264 first, then we could expire them faster in iconv_cache_expire_unused () */
265 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
274 * iconv_cache_bucket_expire:
275 * @node: cache bucket's node
276 * @bucket: cache bucket
278 * Expires a single cache bucket @bucket. This should only ever be
279 * called on a bucket that currently has no used iconv descriptors
282 * @node is not a required argument. If @node is not supplied, we
283 * search for it ourselves.
286 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
288 g_hash_table_remove (iconv_cache, bucket->key);
291 node = g_list_find (iconv_cache_list, bucket);
293 g_assert (node != NULL);
297 node->prev->next = node->next;
299 node->next->prev = node->prev;
303 iconv_cache_list = node->next;
305 node->next->prev = NULL;
308 g_list_free_1 (node);
310 g_free (bucket->key);
311 g_iconv_close (bucket->cd);
319 * iconv_cache_expire_unused:
321 * Expires as many unused cache buckets as it needs to in order to get
322 * the total number of buckets < ICONV_CACHE_SIZE.
325 iconv_cache_expire_unused (void)
327 struct _iconv_cache_bucket *bucket;
330 node = iconv_cache_list;
331 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
336 if (bucket->refcount == 0)
337 iconv_cache_bucket_expire (node, bucket);
344 open_converter (const gchar *to_codeset,
345 const gchar *from_codeset,
348 struct _iconv_cache_bucket *bucket;
349 gchar *key, *dyn_key, auto_key[80];
351 gsize len_from_codeset, len_to_codeset;
354 len_from_codeset = strlen (from_codeset);
355 len_to_codeset = strlen (to_codeset);
356 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
362 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
363 memcpy (key, from_codeset, len_from_codeset);
364 key[len_from_codeset] = ':';
365 strcpy (key + len_from_codeset + 1, to_codeset);
367 G_LOCK (iconv_cache_lock);
369 /* make sure the cache has been initialized */
372 bucket = g_hash_table_lookup (iconv_cache, key);
379 cd = g_iconv_open (to_codeset, from_codeset);
380 if (cd == (GIConv) -1)
385 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
386 * NULL for anything but inbuf; work around that. (NULL outbuf
387 * or NULL *outbuf is allowed by Unix98.)
389 gsize inbytes_left = 0;
390 gchar *outbuf = NULL;
391 gsize outbytes_left = 0;
396 /* reset the descriptor */
397 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
404 cd = g_iconv_open (to_codeset, from_codeset);
405 if (cd == (GIConv) -1)
411 iconv_cache_expire_unused ();
413 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
416 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
418 G_UNLOCK (iconv_cache_lock);
424 G_UNLOCK (iconv_cache_lock);
426 /* Something went wrong. */
430 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
431 _("Conversion from character set '%s' to '%s' is not supported"),
432 from_codeset, to_codeset);
434 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
435 _("Could not open converter from '%s' to '%s'"),
436 from_codeset, to_codeset);
443 close_converter (GIConv converter)
445 struct _iconv_cache_bucket *bucket;
451 if (cd == (GIConv) -1)
454 G_LOCK (iconv_cache_lock);
456 key = g_hash_table_lookup (iconv_open_hash, cd);
459 g_hash_table_remove (iconv_open_hash, cd);
461 bucket = g_hash_table_lookup (iconv_cache, key);
466 if (cd == bucket->cd)
467 bucket->used = FALSE;
471 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
473 /* expire this cache bucket */
474 iconv_cache_bucket_expire (NULL, bucket);
479 G_UNLOCK (iconv_cache_lock);
481 g_warning ("This iconv context wasn't opened using open_converter");
483 return g_iconv_close (converter);
486 G_UNLOCK (iconv_cache_lock);
491 #else /* !NEED_ICONV_CACHE */
494 open_converter (const gchar *to_codeset,
495 const gchar *from_codeset,
500 cd = g_iconv_open (to_codeset, from_codeset);
502 if (cd == (GIConv) -1)
504 /* Something went wrong. */
508 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
509 _("Conversion from character set '%s' to '%s' is not supported"),
510 from_codeset, to_codeset);
512 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
513 _("Could not open converter from '%s' to '%s'"),
514 from_codeset, to_codeset);
522 close_converter (GIConv cd)
524 if (cd == (GIConv) -1)
527 return g_iconv_close (cd);
530 #endif /* NEED_ICONV_CACHE */
533 * g_convert_with_iconv:
534 * @str: the string to convert
535 * @len: the length of the string, or -1 if the string is
536 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
537 * @converter: conversion descriptor from g_iconv_open()
538 * @bytes_read: location to store the number of bytes in the
539 * input string that were successfully converted, or %NULL.
540 * Even if the conversion was successful, this may be
541 * less than @len if there were partial characters
542 * at the end of the input. If the error
543 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
544 * stored will the byte offset after the last valid
546 * @bytes_written: the number of bytes stored in the output buffer (not
547 * including the terminating nul).
548 * @error: location to store the error occuring, or %NULL to ignore
549 * errors. Any of the errors in #GConvertError may occur.
551 * Converts a string from one character set to another.
553 * Note that you should use g_iconv() for streaming
554 * conversions<footnote id="streaming-state">
556 * Despite the fact that @byes_read can return information about partial
557 * characters, the <literal>g_convert_...</literal> functions
558 * are not generally suitable for streaming. If the underlying converter
559 * being used maintains internal state, then this won't be preserved
560 * across successive calls to g_convert(), g_convert_with_iconv() or
561 * g_convert_with_fallback(). (An example of this is the GNU C converter
562 * for CP1255 which does not emit a base character until it knows that
563 * the next character is not a mark that could combine with the base
568 * Return value: If the conversion was successful, a newly allocated
569 * nul-terminated string, which must be freed with
570 * g_free(). Otherwise %NULL and @error will be set.
573 g_convert_with_iconv (const gchar *str,
577 gsize *bytes_written,
583 gsize inbytes_remaining;
584 gsize outbytes_remaining;
587 gboolean have_error = FALSE;
588 gboolean done = FALSE;
589 gboolean reset = FALSE;
591 g_return_val_if_fail (converter != (GIConv) -1, NULL);
597 inbytes_remaining = len;
598 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
600 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
601 outp = dest = g_malloc (outbuf_size);
603 while (!done && !have_error)
606 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
608 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
610 if (err == (gsize) -1)
615 /* Incomplete text, do not report an error */
620 gsize used = outp - dest;
623 dest = g_realloc (dest, outbuf_size);
626 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
631 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
632 _("Invalid byte sequence in conversion input"));
637 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
638 _("Error during conversion: %s"),
648 /* call g_iconv with NULL inbuf to cleanup shift state */
650 inbytes_remaining = 0;
660 *bytes_read = p - str;
663 if ((p - str) != len)
668 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
669 _("Partial character sequence at end of input"));
676 *bytes_written = outp - dest; /* Doesn't include '\0' */
689 * @str: the string to convert
690 * @len: the length of the string, or -1 if the string is
691 * nul-terminated<footnote id="nul-unsafe">
693 Note that some encodings may allow nul bytes to
694 occur inside strings. In that case, using -1 for
695 the @len parameter is unsafe.
698 * @to_codeset: name of character set into which to convert @str
699 * @from_codeset: character set of @str.
700 * @bytes_read: location to store the number of bytes in the
701 * input string that were successfully converted, or %NULL.
702 * Even if the conversion was successful, this may be
703 * less than @len if there were partial characters
704 * at the end of the input. If the error
705 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
706 * stored will the byte offset after the last valid
708 * @bytes_written: the number of bytes stored in the output buffer (not
709 * including the terminating nul).
710 * @error: location to store the error occuring, or %NULL to ignore
711 * errors. Any of the errors in #GConvertError may occur.
713 * Converts a string from one character set to another.
715 * Note that you should use g_iconv() for streaming
716 * conversions<footnoteref linkend="streaming-state"/>.
718 * Return value: If the conversion was successful, a newly allocated
719 * nul-terminated string, which must be freed with
720 * g_free(). Otherwise %NULL and @error will be set.
723 g_convert (const gchar *str,
725 const gchar *to_codeset,
726 const gchar *from_codeset,
728 gsize *bytes_written,
734 g_return_val_if_fail (str != NULL, NULL);
735 g_return_val_if_fail (to_codeset != NULL, NULL);
736 g_return_val_if_fail (from_codeset != NULL, NULL);
738 cd = open_converter (to_codeset, from_codeset, error);
740 if (cd == (GIConv) -1)
751 res = g_convert_with_iconv (str, len, cd,
752 bytes_read, bytes_written,
755 close_converter (cd);
761 * g_convert_with_fallback:
762 * @str: the string to convert
763 * @len: the length of the string, or -1 if the string is
764 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
765 * @to_codeset: name of character set into which to convert @str
766 * @from_codeset: character set of @str.
767 * @fallback: UTF-8 string to use in place of character not
768 * present in the target encoding. (The string must be
769 * representable in the target encoding).
770 If %NULL, characters not in the target encoding will
771 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
772 * @bytes_read: location to store the number of bytes in the
773 * input string that were successfully converted, or %NULL.
774 * Even if the conversion was successful, this may be
775 * less than @len if there were partial characters
776 * at the end of the input.
777 * @bytes_written: the number of bytes stored in the output buffer (not
778 * including the terminating nul).
779 * @error: location to store the error occuring, or %NULL to ignore
780 * errors. Any of the errors in #GConvertError may occur.
782 * Converts a string from one character set to another, possibly
783 * including fallback sequences for characters not representable
784 * in the output. Note that it is not guaranteed that the specification
785 * for the fallback sequences in @fallback will be honored. Some
786 * systems may do an approximate conversion from @from_codeset
787 * to @to_codeset in their iconv() functions,
788 * in which case GLib will simply return that approximate conversion.
790 * Note that you should use g_iconv() for streaming
791 * conversions<footnoteref linkend="streaming-state"/>.
793 * Return value: If the conversion was successful, a newly allocated
794 * nul-terminated string, which must be freed with
795 * g_free(). Otherwise %NULL and @error will be set.
798 g_convert_with_fallback (const gchar *str,
800 const gchar *to_codeset,
801 const gchar *from_codeset,
804 gsize *bytes_written,
810 const gchar *insert_str = NULL;
812 gsize inbytes_remaining;
813 const gchar *save_p = NULL;
814 gsize save_inbytes = 0;
815 gsize outbytes_remaining;
819 gboolean have_error = FALSE;
820 gboolean done = FALSE;
822 GError *local_error = NULL;
824 g_return_val_if_fail (str != NULL, NULL);
825 g_return_val_if_fail (to_codeset != NULL, NULL);
826 g_return_val_if_fail (from_codeset != NULL, NULL);
831 /* Try an exact conversion; we only proceed if this fails
832 * due to an illegal sequence in the input string.
834 dest = g_convert (str, len, to_codeset, from_codeset,
835 bytes_read, bytes_written, &local_error);
839 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
841 g_propagate_error (error, local_error);
845 g_error_free (local_error);
849 /* No go; to proceed, we need a converter from "UTF-8" to
850 * to_codeset, and the string as UTF-8.
852 cd = open_converter (to_codeset, "UTF-8", error);
853 if (cd == (GIConv) -1)
864 utf8 = g_convert (str, len, "UTF-8", from_codeset,
865 bytes_read, &inbytes_remaining, error);
868 close_converter (cd);
874 /* Now the heart of the code. We loop through the UTF-8 string, and
875 * whenever we hit an offending character, we form fallback, convert
876 * the fallback to the target codeset, and then go back to
877 * converting the original string after finishing with the fallback.
879 * The variables save_p and save_inbytes store the input state
880 * for the original string while we are converting the fallback
884 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
885 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
886 outp = dest = g_malloc (outbuf_size);
888 while (!done && !have_error)
890 gsize inbytes_tmp = inbytes_remaining;
891 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
892 inbytes_remaining = inbytes_tmp;
894 if (err == (gsize) -1)
899 g_assert_not_reached();
903 gsize used = outp - dest;
906 dest = g_realloc (dest, outbuf_size);
909 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
916 /* Error converting fallback string - fatal
918 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
919 _("Cannot convert fallback '%s' to codeset '%s'"),
920 insert_str, to_codeset);
928 gunichar ch = g_utf8_get_char (p);
929 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
933 insert_str = fallback;
935 save_p = g_utf8_next_char (p);
936 save_inbytes = inbytes_remaining - (save_p - p);
938 inbytes_remaining = strlen (p);
941 /* fall thru if p is NULL */
943 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
944 _("Error during conversion: %s"),
955 g_free ((gchar *)insert_str);
957 inbytes_remaining = save_inbytes;
962 /* call g_iconv with NULL inbuf to cleanup shift state */
964 inbytes_remaining = 0;
975 close_converter (cd);
978 *bytes_written = outp - dest; /* Doesn't include '\0' */
984 if (save_p && !fallback)
985 g_free ((gchar *)insert_str);
1000 strdup_len (const gchar *string,
1002 gsize *bytes_written,
1009 if (!g_utf8_validate (string, len, NULL))
1016 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1017 _("Invalid byte sequence in conversion input"));
1022 real_len = strlen (string);
1027 while (real_len < len && string[real_len])
1032 *bytes_read = real_len;
1034 *bytes_written = real_len;
1036 return g_strndup (string, real_len);
1041 * @opsysstring: a string in the encoding of the current locale. On Windows
1042 * this means the system codepage.
1043 * @len: the length of the string, or -1 if the string is
1044 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1045 * @bytes_read: location to store the number of bytes in the
1046 * input string that were successfully converted, or %NULL.
1047 * Even if the conversion was successful, this may be
1048 * less than @len if there were partial characters
1049 * at the end of the input. If the error
1050 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1051 * stored will the byte offset after the last valid
1053 * @bytes_written: the number of bytes stored in the output buffer (not
1054 * including the terminating nul).
1055 * @error: location to store the error occuring, or %NULL to ignore
1056 * errors. Any of the errors in #GConvertError may occur.
1058 * Converts a string which is in the encoding used for strings by
1059 * the C runtime (usually the same as that used by the operating
1060 * system) in the <link linkend="setlocale">current locale</link> into a
1063 * Return value: The converted string, or %NULL on an error.
1066 g_locale_to_utf8 (const gchar *opsysstring,
1069 gsize *bytes_written,
1072 const char *charset;
1074 if (g_get_charset (&charset))
1075 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1077 return g_convert (opsysstring, len,
1078 "UTF-8", charset, bytes_read, bytes_written, error);
1082 * g_locale_from_utf8:
1083 * @utf8string: a UTF-8 encoded string
1084 * @len: the length of the string, or -1 if the string is
1085 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1086 * @bytes_read: location to store the number of bytes in the
1087 * input string that were successfully converted, or %NULL.
1088 * Even if the conversion was successful, this may be
1089 * less than @len if there were partial characters
1090 * at the end of the input. If the error
1091 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1092 * stored will the byte offset after the last valid
1094 * @bytes_written: the number of bytes stored in the output buffer (not
1095 * including the terminating nul).
1096 * @error: location to store the error occuring, or %NULL to ignore
1097 * errors. Any of the errors in #GConvertError may occur.
1099 * Converts a string from UTF-8 to the encoding used for strings by
1100 * the C runtime (usually the same as that used by the operating
1101 * system) in the <link linkend="setlocale">current locale</link>. On
1102 * Windows this means the system codepage.
1104 * Return value: The converted string, or %NULL on an error.
1107 g_locale_from_utf8 (const gchar *utf8string,
1110 gsize *bytes_written,
1113 const gchar *charset;
1115 if (g_get_charset (&charset))
1116 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1118 return g_convert (utf8string, len,
1119 charset, "UTF-8", bytes_read, bytes_written, error);
1122 #ifndef G_PLATFORM_WIN32
1124 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1126 struct _GFilenameCharsetCache {
1129 gchar **filename_charsets;
1133 filename_charset_cache_free (gpointer data)
1135 GFilenameCharsetCache *cache = data;
1136 g_free (cache->charset);
1137 g_strfreev (cache->filename_charsets);
1142 * g_get_filename_charsets:
1143 * @charsets: return location for the %NULL-terminated list of encoding names
1145 * Determines the preferred character sets used for filenames.
1146 * The first character set from the @charsets is the filename encoding, the
1147 * subsequent character sets are used when trying to generate a displayable
1148 * representation of a filename, see g_filename_display_name().
1150 * On Unix, the character sets are determined by consulting the
1151 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1152 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1153 * used in the GLib API is always UTF-8 and said environment variables
1156 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1157 * of character set names. The special token "@locale" is taken to
1158 * mean the character set for the <link linkend="setlocale">current
1159 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1160 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1161 * locale is taken as the filename encoding. If neither environment variable
1162 * is set, UTF-8 is taken as the filename encoding, but the character
1163 * set of the current locale is also put in the list of encodings.
1165 * The returned @charsets belong to GLib and must not be freed.
1167 * Note that on Unix, regardless of the locale character set or
1168 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1169 * on a system might be in any random encoding or just gibberish.
1171 * Return value: %TRUE if the filename encoding is UTF-8.
1176 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1178 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1179 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1180 const gchar *charset;
1184 cache = g_new0 (GFilenameCharsetCache, 1);
1185 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1188 g_get_charset (&charset);
1190 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1192 const gchar *new_charset;
1196 g_free (cache->charset);
1197 g_strfreev (cache->filename_charsets);
1198 cache->charset = g_strdup (charset);
1200 p = getenv ("G_FILENAME_ENCODING");
1201 if (p != NULL && p[0] != '\0')
1203 cache->filename_charsets = g_strsplit (p, ",", 0);
1204 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1206 for (i = 0; cache->filename_charsets[i]; i++)
1208 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1210 g_get_charset (&new_charset);
1211 g_free (cache->filename_charsets[i]);
1212 cache->filename_charsets[i] = g_strdup (new_charset);
1216 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1218 cache->filename_charsets = g_new0 (gchar *, 2);
1219 cache->is_utf8 = g_get_charset (&new_charset);
1220 cache->filename_charsets[0] = g_strdup (new_charset);
1224 cache->filename_charsets = g_new0 (gchar *, 3);
1225 cache->is_utf8 = TRUE;
1226 cache->filename_charsets[0] = g_strdup ("UTF-8");
1227 if (!g_get_charset (&new_charset))
1228 cache->filename_charsets[1] = g_strdup (new_charset);
1232 if (filename_charsets)
1233 *filename_charsets = (const gchar **)cache->filename_charsets;
1235 return cache->is_utf8;
1238 #else /* G_PLATFORM_WIN32 */
1241 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1243 static const gchar *charsets[] = {
1249 /* On Windows GLib pretends that the filename charset is UTF-8 */
1250 if (filename_charsets)
1251 *filename_charsets = charsets;
1257 /* Cygwin works like before */
1258 result = g_get_charset (&(charsets[0]));
1260 if (filename_charsets)
1261 *filename_charsets = charsets;
1267 #endif /* G_PLATFORM_WIN32 */
1270 get_filename_charset (const gchar **filename_charset)
1272 const gchar **charsets;
1275 is_utf8 = g_get_filename_charsets (&charsets);
1277 if (filename_charset)
1278 *filename_charset = charsets[0];
1283 /* This is called from g_thread_init(). It's used to
1284 * initialize some static data in a threadsafe way.
1287 _g_convert_thread_init (void)
1289 const gchar **dummy;
1290 (void) g_get_filename_charsets (&dummy);
1294 * g_filename_to_utf8:
1295 * @opsysstring: a string in the encoding for filenames
1296 * @len: the length of the string, or -1 if the string is
1297 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1298 * @bytes_read: location to store the number of bytes in the
1299 * input string that were successfully converted, or %NULL.
1300 * Even if the conversion was successful, this may be
1301 * less than @len if there were partial characters
1302 * at the end of the input. If the error
1303 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1304 * stored will the byte offset after the last valid
1306 * @bytes_written: the number of bytes stored in the output buffer (not
1307 * including the terminating nul).
1308 * @error: location to store the error occuring, or %NULL to ignore
1309 * errors. Any of the errors in #GConvertError may occur.
1311 * Converts a string which is in the encoding used by GLib for
1312 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1313 * for filenames; on other platforms, this function indirectly depends on
1314 * the <link linkend="setlocale">current locale</link>.
1316 * Return value: The converted string, or %NULL on an error.
1319 g_filename_to_utf8 (const gchar *opsysstring,
1322 gsize *bytes_written,
1325 const gchar *charset;
1327 if (get_filename_charset (&charset))
1328 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1330 return g_convert (opsysstring, len,
1331 "UTF-8", charset, bytes_read, bytes_written, error);
1336 #undef g_filename_to_utf8
1338 /* Binary compatibility version. Not for newly compiled code. */
1341 g_filename_to_utf8 (const gchar *opsysstring,
1344 gsize *bytes_written,
1347 const gchar *charset;
1349 if (g_get_charset (&charset))
1350 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1352 return g_convert (opsysstring, len,
1353 "UTF-8", charset, bytes_read, bytes_written, error);
1359 * g_filename_from_utf8:
1360 * @utf8string: a UTF-8 encoded string.
1361 * @len: the length of the string, or -1 if the string is
1363 * @bytes_read: location to store the number of bytes in the
1364 * input string that were successfully converted, or %NULL.
1365 * Even if the conversion was successful, this may be
1366 * less than @len if there were partial characters
1367 * at the end of the input. If the error
1368 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1369 * stored will the byte offset after the last valid
1371 * @bytes_written: the number of bytes stored in the output buffer (not
1372 * including the terminating nul).
1373 * @error: location to store the error occuring, or %NULL to ignore
1374 * errors. Any of the errors in #GConvertError may occur.
1376 * Converts a string from UTF-8 to the encoding GLib uses for
1377 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1378 * on other platforms, this function indirectly depends on the
1379 * <link linkend="setlocale">current locale</link>.
1381 * Return value: The converted string, or %NULL on an error.
1384 g_filename_from_utf8 (const gchar *utf8string,
1387 gsize *bytes_written,
1390 const gchar *charset;
1392 if (get_filename_charset (&charset))
1393 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1395 return g_convert (utf8string, len,
1396 charset, "UTF-8", bytes_read, bytes_written, error);
1401 #undef g_filename_from_utf8
1403 /* Binary compatibility version. Not for newly compiled code. */
1406 g_filename_from_utf8 (const gchar *utf8string,
1409 gsize *bytes_written,
1412 const gchar *charset;
1414 if (g_get_charset (&charset))
1415 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1417 return g_convert (utf8string, len,
1418 charset, "UTF-8", bytes_read, bytes_written, error);
1423 /* Test of haystack has the needle prefix, comparing case
1424 * insensitive. haystack may be UTF-8, but needle must
1425 * contain only ascii. */
1427 has_case_prefix (const gchar *haystack, const gchar *needle)
1431 /* Eat one character at a time. */
1436 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1446 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1447 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1448 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1449 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1450 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1451 } UnsafeCharacterSet;
1453 static const guchar acceptable[96] = {
1454 /* A table of the ASCII chars from space (32) to DEL (127) */
1455 /* ! " # $ % & ' ( ) * + , - . / */
1456 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1457 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1458 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1459 /* @ A B C D E F G H I J K L M N O */
1460 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1461 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1462 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1463 /* ` a b c d e f g h i j k l m n o */
1464 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1465 /* p q r s t u v w x y z { | } ~ DEL */
1466 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1469 static const gchar hex[16] = "0123456789ABCDEF";
1471 /* Note: This escape function works on file: URIs, but if you want to
1472 * escape something else, please read RFC-2396 */
1474 g_escape_uri_string (const gchar *string,
1475 UnsafeCharacterSet mask)
1477 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1484 UnsafeCharacterSet use_mask;
1486 g_return_val_if_fail (mask == UNSAFE_ALL
1487 || mask == UNSAFE_ALLOW_PLUS
1488 || mask == UNSAFE_PATH
1489 || mask == UNSAFE_HOST
1490 || mask == UNSAFE_SLASHES, NULL);
1494 for (p = string; *p != '\0'; p++)
1497 if (!ACCEPTABLE (c))
1501 result = g_malloc (p - string + unacceptable * 2 + 1);
1504 for (q = result, p = string; *p != '\0'; p++)
1508 if (!ACCEPTABLE (c))
1510 *q++ = '%'; /* means hex coming */
1525 g_escape_file_uri (const gchar *hostname,
1526 const gchar *pathname)
1528 char *escaped_hostname = NULL;
1533 char *p, *backslash;
1535 /* Turn backslashes into forward slashes. That's what Netscape
1536 * does, and they are actually more or less equivalent in Windows.
1539 pathname = g_strdup (pathname);
1540 p = (char *) pathname;
1542 while ((backslash = strchr (p, '\\')) != NULL)
1549 if (hostname && *hostname != '\0')
1551 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1554 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1556 res = g_strconcat ("file://",
1557 (escaped_hostname) ? escaped_hostname : "",
1558 (*escaped_path != '/') ? "/" : "",
1563 g_free ((char *) pathname);
1566 g_free (escaped_hostname);
1567 g_free (escaped_path);
1573 unescape_character (const char *scanner)
1578 first_digit = g_ascii_xdigit_value (scanner[0]);
1579 if (first_digit < 0)
1582 second_digit = g_ascii_xdigit_value (scanner[1]);
1583 if (second_digit < 0)
1586 return (first_digit << 4) | second_digit;
1590 g_unescape_uri_string (const char *escaped,
1592 const char *illegal_escaped_characters,
1593 gboolean ascii_must_not_be_escaped)
1595 const gchar *in, *in_end;
1596 gchar *out, *result;
1599 if (escaped == NULL)
1603 len = strlen (escaped);
1605 result = g_malloc (len + 1);
1608 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1614 /* catch partial escape sequences past the end of the substring */
1615 if (in + 3 > in_end)
1618 c = unescape_character (in + 1);
1620 /* catch bad escape sequences and NUL characters */
1624 /* catch escaped ASCII */
1625 if (ascii_must_not_be_escaped && c <= 0x7F)
1628 /* catch other illegal escaped characters */
1629 if (strchr (illegal_escaped_characters, c) != NULL)
1638 g_assert (out - result <= len);
1651 is_asciialphanum (gunichar c)
1653 return c <= 0x7F && g_ascii_isalnum (c);
1657 is_asciialpha (gunichar c)
1659 return c <= 0x7F && g_ascii_isalpha (c);
1662 /* allows an empty string */
1664 hostname_validate (const char *hostname)
1667 gunichar c, first_char, last_char;
1674 /* read in a label */
1675 c = g_utf8_get_char (p);
1676 p = g_utf8_next_char (p);
1677 if (!is_asciialphanum (c))
1683 c = g_utf8_get_char (p);
1684 p = g_utf8_next_char (p);
1686 while (is_asciialphanum (c) || c == '-');
1687 if (last_char == '-')
1690 /* if that was the last label, check that it was a toplabel */
1691 if (c == '\0' || (c == '.' && *p == '\0'))
1692 return is_asciialpha (first_char);
1699 * g_filename_from_uri:
1700 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1701 * @hostname: Location to store hostname for the URI, or %NULL.
1702 * If there is no hostname in the URI, %NULL will be
1703 * stored in this location.
1704 * @error: location to store the error occuring, or %NULL to ignore
1705 * errors. Any of the errors in #GConvertError may occur.
1707 * Converts an escaped ASCII-encoded URI to a local filename in the
1708 * encoding used for filenames.
1710 * Return value: a newly-allocated string holding the resulting
1711 * filename, or %NULL on an error.
1714 g_filename_from_uri (const gchar *uri,
1718 const char *path_part;
1719 const char *host_part;
1720 char *unescaped_hostname;
1731 if (!has_case_prefix (uri, "file:/"))
1733 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1734 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1739 path_part = uri + strlen ("file:");
1741 if (strchr (path_part, '#') != NULL)
1743 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1744 _("The local file URI '%s' may not include a '#'"),
1749 if (has_case_prefix (path_part, "///"))
1751 else if (has_case_prefix (path_part, "//"))
1754 host_part = path_part;
1756 path_part = strchr (path_part, '/');
1758 if (path_part == NULL)
1760 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1761 _("The URI '%s' is invalid"),
1766 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1768 if (unescaped_hostname == NULL ||
1769 !hostname_validate (unescaped_hostname))
1771 g_free (unescaped_hostname);
1772 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1773 _("The hostname of the URI '%s' is invalid"),
1779 *hostname = unescaped_hostname;
1781 g_free (unescaped_hostname);
1784 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1786 if (filename == NULL)
1788 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1789 _("The URI '%s' contains invalidly escaped characters"),
1796 /* Drop localhost */
1797 if (hostname && *hostname != NULL &&
1798 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1804 /* Turn slashes into backslashes, because that's the canonical spelling */
1806 while ((slash = strchr (p, '/')) != NULL)
1812 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1813 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1814 * the filename from the drive letter.
1816 if (g_ascii_isalpha (filename[1]))
1818 if (filename[2] == ':')
1820 else if (filename[2] == '|')
1828 result = g_strdup (filename + offs);
1836 #undef g_filename_from_uri
1839 g_filename_from_uri (const gchar *uri,
1843 gchar *utf8_filename;
1844 gchar *retval = NULL;
1846 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1849 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1850 g_free (utf8_filename);
1858 * g_filename_to_uri:
1859 * @filename: an absolute filename specified in the GLib file name encoding,
1860 * which is the on-disk file name bytes on Unix, and UTF-8 on
1862 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1863 * @error: location to store the error occuring, or %NULL to ignore
1864 * errors. Any of the errors in #GConvertError may occur.
1866 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1867 * component following Section 3.3. of RFC 2396.
1869 * Return value: a newly-allocated string holding the resulting
1870 * URI, or %NULL on an error.
1873 g_filename_to_uri (const gchar *filename,
1874 const gchar *hostname,
1879 g_return_val_if_fail (filename != NULL, NULL);
1881 if (!g_path_is_absolute (filename))
1883 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1884 _("The pathname '%s' is not an absolute path"),
1890 !(g_utf8_validate (hostname, -1, NULL)
1891 && hostname_validate (hostname)))
1893 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1894 _("Invalid hostname"));
1899 /* Don't use localhost unnecessarily */
1900 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1904 escaped_uri = g_escape_file_uri (hostname, filename);
1911 #undef g_filename_to_uri
1914 g_filename_to_uri (const gchar *filename,
1915 const gchar *hostname,
1918 gchar *utf8_filename;
1919 gchar *retval = NULL;
1921 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1925 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1926 g_free (utf8_filename);
1935 * g_uri_list_extract_uris:
1936 * @uri_list: an URI list
1938 * Splits an URI list conforming to the text/uri-list
1939 * mime type defined in RFC 2483 into individual URIs,
1940 * discarding any comments. The URIs are not validated.
1942 * Returns: a newly allocated %NULL-terminated list of
1943 * strings holding the individual URIs. The array should
1944 * be freed with g_strfreev().
1949 g_uri_list_extract_uris (const gchar *uri_list)
1960 /* We don't actually try to validate the URI according to RFC
1961 * 2396, or even check for allowed characters - we just ignore
1962 * comments and trim whitespace off the ends. We also
1963 * allow LF delimination as well as the specified CRLF.
1965 * We do allow comments like specified in RFC 2483.
1971 while (g_ascii_isspace (*p))
1975 while (*q && (*q != '\n') && (*q != '\r'))
1981 while (q > p && g_ascii_isspace (*q))
1986 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1991 p = strchr (p, '\n');
1996 result = g_new (gchar *, n_uris + 1);
1998 result[n_uris--] = NULL;
1999 for (u = uris; u; u = u->next)
2000 result[n_uris--] = u->data;
2002 g_slist_free (uris);
2008 * g_filename_display_basename:
2009 * @filename: an absolute pathname in the GLib file name encoding
2011 * Returns the display basename for the particular filename, guaranteed
2012 * to be valid UTF-8. The display name might not be identical to the filename,
2013 * for instance there might be problems converting it to UTF-8, and some files
2014 * can be translated in the display.
2016 * If GLib can not make sense of the encoding of @filename, as a last resort it
2017 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2018 * You can search the result for the UTF-8 encoding of this character (which is
2019 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2022 * You must pass the whole absolute pathname to this functions so that
2023 * translation of well known locations can be done.
2025 * This function is preferred over g_filename_display_name() if you know the
2026 * whole path, as it allows translation.
2028 * Return value: a newly allocated string containing
2029 * a rendition of the basename of the filename in valid UTF-8
2034 g_filename_display_basename (const gchar *filename)
2039 g_return_val_if_fail (filename != NULL, NULL);
2041 basename = g_path_get_basename (filename);
2042 display_name = g_filename_display_name (basename);
2044 return display_name;
2048 * g_filename_display_name:
2049 * @filename: a pathname hopefully in the GLib file name encoding
2051 * Converts a filename into a valid UTF-8 string. The conversion is
2052 * not necessarily reversible, so you should keep the original around
2053 * and use the return value of this function only for display purposes.
2054 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2055 * even if the filename actually isn't in the GLib file name encoding.
2057 * If GLib can not make sense of the encoding of @filename, as a last resort it
2058 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2059 * You can search the result for the UTF-8 encoding of this character (which is
2060 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2063 * If you know the whole pathname of the file you should use
2064 * g_filename_display_basename(), since that allows location-based
2065 * translation of filenames.
2067 * Return value: a newly allocated string containing
2068 * a rendition of the filename in valid UTF-8
2073 g_filename_display_name (const gchar *filename)
2076 const gchar **charsets;
2077 gchar *display_name = NULL;
2080 is_utf8 = g_get_filename_charsets (&charsets);
2084 if (g_utf8_validate (filename, -1, NULL))
2085 display_name = g_strdup (filename);
2090 /* Try to convert from the filename charsets to UTF-8.
2091 * Skip the first charset if it is UTF-8.
2093 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2095 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2103 /* if all conversions failed, we replace invalid UTF-8
2104 * by a question mark
2107 display_name = _g_utf8_make_valid (filename);
2109 return display_name;
2112 #define __G_CONVERT_C__
2113 #include "galiasdef.c"