Use G_DEFINE_QUARK for GLib's own quarks
[glib.git] / glib / gconvert.c
blob9f3bae3e9532e8e5225c66b0df1e34350519ac6f
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.
23 #include "config.h"
24 #include "glibconfig.h"
26 #ifndef G_OS_WIN32
27 #include <iconv.h>
28 #endif
29 #include <errno.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
34 #ifdef G_OS_WIN32
35 #include "win_iconv.c"
36 #endif
38 #ifdef G_PLATFORM_WIN32
39 #define STRICT
40 #include <windows.h>
41 #undef STRICT
42 #endif
44 #include "gconvert.h"
46 #include "gcharset.h"
47 #include "gslist.h"
48 #include "gstrfuncs.h"
49 #include "gtestutils.h"
50 #include "gthread.h"
51 #include "gunicode.h"
52 #include "gfileutils.h"
54 #ifdef NEED_ICONV_CACHE
55 #include "glist.h"
56 #include "ghash.h"
57 #endif
59 #include "glibintl.h"
61 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
62 #error GNU libiconv in use but included iconv.h not from libiconv
63 #endif
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
67 #endif
70 /**
71 * SECTION:conversions
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>
81 * <para>
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&oacute;n.sxi</filename>". If the
89 * application which created it uses ISO-8859-1 for its encoding,
90 * </para>
91 * <programlisting id="filename-iso8859-1">
92 * Character: P r e s e n t a c i &oacute; n . s x i
93 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
94 * </programlisting>
95 * <para>
96 * However, if the application use UTF-8, the actual file name on
97 * disk would look like this:
98 * </para>
99 * <programlisting id="filename-utf-8">
100 * Character: P r e s e n t a c i &oacute; n . s x i
101 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
102 * </programlisting>
103 * <para>
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).
114 * </para>
115 * <para>
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>:
130 * </para>
131 * <programlisting>
132 * export G_FILENAME_ENCODING=ISO-8859-1
133 * </programlisting>
134 * <para>
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.
142 * </para>
143 * <figure id="file-name-encodings-diagram">
144 * <title>Conversion between File Name Encodings</title>
145 * <graphic fileref="file-name-encodings.png" format="PNG"/>
146 * </figure>
147 * <refsect3 id="file-name-encodings-checklist">
148 * <title>Checklist for Application Writers</title>
149 * <para>
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.
154 * </para>
155 * <orderedlist>
156 * <listitem><para>
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) &mdash; those are "raw" file names which the file
162 * system understands.
163 * </para></listitem>
164 * <listitem><para>
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
175 * encoded in UTF-8.
176 * </para></listitem>
177 * <listitem><para>
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.
185 * </para></listitem>
186 * </orderedlist>
187 * </refsect3>
188 * </refsect2>
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)
199 static gboolean
200 try_conversion (const char *to_codeset,
201 const char *from_codeset,
202 iconv_t *cd)
204 *cd = iconv_open (to_codeset, from_codeset);
206 if (*cd == (iconv_t)-1 && errno == EINVAL)
207 return FALSE;
208 else
209 return TRUE;
212 static gboolean
213 try_to_aliases (const char **to_aliases,
214 const char *from_codeset,
215 iconv_t *cd)
217 if (to_aliases)
219 const char **p = to_aliases;
220 while (*p)
222 if (try_conversion (*p, from_codeset, cd))
223 return TRUE;
225 p++;
229 return FALSE;
232 G_GNUC_INTERNAL extern const char **
233 _g_charset_get_aliases (const char *canonical_name);
236 * g_iconv_open:
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.
250 GIConv
251 g_iconv_open (const gchar *to_codeset,
252 const gchar *from_codeset)
254 iconv_t cd;
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);
261 if (from_aliases)
263 const char **p = from_aliases;
264 while (*p)
266 if (try_conversion (to_codeset, *p, &cd))
267 goto out;
269 if (try_to_aliases (to_aliases, *p, &cd))
270 goto out;
272 p++;
276 if (try_to_aliases (to_aliases, from_codeset, &cd))
277 goto out;
280 out:
281 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
285 * g_iconv:
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
301 gsize
302 g_iconv (GIConv converter,
303 gchar **inbuf,
304 gsize *inbytes_left,
305 gchar **outbuf,
306 gsize *outbytes_left)
308 iconv_t cd = (iconv_t)converter;
310 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
314 * g_iconv_close:
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
328 gint
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 {
342 gchar *key;
343 guint32 refcount;
344 gboolean used;
345 GIConv cd;
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 */
355 static void
356 iconv_cache_init (void)
358 static gboolean initialized = FALSE;
360 if (initialized)
361 return;
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);
367 initialized = TRUE;
372 * iconv_cache_bucket_new:
373 * @key: cache key
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);
389 bucket->key = key;
390 bucket->refcount = 1;
391 bucket->used = TRUE;
392 bucket->cd = cd;
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);
400 iconv_cache_size++;
402 return 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
413 * open.
415 * @node is not a required argument. If @node is not supplied, we
416 * search for it ourselves.
418 static void
419 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
421 g_hash_table_remove (iconv_cache, bucket->key);
423 if (node == NULL)
424 node = g_list_find (iconv_cache_list, bucket);
426 g_assert (node != NULL);
428 if (node->prev)
430 node->prev->next = node->next;
431 if (node->next)
432 node->next->prev = node->prev;
434 else
436 iconv_cache_list = node->next;
437 if (node->next)
438 node->next->prev = NULL;
441 g_list_free_1 (node);
443 g_free (bucket->key);
444 g_iconv_close (bucket->cd);
445 g_free (bucket);
447 iconv_cache_size--;
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.
457 static void
458 iconv_cache_expire_unused (void)
460 struct _iconv_cache_bucket *bucket;
461 GList *node, *next;
463 node = iconv_cache_list;
464 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
466 next = node->next;
468 bucket = node->data;
469 if (bucket->refcount == 0)
470 iconv_cache_bucket_expire (node, bucket);
472 node = next;
476 static GIConv
477 open_converter (const gchar *to_codeset,
478 const gchar *from_codeset,
479 GError **error)
481 struct _iconv_cache_bucket *bucket;
482 gchar *key, *dyn_key, auto_key[80];
483 GIConv cd;
484 gsize len_from_codeset, len_to_codeset;
486 /* create our key */
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))
491 key = auto_key;
492 dyn_key = NULL;
494 else
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 */
503 iconv_cache_init ();
505 bucket = g_hash_table_lookup (iconv_cache, key);
506 if (bucket)
508 g_free (dyn_key);
510 if (bucket->used)
512 cd = g_iconv_open (to_codeset, from_codeset);
513 if (cd == (GIConv) -1)
514 goto error;
516 else
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;
526 cd = bucket->cd;
527 bucket->used = TRUE;
529 /* reset the descriptor */
530 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
533 bucket->refcount++;
535 else
537 cd = g_iconv_open (to_codeset, from_codeset);
538 if (cd == (GIConv) -1)
540 g_free (dyn_key);
541 goto error;
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);
553 return cd;
555 error:
557 G_UNLOCK (iconv_cache_lock);
559 /* Something went wrong. */
560 if (error)
562 if (errno == EINVAL)
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);
566 else
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);
572 return cd;
575 static int
576 close_converter (GIConv converter)
578 struct _iconv_cache_bucket *bucket;
579 const gchar *key;
580 GIConv cd;
582 cd = converter;
584 if (cd == (GIConv) -1)
585 return 0;
587 G_LOCK (iconv_cache_lock);
589 key = g_hash_table_lookup (iconv_open_hash, cd);
590 if (key)
592 g_hash_table_remove (iconv_open_hash, cd);
594 bucket = g_hash_table_lookup (iconv_cache, key);
595 g_assert (bucket);
597 bucket->refcount--;
599 if (cd == bucket->cd)
600 bucket->used = FALSE;
601 else
602 g_iconv_close (cd);
604 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
606 /* expire this cache bucket */
607 iconv_cache_bucket_expire (NULL, bucket);
610 else
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);
621 return 0;
624 #else /* !NEED_ICONV_CACHE */
626 static GIConv
627 open_converter (const gchar *to_codeset,
628 const gchar *from_codeset,
629 GError **error)
631 GIConv cd;
633 cd = g_iconv_open (to_codeset, from_codeset);
635 if (cd == (GIConv) -1)
637 /* Something went wrong. */
638 if (error)
640 if (errno == EINVAL)
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);
644 else
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);
651 return cd;
654 static int
655 close_converter (GIConv cd)
657 if (cd == (GIConv) -1)
658 return 0;
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
678 * input sequence.
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">
688 * <para>
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
697 * character.)
698 * </para>
699 * </footnote>.
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.
705 gchar*
706 g_convert_with_iconv (const gchar *str,
707 gssize len,
708 GIConv converter,
709 gsize *bytes_read,
710 gsize *bytes_written,
711 GError **error)
713 gchar *dest;
714 gchar *outp;
715 const gchar *p;
716 gsize inbytes_remaining;
717 gsize outbytes_remaining;
718 gsize err;
719 gsize outbuf_size;
720 gboolean have_error = FALSE;
721 gboolean done = FALSE;
722 gboolean reset = FALSE;
724 g_return_val_if_fail (converter != (GIConv) -1, NULL);
726 if (len < 0)
727 len = strlen (str);
729 p = str;
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)
738 if (reset)
739 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
740 else
741 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
743 if (err == (gsize) -1)
745 switch (errno)
747 case EINVAL:
748 /* Incomplete text, do not report an error */
749 done = TRUE;
750 break;
751 case E2BIG:
753 gsize used = outp - dest;
755 outbuf_size *= 2;
756 dest = g_realloc (dest, outbuf_size);
758 outp = dest + used;
759 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
761 break;
762 case EILSEQ:
763 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
764 _("Invalid byte sequence in conversion input"));
765 have_error = TRUE;
766 break;
767 default:
769 int errsv = errno;
771 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
772 _("Error during conversion: %s"),
773 g_strerror (errsv));
775 have_error = TRUE;
776 break;
779 else
781 if (!reset)
783 /* call g_iconv with NULL inbuf to cleanup shift state */
784 reset = TRUE;
785 inbytes_remaining = 0;
787 else
788 done = TRUE;
792 memset (outp, 0, NUL_TERMINATOR_LENGTH);
794 if (bytes_read)
795 *bytes_read = p - str;
796 else
798 if ((p - str) != len)
800 if (!have_error)
802 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
803 _("Partial character sequence at end of input"));
804 have_error = TRUE;
809 if (bytes_written)
810 *bytes_written = outp - dest; /* Doesn't include '\0' */
812 if (have_error)
814 g_free (dest);
815 return NULL;
817 else
818 return dest;
822 * g_convert:
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">
826 <para>
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.
830 </para>
831 </footnote>.
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
841 * input sequence.
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.
856 gchar*
857 g_convert (const gchar *str,
858 gssize len,
859 const gchar *to_codeset,
860 const gchar *from_codeset,
861 gsize *bytes_read,
862 gsize *bytes_written,
863 GError **error)
865 gchar *res;
866 GIConv cd;
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)
876 if (bytes_read)
877 *bytes_read = 0;
879 if (bytes_written)
880 *bytes_written = 0;
882 return NULL;
885 res = g_convert_with_iconv (str, len, cd,
886 bytes_read, bytes_written,
887 error);
889 close_converter (cd);
891 return res;
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.
931 gchar*
932 g_convert_with_fallback (const gchar *str,
933 gssize len,
934 const gchar *to_codeset,
935 const gchar *from_codeset,
936 const gchar *fallback,
937 gsize *bytes_read,
938 gsize *bytes_written,
939 GError **error)
941 gchar *utf8;
942 gchar *dest;
943 gchar *outp;
944 const gchar *insert_str = NULL;
945 const gchar *p;
946 gsize inbytes_remaining;
947 const gchar *save_p = NULL;
948 gsize save_inbytes = 0;
949 gsize outbytes_remaining;
950 gsize err;
951 GIConv cd;
952 gsize outbuf_size;
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);
962 if (len < 0)
963 len = strlen (str);
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);
970 if (!local_error)
971 return dest;
973 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
975 g_propagate_error (error, local_error);
976 return NULL;
978 else
979 g_error_free (local_error);
981 local_error = NULL;
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)
989 if (bytes_read)
990 *bytes_read = 0;
992 if (bytes_written)
993 *bytes_written = 0;
995 return NULL;
998 utf8 = g_convert (str, len, "UTF-8", from_codeset,
999 bytes_read, &inbytes_remaining, error);
1000 if (!utf8)
1002 close_converter (cd);
1003 if (bytes_written)
1004 *bytes_written = 0;
1005 return NULL;
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
1016 p = utf8;
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)
1030 switch (errno)
1032 case EINVAL:
1033 g_assert_not_reached();
1034 break;
1035 case E2BIG:
1037 gsize used = outp - dest;
1039 outbuf_size *= 2;
1040 dest = g_realloc (dest, outbuf_size);
1042 outp = dest + used;
1043 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1045 break;
1047 case EILSEQ:
1048 if (save_p)
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);
1055 have_error = TRUE;
1056 break;
1058 else if (p)
1060 if (!fallback)
1062 gunichar ch = g_utf8_get_char (p);
1063 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1064 ch);
1066 else
1067 insert_str = fallback;
1069 save_p = g_utf8_next_char (p);
1070 save_inbytes = inbytes_remaining - (save_p - p);
1071 p = insert_str;
1072 inbytes_remaining = strlen (p);
1073 break;
1075 /* fall thru if p is NULL */
1076 default:
1078 int errsv = errno;
1080 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1081 _("Error during conversion: %s"),
1082 g_strerror (errsv));
1085 have_error = TRUE;
1086 break;
1089 else
1091 if (save_p)
1093 if (!fallback)
1094 g_free ((gchar *)insert_str);
1095 p = save_p;
1096 inbytes_remaining = save_inbytes;
1097 save_p = NULL;
1099 else if (p)
1101 /* call g_iconv with NULL inbuf to cleanup shift state */
1102 p = NULL;
1103 inbytes_remaining = 0;
1105 else
1106 done = TRUE;
1110 /* Cleanup
1112 memset (outp, 0, NUL_TERMINATOR_LENGTH);
1114 close_converter (cd);
1116 if (bytes_written)
1117 *bytes_written = outp - dest; /* Doesn't include '\0' */
1119 g_free (utf8);
1121 if (have_error)
1123 if (save_p && !fallback)
1124 g_free ((gchar *)insert_str);
1125 g_free (dest);
1126 return NULL;
1128 else
1129 return dest;
1133 * g_locale_to_utf8
1138 static gchar *
1139 strdup_len (const gchar *string,
1140 gssize len,
1141 gsize *bytes_written,
1142 gsize *bytes_read,
1143 GError **error)
1146 gsize real_len;
1148 if (!g_utf8_validate (string, len, NULL))
1150 if (bytes_read)
1151 *bytes_read = 0;
1152 if (bytes_written)
1153 *bytes_written = 0;
1155 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1156 _("Invalid byte sequence in conversion input"));
1157 return NULL;
1160 if (len < 0)
1161 real_len = strlen (string);
1162 else
1164 real_len = 0;
1166 while (real_len < len && string[real_len])
1167 real_len++;
1170 if (bytes_read)
1171 *bytes_read = real_len;
1172 if (bytes_written)
1173 *bytes_written = real_len;
1175 return g_strndup (string, real_len);
1179 * g_locale_to_utf8:
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
1191 * input sequence.
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
1200 * UTF-8 string.
1202 * Return value: The converted string, or %NULL on an error.
1204 gchar *
1205 g_locale_to_utf8 (const gchar *opsysstring,
1206 gssize len,
1207 gsize *bytes_read,
1208 gsize *bytes_written,
1209 GError **error)
1211 const char *charset;
1213 if (g_get_charset (&charset))
1214 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1215 else
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
1232 * input sequence.
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.
1245 gchar *
1246 g_locale_from_utf8 (const gchar *utf8string,
1247 gssize len,
1248 gsize *bytes_read,
1249 gsize *bytes_written,
1250 GError **error)
1252 const gchar *charset;
1254 if (g_get_charset (&charset))
1255 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1256 else
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 {
1266 gboolean is_utf8;
1267 gchar *charset;
1268 gchar **filename_charsets;
1271 static void
1272 filename_charset_cache_free (gpointer data)
1274 GFilenameCharsetCache *cache = data;
1275 g_free (cache->charset);
1276 g_strfreev (cache->filename_charsets);
1277 g_free (cache);
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
1293 * have no effect.
1295 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1296 * of character set names. The special token "&commat;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.
1312 * Since: 2.6
1314 gboolean
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;
1321 if (!cache)
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;
1332 gchar *p;
1333 gint i;
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);
1361 else
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 */
1379 gboolean
1380 g_get_filename_charsets (const gchar ***filename_charsets)
1382 static const gchar *charsets[] = {
1383 "UTF-8",
1384 NULL
1387 #ifdef G_OS_WIN32
1388 /* On Windows GLib pretends that the filename charset is UTF-8 */
1389 if (filename_charsets)
1390 *filename_charsets = charsets;
1392 return TRUE;
1393 #else
1394 gboolean result;
1396 /* Cygwin works like before */
1397 result = g_get_charset (&(charsets[0]));
1399 if (filename_charsets)
1400 *filename_charsets = charsets;
1402 return result;
1403 #endif
1406 #endif /* G_PLATFORM_WIN32 */
1408 static gboolean
1409 get_filename_charset (const gchar **filename_charset)
1411 const gchar **charsets;
1412 gboolean is_utf8;
1414 is_utf8 = g_get_filename_charsets (&charsets);
1416 if (filename_charset)
1417 *filename_charset = charsets[0];
1419 return is_utf8;
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
1434 * input sequence.
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.
1447 gchar*
1448 g_filename_to_utf8 (const gchar *opsysstring,
1449 gssize len,
1450 gsize *bytes_read,
1451 gsize *bytes_written,
1452 GError **error)
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);
1460 else
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
1471 * the old versions.
1474 gchar*
1475 g_filename_to_utf8 (const gchar *opsysstring,
1476 gssize len,
1477 gsize *bytes_read,
1478 gsize *bytes_written,
1479 GError **error)
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);
1487 else
1488 return g_convert (opsysstring, len,
1489 "UTF-8", charset, bytes_read, bytes_written, error);
1492 #endif
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
1498 * nul-terminated.
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
1506 * input sequence.
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.
1519 gchar*
1520 g_filename_from_utf8 (const gchar *utf8string,
1521 gssize len,
1522 gsize *bytes_read,
1523 gsize *bytes_written,
1524 GError **error)
1526 const gchar *charset;
1528 if (get_filename_charset (&charset))
1529 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1530 else
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. */
1541 gchar*
1542 g_filename_from_utf8 (const gchar *utf8string,
1543 gssize len,
1544 gsize *bytes_read,
1545 gsize *bytes_written,
1546 GError **error)
1548 const gchar *charset;
1550 if (g_get_charset (&charset))
1551 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1552 else
1553 return g_convert (utf8string, len,
1554 charset, "UTF-8", bytes_read, bytes_written, error);
1557 #endif
1559 /* Test of haystack has the needle prefix, comparing case
1560 * insensitive. haystack may be UTF-8, but needle must
1561 * contain only ascii. */
1562 static gboolean
1563 has_case_prefix (const gchar *haystack, const gchar *needle)
1565 const gchar *h, *n;
1567 /* Eat one character at a time. */
1568 h = haystack;
1569 n = needle;
1571 while (*n && *h &&
1572 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1574 n++;
1575 h++;
1578 return *n == '\0';
1581 typedef enum {
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 */
1609 static gchar *
1610 g_escape_uri_string (const gchar *string,
1611 UnsafeCharacterSet mask)
1613 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1615 const gchar *p;
1616 gchar *q;
1617 gchar *result;
1618 int c;
1619 gint unacceptable;
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);
1628 unacceptable = 0;
1629 use_mask = mask;
1630 for (p = string; *p != '\0'; p++)
1632 c = (guchar) *p;
1633 if (!ACCEPTABLE (c))
1634 unacceptable++;
1637 result = g_malloc (p - string + unacceptable * 2 + 1);
1639 use_mask = mask;
1640 for (q = result, p = string; *p != '\0'; p++)
1642 c = (guchar) *p;
1644 if (!ACCEPTABLE (c))
1646 *q++ = '%'; /* means hex coming */
1647 *q++ = hex[c >> 4];
1648 *q++ = hex[c & 15];
1650 else
1651 *q++ = *p;
1654 *q = '\0';
1656 return result;
1660 static gchar *
1661 g_escape_file_uri (const gchar *hostname,
1662 const gchar *pathname)
1664 char *escaped_hostname = NULL;
1665 char *escaped_path;
1666 char *res;
1668 #ifdef G_OS_WIN32
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)
1680 *backslash = '/';
1681 p = backslash + 1;
1683 #endif
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 != '/') ? "/" : "",
1695 escaped_path,
1696 NULL);
1698 #ifdef G_OS_WIN32
1699 g_free ((char *) pathname);
1700 #endif
1702 g_free (escaped_hostname);
1703 g_free (escaped_path);
1705 return res;
1708 static int
1709 unescape_character (const char *scanner)
1711 int first_digit;
1712 int second_digit;
1714 first_digit = g_ascii_xdigit_value (scanner[0]);
1715 if (first_digit < 0)
1716 return -1;
1718 second_digit = g_ascii_xdigit_value (scanner[1]);
1719 if (second_digit < 0)
1720 return -1;
1722 return (first_digit << 4) | second_digit;
1725 static gchar *
1726 g_unescape_uri_string (const char *escaped,
1727 int len,
1728 const char *illegal_escaped_characters,
1729 gboolean ascii_must_not_be_escaped)
1731 const gchar *in, *in_end;
1732 gchar *out, *result;
1733 int c;
1735 if (escaped == NULL)
1736 return NULL;
1738 if (len < 0)
1739 len = strlen (escaped);
1741 result = g_malloc (len + 1);
1743 out = result;
1744 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1746 c = *in;
1748 if (c == '%')
1750 /* catch partial escape sequences past the end of the substring */
1751 if (in + 3 > in_end)
1752 break;
1754 c = unescape_character (in + 1);
1756 /* catch bad escape sequences and NUL characters */
1757 if (c <= 0)
1758 break;
1760 /* catch escaped ASCII */
1761 if (ascii_must_not_be_escaped && c <= 0x7F)
1762 break;
1764 /* catch other illegal escaped characters */
1765 if (strchr (illegal_escaped_characters, c) != NULL)
1766 break;
1768 in += 2;
1771 *out++ = c;
1774 g_assert (out - result <= len);
1775 *out = '\0';
1777 if (in != in_end)
1779 g_free (result);
1780 return NULL;
1783 return result;
1786 static gboolean
1787 is_asciialphanum (gunichar c)
1789 return c <= 0x7F && g_ascii_isalnum (c);
1792 static gboolean
1793 is_asciialpha (gunichar c)
1795 return c <= 0x7F && g_ascii_isalpha (c);
1798 /* allows an empty string */
1799 static gboolean
1800 hostname_validate (const char *hostname)
1802 const char *p;
1803 gunichar c, first_char, last_char;
1805 p = hostname;
1806 if (*p == '\0')
1807 return TRUE;
1810 /* read in a label */
1811 c = g_utf8_get_char (p);
1812 p = g_utf8_next_char (p);
1813 if (!is_asciialphanum (c))
1814 return FALSE;
1815 first_char = c;
1818 last_char = 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 == '-')
1824 return FALSE;
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);
1830 while (c == '.');
1831 return FALSE;
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.
1849 gchar *
1850 g_filename_from_uri (const gchar *uri,
1851 gchar **hostname,
1852 GError **error)
1854 const char *path_part;
1855 const char *host_part;
1856 char *unescaped_hostname;
1857 char *result;
1858 char *filename;
1859 int offs;
1860 #ifdef G_OS_WIN32
1861 char *p, *slash;
1862 #endif
1864 if (hostname)
1865 *hostname = NULL;
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"),
1871 uri);
1872 return NULL;
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 '#'"),
1881 uri);
1882 return NULL;
1885 if (has_case_prefix (path_part, "///"))
1886 path_part += 2;
1887 else if (has_case_prefix (path_part, "//"))
1889 path_part += 2;
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"),
1898 uri);
1899 return NULL;
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"),
1910 uri);
1911 return NULL;
1914 if (hostname)
1915 *hostname = unescaped_hostname;
1916 else
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"),
1926 uri);
1927 return NULL;
1930 offs = 0;
1931 #ifdef G_OS_WIN32
1932 /* Drop localhost */
1933 if (hostname && *hostname != NULL &&
1934 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1936 g_free (*hostname);
1937 *hostname = NULL;
1940 /* Turn slashes into backslashes, because that's the canonical spelling */
1941 p = filename;
1942 while ((slash = strchr (p, '/')) != NULL)
1944 *slash = '\\';
1945 p = slash + 1;
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] == ':')
1955 offs = 1;
1956 else if (filename[2] == '|')
1958 filename[2] = ':';
1959 offs = 1;
1962 #endif
1964 result = g_strdup (filename + offs);
1965 g_free (filename);
1967 return result;
1970 #if defined (G_OS_WIN32) && !defined (_WIN64)
1972 #undef g_filename_from_uri
1974 gchar *
1975 g_filename_from_uri (const gchar *uri,
1976 gchar **hostname,
1977 GError **error)
1979 gchar *utf8_filename;
1980 gchar *retval = NULL;
1982 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1983 if (utf8_filename)
1985 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1986 g_free (utf8_filename);
1988 return retval;
1991 #endif
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
1997 * Windows
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.
2008 gchar *
2009 g_filename_to_uri (const gchar *filename,
2010 const gchar *hostname,
2011 GError **error)
2013 char *escaped_uri;
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"),
2021 filename);
2022 return NULL;
2025 if (hostname &&
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"));
2031 return NULL;
2034 #ifdef G_OS_WIN32
2035 /* Don't use localhost unnecessarily */
2036 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2037 hostname = NULL;
2038 #endif
2040 escaped_uri = g_escape_file_uri (hostname, filename);
2042 return escaped_uri;
2045 #if defined (G_OS_WIN32) && !defined (_WIN64)
2047 #undef g_filename_to_uri
2049 gchar *
2050 g_filename_to_uri (const gchar *filename,
2051 const gchar *hostname,
2052 GError **error)
2054 gchar *utf8_filename;
2055 gchar *retval = NULL;
2057 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2059 if (utf8_filename)
2061 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2062 g_free (utf8_filename);
2065 return retval;
2068 #endif
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().
2082 * Since: 2.6
2084 gchar **
2085 g_uri_list_extract_uris (const gchar *uri_list)
2087 GSList *uris, *u;
2088 const gchar *p, *q;
2089 gchar **result;
2090 gint n_uris = 0;
2092 uris = NULL;
2094 p = 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.
2103 while (p)
2105 if (*p != '#')
2107 while (g_ascii_isspace (*p))
2108 p++;
2110 q = p;
2111 while (*q && (*q != '\n') && (*q != '\r'))
2112 q++;
2114 if (q > p)
2116 q--;
2117 while (q > p && g_ascii_isspace (*q))
2118 q--;
2120 if (q > p)
2122 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2123 n_uris++;
2127 p = strchr (p, '\n');
2128 if (p)
2129 p++;
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);
2140 return result;
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
2156 * encoding.
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
2167 * Since: 2.6
2169 gchar *
2170 g_filename_display_basename (const gchar *filename)
2172 char *basename;
2173 char *display_name;
2175 g_return_val_if_fail (filename != NULL, NULL);
2177 basename = g_path_get_basename (filename);
2178 display_name = g_filename_display_name (basename);
2179 g_free (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
2197 * encoding.
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
2206 * Since: 2.6
2208 gchar *
2209 g_filename_display_name (const gchar *filename)
2211 gint i;
2212 const gchar **charsets;
2213 gchar *display_name = NULL;
2214 gboolean is_utf8;
2216 is_utf8 = g_get_filename_charsets (&charsets);
2218 if (is_utf8)
2220 if (g_utf8_validate (filename, -1, NULL))
2221 display_name = g_strdup (filename);
2224 if (!display_name)
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],
2232 NULL, NULL, NULL);
2234 if (display_name)
2235 break;
2239 /* if all conversions failed, we replace invalid UTF-8
2240 * by a question mark
2242 if (!display_name)
2243 display_name = _g_utf8_make_valid (filename);
2245 return display_name;