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