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_GNU) && !defined (_LIBICONV_H)
42 #error GNU libiconv in use but included iconv.h not from libiconv
44 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
45 #error GNU 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, g_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 */
1192 #ifndef G_PLATFORM_WIN32
1194 have_broken_filenames (void)
1196 static gboolean initialized = FALSE;
1197 static gboolean broken;
1202 broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1208 #endif /* !G_PLATFORM_WIN32 */
1210 /* This is called from g_thread_init(). It's used to
1211 * initialize some static data in a threadsafe way.
1214 g_convert_init (void)
1216 #ifndef G_PLATFORM_WIN32
1217 (void)have_broken_filenames ();
1218 #endif /* !G_PLATFORM_WIN32 */
1222 * g_filename_to_utf8:
1223 * @opsysstring: a string in the encoding for filenames
1224 * @len: the length of the string, or -1 if the string is
1226 * @bytes_read: location to store the number of bytes in the
1227 * input string that were successfully converted, or %NULL.
1228 * Even if the conversion was successful, this may be
1229 * less than @len if there were partial characters
1230 * at the end of the input. If the error
1231 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1232 * stored will the byte offset after the last valid
1234 * @bytes_written: the number of bytes stored in the output buffer (not
1235 * including the terminating nul).
1236 * @error: location to store the error occuring, or %NULL to ignore
1237 * errors. Any of the errors in #GConvertError may occur.
1239 * Converts a string which is in the encoding used for filenames
1240 * into a UTF-8 string.
1242 * Return value: The converted string, or %NULL on an error.
1245 g_filename_to_utf8 (const gchar *opsysstring,
1248 gsize *bytes_written,
1251 #ifdef G_PLATFORM_WIN32
1252 return g_locale_to_utf8 (opsysstring, len,
1253 bytes_read, bytes_written,
1255 #else /* !G_PLATFORM_WIN32 */
1257 if (have_broken_filenames ())
1258 return g_locale_to_utf8 (opsysstring, len,
1259 bytes_read, bytes_written,
1262 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1263 #endif /* !G_PLATFORM_WIN32 */
1267 * g_filename_from_utf8:
1268 * @utf8string: a UTF-8 encoded string.
1269 * @len: the length of the string, or -1 if the string is
1271 * @bytes_read: location to store the number of bytes in the
1272 * input string that were successfully converted, or %NULL.
1273 * Even if the conversion was successful, this may be
1274 * less than @len if there were partial characters
1275 * at the end of the input. If the error
1276 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1277 * stored will the byte offset after the last valid
1279 * @bytes_written: the number of bytes stored in the output buffer (not
1280 * including the terminating nul).
1281 * @error: location to store the error occuring, or %NULL to ignore
1282 * errors. Any of the errors in #GConvertError may occur.
1284 * Converts a string from UTF-8 to the encoding used for filenames.
1286 * Return value: The converted string, or %NULL on an error.
1289 g_filename_from_utf8 (const gchar *utf8string,
1292 gsize *bytes_written,
1295 #ifdef G_PLATFORM_WIN32
1296 return g_locale_from_utf8 (utf8string, len,
1297 bytes_read, bytes_written,
1299 #else /* !G_PLATFORM_WIN32 */
1300 if (have_broken_filenames ())
1301 return g_locale_from_utf8 (utf8string, len,
1302 bytes_read, bytes_written,
1305 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1306 #endif /* !G_PLATFORM_WIN32 */
1309 /* Test of haystack has the needle prefix, comparing case
1310 * insensitive. haystack may be UTF-8, but needle must
1311 * contain only ascii. */
1313 has_case_prefix (const gchar *haystack, const gchar *needle)
1317 /* Eat one character at a time. */
1322 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1332 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1333 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1334 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1335 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1336 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1337 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1338 } UnsafeCharacterSet;
1340 static const guchar acceptable[96] = {
1341 /* A table of the ASCII chars from space (32) to DEL (127) */
1342 /* ! " # $ % & ' ( ) * + , - . / */
1343 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1344 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1345 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1346 /* @ A B C D E F G H I J K L M N O */
1347 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1348 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1349 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1350 /* ` a b c d e f g h i j k l m n o */
1351 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1352 /* p q r s t u v w x y z { | } ~ DEL */
1353 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1356 static const gchar hex[16] = "0123456789ABCDEF";
1358 /* Note: This escape function works on file: URIs, but if you want to
1359 * escape something else, please read RFC-2396 */
1361 g_escape_uri_string (const gchar *string,
1362 UnsafeCharacterSet mask)
1364 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1371 UnsafeCharacterSet use_mask;
1373 g_return_val_if_fail (mask == UNSAFE_ALL
1374 || mask == UNSAFE_ALLOW_PLUS
1375 || mask == UNSAFE_PATH
1376 || mask == UNSAFE_DOS_PATH
1377 || mask == UNSAFE_HOST
1378 || mask == UNSAFE_SLASHES, NULL);
1382 for (p = string; *p != '\0'; p++)
1385 if (!ACCEPTABLE (c))
1389 result = g_malloc (p - string + unacceptable * 2 + 1);
1392 for (q = result, p = string; *p != '\0'; p++)
1396 if (!ACCEPTABLE (c))
1398 *q++ = '%'; /* means hex coming */
1413 g_escape_file_uri (const gchar *hostname,
1414 const gchar *pathname)
1416 char *escaped_hostname = NULL;
1421 char *p, *backslash;
1423 /* Turn backslashes into forward slashes. That's what Netscape
1424 * does, and they are actually more or less equivalent in Windows.
1427 pathname = g_strdup (pathname);
1428 p = (char *) pathname;
1430 while ((backslash = strchr (p, '\\')) != NULL)
1437 if (hostname && *hostname != '\0')
1439 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1442 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1444 res = g_strconcat ("file://",
1445 (escaped_hostname) ? escaped_hostname : "",
1446 (*escaped_path != '/') ? "/" : "",
1451 g_free ((char *) pathname);
1454 g_free (escaped_hostname);
1455 g_free (escaped_path);
1461 unescape_character (const char *scanner)
1466 first_digit = g_ascii_xdigit_value (scanner[0]);
1467 if (first_digit < 0)
1470 second_digit = g_ascii_xdigit_value (scanner[1]);
1471 if (second_digit < 0)
1474 return (first_digit << 4) | second_digit;
1478 g_unescape_uri_string (const char *escaped,
1480 const char *illegal_escaped_characters,
1481 gboolean ascii_must_not_be_escaped)
1483 const gchar *in, *in_end;
1484 gchar *out, *result;
1487 if (escaped == NULL)
1491 len = strlen (escaped);
1493 result = g_malloc (len + 1);
1496 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1502 /* catch partial escape sequences past the end of the substring */
1503 if (in + 3 > in_end)
1506 c = unescape_character (in + 1);
1508 /* catch bad escape sequences and NUL characters */
1512 /* catch escaped ASCII */
1513 if (ascii_must_not_be_escaped && c <= 0x7F)
1516 /* catch other illegal escaped characters */
1517 if (strchr (illegal_escaped_characters, c) != NULL)
1526 g_assert (out - result <= len);
1529 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1539 is_escalphanum (gunichar c)
1541 return c > 0x7F || g_ascii_isalnum (c);
1545 is_escalpha (gunichar c)
1547 return c > 0x7F || g_ascii_isalpha (c);
1550 /* allows an empty string */
1552 hostname_validate (const char *hostname)
1555 gunichar c, first_char, last_char;
1562 /* read in a label */
1563 c = g_utf8_get_char (p);
1564 p = g_utf8_next_char (p);
1565 if (!is_escalphanum (c))
1571 c = g_utf8_get_char (p);
1572 p = g_utf8_next_char (p);
1574 while (is_escalphanum (c) || c == '-');
1575 if (last_char == '-')
1578 /* if that was the last label, check that it was a toplabel */
1579 if (c == '\0' || (c == '.' && *p == '\0'))
1580 return is_escalpha (first_char);
1587 * g_filename_from_uri:
1588 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1589 * @hostname: Location to store hostname for the URI, or %NULL.
1590 * If there is no hostname in the URI, %NULL will be
1591 * stored in this location.
1592 * @error: location to store the error occuring, or %NULL to ignore
1593 * errors. Any of the errors in #GConvertError may occur.
1595 * Converts an escaped UTF-8 encoded URI to a local filename in the
1596 * encoding used for filenames.
1598 * Return value: a newly-allocated string holding the resulting
1599 * filename, or %NULL on an error.
1602 g_filename_from_uri (const char *uri,
1606 const char *path_part;
1607 const char *host_part;
1608 char *unescaped_hostname;
1619 if (!has_case_prefix (uri, "file:/"))
1621 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1622 _("The URI '%s' is not an absolute URI using the file scheme"),
1627 path_part = uri + strlen ("file:");
1629 if (strchr (path_part, '#') != NULL)
1631 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1632 _("The local file URI '%s' may not include a '#'"),
1637 if (has_case_prefix (path_part, "///"))
1639 else if (has_case_prefix (path_part, "//"))
1642 host_part = path_part;
1644 path_part = strchr (path_part, '/');
1646 if (path_part == NULL)
1648 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1649 _("The URI '%s' is invalid"),
1654 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1656 if (unescaped_hostname == NULL ||
1657 !hostname_validate (unescaped_hostname))
1659 g_free (unescaped_hostname);
1660 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1661 _("The hostname of the URI '%s' is invalid"),
1667 *hostname = unescaped_hostname;
1669 g_free (unescaped_hostname);
1672 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1674 if (filename == NULL)
1676 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1677 _("The URI '%s' contains invalidly escaped characters"),
1684 /* Drop localhost */
1685 if (hostname && *hostname != NULL &&
1686 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1692 /* Turn slashes into backslashes, because that's the canonical spelling */
1694 while ((slash = strchr (p, '/')) != NULL)
1700 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1701 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1702 * the filename from the drive letter.
1704 if (g_ascii_isalpha (filename[1]))
1706 if (filename[2] == ':')
1708 else if (filename[2] == '|')
1716 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1723 * g_filename_to_uri:
1724 * @filename: an absolute filename specified in the encoding
1725 * used for filenames by the operating system.
1726 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1727 * @error: location to store the error occuring, or %NULL to ignore
1728 * errors. Any of the errors in #GConvertError may occur.
1730 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1732 * Return value: a newly-allocated string holding the resulting
1733 * URI, or %NULL on an error.
1736 g_filename_to_uri (const char *filename,
1737 const char *hostname,
1741 char *utf8_filename;
1743 g_return_val_if_fail (filename != NULL, NULL);
1745 if (!g_path_is_absolute (filename))
1747 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1748 _("The pathname '%s' is not an absolute path"),
1754 !(g_utf8_validate (hostname, -1, NULL)
1755 && hostname_validate (hostname)))
1757 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1758 _("Invalid hostname"));
1762 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1763 if (utf8_filename == NULL)
1767 /* Don't use localhost unnecessarily */
1768 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1772 escaped_uri = g_escape_file_uri (hostname,
1774 g_free (utf8_filename);