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