Bug 556921 – gpoll.h breaks hal compilation
[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               if (error)
637                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
638                              _("Error during conversion: %s"),
639                              g_strerror (errno));
640               have_error = TRUE;
641               break;
642             }
643         }
644       else 
645         {
646           if (!reset)
647             {
648               /* call g_iconv with NULL inbuf to cleanup shift state */
649               reset = TRUE;
650               inbytes_remaining = 0;
651             }
652           else
653             done = TRUE;
654         }
655     }
656
657   *outp = '\0';
658   
659   if (bytes_read)
660     *bytes_read = p - str;
661   else
662     {
663       if ((p - str) != len) 
664         {
665           if (!have_error)
666             {
667               if (error)
668                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
669                                      _("Partial character sequence at end of input"));
670               have_error = TRUE;
671             }
672         }
673     }
674
675   if (bytes_written)
676     *bytes_written = outp - dest;       /* Doesn't include '\0' */
677
678   if (have_error)
679     {
680       g_free (dest);
681       return NULL;
682     }
683   else
684     return dest;
685 }
686
687 /**
688  * g_convert:
689  * @str:           the string to convert
690  * @len:           the length of the string, or -1 if the string is 
691  *                 nul-terminated<footnote id="nul-unsafe">
692                      <para>
693                        Note that some encodings may allow nul bytes to 
694                        occur inside strings. In that case, using -1 for 
695                        the @len parameter is unsafe.
696                      </para>
697                    </footnote>. 
698  * @to_codeset:    name of character set into which to convert @str
699  * @from_codeset:  character set of @str.
700  * @bytes_read:    location to store the number of bytes in the
701  *                 input string that were successfully converted, or %NULL.
702  *                 Even if the conversion was successful, this may be 
703  *                 less than @len if there were partial characters
704  *                 at the end of the input. If the error
705  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
706  *                 stored will the byte offset after the last valid
707  *                 input sequence.
708  * @bytes_written: the number of bytes stored in the output buffer (not 
709  *                 including the terminating nul).
710  * @error:         location to store the error occuring, or %NULL to ignore
711  *                 errors. Any of the errors in #GConvertError may occur.
712  *
713  * Converts a string from one character set to another.
714  *
715  * Note that you should use g_iconv() for streaming 
716  * conversions<footnoteref linkend="streaming-state"/>.
717  *
718  * Return value: If the conversion was successful, a newly allocated
719  *               nul-terminated string, which must be freed with
720  *               g_free(). Otherwise %NULL and @error will be set.
721  **/
722 gchar*
723 g_convert (const gchar *str,
724            gssize       len,  
725            const gchar *to_codeset,
726            const gchar *from_codeset,
727            gsize       *bytes_read, 
728            gsize       *bytes_written, 
729            GError     **error)
730 {
731   gchar *res;
732   GIConv cd;
733
734   g_return_val_if_fail (str != NULL, NULL);
735   g_return_val_if_fail (to_codeset != NULL, NULL);
736   g_return_val_if_fail (from_codeset != NULL, NULL);
737   
738   cd = open_converter (to_codeset, from_codeset, error);
739
740   if (cd == (GIConv) -1)
741     {
742       if (bytes_read)
743         *bytes_read = 0;
744       
745       if (bytes_written)
746         *bytes_written = 0;
747       
748       return NULL;
749     }
750
751   res = g_convert_with_iconv (str, len, cd,
752                               bytes_read, bytes_written,
753                               error);
754
755   close_converter (cd);
756
757   return res;
758 }
759
760 /**
761  * g_convert_with_fallback:
762  * @str:          the string to convert
763  * @len:          the length of the string, or -1 if the string is 
764  *                nul-terminated<footnoteref linkend="nul-unsafe"/>. 
765  * @to_codeset:   name of character set into which to convert @str
766  * @from_codeset: character set of @str.
767  * @fallback:     UTF-8 string to use in place of character not
768  *                present in the target encoding. (The string must be
769  *                representable in the target encoding). 
770                   If %NULL, characters not in the target encoding will 
771                   be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
772  * @bytes_read:   location to store the number of bytes in the
773  *                input string that were successfully converted, or %NULL.
774  *                Even if the conversion was successful, this may be 
775  *                less than @len if there were partial characters
776  *                at the end of the input.
777  * @bytes_written: the number of bytes stored in the output buffer (not 
778  *                including the terminating nul).
779  * @error:        location to store the error occuring, or %NULL to ignore
780  *                errors. Any of the errors in #GConvertError may occur.
781  *
782  * Converts a string from one character set to another, possibly
783  * including fallback sequences for characters not representable
784  * in the output. Note that it is not guaranteed that the specification
785  * for the fallback sequences in @fallback will be honored. Some
786  * systems may do an approximate conversion from @from_codeset
787  * to @to_codeset in their iconv() functions, 
788  * in which case GLib will simply return that approximate conversion.
789  *
790  * Note that you should use g_iconv() for streaming 
791  * conversions<footnoteref linkend="streaming-state"/>.
792  *
793  * Return value: If the conversion was successful, a newly allocated
794  *               nul-terminated string, which must be freed with
795  *               g_free(). Otherwise %NULL and @error will be set.
796  **/
797 gchar*
798 g_convert_with_fallback (const gchar *str,
799                          gssize       len,    
800                          const gchar *to_codeset,
801                          const gchar *from_codeset,
802                          gchar       *fallback,
803                          gsize       *bytes_read,
804                          gsize       *bytes_written,
805                          GError     **error)
806 {
807   gchar *utf8;
808   gchar *dest;
809   gchar *outp;
810   const gchar *insert_str = NULL;
811   const gchar *p;
812   gsize inbytes_remaining;   
813   const gchar *save_p = NULL;
814   gsize save_inbytes = 0;
815   gsize outbytes_remaining; 
816   gsize err;
817   GIConv cd;
818   gsize outbuf_size;
819   gboolean have_error = FALSE;
820   gboolean done = FALSE;
821
822   GError *local_error = NULL;
823   
824   g_return_val_if_fail (str != NULL, NULL);
825   g_return_val_if_fail (to_codeset != NULL, NULL);
826   g_return_val_if_fail (from_codeset != NULL, NULL);
827      
828   if (len < 0)
829     len = strlen (str);
830   
831   /* Try an exact conversion; we only proceed if this fails
832    * due to an illegal sequence in the input string.
833    */
834   dest = g_convert (str, len, to_codeset, from_codeset, 
835                     bytes_read, bytes_written, &local_error);
836   if (!local_error)
837     return dest;
838
839   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
840     {
841       g_propagate_error (error, local_error);
842       return NULL;
843     }
844   else
845     g_error_free (local_error);
846
847   local_error = NULL;
848   
849   /* No go; to proceed, we need a converter from "UTF-8" to
850    * to_codeset, and the string as UTF-8.
851    */
852   cd = open_converter (to_codeset, "UTF-8", error);
853   if (cd == (GIConv) -1)
854     {
855       if (bytes_read)
856         *bytes_read = 0;
857       
858       if (bytes_written)
859         *bytes_written = 0;
860       
861       return NULL;
862     }
863
864   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
865                     bytes_read, &inbytes_remaining, error);
866   if (!utf8)
867     {
868       close_converter (cd);
869       if (bytes_written)
870         *bytes_written = 0;
871       return NULL;
872     }
873
874   /* Now the heart of the code. We loop through the UTF-8 string, and
875    * whenever we hit an offending character, we form fallback, convert
876    * the fallback to the target codeset, and then go back to
877    * converting the original string after finishing with the fallback.
878    *
879    * The variables save_p and save_inbytes store the input state
880    * for the original string while we are converting the fallback
881    */
882   p = utf8;
883
884   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
885   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
886   outp = dest = g_malloc (outbuf_size);
887
888   while (!done && !have_error)
889     {
890       gsize inbytes_tmp = inbytes_remaining;
891       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
892       inbytes_remaining = inbytes_tmp;
893
894       if (err == (gsize) -1)
895         {
896           switch (errno)
897             {
898             case EINVAL:
899               g_assert_not_reached();
900               break;
901             case E2BIG:
902               {
903                 gsize used = outp - dest;
904
905                 outbuf_size *= 2;
906                 dest = g_realloc (dest, outbuf_size);
907                 
908                 outp = dest + used;
909                 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
910                 
911                 break;
912               }
913             case EILSEQ:
914               if (save_p)
915                 {
916                   /* Error converting fallback string - fatal
917                    */
918                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
919                                _("Cannot convert fallback '%s' to codeset '%s'"),
920                                insert_str, to_codeset);
921                   have_error = TRUE;
922                   break;
923                 }
924               else if (p)
925                 {
926                   if (!fallback)
927                     { 
928                       gunichar ch = g_utf8_get_char (p);
929                       insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
930                                                     ch);
931                     }
932                   else
933                     insert_str = fallback;
934                   
935                   save_p = g_utf8_next_char (p);
936                   save_inbytes = inbytes_remaining - (save_p - p);
937                   p = insert_str;
938                   inbytes_remaining = strlen (p);
939                   break;
940                 }
941               /* fall thru if p is NULL */
942             default:
943               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
944                            _("Error during conversion: %s"),
945                            g_strerror (errno));
946               have_error = TRUE;
947               break;
948             }
949         }
950       else
951         {
952           if (save_p)
953             {
954               if (!fallback)
955                 g_free ((gchar *)insert_str);
956               p = save_p;
957               inbytes_remaining = save_inbytes;
958               save_p = NULL;
959             }
960           else if (p)
961             {
962               /* call g_iconv with NULL inbuf to cleanup shift state */
963               p = NULL;
964               inbytes_remaining = 0;
965             }
966           else
967             done = TRUE;
968         }
969     }
970
971   /* Cleanup
972    */
973   *outp = '\0';
974   
975   close_converter (cd);
976
977   if (bytes_written)
978     *bytes_written = outp - dest;       /* Doesn't include '\0' */
979
980   g_free (utf8);
981
982   if (have_error)
983     {
984       if (save_p && !fallback)
985         g_free ((gchar *)insert_str);
986       g_free (dest);
987       return NULL;
988     }
989   else
990     return dest;
991 }
992
993 /*
994  * g_locale_to_utf8
995  *
996  * 
997  */
998
999 static gchar *
1000 strdup_len (const gchar *string,
1001             gssize       len,
1002             gsize       *bytes_written,
1003             gsize       *bytes_read,
1004             GError      **error)
1005          
1006 {
1007   gsize real_len;
1008
1009   if (!g_utf8_validate (string, len, NULL))
1010     {
1011       if (bytes_read)
1012         *bytes_read = 0;
1013       if (bytes_written)
1014         *bytes_written = 0;
1015
1016       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1017                            _("Invalid byte sequence in conversion input"));
1018       return NULL;
1019     }
1020   
1021   if (len < 0)
1022     real_len = strlen (string);
1023   else
1024     {
1025       real_len = 0;
1026       
1027       while (real_len < len && string[real_len])
1028         real_len++;
1029     }
1030   
1031   if (bytes_read)
1032     *bytes_read = real_len;
1033   if (bytes_written)
1034     *bytes_written = real_len;
1035
1036   return g_strndup (string, real_len);
1037 }
1038
1039 /**
1040  * g_locale_to_utf8:
1041  * @opsysstring:   a string in the encoding of the current locale. On Windows
1042  *                 this means the system codepage.
1043  * @len:           the length of the string, or -1 if the string is
1044  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1045  * @bytes_read:    location to store the number of bytes in the
1046  *                 input string that were successfully converted, or %NULL.
1047  *                 Even if the conversion was successful, this may be 
1048  *                 less than @len if there were partial characters
1049  *                 at the end of the input. If the error
1050  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1051  *                 stored will the byte offset after the last valid
1052  *                 input sequence.
1053  * @bytes_written: the number of bytes stored in the output buffer (not 
1054  *                 including the terminating nul).
1055  * @error:         location to store the error occuring, or %NULL to ignore
1056  *                 errors. Any of the errors in #GConvertError may occur.
1057  * 
1058  * Converts a string which is in the encoding used for strings by
1059  * the C runtime (usually the same as that used by the operating
1060  * system) in the <link linkend="setlocale">current locale</link> into a
1061  * UTF-8 string.
1062  * 
1063  * Return value: The converted string, or %NULL on an error.
1064  **/
1065 gchar *
1066 g_locale_to_utf8 (const gchar  *opsysstring,
1067                   gssize        len,            
1068                   gsize        *bytes_read,    
1069                   gsize        *bytes_written,
1070                   GError      **error)
1071 {
1072   const char *charset;
1073
1074   if (g_get_charset (&charset))
1075     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1076   else
1077     return g_convert (opsysstring, len, 
1078                       "UTF-8", charset, bytes_read, bytes_written, error);
1079 }
1080
1081 /**
1082  * g_locale_from_utf8:
1083  * @utf8string:    a UTF-8 encoded string 
1084  * @len:           the length of the string, or -1 if the string is
1085  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1086  * @bytes_read:    location to store the number of bytes in the
1087  *                 input string that were successfully converted, or %NULL.
1088  *                 Even if the conversion was successful, this may be 
1089  *                 less than @len if there were partial characters
1090  *                 at the end of the input. If the error
1091  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1092  *                 stored will the byte offset after the last valid
1093  *                 input sequence.
1094  * @bytes_written: the number of bytes stored in the output buffer (not 
1095  *                 including the terminating nul).
1096  * @error:         location to store the error occuring, or %NULL to ignore
1097  *                 errors. Any of the errors in #GConvertError may occur.
1098  * 
1099  * Converts a string from UTF-8 to the encoding used for strings by
1100  * the C runtime (usually the same as that used by the operating
1101  * system) in the <link linkend="setlocale">current locale</link>. On
1102  * Windows this means the system codepage.
1103  * 
1104  * Return value: The converted string, or %NULL on an error.
1105  **/
1106 gchar *
1107 g_locale_from_utf8 (const gchar *utf8string,
1108                     gssize       len,            
1109                     gsize       *bytes_read,    
1110                     gsize       *bytes_written,
1111                     GError     **error)
1112 {
1113   const gchar *charset;
1114
1115   if (g_get_charset (&charset))
1116     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1117   else
1118     return g_convert (utf8string, len,
1119                       charset, "UTF-8", bytes_read, bytes_written, error);
1120 }
1121
1122 #ifndef G_PLATFORM_WIN32
1123
1124 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1125
1126 struct _GFilenameCharsetCache {
1127   gboolean is_utf8;
1128   gchar *charset;
1129   gchar **filename_charsets;
1130 };
1131
1132 static void
1133 filename_charset_cache_free (gpointer data)
1134 {
1135   GFilenameCharsetCache *cache = data;
1136   g_free (cache->charset);
1137   g_strfreev (cache->filename_charsets);
1138   g_free (cache);
1139 }
1140
1141 /**
1142  * g_get_filename_charsets:
1143  * @charsets: return location for the %NULL-terminated list of encoding names
1144  *
1145  * Determines the preferred character sets used for filenames.
1146  * The first character set from the @charsets is the filename encoding, the
1147  * subsequent character sets are used when trying to generate a displayable
1148  * representation of a filename, see g_filename_display_name().
1149  *
1150  * On Unix, the character sets are determined by consulting the
1151  * environment variables <envar>G_FILENAME_ENCODING</envar> and
1152  * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1153  * used in the GLib API is always UTF-8 and said environment variables
1154  * have no effect.
1155  *
1156  * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
1157  * of character set names. The special token "&commat;locale" is taken to 
1158  * mean the character set for the <link linkend="setlocale">current 
1159  * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but 
1160  * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current 
1161  * locale is taken as the filename encoding. If neither environment variable 
1162  * is set, UTF-8 is taken as the filename encoding, but the character
1163  * set of the current locale is also put in the list of encodings.
1164  *
1165  * The returned @charsets belong to GLib and must not be freed.
1166  *
1167  * Note that on Unix, regardless of the locale character set or
1168  * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present 
1169  * on a system might be in any random encoding or just gibberish.
1170  *
1171  * Return value: %TRUE if the filename encoding is UTF-8.
1172  * 
1173  * Since: 2.6
1174  */
1175 gboolean
1176 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1177 {
1178   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1179   GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1180   const gchar *charset;
1181
1182   if (!cache)
1183     {
1184       cache = g_new0 (GFilenameCharsetCache, 1);
1185       g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1186     }
1187
1188   g_get_charset (&charset);
1189
1190   if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1191     {
1192       const gchar *new_charset;
1193       gchar *p;
1194       gint i;
1195
1196       g_free (cache->charset);
1197       g_strfreev (cache->filename_charsets);
1198       cache->charset = g_strdup (charset);
1199       
1200       p = getenv ("G_FILENAME_ENCODING");
1201       if (p != NULL && p[0] != '\0') 
1202         {
1203           cache->filename_charsets = g_strsplit (p, ",", 0);
1204           cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1205
1206           for (i = 0; cache->filename_charsets[i]; i++)
1207             {
1208               if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1209                 {
1210                   g_get_charset (&new_charset);
1211                   g_free (cache->filename_charsets[i]);
1212                   cache->filename_charsets[i] = g_strdup (new_charset);
1213                 }
1214             }
1215         }
1216       else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1217         {
1218           cache->filename_charsets = g_new0 (gchar *, 2);
1219           cache->is_utf8 = g_get_charset (&new_charset);
1220           cache->filename_charsets[0] = g_strdup (new_charset);
1221         }
1222       else 
1223         {
1224           cache->filename_charsets = g_new0 (gchar *, 3);
1225           cache->is_utf8 = TRUE;
1226           cache->filename_charsets[0] = g_strdup ("UTF-8");
1227           if (!g_get_charset (&new_charset))
1228             cache->filename_charsets[1] = g_strdup (new_charset);
1229         }
1230     }
1231
1232   if (filename_charsets)
1233     *filename_charsets = (const gchar **)cache->filename_charsets;
1234
1235   return cache->is_utf8;
1236 }
1237
1238 #else /* G_PLATFORM_WIN32 */
1239
1240 gboolean
1241 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets) 
1242 {
1243   static const gchar *charsets[] = {
1244     "UTF-8",
1245     NULL
1246   };
1247
1248 #ifdef G_OS_WIN32
1249   /* On Windows GLib pretends that the filename charset is UTF-8 */
1250   if (filename_charsets)
1251     *filename_charsets = charsets;
1252
1253   return TRUE;
1254 #else
1255   gboolean result;
1256
1257   /* Cygwin works like before */
1258   result = g_get_charset (&(charsets[0]));
1259
1260   if (filename_charsets)
1261     *filename_charsets = charsets;
1262
1263   return result;
1264 #endif
1265 }
1266
1267 #endif /* G_PLATFORM_WIN32 */
1268
1269 static gboolean
1270 get_filename_charset (const gchar **filename_charset)
1271 {
1272   const gchar **charsets;
1273   gboolean is_utf8;
1274   
1275   is_utf8 = g_get_filename_charsets (&charsets);
1276
1277   if (filename_charset)
1278     *filename_charset = charsets[0];
1279   
1280   return is_utf8;
1281 }
1282
1283 /* This is called from g_thread_init(). It's used to
1284  * initialize some static data in a threadsafe way.
1285  */
1286 void 
1287 _g_convert_thread_init (void)
1288 {
1289   const gchar **dummy;
1290   (void) g_get_filename_charsets (&dummy);
1291 }
1292
1293 /**
1294  * g_filename_to_utf8:
1295  * @opsysstring:   a string in the encoding for filenames
1296  * @len:           the length of the string, or -1 if the string is
1297  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1298  * @bytes_read:    location to store the number of bytes in the
1299  *                 input string that were successfully converted, or %NULL.
1300  *                 Even if the conversion was successful, this may be 
1301  *                 less than @len if there were partial characters
1302  *                 at the end of the input. If the error
1303  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1304  *                 stored will the byte offset after the last valid
1305  *                 input sequence.
1306  * @bytes_written: the number of bytes stored in the output buffer (not 
1307  *                 including the terminating nul).
1308  * @error:         location to store the error occuring, or %NULL to ignore
1309  *                 errors. Any of the errors in #GConvertError may occur.
1310  * 
1311  * Converts a string which is in the encoding used by GLib for
1312  * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1313  * for filenames; on other platforms, this function indirectly depends on 
1314  * the <link linkend="setlocale">current locale</link>.
1315  * 
1316  * Return value: The converted string, or %NULL on an error.
1317  **/
1318 gchar*
1319 g_filename_to_utf8 (const gchar *opsysstring, 
1320                     gssize       len,           
1321                     gsize       *bytes_read,   
1322                     gsize       *bytes_written,
1323                     GError     **error)
1324 {
1325   const gchar *charset;
1326
1327   if (get_filename_charset (&charset))
1328     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1329   else
1330     return g_convert (opsysstring, len, 
1331                       "UTF-8", charset, bytes_read, bytes_written, error);
1332 }
1333
1334 #if defined (G_OS_WIN32) && !defined (_WIN64)
1335
1336 #undef g_filename_to_utf8
1337
1338 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1339  * 64-bit versions as there should be no old deployed binaries that would use
1340  * the old versions.
1341  */
1342
1343 gchar*
1344 g_filename_to_utf8 (const gchar *opsysstring, 
1345                     gssize       len,           
1346                     gsize       *bytes_read,   
1347                     gsize       *bytes_written,
1348                     GError     **error)
1349 {
1350   const gchar *charset;
1351
1352   if (g_get_charset (&charset))
1353     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1354   else
1355     return g_convert (opsysstring, len, 
1356                       "UTF-8", charset, bytes_read, bytes_written, error);
1357 }
1358
1359 #endif
1360
1361 /**
1362  * g_filename_from_utf8:
1363  * @utf8string:    a UTF-8 encoded string.
1364  * @len:           the length of the string, or -1 if the string is
1365  *                 nul-terminated.
1366  * @bytes_read:    location to store the number of bytes in the
1367  *                 input string that were successfully converted, or %NULL.
1368  *                 Even if the conversion was successful, this may be 
1369  *                 less than @len if there were partial characters
1370  *                 at the end of the input. If the error
1371  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1372  *                 stored will the byte offset after the last valid
1373  *                 input sequence.
1374  * @bytes_written: the number of bytes stored in the output buffer (not 
1375  *                 including the terminating nul).
1376  * @error:         location to store the error occuring, or %NULL to ignore
1377  *                 errors. Any of the errors in #GConvertError may occur.
1378  * 
1379  * Converts a string from UTF-8 to the encoding GLib uses for
1380  * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1381  * on other platforms, this function indirectly depends on the 
1382  * <link linkend="setlocale">current locale</link>.
1383  * 
1384  * Return value: The converted string, or %NULL on an error.
1385  **/
1386 gchar*
1387 g_filename_from_utf8 (const gchar *utf8string,
1388                       gssize       len,            
1389                       gsize       *bytes_read,    
1390                       gsize       *bytes_written,
1391                       GError     **error)
1392 {
1393   const gchar *charset;
1394
1395   if (get_filename_charset (&charset))
1396     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1397   else
1398     return g_convert (utf8string, len,
1399                       charset, "UTF-8", bytes_read, bytes_written, error);
1400 }
1401
1402 #if defined (G_OS_WIN32) && !defined (_WIN64)
1403
1404 #undef g_filename_from_utf8
1405
1406 /* Binary compatibility version. Not for newly compiled code. */
1407
1408 gchar*
1409 g_filename_from_utf8 (const gchar *utf8string,
1410                       gssize       len,            
1411                       gsize       *bytes_read,    
1412                       gsize       *bytes_written,
1413                       GError     **error)
1414 {
1415   const gchar *charset;
1416
1417   if (g_get_charset (&charset))
1418     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1419   else
1420     return g_convert (utf8string, len,
1421                       charset, "UTF-8", bytes_read, bytes_written, error);
1422 }
1423
1424 #endif
1425
1426 /* Test of haystack has the needle prefix, comparing case
1427  * insensitive. haystack may be UTF-8, but needle must
1428  * contain only ascii. */
1429 static gboolean
1430 has_case_prefix (const gchar *haystack, const gchar *needle)
1431 {
1432   const gchar *h, *n;
1433   
1434   /* Eat one character at a time. */
1435   h = haystack;
1436   n = needle;
1437
1438   while (*n && *h &&
1439          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1440     {
1441       n++;
1442       h++;
1443     }
1444   
1445   return *n == '\0';
1446 }
1447
1448 typedef enum {
1449   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1450   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1451   UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1452   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1453   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1454 } UnsafeCharacterSet;
1455
1456 static const guchar acceptable[96] = {
1457   /* A table of the ASCII chars from space (32) to DEL (127) */
1458   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1459   0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1460   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1461   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1462   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1463   0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1464   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1465   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1466   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1467   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1468   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1469   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1470 };
1471
1472 static const gchar hex[16] = "0123456789ABCDEF";
1473
1474 /* Note: This escape function works on file: URIs, but if you want to
1475  * escape something else, please read RFC-2396 */
1476 static gchar *
1477 g_escape_uri_string (const gchar *string, 
1478                      UnsafeCharacterSet mask)
1479 {
1480 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1481
1482   const gchar *p;
1483   gchar *q;
1484   gchar *result;
1485   int c;
1486   gint unacceptable;
1487   UnsafeCharacterSet use_mask;
1488   
1489   g_return_val_if_fail (mask == UNSAFE_ALL
1490                         || mask == UNSAFE_ALLOW_PLUS
1491                         || mask == UNSAFE_PATH
1492                         || mask == UNSAFE_HOST
1493                         || mask == UNSAFE_SLASHES, NULL);
1494   
1495   unacceptable = 0;
1496   use_mask = mask;
1497   for (p = string; *p != '\0'; p++)
1498     {
1499       c = (guchar) *p;
1500       if (!ACCEPTABLE (c)) 
1501         unacceptable++;
1502     }
1503   
1504   result = g_malloc (p - string + unacceptable * 2 + 1);
1505   
1506   use_mask = mask;
1507   for (q = result, p = string; *p != '\0'; p++)
1508     {
1509       c = (guchar) *p;
1510       
1511       if (!ACCEPTABLE (c))
1512         {
1513           *q++ = '%'; /* means hex coming */
1514           *q++ = hex[c >> 4];
1515           *q++ = hex[c & 15];
1516         }
1517       else
1518         *q++ = *p;
1519     }
1520   
1521   *q = '\0';
1522   
1523   return result;
1524 }
1525
1526
1527 static gchar *
1528 g_escape_file_uri (const gchar *hostname,
1529                    const gchar *pathname)
1530 {
1531   char *escaped_hostname = NULL;
1532   char *escaped_path;
1533   char *res;
1534
1535 #ifdef G_OS_WIN32
1536   char *p, *backslash;
1537
1538   /* Turn backslashes into forward slashes. That's what Netscape
1539    * does, and they are actually more or less equivalent in Windows.
1540    */
1541   
1542   pathname = g_strdup (pathname);
1543   p = (char *) pathname;
1544   
1545   while ((backslash = strchr (p, '\\')) != NULL)
1546     {
1547       *backslash = '/';
1548       p = backslash + 1;
1549     }
1550 #endif
1551
1552   if (hostname && *hostname != '\0')
1553     {
1554       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1555     }
1556
1557   escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1558
1559   res = g_strconcat ("file://",
1560                      (escaped_hostname) ? escaped_hostname : "",
1561                      (*escaped_path != '/') ? "/" : "",
1562                      escaped_path,
1563                      NULL);
1564
1565 #ifdef G_OS_WIN32
1566   g_free ((char *) pathname);
1567 #endif
1568
1569   g_free (escaped_hostname);
1570   g_free (escaped_path);
1571   
1572   return res;
1573 }
1574
1575 static int
1576 unescape_character (const char *scanner)
1577 {
1578   int first_digit;
1579   int second_digit;
1580
1581   first_digit = g_ascii_xdigit_value (scanner[0]);
1582   if (first_digit < 0) 
1583     return -1;
1584   
1585   second_digit = g_ascii_xdigit_value (scanner[1]);
1586   if (second_digit < 0) 
1587     return -1;
1588   
1589   return (first_digit << 4) | second_digit;
1590 }
1591
1592 static gchar *
1593 g_unescape_uri_string (const char *escaped,
1594                        int         len,
1595                        const char *illegal_escaped_characters,
1596                        gboolean    ascii_must_not_be_escaped)
1597 {
1598   const gchar *in, *in_end;
1599   gchar *out, *result;
1600   int c;
1601   
1602   if (escaped == NULL)
1603     return NULL;
1604
1605   if (len < 0)
1606     len = strlen (escaped);
1607
1608   result = g_malloc (len + 1);
1609   
1610   out = result;
1611   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1612     {
1613       c = *in;
1614
1615       if (c == '%')
1616         {
1617           /* catch partial escape sequences past the end of the substring */
1618           if (in + 3 > in_end)
1619             break;
1620
1621           c = unescape_character (in + 1);
1622
1623           /* catch bad escape sequences and NUL characters */
1624           if (c <= 0)
1625             break;
1626
1627           /* catch escaped ASCII */
1628           if (ascii_must_not_be_escaped && c <= 0x7F)
1629             break;
1630
1631           /* catch other illegal escaped characters */
1632           if (strchr (illegal_escaped_characters, c) != NULL)
1633             break;
1634
1635           in += 2;
1636         }
1637
1638       *out++ = c;
1639     }
1640   
1641   g_assert (out - result <= len);
1642   *out = '\0';
1643
1644   if (in != in_end)
1645     {
1646       g_free (result);
1647       return NULL;
1648     }
1649
1650   return result;
1651 }
1652
1653 static gboolean
1654 is_asciialphanum (gunichar c)
1655 {
1656   return c <= 0x7F && g_ascii_isalnum (c);
1657 }
1658
1659 static gboolean
1660 is_asciialpha (gunichar c)
1661 {
1662   return c <= 0x7F && g_ascii_isalpha (c);
1663 }
1664
1665 /* allows an empty string */
1666 static gboolean
1667 hostname_validate (const char *hostname)
1668 {
1669   const char *p;
1670   gunichar c, first_char, last_char;
1671
1672   p = hostname;
1673   if (*p == '\0')
1674     return TRUE;
1675   do
1676     {
1677       /* read in a label */
1678       c = g_utf8_get_char (p);
1679       p = g_utf8_next_char (p);
1680       if (!is_asciialphanum (c))
1681         return FALSE;
1682       first_char = c;
1683       do
1684         {
1685           last_char = c;
1686           c = g_utf8_get_char (p);
1687           p = g_utf8_next_char (p);
1688         }
1689       while (is_asciialphanum (c) || c == '-');
1690       if (last_char == '-')
1691         return FALSE;
1692       
1693       /* if that was the last label, check that it was a toplabel */
1694       if (c == '\0' || (c == '.' && *p == '\0'))
1695         return is_asciialpha (first_char);
1696     }
1697   while (c == '.');
1698   return FALSE;
1699 }
1700
1701 /**
1702  * g_filename_from_uri:
1703  * @uri: a uri describing a filename (escaped, encoded in ASCII).
1704  * @hostname: Location to store hostname for the URI, or %NULL.
1705  *            If there is no hostname in the URI, %NULL will be
1706  *            stored in this location.
1707  * @error: location to store the error occuring, or %NULL to ignore
1708  *         errors. Any of the errors in #GConvertError may occur.
1709  * 
1710  * Converts an escaped ASCII-encoded URI to a local filename in the
1711  * encoding used for filenames. 
1712  * 
1713  * Return value: a newly-allocated string holding the resulting
1714  *               filename, or %NULL on an error.
1715  **/
1716 gchar *
1717 g_filename_from_uri (const gchar *uri,
1718                      gchar      **hostname,
1719                      GError     **error)
1720 {
1721   const char *path_part;
1722   const char *host_part;
1723   char *unescaped_hostname;
1724   char *result;
1725   char *filename;
1726   int offs;
1727 #ifdef G_OS_WIN32
1728   char *p, *slash;
1729 #endif
1730
1731   if (hostname)
1732     *hostname = NULL;
1733
1734   if (!has_case_prefix (uri, "file:/"))
1735     {
1736       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1737                    _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1738                    uri);
1739       return NULL;
1740     }
1741   
1742   path_part = uri + strlen ("file:");
1743   
1744   if (strchr (path_part, '#') != NULL)
1745     {
1746       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1747                    _("The local file URI '%s' may not include a '#'"),
1748                    uri);
1749       return NULL;
1750     }
1751         
1752   if (has_case_prefix (path_part, "///")) 
1753     path_part += 2;
1754   else if (has_case_prefix (path_part, "//"))
1755     {
1756       path_part += 2;
1757       host_part = path_part;
1758
1759       path_part = strchr (path_part, '/');
1760
1761       if (path_part == NULL)
1762         {
1763           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1764                        _("The URI '%s' is invalid"),
1765                        uri);
1766           return NULL;
1767         }
1768
1769       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1770
1771       if (unescaped_hostname == NULL ||
1772           !hostname_validate (unescaped_hostname))
1773         {
1774           g_free (unescaped_hostname);
1775           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1776                        _("The hostname of the URI '%s' is invalid"),
1777                        uri);
1778           return NULL;
1779         }
1780       
1781       if (hostname)
1782         *hostname = unescaped_hostname;
1783       else
1784         g_free (unescaped_hostname);
1785     }
1786
1787   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1788
1789   if (filename == NULL)
1790     {
1791       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1792                    _("The URI '%s' contains invalidly escaped characters"),
1793                    uri);
1794       return NULL;
1795     }
1796
1797   offs = 0;
1798 #ifdef G_OS_WIN32
1799   /* Drop localhost */
1800   if (hostname && *hostname != NULL &&
1801       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1802     {
1803       g_free (*hostname);
1804       *hostname = NULL;
1805     }
1806
1807   /* Turn slashes into backslashes, because that's the canonical spelling */
1808   p = filename;
1809   while ((slash = strchr (p, '/')) != NULL)
1810     {
1811       *slash = '\\';
1812       p = slash + 1;
1813     }
1814
1815   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1816    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1817    * the filename from the drive letter.
1818    */
1819   if (g_ascii_isalpha (filename[1]))
1820     {
1821       if (filename[2] == ':')
1822         offs = 1;
1823       else if (filename[2] == '|')
1824         {
1825           filename[2] = ':';
1826           offs = 1;
1827         }
1828     }
1829 #endif
1830
1831   result = g_strdup (filename + offs);
1832   g_free (filename);
1833
1834   return result;
1835 }
1836
1837 #if defined (G_OS_WIN32) && !defined (_WIN64)
1838
1839 #undef g_filename_from_uri
1840
1841 gchar *
1842 g_filename_from_uri (const gchar *uri,
1843                      gchar      **hostname,
1844                      GError     **error)
1845 {
1846   gchar *utf8_filename;
1847   gchar *retval = NULL;
1848
1849   utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1850   if (utf8_filename)
1851     {
1852       retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1853       g_free (utf8_filename);
1854     }
1855   return retval;
1856 }
1857
1858 #endif
1859
1860 /**
1861  * g_filename_to_uri:
1862  * @filename: an absolute filename specified in the GLib file name encoding,
1863  *            which is the on-disk file name bytes on Unix, and UTF-8 on 
1864  *            Windows
1865  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1866  * @error: location to store the error occuring, or %NULL to ignore
1867  *         errors. Any of the errors in #GConvertError may occur.
1868  * 
1869  * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1870  * component following Section 3.3. of RFC 2396.
1871  * 
1872  * Return value: a newly-allocated string holding the resulting
1873  *               URI, or %NULL on an error.
1874  **/
1875 gchar *
1876 g_filename_to_uri (const gchar *filename,
1877                    const gchar *hostname,
1878                    GError     **error)
1879 {
1880   char *escaped_uri;
1881
1882   g_return_val_if_fail (filename != NULL, NULL);
1883
1884   if (!g_path_is_absolute (filename))
1885     {
1886       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1887                    _("The pathname '%s' is not an absolute path"),
1888                    filename);
1889       return NULL;
1890     }
1891
1892   if (hostname &&
1893       !(g_utf8_validate (hostname, -1, NULL)
1894         && hostname_validate (hostname)))
1895     {
1896       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1897                            _("Invalid hostname"));
1898       return NULL;
1899     }
1900   
1901 #ifdef G_OS_WIN32
1902   /* Don't use localhost unnecessarily */
1903   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1904     hostname = NULL;
1905 #endif
1906
1907   escaped_uri = g_escape_file_uri (hostname, filename);
1908
1909   return escaped_uri;
1910 }
1911
1912 #if defined (G_OS_WIN32) && !defined (_WIN64)
1913
1914 #undef g_filename_to_uri
1915
1916 gchar *
1917 g_filename_to_uri (const gchar *filename,
1918                    const gchar *hostname,
1919                    GError     **error)
1920 {
1921   gchar *utf8_filename;
1922   gchar *retval = NULL;
1923
1924   utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1925
1926   if (utf8_filename)
1927     {
1928       retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1929       g_free (utf8_filename);
1930     }
1931
1932   return retval;
1933 }
1934
1935 #endif
1936
1937 /**
1938  * g_uri_list_extract_uris:
1939  * @uri_list: an URI list 
1940  *
1941  * Splits an URI list conforming to the text/uri-list
1942  * mime type defined in RFC 2483 into individual URIs,
1943  * discarding any comments. The URIs are not validated.
1944  *
1945  * Returns: a newly allocated %NULL-terminated list of
1946  *   strings holding the individual URIs. The array should
1947  *   be freed with g_strfreev().
1948  *
1949  * Since: 2.6
1950  */
1951 gchar **
1952 g_uri_list_extract_uris (const gchar *uri_list)
1953 {
1954   GSList *uris, *u;
1955   const gchar *p, *q;
1956   gchar **result;
1957   gint n_uris = 0;
1958
1959   uris = NULL;
1960
1961   p = uri_list;
1962
1963   /* We don't actually try to validate the URI according to RFC
1964    * 2396, or even check for allowed characters - we just ignore
1965    * comments and trim whitespace off the ends.  We also
1966    * allow LF delimination as well as the specified CRLF.
1967    *
1968    * We do allow comments like specified in RFC 2483.
1969    */
1970   while (p)
1971     {
1972       if (*p != '#')
1973         {
1974           while (g_ascii_isspace (*p))
1975             p++;
1976
1977           q = p;
1978           while (*q && (*q != '\n') && (*q != '\r'))
1979             q++;
1980
1981           if (q > p)
1982             {
1983               q--;
1984               while (q > p && g_ascii_isspace (*q))
1985                 q--;
1986
1987               if (q > p)
1988                 {
1989                   uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1990                   n_uris++;
1991                 }
1992             }
1993         }
1994       p = strchr (p, '\n');
1995       if (p)
1996         p++;
1997     }
1998
1999   result = g_new (gchar *, n_uris + 1);
2000
2001   result[n_uris--] = NULL;
2002   for (u = uris; u; u = u->next)
2003     result[n_uris--] = u->data;
2004
2005   g_slist_free (uris);
2006
2007   return result;
2008 }
2009
2010 /**
2011  * g_filename_display_basename:
2012  * @filename: an absolute pathname in the GLib file name encoding
2013  *
2014  * Returns the display basename for the particular filename, guaranteed
2015  * to be valid UTF-8. The display name might not be identical to the filename,
2016  * for instance there might be problems converting it to UTF-8, and some files
2017  * can be translated in the display.
2018  *
2019  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2020  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2021  * You can search the result for the UTF-8 encoding of this character (which is
2022  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2023  * encoding.
2024  *
2025  * You must pass the whole absolute pathname to this functions so that
2026  * translation of well known locations can be done.
2027  *
2028  * This function is preferred over g_filename_display_name() if you know the
2029  * whole path, as it allows translation.
2030  *
2031  * Return value: a newly allocated string containing
2032  *   a rendition of the basename of the filename in valid UTF-8
2033  *
2034  * Since: 2.6
2035  **/
2036 gchar *
2037 g_filename_display_basename (const gchar *filename)
2038 {
2039   char *basename;
2040   char *display_name;
2041
2042   g_return_val_if_fail (filename != NULL, NULL);
2043   
2044   basename = g_path_get_basename (filename);
2045   display_name = g_filename_display_name (basename);
2046   g_free (basename);
2047   return display_name;
2048 }
2049
2050 /**
2051  * g_filename_display_name:
2052  * @filename: a pathname hopefully in the GLib file name encoding
2053  * 
2054  * Converts a filename into a valid UTF-8 string. The conversion is 
2055  * not necessarily reversible, so you should keep the original around 
2056  * and use the return value of this function only for display purposes.
2057  * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL 
2058  * even if the filename actually isn't in the GLib file name encoding.
2059  *
2060  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2061  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2062  * You can search the result for the UTF-8 encoding of this character (which is
2063  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2064  * encoding.
2065  *
2066  * If you know the whole pathname of the file you should use
2067  * g_filename_display_basename(), since that allows location-based
2068  * translation of filenames.
2069  *
2070  * Return value: a newly allocated string containing
2071  *   a rendition of the filename in valid UTF-8
2072  *
2073  * Since: 2.6
2074  **/
2075 gchar *
2076 g_filename_display_name (const gchar *filename)
2077 {
2078   gint i;
2079   const gchar **charsets;
2080   gchar *display_name = NULL;
2081   gboolean is_utf8;
2082  
2083   is_utf8 = g_get_filename_charsets (&charsets);
2084
2085   if (is_utf8)
2086     {
2087       if (g_utf8_validate (filename, -1, NULL))
2088         display_name = g_strdup (filename);
2089     }
2090   
2091   if (!display_name)
2092     {
2093       /* Try to convert from the filename charsets to UTF-8.
2094        * Skip the first charset if it is UTF-8.
2095        */
2096       for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2097         {
2098           display_name = g_convert (filename, -1, "UTF-8", charsets[i], 
2099                                     NULL, NULL, NULL);
2100
2101           if (display_name)
2102             break;
2103         }
2104     }
2105   
2106   /* if all conversions failed, we replace invalid UTF-8
2107    * by a question mark
2108    */
2109   if (!display_name) 
2110     display_name = _g_utf8_make_valid (filename);
2111
2112   return display_name;
2113 }
2114
2115 #define __G_CONVERT_C__
2116 #include "galiasdef.c"