1 /* GLIB - Library of useful routines for C programming
3 * gconvert.c: Convert between character sets using iconv
4 * Copyright Red Hat Inc., 2000
5 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
33 #ifdef G_PLATFORM_WIN32
41 #if defined(USE_LIBICONV) && !defined (_LIBICONV_H)
42 #error libiconv in use but included iconv.h not from libiconv
44 #if !defined(USE_LIBICONV) && defined (_LIBICONV_H)
45 #error libiconv not in use but included iconv.h is from libiconv
49 g_convert_error_quark (void)
53 quark = g_quark_from_static_string ("g_convert_error");
59 try_conversion (const char *to_codeset,
60 const char *from_codeset,
63 *cd = iconv_open (to_codeset, from_codeset);
65 if (*cd == (iconv_t)-1 && errno == EINVAL)
72 try_to_aliases (const char **to_aliases,
73 const char *from_codeset,
78 const char **p = to_aliases;
81 if (try_conversion (*p, from_codeset, cd))
91 extern const char **_g_charset_get_aliases (const char *canonical_name);
95 * @to_codeset: destination codeset
96 * @from_codeset: source codeset
98 * Same as the standard UNIX routine <function>iconv_open()</function>, but
99 * may be implemented via libiconv on UNIX flavors that lack
100 * a native implementation.
102 * GLib provides g_convert() and g_locale_to_utf8() which are likely
103 * more convenient than the raw iconv wrappers.
105 * Return value: a "conversion descriptor"
108 g_iconv_open (const gchar *to_codeset,
109 const gchar *from_codeset)
113 if (!try_conversion (to_codeset, from_codeset, &cd))
115 const char **to_aliases = _g_charset_get_aliases (to_codeset);
116 const char **from_aliases = _g_charset_get_aliases (from_codeset);
120 const char **p = from_aliases;
123 if (try_conversion (to_codeset, *p, &cd))
126 if (try_to_aliases (to_aliases, *p, &cd))
133 if (try_to_aliases (to_aliases, from_codeset, &cd))
142 * @converter: conversion descriptor from g_iconv_open()
143 * @inbuf: bytes to convert
144 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
145 * @outbuf: converted output bytes
146 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
148 * Same as the standard UNIX routine <function>iconv()</function>, but
149 * may be implemented via libiconv on UNIX flavors that lack
150 * a native implementation.
152 * GLib provides g_convert() and g_locale_to_utf8() which are likely
153 * more convenient than the raw iconv wrappers.
155 * Return value: count of non-reversible conversions, or -1 on error
158 g_iconv (GIConv converter,
162 gsize *outbytes_left)
164 iconv_t cd = (iconv_t)converter;
166 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
171 * @converter: a conversion descriptor from g_iconv_open()
173 * Same as the standard UNIX routine <function>iconv_close()</function>, but
174 * may be implemented via libiconv on UNIX flavors that lack
175 * a native implementation. Should be called to clean up
176 * the conversion descriptor from g_iconv_open() when
177 * you are done converting things.
179 * GLib provides g_convert() and g_locale_to_utf8() which are likely
180 * more convenient than the raw iconv wrappers.
182 * Return value: -1 on error, 0 on success
185 g_iconv_close (GIConv converter)
187 iconv_t cd = (iconv_t)converter;
189 return iconv_close (cd);
193 #define ICONV_CACHE_SIZE (16)
195 struct _iconv_cache_bucket {
202 static GList *iconv_cache_list;
203 static GHashTable *iconv_cache;
204 static GHashTable *iconv_open_hash;
205 static guint iconv_cache_size = 0;
206 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
208 /* caller *must* hold the iconv_cache_lock */
210 iconv_cache_init (void)
212 static gboolean initialized = FALSE;
217 iconv_cache_list = NULL;
218 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
219 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
226 * iconv_cache_bucket_new:
228 * @cd: iconv descriptor
230 * Creates a new cache bucket, inserts it into the cache and
231 * increments the cache size.
233 * Returns a pointer to the newly allocated cache bucket.
235 struct _iconv_cache_bucket *
236 iconv_cache_bucket_new (const gchar *key, iconv_t cd)
238 struct _iconv_cache_bucket *bucket;
240 bucket = g_new (struct _iconv_cache_bucket, 1);
241 bucket->key = g_strdup (key);
242 bucket->refcount = 1;
246 g_hash_table_insert (iconv_cache, bucket->key, bucket);
248 /* FIXME: if we sorted the list so items with few refcounts were
249 first, then we could expire them faster in iconv_cache_expire_unused () */
250 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
259 * iconv_cache_bucket_expire:
260 * @node: cache bucket's node
261 * @bucket: cache bucket
263 * Expires a single cache bucket @bucket. This should only ever be
264 * called on a bucket that currently has no used iconv descriptors
267 * @node is not a required argument. If @node is not supplied, we
268 * search for it ourselves.
271 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
273 g_hash_table_remove (iconv_cache, bucket->key);
276 node = g_list_find (iconv_cache_list, bucket);
278 g_assert (node != NULL);
282 node->prev->next = node->next;
284 node->next->prev = node->prev;
288 iconv_cache_list = node->next;
290 node->next->prev = NULL;
293 g_list_free_1 (node);
295 g_free (bucket->key);
296 g_iconv_close (bucket->cd);
304 * iconv_cache_expire_unused:
306 * Expires as many unused cache buckets as it needs to in order to get
307 * the total number of buckets < ICONV_CACHE_SIZE.
310 iconv_cache_expire_unused (void)
312 struct _iconv_cache_bucket *bucket;
315 node = iconv_cache_list;
316 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
321 if (bucket->refcount == 0)
322 iconv_cache_bucket_expire (node, bucket);
329 open_converter (const gchar *to_codeset,
330 const gchar *from_codeset,
333 struct _iconv_cache_bucket *bucket;
338 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
339 sprintf (key, "%s:%s", from_codeset, to_codeset);
341 G_LOCK (iconv_cache_lock);
343 /* make sure the cache has been initialized */
346 bucket = g_hash_table_lookup (iconv_cache, key);
351 cd = g_iconv_open (to_codeset, from_codeset);
352 if (cd == (iconv_t) -1)
360 /* reset the descriptor */
361 g_iconv (cd, NULL, NULL, NULL, NULL);
368 cd = g_iconv_open (to_codeset, from_codeset);
369 if (cd == (iconv_t) -1)
372 iconv_cache_expire_unused ();
374 bucket = iconv_cache_bucket_new (key, cd);
377 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
379 G_UNLOCK (iconv_cache_lock);
385 G_UNLOCK (iconv_cache_lock);
387 /* Something went wrong. */
389 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
390 _("Conversion from character set '%s' to '%s' is not supported"),
391 from_codeset, to_codeset);
393 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
394 _("Could not open converter from '%s' to '%s': %s"),
395 from_codeset, to_codeset, strerror (errno));
401 close_converter (GIConv converter)
403 struct _iconv_cache_bucket *bucket;
407 cd = (iconv_t) converter;
409 if (cd == (iconv_t) -1)
412 G_LOCK (iconv_cache_lock);
414 key = g_hash_table_lookup (iconv_open_hash, cd);
417 g_hash_table_remove (iconv_open_hash, cd);
419 bucket = g_hash_table_lookup (iconv_cache, key);
424 if (cd == bucket->cd)
425 bucket->used = FALSE;
429 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
431 /* expire this cache bucket */
432 iconv_cache_bucket_expire (NULL, bucket);
437 G_UNLOCK (iconv_cache_lock);
439 g_warning ("This iconv context wasn't opened using open_converter");
441 return g_iconv_close (converter);
444 G_UNLOCK (iconv_cache_lock);
452 * @str: the string to convert
453 * @len: the length of the string
454 * @to_codeset: name of character set into which to convert @str
455 * @from_codeset: character set of @str.
456 * @bytes_read: location to store the number of bytes in the
457 * input string that were successfully converted, or %NULL.
458 * Even if the conversion was successful, this may be
459 * less than @len if there were partial characters
460 * at the end of the input. If the error
461 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
462 * stored will the byte offset after the last valid
464 * @bytes_written: the number of bytes stored in the output buffer (not
465 * including the terminating nul).
466 * @error: location to store the error occuring, or %NULL to ignore
467 * errors. Any of the errors in #GConvertError may occur.
469 * Converts a string from one character set to another.
471 * Return value: If the conversion was successful, a newly allocated
472 * nul-terminated string, which must be freed with
473 * g_free(). Otherwise %NULL and @error will be set.
476 g_convert (const gchar *str,
478 const gchar *to_codeset,
479 const gchar *from_codeset,
481 gsize *bytes_written,
487 g_return_val_if_fail (str != NULL, NULL);
488 g_return_val_if_fail (to_codeset != NULL, NULL);
489 g_return_val_if_fail (from_codeset != NULL, NULL);
491 cd = open_converter (to_codeset, from_codeset, error);
493 if (cd == (GIConv) -1)
504 res = g_convert_with_iconv (str, len, cd,
505 bytes_read, bytes_written,
508 close_converter (cd);
514 * g_convert_with_iconv:
515 * @str: the string to convert
516 * @len: the length of the string
517 * @converter: conversion descriptor from g_iconv_open()
518 * @bytes_read: location to store the number of bytes in the
519 * input string that were successfully converted, or %NULL.
520 * Even if the conversion was successful, this may be
521 * less than @len if there were partial characters
522 * at the end of the input. If the error
523 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
524 * stored will the byte offset after the last valid
526 * @bytes_written: the number of bytes stored in the output buffer (not
527 * including the terminating nul).
528 * @error: location to store the error occuring, or %NULL to ignore
529 * errors. Any of the errors in #GConvertError may occur.
531 * Converts a string from one character set to another.
533 * Return value: If the conversion was successful, a newly allocated
534 * nul-terminated string, which must be freed with
535 * g_free(). Otherwise %NULL and @error will be set.
538 g_convert_with_iconv (const gchar *str,
542 gsize *bytes_written,
548 gsize inbytes_remaining;
549 gsize outbytes_remaining;
552 gboolean have_error = FALSE;
554 g_return_val_if_fail (str != NULL, NULL);
555 g_return_val_if_fail (converter != (GIConv) -1, NULL);
561 inbytes_remaining = len;
562 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
564 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
565 outp = dest = g_malloc (outbuf_size);
569 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
571 if (err == (size_t) -1)
576 /* Incomplete text, do not report an error */
580 size_t used = outp - dest;
583 dest = g_realloc (dest, outbuf_size);
586 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
591 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
592 _("Invalid byte sequence in conversion input"));
596 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
597 _("Error during conversion: %s"),
607 *bytes_read = p - str;
610 if ((p - str) != len)
614 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
615 _("Partial character sequence at end of input"));
622 *bytes_written = outp - dest; /* Doesn't include '\0' */
634 * g_convert_with_fallback:
635 * @str: the string to convert
636 * @len: the length of the string
637 * @to_codeset: name of character set into which to convert @str
638 * @from_codeset: character set of @str.
639 * @fallback: UTF-8 string to use in place of character not
640 * present in the target encoding. (This must be
641 * in the target encoding), if %NULL, characters
642 * not in the target encoding will be represented
643 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
644 * @bytes_read: location to store the number of bytes in the
645 * input string that were successfully converted, or %NULL.
646 * Even if the conversion was successful, this may be
647 * less than @len if there were partial characters
648 * at the end of the input.
649 * @bytes_written: the number of bytes stored in the output buffer (not
650 * including the terminating nul).
651 * @error: location to store the error occuring, or %NULL to ignore
652 * errors. Any of the errors in #GConvertError may occur.
654 * Converts a string from one character set to another, possibly
655 * including fallback sequences for characters not representable
656 * in the output. Note that it is not guaranteed that the specification
657 * for the fallback sequences in @fallback will be honored. Some
658 * systems may do a approximate conversion from @from_codeset
659 * to @to_codeset in their <function>iconv()</function> functions,
660 * in which case GLib will simply return that approximate conversion.
662 * Return value: If the conversion was successful, a newly allocated
663 * nul-terminated string, which must be freed with
664 * g_free(). Otherwise %NULL and @error will be set.
667 g_convert_with_fallback (const gchar *str,
669 const gchar *to_codeset,
670 const gchar *from_codeset,
673 gsize *bytes_written,
679 const gchar *insert_str = NULL;
681 gsize inbytes_remaining;
682 const gchar *save_p = NULL;
683 gsize save_inbytes = 0;
684 gsize outbytes_remaining;
688 gboolean have_error = FALSE;
689 gboolean done = FALSE;
691 GError *local_error = NULL;
693 g_return_val_if_fail (str != NULL, NULL);
694 g_return_val_if_fail (to_codeset != NULL, NULL);
695 g_return_val_if_fail (from_codeset != NULL, NULL);
700 /* Try an exact conversion; we only proceed if this fails
701 * due to an illegal sequence in the input string.
703 dest = g_convert (str, len, to_codeset, from_codeset,
704 bytes_read, bytes_written, &local_error);
708 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
710 g_propagate_error (error, local_error);
714 g_error_free (local_error);
718 /* No go; to proceed, we need a converter from "UTF-8" to
719 * to_codeset, and the string as UTF-8.
721 cd = open_converter (to_codeset, "UTF-8", error);
722 if (cd == (GIConv) -1)
733 utf8 = g_convert (str, len, "UTF-8", from_codeset,
734 bytes_read, &inbytes_remaining, error);
737 close_converter (cd);
743 /* Now the heart of the code. We loop through the UTF-8 string, and
744 * whenever we hit an offending character, we form fallback, convert
745 * the fallback to the target codeset, and then go back to
746 * converting the original string after finishing with the fallback.
748 * The variables save_p and save_inbytes store the input state
749 * for the original string while we are converting the fallback
753 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
754 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
755 outp = dest = g_malloc (outbuf_size);
757 while (!done && !have_error)
759 size_t inbytes_tmp = inbytes_remaining;
760 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
761 inbytes_remaining = inbytes_tmp;
763 if (err == (size_t) -1)
768 g_assert_not_reached();
772 size_t used = outp - dest;
775 dest = g_realloc (dest, outbuf_size);
778 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
785 /* Error converting fallback string - fatal
787 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
788 _("Cannot convert fallback '%s' to codeset '%s'"),
789 insert_str, to_codeset);
797 gunichar ch = g_utf8_get_char (p);
798 insert_str = g_strdup_printf ("\\x{%0*X}",
799 (ch < 0x10000) ? 4 : 6,
803 insert_str = fallback;
805 save_p = g_utf8_next_char (p);
806 save_inbytes = inbytes_remaining - (save_p - p);
808 inbytes_remaining = strlen (p);
812 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
813 _("Error during conversion: %s"),
824 g_free ((gchar *)insert_str);
826 inbytes_remaining = save_inbytes;
838 close_converter (cd);
841 *bytes_written = outp - dest; /* Doesn't include '\0' */
847 if (save_p && !fallback)
848 g_free ((gchar *)insert_str);
862 #ifndef G_PLATFORM_WIN32
865 strdup_len (const gchar *string,
867 gsize *bytes_written,
874 if (!g_utf8_validate (string, -1, NULL))
881 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
882 _("Invalid byte sequence in conversion input"));
887 real_len = strlen (string);
892 while (real_len < len && string[real_len])
897 *bytes_read = real_len;
899 *bytes_written = real_len;
901 return g_strndup (string, real_len);
908 * @opsysstring: a string in the encoding of the current locale
909 * @len: the length of the string, or -1 if the string is
911 * @bytes_read: location to store the number of bytes in the
912 * input string that were successfully converted, or %NULL.
913 * Even if the conversion was successful, this may be
914 * less than @len if there were partial characters
915 * at the end of the input. If the error
916 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
917 * stored will the byte offset after the last valid
919 * @bytes_written: the number of bytes stored in the output buffer (not
920 * including the terminating nul).
921 * @error: location to store the error occuring, or %NULL to ignore
922 * errors. Any of the errors in #GConvertError may occur.
924 * Converts a string which is in the encoding used for strings by
925 * the C runtime (usually the same as that used by the operating
926 * system) in the current locale into a UTF-8 string.
928 * Return value: The converted string, or %NULL on an error.
931 g_locale_to_utf8 (const gchar *opsysstring,
934 gsize *bytes_written,
937 #ifdef G_PLATFORM_WIN32
939 gint i, clen, total_len, wclen, first;
945 len = strlen (opsysstring);
947 wcs = g_new (wchar_t, len);
948 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
952 for (i = 0; i < wclen; i++)
960 else if (wc < 0x10000)
962 else if (wc < 0x200000)
964 else if (wc < 0x4000000)
970 result = g_malloc (total_len + 1);
974 for (i = 0; i < wclen; i++)
988 else if (wc < 0x10000)
993 else if (wc < 0x200000)
998 else if (wc < 0x4000000)
1012 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1013 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1014 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1015 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1016 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1017 case 1: bp[0] = wc | first;
1029 *bytes_written = total_len;
1033 #else /* !G_PLATFORM_WIN32 */
1035 const char *charset;
1037 if (g_get_charset (&charset))
1038 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1040 return g_convert (opsysstring, len,
1041 "UTF-8", charset, bytes_read, bytes_written, error);
1043 #endif /* !G_PLATFORM_WIN32 */
1047 * g_locale_from_utf8:
1048 * @utf8string: a UTF-8 encoded string
1049 * @len: the length of the string, or -1 if the string is
1051 * @bytes_read: location to store the number of bytes in the
1052 * input string that were successfully converted, or %NULL.
1053 * Even if the conversion was successful, this may be
1054 * less than @len if there were partial characters
1055 * at the end of the input. If the error
1056 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1057 * stored will the byte offset after the last valid
1059 * @bytes_written: the number of bytes stored in the output buffer (not
1060 * including the terminating nul).
1061 * @error: location to store the error occuring, or %NULL to ignore
1062 * errors. Any of the errors in #GConvertError may occur.
1064 * Converts a string from UTF-8 to the encoding used for strings by
1065 * the C runtime (usually the same as that used by the operating
1066 * system) in the current locale.
1068 * Return value: The converted string, or %NULL on an error.
1071 g_locale_from_utf8 (const gchar *utf8string,
1074 gsize *bytes_written,
1077 #ifdef G_PLATFORM_WIN32
1079 gint i, mask, clen, mblen;
1082 guchar *cp, *end, c;
1086 len = strlen (utf8string);
1088 /* First convert to wide chars */
1089 cp = (guchar *) utf8string;
1092 wcs = g_new (wchar_t, len + 1);
1104 else if ((c & 0xe0) == 0xc0)
1109 else if ((c & 0xf0) == 0xe0)
1114 else if ((c & 0xf8) == 0xf0)
1119 else if ((c & 0xfc) == 0xf8)
1124 else if ((c & 0xfc) == 0xfc)
1135 if (cp + clen > end)
1141 *wcp = (cp[0] & mask);
1142 for (i = 1; i < clen; i++)
1144 if ((cp[i] & 0xc0) != 0x80)
1150 *wcp |= (cp[i] & 0x3f);
1163 /* n is the number of wide chars constructed */
1165 /* Convert to a string in the current ANSI codepage */
1167 result = g_new (gchar, 3 * n + 1);
1168 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1175 *bytes_written = mblen;
1179 #else /* !G_PLATFORM_WIN32 */
1181 const gchar *charset;
1183 if (g_get_charset (&charset))
1184 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1186 return g_convert (utf8string, len,
1187 charset, "UTF-8", bytes_read, bytes_written, error);
1189 #endif /* !G_PLATFORM_WIN32 */
1193 * g_filename_to_utf8:
1194 * @opsysstring: a string in the encoding for filenames
1195 * @len: the length of the string, or -1 if the string is
1197 * @bytes_read: location to store the number of bytes in the
1198 * input string that were successfully converted, or %NULL.
1199 * Even if the conversion was successful, this may be
1200 * less than @len if there were partial characters
1201 * at the end of the input. If the error
1202 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1203 * stored will the byte offset after the last valid
1205 * @bytes_written: the number of bytes stored in the output buffer (not
1206 * including the terminating nul).
1207 * @error: location to store the error occuring, or %NULL to ignore
1208 * errors. Any of the errors in #GConvertError may occur.
1210 * Converts a string which is in the encoding used for filenames
1211 * into a UTF-8 string.
1213 * Return value: The converted string, or %NULL on an error.
1216 g_filename_to_utf8 (const gchar *opsysstring,
1219 gsize *bytes_written,
1222 #ifdef G_PLATFORM_WIN32
1223 return g_locale_to_utf8 (opsysstring, len,
1224 bytes_read, bytes_written,
1226 #else /* !G_PLATFORM_WIN32 */
1228 if (getenv ("G_BROKEN_FILENAMES"))
1229 return g_locale_to_utf8 (opsysstring, len,
1230 bytes_read, bytes_written,
1233 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1234 #endif /* !G_PLATFORM_WIN32 */
1238 * g_filename_from_utf8:
1239 * @utf8string: a UTF-8 encoded string.
1240 * @len: the length of the string, or -1 if the string is
1242 * @bytes_read: location to store the number of bytes in the
1243 * input string that were successfully converted, or %NULL.
1244 * Even if the conversion was successful, this may be
1245 * less than @len if there were partial characters
1246 * at the end of the input. If the error
1247 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1248 * stored will the byte offset after the last valid
1250 * @bytes_written: the number of bytes stored in the output buffer (not
1251 * including the terminating nul).
1252 * @error: location to store the error occuring, or %NULL to ignore
1253 * errors. Any of the errors in #GConvertError may occur.
1255 * Converts a string from UTF-8 to the encoding used for filenames.
1257 * Return value: The converted string, or %NULL on an error.
1260 g_filename_from_utf8 (const gchar *utf8string,
1263 gsize *bytes_written,
1266 #ifdef G_PLATFORM_WIN32
1267 return g_locale_from_utf8 (utf8string, len,
1268 bytes_read, bytes_written,
1270 #else /* !G_PLATFORM_WIN32 */
1271 if (getenv ("G_BROKEN_FILENAMES"))
1272 return g_locale_from_utf8 (utf8string, len,
1273 bytes_read, bytes_written,
1276 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1277 #endif /* !G_PLATFORM_WIN32 */
1280 /* Test of haystack has the needle prefix, comparing case
1281 * insensitive. haystack may be UTF-8, but needle must
1282 * contain only ascii. */
1284 has_case_prefix (const gchar *haystack, const gchar *needle)
1288 /* Eat one character at a time. */
1293 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1303 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1304 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1305 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1306 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1307 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1308 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1309 } UnsafeCharacterSet;
1311 static const guchar acceptable[96] = {
1312 /* A table of the ASCII chars from space (32) to DEL (127) */
1313 /* ! " # $ % & ' ( ) * + , - . / */
1314 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1315 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1316 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1317 /* @ A B C D E F G H I J K L M N O */
1318 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1319 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1320 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1321 /* ` a b c d e f g h i j k l m n o */
1322 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1323 /* p q r s t u v w x y z { | } ~ DEL */
1324 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1327 static const gchar hex[16] = "0123456789ABCDEF";
1329 /* Note: This escape function works on file: URIs, but if you want to
1330 * escape something else, please read RFC-2396 */
1332 g_escape_uri_string (const gchar *string,
1333 UnsafeCharacterSet mask)
1335 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1342 UnsafeCharacterSet use_mask;
1344 g_return_val_if_fail (mask == UNSAFE_ALL
1345 || mask == UNSAFE_ALLOW_PLUS
1346 || mask == UNSAFE_PATH
1347 || mask == UNSAFE_DOS_PATH
1348 || mask == UNSAFE_HOST
1349 || mask == UNSAFE_SLASHES, NULL);
1353 for (p = string; *p != '\0'; p++)
1356 if (!ACCEPTABLE (c))
1360 result = g_malloc (p - string + unacceptable * 2 + 1);
1363 for (q = result, p = string; *p != '\0'; p++)
1367 if (!ACCEPTABLE (c))
1369 *q++ = '%'; /* means hex coming */
1384 g_escape_file_uri (const gchar *hostname,
1385 const gchar *pathname)
1387 char *escaped_hostname = NULL;
1392 char *p, *backslash;
1394 /* Turn backslashes into forward slashes. That's what Netscape
1395 * does, and they are actually more or less equivalent in Windows.
1398 pathname = g_strdup (pathname);
1399 p = (char *) pathname;
1401 while ((backslash = strchr (p, '\\')) != NULL)
1408 if (hostname && *hostname != '\0')
1410 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1413 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1415 res = g_strconcat ("file://",
1416 (escaped_hostname) ? escaped_hostname : "",
1417 (*escaped_path != '/') ? "/" : "",
1422 g_free ((char *) pathname);
1425 g_free (escaped_hostname);
1426 g_free (escaped_path);
1432 unescape_character (const char *scanner)
1437 first_digit = g_ascii_xdigit_value (scanner[0]);
1438 if (first_digit < 0)
1441 second_digit = g_ascii_xdigit_value (scanner[1]);
1442 if (second_digit < 0)
1445 return (first_digit << 4) | second_digit;
1449 g_unescape_uri_string (const char *escaped,
1451 const char *illegal_escaped_characters,
1452 gboolean ascii_must_not_be_escaped)
1454 const gchar *in, *in_end;
1455 gchar *out, *result;
1458 if (escaped == NULL)
1462 len = strlen (escaped);
1464 result = g_malloc (len + 1);
1467 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1473 /* catch partial escape sequences past the end of the substring */
1474 if (in + 3 > in_end)
1477 c = unescape_character (in + 1);
1479 /* catch bad escape sequences and NUL characters */
1483 /* catch escaped ASCII */
1484 if (ascii_must_not_be_escaped && c <= 0x7F)
1487 /* catch other illegal escaped characters */
1488 if (strchr (illegal_escaped_characters, c) != NULL)
1497 g_assert (out - result <= len);
1500 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1510 is_escalphanum (gunichar c)
1512 return c > 0x7F || g_ascii_isalnum (c);
1516 is_escalpha (gunichar c)
1518 return c > 0x7F || g_ascii_isalpha (c);
1521 /* allows an empty string */
1523 hostname_validate (const char *hostname)
1526 gunichar c, first_char, last_char;
1533 /* read in a label */
1534 c = g_utf8_get_char (p);
1535 p = g_utf8_next_char (p);
1536 if (!is_escalphanum (c))
1542 c = g_utf8_get_char (p);
1543 p = g_utf8_next_char (p);
1545 while (is_escalphanum (c) || c == '-');
1546 if (last_char == '-')
1549 /* if that was the last label, check that it was a toplabel */
1550 if (c == '\0' || (c == '.' && *p == '\0'))
1551 return is_escalpha (first_char);
1558 * g_filename_from_uri:
1559 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1560 * @hostname: Location to store hostname for the URI, or %NULL.
1561 * If there is no hostname in the URI, %NULL will be
1562 * stored in this location.
1563 * @error: location to store the error occuring, or %NULL to ignore
1564 * errors. Any of the errors in #GConvertError may occur.
1566 * Converts an escaped UTF-8 encoded URI to a local filename in the
1567 * encoding used for filenames.
1569 * Return value: a newly-allocated string holding the resulting
1570 * filename, or %NULL on an error.
1573 g_filename_from_uri (const char *uri,
1577 const char *path_part;
1578 const char *host_part;
1579 char *unescaped_hostname;
1590 if (!has_case_prefix (uri, "file:/"))
1592 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1593 _("The URI '%s' is not an absolute URI using the file scheme"),
1598 path_part = uri + strlen ("file:");
1600 if (strchr (path_part, '#') != NULL)
1602 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1603 _("The local file URI '%s' may not include a '#'"),
1608 if (has_case_prefix (path_part, "///"))
1610 else if (has_case_prefix (path_part, "//"))
1613 host_part = path_part;
1615 path_part = strchr (path_part, '/');
1617 if (path_part == NULL)
1619 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1620 _("The URI '%s' is invalid"),
1625 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1627 if (unescaped_hostname == NULL ||
1628 !hostname_validate (unescaped_hostname))
1630 g_free (unescaped_hostname);
1631 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1632 _("The hostname of the URI '%s' is invalid"),
1638 *hostname = unescaped_hostname;
1640 g_free (unescaped_hostname);
1643 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1645 if (filename == NULL)
1647 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1648 _("The URI '%s' contains invalidly escaped characters"),
1655 /* Drop localhost */
1656 if (hostname && *hostname != NULL &&
1657 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1663 /* Turn slashes into backslashes, because that's the canonical spelling */
1665 while ((slash = strchr (p, '/')) != NULL)
1671 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1672 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1673 * the filename from the drive letter.
1675 if (g_ascii_isalpha (filename[1]))
1677 if (filename[2] == ':')
1679 else if (filename[2] == '|')
1687 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1694 * g_filename_to_uri:
1695 * @filename: an absolute filename specified in the encoding
1696 * used for filenames by the operating system.
1697 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1698 * @error: location to store the error occuring, or %NULL to ignore
1699 * errors. Any of the errors in #GConvertError may occur.
1701 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1703 * Return value: a newly-allocated string holding the resulting
1704 * URI, or %NULL on an error.
1707 g_filename_to_uri (const char *filename,
1708 const char *hostname,
1712 char *utf8_filename;
1714 g_return_val_if_fail (filename != NULL, NULL);
1716 if (!g_path_is_absolute (filename))
1718 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1719 _("The pathname '%s' is not an absolute path"),
1725 !(g_utf8_validate (hostname, -1, NULL)
1726 && hostname_validate (hostname)))
1728 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1729 _("Invalid hostname"));
1733 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1734 if (utf8_filename == NULL)
1738 /* Don't use localhost unnecessarily */
1739 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1743 escaped_uri = g_escape_file_uri (hostname,
1745 g_free (utf8_filename);