]> git.sesse.net Git - vlc/blob - src/misc/unicode.c
- UF8 wrappers for stat, lstat
[vlc] / src / misc / unicode.c
1 /*****************************************************************************
2  * unicode.c: UTF8 <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * $Id$
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 #include <vlc/vlc.h>
28 #include "charset.h"
29
30 #ifdef HAVE_ASSERT
31 # include <assert.h>
32 #else
33 # define assert( c ) ((void)0)
34 #endif
35
36 #include <stdio.h>
37 #include <errno.h>
38 #include <sys/types.h>
39 #include <dirent.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
42 #endif
43 #ifndef HAVE_LSTAT
44 # define lstat( a, b ) stat(a, b)
45 #endif
46
47 #ifdef __APPLE__
48 /* Define this if the OS always use UTF-8 internally */
49 # define ASSUME_UTF8 1
50 #endif
51
52 #if !(defined (WIN32) && defined (ASSUME_UTF8))
53 # define USE_ICONV 1
54 #endif
55
56 #if defined (USE_ICONV) && !defined (HAVE_ICONV)
57 # error No UTF8 charset conversion implemented on this platform!
58 #endif
59
60
61
62 #ifdef USE_ICONV
63 static struct {
64     vlc_iconv_t hd;
65     vlc_mutex_t lock;
66 } from_locale, to_locale;
67 #endif
68
69 void LocaleInit( vlc_object_t *p_this )
70 {
71 #ifdef USE_ICONV
72     char *psz_charset;
73
74     if( vlc_current_charset( &psz_charset ) )
75         /* UTF-8 */
76         from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
77     else
78     {
79         /* not UTF-8 */
80         char *psz_conv = psz_charset;
81
82         /*
83          * Still allow non-ASCII characters when the locale is not set.
84          * Western Europeans are being favored for historical reasons.
85          */
86         psz_conv = strcmp( psz_charset, "ASCII" )
87                 ? psz_charset : "ISO-8859-1";
88
89         vlc_mutex_init( p_this, &from_locale.lock );
90         vlc_mutex_init( p_this, &to_locale.lock );
91         from_locale.hd = vlc_iconv_open( "UTF-8", psz_charset );
92         to_locale.hd = vlc_iconv_open( psz_charset, "UTF-8" );
93     }
94
95     free( psz_charset );
96
97     assert( (from_locale.hd == (vlc_iconv_t)(-1))
98             == (to_locale.hd == (vlc_iconv_t)(-1)) );
99 #else
100     (void)p_this;
101 #endif
102 }
103
104 void LocaleDeinit( void )
105 {
106 #ifdef USE_ICONV
107     if( to_locale.hd != (vlc_iconv_t)(-1) )
108     {
109         vlc_iconv_close( to_locale.hd );
110         vlc_mutex_destroy( &to_locale.lock );
111     }
112
113     if( from_locale.hd != (vlc_iconv_t)(-1) )
114     {
115         vlc_iconv_close( from_locale.hd );
116         vlc_mutex_destroy( &from_locale.lock );
117     }
118 #endif
119 }
120
121 #ifdef WIN32
122 static char *MB2MB( const char *string, UINT fromCP, UINT toCP )
123 {
124     char *out;
125     int ilen = strlen( string ), olen = (4 / sizeof (wchar_t)) * ilen + 1;
126     wchar_t wide[olen];
127
128     ilen = MultiByteToWideChar( fromCP, 0, string, ilen + 1, wide, olen );
129     if( ilen == 0 )
130         return NULL;
131
132     olen = 4 * ilen + 1;
133     out = malloc( olen );
134
135     olen = WideCharToMultiByte( toCP, 0, wide, ilen, out, olen, NULL, NULL );
136     if( olen == 0 )
137     {
138         free( out );
139         return NULL;
140     }
141     return realloc( out, olen );
142 }
143 #endif
144
145 /*****************************************************************************
146  * FromLocale: converts a locale string to UTF-8
147  *****************************************************************************/
148 char *FromLocale( const char *locale )
149 {
150     if( locale == NULL )
151         return NULL;
152
153 #ifndef WIN32
154 # ifdef USE_ICONV
155     if( from_locale.hd != (vlc_iconv_t)(-1) )
156     {
157         char *iptr = (char *)locale, *output, *optr;
158         size_t inb, outb;
159
160         /*
161          * We are not allowed to modify the locale pointer, even if we cast it
162          * to non-const.
163          */
164         inb = strlen( locale );
165         /* FIXME: I'm not sure about the value for the multiplication
166          * (for western people, multiplication by 3 (Latin9) is needed).
167          * While UTF-8 could reach 6 bytes, no existing code point exceeds
168          * 4 bytes. */
169         outb = inb * 4 + 1;
170
171         optr = output = malloc( outb );
172
173         vlc_mutex_lock( &from_locale.lock );
174         vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
175
176         while( vlc_iconv( from_locale.hd, &iptr, &inb, &optr, &outb )
177                == (size_t)-1 )
178         {
179             *optr++ = '?';
180             outb--;
181             iptr++;
182             inb--;
183             vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
184         }
185         vlc_mutex_unlock( &from_locale.lock );
186
187         assert (inb == 0);
188         assert (*iptr == '\0');
189         assert (*optr == '\0');
190         assert (strlen( output ) == (size_t)(optr - output));
191         return realloc( output, optr - output + 1 );
192     }
193 # endif /* USE_ICONV */
194     return (char *)locale;
195 #else /* WIN32 */
196     return MB2MB( locale, CP_ACP, CP_UTF8 );
197 #endif
198 }
199
200 char *FromLocaleDup( const char *locale )
201 {
202 #if defined (ASSUME_UTF8)
203         return strdup( locale );
204 #else
205 # ifdef USE_ICONV
206         if (from_locale.hd == (vlc_iconv_t)(-1))
207                 return strdup( locale );
208 # endif
209         return FromLocale( locale );
210 #endif
211 }
212
213
214 /*****************************************************************************
215  * ToLocale: converts an UTF-8 string to locale
216  *****************************************************************************/
217 char *ToLocale( const char *utf8 )
218 {
219     if( utf8 == NULL )
220         return NULL;
221
222 #ifndef WIN32
223 # ifdef USE_ICONV
224     if( to_locale.hd != (vlc_iconv_t)(-1) )
225     {
226         char *iptr = (char *)utf8, *output, *optr;
227         size_t inb, outb;
228
229         /*
230         * We are not allowed to modify the locale pointer, even if we cast it
231         * to non-const.
232         */
233         inb = strlen( utf8 );
234         /* FIXME: I'm not sure about the value for the multiplication
235         * (for western people, multiplication is not needed) */
236         outb = inb * 2 + 1;
237
238         optr = output = malloc( outb );
239         vlc_mutex_lock( &to_locale.lock );
240         vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
241
242         while( vlc_iconv( to_locale.hd, &iptr, &inb, &optr, &outb )
243                == (size_t)-1 )
244         {
245             *optr++ = '?'; /* should not happen, and yes, it sucks */
246             outb--;
247             iptr++;
248             inb--;
249             vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
250         }
251         vlc_mutex_unlock( &to_locale.lock );
252
253         assert (inb == 0);
254         assert (*iptr == '\0');
255         assert (*optr == '\0');
256         assert (strlen( output ) == (size_t)(optr - output));
257         return realloc( output, optr - output + 1 );
258     }
259 # endif /* USE_ICONV */
260     return (char *)utf8;
261 #else /* WIN32 */
262     return MB2MB( utf8, CP_UTF8, CP_ACP );
263 #endif
264 }
265
266 void LocaleFree( const char *str )
267 {
268 #ifdef USE_ICONV
269     if( to_locale.hd == (vlc_iconv_t)(-1) )
270         return;
271 #endif
272
273 #ifndef ASSUME_UTF8
274     if( str != NULL )
275         free( (char *)str );
276 #endif
277 }
278
279 /*****************************************************************************
280  * utf8_fopen: Calls fopen() after conversion of file name to OS locale
281  *****************************************************************************/
282 FILE *utf8_fopen( const char *filename, const char *mode )
283 {
284 #if !defined WIN32 /*|| !defined UNICODE*/
285     const char *local_name = ToLocale( filename );
286
287     if( local_name != NULL )
288     {
289         FILE *stream = fopen( local_name, mode );
290         LocaleFree( local_name );
291         return stream;
292     }
293     else
294         errno = ENOENT;
295     return NULL;
296 #else
297     wchar_t wpath[MAX_PATH];
298     wchar_t wmode[4];
299
300     if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH - 1)
301      || !MultiByteToWideChar( CP_ACP, 0, mode, -1, wmode, 3 ) )
302     {
303         errno = ENOENT;
304         return NULL;
305     }
306
307     return _wfopen( wpath, wmode );
308 #endif
309 }
310
311 void *utf8_opendir( const char *dirname )
312 {
313     const char *local_name = ToLocale( dirname );
314
315     if( local_name != NULL )
316     {
317         DIR *dir = opendir( local_name );
318         LocaleFree( local_name );
319         return dir;
320     }
321     else
322         errno = ENOENT;
323     return NULL;
324 }
325
326 const char *utf8_readdir( void *dir )
327 {
328     struct dirent *ent;
329
330     ent = readdir( (DIR *)dir );
331     if( ent == NULL )
332         return NULL;
333
334     return FromLocale( ent->d_name );
335 }
336
337
338 static int utf8_statEx( const char *filename, void *buf,
339                         vlc_bool_t deref )
340 {
341 #ifdef HAVE_SYS_STAT_H
342     const char *local_name = ToLocale( filename );
343
344     if( local_name != NULL )
345     {
346         int res = deref ? stat( local_name, (struct stat *)buf )
347                        : lstat( local_name, (struct stat *)buf );
348         LocaleFree( local_name );
349         return res;
350     }
351     errno = ENOENT;
352 #endif
353     return -1;
354 }
355
356
357 int utf8_stat( const char *filename, void *buf)
358 {
359     return utf8_statEx( filename, buf, VLC_TRUE );
360 }
361
362 int utf8_lstat( const char *filename, void *buf)
363 {
364     return utf8_statEx( filename, buf, VLC_FALSE );
365 }
366
367 /*****************************************************************************
368  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
369  *****************************************************************************
370  * Not Todo : convert Latin1 to UTF-8 on the flu
371  * It is not possible given UTF-8 needs more space
372  *****************************************************************************/
373 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF)) 
374 char *EnsureUTF8( char *str )
375 {
376     unsigned char *ptr, c;
377
378     ptr = (unsigned char *)str;
379     while( (c = *ptr) != '\0' )
380     {
381         /* US-ASCII, 1 byte */
382         if( ( ( c >= 0x20 ) && ( c <= 0x7F ) )
383          || ( c == 0x09 ) || ( c == 0x0A ) || ( c == 0x0D ) )
384         {
385             ptr++; /* OK */
386         }
387         else
388         /* 2 bytes */
389         if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
390         {
391             c = ptr[1];
392             if( isutf8cont( c ) )
393                 ptr += 2; /* OK */
394             else
395                 *ptr++ = '?'; /* invalid */
396         }
397         else
398         /* 3 bytes */
399         if( c == 0xE0 )
400         {
401             c = ptr[1];
402             if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
403             {
404                 c = ptr[2];
405                 if( isutf8cont( c ) )
406                     ptr += 3; /* OK */
407                 else
408                     *ptr++ = '?';
409             }
410             else
411                 *ptr++ = '?';
412         }
413         else
414         if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
415          || ( c == 0xEE ) || ( c == 0xEF ) )
416         {
417             c = ptr[1];
418             if( isutf8cont( c ) )
419             {
420                 c = ptr[2];
421                 if( isutf8cont( c ) )
422                     ptr += 3; /* OK */
423                 else
424                     *ptr++ = '?';
425             }
426             else
427                 *ptr++ = '?';
428         }
429         else
430         if( c == 0xED )
431         {
432             c = ptr[1];
433             if( ( c >= 0x80 ) && ( c <= 0x9F ) )
434             {
435                 c = ptr[2];
436                 if( isutf8cont( c ) )
437                     ptr += 3; /* OK */
438                 else
439                     *ptr++ = '?';
440             }
441             else
442                 *ptr++ = '?';
443         }
444         else
445         /* 4 bytes */
446         if( c == 0xF0 )
447         {
448             c = ptr[1];
449             if( ( c >= 0x90 ) && ( c <= 0xBF ) )
450             {
451                 c = ptr[2];
452                 if( isutf8cont( c ) )
453                 {
454                     c = ptr[3];
455                     if( isutf8cont( c ) )
456                         ptr += 4; /* OK */
457                     else
458                         *ptr++ = '?';
459                 }
460                 else
461                     *ptr++ = '?';
462             }
463             else
464                 *ptr++ = '?';
465         }
466         else
467         if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
468         {
469             c = ptr[1];
470             if( isutf8cont( c ) )
471             {
472                 c = ptr[2];
473                 if( isutf8cont( c ) )
474                 {
475                     c = ptr[3];
476                     if( isutf8cont( c ) )
477                         ptr += 4; /* OK */
478                     else
479                         *ptr++ = '?';
480                 }
481                 else
482                     *ptr++ = '?';
483             }
484             else
485                 *ptr++ = '?';
486         }
487         else
488         if( c == 0xF4 )
489         {
490             c = ptr[1];
491             if( ( c >= 0x80 ) && ( c <= 0x8F ) )
492             {
493                 c = ptr[2];
494                 if( isutf8cont( c ) )
495                 {
496                     c = ptr[3];
497                     if( isutf8cont( c ) )
498                         ptr += 4; /* OK */
499                     else
500                         *ptr++ = '?';
501                 }
502                 else
503                     *ptr++ = '?';
504             }
505             else
506                 *ptr++ = '?';
507         }
508         else
509             *ptr++ = '?';
510     }
511
512     return str;
513 }
514
515 /**********************************************************************
516  * UTF32toUTF8: converts an array from UTF-32 to UTF-8
517  *********************************************************************/
518 char *UTF32toUTF8( const wchar_t *src, size_t len, size_t *newlen )
519 {
520     char *res, *out;
521
522     /* allocate memory */
523     out = res = (char *)malloc( 6 * len );
524     if( res == NULL )
525         return NULL;
526
527     while( len > 0 )
528     {
529         uint32_t uv = *src++;
530         len--;
531
532         if( uv < 0x80 )
533         {
534             *out++ = uv;
535             continue;
536         }
537         else
538         if( uv < 0x800 )
539         {
540             *out++ = (( uv >>  6)         | 0xc0);
541             *out++ = (( uv        & 0x3f) | 0x80);
542             continue;
543         }
544         else
545         if( uv < 0x10000 )
546         {
547             *out++ = (( uv >> 12)         | 0xe0);
548             *out++ = (((uv >>  6) & 0x3f) | 0x80);
549             *out++ = (( uv        & 0x3f) | 0x80);
550             continue;
551         }
552         else
553         {
554             *out++ = (( uv >> 18)         | 0xf0);
555             *out++ = (((uv >> 12) & 0x3f) | 0x80);
556             *out++ = (((uv >>  6) & 0x3f) | 0x80);
557             *out++ = (( uv        & 0x3f) | 0x80);
558             continue;
559         }
560     }
561     len = out - res;
562     res = realloc( res, len );
563     if( newlen != NULL )
564         *newlen = len;
565     return res;
566 }
567
568 /**********************************************************************
569  * FromUTF32: converts an UTF-32 string to UTF-8
570  **********************************************************************
571  * The result must be free()'d. NULL on error.
572  *********************************************************************/
573 char *FromUTF32( const wchar_t *src )
574 {
575     size_t len;
576     const wchar_t *in;
577
578     /* determine the size of the string */
579     for( len = 1, in = src; GetWBE( in ); len++ )
580         in++;
581
582     return UTF32toUTF8( src, len, NULL );
583 }