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