unicodeio.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /* Unicode character output to streams with locale dependent encoding.
  2. Copyright (C) 2000-2003, 2006, 2008-2020 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. /* Written by Bruno Haible <haible@clisp.cons.org>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "unicodeio.h"
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #if HAVE_ICONV
  21. # include <iconv.h>
  22. #endif
  23. #include <error.h>
  24. #include "gettext.h"
  25. #define _(msgid) gettext (msgid)
  26. #define N_(msgid) msgid
  27. #include "localcharset.h"
  28. #include "unistr.h"
  29. /* When we pass a Unicode character to iconv(), we must pass it in a
  30. suitable encoding. The standardized Unicode encodings are
  31. UTF-8, UCS-2, UCS-4, UTF-16, UTF-16BE, UTF-16LE, UTF-7.
  32. UCS-2 supports only characters up to \U0000FFFF.
  33. UTF-16 and variants support only characters up to \U0010FFFF.
  34. UTF-7 is way too complex and not supported by glibc-2.1.
  35. UCS-4 specification leaves doubts about endianness and byte order
  36. mark. glibc currently interprets it as big endian without byte order
  37. mark, but this is not backed by an RFC.
  38. So we use UTF-8. It supports characters up to \U7FFFFFFF and is
  39. unambiguously defined. */
  40. /* Luckily, the encoding's name is platform independent. */
  41. #define UTF8_NAME "UTF-8"
  42. /* Converts the Unicode character CODE to its multibyte representation
  43. in the current locale and calls the SUCCESS callback on the resulting
  44. byte sequence. If an error occurs, invokes the FAILURE callback instead,
  45. passing it CODE and an English error string.
  46. Returns whatever the callback returned.
  47. Assumes that the locale doesn't change between two calls. */
  48. long
  49. unicode_to_mb (unsigned int code,
  50. long (*success) (const char *buf, size_t buflen,
  51. void *callback_arg),
  52. long (*failure) (unsigned int code, const char *msg,
  53. void *callback_arg),
  54. void *callback_arg)
  55. {
  56. static int initialized;
  57. static int is_utf8;
  58. #if HAVE_ICONV
  59. static iconv_t utf8_to_local;
  60. #endif
  61. char inbuf[6];
  62. int count;
  63. if (!initialized)
  64. {
  65. const char *charset = locale_charset ();
  66. is_utf8 = !strcmp (charset, UTF8_NAME);
  67. #if HAVE_ICONV
  68. if (!is_utf8)
  69. {
  70. utf8_to_local = iconv_open (charset, UTF8_NAME);
  71. if (utf8_to_local == (iconv_t)(-1))
  72. /* For an unknown encoding, assume ASCII. */
  73. utf8_to_local = iconv_open ("ASCII", UTF8_NAME);
  74. }
  75. #endif
  76. initialized = 1;
  77. }
  78. /* Test whether the utf8_to_local converter is available at all. */
  79. if (!is_utf8)
  80. {
  81. #if HAVE_ICONV
  82. if (utf8_to_local == (iconv_t)(-1))
  83. return failure (code, N_("iconv function not usable"), callback_arg);
  84. #else
  85. return failure (code, N_("iconv function not available"), callback_arg);
  86. #endif
  87. }
  88. /* Convert the character to UTF-8. */
  89. count = u8_uctomb ((unsigned char *) inbuf, code, sizeof (inbuf));
  90. if (count < 0)
  91. return failure (code, N_("character out of range"), callback_arg);
  92. #if HAVE_ICONV
  93. if (!is_utf8)
  94. {
  95. char outbuf[25];
  96. const char *inptr;
  97. size_t inbytesleft;
  98. char *outptr;
  99. size_t outbytesleft;
  100. size_t res;
  101. inptr = inbuf;
  102. inbytesleft = count;
  103. outptr = outbuf;
  104. outbytesleft = sizeof (outbuf);
  105. /* Convert the character from UTF-8 to the locale's charset. */
  106. res = iconv (utf8_to_local,
  107. (ICONV_CONST char **)&inptr, &inbytesleft,
  108. &outptr, &outbytesleft);
  109. /* Analyze what iconv() actually did and distinguish replacements
  110. that are OK (no need to invoke the FAILURE callback), such as
  111. - replacing GREEK SMALL LETTER MU with MICRO SIGN, or
  112. - replacing FULLWIDTH COLON with ':', or
  113. - replacing a Unicode TAG character (U+E00xx) with an empty string,
  114. from replacements that are worse than the FAILURE callback, such as
  115. - replacing 'ç' with '?' (NetBSD, Solaris 11) or '*' (musl) or
  116. NUL (IRIX). */
  117. if (inbytesleft > 0 || res == (size_t)(-1)
  118. /* Irix iconv() inserts a NUL byte if it cannot convert. */
  119. # if !defined _LIBICONV_VERSION && (defined sgi || defined __sgi)
  120. || (res > 0 && code != 0 && outptr - outbuf == 1 && *outbuf == '\0')
  121. # endif
  122. /* NetBSD iconv() and Solaris 11 iconv() insert a '?' if they cannot
  123. convert. */
  124. # if !defined _LIBICONV_VERSION && (defined __NetBSD__ || defined __sun)
  125. || (res > 0 && outptr - outbuf == 1 && *outbuf == '?')
  126. # endif
  127. /* musl libc iconv() inserts a '*' if it cannot convert. */
  128. # if !defined _LIBICONV_VERSION && MUSL_LIBC
  129. || (res > 0 && outptr - outbuf == 1 && *outbuf == '*')
  130. # endif
  131. )
  132. return failure (code, NULL, callback_arg);
  133. /* Avoid glibc-2.1 bug and Solaris 7 bug. */
  134. # if defined _LIBICONV_VERSION \
  135. || !(((__GLIBC__ - 0 == 2 && __GLIBC_MINOR__ - 0 <= 1) \
  136. && !defined __UCLIBC__) \
  137. || defined __sun)
  138. /* Get back to the initial shift state. */
  139. res = iconv (utf8_to_local, NULL, NULL, &outptr, &outbytesleft);
  140. if (res == (size_t)(-1))
  141. return failure (code, NULL, callback_arg);
  142. # endif
  143. return success (outbuf, outptr - outbuf, callback_arg);
  144. }
  145. #endif
  146. /* At this point, is_utf8 is true, so no conversion is needed. */
  147. return success (inbuf, count, callback_arg);
  148. }
  149. /* Simple success callback that outputs the converted string.
  150. The STREAM is passed as callback_arg. */
  151. long
  152. fwrite_success_callback (const char *buf, size_t buflen, void *callback_arg)
  153. {
  154. FILE *stream = (FILE *) callback_arg;
  155. /* The return value of fwrite can be ignored here, because under normal
  156. conditions (STREAM is an open stream and not wide-character oriented)
  157. when fwrite() returns a value != buflen it also sets STREAM's error
  158. indicator. */
  159. fwrite (buf, 1, buflen, stream);
  160. return 0;
  161. }
  162. /* Simple failure callback that displays an error and exits. */
  163. static long
  164. exit_failure_callback (unsigned int code, const char *msg,
  165. void *callback_arg _GL_UNUSED)
  166. {
  167. if (msg == NULL)
  168. error (1, 0, _("cannot convert U+%04X to local character set"), code);
  169. else
  170. error (1, 0, _("cannot convert U+%04X to local character set: %s"), code,
  171. gettext (msg));
  172. return -1;
  173. }
  174. /* Simple failure callback that displays a fallback representation in plain
  175. ASCII, using the same notation as ISO C99 strings. */
  176. static long
  177. fallback_failure_callback (unsigned int code,
  178. const char *msg _GL_UNUSED,
  179. void *callback_arg)
  180. {
  181. FILE *stream = (FILE *) callback_arg;
  182. if (code < 0x10000)
  183. fprintf (stream, "\\u%04X", code);
  184. else
  185. fprintf (stream, "\\U%08X", code);
  186. return -1;
  187. }
  188. /* Outputs the Unicode character CODE to the output stream STREAM.
  189. Upon failure, exit if exit_on_error is true, otherwise output a fallback
  190. notation. */
  191. void
  192. print_unicode_char (FILE *stream, unsigned int code, int exit_on_error)
  193. {
  194. unicode_to_mb (code, fwrite_success_callback,
  195. exit_on_error
  196. ? exit_failure_callback
  197. : fallback_failure_callback,
  198. stream);
  199. }