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 #ifdef G_PLATFORM_WIN32
40 #if defined(USE_LIBICONV) && !defined (_LIBICONV_H)
41 #error libiconv in use but included iconv.h not from libiconv
43 #if !defined(USE_LIBICONV) && defined (_LIBICONV_H)
44 #error libiconv not in use but included iconv.h is from libiconv
48 g_convert_error_quark (void)
52 quark = g_quark_from_static_string ("g_convert_error");
58 try_conversion (const char *to_codeset,
59 const char *from_codeset,
62 *cd = iconv_open (to_codeset, from_codeset);
64 if (*cd == (iconv_t)-1 && errno == EINVAL)
71 try_to_aliases (const char **to_aliases,
72 const char *from_codeset,
77 const char **p = to_aliases;
80 if (try_conversion (*p, from_codeset, cd))
90 extern const char **_g_charset_get_aliases (const char *canonical_name);
94 * @to_codeset: destination codeset
95 * @from_codeset: source codeset
97 * Same as the standard UNIX routine <function>iconv_open()</function>, but
98 * may be implemented via libiconv on UNIX flavors that lack
99 * a native implementation.
101 * GLib provides g_convert() and g_locale_to_utf8() which are likely
102 * more convenient than the raw iconv wrappers.
104 * Return value: a "conversion descriptor"
107 g_iconv_open (const gchar *to_codeset,
108 const gchar *from_codeset)
112 if (!try_conversion (to_codeset, from_codeset, &cd))
114 const char **to_aliases = _g_charset_get_aliases (to_codeset);
115 const char **from_aliases = _g_charset_get_aliases (from_codeset);
119 const char **p = from_aliases;
122 if (try_conversion (to_codeset, *p, &cd))
125 if (try_to_aliases (to_aliases, *p, &cd))
132 if (try_to_aliases (to_aliases, from_codeset, &cd))
141 * @converter: conversion descriptor from g_iconv_open()
142 * @inbuf: bytes to convert
143 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
144 * @outbuf: converted output bytes
145 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
147 * Same as the standard UNIX routine <function>iconv()</function>, but
148 * may be implemented via libiconv on UNIX flavors that lack
149 * a native implementation.
151 * GLib provides g_convert() and g_locale_to_utf8() which are likely
152 * more convenient than the raw iconv wrappers.
154 * Return value: count of non-reversible conversions, or -1 on error
157 g_iconv (GIConv converter,
161 gsize *outbytes_left)
163 iconv_t cd = (iconv_t)converter;
165 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
170 * @converter: a conversion descriptor from g_iconv_open()
172 * Same as the standard UNIX routine <function>iconv_close()</function>, but
173 * may be implemented via libiconv on UNIX flavors that lack
174 * a native implementation. Should be called to clean up
175 * the conversion descriptor from g_iconv_open() when
176 * you are done converting things.
178 * GLib provides g_convert() and g_locale_to_utf8() which are likely
179 * more convenient than the raw iconv wrappers.
181 * Return value: -1 on error, 0 on success
184 g_iconv_close (GIConv converter)
186 iconv_t cd = (iconv_t)converter;
188 return iconv_close (cd);
192 #define ICONV_CACHE_SIZE (16)
194 struct _iconv_cache_bucket {
201 static GList *iconv_cache_list;
202 static GHashTable *iconv_cache;
203 static GHashTable *iconv_open_hash;
204 static guint iconv_cache_size = 0;
205 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
207 /* caller *must* hold the iconv_cache_lock */
209 iconv_cache_init (void)
211 static gboolean initialized = FALSE;
216 iconv_cache_list = NULL;
217 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
218 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
225 * iconv_cache_bucket_new:
227 * @cd: iconv descriptor
229 * Creates a new cache bucket, inserts it into the cache and
230 * increments the cache size.
232 * Returns a pointer to the newly allocated cache bucket.
234 struct _iconv_cache_bucket *
235 iconv_cache_bucket_new (const gchar *key, iconv_t cd)
237 struct _iconv_cache_bucket *bucket;
239 bucket = g_new (struct _iconv_cache_bucket, 1);
240 bucket->key = g_strdup (key);
241 bucket->refcount = 1;
245 g_hash_table_insert (iconv_cache, bucket->key, bucket);
247 /* FIXME: if we sorted the list so items with few refcounts were
248 first, then we could expire them faster in iconv_cache_expire_unused () */
249 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
258 * iconv_cache_bucket_expire:
259 * @node: cache bucket's node
260 * @bucket: cache bucket
262 * Expires a single cache bucket @bucket. This should only ever be
263 * called on a bucket that currently has no used iconv descriptors
266 * @node is not a required argument. If @node is not supplied, we
267 * search for it ourselves.
270 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
272 g_hash_table_remove (iconv_cache, bucket->key);
275 node = g_list_find (iconv_cache_list, bucket);
277 g_assert (node != NULL);
281 node->prev->next = node->next;
283 node->next->prev = node->prev;
287 iconv_cache_list = node->next;
289 node->next->prev = NULL;
292 g_list_free_1 (node);
294 g_free (bucket->key);
295 g_iconv_close (bucket->cd);
303 * iconv_cache_expire_unused:
305 * Expires as many unused cache buckets as it needs to in order to get
306 * the total number of buckets < ICONV_CACHE_SIZE.
309 iconv_cache_expire_unused (void)
311 struct _iconv_cache_bucket *bucket;
314 node = iconv_cache_list;
315 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
320 if (bucket->refcount == 0)
321 iconv_cache_bucket_expire (node, bucket);
328 open_converter (const gchar *to_codeset,
329 const gchar *from_codeset,
332 struct _iconv_cache_bucket *bucket;
337 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
338 sprintf (key, "%s:%s", from_codeset, to_codeset);
340 G_LOCK (iconv_cache_lock);
342 /* make sure the cache has been initialized */
345 bucket = g_hash_table_lookup (iconv_cache, key);
350 cd = g_iconv_open (to_codeset, from_codeset);
351 if (cd == (iconv_t) -1)
359 /* reset the descriptor */
360 g_iconv (cd, NULL, NULL, NULL, NULL);
367 cd = g_iconv_open (to_codeset, from_codeset);
368 if (cd == (iconv_t) -1)
371 iconv_cache_expire_unused ();
373 bucket = iconv_cache_bucket_new (key, cd);
376 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
378 G_UNLOCK (iconv_cache_lock);
384 G_UNLOCK (iconv_cache_lock);
386 /* Something went wrong. */
388 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
389 _("Conversion from character set '%s' to '%s' is not supported"),
390 from_codeset, to_codeset);
392 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
393 _("Could not open converter from '%s' to '%s': %s"),
394 from_codeset, to_codeset, strerror (errno));
400 close_converter (GIConv converter)
402 struct _iconv_cache_bucket *bucket;
406 cd = (iconv_t) converter;
408 if (cd == (iconv_t) -1)
411 G_LOCK (iconv_cache_lock);
413 key = g_hash_table_lookup (iconv_open_hash, cd);
416 g_hash_table_remove (iconv_open_hash, cd);
418 bucket = g_hash_table_lookup (iconv_cache, key);
423 if (cd == bucket->cd)
424 bucket->used = FALSE;
428 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
430 /* expire this cache bucket */
431 iconv_cache_bucket_expire (NULL, bucket);
436 G_UNLOCK (iconv_cache_lock);
438 g_warning ("This iconv context wasn't opened using open_converter");
440 return g_iconv_close (converter);
443 G_UNLOCK (iconv_cache_lock);
451 * @str: the string to convert
452 * @len: the length of the string
453 * @to_codeset: name of character set into which to convert @str
454 * @from_codeset: character set of @str.
455 * @bytes_read: location to store the number of bytes in the
456 * input string that were successfully converted, or %NULL.
457 * Even if the conversion was successful, this may be
458 * less than @len if there were partial characters
459 * at the end of the input. If the error
460 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
461 * stored will the byte offset after the last valid
463 * @bytes_written: the number of bytes stored in the output buffer (not
464 * including the terminating nul).
465 * @error: location to store the error occuring, or %NULL to ignore
466 * errors. Any of the errors in #GConvertError may occur.
468 * Converts a string from one character set to another.
470 * Return value: If the conversion was successful, a newly allocated
471 * nul-terminated string, which must be freed with
472 * g_free(). Otherwise %NULL and @error will be set.
475 g_convert (const gchar *str,
477 const gchar *to_codeset,
478 const gchar *from_codeset,
480 gsize *bytes_written,
486 g_return_val_if_fail (str != NULL, NULL);
487 g_return_val_if_fail (to_codeset != NULL, NULL);
488 g_return_val_if_fail (from_codeset != NULL, NULL);
490 cd = open_converter (to_codeset, from_codeset, error);
492 if (cd == (GIConv) -1)
503 res = g_convert_with_iconv (str, len, cd,
504 bytes_read, bytes_written,
507 close_converter (cd);
513 * g_convert_with_iconv:
514 * @str: the string to convert
515 * @len: the length of the string
516 * @converter: conversion descriptor from g_iconv_open()
517 * @bytes_read: location to store the number of bytes in the
518 * input string that were successfully converted, or %NULL.
519 * Even if the conversion was successful, this may be
520 * less than @len if there were partial characters
521 * at the end of the input. If the error
522 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
523 * stored will the byte offset after the last valid
525 * @bytes_written: the number of bytes stored in the output buffer (not
526 * including the terminating nul).
527 * @error: location to store the error occuring, or %NULL to ignore
528 * errors. Any of the errors in #GConvertError may occur.
530 * Converts a string from one character set to another.
532 * Return value: If the conversion was successful, a newly allocated
533 * nul-terminated string, which must be freed with
534 * g_free(). Otherwise %NULL and @error will be set.
537 g_convert_with_iconv (const gchar *str,
541 gsize *bytes_written,
547 gsize inbytes_remaining;
548 gsize outbytes_remaining;
551 gboolean have_error = FALSE;
553 g_return_val_if_fail (str != NULL, NULL);
554 g_return_val_if_fail (converter != (GIConv) -1, NULL);
560 inbytes_remaining = len;
561 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
563 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
564 outp = dest = g_malloc (outbuf_size);
568 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
570 if (err == (size_t) -1)
575 /* Incomplete text, do not report an error */
579 size_t used = outp - dest;
582 dest = g_realloc (dest, outbuf_size);
585 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
590 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
591 _("Invalid byte sequence in conversion input"));
595 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
596 _("Error during conversion: %s"),
606 *bytes_read = p - str;
609 if ((p - str) != len)
613 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
614 _("Partial character sequence at end of input"));
621 *bytes_written = outp - dest; /* Doesn't include '\0' */
633 * g_convert_with_fallback:
634 * @str: the string to convert
635 * @len: the length of the string
636 * @to_codeset: name of character set into which to convert @str
637 * @from_codeset: character set of @str.
638 * @fallback: UTF-8 string to use in place of character not
639 * present in the target encoding. (This must be
640 * in the target encoding), if %NULL, characters
641 * not in the target encoding will be represented
642 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
643 * @bytes_read: location to store the number of bytes in the
644 * input string that were successfully converted, or %NULL.
645 * Even if the conversion was successful, this may be
646 * less than @len if there were partial characters
647 * at the end of the input.
648 * @bytes_written: the number of bytes stored in the output buffer (not
649 * including the terminating nul).
650 * @error: location to store the error occuring, or %NULL to ignore
651 * errors. Any of the errors in #GConvertError may occur.
653 * Converts a string from one character set to another, possibly
654 * including fallback sequences for characters not representable
655 * in the output. Note that it is not guaranteed that the specification
656 * for the fallback sequences in @fallback will be honored. Some
657 * systems may do a approximate conversion from @from_codeset
658 * to @to_codeset in their <function>iconv()</function> functions,
659 * in which case GLib will simply return that approximate conversion.
661 * Return value: If the conversion was successful, a newly allocated
662 * nul-terminated string, which must be freed with
663 * g_free(). Otherwise %NULL and @error will be set.
666 g_convert_with_fallback (const gchar *str,
668 const gchar *to_codeset,
669 const gchar *from_codeset,
672 gsize *bytes_written,
678 const gchar *insert_str = NULL;
680 gsize inbytes_remaining;
681 const gchar *save_p = NULL;
682 gsize save_inbytes = 0;
683 gsize outbytes_remaining;
687 gboolean have_error = FALSE;
688 gboolean done = FALSE;
690 GError *local_error = NULL;
692 g_return_val_if_fail (str != NULL, NULL);
693 g_return_val_if_fail (to_codeset != NULL, NULL);
694 g_return_val_if_fail (from_codeset != NULL, NULL);
699 /* Try an exact conversion; we only proceed if this fails
700 * due to an illegal sequence in the input string.
702 dest = g_convert (str, len, to_codeset, from_codeset,
703 bytes_read, bytes_written, &local_error);
707 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
709 g_propagate_error (error, local_error);
713 g_error_free (local_error);
717 /* No go; to proceed, we need a converter from "UTF-8" to
718 * to_codeset, and the string as UTF-8.
720 cd = open_converter (to_codeset, "UTF-8", error);
721 if (cd == (GIConv) -1)
732 utf8 = g_convert (str, len, "UTF-8", from_codeset,
733 bytes_read, &inbytes_remaining, error);
736 close_converter (cd);
742 /* Now the heart of the code. We loop through the UTF-8 string, and
743 * whenever we hit an offending character, we form fallback, convert
744 * the fallback to the target codeset, and then go back to
745 * converting the original string after finishing with the fallback.
747 * The variables save_p and save_inbytes store the input state
748 * for the original string while we are converting the fallback
752 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
753 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
754 outp = dest = g_malloc (outbuf_size);
756 while (!done && !have_error)
758 size_t inbytes_tmp = inbytes_remaining;
759 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
760 inbytes_remaining = inbytes_tmp;
762 if (err == (size_t) -1)
767 g_assert_not_reached();
771 size_t used = outp - dest;
774 dest = g_realloc (dest, outbuf_size);
777 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
784 /* Error converting fallback string - fatal
786 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
787 _("Cannot convert fallback '%s' to codeset '%s'"),
788 insert_str, to_codeset);
796 gunichar ch = g_utf8_get_char (p);
797 insert_str = g_strdup_printf ("\\x{%0*X}",
798 (ch < 0x10000) ? 4 : 6,
802 insert_str = fallback;
804 save_p = g_utf8_next_char (p);
805 save_inbytes = inbytes_remaining - (save_p - p);
807 inbytes_remaining = strlen (p);
811 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
812 _("Error during conversion: %s"),
823 g_free ((gchar *)insert_str);
825 inbytes_remaining = save_inbytes;
837 close_converter (cd);
840 *bytes_written = outp - dest; /* Doesn't include '\0' */
846 if (save_p && !fallback)
847 g_free ((gchar *)insert_str);
861 #ifndef G_PLATFORM_WIN32
864 strdup_len (const gchar *string,
866 gsize *bytes_written,
873 if (!g_utf8_validate (string, -1, NULL))
880 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
881 _("Invalid byte sequence in conversion input"));
886 real_len = strlen (string);
891 while (real_len < len && string[real_len])
896 *bytes_read = real_len;
898 *bytes_written = real_len;
900 return g_strndup (string, real_len);
907 * @opsysstring: a string in the encoding of the current locale
908 * @len: the length of the string, or -1 if the string is
910 * @bytes_read: location to store the number of bytes in the
911 * input string that were successfully converted, or %NULL.
912 * Even if the conversion was successful, this may be
913 * less than @len if there were partial characters
914 * at the end of the input. If the error
915 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
916 * stored will the byte offset after the last valid
918 * @bytes_written: the number of bytes stored in the output buffer (not
919 * including the terminating nul).
920 * @error: location to store the error occuring, or %NULL to ignore
921 * errors. Any of the errors in #GConvertError may occur.
923 * Converts a string which is in the encoding used for strings by
924 * the C runtime (usually the same as that used by the operating
925 * system) in the current locale into a UTF-8 string.
927 * Return value: The converted string, or %NULL on an error.
930 g_locale_to_utf8 (const gchar *opsysstring,
933 gsize *bytes_written,
936 #ifdef G_PLATFORM_WIN32
938 gint i, clen, total_len, wclen, first;
944 len = strlen (opsysstring);
946 wcs = g_new (wchar_t, len);
947 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
951 for (i = 0; i < wclen; i++)
959 else if (wc < 0x10000)
961 else if (wc < 0x200000)
963 else if (wc < 0x4000000)
969 result = g_malloc (total_len + 1);
973 for (i = 0; i < wclen; i++)
987 else if (wc < 0x10000)
992 else if (wc < 0x200000)
997 else if (wc < 0x4000000)
1011 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1012 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1013 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1014 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1015 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1016 case 1: bp[0] = wc | first;
1028 *bytes_written = total_len;
1032 #else /* !G_PLATFORM_WIN32 */
1034 const char *charset;
1036 if (g_get_charset (&charset))
1037 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1039 return g_convert (opsysstring, len,
1040 "UTF-8", charset, bytes_read, bytes_written, error);
1042 #endif /* !G_PLATFORM_WIN32 */
1046 * g_locale_from_utf8:
1047 * @utf8string: a UTF-8 encoded string
1048 * @len: the length of the string, or -1 if the string is
1050 * @bytes_read: location to store the number of bytes in the
1051 * input string that were successfully converted, or %NULL.
1052 * Even if the conversion was successful, this may be
1053 * less than @len if there were partial characters
1054 * at the end of the input. If the error
1055 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1056 * stored will the byte offset after the last valid
1058 * @bytes_written: the number of bytes stored in the output buffer (not
1059 * including the terminating nul).
1060 * @error: location to store the error occuring, or %NULL to ignore
1061 * errors. Any of the errors in #GConvertError may occur.
1063 * Converts a string from UTF-8 to the encoding used for strings by
1064 * the C runtime (usually the same as that used by the operating
1065 * system) in the current locale.
1067 * Return value: The converted string, or %NULL on an error.
1070 g_locale_from_utf8 (const gchar *utf8string,
1073 gsize *bytes_written,
1076 #ifdef G_PLATFORM_WIN32
1078 gint i, mask, clen, mblen;
1081 guchar *cp, *end, c;
1085 len = strlen (utf8string);
1087 /* First convert to wide chars */
1088 cp = (guchar *) utf8string;
1091 wcs = g_new (wchar_t, len + 1);
1103 else if ((c & 0xe0) == 0xc0)
1108 else if ((c & 0xf0) == 0xe0)
1113 else if ((c & 0xf8) == 0xf0)
1118 else if ((c & 0xfc) == 0xf8)
1123 else if ((c & 0xfc) == 0xfc)
1134 if (cp + clen > end)
1140 *wcp = (cp[0] & mask);
1141 for (i = 1; i < clen; i++)
1143 if ((cp[i] & 0xc0) != 0x80)
1149 *wcp |= (cp[i] & 0x3f);
1162 /* n is the number of wide chars constructed */
1164 /* Convert to a string in the current ANSI codepage */
1166 result = g_new (gchar, 3 * n + 1);
1167 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1174 *bytes_written = mblen;
1178 #else /* !G_PLATFORM_WIN32 */
1180 const gchar *charset;
1182 if (g_get_charset (&charset))
1183 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1185 return g_convert (utf8string, len,
1186 charset, "UTF-8", bytes_read, bytes_written, error);
1188 #endif /* !G_PLATFORM_WIN32 */
1192 * g_filename_to_utf8:
1193 * @opsysstring: a string in the encoding for filenames
1194 * @len: the length of the string, or -1 if the string is
1196 * @bytes_read: location to store the number of bytes in the
1197 * input string that were successfully converted, or %NULL.
1198 * Even if the conversion was successful, this may be
1199 * less than @len if there were partial characters
1200 * at the end of the input. If the error
1201 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1202 * stored will the byte offset after the last valid
1204 * @bytes_written: the number of bytes stored in the output buffer (not
1205 * including the terminating nul).
1206 * @error: location to store the error occuring, or %NULL to ignore
1207 * errors. Any of the errors in #GConvertError may occur.
1209 * Converts a string which is in the encoding used for filenames
1210 * into a UTF-8 string.
1212 * Return value: The converted string, or %NULL on an error.
1215 g_filename_to_utf8 (const gchar *opsysstring,
1218 gsize *bytes_written,
1221 #ifdef G_PLATFORM_WIN32
1222 return g_locale_to_utf8 (opsysstring, len,
1223 bytes_read, bytes_written,
1225 #else /* !G_PLATFORM_WIN32 */
1227 if (getenv ("G_BROKEN_FILENAMES"))
1228 return g_locale_to_utf8 (opsysstring, len,
1229 bytes_read, bytes_written,
1232 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1233 #endif /* !G_PLATFORM_WIN32 */
1237 * g_filename_from_utf8:
1238 * @utf8string: a UTF-8 encoded string.
1239 * @len: the length of the string, or -1 if the string is
1241 * @bytes_read: location to store the number of bytes in the
1242 * input string that were successfully converted, or %NULL.
1243 * Even if the conversion was successful, this may be
1244 * less than @len if there were partial characters
1245 * at the end of the input. If the error
1246 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1247 * stored will the byte offset after the last valid
1249 * @bytes_written: the number of bytes stored in the output buffer (not
1250 * including the terminating nul).
1251 * @error: location to store the error occuring, or %NULL to ignore
1252 * errors. Any of the errors in #GConvertError may occur.
1254 * Converts a string from UTF-8 to the encoding used for filenames.
1256 * Return value: The converted string, or %NULL on an error.
1259 g_filename_from_utf8 (const gchar *utf8string,
1262 gsize *bytes_written,
1265 #ifdef G_PLATFORM_WIN32
1266 return g_locale_from_utf8 (utf8string, len,
1267 bytes_read, bytes_written,
1269 #else /* !G_PLATFORM_WIN32 */
1270 if (getenv ("G_BROKEN_FILENAMES"))
1271 return g_locale_from_utf8 (utf8string, len,
1272 bytes_read, bytes_written,
1275 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1276 #endif /* !G_PLATFORM_WIN32 */
1279 /* Test of haystack has the needle prefix, comparing case
1280 * insensitive. haystack may be UTF-8, but needle must
1281 * contain only ascii. */
1283 has_case_prefix (const gchar *haystack, const gchar *needle)
1287 /* Eat one character at a time. */
1292 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1302 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1303 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1304 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1305 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1306 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1307 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1308 } UnsafeCharacterSet;
1310 static const guchar acceptable[96] = {
1311 /* A table of the ASCII chars from space (32) to DEL (127) */
1312 /* ! " # $ % & ' ( ) * + , - . / */
1313 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1314 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1315 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1316 /* @ A B C D E F G H I J K L M N O */
1317 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1318 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1319 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1320 /* ` a b c d e f g h i j k l m n o */
1321 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1322 /* p q r s t u v w x y z { | } ~ DEL */
1323 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1326 static const gchar hex[16] = "0123456789ABCDEF";
1328 /* Note: This escape function works on file: URIs, but if you want to
1329 * escape something else, please read RFC-2396 */
1331 g_escape_uri_string (const gchar *string,
1332 UnsafeCharacterSet mask)
1334 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1341 UnsafeCharacterSet use_mask;
1343 g_return_val_if_fail (mask == UNSAFE_ALL
1344 || mask == UNSAFE_ALLOW_PLUS
1345 || mask == UNSAFE_PATH
1346 || mask == UNSAFE_DOS_PATH
1347 || mask == UNSAFE_HOST
1348 || mask == UNSAFE_SLASHES, NULL);
1352 for (p = string; *p != '\0'; p++)
1355 if (!ACCEPTABLE (c))
1359 result = g_malloc (p - string + unacceptable * 2 + 1);
1362 for (q = result, p = string; *p != '\0'; p++)
1366 if (!ACCEPTABLE (c))
1368 *q++ = '%'; /* means hex coming */
1383 g_escape_file_uri (const gchar *hostname,
1384 const gchar *pathname)
1386 char *escaped_hostname = NULL;
1391 char *p, *backslash;
1393 /* Turn backslashes into forward slashes. That's what Netscape
1394 * does, and they are actually more or less equivalent in Windows.
1397 pathname = g_strdup (pathname);
1398 p = (char *) pathname;
1400 while ((backslash = strchr (p, '\\')) != NULL)
1407 if (hostname && *hostname != '\0')
1409 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1412 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1414 res = g_strconcat ("file://",
1415 (escaped_hostname) ? escaped_hostname : "",
1416 (*escaped_path != '/') ? "/" : "",
1421 g_free ((char *) pathname);
1424 g_free (escaped_hostname);
1425 g_free (escaped_path);
1431 unescape_character (const char *scanner)
1436 first_digit = g_ascii_xdigit_value (scanner[0]);
1437 if (first_digit < 0)
1440 second_digit = g_ascii_xdigit_value (scanner[1]);
1441 if (second_digit < 0)
1444 return (first_digit << 4) | second_digit;
1448 g_unescape_uri_string (const char *escaped,
1450 const char *illegal_escaped_characters,
1451 gboolean ascii_must_not_be_escaped)
1453 const gchar *in, *in_end;
1454 gchar *out, *result;
1457 if (escaped == NULL)
1461 len = strlen (escaped);
1463 result = g_malloc (len + 1);
1466 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1472 /* catch partial escape sequences past the end of the substring */
1473 if (in + 3 > in_end)
1476 c = unescape_character (in + 1);
1478 /* catch bad escape sequences and NUL characters */
1482 /* catch escaped ASCII */
1483 if (ascii_must_not_be_escaped && c <= 0x7F)
1486 /* catch other illegal escaped characters */
1487 if (strchr (illegal_escaped_characters, c) != NULL)
1496 g_assert (out - result <= len);
1499 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1509 is_escalphanum (gunichar c)
1511 return c > 0x7F || g_ascii_isalnum (c);
1515 is_escalpha (gunichar c)
1517 return c > 0x7F || g_ascii_isalpha (c);
1520 /* allows an empty string */
1522 hostname_validate (const char *hostname)
1525 gunichar c, first_char, last_char;
1532 /* read in a label */
1533 c = g_utf8_get_char (p);
1534 p = g_utf8_next_char (p);
1535 if (!is_escalphanum (c))
1541 c = g_utf8_get_char (p);
1542 p = g_utf8_next_char (p);
1544 while (is_escalphanum (c) || c == '-');
1545 if (last_char == '-')
1548 /* if that was the last label, check that it was a toplabel */
1549 if (c == '\0' || (c == '.' && *p == '\0'))
1550 return is_escalpha (first_char);
1557 * g_filename_from_uri:
1558 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1559 * @hostname: Location to store hostname for the URI, or %NULL.
1560 * If there is no hostname in the URI, %NULL will be
1561 * stored in this location.
1562 * @error: location to store the error occuring, or %NULL to ignore
1563 * errors. Any of the errors in #GConvertError may occur.
1565 * Converts an escaped UTF-8 encoded URI to a local filename in the
1566 * encoding used for filenames.
1568 * Return value: a newly-allocated string holding the resulting
1569 * filename, or %NULL on an error.
1572 g_filename_from_uri (const char *uri,
1576 const char *path_part;
1577 const char *host_part;
1578 char *unescaped_hostname;
1589 if (!has_case_prefix (uri, "file:/"))
1591 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1592 _("The URI '%s' is not an absolute URI using the file scheme"),
1597 path_part = uri + strlen ("file:");
1599 if (strchr (path_part, '#') != NULL)
1601 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1602 _("The local file URI '%s' may not include a '#'"),
1607 if (has_case_prefix (path_part, "///"))
1609 else if (has_case_prefix (path_part, "//"))
1612 host_part = path_part;
1614 path_part = strchr (path_part, '/');
1616 if (path_part == NULL)
1618 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1619 _("The URI '%s' is invalid"),
1624 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1626 if (unescaped_hostname == NULL ||
1627 !hostname_validate (unescaped_hostname))
1629 g_free (unescaped_hostname);
1630 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1631 _("The hostname of the URI '%s' is invalid"),
1637 *hostname = unescaped_hostname;
1639 g_free (unescaped_hostname);
1642 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1644 if (filename == NULL)
1646 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1647 _("The URI '%s' contains invalidly escaped characters"),
1654 /* Drop localhost */
1655 if (hostname && *hostname != NULL &&
1656 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1662 /* Turn slashes into backslashes, because that's the canonical spelling */
1664 while ((slash = strchr (p, '/')) != NULL)
1670 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1671 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1672 * the filename from the drive letter.
1674 if (g_ascii_isalpha (filename[1]))
1676 if (filename[2] == ':')
1678 else if (filename[2] == '|')
1686 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1693 * g_filename_to_uri:
1694 * @filename: an absolute filename specified in the encoding
1695 * used for filenames by the operating system.
1696 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1697 * @error: location to store the error occuring, or %NULL to ignore
1698 * errors. Any of the errors in #GConvertError may occur.
1700 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1702 * Return value: a newly-allocated string holding the resulting
1703 * URI, or %NULL on an error.
1706 g_filename_to_uri (const char *filename,
1707 const char *hostname,
1711 char *utf8_filename;
1713 g_return_val_if_fail (filename != NULL, NULL);
1715 if (!g_path_is_absolute (filename))
1717 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1718 _("The pathname '%s' is not an absolute path"),
1724 !(g_utf8_validate (hostname, -1, NULL)
1725 && hostname_validate (hostname)))
1727 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1728 _("Invalid hostname"));
1732 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1733 if (utf8_filename == NULL)
1737 /* Don't use localhost unnecessarily */
1738 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1742 escaped_uri = g_escape_file_uri (hostname,
1744 g_free (utf8_filename);