docs: Small improvements to glib-mkenums man page
[glib.git] / glib / gconvert.c
blobc1422062d31c5f2fdc1538129738c930428b554a
1 /* GLIB - Library of useful routines for C programming
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>
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.1 of the License, or (at your option) any later version.
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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
22 #include "glibconfig.h"
24 #ifndef G_OS_WIN32
25 #include <iconv.h>
26 #endif
27 #include <errno.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
32 #ifdef G_OS_WIN32
33 #include "win_iconv.c"
34 #endif
36 #ifdef G_PLATFORM_WIN32
37 #define STRICT
38 #include <windows.h>
39 #undef STRICT
40 #endif
42 #include "gconvert.h"
44 #include "gcharsetprivate.h"
45 #include "gslist.h"
46 #include "gstrfuncs.h"
47 #include "gtestutils.h"
48 #include "gthread.h"
49 #include "gunicode.h"
50 #include "gfileutils.h"
52 #include "glibintl.h"
54 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
55 #error GNU libiconv in use but included iconv.h not from libiconv
56 #endif
57 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H) \
58 && !defined (__APPLE_CC__) && !defined (__LP_64__)
59 #error GNU libiconv not in use but included iconv.h is from libiconv
60 #endif
63 /**
64 * SECTION:conversions
65 * @title: Character Set Conversion
66 * @short_description: convert strings between different character sets
68 * The g_convert() family of function wraps the functionality of iconv().
69 * In addition to pure character set conversions, GLib has functions to
70 * deal with the extra complications of encodings for file names.
72 * ## File Name Encodings
74 * Historically, UNIX has not had a defined encoding for file names:
75 * a file name is valid as long as it does not have path separators
76 * in it ("/"). However, displaying file names may require conversion:
77 * from the character set in which they were created, to the character
78 * set in which the application operates. Consider the Spanish file name
79 * "Presentaci&oacute;n.sxi". If the application which created it uses
80 * ISO-8859-1 for its encoding,
81 * |[
82 * Character: P r e s e n t a c i ó n . s x i
83 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
84 * ]|
85 * However, if the application use UTF-8, the actual file name on
86 * disk would look like this:
87 * |[
88 * Character: P r e s e n t a c i ó n . s x i
89 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
90 * ]|
91 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+ that use
92 * Glib do the same thing. If you get a file name from the file system,
93 * for example, from readdir() or from g_dir_read_name(), and you wish
94 * to display the file name to the user, you will need to convert it
95 * into UTF-8. The opposite case is when the user types the name of a
96 * file he wishes to save: the toolkit will give you that string in
97 * UTF-8 encoding, and you will need to convert it to the character
98 * set used for file names before you can create the file with open()
99 * or fopen().
101 * By default, Glib assumes that file names on disk are in UTF-8
102 * encoding. This is a valid assumption for file systems which
103 * were created relatively recently: most applications use UTF-8
104 * encoding for their strings, and that is also what they use for
105 * the file names they create. However, older file systems may
106 * still contain file names created in "older" encodings, such as
107 * ISO-8859-1. In this case, for compatibility reasons, you may want
108 * to instruct Glib to use that particular encoding for file names
109 * rather than UTF-8. You can do this by specifying the encoding for
110 * file names in the [`G_FILENAME_ENCODING`][G_FILENAME_ENCODING]
111 * environment variable. For example, if your installation uses
112 * ISO-8859-1 for file names, you can put this in your `~/.profile`
113 * |[
114 * export G_FILENAME_ENCODING=ISO-8859-1
115 * ]|
116 * Glib provides the functions g_filename_to_utf8() and
117 * g_filename_from_utf8() to perform the necessary conversions.
118 * These functions convert file names from the encoding specified
119 * in `G_FILENAME_ENCODING` to UTF-8 and vice-versa. This
120 * [diagram][file-name-encodings-diagram] illustrates how
121 * these functions are used to convert between UTF-8 and the
122 * encoding for file names in the file system.
124 * ## Conversion between file name encodings # {#file-name-encodings-diagram)
126 * ![](file-name-encodings.png)
128 * ## Checklist for Application Writers
130 * This section is a practical summary of the detailed
131 * things to do to make sure your applications process file
132 * name encodings correctly.
134 * 1. If you get a file name from the file system from a function
135 * such as readdir() or gtk_file_chooser_get_filename(), you do
136 * not need to do any conversion to pass that file name to
137 * functions like open(), rename(), or fopen() -- those are "raw"
138 * file names which the file system understands.
140 * 2. If you need to display a file name, convert it to UTF-8 first
141 * by using g_filename_to_utf8(). If conversion fails, display a
142 * string like "Unknown file name". Do not convert this string back
143 * into the encoding used for file names if you wish to pass it to
144 * the file system; use the original file name instead.
146 * For example, the document window of a word processor could display
147 * "Unknown file name" in its title bar but still let the user save
148 * the file, as it would keep the raw file name internally. This
149 * can happen if the user has not set the `G_FILENAME_ENCODING`
150 * environment variable even though he has files whose names are
151 * not encoded in UTF-8.
153 * 3. If your user interface lets the user type a file name for saving
154 * or renaming, convert it to the encoding used for file names in
155 * the file system by using g_filename_from_utf8(). Pass the converted
156 * file name to functions like fopen(). If conversion fails, ask the
157 * user to enter a different file name. This can happen if the user
158 * types Japanese characters when `G_FILENAME_ENCODING` is set to
159 * `ISO-8859-1`, for example.
162 /* We try to terminate strings in unknown charsets with this many zero bytes
163 * to ensure that multibyte strings really are nul-terminated when we return
164 * them from g_convert() and friends.
166 #define NUL_TERMINATOR_LENGTH 4
168 G_DEFINE_QUARK (g_convert_error, g_convert_error)
170 static gboolean
171 try_conversion (const char *to_codeset,
172 const char *from_codeset,
173 iconv_t *cd)
175 *cd = iconv_open (to_codeset, from_codeset);
177 if (*cd == (iconv_t)-1 && errno == EINVAL)
178 return FALSE;
179 else
180 return TRUE;
183 static gboolean
184 try_to_aliases (const char **to_aliases,
185 const char *from_codeset,
186 iconv_t *cd)
188 if (to_aliases)
190 const char **p = to_aliases;
191 while (*p)
193 if (try_conversion (*p, from_codeset, cd))
194 return TRUE;
196 p++;
200 return FALSE;
204 * g_iconv_open: (skip)
205 * @to_codeset: destination codeset
206 * @from_codeset: source codeset
208 * Same as the standard UNIX routine iconv_open(), but
209 * may be implemented via libiconv on UNIX flavors that lack
210 * a native implementation.
212 * GLib provides g_convert() and g_locale_to_utf8() which are likely
213 * more convenient than the raw iconv wrappers.
215 * Returns: a "conversion descriptor", or (GIConv)-1 if
216 * opening the converter failed.
218 GIConv
219 g_iconv_open (const gchar *to_codeset,
220 const gchar *from_codeset)
222 iconv_t cd;
224 if (!try_conversion (to_codeset, from_codeset, &cd))
226 const char **to_aliases = _g_charset_get_aliases (to_codeset);
227 const char **from_aliases = _g_charset_get_aliases (from_codeset);
229 if (from_aliases)
231 const char **p = from_aliases;
232 while (*p)
234 if (try_conversion (to_codeset, *p, &cd))
235 goto out;
237 if (try_to_aliases (to_aliases, *p, &cd))
238 goto out;
240 p++;
244 if (try_to_aliases (to_aliases, from_codeset, &cd))
245 goto out;
248 out:
249 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
253 * g_iconv: (skip)
254 * @converter: conversion descriptor from g_iconv_open()
255 * @inbuf: bytes to convert
256 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
257 * @outbuf: converted output bytes
258 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
260 * Same as the standard UNIX routine iconv(), but
261 * may be implemented via libiconv on UNIX flavors that lack
262 * a native implementation.
264 * GLib provides g_convert() and g_locale_to_utf8() which are likely
265 * more convenient than the raw iconv wrappers.
267 * Returns: count of non-reversible conversions, or -1 on error
269 gsize
270 g_iconv (GIConv converter,
271 gchar **inbuf,
272 gsize *inbytes_left,
273 gchar **outbuf,
274 gsize *outbytes_left)
276 iconv_t cd = (iconv_t)converter;
278 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
282 * g_iconv_close: (skip)
283 * @converter: a conversion descriptor from g_iconv_open()
285 * Same as the standard UNIX routine iconv_close(), but
286 * may be implemented via libiconv on UNIX flavors that lack
287 * a native implementation. Should be called to clean up
288 * the conversion descriptor from g_iconv_open() when
289 * you are done converting things.
291 * GLib provides g_convert() and g_locale_to_utf8() which are likely
292 * more convenient than the raw iconv wrappers.
294 * Returns: -1 on error, 0 on success
296 gint
297 g_iconv_close (GIConv converter)
299 iconv_t cd = (iconv_t)converter;
301 return iconv_close (cd);
304 static GIConv
305 open_converter (const gchar *to_codeset,
306 const gchar *from_codeset,
307 GError **error)
309 GIConv cd;
311 cd = g_iconv_open (to_codeset, from_codeset);
313 if (cd == (GIConv) -1)
315 /* Something went wrong. */
316 if (error)
318 if (errno == EINVAL)
319 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
320 _("Conversion from character set “%s” to “%s” is not supported"),
321 from_codeset, to_codeset);
322 else
323 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
324 _("Could not open converter from “%s” to “%s”"),
325 from_codeset, to_codeset);
329 return cd;
332 static int
333 close_converter (GIConv cd)
335 if (cd == (GIConv) -1)
336 return 0;
338 return g_iconv_close (cd);
342 * g_convert_with_iconv: (skip)
343 * @str: the string to convert
344 * @len: the length of the string in bytes, or -1 if the string is
345 * nul-terminated (Note that some encodings may allow nul
346 * bytes to occur inside strings. In that case, using -1
347 * for the @len parameter is unsafe)
348 * @converter: conversion descriptor from g_iconv_open()
349 * @bytes_read: location to store the number of bytes in the
350 * input string that were successfully converted, or %NULL.
351 * Even if the conversion was successful, this may be
352 * less than @len if there were partial characters
353 * at the end of the input. If the error
354 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
355 * stored will the byte offset after the last valid
356 * input sequence.
357 * @bytes_written: the number of bytes stored in the output buffer (not
358 * including the terminating nul).
359 * @error: location to store the error occurring, or %NULL to ignore
360 * errors. Any of the errors in #GConvertError may occur.
362 * Converts a string from one character set to another.
364 * Note that you should use g_iconv() for streaming conversions.
365 * Despite the fact that @bytes_read can return information about partial
366 * characters, the g_convert_... functions are not generally suitable
367 * for streaming. If the underlying converter maintains internal state,
368 * then this won't be preserved across successive calls to g_convert(),
369 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
370 * this is the GNU C converter for CP1255 which does not emit a base
371 * character until it knows that the next character is not a mark that
372 * could combine with the base character.)
374 * Returns: If the conversion was successful, a newly allocated
375 * nul-terminated string, which must be freed with
376 * g_free(). Otherwise %NULL and @error will be set.
378 gchar*
379 g_convert_with_iconv (const gchar *str,
380 gssize len,
381 GIConv converter,
382 gsize *bytes_read,
383 gsize *bytes_written,
384 GError **error)
386 gchar *dest;
387 gchar *outp;
388 const gchar *p;
389 gsize inbytes_remaining;
390 gsize outbytes_remaining;
391 gsize err;
392 gsize outbuf_size;
393 gboolean have_error = FALSE;
394 gboolean done = FALSE;
395 gboolean reset = FALSE;
397 g_return_val_if_fail (converter != (GIConv) -1, NULL);
399 if (len < 0)
400 len = strlen (str);
402 p = str;
403 inbytes_remaining = len;
404 outbuf_size = len + NUL_TERMINATOR_LENGTH;
406 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
407 outp = dest = g_malloc (outbuf_size);
409 while (!done && !have_error)
411 if (reset)
412 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
413 else
414 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
416 if (err == (gsize) -1)
418 switch (errno)
420 case EINVAL:
421 /* Incomplete text, do not report an error */
422 done = TRUE;
423 break;
424 case E2BIG:
426 gsize used = outp - dest;
428 outbuf_size *= 2;
429 dest = g_realloc (dest, outbuf_size);
431 outp = dest + used;
432 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
434 break;
435 case EILSEQ:
436 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
437 _("Invalid byte sequence in conversion input"));
438 have_error = TRUE;
439 break;
440 default:
442 int errsv = errno;
444 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
445 _("Error during conversion: %s"),
446 g_strerror (errsv));
448 have_error = TRUE;
449 break;
452 else
454 if (!reset)
456 /* call g_iconv with NULL inbuf to cleanup shift state */
457 reset = TRUE;
458 inbytes_remaining = 0;
460 else
461 done = TRUE;
465 memset (outp, 0, NUL_TERMINATOR_LENGTH);
467 if (bytes_read)
468 *bytes_read = p - str;
469 else
471 if ((p - str) != len)
473 if (!have_error)
475 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
476 _("Partial character sequence at end of input"));
477 have_error = TRUE;
482 if (bytes_written)
483 *bytes_written = outp - dest; /* Doesn't include '\0' */
485 if (have_error)
487 g_free (dest);
488 return NULL;
490 else
491 return dest;
495 * g_convert:
496 * @str: the string to convert
497 * @len: the length of the string in bytes, or -1 if the string is
498 * nul-terminated (Note that some encodings may allow nul
499 * bytes to occur inside strings. In that case, using -1
500 * for the @len parameter is unsafe)
501 * @to_codeset: name of character set into which to convert @str
502 * @from_codeset: character set of @str.
503 * @bytes_read: (out): location to store the number of bytes in the
504 * input string that were successfully converted, or %NULL.
505 * Even if the conversion was successful, this may be
506 * less than @len if there were partial characters
507 * at the end of the input. If the error
508 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
509 * stored will the byte offset after the last valid
510 * input sequence.
511 * @bytes_written: (out): the number of bytes stored in the output buffer (not
512 * including the terminating nul).
513 * @error: location to store the error occurring, or %NULL to ignore
514 * errors. Any of the errors in #GConvertError may occur.
516 * Converts a string from one character set to another.
518 * Note that you should use g_iconv() for streaming conversions.
519 * Despite the fact that @bytes_read can return information about partial
520 * characters, the g_convert_... functions are not generally suitable
521 * for streaming. If the underlying converter maintains internal state,
522 * then this won't be preserved across successive calls to g_convert(),
523 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
524 * this is the GNU C converter for CP1255 which does not emit a base
525 * character until it knows that the next character is not a mark that
526 * could combine with the base character.)
528 * Using extensions such as "//TRANSLIT" may not work (or may not work
529 * well) on many platforms. Consider using g_str_to_ascii() instead.
531 * Returns: If the conversion was successful, a newly allocated
532 * nul-terminated string, which must be freed with
533 * g_free(). Otherwise %NULL and @error will be set.
535 gchar*
536 g_convert (const gchar *str,
537 gssize len,
538 const gchar *to_codeset,
539 const gchar *from_codeset,
540 gsize *bytes_read,
541 gsize *bytes_written,
542 GError **error)
544 gchar *res;
545 GIConv cd;
547 g_return_val_if_fail (str != NULL, NULL);
548 g_return_val_if_fail (to_codeset != NULL, NULL);
549 g_return_val_if_fail (from_codeset != NULL, NULL);
551 cd = open_converter (to_codeset, from_codeset, error);
553 if (cd == (GIConv) -1)
555 if (bytes_read)
556 *bytes_read = 0;
558 if (bytes_written)
559 *bytes_written = 0;
561 return NULL;
564 res = g_convert_with_iconv (str, len, cd,
565 bytes_read, bytes_written,
566 error);
568 close_converter (cd);
570 return res;
574 * g_convert_with_fallback:
575 * @str: the string to convert
576 * @len: the length of the string in bytes, or -1 if the string is
577 * nul-terminated (Note that some encodings may allow nul
578 * bytes to occur inside strings. In that case, using -1
579 * for the @len parameter is unsafe)
580 * @to_codeset: name of character set into which to convert @str
581 * @from_codeset: character set of @str.
582 * @fallback: UTF-8 string to use in place of character not
583 * present in the target encoding. (The string must be
584 * representable in the target encoding).
585 * If %NULL, characters not in the target encoding will
586 * be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
587 * @bytes_read: location to store the number of bytes in the
588 * input string that were successfully converted, or %NULL.
589 * Even if the conversion was successful, this may be
590 * less than @len if there were partial characters
591 * at the end of the input.
592 * @bytes_written: the number of bytes stored in the output buffer (not
593 * including the terminating nul).
594 * @error: location to store the error occurring, or %NULL to ignore
595 * errors. Any of the errors in #GConvertError may occur.
597 * Converts a string from one character set to another, possibly
598 * including fallback sequences for characters not representable
599 * in the output. Note that it is not guaranteed that the specification
600 * for the fallback sequences in @fallback will be honored. Some
601 * systems may do an approximate conversion from @from_codeset
602 * to @to_codeset in their iconv() functions,
603 * in which case GLib will simply return that approximate conversion.
605 * Note that you should use g_iconv() for streaming conversions.
606 * Despite the fact that @bytes_read can return information about partial
607 * characters, the g_convert_... functions are not generally suitable
608 * for streaming. If the underlying converter maintains internal state,
609 * then this won't be preserved across successive calls to g_convert(),
610 * g_convert_with_iconv() or g_convert_with_fallback(). (An example of
611 * this is the GNU C converter for CP1255 which does not emit a base
612 * character until it knows that the next character is not a mark that
613 * could combine with the base character.)
615 * Returns: If the conversion was successful, a newly allocated
616 * nul-terminated string, which must be freed with
617 * g_free(). Otherwise %NULL and @error will be set.
619 gchar*
620 g_convert_with_fallback (const gchar *str,
621 gssize len,
622 const gchar *to_codeset,
623 const gchar *from_codeset,
624 const gchar *fallback,
625 gsize *bytes_read,
626 gsize *bytes_written,
627 GError **error)
629 gchar *utf8;
630 gchar *dest;
631 gchar *outp;
632 const gchar *insert_str = NULL;
633 const gchar *p;
634 gsize inbytes_remaining;
635 const gchar *save_p = NULL;
636 gsize save_inbytes = 0;
637 gsize outbytes_remaining;
638 gsize err;
639 GIConv cd;
640 gsize outbuf_size;
641 gboolean have_error = FALSE;
642 gboolean done = FALSE;
644 GError *local_error = NULL;
646 g_return_val_if_fail (str != NULL, NULL);
647 g_return_val_if_fail (to_codeset != NULL, NULL);
648 g_return_val_if_fail (from_codeset != NULL, NULL);
650 if (len < 0)
651 len = strlen (str);
653 /* Try an exact conversion; we only proceed if this fails
654 * due to an illegal sequence in the input string.
656 dest = g_convert (str, len, to_codeset, from_codeset,
657 bytes_read, bytes_written, &local_error);
658 if (!local_error)
659 return dest;
661 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
663 g_propagate_error (error, local_error);
664 return NULL;
666 else
667 g_error_free (local_error);
669 local_error = NULL;
671 /* No go; to proceed, we need a converter from "UTF-8" to
672 * to_codeset, and the string as UTF-8.
674 cd = open_converter (to_codeset, "UTF-8", error);
675 if (cd == (GIConv) -1)
677 if (bytes_read)
678 *bytes_read = 0;
680 if (bytes_written)
681 *bytes_written = 0;
683 return NULL;
686 utf8 = g_convert (str, len, "UTF-8", from_codeset,
687 bytes_read, &inbytes_remaining, error);
688 if (!utf8)
690 close_converter (cd);
691 if (bytes_written)
692 *bytes_written = 0;
693 return NULL;
696 /* Now the heart of the code. We loop through the UTF-8 string, and
697 * whenever we hit an offending character, we form fallback, convert
698 * the fallback to the target codeset, and then go back to
699 * converting the original string after finishing with the fallback.
701 * The variables save_p and save_inbytes store the input state
702 * for the original string while we are converting the fallback
704 p = utf8;
706 outbuf_size = len + NUL_TERMINATOR_LENGTH;
707 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
708 outp = dest = g_malloc (outbuf_size);
710 while (!done && !have_error)
712 gsize inbytes_tmp = inbytes_remaining;
713 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
714 inbytes_remaining = inbytes_tmp;
716 if (err == (gsize) -1)
718 switch (errno)
720 case EINVAL:
721 g_assert_not_reached();
722 break;
723 case E2BIG:
725 gsize used = outp - dest;
727 outbuf_size *= 2;
728 dest = g_realloc (dest, outbuf_size);
730 outp = dest + used;
731 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
733 break;
735 case EILSEQ:
736 if (save_p)
738 /* Error converting fallback string - fatal
740 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
741 _("Cannot convert fallback “%s” to codeset “%s”"),
742 insert_str, to_codeset);
743 have_error = TRUE;
744 break;
746 else if (p)
748 if (!fallback)
750 gunichar ch = g_utf8_get_char (p);
751 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
752 ch);
754 else
755 insert_str = fallback;
757 save_p = g_utf8_next_char (p);
758 save_inbytes = inbytes_remaining - (save_p - p);
759 p = insert_str;
760 inbytes_remaining = strlen (p);
761 break;
763 /* fall thru if p is NULL */
764 default:
766 int errsv = errno;
768 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
769 _("Error during conversion: %s"),
770 g_strerror (errsv));
773 have_error = TRUE;
774 break;
777 else
779 if (save_p)
781 if (!fallback)
782 g_free ((gchar *)insert_str);
783 p = save_p;
784 inbytes_remaining = save_inbytes;
785 save_p = NULL;
787 else if (p)
789 /* call g_iconv with NULL inbuf to cleanup shift state */
790 p = NULL;
791 inbytes_remaining = 0;
793 else
794 done = TRUE;
798 /* Cleanup
800 memset (outp, 0, NUL_TERMINATOR_LENGTH);
802 close_converter (cd);
804 if (bytes_written)
805 *bytes_written = outp - dest; /* Doesn't include '\0' */
807 g_free (utf8);
809 if (have_error)
811 if (save_p && !fallback)
812 g_free ((gchar *)insert_str);
813 g_free (dest);
814 return NULL;
816 else
817 return dest;
821 * g_locale_to_utf8
826 static gchar *
827 strdup_len (const gchar *string,
828 gssize len,
829 gsize *bytes_written,
830 gsize *bytes_read,
831 GError **error)
834 gsize real_len;
836 if (!g_utf8_validate (string, len, NULL))
838 if (bytes_read)
839 *bytes_read = 0;
840 if (bytes_written)
841 *bytes_written = 0;
843 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
844 _("Invalid byte sequence in conversion input"));
845 return NULL;
848 if (len < 0)
849 real_len = strlen (string);
850 else
852 real_len = 0;
854 while (real_len < len && string[real_len])
855 real_len++;
858 if (bytes_read)
859 *bytes_read = real_len;
860 if (bytes_written)
861 *bytes_written = real_len;
863 return g_strndup (string, real_len);
867 * g_locale_to_utf8:
868 * @opsysstring: a string in the encoding of the current locale. On Windows
869 * this means the system codepage.
870 * @len: the length of the string, or -1 if the string is
871 * nul-terminated (Note that some encodings may allow nul
872 * bytes to occur inside strings. In that case, using -1
873 * for the @len parameter is unsafe)
874 * @bytes_read: (out) (optional): location to store the number of bytes in the
875 * input string that were successfully converted, or %NULL.
876 * Even if the conversion was successful, this may be
877 * less than @len if there were partial characters
878 * at the end of the input. If the error
879 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
880 * stored will the byte offset after the last valid
881 * input sequence.
882 * @bytes_written: (out) (optional): the number of bytes stored in the output
883 * buffer (not including the terminating nul).
884 * @error: location to store the error occurring, or %NULL to ignore
885 * errors. Any of the errors in #GConvertError may occur.
887 * Converts a string which is in the encoding used for strings by
888 * the C runtime (usually the same as that used by the operating
889 * system) in the [current locale][setlocale] into a UTF-8 string.
891 * Returns: A newly-allocated buffer containing the converted string,
892 * or %NULL on an error, and error will be set.
894 gchar *
895 g_locale_to_utf8 (const gchar *opsysstring,
896 gssize len,
897 gsize *bytes_read,
898 gsize *bytes_written,
899 GError **error)
901 const char *charset;
903 if (g_get_charset (&charset))
904 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
905 else
906 return g_convert (opsysstring, len,
907 "UTF-8", charset, bytes_read, bytes_written, error);
911 * g_locale_from_utf8:
912 * @utf8string: a UTF-8 encoded string
913 * @len: the length of the string, or -1 if the string is
914 * nul-terminated (Note that some encodings may allow nul
915 * bytes to occur inside strings. In that case, using -1
916 * for the @len parameter is unsafe)
917 * @bytes_read: (out) (optional): location to store the number of bytes in the
918 * input string that were successfully converted, or %NULL.
919 * Even if the conversion was successful, this may be
920 * less than @len if there were partial characters
921 * at the end of the input. If the error
922 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
923 * stored will the byte offset after the last valid
924 * input sequence.
925 * @bytes_written: (out) (optional): the number of bytes stored in the output
926 * buffer (not including the terminating nul).
927 * @error: location to store the error occurring, or %NULL to ignore
928 * errors. Any of the errors in #GConvertError may occur.
930 * Converts a string from UTF-8 to the encoding used for strings by
931 * the C runtime (usually the same as that used by the operating
932 * system) in the [current locale][setlocale]. On Windows this means
933 * the system codepage.
935 * Returns: A newly-allocated buffer containing the converted string,
936 * or %NULL on an error, and error will be set.
938 gchar *
939 g_locale_from_utf8 (const gchar *utf8string,
940 gssize len,
941 gsize *bytes_read,
942 gsize *bytes_written,
943 GError **error)
945 const gchar *charset;
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);
954 #ifndef G_PLATFORM_WIN32
956 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
958 struct _GFilenameCharsetCache {
959 gboolean is_utf8;
960 gchar *charset;
961 gchar **filename_charsets;
964 static void
965 filename_charset_cache_free (gpointer data)
967 GFilenameCharsetCache *cache = data;
968 g_free (cache->charset);
969 g_strfreev (cache->filename_charsets);
970 g_free (cache);
974 * g_get_filename_charsets:
975 * @charsets: return location for the %NULL-terminated list of encoding names
977 * Determines the preferred character sets used for filenames.
978 * The first character set from the @charsets is the filename encoding, the
979 * subsequent character sets are used when trying to generate a displayable
980 * representation of a filename, see g_filename_display_name().
982 * On Unix, the character sets are determined by consulting the
983 * environment variables `G_FILENAME_ENCODING` and `G_BROKEN_FILENAMES`.
984 * On Windows, the character set used in the GLib API is always UTF-8
985 * and said environment variables have no effect.
987 * `G_FILENAME_ENCODING` may be set to a comma-separated list of
988 * character set names. The special token "\@locale" is taken
989 * to mean the character set for the [current locale][setlocale].
990 * If `G_FILENAME_ENCODING` is not set, but `G_BROKEN_FILENAMES` is,
991 * the character set of the current locale is taken as the filename
992 * encoding. If neither environment variable is set, UTF-8 is taken
993 * as the filename encoding, but the character set of the current locale
994 * is also put in the list of encodings.
996 * The returned @charsets belong to GLib and must not be freed.
998 * Note that on Unix, regardless of the locale character set or
999 * `G_FILENAME_ENCODING` value, the actual file names present
1000 * on a system might be in any random encoding or just gibberish.
1002 * Returns: %TRUE if the filename encoding is UTF-8.
1004 * Since: 2.6
1006 gboolean
1007 g_get_filename_charsets (const gchar ***filename_charsets)
1009 static GPrivate cache_private = G_PRIVATE_INIT (filename_charset_cache_free);
1010 GFilenameCharsetCache *cache = g_private_get (&cache_private);
1011 const gchar *charset;
1013 if (!cache)
1015 cache = g_new0 (GFilenameCharsetCache, 1);
1016 g_private_set (&cache_private, cache);
1019 g_get_charset (&charset);
1021 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1023 const gchar *new_charset;
1024 gchar *p;
1025 gint i;
1027 g_free (cache->charset);
1028 g_strfreev (cache->filename_charsets);
1029 cache->charset = g_strdup (charset);
1031 p = getenv ("G_FILENAME_ENCODING");
1032 if (p != NULL && p[0] != '\0')
1034 cache->filename_charsets = g_strsplit (p, ",", 0);
1035 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1037 for (i = 0; cache->filename_charsets[i]; i++)
1039 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1041 g_get_charset (&new_charset);
1042 g_free (cache->filename_charsets[i]);
1043 cache->filename_charsets[i] = g_strdup (new_charset);
1047 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1049 cache->filename_charsets = g_new0 (gchar *, 2);
1050 cache->is_utf8 = g_get_charset (&new_charset);
1051 cache->filename_charsets[0] = g_strdup (new_charset);
1053 else
1055 cache->filename_charsets = g_new0 (gchar *, 3);
1056 cache->is_utf8 = TRUE;
1057 cache->filename_charsets[0] = g_strdup ("UTF-8");
1058 if (!g_get_charset (&new_charset))
1059 cache->filename_charsets[1] = g_strdup (new_charset);
1063 if (filename_charsets)
1064 *filename_charsets = (const gchar **)cache->filename_charsets;
1066 return cache->is_utf8;
1069 #else /* G_PLATFORM_WIN32 */
1071 gboolean
1072 g_get_filename_charsets (const gchar ***filename_charsets)
1074 static const gchar *charsets[] = {
1075 "UTF-8",
1076 NULL
1079 #ifdef G_OS_WIN32
1080 /* On Windows GLib pretends that the filename charset is UTF-8 */
1081 if (filename_charsets)
1082 *filename_charsets = charsets;
1084 return TRUE;
1085 #else
1086 gboolean result;
1088 /* Cygwin works like before */
1089 result = g_get_charset (&(charsets[0]));
1091 if (filename_charsets)
1092 *filename_charsets = charsets;
1094 return result;
1095 #endif
1098 #endif /* G_PLATFORM_WIN32 */
1100 static gboolean
1101 get_filename_charset (const gchar **filename_charset)
1103 const gchar **charsets;
1104 gboolean is_utf8;
1106 is_utf8 = g_get_filename_charsets (&charsets);
1108 if (filename_charset)
1109 *filename_charset = charsets[0];
1111 return is_utf8;
1115 * g_filename_to_utf8:
1116 * @opsysstring: (type filename): a string in the encoding for filenames
1117 * @len: the length of the string, or -1 if the string is
1118 * nul-terminated (Note that some encodings may allow nul
1119 * bytes to occur inside strings. In that case, using -1
1120 * for the @len parameter is unsafe)
1121 * @bytes_read: (out) (optional): location to store the number of bytes in the
1122 * input string that were successfully converted, or %NULL.
1123 * Even if the conversion was successful, this may be
1124 * less than @len if there were partial characters
1125 * at the end of the input. If the error
1126 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1127 * stored will the byte offset after the last valid
1128 * input sequence.
1129 * @bytes_written: (out) (optional): the number of bytes stored in the output
1130 * buffer (not including the terminating nul).
1131 * @error: location to store the error occurring, or %NULL to ignore
1132 * errors. Any of the errors in #GConvertError may occur.
1134 * Converts a string which is in the encoding used by GLib for
1135 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1136 * for filenames; on other platforms, this function indirectly depends on
1137 * the [current locale][setlocale].
1139 * Returns: The converted string, or %NULL on an error.
1141 gchar*
1142 g_filename_to_utf8 (const gchar *opsysstring,
1143 gssize len,
1144 gsize *bytes_read,
1145 gsize *bytes_written,
1146 GError **error)
1148 const gchar *charset;
1150 g_return_val_if_fail (opsysstring != NULL, NULL);
1152 if (get_filename_charset (&charset))
1153 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1154 else
1155 return g_convert (opsysstring, len,
1156 "UTF-8", charset, bytes_read, bytes_written, error);
1160 * g_filename_from_utf8:
1161 * @utf8string: a UTF-8 encoded string.
1162 * @len: the length of the string, or -1 if the string is
1163 * nul-terminated.
1164 * @bytes_read: (out) (optional): location to store the number of bytes in
1165 * the input string that were successfully converted, or %NULL.
1166 * Even if the conversion was successful, this may be
1167 * less than @len if there were partial characters
1168 * at the end of the input. If the error
1169 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1170 * stored will the byte offset after the last valid
1171 * input sequence.
1172 * @bytes_written: (out): the number of bytes stored in the output buffer (not
1173 * including the terminating nul).
1174 * @error: location to store the error occurring, or %NULL to ignore
1175 * errors. Any of the errors in #GConvertError may occur.
1177 * Converts a string from UTF-8 to the encoding GLib uses for
1178 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1179 * on other platforms, this function indirectly depends on the
1180 * [current locale][setlocale].
1182 * Returns: (array length=bytes_written) (element-type guint8) (transfer full):
1183 * The converted string, or %NULL on an error.
1185 gchar*
1186 g_filename_from_utf8 (const gchar *utf8string,
1187 gssize len,
1188 gsize *bytes_read,
1189 gsize *bytes_written,
1190 GError **error)
1192 const gchar *charset;
1194 if (get_filename_charset (&charset))
1195 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1196 else
1197 return g_convert (utf8string, len,
1198 charset, "UTF-8", bytes_read, bytes_written, error);
1201 /* Test of haystack has the needle prefix, comparing case
1202 * insensitive. haystack may be UTF-8, but needle must
1203 * contain only ascii. */
1204 static gboolean
1205 has_case_prefix (const gchar *haystack, const gchar *needle)
1207 const gchar *h, *n;
1209 /* Eat one character at a time. */
1210 h = haystack;
1211 n = needle;
1213 while (*n && *h &&
1214 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1216 n++;
1217 h++;
1220 return *n == '\0';
1223 typedef enum {
1224 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1225 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1226 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1227 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1228 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1229 } UnsafeCharacterSet;
1231 static const guchar acceptable[96] = {
1232 /* A table of the ASCII chars from space (32) to DEL (127) */
1233 /* ! " # $ % & ' ( ) * + , - . / */
1234 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1235 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1236 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1237 /* @ A B C D E F G H I J K L M N O */
1238 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1239 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1240 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1241 /* ` a b c d e f g h i j k l m n o */
1242 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1243 /* p q r s t u v w x y z { | } ~ DEL */
1244 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1247 static const gchar hex[16] = "0123456789ABCDEF";
1249 /* Note: This escape function works on file: URIs, but if you want to
1250 * escape something else, please read RFC-2396 */
1251 static gchar *
1252 g_escape_uri_string (const gchar *string,
1253 UnsafeCharacterSet mask)
1255 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1257 const gchar *p;
1258 gchar *q;
1259 gchar *result;
1260 int c;
1261 gint unacceptable;
1262 UnsafeCharacterSet use_mask;
1264 g_return_val_if_fail (mask == UNSAFE_ALL
1265 || mask == UNSAFE_ALLOW_PLUS
1266 || mask == UNSAFE_PATH
1267 || mask == UNSAFE_HOST
1268 || mask == UNSAFE_SLASHES, NULL);
1270 unacceptable = 0;
1271 use_mask = mask;
1272 for (p = string; *p != '\0'; p++)
1274 c = (guchar) *p;
1275 if (!ACCEPTABLE (c))
1276 unacceptable++;
1279 result = g_malloc (p - string + unacceptable * 2 + 1);
1281 use_mask = mask;
1282 for (q = result, p = string; *p != '\0'; p++)
1284 c = (guchar) *p;
1286 if (!ACCEPTABLE (c))
1288 *q++ = '%'; /* means hex coming */
1289 *q++ = hex[c >> 4];
1290 *q++ = hex[c & 15];
1292 else
1293 *q++ = *p;
1296 *q = '\0';
1298 return result;
1302 static gchar *
1303 g_escape_file_uri (const gchar *hostname,
1304 const gchar *pathname)
1306 char *escaped_hostname = NULL;
1307 char *escaped_path;
1308 char *res;
1310 #ifdef G_OS_WIN32
1311 char *p, *backslash;
1313 /* Turn backslashes into forward slashes. That's what Netscape
1314 * does, and they are actually more or less equivalent in Windows.
1317 pathname = g_strdup (pathname);
1318 p = (char *) pathname;
1320 while ((backslash = strchr (p, '\\')) != NULL)
1322 *backslash = '/';
1323 p = backslash + 1;
1325 #endif
1327 if (hostname && *hostname != '\0')
1329 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1332 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1334 res = g_strconcat ("file://",
1335 (escaped_hostname) ? escaped_hostname : "",
1336 (*escaped_path != '/') ? "/" : "",
1337 escaped_path,
1338 NULL);
1340 #ifdef G_OS_WIN32
1341 g_free ((char *) pathname);
1342 #endif
1344 g_free (escaped_hostname);
1345 g_free (escaped_path);
1347 return res;
1350 static int
1351 unescape_character (const char *scanner)
1353 int first_digit;
1354 int second_digit;
1356 first_digit = g_ascii_xdigit_value (scanner[0]);
1357 if (first_digit < 0)
1358 return -1;
1360 second_digit = g_ascii_xdigit_value (scanner[1]);
1361 if (second_digit < 0)
1362 return -1;
1364 return (first_digit << 4) | second_digit;
1367 static gchar *
1368 g_unescape_uri_string (const char *escaped,
1369 int len,
1370 const char *illegal_escaped_characters,
1371 gboolean ascii_must_not_be_escaped)
1373 const gchar *in, *in_end;
1374 gchar *out, *result;
1375 int c;
1377 if (escaped == NULL)
1378 return NULL;
1380 if (len < 0)
1381 len = strlen (escaped);
1383 result = g_malloc (len + 1);
1385 out = result;
1386 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1388 c = *in;
1390 if (c == '%')
1392 /* catch partial escape sequences past the end of the substring */
1393 if (in + 3 > in_end)
1394 break;
1396 c = unescape_character (in + 1);
1398 /* catch bad escape sequences and NUL characters */
1399 if (c <= 0)
1400 break;
1402 /* catch escaped ASCII */
1403 if (ascii_must_not_be_escaped && c <= 0x7F)
1404 break;
1406 /* catch other illegal escaped characters */
1407 if (strchr (illegal_escaped_characters, c) != NULL)
1408 break;
1410 in += 2;
1413 *out++ = c;
1416 g_assert (out - result <= len);
1417 *out = '\0';
1419 if (in != in_end)
1421 g_free (result);
1422 return NULL;
1425 return result;
1428 static gboolean
1429 is_asciialphanum (gunichar c)
1431 return c <= 0x7F && g_ascii_isalnum (c);
1434 static gboolean
1435 is_asciialpha (gunichar c)
1437 return c <= 0x7F && g_ascii_isalpha (c);
1440 /* allows an empty string */
1441 static gboolean
1442 hostname_validate (const char *hostname)
1444 const char *p;
1445 gunichar c, first_char, last_char;
1447 p = hostname;
1448 if (*p == '\0')
1449 return TRUE;
1452 /* read in a label */
1453 c = g_utf8_get_char (p);
1454 p = g_utf8_next_char (p);
1455 if (!is_asciialphanum (c))
1456 return FALSE;
1457 first_char = c;
1460 last_char = c;
1461 c = g_utf8_get_char (p);
1462 p = g_utf8_next_char (p);
1464 while (is_asciialphanum (c) || c == '-');
1465 if (last_char == '-')
1466 return FALSE;
1468 /* if that was the last label, check that it was a toplabel */
1469 if (c == '\0' || (c == '.' && *p == '\0'))
1470 return is_asciialpha (first_char);
1472 while (c == '.');
1473 return FALSE;
1477 * g_filename_from_uri:
1478 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1479 * @hostname: (out) (optional) (nullable): Location to store hostname for the URI.
1480 * If there is no hostname in the URI, %NULL will be
1481 * stored in this location.
1482 * @error: location to store the error occurring, or %NULL to ignore
1483 * errors. Any of the errors in #GConvertError may occur.
1485 * Converts an escaped ASCII-encoded URI to a local filename in the
1486 * encoding used for filenames.
1488 * Returns: (type filename): a newly-allocated string holding
1489 * the resulting filename, or %NULL on an error.
1491 gchar *
1492 g_filename_from_uri (const gchar *uri,
1493 gchar **hostname,
1494 GError **error)
1496 const char *path_part;
1497 const char *host_part;
1498 char *unescaped_hostname;
1499 char *result;
1500 char *filename;
1501 int offs;
1502 #ifdef G_OS_WIN32
1503 char *p, *slash;
1504 #endif
1506 if (hostname)
1507 *hostname = NULL;
1509 if (!has_case_prefix (uri, "file:/"))
1511 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1512 _("The URI “%s” is not an absolute URI using the “file” scheme"),
1513 uri);
1514 return NULL;
1517 path_part = uri + strlen ("file:");
1519 if (strchr (path_part, '#') != NULL)
1521 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1522 _("The local file URI “%s” may not include a “#”"),
1523 uri);
1524 return NULL;
1527 if (has_case_prefix (path_part, "///"))
1528 path_part += 2;
1529 else if (has_case_prefix (path_part, "//"))
1531 path_part += 2;
1532 host_part = path_part;
1534 path_part = strchr (path_part, '/');
1536 if (path_part == NULL)
1538 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1539 _("The URI “%s” is invalid"),
1540 uri);
1541 return NULL;
1544 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1546 if (unescaped_hostname == NULL ||
1547 !hostname_validate (unescaped_hostname))
1549 g_free (unescaped_hostname);
1550 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1551 _("The hostname of the URI “%s” is invalid"),
1552 uri);
1553 return NULL;
1556 if (hostname)
1557 *hostname = unescaped_hostname;
1558 else
1559 g_free (unescaped_hostname);
1562 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1564 if (filename == NULL)
1566 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1567 _("The URI “%s” contains invalidly escaped characters"),
1568 uri);
1569 return NULL;
1572 offs = 0;
1573 #ifdef G_OS_WIN32
1574 /* Drop localhost */
1575 if (hostname && *hostname != NULL &&
1576 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1578 g_free (*hostname);
1579 *hostname = NULL;
1582 /* Turn slashes into backslashes, because that's the canonical spelling */
1583 p = filename;
1584 while ((slash = strchr (p, '/')) != NULL)
1586 *slash = '\\';
1587 p = slash + 1;
1590 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1591 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1592 * the filename from the drive letter.
1594 if (g_ascii_isalpha (filename[1]))
1596 if (filename[2] == ':')
1597 offs = 1;
1598 else if (filename[2] == '|')
1600 filename[2] = ':';
1601 offs = 1;
1604 #endif
1606 result = g_strdup (filename + offs);
1607 g_free (filename);
1609 return result;
1613 * g_filename_to_uri:
1614 * @filename: (type filename): an absolute filename specified in the GLib file
1615 * name encoding, which is the on-disk file name bytes on Unix, and UTF-8
1616 * on Windows
1617 * @hostname: (nullable): A UTF-8 encoded hostname, or %NULL for none.
1618 * @error: location to store the error occurring, or %NULL to ignore
1619 * errors. Any of the errors in #GConvertError may occur.
1621 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1622 * component following Section 3.3. of RFC 2396.
1624 * Returns: a newly-allocated string holding the resulting
1625 * URI, or %NULL on an error.
1627 gchar *
1628 g_filename_to_uri (const gchar *filename,
1629 const gchar *hostname,
1630 GError **error)
1632 char *escaped_uri;
1634 g_return_val_if_fail (filename != NULL, NULL);
1636 if (!g_path_is_absolute (filename))
1638 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1639 _("The pathname “%s” is not an absolute path"),
1640 filename);
1641 return NULL;
1644 if (hostname &&
1645 !(g_utf8_validate (hostname, -1, NULL)
1646 && hostname_validate (hostname)))
1648 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1649 _("Invalid hostname"));
1650 return NULL;
1653 #ifdef G_OS_WIN32
1654 /* Don't use localhost unnecessarily */
1655 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1656 hostname = NULL;
1657 #endif
1659 escaped_uri = g_escape_file_uri (hostname, filename);
1661 return escaped_uri;
1665 * g_uri_list_extract_uris:
1666 * @uri_list: an URI list
1668 * Splits an URI list conforming to the text/uri-list
1669 * mime type defined in RFC 2483 into individual URIs,
1670 * discarding any comments. The URIs are not validated.
1672 * Returns: (transfer full): a newly allocated %NULL-terminated list
1673 * of strings holding the individual URIs. The array should be freed
1674 * with g_strfreev().
1676 * Since: 2.6
1678 gchar **
1679 g_uri_list_extract_uris (const gchar *uri_list)
1681 GSList *uris, *u;
1682 const gchar *p, *q;
1683 gchar **result;
1684 gint n_uris = 0;
1686 uris = NULL;
1688 p = uri_list;
1690 /* We don't actually try to validate the URI according to RFC
1691 * 2396, or even check for allowed characters - we just ignore
1692 * comments and trim whitespace off the ends. We also
1693 * allow LF delimination as well as the specified CRLF.
1695 * We do allow comments like specified in RFC 2483.
1697 while (p)
1699 if (*p != '#')
1701 while (g_ascii_isspace (*p))
1702 p++;
1704 q = p;
1705 while (*q && (*q != '\n') && (*q != '\r'))
1706 q++;
1708 if (q > p)
1710 q--;
1711 while (q > p && g_ascii_isspace (*q))
1712 q--;
1714 if (q > p)
1716 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
1717 n_uris++;
1721 p = strchr (p, '\n');
1722 if (p)
1723 p++;
1726 result = g_new (gchar *, n_uris + 1);
1728 result[n_uris--] = NULL;
1729 for (u = uris; u; u = u->next)
1730 result[n_uris--] = u->data;
1732 g_slist_free (uris);
1734 return result;
1738 * g_filename_display_basename:
1739 * @filename: (type filename): an absolute pathname in the
1740 * GLib file name encoding
1742 * Returns the display basename for the particular filename, guaranteed
1743 * to be valid UTF-8. The display name might not be identical to the filename,
1744 * for instance there might be problems converting it to UTF-8, and some files
1745 * can be translated in the display.
1747 * If GLib cannot make sense of the encoding of @filename, as a last resort it
1748 * replaces unknown characters with U+FFFD, the Unicode replacement character.
1749 * You can search the result for the UTF-8 encoding of this character (which is
1750 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
1751 * encoding.
1753 * You must pass the whole absolute pathname to this functions so that
1754 * translation of well known locations can be done.
1756 * This function is preferred over g_filename_display_name() if you know the
1757 * whole path, as it allows translation.
1759 * Returns: a newly allocated string containing
1760 * a rendition of the basename of the filename in valid UTF-8
1762 * Since: 2.6
1764 gchar *
1765 g_filename_display_basename (const gchar *filename)
1767 char *basename;
1768 char *display_name;
1770 g_return_val_if_fail (filename != NULL, NULL);
1772 basename = g_path_get_basename (filename);
1773 display_name = g_filename_display_name (basename);
1774 g_free (basename);
1775 return display_name;
1779 * g_filename_display_name:
1780 * @filename: (type filename): a pathname hopefully in the
1781 * GLib file name encoding
1783 * Converts a filename into a valid UTF-8 string. The conversion is
1784 * not necessarily reversible, so you should keep the original around
1785 * and use the return value of this function only for display purposes.
1786 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
1787 * even if the filename actually isn't in the GLib file name encoding.
1789 * If GLib cannot make sense of the encoding of @filename, as a last resort it
1790 * replaces unknown characters with U+FFFD, the Unicode replacement character.
1791 * You can search the result for the UTF-8 encoding of this character (which is
1792 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
1793 * encoding.
1795 * If you know the whole pathname of the file you should use
1796 * g_filename_display_basename(), since that allows location-based
1797 * translation of filenames.
1799 * Returns: a newly allocated string containing
1800 * a rendition of the filename in valid UTF-8
1802 * Since: 2.6
1804 gchar *
1805 g_filename_display_name (const gchar *filename)
1807 gint i;
1808 const gchar **charsets;
1809 gchar *display_name = NULL;
1810 gboolean is_utf8;
1812 is_utf8 = g_get_filename_charsets (&charsets);
1814 if (is_utf8)
1816 if (g_utf8_validate (filename, -1, NULL))
1817 display_name = g_strdup (filename);
1820 if (!display_name)
1822 /* Try to convert from the filename charsets to UTF-8.
1823 * Skip the first charset if it is UTF-8.
1825 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
1827 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
1828 NULL, NULL, NULL);
1830 if (display_name)
1831 break;
1835 /* if all conversions failed, we replace invalid UTF-8
1836 * by a question mark
1838 if (!display_name)
1839 display_name = g_utf8_make_valid (filename, -1);
1841 return display_name;
1844 #ifdef G_OS_WIN32
1846 /* Binary compatibility versions. Not for newly compiled code. */
1848 _GLIB_EXTERN gchar *g_filename_to_utf8_utf8 (const gchar *opsysstring,
1849 gssize len,
1850 gsize *bytes_read,
1851 gsize *bytes_written,
1852 GError **error) G_GNUC_MALLOC;
1853 _GLIB_EXTERN gchar *g_filename_from_utf8_utf8 (const gchar *utf8string,
1854 gssize len,
1855 gsize *bytes_read,
1856 gsize *bytes_written,
1857 GError **error) G_GNUC_MALLOC;
1858 _GLIB_EXTERN gchar *g_filename_from_uri_utf8 (const gchar *uri,
1859 gchar **hostname,
1860 GError **error) G_GNUC_MALLOC;
1861 _GLIB_EXTERN gchar *g_filename_to_uri_utf8 (const gchar *filename,
1862 const gchar *hostname,
1863 GError **error) G_GNUC_MALLOC;
1865 gchar *
1866 g_filename_to_utf8_utf8 (const gchar *opsysstring,
1867 gssize len,
1868 gsize *bytes_read,
1869 gsize *bytes_written,
1870 GError **error)
1872 return g_filename_to_utf8 (opsysstring, len, bytes_read, bytes_written, error);
1875 gchar *
1876 g_filename_from_utf8_utf8 (const gchar *utf8string,
1877 gssize len,
1878 gsize *bytes_read,
1879 gsize *bytes_written,
1880 GError **error)
1882 return g_filename_from_utf8 (utf8string, len, bytes_read, bytes_written, error);
1885 gchar *
1886 g_filename_from_uri_utf8 (const gchar *uri,
1887 gchar **hostname,
1888 GError **error)
1890 return g_filename_from_uri (uri, hostname, error);
1893 gchar *
1894 g_filename_to_uri_utf8 (const gchar *filename,
1895 const gchar *hostname,
1896 GError **error)
1898 return g_filename_to_uri (filename, hostname, error);
1901 #endif