Check for iconv_* in -liconv as well as libiconv_* in -liconv since AIX
[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   iconv_t 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, iconv_t 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 == (iconv_t) -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 == (iconv_t) -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, 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   iconv_t cd;
406   
407   cd = (iconv_t) converter;
408   
409   if (cd == (iconv_t) -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                        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                            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 /**
1193  * g_filename_to_utf8:
1194  * @opsysstring:   a string in the encoding for filenames
1195  * @len:           the length of the string, or -1 if the string is
1196  *                 nul-terminated.
1197  * @bytes_read:    location to store the number of bytes in the
1198  *                 input string that were successfully converted, or %NULL.
1199  *                 Even if the conversion was successful, this may be 
1200  *                 less than @len if there were partial characters
1201  *                 at the end of the input. If the error
1202  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1203  *                 stored will the byte offset after the last valid
1204  *                 input sequence.
1205  * @bytes_written: the number of bytes stored in the output buffer (not 
1206  *                 including the terminating nul).
1207  * @error:         location to store the error occuring, or %NULL to ignore
1208  *                 errors. Any of the errors in #GConvertError may occur.
1209  * 
1210  * Converts a string which is in the encoding used for filenames
1211  * into a UTF-8 string.
1212  * 
1213  * Return value: The converted string, or %NULL on an error.
1214  **/
1215 gchar*
1216 g_filename_to_utf8 (const gchar *opsysstring, 
1217                     gssize       len,           
1218                     gsize       *bytes_read,   
1219                     gsize       *bytes_written,
1220                     GError     **error)
1221 {
1222 #ifdef G_PLATFORM_WIN32
1223   return g_locale_to_utf8 (opsysstring, len,
1224                            bytes_read, bytes_written,
1225                            error);
1226 #else  /* !G_PLATFORM_WIN32 */
1227       
1228   if (getenv ("G_BROKEN_FILENAMES"))
1229     return g_locale_to_utf8 (opsysstring, len,
1230                              bytes_read, bytes_written,
1231                              error);
1232   else
1233     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1234 #endif /* !G_PLATFORM_WIN32 */
1235 }
1236
1237 /**
1238  * g_filename_from_utf8:
1239  * @utf8string:    a UTF-8 encoded string.
1240  * @len:           the length of the string, or -1 if the string is
1241  *                 nul-terminated.
1242  * @bytes_read:    location to store the number of bytes in the
1243  *                 input string that were successfully converted, or %NULL.
1244  *                 Even if the conversion was successful, this may be 
1245  *                 less than @len if there were partial characters
1246  *                 at the end of the input. If the error
1247  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1248  *                 stored will the byte offset after the last valid
1249  *                 input sequence.
1250  * @bytes_written: the number of bytes stored in the output buffer (not 
1251  *                 including the terminating nul).
1252  * @error:         location to store the error occuring, or %NULL to ignore
1253  *                 errors. Any of the errors in #GConvertError may occur.
1254  * 
1255  * Converts a string from UTF-8 to the encoding used for filenames.
1256  * 
1257  * Return value: The converted string, or %NULL on an error.
1258  **/
1259 gchar*
1260 g_filename_from_utf8 (const gchar *utf8string,
1261                       gssize       len,            
1262                       gsize       *bytes_read,    
1263                       gsize       *bytes_written,
1264                       GError     **error)
1265 {
1266 #ifdef G_PLATFORM_WIN32
1267   return g_locale_from_utf8 (utf8string, len,
1268                              bytes_read, bytes_written,
1269                              error);
1270 #else  /* !G_PLATFORM_WIN32 */
1271   if (getenv ("G_BROKEN_FILENAMES"))
1272     return g_locale_from_utf8 (utf8string, len,
1273                                bytes_read, bytes_written,
1274                                error);
1275   else
1276     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1277 #endif /* !G_PLATFORM_WIN32 */
1278 }
1279
1280 /* Test of haystack has the needle prefix, comparing case
1281  * insensitive. haystack may be UTF-8, but needle must
1282  * contain only ascii. */
1283 static gboolean
1284 has_case_prefix (const gchar *haystack, const gchar *needle)
1285 {
1286   const gchar *h, *n;
1287   
1288   /* Eat one character at a time. */
1289   h = haystack;
1290   n = needle;
1291
1292   while (*n && *h &&
1293          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1294     {
1295       n++;
1296       h++;
1297     }
1298   
1299   return *n == '\0';
1300 }
1301
1302 typedef enum {
1303   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1304   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1305   UNSAFE_PATH       = 0x4,  /* Allows '/' and '?' and '&' and '='  */
1306   UNSAFE_DOS_PATH   = 0x8,  /* Allows '/' and '?' and '&' and '=' and ':' */
1307   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1308   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1309 } UnsafeCharacterSet;
1310
1311 static const guchar acceptable[96] = {
1312   /* A table of the ASCII chars from space (32) to DEL (127) */
1313   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1314   0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1315   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1316   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1317   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1318   0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1319   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1320   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1321   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1322   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1323   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1324   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1325 };
1326
1327 static const gchar hex[16] = "0123456789ABCDEF";
1328
1329 /* Note: This escape function works on file: URIs, but if you want to
1330  * escape something else, please read RFC-2396 */
1331 static gchar *
1332 g_escape_uri_string (const gchar *string, 
1333                      UnsafeCharacterSet mask)
1334 {
1335 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1336
1337   const gchar *p;
1338   gchar *q;
1339   gchar *result;
1340   int c;
1341   gint unacceptable;
1342   UnsafeCharacterSet use_mask;
1343   
1344   g_return_val_if_fail (mask == UNSAFE_ALL
1345                         || mask == UNSAFE_ALLOW_PLUS
1346                         || mask == UNSAFE_PATH
1347                         || mask == UNSAFE_DOS_PATH
1348                         || mask == UNSAFE_HOST
1349                         || mask == UNSAFE_SLASHES, NULL);
1350   
1351   unacceptable = 0;
1352   use_mask = mask;
1353   for (p = string; *p != '\0'; p++)
1354     {
1355       c = (guchar) *p;
1356       if (!ACCEPTABLE (c)) 
1357         unacceptable++;
1358     }
1359   
1360   result = g_malloc (p - string + unacceptable * 2 + 1);
1361   
1362   use_mask = mask;
1363   for (q = result, p = string; *p != '\0'; p++)
1364     {
1365       c = (guchar) *p;
1366       
1367       if (!ACCEPTABLE (c))
1368         {
1369           *q++ = '%'; /* means hex coming */
1370           *q++ = hex[c >> 4];
1371           *q++ = hex[c & 15];
1372         }
1373       else
1374         *q++ = *p;
1375     }
1376   
1377   *q = '\0';
1378   
1379   return result;
1380 }
1381
1382
1383 static gchar *
1384 g_escape_file_uri (const gchar *hostname,
1385                    const gchar *pathname)
1386 {
1387   char *escaped_hostname = NULL;
1388   char *escaped_path;
1389   char *res;
1390
1391 #ifdef G_OS_WIN32
1392   char *p, *backslash;
1393
1394   /* Turn backslashes into forward slashes. That's what Netscape
1395    * does, and they are actually more or less equivalent in Windows.
1396    */
1397   
1398   pathname = g_strdup (pathname);
1399   p = (char *) pathname;
1400   
1401   while ((backslash = strchr (p, '\\')) != NULL)
1402     {
1403       *backslash = '/';
1404       p = backslash + 1;
1405     }
1406 #endif
1407
1408   if (hostname && *hostname != '\0')
1409     {
1410       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1411     }
1412
1413   escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1414
1415   res = g_strconcat ("file://",
1416                      (escaped_hostname) ? escaped_hostname : "",
1417                      (*escaped_path != '/') ? "/" : "",
1418                      escaped_path,
1419                      NULL);
1420
1421 #ifdef G_OS_WIN32
1422   g_free ((char *) pathname);
1423 #endif
1424
1425   g_free (escaped_hostname);
1426   g_free (escaped_path);
1427   
1428   return res;
1429 }
1430
1431 static int
1432 unescape_character (const char *scanner)
1433 {
1434   int first_digit;
1435   int second_digit;
1436
1437   first_digit = g_ascii_xdigit_value (scanner[0]);
1438   if (first_digit < 0) 
1439     return -1;
1440   
1441   second_digit = g_ascii_xdigit_value (scanner[1]);
1442   if (second_digit < 0) 
1443     return -1;
1444   
1445   return (first_digit << 4) | second_digit;
1446 }
1447
1448 static gchar *
1449 g_unescape_uri_string (const char *escaped,
1450                        int         len,
1451                        const char *illegal_escaped_characters,
1452                        gboolean    ascii_must_not_be_escaped)
1453 {
1454   const gchar *in, *in_end;
1455   gchar *out, *result;
1456   int c;
1457   
1458   if (escaped == NULL)
1459     return NULL;
1460
1461   if (len < 0)
1462     len = strlen (escaped);
1463
1464   result = g_malloc (len + 1);
1465   
1466   out = result;
1467   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1468     {
1469       c = *in;
1470
1471       if (c == '%')
1472         {
1473           /* catch partial escape sequences past the end of the substring */
1474           if (in + 3 > in_end)
1475             break;
1476
1477           c = unescape_character (in + 1);
1478
1479           /* catch bad escape sequences and NUL characters */
1480           if (c <= 0)
1481             break;
1482
1483           /* catch escaped ASCII */
1484           if (ascii_must_not_be_escaped && c <= 0x7F)
1485             break;
1486
1487           /* catch other illegal escaped characters */
1488           if (strchr (illegal_escaped_characters, c) != NULL)
1489             break;
1490
1491           in += 2;
1492         }
1493
1494       *out++ = c;
1495     }
1496   
1497   g_assert (out - result <= len);
1498   *out = '\0';
1499
1500   if (in != in_end || !g_utf8_validate (result, -1, NULL))
1501     {
1502       g_free (result);
1503       return NULL;
1504     }
1505
1506   return result;
1507 }
1508
1509 static gboolean
1510 is_escalphanum (gunichar c)
1511 {
1512   return c > 0x7F || g_ascii_isalnum (c);
1513 }
1514
1515 static gboolean
1516 is_escalpha (gunichar c)
1517 {
1518   return c > 0x7F || g_ascii_isalpha (c);
1519 }
1520
1521 /* allows an empty string */
1522 static gboolean
1523 hostname_validate (const char *hostname)
1524 {
1525   const char *p;
1526   gunichar c, first_char, last_char;
1527
1528   p = hostname;
1529   if (*p == '\0')
1530     return TRUE;
1531   do
1532     {
1533       /* read in a label */
1534       c = g_utf8_get_char (p);
1535       p = g_utf8_next_char (p);
1536       if (!is_escalphanum (c))
1537         return FALSE;
1538       first_char = c;
1539       do
1540         {
1541           last_char = c;
1542           c = g_utf8_get_char (p);
1543           p = g_utf8_next_char (p);
1544         }
1545       while (is_escalphanum (c) || c == '-');
1546       if (last_char == '-')
1547         return FALSE;
1548       
1549       /* if that was the last label, check that it was a toplabel */
1550       if (c == '\0' || (c == '.' && *p == '\0'))
1551         return is_escalpha (first_char);
1552     }
1553   while (c == '.');
1554   return FALSE;
1555 }
1556
1557 /**
1558  * g_filename_from_uri:
1559  * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1560  * @hostname: Location to store hostname for the URI, or %NULL.
1561  *            If there is no hostname in the URI, %NULL will be
1562  *            stored in this location.
1563  * @error: location to store the error occuring, or %NULL to ignore
1564  *         errors. Any of the errors in #GConvertError may occur.
1565  * 
1566  * Converts an escaped UTF-8 encoded URI to a local filename in the
1567  * encoding used for filenames. 
1568  * 
1569  * Return value: a newly-allocated string holding the resulting
1570  *               filename, or %NULL on an error.
1571  **/
1572 gchar *
1573 g_filename_from_uri (const char *uri,
1574                      char      **hostname,
1575                      GError    **error)
1576 {
1577   const char *path_part;
1578   const char *host_part;
1579   char *unescaped_hostname;
1580   char *result;
1581   char *filename;
1582   int offs;
1583 #ifdef G_OS_WIN32
1584   char *p, *slash;
1585 #endif
1586
1587   if (hostname)
1588     *hostname = NULL;
1589
1590   if (!has_case_prefix (uri, "file:/"))
1591     {
1592       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1593                    _("The URI '%s' is not an absolute URI using the file scheme"),
1594                    uri);
1595       return NULL;
1596     }
1597   
1598   path_part = uri + strlen ("file:");
1599   
1600   if (strchr (path_part, '#') != NULL)
1601     {
1602       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1603                    _("The local file URI '%s' may not include a '#'"),
1604                    uri);
1605       return NULL;
1606     }
1607         
1608   if (has_case_prefix (path_part, "///")) 
1609     path_part += 2;
1610   else if (has_case_prefix (path_part, "//"))
1611     {
1612       path_part += 2;
1613       host_part = path_part;
1614
1615       path_part = strchr (path_part, '/');
1616
1617       if (path_part == NULL)
1618         {
1619           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1620                        _("The URI '%s' is invalid"),
1621                        uri);
1622           return NULL;
1623         }
1624
1625       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1626
1627       if (unescaped_hostname == NULL ||
1628           !hostname_validate (unescaped_hostname))
1629         {
1630           g_free (unescaped_hostname);
1631           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1632                        _("The hostname of the URI '%s' is invalid"),
1633                        uri);
1634           return NULL;
1635         }
1636       
1637       if (hostname)
1638         *hostname = unescaped_hostname;
1639       else
1640         g_free (unescaped_hostname);
1641     }
1642
1643   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1644
1645   if (filename == NULL)
1646     {
1647       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1648                    _("The URI '%s' contains invalidly escaped characters"),
1649                    uri);
1650       return NULL;
1651     }
1652
1653   offs = 0;
1654 #ifdef G_OS_WIN32
1655   /* Drop localhost */
1656   if (hostname && *hostname != NULL &&
1657       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1658     {
1659       g_free (*hostname);
1660       *hostname = NULL;
1661     }
1662
1663   /* Turn slashes into backslashes, because that's the canonical spelling */
1664   p = filename;
1665   while ((slash = strchr (p, '/')) != NULL)
1666     {
1667       *slash = '\\';
1668       p = slash + 1;
1669     }
1670
1671   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1672    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1673    * the filename from the drive letter.
1674    */
1675   if (g_ascii_isalpha (filename[1]))
1676     {
1677       if (filename[2] == ':')
1678         offs = 1;
1679       else if (filename[2] == '|')
1680         {
1681           filename[2] = ':';
1682           offs = 1;
1683         }
1684     }
1685 #endif
1686   
1687   result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1688   g_free (filename);
1689   
1690   return result;
1691 }
1692
1693 /**
1694  * g_filename_to_uri:
1695  * @filename: an absolute filename specified in the encoding
1696  *            used for filenames by the operating system.
1697  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1698  * @error: location to store the error occuring, or %NULL to ignore
1699  *         errors. Any of the errors in #GConvertError may occur.
1700  * 
1701  * Converts an absolute filename to an escaped UTF-8 encoded URI.
1702  * 
1703  * Return value: a newly-allocated string holding the resulting
1704  *               URI, or %NULL on an error.
1705  **/
1706 gchar *
1707 g_filename_to_uri   (const char *filename,
1708                      const char *hostname,
1709                      GError    **error)
1710 {
1711   char *escaped_uri;
1712   char *utf8_filename;
1713
1714   g_return_val_if_fail (filename != NULL, NULL);
1715
1716   if (!g_path_is_absolute (filename))
1717     {
1718       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1719                    _("The pathname '%s' is not an absolute path"),
1720                    filename);
1721       return NULL;
1722     }
1723
1724   if (hostname &&
1725       !(g_utf8_validate (hostname, -1, NULL)
1726         && hostname_validate (hostname)))
1727     {
1728       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1729                    _("Invalid hostname"));
1730       return NULL;
1731     }
1732   
1733   utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1734   if (utf8_filename == NULL)
1735     return NULL;
1736   
1737 #ifdef G_OS_WIN32
1738   /* Don't use localhost unnecessarily */
1739   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1740     hostname = NULL;
1741 #endif
1742
1743   escaped_uri = g_escape_file_uri (hostname,
1744                                    utf8_filename);
1745   g_free (utf8_filename);
1746   
1747   return escaped_uri;
1748 }
1749