1 /* GLIB - Library of useful routines for C programming
3 * gconvert.c: Convert between character sets using iconv
4 * Copyright Red Hat Inc., 2000
5 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
32 #include "gprintfint.h"
34 #ifdef G_PLATFORM_WIN32
42 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
43 #error GNU libiconv in use but included iconv.h not from libiconv
45 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
46 #error GNU libiconv not in use but included iconv.h is from libiconv
50 g_convert_error_quark (void)
54 quark = g_quark_from_static_string ("g_convert_error");
60 try_conversion (const char *to_codeset,
61 const char *from_codeset,
64 *cd = iconv_open (to_codeset, from_codeset);
66 if (*cd == (iconv_t)-1 && errno == EINVAL)
73 try_to_aliases (const char **to_aliases,
74 const char *from_codeset,
79 const char **p = to_aliases;
82 if (try_conversion (*p, from_codeset, cd))
92 extern const char **_g_charset_get_aliases (const char *canonical_name);
96 * @to_codeset: destination codeset
97 * @from_codeset: source codeset
99 * Same as the standard UNIX routine <function>iconv_open()</function>, but
100 * may be implemented via libiconv on UNIX flavors that lack
101 * a native implementation.
103 * GLib provides g_convert() and g_locale_to_utf8() which are likely
104 * more convenient than the raw iconv wrappers.
106 * Return value: a "conversion descriptor", or (GIConv)-1 if
107 * opening the converter failed.
110 g_iconv_open (const gchar *to_codeset,
111 const gchar *from_codeset)
115 if (!try_conversion (to_codeset, from_codeset, &cd))
117 const char **to_aliases = _g_charset_get_aliases (to_codeset);
118 const char **from_aliases = _g_charset_get_aliases (from_codeset);
122 const char **p = from_aliases;
125 if (try_conversion (to_codeset, *p, &cd))
128 if (try_to_aliases (to_aliases, *p, &cd))
135 if (try_to_aliases (to_aliases, from_codeset, &cd))
140 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
145 * @converter: conversion descriptor from g_iconv_open()
146 * @inbuf: bytes to convert
147 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
148 * @outbuf: converted output bytes
149 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
151 * Same as the standard UNIX routine <function>iconv()</function>, but
152 * may be implemented via libiconv on UNIX flavors that lack
153 * a native implementation.
155 * GLib provides g_convert() and g_locale_to_utf8() which are likely
156 * more convenient than the raw iconv wrappers.
158 * Return value: count of non-reversible conversions, or -1 on error
161 g_iconv (GIConv converter,
165 gsize *outbytes_left)
167 iconv_t cd = (iconv_t)converter;
169 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
174 * @converter: a conversion descriptor from g_iconv_open()
176 * Same as the standard UNIX routine <function>iconv_close()</function>, but
177 * may be implemented via libiconv on UNIX flavors that lack
178 * a native implementation. Should be called to clean up
179 * the conversion descriptor from g_iconv_open() when
180 * you are done converting things.
182 * GLib provides g_convert() and g_locale_to_utf8() which are likely
183 * more convenient than the raw iconv wrappers.
185 * Return value: -1 on error, 0 on success
188 g_iconv_close (GIConv converter)
190 iconv_t cd = (iconv_t)converter;
192 return iconv_close (cd);
196 #define ICONV_CACHE_SIZE (16)
198 struct _iconv_cache_bucket {
205 static GList *iconv_cache_list;
206 static GHashTable *iconv_cache;
207 static GHashTable *iconv_open_hash;
208 static guint iconv_cache_size = 0;
209 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
211 /* caller *must* hold the iconv_cache_lock */
213 iconv_cache_init (void)
215 static gboolean initialized = FALSE;
220 iconv_cache_list = NULL;
221 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
222 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
229 * iconv_cache_bucket_new:
231 * @cd: iconv descriptor
233 * Creates a new cache bucket, inserts it into the cache and
234 * increments the cache size.
236 * Returns a pointer to the newly allocated cache bucket.
238 struct _iconv_cache_bucket *
239 iconv_cache_bucket_new (const gchar *key, GIConv cd)
241 struct _iconv_cache_bucket *bucket;
243 bucket = g_new (struct _iconv_cache_bucket, 1);
244 bucket->key = g_strdup (key);
245 bucket->refcount = 1;
249 g_hash_table_insert (iconv_cache, bucket->key, bucket);
251 /* FIXME: if we sorted the list so items with few refcounts were
252 first, then we could expire them faster in iconv_cache_expire_unused () */
253 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
262 * iconv_cache_bucket_expire:
263 * @node: cache bucket's node
264 * @bucket: cache bucket
266 * Expires a single cache bucket @bucket. This should only ever be
267 * called on a bucket that currently has no used iconv descriptors
270 * @node is not a required argument. If @node is not supplied, we
271 * search for it ourselves.
274 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
276 g_hash_table_remove (iconv_cache, bucket->key);
279 node = g_list_find (iconv_cache_list, bucket);
281 g_assert (node != NULL);
285 node->prev->next = node->next;
287 node->next->prev = node->prev;
291 iconv_cache_list = node->next;
293 node->next->prev = NULL;
296 g_list_free_1 (node);
298 g_free (bucket->key);
299 g_iconv_close (bucket->cd);
307 * iconv_cache_expire_unused:
309 * Expires as many unused cache buckets as it needs to in order to get
310 * the total number of buckets < ICONV_CACHE_SIZE.
313 iconv_cache_expire_unused (void)
315 struct _iconv_cache_bucket *bucket;
318 node = iconv_cache_list;
319 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
324 if (bucket->refcount == 0)
325 iconv_cache_bucket_expire (node, bucket);
332 open_converter (const gchar *to_codeset,
333 const gchar *from_codeset,
336 struct _iconv_cache_bucket *bucket;
341 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
342 _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
344 G_LOCK (iconv_cache_lock);
346 /* make sure the cache has been initialized */
349 bucket = g_hash_table_lookup (iconv_cache, key);
354 cd = g_iconv_open (to_codeset, from_codeset);
355 if (cd == (GIConv) -1)
360 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
361 * NULL for anything but inbuf; work around that. (NULL outbuf
362 * or NULL *outbuf is allowed by Unix98.)
364 gsize inbytes_left = 0;
365 gchar *outbuf = NULL;
366 gsize outbytes_left = 0;
371 /* reset the descriptor */
372 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
379 cd = g_iconv_open (to_codeset, from_codeset);
380 if (cd == (GIConv) -1)
383 iconv_cache_expire_unused ();
385 bucket = iconv_cache_bucket_new (key, cd);
388 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
390 G_UNLOCK (iconv_cache_lock);
396 G_UNLOCK (iconv_cache_lock);
398 /* Something went wrong. */
400 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
401 _("Conversion from character set '%s' to '%s' is not supported"),
402 from_codeset, to_codeset);
404 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
405 _("Could not open converter from '%s' to '%s': %s"),
406 from_codeset, to_codeset, g_strerror (errno));
412 close_converter (GIConv converter)
414 struct _iconv_cache_bucket *bucket;
420 if (cd == (GIConv) -1)
423 G_LOCK (iconv_cache_lock);
425 key = g_hash_table_lookup (iconv_open_hash, cd);
428 g_hash_table_remove (iconv_open_hash, cd);
430 bucket = g_hash_table_lookup (iconv_cache, key);
435 if (cd == bucket->cd)
436 bucket->used = FALSE;
440 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
442 /* expire this cache bucket */
443 iconv_cache_bucket_expire (NULL, bucket);
448 G_UNLOCK (iconv_cache_lock);
450 g_warning ("This iconv context wasn't opened using open_converter");
452 return g_iconv_close (converter);
455 G_UNLOCK (iconv_cache_lock);
463 * @str: the string to convert
464 * @len: the length of the string
465 * @to_codeset: name of character set into which to convert @str
466 * @from_codeset: character set of @str.
467 * @bytes_read: location to store the number of bytes in the
468 * input string that were successfully converted, or %NULL.
469 * Even if the conversion was successful, this may be
470 * less than @len if there were partial characters
471 * at the end of the input. If the error
472 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
473 * stored will the byte offset after the last valid
475 * @bytes_written: the number of bytes stored in the output buffer (not
476 * including the terminating nul).
477 * @error: location to store the error occuring, or %NULL to ignore
478 * errors. Any of the errors in #GConvertError may occur.
480 * Converts a string from one character set to another.
482 * Return value: If the conversion was successful, a newly allocated
483 * nul-terminated string, which must be freed with
484 * g_free(). Otherwise %NULL and @error will be set.
487 g_convert (const gchar *str,
489 const gchar *to_codeset,
490 const gchar *from_codeset,
492 gsize *bytes_written,
498 g_return_val_if_fail (str != NULL, NULL);
499 g_return_val_if_fail (to_codeset != NULL, NULL);
500 g_return_val_if_fail (from_codeset != NULL, NULL);
502 cd = open_converter (to_codeset, from_codeset, error);
504 if (cd == (GIConv) -1)
515 res = g_convert_with_iconv (str, len, cd,
516 bytes_read, bytes_written,
519 close_converter (cd);
525 * g_convert_with_iconv:
526 * @str: the string to convert
527 * @len: the length of the string
528 * @converter: conversion descriptor from g_iconv_open()
529 * @bytes_read: location to store the number of bytes in the
530 * input string that were successfully converted, or %NULL.
531 * Even if the conversion was successful, this may be
532 * less than @len if there were partial characters
533 * at the end of the input. If the error
534 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
535 * stored will the byte offset after the last valid
537 * @bytes_written: the number of bytes stored in the output buffer (not
538 * including the terminating nul).
539 * @error: location to store the error occuring, or %NULL to ignore
540 * errors. Any of the errors in #GConvertError may occur.
542 * Converts a string from one character set to another.
544 * Return value: If the conversion was successful, a newly allocated
545 * nul-terminated string, which must be freed with
546 * g_free(). Otherwise %NULL and @error will be set.
549 g_convert_with_iconv (const gchar *str,
553 gsize *bytes_written,
559 gsize inbytes_remaining;
560 gsize outbytes_remaining;
563 gboolean have_error = FALSE;
565 g_return_val_if_fail (str != NULL, NULL);
566 g_return_val_if_fail (converter != (GIConv) -1, NULL);
572 inbytes_remaining = len;
573 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
575 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
576 outp = dest = g_malloc (outbuf_size);
580 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
582 if (err == (size_t) -1)
587 /* Incomplete text, do not report an error */
591 size_t used = outp - dest;
594 dest = g_realloc (dest, outbuf_size);
597 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
602 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
603 _("Invalid byte sequence in conversion input"));
607 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
608 _("Error during conversion: %s"),
618 *bytes_read = p - str;
621 if ((p - str) != len)
625 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
626 _("Partial character sequence at end of input"));
633 *bytes_written = outp - dest; /* Doesn't include '\0' */
645 * g_convert_with_fallback:
646 * @str: the string to convert
647 * @len: the length of the string
648 * @to_codeset: name of character set into which to convert @str
649 * @from_codeset: character set of @str.
650 * @fallback: UTF-8 string to use in place of character not
651 * present in the target encoding. (This must be
652 * in the target encoding), if %NULL, characters
653 * not in the target encoding will be represented
654 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
655 * @bytes_read: location to store the number of bytes in the
656 * input string that were successfully converted, or %NULL.
657 * Even if the conversion was successful, this may be
658 * less than @len if there were partial characters
659 * at the end of the input.
660 * @bytes_written: the number of bytes stored in the output buffer (not
661 * including the terminating nul).
662 * @error: location to store the error occuring, or %NULL to ignore
663 * errors. Any of the errors in #GConvertError may occur.
665 * Converts a string from one character set to another, possibly
666 * including fallback sequences for characters not representable
667 * in the output. Note that it is not guaranteed that the specification
668 * for the fallback sequences in @fallback will be honored. Some
669 * systems may do a approximate conversion from @from_codeset
670 * to @to_codeset in their <function>iconv()</function> functions,
671 * in which case GLib will simply return that approximate conversion.
673 * Return value: If the conversion was successful, a newly allocated
674 * nul-terminated string, which must be freed with
675 * g_free(). Otherwise %NULL and @error will be set.
678 g_convert_with_fallback (const gchar *str,
680 const gchar *to_codeset,
681 const gchar *from_codeset,
684 gsize *bytes_written,
690 const gchar *insert_str = NULL;
692 gsize inbytes_remaining;
693 const gchar *save_p = NULL;
694 gsize save_inbytes = 0;
695 gsize outbytes_remaining;
699 gboolean have_error = FALSE;
700 gboolean done = FALSE;
702 GError *local_error = NULL;
704 g_return_val_if_fail (str != NULL, NULL);
705 g_return_val_if_fail (to_codeset != NULL, NULL);
706 g_return_val_if_fail (from_codeset != NULL, NULL);
711 /* Try an exact conversion; we only proceed if this fails
712 * due to an illegal sequence in the input string.
714 dest = g_convert (str, len, to_codeset, from_codeset,
715 bytes_read, bytes_written, &local_error);
719 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
721 g_propagate_error (error, local_error);
725 g_error_free (local_error);
729 /* No go; to proceed, we need a converter from "UTF-8" to
730 * to_codeset, and the string as UTF-8.
732 cd = open_converter (to_codeset, "UTF-8", error);
733 if (cd == (GIConv) -1)
744 utf8 = g_convert (str, len, "UTF-8", from_codeset,
745 bytes_read, &inbytes_remaining, error);
748 close_converter (cd);
754 /* Now the heart of the code. We loop through the UTF-8 string, and
755 * whenever we hit an offending character, we form fallback, convert
756 * the fallback to the target codeset, and then go back to
757 * converting the original string after finishing with the fallback.
759 * The variables save_p and save_inbytes store the input state
760 * for the original string while we are converting the fallback
764 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
765 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
766 outp = dest = g_malloc (outbuf_size);
768 while (!done && !have_error)
770 size_t inbytes_tmp = inbytes_remaining;
771 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
772 inbytes_remaining = inbytes_tmp;
774 if (err == (size_t) -1)
779 g_assert_not_reached();
783 size_t used = outp - dest;
786 dest = g_realloc (dest, outbuf_size);
789 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
796 /* Error converting fallback string - fatal
798 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
799 _("Cannot convert fallback '%s' to codeset '%s'"),
800 insert_str, to_codeset);
808 gunichar ch = g_utf8_get_char (p);
809 insert_str = g_strdup_printf ("\\x{%0*X}",
810 (ch < 0x10000) ? 4 : 6,
814 insert_str = fallback;
816 save_p = g_utf8_next_char (p);
817 save_inbytes = inbytes_remaining - (save_p - p);
819 inbytes_remaining = strlen (p);
823 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
824 _("Error during conversion: %s"),
835 g_free ((gchar *)insert_str);
837 inbytes_remaining = save_inbytes;
849 close_converter (cd);
852 *bytes_written = outp - dest; /* Doesn't include '\0' */
858 if (save_p && !fallback)
859 g_free ((gchar *)insert_str);
873 #ifndef G_PLATFORM_WIN32
876 strdup_len (const gchar *string,
878 gsize *bytes_written,
885 if (!g_utf8_validate (string, len, NULL))
892 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
893 _("Invalid byte sequence in conversion input"));
898 real_len = strlen (string);
903 while (real_len < len && string[real_len])
908 *bytes_read = real_len;
910 *bytes_written = real_len;
912 return g_strndup (string, real_len);
919 * @opsysstring: a string in the encoding of the current locale
920 * @len: the length of the string, or -1 if the string is
922 * @bytes_read: location to store the number of bytes in the
923 * input string that were successfully converted, or %NULL.
924 * Even if the conversion was successful, this may be
925 * less than @len if there were partial characters
926 * at the end of the input. If the error
927 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
928 * stored will the byte offset after the last valid
930 * @bytes_written: the number of bytes stored in the output buffer (not
931 * including the terminating nul).
932 * @error: location to store the error occuring, or %NULL to ignore
933 * errors. Any of the errors in #GConvertError may occur.
935 * Converts a string which is in the encoding used for strings by
936 * the C runtime (usually the same as that used by the operating
937 * system) in the current locale into a UTF-8 string.
939 * Return value: The converted string, or %NULL on an error.
942 g_locale_to_utf8 (const gchar *opsysstring,
945 gsize *bytes_written,
948 #ifdef G_PLATFORM_WIN32
950 gint i, clen, total_len, wclen, first;
956 len = strlen (opsysstring);
958 wcs = g_new (wchar_t, len);
959 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
963 for (i = 0; i < wclen; i++)
971 else if (wc < 0x10000)
973 else if (wc < 0x200000)
975 else if (wc < 0x4000000)
981 result = g_malloc (total_len + 1);
985 for (i = 0; i < wclen; i++)
999 else if (wc < 0x10000)
1004 else if (wc < 0x200000)
1009 else if (wc < 0x4000000)
1023 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1024 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1025 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1026 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1027 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1028 case 1: bp[0] = wc | first;
1040 *bytes_written = total_len;
1044 #else /* !G_PLATFORM_WIN32 */
1046 const char *charset;
1048 if (g_get_charset (&charset))
1049 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1051 return g_convert (opsysstring, len,
1052 "UTF-8", charset, bytes_read, bytes_written, error);
1054 #endif /* !G_PLATFORM_WIN32 */
1058 * g_locale_from_utf8:
1059 * @utf8string: a UTF-8 encoded string
1060 * @len: the length of the string, or -1 if the string is
1062 * @bytes_read: location to store the number of bytes in the
1063 * input string that were successfully converted, or %NULL.
1064 * Even if the conversion was successful, this may be
1065 * less than @len if there were partial characters
1066 * at the end of the input. If the error
1067 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1068 * stored will the byte offset after the last valid
1070 * @bytes_written: the number of bytes stored in the output buffer (not
1071 * including the terminating nul).
1072 * @error: location to store the error occuring, or %NULL to ignore
1073 * errors. Any of the errors in #GConvertError may occur.
1075 * Converts a string from UTF-8 to the encoding used for strings by
1076 * the C runtime (usually the same as that used by the operating
1077 * system) in the current locale.
1079 * Return value: The converted string, or %NULL on an error.
1082 g_locale_from_utf8 (const gchar *utf8string,
1085 gsize *bytes_written,
1088 #ifdef G_PLATFORM_WIN32
1090 gint i, mask, clen, mblen;
1093 guchar *cp, *end, c;
1097 len = strlen (utf8string);
1099 /* First convert to wide chars */
1100 cp = (guchar *) utf8string;
1103 wcs = g_new (wchar_t, len + 1);
1115 else if ((c & 0xe0) == 0xc0)
1120 else if ((c & 0xf0) == 0xe0)
1125 else if ((c & 0xf8) == 0xf0)
1130 else if ((c & 0xfc) == 0xf8)
1135 else if ((c & 0xfc) == 0xfc)
1146 if (cp + clen > end)
1152 *wcp = (cp[0] & mask);
1153 for (i = 1; i < clen; i++)
1155 if ((cp[i] & 0xc0) != 0x80)
1161 *wcp |= (cp[i] & 0x3f);
1174 /* n is the number of wide chars constructed */
1176 /* Convert to a string in the current ANSI codepage */
1178 result = g_new (gchar, 3 * n + 1);
1179 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1186 *bytes_written = mblen;
1190 #else /* !G_PLATFORM_WIN32 */
1192 const gchar *charset;
1194 if (g_get_charset (&charset))
1195 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1197 return g_convert (utf8string, len,
1198 charset, "UTF-8", bytes_read, bytes_written, error);
1200 #endif /* !G_PLATFORM_WIN32 */
1203 #ifndef G_PLATFORM_WIN32
1205 have_broken_filenames (void)
1207 static gboolean initialized = FALSE;
1208 static gboolean broken;
1213 broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1219 #endif /* !G_PLATFORM_WIN32 */
1221 /* This is called from g_thread_init(). It's used to
1222 * initialize some static data in a threadsafe way.
1225 g_convert_init (void)
1227 #ifndef G_PLATFORM_WIN32
1228 (void)have_broken_filenames ();
1229 #endif /* !G_PLATFORM_WIN32 */
1233 * g_filename_to_utf8:
1234 * @opsysstring: a string in the encoding for filenames
1235 * @len: the length of the string, or -1 if the string is
1237 * @bytes_read: location to store the number of bytes in the
1238 * input string that were successfully converted, or %NULL.
1239 * Even if the conversion was successful, this may be
1240 * less than @len if there were partial characters
1241 * at the end of the input. If the error
1242 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1243 * stored will the byte offset after the last valid
1245 * @bytes_written: the number of bytes stored in the output buffer (not
1246 * including the terminating nul).
1247 * @error: location to store the error occuring, or %NULL to ignore
1248 * errors. Any of the errors in #GConvertError may occur.
1250 * Converts a string which is in the encoding used for filenames
1251 * into a UTF-8 string.
1253 * Return value: The converted string, or %NULL on an error.
1256 g_filename_to_utf8 (const gchar *opsysstring,
1259 gsize *bytes_written,
1262 #ifdef G_PLATFORM_WIN32
1263 return g_locale_to_utf8 (opsysstring, len,
1264 bytes_read, bytes_written,
1266 #else /* !G_PLATFORM_WIN32 */
1268 if (have_broken_filenames ())
1269 return g_locale_to_utf8 (opsysstring, len,
1270 bytes_read, bytes_written,
1273 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1274 #endif /* !G_PLATFORM_WIN32 */
1278 * g_filename_from_utf8:
1279 * @utf8string: a UTF-8 encoded string.
1280 * @len: the length of the string, or -1 if the string is
1282 * @bytes_read: location to store the number of bytes in the
1283 * input string that were successfully converted, or %NULL.
1284 * Even if the conversion was successful, this may be
1285 * less than @len if there were partial characters
1286 * at the end of the input. If the error
1287 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1288 * stored will the byte offset after the last valid
1290 * @bytes_written: the number of bytes stored in the output buffer (not
1291 * including the terminating nul).
1292 * @error: location to store the error occuring, or %NULL to ignore
1293 * errors. Any of the errors in #GConvertError may occur.
1295 * Converts a string from UTF-8 to the encoding used for filenames.
1297 * Return value: The converted string, or %NULL on an error.
1300 g_filename_from_utf8 (const gchar *utf8string,
1303 gsize *bytes_written,
1306 #ifdef G_PLATFORM_WIN32
1307 return g_locale_from_utf8 (utf8string, len,
1308 bytes_read, bytes_written,
1310 #else /* !G_PLATFORM_WIN32 */
1311 if (have_broken_filenames ())
1312 return g_locale_from_utf8 (utf8string, len,
1313 bytes_read, bytes_written,
1316 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1317 #endif /* !G_PLATFORM_WIN32 */
1320 /* Test of haystack has the needle prefix, comparing case
1321 * insensitive. haystack may be UTF-8, but needle must
1322 * contain only ascii. */
1324 has_case_prefix (const gchar *haystack, const gchar *needle)
1328 /* Eat one character at a time. */
1333 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1343 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1344 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1345 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1346 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1347 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1348 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1349 } UnsafeCharacterSet;
1351 static const guchar acceptable[96] = {
1352 /* A table of the ASCII chars from space (32) to DEL (127) */
1353 /* ! " # $ % & ' ( ) * + , - . / */
1354 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1355 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1356 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1357 /* @ A B C D E F G H I J K L M N O */
1358 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1359 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1360 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1361 /* ` a b c d e f g h i j k l m n o */
1362 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1363 /* p q r s t u v w x y z { | } ~ DEL */
1364 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1367 static const gchar hex[16] = "0123456789ABCDEF";
1369 /* Note: This escape function works on file: URIs, but if you want to
1370 * escape something else, please read RFC-2396 */
1372 g_escape_uri_string (const gchar *string,
1373 UnsafeCharacterSet mask)
1375 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1382 UnsafeCharacterSet use_mask;
1384 g_return_val_if_fail (mask == UNSAFE_ALL
1385 || mask == UNSAFE_ALLOW_PLUS
1386 || mask == UNSAFE_PATH
1387 || mask == UNSAFE_DOS_PATH
1388 || mask == UNSAFE_HOST
1389 || mask == UNSAFE_SLASHES, NULL);
1393 for (p = string; *p != '\0'; p++)
1396 if (!ACCEPTABLE (c))
1400 result = g_malloc (p - string + unacceptable * 2 + 1);
1403 for (q = result, p = string; *p != '\0'; p++)
1407 if (!ACCEPTABLE (c))
1409 *q++ = '%'; /* means hex coming */
1424 g_escape_file_uri (const gchar *hostname,
1425 const gchar *pathname)
1427 char *escaped_hostname = NULL;
1432 char *p, *backslash;
1434 /* Turn backslashes into forward slashes. That's what Netscape
1435 * does, and they are actually more or less equivalent in Windows.
1438 pathname = g_strdup (pathname);
1439 p = (char *) pathname;
1441 while ((backslash = strchr (p, '\\')) != NULL)
1448 if (hostname && *hostname != '\0')
1450 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1453 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1455 res = g_strconcat ("file://",
1456 (escaped_hostname) ? escaped_hostname : "",
1457 (*escaped_path != '/') ? "/" : "",
1462 g_free ((char *) pathname);
1465 g_free (escaped_hostname);
1466 g_free (escaped_path);
1472 unescape_character (const char *scanner)
1477 first_digit = g_ascii_xdigit_value (scanner[0]);
1478 if (first_digit < 0)
1481 second_digit = g_ascii_xdigit_value (scanner[1]);
1482 if (second_digit < 0)
1485 return (first_digit << 4) | second_digit;
1489 g_unescape_uri_string (const char *escaped,
1491 const char *illegal_escaped_characters,
1492 gboolean ascii_must_not_be_escaped)
1494 const gchar *in, *in_end;
1495 gchar *out, *result;
1498 if (escaped == NULL)
1502 len = strlen (escaped);
1504 result = g_malloc (len + 1);
1507 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1513 /* catch partial escape sequences past the end of the substring */
1514 if (in + 3 > in_end)
1517 c = unescape_character (in + 1);
1519 /* catch bad escape sequences and NUL characters */
1523 /* catch escaped ASCII */
1524 if (ascii_must_not_be_escaped && c <= 0x7F)
1527 /* catch other illegal escaped characters */
1528 if (strchr (illegal_escaped_characters, c) != NULL)
1537 g_assert (out - result <= len);
1540 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1550 is_escalphanum (gunichar c)
1552 return c > 0x7F || g_ascii_isalnum (c);
1556 is_escalpha (gunichar c)
1558 return c > 0x7F || g_ascii_isalpha (c);
1561 /* allows an empty string */
1563 hostname_validate (const char *hostname)
1566 gunichar c, first_char, last_char;
1573 /* read in a label */
1574 c = g_utf8_get_char (p);
1575 p = g_utf8_next_char (p);
1576 if (!is_escalphanum (c))
1582 c = g_utf8_get_char (p);
1583 p = g_utf8_next_char (p);
1585 while (is_escalphanum (c) || c == '-');
1586 if (last_char == '-')
1589 /* if that was the last label, check that it was a toplabel */
1590 if (c == '\0' || (c == '.' && *p == '\0'))
1591 return is_escalpha (first_char);
1598 * g_filename_from_uri:
1599 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1600 * @hostname: Location to store hostname for the URI, or %NULL.
1601 * If there is no hostname in the URI, %NULL will be
1602 * stored in this location.
1603 * @error: location to store the error occuring, or %NULL to ignore
1604 * errors. Any of the errors in #GConvertError may occur.
1606 * Converts an escaped UTF-8 encoded URI to a local filename in the
1607 * encoding used for filenames.
1609 * Return value: a newly-allocated string holding the resulting
1610 * filename, or %NULL on an error.
1613 g_filename_from_uri (const char *uri,
1617 const char *path_part;
1618 const char *host_part;
1619 char *unescaped_hostname;
1630 if (!has_case_prefix (uri, "file:/"))
1632 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1633 _("The URI '%s' is not an absolute URI using the file scheme"),
1638 path_part = uri + strlen ("file:");
1640 if (strchr (path_part, '#') != NULL)
1642 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1643 _("The local file URI '%s' may not include a '#'"),
1648 if (has_case_prefix (path_part, "///"))
1650 else if (has_case_prefix (path_part, "//"))
1653 host_part = path_part;
1655 path_part = strchr (path_part, '/');
1657 if (path_part == NULL)
1659 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1660 _("The URI '%s' is invalid"),
1665 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1667 if (unescaped_hostname == NULL ||
1668 !hostname_validate (unescaped_hostname))
1670 g_free (unescaped_hostname);
1671 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1672 _("The hostname of the URI '%s' is invalid"),
1678 *hostname = unescaped_hostname;
1680 g_free (unescaped_hostname);
1683 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1685 if (filename == NULL)
1687 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1688 _("The URI '%s' contains invalidly escaped characters"),
1695 /* Drop localhost */
1696 if (hostname && *hostname != NULL &&
1697 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1703 /* Turn slashes into backslashes, because that's the canonical spelling */
1705 while ((slash = strchr (p, '/')) != NULL)
1711 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1712 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1713 * the filename from the drive letter.
1715 if (g_ascii_isalpha (filename[1]))
1717 if (filename[2] == ':')
1719 else if (filename[2] == '|')
1727 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1734 * g_filename_to_uri:
1735 * @filename: an absolute filename specified in the encoding
1736 * used for filenames by the operating system.
1737 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1738 * @error: location to store the error occuring, or %NULL to ignore
1739 * errors. Any of the errors in #GConvertError may occur.
1741 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1743 * Return value: a newly-allocated string holding the resulting
1744 * URI, or %NULL on an error.
1747 g_filename_to_uri (const char *filename,
1748 const char *hostname,
1752 char *utf8_filename;
1754 g_return_val_if_fail (filename != NULL, NULL);
1756 if (!g_path_is_absolute (filename))
1758 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1759 _("The pathname '%s' is not an absolute path"),
1765 !(g_utf8_validate (hostname, -1, NULL)
1766 && hostname_validate (hostname)))
1768 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1769 _("Invalid hostname"));
1773 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1774 if (utf8_filename == NULL)
1778 /* Don't use localhost unnecessarily */
1779 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1783 escaped_uri = g_escape_file_uri (hostname,
1785 g_free (utf8_filename);