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 "gthreadinit.h"
35 #ifdef G_PLATFORM_WIN32
43 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
44 #error GNU libiconv in use but included iconv.h not from libiconv
46 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
47 #error GNU libiconv not in use but included iconv.h is from libiconv
51 g_convert_error_quark (void)
55 quark = g_quark_from_static_string ("g_convert_error");
61 try_conversion (const char *to_codeset,
62 const char *from_codeset,
65 *cd = iconv_open (to_codeset, from_codeset);
67 if (*cd == (iconv_t)-1 && errno == EINVAL)
74 try_to_aliases (const char **to_aliases,
75 const char *from_codeset,
80 const char **p = to_aliases;
83 if (try_conversion (*p, from_codeset, cd))
93 extern const char **_g_charset_get_aliases (const char *canonical_name);
97 * @to_codeset: destination codeset
98 * @from_codeset: source codeset
100 * Same as the standard UNIX routine <function>iconv_open()</function>, but
101 * may be implemented via libiconv on UNIX flavors that lack
102 * a native implementation.
104 * GLib provides g_convert() and g_locale_to_utf8() which are likely
105 * more convenient than the raw iconv wrappers.
107 * Return value: a "conversion descriptor", or (GIConv)-1 if
108 * opening the converter failed.
111 g_iconv_open (const gchar *to_codeset,
112 const gchar *from_codeset)
116 if (!try_conversion (to_codeset, from_codeset, &cd))
118 const char **to_aliases = _g_charset_get_aliases (to_codeset);
119 const char **from_aliases = _g_charset_get_aliases (from_codeset);
123 const char **p = from_aliases;
126 if (try_conversion (to_codeset, *p, &cd))
129 if (try_to_aliases (to_aliases, *p, &cd))
136 if (try_to_aliases (to_aliases, from_codeset, &cd))
141 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
146 * @converter: conversion descriptor from g_iconv_open()
147 * @inbuf: bytes to convert
148 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
149 * @outbuf: converted output bytes
150 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
152 * Same as the standard UNIX routine <function>iconv()</function>, but
153 * may be implemented via libiconv on UNIX flavors that lack
154 * a native implementation.
156 * GLib provides g_convert() and g_locale_to_utf8() which are likely
157 * more convenient than the raw iconv wrappers.
159 * Return value: count of non-reversible conversions, or -1 on error
162 g_iconv (GIConv converter,
166 gsize *outbytes_left)
168 iconv_t cd = (iconv_t)converter;
170 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
175 * @converter: a conversion descriptor from g_iconv_open()
177 * Same as the standard UNIX routine <function>iconv_close()</function>, but
178 * may be implemented via libiconv on UNIX flavors that lack
179 * a native implementation. Should be called to clean up
180 * the conversion descriptor from g_iconv_open() when
181 * you are done converting things.
183 * GLib provides g_convert() and g_locale_to_utf8() which are likely
184 * more convenient than the raw iconv wrappers.
186 * Return value: -1 on error, 0 on success
189 g_iconv_close (GIConv converter)
191 iconv_t cd = (iconv_t)converter;
193 return iconv_close (cd);
197 #define ICONV_CACHE_SIZE (16)
199 struct _iconv_cache_bucket {
206 static GList *iconv_cache_list;
207 static GHashTable *iconv_cache;
208 static GHashTable *iconv_open_hash;
209 static guint iconv_cache_size = 0;
210 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
212 /* caller *must* hold the iconv_cache_lock */
214 iconv_cache_init (void)
216 static gboolean initialized = FALSE;
221 iconv_cache_list = NULL;
222 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
223 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
230 * iconv_cache_bucket_new:
232 * @cd: iconv descriptor
234 * Creates a new cache bucket, inserts it into the cache and
235 * increments the cache size.
237 * Returns a pointer to the newly allocated cache bucket.
239 struct _iconv_cache_bucket *
240 iconv_cache_bucket_new (const gchar *key, GIConv cd)
242 struct _iconv_cache_bucket *bucket;
244 bucket = g_new (struct _iconv_cache_bucket, 1);
245 bucket->key = g_strdup (key);
246 bucket->refcount = 1;
250 g_hash_table_insert (iconv_cache, bucket->key, bucket);
252 /* FIXME: if we sorted the list so items with few refcounts were
253 first, then we could expire them faster in iconv_cache_expire_unused () */
254 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
263 * iconv_cache_bucket_expire:
264 * @node: cache bucket's node
265 * @bucket: cache bucket
267 * Expires a single cache bucket @bucket. This should only ever be
268 * called on a bucket that currently has no used iconv descriptors
271 * @node is not a required argument. If @node is not supplied, we
272 * search for it ourselves.
275 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
277 g_hash_table_remove (iconv_cache, bucket->key);
280 node = g_list_find (iconv_cache_list, bucket);
282 g_assert (node != NULL);
286 node->prev->next = node->next;
288 node->next->prev = node->prev;
292 iconv_cache_list = node->next;
294 node->next->prev = NULL;
297 g_list_free_1 (node);
299 g_free (bucket->key);
300 g_iconv_close (bucket->cd);
308 * iconv_cache_expire_unused:
310 * Expires as many unused cache buckets as it needs to in order to get
311 * the total number of buckets < ICONV_CACHE_SIZE.
314 iconv_cache_expire_unused (void)
316 struct _iconv_cache_bucket *bucket;
319 node = iconv_cache_list;
320 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
325 if (bucket->refcount == 0)
326 iconv_cache_bucket_expire (node, bucket);
333 open_converter (const gchar *to_codeset,
334 const gchar *from_codeset,
337 struct _iconv_cache_bucket *bucket;
342 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
343 _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
345 G_LOCK (iconv_cache_lock);
347 /* make sure the cache has been initialized */
350 bucket = g_hash_table_lookup (iconv_cache, key);
355 cd = g_iconv_open (to_codeset, from_codeset);
356 if (cd == (GIConv) -1)
361 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
362 * NULL for anything but inbuf; work around that. (NULL outbuf
363 * or NULL *outbuf is allowed by Unix98.)
365 gsize inbytes_left = 0;
366 gchar *outbuf = NULL;
367 gsize outbytes_left = 0;
372 /* reset the descriptor */
373 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
380 cd = g_iconv_open (to_codeset, from_codeset);
381 if (cd == (GIConv) -1)
384 iconv_cache_expire_unused ();
386 bucket = iconv_cache_bucket_new (key, cd);
389 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
391 G_UNLOCK (iconv_cache_lock);
397 G_UNLOCK (iconv_cache_lock);
399 /* Something went wrong. */
401 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
402 _("Conversion from character set '%s' to '%s' is not supported"),
403 from_codeset, to_codeset);
405 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
406 _("Could not open converter from '%s' to '%s': %s"),
407 from_codeset, to_codeset, g_strerror (errno));
413 close_converter (GIConv converter)
415 struct _iconv_cache_bucket *bucket;
421 if (cd == (GIConv) -1)
424 G_LOCK (iconv_cache_lock);
426 key = g_hash_table_lookup (iconv_open_hash, cd);
429 g_hash_table_remove (iconv_open_hash, cd);
431 bucket = g_hash_table_lookup (iconv_cache, key);
436 if (cd == bucket->cd)
437 bucket->used = FALSE;
441 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
443 /* expire this cache bucket */
444 iconv_cache_bucket_expire (NULL, bucket);
449 G_UNLOCK (iconv_cache_lock);
451 g_warning ("This iconv context wasn't opened using open_converter");
453 return g_iconv_close (converter);
456 G_UNLOCK (iconv_cache_lock);
464 * @str: the string to convert
465 * @len: the length of the string
466 * @to_codeset: name of character set into which to convert @str
467 * @from_codeset: character set of @str.
468 * @bytes_read: location to store the number of bytes in the
469 * input string that were successfully converted, or %NULL.
470 * Even if the conversion was successful, this may be
471 * less than @len if there were partial characters
472 * at the end of the input. If the error
473 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
474 * stored will the byte offset after the last valid
476 * @bytes_written: the number of bytes stored in the output buffer (not
477 * including the terminating nul).
478 * @error: location to store the error occuring, or %NULL to ignore
479 * errors. Any of the errors in #GConvertError may occur.
481 * Converts a string from one character set to another.
483 * Return value: If the conversion was successful, a newly allocated
484 * nul-terminated string, which must be freed with
485 * g_free(). Otherwise %NULL and @error will be set.
488 g_convert (const gchar *str,
490 const gchar *to_codeset,
491 const gchar *from_codeset,
493 gsize *bytes_written,
499 g_return_val_if_fail (str != NULL, NULL);
500 g_return_val_if_fail (to_codeset != NULL, NULL);
501 g_return_val_if_fail (from_codeset != NULL, NULL);
503 cd = open_converter (to_codeset, from_codeset, error);
505 if (cd == (GIConv) -1)
516 res = g_convert_with_iconv (str, len, cd,
517 bytes_read, bytes_written,
520 close_converter (cd);
526 * g_convert_with_iconv:
527 * @str: the string to convert
528 * @len: the length of the string
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 * Return value: If the conversion was successful, a newly allocated
546 * nul-terminated string, which must be freed with
547 * g_free(). Otherwise %NULL and @error will be set.
550 g_convert_with_iconv (const gchar *str,
554 gsize *bytes_written,
560 gsize inbytes_remaining;
561 gsize outbytes_remaining;
564 gboolean have_error = FALSE;
566 g_return_val_if_fail (str != NULL, NULL);
567 g_return_val_if_fail (converter != (GIConv) -1, NULL);
573 inbytes_remaining = len;
574 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
576 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
577 outp = dest = g_malloc (outbuf_size);
581 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
583 if (err == (size_t) -1)
588 /* Incomplete text, do not report an error */
592 size_t used = outp - dest;
595 dest = g_realloc (dest, outbuf_size);
598 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
603 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
604 _("Invalid byte sequence in conversion input"));
608 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
609 _("Error during conversion: %s"),
619 *bytes_read = p - str;
622 if ((p - str) != len)
626 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
627 _("Partial character sequence at end of input"));
634 *bytes_written = outp - dest; /* Doesn't include '\0' */
646 * g_convert_with_fallback:
647 * @str: the string to convert
648 * @len: the length of the string
649 * @to_codeset: name of character set into which to convert @str
650 * @from_codeset: character set of @str.
651 * @fallback: UTF-8 string to use in place of character not
652 * present in the target encoding. (This must be
653 * in the target encoding), if %NULL, characters
654 * not in the target encoding will be represented
655 * as Unicode escapes \uxxxx or \Uxxxxyyyy.
656 * @bytes_read: location to store the number of bytes in the
657 * input string that were successfully converted, or %NULL.
658 * Even if the conversion was successful, this may be
659 * less than @len if there were partial characters
660 * at the end of the input.
661 * @bytes_written: the number of bytes stored in the output buffer (not
662 * including the terminating nul).
663 * @error: location to store the error occuring, or %NULL to ignore
664 * errors. Any of the errors in #GConvertError may occur.
666 * Converts a string from one character set to another, possibly
667 * including fallback sequences for characters not representable
668 * in the output. Note that it is not guaranteed that the specification
669 * for the fallback sequences in @fallback will be honored. Some
670 * systems may do a approximate conversion from @from_codeset
671 * to @to_codeset in their <function>iconv()</function> functions,
672 * in which case GLib will simply return that approximate conversion.
674 * Return value: If the conversion was successful, a newly allocated
675 * nul-terminated string, which must be freed with
676 * g_free(). Otherwise %NULL and @error will be set.
679 g_convert_with_fallback (const gchar *str,
681 const gchar *to_codeset,
682 const gchar *from_codeset,
685 gsize *bytes_written,
691 const gchar *insert_str = NULL;
693 gsize inbytes_remaining;
694 const gchar *save_p = NULL;
695 gsize save_inbytes = 0;
696 gsize outbytes_remaining;
700 gboolean have_error = FALSE;
701 gboolean done = FALSE;
703 GError *local_error = NULL;
705 g_return_val_if_fail (str != NULL, NULL);
706 g_return_val_if_fail (to_codeset != NULL, NULL);
707 g_return_val_if_fail (from_codeset != NULL, NULL);
712 /* Try an exact conversion; we only proceed if this fails
713 * due to an illegal sequence in the input string.
715 dest = g_convert (str, len, to_codeset, from_codeset,
716 bytes_read, bytes_written, &local_error);
720 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
722 g_propagate_error (error, local_error);
726 g_error_free (local_error);
730 /* No go; to proceed, we need a converter from "UTF-8" to
731 * to_codeset, and the string as UTF-8.
733 cd = open_converter (to_codeset, "UTF-8", error);
734 if (cd == (GIConv) -1)
745 utf8 = g_convert (str, len, "UTF-8", from_codeset,
746 bytes_read, &inbytes_remaining, error);
749 close_converter (cd);
755 /* Now the heart of the code. We loop through the UTF-8 string, and
756 * whenever we hit an offending character, we form fallback, convert
757 * the fallback to the target codeset, and then go back to
758 * converting the original string after finishing with the fallback.
760 * The variables save_p and save_inbytes store the input state
761 * for the original string while we are converting the fallback
765 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
766 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
767 outp = dest = g_malloc (outbuf_size);
769 while (!done && !have_error)
771 size_t inbytes_tmp = inbytes_remaining;
772 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
773 inbytes_remaining = inbytes_tmp;
775 if (err == (size_t) -1)
780 g_assert_not_reached();
784 size_t used = outp - dest;
787 dest = g_realloc (dest, outbuf_size);
790 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
797 /* Error converting fallback string - fatal
799 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
800 _("Cannot convert fallback '%s' to codeset '%s'"),
801 insert_str, to_codeset);
809 gunichar ch = g_utf8_get_char (p);
810 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
814 insert_str = fallback;
816 save_p = g_utf8_next_char (p);
817 save_inbytes = inbytes_remaining - (save_p - p);
819 inbytes_remaining = strlen (p);
823 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
824 _("Error during conversion: %s"),
835 g_free ((gchar *)insert_str);
837 inbytes_remaining = save_inbytes;
849 close_converter (cd);
852 *bytes_written = outp - dest; /* Doesn't include '\0' */
858 if (save_p && !fallback)
859 g_free ((gchar *)insert_str);
873 #ifndef G_PLATFORM_WIN32
876 strdup_len (const gchar *string,
878 gsize *bytes_written,
885 if (!g_utf8_validate (string, len, NULL))
892 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
893 _("Invalid byte sequence in conversion input"));
898 real_len = strlen (string);
903 while (real_len < len && string[real_len])
908 *bytes_read = real_len;
910 *bytes_written = real_len;
912 return g_strndup (string, real_len);
919 * @opsysstring: a string in the encoding of the current locale
920 * @len: the length of the string, or -1 if the string is
922 * @bytes_read: location to store the number of bytes in the
923 * input string that were successfully converted, or %NULL.
924 * Even if the conversion was successful, this may be
925 * less than @len if there were partial characters
926 * at the end of the input. If the error
927 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
928 * stored will the byte offset after the last valid
930 * @bytes_written: the number of bytes stored in the output buffer (not
931 * including the terminating nul).
932 * @error: location to store the error occuring, or %NULL to ignore
933 * errors. Any of the errors in #GConvertError may occur.
935 * Converts a string which is in the encoding used for strings by
936 * the C runtime (usually the same as that used by the operating
937 * system) in the current locale into a UTF-8 string.
939 * Return value: The converted string, or %NULL on an error.
942 g_locale_to_utf8 (const gchar *opsysstring,
945 gsize *bytes_written,
948 #ifdef G_PLATFORM_WIN32
950 gint i, clen, total_len, wclen, first;
956 len = strlen (opsysstring);
958 wcs = g_new (wchar_t, len);
959 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
963 for (i = 0; i < wclen; i++)
971 else if (wc < 0x10000)
973 else if (wc < 0x200000)
975 else if (wc < 0x4000000)
981 result = g_malloc (total_len + 1);
985 for (i = 0; i < wclen; i++)
999 else if (wc < 0x10000)
1004 else if (wc < 0x200000)
1009 else if (wc < 0x4000000)
1023 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1024 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1025 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1026 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1027 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1028 case 1: bp[0] = wc | first;
1040 *bytes_written = total_len;
1044 #else /* !G_PLATFORM_WIN32 */
1046 const char *charset;
1048 if (g_get_charset (&charset))
1049 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1051 return g_convert (opsysstring, len,
1052 "UTF-8", charset, bytes_read, bytes_written, error);
1054 #endif /* !G_PLATFORM_WIN32 */
1058 * g_locale_from_utf8:
1059 * @utf8string: a UTF-8 encoded string
1060 * @len: the length of the string, or -1 if the string is
1062 * @bytes_read: location to store the number of bytes in the
1063 * input string that were successfully converted, or %NULL.
1064 * Even if the conversion was successful, this may be
1065 * less than @len if there were partial characters
1066 * at the end of the input. If the error
1067 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1068 * stored will the byte offset after the last valid
1070 * @bytes_written: the number of bytes stored in the output buffer (not
1071 * including the terminating nul).
1072 * @error: location to store the error occuring, or %NULL to ignore
1073 * errors. Any of the errors in #GConvertError may occur.
1075 * Converts a string from UTF-8 to the encoding used for strings by
1076 * the C runtime (usually the same as that used by the operating
1077 * system) in the current locale.
1079 * Return value: The converted string, or %NULL on an error.
1082 g_locale_from_utf8 (const gchar *utf8string,
1085 gsize *bytes_written,
1088 #ifdef G_PLATFORM_WIN32
1090 gint i, mask, clen, mblen;
1093 guchar *cp, *end, c;
1097 len = strlen (utf8string);
1099 /* First convert to wide chars */
1100 cp = (guchar *) utf8string;
1103 wcs = g_new (wchar_t, len + 1);
1115 else if ((c & 0xe0) == 0xc0)
1120 else if ((c & 0xf0) == 0xe0)
1125 else if ((c & 0xf8) == 0xf0)
1130 else if ((c & 0xfc) == 0xf8)
1135 else if ((c & 0xfc) == 0xfc)
1146 if (cp + clen > end)
1152 *wcp = (cp[0] & mask);
1153 for (i = 1; i < clen; i++)
1155 if ((cp[i] & 0xc0) != 0x80)
1161 *wcp |= (cp[i] & 0x3f);
1174 /* n is the number of wide chars constructed */
1176 /* Convert to a string in the current ANSI codepage */
1178 result = g_new (gchar, 3 * n + 1);
1179 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1186 *bytes_written = mblen;
1190 #else /* !G_PLATFORM_WIN32 */
1192 const gchar *charset;
1194 if (g_get_charset (&charset))
1195 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1197 return g_convert (utf8string, len,
1198 charset, "UTF-8", bytes_read, bytes_written, error);
1200 #endif /* !G_PLATFORM_WIN32 */
1203 #ifndef G_PLATFORM_WIN32
1205 have_broken_filenames (void)
1207 static gboolean initialized = FALSE;
1208 static gboolean broken;
1213 broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1219 #endif /* !G_PLATFORM_WIN32 */
1221 /* This is called from g_thread_init(). It's used to
1222 * initialize some static data in a threadsafe way.
1225 _g_convert_thread_init (void)
1227 #ifndef G_PLATFORM_WIN32
1228 (void)have_broken_filenames ();
1229 #endif /* !G_PLATFORM_WIN32 */
1233 * g_filename_to_utf8:
1234 * @opsysstring: a string in the encoding for filenames
1235 * @len: the length of the string, or -1 if the string is
1237 * @bytes_read: location to store the number of bytes in the
1238 * input string that were successfully converted, or %NULL.
1239 * Even if the conversion was successful, this may be
1240 * less than @len if there were partial characters
1241 * at the end of the input. If the error
1242 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1243 * stored will the byte offset after the last valid
1245 * @bytes_written: the number of bytes stored in the output buffer (not
1246 * including the terminating nul).
1247 * @error: location to store the error occuring, or %NULL to ignore
1248 * errors. Any of the errors in #GConvertError may occur.
1250 * Converts a string which is in the encoding used for filenames
1251 * into a UTF-8 string.
1253 * Return value: The converted string, or %NULL on an error.
1256 g_filename_to_utf8 (const gchar *opsysstring,
1259 gsize *bytes_written,
1262 #ifdef G_PLATFORM_WIN32
1263 return g_locale_to_utf8 (opsysstring, len,
1264 bytes_read, bytes_written,
1266 #else /* !G_PLATFORM_WIN32 */
1268 if (have_broken_filenames ())
1269 return g_locale_to_utf8 (opsysstring, len,
1270 bytes_read, bytes_written,
1273 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1274 #endif /* !G_PLATFORM_WIN32 */
1278 * g_filename_from_utf8:
1279 * @utf8string: a UTF-8 encoded string.
1280 * @len: the length of the string, or -1 if the string is
1282 * @bytes_read: location to store the number of bytes in the
1283 * input string that were successfully converted, or %NULL.
1284 * Even if the conversion was successful, this may be
1285 * less than @len if there were partial characters
1286 * at the end of the input. If the error
1287 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1288 * stored will the byte offset after the last valid
1290 * @bytes_written: the number of bytes stored in the output buffer (not
1291 * including the terminating nul).
1292 * @error: location to store the error occuring, or %NULL to ignore
1293 * errors. Any of the errors in #GConvertError may occur.
1295 * Converts a string from UTF-8 to the encoding used for filenames.
1297 * Return value: The converted string, or %NULL on an error.
1300 g_filename_from_utf8 (const gchar *utf8string,
1303 gsize *bytes_written,
1306 #ifdef G_PLATFORM_WIN32
1307 return g_locale_from_utf8 (utf8string, len,
1308 bytes_read, bytes_written,
1310 #else /* !G_PLATFORM_WIN32 */
1311 if (have_broken_filenames ())
1312 return g_locale_from_utf8 (utf8string, len,
1313 bytes_read, bytes_written,
1316 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1317 #endif /* !G_PLATFORM_WIN32 */
1320 /* Test of haystack has the needle prefix, comparing case
1321 * insensitive. haystack may be UTF-8, but needle must
1322 * contain only ascii. */
1324 has_case_prefix (const gchar *haystack, const gchar *needle)
1328 /* Eat one character at a time. */
1333 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1343 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1344 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1345 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1346 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1347 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1348 } UnsafeCharacterSet;
1350 static const guchar acceptable[96] = {
1351 /* A table of the ASCII chars from space (32) to DEL (127) */
1352 /* ! " # $ % & ' ( ) * + , - . / */
1353 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1354 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1355 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1356 /* @ A B C D E F G H I J K L M N O */
1357 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1358 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1359 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1360 /* ` a b c d e f g h i j k l m n o */
1361 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1362 /* p q r s t u v w x y z { | } ~ DEL */
1363 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1366 static const gchar hex[16] = "0123456789ABCDEF";
1368 /* Note: This escape function works on file: URIs, but if you want to
1369 * escape something else, please read RFC-2396 */
1371 g_escape_uri_string (const gchar *string,
1372 UnsafeCharacterSet mask)
1374 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1381 UnsafeCharacterSet use_mask;
1383 g_return_val_if_fail (mask == UNSAFE_ALL
1384 || mask == UNSAFE_ALLOW_PLUS
1385 || mask == UNSAFE_PATH
1386 || mask == UNSAFE_HOST
1387 || mask == UNSAFE_SLASHES, NULL);
1391 for (p = string; *p != '\0'; p++)
1394 if (!ACCEPTABLE (c))
1398 result = g_malloc (p - string + unacceptable * 2 + 1);
1401 for (q = result, p = string; *p != '\0'; p++)
1405 if (!ACCEPTABLE (c))
1407 *q++ = '%'; /* means hex coming */
1422 g_escape_file_uri (const gchar *hostname,
1423 const gchar *pathname)
1425 char *escaped_hostname = NULL;
1430 char *p, *backslash;
1432 /* Turn backslashes into forward slashes. That's what Netscape
1433 * does, and they are actually more or less equivalent in Windows.
1436 pathname = g_strdup (pathname);
1437 p = (char *) pathname;
1439 while ((backslash = strchr (p, '\\')) != NULL)
1446 if (hostname && *hostname != '\0')
1448 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1451 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1453 res = g_strconcat ("file://",
1454 (escaped_hostname) ? escaped_hostname : "",
1455 (*escaped_path != '/') ? "/" : "",
1460 g_free ((char *) pathname);
1463 g_free (escaped_hostname);
1464 g_free (escaped_path);
1470 unescape_character (const char *scanner)
1475 first_digit = g_ascii_xdigit_value (scanner[0]);
1476 if (first_digit < 0)
1479 second_digit = g_ascii_xdigit_value (scanner[1]);
1480 if (second_digit < 0)
1483 return (first_digit << 4) | second_digit;
1487 g_unescape_uri_string (const char *escaped,
1489 const char *illegal_escaped_characters,
1490 gboolean ascii_must_not_be_escaped)
1492 const gchar *in, *in_end;
1493 gchar *out, *result;
1496 if (escaped == NULL)
1500 len = strlen (escaped);
1502 result = g_malloc (len + 1);
1505 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1511 /* catch partial escape sequences past the end of the substring */
1512 if (in + 3 > in_end)
1515 c = unescape_character (in + 1);
1517 /* catch bad escape sequences and NUL characters */
1521 /* catch escaped ASCII */
1522 if (ascii_must_not_be_escaped && c <= 0x7F)
1525 /* catch other illegal escaped characters */
1526 if (strchr (illegal_escaped_characters, c) != NULL)
1535 g_assert (out - result <= len);
1538 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1548 is_escalphanum (gunichar c)
1550 return c > 0x7F || g_ascii_isalnum (c);
1554 is_escalpha (gunichar c)
1556 return c > 0x7F || g_ascii_isalpha (c);
1559 /* allows an empty string */
1561 hostname_validate (const char *hostname)
1564 gunichar c, first_char, last_char;
1571 /* read in a label */
1572 c = g_utf8_get_char (p);
1573 p = g_utf8_next_char (p);
1574 if (!is_escalphanum (c))
1580 c = g_utf8_get_char (p);
1581 p = g_utf8_next_char (p);
1583 while (is_escalphanum (c) || c == '-');
1584 if (last_char == '-')
1587 /* if that was the last label, check that it was a toplabel */
1588 if (c == '\0' || (c == '.' && *p == '\0'))
1589 return is_escalpha (first_char);
1596 * g_filename_from_uri:
1597 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1598 * @hostname: Location to store hostname for the URI, or %NULL.
1599 * If there is no hostname in the URI, %NULL will be
1600 * stored in this location.
1601 * @error: location to store the error occuring, or %NULL to ignore
1602 * errors. Any of the errors in #GConvertError may occur.
1604 * Converts an escaped UTF-8 encoded URI to a local filename in the
1605 * encoding used for filenames.
1607 * Return value: a newly-allocated string holding the resulting
1608 * filename, or %NULL on an error.
1611 g_filename_from_uri (const char *uri,
1615 const char *path_part;
1616 const char *host_part;
1617 char *unescaped_hostname;
1628 if (!has_case_prefix (uri, "file:/"))
1630 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1631 _("The URI '%s' is not an absolute URI using the file scheme"),
1636 path_part = uri + strlen ("file:");
1638 if (strchr (path_part, '#') != NULL)
1640 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1641 _("The local file URI '%s' may not include a '#'"),
1646 if (has_case_prefix (path_part, "///"))
1648 else if (has_case_prefix (path_part, "//"))
1651 host_part = path_part;
1653 path_part = strchr (path_part, '/');
1655 if (path_part == NULL)
1657 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1658 _("The URI '%s' is invalid"),
1663 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1665 if (unescaped_hostname == NULL ||
1666 !hostname_validate (unescaped_hostname))
1668 g_free (unescaped_hostname);
1669 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1670 _("The hostname of the URI '%s' is invalid"),
1676 *hostname = unescaped_hostname;
1678 g_free (unescaped_hostname);
1681 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1683 if (filename == NULL)
1685 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1686 _("The URI '%s' contains invalidly escaped characters"),
1693 /* Drop localhost */
1694 if (hostname && *hostname != NULL &&
1695 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1701 /* Turn slashes into backslashes, because that's the canonical spelling */
1703 while ((slash = strchr (p, '/')) != NULL)
1709 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1710 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1711 * the filename from the drive letter.
1713 if (g_ascii_isalpha (filename[1]))
1715 if (filename[2] == ':')
1717 else if (filename[2] == '|')
1725 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1732 * g_filename_to_uri:
1733 * @filename: an absolute filename specified in the encoding
1734 * used for filenames by the operating system.
1735 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1736 * @error: location to store the error occuring, or %NULL to ignore
1737 * errors. Any of the errors in #GConvertError may occur.
1739 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1741 * Return value: a newly-allocated string holding the resulting
1742 * URI, or %NULL on an error.
1745 g_filename_to_uri (const char *filename,
1746 const char *hostname,
1750 char *utf8_filename;
1752 g_return_val_if_fail (filename != NULL, NULL);
1754 if (!g_path_is_absolute (filename))
1756 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1757 _("The pathname '%s' is not an absolute path"),
1763 !(g_utf8_validate (hostname, -1, NULL)
1764 && hostname_validate (hostname)))
1766 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1767 _("Invalid hostname"));
1771 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1772 if (utf8_filename == NULL)
1776 /* Don't use localhost unnecessarily */
1777 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1781 escaped_uri = g_escape_file_uri (hostname,
1783 g_free (utf8_filename);