Not used on Windows, don't even compile it then.
[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 <function>iconv_open()</function>, 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 (from_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 <function>iconv()</function>, 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 <function>iconv_close()</function>, 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 g_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 nul).
230  * @error:         location to store the error occuring, or %NULL to ignore
231  *                 errors. Any of the errors in #GConvertError may occur.
232  *
233  * Converts 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 successful, 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 nul).
292  * @error:         location to store the error occuring, or %NULL to ignore
293  *                 errors. Any of the errors in #GConvertError may occur.
294  *
295  * Converts 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 successful, 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 nul).
415  * @error:        location to store the error occuring, or %NULL to ignore
416  *                errors. Any of the errors in #GConvertError may occur.
417  *
418  * Converts 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 <function>iconv()</function> functions, 
424  * in which case GLib 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     {
501       g_iconv_close (cd);
502       if (bytes_written)
503         *bytes_written = 0;
504       return NULL;
505     }
506
507   /* Now the heart of the code. We loop through the UTF-8 string, and
508    * whenever we hit an offending character, we form fallback, convert
509    * the fallback to the target codeset, and then go back to
510    * converting the original string after finishing with the fallback.
511    *
512    * The variables save_p and save_inbytes store the input state
513    * for the original string while we are converting the fallback
514    */
515   p = utf8;
516
517   outbuf_size = len + 1; /* + 1 for nul in case len == 1 */
518   outbytes_remaining = outbuf_size - 1; /* -1 for nul */
519   outp = dest = g_malloc (outbuf_size);
520
521   while (!done && !have_error)
522     {
523       size_t inbytes_tmp = inbytes_remaining;
524       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
525       inbytes_remaining = inbytes_tmp;
526
527       if (err == (size_t) -1)
528         {
529           switch (errno)
530             {
531             case EINVAL:
532               g_assert_not_reached();
533               break;
534             case E2BIG:
535               {
536                 size_t used = outp - dest;
537
538                 outbuf_size *= 2;
539                 dest = g_realloc (dest, outbuf_size);
540                 
541                 outp = dest + used;
542                 outbytes_remaining = outbuf_size - used - 1; /* -1 for nul */
543                 
544                 break;
545               }
546             case EILSEQ:
547               if (save_p)
548                 {
549                   /* Error converting fallback string - fatal
550                    */
551                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
552                                _("Cannot convert fallback '%s' to codeset '%s'"),
553                                insert_str, to_codeset);
554                   have_error = TRUE;
555                   break;
556                 }
557               else
558                 {
559                   if (!fallback)
560                     { 
561                       gunichar ch = g_utf8_get_char (p);
562                       insert_str = g_strdup_printf ("\\x{%0*X}",
563                                                     (ch < 0x10000) ? 4 : 6,
564                                                     ch);
565                     }
566                   else
567                     insert_str = fallback;
568                   
569                   save_p = g_utf8_next_char (p);
570                   save_inbytes = inbytes_remaining - (save_p - p);
571                   p = insert_str;
572                   inbytes_remaining = strlen (p);
573                 }
574               break;
575             default:
576               g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
577                            _("Error during conversion: %s"),
578                            strerror (errno));
579               have_error = TRUE;
580               break;
581             }
582         }
583       else
584         {
585           if (save_p)
586             {
587               if (!fallback)
588                 g_free ((gchar *)insert_str);
589               p = save_p;
590               inbytes_remaining = save_inbytes;
591               save_p = NULL;
592             }
593           else
594             done = TRUE;
595         }
596     }
597
598   /* Cleanup
599    */
600   *outp = '\0';
601   
602   g_iconv_close (cd);
603
604   if (bytes_written)
605     *bytes_written = outp - dest;       /* Doesn't include '\0' */
606
607   g_free (utf8);
608
609   if (have_error)
610     {
611       if (save_p && !fallback)
612         g_free ((gchar *)insert_str);
613       g_free (dest);
614       return NULL;
615     }
616   else
617     return dest;
618 }
619
620 /*
621  * g_locale_to_utf8
622  *
623  * 
624  */
625
626 #ifndef G_PLATFORM_WIN32
627
628 static gchar *
629 strdup_len (const gchar *string,
630             gssize       len,
631             gsize       *bytes_written,
632             gsize       *bytes_read,
633             GError      **error)
634          
635 {
636   gsize real_len;
637
638   if (!g_utf8_validate (string, -1, NULL))
639     {
640       if (bytes_read)
641         *bytes_read = 0;
642       if (bytes_written)
643         *bytes_written = 0;
644
645       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
646                    _("Invalid byte sequence in conversion input"));
647       return NULL;
648     }
649   
650   if (len < 0)
651     real_len = strlen (string);
652   else
653     {
654       real_len = 0;
655       
656       while (real_len < len && string[real_len])
657         real_len++;
658     }
659   
660   if (bytes_read)
661     *bytes_read = real_len;
662   if (bytes_written)
663     *bytes_written = real_len;
664
665   return g_strndup (string, real_len);
666 }
667
668 #endif
669
670 /**
671  * g_locale_to_utf8:
672  * @opsysstring:   a string in the encoding of the current locale
673  * @len:           the length of the string, or -1 if the string is
674  *                 nul-terminated.
675  * @bytes_read:    location to store the number of bytes in the
676  *                 input string that were successfully converted, or %NULL.
677  *                 Even if the conversion was successful, this may be 
678  *                 less than @len if there were partial characters
679  *                 at the end of the input. If the error
680  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
681  *                 stored will the byte offset after the last valid
682  *                 input sequence.
683  * @bytes_written: the number of bytes stored in the output buffer (not 
684  *                 including the terminating nul).
685  * @error:         location to store the error occuring, or %NULL to ignore
686  *                 errors. Any of the errors in #GConvertError may occur.
687  * 
688  * Converts a string which is in the encoding used for strings by
689  * the C runtime (usually the same as that used by the operating
690  * system) in the current locale into a UTF-8 string.
691  * 
692  * Return value: The converted string, or %NULL on an error.
693  **/
694 gchar *
695 g_locale_to_utf8 (const gchar  *opsysstring,
696                   gssize        len,            
697                   gsize        *bytes_read,    
698                   gsize        *bytes_written,
699                   GError      **error)
700 {
701 #ifdef G_PLATFORM_WIN32
702
703   gint i, clen, total_len, wclen, first;
704   wchar_t *wcs, wc;
705   gchar *result, *bp;
706   const wchar_t *wcp;
707
708   if (len == -1)
709     len = strlen (opsysstring);
710   
711   wcs = g_new (wchar_t, len);
712   wclen = MultiByteToWideChar (CP_ACP, 0, opsysstring, len, wcs, len);
713
714   wcp = wcs;
715   total_len = 0;
716   for (i = 0; i < wclen; i++)
717     {
718       wc = *wcp++;
719
720       if (wc < 0x80)
721         total_len += 1;
722       else if (wc < 0x800)
723         total_len += 2;
724       else if (wc < 0x10000)
725         total_len += 3;
726       else if (wc < 0x200000)
727         total_len += 4;
728       else if (wc < 0x4000000)
729         total_len += 5;
730       else
731         total_len += 6;
732     }
733
734   result = g_malloc (total_len + 1);
735   
736   wcp = wcs;
737   bp = result;
738   for (i = 0; i < wclen; i++)
739     {
740       wc = *wcp++;
741
742       if (wc < 0x80)
743         {
744           first = 0;
745           clen = 1;
746         }
747       else if (wc < 0x800)
748         {
749           first = 0xc0;
750           clen = 2;
751         }
752       else if (wc < 0x10000)
753         {
754           first = 0xe0;
755           clen = 3;
756         }
757       else if (wc < 0x200000)
758         {
759           first = 0xf0;
760           clen = 4;
761         }
762       else if (wc < 0x4000000)
763         {
764           first = 0xf8;
765           clen = 5;
766         }
767       else
768         {
769           first = 0xfc;
770           clen = 6;
771         }
772       
773       /* Woo-hoo! */
774       switch (clen)
775         {
776         case 6: bp[5] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
777         case 5: bp[4] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
778         case 4: bp[3] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
779         case 3: bp[2] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
780         case 2: bp[1] = (wc & 0x3f) | 0x80; wc >>= 6; /* Fall through */
781         case 1: bp[0] = wc | first;
782         }
783
784       bp += clen;
785     }
786   *bp = 0;
787
788   g_free (wcs);
789
790   if (bytes_read)
791     *bytes_read = len;
792   if (bytes_written)
793     *bytes_written = total_len;
794   
795   return result;
796
797 #else  /* !G_PLATFORM_WIN32 */
798
799   const char *charset;
800
801   if (g_get_charset (&charset))
802     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
803   else
804     return g_convert (opsysstring, len, 
805                       "UTF-8", charset, bytes_read, bytes_written, error);
806
807 #endif /* !G_PLATFORM_WIN32 */
808 }
809
810 /**
811  * g_locale_from_utf8:
812  * @utf8string:    a UTF-8 encoded string 
813  * @len:           the length of the string, or -1 if the string is
814  *                 nul-terminated.
815  * @bytes_read:    location to store the number of bytes in the
816  *                 input string that were successfully converted, or %NULL.
817  *                 Even if the conversion was successful, this may be 
818  *                 less than @len if there were partial characters
819  *                 at the end of the input. If the error
820  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
821  *                 stored will the byte offset after the last valid
822  *                 input sequence.
823  * @bytes_written: the number of bytes stored in the output buffer (not 
824  *                 including the terminating nul).
825  * @error:         location to store the error occuring, or %NULL to ignore
826  *                 errors. Any of the errors in #GConvertError may occur.
827  * 
828  * Converts a string from UTF-8 to the encoding used for strings by
829  * the C runtime (usually the same as that used by the operating
830  * system) in the current locale.
831  * 
832  * Return value: The converted string, or %NULL on an error.
833  **/
834 gchar *
835 g_locale_from_utf8 (const gchar *utf8string,
836                     gssize       len,            
837                     gsize       *bytes_read,    
838                     gsize       *bytes_written,
839                     GError     **error)
840 {
841 #ifdef G_PLATFORM_WIN32
842
843   gint i, mask, clen, mblen;
844   wchar_t *wcs, *wcp;
845   gchar *result;
846   guchar *cp, *end, c;
847   gint n;
848   
849   if (len == -1)
850     len = strlen (utf8string);
851   
852   /* First convert to wide chars */
853   cp = (guchar *) utf8string;
854   end = cp + len;
855   n = 0;
856   wcs = g_new (wchar_t, len + 1);
857   wcp = wcs;
858   while (cp != end)
859     {
860       mask = 0;
861       c = *cp;
862
863       if (c < 0x80)
864         {
865           clen = 1;
866           mask = 0x7f;
867         }
868       else if ((c & 0xe0) == 0xc0)
869         {
870           clen = 2;
871           mask = 0x1f;
872         }
873       else if ((c & 0xf0) == 0xe0)
874         {
875           clen = 3;
876           mask = 0x0f;
877         }
878       else if ((c & 0xf8) == 0xf0)
879         {
880           clen = 4;
881           mask = 0x07;
882         }
883       else if ((c & 0xfc) == 0xf8)
884         {
885           clen = 5;
886           mask = 0x03;
887         }
888       else if ((c & 0xfc) == 0xfc)
889         {
890           clen = 6;
891           mask = 0x01;
892         }
893       else
894         {
895           g_free (wcs);
896           return NULL;
897         }
898
899       if (cp + clen > end)
900         {
901           g_free (wcs);
902           return NULL;
903         }
904
905       *wcp = (cp[0] & mask);
906       for (i = 1; i < clen; i++)
907         {
908           if ((cp[i] & 0xc0) != 0x80)
909             {
910               g_free (wcs);
911               return NULL;
912             }
913           *wcp <<= 6;
914           *wcp |= (cp[i] & 0x3f);
915         }
916
917       cp += clen;
918       wcp++;
919       n++;
920     }
921   if (cp != end)
922     {
923       g_free (wcs);
924       return NULL;
925     }
926
927   /* n is the number of wide chars constructed */
928
929   /* Convert to a string in the current ANSI codepage */
930
931   result = g_new (gchar, 3 * n + 1);
932   mblen = WideCharToMultiByte (CP_ACP, 0, wcs, n, result, 3*n, NULL, NULL);
933   result[mblen] = 0;
934   g_free (wcs);
935
936   if (bytes_read)
937     *bytes_read = len;
938   if (bytes_written)
939     *bytes_written = mblen;
940   
941   return result;
942
943 #else  /* !G_PLATFORM_WIN32 */
944   
945   const gchar *charset;
946
947   if (g_get_charset (&charset))
948     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
949   else
950     return g_convert (utf8string, len,
951                       charset, "UTF-8", bytes_read, bytes_written, error);
952
953 #endif /* !G_PLATFORM_WIN32 */
954 }
955
956 /**
957  * g_filename_to_utf8:
958  * @opsysstring:   a string in the encoding for filenames
959  * @len:           the length of the string, or -1 if the string is
960  *                 nul-terminated.
961  * @bytes_read:    location to store the number of bytes in the
962  *                 input string that were successfully converted, or %NULL.
963  *                 Even if the conversion was successful, this may be 
964  *                 less than @len if there were partial characters
965  *                 at the end of the input. If the error
966  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
967  *                 stored will the byte offset after the last valid
968  *                 input sequence.
969  * @bytes_written: the number of bytes stored in the output buffer (not 
970  *                 including the terminating nul).
971  * @error:         location to store the error occuring, or %NULL to ignore
972  *                 errors. Any of the errors in #GConvertError may occur.
973  * 
974  * Converts a string which is in the encoding used for filenames
975  * into a UTF-8 string.
976  * 
977  * Return value: The converted string, or %NULL on an error.
978  **/
979 gchar*
980 g_filename_to_utf8 (const gchar *opsysstring, 
981                     gssize       len,           
982                     gsize       *bytes_read,   
983                     gsize       *bytes_written,
984                     GError     **error)
985 {
986 #ifdef G_PLATFORM_WIN32
987   return g_locale_to_utf8 (opsysstring, len,
988                            bytes_read, bytes_written,
989                            error);
990 #else  /* !G_PLATFORM_WIN32 */
991       
992   if (getenv ("G_BROKEN_FILENAMES"))
993     return g_locale_to_utf8 (opsysstring, len,
994                              bytes_read, bytes_written,
995                              error);
996   else
997     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
998 #endif /* !G_PLATFORM_WIN32 */
999 }
1000
1001 /**
1002  * g_filename_from_utf8:
1003  * @utf8string:    a UTF-8 encoded string.
1004  * @len:           the length of the string, or -1 if the string is
1005  *                 nul-terminated.
1006  * @bytes_read:    location to store the number of bytes in the
1007  *                 input string that were successfully converted, or %NULL.
1008  *                 Even if the conversion was successful, this may be 
1009  *                 less than @len if there were partial characters
1010  *                 at the end of the input. If the error
1011  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1012  *                 stored will the byte offset after the last valid
1013  *                 input sequence.
1014  * @bytes_written: the number of bytes stored in the output buffer (not 
1015  *                 including the terminating nul).
1016  * @error:         location to store the error occuring, or %NULL to ignore
1017  *                 errors. Any of the errors in #GConvertError may occur.
1018  * 
1019  * Converts a string from UTF-8 to the encoding used for filenames.
1020  * 
1021  * Return value: The converted string, or %NULL on an error.
1022  **/
1023 gchar*
1024 g_filename_from_utf8 (const gchar *utf8string,
1025                       gssize       len,            
1026                       gsize       *bytes_read,    
1027                       gsize       *bytes_written,
1028                       GError     **error)
1029 {
1030 #ifdef G_PLATFORM_WIN32
1031   return g_locale_from_utf8 (utf8string, len,
1032                              bytes_read, bytes_written,
1033                              error);
1034 #else  /* !G_PLATFORM_WIN32 */
1035   if (getenv ("G_BROKEN_FILENAMES"))
1036     return g_locale_from_utf8 (utf8string, len,
1037                                bytes_read, bytes_written,
1038                                error);
1039   else
1040     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1041 #endif /* !G_PLATFORM_WIN32 */
1042 }
1043
1044 /* Test of haystack has the needle prefix, comparing case
1045  * insensitive. haystack may be UTF-8, but needle must
1046  * contain only ascii. */
1047 static gboolean
1048 has_case_prefix (const gchar *haystack, const gchar *needle)
1049 {
1050   const gchar *h, *n;
1051   
1052   /* Eat one character at a time. */
1053   h = haystack;
1054   n = needle;
1055
1056   while (*n && *h &&
1057          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1058     {
1059       n++;
1060       h++;
1061     }
1062   
1063   return *n == '\0';
1064 }
1065
1066 typedef enum {
1067   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1068   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1069   UNSAFE_PATH       = 0x4,  /* Allows '/' and '?' and '&' and '='  */
1070   UNSAFE_DOS_PATH   = 0x8,  /* Allows '/' and '?' and '&' and '=' and ':' */
1071   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1072   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1073 } UnsafeCharacterSet;
1074
1075 static const guchar acceptable[96] = {
1076   /* A table of the ASCII chars from space (32) to DEL (127) */
1077   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1078   0x00,0x3F,0x20,0x20,0x20,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x22,0x20,0x3F,0x3F,0x1C,
1079   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1080   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x2C,
1081   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1082   0x30,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1083   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1084   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1085   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1086   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1087   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1088   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1089 };
1090
1091 static const gchar hex[16] = "0123456789ABCDEF";
1092
1093 /* Note: This escape function works on file: URIs, but if you want to
1094  * escape something else, please read RFC-2396 */
1095 static gchar *
1096 g_escape_uri_string (const gchar *string, 
1097                      UnsafeCharacterSet mask)
1098 {
1099 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1100
1101   const gchar *p;
1102   gchar *q;
1103   gchar *result;
1104   int c;
1105   gint unacceptable;
1106   UnsafeCharacterSet use_mask;
1107   
1108   g_return_val_if_fail (mask == UNSAFE_ALL
1109                         || mask == UNSAFE_ALLOW_PLUS
1110                         || mask == UNSAFE_PATH
1111                         || mask == UNSAFE_DOS_PATH
1112                         || mask == UNSAFE_HOST
1113                         || mask == UNSAFE_SLASHES, NULL);
1114   
1115   unacceptable = 0;
1116   use_mask = mask;
1117   for (p = string; *p != '\0'; p++)
1118     {
1119       c = (guchar) *p;
1120       if (!ACCEPTABLE (c)) 
1121         unacceptable++;
1122     }
1123   
1124   result = g_malloc (p - string + unacceptable * 2 + 1);
1125   
1126   use_mask = mask;
1127   for (q = result, p = string; *p != '\0'; p++)
1128     {
1129       c = (guchar) *p;
1130       
1131       if (!ACCEPTABLE (c))
1132         {
1133           *q++ = '%'; /* means hex coming */
1134           *q++ = hex[c >> 4];
1135           *q++ = hex[c & 15];
1136         }
1137       else
1138         *q++ = *p;
1139     }
1140   
1141   *q = '\0';
1142   
1143   return result;
1144 }
1145
1146
1147 static gchar *
1148 g_escape_file_uri (const gchar *hostname,
1149                    const gchar *pathname)
1150 {
1151   char *escaped_hostname = NULL;
1152   char *escaped_path;
1153   char *res;
1154
1155 #ifdef G_OS_WIN32
1156   char *p, *backslash;
1157
1158   /* Turn backslashes into forward slashes. That's what Netscape
1159    * does, and they are actually more or less equivalent in Windows.
1160    */
1161   
1162   pathname = g_strdup (pathname);
1163   p = (char *) pathname;
1164   
1165   while ((backslash = strchr (p, '\\')) != NULL)
1166     {
1167       *backslash = '/';
1168       p = backslash + 1;
1169     }
1170 #endif
1171
1172   if (hostname && *hostname != '\0')
1173     {
1174       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1175     }
1176
1177   escaped_path = g_escape_uri_string (pathname, UNSAFE_DOS_PATH);
1178
1179   res = g_strconcat ("file://",
1180                      (escaped_hostname) ? escaped_hostname : "",
1181                      (*escaped_path != '/') ? "/" : "",
1182                      escaped_path,
1183                      NULL);
1184
1185 #ifdef G_OS_WIN32
1186   g_free ((char *) pathname);
1187 #endif
1188
1189   g_free (escaped_hostname);
1190   g_free (escaped_path);
1191   
1192   return res;
1193 }
1194
1195 static int
1196 unescape_character (const char *scanner)
1197 {
1198   int first_digit;
1199   int second_digit;
1200
1201   first_digit = g_ascii_xdigit_value (*scanner++);
1202   
1203   if (first_digit < 0) 
1204     return -1;
1205   
1206   second_digit = g_ascii_xdigit_value (*scanner++);
1207   if (second_digit < 0) 
1208     return -1;
1209   
1210   return (first_digit << 4) | second_digit;
1211 }
1212
1213 static gchar *
1214 g_unescape_uri_string (const gchar *escaped,
1215                        const gchar *illegal_characters,
1216                        int          len)
1217 {
1218   const gchar *in, *in_end;
1219   gchar *out, *result;
1220   int character;
1221   
1222   if (escaped == NULL)
1223     return NULL;
1224
1225   if (len < 0)
1226     len = strlen (escaped);
1227
1228     result = g_malloc (len + 1);
1229   
1230   out = result;
1231   for (in = escaped, in_end = escaped + len; in < in_end && *in != '\0'; in++)
1232     {
1233       character = *in;
1234       if (character == '%')
1235         {
1236           character = unescape_character (in + 1);
1237       
1238           /* Check for an illegal character. We consider '\0' illegal here. */
1239           if (character == 0
1240               || (illegal_characters != NULL
1241                   && strchr (illegal_characters, (char)character) != NULL))
1242             {
1243               g_free (result);
1244               return NULL;
1245             }
1246           in += 2;
1247         }
1248       *out++ = character;
1249     }
1250   
1251   *out = '\0';
1252   
1253   g_assert (out - result <= strlen (escaped));
1254
1255   if (!g_utf8_validate (result, -1, NULL))
1256     {
1257       g_free (result);
1258       return NULL;
1259     }
1260   
1261   return result;
1262 }
1263
1264 /**
1265  * g_filename_from_uri:
1266  * @uri: a uri describing a filename (escaped, encoded in UTF-8).
1267  * @hostname: Location to store hostname for the URI, or %NULL.
1268  *            If there is no hostname in the URI, %NULL will be
1269  *            stored in this location.
1270  * @error: location to store the error occuring, or %NULL to ignore
1271  *         errors. Any of the errors in #GConvertError may occur.
1272  * 
1273  * Converts an escaped UTF-8 encoded URI to a local filename in the
1274  * encoding used for filenames. 
1275  * 
1276  * Return value: a newly-allocated string holding the resulting
1277  *               filename, or %NULL on an error.
1278  **/
1279 gchar *
1280 g_filename_from_uri (const char *uri,
1281                      char      **hostname,
1282                      GError    **error)
1283 {
1284   const char *path_part;
1285   const char *host_part;
1286   char *unescaped_hostname;
1287   char *result;
1288   char *filename;
1289   int offs;
1290 #ifdef G_OS_WIN32
1291   char *p, *slash;
1292 #endif
1293
1294   if (hostname)
1295     *hostname = NULL;
1296
1297   if (!has_case_prefix (uri, "file:/"))
1298     {
1299       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1300                    _("The URI '%s' is not an absolute URI using the file scheme"),
1301                    uri);
1302       return NULL;
1303     }
1304   
1305   path_part = uri + strlen ("file:");
1306   
1307   if (strchr (path_part, '#') != NULL)
1308     {
1309       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1310                    _("The local file URI '%s' may not include a '#'"),
1311                    uri);
1312       return NULL;
1313     }
1314         
1315   if (has_case_prefix (path_part, "///")) 
1316     path_part += 2;
1317   else if (has_case_prefix (path_part, "//"))
1318     {
1319       path_part += 2;
1320       host_part = path_part;
1321
1322       path_part = strchr (path_part, '/');
1323
1324       if (path_part == NULL)
1325         {
1326           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1327                        _("The URI '%s' is invalid"),
1328                        uri);
1329           return NULL;
1330         }
1331
1332       unescaped_hostname = g_unescape_uri_string (host_part, "", path_part - host_part);
1333       if (unescaped_hostname == NULL)
1334         {
1335           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1336                        _("The hostname of the URI '%s' contains invalidly escaped characters"),
1337                        uri);
1338           return NULL;
1339         }
1340       
1341       if (hostname)
1342         *hostname = unescaped_hostname;
1343       else
1344         g_free (unescaped_hostname);
1345     }
1346
1347   filename = g_unescape_uri_string (path_part, "/", -1);
1348
1349   if (filename == NULL)
1350     {
1351       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1352                    _("The URI '%s' contains invalidly escaped characters"),
1353                    uri);
1354       return NULL;
1355     }
1356
1357   offs = 0;
1358 #ifdef G_OS_WIN32
1359   /* Drop localhost */
1360   if (hostname && *hostname != NULL &&
1361       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1362     {
1363       g_free (*hostname);
1364       *hostname = NULL;
1365     }
1366
1367   /* Turn slashes into backslashes, because that's the canonical spelling */
1368   p = filename;
1369   while ((slash = strchr (p, '/')) != NULL)
1370     {
1371       *slash = '\\';
1372       p = slash + 1;
1373     }
1374
1375   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1376    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1377    * the filename from the drive letter.
1378    */
1379   if (g_ascii_isalpha (filename[1]))
1380     {
1381       if (filename[2] == ':')
1382         offs = 1;
1383       else if (filename[2] == '|')
1384         {
1385           filename[2] = ':';
1386           offs = 1;
1387         }
1388     }
1389 #endif
1390   
1391   result = g_filename_from_utf8 (filename + offs, -1, NULL, NULL, error);
1392   g_free (filename);
1393   
1394   return result;
1395 }
1396
1397 /**
1398  * g_filename_to_uri:
1399  * @filename: an absolute filename specified in the encoding
1400  *            used for filenames by the operating system.
1401  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1402  * @error: location to store the error occuring, or %NULL to ignore
1403  *         errors. Any of the errors in #GConvertError may occur.
1404  * 
1405  * Converts an absolute filename to an escaped UTF-8 encoded URI.
1406  * 
1407  * Return value: a newly-allocated string holding the resulting
1408  *               URI, or %NULL on an error.
1409  **/
1410 gchar *
1411 g_filename_to_uri   (const char *filename,
1412                      char       *hostname,
1413                      GError    **error)
1414 {
1415   char *escaped_uri;
1416   char *utf8_filename;
1417
1418   g_return_val_if_fail (filename != NULL, NULL);
1419
1420   if (!g_path_is_absolute (filename))
1421     {
1422       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1423                    _("The pathname '%s' is not an absolute path"),
1424                    filename);
1425       return NULL;
1426     }
1427
1428   utf8_filename = g_filename_to_utf8 (filename, -1, NULL, NULL, error);
1429   if (utf8_filename == NULL)
1430     return NULL;
1431   
1432   if (hostname &&
1433       !g_utf8_validate (hostname, -1, NULL))
1434     {
1435       g_free (utf8_filename);
1436       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1437                    _("Invalid byte sequence in hostname"));
1438       return NULL;
1439     }
1440   
1441 #ifdef G_OS_WIN32
1442   /* Don't use localhost unnecessarily */
1443   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1444     hostname = NULL;
1445 #endif
1446
1447   escaped_uri = g_escape_file_uri (hostname,
1448                                    utf8_filename);
1449   g_free (utf8_filename);
1450   
1451   return escaped_uri;
1452 }
1453