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