]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Remove bogus variable
[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     int len;
189
190     if (string == NULL)
191         return NULL;
192
193     len = 1 + MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
194     wchar_t wide[len];
195
196     MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
197     len = 1 + WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
198     out = malloc (len);
199     if (out == NULL)
200         return NULL;
201
202     WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
203     return out;
204 #else
205     return (char *)string;
206 #endif
207 }
208
209
210 static inline char *locale_dup (const char *string, locale_data_t *p)
211 {
212 #if defined (USE_ICONV)
213     return (p->hd == (vlc_iconv_t)(-1))
214             ? strdup (string)
215             : locale_fast (string, p);
216 #elif defined (USE_MB2MB)
217     return locale_fast (string, p);
218 #else
219     return strdup (string);
220 #endif
221 }
222
223
224 void LocaleFree (const char *str)
225 {
226 #if defined (USE_ICONV)
227     assert ((to_locale.hd == (vlc_iconv_t)(-1))
228          == (from_locale.hd == (vlc_iconv_t)(-1)));
229
230     if( to_locale.hd != (vlc_iconv_t)(-1) )
231         free ((char *)str);
232 #elif defined (USE_MB2MB)
233     free ((char *)str);
234 #endif
235 }
236
237
238 /**
239  * FromLocale: converts a locale string to UTF-8
240  *
241  * @param locale nul-terminated string to be converted
242  *
243  * @return a nul-terminated UTF-8 string, or NULL in case of error.
244  * To avoid memory leak, you have to pass the result to LocaleFree()
245  * when it is no longer needed.
246  */
247 char *FromLocale (const char *locale)
248 {
249     return locale_fast (locale, &from_locale);
250 }
251
252 char *FromLocaleDup (const char *locale)
253 {
254     return locale_dup (locale, &from_locale);
255 }
256
257
258 /**
259  * ToLocale: converts a UTF-8 string to local system encoding.
260  *
261  * @param utf8 nul-terminated string to be converted
262  *
263  * @return a nul-terminated string, or NULL in case of error.
264  * To avoid memory leak, you have to pass the result to LocaleFree()
265  * when it is no longer needed.
266  */
267 char *ToLocale (const char *utf8)
268 {
269     return locale_fast (utf8, &to_locale);
270 }
271
272
273 static char *ToLocaleDup (const char *utf8)
274 {
275     return locale_dup (utf8, &to_locale);
276 }
277
278
279 /**
280  * utf8_open: open() wrapper for UTF-8 filenames
281  */
282 int utf8_open (const char *filename, int flags, mode_t mode)
283 {
284 #if defined (WIN32) || defined (UNDER_CE)
285     if (GetVersion() < 0x80000000)
286     {
287         /* for Windows NT and above */
288         wchar_t wpath[MAX_PATH + 1];
289
290         if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
291         {
292             errno = ENOENT;
293             return -1;
294         }
295         wpath[MAX_PATH] = L'\0';
296
297         /*
298          * open() cannot open files with non-“ANSI” characters on Windows.
299          * We use _wopen() instead. Same thing for mkdir() and stat().
300          */
301         return _wopen (wpath, flags, mode);
302     }
303 #endif
304     const char *local_name = ToLocale (filename);
305
306     if (local_name == NULL)
307     {
308         errno = ENOENT;
309         return -1;
310     }
311
312     int fd = open (local_name, flags, mode);
313     LocaleFree (local_name);
314     return fd;
315 }
316
317 /**
318  * utf8_fopen: fopen() wrapper for UTF-8 filenames
319  */
320 FILE *utf8_fopen (const char *filename, const char *mode)
321 {
322     int rwflags = 0, oflags = 0;
323     vlc_bool_t append = VLC_FALSE;
324
325     for (const char *ptr = mode; *ptr; ptr++)
326     {
327         switch (*ptr)
328         {
329             case 'r':
330                 rwflags = O_RDONLY;
331                 break;
332
333             case 'a':
334                 rwflags = O_WRONLY;
335                 oflags |= O_CREAT;
336                 append = VLC_TRUE;
337                 break;
338
339             case 'w':
340                 rwflags = O_WRONLY;
341                 oflags |= O_CREAT | O_TRUNC;
342                 break;
343
344             case '+':
345                 rwflags = O_RDWR;
346                 break;
347
348 #ifdef O_TEXT
349             case 't':
350                 oflags |= O_TEXT;
351                 break;
352 #endif
353         }
354     }
355
356     int fd = utf8_open (filename, rwflags | oflags, 0666);
357     if (fd == -1)
358         return NULL;
359
360     if (append && (lseek (fd, 0, SEEK_END) == -1))
361     {
362         close (fd);
363         return NULL;
364     }
365
366     FILE *stream = fdopen (fd, mode);
367     if (stream == NULL)
368         close (fd);
369
370     return stream;
371 }
372
373 /**
374  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
375  *
376  * @param dirname a UTF-8 string with the name of the directory that you
377  *        want to create.
378  * @return A 0 return value indicates success. A -1 return value indicates an
379  *        error, and an error code is stored in errno
380  */
381 int utf8_mkdir( const char *dirname )
382 {
383 #if defined (UNDER_CE) || defined (WIN32)
384     wchar_t wname[MAX_PATH + 1];
385     char mod[MAX_PATH + 1];
386     int i;
387
388     /* Convert '/' into '\' */
389     for( i = 0; *dirname; i++ )
390     {
391         if( i == MAX_PATH )
392             return -1; /* overflow */
393
394         if( *dirname == '/' )
395             mod[i] = '\\';
396         else
397             mod[i] = *dirname;
398         dirname++;
399
400     }
401     mod[i] = 0;
402
403     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
404     {
405         errno = ENOENT;
406         return -1;
407     }
408     wname[MAX_PATH] = L'\0';
409
410     if( CreateDirectoryW( wname, NULL ) == 0 )
411     {
412         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
413             errno = EEXIST;
414         else
415             errno = ENOENT;
416         return -1;
417     }
418     return 0;
419 #else
420     char *locname = ToLocale( dirname );
421     int res;
422
423     if( locname == NULL )
424     {
425         errno = ENOENT;
426         return -1;
427     }
428     res = mkdir( locname, 0755 );
429
430     LocaleFree( locname );
431     return res;
432 #endif
433 }
434
435 /**
436  * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
437  *
438  * @param dirname UTF-8 representation of the directory name
439  *
440  * @return a pointer to the DIR struct. Release with closedir().
441  */
442 DIR *utf8_opendir( const char *dirname )
443 {
444 #ifdef WIN32
445     wchar_t wname[MAX_PATH + 1];
446
447     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
448     {
449         wname[MAX_PATH] = L'\0';
450         return (DIR *)vlc_wopendir (wname);
451     }
452 #else
453     const char *local_name = ToLocale( dirname );
454
455     if( local_name != NULL )
456     {
457         DIR *dir = opendir( local_name );
458         LocaleFree( local_name );
459         return dir;
460     }
461 #endif
462
463     errno = ENOENT;
464     return NULL;
465 }
466
467 /**
468  * utf8_readdir: a readdir wrapper that returns the name of the next entry
469  *     in the directory as a UTF-8 string.
470  *
471  * @param dir The directory that is being read
472  *
473  * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
474  */
475 char *utf8_readdir( DIR *dir )
476 {
477 #ifdef WIN32
478     struct _wdirent *ent = vlc_wreaddir (dir);
479     if (ent == NULL)
480         return NULL;
481
482     return FromWide (ent->d_name);
483 #else
484     struct dirent *ent;
485
486     ent = readdir( (DIR *)dir );
487     if( ent == NULL )
488         return NULL;
489
490     return vlc_fix_readdir( ent->d_name );
491 #endif
492 }
493
494 static int dummy_select( const char *str )
495 {
496     (void)str;
497     return 1;
498 }
499
500 int utf8_loaddir( DIR *dir, char ***namelist,
501                   int (*select)( const char * ),
502                   int (*compar)( const char **, const char ** ) )
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         rewinddir( dir );
516
517         while( ( entry = utf8_readdir( dir ) ) != NULL )
518         {
519             char **newtab;
520
521             if( !select( entry ) )
522             {
523                 free( entry );
524                 continue;
525             }
526
527             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
528             if( newtab == NULL )
529             {
530                 free( entry );
531                 goto error;
532             }
533             tab = newtab;
534             tab[num++] = entry;
535         }
536
537         if( compar != NULL )
538             qsort( tab, num, sizeof( tab[0] ),
539                    (int (*)( const void *, const void *))compar );
540
541         *namelist = tab;
542         return num;
543
544     error:{
545         unsigned i;
546
547         for( i = 0; i < num; i++ )
548             free( tab[i] );
549         if( tab != NULL )
550             free( tab );
551         }
552     }
553     return -1;
554 }
555
556 int utf8_scandir( const char *dirname, char ***namelist,
557                   int (*select)( const char * ),
558                   int (*compar)( const char **, const char ** ) )
559 {
560     DIR *dir = utf8_opendir (dirname);
561     int val = -1;
562
563     if (dir != NULL)
564     {
565         val = utf8_loaddir (dir, namelist, select, compar);
566         closedir (dir);
567     }
568     return val;
569 }
570
571 static int utf8_statEx( const char *filename, struct stat *buf,
572                         vlc_bool_t deref )
573 {
574 #if defined (WIN32) || defined (UNDER_CE)
575     /* retrieve Windows OS version */
576     if( GetVersion() < 0x80000000 )
577     {
578         /* for Windows NT and above */
579         wchar_t wpath[MAX_PATH + 1];
580
581         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
582         {
583             errno = ENOENT;
584             return -1;
585         }
586         wpath[MAX_PATH] = L'\0';
587
588         return _wstati64( wpath, buf );
589     }
590 #endif
591 #ifdef HAVE_SYS_STAT_H
592     const char *local_name = ToLocale( filename );
593
594     if( local_name != NULL )
595     {
596         int res = deref ? stat( local_name, buf )
597                        : lstat( local_name, buf );
598         LocaleFree( local_name );
599         return res;
600     }
601     errno = ENOENT;
602 #endif
603     return -1;
604 }
605
606
607 int utf8_stat( const char *filename, struct stat *buf)
608 {
609     return utf8_statEx( filename, buf, VLC_TRUE );
610 }
611
612 int utf8_lstat( const char *filename, struct stat *buf)
613 {
614     return utf8_statEx( filename, buf, VLC_FALSE );
615 }
616
617 /**
618  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
619  */
620 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
621 {
622     char *utf8;
623     int res = vasprintf( &utf8, fmt, ap );
624     if( res == -1 )
625         return -1;
626
627     *str = ToLocaleDup( utf8 );
628     free( utf8 );
629     return res;
630 }
631
632 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
633 {
634     char *str;
635     int res = utf8_vasprintf( &str, fmt, ap );
636     if( res == -1 )
637         return -1;
638
639     fputs( str, stream );
640     free( str );
641     return res;
642 }
643
644 int utf8_fprintf( FILE *stream, const char *fmt, ... )
645 {
646     va_list ap;
647     int res;
648
649     va_start( ap, fmt );
650     res = utf8_vfprintf( stream, fmt, ap );
651     va_end( ap );
652     return res;
653 }
654
655
656 static char *CheckUTF8( char *str, char rep )
657 {
658     uint8_t *ptr = (uint8_t *)str;
659     assert (str != NULL);
660
661     for (;;)
662     {
663         uint8_t c = ptr[0];
664         int charlen = -1;
665
666         if (c == '\0')
667             break;
668
669         for (int i = 0; i < 7; i++)
670             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
671             {
672                 charlen = i;
673                 break;
674             }
675
676         switch (charlen)
677         {
678             case 0: // 7-bit ASCII character -> OK
679                 ptr++;
680                 continue;
681
682             case -1: // 1111111x -> error
683             case 1: // continuation byte -> error
684                 goto error;
685         }
686
687         assert (charlen >= 2);
688
689         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
690         for (int i = 1; i < charlen; i++)
691         {
692             assert (cp < (1 << 26));
693             c = ptr[i];
694
695             if ((c == '\0') // unexpected end of string
696              || ((c >> 6) != 2)) // not a continuation byte
697                 goto error;
698
699             cp = (cp << 6) | (ptr[i] & 0x3f);
700         }
701
702         if (cp < 128) // overlong (special case for ASCII)
703             goto error;
704         if (cp < (1u << (5 * charlen - 3))) // overlong
705             goto error;
706
707         ptr += charlen;
708         continue;
709
710     error:
711         if (rep == 0)
712             return NULL;
713         *ptr++ = rep;
714         str = NULL;
715     }
716
717     return str;
718 }
719
720 /**
721  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
722  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
723  * so we don't try that, even though it would be less disruptive.
724  *
725  * @return str if it was valid UTF-8, NULL if not.
726  */
727 char *EnsureUTF8( char *str )
728 {
729     return CheckUTF8( str, '?' );
730 }
731
732
733 /**
734  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
735  *
736  * @param str nul-terminated string to be checked
737  *
738  * @return str if it was valid UTF-8, NULL if not.
739  */
740 const char *IsUTF8( const char *str )
741 {
742     return CheckUTF8( (char *)str, 0 );
743 }