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