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))
139 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
144 * @converter: conversion descriptor from g_iconv_open()
145 * @inbuf: bytes to convert
146 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
147 * @outbuf: converted output bytes
148 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
150 * Same as the standard UNIX routine <function>iconv()</function>, but
151 * may be implemented via libiconv on UNIX flavors that lack
152 * a native implementation.
154 * GLib provides g_convert() and g_locale_to_utf8() which are likely
155 * more convenient than the raw iconv wrappers.
157 * Return value: count of non-reversible conversions, or -1 on error
160 g_iconv (GIConv converter,
164 gsize *outbytes_left)
166 iconv_t cd = (iconv_t)converter;
168 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
173 * @converter: a conversion descriptor from g_iconv_open()
175 * Same as the standard UNIX routine <function>iconv_close()</function>, but
176 * may be implemented via libiconv on UNIX flavors that lack
177 * a native implementation. Should be called to clean up
178 * the conversion descriptor from g_iconv_open() when
179 * you are done converting things.
181 * GLib provides g_convert() and g_locale_to_utf8() which are likely
182 * more convenient than the raw iconv wrappers.
184 * Return value: -1 on error, 0 on success
187 g_iconv_close (GIConv converter)
189 iconv_t cd = (iconv_t)converter;
191 return iconv_close (cd);
195 #define ICONV_CACHE_SIZE (16)
197 struct _iconv_cache_bucket {
204 static GList *iconv_cache_list;
205 static GHashTable *iconv_cache;
206 static GHashTable *iconv_open_hash;
207 static guint iconv_cache_size = 0;
208 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
210 /* caller *must* hold the iconv_cache_lock */
212 iconv_cache_init (void)
214 static gboolean initialized = FALSE;
219 iconv_cache_list = NULL;
220 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
221 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
228 * iconv_cache_bucket_new:
230 * @cd: iconv descriptor
232 * Creates a new cache bucket, inserts it into the cache and
233 * increments the cache size.
235 * Returns a pointer to the newly allocated cache bucket.
237 struct _iconv_cache_bucket *
238 iconv_cache_bucket_new (const gchar *key, GIConv cd)
240 struct _iconv_cache_bucket *bucket;
242 bucket = g_new (struct _iconv_cache_bucket, 1);
243 bucket->key = g_strdup (key);
244 bucket->refcount = 1;
248 g_hash_table_insert (iconv_cache, bucket->key, bucket);
250 /* FIXME: if we sorted the list so items with few refcounts were
251 first, then we could expire them faster in iconv_cache_expire_unused () */
252 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
261 * iconv_cache_bucket_expire:
262 * @node: cache bucket's node
263 * @bucket: cache bucket
265 * Expires a single cache bucket @bucket. This should only ever be
266 * called on a bucket that currently has no used iconv descriptors
269 * @node is not a required argument. If @node is not supplied, we
270 * search for it ourselves.
273 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
275 g_hash_table_remove (iconv_cache, bucket->key);
278 node = g_list_find (iconv_cache_list, bucket);
280 g_assert (node != NULL);
284 node->prev->next = node->next;
286 node->next->prev = node->prev;
290 iconv_cache_list = node->next;
292 node->next->prev = NULL;
295 g_list_free_1 (node);
297 g_free (bucket->key);
298 g_iconv_close (bucket->cd);
306 * iconv_cache_expire_unused:
308 * Expires as many unused cache buckets as it needs to in order to get
309 * the total number of buckets < ICONV_CACHE_SIZE.
312 iconv_cache_expire_unused (void)
314 struct _iconv_cache_bucket *bucket;
317 node = iconv_cache_list;
318 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
323 if (bucket->refcount == 0)
324 iconv_cache_bucket_expire (node, bucket);
331 open_converter (const gchar *to_codeset,
332 const gchar *from_codeset,
335 struct _iconv_cache_bucket *bucket;
340 key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
341 sprintf (key, "%s:%s", from_codeset, to_codeset);
343 G_LOCK (iconv_cache_lock);
345 /* make sure the cache has been initialized */
348 bucket = g_hash_table_lookup (iconv_cache, key);
353 cd = g_iconv_open (to_codeset, from_codeset);
354 if (cd == (GIConv) -1)
359 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
360 * NULL for anything but inbuf; work around that. (NULL outbuf
361 * or NULL *outbuf is allowed by Unix98.)
363 gsize inbytes_left = 0;
364 gchar *outbuf = NULL;
365 gsize outbytes_left = 0;
370 /* reset the descriptor */
371 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
378 cd = g_iconv_open (to_codeset, from_codeset);
379 if (cd == (GIConv) -1)
382 iconv_cache_expire_unused ();
384 bucket = iconv_cache_bucket_new (key, cd);
387 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
389 G_UNLOCK (iconv_cache_lock);
395 G_UNLOCK (iconv_cache_lock);
397 /* Something went wrong. */
399 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
400 _("Conversion from character set '%s' to '%s' is not supported"),
401 from_codeset, to_codeset);
403 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
404 _("Could not open converter from '%s' to '%s': %s"),
405 from_codeset, to_codeset, g_strerror (errno));
411 close_converter (GIConv converter)
413 struct _iconv_cache_bucket *bucket;
419 if (cd == (GIConv) -1)
422 G_LOCK (iconv_cache_lock);
424 key = g_hash_table_lookup (iconv_open_hash, cd);
427 g_hash_table_remove (iconv_open_hash, cd);
429 bucket = g_hash_table_lookup (iconv_cache, key);
434 if (cd == bucket->cd)
435 bucket->used = FALSE;
439 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
441 /* expire this cache bucket */
442 iconv_cache_bucket_expire (NULL, bucket);
447 G_UNLOCK (iconv_cache_lock);
449 g_warning ("This iconv context wasn't opened using open_converter");
451 return g_iconv_close (converter);
454 G_UNLOCK (iconv_cache_lock);
462 * @str: the string to convert
463 * @len: the length of the string
464 * @to_codeset: name of character set into which to convert @str
465 * @from_codeset: character set of @str.
466 * @bytes_read: location to store the number of bytes in the
467 * input string that were successfully converted, or %NULL.
468 * Even if the conversion was successful, this may be
469 * less than @len if there were partial characters
470 * at the end of the input. If the error
471 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
472 * stored will the byte offset after the last valid
474 * @bytes_written: the number of bytes stored in the output buffer (not
475 * including the terminating nul).
476 * @error: location to store the error occuring, or %NULL to ignore
477 * errors. Any of the errors in #GConvertError may occur.
479 * Converts a string from one character set to another.
481 * Return value: If the conversion was successful, a newly allocated
482 * nul-terminated string, which must be freed with
483 * g_free(). Otherwise %NULL and @error will be set.
486 g_convert (const gchar *str,
488 const gchar *to_codeset,
489 const gchar *from_codeset,
491 gsize *bytes_written,
497 g_return_val_if_fail (str != NULL, NULL);
498 g_return_val_if_fail (to_codeset != NULL, NULL);
499 g_return_val_if_fail (from_codeset != NULL, NULL);
501 cd = open_converter (to_codeset, from_codeset, error);
503 if (cd == (GIConv) -1)
514 res = g_convert_with_iconv (str, len, cd,
515 bytes_read, bytes_written,
518 close_converter (cd);
524 * g_convert_with_iconv:
525 * @str: the string to convert
526 * @len: the length of the string
527 * @converter: conversion descriptor from g_iconv_open()
528 * @bytes_read: location to store the number of bytes in the
529 * input string that were successfully converted, or %NULL.
530 * Even if the conversion was successful, this may be
531 * less than @len if there were partial characters
532 * at the end of the input. If the error
533 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
534 * stored will the byte offset after the last valid
536 * @bytes_written: the number of bytes stored in the output buffer (not
537 * including the terminating nul).
538 * @error: location to store the error occuring, or %NULL to ignore
539 * errors. Any of the errors in #GConvertError may occur.
541 * Converts a string from one character set to another.
543 * Return value: If the conversion was successful, a newly allocated
544 * nul-terminated string, which must be freed with
545 * g_free(). Otherwise %NULL and @error will be set.
548 g_convert_with_iconv (const gchar *str,
552 gsize *bytes_written,
558 gsize inbytes_remaining;
559 gsize outbytes_remaining;
562 gboolean have_error = FALSE;
564 g_return_val_if_fail (str != NULL, NULL);
565 g_return_val_if_fail (converter != (GIConv) -1, NULL);
571 inbytes_remaining = len;
572 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
574 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
575 outp = dest = g_malloc (outbuf_size);
579 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
581 if (err == (size_t) -1)
586 /* Incomplete text, do not report an error */
590 size_t used = outp - dest;
593 dest = g_realloc (dest, outbuf_size);
596 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
601 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
602 _("Invalid byte sequence in conversion input"));
606 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
607 _("Error during conversion: %s"),
617 *bytes_read = p - str;
620 if ((p - str) != len)
624 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
625 _("Partial character sequence at end of input"));
632 *bytes_written = outp - dest; /* Doesn't include '\0' */
644 * g_convert_with_fallback:
645 * @str: the string to convert
646 * @len: the length of the string
647 * @to_codeset: name of character set into which to convert @str
648 * @from_codeset: character set of @str.
649 * @fallback: UTF-8 string to use in place of character not
650 * present in the target encoding. (This must be
651 * in the target encoding), if %NULL, characters
652 * not in the target encoding will be represented
653 * as Unicode escapes \x{XXXX} or \x{XXXXXX}.
654 * @bytes_read: location to store the number of bytes in the
655 * input string that were successfully converted, or %NULL.
656 * Even if the conversion was successful, this may be
657 * less than @len if there were partial characters
658 * at the end of the input.
659 * @bytes_written: the number of bytes stored in the output buffer (not
660 * including the terminating nul).
661 * @error: location to store the error occuring, or %NULL to ignore
662 * errors. Any of the errors in #GConvertError may occur.
664 * Converts a string from one character set to another, possibly
665 * including fallback sequences for characters not representable
666 * in the output. Note that it is not guaranteed that the specification
667 * for the fallback sequences in @fallback will be honored. Some
668 * systems may do a approximate conversion from @from_codeset
669 * to @to_codeset in their <function>iconv()</function> functions,
670 * in which case GLib will simply return that approximate conversion.
672 * Return value: If the conversion was successful, a newly allocated
673 * nul-terminated string, which must be freed with
674 * g_free(). Otherwise %NULL and @error will be set.
677 g_convert_with_fallback (const gchar *str,
679 const gchar *to_codeset,
680 const gchar *from_codeset,
683 gsize *bytes_written,
689 const gchar *insert_str = NULL;
691 gsize inbytes_remaining;
692 const gchar *save_p = NULL;
693 gsize save_inbytes = 0;
694 gsize outbytes_remaining;
698 gboolean have_error = FALSE;
699 gboolean done = FALSE;
701 GError *local_error = NULL;
703 g_return_val_if_fail (str != NULL, NULL);
704 g_return_val_if_fail (to_codeset != NULL, NULL);
705 g_return_val_if_fail (from_codeset != NULL, NULL);
710 /* Try an exact conversion; we only proceed if this fails
711 * due to an illegal sequence in the input string.
713 dest = g_convert (str, len, to_codeset, from_codeset,
714 bytes_read, bytes_written, &local_error);
718 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
720 g_propagate_error (error, local_error);
724 g_error_free (local_error);
728 /* No go; to proceed, we need a converter from "UTF-8" to
729 * to_codeset, and the string as UTF-8.
731 cd = open_converter (to_codeset, "UTF-8", error);
732 if (cd == (GIConv) -1)
743 utf8 = g_convert (str, len, "UTF-8", from_codeset,
744 bytes_read, &inbytes_remaining, error);
747 close_converter (cd);
753 /* Now the heart of the code. We loop through the UTF-8 string, and
754 * whenever we hit an offending character, we form fallback, convert
755 * the fallback to the target codeset, and then go back to
756 * converting the original string after finishing with the fallback.
758 * The variables save_p and save_inbytes store the input state
759 * for the original string while we are converting the fallback
763 outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
764 outbytes_remaining = outbuf_size - 1; /* -1 for nul */
765 outp = dest = g_malloc (outbuf_size);
767 while (!done && !have_error)
769 size_t inbytes_tmp = inbytes_remaining;
770 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
771 inbytes_remaining = inbytes_tmp;
773 if (err == (size_t) -1)
778 g_assert_not_reached();
782 size_t used = outp - dest;
785 dest = g_realloc (dest, outbuf_size);
788 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
795 /* Error converting fallback string - fatal
797 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
798 _("Cannot convert fallback '%s' to codeset '%s'"),
799 insert_str, to_codeset);
807 gunichar ch = g_utf8_get_char (p);
808 insert_str = g_strdup_printf ("\\x{%0*X}",
809 (ch < 0x10000) ? 4 : 6,
813 insert_str = fallback;
815 save_p = g_utf8_next_char (p);
816 save_inbytes = inbytes_remaining - (save_p - p);
818 inbytes_remaining = strlen (p);
822 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
823 _("Error during conversion: %s"),
834 g_free ((gchar *)insert_str);
836 inbytes_remaining = save_inbytes;
848 close_converter (cd);
851 *bytes_written = outp - dest; /* Doesn't include '\0' */
857 if (save_p && !fallback)
858 g_free ((gchar *)insert_str);
872 #ifndef G_PLATFORM_WIN32
875 strdup_len (const gchar *string,
877 gsize *bytes_written,
884 if (!g_utf8_validate (string, -1, NULL))
891 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
892 _("Invalid byte sequence in conversion input"));
897 real_len = strlen (string);
902 while (real_len < len && string[real_len])
907 *bytes_read = real_len;
909 *bytes_written = real_len;
911 return g_strndup (string, real_len);
918 * @opsysstring: a string in the encoding of the current locale
919 * @len: the length of the string, or -1 if the string is
921 * @bytes_read: location to store the number of bytes in the
922 * input string that were successfully converted, or %NULL.
923 * Even if the conversion was successful, this may be
924 * less than @len if there were partial characters
925 * at the end of the input. If the error
926 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
927 * stored will the byte offset after the last valid
929 * @bytes_written: the number of bytes stored in the output buffer (not
930 * including the terminating nul).
931 * @error: location to store the error occuring, or %NULL to ignore
932 * errors. Any of the errors in #GConvertError may occur.
934 * Converts a string which is in the encoding used for strings by
935 * the C runtime (usually the same as that used by the operating
936 * system) in the current locale into a UTF-8 string.
938 * Return value: The converted string, or %NULL on an error.
941 g_locale_to_utf8 (const gchar *opsysstring,
944 gsize *bytes_written,
947 #ifdef G_PLATFORM_WIN32
949 gint i, clen, total_len, wclen, first;
955 len = strlen (opsysstring);
957 wcs = g_new (wchar_t, len);
958 wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
962 for (i = 0; i < wclen; i++)
970 else if (wc < 0x10000)
972 else if (wc < 0x200000)
974 else if (wc < 0x4000000)
980 result = g_malloc (total_len + 1);
984 for (i = 0; i < wclen; i++)
998 else if (wc < 0x10000)
1003 else if (wc < 0x200000)
1008 else if (wc < 0x4000000)
1022 case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1023 case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1024 case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1025 case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1026 case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1027 case 1: bp[0] = wc | first;
1039 *bytes_written = total_len;
1043 #else /* !G_PLATFORM_WIN32 */
1045 const char *charset;
1047 if (g_get_charset (&charset))
1048 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1050 return g_convert (opsysstring, len,
1051 "UTF-8", charset, bytes_read, bytes_written, error);
1053 #endif /* !G_PLATFORM_WIN32 */
1057 * g_locale_from_utf8:
1058 * @utf8string: a UTF-8 encoded string
1059 * @len: the length of the string, or -1 if the string is
1061 * @bytes_read: location to store the number of bytes in the
1062 * input string that were successfully converted, or %NULL.
1063 * Even if the conversion was successful, this may be
1064 * less than @len if there were partial characters
1065 * at the end of the input. If the error
1066 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1067 * stored will the byte offset after the last valid
1069 * @bytes_written: the number of bytes stored in the output buffer (not
1070 * including the terminating nul).
1071 * @error: location to store the error occuring, or %NULL to ignore
1072 * errors. Any of the errors in #GConvertError may occur.
1074 * Converts a string from UTF-8 to the encoding used for strings by
1075 * the C runtime (usually the same as that used by the operating
1076 * system) in the current locale.
1078 * Return value: The converted string, or %NULL on an error.
1081 g_locale_from_utf8 (const gchar *utf8string,
1084 gsize *bytes_written,
1087 #ifdef G_PLATFORM_WIN32
1089 gint i, mask, clen, mblen;
1092 guchar *cp, *end, c;
1096 len = strlen (utf8string);
1098 /* First convert to wide chars */
1099 cp = (guchar *) utf8string;
1102 wcs = g_new (wchar_t, len + 1);
1114 else if ((c & 0xe0) == 0xc0)
1119 else if ((c & 0xf0) == 0xe0)
1124 else if ((c & 0xf8) == 0xf0)
1129 else if ((c & 0xfc) == 0xf8)
1134 else if ((c & 0xfc) == 0xfc)
1145 if (cp + clen > end)
1151 *wcp = (cp[0] & mask);
1152 for (i = 1; i < clen; i++)
1154 if ((cp[i] & 0xc0) != 0x80)
1160 *wcp |= (cp[i] & 0x3f);
1173 /* n is the number of wide chars constructed */
1175 /* Convert to a string in the current ANSI codepage */
1177 result = g_new (gchar, 3 * n + 1);
1178 mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1185 *bytes_written = mblen;
1189 #else /* !G_PLATFORM_WIN32 */
1191 const gchar *charset;
1193 if (g_get_charset (&charset))
1194 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1196 return g_convert (utf8string, len,
1197 charset, "UTF-8", bytes_read, bytes_written, error);
1199 #endif /* !G_PLATFORM_WIN32 */
1202 #ifndef G_PLATFORM_WIN32
1204 have_broken_filenames (void)
1206 static gboolean initialized = FALSE;
1207 static gboolean broken;
1212 broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1218 #endif /* !G_PLATFORM_WIN32 */
1220 /* This is called from g_thread_init(). It's used to
1221 * initialize some static data in a threadsafe way.
1224 g_convert_init (void)
1226 #ifndef G_PLATFORM_WIN32
1227 (void)have_broken_filenames ();
1228 #endif /* !G_PLATFORM_WIN32 */
1232 * g_filename_to_utf8:
1233 * @opsysstring: a string in the encoding for filenames
1234 * @len: the length of the string, or -1 if the string is
1236 * @bytes_read: location to store the number of bytes in the
1237 * input string that were successfully converted, or %NULL.
1238 * Even if the conversion was successful, this may be
1239 * less than @len if there were partial characters
1240 * at the end of the input. If the error
1241 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1242 * stored will the byte offset after the last valid
1244 * @bytes_written: the number of bytes stored in the output buffer (not
1245 * including the terminating nul).
1246 * @error: location to store the error occuring, or %NULL to ignore
1247 * errors. Any of the errors in #GConvertError may occur.
1249 * Converts a string which is in the encoding used for filenames
1250 * into a UTF-8 string.
1252 * Return value: The converted string, or %NULL on an error.
1255 g_filename_to_utf8 (const gchar *opsysstring,
1258 gsize *bytes_written,
1261 #ifdef G_PLATFORM_WIN32
1262 return g_locale_to_utf8 (opsysstring, len,
1263 bytes_read, bytes_written,
1265 #else /* !G_PLATFORM_WIN32 */
1267 if (have_broken_filenames ())
1268 return g_locale_to_utf8 (opsysstring, len,
1269 bytes_read, bytes_written,
1272 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1273 #endif /* !G_PLATFORM_WIN32 */
1277 * g_filename_from_utf8:
1278 * @utf8string: a UTF-8 encoded string.
1279 * @len: the length of the string, or -1 if the string is
1281 * @bytes_read: location to store the number of bytes in the
1282 * input string that were successfully converted, or %NULL.
1283 * Even if the conversion was successful, this may be
1284 * less than @len if there were partial characters
1285 * at the end of the input. If the error
1286 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1287 * stored will the byte offset after the last valid
1289 * @bytes_written: the number of bytes stored in the output buffer (not
1290 * including the terminating nul).
1291 * @error: location to store the error occuring, or %NULL to ignore
1292 * errors. Any of the errors in #GConvertError may occur.
1294 * Converts a string from UTF-8 to the encoding used for filenames.
1296 * Return value: The converted string, or %NULL on an error.
1299 g_filename_from_utf8 (const gchar *utf8string,
1302 gsize *bytes_written,
1305 #ifdef G_PLATFORM_WIN32
1306 return g_locale_from_utf8 (utf8string, len,
1307 bytes_read, bytes_written,
1309 #else /* !G_PLATFORM_WIN32 */
1310 if (have_broken_filenames ())
1311 return g_locale_from_utf8 (utf8string, len,
1312 bytes_read, bytes_written,
1315 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1316 #endif /* !G_PLATFORM_WIN32 */
1319 /* Test of haystack has the needle prefix, comparing case
1320 * insensitive. haystack may be UTF-8, but needle must
1321 * contain only ascii. */
1323 has_case_prefix (const gchar *haystack, const gchar *needle)
1327 /* Eat one character at a time. */
1332 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1342 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1343 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1344 UNSAFE_PATH = 0x4, /* Allows '/' and '?' and '&' and '=' */
1345 UNSAFE_DOS_PATH = 0x8, /* Allows '/' and '?' and '&' and '=' and ':' */
1346 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1347 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1348 } UnsafeCharacterSet;
1350 static const guchar acceptable[96] = {
1351 /* A table of the ASCII chars from space (32) to DEL (127) */
1352 /* ! " # $ % & ' ( ) * + , - . / */
1353 0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1354 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1355 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1356 /* @ A B C D E F G H I J K L M N O */
1357 0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1358 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1359 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1360 /* ` a b c d e f g h i j k l m n o */
1361 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1362 /* p q r s t u v w x y z { | } ~ DEL */
1363 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1366 static const gchar hex[16] = "0123456789ABCDEF";
1368 /* Note: This escape function works on file: URIs, but if you want to
1369 * escape something else, please read RFC-2396 */
1371 g_escape_uri_string (const gchar *string,
1372 UnsafeCharacterSet mask)
1374 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1381 UnsafeCharacterSet use_mask;
1383 g_return_val_if_fail (mask == UNSAFE_ALL
1384 || mask == UNSAFE_ALLOW_PLUS
1385 || mask == UNSAFE_PATH
1386 || mask == UNSAFE_DOS_PATH
1387 || mask == UNSAFE_HOST
1388 || mask == UNSAFE_SLASHES, NULL);
1392 for (p = string; *p != '\0'; p++)
1395 if (!ACCEPTABLE (c))
1399 result = g_malloc (p - string + unacceptable * 2 + 1);
1402 for (q = result, p = string; *p != '\0'; p++)
1406 if (!ACCEPTABLE (c))
1408 *q++ = '%'; /* means hex coming */
1423 g_escape_file_uri (const gchar *hostname,
1424 const gchar *pathname)
1426 char *escaped_hostname = NULL;
1431 char *p, *backslash;
1433 /* Turn backslashes into forward slashes. That's what Netscape
1434 * does, and they are actually more or less equivalent in Windows.
1437 pathname = g_strdup (pathname);
1438 p = (char *) pathname;
1440 while ((backslash = strchr (p, '\\')) != NULL)
1447 if (hostname && *hostname != '\0')
1449 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1452 escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1454 res = g_strconcat ("file://",
1455 (escaped_hostname) ? escaped_hostname : "",
1456 (*escaped_path != '/') ? "/" : "",
1461 g_free ((char *) pathname);
1464 g_free (escaped_hostname);
1465 g_free (escaped_path);
1471 unescape_character (const char *scanner)
1476 first_digit = g_ascii_xdigit_value (scanner[0]);
1477 if (first_digit < 0)
1480 second_digit = g_ascii_xdigit_value (scanner[1]);
1481 if (second_digit < 0)
1484 return (first_digit << 4) | second_digit;
1488 g_unescape_uri_string (const char *escaped,
1490 const char *illegal_escaped_characters,
1491 gboolean ascii_must_not_be_escaped)
1493 const gchar *in, *in_end;
1494 gchar *out, *result;
1497 if (escaped == NULL)
1501 len = strlen (escaped);
1503 result = g_malloc (len + 1);
1506 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1512 /* catch partial escape sequences past the end of the substring */
1513 if (in + 3 > in_end)
1516 c = unescape_character (in + 1);
1518 /* catch bad escape sequences and NUL characters */
1522 /* catch escaped ASCII */
1523 if (ascii_must_not_be_escaped && c <= 0x7F)
1526 /* catch other illegal escaped characters */
1527 if (strchr (illegal_escaped_characters, c) != NULL)
1536 g_assert (out - result <= len);
1539 if (in != in_end || !g_utf8_validate (result, -1, NULL))
1549 is_escalphanum (gunichar c)
1551 return c > 0x7F || g_ascii_isalnum (c);
1555 is_escalpha (gunichar c)
1557 return c > 0x7F || g_ascii_isalpha (c);
1560 /* allows an empty string */
1562 hostname_validate (const char *hostname)
1565 gunichar c, first_char, last_char;
1572 /* read in a label */
1573 c = g_utf8_get_char (p);
1574 p = g_utf8_next_char (p);
1575 if (!is_escalphanum (c))
1581 c = g_utf8_get_char (p);
1582 p = g_utf8_next_char (p);
1584 while (is_escalphanum (c) || c == '-');
1585 if (last_char == '-')
1588 /* if that was the last label, check that it was a toplabel */
1589 if (c == '\0' || (c == '.' && *p == '\0'))
1590 return is_escalpha (first_char);
1597 * g_filename_from_uri:
1598 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1599 * @hostname: Location to store hostname for the URI, or %NULL.
1600 * If there is no hostname in the URI, %NULL will be
1601 * stored in this location.
1602 * @error: location to store the error occuring, or %NULL to ignore
1603 * errors. Any of the errors in #GConvertError may occur.
1605 * Converts an escaped UTF-8 encoded URI to a local filename in the
1606 * encoding used for filenames.
1608 * Return value: a newly-allocated string holding the resulting
1609 * filename, or %NULL on an error.
1612 g_filename_from_uri (const char *uri,
1616 const char *path_part;
1617 const char *host_part;
1618 char *unescaped_hostname;
1629 if (!has_case_prefix (uri, "file:/"))
1631 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1632 _("The URI '%s' is not an absolute URI using the file scheme"),
1637 path_part = uri + strlen ("file:");
1639 if (strchr (path_part, '#') != NULL)
1641 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1642 _("The local file URI '%s' may not include a '#'"),
1647 if (has_case_prefix (path_part, "///"))
1649 else if (has_case_prefix (path_part, "//"))
1652 host_part = path_part;
1654 path_part = strchr (path_part, '/');
1656 if (path_part == NULL)
1658 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1659 _("The URI '%s' is invalid"),
1664 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1666 if (unescaped_hostname == NULL ||
1667 !hostname_validate (unescaped_hostname))
1669 g_free (unescaped_hostname);
1670 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1671 _("The hostname of the URI '%s' is invalid"),
1677 *hostname = unescaped_hostname;
1679 g_free (unescaped_hostname);
1682 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1684 if (filename == NULL)
1686 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1687 _("The URI '%s' contains invalidly escaped characters"),
1694 /* Drop localhost */
1695 if (hostname && *hostname != NULL &&
1696 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1702 /* Turn slashes into backslashes, because that's the canonical spelling */
1704 while ((slash = strchr (p, '/')) != NULL)
1710 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1711 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1712 * the filename from the drive letter.
1714 if (g_ascii_isalpha (filename[1]))
1716 if (filename[2] == ':')
1718 else if (filename[2] == '|')
1726 result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1733 * g_filename_to_uri:
1734 * @filename: an absolute filename specified in the encoding
1735 * used for filenames by the operating system.
1736 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1737 * @error: location to store the error occuring, or %NULL to ignore
1738 * errors. Any of the errors in #GConvertError may occur.
1740 * Converts an absolute filename to an escaped UTF-8 encoded URI.
1742 * Return value: a newly-allocated string holding the resulting
1743 * URI, or %NULL on an error.
1746 g_filename_to_uri (const char *filename,
1747 const char *hostname,
1751 char *utf8_filename;
1753 g_return_val_if_fail (filename != NULL, NULL);
1755 if (!g_path_is_absolute (filename))
1757 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1758 _("The pathname '%s' is not an absolute path"),
1764 !(g_utf8_validate (hostname, -1, NULL)
1765 && hostname_validate (hostname)))
1767 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1768 _("Invalid hostname"));
1772 utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1773 if (utf8_filename == NULL)
1777 /* Don't use localhost unnecessarily */
1778 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1782 escaped_uri = g_escape_file_uri (hostname,
1784 g_free (utf8_filename);