]> git.sesse.net Git - vlc/blob - src/text/unicode.c
* Fix utf8_scandir (wasn't using vlc_closedir_wrapper)
[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 #ifndef ASSUME_UTF8
66 # if defined (HAVE_ICONV)
67 /* libiconv is more powerful than Win32 API (it has translit) */
68 #  define USE_ICONV 1
69 # elif defined (WIN32) || defined (UNDER_CE)
70 #  define USE_MB2MB 1
71 # else
72 #  error No UTF8 charset conversion implemented on this platform!
73 # endif
74 #endif
75
76 typedef struct locale_data_t
77 {
78 #if defined (USE_ICONV)
79     vlc_iconv_t hd;
80     vlc_mutex_t lock;
81 #elif defined (USE_MB2MB)
82     UINT fromCP;
83     UINT toCP;
84 #endif
85 } locale_data_t;
86
87 static locale_data_t from_locale, to_locale;
88
89
90 void LocaleInit( vlc_object_t *p_this )
91 {
92 #if defined USE_ICONV
93     char *psz_charset;
94
95     if( vlc_current_charset( &psz_charset ) )
96         /* UTF-8 */
97         from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
98     else
99     {
100         /* not UTF-8 */
101         char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
102         const char *psz_conv;
103
104         /*
105          * Still allow non-ASCII characters when the locale is not set.
106          * Western Europeans are being favored for historical reasons.
107          */
108         if( strcmp( psz_charset, "ASCII" ) )
109         {
110             sprintf( psz_buf, "%s//translit", psz_charset );
111             psz_conv = psz_buf;
112         }
113         else
114             psz_conv = "ISO-8859-1//translit";
115
116         vlc_mutex_init( p_this, &from_locale.lock );
117         vlc_mutex_init( p_this, &to_locale.lock );
118         from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
119         to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
120     }
121
122     free( psz_charset );
123
124     assert( (from_locale.hd == (vlc_iconv_t)(-1))
125             == (to_locale.hd == (vlc_iconv_t)(-1)) );
126
127 #elif defined (USE_MB2MB)
128     to_locale.toCP = from_locale.fromCP = CP_ACP;
129     from_locale.toCP = to_locale.fromCP = CP_UTF8;
130 #else
131     (void)p_this;
132 #endif
133 }
134
135 void LocaleDeinit( void )
136 {
137 #ifdef USE_ICONV
138     if( to_locale.hd != (vlc_iconv_t)(-1) )
139     {
140         vlc_iconv_close( to_locale.hd );
141         vlc_mutex_destroy( &to_locale.lock );
142     }
143
144     if( from_locale.hd != (vlc_iconv_t)(-1) )
145     {
146         vlc_iconv_close( from_locale.hd );
147         vlc_mutex_destroy( &from_locale.lock );
148     }
149 #endif
150 }
151
152 static char *locale_fast (const char *string, locale_data_t *p)
153 {
154 #if defined (USE_ICONV)
155     vlc_iconv_t hd = p->hd;
156
157     if (hd == (vlc_iconv_t)(-1))
158         return (char *)string;
159
160     const char *iptr = string;
161     size_t inb = strlen (string);
162     size_t outb = inb * 6 + 1;
163     char output[outb], *optr = output;
164
165     if (string == NULL)
166         return NULL;
167
168     vlc_mutex_lock (&p->lock);
169     vlc_iconv (hd, NULL, NULL, NULL, NULL);
170
171     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
172     {
173         *optr++ = '?';
174         outb--;
175         iptr++;
176         inb--;
177         vlc_iconv (hd, NULL, NULL, NULL, NULL);
178     }
179     vlc_mutex_unlock (&p->lock);
180     *optr = '\0';
181
182     assert (inb == 0);
183     assert (*iptr == '\0');
184     assert (*optr == '\0');
185     assert (strlen (output) == (size_t)(optr - output));
186     return strdup (output);
187 #elif defined (USE_MB2MB)
188     char *out;
189     wchar_t *wide;
190     int len;
191
192     if (string == NULL)
193         return NULL;
194
195     len = MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
196     if (len == 0)
197         return NULL;
198
199     wchar_t wide[len];
200
201     MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
202     len = WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
203     if (len == 0)
204         return NULL;
205     out = malloc (len);
206
207     WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
208     return out;
209 #else
210     return (char *)string;
211 #endif
212 }
213
214
215 static inline char *locale_dup (const char *string, locale_data_t *p)
216 {
217 #if defined (USE_ICONV)
218     return (p->hd == (vlc_iconv_t)(-1))
219             ? strdup (string)
220             : locale_fast (string, p);
221 #elif defined (USE_MB2MB)
222     return locale_fast (string, p);
223 #else
224     return strdup (string);
225 #endif
226 }
227
228
229 void LocaleFree (const char *str)
230 {
231 #if defined (USE_ICONV)
232     assert ((to_locale.hd == (vlc_iconv_t)(-1))
233          == (from_locale.hd == (vlc_iconv_t)(-1)));
234
235     if( to_locale.hd != (vlc_iconv_t)(-1) )
236         free ((char *)str);
237 #elif defined (USE_MB2MB)
238     free ((char *)str);
239 #endif
240 }
241
242
243 /**
244  * FromLocale: converts a locale string to UTF-8
245  *
246  * @param locale nul-terminated string to be converted
247  *
248  * @return a nul-terminated UTF-8 string, or NULL in case of error.
249  * To avoid memory leak, you have to pass the result to LocaleFree()
250  * when it is no longer needed.
251  */
252 char *FromLocale (const char *locale)
253 {
254     return locale_fast (locale, &from_locale);
255 }
256
257 char *FromLocaleDup (const char *locale)
258 {
259     return locale_dup (locale, &from_locale);
260 }
261
262
263 /**
264  * ToLocale: converts a UTF-8 string to local system encoding.
265  *
266  * @param utf8 nul-terminated string to be converted
267  *
268  * @return a nul-terminated string, or NULL in case of error.
269  * To avoid memory leak, you have to pass the result to LocaleFree()
270  * when it is no longer needed.
271  */
272 char *ToLocale (const char *utf8)
273 {
274     return locale_fast (utf8, &to_locale);
275 }
276
277
278 static char *ToLocaleDup (const char *utf8)
279 {
280     return locale_dup (utf8, &to_locale);
281 }
282
283
284 /**
285  * utf8_open: open() wrapper for UTF-8 filenames
286  */
287 int utf8_open (const char *filename, int flags, mode_t mode)
288 {
289 #if defined (WIN32) || defined (UNDER_CE)
290     if (GetVersion() < 0x80000000)
291     {
292         /* for Windows NT and above */
293         wchar_t wpath[MAX_PATH + 1];
294
295         if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
296         {
297             errno = ENOENT;
298             return -1;
299         }
300         wpath[MAX_PATH] = L'\0';
301
302         /*
303          * open() cannot open files with non-“ANSI” characters on Windows.
304          * We use _wopen() instead. Same thing for mkdir() and stat().
305          */
306         return _wopen (wpath, flags, mode);
307     }
308 #endif
309     const char *local_name = ToLocale (filename);
310
311     if (local_name == NULL)
312     {
313         errno = ENOENT;
314         return -1;
315     }
316
317     int fd = open (local_name, flags, mode);
318     LocaleFree (local_name);
319     return fd;
320 }
321
322 /**
323  * utf8_fopen: fopen() wrapper for UTF-8 filenames
324  */
325 FILE *utf8_fopen (const char *filename, const char *mode)
326 {
327     int rwflags = 0, oflags = 0;
328     vlc_bool_t append = VLC_FALSE;
329
330     for (const char *ptr = mode; *ptr; ptr++)
331     {
332         switch (*ptr)
333         {
334             case 'r':
335                 rwflags = O_RDONLY;
336                 break;
337
338             case 'a':
339                 rwflags = O_WRONLY;
340                 oflags |= O_CREAT;
341                 append = VLC_TRUE;
342                 break;
343
344             case 'w':
345                 rwflags = O_WRONLY;
346                 oflags |= O_CREAT | O_TRUNC;
347                 break;
348
349             case '+':
350                 rwflags = O_RDWR;
351                 break;
352         }
353     }
354
355     int fd = utf8_open (filename, rwflags | oflags, 0666);
356     if (fd == -1)
357         return NULL;
358
359     if (append && (lseek (fd, 0, SEEK_END) == -1))
360     {
361         close (fd);
362         return NULL;
363     }
364
365     FILE *stream = fdopen (fd, mode);
366     if (stream == NULL)
367         close (fd);
368
369     return stream;
370 }
371
372 /**
373  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
374  *
375  * @param dirname a UTF-8 string with the name of the directory that you
376  *        want to create.
377  * @return A 0 return value indicates success. A -1 return value indicates an
378  *        error, and an error code is stored in errno
379  */
380 int utf8_mkdir( const char *dirname )
381 {
382 #if defined (UNDER_CE) || defined (WIN32)
383     wchar_t wname[MAX_PATH + 1];
384     char mod[MAX_PATH + 1];
385     int i;
386
387     /* Convert '/' into '\' */
388     for( i = 0; *dirname; i++ )
389     {
390         if( i == MAX_PATH )
391             return -1; /* overflow */
392
393         if( *dirname == '/' )
394             mod[i] = '\\';
395         else
396             mod[i] = *dirname;
397         dirname++;
398
399     }
400     mod[i] = 0;
401
402     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
403     {
404         errno = ENOENT;
405         return -1;
406     }
407     wname[MAX_PATH] = L'\0';
408
409     if( CreateDirectoryW( wname, NULL ) == 0 )
410     {
411         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
412             errno = EEXIST;
413         else
414             errno = ENOENT;
415         return -1;
416     }
417     return 0;
418 #else
419     char *locname = ToLocale( dirname );
420     int res;
421
422     if( locname == NULL )
423     {
424         errno = ENOENT;
425         return -1;
426     }
427     res = mkdir( locname, 0755 );
428
429     LocaleFree( locname );
430     return res;
431 #endif
432 }
433
434 /**
435  * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
436  *
437  * @param dirname UTF-8 representation of the directory name
438  *
439  * @return a pointer to the DIR struct. Use vlc_closedir_wrapper() once you are done.
440 DIR *utf8_opendir( const char *dirname )
441 {
442 #ifdef WIN32
443     wchar_t wname[MAX_PATH + 1];
444
445     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
446     {
447         wname[MAX_PATH] = L'\0';
448         return (DIR *)vlc_wopendir (wname);
449     }
450 #else
451     const char *local_name = ToLocale( dirname );
452
453     if( local_name != NULL )
454     {
455         DIR *dir = opendir( local_name );
456         LocaleFree( local_name );
457         return dir;
458     }
459 #endif
460
461     errno = ENOENT;
462     return NULL;
463 }
464
465 /**
466  * utf8_readdir: a readdir wrapper that returns the name of the next entry
467  *     in the directory as a UTF-8 string.
468  *
469  * @param dir The directory that is being read
470  *
471  * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
472  */
473 char *utf8_readdir( DIR *dir )
474 {
475 #ifdef WIN32
476     struct _wdirent *ent = vlc_wreaddir (dir);
477     if (ent == NULL)
478         return NULL;
479
480     return FromWide (ent->d_name);
481 #else
482     struct dirent *ent;
483
484     ent = readdir( (DIR *)dir );
485     if( ent == NULL )
486         return NULL;
487
488     return vlc_fix_readdir( ent->d_name );
489 #endif
490 }
491
492 static int dummy_select( const char *str )
493 {
494     (void)str;
495     return 1;
496 }
497
498 int utf8_scandir( const char *dirname, char ***namelist,
499                   int (*select)( const char * ),
500                   int (*compar)( const char **, const char ** ) )
501 {
502     DIR *dir = utf8_opendir( dirname );
503
504     if( select == NULL )
505         select = dummy_select;
506
507     if( dir == NULL )
508         return -1;
509     else
510     {
511         char **tab = NULL;
512         char *entry;
513         unsigned num = 0;
514
515         while( ( entry = utf8_readdir( dir ) ) != NULL )
516         {
517             char **newtab;
518
519             if( !select( entry ) )
520             {
521                 free( entry );
522                 continue;
523             }
524
525             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
526             if( newtab == NULL )
527             {
528                 free( entry );
529                 goto error;
530             }
531             tab = newtab;
532             tab[num++] = entry;
533         }
534         vlc_closedir_wrapper( dir );
535
536         if( compar != NULL )
537             qsort( tab, num, sizeof( tab[0] ),
538                    (int (*)( const void *, const void *))compar );
539
540         *namelist = tab;
541         return num;
542
543     error:{
544         unsigned i;
545
546         for( i = 0; i < num; i++ )
547             free( tab[i] );
548         if( tab != NULL )
549             free( tab );
550         return -1;}
551     }
552 }
553
554
555 static int utf8_statEx( const char *filename, struct stat *buf,
556                         vlc_bool_t deref )
557 {
558 #if defined (WIN32) || defined (UNDER_CE)
559     /* retrieve Windows OS version */
560     if( GetVersion() < 0x80000000 )
561     {
562         /* for Windows NT and above */
563         wchar_t wpath[MAX_PATH + 1];
564
565         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
566         {
567             errno = ENOENT;
568             return -1;
569         }
570         wpath[MAX_PATH] = L'\0';
571
572         return _wstati64( wpath, buf );
573     }
574 #endif
575 #ifdef HAVE_SYS_STAT_H
576     const char *local_name = ToLocale( filename );
577
578     if( local_name != NULL )
579     {
580         int res = deref ? stat( local_name, buf )
581                        : lstat( local_name, buf );
582         LocaleFree( local_name );
583         return res;
584     }
585     errno = ENOENT;
586 #endif
587     return -1;
588 }
589
590
591 int utf8_stat( const char *filename, struct stat *buf)
592 {
593     return utf8_statEx( filename, buf, VLC_TRUE );
594 }
595
596 int utf8_lstat( const char *filename, struct stat *buf)
597 {
598     return utf8_statEx( filename, buf, VLC_FALSE );
599 }
600
601 /**
602  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
603  */
604 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
605 {
606     char *utf8;
607     int res = vasprintf( &utf8, fmt, ap );
608     if( res == -1 )
609         return -1;
610
611     *str = ToLocaleDup( utf8 );
612     free( utf8 );
613     return res;
614 }
615
616 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
617 {
618     char *str;
619     int res = utf8_vasprintf( &str, fmt, ap );
620     if( res == -1 )
621         return -1;
622
623     fputs( str, stream );
624     free( str );
625     return res;
626 }
627
628 int utf8_fprintf( FILE *stream, const char *fmt, ... )
629 {
630     va_list ap;
631     int res;
632
633     va_start( ap, fmt );
634     res = utf8_vfprintf( stream, fmt, ap );
635     va_end( ap );
636     return res;
637 }
638
639
640 static char *CheckUTF8( char *str, char rep )
641 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF)) 
642 {
643     unsigned char *ptr, c;
644
645     assert (str != NULL);
646
647     ptr = (unsigned char *)str;
648     while( (c = *ptr) != '\0' )
649     {
650         /* US-ASCII, 1 byte */
651         if( c <= 0x7F )
652             ptr++; /* OK */
653         else
654         /* 2 bytes */
655         if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
656         {
657             c = ptr[1];
658             if( isutf8cont( c ) )
659                 ptr += 2; /* OK */
660             else
661                 goto error;
662         }
663         else
664         /* 3 bytes */
665         if( c == 0xE0 )
666         {
667             c = ptr[1];
668             if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
669             {
670                 c = ptr[2];
671                 if( isutf8cont( c ) )
672                     ptr += 3; /* OK */
673                 else
674                     goto error;
675             }
676             else
677                 goto error;
678         }
679         else
680         if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
681          || ( c == 0xEE ) || ( c == 0xEF ) )
682         {
683             c = ptr[1];
684             if( isutf8cont( c ) )
685             {
686                 c = ptr[2];
687                 if( isutf8cont( c ) )
688                     ptr += 3; /* OK */
689                 else
690                     goto error;
691             }
692             else
693                 goto error;
694         }
695         else
696         if( c == 0xED )
697         {
698             c = ptr[1];
699             if( ( c >= 0x80 ) && ( c <= 0x9F ) )
700             {
701                 c = ptr[2];
702                 if( isutf8cont( c ) )
703                     ptr += 3; /* OK */
704                 else
705                     goto error;
706             }
707             else
708                 goto error;
709         }
710         else
711         /* 4 bytes */
712         if( c == 0xF0 )
713         {
714             c = ptr[1];
715             if( ( c >= 0x90 ) && ( c <= 0xBF ) )
716             {
717                 c = ptr[2];
718                 if( isutf8cont( c ) )
719                 {
720                     c = ptr[3];
721                     if( isutf8cont( c ) )
722                         ptr += 4; /* OK */
723                     else
724                         goto error;
725                 }
726                 else
727                     goto error;
728             }
729             else
730                 goto error;
731         }
732         else
733         if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
734         {
735             c = ptr[1];
736             if( isutf8cont( c ) )
737             {
738                 c = ptr[2];
739                 if( isutf8cont( c ) )
740                 {
741                     c = ptr[3];
742                     if( isutf8cont( c ) )
743                         ptr += 4; /* OK */
744                     goto error;
745                 }
746                 else
747                     goto error;
748             }
749             else
750                 goto error;
751         }
752         else
753         if( c == 0xF4 )
754         {
755             c = ptr[1];
756             if( ( c >= 0x80 ) && ( c <= 0x8F ) )
757             {
758                 c = ptr[2];
759                 if( isutf8cont( c ) )
760                 {
761                     c = ptr[3];
762                     if( isutf8cont( c ) )
763                         ptr += 4; /* OK */
764                     else
765                         goto error;
766                 }
767                 else
768                     goto error;
769             }
770             else
771                 goto error;
772         }
773         else
774             goto error;
775
776         continue;
777
778 error:
779         if( rep == 0 )
780             return NULL;
781         *ptr++ = '?';
782         str = NULL;
783     }
784
785     return str;
786 }
787
788 /**
789  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
790  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
791  * so we don't try that, even though it would be less disruptive.
792  *
793  * @return str if it was valid UTF-8, NULL if not.
794  */
795 char *EnsureUTF8( char *str )
796 {
797     return CheckUTF8( str, '?' );
798 }
799
800
801 /**
802  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
803  *
804  * @param str nul-terminated string to be checked
805  *
806  * @return str if it was valid UTF-8, NULL if not.
807  */
808 const char *IsUTF8( const char *str )
809 {
810     return CheckUTF8( (char *)str, 0 );
811 }