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