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