Drop the GMenu markup functions
[glib.git] / glib / gconvert.c
blob517b7b4321eb9075ca34870f96227e263a9f9244
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 #error GNU libiconv not in use but included iconv.h is from libiconv
66 #endif
69 /**
70 * SECTION:conversions
71 * @title: Character Set Conversion
72 * @short_description: convert strings between different character sets
74 * The g_convert() family of function wraps the functionality of iconv(). In
75 * addition to pure character set conversions, GLib has functions to deal
76 * with the extra complications of encodings for file names.
78 * <refsect2 id="file-name-encodings">
79 * <title>File Name Encodings</title>
80 * <para>
81 * Historically, Unix has not had a defined encoding for file
82 * names: a file name is valid as long as it does not have path
83 * separators in it ("/"). However, displaying file names may
84 * require conversion: from the character set in which they were
85 * created, to the character set in which the application
86 * operates. Consider the Spanish file name
87 * "<filename>Presentaci&oacute;n.sxi</filename>". If the
88 * application which created it uses ISO-8859-1 for its encoding,
89 * </para>
90 * <programlisting id="filename-iso8859-1">
91 * Character: P r e s e n t a c i &oacute; n . s x i
92 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
93 * </programlisting>
94 * <para>
95 * However, if the application use UTF-8, the actual file name on
96 * disk would look like this:
97 * </para>
98 * <programlisting id="filename-utf-8">
99 * Character: P r e s e n t a c i &oacute; n . s x i
100 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
101 * </programlisting>
102 * <para>
103 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
104 * that use Glib do the same thing. If you get a file name from
105 * the file system, for example, from readdir(3) or from g_dir_read_name(),
106 * and you wish to display the file name to the user, you
107 * <emphasis>will</emphasis> need to convert it into UTF-8. The
108 * opposite case is when the user types the name of a file he
109 * wishes to save: the toolkit will give you that string in
110 * UTF-8 encoding, and you will need to convert it to the
111 * character set used for file names before you can create the
112 * file with open(2) or fopen(3).
113 * </para>
114 * <para>
115 * By default, Glib assumes that file names on disk are in UTF-8
116 * encoding. This is a valid assumption for file systems which
117 * were created relatively recently: most applications use UTF-8
118 * encoding for their strings, and that is also what they use for
119 * the file names they create. However, older file systems may
120 * still contain file names created in "older" encodings, such as
121 * ISO-8859-1. In this case, for compatibility reasons, you may
122 * want to instruct Glib to use that particular encoding for file
123 * names rather than UTF-8. You can do this by specifying the
124 * encoding for file names in the <link
125 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
126 * environment variable. For example, if your installation uses
127 * ISO-8859-1 for file names, you can put this in your
128 * <filename>~/.profile</filename>:
129 * </para>
130 * <programlisting>
131 * export G_FILENAME_ENCODING=ISO-8859-1
132 * </programlisting>
133 * <para>
134 * Glib provides the functions g_filename_to_utf8() and
135 * g_filename_from_utf8() to perform the necessary conversions. These
136 * functions convert file names from the encoding specified in
137 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
138 * <xref linkend="file-name-encodings-diagram"/> illustrates how
139 * these functions are used to convert between UTF-8 and the
140 * encoding for file names in the file system.
141 * </para>
142 * <figure id="file-name-encodings-diagram">
143 * <title>Conversion between File Name Encodings</title>
144 * <graphic fileref="file-name-encodings.png" format="PNG"/>
145 * </figure>
146 * <refsect3 id="file-name-encodings-checklist">
147 * <title>Checklist for Application Writers</title>
148 * <para>
149 * This section is a practical summary of the detailed
150 * description above. You can use this as a checklist of
151 * things to do to make sure your applications process file
152 * name encodings correctly.
153 * </para>
154 * <orderedlist>
155 * <listitem><para>
156 * If you get a file name from the file system from a function
157 * such as readdir(3) or gtk_file_chooser_get_filename(),
158 * you do not need to do any conversion to pass that
159 * file name to functions like open(2), rename(2), or
160 * fopen(3) &mdash; those are "raw" file names which the file
161 * system understands.
162 * </para></listitem>
163 * <listitem><para>
164 * If you need to display a file name, convert it to UTF-8 first by
165 * using g_filename_to_utf8(). If conversion fails, display a string like
166 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
167 * convert this string back into the encoding used for file names if you
168 * wish to pass it to the file system; use the original file name instead.
169 * For example, the document window of a word processor could display
170 * "Unknown file name" in its title bar but still let the user save the
171 * file, as it would keep the raw file name internally. This can happen
172 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
173 * environment variable even though he has files whose names are not
174 * encoded in UTF-8.
175 * </para></listitem>
176 * <listitem><para>
177 * If your user interface lets the user type a file name for saving or
178 * renaming, convert it to the encoding used for file names in the file
179 * system by using g_filename_from_utf8(). Pass the converted file name
180 * to functions like fopen(3). If conversion fails, ask the user to enter
181 * a different file name. This can happen if the user types Japanese
182 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
183 * <literal>ISO-8859-1</literal>, for example.
184 * </para></listitem>
185 * </orderedlist>
186 * </refsect3>
187 * </refsect2>
190 /* We try to terminate strings in unknown charsets with this many zero bytes
191 * to ensure that multibyte strings really are nul-terminated when we return
192 * them from g_convert() and friends.
194 #define NUL_TERMINATOR_LENGTH 4
196 GQuark
197 g_convert_error_quark (void)
199 return g_quark_from_static_string ("g_convert_error");
202 static gboolean
203 try_conversion (const char *to_codeset,
204 const char *from_codeset,
205 iconv_t *cd)
207 *cd = iconv_open (to_codeset, from_codeset);
209 if (*cd == (iconv_t)-1 && errno == EINVAL)
210 return FALSE;
211 else
212 return TRUE;
215 static gboolean
216 try_to_aliases (const char **to_aliases,
217 const char *from_codeset,
218 iconv_t *cd)
220 if (to_aliases)
222 const char **p = to_aliases;
223 while (*p)
225 if (try_conversion (*p, from_codeset, cd))
226 return TRUE;
228 p++;
232 return FALSE;
235 G_GNUC_INTERNAL extern const char **
236 _g_charset_get_aliases (const char *canonical_name);
239 * g_iconv_open:
240 * @to_codeset: destination codeset
241 * @from_codeset: source codeset
243 * Same as the standard UNIX routine iconv_open(), but
244 * may be implemented via libiconv on UNIX flavors that lack
245 * a native implementation.
247 * GLib provides g_convert() and g_locale_to_utf8() which are likely
248 * more convenient than the raw iconv wrappers.
250 * Return value: a "conversion descriptor", or (GIConv)-1 if
251 * opening the converter failed.
253 GIConv
254 g_iconv_open (const gchar *to_codeset,
255 const gchar *from_codeset)
257 iconv_t cd;
259 if (!try_conversion (to_codeset, from_codeset, &cd))
261 const char **to_aliases = _g_charset_get_aliases (to_codeset);
262 const char **from_aliases = _g_charset_get_aliases (from_codeset);
264 if (from_aliases)
266 const char **p = from_aliases;
267 while (*p)
269 if (try_conversion (to_codeset, *p, &cd))
270 goto out;
272 if (try_to_aliases (to_aliases, *p, &cd))
273 goto out;
275 p++;
279 if (try_to_aliases (to_aliases, from_codeset, &cd))
280 goto out;
283 out:
284 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
288 * g_iconv:
289 * @converter: conversion descriptor from g_iconv_open()
290 * @inbuf: bytes to convert
291 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
292 * @outbuf: converted output bytes
293 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
295 * Same as the standard UNIX routine iconv(), but
296 * may be implemented via libiconv on UNIX flavors that lack
297 * a native implementation.
299 * GLib provides g_convert() and g_locale_to_utf8() which are likely
300 * more convenient than the raw iconv wrappers.
302 * Return value: count of non-reversible conversions, or -1 on error
304 gsize
305 g_iconv (GIConv converter,
306 gchar **inbuf,
307 gsize *inbytes_left,
308 gchar **outbuf,
309 gsize *outbytes_left)
311 iconv_t cd = (iconv_t)converter;
313 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
317 * g_iconv_close:
318 * @converter: a conversion descriptor from g_iconv_open()
320 * Same as the standard UNIX routine iconv_close(), but
321 * may be implemented via libiconv on UNIX flavors that lack
322 * a native implementation. Should be called to clean up
323 * the conversion descriptor from g_iconv_open() when
324 * you are done converting things.
326 * GLib provides g_convert() and g_locale_to_utf8() which are likely
327 * more convenient than the raw iconv wrappers.
329 * Return value: -1 on error, 0 on success
331 gint
332 g_iconv_close (GIConv converter)
334 iconv_t cd = (iconv_t)converter;
336 return iconv_close (cd);
340 #ifdef NEED_ICONV_CACHE
342 #define ICONV_CACHE_SIZE (16)
344 struct _iconv_cache_bucket {
345 gchar *key;
346 guint32 refcount;
347 gboolean used;
348 GIConv cd;
351 static GList *iconv_cache_list;
352 static GHashTable *iconv_cache;
353 static GHashTable *iconv_open_hash;
354 static guint iconv_cache_size = 0;
355 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
357 /* caller *must* hold the iconv_cache_lock */
358 static void
359 iconv_cache_init (void)
361 static gboolean initialized = FALSE;
363 if (initialized)
364 return;
366 iconv_cache_list = NULL;
367 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
368 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
370 initialized = TRUE;
375 * iconv_cache_bucket_new:
376 * @key: cache key
377 * @cd: iconv descriptor
379 * Creates a new cache bucket, inserts it into the cache and
380 * increments the cache size.
382 * This assumes ownership of @key.
384 * Returns a pointer to the newly allocated cache bucket.
386 static struct _iconv_cache_bucket *
387 iconv_cache_bucket_new (gchar *key, GIConv cd)
389 struct _iconv_cache_bucket *bucket;
391 bucket = g_new (struct _iconv_cache_bucket, 1);
392 bucket->key = key;
393 bucket->refcount = 1;
394 bucket->used = TRUE;
395 bucket->cd = cd;
397 g_hash_table_insert (iconv_cache, bucket->key, bucket);
399 /* FIXME: if we sorted the list so items with few refcounts were
400 first, then we could expire them faster in iconv_cache_expire_unused () */
401 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
403 iconv_cache_size++;
405 return bucket;
410 * iconv_cache_bucket_expire:
411 * @node: cache bucket's node
412 * @bucket: cache bucket
414 * Expires a single cache bucket @bucket. This should only ever be
415 * called on a bucket that currently has no used iconv descriptors
416 * open.
418 * @node is not a required argument. If @node is not supplied, we
419 * search for it ourselves.
421 static void
422 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
424 g_hash_table_remove (iconv_cache, bucket->key);
426 if (node == NULL)
427 node = g_list_find (iconv_cache_list, bucket);
429 g_assert (node != NULL);
431 if (node->prev)
433 node->prev->next = node->next;
434 if (node->next)
435 node->next->prev = node->prev;
437 else
439 iconv_cache_list = node->next;
440 if (node->next)
441 node->next->prev = NULL;
444 g_list_free_1 (node);
446 g_free (bucket->key);
447 g_iconv_close (bucket->cd);
448 g_free (bucket);
450 iconv_cache_size--;
455 * iconv_cache_expire_unused:
457 * Expires as many unused cache buckets as it needs to in order to get
458 * the total number of buckets < ICONV_CACHE_SIZE.
460 static void
461 iconv_cache_expire_unused (void)
463 struct _iconv_cache_bucket *bucket;
464 GList *node, *next;
466 node = iconv_cache_list;
467 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
469 next = node->next;
471 bucket = node->data;
472 if (bucket->refcount == 0)
473 iconv_cache_bucket_expire (node, bucket);
475 node = next;
479 static GIConv
480 open_converter (const gchar *to_codeset,
481 const gchar *from_codeset,
482 GError **error)
484 struct _iconv_cache_bucket *bucket;
485 gchar *key, *dyn_key, auto_key[80];
486 GIConv cd;
487 gsize len_from_codeset, len_to_codeset;
489 /* create our key */
490 len_from_codeset = strlen (from_codeset);
491 len_to_codeset = strlen (to_codeset);
492 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
494 key = auto_key;
495 dyn_key = NULL;
497 else
498 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
499 memcpy (key, from_codeset, len_from_codeset);
500 key[len_from_codeset] = ':';
501 strcpy (key + len_from_codeset + 1, to_codeset);
503 G_LOCK (iconv_cache_lock);
505 /* make sure the cache has been initialized */
506 iconv_cache_init ();
508 bucket = g_hash_table_lookup (iconv_cache, key);
509 if (bucket)
511 g_free (dyn_key);
513 if (bucket->used)
515 cd = g_iconv_open (to_codeset, from_codeset);
516 if (cd == (GIConv) -1)
517 goto error;
519 else
521 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
522 * NULL for anything but inbuf; work around that. (NULL outbuf
523 * or NULL *outbuf is allowed by Unix98.)
525 gsize inbytes_left = 0;
526 gchar *outbuf = NULL;
527 gsize outbytes_left = 0;
529 cd = bucket->cd;
530 bucket->used = TRUE;
532 /* reset the descriptor */
533 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
536 bucket->refcount++;
538 else
540 cd = g_iconv_open (to_codeset, from_codeset);
541 if (cd == (GIConv) -1)
543 g_free (dyn_key);
544 goto error;
547 iconv_cache_expire_unused ();
549 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
552 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
554 G_UNLOCK (iconv_cache_lock);
556 return cd;
558 error:
560 G_UNLOCK (iconv_cache_lock);
562 /* Something went wrong. */
563 if (error)
565 if (errno == EINVAL)
566 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
567 _("Conversion from character set '%s' to '%s' is not supported"),
568 from_codeset, to_codeset);
569 else
570 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
571 _("Could not open converter from '%s' to '%s'"),
572 from_codeset, to_codeset);
575 return cd;
578 static int
579 close_converter (GIConv converter)
581 struct _iconv_cache_bucket *bucket;
582 const gchar *key;
583 GIConv cd;
585 cd = converter;
587 if (cd == (GIConv) -1)
588 return 0;
590 G_LOCK (iconv_cache_lock);
592 key = g_hash_table_lookup (iconv_open_hash, cd);
593 if (key)
595 g_hash_table_remove (iconv_open_hash, cd);
597 bucket = g_hash_table_lookup (iconv_cache, key);
598 g_assert (bucket);
600 bucket->refcount--;
602 if (cd == bucket->cd)
603 bucket->used = FALSE;
604 else
605 g_iconv_close (cd);
607 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
609 /* expire this cache bucket */
610 iconv_cache_bucket_expire (NULL, bucket);
613 else
615 G_UNLOCK (iconv_cache_lock);
617 g_warning ("This iconv context wasn't opened using open_converter");
619 return g_iconv_close (converter);
622 G_UNLOCK (iconv_cache_lock);
624 return 0;
627 #else /* !NEED_ICONV_CACHE */
629 static GIConv
630 open_converter (const gchar *to_codeset,
631 const gchar *from_codeset,
632 GError **error)
634 GIConv cd;
636 cd = g_iconv_open (to_codeset, from_codeset);
638 if (cd == (GIConv) -1)
640 /* Something went wrong. */
641 if (error)
643 if (errno == EINVAL)
644 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
645 _("Conversion from character set '%s' to '%s' is not supported"),
646 from_codeset, to_codeset);
647 else
648 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
649 _("Could not open converter from '%s' to '%s'"),
650 from_codeset, to_codeset);
654 return cd;
657 static int
658 close_converter (GIConv cd)
660 if (cd == (GIConv) -1)
661 return 0;
663 return g_iconv_close (cd);
666 #endif /* NEED_ICONV_CACHE */
669 * g_convert_with_iconv:
670 * @str: the string to convert
671 * @len: the length of the string, or -1 if the string is
672 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
673 * @converter: conversion descriptor from g_iconv_open()
674 * @bytes_read: location to store the number of bytes in the
675 * input string that were successfully converted, or %NULL.
676 * Even if the conversion was successful, this may be
677 * less than @len if there were partial characters
678 * at the end of the input. If the error
679 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
680 * stored will the byte offset after the last valid
681 * input sequence.
682 * @bytes_written: the number of bytes stored in the output buffer (not
683 * including the terminating nul).
684 * @error: location to store the error occurring, or %NULL to ignore
685 * errors. Any of the errors in #GConvertError may occur.
687 * Converts a string from one character set to another.
689 * Note that you should use g_iconv() for streaming
690 * conversions<footnote id="streaming-state">
691 * <para>
692 * Despite the fact that @byes_read can return information about partial
693 * characters, the <literal>g_convert_...</literal> functions
694 * are not generally suitable for streaming. If the underlying converter
695 * being used maintains internal state, then this won't be preserved
696 * across successive calls to g_convert(), g_convert_with_iconv() or
697 * g_convert_with_fallback(). (An example of this is the GNU C converter
698 * for CP1255 which does not emit a base character until it knows that
699 * the next character is not a mark that could combine with the base
700 * character.)
701 * </para>
702 * </footnote>.
704 * Return value: If the conversion was successful, a newly allocated
705 * nul-terminated string, which must be freed with
706 * g_free(). Otherwise %NULL and @error will be set.
708 gchar*
709 g_convert_with_iconv (const gchar *str,
710 gssize len,
711 GIConv converter,
712 gsize *bytes_read,
713 gsize *bytes_written,
714 GError **error)
716 gchar *dest;
717 gchar *outp;
718 const gchar *p;
719 gsize inbytes_remaining;
720 gsize outbytes_remaining;
721 gsize err;
722 gsize outbuf_size;
723 gboolean have_error = FALSE;
724 gboolean done = FALSE;
725 gboolean reset = FALSE;
727 g_return_val_if_fail (converter != (GIConv) -1, NULL);
729 if (len < 0)
730 len = strlen (str);
732 p = str;
733 inbytes_remaining = len;
734 outbuf_size = len + NUL_TERMINATOR_LENGTH;
736 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
737 outp = dest = g_malloc (outbuf_size);
739 while (!done && !have_error)
741 if (reset)
742 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
743 else
744 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
746 if (err == (gsize) -1)
748 switch (errno)
750 case EINVAL:
751 /* Incomplete text, do not report an error */
752 done = TRUE;
753 break;
754 case E2BIG:
756 gsize used = outp - dest;
758 outbuf_size *= 2;
759 dest = g_realloc (dest, outbuf_size);
761 outp = dest + used;
762 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
764 break;
765 case EILSEQ:
766 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
767 _("Invalid byte sequence in conversion input"));
768 have_error = TRUE;
769 break;
770 default:
772 int errsv = errno;
774 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
775 _("Error during conversion: %s"),
776 g_strerror (errsv));
778 have_error = TRUE;
779 break;
782 else
784 if (!reset)
786 /* call g_iconv with NULL inbuf to cleanup shift state */
787 reset = TRUE;
788 inbytes_remaining = 0;
790 else
791 done = TRUE;
795 memset (outp, 0, NUL_TERMINATOR_LENGTH);
797 if (bytes_read)
798 *bytes_read = p - str;
799 else
801 if ((p - str) != len)
803 if (!have_error)
805 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
806 _("Partial character sequence at end of input"));
807 have_error = TRUE;
812 if (bytes_written)
813 *bytes_written = outp - dest; /* Doesn't include '\0' */
815 if (have_error)
817 g_free (dest);
818 return NULL;
820 else
821 return dest;
825 * g_convert:
826 * @str: the string to convert
827 * @len: the length of the string, or -1 if the string is
828 * nul-terminated<footnote id="nul-unsafe">
829 <para>
830 Note that some encodings may allow nul bytes to
831 occur inside strings. In that case, using -1 for
832 the @len parameter is unsafe.
833 </para>
834 </footnote>.
835 * @to_codeset: name of character set into which to convert @str
836 * @from_codeset: character set of @str.
837 * @bytes_read: (out): location to store the number of bytes in the
838 * input string that were successfully converted, or %NULL.
839 * Even if the conversion was successful, this may be
840 * less than @len if there were partial characters
841 * at the end of the input. If the error
842 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
843 * stored will the byte offset after the last valid
844 * input sequence.
845 * @bytes_written: (out): the number of bytes stored in the output buffer (not
846 * including the terminating nul).
847 * @error: location to store the error occurring, or %NULL to ignore
848 * errors. Any of the errors in #GConvertError may occur.
850 * Converts a string from one character set to another.
852 * Note that you should use g_iconv() for streaming
853 * conversions<footnoteref linkend="streaming-state"/>.
855 * Return value: If the conversion was successful, a newly allocated
856 * nul-terminated string, which must be freed with
857 * g_free(). Otherwise %NULL and @error will be set.
859 gchar*
860 g_convert (const gchar *str,
861 gssize len,
862 const gchar *to_codeset,
863 const gchar *from_codeset,
864 gsize *bytes_read,
865 gsize *bytes_written,
866 GError **error)
868 gchar *res;
869 GIConv cd;
871 g_return_val_if_fail (str != NULL, NULL);
872 g_return_val_if_fail (to_codeset != NULL, NULL);
873 g_return_val_if_fail (from_codeset != NULL, NULL);
875 cd = open_converter (to_codeset, from_codeset, error);
877 if (cd == (GIConv) -1)
879 if (bytes_read)
880 *bytes_read = 0;
882 if (bytes_written)
883 *bytes_written = 0;
885 return NULL;
888 res = g_convert_with_iconv (str, len, cd,
889 bytes_read, bytes_written,
890 error);
892 close_converter (cd);
894 return res;
898 * g_convert_with_fallback:
899 * @str: the string to convert
900 * @len: the length of the string, or -1 if the string is
901 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
902 * @to_codeset: name of character set into which to convert @str
903 * @from_codeset: character set of @str.
904 * @fallback: UTF-8 string to use in place of character not
905 * present in the target encoding. (The string must be
906 * representable in the target encoding).
907 If %NULL, characters not in the target encoding will
908 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
909 * @bytes_read: location to store the number of bytes in the
910 * input string that were successfully converted, or %NULL.
911 * Even if the conversion was successful, this may be
912 * less than @len if there were partial characters
913 * at the end of the input.
914 * @bytes_written: the number of bytes stored in the output buffer (not
915 * including the terminating nul).
916 * @error: location to store the error occurring, or %NULL to ignore
917 * errors. Any of the errors in #GConvertError may occur.
919 * Converts a string from one character set to another, possibly
920 * including fallback sequences for characters not representable
921 * in the output. Note that it is not guaranteed that the specification
922 * for the fallback sequences in @fallback will be honored. Some
923 * systems may do an approximate conversion from @from_codeset
924 * to @to_codeset in their iconv() functions,
925 * in which case GLib will simply return that approximate conversion.
927 * Note that you should use g_iconv() for streaming
928 * conversions<footnoteref linkend="streaming-state"/>.
930 * Return value: If the conversion was successful, a newly allocated
931 * nul-terminated string, which must be freed with
932 * g_free(). Otherwise %NULL and @error will be set.
934 gchar*
935 g_convert_with_fallback (const gchar *str,
936 gssize len,
937 const gchar *to_codeset,
938 const gchar *from_codeset,
939 const gchar *fallback,
940 gsize *bytes_read,
941 gsize *bytes_written,
942 GError **error)
944 gchar *utf8;
945 gchar *dest;
946 gchar *outp;
947 const gchar *insert_str = NULL;
948 const gchar *p;
949 gsize inbytes_remaining;
950 const gchar *save_p = NULL;
951 gsize save_inbytes = 0;
952 gsize outbytes_remaining;
953 gsize err;
954 GIConv cd;
955 gsize outbuf_size;
956 gboolean have_error = FALSE;
957 gboolean done = FALSE;
959 GError *local_error = NULL;
961 g_return_val_if_fail (str != NULL, NULL);
962 g_return_val_if_fail (to_codeset != NULL, NULL);
963 g_return_val_if_fail (from_codeset != NULL, NULL);
965 if (len < 0)
966 len = strlen (str);
968 /* Try an exact conversion; we only proceed if this fails
969 * due to an illegal sequence in the input string.
971 dest = g_convert (str, len, to_codeset, from_codeset,
972 bytes_read, bytes_written, &local_error);
973 if (!local_error)
974 return dest;
976 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
978 g_propagate_error (error, local_error);
979 return NULL;
981 else
982 g_error_free (local_error);
984 local_error = NULL;
986 /* No go; to proceed, we need a converter from "UTF-8" to
987 * to_codeset, and the string as UTF-8.
989 cd = open_converter (to_codeset, "UTF-8", error);
990 if (cd == (GIConv) -1)
992 if (bytes_read)
993 *bytes_read = 0;
995 if (bytes_written)
996 *bytes_written = 0;
998 return NULL;
1001 utf8 = g_convert (str, len, "UTF-8", from_codeset,
1002 bytes_read, &inbytes_remaining, error);
1003 if (!utf8)
1005 close_converter (cd);
1006 if (bytes_written)
1007 *bytes_written = 0;
1008 return NULL;
1011 /* Now the heart of the code. We loop through the UTF-8 string, and
1012 * whenever we hit an offending character, we form fallback, convert
1013 * the fallback to the target codeset, and then go back to
1014 * converting the original string after finishing with the fallback.
1016 * The variables save_p and save_inbytes store the input state
1017 * for the original string while we are converting the fallback
1019 p = utf8;
1021 outbuf_size = len + NUL_TERMINATOR_LENGTH;
1022 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1023 outp = dest = g_malloc (outbuf_size);
1025 while (!done && !have_error)
1027 gsize inbytes_tmp = inbytes_remaining;
1028 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1029 inbytes_remaining = inbytes_tmp;
1031 if (err == (gsize) -1)
1033 switch (errno)
1035 case EINVAL:
1036 g_assert_not_reached();
1037 break;
1038 case E2BIG:
1040 gsize used = outp - dest;
1042 outbuf_size *= 2;
1043 dest = g_realloc (dest, outbuf_size);
1045 outp = dest + used;
1046 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1048 break;
1050 case EILSEQ:
1051 if (save_p)
1053 /* Error converting fallback string - fatal
1055 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1056 _("Cannot convert fallback '%s' to codeset '%s'"),
1057 insert_str, to_codeset);
1058 have_error = TRUE;
1059 break;
1061 else if (p)
1063 if (!fallback)
1065 gunichar ch = g_utf8_get_char (p);
1066 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1067 ch);
1069 else
1070 insert_str = fallback;
1072 save_p = g_utf8_next_char (p);
1073 save_inbytes = inbytes_remaining - (save_p - p);
1074 p = insert_str;
1075 inbytes_remaining = strlen (p);
1076 break;
1078 /* fall thru if p is NULL */
1079 default:
1081 int errsv = errno;
1083 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1084 _("Error during conversion: %s"),
1085 g_strerror (errsv));
1088 have_error = TRUE;
1089 break;
1092 else
1094 if (save_p)
1096 if (!fallback)
1097 g_free ((gchar *)insert_str);
1098 p = save_p;
1099 inbytes_remaining = save_inbytes;
1100 save_p = NULL;
1102 else if (p)
1104 /* call g_iconv with NULL inbuf to cleanup shift state */
1105 p = NULL;
1106 inbytes_remaining = 0;
1108 else
1109 done = TRUE;
1113 /* Cleanup
1115 memset (outp, 0, NUL_TERMINATOR_LENGTH);
1117 close_converter (cd);
1119 if (bytes_written)
1120 *bytes_written = outp - dest; /* Doesn't include '\0' */
1122 g_free (utf8);
1124 if (have_error)
1126 if (save_p && !fallback)
1127 g_free ((gchar *)insert_str);
1128 g_free (dest);
1129 return NULL;
1131 else
1132 return dest;
1136 * g_locale_to_utf8
1141 static gchar *
1142 strdup_len (const gchar *string,
1143 gssize len,
1144 gsize *bytes_written,
1145 gsize *bytes_read,
1146 GError **error)
1149 gsize real_len;
1151 if (!g_utf8_validate (string, len, NULL))
1153 if (bytes_read)
1154 *bytes_read = 0;
1155 if (bytes_written)
1156 *bytes_written = 0;
1158 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1159 _("Invalid byte sequence in conversion input"));
1160 return NULL;
1163 if (len < 0)
1164 real_len = strlen (string);
1165 else
1167 real_len = 0;
1169 while (real_len < len && string[real_len])
1170 real_len++;
1173 if (bytes_read)
1174 *bytes_read = real_len;
1175 if (bytes_written)
1176 *bytes_written = real_len;
1178 return g_strndup (string, real_len);
1182 * g_locale_to_utf8:
1183 * @opsysstring: a string in the encoding of the current locale. On Windows
1184 * this means the system codepage.
1185 * @len: the length of the string, or -1 if the string is
1186 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1187 * @bytes_read: location to store the number of bytes in the
1188 * input string that were successfully converted, or %NULL.
1189 * Even if the conversion was successful, this may be
1190 * less than @len if there were partial characters
1191 * at the end of the input. If the error
1192 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1193 * stored will the byte offset after the last valid
1194 * input sequence.
1195 * @bytes_written: the number of bytes stored in the output buffer (not
1196 * including the terminating nul).
1197 * @error: location to store the error occurring, or %NULL to ignore
1198 * errors. Any of the errors in #GConvertError may occur.
1200 * Converts a string which is in the encoding used for strings by
1201 * the C runtime (usually the same as that used by the operating
1202 * system) in the <link linkend="setlocale">current locale</link> into a
1203 * UTF-8 string.
1205 * Return value: The converted string, or %NULL on an error.
1207 gchar *
1208 g_locale_to_utf8 (const gchar *opsysstring,
1209 gssize len,
1210 gsize *bytes_read,
1211 gsize *bytes_written,
1212 GError **error)
1214 const char *charset;
1216 if (g_get_charset (&charset))
1217 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1218 else
1219 return g_convert (opsysstring, len,
1220 "UTF-8", charset, bytes_read, bytes_written, error);
1224 * g_locale_from_utf8:
1225 * @utf8string: a UTF-8 encoded string
1226 * @len: the length of the string, or -1 if the string is
1227 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1228 * @bytes_read: location to store the number of bytes in the
1229 * input string that were successfully converted, or %NULL.
1230 * Even if the conversion was successful, this may be
1231 * less than @len if there were partial characters
1232 * at the end of the input. If the error
1233 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1234 * stored will the byte offset after the last valid
1235 * input sequence.
1236 * @bytes_written: the number of bytes stored in the output buffer (not
1237 * including the terminating nul).
1238 * @error: location to store the error occurring, or %NULL to ignore
1239 * errors. Any of the errors in #GConvertError may occur.
1241 * Converts a string from UTF-8 to the encoding used for strings by
1242 * the C runtime (usually the same as that used by the operating
1243 * system) in the <link linkend="setlocale">current locale</link>. On
1244 * Windows this means the system codepage.
1246 * Return value: The converted string, or %NULL on an error.
1248 gchar *
1249 g_locale_from_utf8 (const gchar *utf8string,
1250 gssize len,
1251 gsize *bytes_read,
1252 gsize *bytes_written,
1253 GError **error)
1255 const gchar *charset;
1257 if (g_get_charset (&charset))
1258 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1259 else
1260 return g_convert (utf8string, len,
1261 charset, "UTF-8", bytes_read, bytes_written, error);
1264 #ifndef G_PLATFORM_WIN32
1266 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1268 struct _GFilenameCharsetCache {
1269 gboolean is_utf8;
1270 gchar *charset;
1271 gchar **filename_charsets;
1274 static void
1275 filename_charset_cache_free (gpointer data)
1277 GFilenameCharsetCache *cache = data;
1278 g_free (cache->charset);
1279 g_strfreev (cache->filename_charsets);
1280 g_free (cache);
1284 * g_get_filename_charsets:
1285 * @charsets: return location for the %NULL-terminated list of encoding names
1287 * Determines the preferred character sets used for filenames.
1288 * The first character set from the @charsets is the filename encoding, the
1289 * subsequent character sets are used when trying to generate a displayable
1290 * representation of a filename, see g_filename_display_name().
1292 * On Unix, the character sets are determined by consulting the
1293 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1294 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1295 * used in the GLib API is always UTF-8 and said environment variables
1296 * have no effect.
1298 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1299 * of character set names. The special token "&commat;locale" is taken to
1300 * mean the character set for the <link linkend="setlocale">current
1301 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1302 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1303 * locale is taken as the filename encoding. If neither environment variable
1304 * is set, UTF-8 is taken as the filename encoding, but the character
1305 * set of the current locale is also put in the list of encodings.
1307 * The returned @charsets belong to GLib and must not be freed.
1309 * Note that on Unix, regardless of the locale character set or
1310 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1311 * on a system might be in any random encoding or just gibberish.
1313 * Return value: %TRUE if the filename encoding is UTF-8.
1315 * Since: 2.6
1317 gboolean
1318 g_get_filename_charsets (const gchar ***filename_charsets)
1320 static GPrivate cache_private = G_PRIVATE_INIT (filename_charset_cache_free);
1321 GFilenameCharsetCache *cache = g_private_get (&cache_private);
1322 const gchar *charset;
1324 if (!cache)
1326 cache = g_new0 (GFilenameCharsetCache, 1);
1327 g_private_set (&cache_private, cache);
1330 g_get_charset (&charset);
1332 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1334 const gchar *new_charset;
1335 gchar *p;
1336 gint i;
1338 g_free (cache->charset);
1339 g_strfreev (cache->filename_charsets);
1340 cache->charset = g_strdup (charset);
1342 p = getenv ("G_FILENAME_ENCODING");
1343 if (p != NULL && p[0] != '\0')
1345 cache->filename_charsets = g_strsplit (p, ",", 0);
1346 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1348 for (i = 0; cache->filename_charsets[i]; i++)
1350 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1352 g_get_charset (&new_charset);
1353 g_free (cache->filename_charsets[i]);
1354 cache->filename_charsets[i] = g_strdup (new_charset);
1358 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1360 cache->filename_charsets = g_new0 (gchar *, 2);
1361 cache->is_utf8 = g_get_charset (&new_charset);
1362 cache->filename_charsets[0] = g_strdup (new_charset);
1364 else
1366 cache->filename_charsets = g_new0 (gchar *, 3);
1367 cache->is_utf8 = TRUE;
1368 cache->filename_charsets[0] = g_strdup ("UTF-8");
1369 if (!g_get_charset (&new_charset))
1370 cache->filename_charsets[1] = g_strdup (new_charset);
1374 if (filename_charsets)
1375 *filename_charsets = (const gchar **)cache->filename_charsets;
1377 return cache->is_utf8;
1380 #else /* G_PLATFORM_WIN32 */
1382 gboolean
1383 g_get_filename_charsets (const gchar ***filename_charsets)
1385 static const gchar *charsets[] = {
1386 "UTF-8",
1387 NULL
1390 #ifdef G_OS_WIN32
1391 /* On Windows GLib pretends that the filename charset is UTF-8 */
1392 if (filename_charsets)
1393 *filename_charsets = charsets;
1395 return TRUE;
1396 #else
1397 gboolean result;
1399 /* Cygwin works like before */
1400 result = g_get_charset (&(charsets[0]));
1402 if (filename_charsets)
1403 *filename_charsets = charsets;
1405 return result;
1406 #endif
1409 #endif /* G_PLATFORM_WIN32 */
1411 static gboolean
1412 get_filename_charset (const gchar **filename_charset)
1414 const gchar **charsets;
1415 gboolean is_utf8;
1417 is_utf8 = g_get_filename_charsets (&charsets);
1419 if (filename_charset)
1420 *filename_charset = charsets[0];
1422 return is_utf8;
1426 * g_filename_to_utf8:
1427 * @opsysstring: a string in the encoding for filenames
1428 * @len: the length of the string, or -1 if the string is
1429 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1430 * @bytes_read: location to store the number of bytes in the
1431 * input string that were successfully converted, or %NULL.
1432 * Even if the conversion was successful, this may be
1433 * less than @len if there were partial characters
1434 * at the end of the input. If the error
1435 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1436 * stored will the byte offset after the last valid
1437 * input sequence.
1438 * @bytes_written: the number of bytes stored in the output buffer (not
1439 * including the terminating nul).
1440 * @error: location to store the error occurring, or %NULL to ignore
1441 * errors. Any of the errors in #GConvertError may occur.
1443 * Converts a string which is in the encoding used by GLib for
1444 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1445 * for filenames; on other platforms, this function indirectly depends on
1446 * the <link linkend="setlocale">current locale</link>.
1448 * Return value: The converted string, or %NULL on an error.
1450 gchar*
1451 g_filename_to_utf8 (const gchar *opsysstring,
1452 gssize len,
1453 gsize *bytes_read,
1454 gsize *bytes_written,
1455 GError **error)
1457 const gchar *charset;
1459 g_return_val_if_fail (opsysstring != NULL, NULL);
1461 if (get_filename_charset (&charset))
1462 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1463 else
1464 return g_convert (opsysstring, len,
1465 "UTF-8", charset, bytes_read, bytes_written, error);
1468 #if defined (G_OS_WIN32) && !defined (_WIN64)
1470 #undef g_filename_to_utf8
1472 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1473 * 64-bit versions as there should be no old deployed binaries that would use
1474 * the old versions.
1477 gchar*
1478 g_filename_to_utf8 (const gchar *opsysstring,
1479 gssize len,
1480 gsize *bytes_read,
1481 gsize *bytes_written,
1482 GError **error)
1484 const gchar *charset;
1486 g_return_val_if_fail (opsysstring != NULL, NULL);
1488 if (g_get_charset (&charset))
1489 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1490 else
1491 return g_convert (opsysstring, len,
1492 "UTF-8", charset, bytes_read, bytes_written, error);
1495 #endif
1498 * g_filename_from_utf8:
1499 * @utf8string: a UTF-8 encoded string.
1500 * @len: the length of the string, or -1 if the string is
1501 * nul-terminated.
1502 * @bytes_read: location to store the number of bytes in the
1503 * input string that were successfully converted, or %NULL.
1504 * Even if the conversion was successful, this may be
1505 * less than @len if there were partial characters
1506 * at the end of the input. If the error
1507 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1508 * stored will the byte offset after the last valid
1509 * input sequence.
1510 * @bytes_written: the number of bytes stored in the output buffer (not
1511 * including the terminating nul).
1512 * @error: location to store the error occurring, or %NULL to ignore
1513 * errors. Any of the errors in #GConvertError may occur.
1515 * Converts a string from UTF-8 to the encoding GLib uses for
1516 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1517 * on other platforms, this function indirectly depends on the
1518 * <link linkend="setlocale">current locale</link>.
1520 * Return value: The converted string, or %NULL on an error.
1522 gchar*
1523 g_filename_from_utf8 (const gchar *utf8string,
1524 gssize len,
1525 gsize *bytes_read,
1526 gsize *bytes_written,
1527 GError **error)
1529 const gchar *charset;
1531 if (get_filename_charset (&charset))
1532 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1533 else
1534 return g_convert (utf8string, len,
1535 charset, "UTF-8", bytes_read, bytes_written, error);
1538 #if defined (G_OS_WIN32) && !defined (_WIN64)
1540 #undef g_filename_from_utf8
1542 /* Binary compatibility version. Not for newly compiled code. */
1544 gchar*
1545 g_filename_from_utf8 (const gchar *utf8string,
1546 gssize len,
1547 gsize *bytes_read,
1548 gsize *bytes_written,
1549 GError **error)
1551 const gchar *charset;
1553 if (g_get_charset (&charset))
1554 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1555 else
1556 return g_convert (utf8string, len,
1557 charset, "UTF-8", bytes_read, bytes_written, error);
1560 #endif
1562 /* Test of haystack has the needle prefix, comparing case
1563 * insensitive. haystack may be UTF-8, but needle must
1564 * contain only ascii. */
1565 static gboolean
1566 has_case_prefix (const gchar *haystack, const gchar *needle)
1568 const gchar *h, *n;
1570 /* Eat one character at a time. */
1571 h = haystack;
1572 n = needle;
1574 while (*n && *h &&
1575 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1577 n++;
1578 h++;
1581 return *n == '\0';
1584 typedef enum {
1585 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1586 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1587 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1588 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1589 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1590 } UnsafeCharacterSet;
1592 static const guchar acceptable[96] = {
1593 /* A table of the ASCII chars from space (32) to DEL (127) */
1594 /* ! " # $ % & ' ( ) * + , - . / */
1595 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1596 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1597 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1598 /* @ A B C D E F G H I J K L M N O */
1599 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1600 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1601 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1602 /* ` a b c d e f g h i j k l m n o */
1603 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1604 /* p q r s t u v w x y z { | } ~ DEL */
1605 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1608 static const gchar hex[16] = "0123456789ABCDEF";
1610 /* Note: This escape function works on file: URIs, but if you want to
1611 * escape something else, please read RFC-2396 */
1612 static gchar *
1613 g_escape_uri_string (const gchar *string,
1614 UnsafeCharacterSet mask)
1616 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1618 const gchar *p;
1619 gchar *q;
1620 gchar *result;
1621 int c;
1622 gint unacceptable;
1623 UnsafeCharacterSet use_mask;
1625 g_return_val_if_fail (mask == UNSAFE_ALL
1626 || mask == UNSAFE_ALLOW_PLUS
1627 || mask == UNSAFE_PATH
1628 || mask == UNSAFE_HOST
1629 || mask == UNSAFE_SLASHES, NULL);
1631 unacceptable = 0;
1632 use_mask = mask;
1633 for (p = string; *p != '\0'; p++)
1635 c = (guchar) *p;
1636 if (!ACCEPTABLE (c))
1637 unacceptable++;
1640 result = g_malloc (p - string + unacceptable * 2 + 1);
1642 use_mask = mask;
1643 for (q = result, p = string; *p != '\0'; p++)
1645 c = (guchar) *p;
1647 if (!ACCEPTABLE (c))
1649 *q++ = '%'; /* means hex coming */
1650 *q++ = hex[c >> 4];
1651 *q++ = hex[c & 15];
1653 else
1654 *q++ = *p;
1657 *q = '\0';
1659 return result;
1663 static gchar *
1664 g_escape_file_uri (const gchar *hostname,
1665 const gchar *pathname)
1667 char *escaped_hostname = NULL;
1668 char *escaped_path;
1669 char *res;
1671 #ifdef G_OS_WIN32
1672 char *p, *backslash;
1674 /* Turn backslashes into forward slashes. That's what Netscape
1675 * does, and they are actually more or less equivalent in Windows.
1678 pathname = g_strdup (pathname);
1679 p = (char *) pathname;
1681 while ((backslash = strchr (p, '\\')) != NULL)
1683 *backslash = '/';
1684 p = backslash + 1;
1686 #endif
1688 if (hostname && *hostname != '\0')
1690 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1693 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1695 res = g_strconcat ("file://",
1696 (escaped_hostname) ? escaped_hostname : "",
1697 (*escaped_path != '/') ? "/" : "",
1698 escaped_path,
1699 NULL);
1701 #ifdef G_OS_WIN32
1702 g_free ((char *) pathname);
1703 #endif
1705 g_free (escaped_hostname);
1706 g_free (escaped_path);
1708 return res;
1711 static int
1712 unescape_character (const char *scanner)
1714 int first_digit;
1715 int second_digit;
1717 first_digit = g_ascii_xdigit_value (scanner[0]);
1718 if (first_digit < 0)
1719 return -1;
1721 second_digit = g_ascii_xdigit_value (scanner[1]);
1722 if (second_digit < 0)
1723 return -1;
1725 return (first_digit << 4) | second_digit;
1728 static gchar *
1729 g_unescape_uri_string (const char *escaped,
1730 int len,
1731 const char *illegal_escaped_characters,
1732 gboolean ascii_must_not_be_escaped)
1734 const gchar *in, *in_end;
1735 gchar *out, *result;
1736 int c;
1738 if (escaped == NULL)
1739 return NULL;
1741 if (len < 0)
1742 len = strlen (escaped);
1744 result = g_malloc (len + 1);
1746 out = result;
1747 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1749 c = *in;
1751 if (c == '%')
1753 /* catch partial escape sequences past the end of the substring */
1754 if (in + 3 > in_end)
1755 break;
1757 c = unescape_character (in + 1);
1759 /* catch bad escape sequences and NUL characters */
1760 if (c <= 0)
1761 break;
1763 /* catch escaped ASCII */
1764 if (ascii_must_not_be_escaped && c <= 0x7F)
1765 break;
1767 /* catch other illegal escaped characters */
1768 if (strchr (illegal_escaped_characters, c) != NULL)
1769 break;
1771 in += 2;
1774 *out++ = c;
1777 g_assert (out - result <= len);
1778 *out = '\0';
1780 if (in != in_end)
1782 g_free (result);
1783 return NULL;
1786 return result;
1789 static gboolean
1790 is_asciialphanum (gunichar c)
1792 return c <= 0x7F && g_ascii_isalnum (c);
1795 static gboolean
1796 is_asciialpha (gunichar c)
1798 return c <= 0x7F && g_ascii_isalpha (c);
1801 /* allows an empty string */
1802 static gboolean
1803 hostname_validate (const char *hostname)
1805 const char *p;
1806 gunichar c, first_char, last_char;
1808 p = hostname;
1809 if (*p == '\0')
1810 return TRUE;
1813 /* read in a label */
1814 c = g_utf8_get_char (p);
1815 p = g_utf8_next_char (p);
1816 if (!is_asciialphanum (c))
1817 return FALSE;
1818 first_char = c;
1821 last_char = c;
1822 c = g_utf8_get_char (p);
1823 p = g_utf8_next_char (p);
1825 while (is_asciialphanum (c) || c == '-');
1826 if (last_char == '-')
1827 return FALSE;
1829 /* if that was the last label, check that it was a toplabel */
1830 if (c == '\0' || (c == '.' && *p == '\0'))
1831 return is_asciialpha (first_char);
1833 while (c == '.');
1834 return FALSE;
1838 * g_filename_from_uri:
1839 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1840 * @hostname: Location to store hostname for the URI, or %NULL.
1841 * If there is no hostname in the URI, %NULL will be
1842 * stored in this location.
1843 * @error: location to store the error occurring, or %NULL to ignore
1844 * errors. Any of the errors in #GConvertError may occur.
1846 * Converts an escaped ASCII-encoded URI to a local filename in the
1847 * encoding used for filenames.
1849 * Return value: a newly-allocated string holding the resulting
1850 * filename, or %NULL on an error.
1852 gchar *
1853 g_filename_from_uri (const gchar *uri,
1854 gchar **hostname,
1855 GError **error)
1857 const char *path_part;
1858 const char *host_part;
1859 char *unescaped_hostname;
1860 char *result;
1861 char *filename;
1862 int offs;
1863 #ifdef G_OS_WIN32
1864 char *p, *slash;
1865 #endif
1867 if (hostname)
1868 *hostname = NULL;
1870 if (!has_case_prefix (uri, "file:/"))
1872 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1873 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1874 uri);
1875 return NULL;
1878 path_part = uri + strlen ("file:");
1880 if (strchr (path_part, '#') != NULL)
1882 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1883 _("The local file URI '%s' may not include a '#'"),
1884 uri);
1885 return NULL;
1888 if (has_case_prefix (path_part, "///"))
1889 path_part += 2;
1890 else if (has_case_prefix (path_part, "//"))
1892 path_part += 2;
1893 host_part = path_part;
1895 path_part = strchr (path_part, '/');
1897 if (path_part == NULL)
1899 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1900 _("The URI '%s' is invalid"),
1901 uri);
1902 return NULL;
1905 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1907 if (unescaped_hostname == NULL ||
1908 !hostname_validate (unescaped_hostname))
1910 g_free (unescaped_hostname);
1911 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1912 _("The hostname of the URI '%s' is invalid"),
1913 uri);
1914 return NULL;
1917 if (hostname)
1918 *hostname = unescaped_hostname;
1919 else
1920 g_free (unescaped_hostname);
1923 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1925 if (filename == NULL)
1927 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1928 _("The URI '%s' contains invalidly escaped characters"),
1929 uri);
1930 return NULL;
1933 offs = 0;
1934 #ifdef G_OS_WIN32
1935 /* Drop localhost */
1936 if (hostname && *hostname != NULL &&
1937 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1939 g_free (*hostname);
1940 *hostname = NULL;
1943 /* Turn slashes into backslashes, because that's the canonical spelling */
1944 p = filename;
1945 while ((slash = strchr (p, '/')) != NULL)
1947 *slash = '\\';
1948 p = slash + 1;
1951 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1952 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1953 * the filename from the drive letter.
1955 if (g_ascii_isalpha (filename[1]))
1957 if (filename[2] == ':')
1958 offs = 1;
1959 else if (filename[2] == '|')
1961 filename[2] = ':';
1962 offs = 1;
1965 #endif
1967 result = g_strdup (filename + offs);
1968 g_free (filename);
1970 return result;
1973 #if defined (G_OS_WIN32) && !defined (_WIN64)
1975 #undef g_filename_from_uri
1977 gchar *
1978 g_filename_from_uri (const gchar *uri,
1979 gchar **hostname,
1980 GError **error)
1982 gchar *utf8_filename;
1983 gchar *retval = NULL;
1985 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1986 if (utf8_filename)
1988 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1989 g_free (utf8_filename);
1991 return retval;
1994 #endif
1997 * g_filename_to_uri:
1998 * @filename: an absolute filename specified in the GLib file name encoding,
1999 * which is the on-disk file name bytes on Unix, and UTF-8 on
2000 * Windows
2001 * @hostname: (allow-none): A UTF-8 encoded hostname, or %NULL for none.
2002 * @error: location to store the error occurring, or %NULL to ignore
2003 * errors. Any of the errors in #GConvertError may occur.
2005 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2006 * component following Section 3.3. of RFC 2396.
2008 * Return value: a newly-allocated string holding the resulting
2009 * URI, or %NULL on an error.
2011 gchar *
2012 g_filename_to_uri (const gchar *filename,
2013 const gchar *hostname,
2014 GError **error)
2016 char *escaped_uri;
2018 g_return_val_if_fail (filename != NULL, NULL);
2020 if (!g_path_is_absolute (filename))
2022 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2023 _("The pathname '%s' is not an absolute path"),
2024 filename);
2025 return NULL;
2028 if (hostname &&
2029 !(g_utf8_validate (hostname, -1, NULL)
2030 && hostname_validate (hostname)))
2032 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2033 _("Invalid hostname"));
2034 return NULL;
2037 #ifdef G_OS_WIN32
2038 /* Don't use localhost unnecessarily */
2039 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2040 hostname = NULL;
2041 #endif
2043 escaped_uri = g_escape_file_uri (hostname, filename);
2045 return escaped_uri;
2048 #if defined (G_OS_WIN32) && !defined (_WIN64)
2050 #undef g_filename_to_uri
2052 gchar *
2053 g_filename_to_uri (const gchar *filename,
2054 const gchar *hostname,
2055 GError **error)
2057 gchar *utf8_filename;
2058 gchar *retval = NULL;
2060 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2062 if (utf8_filename)
2064 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2065 g_free (utf8_filename);
2068 return retval;
2071 #endif
2074 * g_uri_list_extract_uris:
2075 * @uri_list: an URI list
2077 * Splits an URI list conforming to the text/uri-list
2078 * mime type defined in RFC 2483 into individual URIs,
2079 * discarding any comments. The URIs are not validated.
2081 * Returns: a newly allocated %NULL-terminated list of
2082 * strings holding the individual URIs. The array should
2083 * be freed with g_strfreev().
2085 * Since: 2.6
2087 gchar **
2088 g_uri_list_extract_uris (const gchar *uri_list)
2090 GSList *uris, *u;
2091 const gchar *p, *q;
2092 gchar **result;
2093 gint n_uris = 0;
2095 uris = NULL;
2097 p = uri_list;
2099 /* We don't actually try to validate the URI according to RFC
2100 * 2396, or even check for allowed characters - we just ignore
2101 * comments and trim whitespace off the ends. We also
2102 * allow LF delimination as well as the specified CRLF.
2104 * We do allow comments like specified in RFC 2483.
2106 while (p)
2108 if (*p != '#')
2110 while (g_ascii_isspace (*p))
2111 p++;
2113 q = p;
2114 while (*q && (*q != '\n') && (*q != '\r'))
2115 q++;
2117 if (q > p)
2119 q--;
2120 while (q > p && g_ascii_isspace (*q))
2121 q--;
2123 if (q > p)
2125 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2126 n_uris++;
2130 p = strchr (p, '\n');
2131 if (p)
2132 p++;
2135 result = g_new (gchar *, n_uris + 1);
2137 result[n_uris--] = NULL;
2138 for (u = uris; u; u = u->next)
2139 result[n_uris--] = u->data;
2141 g_slist_free (uris);
2143 return result;
2147 * g_filename_display_basename:
2148 * @filename: an absolute pathname in the GLib file name encoding
2150 * Returns the display basename for the particular filename, guaranteed
2151 * to be valid UTF-8. The display name might not be identical to the filename,
2152 * for instance there might be problems converting it to UTF-8, and some files
2153 * can be translated in the display.
2155 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2156 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2157 * You can search the result for the UTF-8 encoding of this character (which is
2158 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2159 * encoding.
2161 * You must pass the whole absolute pathname to this functions so that
2162 * translation of well known locations can be done.
2164 * This function is preferred over g_filename_display_name() if you know the
2165 * whole path, as it allows translation.
2167 * Return value: a newly allocated string containing
2168 * a rendition of the basename of the filename in valid UTF-8
2170 * Since: 2.6
2172 gchar *
2173 g_filename_display_basename (const gchar *filename)
2175 char *basename;
2176 char *display_name;
2178 g_return_val_if_fail (filename != NULL, NULL);
2180 basename = g_path_get_basename (filename);
2181 display_name = g_filename_display_name (basename);
2182 g_free (basename);
2183 return display_name;
2187 * g_filename_display_name:
2188 * @filename: a pathname hopefully in the GLib file name encoding
2190 * Converts a filename into a valid UTF-8 string. The conversion is
2191 * not necessarily reversible, so you should keep the original around
2192 * and use the return value of this function only for display purposes.
2193 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2194 * even if the filename actually isn't in the GLib file name encoding.
2196 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2197 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2198 * You can search the result for the UTF-8 encoding of this character (which is
2199 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2200 * encoding.
2202 * If you know the whole pathname of the file you should use
2203 * g_filename_display_basename(), since that allows location-based
2204 * translation of filenames.
2206 * Return value: a newly allocated string containing
2207 * a rendition of the filename in valid UTF-8
2209 * Since: 2.6
2211 gchar *
2212 g_filename_display_name (const gchar *filename)
2214 gint i;
2215 const gchar **charsets;
2216 gchar *display_name = NULL;
2217 gboolean is_utf8;
2219 is_utf8 = g_get_filename_charsets (&charsets);
2221 if (is_utf8)
2223 if (g_utf8_validate (filename, -1, NULL))
2224 display_name = g_strdup (filename);
2227 if (!display_name)
2229 /* Try to convert from the filename charsets to UTF-8.
2230 * Skip the first charset if it is UTF-8.
2232 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2234 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2235 NULL, NULL, NULL);
2237 if (display_name)
2238 break;
2242 /* if all conversions failed, we replace invalid UTF-8
2243 * by a question mark
2245 if (!display_name)
2246 display_name = _g_utf8_make_valid (filename);
2248 return display_name;