4de433a75e7107a217caf64bb2e8b9e6931708fe
[platform/upstream/glib.git] / glib / gconvert.c
1 /* GLIB - Library of useful routines for C programming
2  *
3  * gconvert.c: Convert between character sets using iconv
4  * Copyright Red Hat Inc., 2000
5  * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include <config.h>
24
25 #include <iconv.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 #include "glib.h"
32 #include "gprintfint.h"
33
34 #ifdef G_PLATFORM_WIN32
35 #define STRICT
36 #include <windows.h>
37 #undef STRICT
38 #endif
39
40 #include "glibintl.h"
41
42 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
43 #error GNU libiconv in use but included iconv.h not from libiconv
44 #endif
45 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
46 #error GNU libiconv not in use but included iconv.h is from libiconv
47 #endif
48
49 GQuark 
50 g_convert_error_quark (void)
51 {
52   static GQuark quark;
53   if (!quark)
54     quark = g_quark_from_static_string ("g_convert_error");
55
56   return quark;
57 }
58
59 static gboolean
60 try_conversion (const char *to_codeset,
61                 const char *from_codeset,
62                 iconv_t    *cd)
63 {
64   *cd = iconv_open (to_codeset, from_codeset);
65
66   if (*cd == (iconv_t)-1 && errno == EINVAL)
67     return FALSE;
68   else
69     return TRUE;
70 }
71
72 static gboolean
73 try_to_aliases (const char **to_aliases,
74                 const char  *from_codeset,
75                 iconv_t     *cd)
76 {
77   if (to_aliases)
78     {
79       const char **p = to_aliases;
80       while (*p)
81         {
82           if (try_conversion (*p, from_codeset, cd))
83             return TRUE;
84
85           p++;
86         }
87     }
88
89   return FALSE;
90 }
91
92 extern const char **_g_charset_get_aliases (const char *canonical_name);
93
94 /**
95  * g_iconv_open:
96  * @to_codeset: destination codeset
97  * @from_codeset: source codeset
98  * 
99  * Same as the standard UNIX routine <function>iconv_open()</function>, but
100  * may be implemented via libiconv on UNIX flavors that lack
101  * a native implementation.
102  * 
103  * GLib provides g_convert() and g_locale_to_utf8() which are likely
104  * more convenient than the raw iconv wrappers.
105  * 
106  * Return value: a "conversion descriptor", or (GIConv)-1 if
107  *  opening the converter failed.
108  **/
109 GIConv
110 g_iconv_open (const gchar  *to_codeset,
111               const gchar  *from_codeset)
112 {
113   iconv_t cd;
114   
115   if (!try_conversion (to_codeset, from_codeset, &cd))
116     {
117       const char **to_aliases = _g_charset_get_aliases (to_codeset);
118       const char **from_aliases = _g_charset_get_aliases (from_codeset);
119
120       if (from_aliases)
121         {
122           const char **p = from_aliases;
123           while (*p)
124             {
125               if (try_conversion (to_codeset, *p, &cd))
126                 goto out;
127
128               if (try_to_aliases (to_aliases, *p, &cd))
129                 goto out;
130
131               p++;
132             }
133         }
134
135       if (try_to_aliases (to_aliases, from_codeset, &cd))
136         goto out;
137     }
138
139  out:
140   return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
141 }
142
143 /**
144  * g_iconv:
145  * @converter: conversion descriptor from g_iconv_open()
146  * @inbuf: bytes to convert
147  * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
148  * @outbuf: converted output bytes
149  * @outbytes_left: inout parameter, bytes available to fill in @outbuf
150  * 
151  * Same as the standard UNIX routine <function>iconv()</function>, but
152  * may be implemented via libiconv on UNIX flavors that lack
153  * a native implementation.
154  *
155  * GLib provides g_convert() and g_locale_to_utf8() which are likely
156  * more convenient than the raw iconv wrappers.
157  * 
158  * Return value: count of non-reversible conversions, or -1 on error
159  **/
160 size_t 
161 g_iconv (GIConv   converter,
162          gchar  **inbuf,
163          gsize   *inbytes_left,
164          gchar  **outbuf,
165          gsize   *outbytes_left)
166 {
167   iconv_t cd = (iconv_t)converter;
168
169   return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
170 }
171
172 /**
173  * g_iconv_close:
174  * @converter: a conversion descriptor from g_iconv_open()
175  *
176  * Same as the standard UNIX routine <function>iconv_close()</function>, but
177  * may be implemented via libiconv on UNIX flavors that lack
178  * a native implementation. Should be called to clean up
179  * the conversion descriptor from g_iconv_open() when
180  * you are done converting things.
181  *
182  * GLib provides g_convert() and g_locale_to_utf8() which are likely
183  * more convenient than the raw iconv wrappers.
184  * 
185  * Return value: -1 on error, 0 on success
186  **/
187 gint
188 g_iconv_close (GIConv converter)
189 {
190   iconv_t cd = (iconv_t)converter;
191
192   return iconv_close (cd);
193 }
194
195
196 #define ICONV_CACHE_SIZE   (16)
197
198 struct _iconv_cache_bucket {
199   gchar *key;
200   guint32 refcount;
201   gboolean used;
202   GIConv cd;
203 };
204
205 static GList *iconv_cache_list;
206 static GHashTable *iconv_cache;
207 static GHashTable *iconv_open_hash;
208 static guint iconv_cache_size = 0;
209 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
210
211 /* caller *must* hold the iconv_cache_lock */
212 static void
213 iconv_cache_init (void)
214 {
215   static gboolean initialized = FALSE;
216   
217   if (initialized)
218     return;
219   
220   iconv_cache_list = NULL;
221   iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
222   iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
223   
224   initialized = TRUE;
225 }
226
227
228 /**
229  * iconv_cache_bucket_new:
230  * @key: cache key
231  * @cd: iconv descriptor
232  *
233  * Creates a new cache bucket, inserts it into the cache and
234  * increments the cache size.
235  *
236  * Returns a pointer to the newly allocated cache bucket.
237  **/
238 struct _iconv_cache_bucket *
239 iconv_cache_bucket_new (const gchar *key, GIConv cd)
240 {
241   struct _iconv_cache_bucket *bucket;
242   
243   bucket = g_new (struct _iconv_cache_bucket, 1);
244   bucket->key = g_strdup (key);
245   bucket->refcount = 1;
246   bucket->used = TRUE;
247   bucket->cd = cd;
248   
249   g_hash_table_insert (iconv_cache, bucket->key, bucket);
250   
251   /* FIXME: if we sorted the list so items with few refcounts were
252      first, then we could expire them faster in iconv_cache_expire_unused () */
253   iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
254   
255   iconv_cache_size++;
256   
257   return bucket;
258 }
259
260
261 /**
262  * iconv_cache_bucket_expire:
263  * @node: cache bucket's node
264  * @bucket: cache bucket
265  *
266  * Expires a single cache bucket @bucket. This should only ever be
267  * called on a bucket that currently has no used iconv descriptors
268  * open.
269  *
270  * @node is not a required argument. If @node is not supplied, we
271  * search for it ourselves.
272  **/
273 static void
274 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
275 {
276   g_hash_table_remove (iconv_cache, bucket->key);
277   
278   if (node == NULL)
279     node = g_list_find (iconv_cache_list, bucket);
280   
281   g_assert (node != NULL);
282   
283   if (node->prev)
284     {
285       node->prev->next = node->next;
286       if (node->next)
287         node->next->prev = node->prev;
288     }
289   else
290     {
291       iconv_cache_list = node->next;
292       if (node->next)
293         node->next->prev = NULL;
294     }
295   
296   g_list_free_1 (node);
297   
298   g_free (bucket->key);
299   g_iconv_close (bucket->cd);
300   g_free (bucket);
301   
302   iconv_cache_size--;
303 }
304
305
306 /**
307  * iconv_cache_expire_unused:
308  *
309  * Expires as many unused cache buckets as it needs to in order to get
310  * the total number of buckets < ICONV_CACHE_SIZE.
311  **/
312 static void
313 iconv_cache_expire_unused (void)
314 {
315   struct _iconv_cache_bucket *bucket;
316   GList *node, *next;
317   
318   node = iconv_cache_list;
319   while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
320     {
321       next = node->next;
322       
323       bucket = node->data;
324       if (bucket->refcount == 0)
325         iconv_cache_bucket_expire (node, bucket);
326       
327       node = next;
328     }
329 }
330
331 static GIConv
332 open_converter (const gchar *to_codeset,
333                 const gchar *from_codeset,
334                 GError     **error)
335 {
336   struct _iconv_cache_bucket *bucket;
337   gchar *key;
338   GIConv cd;
339   
340   /* create our key */
341   key = g_alloca (strlen (from_codeset) + strlen (to_codeset) + 2);
342   _g_sprintf (key, "%s:%s", from_codeset, to_codeset);
343   
344   G_LOCK (iconv_cache_lock);
345   
346   /* make sure the cache has been initialized */
347   iconv_cache_init ();
348   
349   bucket = g_hash_table_lookup (iconv_cache, key);
350   if (bucket)
351     {
352       if (bucket->used)
353         {
354           cd = g_iconv_open (to_codeset, from_codeset);
355           if (cd == (GIConv) -1)
356             goto error;
357         }
358       else
359         {
360           /* Apparently iconv on Solaris <= 7 segfaults if you pass in
361            * NULL for anything but inbuf; work around that. (NULL outbuf
362            * or NULL *outbuf is allowed by Unix98.)
363            */
364           gsize inbytes_left = 0;
365           gchar *outbuf = NULL;
366           gsize outbytes_left = 0;
367                 
368           cd = bucket->cd;
369           bucket->used = TRUE;
370           
371           /* reset the descriptor */
372           g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
373         }
374       
375       bucket->refcount++;
376     }
377   else
378     {
379       cd = g_iconv_open (to_codeset, from_codeset);
380       if (cd == (GIConv) -1)
381         goto error;
382       
383       iconv_cache_expire_unused ();
384       
385       bucket = iconv_cache_bucket_new (key, cd);
386     }
387   
388   g_hash_table_insert (iconv_open_hash, cd, bucket->key);
389   
390   G_UNLOCK (iconv_cache_lock);
391   
392   return cd;
393   
394  error:
395   
396   G_UNLOCK (iconv_cache_lock);
397   
398   /* Something went wrong.  */
399   if (errno == EINVAL)
400     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
401                  _("Conversion from character set '%s' to '%s' is not supported"),
402                  from_codeset, to_codeset);
403   else
404     g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
405                  _("Could not open converter from '%s' to '%s': %s"),
406                  from_codeset, to_codeset, g_strerror (errno));
407   
408   return cd;
409 }
410
411 static int
412 close_converter (GIConv converter)
413 {
414   struct _iconv_cache_bucket *bucket;
415   const gchar *key;
416   GIConv cd;
417   
418   cd = converter;
419   
420   if (cd == (GIConv) -1)
421     return 0;
422   
423   G_LOCK (iconv_cache_lock);
424   
425   key = g_hash_table_lookup (iconv_open_hash, cd);
426   if (key)
427     {
428       g_hash_table_remove (iconv_open_hash, cd);
429       
430       bucket = g_hash_table_lookup (iconv_cache, key);
431       g_assert (bucket);
432       
433       bucket->refcount--;
434       
435       if (cd == bucket->cd)
436         bucket->used = FALSE;
437       else
438         g_iconv_close (cd);
439       
440       if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
441         {
442           /* expire this cache bucket */
443           iconv_cache_bucket_expire (NULL, bucket);
444         }
445     }
446   else
447     {
448       G_UNLOCK (iconv_cache_lock);
449       
450       g_warning ("This iconv context wasn't opened using open_converter");
451       
452       return g_iconv_close (converter);
453     }
454   
455   G_UNLOCK (iconv_cache_lock);
456   
457   return 0;
458 }
459
460
461 /**
462  * g_convert:
463  * @str:           the string to convert
464  * @len:           the length of the string
465  * @to_codeset:    name of character set into which to convert @str
466  * @from_codeset:  character set of @str.
467  * @bytes_read:    location to store the number of bytes in the
468  *                 input string that were successfully converted, or %NULL.
469  *                 Even if the conversion was successful, this may be 
470  *                 less than @len if there were partial characters
471  *                 at the end of the input. If the error
472  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
473  *                 stored will the byte offset after the last valid
474  *                 input sequence.
475  * @bytes_written: the number of bytes stored in the output buffer (not 
476  *                 including the terminating nul).
477  * @error:         location to store the error occuring, or %NULL to ignore
478  *                 errors. Any of the errors in #GConvertError may occur.
479  *
480  * Converts a string from one character set to another.
481  *
482  * Return value: If the conversion was successful, a newly allocated
483  *               nul-terminated string, which must be freed with
484  *               g_free(). Otherwise %NULL and @error will be set.
485  **/
486 gchar*
487 g_convert (const gchar *str,
488            gssize       len,  
489            const gchar *to_codeset,
490            const gchar *from_codeset,
491            gsize       *bytes_read, 
492            gsize       *bytes_written, 
493            GError     **error)
494 {
495   gchar *res;
496   GIConv cd;
497   
498   g_return_val_if_fail (str != NULL, NULL);
499   g_return_val_if_fail (to_codeset != NULL, NULL);
500   g_return_val_if_fail (from_codeset != NULL, NULL);
501   
502   cd = open_converter (to_codeset, from_codeset, error);
503
504   if (cd == (GIConv) -1)
505     {
506       if (bytes_read)
507         *bytes_read = 0;
508       
509       if (bytes_written)
510         *bytes_written = 0;
511       
512       return NULL;
513     }
514
515   res = g_convert_with_iconv (str, len, cd,
516                               bytes_read, bytes_written,
517                               error);
518   
519   close_converter (cd);
520
521   return res;
522 }
523
524 /**
525  * g_convert_with_iconv:
526  * @str:           the string to convert
527  * @len:           the length of the string
528  * @converter:     conversion descriptor from g_iconv_open()
529  * @bytes_read:    location to store the number of bytes in the
530  *                 input string that were successfully converted, or %NULL.
531  *                 Even if the conversion was successful, this may be 
532  *                 less than @len if there were partial characters
533  *                 at the end of the input. If the error
534  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
535  *                 stored will the byte offset after the last valid
536  *                 input sequence.
537  * @bytes_written: the number of bytes stored in the output buffer (not 
538  *                 including the terminating nul).
539  * @error:         location to store the error occuring, or %NULL to ignore
540  *                 errors. Any of the errors in #GConvertError may occur.
541  *
542  * Converts a string from one character set to another.
543  *
544  * Return value: If the conversion was successful, a newly allocated
545  *               nul-terminated string, which must be freed with
546  *               g_free(). Otherwise %NULL and @error will be set.
547  **/
548 gchar*
549 g_convert_with_iconv (const gchar *str,
550                       gssize       len,
551                       GIConv       converter,
552                       gsize       *bytes_read, 
553                       gsize       *bytes_written, 
554                       GError     **error)
555 {
556   gchar *dest;
557   gchar *outp;
558   const gchar *p;
559   gsize inbytes_remaining;
560   gsize outbytes_remaining;
561   gsize err;
562   gsize outbuf_size;
563   gboolean have_error = FALSE;
564   
565   g_return_val_if_fail (str != NULL, NULL);
566   g_return_val_if_fail (converter != (GIConv) -1, NULL);
567      
568   if (len < 0)
569     len = strlen (str);
570
571   p = str;
572   inbytes_remaining = len;
573   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
574   
575   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
576   outp = dest = g_malloc (outbuf_size);
577
578  again:
579   
580   err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
581
582   if (err == (size_t) -1)
583     {
584       switch (errno)
585         {
586         case EINVAL:
587           /* Incomplete text, do not report an error */
588           break;
589         case E2BIG:
590           {
591             size_t used = outp - dest;
592
593             outbuf_size *= 2;
594             dest = g_realloc (dest, outbuf_size);
595                 
596             outp = dest + used;
597             outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
598
599             goto again;
600           }
601         case EILSEQ:
602           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
603                        _("Invalid byte sequence in conversion input"));
604           have_error = TRUE;
605           break;
606         default:
607           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
608                        _("Error during conversion: %s"),
609                        g_strerror (errno));
610           have_error = TRUE;
611           break;
612         }
613     }
614
615   *outp = '\0';
616   
617   if (bytes_read)
618     *bytes_read = p - str;
619   else
620     {
621       if ((p - str) != len) 
622         {
623           if (!have_error)
624             {
625               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
626                            _("Partial character sequence at end of input"));
627               have_error = TRUE;
628             }
629         }
630     }
631
632   if (bytes_written)
633     *bytes_written = outp - dest;       /* Doesn't include '\0' */
634
635   if (have_error)
636     {
637       g_free (dest);
638       return NULL;
639     }
640   else
641     return dest;
642 }
643
644 /**
645  * g_convert_with_fallback:
646  * @str:          the string to convert
647  * @len:          the length of the string
648  * @to_codeset:   name of character set into which to convert @str
649  * @from_codeset: character set of @str.
650  * @fallback:     UTF-8 string to use in place of character not
651  *                present in the target encoding. (This must be
652  *                in the target encoding), if %NULL, characters
653  *                not in the target encoding will be represented
654  *                as Unicode escapes \x{XXXX} or \x{XXXXXX}.
655  * @bytes_read:   location to store the number of bytes in the
656  *                input string that were successfully converted, or %NULL.
657  *                Even if the conversion was successful, this may be 
658  *                less than @len if there were partial characters
659  *                at the end of the input.
660  * @bytes_written: the number of bytes stored in the output buffer (not 
661  *                including the terminating nul).
662  * @error:        location to store the error occuring, or %NULL to ignore
663  *                errors. Any of the errors in #GConvertError may occur.
664  *
665  * Converts a string from one character set to another, possibly
666  * including fallback sequences for characters not representable
667  * in the output. Note that it is not guaranteed that the specification
668  * for the fallback sequences in @fallback will be honored. Some
669  * systems may do a approximate conversion from @from_codeset
670  * to @to_codeset in their <function>iconv()</function> functions, 
671  * in which case GLib will simply return that approximate conversion.
672  *
673  * Return value: If the conversion was successful, a newly allocated
674  *               nul-terminated string, which must be freed with
675  *               g_free(). Otherwise %NULL and @error will be set.
676  **/
677 gchar*
678 g_convert_with_fallback (const gchar *str,
679                          gssize       len,    
680                          const gchar *to_codeset,
681                          const gchar *from_codeset,
682                          gchar       *fallback,
683                          gsize       *bytes_read,
684                          gsize       *bytes_written,
685                          GError     **error)
686 {
687   gchar *utf8;
688   gchar *dest;
689   gchar *outp;
690   const gchar *insert_str = NULL;
691   const gchar *p;
692   gsize inbytes_remaining;   
693   const gchar *save_p = NULL;
694   gsize save_inbytes = 0;
695   gsize outbytes_remaining; 
696   gsize err;
697   GIConv cd;
698   gsize outbuf_size;
699   gboolean have_error = FALSE;
700   gboolean done = FALSE;
701
702   GError *local_error = NULL;
703   
704   g_return_val_if_fail (str != NULL, NULL);
705   g_return_val_if_fail (to_codeset != NULL, NULL);
706   g_return_val_if_fail (from_codeset != NULL, NULL);
707      
708   if (len < 0)
709     len = strlen (str);
710   
711   /* Try an exact conversion; we only proceed if this fails
712    * due to an illegal sequence in the input string.
713    */
714   dest = g_convert (str, len, to_codeset, from_codeset, 
715                     bytes_read, bytes_written, &local_error);
716   if (!local_error)
717     return dest;
718
719   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
720     {
721       g_propagate_error (error, local_error);
722       return NULL;
723     }
724   else
725     g_error_free (local_error);
726
727   local_error = NULL;
728   
729   /* No go; to proceed, we need a converter from "UTF-8" to
730    * to_codeset, and the string as UTF-8.
731    */
732   cd = open_converter (to_codeset, "UTF-8", error);
733   if (cd == (GIConv) -1)
734     {
735       if (bytes_read)
736         *bytes_read = 0;
737       
738       if (bytes_written)
739         *bytes_written = 0;
740       
741       return NULL;
742     }
743
744   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
745                     bytes_read, &inbytes_remaining, error);
746   if (!utf8)
747     {
748       close_converter (cd);
749       if (bytes_written)
750         *bytes_written = 0;
751       return NULL;
752     }
753
754   /* Now the heart of the code. We loop through the UTF-8 string, and
755    * whenever we hit an offending character, we form fallback, convert
756    * the fallback to the target codeset, and then go back to
757    * converting the original string after finishing with the fallback.
758    *
759    * The variables save_p and save_inbytes store the input state
760    * for the original string while we are converting the fallback
761    */
762   p = utf8;
763
764   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
765   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
766   outp = dest = g_malloc (outbuf_size);
767
768   while (!done && !have_error)
769     {
770       size_t inbytes_tmp = inbytes_remaining;
771       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
772       inbytes_remaining = inbytes_tmp;
773
774       if (err == (size_t) -1)
775         {
776           switch (errno)
777             {
778             case EINVAL:
779               g_assert_not_reached();
780               break;
781             case E2BIG:
782               {
783                 size_t used = outp - dest;
784
785                 outbuf_size *= 2;
786                 dest = g_realloc (dest, outbuf_size);
787                 
788                 outp = dest + used;
789                 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
790                 
791                 break;
792               }
793             case EILSEQ:
794               if (save_p)
795                 {
796                   /* Error converting fallback string - fatal
797                    */
798                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
799                                _("Cannot convert fallback '%s' to codeset '%s'"),
800                                insert_str, to_codeset);
801                   have_error = TRUE;
802                   break;
803                 }
804               else
805                 {
806                   if (!fallback)
807                     { 
808                       gunichar ch = g_utf8_get_char (p);
809                       insert_str = g_strdup_printf ("\\x{%0*X}",
810                                                     (ch < 0x10000) ? 4 : 6,
811                                                     ch);
812                     }
813                   else
814                     insert_str = fallback;
815                   
816                   save_p = g_utf8_next_char (p);
817                   save_inbytes = inbytes_remaining - (save_p - p);
818                   p = insert_str;
819                   inbytes_remaining = strlen (p);
820                 }
821               break;
822             default:
823               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
824                            _("Error during conversion: %s"),
825                            g_strerror (errno));
826               have_error = TRUE;
827               break;
828             }
829         }
830       else
831         {
832           if (save_p)
833             {
834               if (!fallback)
835                 g_free ((gchar *)insert_str);
836               p = save_p;
837               inbytes_remaining = save_inbytes;
838               save_p = NULL;
839             }
840           else
841             done = TRUE;
842         }
843     }
844
845   /* Cleanup
846    */
847   *outp = '\0';
848   
849   close_converter (cd);
850
851   if (bytes_written)
852     *bytes_written = outp - dest;       /* Doesn't include '\0' */
853
854   g_free (utf8);
855
856   if (have_error)
857     {
858       if (save_p && !fallback)
859         g_free ((gchar *)insert_str);
860       g_free (dest);
861       return NULL;
862     }
863   else
864     return dest;
865 }
866
867 /*
868  * g_locale_to_utf8
869  *
870  * 
871  */
872
873 #ifndef G_PLATFORM_WIN32
874
875 static gchar *
876 strdup_len (const gchar *string,
877             gssize       len,
878             gsize       *bytes_written,
879             gsize       *bytes_read,
880             GError      **error)
881          
882 {
883   gsize real_len;
884
885   if (!g_utf8_validate (string, len, NULL))
886     {
887       if (bytes_read)
888         *bytes_read = 0;
889       if (bytes_written)
890         *bytes_written = 0;
891
892       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
893                    _("Invalid byte sequence in conversion input"));
894       return NULL;
895     }
896   
897   if (len < 0)
898     real_len = strlen (string);
899   else
900     {
901       real_len = 0;
902       
903       while (real_len < len && string[real_len])
904         real_len++;
905     }
906   
907   if (bytes_read)
908     *bytes_read = real_len;
909   if (bytes_written)
910     *bytes_written = real_len;
911
912   return g_strndup (string, real_len);
913 }
914
915 #endif
916
917 /**
918  * g_locale_to_utf8:
919  * @opsysstring:   a string in the encoding of the current locale
920  * @len:           the length of the string, or -1 if the string is
921  *                 nul-terminated.
922  * @bytes_read:    location to store the number of bytes in the
923  *                 input string that were successfully converted, or %NULL.
924  *                 Even if the conversion was successful, this may be 
925  *                 less than @len if there were partial characters
926  *                 at the end of the input. If the error
927  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
928  *                 stored will the byte offset after the last valid
929  *                 input sequence.
930  * @bytes_written: the number of bytes stored in the output buffer (not 
931  *                 including the terminating nul).
932  * @error:         location to store the error occuring, or %NULL to ignore
933  *                 errors. Any of the errors in #GConvertError may occur.
934  * 
935  * Converts a string which is in the encoding used for strings by
936  * the C runtime (usually the same as that used by the operating
937  * system) in the current locale into a UTF-8 string.
938  * 
939  * Return value: The converted string, or %NULL on an error.
940  **/
941 gchar *
942 g_locale_to_utf8 (const gchar  *opsysstring,
943                   gssize        len,            
944                   gsize        *bytes_read,    
945                   gsize        *bytes_written,
946                   GError      **error)
947 {
948 #ifdef G_PLATFORM_WIN32
949
950   gint i, clen, total_len, wclen, first;
951   wchar_t *wcs, wc;
952   gchar *result, *bp;
953   const wchar_t *wcp;
954
955   if (len == -1)
956     len = strlen (opsysstring);
957   
958   wcs = g_new (wchar_t, len);
959   wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
960
961   wcp = wcs;
962   total_len = 0;
963   for (i = 0; i < wclen; i++)
964     {
965       wc = *wcp++;
966
967       if (wc < 0x80)
968         total_len += 1;
969       else if (wc < 0x800)
970         total_len += 2;
971       else if (wc < 0x10000)
972         total_len += 3;
973       else if (wc < 0x200000)
974         total_len += 4;
975       else if (wc < 0x4000000)
976         total_len += 5;
977       else
978         total_len += 6;
979     }
980
981   result = g_malloc (total_len + 1);
982   
983   wcp = wcs;
984   bp = result;
985   for (i = 0; i < wclen; i++)
986     {
987       wc = *wcp++;
988
989       if (wc < 0x80)
990         {
991           first = 0;
992           clen = 1;
993         }
994       else if (wc < 0x800)
995         {
996           first = 0xc0;
997           clen = 2;
998         }
999       else if (wc < 0x10000)
1000         {
1001           first = 0xe0;
1002           clen = 3;
1003         }
1004       else if (wc < 0x200000)
1005         {
1006           first = 0xf0;
1007           clen = 4;
1008         }
1009       else if (wc < 0x4000000)
1010         {
1011           first = 0xf8;
1012           clen = 5;
1013         }
1014       else
1015         {
1016           first = 0xfc;
1017           clen = 6;
1018         }
1019       
1020       /* Woo-hoo! */
1021       switch (clen)
1022         {
1023         case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1024         case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1025         case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1026         case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1027         case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
1028         case 1: bp[0] = wc | first;
1029         }
1030
1031       bp += clen;
1032     }
1033   *bp = 0;
1034
1035   g_free (wcs);
1036
1037   if (bytes_read)
1038     *bytes_read = len;
1039   if (bytes_written)
1040     *bytes_written = total_len;
1041   
1042   return result;
1043
1044 #else  /* !G_PLATFORM_WIN32 */
1045
1046   const char *charset;
1047
1048   if (g_get_charset (&charset))
1049     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1050   else
1051     return g_convert (opsysstring, len, 
1052                       "UTF-8", charset, bytes_read, bytes_written, error);
1053
1054 #endif /* !G_PLATFORM_WIN32 */
1055 }
1056
1057 /**
1058  * g_locale_from_utf8:
1059  * @utf8string:    a UTF-8 encoded string 
1060  * @len:           the length of the string, or -1 if the string is
1061  *                 nul-terminated.
1062  * @bytes_read:    location to store the number of bytes in the
1063  *                 input string that were successfully converted, or %NULL.
1064  *                 Even if the conversion was successful, this may be 
1065  *                 less than @len if there were partial characters
1066  *                 at the end of the input. If the error
1067  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1068  *                 stored will the byte offset after the last valid
1069  *                 input sequence.
1070  * @bytes_written: the number of bytes stored in the output buffer (not 
1071  *                 including the terminating nul).
1072  * @error:         location to store the error occuring, or %NULL to ignore
1073  *                 errors. Any of the errors in #GConvertError may occur.
1074  * 
1075  * Converts a string from UTF-8 to the encoding used for strings by
1076  * the C runtime (usually the same as that used by the operating
1077  * system) in the current locale.
1078  * 
1079  * Return value: The converted string, or %NULL on an error.
1080  **/
1081 gchar *
1082 g_locale_from_utf8 (const gchar *utf8string,
1083                     gssize       len,            
1084                     gsize       *bytes_read,    
1085                     gsize       *bytes_written,
1086                     GError     **error)
1087 {
1088 #ifdef G_PLATFORM_WIN32
1089
1090   gint i, mask, clen, mblen;
1091   wchar_t *wcs, *wcp;
1092   gchar *result;
1093   guchar *cp, *end, c;
1094   gint n;
1095   
1096   if (len == -1)
1097     len = strlen (utf8string);
1098   
1099   /* First convert to wide chars */
1100   cp = (guchar *) utf8string;
1101   end = cp + len;
1102   n = 0;
1103   wcs = g_new (wchar_t, len + 1);
1104   wcp = wcs;
1105   while (cp != end)
1106     {
1107       mask = 0;
1108       c = *cp;
1109
1110       if (c < 0x80)
1111         {
1112           clen = 1;
1113           mask = 0x7f;
1114         }
1115       else if ((c & 0xe0) == 0xc0)
1116         {
1117           clen = 2;
1118           mask = 0x1f;
1119         }
1120       else if ((c & 0xf0) == 0xe0)
1121         {
1122           clen = 3;
1123           mask = 0x0f;
1124         }
1125       else if ((c & 0xf8) == 0xf0)
1126         {
1127           clen = 4;
1128           mask = 0x07;
1129         }
1130       else if ((c & 0xfc) == 0xf8)
1131         {
1132           clen = 5;
1133           mask = 0x03;
1134         }
1135       else if ((c & 0xfc) == 0xfc)
1136         {
1137           clen = 6;
1138           mask = 0x01;
1139         }
1140       else
1141         {
1142           g_free (wcs);
1143           return NULL;
1144         }
1145
1146       if (cp + clen > end)
1147         {
1148           g_free (wcs);
1149           return NULL;
1150         }
1151
1152       *wcp = (cp[0] & mask);
1153       for (i = 1; i < clen; i++)
1154         {
1155           if ((cp[i] & 0xc0) != 0x80)
1156             {
1157               g_free (wcs);
1158               return NULL;
1159             }
1160           *wcp <<= 6;
1161           *wcp |= (cp[i] & 0x3f);
1162         }
1163
1164       cp += clen;
1165       wcp++;
1166       n++;
1167     }
1168   if (cp != end)
1169     {
1170       g_free (wcs);
1171       return NULL;
1172     }
1173
1174   /* n is the number of wide chars constructed */
1175
1176   /* Convert to a string in the current ANSI codepage */
1177
1178   result = g_new (gchar, 3 * n + 1);
1179   mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
1180   result[mblen] = 0;
1181   g_free (wcs);
1182
1183   if (bytes_read)
1184     *bytes_read = len;
1185   if (bytes_written)
1186     *bytes_written = mblen;
1187   
1188   return result;
1189
1190 #else  /* !G_PLATFORM_WIN32 */
1191   
1192   const gchar *charset;
1193
1194   if (g_get_charset (&charset))
1195     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1196   else
1197     return g_convert (utf8string, len,
1198                       charset, "UTF-8", bytes_read, bytes_written, error);
1199
1200 #endif /* !G_PLATFORM_WIN32 */
1201 }
1202
1203 #ifndef G_PLATFORM_WIN32
1204 static gboolean
1205 have_broken_filenames (void)
1206 {
1207   static gboolean initialized = FALSE;
1208   static gboolean broken;
1209   
1210   if (initialized)
1211     return broken;
1212
1213   broken = (getenv ("G_BROKEN_FILENAMES") != NULL);
1214   
1215   initialized = TRUE;
1216   
1217   return broken;
1218 }
1219 #endif /* !G_PLATFORM_WIN32 */
1220
1221 /* This is called from g_thread_init(). It's used to
1222  * initialize some static data in a threadsafe way.
1223  */
1224 void 
1225 g_convert_init (void)
1226 {
1227 #ifndef G_PLATFORM_WIN32
1228   (void)have_broken_filenames ();
1229 #endif /* !G_PLATFORM_WIN32 */
1230 }
1231
1232 /**
1233  * g_filename_to_utf8:
1234  * @opsysstring:   a string in the encoding for filenames
1235  * @len:           the length of the string, or -1 if the string is
1236  *                 nul-terminated.
1237  * @bytes_read:    location to store the number of bytes in the
1238  *                 input string that were successfully converted, or %NULL.
1239  *                 Even if the conversion was successful, this may be 
1240  *                 less than @len if there were partial characters
1241  *                 at the end of the input. If the error
1242  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1243  *                 stored will the byte offset after the last valid
1244  *                 input sequence.
1245  * @bytes_written: the number of bytes stored in the output buffer (not 
1246  *                 including the terminating nul).
1247  * @error:         location to store the error occuring, or %NULL to ignore
1248  *                 errors. Any of the errors in #GConvertError may occur.
1249  * 
1250  * Converts a string which is in the encoding used for filenames
1251  * into a UTF-8 string.
1252  * 
1253  * Return value: The converted string, or %NULL on an error.
1254  **/
1255 gchar*
1256 g_filename_to_utf8 (const gchar *opsysstring, 
1257                     gssize       len,           
1258                     gsize       *bytes_read,   
1259                     gsize       *bytes_written,
1260                     GError     **error)
1261 {
1262 #ifdef G_PLATFORM_WIN32
1263   return g_locale_to_utf8 (opsysstring, len,
1264                            bytes_read, bytes_written,
1265                            error);
1266 #else  /* !G_PLATFORM_WIN32 */
1267       
1268   if (have_broken_filenames ())
1269     return g_locale_to_utf8 (opsysstring, len,
1270                              bytes_read, bytes_written,
1271                              error);
1272   else
1273     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1274 #endif /* !G_PLATFORM_WIN32 */
1275 }
1276
1277 /**
1278  * g_filename_from_utf8:
1279  * @utf8string:    a UTF-8 encoded string.
1280  * @len:           the length of the string, or -1 if the string is
1281  *                 nul-terminated.
1282  * @bytes_read:    location to store the number of bytes in the
1283  *                 input string that were successfully converted, or %NULL.
1284  *                 Even if the conversion was successful, this may be 
1285  *                 less than @len if there were partial characters
1286  *                 at the end of the input. If the error
1287  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1288  *                 stored will the byte offset after the last valid
1289  *                 input sequence.
1290  * @bytes_written: the number of bytes stored in the output buffer (not 
1291  *                 including the terminating nul).
1292  * @error:         location to store the error occuring, or %NULL to ignore
1293  *                 errors. Any of the errors in #GConvertError may occur.
1294  * 
1295  * Converts a string from UTF-8 to the encoding used for filenames.
1296  * 
1297  * Return value: The converted string, or %NULL on an error.
1298  **/
1299 gchar*
1300 g_filename_from_utf8 (const gchar *utf8string,
1301                       gssize       len,            
1302                       gsize       *bytes_read,    
1303                       gsize       *bytes_written,
1304                       GError     **error)
1305 {
1306 #ifdef G_PLATFORM_WIN32
1307   return g_locale_from_utf8 (utf8string, len,
1308                              bytes_read, bytes_written,
1309                              error);
1310 #else  /* !G_PLATFORM_WIN32 */
1311   if (have_broken_filenames ())
1312     return g_locale_from_utf8 (utf8string, len,
1313                                bytes_read, bytes_written,
1314                                error);
1315   else
1316     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1317 #endif /* !G_PLATFORM_WIN32 */
1318 }
1319
1320 /* Test of haystack has the needle prefix, comparing case
1321  * insensitive. haystack may be UTF-8, but needle must
1322  * contain only ascii. */
1323 static gboolean
1324 has_case_prefix (const gchar *haystack, const gchar *needle)
1325 {
1326   const gchar *h, *n;
1327   
1328   /* Eat one character at a time. */
1329   h = haystack;
1330   n = needle;
1331
1332   while (*n && *h &&
1333          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1334     {
1335       n++;
1336       h++;
1337     }
1338   
1339   return *n == '\0';
1340 }
1341
1342 typedef enum {
1343   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1344   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1345   UNSAFE_PATH       = 0x4,  /* Allows '/' and '?' and '&' and '='  */
1346   UNSAFE_DOS_PATH   = 0x8,  /* Allows '/' and '?' and '&' and '=' and ':' */
1347   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1348   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1349 } UnsafeCharacterSet;
1350
1351 static const guchar acceptable[96] = {
1352   /* A table of the ASCII chars from space (32) to DEL (127) */
1353   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1354   0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1355   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1356   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1357   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1358   0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1359   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1360   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1361   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1362   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1363   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1364   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1365 };
1366
1367 static const gchar hex[16] = "0123456789ABCDEF";
1368
1369 /* Note: This escape function works on file: URIs, but if you want to
1370  * escape something else, please read RFC-2396 */
1371 static gchar *
1372 g_escape_uri_string (const gchar *string, 
1373                      UnsafeCharacterSet mask)
1374 {
1375 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1376
1377   const gchar *p;
1378   gchar *q;
1379   gchar *result;
1380   int c;
1381   gint unacceptable;
1382   UnsafeCharacterSet use_mask;
1383   
1384   g_return_val_if_fail (mask == UNSAFE_ALL
1385                         || mask == UNSAFE_ALLOW_PLUS
1386                         || mask == UNSAFE_PATH
1387                         || mask == UNSAFE_DOS_PATH
1388                         || mask == UNSAFE_HOST
1389                         || mask == UNSAFE_SLASHES, NULL);
1390   
1391   unacceptable = 0;
1392   use_mask = mask;
1393   for (p = string; *p != '\0'; p++)
1394     {
1395       c = (guchar) *p;
1396       if (!ACCEPTABLE (c)) 
1397         unacceptable++;
1398     }
1399   
1400   result = g_malloc (p - string + unacceptable * 2 + 1);
1401   
1402   use_mask = mask;
1403   for (q = result, p = string; *p != '\0'; p++)
1404     {
1405       c = (guchar) *p;
1406       
1407       if (!ACCEPTABLE (c))
1408         {
1409           *q++ = '%'; /* means hex coming */
1410           *q++ = hex[c >> 4];
1411           *q++ = hex[c & 15];
1412         }
1413       else
1414         *q++ = *p;
1415     }
1416   
1417   *q = '\0';
1418   
1419   return result;
1420 }
1421
1422
1423 static gchar *
1424 g_escape_file_uri (const gchar *hostname,
1425                    const gchar *pathname)
1426 {
1427   char *escaped_hostname = NULL;
1428   char *escaped_path;
1429   char *res;
1430
1431 #ifdef G_OS_WIN32
1432   char *p, *backslash;
1433
1434   /* Turn backslashes into forward slashes. That's what Netscape
1435    * does, and they are actually more or less equivalent in Windows.
1436    */
1437   
1438   pathname = g_strdup (pathname);
1439   p = (char *) pathname;
1440   
1441   while ((backslash = strchr (p, '\\')) != NULL)
1442     {
1443       *backslash = '/';
1444       p = backslash + 1;
1445     }
1446 #endif
1447
1448   if (hostname && *hostname != '\0')
1449     {
1450       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1451     }
1452
1453   escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1454
1455   res = g_strconcat ("file://",
1456                      (escaped_hostname) ? escaped_hostname : "",
1457                      (*escaped_path != '/') ? "/" : "",
1458                      escaped_path,
1459                      NULL);
1460
1461 #ifdef G_OS_WIN32
1462   g_free ((char *) pathname);
1463 #endif
1464
1465   g_free (escaped_hostname);
1466   g_free (escaped_path);
1467   
1468   return res;
1469 }
1470
1471 static int
1472 unescape_character (const char *scanner)
1473 {
1474   int first_digit;
1475   int second_digit;
1476
1477   first_digit = g_ascii_xdigit_value (scanner[0]);
1478   if (first_digit < 0) 
1479     return -1;
1480   
1481   second_digit = g_ascii_xdigit_value (scanner[1]);
1482   if (second_digit < 0) 
1483     return -1;
1484   
1485   return (first_digit << 4) | second_digit;
1486 }
1487
1488 static gchar *
1489 g_unescape_uri_string (const char *escaped,
1490                        int         len,
1491                        const char *illegal_escaped_characters,
1492                        gboolean    ascii_must_not_be_escaped)
1493 {
1494   const gchar *in, *in_end;
1495   gchar *out, *result;
1496   int c;
1497   
1498   if (escaped == NULL)
1499     return NULL;
1500
1501   if (len < 0)
1502     len = strlen (escaped);
1503
1504   result = g_malloc (len + 1);
1505   
1506   out = result;
1507   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1508     {
1509       c = *in;
1510
1511       if (c == '%')
1512         {
1513           /* catch partial escape sequences past the end of the substring */
1514           if (in + 3 > in_end)
1515             break;
1516
1517           c = unescape_character (in + 1);
1518
1519           /* catch bad escape sequences and NUL characters */
1520           if (c <= 0)
1521             break;
1522
1523           /* catch escaped ASCII */
1524           if (ascii_must_not_be_escaped && c <= 0x7F)
1525             break;
1526
1527           /* catch other illegal escaped characters */
1528           if (strchr (illegal_escaped_characters, c) != NULL)
1529             break;
1530
1531           in += 2;
1532         }
1533
1534       *out++ = c;
1535     }
1536   
1537   g_assert (out - result <= len);
1538   *out = '\0';
1539
1540   if (in != in_end || !g_utf8_validate (result, -1, NULL))
1541     {
1542       g_free (result);
1543       return NULL;
1544     }
1545
1546   return result;
1547 }
1548
1549 static gboolean
1550 is_escalphanum (gunichar c)
1551 {
1552   return c > 0x7F || g_ascii_isalnum (c);
1553 }
1554
1555 static gboolean
1556 is_escalpha (gunichar c)
1557 {
1558   return c > 0x7F || g_ascii_isalpha (c);
1559 }
1560
1561 /* allows an empty string */
1562 static gboolean
1563 hostname_validate (const char *hostname)
1564 {
1565   const char *p;
1566   gunichar c, first_char, last_char;
1567
1568   p = hostname;
1569   if (*p == '\0')
1570     return TRUE;
1571   do
1572     {
1573       /* read in a label */
1574       c = g_utf8_get_char (p);
1575       p = g_utf8_next_char (p);
1576       if (!is_escalphanum (c))
1577         return FALSE;
1578       first_char = c;
1579       do
1580         {
1581           last_char = c;
1582           c = g_utf8_get_char (p);
1583           p = g_utf8_next_char (p);
1584         }
1585       while (is_escalphanum (c) || c == '-');
1586       if (last_char == '-')
1587         return FALSE;
1588       
1589       /* if that was the last label, check that it was a toplabel */
1590       if (c == '\0' || (c == '.' && *p == '\0'))
1591         return is_escalpha (first_char);
1592     }
1593   while (c == '.');
1594   return FALSE;
1595 }
1596
1597 /**
1598  * g_filename_from_uri:
1599  * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1600  * @hostname: Location to store hostname for the URI, or %NULL.
1601  *            If there is no hostname in the URI, %NULL will be
1602  *            stored in this location.
1603  * @error: location to store the error occuring, or %NULL to ignore
1604  *         errors. Any of the errors in #GConvertError may occur.
1605  * 
1606  * Converts an escaped UTF-8 encoded URI to a local filename in the
1607  * encoding used for filenames. 
1608  * 
1609  * Return value: a newly-allocated string holding the resulting
1610  *               filename, or %NULL on an error.
1611  **/
1612 gchar *
1613 g_filename_from_uri (const char *uri,
1614                      char      **hostname,
1615                      GError    **error)
1616 {
1617   const char *path_part;
1618   const char *host_part;
1619   char *unescaped_hostname;
1620   char *result;
1621   char *filename;
1622   int offs;
1623 #ifdef G_OS_WIN32
1624   char *p, *slash;
1625 #endif
1626
1627   if (hostname)
1628     *hostname = NULL;
1629
1630   if (!has_case_prefix (uri, "file:/"))
1631     {
1632       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1633                    _("The URI '%s' is not an absolute URI using the file scheme"),
1634                    uri);
1635       return NULL;
1636     }
1637   
1638   path_part = uri + strlen ("file:");
1639   
1640   if (strchr (path_part, '#') != NULL)
1641     {
1642       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1643                    _("The local file URI '%s' may not include a '#'"),
1644                    uri);
1645       return NULL;
1646     }
1647         
1648   if (has_case_prefix (path_part, "///")) 
1649     path_part += 2;
1650   else if (has_case_prefix (path_part, "//"))
1651     {
1652       path_part += 2;
1653       host_part = path_part;
1654
1655       path_part = strchr (path_part, '/');
1656
1657       if (path_part == NULL)
1658         {
1659           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1660                        _("The URI '%s' is invalid"),
1661                        uri);
1662           return NULL;
1663         }
1664
1665       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1666
1667       if (unescaped_hostname == NULL ||
1668           !hostname_validate (unescaped_hostname))
1669         {
1670           g_free (unescaped_hostname);
1671           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1672                        _("The hostname of the URI '%s' is invalid"),
1673                        uri);
1674           return NULL;
1675         }
1676       
1677       if (hostname)
1678         *hostname = unescaped_hostname;
1679       else
1680         g_free (unescaped_hostname);
1681     }
1682
1683   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1684
1685   if (filename == NULL)
1686     {
1687       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1688                    _("The URI '%s' contains invalidly escaped characters"),
1689                    uri);
1690       return NULL;
1691     }
1692
1693   offs = 0;
1694 #ifdef G_OS_WIN32
1695   /* Drop localhost */
1696   if (hostname && *hostname != NULL &&
1697       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1698     {
1699       g_free (*hostname);
1700       *hostname = NULL;
1701     }
1702
1703   /* Turn slashes into backslashes, because that's the canonical spelling */
1704   p = filename;
1705   while ((slash = strchr (p, '/')) != NULL)
1706     {
1707       *slash = '\\';
1708       p = slash + 1;
1709     }
1710
1711   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1712    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1713    * the filename from the drive letter.
1714    */
1715   if (g_ascii_isalpha (filename[1]))
1716     {
1717       if (filename[2] == ':')
1718         offs = 1;
1719       else if (filename[2] == '|')
1720         {
1721           filename[2] = ':';
1722           offs = 1;
1723         }
1724     }
1725 #endif
1726   
1727   result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1728   g_free (filename);
1729   
1730   return result;
1731 }
1732
1733 /**
1734  * g_filename_to_uri:
1735  * @filename: an absolute filename specified in the encoding
1736  *            used for filenames by the operating system.
1737  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1738  * @error: location to store the error occuring, or %NULL to ignore
1739  *         errors. Any of the errors in #GConvertError may occur.
1740  * 
1741  * Converts an absolute filename to an escaped UTF-8 encoded URI.
1742  * 
1743  * Return value: a newly-allocated string holding the resulting
1744  *               URI, or %NULL on an error.
1745  **/
1746 gchar *
1747 g_filename_to_uri   (const char *filename,
1748                      const char *hostname,
1749                      GError    **error)
1750 {
1751   char *escaped_uri;
1752   char *utf8_filename;
1753
1754   g_return_val_if_fail (filename != NULL, NULL);
1755
1756   if (!g_path_is_absolute (filename))
1757     {
1758       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1759                    _("The pathname '%s' is not an absolute path"),
1760                    filename);
1761       return NULL;
1762     }
1763
1764   if (hostname &&
1765       !(g_utf8_validate (hostname, -1, NULL)
1766         && hostname_validate (hostname)))
1767     {
1768       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1769                    _("Invalid hostname"));
1770       return NULL;
1771     }
1772   
1773   utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1774   if (utf8_filename == NULL)
1775     return NULL;
1776   
1777 #ifdef G_OS_WIN32
1778   /* Don't use localhost unnecessarily */
1779   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1780     hostname = NULL;
1781 #endif
1782
1783   escaped_uri = g_escape_file_uri (hostname,
1784                                    utf8_filename);
1785   g_free (utf8_filename);
1786   
1787   return escaped_uri;
1788 }
1789