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