]> git.sesse.net Git - vlc/blob - src/text/unicode.c
IsUTF8: redumdant check for nul
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33
34 #include <assert.h>
35
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <sys/types.h>
40 #ifdef UNDER_CE
41 #  include <tchar.h>
42 #endif
43 #include <errno.h>
44
45 #if defined (__APPLE__) || defined (HAVE_MAEMO)
46 /* Define this if the OS always use UTF-8 internally */
47 # define ASSUME_UTF8 1
48 #endif
49
50 #if defined (ASSUME_UTF8)
51 /* Cool */
52 #elif defined (WIN32) || defined (UNDER_CE)
53 # define USE_MB2MB 1
54 #elif defined (HAVE_ICONV)
55 # define USE_ICONV 1
56 #else
57 # error No UTF8 charset conversion implemented on this platform!
58 #endif
59
60 #if defined (USE_ICONV)
61 # include <langinfo.h>
62 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
63
64 static void find_charset_once (void)
65 {
66     strlcpy (charset, nl_langinfo (CODESET), sizeof (charset));
67     if (!strcasecmp (charset, "ASCII")
68      || !strcasecmp (charset, "ANSI_X3.4-1968"))
69         strcpy (charset, "UTF-8"); /* superset... */
70 }
71
72 static int find_charset (void)
73 {
74     static pthread_once_t once = PTHREAD_ONCE_INIT;
75     pthread_once (&once, find_charset_once);
76     return !strcasecmp (charset, "UTF-8");
77 }
78 #endif
79
80
81 static char *locale_fast (const char *string, bool from)
82 {
83     if( string == NULL )
84         return NULL;
85
86 #if defined (USE_ICONV)
87     if (find_charset ())
88         return (char *)string;
89
90     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
91                                      from ? charset : "UTF-8");
92     if (hd == (vlc_iconv_t)(-1))
93         return NULL; /* Uho! */
94
95     const char *iptr = string;
96     size_t inb = strlen (string);
97     size_t outb = inb * 6 + 1;
98     char output[outb], *optr = output;
99
100     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
101     {
102         *optr++ = '?';
103         outb--;
104         iptr++;
105         inb--;
106         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
107     }
108     *optr = '\0';
109     vlc_iconv_close (hd);
110
111     assert (inb == 0);
112     assert (*iptr == '\0');
113     assert (*optr == '\0');
114     assert (strlen (output) == (size_t)(optr - output));
115     return strdup (output);
116 #elif defined (USE_MB2MB)
117     char *out;
118     int len;
119
120     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
121                                    0, string, -1, NULL, 0);
122     wchar_t *wide = malloc (len * sizeof (wchar_t));
123     if (wide == NULL)
124         return NULL;
125
126     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
127     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
128                                    NULL, 0, NULL, NULL);
129     out = malloc (len);
130     if (out != NULL)
131         WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
132                              NULL, NULL);
133     free (wide);
134     return out;
135 #else
136     (void)from;
137     return (char *)string;
138 #endif
139 }
140
141
142 static inline char *locale_dup (const char *string, bool from)
143 {
144     assert( string );
145
146 #if defined (USE_ICONV)
147     if (find_charset ())
148         return strdup (string);
149     return locale_fast (string, from);
150 #elif defined (USE_MB2MB)
151     return locale_fast (string, from);
152 #else
153     (void)from;
154     return strdup (string);
155 #endif
156 }
157
158 /**
159  * Releases (if needed) a localized or uniformized string.
160  * @param str non-NULL return value from FromLocale() or ToLocale().
161  */
162 void LocaleFree (const char *str)
163 {
164 #if defined (USE_ICONV)
165     if (!find_charset ())
166         free ((char *)str);
167 #elif defined (USE_MB2MB)
168     free ((char *)str);
169 #else
170     (void)str;
171 #endif
172 }
173
174
175 /**
176  * Converts a string from the system locale character encoding to UTF-8.
177  *
178  * @param locale nul-terminated string to convert
179  *
180  * @return a nul-terminated UTF-8 string, or NULL in case of error.
181  * To avoid memory leak, you have to pass the result to LocaleFree()
182  * when it is no longer needed.
183  */
184 char *FromLocale (const char *locale)
185 {
186     return locale_fast (locale, true);
187 }
188
189 /**
190  * converts a string from the system locale character encoding to utf-8,
191  * the result is always allocated on the heap.
192  *
193  * @param locale nul-terminated string to convert
194  *
195  * @return a nul-terminated utf-8 string, or null in case of error.
196  * The result must be freed using free() - as with the strdup() function.
197  */
198 char *FromLocaleDup (const char *locale)
199 {
200     return locale_dup (locale, true);
201 }
202
203
204 /**
205  * ToLocale: converts an UTF-8 string to local system encoding.
206  *
207  * @param utf8 nul-terminated string to be converted
208  *
209  * @return a nul-terminated string, or NULL in case of error.
210  * To avoid memory leak, you have to pass the result to LocaleFree()
211  * when it is no longer needed.
212  */
213 char *ToLocale (const char *utf8)
214 {
215     return locale_fast (utf8, false);
216 }
217
218
219 /**
220  * converts a string from UTF-8 to the system locale character encoding,
221  * the result is always allocated on the heap.
222  *
223  * @param utf8 nul-terminated string to convert
224  *
225  * @return a nul-terminated string, or null in case of error.
226  * The result must be freed using free() - as with the strdup() function.
227  */
228 char *ToLocaleDup (const char *utf8)
229 {
230     return locale_dup (utf8, false);
231 }
232
233 /**
234  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
235  * appropriate conversion to local encoding.
236  */
237 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
238 {
239     char *utf8;
240     int res = vasprintf( &utf8, fmt, ap );
241     if( res == -1 )
242         return -1;
243
244     *str = ToLocaleDup( utf8 );
245     free( utf8 );
246     return res;
247 }
248
249 /**
250  * Formats an UTF-8 string as vfprintf(), then print it, with
251  * appropriate conversion to local encoding.
252  */
253 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
254 {
255     char *str;
256     int res = utf8_vasprintf( &str, fmt, ap );
257     if( res == -1 )
258         return -1;
259
260     fputs( str, stream );
261     free( str );
262     return res;
263 }
264
265 /**
266  * Formats an UTF-8 string as fprintf(), then print it, with
267  * appropriate conversion to local encoding.
268  */
269 int utf8_fprintf( FILE *stream, const char *fmt, ... )
270 {
271     va_list ap;
272     int res;
273
274     va_start( ap, fmt );
275     res = utf8_vfprintf( stream, fmt, ap );
276     va_end( ap );
277     return res;
278 }
279
280
281 static char *CheckUTF8( char *str, char rep )
282 {
283     uint8_t *ptr = (uint8_t *)str;
284     assert (str != NULL);
285
286     for (;;)
287     {
288         uint8_t c = ptr[0];
289         int charlen = -1;
290
291         if (c == '\0')
292             break;
293
294         for (int i = 0; i < 7; i++)
295             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
296             {
297                 charlen = i;
298                 break;
299             }
300
301         switch (charlen)
302         {
303             case 0: // 7-bit ASCII character -> OK
304                 ptr++;
305                 continue;
306
307             case -1: // 1111111x -> error
308             case 1: // continuation byte -> error
309                 goto error;
310         }
311
312         assert (charlen >= 2);
313
314         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
315         for (int i = 1; i < charlen; i++)
316         {
317             assert (cp < (1 << 26));
318             c = ptr[i];
319
320             if ((c >> 6) != 2) // not a continuation byte
321                 goto error;
322
323             cp = (cp << 6) | (ptr[i] & 0x3f);
324         }
325
326         if (cp < 128) // overlong (special case for ASCII)
327             goto error;
328         if (cp < (1u << (5 * charlen - 3))) // overlong
329             goto error;
330
331         ptr += charlen;
332         continue;
333
334     error:
335         if (rep == 0)
336             return NULL;
337         *ptr++ = rep;
338         str = NULL;
339     }
340
341     return str;
342 }
343
344 /**
345  * Replaces invalid/overlong UTF-8 sequences with question marks.
346  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
347  * so we don't try that, even though it would be less disruptive.
348  *
349  * @return str if it was valid UTF-8, NULL if not.
350  */
351 char *EnsureUTF8( char *str )
352 {
353     return CheckUTF8( str, '?' );
354 }
355
356
357 /**
358  * Checks whether a string is a valid UTF-8 byte sequence.
359  *
360  * @param str nul-terminated string to be checked
361  *
362  * @return str if it was valid UTF-8, NULL if not.
363  */
364 const char *IsUTF8( const char *str )
365 {
366     return CheckUTF8( (char *)str, 0 );
367 }
368
369 /**
370  * Converts a string from the given character encoding to utf-8.
371  *
372  * @return a nul-terminated utf-8 string, or null in case of error.
373  * The result must be freed using free().
374  */
375 char *FromCharset(const char *charset, const void *data, size_t data_size)
376 {
377     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
378     if (handle == (vlc_iconv_t)(-1))
379         return NULL;
380
381     char *out = NULL;
382     for(unsigned mul = 4; mul < 8; mul++ )
383     {
384         size_t in_size = data_size;
385         const char *in = data;
386         size_t out_max = mul * data_size;
387         char *tmp = out = malloc (1 + out_max);
388         if (!out)
389             break;
390
391         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
392             *tmp = '\0';
393             break;
394         }
395         free(out);
396         out = NULL;
397
398         if (errno != E2BIG)
399             break;
400     }
401     vlc_iconv_close(handle);
402     return out;
403 }
404