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.
24 #include "glibconfig.h"
35 #include "win_iconv.c"
38 #ifdef G_PLATFORM_WIN32
48 #include "gstrfuncs.h"
49 #include "gtestutils.h"
52 #include "gfileutils.h"
54 #ifdef NEED_ICONV_CACHE
61 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
62 #error GNU libiconv in use but included iconv.h not from libiconv
64 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H) \
65 && !defined (__APPLE_CC__) && !defined (__LP_64__)
66 #error GNU libiconv not in use but included iconv.h is from libiconv
72 * @title: Character Set Conversion
73 * @short_description: convert strings between different character sets
75 * The g_convert() family of function wraps the functionality of iconv(). In
76 * addition to pure character set conversions, GLib has functions to deal
77 * with the extra complications of encodings for file names.
79 * <refsect2 id="file-name-encodings">
80 * <title>File Name Encodings</title>
82 * Historically, Unix has not had a defined encoding for file
83 * names: a file name is valid as long as it does not have path
84 * separators in it ("/"). However, displaying file names may
85 * require conversion: from the character set in which they were
86 * created, to the character set in which the application
87 * operates. Consider the Spanish file name
88 * "<filename>Presentación.sxi</filename>". If the
89 * application which created it uses ISO-8859-1 for its encoding,
91 * <programlisting id="filename-iso8859-1">
92 * Character: P r e s e n t a c i ó n . s x i
93 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
96 * However, if the application use UTF-8, the actual file name on
97 * disk would look like this:
99 * <programlisting id="filename-utf-8">
100 * Character: P r e s e n t a c i ó n . s x i
101 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
104 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
105 * that use Glib do the same thing. If you get a file name from
106 * the file system, for example, from readdir(3) or from g_dir_read_name(),
107 * and you wish to display the file name to the user, you
108 * <emphasis>will</emphasis> need to convert it into UTF-8. The
109 * opposite case is when the user types the name of a file he
110 * wishes to save: the toolkit will give you that string in
111 * UTF-8 encoding, and you will need to convert it to the
112 * character set used for file names before you can create the
113 * file with open(2) or fopen(3).
116 * By default, Glib assumes that file names on disk are in UTF-8
117 * encoding. This is a valid assumption for file systems which
118 * were created relatively recently: most applications use UTF-8
119 * encoding for their strings, and that is also what they use for
120 * the file names they create. However, older file systems may
121 * still contain file names created in "older" encodings, such as
122 * ISO-8859-1. In this case, for compatibility reasons, you may
123 * want to instruct Glib to use that particular encoding for file
124 * names rather than UTF-8. You can do this by specifying the
125 * encoding for file names in the <link
126 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
127 * environment variable. For example, if your installation uses
128 * ISO-8859-1 for file names, you can put this in your
129 * <filename>~/.profile</filename>:
132 * export G_FILENAME_ENCODING=ISO-8859-1
135 * Glib provides the functions g_filename_to_utf8() and
136 * g_filename_from_utf8() to perform the necessary conversions. These
137 * functions convert file names from the encoding specified in
138 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
139 * <xref linkend="file-name-encodings-diagram"/> illustrates how
140 * these functions are used to convert between UTF-8 and the
141 * encoding for file names in the file system.
143 * <figure id="file-name-encodings-diagram">
144 * <title>Conversion between File Name Encodings</title>
145 * <graphic fileref="file-name-encodings.png" format="PNG"/>
147 * <refsect3 id="file-name-encodings-checklist">
148 * <title>Checklist for Application Writers</title>
150 * This section is a practical summary of the detailed
151 * description above. You can use this as a checklist of
152 * things to do to make sure your applications process file
153 * name encodings correctly.
157 * If you get a file name from the file system from a function
158 * such as readdir(3) or gtk_file_chooser_get_filename(),
159 * you do not need to do any conversion to pass that
160 * file name to functions like open(2), rename(2), or
161 * fopen(3) — those are "raw" file names which the file
162 * system understands.
165 * If you need to display a file name, convert it to UTF-8 first by
166 * using g_filename_to_utf8(). If conversion fails, display a string like
167 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
168 * convert this string back into the encoding used for file names if you
169 * wish to pass it to the file system; use the original file name instead.
170 * For example, the document window of a word processor could display
171 * "Unknown file name" in its title bar but still let the user save the
172 * file, as it would keep the raw file name internally. This can happen
173 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
174 * environment variable even though he has files whose names are not
178 * If your user interface lets the user type a file name for saving or
179 * renaming, convert it to the encoding used for file names in the file
180 * system by using g_filename_from_utf8(). Pass the converted file name
181 * to functions like fopen(3). If conversion fails, ask the user to enter
182 * a different file name. This can happen if the user types Japanese
183 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
184 * <literal>ISO-8859-1</literal>, for example.
191 /* We try to terminate strings in unknown charsets with this many zero bytes
192 * to ensure that multibyte strings really are nul-terminated when we return
193 * them from g_convert() and friends.
195 #define NUL_TERMINATOR_LENGTH 4
197 G_DEFINE_QUARK ("g_convert_error", g_convert_error
)
200 try_conversion (const char *to_codeset
,
201 const char *from_codeset
,
204 *cd
= iconv_open (to_codeset
, from_codeset
);
206 if (*cd
== (iconv_t
)-1 && errno
== EINVAL
)
213 try_to_aliases (const char **to_aliases
,
214 const char *from_codeset
,
219 const char **p
= to_aliases
;
222 if (try_conversion (*p
, from_codeset
, cd
))
232 G_GNUC_INTERNAL
extern const char **
233 _g_charset_get_aliases (const char *canonical_name
);
237 * @to_codeset: destination codeset
238 * @from_codeset: source codeset
240 * Same as the standard UNIX routine iconv_open(), but
241 * may be implemented via libiconv on UNIX flavors that lack
242 * a native implementation.
244 * GLib provides g_convert() and g_locale_to_utf8() which are likely
245 * more convenient than the raw iconv wrappers.
247 * Return value: a "conversion descriptor", or (GIConv)-1 if
248 * opening the converter failed.
251 g_iconv_open (const gchar
*to_codeset
,
252 const gchar
*from_codeset
)
256 if (!try_conversion (to_codeset
, from_codeset
, &cd
))
258 const char **to_aliases
= _g_charset_get_aliases (to_codeset
);
259 const char **from_aliases
= _g_charset_get_aliases (from_codeset
);
263 const char **p
= from_aliases
;
266 if (try_conversion (to_codeset
, *p
, &cd
))
269 if (try_to_aliases (to_aliases
, *p
, &cd
))
276 if (try_to_aliases (to_aliases
, from_codeset
, &cd
))
281 return (cd
== (iconv_t
)-1) ? (GIConv
)-1 : (GIConv
)cd
;
286 * @converter: conversion descriptor from g_iconv_open()
287 * @inbuf: bytes to convert
288 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
289 * @outbuf: converted output bytes
290 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
292 * Same as the standard UNIX routine iconv(), but
293 * may be implemented via libiconv on UNIX flavors that lack
294 * a native implementation.
296 * GLib provides g_convert() and g_locale_to_utf8() which are likely
297 * more convenient than the raw iconv wrappers.
299 * Return value: count of non-reversible conversions, or -1 on error
302 g_iconv (GIConv converter
,
306 gsize
*outbytes_left
)
308 iconv_t cd
= (iconv_t
)converter
;
310 return iconv (cd
, inbuf
, inbytes_left
, outbuf
, outbytes_left
);
315 * @converter: a conversion descriptor from g_iconv_open()
317 * Same as the standard UNIX routine iconv_close(), but
318 * may be implemented via libiconv on UNIX flavors that lack
319 * a native implementation. Should be called to clean up
320 * the conversion descriptor from g_iconv_open() when
321 * you are done converting things.
323 * GLib provides g_convert() and g_locale_to_utf8() which are likely
324 * more convenient than the raw iconv wrappers.
326 * Return value: -1 on error, 0 on success
329 g_iconv_close (GIConv converter
)
331 iconv_t cd
= (iconv_t
)converter
;
333 return iconv_close (cd
);
337 #ifdef NEED_ICONV_CACHE
339 #define ICONV_CACHE_SIZE (16)
341 struct _iconv_cache_bucket
{
348 static GList
*iconv_cache_list
;
349 static GHashTable
*iconv_cache
;
350 static GHashTable
*iconv_open_hash
;
351 static guint iconv_cache_size
= 0;
352 G_LOCK_DEFINE_STATIC (iconv_cache_lock
);
354 /* caller *must* hold the iconv_cache_lock */
356 iconv_cache_init (void)
358 static gboolean initialized
= FALSE
;
363 iconv_cache_list
= NULL
;
364 iconv_cache
= g_hash_table_new (g_str_hash
, g_str_equal
);
365 iconv_open_hash
= g_hash_table_new (g_direct_hash
, g_direct_equal
);
372 * iconv_cache_bucket_new:
374 * @cd: iconv descriptor
376 * Creates a new cache bucket, inserts it into the cache and
377 * increments the cache size.
379 * This assumes ownership of @key.
381 * Returns a pointer to the newly allocated cache bucket.
383 static struct _iconv_cache_bucket
*
384 iconv_cache_bucket_new (gchar
*key
, GIConv cd
)
386 struct _iconv_cache_bucket
*bucket
;
388 bucket
= g_new (struct _iconv_cache_bucket
, 1);
390 bucket
->refcount
= 1;
394 g_hash_table_insert (iconv_cache
, bucket
->key
, bucket
);
396 /* FIXME: if we sorted the list so items with few refcounts were
397 first, then we could expire them faster in iconv_cache_expire_unused () */
398 iconv_cache_list
= g_list_prepend (iconv_cache_list
, bucket
);
407 * iconv_cache_bucket_expire:
408 * @node: cache bucket's node
409 * @bucket: cache bucket
411 * Expires a single cache bucket @bucket. This should only ever be
412 * called on a bucket that currently has no used iconv descriptors
415 * @node is not a required argument. If @node is not supplied, we
416 * search for it ourselves.
419 iconv_cache_bucket_expire (GList
*node
, struct _iconv_cache_bucket
*bucket
)
421 g_hash_table_remove (iconv_cache
, bucket
->key
);
424 node
= g_list_find (iconv_cache_list
, bucket
);
426 g_assert (node
!= NULL
);
430 node
->prev
->next
= node
->next
;
432 node
->next
->prev
= node
->prev
;
436 iconv_cache_list
= node
->next
;
438 node
->next
->prev
= NULL
;
441 g_list_free_1 (node
);
443 g_free (bucket
->key
);
444 g_iconv_close (bucket
->cd
);
452 * iconv_cache_expire_unused:
454 * Expires as many unused cache buckets as it needs to in order to get
455 * the total number of buckets < ICONV_CACHE_SIZE.
458 iconv_cache_expire_unused (void)
460 struct _iconv_cache_bucket
*bucket
;
463 node
= iconv_cache_list
;
464 while (node
&& iconv_cache_size
>= ICONV_CACHE_SIZE
)
469 if (bucket
->refcount
== 0)
470 iconv_cache_bucket_expire (node
, bucket
);
477 open_converter (const gchar
*to_codeset
,
478 const gchar
*from_codeset
,
481 struct _iconv_cache_bucket
*bucket
;
482 gchar
*key
, *dyn_key
, auto_key
[80];
484 gsize len_from_codeset
, len_to_codeset
;
487 len_from_codeset
= strlen (from_codeset
);
488 len_to_codeset
= strlen (to_codeset
);
489 if (len_from_codeset
+ len_to_codeset
+ 2 < sizeof (auto_key
))
495 key
= dyn_key
= g_malloc (len_from_codeset
+ len_to_codeset
+ 2);
496 memcpy (key
, from_codeset
, len_from_codeset
);
497 key
[len_from_codeset
] = ':';
498 strcpy (key
+ len_from_codeset
+ 1, to_codeset
);
500 G_LOCK (iconv_cache_lock
);
502 /* make sure the cache has been initialized */
505 bucket
= g_hash_table_lookup (iconv_cache
, key
);
512 cd
= g_iconv_open (to_codeset
, from_codeset
);
513 if (cd
== (GIConv
) -1)
518 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
519 * NULL for anything but inbuf; work around that. (NULL outbuf
520 * or NULL *outbuf is allowed by Unix98.)
522 gsize inbytes_left
= 0;
523 gchar
*outbuf
= NULL
;
524 gsize outbytes_left
= 0;
529 /* reset the descriptor */
530 g_iconv (cd
, NULL
, &inbytes_left
, &outbuf
, &outbytes_left
);
537 cd
= g_iconv_open (to_codeset
, from_codeset
);
538 if (cd
== (GIConv
) -1)
544 iconv_cache_expire_unused ();
546 bucket
= iconv_cache_bucket_new (dyn_key
? dyn_key
: g_strdup (key
), cd
);
549 g_hash_table_insert (iconv_open_hash
, cd
, bucket
->key
);
551 G_UNLOCK (iconv_cache_lock
);
557 G_UNLOCK (iconv_cache_lock
);
559 /* Something went wrong. */
563 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_NO_CONVERSION
,
564 _("Conversion from character set '%s' to '%s' is not supported"),
565 from_codeset
, to_codeset
);
567 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
568 _("Could not open converter from '%s' to '%s'"),
569 from_codeset
, to_codeset
);
576 close_converter (GIConv converter
)
578 struct _iconv_cache_bucket
*bucket
;
584 if (cd
== (GIConv
) -1)
587 G_LOCK (iconv_cache_lock
);
589 key
= g_hash_table_lookup (iconv_open_hash
, cd
);
592 g_hash_table_remove (iconv_open_hash
, cd
);
594 bucket
= g_hash_table_lookup (iconv_cache
, key
);
599 if (cd
== bucket
->cd
)
600 bucket
->used
= FALSE
;
604 if (!bucket
->refcount
&& iconv_cache_size
> ICONV_CACHE_SIZE
)
606 /* expire this cache bucket */
607 iconv_cache_bucket_expire (NULL
, bucket
);
612 G_UNLOCK (iconv_cache_lock
);
614 g_warning ("This iconv context wasn't opened using open_converter");
616 return g_iconv_close (converter
);
619 G_UNLOCK (iconv_cache_lock
);
624 #else /* !NEED_ICONV_CACHE */
627 open_converter (const gchar
*to_codeset
,
628 const gchar
*from_codeset
,
633 cd
= g_iconv_open (to_codeset
, from_codeset
);
635 if (cd
== (GIConv
) -1)
637 /* Something went wrong. */
641 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_NO_CONVERSION
,
642 _("Conversion from character set '%s' to '%s' is not supported"),
643 from_codeset
, to_codeset
);
645 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
646 _("Could not open converter from '%s' to '%s'"),
647 from_codeset
, to_codeset
);
655 close_converter (GIConv cd
)
657 if (cd
== (GIConv
) -1)
660 return g_iconv_close (cd
);
663 #endif /* NEED_ICONV_CACHE */
666 * g_convert_with_iconv:
667 * @str: the string to convert
668 * @len: the length of the string, or -1 if the string is
669 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
670 * @converter: conversion descriptor from g_iconv_open()
671 * @bytes_read: location to store the number of bytes in the
672 * input string that were successfully converted, or %NULL.
673 * Even if the conversion was successful, this may be
674 * less than @len if there were partial characters
675 * at the end of the input. If the error
676 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
677 * stored will the byte offset after the last valid
679 * @bytes_written: the number of bytes stored in the output buffer (not
680 * including the terminating nul).
681 * @error: location to store the error occurring, or %NULL to ignore
682 * errors. Any of the errors in #GConvertError may occur.
684 * Converts a string from one character set to another.
686 * Note that you should use g_iconv() for streaming
687 * conversions<footnote id="streaming-state">
689 * Despite the fact that @byes_read can return information about partial
690 * characters, the <literal>g_convert_...</literal> functions
691 * are not generally suitable for streaming. If the underlying converter
692 * being used maintains internal state, then this won't be preserved
693 * across successive calls to g_convert(), g_convert_with_iconv() or
694 * g_convert_with_fallback(). (An example of this is the GNU C converter
695 * for CP1255 which does not emit a base character until it knows that
696 * the next character is not a mark that could combine with the base
701 * Return value: If the conversion was successful, a newly allocated
702 * nul-terminated string, which must be freed with
703 * g_free(). Otherwise %NULL and @error will be set.
706 g_convert_with_iconv (const gchar
*str
,
710 gsize
*bytes_written
,
716 gsize inbytes_remaining
;
717 gsize outbytes_remaining
;
720 gboolean have_error
= FALSE
;
721 gboolean done
= FALSE
;
722 gboolean reset
= FALSE
;
724 g_return_val_if_fail (converter
!= (GIConv
) -1, NULL
);
730 inbytes_remaining
= len
;
731 outbuf_size
= len
+ NUL_TERMINATOR_LENGTH
;
733 outbytes_remaining
= outbuf_size
- NUL_TERMINATOR_LENGTH
;
734 outp
= dest
= g_malloc (outbuf_size
);
736 while (!done
&& !have_error
)
739 err
= g_iconv (converter
, NULL
, &inbytes_remaining
, &outp
, &outbytes_remaining
);
741 err
= g_iconv (converter
, (char **)&p
, &inbytes_remaining
, &outp
, &outbytes_remaining
);
743 if (err
== (gsize
) -1)
748 /* Incomplete text, do not report an error */
753 gsize used
= outp
- dest
;
756 dest
= g_realloc (dest
, outbuf_size
);
759 outbytes_remaining
= outbuf_size
- used
- NUL_TERMINATOR_LENGTH
;
763 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
764 _("Invalid byte sequence in conversion input"));
771 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
772 _("Error during conversion: %s"),
783 /* call g_iconv with NULL inbuf to cleanup shift state */
785 inbytes_remaining
= 0;
792 memset (outp
, 0, NUL_TERMINATOR_LENGTH
);
795 *bytes_read
= p
- str
;
798 if ((p
- str
) != len
)
802 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_PARTIAL_INPUT
,
803 _("Partial character sequence at end of input"));
810 *bytes_written
= outp
- dest
; /* Doesn't include '\0' */
823 * @str: the string to convert
824 * @len: the length of the string, or -1 if the string is
825 * nul-terminated<footnote id="nul-unsafe">
827 Note that some encodings may allow nul bytes to
828 occur inside strings. In that case, using -1 for
829 the @len parameter is unsafe.
832 * @to_codeset: name of character set into which to convert @str
833 * @from_codeset: character set of @str.
834 * @bytes_read: (out): location to store the number of bytes in the
835 * input string that were successfully converted, or %NULL.
836 * Even if the conversion was successful, this may be
837 * less than @len if there were partial characters
838 * at the end of the input. If the error
839 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
840 * stored will the byte offset after the last valid
842 * @bytes_written: (out): the number of bytes stored in the output buffer (not
843 * including the terminating nul).
844 * @error: location to store the error occurring, or %NULL to ignore
845 * errors. Any of the errors in #GConvertError may occur.
847 * Converts a string from one character set to another.
849 * Note that you should use g_iconv() for streaming
850 * conversions<footnoteref linkend="streaming-state"/>.
852 * Return value: If the conversion was successful, a newly allocated
853 * nul-terminated string, which must be freed with
854 * g_free(). Otherwise %NULL and @error will be set.
857 g_convert (const gchar
*str
,
859 const gchar
*to_codeset
,
860 const gchar
*from_codeset
,
862 gsize
*bytes_written
,
868 g_return_val_if_fail (str
!= NULL
, NULL
);
869 g_return_val_if_fail (to_codeset
!= NULL
, NULL
);
870 g_return_val_if_fail (from_codeset
!= NULL
, NULL
);
872 cd
= open_converter (to_codeset
, from_codeset
, error
);
874 if (cd
== (GIConv
) -1)
885 res
= g_convert_with_iconv (str
, len
, cd
,
886 bytes_read
, bytes_written
,
889 close_converter (cd
);
895 * g_convert_with_fallback:
896 * @str: the string to convert
897 * @len: the length of the string, or -1 if the string is
898 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
899 * @to_codeset: name of character set into which to convert @str
900 * @from_codeset: character set of @str.
901 * @fallback: UTF-8 string to use in place of character not
902 * present in the target encoding. (The string must be
903 * representable in the target encoding).
904 If %NULL, characters not in the target encoding will
905 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
906 * @bytes_read: location to store the number of bytes in the
907 * input string that were successfully converted, or %NULL.
908 * Even if the conversion was successful, this may be
909 * less than @len if there were partial characters
910 * at the end of the input.
911 * @bytes_written: the number of bytes stored in the output buffer (not
912 * including the terminating nul).
913 * @error: location to store the error occurring, or %NULL to ignore
914 * errors. Any of the errors in #GConvertError may occur.
916 * Converts a string from one character set to another, possibly
917 * including fallback sequences for characters not representable
918 * in the output. Note that it is not guaranteed that the specification
919 * for the fallback sequences in @fallback will be honored. Some
920 * systems may do an approximate conversion from @from_codeset
921 * to @to_codeset in their iconv() functions,
922 * in which case GLib will simply return that approximate conversion.
924 * Note that you should use g_iconv() for streaming
925 * conversions<footnoteref linkend="streaming-state"/>.
927 * Return value: If the conversion was successful, a newly allocated
928 * nul-terminated string, which must be freed with
929 * g_free(). Otherwise %NULL and @error will be set.
932 g_convert_with_fallback (const gchar
*str
,
934 const gchar
*to_codeset
,
935 const gchar
*from_codeset
,
936 const gchar
*fallback
,
938 gsize
*bytes_written
,
944 const gchar
*insert_str
= NULL
;
946 gsize inbytes_remaining
;
947 const gchar
*save_p
= NULL
;
948 gsize save_inbytes
= 0;
949 gsize outbytes_remaining
;
953 gboolean have_error
= FALSE
;
954 gboolean done
= FALSE
;
956 GError
*local_error
= NULL
;
958 g_return_val_if_fail (str
!= NULL
, NULL
);
959 g_return_val_if_fail (to_codeset
!= NULL
, NULL
);
960 g_return_val_if_fail (from_codeset
!= NULL
, NULL
);
965 /* Try an exact conversion; we only proceed if this fails
966 * due to an illegal sequence in the input string.
968 dest
= g_convert (str
, len
, to_codeset
, from_codeset
,
969 bytes_read
, bytes_written
, &local_error
);
973 if (!g_error_matches (local_error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
))
975 g_propagate_error (error
, local_error
);
979 g_error_free (local_error
);
983 /* No go; to proceed, we need a converter from "UTF-8" to
984 * to_codeset, and the string as UTF-8.
986 cd
= open_converter (to_codeset
, "UTF-8", error
);
987 if (cd
== (GIConv
) -1)
998 utf8
= g_convert (str
, len
, "UTF-8", from_codeset
,
999 bytes_read
, &inbytes_remaining
, error
);
1002 close_converter (cd
);
1008 /* Now the heart of the code. We loop through the UTF-8 string, and
1009 * whenever we hit an offending character, we form fallback, convert
1010 * the fallback to the target codeset, and then go back to
1011 * converting the original string after finishing with the fallback.
1013 * The variables save_p and save_inbytes store the input state
1014 * for the original string while we are converting the fallback
1018 outbuf_size
= len
+ NUL_TERMINATOR_LENGTH
;
1019 outbytes_remaining
= outbuf_size
- NUL_TERMINATOR_LENGTH
;
1020 outp
= dest
= g_malloc (outbuf_size
);
1022 while (!done
&& !have_error
)
1024 gsize inbytes_tmp
= inbytes_remaining
;
1025 err
= g_iconv (cd
, (char **)&p
, &inbytes_tmp
, &outp
, &outbytes_remaining
);
1026 inbytes_remaining
= inbytes_tmp
;
1028 if (err
== (gsize
) -1)
1033 g_assert_not_reached();
1037 gsize used
= outp
- dest
;
1040 dest
= g_realloc (dest
, outbuf_size
);
1043 outbytes_remaining
= outbuf_size
- used
- NUL_TERMINATOR_LENGTH
;
1050 /* Error converting fallback string - fatal
1052 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
1053 _("Cannot convert fallback '%s' to codeset '%s'"),
1054 insert_str
, to_codeset
);
1062 gunichar ch
= g_utf8_get_char (p
);
1063 insert_str
= g_strdup_printf (ch
< 0x10000 ? "\\u%04x" : "\\U%08x",
1067 insert_str
= fallback
;
1069 save_p
= g_utf8_next_char (p
);
1070 save_inbytes
= inbytes_remaining
- (save_p
- p
);
1072 inbytes_remaining
= strlen (p
);
1075 /* fall thru if p is NULL */
1080 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
1081 _("Error during conversion: %s"),
1082 g_strerror (errsv
));
1094 g_free ((gchar
*)insert_str
);
1096 inbytes_remaining
= save_inbytes
;
1101 /* call g_iconv with NULL inbuf to cleanup shift state */
1103 inbytes_remaining
= 0;
1112 memset (outp
, 0, NUL_TERMINATOR_LENGTH
);
1114 close_converter (cd
);
1117 *bytes_written
= outp
- dest
; /* Doesn't include '\0' */
1123 if (save_p
&& !fallback
)
1124 g_free ((gchar
*)insert_str
);
1139 strdup_len (const gchar
*string
,
1141 gsize
*bytes_written
,
1148 if (!g_utf8_validate (string
, len
, NULL
))
1155 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
1156 _("Invalid byte sequence in conversion input"));
1161 real_len
= strlen (string
);
1166 while (real_len
< len
&& string
[real_len
])
1171 *bytes_read
= real_len
;
1173 *bytes_written
= real_len
;
1175 return g_strndup (string
, real_len
);
1180 * @opsysstring: a string in the encoding of the current locale. On Windows
1181 * this means the system codepage.
1182 * @len: the length of the string, or -1 if the string is
1183 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1184 * @bytes_read: location to store the number of bytes in the
1185 * input string that were successfully converted, or %NULL.
1186 * Even if the conversion was successful, this may be
1187 * less than @len if there were partial characters
1188 * at the end of the input. If the error
1189 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1190 * stored will the byte offset after the last valid
1192 * @bytes_written: the number of bytes stored in the output buffer (not
1193 * including the terminating nul).
1194 * @error: location to store the error occurring, or %NULL to ignore
1195 * errors. Any of the errors in #GConvertError may occur.
1197 * Converts a string which is in the encoding used for strings by
1198 * the C runtime (usually the same as that used by the operating
1199 * system) in the <link linkend="setlocale">current locale</link> into a
1202 * Return value: The converted string, or %NULL on an error.
1205 g_locale_to_utf8 (const gchar
*opsysstring
,
1208 gsize
*bytes_written
,
1211 const char *charset
;
1213 if (g_get_charset (&charset
))
1214 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
1216 return g_convert (opsysstring
, len
,
1217 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
1221 * g_locale_from_utf8:
1222 * @utf8string: a UTF-8 encoded string
1223 * @len: the length of the string, or -1 if the string is
1224 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1225 * @bytes_read: location to store the number of bytes in the
1226 * input string that were successfully converted, or %NULL.
1227 * Even if the conversion was successful, this may be
1228 * less than @len if there were partial characters
1229 * at the end of the input. If the error
1230 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1231 * stored will the byte offset after the last valid
1233 * @bytes_written: the number of bytes stored in the output buffer (not
1234 * including the terminating nul).
1235 * @error: location to store the error occurring, or %NULL to ignore
1236 * errors. Any of the errors in #GConvertError may occur.
1238 * Converts a string from UTF-8 to the encoding used for strings by
1239 * the C runtime (usually the same as that used by the operating
1240 * system) in the <link linkend="setlocale">current locale</link>. On
1241 * Windows this means the system codepage.
1243 * Return value: The converted string, or %NULL on an error.
1246 g_locale_from_utf8 (const gchar
*utf8string
,
1249 gsize
*bytes_written
,
1252 const gchar
*charset
;
1254 if (g_get_charset (&charset
))
1255 return strdup_len (utf8string
, len
, bytes_read
, bytes_written
, error
);
1257 return g_convert (utf8string
, len
,
1258 charset
, "UTF-8", bytes_read
, bytes_written
, error
);
1261 #ifndef G_PLATFORM_WIN32
1263 typedef struct _GFilenameCharsetCache GFilenameCharsetCache
;
1265 struct _GFilenameCharsetCache
{
1268 gchar
**filename_charsets
;
1272 filename_charset_cache_free (gpointer data
)
1274 GFilenameCharsetCache
*cache
= data
;
1275 g_free (cache
->charset
);
1276 g_strfreev (cache
->filename_charsets
);
1281 * g_get_filename_charsets:
1282 * @charsets: return location for the %NULL-terminated list of encoding names
1284 * Determines the preferred character sets used for filenames.
1285 * The first character set from the @charsets is the filename encoding, the
1286 * subsequent character sets are used when trying to generate a displayable
1287 * representation of a filename, see g_filename_display_name().
1289 * On Unix, the character sets are determined by consulting the
1290 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1291 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1292 * used in the GLib API is always UTF-8 and said environment variables
1295 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1296 * of character set names. The special token "@locale" is taken to
1297 * mean the character set for the <link linkend="setlocale">current
1298 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1299 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1300 * locale is taken as the filename encoding. If neither environment variable
1301 * is set, UTF-8 is taken as the filename encoding, but the character
1302 * set of the current locale is also put in the list of encodings.
1304 * The returned @charsets belong to GLib and must not be freed.
1306 * Note that on Unix, regardless of the locale character set or
1307 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1308 * on a system might be in any random encoding or just gibberish.
1310 * Return value: %TRUE if the filename encoding is UTF-8.
1315 g_get_filename_charsets (const gchar
***filename_charsets
)
1317 static GPrivate cache_private
= G_PRIVATE_INIT (filename_charset_cache_free
);
1318 GFilenameCharsetCache
*cache
= g_private_get (&cache_private
);
1319 const gchar
*charset
;
1323 cache
= g_new0 (GFilenameCharsetCache
, 1);
1324 g_private_set (&cache_private
, cache
);
1327 g_get_charset (&charset
);
1329 if (!(cache
->charset
&& strcmp (cache
->charset
, charset
) == 0))
1331 const gchar
*new_charset
;
1335 g_free (cache
->charset
);
1336 g_strfreev (cache
->filename_charsets
);
1337 cache
->charset
= g_strdup (charset
);
1339 p
= getenv ("G_FILENAME_ENCODING");
1340 if (p
!= NULL
&& p
[0] != '\0')
1342 cache
->filename_charsets
= g_strsplit (p
, ",", 0);
1343 cache
->is_utf8
= (strcmp (cache
->filename_charsets
[0], "UTF-8") == 0);
1345 for (i
= 0; cache
->filename_charsets
[i
]; i
++)
1347 if (strcmp ("@locale", cache
->filename_charsets
[i
]) == 0)
1349 g_get_charset (&new_charset
);
1350 g_free (cache
->filename_charsets
[i
]);
1351 cache
->filename_charsets
[i
] = g_strdup (new_charset
);
1355 else if (getenv ("G_BROKEN_FILENAMES") != NULL
)
1357 cache
->filename_charsets
= g_new0 (gchar
*, 2);
1358 cache
->is_utf8
= g_get_charset (&new_charset
);
1359 cache
->filename_charsets
[0] = g_strdup (new_charset
);
1363 cache
->filename_charsets
= g_new0 (gchar
*, 3);
1364 cache
->is_utf8
= TRUE
;
1365 cache
->filename_charsets
[0] = g_strdup ("UTF-8");
1366 if (!g_get_charset (&new_charset
))
1367 cache
->filename_charsets
[1] = g_strdup (new_charset
);
1371 if (filename_charsets
)
1372 *filename_charsets
= (const gchar
**)cache
->filename_charsets
;
1374 return cache
->is_utf8
;
1377 #else /* G_PLATFORM_WIN32 */
1380 g_get_filename_charsets (const gchar
***filename_charsets
)
1382 static const gchar
*charsets
[] = {
1388 /* On Windows GLib pretends that the filename charset is UTF-8 */
1389 if (filename_charsets
)
1390 *filename_charsets
= charsets
;
1396 /* Cygwin works like before */
1397 result
= g_get_charset (&(charsets
[0]));
1399 if (filename_charsets
)
1400 *filename_charsets
= charsets
;
1406 #endif /* G_PLATFORM_WIN32 */
1409 get_filename_charset (const gchar
**filename_charset
)
1411 const gchar
**charsets
;
1414 is_utf8
= g_get_filename_charsets (&charsets
);
1416 if (filename_charset
)
1417 *filename_charset
= charsets
[0];
1423 * g_filename_to_utf8:
1424 * @opsysstring: a string in the encoding for filenames
1425 * @len: the length of the string, or -1 if the string is
1426 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1427 * @bytes_read: location to store the number of bytes in the
1428 * input string that were successfully converted, or %NULL.
1429 * Even if the conversion was successful, this may be
1430 * less than @len if there were partial characters
1431 * at the end of the input. If the error
1432 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1433 * stored will the byte offset after the last valid
1435 * @bytes_written: the number of bytes stored in the output buffer (not
1436 * including the terminating nul).
1437 * @error: location to store the error occurring, or %NULL to ignore
1438 * errors. Any of the errors in #GConvertError may occur.
1440 * Converts a string which is in the encoding used by GLib for
1441 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1442 * for filenames; on other platforms, this function indirectly depends on
1443 * the <link linkend="setlocale">current locale</link>.
1445 * Return value: The converted string, or %NULL on an error.
1448 g_filename_to_utf8 (const gchar
*opsysstring
,
1451 gsize
*bytes_written
,
1454 const gchar
*charset
;
1456 g_return_val_if_fail (opsysstring
!= NULL
, NULL
);
1458 if (get_filename_charset (&charset
))
1459 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
1461 return g_convert (opsysstring
, len
,
1462 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
1465 #if defined (G_OS_WIN32) && !defined (_WIN64)
1467 #undef g_filename_to_utf8
1469 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1470 * 64-bit versions as there should be no old deployed binaries that would use
1475 g_filename_to_utf8 (const gchar
*opsysstring
,
1478 gsize
*bytes_written
,
1481 const gchar
*charset
;
1483 g_return_val_if_fail (opsysstring
!= NULL
, NULL
);
1485 if (g_get_charset (&charset
))
1486 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
1488 return g_convert (opsysstring
, len
,
1489 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
1495 * g_filename_from_utf8:
1496 * @utf8string: a UTF-8 encoded string.
1497 * @len: the length of the string, or -1 if the string is
1499 * @bytes_read: location to store the number of bytes in the
1500 * input string that were successfully converted, or %NULL.
1501 * Even if the conversion was successful, this may be
1502 * less than @len if there were partial characters
1503 * at the end of the input. If the error
1504 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1505 * stored will the byte offset after the last valid
1507 * @bytes_written: the number of bytes stored in the output buffer (not
1508 * including the terminating nul).
1509 * @error: location to store the error occurring, or %NULL to ignore
1510 * errors. Any of the errors in #GConvertError may occur.
1512 * Converts a string from UTF-8 to the encoding GLib uses for
1513 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1514 * on other platforms, this function indirectly depends on the
1515 * <link linkend="setlocale">current locale</link>.
1517 * Return value: The converted string, or %NULL on an error.
1520 g_filename_from_utf8 (const gchar
*utf8string
,
1523 gsize
*bytes_written
,
1526 const gchar
*charset
;
1528 if (get_filename_charset (&charset
))
1529 return strdup_len (utf8string
, len
, bytes_read
, bytes_written
, error
);
1531 return g_convert (utf8string
, len
,
1532 charset
, "UTF-8", bytes_read
, bytes_written
, error
);
1535 #if defined (G_OS_WIN32) && !defined (_WIN64)
1537 #undef g_filename_from_utf8
1539 /* Binary compatibility version. Not for newly compiled code. */
1542 g_filename_from_utf8 (const gchar
*utf8string
,
1545 gsize
*bytes_written
,
1548 const gchar
*charset
;
1550 if (g_get_charset (&charset
))
1551 return strdup_len (utf8string
, len
, bytes_read
, bytes_written
, error
);
1553 return g_convert (utf8string
, len
,
1554 charset
, "UTF-8", bytes_read
, bytes_written
, error
);
1559 /* Test of haystack has the needle prefix, comparing case
1560 * insensitive. haystack may be UTF-8, but needle must
1561 * contain only ascii. */
1563 has_case_prefix (const gchar
*haystack
, const gchar
*needle
)
1567 /* Eat one character at a time. */
1572 g_ascii_tolower (*n
) == g_ascii_tolower (*h
))
1582 UNSAFE_ALL
= 0x1, /* Escape all unsafe characters */
1583 UNSAFE_ALLOW_PLUS
= 0x2, /* Allows '+' */
1584 UNSAFE_PATH
= 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1585 UNSAFE_HOST
= 0x10, /* Allows '/' and ':' and '@' */
1586 UNSAFE_SLASHES
= 0x20 /* Allows all characters except for '/' and '%' */
1587 } UnsafeCharacterSet
;
1589 static const guchar acceptable
[96] = {
1590 /* A table of the ASCII chars from space (32) to DEL (127) */
1591 /* ! " # $ % & ' ( ) * + , - . / */
1592 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1593 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1594 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1595 /* @ A B C D E F G H I J K L M N O */
1596 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1597 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1598 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1599 /* ` a b c d e f g h i j k l m n o */
1600 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1601 /* p q r s t u v w x y z { | } ~ DEL */
1602 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1605 static const gchar hex
[16] = "0123456789ABCDEF";
1607 /* Note: This escape function works on file: URIs, but if you want to
1608 * escape something else, please read RFC-2396 */
1610 g_escape_uri_string (const gchar
*string
,
1611 UnsafeCharacterSet mask
)
1613 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1620 UnsafeCharacterSet use_mask
;
1622 g_return_val_if_fail (mask
== UNSAFE_ALL
1623 || mask
== UNSAFE_ALLOW_PLUS
1624 || mask
== UNSAFE_PATH
1625 || mask
== UNSAFE_HOST
1626 || mask
== UNSAFE_SLASHES
, NULL
);
1630 for (p
= string
; *p
!= '\0'; p
++)
1633 if (!ACCEPTABLE (c
))
1637 result
= g_malloc (p
- string
+ unacceptable
* 2 + 1);
1640 for (q
= result
, p
= string
; *p
!= '\0'; p
++)
1644 if (!ACCEPTABLE (c
))
1646 *q
++ = '%'; /* means hex coming */
1661 g_escape_file_uri (const gchar
*hostname
,
1662 const gchar
*pathname
)
1664 char *escaped_hostname
= NULL
;
1669 char *p
, *backslash
;
1671 /* Turn backslashes into forward slashes. That's what Netscape
1672 * does, and they are actually more or less equivalent in Windows.
1675 pathname
= g_strdup (pathname
);
1676 p
= (char *) pathname
;
1678 while ((backslash
= strchr (p
, '\\')) != NULL
)
1685 if (hostname
&& *hostname
!= '\0')
1687 escaped_hostname
= g_escape_uri_string (hostname
, UNSAFE_HOST
);
1690 escaped_path
= g_escape_uri_string (pathname
, UNSAFE_PATH
);
1692 res
= g_strconcat ("file://",
1693 (escaped_hostname
) ? escaped_hostname
: "",
1694 (*escaped_path
!= '/') ? "/" : "",
1699 g_free ((char *) pathname
);
1702 g_free (escaped_hostname
);
1703 g_free (escaped_path
);
1709 unescape_character (const char *scanner
)
1714 first_digit
= g_ascii_xdigit_value (scanner
[0]);
1715 if (first_digit
< 0)
1718 second_digit
= g_ascii_xdigit_value (scanner
[1]);
1719 if (second_digit
< 0)
1722 return (first_digit
<< 4) | second_digit
;
1726 g_unescape_uri_string (const char *escaped
,
1728 const char *illegal_escaped_characters
,
1729 gboolean ascii_must_not_be_escaped
)
1731 const gchar
*in
, *in_end
;
1732 gchar
*out
, *result
;
1735 if (escaped
== NULL
)
1739 len
= strlen (escaped
);
1741 result
= g_malloc (len
+ 1);
1744 for (in
= escaped
, in_end
= escaped
+ len
; in
< in_end
; in
++)
1750 /* catch partial escape sequences past the end of the substring */
1751 if (in
+ 3 > in_end
)
1754 c
= unescape_character (in
+ 1);
1756 /* catch bad escape sequences and NUL characters */
1760 /* catch escaped ASCII */
1761 if (ascii_must_not_be_escaped
&& c
<= 0x7F)
1764 /* catch other illegal escaped characters */
1765 if (strchr (illegal_escaped_characters
, c
) != NULL
)
1774 g_assert (out
- result
<= len
);
1787 is_asciialphanum (gunichar c
)
1789 return c
<= 0x7F && g_ascii_isalnum (c
);
1793 is_asciialpha (gunichar c
)
1795 return c
<= 0x7F && g_ascii_isalpha (c
);
1798 /* allows an empty string */
1800 hostname_validate (const char *hostname
)
1803 gunichar c
, first_char
, last_char
;
1810 /* read in a label */
1811 c
= g_utf8_get_char (p
);
1812 p
= g_utf8_next_char (p
);
1813 if (!is_asciialphanum (c
))
1819 c
= g_utf8_get_char (p
);
1820 p
= g_utf8_next_char (p
);
1822 while (is_asciialphanum (c
) || c
== '-');
1823 if (last_char
== '-')
1826 /* if that was the last label, check that it was a toplabel */
1827 if (c
== '\0' || (c
== '.' && *p
== '\0'))
1828 return is_asciialpha (first_char
);
1835 * g_filename_from_uri:
1836 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1837 * @hostname: (allow-none): Location to store hostname for the URI, or %NULL.
1838 * If there is no hostname in the URI, %NULL will be
1839 * stored in this location.
1840 * @error: location to store the error occurring, or %NULL to ignore
1841 * errors. Any of the errors in #GConvertError may occur.
1843 * Converts an escaped ASCII-encoded URI to a local filename in the
1844 * encoding used for filenames.
1846 * Return value: a newly-allocated string holding the resulting
1847 * filename, or %NULL on an error.
1850 g_filename_from_uri (const gchar
*uri
,
1854 const char *path_part
;
1855 const char *host_part
;
1856 char *unescaped_hostname
;
1867 if (!has_case_prefix (uri
, "file:/"))
1869 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1870 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1875 path_part
= uri
+ strlen ("file:");
1877 if (strchr (path_part
, '#') != NULL
)
1879 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1880 _("The local file URI '%s' may not include a '#'"),
1885 if (has_case_prefix (path_part
, "///"))
1887 else if (has_case_prefix (path_part
, "//"))
1890 host_part
= path_part
;
1892 path_part
= strchr (path_part
, '/');
1894 if (path_part
== NULL
)
1896 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1897 _("The URI '%s' is invalid"),
1902 unescaped_hostname
= g_unescape_uri_string (host_part
, path_part
- host_part
, "", TRUE
);
1904 if (unescaped_hostname
== NULL
||
1905 !hostname_validate (unescaped_hostname
))
1907 g_free (unescaped_hostname
);
1908 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1909 _("The hostname of the URI '%s' is invalid"),
1915 *hostname
= unescaped_hostname
;
1917 g_free (unescaped_hostname
);
1920 filename
= g_unescape_uri_string (path_part
, -1, "/", FALSE
);
1922 if (filename
== NULL
)
1924 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1925 _("The URI '%s' contains invalidly escaped characters"),
1932 /* Drop localhost */
1933 if (hostname
&& *hostname
!= NULL
&&
1934 g_ascii_strcasecmp (*hostname
, "localhost") == 0)
1940 /* Turn slashes into backslashes, because that's the canonical spelling */
1942 while ((slash
= strchr (p
, '/')) != NULL
)
1948 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1949 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1950 * the filename from the drive letter.
1952 if (g_ascii_isalpha (filename
[1]))
1954 if (filename
[2] == ':')
1956 else if (filename
[2] == '|')
1964 result
= g_strdup (filename
+ offs
);
1970 #if defined (G_OS_WIN32) && !defined (_WIN64)
1972 #undef g_filename_from_uri
1975 g_filename_from_uri (const gchar
*uri
,
1979 gchar
*utf8_filename
;
1980 gchar
*retval
= NULL
;
1982 utf8_filename
= g_filename_from_uri_utf8 (uri
, hostname
, error
);
1985 retval
= g_locale_from_utf8 (utf8_filename
, -1, NULL
, NULL
, error
);
1986 g_free (utf8_filename
);
1994 * g_filename_to_uri:
1995 * @filename: an absolute filename specified in the GLib file name encoding,
1996 * which is the on-disk file name bytes on Unix, and UTF-8 on
1998 * @hostname: (allow-none): A UTF-8 encoded hostname, or %NULL for none.
1999 * @error: location to store the error occurring, or %NULL to ignore
2000 * errors. Any of the errors in #GConvertError may occur.
2002 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2003 * component following Section 3.3. of RFC 2396.
2005 * Return value: a newly-allocated string holding the resulting
2006 * URI, or %NULL on an error.
2009 g_filename_to_uri (const gchar
*filename
,
2010 const gchar
*hostname
,
2015 g_return_val_if_fail (filename
!= NULL
, NULL
);
2017 if (!g_path_is_absolute (filename
))
2019 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH
,
2020 _("The pathname '%s' is not an absolute path"),
2026 !(g_utf8_validate (hostname
, -1, NULL
)
2027 && hostname_validate (hostname
)))
2029 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
2030 _("Invalid hostname"));
2035 /* Don't use localhost unnecessarily */
2036 if (hostname
&& g_ascii_strcasecmp (hostname
, "localhost") == 0)
2040 escaped_uri
= g_escape_file_uri (hostname
, filename
);
2045 #if defined (G_OS_WIN32) && !defined (_WIN64)
2047 #undef g_filename_to_uri
2050 g_filename_to_uri (const gchar
*filename
,
2051 const gchar
*hostname
,
2054 gchar
*utf8_filename
;
2055 gchar
*retval
= NULL
;
2057 utf8_filename
= g_locale_to_utf8 (filename
, -1, NULL
, NULL
, error
);
2061 retval
= g_filename_to_uri_utf8 (utf8_filename
, hostname
, error
);
2062 g_free (utf8_filename
);
2071 * g_uri_list_extract_uris:
2072 * @uri_list: an URI list
2074 * Splits an URI list conforming to the text/uri-list
2075 * mime type defined in RFC 2483 into individual URIs,
2076 * discarding any comments. The URIs are not validated.
2078 * Returns: (transfer full): a newly allocated %NULL-terminated list
2079 * of strings holding the individual URIs. The array should be freed
2080 * with g_strfreev().
2085 g_uri_list_extract_uris (const gchar
*uri_list
)
2096 /* We don't actually try to validate the URI according to RFC
2097 * 2396, or even check for allowed characters - we just ignore
2098 * comments and trim whitespace off the ends. We also
2099 * allow LF delimination as well as the specified CRLF.
2101 * We do allow comments like specified in RFC 2483.
2107 while (g_ascii_isspace (*p
))
2111 while (*q
&& (*q
!= '\n') && (*q
!= '\r'))
2117 while (q
> p
&& g_ascii_isspace (*q
))
2122 uris
= g_slist_prepend (uris
, g_strndup (p
, q
- p
+ 1));
2127 p
= strchr (p
, '\n');
2132 result
= g_new (gchar
*, n_uris
+ 1);
2134 result
[n_uris
--] = NULL
;
2135 for (u
= uris
; u
; u
= u
->next
)
2136 result
[n_uris
--] = u
->data
;
2138 g_slist_free (uris
);
2144 * g_filename_display_basename:
2145 * @filename: an absolute pathname in the GLib file name encoding
2147 * Returns the display basename for the particular filename, guaranteed
2148 * to be valid UTF-8. The display name might not be identical to the filename,
2149 * for instance there might be problems converting it to UTF-8, and some files
2150 * can be translated in the display.
2152 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2153 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2154 * You can search the result for the UTF-8 encoding of this character (which is
2155 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2158 * You must pass the whole absolute pathname to this functions so that
2159 * translation of well known locations can be done.
2161 * This function is preferred over g_filename_display_name() if you know the
2162 * whole path, as it allows translation.
2164 * Return value: a newly allocated string containing
2165 * a rendition of the basename of the filename in valid UTF-8
2170 g_filename_display_basename (const gchar
*filename
)
2175 g_return_val_if_fail (filename
!= NULL
, NULL
);
2177 basename
= g_path_get_basename (filename
);
2178 display_name
= g_filename_display_name (basename
);
2180 return display_name
;
2184 * g_filename_display_name:
2185 * @filename: a pathname hopefully in the GLib file name encoding
2187 * Converts a filename into a valid UTF-8 string. The conversion is
2188 * not necessarily reversible, so you should keep the original around
2189 * and use the return value of this function only for display purposes.
2190 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2191 * even if the filename actually isn't in the GLib file name encoding.
2193 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2194 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2195 * You can search the result for the UTF-8 encoding of this character (which is
2196 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2199 * If you know the whole pathname of the file you should use
2200 * g_filename_display_basename(), since that allows location-based
2201 * translation of filenames.
2203 * Return value: a newly allocated string containing
2204 * a rendition of the filename in valid UTF-8
2209 g_filename_display_name (const gchar
*filename
)
2212 const gchar
**charsets
;
2213 gchar
*display_name
= NULL
;
2216 is_utf8
= g_get_filename_charsets (&charsets
);
2220 if (g_utf8_validate (filename
, -1, NULL
))
2221 display_name
= g_strdup (filename
);
2226 /* Try to convert from the filename charsets to UTF-8.
2227 * Skip the first charset if it is UTF-8.
2229 for (i
= is_utf8
? 1 : 0; charsets
[i
]; i
++)
2231 display_name
= g_convert (filename
, -1, "UTF-8", charsets
[i
],
2239 /* if all conversions failed, we replace invalid UTF-8
2240 * by a question mark
2243 display_name
= _g_utf8_make_valid (filename
);
2245 return display_name
;