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