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