Don't call g_set_error() unless the GError pointer is non-NULL. This
[platform/upstream/glib.git] / glib / gconvert.c
1 /* GLIB - Library of useful routines for C programming
2  *
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
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 #include "config.h"
24
25 #include <iconv.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #include "glib.h"
32 #include "gprintfint.h"
33 #include "gthreadinit.h"
34
35 #ifdef G_PLATFORM_WIN32
36 #define STRICT
37 #include <windows.h>
38 #undef STRICT
39 #endif
40
41 #include "glibintl.h"
42
43 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
44 #error GNU libiconv in use but included iconv.h not from libiconv
45 #endif
46 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
47 #error GNU libiconv not in use but included iconv.h is from libiconv
48 #endif
49
50 #include "galias.h"
51
52 GQuark 
53 g_convert_error_quark (void)
54 {
55   static GQuark quark;
56   if (!quark)
57     quark = g_quark_from_static_string ("g_convert_error");
58
59   return quark;
60 }
61
62 static gboolean
63 try_conversion (const char *to_codeset,
64                 const char *from_codeset,
65                 iconv_t    *cd)
66 {
67   *cd = iconv_open (to_codeset, from_codeset);
68
69   if (*cd == (iconv_t)-1 && errno == EINVAL)
70     return FALSE;
71   else
72     return TRUE;
73 }
74
75 static gboolean
76 try_to_aliases (const char **to_aliases,
77                 const char  *from_codeset,
78                 iconv_t     *cd)
79 {
80   if (to_aliases)
81     {
82       const char **p = to_aliases;
83       while (*p)
84         {
85           if (try_conversion (*p, from_codeset, cd))
86             return TRUE;
87
88           p++;
89         }
90     }
91
92   return FALSE;
93 }
94
95 extern const char **_g_charset_get_aliases (const char *canonical_name) G_GNUC_INTERNAL;
96
97 /**
98  * g_iconv_open:
99  * @to_codeset: destination codeset
100  * @from_codeset: source codeset
101  * 
102  * Same as the standard UNIX routine iconv_open(), but
103  * may be implemented via libiconv on UNIX flavors that lack
104  * a native implementation.
105  * 
106  * GLib provides g_convert() and g_locale_to_utf8() which are likely
107  * more convenient than the raw iconv wrappers.
108  * 
109  * Return value: a "conversion descriptor", or (GIConv)-1 if
110  *  opening the converter failed.
111  **/
112 GIConv
113 g_iconv_open (const gchar  *to_codeset,
114               const gchar  *from_codeset)
115 {
116   iconv_t cd;
117   
118   if (!try_conversion (to_codeset, from_codeset, &cd))
119     {
120       const char **to_aliases = _g_charset_get_aliases (to_codeset);
121       const char **from_aliases = _g_charset_get_aliases (from_codeset);
122
123       if (from_aliases)
124         {
125           const char **p = from_aliases;
126           while (*p)
127             {
128               if (try_conversion (to_codeset, *p, &cd))
129                 goto out;
130
131               if (try_to_aliases (to_aliases, *p, &cd))
132                 goto out;
133
134               p++;
135             }
136         }
137
138       if (try_to_aliases (to_aliases, from_codeset, &cd))
139         goto out;
140     }
141
142  out:
143   return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
144 }
145
146 /**
147  * g_iconv:
148  * @converter: conversion descriptor from g_iconv_open()
149  * @inbuf: bytes to convert
150  * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
151  * @outbuf: converted output bytes
152  * @outbytes_left: inout parameter, bytes available to fill in @outbuf
153  * 
154  * Same as the standard UNIX routine iconv(), but
155  * may be implemented via libiconv on UNIX flavors that lack
156  * a native implementation.
157  *
158  * GLib provides g_convert() and g_locale_to_utf8() which are likely
159  * more convenient than the raw iconv wrappers.
160  * 
161  * Return value: count of non-reversible conversions, or -1 on error
162  **/
163 size_t 
164 g_iconv (GIConv   converter,
165          gchar  **inbuf,
166          gsize   *inbytes_left,
167          gchar  **outbuf,
168          gsize   *outbytes_left)
169 {
170   iconv_t cd = (iconv_t)converter;
171
172   return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
173 }
174
175 /**
176  * g_iconv_close:
177  * @converter: a conversion descriptor from g_iconv_open()
178  *
179  * Same as the standard UNIX routine iconv_close(), but
180  * may be implemented via libiconv on UNIX flavors that lack
181  * a native implementation. Should be called to clean up
182  * the conversion descriptor from g_iconv_open() when
183  * you are done converting things.
184  *
185  * GLib provides g_convert() and g_locale_to_utf8() which are likely
186  * more convenient than the raw iconv wrappers.
187  * 
188  * Return value: -1 on error, 0 on success
189  **/
190 gint
191 g_iconv_close (GIConv converter)
192 {
193   iconv_t cd = (iconv_t)converter;
194
195   return iconv_close (cd);
196 }
197
198
199 #define ICONV_CACHE_SIZE   (16)
200
201 struct _iconv_cache_bucket {
202   gchar *key;
203   guint32 refcount;
204   gboolean used;
205   GIConv cd;
206 };
207
208 static GList *iconv_cache_list;
209 static GHashTable *iconv_cache;
210 static GHashTable *iconv_open_hash;
211 static guint iconv_cache_size = 0;
212 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
213
214 /* caller *must* hold the iconv_cache_lock */
215 static void
216 iconv_cache_init (void)
217 {
218   static gboolean initialized = FALSE;
219   
220   if (initialized)
221     return;
222   
223   iconv_cache_list = NULL;
224   iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
225   iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
226   
227   initialized = TRUE;
228 }
229
230
231 /**
232  * iconv_cache_bucket_new:
233  * @key: cache key
234  * @cd: iconv descriptor
235  *
236  * Creates a new cache bucket, inserts it into the cache and
237  * increments the cache size.
238  *
239  * Returns a pointer to the newly allocated cache bucket.
240  **/
241 static struct _iconv_cache_bucket *
242 iconv_cache_bucket_new (const gchar *key, GIConv cd)
243 {
244   struct _iconv_cache_bucket *bucket;
245   
246   bucket = g_new (struct _iconv_cache_bucket, 1);
247   bucket->key = g_strdup (key);
248   bucket->refcount = 1;
249   bucket->used = TRUE;
250   bucket->cd = cd;
251   
252   g_hash_table_insert (iconv_cache, bucket->key, bucket);
253   
254   /* FIXME: if we sorted the list so items with few refcounts were
255      first, then we could expire them faster in iconv_cache_expire_unused () */
256   iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
257   
258   iconv_cache_size++;
259   
260   return bucket;
261 }
262
263
264 /**
265  * iconv_cache_bucket_expire:
266  * @node: cache bucket's node
267  * @bucket: cache bucket
268  *
269  * Expires a single cache bucket @bucket. This should only ever be
270  * called on a bucket that currently has no used iconv descriptors
271  * open.
272  *
273  * @node is not a required argument. If @node is not supplied, we
274  * search for it ourselves.
275  **/
276 static void
277 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
278 {
279   g_hash_table_remove (iconv_cache, bucket->key);
280   
281   if (node == NULL)
282     node = g_list_find (iconv_cache_list, bucket);
283   
284   g_assert (node != NULL);
285   
286   if (node->prev)
287     {
288       node->prev->next = node->next;
289       if (node->next)
290         node->next->prev = node->prev;
291     }
292   else
293     {
294       iconv_cache_list = node->next;
295       if (node->next)
296         node->next->prev = NULL;
297     }
298   
299   g_list_free_1 (node);
300   
301   g_free (bucket->key);
302   g_iconv_close (bucket->cd);
303   g_free (bucket);
304   
305   iconv_cache_size--;
306 }
307
308
309 /**
310  * iconv_cache_expire_unused:
311  *
312  * Expires as many unused cache buckets as it needs to in order to get
313  * the total number of buckets < ICONV_CACHE_SIZE.
314  **/
315 static void
316 iconv_cache_expire_unused (void)
317 {
318   struct _iconv_cache_bucket *bucket;
319   GList *node, *next;
320   
321   node = iconv_cache_list;
322   while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
323     {
324       next = node->next;
325       
326       bucket = node->data;
327       if (bucket->refcount == 0)
328         iconv_cache_bucket_expire (node, bucket);
329       
330       node = next;
331     }
332 }
333
334 static GIConv
335 open_converter (const gchar *to_codeset,
336                 const gchar *from_codeset,
337                 GError     **error)
338 {
339   struct _iconv_cache_bucket *bucket;
340   gchar *key;
341   GIConv cd;
342   
343   /* create our key */
344   key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
345   _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
346   
347   G_LOCK (iconv_cache_lock);
348   
349   /* make sure the cache has been initialized */
350   iconv_cache_init ();
351   
352   bucket = g_hash_table_lookup (iconv_cache, key);
353   if (bucket)
354     {
355       if (bucket->used)
356         {
357           cd = g_iconv_open (to_codeset, from_codeset);
358           if (cd == (GIConv) -1)
359             goto error;
360         }
361       else
362         {
363           /* Apparently iconv on Solaris <= 7 segfaults if you pass in
364            * NULL for anything but inbuf; work around that. (NULL outbuf
365            * or NULL *outbuf is allowed by Unix98.)
366            */
367           gsize inbytes_left = 0;
368           gchar *outbuf = NULL;
369           gsize outbytes_left = 0;
370                 
371           cd = bucket->cd;
372           bucket->used = TRUE;
373           
374           /* reset the descriptor */
375           g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
376         }
377       
378       bucket->refcount++;
379     }
380   else
381     {
382       cd = g_iconv_open (to_codeset, from_codeset);
383       if (cd == (GIConv) -1)
384         goto error;
385       
386       iconv_cache_expire_unused ();
387       
388       bucket = iconv_cache_bucket_new (key, cd);
389     }
390   
391   g_hash_table_insert (iconv_open_hash, cd, bucket->key);
392   
393   G_UNLOCK (iconv_cache_lock);
394   
395   return cd;
396   
397  error:
398   
399   G_UNLOCK (iconv_cache_lock);
400   
401   /* Something went wrong.  */
402   if (error)
403     {
404       if (errno == EINVAL)
405         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
406                      _("Conversion from character set '%s' to '%s' is not supported"),
407                      from_codeset, to_codeset);
408       else
409         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
410                      _("Could not open converter from '%s' to '%s'"),
411                      from_codeset, to_codeset);
412     }
413   
414   return cd;
415 }
416
417 static int
418 close_converter (GIConv converter)
419 {
420   struct _iconv_cache_bucket *bucket;
421   const gchar *key;
422   GIConv cd;
423   
424   cd = converter;
425   
426   if (cd == (GIConv) -1)
427     return 0;
428   
429   G_LOCK (iconv_cache_lock);
430   
431   key = g_hash_table_lookup (iconv_open_hash, cd);
432   if (key)
433     {
434       g_hash_table_remove (iconv_open_hash, cd);
435       
436       bucket = g_hash_table_lookup (iconv_cache, key);
437       g_assert (bucket);
438       
439       bucket->refcount--;
440       
441       if (cd == bucket->cd)
442         bucket->used = FALSE;
443       else
444         g_iconv_close (cd);
445       
446       if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
447         {
448           /* expire this cache bucket */
449           iconv_cache_bucket_expire (NULL, bucket);
450         }
451     }
452   else
453     {
454       G_UNLOCK (iconv_cache_lock);
455       
456       g_warning ("This iconv context wasn't opened using open_converter");
457       
458       return g_iconv_close (converter);
459     }
460   
461   G_UNLOCK (iconv_cache_lock);
462   
463   return 0;
464 }
465
466
467 /**
468  * g_convert:
469  * @str:           the string to convert
470  * @len:           the length of the string, or -1 if the string is 
471  *                 nul-terminated<footnote id="nul-unsafe">
472                      <para>
473                        Note that some encodings may allow nul bytes to 
474                        occur inside strings. In that case, using -1 for 
475                        the @len parameter is unsafe.
476                      </para>
477                    </footnote>. 
478  * @to_codeset:    name of character set into which to convert @str
479  * @from_codeset:  character set of @str.
480  * @bytes_read:    location to store the number of bytes in the
481  *                 input string that were successfully converted, or %NULL.
482  *                 Even if the conversion was successful, this may be 
483  *                 less than @len if there were partial characters
484  *                 at the end of the input. If the error
485  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
486  *                 stored will the byte offset after the last valid
487  *                 input sequence.
488  * @bytes_written: the number of bytes stored in the output buffer (not 
489  *                 including the terminating nul).
490  * @error:         location to store the error occuring, or %NULL to ignore
491  *                 errors. Any of the errors in #GConvertError may occur.
492  *
493  * Converts a string from one character set to another.
494  *
495  * Return value: If the conversion was successful, a newly allocated
496  *               nul-terminated string, which must be freed with
497  *               g_free(). Otherwise %NULL and @error will be set.
498  **/
499 gchar*
500 g_convert (const gchar *str,
501            gssize       len,  
502            const gchar *to_codeset,
503            const gchar *from_codeset,
504            gsize       *bytes_read, 
505            gsize       *bytes_written, 
506            GError     **error)
507 {
508   gchar *res;
509   GIConv cd;
510   
511   g_return_val_if_fail (str != NULL, NULL);
512   g_return_val_if_fail (to_codeset != NULL, NULL);
513   g_return_val_if_fail (from_codeset != NULL, NULL);
514   
515   cd = open_converter (to_codeset, from_codeset, error);
516
517   if (cd == (GIConv) -1)
518     {
519       if (bytes_read)
520         *bytes_read = 0;
521       
522       if (bytes_written)
523         *bytes_written = 0;
524       
525       return NULL;
526     }
527
528   res = g_convert_with_iconv (str, len, cd,
529                               bytes_read, bytes_written,
530                               error);
531   
532   close_converter (cd);
533
534   return res;
535 }
536
537 /**
538  * g_convert_with_iconv:
539  * @str:           the string to convert
540  * @len:           the length of the string, or -1 if the string is 
541  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
542  * @converter:     conversion descriptor from g_iconv_open()
543  * @bytes_read:    location to store the number of bytes in the
544  *                 input string that were successfully converted, or %NULL.
545  *                 Even if the conversion was successful, this may be 
546  *                 less than @len if there were partial characters
547  *                 at the end of the input. If the error
548  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
549  *                 stored will the byte offset after the last valid
550  *                 input sequence.
551  * @bytes_written: the number of bytes stored in the output buffer (not 
552  *                 including the terminating nul).
553  * @error:         location to store the error occuring, or %NULL to ignore
554  *                 errors. Any of the errors in #GConvertError may occur.
555  *
556  * Converts a string from one character set to another.
557  *
558  * Return value: If the conversion was successful, a newly allocated
559  *               nul-terminated string, which must be freed with
560  *               g_free(). Otherwise %NULL and @error will be set.
561  **/
562 gchar*
563 g_convert_with_iconv (const gchar *str,
564                       gssize       len,
565                       GIConv       converter,
566                       gsize       *bytes_read, 
567                       gsize       *bytes_written, 
568                       GError     **error)
569 {
570   gchar *dest;
571   gchar *outp;
572   const gchar *p;
573   gsize inbytes_remaining;
574   gsize outbytes_remaining;
575   gsize err;
576   gsize outbuf_size;
577   gboolean have_error = FALSE;
578   
579   g_return_val_if_fail (str != NULL, NULL);
580   g_return_val_if_fail (converter != (GIConv) -1, NULL);
581      
582   if (len < 0)
583     len = strlen (str);
584
585   p = str;
586   inbytes_remaining = len;
587   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
588   
589   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
590   outp = dest = g_malloc (outbuf_size);
591
592  again:
593   
594   err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
595
596   if (err == (size_t) -1)
597     {
598       switch (errno)
599         {
600         case EINVAL:
601           /* Incomplete text, do not report an error */
602           break;
603         case E2BIG:
604           {
605             size_t used = outp - dest;
606
607             outbuf_size *= 2;
608             dest = g_realloc (dest, outbuf_size);
609                 
610             outp = dest + used;
611             outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
612
613             goto again;
614           }
615         case EILSEQ:
616           if (error)
617             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
618                          _("Invalid byte sequence in conversion input"));
619           have_error = TRUE;
620           break;
621         default:
622           if (error)
623             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
624                          _("Error during conversion: %s"),
625                          g_strerror (errno));
626           have_error = TRUE;
627           break;
628         }
629     }
630
631   *outp = '\0';
632   
633   if (bytes_read)
634     *bytes_read = p - str;
635   else
636     {
637       if ((p - str) != len) 
638         {
639           if (!have_error)
640             {
641               if (error)
642                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
643                              _("Partial character sequence at end of input"));
644               have_error = TRUE;
645             }
646         }
647     }
648
649   if (bytes_written)
650     *bytes_written = outp - dest;       /* Doesn't include '\0' */
651
652   if (have_error)
653     {
654       g_free (dest);
655       return NULL;
656     }
657   else
658     return dest;
659 }
660
661 /**
662  * g_convert_with_fallback:
663  * @str:          the string to convert
664  * @len:          the length of the string, or -1 if the string is 
665  *                nul-terminated<footnoteref linkend="nul-unsafe"/>. 
666  * @to_codeset:   name of character set into which to convert @str
667  * @from_codeset: character set of @str.
668  * @fallback:     UTF-8 string to use in place of character not
669  *                present in the target encoding. (The string must be
670  *                representable in the target encoding). 
671                   If %NULL, characters not in the target encoding will 
672                   be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
673  * @bytes_read:   location to store the number of bytes in the
674  *                input string that were successfully converted, or %NULL.
675  *                Even if the conversion was successful, this may be 
676  *                less than @len if there were partial characters
677  *                at the end of the input.
678  * @bytes_written: the number of bytes stored in the output buffer (not 
679  *                including the terminating nul).
680  * @error:        location to store the error occuring, or %NULL to ignore
681  *                errors. Any of the errors in #GConvertError may occur.
682  *
683  * Converts a string from one character set to another, possibly
684  * including fallback sequences for characters not representable
685  * in the output. Note that it is not guaranteed that the specification
686  * for the fallback sequences in @fallback will be honored. Some
687  * systems may do a approximate conversion from @from_codeset
688  * to @to_codeset in their iconv() functions, 
689  * in which case GLib will simply return that approximate conversion.
690  *
691  * Return value: If the conversion was successful, a newly allocated
692  *               nul-terminated string, which must be freed with
693  *               g_free(). Otherwise %NULL and @error will be set.
694  **/
695 gchar*
696 g_convert_with_fallback (const gchar *str,
697                          gssize       len,    
698                          const gchar *to_codeset,
699                          const gchar *from_codeset,
700                          gchar       *fallback,
701                          gsize       *bytes_read,
702                          gsize       *bytes_written,
703                          GError     **error)
704 {
705   gchar *utf8;
706   gchar *dest;
707   gchar *outp;
708   const gchar *insert_str = NULL;
709   const gchar *p;
710   gsize inbytes_remaining;   
711   const gchar *save_p = NULL;
712   gsize save_inbytes = 0;
713   gsize outbytes_remaining; 
714   gsize err;
715   GIConv cd;
716   gsize outbuf_size;
717   gboolean have_error = FALSE;
718   gboolean done = FALSE;
719
720   GError *local_error = NULL;
721   
722   g_return_val_if_fail (str != NULL, NULL);
723   g_return_val_if_fail (to_codeset != NULL, NULL);
724   g_return_val_if_fail (from_codeset != NULL, NULL);
725      
726   if (len < 0)
727     len = strlen (str);
728   
729   /* Try an exact conversion; we only proceed if this fails
730    * due to an illegal sequence in the input string.
731    */
732   dest = g_convert (str, len, to_codeset, from_codeset, 
733                     bytes_read, bytes_written, &local_error);
734   if (!local_error)
735     return dest;
736
737   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
738     {
739       g_propagate_error (error, local_error);
740       return NULL;
741     }
742   else
743     g_error_free (local_error);
744
745   local_error = NULL;
746   
747   /* No go; to proceed, we need a converter from "UTF-8" to
748    * to_codeset, and the string as UTF-8.
749    */
750   cd = open_converter (to_codeset, "UTF-8", error);
751   if (cd == (GIConv) -1)
752     {
753       if (bytes_read)
754         *bytes_read = 0;
755       
756       if (bytes_written)
757         *bytes_written = 0;
758       
759       return NULL;
760     }
761
762   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
763                     bytes_read, &inbytes_remaining, error);
764   if (!utf8)
765     {
766       close_converter (cd);
767       if (bytes_written)
768         *bytes_written = 0;
769       return NULL;
770     }
771
772   /* Now the heart of the code. We loop through the UTF-8 string, and
773    * whenever we hit an offending character, we form fallback, convert
774    * the fallback to the target codeset, and then go back to
775    * converting the original string after finishing with the fallback.
776    *
777    * The variables save_p and save_inbytes store the input state
778    * for the original string while we are converting the fallback
779    */
780   p = utf8;
781
782   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
783   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
784   outp = dest = g_malloc (outbuf_size);
785
786   while (!done && !have_error)
787     {
788       size_t inbytes_tmp = inbytes_remaining;
789       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
790       inbytes_remaining = inbytes_tmp;
791
792       if (err == (size_t) -1)
793         {
794           switch (errno)
795             {
796             case EINVAL:
797               g_assert_not_reached();
798               break;
799             case E2BIG:
800               {
801                 size_t used = outp - dest;
802
803                 outbuf_size *= 2;
804                 dest = g_realloc (dest, outbuf_size);
805                 
806                 outp = dest + used;
807                 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
808                 
809                 break;
810               }
811             case EILSEQ:
812               if (save_p)
813                 {
814                   /* Error converting fallback string - fatal
815                    */
816                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
817                                _("Cannot convert fallback '%s' to codeset '%s'"),
818                                insert_str, to_codeset);
819                   have_error = TRUE;
820                   break;
821                 }
822               else
823                 {
824                   if (!fallback)
825                     { 
826                       gunichar ch = g_utf8_get_char (p);
827                       insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
828                                                     ch);
829                     }
830                   else
831                     insert_str = fallback;
832                   
833                   save_p = g_utf8_next_char (p);
834                   save_inbytes = inbytes_remaining - (save_p - p);
835                   p = insert_str;
836                   inbytes_remaining = strlen (p);
837                 }
838               break;
839             default:
840               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
841                            _("Error during conversion: %s"),
842                            g_strerror (errno));
843               have_error = TRUE;
844               break;
845             }
846         }
847       else
848         {
849           if (save_p)
850             {
851               if (!fallback)
852                 g_free ((gchar *)insert_str);
853               p = save_p;
854               inbytes_remaining = save_inbytes;
855               save_p = NULL;
856             }
857           else
858             done = TRUE;
859         }
860     }
861
862   /* Cleanup
863    */
864   *outp = '\0';
865   
866   close_converter (cd);
867
868   if (bytes_written)
869     *bytes_written = outp - dest;       /* Doesn't include '\0' */
870
871   g_free (utf8);
872
873   if (have_error)
874     {
875       if (save_p && !fallback)
876         g_free ((gchar *)insert_str);
877       g_free (dest);
878       return NULL;
879     }
880   else
881     return dest;
882 }
883
884 /*
885  * g_locale_to_utf8
886  *
887  * 
888  */
889
890 static gchar *
891 strdup_len (const gchar *string,
892             gssize       len,
893             gsize       *bytes_written,
894             gsize       *bytes_read,
895             GError      **error)
896          
897 {
898   gsize real_len;
899
900   if (!g_utf8_validate (string, len, NULL))
901     {
902       if (bytes_read)
903         *bytes_read = 0;
904       if (bytes_written)
905         *bytes_written = 0;
906
907       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
908                    _("Invalid byte sequence in conversion input"));
909       return NULL;
910     }
911   
912   if (len < 0)
913     real_len = strlen (string);
914   else
915     {
916       real_len = 0;
917       
918       while (real_len < len && string[real_len])
919         real_len++;
920     }
921   
922   if (bytes_read)
923     *bytes_read = real_len;
924   if (bytes_written)
925     *bytes_written = real_len;
926
927   return g_strndup (string, real_len);
928 }
929
930 /**
931  * g_locale_to_utf8:
932  * @opsysstring:   a string in the encoding of the current locale. On Windows
933  *                 this means the system codepage.
934  * @len:           the length of the string, or -1 if the string is
935  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
936  * @bytes_read:    location to store the number of bytes in the
937  *                 input string that were successfully converted, or %NULL.
938  *                 Even if the conversion was successful, this may be 
939  *                 less than @len if there were partial characters
940  *                 at the end of the input. If the error
941  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
942  *                 stored will the byte offset after the last valid
943  *                 input sequence.
944  * @bytes_written: the number of bytes stored in the output buffer (not 
945  *                 including the terminating nul).
946  * @error:         location to store the error occuring, or %NULL to ignore
947  *                 errors. Any of the errors in #GConvertError may occur.
948  * 
949  * Converts a string which is in the encoding used for strings by
950  * the C runtime (usually the same as that used by the operating
951  * system) in the current locale into a UTF-8 string.
952  * 
953  * Return value: The converted string, or %NULL on an error.
954  **/
955 gchar *
956 g_locale_to_utf8 (const gchar  *opsysstring,
957                   gssize        len,            
958                   gsize        *bytes_read,    
959                   gsize        *bytes_written,
960                   GError      **error)
961 {
962   const char *charset;
963
964   if (g_get_charset (&charset))
965     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
966   else
967     return g_convert (opsysstring, len, 
968                       "UTF-8", charset, bytes_read, bytes_written, error);
969 }
970
971 /**
972  * g_locale_from_utf8:
973  * @utf8string:    a UTF-8 encoded string 
974  * @len:           the length of the string, or -1 if the string is
975  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
976  * @bytes_read:    location to store the number of bytes in the
977  *                 input string that were successfully converted, or %NULL.
978  *                 Even if the conversion was successful, this may be 
979  *                 less than @len if there were partial characters
980  *                 at the end of the input. If the error
981  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
982  *                 stored will the byte offset after the last valid
983  *                 input sequence.
984  * @bytes_written: the number of bytes stored in the output buffer (not 
985  *                 including the terminating nul).
986  * @error:         location to store the error occuring, or %NULL to ignore
987  *                 errors. Any of the errors in #GConvertError may occur.
988  * 
989  * Converts a string from UTF-8 to the encoding used for strings by
990  * the C runtime (usually the same as that used by the operating
991  * system) in the current locale.
992  * 
993  * Return value: The converted string, or %NULL on an error.
994  **/
995 gchar *
996 g_locale_from_utf8 (const gchar *utf8string,
997                     gssize       len,            
998                     gsize       *bytes_read,    
999                     gsize       *bytes_written,
1000                     GError     **error)
1001 {
1002   const gchar *charset;
1003
1004   if (g_get_charset (&charset))
1005     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1006   else
1007     return g_convert (utf8string, len,
1008                       charset, "UTF-8", bytes_read, bytes_written, error);
1009 }
1010
1011 #ifndef G_PLATFORM_WIN32
1012
1013 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1014
1015 struct _GFilenameCharsetCache {
1016   gboolean is_utf8;
1017   gchar *charset;
1018   gchar **filename_charsets;
1019 };
1020
1021 static void
1022 filename_charset_cache_free (gpointer data)
1023 {
1024   GFilenameCharsetCache *cache = data;
1025   g_free (cache->charset);
1026   g_strfreev (cache->filename_charsets);
1027   g_free (cache);
1028 }
1029
1030 /**
1031  * g_get_filename_charsets:
1032  * @charsets: return location for the %NULL-terminated list of encoding names
1033  *
1034  * Determines the preferred character sets used for filenames.
1035  * The first character set from the @charsets is the filename encoding, the
1036  * subsequent character sets are used when trying to generate a displayable
1037  * representation of a filename, see g_filename_display_name().
1038  *
1039  * On Unix, the character sets are determined by consulting the
1040  * environment variables <envar>G_FILENAME_ENCODING</envar> and
1041  * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1042  * used in the GLib API is always UTF-8 and said environment variables
1043  * have no effect.
1044  *
1045  * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
1046  * of character set names. The special token "@locale" is taken to mean the 
1047  * character set for the current locale. If <envar>G_FILENAME_ENCODING</envar> 
1048  * is not set, but <envar>G_BROKEN_FILENAMES</envar> is, the character set of 
1049  * the current locale is taken as the filename encoding. If neither environment
1050  * variable is set, UTF-8 is taken as the filename encoding, but the character
1051  * set of the current locale is also put in the list of encodings.
1052  *
1053  * The returned @charsets belong to GLib and must not be freed.
1054  *
1055  * Note that on Unix, regardless of the locale character set or
1056  * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present on a
1057  * system might be in any random encoding or just gibberish.
1058  *
1059  * Return value: %TRUE if the filename encoding is UTF-8.
1060  * 
1061  * Since: 2.6
1062  */
1063 gboolean
1064 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1065 {
1066   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1067   GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1068   const gchar *charset;
1069
1070   if (!cache)
1071     {
1072       cache = g_new0 (GFilenameCharsetCache, 1);
1073       g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1074     }
1075
1076   g_get_charset (&charset);
1077
1078   if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1079     {
1080       const gchar *new_charset;
1081       gchar *p;
1082       gint i;
1083
1084       g_free (cache->charset);
1085       g_strfreev (cache->filename_charsets);
1086       cache->charset = g_strdup (charset);
1087       
1088       p = getenv ("G_FILENAME_ENCODING");
1089       if (p != NULL && p[0] != '\0') 
1090         {
1091           cache->filename_charsets = g_strsplit (p, ",", 0);
1092           cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1093
1094           for (i = 0; cache->filename_charsets[i]; i++)
1095             {
1096               if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1097                 {
1098                   g_get_charset (&new_charset);
1099                   g_free (cache->filename_charsets[i]);
1100                   cache->filename_charsets[i] = g_strdup (new_charset);
1101                 }
1102             }
1103         }
1104       else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1105         {
1106           cache->filename_charsets = g_new0 (gchar *, 2);
1107           cache->is_utf8 = g_get_charset (&new_charset);
1108           cache->filename_charsets[0] = g_strdup (new_charset);
1109         }
1110       else 
1111         {
1112           cache->filename_charsets = g_new0 (gchar *, 3);
1113           cache->is_utf8 = TRUE;
1114           cache->filename_charsets[0] = g_strdup ("UTF-8");
1115           if (!g_get_charset (&new_charset))
1116             cache->filename_charsets[1] = g_strdup (new_charset);
1117         }
1118     }
1119
1120   if (filename_charsets)
1121     *filename_charsets = (const gchar **)cache->filename_charsets;
1122
1123   return cache->is_utf8;
1124 }
1125
1126 #else /* G_PLATFORM_WIN32 */
1127
1128 gboolean
1129 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets) 
1130 {
1131   static const gchar *charsets[] = {
1132     "UTF-8",
1133     NULL
1134   };
1135
1136 #ifdef G_OS_WIN32
1137   /* On Windows GLib pretends that the filename charset is UTF-8 */
1138   if (filename_charsets)
1139     *filename_charsets = charsets;
1140
1141   return TRUE;
1142 #else
1143   gboolean result;
1144
1145   /* Cygwin works like before */
1146   result = g_get_charset (&(charsets[0]));
1147
1148   if (filename_charsets)
1149     *filename_charsets = charsets;
1150
1151   return result;
1152 #endif
1153 }
1154
1155 #endif /* G_PLATFORM_WIN32 */
1156
1157 static gboolean
1158 get_filename_charset (const gchar **filename_charset)
1159 {
1160   const gchar **charsets;
1161   gboolean is_utf8;
1162   
1163   is_utf8 = g_get_filename_charsets (&charsets);
1164
1165   if (filename_charset)
1166     *filename_charset = charsets[0];
1167   
1168   return is_utf8;
1169 }
1170
1171 /* This is called from g_thread_init(). It's used to
1172  * initialize some static data in a threadsafe way.
1173  */
1174 void 
1175 _g_convert_thread_init (void)
1176 {
1177   const gchar **dummy;
1178   (void) g_get_filename_charsets (&dummy);
1179 }
1180
1181 /**
1182  * g_filename_to_utf8:
1183  * @opsysstring:   a string in the encoding for filenames
1184  * @len:           the length of the string, or -1 if the string is
1185  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1186  * @bytes_read:    location to store the number of bytes in the
1187  *                 input string that were successfully converted, or %NULL.
1188  *                 Even if the conversion was successful, this may be 
1189  *                 less than @len if there were partial characters
1190  *                 at the end of the input. If the error
1191  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1192  *                 stored will the byte offset after the last valid
1193  *                 input sequence.
1194  * @bytes_written: the number of bytes stored in the output buffer (not 
1195  *                 including the terminating nul).
1196  * @error:         location to store the error occuring, or %NULL to ignore
1197  *                 errors. Any of the errors in #GConvertError may occur.
1198  * 
1199  * Converts a string which is in the encoding used by GLib for
1200  * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1201  * for filenames.
1202  * 
1203  * Return value: The converted string, or %NULL on an error.
1204  **/
1205 gchar*
1206 g_filename_to_utf8 (const gchar *opsysstring, 
1207                     gssize       len,           
1208                     gsize       *bytes_read,   
1209                     gsize       *bytes_written,
1210                     GError     **error)
1211 {
1212   const gchar *charset;
1213
1214   if (get_filename_charset (&charset))
1215     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1216   else
1217     return g_convert (opsysstring, len, 
1218                       "UTF-8", charset, bytes_read, bytes_written, error);
1219 }
1220
1221 #ifdef G_OS_WIN32
1222
1223 #undef g_filename_to_utf8
1224
1225 /* Binary compatibility version. Not for newly compiled code. */
1226
1227 gchar*
1228 g_filename_to_utf8 (const gchar *opsysstring, 
1229                     gssize       len,           
1230                     gsize       *bytes_read,   
1231                     gsize       *bytes_written,
1232                     GError     **error)
1233 {
1234   const gchar *charset;
1235
1236   if (g_get_charset (&charset))
1237     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1238   else
1239     return g_convert (opsysstring, len, 
1240                       "UTF-8", charset, bytes_read, bytes_written, error);
1241 }
1242
1243 #endif
1244
1245 /**
1246  * g_filename_from_utf8:
1247  * @utf8string:    a UTF-8 encoded string.
1248  * @len:           the length of the string, or -1 if the string is
1249  *                 nul-terminated.
1250  * @bytes_read:    location to store the number of bytes in the
1251  *                 input string that were successfully converted, or %NULL.
1252  *                 Even if the conversion was successful, this may be 
1253  *                 less than @len if there were partial characters
1254  *                 at the end of the input. If the error
1255  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1256  *                 stored will the byte offset after the last valid
1257  *                 input sequence.
1258  * @bytes_written: the number of bytes stored in the output buffer (not 
1259  *                 including the terminating nul).
1260  * @error:         location to store the error occuring, or %NULL to ignore
1261  *                 errors. Any of the errors in #GConvertError may occur.
1262  * 
1263  * Converts a string from UTF-8 to the encoding GLib uses for
1264  * filenames. Note that on Windows GLib uses UTF-8 for filenames.
1265  * 
1266  * Return value: The converted string, or %NULL on an error.
1267  **/
1268 gchar*
1269 g_filename_from_utf8 (const gchar *utf8string,
1270                       gssize       len,            
1271                       gsize       *bytes_read,    
1272                       gsize       *bytes_written,
1273                       GError     **error)
1274 {
1275   const gchar *charset;
1276
1277   if (get_filename_charset (&charset))
1278     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1279   else
1280     return g_convert (utf8string, len,
1281                       charset, "UTF-8", bytes_read, bytes_written, error);
1282 }
1283
1284 #ifdef G_OS_WIN32
1285
1286 #undef g_filename_from_utf8
1287
1288 /* Binary compatibility version. Not for newly compiled code. */
1289
1290 gchar*
1291 g_filename_from_utf8 (const gchar *utf8string,
1292                       gssize       len,            
1293                       gsize       *bytes_read,    
1294                       gsize       *bytes_written,
1295                       GError     **error)
1296 {
1297   const gchar *charset;
1298
1299   if (g_get_charset (&charset))
1300     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1301   else
1302     return g_convert (utf8string, len,
1303                       charset, "UTF-8", bytes_read, bytes_written, error);
1304 }
1305
1306 #endif
1307
1308 /* Test of haystack has the needle prefix, comparing case
1309  * insensitive. haystack may be UTF-8, but needle must
1310  * contain only ascii. */
1311 static gboolean
1312 has_case_prefix (const gchar *haystack, const gchar *needle)
1313 {
1314   const gchar *h, *n;
1315   
1316   /* Eat one character at a time. */
1317   h = haystack;
1318   n = needle;
1319
1320   while (*n && *h &&
1321          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1322     {
1323       n++;
1324       h++;
1325     }
1326   
1327   return *n == '\0';
1328 }
1329
1330 typedef enum {
1331   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1332   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1333   UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1334   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1335   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1336 } UnsafeCharacterSet;
1337
1338 static const guchar acceptable[96] = {
1339   /* A table of the ASCII chars from space (32) to DEL (127) */
1340   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1341   0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1342   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1343   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1344   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1345   0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1346   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1347   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1348   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1349   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1350   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1351   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1352 };
1353
1354 static const gchar hex[16] = "0123456789ABCDEF";
1355
1356 /* Note: This escape function works on file: URIs, but if you want to
1357  * escape something else, please read RFC-2396 */
1358 static gchar *
1359 g_escape_uri_string (const gchar *string, 
1360                      UnsafeCharacterSet mask)
1361 {
1362 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1363
1364   const gchar *p;
1365   gchar *q;
1366   gchar *result;
1367   int c;
1368   gint unacceptable;
1369   UnsafeCharacterSet use_mask;
1370   
1371   g_return_val_if_fail (mask == UNSAFE_ALL
1372                         || mask == UNSAFE_ALLOW_PLUS
1373                         || mask == UNSAFE_PATH
1374                         || mask == UNSAFE_HOST
1375                         || mask == UNSAFE_SLASHES, NULL);
1376   
1377   unacceptable = 0;
1378   use_mask = mask;
1379   for (p = string; *p != '\0'; p++)
1380     {
1381       c = (guchar) *p;
1382       if (!ACCEPTABLE (c)) 
1383         unacceptable++;
1384     }
1385   
1386   result = g_malloc (p - string + unacceptable * 2 + 1);
1387   
1388   use_mask = mask;
1389   for (q = result, p = string; *p != '\0'; p++)
1390     {
1391       c = (guchar) *p;
1392       
1393       if (!ACCEPTABLE (c))
1394         {
1395           *q++ = '%'; /* means hex coming */
1396           *q++ = hex[c >> 4];
1397           *q++ = hex[c & 15];
1398         }
1399       else
1400         *q++ = *p;
1401     }
1402   
1403   *q = '\0';
1404   
1405   return result;
1406 }
1407
1408
1409 static gchar *
1410 g_escape_file_uri (const gchar *hostname,
1411                    const gchar *pathname)
1412 {
1413   char *escaped_hostname = NULL;
1414   char *escaped_path;
1415   char *res;
1416
1417 #ifdef G_OS_WIN32
1418   char *p, *backslash;
1419
1420   /* Turn backslashes into forward slashes. That's what Netscape
1421    * does, and they are actually more or less equivalent in Windows.
1422    */
1423   
1424   pathname = g_strdup (pathname);
1425   p = (char *) pathname;
1426   
1427   while ((backslash = strchr (p, '\\')) != NULL)
1428     {
1429       *backslash = '/';
1430       p = backslash + 1;
1431     }
1432 #endif
1433
1434   if (hostname && *hostname != '\0')
1435     {
1436       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1437     }
1438
1439   escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1440
1441   res = g_strconcat ("file://",
1442                      (escaped_hostname) ? escaped_hostname : "",
1443                      (*escaped_path != '/') ? "/" : "",
1444                      escaped_path,
1445                      NULL);
1446
1447 #ifdef G_OS_WIN32
1448   g_free ((char *) pathname);
1449 #endif
1450
1451   g_free (escaped_hostname);
1452   g_free (escaped_path);
1453   
1454   return res;
1455 }
1456
1457 static int
1458 unescape_character (const char *scanner)
1459 {
1460   int first_digit;
1461   int second_digit;
1462
1463   first_digit = g_ascii_xdigit_value (scanner[0]);
1464   if (first_digit < 0) 
1465     return -1;
1466   
1467   second_digit = g_ascii_xdigit_value (scanner[1]);
1468   if (second_digit < 0) 
1469     return -1;
1470   
1471   return (first_digit << 4) | second_digit;
1472 }
1473
1474 static gchar *
1475 g_unescape_uri_string (const char *escaped,
1476                        int         len,
1477                        const char *illegal_escaped_characters,
1478                        gboolean    ascii_must_not_be_escaped)
1479 {
1480   const gchar *in, *in_end;
1481   gchar *out, *result;
1482   int c;
1483   
1484   if (escaped == NULL)
1485     return NULL;
1486
1487   if (len < 0)
1488     len = strlen (escaped);
1489
1490   result = g_malloc (len + 1);
1491   
1492   out = result;
1493   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1494     {
1495       c = *in;
1496
1497       if (c == '%')
1498         {
1499           /* catch partial escape sequences past the end of the substring */
1500           if (in + 3 > in_end)
1501             break;
1502
1503           c = unescape_character (in + 1);
1504
1505           /* catch bad escape sequences and NUL characters */
1506           if (c <= 0)
1507             break;
1508
1509           /* catch escaped ASCII */
1510           if (ascii_must_not_be_escaped && c <= 0x7F)
1511             break;
1512
1513           /* catch other illegal escaped characters */
1514           if (strchr (illegal_escaped_characters, c) != NULL)
1515             break;
1516
1517           in += 2;
1518         }
1519
1520       *out++ = c;
1521     }
1522   
1523   g_assert (out - result <= len);
1524   *out = '\0';
1525
1526   if (in != in_end)
1527     {
1528       g_free (result);
1529       return NULL;
1530     }
1531
1532   return result;
1533 }
1534
1535 static gboolean
1536 is_asciialphanum (gunichar c)
1537 {
1538   return c <= 0x7F && g_ascii_isalnum (c);
1539 }
1540
1541 static gboolean
1542 is_asciialpha (gunichar c)
1543 {
1544   return c <= 0x7F && g_ascii_isalpha (c);
1545 }
1546
1547 /* allows an empty string */
1548 static gboolean
1549 hostname_validate (const char *hostname)
1550 {
1551   const char *p;
1552   gunichar c, first_char, last_char;
1553
1554   p = hostname;
1555   if (*p == '\0')
1556     return TRUE;
1557   do
1558     {
1559       /* read in a label */
1560       c = g_utf8_get_char (p);
1561       p = g_utf8_next_char (p);
1562       if (!is_asciialphanum (c))
1563         return FALSE;
1564       first_char = c;
1565       do
1566         {
1567           last_char = c;
1568           c = g_utf8_get_char (p);
1569           p = g_utf8_next_char (p);
1570         }
1571       while (is_asciialphanum (c) || c == '-');
1572       if (last_char == '-')
1573         return FALSE;
1574       
1575       /* if that was the last label, check that it was a toplabel */
1576       if (c == '\0' || (c == '.' && *p == '\0'))
1577         return is_asciialpha (first_char);
1578     }
1579   while (c == '.');
1580   return FALSE;
1581 }
1582
1583 /**
1584  * g_filename_from_uri:
1585  * @uri: a uri describing a filename (escaped, encoded in ASCII).
1586  * @hostname: Location to store hostname for the URI, or %NULL.
1587  *            If there is no hostname in the URI, %NULL will be
1588  *            stored in this location.
1589  * @error: location to store the error occuring, or %NULL to ignore
1590  *         errors. Any of the errors in #GConvertError may occur.
1591  * 
1592  * Converts an escaped ASCII-encoded URI to a local filename in the
1593  * encoding used for filenames. 
1594  * 
1595  * Return value: a newly-allocated string holding the resulting
1596  *               filename, or %NULL on an error.
1597  **/
1598 gchar *
1599 g_filename_from_uri (const gchar *uri,
1600                      gchar      **hostname,
1601                      GError     **error)
1602 {
1603   const char *path_part;
1604   const char *host_part;
1605   char *unescaped_hostname;
1606   char *result;
1607   char *filename;
1608   int offs;
1609 #ifdef G_OS_WIN32
1610   char *p, *slash;
1611 #endif
1612
1613   if (hostname)
1614     *hostname = NULL;
1615
1616   if (!has_case_prefix (uri, "file:/"))
1617     {
1618       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1619                    _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1620                    uri);
1621       return NULL;
1622     }
1623   
1624   path_part = uri + strlen ("file:");
1625   
1626   if (strchr (path_part, '#') != NULL)
1627     {
1628       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1629                    _("The local file URI '%s' may not include a '#'"),
1630                    uri);
1631       return NULL;
1632     }
1633         
1634   if (has_case_prefix (path_part, "///")) 
1635     path_part += 2;
1636   else if (has_case_prefix (path_part, "//"))
1637     {
1638       path_part += 2;
1639       host_part = path_part;
1640
1641       path_part = strchr (path_part, '/');
1642
1643       if (path_part == NULL)
1644         {
1645           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1646                        _("The URI '%s' is invalid"),
1647                        uri);
1648           return NULL;
1649         }
1650
1651       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1652
1653       if (unescaped_hostname == NULL ||
1654           !hostname_validate (unescaped_hostname))
1655         {
1656           g_free (unescaped_hostname);
1657           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1658                        _("The hostname of the URI '%s' is invalid"),
1659                        uri);
1660           return NULL;
1661         }
1662       
1663       if (hostname)
1664         *hostname = unescaped_hostname;
1665       else
1666         g_free (unescaped_hostname);
1667     }
1668
1669   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1670
1671   if (filename == NULL)
1672     {
1673       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1674                    _("The URI '%s' contains invalidly escaped characters"),
1675                    uri);
1676       return NULL;
1677     }
1678
1679   offs = 0;
1680 #ifdef G_OS_WIN32
1681   /* Drop localhost */
1682   if (hostname && *hostname != NULL &&
1683       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1684     {
1685       g_free (*hostname);
1686       *hostname = NULL;
1687     }
1688
1689   /* Turn slashes into backslashes, because that's the canonical spelling */
1690   p = filename;
1691   while ((slash = strchr (p, '/')) != NULL)
1692     {
1693       *slash = '\\';
1694       p = slash + 1;
1695     }
1696
1697   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1698    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1699    * the filename from the drive letter.
1700    */
1701   if (g_ascii_isalpha (filename[1]))
1702     {
1703       if (filename[2] == ':')
1704         offs = 1;
1705       else if (filename[2] == '|')
1706         {
1707           filename[2] = ':';
1708           offs = 1;
1709         }
1710     }
1711 #endif
1712
1713   result = g_strdup (filename + offs);
1714   g_free (filename);
1715
1716   return result;
1717 }
1718
1719 #ifdef G_OS_WIN32
1720
1721 #undef g_filename_from_uri
1722
1723 gchar *
1724 g_filename_from_uri (const gchar *uri,
1725                      gchar      **hostname,
1726                      GError     **error)
1727 {
1728   gchar *utf8_filename;
1729   gchar *retval = NULL;
1730
1731   utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1732   if (utf8_filename)
1733     {
1734       retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1735       g_free (utf8_filename);
1736     }
1737   return retval;
1738 }
1739
1740 #endif
1741
1742 /**
1743  * g_filename_to_uri:
1744  * @filename: an absolute filename specified in the GLib file name encoding,
1745  *            which is the on-disk file name bytes on Unix, and UTF-8 on 
1746  *            Windows
1747  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1748  * @error: location to store the error occuring, or %NULL to ignore
1749  *         errors. Any of the errors in #GConvertError may occur.
1750  * 
1751  * Converts an absolute filename to an escaped ASCII-encoded URI.
1752  * 
1753  * Return value: a newly-allocated string holding the resulting
1754  *               URI, or %NULL on an error.
1755  **/
1756 gchar *
1757 g_filename_to_uri (const gchar *filename,
1758                    const gchar *hostname,
1759                    GError     **error)
1760 {
1761   char *escaped_uri;
1762
1763   g_return_val_if_fail (filename != NULL, NULL);
1764
1765   if (!g_path_is_absolute (filename))
1766     {
1767       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1768                    _("The pathname '%s' is not an absolute path"),
1769                    filename);
1770       return NULL;
1771     }
1772
1773   if (hostname &&
1774       !(g_utf8_validate (hostname, -1, NULL)
1775         && hostname_validate (hostname)))
1776     {
1777       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1778                    _("Invalid hostname"));
1779       return NULL;
1780     }
1781   
1782 #ifdef G_OS_WIN32
1783   /* Don't use localhost unnecessarily */
1784   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1785     hostname = NULL;
1786 #endif
1787
1788   escaped_uri = g_escape_file_uri (hostname, filename);
1789
1790   return escaped_uri;
1791 }
1792
1793 #ifdef G_OS_WIN32
1794
1795 #undef g_filename_to_uri
1796
1797 gchar *
1798 g_filename_to_uri (const gchar *filename,
1799                    const gchar *hostname,
1800                    GError     **error)
1801 {
1802   gchar *utf8_filename;
1803   gchar *retval = NULL;
1804
1805   utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1806
1807   if (utf8_filename)
1808     {
1809       retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1810       g_free (utf8_filename);
1811     }
1812
1813   return retval;
1814 }
1815
1816 #endif
1817
1818 /**
1819  * g_uri_list_extract_uris:
1820  * @uri_list: an URI list 
1821  *
1822  * Splits an URI list conforming to the text/uri-list
1823  * mime type defined in RFC 2483 into individual URIs,
1824  * discarding any comments. The URIs are not validated.
1825  *
1826  * Returns: a newly allocated %NULL-terminated list of
1827  *   strings holding the individual URIs. The array should
1828  *   be freed with g_strfreev().
1829  *
1830  * Since: 2.6
1831  */
1832 gchar **
1833 g_uri_list_extract_uris (const gchar *uri_list)
1834 {
1835   GSList *uris, *u;
1836   const gchar *p, *q;
1837   gchar **result;
1838   gint n_uris = 0;
1839
1840   uris = NULL;
1841
1842   p = uri_list;
1843
1844   /* We don't actually try to validate the URI according to RFC
1845    * 2396, or even check for allowed characters - we just ignore
1846    * comments and trim whitespace off the ends.  We also
1847    * allow LF delimination as well as the specified CRLF.
1848    *
1849    * We do allow comments like specified in RFC 2483.
1850    */
1851   while (p)
1852     {
1853       if (*p != '#')
1854         {
1855           while (g_ascii_isspace (*p))
1856             p++;
1857
1858           q = p;
1859           while (*q && (*q != '\n') && (*q != '\r'))
1860             q++;
1861
1862           if (q > p)
1863             {
1864               q--;
1865               while (q > p && g_ascii_isspace (*q))
1866                 q--;
1867
1868               if (q > p)
1869                 {
1870                   uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1871                   n_uris++;
1872                 }
1873             }
1874         }
1875       p = strchr (p, '\n');
1876       if (p)
1877         p++;
1878     }
1879
1880   result = g_new (gchar *, n_uris + 1);
1881
1882   result[n_uris--] = NULL;
1883   for (u = uris; u; u = u->next)
1884     result[n_uris--] = u->data;
1885
1886   g_slist_free (uris);
1887
1888   return result;
1889 }
1890
1891 static gchar *
1892 make_valid_utf8 (const gchar *name)
1893 {
1894   GString *string;
1895   const gchar *remainder, *invalid;
1896   gint remaining_bytes, valid_bytes;
1897   
1898   string = NULL;
1899   remainder = name;
1900   remaining_bytes = strlen (name);
1901   
1902   while (remaining_bytes != 0) 
1903     {
1904       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1905         break;
1906       valid_bytes = invalid - remainder;
1907     
1908       if (string == NULL) 
1909         string = g_string_sized_new (remaining_bytes);
1910
1911       g_string_append_len (string, remainder, valid_bytes);
1912       g_string_append_c (string, '?');
1913       
1914       remaining_bytes -= valid_bytes + 1;
1915       remainder = invalid + 1;
1916     }
1917   
1918   if (string == NULL)
1919     return g_strdup (name);
1920   
1921   g_string_append (string, remainder);
1922   g_string_append (string, " (invalid encoding)");
1923
1924   g_assert (g_utf8_validate (string->str, -1, NULL));
1925   
1926   return g_string_free (string, FALSE);
1927 }
1928
1929 /**
1930  * g_filename_display_basename:
1931  * @filename: an absolute pathname in the GLib file name encoding
1932  *
1933  * Returns the display basename for the particular filename, guaranteed
1934  * to be valid UTF-8. The display name might not be identical to the filename,
1935  * for instance there might be problems converting it to UTF-8, and some files
1936  * can be translated in the display
1937  *
1938  * You must pass the whole absolute pathname to this functions so that
1939  * translation of well known locations can be done.
1940  *
1941  * This function is preferred over g_filename_display_name() if you know the
1942  * whole path, as it allows translation.
1943  *
1944  * Return value: a newly allocated string containing
1945  *   a rendition of the basename of the filename in valid UTF-8
1946  *
1947  * Since: 2.6
1948  **/
1949 gchar *
1950 g_filename_display_basename (const gchar *filename)
1951 {
1952   char *basename;
1953   char *display_name;
1954
1955   g_return_val_if_fail (filename != NULL, NULL);
1956   
1957   basename = g_path_get_basename (filename);
1958   display_name = g_filename_display_name (basename);
1959   g_free (basename);
1960   return display_name;
1961 }
1962
1963 /**
1964  * g_filename_display_name:
1965  * @filename: a pathname hopefully in the GLib file name encoding
1966  * 
1967  * Converts a filename into a valid UTF-8 string. The 
1968  * conversion is not necessarily reversible, so you 
1969  * should keep the original around and use the return
1970  * value of this function only for display purposes.
1971  * Unlike g_filename_to_utf8(), the result is guaranteed 
1972  * to be non-NULL even if the filename actually isn't in the GLib
1973  * file name encoding.
1974  *
1975  * If you know the whole pathname of the file you should use
1976  * g_filename_display_basename(), since that allows location-based
1977  * translation of filenames.
1978  *
1979  * Return value: a newly allocated string containing
1980  *   a rendition of the filename in valid UTF-8
1981  *
1982  * Since: 2.6
1983  **/
1984 gchar *
1985 g_filename_display_name (const gchar *filename)
1986 {
1987   gint i;
1988   const gchar **charsets;
1989   gchar *display_name = NULL;
1990   gboolean is_utf8;
1991  
1992   is_utf8 = g_get_filename_charsets (&charsets);
1993
1994   if (is_utf8)
1995     {
1996       if (g_utf8_validate (filename, -1, NULL))
1997         display_name = g_strdup (filename);
1998     }
1999   
2000   if (!display_name)
2001     {
2002       /* Try to convert from the filename charsets to UTF-8.
2003        * Skip the first charset if it is UTF-8.
2004        */
2005       for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2006         {
2007           display_name = g_convert (filename, -1, "UTF-8", charsets[i], 
2008                                     NULL, NULL, NULL);
2009
2010           if (display_name)
2011             break;
2012         }
2013     }
2014   
2015   /* if all conversions failed, we replace invalid UTF-8
2016    * by a question mark
2017    */
2018   if (!display_name) 
2019     display_name = make_valid_utf8 (filename);
2020
2021   return display_name;
2022 }
2023
2024 #define __G_CONVERT_C__
2025 #include "galiasdef.c"