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