Convert G_CONVERT_ERROR_NOT_ABSOLUTE_FILE_URI and
[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 <iconv.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <stdlib.h>
27
28 #include "glib.h"
29 #include "config.h"
30
31 #ifdef G_PLATFORM_WIN32
32 #define STRICT
33 #include <windows.h>
34 #undef STRICT
35 #endif
36
37 #include "glibintl.h"
38
39 GQuark 
40 g_convert_error_quark()
41 {
42   static GQuark quark;
43   if (!quark)
44     quark = g_quark_from_static_string ("g_convert_error");
45
46   return quark;
47 }
48
49 #if defined(USE_LIBICONV) && !defined (_LIBICONV_H)
50 #error libiconv in use but included iconv.h not from libiconv
51 #endif
52 #if !defined(USE_LIBICONV) && defined (_LIBICONV_H)
53 #error libiconv not in use but included iconv.h is from libiconv
54 #endif
55
56 static gboolean
57 try_conversion (const char *to_codeset,
58                 const char *from_codeset,
59                 iconv_t    *cd)
60 {
61   *cd = iconv_open (to_codeset, from_codeset);
62
63   if (*cd == (iconv_t)-1 && errno == EINVAL)
64     return FALSE;
65   else
66     return TRUE;
67 }
68
69 static gboolean
70 try_to_aliases (const char **to_aliases,
71                 const char  *from_codeset,
72                 iconv_t     *cd)
73 {
74   if (to_aliases)
75     {
76       const char **p = to_aliases;
77       while (*p)
78         {
79           if (try_conversion (*p, from_codeset, cd))
80             return TRUE;
81
82           p++;
83         }
84     }
85
86   return FALSE;
87 }
88
89 extern const char **_g_charset_get_aliases (const char *canonical_name);
90
91 /**
92  * g_iconv_open:
93  * @to_codeset: destination codeset
94  * @from_codeset: source codeset
95  * 
96  * Same as the standard UNIX routine iconv_open(), but
97  * may be implemented via libiconv on UNIX flavors that lack
98  * a native implementation.
99  * 
100  * GLib provides g_convert() and g_locale_to_utf8() which are likely
101  * more convenient than the raw iconv wrappers.
102  * 
103  * Return value: a "conversion descriptor"
104  **/
105 GIConv
106 g_iconv_open (const gchar  *to_codeset,
107               const gchar  *from_codeset)
108 {
109   iconv_t cd;
110   
111   if (!try_conversion (to_codeset, from_codeset, &cd))
112     {
113       const char **to_aliases = _g_charset_get_aliases (to_codeset);
114       const char **from_aliases = _g_charset_get_aliases (to_codeset);
115
116       if (from_aliases)
117         {
118           const char **p = from_aliases;
119           while (*p)
120             {
121               if (try_conversion (to_codeset, *p, &cd))
122                 return (GIConv)cd;
123
124               if (try_to_aliases (to_aliases, *p, &cd))
125                 return (GIConv)cd;
126
127               p++;
128             }
129         }
130
131       if (try_to_aliases (to_aliases, from_codeset, &cd))
132         return (GIConv)cd;
133     }
134
135   return (GIConv)cd;
136 }
137
138 /**
139  * g_iconv:
140  * @converter: conversion descriptor from g_iconv_open()
141  * @inbuf: bytes to convert
142  * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
143  * @outbuf: converted output bytes
144  * @outbytes_left: inout parameter, bytes available to fill in @outbuf
145  * 
146  * Same as the standard UNIX routine iconv(), but
147  * may be implemented via libiconv on UNIX flavors that lack
148  * a native implementation.
149  *
150  * GLib provides g_convert() and g_locale_to_utf8() which are likely
151  * more convenient than the raw iconv wrappers.
152  * 
153  * Return value: count of non-reversible conversions, or -1 on error
154  **/
155 size_t 
156 g_iconv (GIConv   converter,
157          gchar  **inbuf,
158          gsize   *inbytes_left,
159          gchar  **outbuf,
160          gsize   *outbytes_left)
161 {
162   iconv_t cd = (iconv_t)converter;
163
164   return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
165 }
166
167 /**
168  * g_iconv_close:
169  * @converter: a conversion descriptor from g_iconv_open()
170  *
171  * Same as the standard UNIX routine iconv_close(), but
172  * may be implemented via libiconv on UNIX flavors that lack
173  * a native implementation. Should be called to clean up
174  * the conversion descriptor from iconv_open() when
175  * you are done converting things.
176  *
177  * GLib provides g_convert() and g_locale_to_utf8() which are likely
178  * more convenient than the raw iconv wrappers.
179  * 
180  * Return value: -1 on error, 0 on success
181  **/
182 gint
183 g_iconv_close (GIConv converter)
184 {
185   iconv_t cd = (iconv_t)converter;
186
187   return iconv_close (cd);
188 }
189
190 static GIConv
191 open_converter (const gchar *to_codeset,
192                 const gchar *from_codeset,
193                 GError     **error)
194 {
195   GIConv cd = g_iconv_open (to_codeset, from_codeset);
196
197   if (cd == (iconv_t) -1)
198     {
199       /* Something went wrong.  */
200       if (errno == EINVAL)
201         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
202                      _("Conversion from character set '%s' to '%s' is not supported"),
203                      from_codeset, to_codeset);
204       else
205         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
206                      _("Could not open converter from '%s' to '%s': %s"),
207                      from_codeset, to_codeset, strerror (errno));
208     }
209
210   return cd;
211
212 }
213
214 /**
215  * g_convert:
216  * @str:           the string to convert
217  * @len:           the length of the string
218  * @to_codeset:    name of character set into which to convert @str
219  * @from_codeset:  character set of @str.
220  * @bytes_read:    location to store the number of bytes in the
221  *                 input string that were successfully converted, or %NULL.
222  *                 Even if the conversion was successful, this may be 
223  *                 less than @len if there were partial characters
224  *                 at the end of the input. If the error
225  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
226  *                 stored will the byte offset after the last valid
227  *                 input sequence.
228  * @bytes_written: the number of bytes stored in the output buffer (not 
229  *                 including the terminating NULL).
230  * @error:         location to store the error occuring, or %NULL to ignore
231  *                 errors. Any of the errors in #GConvertError may occur.
232  *
233  * Convert a string from one character set to another.
234  *
235  * Return value: If the conversion was successful, a newly allocated
236  *               nul-terminated string, which must be freed with
237  *               g_free(). Otherwise %NULL and @error will be set.
238  **/
239 gchar*
240 g_convert (const gchar *str,
241            gssize       len,  
242            const gchar *to_codeset,
243            const gchar *from_codeset,
244            gsize       *bytes_read, 
245            gsize       *bytes_written, 
246            GError     **error)
247 {
248   gchar *res;
249   GIConv cd;
250   
251   g_return_val_if_fail (str != NULL, NULL);
252   g_return_val_if_fail (to_codeset != NULL, NULL);
253   g_return_val_if_fail (from_codeset != NULL, NULL);
254      
255   cd = open_converter (to_codeset, from_codeset, error);
256
257   if (cd == (GIConv) -1)
258     {
259       if (bytes_read)
260         *bytes_read = 0;
261       
262       if (bytes_written)
263         *bytes_written = 0;
264       
265       return NULL;
266     }
267
268   res = g_convert_with_iconv (str, len, cd,
269                               bytes_read, bytes_written,
270                               error);
271   
272   g_iconv_close (cd);
273
274   return res;
275 }
276
277 /**
278  * g_convert_with_iconv:
279  * @str:           the string to convert
280  * @len:           the length of the string
281  * @converter:     conversion descriptor from g_iconv_open()
282  * @bytes_read:    location to store the number of bytes in the
283  *                 input string that were successfully converted, or %NULL.
284  *                 Even if the conversion was succesful, this may be 
285  *                 less than @len if there were partial characters
286  *                 at the end of the input. If the error
287  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
288  *                 stored will the byte offset after the last valid
289  *                 input sequence.
290  * @bytes_written: the number of bytes stored in the output buffer (not 
291  *                 including the terminating NULL).
292  * @error:         location to store the error occuring, or %NULL to ignore
293  *                 errors. Any of the errors in #GConvertError may occur.
294  *
295  * Convert a string from one character set to another.
296  *
297  * Return value: If the conversion was successful, a newly allocated
298  *               nul-terminated string, which must be freed with
299  *               g_free(). Otherwise %NULL and @error will be set.
300  **/
301 gchar*
302 g_convert_with_iconv (const gchar *str,
303                       gssize       len,
304                       GIConv       converter,
305                       gsize       *bytes_read, 
306                       gsize       *bytes_written, 
307                       GError     **error)
308 {
309   gchar *dest;
310   gchar *outp;
311   const gchar *p;
312   gsize inbytes_remaining;
313   gsize outbytes_remaining;
314   gsize err;
315   gsize outbuf_size;
316   gboolean have_error = FALSE;
317   
318   g_return_val_if_fail (str != NULL, NULL);
319   g_return_val_if_fail (converter != (GIConv) -1, NULL);
320      
321   if (len < 0)
322     len = strlen (str);
323
324   p = str;
325   inbytes_remaining = len;
326   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
327   
328   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
329   outp = dest = g_malloc (outbuf_size);
330
331  again:
332   
333   err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
334
335   if (err == (size_t) -1)
336     {
337       switch (errno)
338         {
339         case EINVAL:
340           /* Incomplete text, do not report an error */
341           break;
342         case E2BIG:
343           {
344             size_t used = outp - dest;
345
346             outbuf_size *= 2;
347             dest = g_realloc (dest, outbuf_size);
348                 
349             outp = dest + used;
350             outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
351
352             goto again;
353           }
354         case EILSEQ:
355           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
356                        _("Invalid byte sequence in conversion input"));
357           have_error = TRUE;
358           break;
359         default:
360           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
361                        _("Error during conversion: %s"),
362                        strerror (errno));
363           have_error = TRUE;
364           break;
365         }
366     }
367
368   *outp = '\0';
369   
370   if (bytes_read)
371     *bytes_read = p - str;
372   else
373     {
374       if ((p - str) != len) 
375         {
376           if (!have_error)
377             {
378               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
379                            _("Partial character sequence at end of input"));
380               have_error = TRUE;
381             }
382         }
383     }
384
385   if (bytes_written)
386     *bytes_written = outp - dest;       /* Doesn't include '\0' */
387
388   if (have_error)
389     {
390       g_free (dest);
391       return NULL;
392     }
393   else
394     return dest;
395 }
396
397 /**
398  * g_convert_with_fallback:
399  * @str:          the string to convert
400  * @len:          the length of the string
401  * @to_codeset:   name of character set into which to convert @str
402  * @from_codeset: character set of @str.
403  * @fallback:     UTF-8 string to use in place of character not
404  *                present in the target encoding. (This must be
405  *                in the target encoding), if %NULL, characters
406  *                not in the target encoding will be represented
407  *                as Unicode escapes \x{XXXX} or \x{XXXXXX}.
408  * @bytes_read:   location to store the number of bytes in the
409  *                input string that were successfully converted, or %NULL.
410  *                Even if the conversion was succesful, this may be 
411  *                less than @len if there were partial characters
412  *                at the end of the input.
413  * @bytes_written: the number of bytes stored in the output buffer (not 
414  *                including the terminating NULL).
415  * @error:        location to store the error occuring, or %NULL to ignore
416  *                errors. Any of the errors in #GConvertError may occur.
417  *
418  * Convert a string from one character set to another, possibly
419  * including fallback sequences for characters not representable
420  * in the output. Note that it is not guaranteed that the specification
421  * for the fallback sequences in @fallback will be honored. Some
422  * systems may do a approximate conversion from @from_codeset
423  * to @to_codeset in their iconv() functions, in which case GLib
424  * will simply return that approximate conversion.
425  *
426  * Return value: If the conversion was successful, a newly allocated
427  *               nul-terminated string, which must be freed with
428  *               g_free(). Otherwise %NULL and @error will be set.
429  **/
430 gchar*
431 g_convert_with_fallback (const gchar *str,
432                          gssize       len,    
433                          const gchar *to_codeset,
434                          const gchar *from_codeset,
435                          gchar       *fallback,
436                          gsize       *bytes_read,
437                          gsize       *bytes_written,
438                          GError     **error)
439 {
440   gchar *utf8;
441   gchar *dest;
442   gchar *outp;
443   const gchar *insert_str = NULL;
444   const gchar *p;
445   gsize inbytes_remaining;   
446   const gchar *save_p = NULL;
447   gsize save_inbytes = 0;
448   gsize outbytes_remaining; 
449   gsize err;
450   GIConv cd;
451   gsize outbuf_size;
452   gboolean have_error = FALSE;
453   gboolean done = FALSE;
454
455   GError *local_error = NULL;
456   
457   g_return_val_if_fail (str != NULL, NULL);
458   g_return_val_if_fail (to_codeset != NULL, NULL);
459   g_return_val_if_fail (from_codeset != NULL, NULL);
460      
461   if (len < 0)
462     len = strlen (str);
463   
464   /* Try an exact conversion; we only proceed if this fails
465    * due to an illegal sequence in the input string.
466    */
467   dest = g_convert (str, len, to_codeset, from_codeset, 
468                     bytes_read, bytes_written, &local_error);
469   if (!local_error)
470     return dest;
471
472   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
473     {
474       g_propagate_error (error, local_error);
475       return NULL;
476     }
477   else
478     g_error_free (local_error);
479
480   local_error = NULL;
481   
482   /* No go; to proceed, we need a converter from "UTF-8" to
483    * to_codeset, and the string as UTF-8.
484    */
485   cd = open_converter (to_codeset, "UTF-8", error);
486   if (cd == (GIConv) -1)
487     {
488       if (bytes_read)
489         *bytes_read = 0;
490       
491       if (bytes_written)
492         *bytes_written = 0;
493       
494       return NULL;
495     }
496
497   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
498                     bytes_read, &inbytes_remaining, error);
499   if (!utf8)
500     return NULL;
501
502   /* Now the heart of the code. We loop through the UTF-8 string, and
503    * whenever we hit an offending character, we form fallback, convert
504    * the fallback to the target codeset, and then go back to
505    * converting the original string after finishing with the fallback.
506    *
507    * The variables save_p and save_inbytes store the input state
508    * for the original string while we are converting the fallback
509    */
510   p = utf8;
511
512   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
513   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
514   outp = dest = g_malloc (outbuf_size);
515
516   while (!done && !have_error)
517     {
518       size_t inbytes_tmp = inbytes_remaining;
519       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
520       inbytes_remaining = inbytes_tmp;
521
522       if (err == (size_t) -1)
523         {
524           switch (errno)
525             {
526             case EINVAL:
527               g_assert_not_reached();
528               break;
529             case E2BIG:
530               {
531                 size_t used = outp - dest;
532
533                 outbuf_size *= 2;
534                 dest = g_realloc (dest, outbuf_size);
535                 
536                 outp = dest + used;
537                 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
538                 
539                 break;
540               }
541             case EILSEQ:
542               if (save_p)
543                 {
544                   /* Error converting fallback string - fatal
545                    */
546                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
547                                _("Cannot convert fallback '%s' to codeset '%s'"),
548                                insert_str, to_codeset);
549                   have_error = TRUE;
550                   break;
551                 }
552               else
553                 {
554                   if (!fallback)
555                     { 
556                       gunichar ch = g_utf8_get_char (p);
557                       insert_str = g_strdup_printf ("\\x{%0*X}",
558                                                     (ch < 0x10000) ? 4 : 6,
559                                                     ch);
560                     }
561                   else
562                     insert_str = fallback;
563                   
564                   save_p = g_utf8_next_char (p);
565                   save_inbytes = inbytes_remaining - (save_p - p);
566                   p = insert_str;
567                   inbytes_remaining = strlen (p);
568                 }
569               break;
570             default:
571               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
572                            _("Error during conversion: %s"),
573                            strerror (errno));
574               have_error = TRUE;
575               break;
576             }
577         }
578       else
579         {
580           if (save_p)
581             {
582               if (!fallback)
583                 g_free ((gchar *)insert_str);
584               p = save_p;
585               inbytes_remaining = save_inbytes;
586               save_p = NULL;
587             }
588           else
589             done = TRUE;
590         }
591     }
592
593   /* Cleanup
594    */
595   *outp = '\0';
596   
597   g_iconv_close (cd);
598
599   if (bytes_written)
600     *bytes_written = outp - str;        /* Doesn't include '\0' */
601
602   g_free (utf8);
603
604   if (have_error)
605     {
606       if (save_p && !fallback)
607         g_free ((gchar *)insert_str);
608       g_free (dest);
609       return NULL;
610     }
611   else
612     return dest;
613 }
614
615 /*
616  * g_locale_to_utf8
617  *
618  * 
619  */
620
621 static gchar *
622 strdup_len (const gchar *string,
623             gssize       len,
624             gsize       *bytes_written,
625             gsize       *bytes_read,
626             GError      **error)
627          
628 {
629   gsize real_len;
630
631   if (!g_utf8_validate (string, -1, NULL))
632     {
633       if (bytes_read)
634         *bytes_read = 0;
635       if (bytes_written)
636         *bytes_written = 0;
637
638       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
639                    _("Invalid byte sequence in conversion input"));
640       return NULL;
641     }
642   
643   if (len < 0)
644     real_len = strlen (string);
645   else
646     {
647       real_len = 0;
648       
649       while (real_len < len && string[real_len])
650         real_len++;
651     }
652   
653   if (bytes_read)
654     *bytes_read = real_len;
655   if (bytes_written)
656     *bytes_written = real_len;
657
658   return g_strndup (string, real_len);
659 }
660
661 /**
662  * g_locale_to_utf8:
663  * @opsysstring:   a string in the encoding of the current locale
664  * @len:           the length of the string, or -1 if the string is
665  *                 nul-terminated.
666  * @bytes_read:    location to store the number of bytes in the
667  *                 input string that were successfully converted, or %NULL.
668  *                 Even if the conversion was succesful, this may be 
669  *                 less than @len if there were partial characters
670  *                 at the end of the input. If the error
671  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
672  *                 stored will the byte offset after the last valid
673  *                 input sequence.
674  * @bytes_written: the number of bytes stored in the output buffer (not 
675  *                 including the terminating NULL).
676  * @error:         location to store the error occuring, or %NULL to ignore
677  *                 errors. Any of the errors in #GConvertError may occur.
678  * 
679  * Converts a string which is in the encoding used for strings by
680  * the C runtime (usually the same as that used by the operating
681  * system) in the current locale into a UTF-8 string.
682  * 
683  * Return value: The converted string, or %NULL on an error.
684  **/
685 gchar *
686 g_locale_to_utf8 (const gchar  *opsysstring,
687                   gssize        len,            
688                   gsize        *bytes_read,    
689                   gsize        *bytes_written,
690                   GError      **error)
691 {
692 #ifdef G_PLATFORM_WIN32
693
694   gint i, clen, total_len, wclen, first;
695   wchar_t *wcs, wc;
696   gchar *result, *bp;
697   const wchar_t *wcp;
698
699   if (len == -1)
700     len = strlen (opsysstring);
701   
702   wcs = g_new (wchar_t, len);
703   wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
704
705   wcp = wcs;
706   total_len = 0;
707   for (i = 0; i < wclen; i++)
708     {
709       wc = *wcp++;
710
711       if (wc < 0x80)
712         total_len += 1;
713       else if (wc < 0x800)
714         total_len += 2;
715       else if (wc < 0x10000)
716         total_len += 3;
717       else if (wc < 0x200000)
718         total_len += 4;
719       else if (wc < 0x4000000)
720         total_len += 5;
721       else
722         total_len += 6;
723     }
724
725   result = g_malloc (total_len + 1);
726   
727   wcp = wcs;
728   bp = result;
729   for (i = 0; i < wclen; i++)
730     {
731       wc = *wcp++;
732
733       if (wc < 0x80)
734         {
735           first = 0;
736           clen = 1;
737         }
738       else if (wc < 0x800)
739         {
740           first = 0xc0;
741           clen = 2;
742         }
743       else if (wc < 0x10000)
744         {
745           first = 0xe0;
746           clen = 3;
747         }
748       else if (wc < 0x200000)
749         {
750           first = 0xf0;
751           clen = 4;
752         }
753       else if (wc < 0x4000000)
754         {
755           first = 0xf8;
756           clen = 5;
757         }
758       else
759         {
760           first = 0xfc;
761           clen = 6;
762         }
763       
764       /* Woo-hoo! */
765       switch (clen)
766         {
767         case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
768         case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
769         case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
770         case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
771         case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
772         case 1: bp[0] = wc | first;
773         }
774
775       bp += clen;
776     }
777   *bp = 0;
778
779   g_free (wcs);
780
781   if (bytes_read)
782     *bytes_read = len;
783   if (bytes_written)
784     *bytes_written = total_len;
785   
786   return result;
787
788 #else  /* !G_PLATFORM_WIN32 */
789
790   const char *charset;
791
792   if (g_get_charset (&charset))
793     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
794   else
795     return g_convert (opsysstring, len, 
796                       "UTF-8", charset, bytes_read, bytes_written, error);
797
798 #endif /* !G_PLATFORM_WIN32 */
799 }
800
801 /**
802  * g_locale_from_utf8:
803  * @utf8string:    a UTF-8 encoded string 
804  * @len:           the length of the string, or -1 if the string is
805  *                 nul-terminated.
806  * @bytes_read:    location to store the number of bytes in the
807  *                 input string that were successfully converted, or %NULL.
808  *                 Even if the conversion was succesful, this may be 
809  *                 less than @len if there were partial characters
810  *                 at the end of the input. If the error
811  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
812  *                 stored will the byte offset after the last valid
813  *                 input sequence.
814  * @bytes_written: the number of bytes stored in the output buffer (not 
815  *                 including the terminating NULL).
816  * @error:         location to store the error occuring, or %NULL to ignore
817  *                 errors. Any of the errors in #GConvertError may occur.
818  * 
819  * Converts a string from UTF-8 to the encoding used for strings by
820  * the C runtime (usually the same as that used by the operating
821  * system) in the current locale.
822  * 
823  * Return value: The converted string, or %NULL on an error.
824  **/
825 gchar *
826 g_locale_from_utf8 (const gchar *utf8string,
827                     gssize       len,            
828                     gsize       *bytes_read,    
829                     gsize       *bytes_written,
830                     GError     **error)
831 {
832 #ifdef G_PLATFORM_WIN32
833
834   gint i, mask, clen, mblen;
835   wchar_t *wcs, *wcp;
836   gchar *result;
837   guchar *cp, *end, c;
838   gint n;
839   
840   if (len == -1)
841     len = strlen (utf8string);
842   
843   /* First convert to wide chars */
844   cp = (guchar *) utf8string;
845   end = cp + len;
846   n = 0;
847   wcs = g_new (wchar_t, len + 1);
848   wcp = wcs;
849   while (cp != end)
850     {
851       mask = 0;
852       c = *cp;
853
854       if (c < 0x80)
855         {
856           clen = 1;
857           mask = 0x7f;
858         }
859       else if ((c & 0xe0) == 0xc0)
860         {
861           clen = 2;
862           mask = 0x1f;
863         }
864       else if ((c & 0xf0) == 0xe0)
865         {
866           clen = 3;
867           mask = 0x0f;
868         }
869       else if ((c & 0xf8) == 0xf0)
870         {
871           clen = 4;
872           mask = 0x07;
873         }
874       else if ((c & 0xfc) == 0xf8)
875         {
876           clen = 5;
877           mask = 0x03;
878         }
879       else if ((c & 0xfc) == 0xfc)
880         {
881           clen = 6;
882           mask = 0x01;
883         }
884       else
885         {
886           g_free (wcs);
887           return NULL;
888         }
889
890       if (cp + clen > end)
891         {
892           g_free (wcs);
893           return NULL;
894         }
895
896       *wcp = (cp[0] & mask);
897       for (i = 1; i < clen; i++)
898         {
899           if ((cp[i] & 0xc0) != 0x80)
900             {
901               g_free (wcs);
902               return NULL;
903             }
904           *wcp <<= 6;
905           *wcp |= (cp[i] & 0x3f);
906         }
907
908       cp += clen;
909       wcp++;
910       n++;
911     }
912   if (cp != end)
913     {
914       g_free (wcs);
915       return NULL;
916     }
917
918   /* n is the number of wide chars constructed */
919
920   /* Convert to a string in the current ANSI codepage */
921
922   result = g_new (gchar, 3 * n + 1);
923   mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
924   result[mblen] = 0;
925   g_free (wcs);
926
927   if (bytes_read)
928     *bytes_read = len;
929   if (bytes_written)
930     *bytes_written = mblen;
931   
932   return result;
933
934 #else  /* !G_PLATFORM_WIN32 */
935   
936   const gchar *charset;
937
938   if (g_get_charset (&charset))
939     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
940   else
941     return g_convert (utf8string, len,
942                       charset, "UTF-8", bytes_read, bytes_written, error);
943
944 #endif /* !G_PLATFORM_WIN32 */
945 }
946
947 /**
948  * g_filename_to_utf8:
949  * @opsysstring:   a string in the encoding for filenames
950  * @len:           the length of the string, or -1 if the string is
951  *                 nul-terminated.
952  * @bytes_read:    location to store the number of bytes in the
953  *                 input string that were successfully converted, or %NULL.
954  *                 Even if the conversion was succesful, this may be 
955  *                 less than @len if there were partial characters
956  *                 at the end of the input. If the error
957  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
958  *                 stored will the byte offset after the last valid
959  *                 input sequence.
960  * @bytes_written: the number of bytes stored in the output buffer (not 
961  *                 including the terminating NULL).
962  * @error:         location to store the error occuring, or %NULL to ignore
963  *                 errors. Any of the errors in #GConvertError may occur.
964  * 
965  * Converts a string which is in the encoding used for filenames
966  * into a UTF-8 string.
967  * 
968  * Return value: The converted string, or %NULL on an error.
969  **/
970 gchar*
971 g_filename_to_utf8 (const gchar *opsysstring, 
972                     gssize       len,           
973                     gsize       *bytes_read,   
974                     gsize       *bytes_written,
975                     GError     **error)
976 {
977 #ifdef G_PLATFORM_WIN32
978   return g_locale_to_utf8 (opsysstring, len,
979                            bytes_read, bytes_written,
980                            error);
981 #else  /* !G_PLATFORM_WIN32 */
982       
983   if (getenv ("G_BROKEN_FILENAMES"))
984     return g_locale_to_utf8 (opsysstring, len,
985                              bytes_read, bytes_written,
986                              error);
987   else
988     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
989 #endif /* !G_PLATFORM_WIN32 */
990 }
991
992 /**
993  * g_filename_from_utf8:
994  * @utf8string:    a UTF-8 encoded string.
995  * @len:           the length of the string, or -1 if the string is
996  *                 nul-terminated.
997  * @bytes_read:    location to store the number of bytes in the
998  *                 input string that were successfully converted, or %NULL.
999  *                 Even if the conversion was succesful, this may be 
1000  *                 less than @len if there were partial characters
1001  *                 at the end of the input. If the error
1002  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1003  *                 stored will the byte offset after the last valid
1004  *                 input sequence.
1005  * @bytes_written: the number of bytes stored in the output buffer (not 
1006  *                 including the terminating NULL).
1007  * @error:         location to store the error occuring, or %NULL to ignore
1008  *                 errors. Any of the errors in #GConvertError may occur.
1009  * 
1010  * Converts a string from UTF-8 to the encoding used for filenames.
1011  * 
1012  * Return value: The converted string, or %NULL on an error.
1013  **/
1014 gchar*
1015 g_filename_from_utf8 (const gchar *utf8string,
1016                       gssize       len,            
1017                       gsize       *bytes_read,    
1018                       gsize       *bytes_written,
1019                       GError     **error)
1020 {
1021 #ifdef G_PLATFORM_WIN32
1022   return g_locale_from_utf8 (utf8string, len,
1023                              bytes_read, bytes_written,
1024                              error);
1025 #else  /* !G_PLATFORM_WIN32 */
1026   if (getenv ("G_BROKEN_FILENAMES"))
1027     return g_locale_from_utf8 (utf8string, len,
1028                                bytes_read, bytes_written,
1029                                error);
1030   else
1031     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1032 #endif /* !G_PLATFORM_WIN32 */
1033 }
1034
1035 /* Test of haystack has the needle prefix, comparing case
1036  * insensitive. haystack may be UTF-8, but needle must
1037  * contain only ascii. */
1038 static gboolean
1039 has_case_prefix (const gchar *haystack, const gchar *needle)
1040 {
1041   const gchar *h, *n;
1042   
1043   /* Eat one character at a time. */
1044   h = haystack;
1045   n = needle;
1046
1047   while (*n && *h &&
1048          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1049     {
1050       n++;
1051       h++;
1052     }
1053   
1054   return *n == '\0';
1055 }
1056
1057 typedef enum {
1058   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1059   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1060   UNSAFE_PATH       = 0x4,  /* Allows '/' and '?' and '&' and '='  */
1061   UNSAFE_DOS_PATH   = 0x8,  /* Allows '/' and '?' and '&' and '=' and ':' */
1062   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1063   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1064 } UnsafeCharacterSet;
1065
1066 static const guchar acceptable[96] = {
1067  /* X0   X1   X2   X3   X4   X5   X6   X7   X8   X9   XA   XB   XC   XD   XE   XF */
1068   0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C, /* 2X  !"#$%&'()*+,-./   */
1069   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C, /* 3X 0123456789:;<=>?   */
1070   0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, /* 4X @ABCDEFGHIJKLMNO   */
1071   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F, /* 5X PQRSTUVWXYZ[\]^_   */
1072   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, /* 6X `abcdefghijklmno   */
1073   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20  /* 7X pqrstuvwxyz{|}~DEL */
1074 };
1075
1076 static const gchar hex[16] = "0123456789ABCDEF";
1077
1078 /* Note: This escape function works on file: URIs, but if you want to
1079  * escape something else, please read RFC-2396 */
1080 static gchar *
1081 g_escape_uri_string (const gchar *string, 
1082                      UnsafeCharacterSet mask)
1083 {
1084 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1085
1086   const gchar *p;
1087   gchar *q;
1088   gchar *result;
1089   int c;
1090   gint unacceptable;
1091   UnsafeCharacterSet use_mask;
1092   
1093   g_return_val_if_fail (mask == UNSAFE_ALL
1094                         || mask == UNSAFE_ALLOW_PLUS
1095                         || mask == UNSAFE_PATH
1096                         || mask == UNSAFE_DOS_PATH
1097                         || mask == UNSAFE_HOST
1098                         || mask == UNSAFE_SLASHES, NULL);
1099   
1100   unacceptable = 0;
1101   use_mask = mask;
1102   for (p = string; *p != '\0'; p++)
1103     {
1104       c = *p;
1105       if (!ACCEPTABLE (c)) 
1106         unacceptable++;
1107     }
1108   
1109   result = g_malloc (p - string + unacceptable * 2 + 1);
1110   
1111   use_mask = mask;
1112   for (q = result, p = string; *p != '\0'; p++)
1113     {
1114       c = (unsigned char)*p;
1115       
1116       if (!ACCEPTABLE (c))
1117         {
1118           *q++ = '%'; /* means hex coming */
1119           *q++ = hex[c >> 4];
1120           *q++ = hex[c & 15];
1121         }
1122       else
1123         *q++ = *p;
1124     }
1125   
1126   *q = '\0';
1127   
1128   return result;
1129 }
1130
1131
1132 static gchar *
1133 g_escape_file_uri (const gchar *hostname,
1134                    const gchar *pathname)
1135 {
1136   char *escaped_hostname = NULL;
1137   char *escaped_path;
1138   char *res;
1139
1140   if (hostname && *hostname != '\0')
1141     {
1142       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1143     }
1144
1145   escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1146
1147   res = g_strconcat ("file://",
1148                      (escaped_hostname) ? escaped_hostname : "",
1149                      (*escaped_path != '/') ? "/" : "",
1150                      escaped_path,
1151                      NULL);
1152
1153   g_free (escaped_hostname);
1154   g_free (escaped_path);
1155   
1156   return res;
1157 }
1158
1159 static int
1160 unescape_character (const char *scanner)
1161 {
1162   int first_digit;
1163   int second_digit;
1164
1165   first_digit = g_ascii_xdigit_value (*scanner++);
1166   
1167   if (first_digit < 0) 
1168     return -1;
1169   
1170   second_digit = g_ascii_xdigit_value (*scanner++);
1171   if (second_digit < 0) 
1172     return -1;
1173   
1174   return (first_digit << 4) | second_digit;
1175 }
1176
1177 static gchar *
1178 g_unescape_uri_string (const gchar *escaped,
1179                        const gchar *illegal_characters,
1180                        int          len)
1181 {
1182   const gchar *in, *in_end;
1183   gchar *out, *result;
1184   int character;
1185   
1186   if (escaped == NULL)
1187     return NULL;
1188
1189   if (len < 0)
1190     len = strlen (escaped);
1191
1192     result = g_malloc (len + 1);
1193   
1194   out = result;
1195   for (in = escaped, in_end = escaped + len; in < in_end && *in != '\0'; in++)
1196     {
1197       character = *in;
1198       if (character == '%')
1199         {
1200           character = unescape_character (in + 1);
1201       
1202           /* Check for an illegal character. We consider '\0' illegal here. */
1203           if (character == 0
1204               || (illegal_characters != NULL
1205                   && strchr (illegal_characters, (char)character) != NULL))
1206             {
1207               g_free (result);
1208               return NULL;
1209             }
1210           in += 2;
1211         }
1212       *out++ = character;
1213     }
1214   
1215   *out = '\0';
1216   
1217   g_assert (out - result <= strlen (escaped));
1218
1219   if (!g_utf8_validate (result, -1, NULL))
1220     {
1221       g_free (result);
1222       return NULL;
1223     }
1224   
1225   return result;
1226 }
1227
1228 /**
1229  * g_filename_from_uri:
1230  * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1231  * @hostname: Location to store hostname for the URI, or %NULL.
1232  *            If there is no hostname in the URI, %NULL will be
1233  *            stored in this location.
1234  * @error: location to store the error occuring, or %NULL to ignore
1235  *         errors. Any of the errors in #GConvertError may occur.
1236  * 
1237  * Converts an escaped UTF-8 encoded URI to a local filename in the
1238  * encoding used for filenames. 
1239  * 
1240  * Return value: a newly allocated string holding the resulting
1241  *               filename, or %NULL on an error.
1242  **/
1243 gchar *
1244 g_filename_from_uri (const char *uri,
1245                      char      **hostname,
1246                      GError    **error)
1247 {
1248   const char *path_part;
1249   const char *host_part;
1250   char *unescaped_hostname;
1251   char *result;
1252   char *filename;
1253   int offs;
1254
1255   if (hostname)
1256     *hostname = NULL;
1257
1258   if (!has_case_prefix (uri, "file:/"))
1259     {
1260       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1261                    _("The URI '%s' is not an absolute URI using the file scheme"),
1262                    uri);
1263       return NULL;
1264     }
1265   
1266   path_part = uri + strlen ("file:");
1267   
1268   if (strchr (path_part, '#') != NULL)
1269     {
1270       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1271                    _("The local file URI '%s' may not include a '#'"),
1272                    uri);
1273       return NULL;
1274     }
1275         
1276   if (has_case_prefix (path_part, "///")) 
1277     path_part += 2;
1278   else if (has_case_prefix (path_part, "//"))
1279     {
1280       path_part += 2;
1281       host_part = path_part;
1282
1283       path_part = strchr (path_part, '/');
1284
1285       if (path_part == NULL)
1286         {
1287           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1288                        _("The URI '%s' is invalid"),
1289                        uri);
1290           return NULL;
1291         }
1292
1293       unescaped_hostname = g_unescape_uri_string (host_part, "", path_part - host_part);
1294       if (unescaped_hostname == NULL)
1295         {
1296           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1297                        _("The hostname of the URI '%s' contains invalidly escaped characters"),
1298                        uri);
1299           return NULL;
1300         }
1301       
1302       if (hostname)
1303         *hostname = unescaped_hostname;
1304       else
1305         g_free (unescaped_hostname);
1306     }
1307
1308   filename = g_unescape_uri_string (path_part, "/", -1);
1309
1310   if (filename == NULL)
1311     {
1312       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1313                    _("The URI '%s' contains invalidly escaped characters"),
1314                    uri);
1315       return NULL;
1316     }
1317
1318   /* DOS uri's are like "file://host/c:\foo", so we need to check if we need to
1319    * drop the initial slash */
1320   offs = 0;
1321   if (g_path_is_absolute (filename+1))
1322     offs = 1;
1323   
1324   result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1325   g_free (filename);
1326   
1327   return result;
1328 }
1329
1330 /**
1331  * g_filename_to_uri:
1332  * @filename: an absolute filename specified in the encoding
1333  *            used for filenames by the operating system.
1334  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1335  * @error: location to store the error occuring, or %NULL to ignore
1336  *         errors. Any of the errors in #GConvertError may occur.
1337  * 
1338  * Converts an absolute filename to an escaped UTF-8 encoded URI.
1339  * 
1340  * Return value: a newly allocated string holding the resulting
1341  *               URI, or %NULL on an error.
1342  **/
1343 gchar *
1344 g_filename_to_uri   (const char *filename,
1345                      char       *hostname,
1346                      GError    **error)
1347 {
1348   char *escaped_uri;
1349   char *utf8_filename;
1350
1351   g_return_val_if_fail (filename != NULL, NULL);
1352
1353   if (!g_path_is_absolute (filename))
1354     {
1355       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1356                    _("The pathname '%s' is not an absolute path"),
1357                    filename);
1358       return NULL;
1359     }
1360
1361   utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1362   if (utf8_filename == NULL)
1363     return NULL;
1364   
1365   if (hostname &&
1366       !g_utf8_validate (hostname, -1, NULL))
1367     {
1368       g_free (utf8_filename);
1369       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1370                    _("Invalid byte sequence in hostname"));
1371       return NULL;
1372     }
1373   
1374   escaped_uri = g_escape_file_uri (hostname,
1375                                    utf8_filename);
1376   g_free (utf8_filename);
1377   
1378   return escaped_uri;
1379 }
1380