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", or (GIConv)-1 if
106 * opening the converter failed.
109 g_iconv_open (const gchar *to_codeset,
110 const gchar *from_codeset)
114 if (!try_conversion (to_codeset, from_codeset, &cd))
116 const char **to_aliases = _g_charset_get_aliases (to_codeset);
117 const char **from_aliases = _g_charset_get_aliases (from_codeset);
121 const char **p = from_aliases;
124 if (try_conversion (to_codeset, *p, &cd))
127 if (try_to_aliases (to_aliases, *p, &cd))
134 if (try_to_aliases (to_aliases, from_codeset, &cd))
138 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
143 * @converter: conversion descriptor from g_iconv_open()
144 * @inbuf: bytes to convert
145 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
146 * @outbuf: converted output bytes
147 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
149 * Same as the standard UNIX routine <function>iconv()</function>, but
150 * may be implemented via libiconv on UNIX flavors that lack
151 * a native implementation.
153 * GLib provides g_convert() and g_locale_to_utf8() which are likely
154 * more convenient than the raw iconv wrappers.
156 * Return value: count of non-reversible conversions, or -1 on error
159 g_iconv (GIConv converter,
163 gsize *outbytes_left)
165 iconv_t cd = (iconv_t)converter;
167 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
172 * @converter: a conversion descriptor from g_iconv_open()
174 * Same as the standard UNIX routine <function>iconv_close()</function>, but
175 * may be implemented via libiconv on UNIX flavors that lack
176 * a native implementation. Should be called to clean up
177 * the conversion descriptor from g_iconv_open() when
178 * you are done converting things.
180 * GLib provides g_convert() and g_locale_to_utf8() which are likely
181 * more convenient than the raw iconv wrappers.
183 * Return value: -1 on error, 0 on success
186 g_iconv_close (GIConv converter)
188 iconv_t cd = (iconv_t)converter;
190 return iconv_close (cd);
194 #define ICONV_CACHE_SIZE (16)
196 struct _iconv_cache_bucket {
203 static GList *iconv_cache_list;
204 static GHashTable *iconv_cache;
205 static GHashTable *iconv_open_hash;
206 static guint iconv_cache_size = 0;
207 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
209 /* caller *must* hold the iconv_cache_lock */
211 iconv_cache_init (void)
213 static gboolean initialized = FALSE;
218 iconv_cache_list = NULL;
219 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
220 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
227 * iconv_cache_bucket_new:
229 * @cd: iconv descriptor
231 * Creates a new cache bucket, inserts it into the cache and
232 * increments the cache size.
234 * Returns a pointer to the newly allocated cache bucket.
236 struct _iconv_cache_bucket *
237 iconv_cache_bucket_new (const gchar *key, GIConv cd)
239 struct _iconv_cache_bucket *bucket;
241 bucket = g_new (struct _iconv_cache_bucket, 1);
242 bucket->key = g_strdup (key);
243 bucket->refcount = 1;
247 g_hash_table_insert (iconv_cache, bucket->key, bucket);
249 /* FIXME: if we sorted the list so items with few refcounts were
250 first, then we could expire them faster in iconv_cache_expire_unused () */
251 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
260 * iconv_cache_bucket_expire:
261 * @node: cache bucket's node
262 * @bucket: cache bucket
264 * Expires a single cache bucket @bucket. This should only ever be
265 * called on a bucket that currently has no used iconv descriptors
268 * @node is not a required argument. If @node is not supplied, we
269 * search for it ourselves.
272 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
274 g_hash_table_remove (iconv_cache, bucket->key);
277 node = g_list_find (iconv_cache_list, bucket);
279 g_assert (node != NULL);
283 node->prev->next = node->next;
285 node->next->prev = node->prev;
289 iconv_cache_list = node->next;
291 node->next->prev = NULL;
294 g_list_free_1 (node);
296 g_free (bucket->key);
297 g_iconv_close (bucket->cd);
305 * iconv_cache_expire_unused:
307 * Expires as many unused cache buckets as it needs to in order to get
308 * the total number of buckets < ICONV_CACHE_SIZE.
311 iconv_cache_expire_unused (void)
313 struct _iconv_cache_bucket *bucket;
316 node = iconv_cache_list;
317 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
322 if (bucket->refcount == 0)
323 iconv_cache_bucket_expire (node, bucket);
330 open_converter (const gchar *to_codeset,
331 const gchar *from_codeset,
334 struct _iconv_cache_bucket *bucket;
339 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
340 sprintf (key, "%s:%s", from_codeset, to_codeset);
342 G_LOCK (iconv_cache_lock);
344 /* make sure the cache has been initialized */
347 bucket = g_hash_table_lookup (iconv_cache, key);
352 cd = g_iconv_open (to_codeset, from_codeset);
353 if (cd == (GIConv) -1)
358 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
359 * NULL for anything but inbuf; work around that. (NULL outbuf
360 * or NULL *outbuf is allowed by Unix98.)
362 gsize inbytes_left = 0;
363 gchar *outbuf = NULL;
364 gsize outbytes_left = 0;
369 /* reset the descriptor */
370 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
377 cd = g_iconv_open (to_codeset, from_codeset);
378 if (cd == (GIConv) -1)
381 iconv_cache_expire_unused ();
383 bucket = iconv_cache_bucket_new (key, cd);
386 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
388 G_UNLOCK (iconv_cache_lock);
394 G_UNLOCK (iconv_cache_lock);
396 /* Something went wrong. */
398 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
399 _("Conversion from character set '%s' to '%s' is not supported"),
400 from_codeset, to_codeset);
402 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
403 _("Could not open converter from '%s' to '%s': %s"),
404 from_codeset, to_codeset, g_strerror (errno));
410 close_converter (GIConv converter)
412 struct _iconv_cache_bucket *bucket;
418 if (cd == (GIConv) -1)
421 G_LOCK (iconv_cache_lock);
423 key = g_hash_table_lookup (iconv_open_hash, cd);
426 g_hash_table_remove (iconv_open_hash, cd);
428 bucket = g_hash_table_lookup (iconv_cache, key);
433 if (cd == bucket->cd)
434 bucket->used = FALSE;
438 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
440 /* expire this cache bucket */
441 iconv_cache_bucket_expire (NULL, bucket);
446 G_UNLOCK (iconv_cache_lock);
448 g_warning ("This iconv context wasn't opened using open_converter");
450 return g_iconv_close (converter);
453 G_UNLOCK (iconv_cache_lock);
461 * @str: the string to convert
462 * @len: the length of the string
463 * @to_codeset: name of character set into which to convert @str
464 * @from_codeset: character set of @str.
465 * @bytes_read: location to store the number of bytes in the
466 * input string that were successfully converted, or %NULL.
467 * Even if the conversion was successful, this may be
468 * less than @len if there were partial characters
469 * at the end of the input. If the error
470 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
471 * stored will the byte offset after the last valid
473 * @bytes_written: the number of bytes stored in the output buffer (not
474 * including the terminating nul).
475 * @error: location to store the error occuring, or %NULL to ignore
476 * errors. Any of the errors in #GConvertError may occur.
478 * Converts a string from one character set to another.
480 * Return value: If the conversion was successful, a newly allocated
481 * nul-terminated string, which must be freed with
482 * g_free(). Otherwise %NULL and @error will be set.
485 g_convert (const gchar *str,
487 const gchar *to_codeset,
488 const gchar *from_codeset,
490 gsize *bytes_written,
496 g_return_val_if_fail (str != NULL, NULL);
497 g_return_val_if_fail (to_codeset != NULL, NULL);
498 g_return_val_if_fail (from_codeset != NULL, NULL);
500 cd = open_converter (to_codeset, from_codeset, error);
502 if (cd == (GIConv) -1)
513 res = g_convert_with_iconv (str, len, cd,
514 bytes_read, bytes_written,
517 close_converter (cd);
523 * g_convert_with_iconv:
524 * @str: the string to convert
525 * @len: the length of the string
526 * @converter: conversion descriptor from g_iconv_open()
527 * @bytes_read: location to store the number of bytes in the
528 * input string that were successfully converted, or %NULL.
529 * Even if the conversion was successful, this may be
530 * less than @len if there were partial characters
531 * at the end of the input. If the error
532 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
533 * stored will the byte offset after the last valid
535 * @bytes_written: the number of bytes stored in the output buffer (not
536 * including the terminating nul).
537 * @error: location to store the error occuring, or %NULL to ignore
538 * errors. Any of the errors in #GConvertError may occur.
540 * Converts a string from one character set to another.
542 * Return value: If the conversion was successful, a newly allocated
543 * nul-terminated string, which must be freed with
544 * g_free(). Otherwise %NULL and @error will be set.
547 g_convert_with_iconv (const gchar *str,
551 gsize *bytes_written,
557 gsize inbytes_remaining;
558 gsize outbytes_remaining;
561 gboolean have_error = FALSE;
563 g_return_val_if_fail (str != NULL, NULL);
564 g_return_val_if_fail (converter != (GIConv) -1, NULL);
570 inbytes_remaining = len;
571 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
573 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
574 outp = dest = g_malloc (outbuf_size);
578 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
580 if (err == (size_t) -1)
585 /* Incomplete text, do not report an error */
589 size_t used = outp - dest;
592 dest = g_realloc (dest, outbuf_size);
595 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
600 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
601 _("Invalid byte sequence in conversion input"));
605 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
606 _("Error during conversion: %s"),
616 *bytes_read = p - str;
619 if ((p - str) != len)
623 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
624 _("Partial character sequence at end of input"));
631 *bytes_written = outp - dest; /* Doesn't include '\0' */
643 * g_convert_with_fallback:
644 * @str: the string to convert
645 * @len: the length of the string
646 * @to_codeset: name of character set into which to convert @str
647 * @from_codeset: character set of @str.
648 * @fallback: UTF-8 string to use in place of character not
649 * present in the target encoding. (This must be
650 * in the target encoding), if %NULL, characters
651 * not in the target encoding will be represented
652 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
653 * @bytes_read: location to store the number of bytes in the
654 * input string that were successfully converted, or %NULL.
655 * Even if the conversion was successful, this may be
656 * less than @len if there were partial characters
657 * at the end of the input.
658 * @bytes_written: the number of bytes stored in the output buffer (not
659 * including the terminating nul).
660 * @error: location to store the error occuring, or %NULL to ignore
661 * errors. Any of the errors in #GConvertError may occur.
663 * Converts a string from one character set to another, possibly
664 * including fallback sequences for characters not representable
665 * in the output. Note that it is not guaranteed that the specification
666 * for the fallback sequences in @fallback will be honored. Some
667 * systems may do a approximate conversion from @from_codeset
668 * to @to_codeset in their <function>iconv()</function> functions,
669 * in which case GLib will simply return that approximate conversion.
671 * Return value: If the conversion was successful, a newly allocated
672 * nul-terminated string, which must be freed with
673 * g_free(). Otherwise %NULL and @error will be set.
676 g_convert_with_fallback (const gchar *str,
678 const gchar *to_codeset,
679 const gchar *from_codeset,
682 gsize *bytes_written,
688 const gchar *insert_str = NULL;
690 gsize inbytes_remaining;
691 const gchar *save_p = NULL;
692 gsize save_inbytes = 0;
693 gsize outbytes_remaining;
697 gboolean have_error = FALSE;
698 gboolean done = FALSE;
700 GError *local_error = NULL;
702 g_return_val_if_fail (str != NULL, NULL);
703 g_return_val_if_fail (to_codeset != NULL, NULL);
704 g_return_val_if_fail (from_codeset != NULL, NULL);
709 /* Try an exact conversion; we only proceed if this fails
710 * due to an illegal sequence in the input string.
712 dest = g_convert (str, len, to_codeset, from_codeset,
713 bytes_read, bytes_written, &local_error);
717 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
719 g_propagate_error (error, local_error);
723 g_error_free (local_error);
727 /* No go; to proceed, we need a converter from "UTF-8" to
728 * to_codeset, and the string as UTF-8.
730 cd = open_converter (to_codeset, "UTF-8", error);
731 if (cd == (GIConv) -1)
742 utf8 = g_convert (str, len, "UTF-8", from_codeset,
743 bytes_read, &inbytes_remaining, error);
746 close_converter (cd);
752 /* Now the heart of the code. We loop through the UTF-8 string, and
753 * whenever we hit an offending character, we form fallback, convert
754 * the fallback to the target codeset, and then go back to
755 * converting the original string after finishing with the fallback.
757 * The variables save_p and save_inbytes store the input state
758 * for the original string while we are converting the fallback
762 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
763 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
764 outp = dest = g_malloc (outbuf_size);
766 while (!done && !have_error)
768 size_t inbytes_tmp = inbytes_remaining;
769 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
770 inbytes_remaining = inbytes_tmp;
772 if (err == (size_t) -1)
777 g_assert_not_reached();
781 size_t used = outp - dest;
784 dest = g_realloc (dest, outbuf_size);
787 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
794 /* Error converting fallback string - fatal
796 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
797 _("Cannot convert fallback '%s' to codeset '%s'"),
798 insert_str, to_codeset);
806 gunichar ch = g_utf8_get_char (p);
807 insert_str = g_strdup_printf ("\\x{%0*X}",
808 (ch < 0x10000) ? 4 : 6,
812 insert_str = fallback;
814 save_p = g_utf8_next_char (p);
815 save_inbytes = inbytes_remaining - (save_p - p);
817 inbytes_remaining = strlen (p);
821 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
822 _("Error during conversion: %s"),
833 g_free ((gchar *)insert_str);
835 inbytes_remaining = save_inbytes;
847 close_converter (cd);
850 *bytes_written = outp - dest; /* Doesn't include '\0' */
856 if (save_p && !fallback)
857 g_free ((gchar *)insert_str);
871 #ifndef G_PLATFORM_WIN32
874 strdup_len (const gchar *string,
876 gsize *bytes_written,
883 if (!g_utf8_validate (string, -1, NULL))
890 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
891 _("Invalid byte sequence in conversion input"));
896 real_len = strlen (string);
901 while (real_len < len && string[real_len])
906 *bytes_read = real_len;
908 *bytes_written = real_len;
910 return g_strndup (string, real_len);
917 * @opsysstring: a string in the encoding of the current locale
918 * @len: the length of the string, or -1 if the string is
920 * @bytes_read: location to store the number of bytes in the
921 * input string that were successfully converted, or %NULL.
922 * Even if the conversion was successful, this may be
923 * less than @len if there were partial characters
924 * at the end of the input. If the error
925 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
926 * stored will the byte offset after the last valid
928 * @bytes_written: the number of bytes stored in the output buffer (not
929 * including the terminating nul).
930 * @error: location to store the error occuring, or %NULL to ignore
931 * errors. Any of the errors in #GConvertError may occur.
933 * Converts a string which is in the encoding used for strings by
934 * the C runtime (usually the same as that used by the operating
935 * system) in the current locale into a UTF-8 string.
937 * Return value: The converted string, or %NULL on an error.
940 g_locale_to_utf8 (const gchar *opsysstring,
943 gsize *bytes_written,
946 #ifdef G_PLATFORM_WIN32
948 gint i, clen, total_len, wclen, first;
954 len = strlen (opsysstring);
956 wcs = g_new (wchar_t, len);
957 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
961 for (i = 0; i < wclen; i++)
969 else if (wc < 0x10000)
971 else if (wc < 0x200000)
973 else if (wc < 0x4000000)
979 result = g_malloc (total_len + 1);
983 for (i = 0; i < wclen; i++)
997 else if (wc < 0x10000)
1002 else if (wc < 0x200000)
1007 else if (wc < 0x4000000)
1021 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1022 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1023 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1024 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1025 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1026 case 1: bp[0] = wc | first;
1038 *bytes_written = total_len;
1042 #else /* !G_PLATFORM_WIN32 */
1044 const char *charset;
1046 if (g_get_charset (&charset))
1047 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1049 return g_convert (opsysstring, len,
1050 "UTF-8", charset, bytes_read, bytes_written, error);
1052 #endif /* !G_PLATFORM_WIN32 */
1056 * g_locale_from_utf8:
1057 * @utf8string: a UTF-8 encoded string
1058 * @len: the length of the string, or -1 if the string is
1060 * @bytes_read: location to store the number of bytes in the
1061 * input string that were successfully converted, or %NULL.
1062 * Even if the conversion was successful, this may be
1063 * less than @len if there were partial characters
1064 * at the end of the input. If the error
1065 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1066 * stored will the byte offset after the last valid
1068 * @bytes_written: the number of bytes stored in the output buffer (not
1069 * including the terminating nul).
1070 * @error: location to store the error occuring, or %NULL to ignore
1071 * errors. Any of the errors in #GConvertError may occur.
1073 * Converts a string from UTF-8 to the encoding used for strings by
1074 * the C runtime (usually the same as that used by the operating
1075 * system) in the current locale.
1077 * Return value: The converted string, or %NULL on an error.
1080 g_locale_from_utf8 (const gchar *utf8string,
1083 gsize *bytes_written,
1086 #ifdef G_PLATFORM_WIN32
1088 gint i, mask, clen, mblen;
1091 guchar *cp, *end, c;
1095 len = strlen (utf8string);
1097 /* First convert to wide chars */
1098 cp = (guchar *) utf8string;
1101 wcs = g_new (wchar_t, len + 1);
1113 else if ((c & 0xe0) == 0xc0)
1118 else if ((c & 0xf0) == 0xe0)
1123 else if ((c & 0xf8) == 0xf0)
1128 else if ((c & 0xfc) == 0xf8)
1133 else if ((c & 0xfc) == 0xfc)
1144 if (cp + clen > end)
1150 *wcp = (cp[0] & mask);
1151 for (i = 1; i < clen; i++)
1153 if ((cp[i] & 0xc0) != 0x80)
1159 *wcp |= (cp[i] & 0x3f);
1172 /* n is the number of wide chars constructed */
1174 /* Convert to a string in the current ANSI codepage */
1176 result = g_new (gchar, 3 * n + 1);
1177 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1184 *bytes_written = mblen;
1188 #else /* !G_PLATFORM_WIN32 */
1190 const gchar *charset;
1192 if (g_get_charset (&charset))
1193 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1195 return g_convert (utf8string, len,
1196 charset, "UTF-8", bytes_read, bytes_written, error);
1198 #endif /* !G_PLATFORM_WIN32 */
1201 #ifndef G_PLATFORM_WIN32
1203 have_broken_filenames (void)
1205 static gboolean initialized = FALSE;
1206 static gboolean broken;
1211 broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1217 #endif /* !G_PLATFORM_WIN32 */
1219 /* This is called from g_thread_init(). It's used to
1220 * initialize some static data in a threadsafe way.
1223 g_convert_init (void)
1225 #ifndef G_PLATFORM_WIN32
1226 (void)have_broken_filenames ();
1227 #endif /* !G_PLATFORM_WIN32 */
1231 * g_filename_to_utf8:
1232 * @opsysstring: a string in the encoding for filenames
1233 * @len: the length of the string, or -1 if the string is
1235 * @bytes_read: location to store the number of bytes in the
1236 * input string that were successfully converted, or %NULL.
1237 * Even if the conversion was successful, this may be
1238 * less than @len if there were partial characters
1239 * at the end of the input. If the error
1240 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1241 * stored will the byte offset after the last valid
1243 * @bytes_written: the number of bytes stored in the output buffer (not
1244 * including the terminating nul).
1245 * @error: location to store the error occuring, or %NULL to ignore
1246 * errors. Any of the errors in #GConvertError may occur.
1248 * Converts a string which is in the encoding used for filenames
1249 * into a UTF-8 string.
1251 * Return value: The converted string, or %NULL on an error.
1254 g_filename_to_utf8 (const gchar *opsysstring,
1257 gsize *bytes_written,
1260 #ifdef G_PLATFORM_WIN32
1261 return g_locale_to_utf8 (opsysstring, len,
1262 bytes_read, bytes_written,
1264 #else /* !G_PLATFORM_WIN32 */
1266 if (have_broken_filenames ())
1267 return g_locale_to_utf8 (opsysstring, len,
1268 bytes_read, bytes_written,
1271 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1272 #endif /* !G_PLATFORM_WIN32 */
1276 * g_filename_from_utf8:
1277 * @utf8string: a UTF-8 encoded string.
1278 * @len: the length of the string, or -1 if the string is
1280 * @bytes_read: location to store the number of bytes in the
1281 * input string that were successfully converted, or %NULL.
1282 * Even if the conversion was successful, this may be
1283 * less than @len if there were partial characters
1284 * at the end of the input. If the error
1285 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1286 * stored will the byte offset after the last valid
1288 * @bytes_written: the number of bytes stored in the output buffer (not
1289 * including the terminating nul).
1290 * @error: location to store the error occuring, or %NULL to ignore
1291 * errors. Any of the errors in #GConvertError may occur.
1293 * Converts a string from UTF-8 to the encoding used for filenames.
1295 * Return value: The converted string, or %NULL on an error.
1298 g_filename_from_utf8 (const gchar *utf8string,
1301 gsize *bytes_written,
1304 #ifdef G_PLATFORM_WIN32
1305 return g_locale_from_utf8 (utf8string, len,
1306 bytes_read, bytes_written,
1308 #else /* !G_PLATFORM_WIN32 */
1309 if (have_broken_filenames ())
1310 return g_locale_from_utf8 (utf8string, len,
1311 bytes_read, bytes_written,
1314 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1315 #endif /* !G_PLATFORM_WIN32 */
1318 /* Test of haystack has the needle prefix, comparing case
1319 * insensitive. haystack may be UTF-8, but needle must
1320 * contain only ascii. */
1322 has_case_prefix (const gchar *haystack, const gchar *needle)
1326 /* Eat one character at a time. */
1331 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1341 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1342 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1343 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1344 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1345 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1346 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1347 } UnsafeCharacterSet;
1349 static const guchar acceptable[96] = {
1350 /* A table of the ASCII chars from space (32) to DEL (127) */
1351 /* ! " # $ % & ' ( ) * + , - . / */
1352 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1353 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1354 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1355 /* @ A B C D E F G H I J K L M N O */
1356 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1357 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1358 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1359 /* ` a b c d e f g h i j k l m n o */
1360 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1361 /* p q r s t u v w x y z { | } ~ DEL */
1362 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1365 static const gchar hex[16] = "0123456789ABCDEF";
1367 /* Note: This escape function works on file: URIs, but if you want to
1368 * escape something else, please read RFC-2396 */
1370 g_escape_uri_string (const gchar *string,
1371 UnsafeCharacterSet mask)
1373 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1380 UnsafeCharacterSet use_mask;
1382 g_return_val_if_fail (mask == UNSAFE_ALL
1383 || mask == UNSAFE_ALLOW_PLUS
1384 || mask == UNSAFE_PATH
1385 || mask == UNSAFE_DOS_PATH
1386 || mask == UNSAFE_HOST
1387 || mask == UNSAFE_SLASHES, NULL);
1391 for (p = string; *p != '\0'; p++)
1394 if (!ACCEPTABLE (c))
1398 result = g_malloc (p - string + unacceptable * 2 + 1);
1401 for (q = result, p = string; *p != '\0'; p++)
1405 if (!ACCEPTABLE (c))
1407 *q++ = '%'; /* means hex coming */
1422 g_escape_file_uri (const gchar *hostname,
1423 const gchar *pathname)
1425 char *escaped_hostname = NULL;
1430 char *p, *backslash;
1432 /* Turn backslashes into forward slashes. That's what Netscape
1433 * does, and they are actually more or less equivalent in Windows.
1436 pathname = g_strdup (pathname);
1437 p = (char *) pathname;
1439 while ((backslash = strchr (p, '\\')) != NULL)
1446 if (hostname && *hostname != '\0')
1448 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1451 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1453 res = g_strconcat ("file://",
1454 (escaped_hostname) ? escaped_hostname : "",
1455 (*escaped_path != '/') ? "/" : "",
1460 g_free ((char *) pathname);
1463 g_free (escaped_hostname);
1464 g_free (escaped_path);
1470 unescape_character (const char *scanner)
1475 first_digit = g_ascii_xdigit_value (scanner[0]);
1476 if (first_digit < 0)
1479 second_digit = g_ascii_xdigit_value (scanner[1]);
1480 if (second_digit < 0)
1483 return (first_digit << 4) | second_digit;
1487 g_unescape_uri_string (const char *escaped,
1489 const char *illegal_escaped_characters,
1490 gboolean ascii_must_not_be_escaped)
1492 const gchar *in, *in_end;
1493 gchar *out, *result;
1496 if (escaped == NULL)
1500 len = strlen (escaped);
1502 result = g_malloc (len + 1);
1505 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1511 /* catch partial escape sequences past the end of the substring */
1512 if (in + 3 > in_end)
1515 c = unescape_character (in + 1);
1517 /* catch bad escape sequences and NUL characters */
1521 /* catch escaped ASCII */
1522 if (ascii_must_not_be_escaped && c <= 0x7F)
1525 /* catch other illegal escaped characters */
1526 if (strchr (illegal_escaped_characters, c) != NULL)
1535 g_assert (out - result <= len);
1538 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1548 is_escalphanum (gunichar c)
1550 return c > 0x7F || g_ascii_isalnum (c);
1554 is_escalpha (gunichar c)
1556 return c > 0x7F || g_ascii_isalpha (c);
1559 /* allows an empty string */
1561 hostname_validate (const char *hostname)
1564 gunichar c, first_char, last_char;
1571 /* read in a label */
1572 c = g_utf8_get_char (p);
1573 p = g_utf8_next_char (p);
1574 if (!is_escalphanum (c))
1580 c = g_utf8_get_char (p);
1581 p = g_utf8_next_char (p);
1583 while (is_escalphanum (c) || c == '-');
1584 if (last_char == '-')
1587 /* if that was the last label, check that it was a toplabel */
1588 if (c == '\0' || (c == '.' && *p == '\0'))
1589 return is_escalpha (first_char);
1596 * g_filename_from_uri:
1597 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1598 * @hostname: Location to store hostname for the URI, or %NULL.
1599 * If there is no hostname in the URI, %NULL will be
1600 * stored in this location.
1601 * @error: location to store the error occuring, or %NULL to ignore
1602 * errors. Any of the errors in #GConvertError may occur.
1604 * Converts an escaped UTF-8 encoded URI to a local filename in the
1605 * encoding used for filenames.
1607 * Return value: a newly-allocated string holding the resulting
1608 * filename, or %NULL on an error.
1611 g_filename_from_uri (const char *uri,
1615 const char *path_part;
1616 const char *host_part;
1617 char *unescaped_hostname;
1628 if (!has_case_prefix (uri, "file:/"))
1630 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1631 _("The URI '%s' is not an absolute URI using the file scheme"),
1636 path_part = uri + strlen ("file:");
1638 if (strchr (path_part, '#') != NULL)
1640 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1641 _("The local file URI '%s' may not include a '#'"),
1646 if (has_case_prefix (path_part, "///"))
1648 else if (has_case_prefix (path_part, "//"))
1651 host_part = path_part;
1653 path_part = strchr (path_part, '/');
1655 if (path_part == NULL)
1657 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1658 _("The URI '%s' is invalid"),
1663 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1665 if (unescaped_hostname == NULL ||
1666 !hostname_validate (unescaped_hostname))
1668 g_free (unescaped_hostname);
1669 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1670 _("The hostname of the URI '%s' is invalid"),
1676 *hostname = unescaped_hostname;
1678 g_free (unescaped_hostname);
1681 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1683 if (filename == NULL)
1685 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1686 _("The URI '%s' contains invalidly escaped characters"),
1693 /* Drop localhost */
1694 if (hostname && *hostname != NULL &&
1695 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1701 /* Turn slashes into backslashes, because that's the canonical spelling */
1703 while ((slash = strchr (p, '/')) != NULL)
1709 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1710 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1711 * the filename from the drive letter.
1713 if (g_ascii_isalpha (filename[1]))
1715 if (filename[2] == ':')
1717 else if (filename[2] == '|')
1725 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1732 * g_filename_to_uri:
1733 * @filename: an absolute filename specified in the encoding
1734 * used for filenames by the operating system.
1735 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1736 * @error: location to store the error occuring, or %NULL to ignore
1737 * errors. Any of the errors in #GConvertError may occur.
1739 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1741 * Return value: a newly-allocated string holding the resulting
1742 * URI, or %NULL on an error.
1745 g_filename_to_uri (const char *filename,
1746 const char *hostname,
1750 char *utf8_filename;
1752 g_return_val_if_fail (filename != NULL, NULL);
1754 if (!g_path_is_absolute (filename))
1756 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1757 _("The pathname '%s' is not an absolute path"),
1763 !(g_utf8_validate (hostname, -1, NULL)
1764 && hostname_validate (hostname)))
1766 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1767 _("Invalid hostname"));
1771 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1772 if (utf8_filename == NULL)
1776 /* Don't use localhost unnecessarily */
1777 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1781 escaped_uri = g_escape_file_uri (hostname,
1783 g_free (utf8_filename);