]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Fix MB2MB and use it
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2006 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Rémi Denis-Courmont <rem # videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc_charset.h>
30
31 #include <assert.h>
32
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <sys/types.h>
38 #ifdef HAVE_DIRENT_H
39 #  include <dirent.h>
40 #endif
41 #ifdef UNDER_CE
42 #  include <tchar.h>
43 #endif
44 #ifdef HAVE_SYS_STAT_H
45 # include <sys/stat.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 # include <fcntl.h>
49 #endif
50 #ifdef WIN32
51 # include <io.h>
52 #else
53 # include <unistd.h>
54 #endif
55
56 #ifndef HAVE_LSTAT
57 # define lstat( a, b ) stat(a, b)
58 #endif
59
60 #ifdef __APPLE__
61 /* Define this if the OS always use UTF-8 internally */
62 # define ASSUME_UTF8 1
63 #endif
64
65 #if defined (ASSUME_UTF8)
66 /* Cool */
67 #elif defined (WIN32) || defined (UNDER_CE)
68 # define USE_MB2MB 1
69 #elif defined (HAVE_ICONV)
70 # define USE_ICONV 1
71 #else
72 # error No UTF8 charset conversion implemented on this platform!
73 #endif
74
75 typedef struct locale_data_t
76 {
77 #if defined (USE_ICONV)
78     vlc_iconv_t hd;
79     vlc_mutex_t lock;
80 #elif defined (USE_MB2MB)
81     UINT fromCP;
82     UINT toCP;
83 #endif
84 } locale_data_t;
85
86 static locale_data_t from_locale, to_locale;
87
88
89 void LocaleInit( vlc_object_t *p_this )
90 {
91 #if defined USE_ICONV
92     char *psz_charset;
93
94     if( vlc_current_charset( &psz_charset ) )
95         /* UTF-8 */
96         from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
97     else
98     {
99         /* not UTF-8 */
100         char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
101         const char *psz_conv;
102
103         /*
104          * Still allow non-ASCII characters when the locale is not set.
105          * Western Europeans are being favored for historical reasons.
106          */
107         if( strcmp( psz_charset, "ASCII" ) )
108         {
109             sprintf( psz_buf, "%s//translit", psz_charset );
110             psz_conv = psz_buf;
111         }
112         else
113             psz_conv = "ISO-8859-1//translit";
114
115         vlc_mutex_init( p_this, &from_locale.lock );
116         vlc_mutex_init( p_this, &to_locale.lock );
117         from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
118         to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
119     }
120
121     free( psz_charset );
122
123     assert( (from_locale.hd == (vlc_iconv_t)(-1))
124             == (to_locale.hd == (vlc_iconv_t)(-1)) );
125
126 #elif defined (USE_MB2MB)
127     to_locale.toCP = from_locale.fromCP = CP_ACP;
128     from_locale.toCP = to_locale.fromCP = CP_UTF8;
129 #else
130     (void)p_this;
131 #endif
132 }
133
134 void LocaleDeinit( void )
135 {
136 #ifdef USE_ICONV
137     if( to_locale.hd != (vlc_iconv_t)(-1) )
138     {
139         vlc_iconv_close( to_locale.hd );
140         vlc_mutex_destroy( &to_locale.lock );
141     }
142
143     if( from_locale.hd != (vlc_iconv_t)(-1) )
144     {
145         vlc_iconv_close( from_locale.hd );
146         vlc_mutex_destroy( &from_locale.lock );
147     }
148 #endif
149 }
150
151 static char *locale_fast (const char *string, locale_data_t *p)
152 {
153 #if defined (USE_ICONV)
154     vlc_iconv_t hd = p->hd;
155
156     if (hd == (vlc_iconv_t)(-1))
157         return (char *)string;
158
159     const char *iptr = string;
160     size_t inb = strlen (string);
161     size_t outb = inb * 6 + 1;
162     char output[outb], *optr = output;
163
164     if (string == NULL)
165         return NULL;
166
167     vlc_mutex_lock (&p->lock);
168     vlc_iconv (hd, NULL, NULL, NULL, NULL);
169
170     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
171     {
172         *optr++ = '?';
173         outb--;
174         iptr++;
175         inb--;
176         vlc_iconv (hd, NULL, NULL, NULL, NULL);
177     }
178     vlc_mutex_unlock (&p->lock);
179     *optr = '\0';
180
181     assert (inb == 0);
182     assert (*iptr == '\0');
183     assert (*optr == '\0');
184     assert (strlen (output) == (size_t)(optr - output));
185     return strdup (output);
186 #elif defined (USE_MB2MB)
187     char *out;
188     wchar_t *wide;
189     int len;
190
191     if (string == NULL)
192         return NULL;
193
194     len = 1 + MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
195     wchar_t wide[len];
196
197     MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
198     len = 1 + WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
199     out = malloc (len);
200     if (out == NULL)
201         return NULL;
202
203     WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
204     return out;
205 #else
206     return (char *)string;
207 #endif
208 }
209
210
211 static inline char *locale_dup (const char *string, locale_data_t *p)
212 {
213 #if defined (USE_ICONV)
214     return (p->hd == (vlc_iconv_t)(-1))
215             ? strdup (string)
216             : locale_fast (string, p);
217 #elif defined (USE_MB2MB)
218     return locale_fast (string, p);
219 #else
220     return strdup (string);
221 #endif
222 }
223
224
225 void LocaleFree (const char *str)
226 {
227 #if defined (USE_ICONV)
228     assert ((to_locale.hd == (vlc_iconv_t)(-1))
229          == (from_locale.hd == (vlc_iconv_t)(-1)));
230
231     if( to_locale.hd != (vlc_iconv_t)(-1) )
232         free ((char *)str);
233 #elif defined (USE_MB2MB)
234     free ((char *)str);
235 #endif
236 }
237
238
239 /**
240  * FromLocale: converts a locale string to UTF-8
241  *
242  * @param locale nul-terminated string to be converted
243  *
244  * @return a nul-terminated UTF-8 string, or NULL in case of error.
245  * To avoid memory leak, you have to pass the result to LocaleFree()
246  * when it is no longer needed.
247  */
248 char *FromLocale (const char *locale)
249 {
250     return locale_fast (locale, &from_locale);
251 }
252
253 char *FromLocaleDup (const char *locale)
254 {
255     return locale_dup (locale, &from_locale);
256 }
257
258
259 /**
260  * ToLocale: converts a UTF-8 string to local system encoding.
261  *
262  * @param utf8 nul-terminated string to be converted
263  *
264  * @return a nul-terminated string, or NULL in case of error.
265  * To avoid memory leak, you have to pass the result to LocaleFree()
266  * when it is no longer needed.
267  */
268 char *ToLocale (const char *utf8)
269 {
270     return locale_fast (utf8, &to_locale);
271 }
272
273
274 static char *ToLocaleDup (const char *utf8)
275 {
276     return locale_dup (utf8, &to_locale);
277 }
278
279
280 /**
281  * utf8_open: open() wrapper for UTF-8 filenames
282  */
283 int utf8_open (const char *filename, int flags, mode_t mode)
284 {
285 #if defined (WIN32) || defined (UNDER_CE)
286     if (GetVersion() < 0x80000000)
287     {
288         /* for Windows NT and above */
289         wchar_t wpath[MAX_PATH + 1];
290
291         if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
292         {
293             errno = ENOENT;
294             return -1;
295         }
296         wpath[MAX_PATH] = L'\0';
297
298         /*
299          * open() cannot open files with non-“ANSI” characters on Windows.
300          * We use _wopen() instead. Same thing for mkdir() and stat().
301          */
302         return _wopen (wpath, flags, mode);
303     }
304 #endif
305     const char *local_name = ToLocale (filename);
306
307     if (local_name == NULL)
308     {
309         errno = ENOENT;
310         return -1;
311     }
312
313     int fd = open (local_name, flags, mode);
314     LocaleFree (local_name);
315     return fd;
316 }
317
318 /**
319  * utf8_fopen: fopen() wrapper for UTF-8 filenames
320  */
321 FILE *utf8_fopen (const char *filename, const char *mode)
322 {
323     int rwflags = 0, oflags = 0;
324     vlc_bool_t append = VLC_FALSE;
325
326     for (const char *ptr = mode; *ptr; ptr++)
327     {
328         switch (*ptr)
329         {
330             case 'r':
331                 rwflags = O_RDONLY;
332                 break;
333
334             case 'a':
335                 rwflags = O_WRONLY;
336                 oflags |= O_CREAT;
337                 append = VLC_TRUE;
338                 break;
339
340             case 'w':
341                 rwflags = O_WRONLY;
342                 oflags |= O_CREAT | O_TRUNC;
343                 break;
344
345             case '+':
346                 rwflags = O_RDWR;
347                 break;
348
349 #ifdef O_TEXT
350             case 't':
351                 oflags |= O_TEXT;
352                 break;
353 #endif
354         }
355     }
356
357     int fd = utf8_open (filename, rwflags | oflags, 0666);
358     if (fd == -1)
359         return NULL;
360
361     if (append && (lseek (fd, 0, SEEK_END) == -1))
362     {
363         close (fd);
364         return NULL;
365     }
366
367     FILE *stream = fdopen (fd, mode);
368     if (stream == NULL)
369         close (fd);
370
371     return stream;
372 }
373
374 /**
375  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
376  *
377  * @param dirname a UTF-8 string with the name of the directory that you
378  *        want to create.
379  * @return A 0 return value indicates success. A -1 return value indicates an
380  *        error, and an error code is stored in errno
381  */
382 int utf8_mkdir( const char *dirname )
383 {
384 #if defined (UNDER_CE) || defined (WIN32)
385     wchar_t wname[MAX_PATH + 1];
386     char mod[MAX_PATH + 1];
387     int i;
388
389     /* Convert '/' into '\' */
390     for( i = 0; *dirname; i++ )
391     {
392         if( i == MAX_PATH )
393             return -1; /* overflow */
394
395         if( *dirname == '/' )
396             mod[i] = '\\';
397         else
398             mod[i] = *dirname;
399         dirname++;
400
401     }
402     mod[i] = 0;
403
404     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
405     {
406         errno = ENOENT;
407         return -1;
408     }
409     wname[MAX_PATH] = L'\0';
410
411     if( CreateDirectoryW( wname, NULL ) == 0 )
412     {
413         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
414             errno = EEXIST;
415         else
416             errno = ENOENT;
417         return -1;
418     }
419     return 0;
420 #else
421     char *locname = ToLocale( dirname );
422     int res;
423
424     if( locname == NULL )
425     {
426         errno = ENOENT;
427         return -1;
428     }
429     res = mkdir( locname, 0755 );
430
431     LocaleFree( locname );
432     return res;
433 #endif
434 }
435
436 /**
437  * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
438  *
439  * @param dirname UTF-8 representation of the directory name
440  *
441  * @return a pointer to the DIR struct. Release with closedir().
442  */
443 DIR *utf8_opendir( const char *dirname )
444 {
445 #ifdef WIN32
446     wchar_t wname[MAX_PATH + 1];
447
448     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
449     {
450         wname[MAX_PATH] = L'\0';
451         return (DIR *)vlc_wopendir (wname);
452     }
453 #else
454     const char *local_name = ToLocale( dirname );
455
456     if( local_name != NULL )
457     {
458         DIR *dir = opendir( local_name );
459         LocaleFree( local_name );
460         return dir;
461     }
462 #endif
463
464     errno = ENOENT;
465     return NULL;
466 }
467
468 /**
469  * utf8_readdir: a readdir wrapper that returns the name of the next entry
470  *     in the directory as a UTF-8 string.
471  *
472  * @param dir The directory that is being read
473  *
474  * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
475  */
476 char *utf8_readdir( DIR *dir )
477 {
478 #ifdef WIN32
479     struct _wdirent *ent = vlc_wreaddir (dir);
480     if (ent == NULL)
481         return NULL;
482
483     return FromWide (ent->d_name);
484 #else
485     struct dirent *ent;
486
487     ent = readdir( (DIR *)dir );
488     if( ent == NULL )
489         return NULL;
490
491     return vlc_fix_readdir( ent->d_name );
492 #endif
493 }
494
495 static int dummy_select( const char *str )
496 {
497     (void)str;
498     return 1;
499 }
500
501 int utf8_loaddir( DIR *dir, char ***namelist,
502                   int (*select)( const char * ),
503                   int (*compar)( const char **, const char ** ) )
504 {
505     if( select == NULL )
506         select = dummy_select;
507
508     if( dir == NULL )
509         return -1;
510     else
511     {
512         char **tab = NULL;
513         char *entry;
514         unsigned num = 0;
515
516         rewinddir( dir );
517
518         while( ( entry = utf8_readdir( dir ) ) != NULL )
519         {
520             char **newtab;
521
522             if( !select( entry ) )
523             {
524                 free( entry );
525                 continue;
526             }
527
528             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
529             if( newtab == NULL )
530             {
531                 free( entry );
532                 goto error;
533             }
534             tab = newtab;
535             tab[num++] = entry;
536         }
537
538         if( compar != NULL )
539             qsort( tab, num, sizeof( tab[0] ),
540                    (int (*)( const void *, const void *))compar );
541
542         *namelist = tab;
543         return num;
544
545     error:{
546         unsigned i;
547
548         for( i = 0; i < num; i++ )
549             free( tab[i] );
550         if( tab != NULL )
551             free( tab );
552         }
553     }
554     return -1;
555 }
556
557 int utf8_scandir( const char *dirname, char ***namelist,
558                   int (*select)( const char * ),
559                   int (*compar)( const char **, const char ** ) )
560 {
561     DIR *dir = utf8_opendir (dirname);
562     int val = -1;
563
564     if (dir != NULL)
565     {
566         val = utf8_loaddir (dir, namelist, select, compar);
567         closedir (dir);
568     }
569     return val;
570 }
571
572 static int utf8_statEx( const char *filename, struct stat *buf,
573                         vlc_bool_t deref )
574 {
575 #if defined (WIN32) || defined (UNDER_CE)
576     /* retrieve Windows OS version */
577     if( GetVersion() < 0x80000000 )
578     {
579         /* for Windows NT and above */
580         wchar_t wpath[MAX_PATH + 1];
581
582         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
583         {
584             errno = ENOENT;
585             return -1;
586         }
587         wpath[MAX_PATH] = L'\0';
588
589         return _wstati64( wpath, buf );
590     }
591 #endif
592 #ifdef HAVE_SYS_STAT_H
593     const char *local_name = ToLocale( filename );
594
595     if( local_name != NULL )
596     {
597         int res = deref ? stat( local_name, buf )
598                        : lstat( local_name, buf );
599         LocaleFree( local_name );
600         return res;
601     }
602     errno = ENOENT;
603 #endif
604     return -1;
605 }
606
607
608 int utf8_stat( const char *filename, struct stat *buf)
609 {
610     return utf8_statEx( filename, buf, VLC_TRUE );
611 }
612
613 int utf8_lstat( const char *filename, struct stat *buf)
614 {
615     return utf8_statEx( filename, buf, VLC_FALSE );
616 }
617
618 /**
619  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
620  */
621 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
622 {
623     char *utf8;
624     int res = vasprintf( &utf8, fmt, ap );
625     if( res == -1 )
626         return -1;
627
628     *str = ToLocaleDup( utf8 );
629     free( utf8 );
630     return res;
631 }
632
633 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
634 {
635     char *str;
636     int res = utf8_vasprintf( &str, fmt, ap );
637     if( res == -1 )
638         return -1;
639
640     fputs( str, stream );
641     free( str );
642     return res;
643 }
644
645 int utf8_fprintf( FILE *stream, const char *fmt, ... )
646 {
647     va_list ap;
648     int res;
649
650     va_start( ap, fmt );
651     res = utf8_vfprintf( stream, fmt, ap );
652     va_end( ap );
653     return res;
654 }
655
656
657 static char *CheckUTF8( char *str, char rep )
658 {
659     uint8_t *ptr = (uint8_t *)str;
660     assert (str != NULL);
661
662     for (;;)
663     {
664         uint8_t c = ptr[0];
665         int charlen = -1;
666
667         if (c == '\0')
668             break;
669
670         for (int i = 0; i < 7; i++)
671             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
672             {
673                 charlen = i;
674                 break;
675             }
676
677         switch (charlen)
678         {
679             case 0: // 7-bit ASCII character -> OK
680                 ptr++;
681                 continue;
682
683             case -1: // 1111111x -> error
684             case 1: // continuation byte -> error
685                 goto error;
686         }
687
688         assert (charlen >= 2);
689
690         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
691         for (int i = 1; i < charlen; i++)
692         {
693             assert (cp < (1 << 26));
694             c = ptr[i];
695
696             if ((c == '\0') // unexpected end of string
697              || ((c >> 6) != 2)) // not a continuation byte
698                 goto error;
699
700             cp = (cp << 6) | (ptr[i] & 0x3f);
701         }
702
703         if (cp < 128) // overlong (special case for ASCII)
704             goto error;
705         if (cp < (1u << (5 * charlen - 3))) // overlong
706             goto error;
707
708         ptr += charlen;
709         continue;
710
711     error:
712         if (rep == 0)
713             return NULL;
714         *ptr++ = rep;
715         str = NULL;
716     }
717
718     return str;
719 }
720
721 /**
722  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
723  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
724  * so we don't try that, even though it would be less disruptive.
725  *
726  * @return str if it was valid UTF-8, NULL if not.
727  */
728 char *EnsureUTF8( char *str )
729 {
730     return CheckUTF8( str, '?' );
731 }
732
733
734 /**
735  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
736  *
737  * @param str nul-terminated string to be checked
738  *
739  * @return str if it was valid UTF-8, NULL if not.
740  */
741 const char *IsUTF8( const char *str )
742 {
743     return CheckUTF8( (char *)str, 0 );
744 }