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