Call setlocale initially
[glib.git] / glib / gconvert.c
blob520c32abe2509834f9a0302b1dd3fcd21b10d418
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"
25 #include "glib.h"
27 #ifndef G_OS_WIN32
28 #include <iconv.h>
29 #endif
30 #include <errno.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
35 #include "gprintfint.h"
36 #include "gthreadprivate.h"
37 #include "gunicode.h"
39 #ifdef G_OS_WIN32
40 #include "win_iconv.c"
41 #endif
43 #ifdef G_PLATFORM_WIN32
44 #define STRICT
45 #include <windows.h>
46 #undef STRICT
47 #endif
49 #include "glibintl.h"
51 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
52 #error GNU libiconv in use but included iconv.h not from libiconv
53 #endif
54 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
55 #error GNU libiconv not in use but included iconv.h is from libiconv
56 #endif
58 #include "galias.h"
60 /* We try to terminate strings in unknown charsets with this many zero bytes
61 * to ensure that multibyte strings really are nul-terminated when we return
62 * them from g_convert() and friends.
64 #define NUL_TERMINATOR_LENGTH 4
66 GQuark
67 g_convert_error_quark (void)
69 return g_quark_from_static_string ("g_convert_error");
72 static gboolean
73 try_conversion (const char *to_codeset,
74 const char *from_codeset,
75 iconv_t *cd)
77 *cd = iconv_open (to_codeset, from_codeset);
79 if (*cd == (iconv_t)-1 && errno == EINVAL)
80 return FALSE;
81 else
82 return TRUE;
85 static gboolean
86 try_to_aliases (const char **to_aliases,
87 const char *from_codeset,
88 iconv_t *cd)
90 if (to_aliases)
92 const char **p = to_aliases;
93 while (*p)
95 if (try_conversion (*p, from_codeset, cd))
96 return TRUE;
98 p++;
102 return FALSE;
105 G_GNUC_INTERNAL extern const char **
106 _g_charset_get_aliases (const char *canonical_name);
109 * g_iconv_open:
110 * @to_codeset: destination codeset
111 * @from_codeset: source codeset
113 * Same as the standard UNIX routine iconv_open(), but
114 * may be implemented via libiconv on UNIX flavors that lack
115 * a native implementation.
117 * GLib provides g_convert() and g_locale_to_utf8() which are likely
118 * more convenient than the raw iconv wrappers.
120 * Return value: a "conversion descriptor", or (GIConv)-1 if
121 * opening the converter failed.
123 GIConv
124 g_iconv_open (const gchar *to_codeset,
125 const gchar *from_codeset)
127 iconv_t cd;
129 if (!try_conversion (to_codeset, from_codeset, &cd))
131 const char **to_aliases = _g_charset_get_aliases (to_codeset);
132 const char **from_aliases = _g_charset_get_aliases (from_codeset);
134 if (from_aliases)
136 const char **p = from_aliases;
137 while (*p)
139 if (try_conversion (to_codeset, *p, &cd))
140 goto out;
142 if (try_to_aliases (to_aliases, *p, &cd))
143 goto out;
145 p++;
149 if (try_to_aliases (to_aliases, from_codeset, &cd))
150 goto out;
153 out:
154 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
158 * g_iconv:
159 * @converter: conversion descriptor from g_iconv_open()
160 * @inbuf: bytes to convert
161 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
162 * @outbuf: converted output bytes
163 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
165 * Same as the standard UNIX routine iconv(), but
166 * may be implemented via libiconv on UNIX flavors that lack
167 * a native implementation.
169 * GLib provides g_convert() and g_locale_to_utf8() which are likely
170 * more convenient than the raw iconv wrappers.
172 * Return value: count of non-reversible conversions, or -1 on error
174 gsize
175 g_iconv (GIConv converter,
176 gchar **inbuf,
177 gsize *inbytes_left,
178 gchar **outbuf,
179 gsize *outbytes_left)
181 iconv_t cd = (iconv_t)converter;
183 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
187 * g_iconv_close:
188 * @converter: a conversion descriptor from g_iconv_open()
190 * Same as the standard UNIX routine iconv_close(), but
191 * may be implemented via libiconv on UNIX flavors that lack
192 * a native implementation. Should be called to clean up
193 * the conversion descriptor from g_iconv_open() when
194 * you are done converting things.
196 * GLib provides g_convert() and g_locale_to_utf8() which are likely
197 * more convenient than the raw iconv wrappers.
199 * Return value: -1 on error, 0 on success
201 gint
202 g_iconv_close (GIConv converter)
204 iconv_t cd = (iconv_t)converter;
206 return iconv_close (cd);
210 #ifdef NEED_ICONV_CACHE
212 #define ICONV_CACHE_SIZE (16)
214 struct _iconv_cache_bucket {
215 gchar *key;
216 guint32 refcount;
217 gboolean used;
218 GIConv cd;
221 static GList *iconv_cache_list;
222 static GHashTable *iconv_cache;
223 static GHashTable *iconv_open_hash;
224 static guint iconv_cache_size = 0;
225 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
227 /* caller *must* hold the iconv_cache_lock */
228 static void
229 iconv_cache_init (void)
231 static gboolean initialized = FALSE;
233 if (initialized)
234 return;
236 iconv_cache_list = NULL;
237 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
238 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
240 initialized = TRUE;
245 * iconv_cache_bucket_new:
246 * @key: cache key
247 * @cd: iconv descriptor
249 * Creates a new cache bucket, inserts it into the cache and
250 * increments the cache size.
252 * This assumes ownership of @key.
254 * Returns a pointer to the newly allocated cache bucket.
256 static struct _iconv_cache_bucket *
257 iconv_cache_bucket_new (gchar *key, GIConv cd)
259 struct _iconv_cache_bucket *bucket;
261 bucket = g_new (struct _iconv_cache_bucket, 1);
262 bucket->key = key;
263 bucket->refcount = 1;
264 bucket->used = TRUE;
265 bucket->cd = cd;
267 g_hash_table_insert (iconv_cache, bucket->key, bucket);
269 /* FIXME: if we sorted the list so items with few refcounts were
270 first, then we could expire them faster in iconv_cache_expire_unused () */
271 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
273 iconv_cache_size++;
275 return bucket;
280 * iconv_cache_bucket_expire:
281 * @node: cache bucket's node
282 * @bucket: cache bucket
284 * Expires a single cache bucket @bucket. This should only ever be
285 * called on a bucket that currently has no used iconv descriptors
286 * open.
288 * @node is not a required argument. If @node is not supplied, we
289 * search for it ourselves.
291 static void
292 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
294 g_hash_table_remove (iconv_cache, bucket->key);
296 if (node == NULL)
297 node = g_list_find (iconv_cache_list, bucket);
299 g_assert (node != NULL);
301 if (node->prev)
303 node->prev->next = node->next;
304 if (node->next)
305 node->next->prev = node->prev;
307 else
309 iconv_cache_list = node->next;
310 if (node->next)
311 node->next->prev = NULL;
314 g_list_free_1 (node);
316 g_free (bucket->key);
317 g_iconv_close (bucket->cd);
318 g_free (bucket);
320 iconv_cache_size--;
325 * iconv_cache_expire_unused:
327 * Expires as many unused cache buckets as it needs to in order to get
328 * the total number of buckets < ICONV_CACHE_SIZE.
330 static void
331 iconv_cache_expire_unused (void)
333 struct _iconv_cache_bucket *bucket;
334 GList *node, *next;
336 node = iconv_cache_list;
337 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
339 next = node->next;
341 bucket = node->data;
342 if (bucket->refcount == 0)
343 iconv_cache_bucket_expire (node, bucket);
345 node = next;
349 static GIConv
350 open_converter (const gchar *to_codeset,
351 const gchar *from_codeset,
352 GError **error)
354 struct _iconv_cache_bucket *bucket;
355 gchar *key, *dyn_key, auto_key[80];
356 GIConv cd;
357 gsize len_from_codeset, len_to_codeset;
359 /* create our key */
360 len_from_codeset = strlen (from_codeset);
361 len_to_codeset = strlen (to_codeset);
362 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
364 key = auto_key;
365 dyn_key = NULL;
367 else
368 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
369 memcpy (key, from_codeset, len_from_codeset);
370 key[len_from_codeset] = ':';
371 strcpy (key + len_from_codeset + 1, to_codeset);
373 G_LOCK (iconv_cache_lock);
375 /* make sure the cache has been initialized */
376 iconv_cache_init ();
378 bucket = g_hash_table_lookup (iconv_cache, key);
379 if (bucket)
381 g_free (dyn_key);
383 if (bucket->used)
385 cd = g_iconv_open (to_codeset, from_codeset);
386 if (cd == (GIConv) -1)
387 goto error;
389 else
391 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
392 * NULL for anything but inbuf; work around that. (NULL outbuf
393 * or NULL *outbuf is allowed by Unix98.)
395 gsize inbytes_left = 0;
396 gchar *outbuf = NULL;
397 gsize outbytes_left = 0;
399 cd = bucket->cd;
400 bucket->used = TRUE;
402 /* reset the descriptor */
403 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
406 bucket->refcount++;
408 else
410 cd = g_iconv_open (to_codeset, from_codeset);
411 if (cd == (GIConv) -1)
413 g_free (dyn_key);
414 goto error;
417 iconv_cache_expire_unused ();
419 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
422 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
424 G_UNLOCK (iconv_cache_lock);
426 return cd;
428 error:
430 G_UNLOCK (iconv_cache_lock);
432 /* Something went wrong. */
433 if (error)
435 if (errno == EINVAL)
436 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
437 _("Conversion from character set '%s' to '%s' is not supported"),
438 from_codeset, to_codeset);
439 else
440 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
441 _("Could not open converter from '%s' to '%s'"),
442 from_codeset, to_codeset);
445 return cd;
448 static int
449 close_converter (GIConv converter)
451 struct _iconv_cache_bucket *bucket;
452 const gchar *key;
453 GIConv cd;
455 cd = converter;
457 if (cd == (GIConv) -1)
458 return 0;
460 G_LOCK (iconv_cache_lock);
462 key = g_hash_table_lookup (iconv_open_hash, cd);
463 if (key)
465 g_hash_table_remove (iconv_open_hash, cd);
467 bucket = g_hash_table_lookup (iconv_cache, key);
468 g_assert (bucket);
470 bucket->refcount--;
472 if (cd == bucket->cd)
473 bucket->used = FALSE;
474 else
475 g_iconv_close (cd);
477 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
479 /* expire this cache bucket */
480 iconv_cache_bucket_expire (NULL, bucket);
483 else
485 G_UNLOCK (iconv_cache_lock);
487 g_warning ("This iconv context wasn't opened using open_converter");
489 return g_iconv_close (converter);
492 G_UNLOCK (iconv_cache_lock);
494 return 0;
497 #else /* !NEED_ICONV_CACHE */
499 static GIConv
500 open_converter (const gchar *to_codeset,
501 const gchar *from_codeset,
502 GError **error)
504 GIConv cd;
506 cd = g_iconv_open (to_codeset, from_codeset);
508 if (cd == (GIConv) -1)
510 /* Something went wrong. */
511 if (error)
513 if (errno == EINVAL)
514 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
515 _("Conversion from character set '%s' to '%s' is not supported"),
516 from_codeset, to_codeset);
517 else
518 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
519 _("Could not open converter from '%s' to '%s'"),
520 from_codeset, to_codeset);
524 return cd;
527 static int
528 close_converter (GIConv cd)
530 if (cd == (GIConv) -1)
531 return 0;
533 return g_iconv_close (cd);
536 #endif /* NEED_ICONV_CACHE */
539 * g_convert_with_iconv:
540 * @str: the string to convert
541 * @len: the length of the string, or -1 if the string is
542 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
543 * @converter: conversion descriptor from g_iconv_open()
544 * @bytes_read: location to store the number of bytes in the
545 * input string that were successfully converted, or %NULL.
546 * Even if the conversion was successful, this may be
547 * less than @len if there were partial characters
548 * at the end of the input. If the error
549 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
550 * stored will the byte offset after the last valid
551 * input sequence.
552 * @bytes_written: the number of bytes stored in the output buffer (not
553 * including the terminating nul).
554 * @error: location to store the error occuring, or %NULL to ignore
555 * errors. Any of the errors in #GConvertError may occur.
557 * Converts a string from one character set to another.
559 * Note that you should use g_iconv() for streaming
560 * conversions<footnote id="streaming-state">
561 * <para>
562 * Despite the fact that @byes_read can return information about partial
563 * characters, the <literal>g_convert_...</literal> functions
564 * are not generally suitable for streaming. If the underlying converter
565 * being used maintains internal state, then this won't be preserved
566 * across successive calls to g_convert(), g_convert_with_iconv() or
567 * g_convert_with_fallback(). (An example of this is the GNU C converter
568 * for CP1255 which does not emit a base character until it knows that
569 * the next character is not a mark that could combine with the base
570 * character.)
571 * </para>
572 * </footnote>.
574 * Return value: If the conversion was successful, a newly allocated
575 * nul-terminated string, which must be freed with
576 * g_free(). Otherwise %NULL and @error will be set.
578 gchar*
579 g_convert_with_iconv (const gchar *str,
580 gssize len,
581 GIConv converter,
582 gsize *bytes_read,
583 gsize *bytes_written,
584 GError **error)
586 gchar *dest;
587 gchar *outp;
588 const gchar *p;
589 gsize inbytes_remaining;
590 gsize outbytes_remaining;
591 gsize err;
592 gsize outbuf_size;
593 gboolean have_error = FALSE;
594 gboolean done = FALSE;
595 gboolean reset = FALSE;
597 g_return_val_if_fail (converter != (GIConv) -1, NULL);
599 if (len < 0)
600 len = strlen (str);
602 p = str;
603 inbytes_remaining = len;
604 outbuf_size = len + NUL_TERMINATOR_LENGTH;
606 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
607 outp = dest = g_malloc (outbuf_size);
609 while (!done && !have_error)
611 if (reset)
612 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
613 else
614 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
616 if (err == (gsize) -1)
618 switch (errno)
620 case EINVAL:
621 /* Incomplete text, do not report an error */
622 done = TRUE;
623 break;
624 case E2BIG:
626 gsize used = outp - dest;
628 outbuf_size *= 2;
629 dest = g_realloc (dest, outbuf_size);
631 outp = dest + used;
632 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
634 break;
635 case EILSEQ:
636 if (error)
637 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
638 _("Invalid byte sequence in conversion input"));
639 have_error = TRUE;
640 break;
641 default:
643 int errsv = errno;
645 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
646 _("Error during conversion: %s"),
647 g_strerror (errsv));
649 have_error = TRUE;
650 break;
653 else
655 if (!reset)
657 /* call g_iconv with NULL inbuf to cleanup shift state */
658 reset = TRUE;
659 inbytes_remaining = 0;
661 else
662 done = TRUE;
666 memset (outp, 0, NUL_TERMINATOR_LENGTH);
668 if (bytes_read)
669 *bytes_read = p - str;
670 else
672 if ((p - str) != len)
674 if (!have_error)
676 if (error)
677 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
678 _("Partial character sequence at end of input"));
679 have_error = TRUE;
684 if (bytes_written)
685 *bytes_written = outp - dest; /* Doesn't include '\0' */
687 if (have_error)
689 g_free (dest);
690 return NULL;
692 else
693 return dest;
697 * g_convert:
698 * @str: the string to convert
699 * @len: the length of the string, or -1 if the string is
700 * nul-terminated<footnote id="nul-unsafe">
701 <para>
702 Note that some encodings may allow nul bytes to
703 occur inside strings. In that case, using -1 for
704 the @len parameter is unsafe.
705 </para>
706 </footnote>.
707 * @to_codeset: name of character set into which to convert @str
708 * @from_codeset: character set of @str.
709 * @bytes_read: location to store the number of bytes in the
710 * input string that were successfully converted, or %NULL.
711 * Even if the conversion was successful, this may be
712 * less than @len if there were partial characters
713 * at the end of the input. If the error
714 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
715 * stored will the byte offset after the last valid
716 * input sequence.
717 * @bytes_written: the number of bytes stored in the output buffer (not
718 * including the terminating nul).
719 * @error: location to store the error occuring, or %NULL to ignore
720 * errors. Any of the errors in #GConvertError may occur.
722 * Converts a string from one character set to another.
724 * Note that you should use g_iconv() for streaming
725 * conversions<footnoteref linkend="streaming-state"/>.
727 * Return value: If the conversion was successful, a newly allocated
728 * nul-terminated string, which must be freed with
729 * g_free(). Otherwise %NULL and @error will be set.
731 gchar*
732 g_convert (const gchar *str,
733 gssize len,
734 const gchar *to_codeset,
735 const gchar *from_codeset,
736 gsize *bytes_read,
737 gsize *bytes_written,
738 GError **error)
740 gchar *res;
741 GIConv cd;
743 g_return_val_if_fail (str != NULL, NULL);
744 g_return_val_if_fail (to_codeset != NULL, NULL);
745 g_return_val_if_fail (from_codeset != NULL, NULL);
747 cd = open_converter (to_codeset, from_codeset, error);
749 if (cd == (GIConv) -1)
751 if (bytes_read)
752 *bytes_read = 0;
754 if (bytes_written)
755 *bytes_written = 0;
757 return NULL;
760 res = g_convert_with_iconv (str, len, cd,
761 bytes_read, bytes_written,
762 error);
764 close_converter (cd);
766 return res;
770 * g_convert_with_fallback:
771 * @str: the string to convert
772 * @len: the length of the string, or -1 if the string is
773 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
774 * @to_codeset: name of character set into which to convert @str
775 * @from_codeset: character set of @str.
776 * @fallback: UTF-8 string to use in place of character not
777 * present in the target encoding. (The string must be
778 * representable in the target encoding).
779 If %NULL, characters not in the target encoding will
780 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
781 * @bytes_read: location to store the number of bytes in the
782 * input string that were successfully converted, or %NULL.
783 * Even if the conversion was successful, this may be
784 * less than @len if there were partial characters
785 * at the end of the input.
786 * @bytes_written: the number of bytes stored in the output buffer (not
787 * including the terminating nul).
788 * @error: location to store the error occuring, or %NULL to ignore
789 * errors. Any of the errors in #GConvertError may occur.
791 * Converts a string from one character set to another, possibly
792 * including fallback sequences for characters not representable
793 * in the output. Note that it is not guaranteed that the specification
794 * for the fallback sequences in @fallback will be honored. Some
795 * systems may do an approximate conversion from @from_codeset
796 * to @to_codeset in their iconv() functions,
797 * in which case GLib will simply return that approximate conversion.
799 * Note that you should use g_iconv() for streaming
800 * conversions<footnoteref linkend="streaming-state"/>.
802 * Return value: If the conversion was successful, a newly allocated
803 * nul-terminated string, which must be freed with
804 * g_free(). Otherwise %NULL and @error will be set.
806 gchar*
807 g_convert_with_fallback (const gchar *str,
808 gssize len,
809 const gchar *to_codeset,
810 const gchar *from_codeset,
811 const gchar *fallback,
812 gsize *bytes_read,
813 gsize *bytes_written,
814 GError **error)
816 gchar *utf8;
817 gchar *dest;
818 gchar *outp;
819 const gchar *insert_str = NULL;
820 const gchar *p;
821 gsize inbytes_remaining;
822 const gchar *save_p = NULL;
823 gsize save_inbytes = 0;
824 gsize outbytes_remaining;
825 gsize err;
826 GIConv cd;
827 gsize outbuf_size;
828 gboolean have_error = FALSE;
829 gboolean done = FALSE;
831 GError *local_error = NULL;
833 g_return_val_if_fail (str != NULL, NULL);
834 g_return_val_if_fail (to_codeset != NULL, NULL);
835 g_return_val_if_fail (from_codeset != NULL, NULL);
837 if (len < 0)
838 len = strlen (str);
840 /* Try an exact conversion; we only proceed if this fails
841 * due to an illegal sequence in the input string.
843 dest = g_convert (str, len, to_codeset, from_codeset,
844 bytes_read, bytes_written, &local_error);
845 if (!local_error)
846 return dest;
848 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
850 g_propagate_error (error, local_error);
851 return NULL;
853 else
854 g_error_free (local_error);
856 local_error = NULL;
858 /* No go; to proceed, we need a converter from "UTF-8" to
859 * to_codeset, and the string as UTF-8.
861 cd = open_converter (to_codeset, "UTF-8", error);
862 if (cd == (GIConv) -1)
864 if (bytes_read)
865 *bytes_read = 0;
867 if (bytes_written)
868 *bytes_written = 0;
870 return NULL;
873 utf8 = g_convert (str, len, "UTF-8", from_codeset,
874 bytes_read, &inbytes_remaining, error);
875 if (!utf8)
877 close_converter (cd);
878 if (bytes_written)
879 *bytes_written = 0;
880 return NULL;
883 /* Now the heart of the code. We loop through the UTF-8 string, and
884 * whenever we hit an offending character, we form fallback, convert
885 * the fallback to the target codeset, and then go back to
886 * converting the original string after finishing with the fallback.
888 * The variables save_p and save_inbytes store the input state
889 * for the original string while we are converting the fallback
891 p = utf8;
893 outbuf_size = len + NUL_TERMINATOR_LENGTH;
894 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
895 outp = dest = g_malloc (outbuf_size);
897 while (!done && !have_error)
899 gsize inbytes_tmp = inbytes_remaining;
900 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
901 inbytes_remaining = inbytes_tmp;
903 if (err == (gsize) -1)
905 switch (errno)
907 case EINVAL:
908 g_assert_not_reached();
909 break;
910 case E2BIG:
912 gsize used = outp - dest;
914 outbuf_size *= 2;
915 dest = g_realloc (dest, outbuf_size);
917 outp = dest + used;
918 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
920 break;
922 case EILSEQ:
923 if (save_p)
925 /* Error converting fallback string - fatal
927 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
928 _("Cannot convert fallback '%s' to codeset '%s'"),
929 insert_str, to_codeset);
930 have_error = TRUE;
931 break;
933 else if (p)
935 if (!fallback)
937 gunichar ch = g_utf8_get_char (p);
938 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
939 ch);
941 else
942 insert_str = fallback;
944 save_p = g_utf8_next_char (p);
945 save_inbytes = inbytes_remaining - (save_p - p);
946 p = insert_str;
947 inbytes_remaining = strlen (p);
948 break;
950 /* fall thru if p is NULL */
951 default:
953 int errsv = errno;
955 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
956 _("Error during conversion: %s"),
957 g_strerror (errsv));
960 have_error = TRUE;
961 break;
964 else
966 if (save_p)
968 if (!fallback)
969 g_free ((gchar *)insert_str);
970 p = save_p;
971 inbytes_remaining = save_inbytes;
972 save_p = NULL;
974 else if (p)
976 /* call g_iconv with NULL inbuf to cleanup shift state */
977 p = NULL;
978 inbytes_remaining = 0;
980 else
981 done = TRUE;
985 /* Cleanup
987 memset (outp, 0, NUL_TERMINATOR_LENGTH);
989 close_converter (cd);
991 if (bytes_written)
992 *bytes_written = outp - dest; /* Doesn't include '\0' */
994 g_free (utf8);
996 if (have_error)
998 if (save_p && !fallback)
999 g_free ((gchar *)insert_str);
1000 g_free (dest);
1001 return NULL;
1003 else
1004 return dest;
1008 * g_locale_to_utf8
1013 static gchar *
1014 strdup_len (const gchar *string,
1015 gssize len,
1016 gsize *bytes_written,
1017 gsize *bytes_read,
1018 GError **error)
1021 gsize real_len;
1023 if (!g_utf8_validate (string, len, NULL))
1025 if (bytes_read)
1026 *bytes_read = 0;
1027 if (bytes_written)
1028 *bytes_written = 0;
1030 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1031 _("Invalid byte sequence in conversion input"));
1032 return NULL;
1035 if (len < 0)
1036 real_len = strlen (string);
1037 else
1039 real_len = 0;
1041 while (real_len < len && string[real_len])
1042 real_len++;
1045 if (bytes_read)
1046 *bytes_read = real_len;
1047 if (bytes_written)
1048 *bytes_written = real_len;
1050 return g_strndup (string, real_len);
1054 * g_locale_to_utf8:
1055 * @opsysstring: a string in the encoding of the current locale. On Windows
1056 * this means the system codepage.
1057 * @len: the length of the string, or -1 if the string is
1058 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1059 * @bytes_read: location to store the number of bytes in the
1060 * input string that were successfully converted, or %NULL.
1061 * Even if the conversion was successful, this may be
1062 * less than @len if there were partial characters
1063 * at the end of the input. If the error
1064 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1065 * stored will the byte offset after the last valid
1066 * input sequence.
1067 * @bytes_written: the number of bytes stored in the output buffer (not
1068 * including the terminating nul).
1069 * @error: location to store the error occuring, or %NULL to ignore
1070 * errors. Any of the errors in #GConvertError may occur.
1072 * Converts a string which is in the encoding used for strings by
1073 * the C runtime (usually the same as that used by the operating
1074 * system) in the <link linkend="setlocale">current locale</link> into a
1075 * UTF-8 string.
1077 * Return value: The converted string, or %NULL on an error.
1079 gchar *
1080 g_locale_to_utf8 (const gchar *opsysstring,
1081 gssize len,
1082 gsize *bytes_read,
1083 gsize *bytes_written,
1084 GError **error)
1086 const char *charset;
1088 if (g_get_charset (&charset))
1089 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1090 else
1091 return g_convert (opsysstring, len,
1092 "UTF-8", charset, bytes_read, bytes_written, error);
1096 * g_locale_from_utf8:
1097 * @utf8string: a UTF-8 encoded string
1098 * @len: the length of the string, or -1 if the string is
1099 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1100 * @bytes_read: location to store the number of bytes in the
1101 * input string that were successfully converted, or %NULL.
1102 * Even if the conversion was successful, this may be
1103 * less than @len if there were partial characters
1104 * at the end of the input. If the error
1105 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1106 * stored will the byte offset after the last valid
1107 * input sequence.
1108 * @bytes_written: the number of bytes stored in the output buffer (not
1109 * including the terminating nul).
1110 * @error: location to store the error occuring, or %NULL to ignore
1111 * errors. Any of the errors in #GConvertError may occur.
1113 * Converts a string from UTF-8 to the encoding used for strings by
1114 * the C runtime (usually the same as that used by the operating
1115 * system) in the <link linkend="setlocale">current locale</link>. On
1116 * Windows this means the system codepage.
1118 * Return value: The converted string, or %NULL on an error.
1120 gchar *
1121 g_locale_from_utf8 (const gchar *utf8string,
1122 gssize len,
1123 gsize *bytes_read,
1124 gsize *bytes_written,
1125 GError **error)
1127 const gchar *charset;
1129 if (g_get_charset (&charset))
1130 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1131 else
1132 return g_convert (utf8string, len,
1133 charset, "UTF-8", bytes_read, bytes_written, error);
1136 #ifndef G_PLATFORM_WIN32
1138 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1140 struct _GFilenameCharsetCache {
1141 gboolean is_utf8;
1142 gchar *charset;
1143 gchar **filename_charsets;
1146 static void
1147 filename_charset_cache_free (gpointer data)
1149 GFilenameCharsetCache *cache = data;
1150 g_free (cache->charset);
1151 g_strfreev (cache->filename_charsets);
1152 g_free (cache);
1156 * g_get_filename_charsets:
1157 * @charsets: return location for the %NULL-terminated list of encoding names
1159 * Determines the preferred character sets used for filenames.
1160 * The first character set from the @charsets is the filename encoding, the
1161 * subsequent character sets are used when trying to generate a displayable
1162 * representation of a filename, see g_filename_display_name().
1164 * On Unix, the character sets are determined by consulting the
1165 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1166 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1167 * used in the GLib API is always UTF-8 and said environment variables
1168 * have no effect.
1170 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1171 * of character set names. The special token "&commat;locale" is taken to
1172 * mean the character set for the <link linkend="setlocale">current
1173 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1174 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1175 * locale is taken as the filename encoding. If neither environment variable
1176 * is set, UTF-8 is taken as the filename encoding, but the character
1177 * set of the current locale is also put in the list of encodings.
1179 * The returned @charsets belong to GLib and must not be freed.
1181 * Note that on Unix, regardless of the locale character set or
1182 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1183 * on a system might be in any random encoding or just gibberish.
1185 * Return value: %TRUE if the filename encoding is UTF-8.
1187 * Since: 2.6
1189 gboolean
1190 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1192 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1193 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1194 const gchar *charset;
1196 if (!cache)
1198 cache = g_new0 (GFilenameCharsetCache, 1);
1199 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1202 g_get_charset (&charset);
1204 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1206 const gchar *new_charset;
1207 gchar *p;
1208 gint i;
1210 g_free (cache->charset);
1211 g_strfreev (cache->filename_charsets);
1212 cache->charset = g_strdup (charset);
1214 p = getenv ("G_FILENAME_ENCODING");
1215 if (p != NULL && p[0] != '\0')
1217 cache->filename_charsets = g_strsplit (p, ",", 0);
1218 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1220 for (i = 0; cache->filename_charsets[i]; i++)
1222 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1224 g_get_charset (&new_charset);
1225 g_free (cache->filename_charsets[i]);
1226 cache->filename_charsets[i] = g_strdup (new_charset);
1230 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1232 cache->filename_charsets = g_new0 (gchar *, 2);
1233 cache->is_utf8 = g_get_charset (&new_charset);
1234 cache->filename_charsets[0] = g_strdup (new_charset);
1236 else
1238 cache->filename_charsets = g_new0 (gchar *, 3);
1239 cache->is_utf8 = TRUE;
1240 cache->filename_charsets[0] = g_strdup ("UTF-8");
1241 if (!g_get_charset (&new_charset))
1242 cache->filename_charsets[1] = g_strdup (new_charset);
1246 if (filename_charsets)
1247 *filename_charsets = (const gchar **)cache->filename_charsets;
1249 return cache->is_utf8;
1252 #else /* G_PLATFORM_WIN32 */
1254 gboolean
1255 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1257 static const gchar *charsets[] = {
1258 "UTF-8",
1259 NULL
1262 #ifdef G_OS_WIN32
1263 /* On Windows GLib pretends that the filename charset is UTF-8 */
1264 if (filename_charsets)
1265 *filename_charsets = charsets;
1267 return TRUE;
1268 #else
1269 gboolean result;
1271 /* Cygwin works like before */
1272 result = g_get_charset (&(charsets[0]));
1274 if (filename_charsets)
1275 *filename_charsets = charsets;
1277 return result;
1278 #endif
1281 #endif /* G_PLATFORM_WIN32 */
1283 static gboolean
1284 get_filename_charset (const gchar **filename_charset)
1286 const gchar **charsets;
1287 gboolean is_utf8;
1289 is_utf8 = g_get_filename_charsets (&charsets);
1291 if (filename_charset)
1292 *filename_charset = charsets[0];
1294 return is_utf8;
1297 /* This is called from g_thread_init(). It's used to
1298 * initialize some static data in a threadsafe way.
1300 void
1301 _g_convert_thread_init (void)
1303 const gchar **dummy;
1304 (void) g_get_filename_charsets (&dummy);
1308 * g_filename_to_utf8:
1309 * @opsysstring: a string in the encoding for filenames
1310 * @len: the length of the string, or -1 if the string is
1311 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1312 * @bytes_read: location to store the number of bytes in the
1313 * input string that were successfully converted, or %NULL.
1314 * Even if the conversion was successful, this may be
1315 * less than @len if there were partial characters
1316 * at the end of the input. If the error
1317 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1318 * stored will the byte offset after the last valid
1319 * input sequence.
1320 * @bytes_written: the number of bytes stored in the output buffer (not
1321 * including the terminating nul).
1322 * @error: location to store the error occuring, or %NULL to ignore
1323 * errors. Any of the errors in #GConvertError may occur.
1325 * Converts a string which is in the encoding used by GLib for
1326 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1327 * for filenames; on other platforms, this function indirectly depends on
1328 * the <link linkend="setlocale">current locale</link>.
1330 * Return value: The converted string, or %NULL on an error.
1332 gchar*
1333 g_filename_to_utf8 (const gchar *opsysstring,
1334 gssize len,
1335 gsize *bytes_read,
1336 gsize *bytes_written,
1337 GError **error)
1339 const gchar *charset;
1341 if (get_filename_charset (&charset))
1342 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1343 else
1344 return g_convert (opsysstring, len,
1345 "UTF-8", charset, bytes_read, bytes_written, error);
1348 #if defined (G_OS_WIN32) && !defined (_WIN64)
1350 #undef g_filename_to_utf8
1352 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1353 * 64-bit versions as there should be no old deployed binaries that would use
1354 * the old versions.
1357 gchar*
1358 g_filename_to_utf8 (const gchar *opsysstring,
1359 gssize len,
1360 gsize *bytes_read,
1361 gsize *bytes_written,
1362 GError **error)
1364 const gchar *charset;
1366 if (g_get_charset (&charset))
1367 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1368 else
1369 return g_convert (opsysstring, len,
1370 "UTF-8", charset, bytes_read, bytes_written, error);
1373 #endif
1376 * g_filename_from_utf8:
1377 * @utf8string: a UTF-8 encoded string.
1378 * @len: the length of the string, or -1 if the string is
1379 * nul-terminated.
1380 * @bytes_read: location to store the number of bytes in the
1381 * input string that were successfully converted, or %NULL.
1382 * Even if the conversion was successful, this may be
1383 * less than @len if there were partial characters
1384 * at the end of the input. If the error
1385 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1386 * stored will the byte offset after the last valid
1387 * input sequence.
1388 * @bytes_written: the number of bytes stored in the output buffer (not
1389 * including the terminating nul).
1390 * @error: location to store the error occuring, or %NULL to ignore
1391 * errors. Any of the errors in #GConvertError may occur.
1393 * Converts a string from UTF-8 to the encoding GLib uses for
1394 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1395 * on other platforms, this function indirectly depends on the
1396 * <link linkend="setlocale">current locale</link>.
1398 * Return value: The converted string, or %NULL on an error.
1400 gchar*
1401 g_filename_from_utf8 (const gchar *utf8string,
1402 gssize len,
1403 gsize *bytes_read,
1404 gsize *bytes_written,
1405 GError **error)
1407 const gchar *charset;
1409 if (get_filename_charset (&charset))
1410 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1411 else
1412 return g_convert (utf8string, len,
1413 charset, "UTF-8", bytes_read, bytes_written, error);
1416 #if defined (G_OS_WIN32) && !defined (_WIN64)
1418 #undef g_filename_from_utf8
1420 /* Binary compatibility version. Not for newly compiled code. */
1422 gchar*
1423 g_filename_from_utf8 (const gchar *utf8string,
1424 gssize len,
1425 gsize *bytes_read,
1426 gsize *bytes_written,
1427 GError **error)
1429 const gchar *charset;
1431 if (g_get_charset (&charset))
1432 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1433 else
1434 return g_convert (utf8string, len,
1435 charset, "UTF-8", bytes_read, bytes_written, error);
1438 #endif
1440 /* Test of haystack has the needle prefix, comparing case
1441 * insensitive. haystack may be UTF-8, but needle must
1442 * contain only ascii. */
1443 static gboolean
1444 has_case_prefix (const gchar *haystack, const gchar *needle)
1446 const gchar *h, *n;
1448 /* Eat one character at a time. */
1449 h = haystack;
1450 n = needle;
1452 while (*n && *h &&
1453 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1455 n++;
1456 h++;
1459 return *n == '\0';
1462 typedef enum {
1463 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1464 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1465 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1466 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1467 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1468 } UnsafeCharacterSet;
1470 static const guchar acceptable[96] = {
1471 /* A table of the ASCII chars from space (32) to DEL (127) */
1472 /* ! " # $ % & ' ( ) * + , - . / */
1473 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1474 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1475 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1476 /* @ A B C D E F G H I J K L M N O */
1477 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1478 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1479 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1480 /* ` a b c d e f g h i j k l m n o */
1481 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1482 /* p q r s t u v w x y z { | } ~ DEL */
1483 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1486 static const gchar hex[16] = "0123456789ABCDEF";
1488 /* Note: This escape function works on file: URIs, but if you want to
1489 * escape something else, please read RFC-2396 */
1490 static gchar *
1491 g_escape_uri_string (const gchar *string,
1492 UnsafeCharacterSet mask)
1494 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1496 const gchar *p;
1497 gchar *q;
1498 gchar *result;
1499 int c;
1500 gint unacceptable;
1501 UnsafeCharacterSet use_mask;
1503 g_return_val_if_fail (mask == UNSAFE_ALL
1504 || mask == UNSAFE_ALLOW_PLUS
1505 || mask == UNSAFE_PATH
1506 || mask == UNSAFE_HOST
1507 || mask == UNSAFE_SLASHES, NULL);
1509 unacceptable = 0;
1510 use_mask = mask;
1511 for (p = string; *p != '\0'; p++)
1513 c = (guchar) *p;
1514 if (!ACCEPTABLE (c))
1515 unacceptable++;
1518 result = g_malloc (p - string + unacceptable * 2 + 1);
1520 use_mask = mask;
1521 for (q = result, p = string; *p != '\0'; p++)
1523 c = (guchar) *p;
1525 if (!ACCEPTABLE (c))
1527 *q++ = '%'; /* means hex coming */
1528 *q++ = hex[c >> 4];
1529 *q++ = hex[c & 15];
1531 else
1532 *q++ = *p;
1535 *q = '\0';
1537 return result;
1541 static gchar *
1542 g_escape_file_uri (const gchar *hostname,
1543 const gchar *pathname)
1545 char *escaped_hostname = NULL;
1546 char *escaped_path;
1547 char *res;
1549 #ifdef G_OS_WIN32
1550 char *p, *backslash;
1552 /* Turn backslashes into forward slashes. That's what Netscape
1553 * does, and they are actually more or less equivalent in Windows.
1556 pathname = g_strdup (pathname);
1557 p = (char *) pathname;
1559 while ((backslash = strchr (p, '\\')) != NULL)
1561 *backslash = '/';
1562 p = backslash + 1;
1564 #endif
1566 if (hostname && *hostname != '\0')
1568 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1571 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1573 res = g_strconcat ("file://",
1574 (escaped_hostname) ? escaped_hostname : "",
1575 (*escaped_path != '/') ? "/" : "",
1576 escaped_path,
1577 NULL);
1579 #ifdef G_OS_WIN32
1580 g_free ((char *) pathname);
1581 #endif
1583 g_free (escaped_hostname);
1584 g_free (escaped_path);
1586 return res;
1589 static int
1590 unescape_character (const char *scanner)
1592 int first_digit;
1593 int second_digit;
1595 first_digit = g_ascii_xdigit_value (scanner[0]);
1596 if (first_digit < 0)
1597 return -1;
1599 second_digit = g_ascii_xdigit_value (scanner[1]);
1600 if (second_digit < 0)
1601 return -1;
1603 return (first_digit << 4) | second_digit;
1606 static gchar *
1607 g_unescape_uri_string (const char *escaped,
1608 int len,
1609 const char *illegal_escaped_characters,
1610 gboolean ascii_must_not_be_escaped)
1612 const gchar *in, *in_end;
1613 gchar *out, *result;
1614 int c;
1616 if (escaped == NULL)
1617 return NULL;
1619 if (len < 0)
1620 len = strlen (escaped);
1622 result = g_malloc (len + 1);
1624 out = result;
1625 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1627 c = *in;
1629 if (c == '%')
1631 /* catch partial escape sequences past the end of the substring */
1632 if (in + 3 > in_end)
1633 break;
1635 c = unescape_character (in + 1);
1637 /* catch bad escape sequences and NUL characters */
1638 if (c <= 0)
1639 break;
1641 /* catch escaped ASCII */
1642 if (ascii_must_not_be_escaped && c <= 0x7F)
1643 break;
1645 /* catch other illegal escaped characters */
1646 if (strchr (illegal_escaped_characters, c) != NULL)
1647 break;
1649 in += 2;
1652 *out++ = c;
1655 g_assert (out - result <= len);
1656 *out = '\0';
1658 if (in != in_end)
1660 g_free (result);
1661 return NULL;
1664 return result;
1667 static gboolean
1668 is_asciialphanum (gunichar c)
1670 return c <= 0x7F && g_ascii_isalnum (c);
1673 static gboolean
1674 is_asciialpha (gunichar c)
1676 return c <= 0x7F && g_ascii_isalpha (c);
1679 /* allows an empty string */
1680 static gboolean
1681 hostname_validate (const char *hostname)
1683 const char *p;
1684 gunichar c, first_char, last_char;
1686 p = hostname;
1687 if (*p == '\0')
1688 return TRUE;
1691 /* read in a label */
1692 c = g_utf8_get_char (p);
1693 p = g_utf8_next_char (p);
1694 if (!is_asciialphanum (c))
1695 return FALSE;
1696 first_char = c;
1699 last_char = c;
1700 c = g_utf8_get_char (p);
1701 p = g_utf8_next_char (p);
1703 while (is_asciialphanum (c) || c == '-');
1704 if (last_char == '-')
1705 return FALSE;
1707 /* if that was the last label, check that it was a toplabel */
1708 if (c == '\0' || (c == '.' && *p == '\0'))
1709 return is_asciialpha (first_char);
1711 while (c == '.');
1712 return FALSE;
1716 * g_filename_from_uri:
1717 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1718 * @hostname: Location to store hostname for the URI, or %NULL.
1719 * If there is no hostname in the URI, %NULL will be
1720 * stored in this location.
1721 * @error: location to store the error occuring, or %NULL to ignore
1722 * errors. Any of the errors in #GConvertError may occur.
1724 * Converts an escaped ASCII-encoded URI to a local filename in the
1725 * encoding used for filenames.
1727 * Return value: a newly-allocated string holding the resulting
1728 * filename, or %NULL on an error.
1730 gchar *
1731 g_filename_from_uri (const gchar *uri,
1732 gchar **hostname,
1733 GError **error)
1735 const char *path_part;
1736 const char *host_part;
1737 char *unescaped_hostname;
1738 char *result;
1739 char *filename;
1740 int offs;
1741 #ifdef G_OS_WIN32
1742 char *p, *slash;
1743 #endif
1745 if (hostname)
1746 *hostname = NULL;
1748 if (!has_case_prefix (uri, "file:/"))
1750 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1751 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1752 uri);
1753 return NULL;
1756 path_part = uri + strlen ("file:");
1758 if (strchr (path_part, '#') != NULL)
1760 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1761 _("The local file URI '%s' may not include a '#'"),
1762 uri);
1763 return NULL;
1766 if (has_case_prefix (path_part, "///"))
1767 path_part += 2;
1768 else if (has_case_prefix (path_part, "//"))
1770 path_part += 2;
1771 host_part = path_part;
1773 path_part = strchr (path_part, '/');
1775 if (path_part == NULL)
1777 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1778 _("The URI '%s' is invalid"),
1779 uri);
1780 return NULL;
1783 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1785 if (unescaped_hostname == NULL ||
1786 !hostname_validate (unescaped_hostname))
1788 g_free (unescaped_hostname);
1789 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1790 _("The hostname of the URI '%s' is invalid"),
1791 uri);
1792 return NULL;
1795 if (hostname)
1796 *hostname = unescaped_hostname;
1797 else
1798 g_free (unescaped_hostname);
1801 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1803 if (filename == NULL)
1805 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1806 _("The URI '%s' contains invalidly escaped characters"),
1807 uri);
1808 return NULL;
1811 offs = 0;
1812 #ifdef G_OS_WIN32
1813 /* Drop localhost */
1814 if (hostname && *hostname != NULL &&
1815 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1817 g_free (*hostname);
1818 *hostname = NULL;
1821 /* Turn slashes into backslashes, because that's the canonical spelling */
1822 p = filename;
1823 while ((slash = strchr (p, '/')) != NULL)
1825 *slash = '\\';
1826 p = slash + 1;
1829 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1830 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1831 * the filename from the drive letter.
1833 if (g_ascii_isalpha (filename[1]))
1835 if (filename[2] == ':')
1836 offs = 1;
1837 else if (filename[2] == '|')
1839 filename[2] = ':';
1840 offs = 1;
1843 #endif
1845 result = g_strdup (filename + offs);
1846 g_free (filename);
1848 return result;
1851 #if defined (G_OS_WIN32) && !defined (_WIN64)
1853 #undef g_filename_from_uri
1855 gchar *
1856 g_filename_from_uri (const gchar *uri,
1857 gchar **hostname,
1858 GError **error)
1860 gchar *utf8_filename;
1861 gchar *retval = NULL;
1863 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1864 if (utf8_filename)
1866 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1867 g_free (utf8_filename);
1869 return retval;
1872 #endif
1875 * g_filename_to_uri:
1876 * @filename: an absolute filename specified in the GLib file name encoding,
1877 * which is the on-disk file name bytes on Unix, and UTF-8 on
1878 * Windows
1879 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1880 * @error: location to store the error occuring, or %NULL to ignore
1881 * errors. Any of the errors in #GConvertError may occur.
1883 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1884 * component following Section 3.3. of RFC 2396.
1886 * Return value: a newly-allocated string holding the resulting
1887 * URI, or %NULL on an error.
1889 gchar *
1890 g_filename_to_uri (const gchar *filename,
1891 const gchar *hostname,
1892 GError **error)
1894 char *escaped_uri;
1896 g_return_val_if_fail (filename != NULL, NULL);
1898 if (!g_path_is_absolute (filename))
1900 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1901 _("The pathname '%s' is not an absolute path"),
1902 filename);
1903 return NULL;
1906 if (hostname &&
1907 !(g_utf8_validate (hostname, -1, NULL)
1908 && hostname_validate (hostname)))
1910 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1911 _("Invalid hostname"));
1912 return NULL;
1915 #ifdef G_OS_WIN32
1916 /* Don't use localhost unnecessarily */
1917 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1918 hostname = NULL;
1919 #endif
1921 escaped_uri = g_escape_file_uri (hostname, filename);
1923 return escaped_uri;
1926 #if defined (G_OS_WIN32) && !defined (_WIN64)
1928 #undef g_filename_to_uri
1930 gchar *
1931 g_filename_to_uri (const gchar *filename,
1932 const gchar *hostname,
1933 GError **error)
1935 gchar *utf8_filename;
1936 gchar *retval = NULL;
1938 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1940 if (utf8_filename)
1942 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1943 g_free (utf8_filename);
1946 return retval;
1949 #endif
1952 * g_uri_list_extract_uris:
1953 * @uri_list: an URI list
1955 * Splits an URI list conforming to the text/uri-list
1956 * mime type defined in RFC 2483 into individual URIs,
1957 * discarding any comments. The URIs are not validated.
1959 * Returns: a newly allocated %NULL-terminated list of
1960 * strings holding the individual URIs. The array should
1961 * be freed with g_strfreev().
1963 * Since: 2.6
1965 gchar **
1966 g_uri_list_extract_uris (const gchar *uri_list)
1968 GSList *uris, *u;
1969 const gchar *p, *q;
1970 gchar **result;
1971 gint n_uris = 0;
1973 uris = NULL;
1975 p = uri_list;
1977 /* We don't actually try to validate the URI according to RFC
1978 * 2396, or even check for allowed characters - we just ignore
1979 * comments and trim whitespace off the ends. We also
1980 * allow LF delimination as well as the specified CRLF.
1982 * We do allow comments like specified in RFC 2483.
1984 while (p)
1986 if (*p != '#')
1988 while (g_ascii_isspace (*p))
1989 p++;
1991 q = p;
1992 while (*q && (*q != '\n') && (*q != '\r'))
1993 q++;
1995 if (q > p)
1997 q--;
1998 while (q > p && g_ascii_isspace (*q))
1999 q--;
2001 if (q > p)
2003 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2004 n_uris++;
2008 p = strchr (p, '\n');
2009 if (p)
2010 p++;
2013 result = g_new (gchar *, n_uris + 1);
2015 result[n_uris--] = NULL;
2016 for (u = uris; u; u = u->next)
2017 result[n_uris--] = u->data;
2019 g_slist_free (uris);
2021 return result;
2025 * g_filename_display_basename:
2026 * @filename: an absolute pathname in the GLib file name encoding
2028 * Returns the display basename for the particular filename, guaranteed
2029 * to be valid UTF-8. The display name might not be identical to the filename,
2030 * for instance there might be problems converting it to UTF-8, and some files
2031 * can be translated in the display.
2033 * If GLib can not make sense of the encoding of @filename, as a last resort it
2034 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2035 * You can search the result for the UTF-8 encoding of this character (which is
2036 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2037 * encoding.
2039 * You must pass the whole absolute pathname to this functions so that
2040 * translation of well known locations can be done.
2042 * This function is preferred over g_filename_display_name() if you know the
2043 * whole path, as it allows translation.
2045 * Return value: a newly allocated string containing
2046 * a rendition of the basename of the filename in valid UTF-8
2048 * Since: 2.6
2050 gchar *
2051 g_filename_display_basename (const gchar *filename)
2053 char *basename;
2054 char *display_name;
2056 g_return_val_if_fail (filename != NULL, NULL);
2058 basename = g_path_get_basename (filename);
2059 display_name = g_filename_display_name (basename);
2060 g_free (basename);
2061 return display_name;
2065 * g_filename_display_name:
2066 * @filename: a pathname hopefully in the GLib file name encoding
2068 * Converts a filename into a valid UTF-8 string. The conversion is
2069 * not necessarily reversible, so you should keep the original around
2070 * and use the return value of this function only for display purposes.
2071 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2072 * even if the filename actually isn't in the GLib file name encoding.
2074 * If GLib can not make sense of the encoding of @filename, as a last resort it
2075 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2076 * You can search the result for the UTF-8 encoding of this character (which is
2077 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2078 * encoding.
2080 * If you know the whole pathname of the file you should use
2081 * g_filename_display_basename(), since that allows location-based
2082 * translation of filenames.
2084 * Return value: a newly allocated string containing
2085 * a rendition of the filename in valid UTF-8
2087 * Since: 2.6
2089 gchar *
2090 g_filename_display_name (const gchar *filename)
2092 gint i;
2093 const gchar **charsets;
2094 gchar *display_name = NULL;
2095 gboolean is_utf8;
2097 is_utf8 = g_get_filename_charsets (&charsets);
2099 if (is_utf8)
2101 if (g_utf8_validate (filename, -1, NULL))
2102 display_name = g_strdup (filename);
2105 if (!display_name)
2107 /* Try to convert from the filename charsets to UTF-8.
2108 * Skip the first charset if it is UTF-8.
2110 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2112 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2113 NULL, NULL, NULL);
2115 if (display_name)
2116 break;
2120 /* if all conversions failed, we replace invalid UTF-8
2121 * by a question mark
2123 if (!display_name)
2124 display_name = _g_utf8_make_valid (filename);
2126 return display_name;
2129 #define __G_CONVERT_C__
2130 #include "galiasdef.c"