]> git.sesse.net Git - vlc/blob - src/text/unicode.c
text/unicode.c: More unused warning fix.
[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 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc/vlc.h>
33 #include <vlc_charset.h>
34 #include "libvlc.h" /* utf8_mkdir */
35
36 #include <assert.h>
37
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <errno.h>
42 #include <sys/types.h>
43 #ifdef HAVE_DIRENT_H
44 #  include <dirent.h>
45 #endif
46 #ifdef UNDER_CE
47 #  include <tchar.h>
48 #endif
49 #ifdef HAVE_SYS_STAT_H
50 # include <sys/stat.h>
51 #endif
52 #ifdef HAVE_FCNTL_H
53 # include <fcntl.h>
54 #endif
55 #ifdef WIN32
56 # include <io.h>
57 #else
58 # include <unistd.h>
59 #endif
60
61 #ifndef HAVE_LSTAT
62 # define lstat( a, b ) stat(a, b)
63 #endif
64
65 #ifdef __APPLE__
66 /* Define this if the OS always use UTF-8 internally */
67 # define ASSUME_UTF8 1
68 #endif
69
70 #if defined (ASSUME_UTF8)
71 /* Cool */
72 #elif defined (WIN32) || defined (UNDER_CE)
73 # define USE_MB2MB 1
74 #elif defined (HAVE_ICONV)
75 # define USE_ICONV 1
76 #else
77 # error No UTF8 charset conversion implemented on this platform!
78 #endif
79
80 #if defined (USE_ICONV)
81 static char charset[sizeof ("CSISO11SWEDISHFORNAMES//translit")] = "";
82
83 static void find_charset_once (void)
84 {
85     char *psz_charset;
86     if (vlc_current_charset (&psz_charset)
87      || (psz_charset == NULL)
88      || (strcmp (psz_charset, "ASCII") == 0)
89      || ((size_t)snprintf (charset, sizeof (charset), "%s//translit",
90                            psz_charset) >= sizeof (charset)))
91         strcpy (charset, "UTF-8");
92
93     free (psz_charset);
94 }
95
96 static int find_charset (void)
97 {
98     static pthread_once_t once = PTHREAD_ONCE_INIT;
99     pthread_once (&once, find_charset_once);
100     return !strcmp (charset, "UTF-8");
101 }
102 #endif
103
104
105 static char *locale_fast (const char *string, vlc_bool_t from)
106 {
107 #if defined (USE_ICONV)
108     if (find_charset ())
109         return (char *)string;
110
111     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
112                                      from ? charset : "UTF-8");
113     if (hd == (vlc_iconv_t)(-1))
114         return strdup (string); /* Uho! */
115
116     const char *iptr = string;
117     size_t inb = strlen (string);
118     size_t outb = inb * 6 + 1;
119     char output[outb], *optr = output;
120
121     if (string == NULL)
122         return NULL;
123
124     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
125     {
126         *optr++ = '?';
127         outb--;
128         iptr++;
129         inb--;
130         vlc_iconv (hd, NULL, NULL, NULL, NULL);
131     }
132     *optr = '\0';
133     vlc_iconv_close (hd);
134
135     assert (inb == 0);
136     assert (*iptr == '\0');
137     assert (*optr == '\0');
138     assert (strlen (output) == (size_t)(optr - output));
139     return strdup (output);
140 #elif defined (USE_MB2MB)
141     char *out;
142     int len;
143
144     if (string == NULL)
145         return NULL;
146
147     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
148                                    0, string, -1, NULL, 0);
149     wchar_t wide[len];
150
151     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
152     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, NULL, 0, NULL, NULL);
153     out = malloc (len);
154     if (out == NULL)
155         return NULL;
156
157     WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len, NULL, NULL);
158     return out;
159 #else
160     VLC_UNUSED(from);
161     return (char *)string;
162 #endif
163 }
164
165
166 static inline char *locale_dup (const char *string, vlc_bool_t from)
167 {
168 #if defined (USE_ICONV)
169     if (find_charset ())
170         return strdup (string);
171     return locale_fast (string, from);
172 #elif defined (USE_MB2MB)
173     return locale_fast (string, from);
174 #else
175     VLC_UNUSED(from);
176     return strdup (string);
177 #endif
178 }
179
180
181 void LocaleFree (const char *str)
182 {
183 #if defined (USE_ICONV)
184     if (!find_charset ())
185         free ((char *)str);
186 #elif defined (USE_MB2MB)
187     free ((char *)str);
188 #else
189     VLC_UNUSED(str);
190 #endif
191 }
192
193
194 /**
195  * FromLocale: converts a locale string to UTF-8
196  *
197  * @param locale nul-terminated string to be converted
198  *
199  * @return a nul-terminated UTF-8 string, or NULL in case of error.
200  * To avoid memory leak, you have to pass the result to LocaleFree()
201  * when it is no longer needed.
202  */
203 char *FromLocale (const char *locale)
204 {
205     return locale_fast (locale, VLC_TRUE);
206 }
207
208 char *FromLocaleDup (const char *locale)
209 {
210     return locale_dup (locale, VLC_TRUE);
211 }
212
213
214 /**
215  * ToLocale: converts a UTF-8 string to local system encoding.
216  *
217  * @param utf8 nul-terminated string to be converted
218  *
219  * @return a nul-terminated string, or NULL in case of error.
220  * To avoid memory leak, you have to pass the result to LocaleFree()
221  * when it is no longer needed.
222  */
223 char *ToLocale (const char *utf8)
224 {
225     return locale_fast (utf8, VLC_FALSE);
226 }
227
228
229 static char *ToLocaleDup (const char *utf8)
230 {
231     return locale_dup (utf8, VLC_FALSE);
232 }
233
234
235 /**
236  * utf8_open: open() wrapper for UTF-8 filenames
237  */
238 int utf8_open (const char *filename, int flags, mode_t mode)
239 {
240 #if defined (WIN32) || defined (UNDER_CE)
241     if (GetVersion() < 0x80000000)
242     {
243         /* for Windows NT and above */
244         wchar_t wpath[MAX_PATH + 1];
245
246         if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
247         {
248             errno = ENOENT;
249             return -1;
250         }
251         wpath[MAX_PATH] = L'\0';
252
253         /*
254          * open() cannot open files with non-“ANSI” characters on Windows.
255          * We use _wopen() instead. Same thing for mkdir() and stat().
256          */
257         return _wopen (wpath, flags, mode);
258     }
259 #endif
260     const char *local_name = ToLocale (filename);
261
262     if (local_name == NULL)
263     {
264         errno = ENOENT;
265         return -1;
266     }
267
268     int fd = open (local_name, flags, mode);
269     LocaleFree (local_name);
270     return fd;
271 }
272
273 /**
274  * utf8_fopen: fopen() wrapper for UTF-8 filenames
275  */
276 FILE *utf8_fopen (const char *filename, const char *mode)
277 {
278     int rwflags = 0, oflags = 0;
279     vlc_bool_t append = VLC_FALSE;
280
281     for (const char *ptr = mode; *ptr; ptr++)
282     {
283         switch (*ptr)
284         {
285             case 'r':
286                 rwflags = O_RDONLY;
287                 break;
288
289             case 'a':
290                 rwflags = O_WRONLY;
291                 oflags |= O_CREAT;
292                 append = VLC_TRUE;
293                 break;
294
295             case 'w':
296                 rwflags = O_WRONLY;
297                 oflags |= O_CREAT | O_TRUNC;
298                 break;
299
300             case '+':
301                 rwflags = O_RDWR;
302                 break;
303
304 #ifdef O_TEXT
305             case 't':
306                 oflags |= O_TEXT;
307                 break;
308 #endif
309         }
310     }
311
312     int fd = utf8_open (filename, rwflags | oflags, 0666);
313     if (fd == -1)
314         return NULL;
315
316     if (append && (lseek (fd, 0, SEEK_END) == -1))
317     {
318         close (fd);
319         return NULL;
320     }
321
322     FILE *stream = fdopen (fd, mode);
323     if (stream == NULL)
324         close (fd);
325
326     return stream;
327 }
328
329 /**
330  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
331  *
332  * @param dirname a UTF-8 string with the name of the directory that you
333  *        want to create.
334  * @return A 0 return value indicates success. A -1 return value indicates an
335  *        error, and an error code is stored in errno
336  */
337 int utf8_mkdir( const char *dirname, mode_t mode )
338 {
339 #if defined (UNDER_CE) || defined (WIN32)
340     wchar_t wname[MAX_PATH + 1];
341     char mod[MAX_PATH + 1];
342     int i;
343
344     /* Convert '/' into '\' */
345     for( i = 0; *dirname; i++ )
346     {
347         if( i == MAX_PATH )
348             return -1; /* overflow */
349
350         if( *dirname == '/' )
351             mod[i] = '\\';
352         else
353             mod[i] = *dirname;
354         dirname++;
355
356     }
357     mod[i] = 0;
358
359     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
360     {
361         errno = ENOENT;
362         return -1;
363     }
364     wname[MAX_PATH] = L'\0';
365
366     if( CreateDirectoryW( wname, NULL ) == 0 )
367     {
368         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
369             errno = EEXIST;
370         else
371             errno = ENOENT;
372         return -1;
373     }
374     return 0;
375 #else
376     char *locname = ToLocale( dirname );
377     int res;
378
379     if( locname == NULL )
380     {
381         errno = ENOENT;
382         return -1;
383     }
384     res = mkdir( locname, mode );
385
386     LocaleFree( locname );
387     return res;
388 #endif
389 }
390
391 /**
392  * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
393  *
394  * @param dirname UTF-8 representation of the directory name
395  *
396  * @return a pointer to the DIR struct. Release with closedir().
397  */
398 DIR *utf8_opendir( const char *dirname )
399 {
400 #ifdef WIN32
401     wchar_t wname[MAX_PATH + 1];
402
403     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
404     {
405         wname[MAX_PATH] = L'\0';
406         return (DIR *)vlc_wopendir (wname);
407     }
408 #else
409     const char *local_name = ToLocale( dirname );
410
411     if( local_name != NULL )
412     {
413         DIR *dir = opendir( local_name );
414         LocaleFree( local_name );
415         return dir;
416     }
417 #endif
418
419     errno = ENOENT;
420     return NULL;
421 }
422
423 /**
424  * utf8_readdir: a readdir wrapper that returns the name of the next entry
425  *     in the directory as a UTF-8 string.
426  *
427  * @param dir The directory that is being read
428  *
429  * @return a UTF-8 string of the directory entry. Use free() to free this memory.
430  */
431 char *utf8_readdir( DIR *dir )
432 {
433 #ifdef WIN32
434     struct _wdirent *ent = vlc_wreaddir (dir);
435     if (ent == NULL)
436         return NULL;
437
438     return FromWide (ent->d_name);
439 #else
440     struct dirent *ent;
441
442     ent = readdir( (DIR *)dir );
443     if( ent == NULL )
444         return NULL;
445
446     return vlc_fix_readdir( ent->d_name );
447 #endif
448 }
449
450 static int dummy_select( const char *str )
451 {
452     (void)str;
453     return 1;
454 }
455
456 int utf8_loaddir( DIR *dir, char ***namelist,
457                   int (*select)( const char * ),
458                   int (*compar)( const char **, const char ** ) )
459 {
460     if( select == NULL )
461         select = dummy_select;
462
463     if( dir == NULL )
464         return -1;
465     else
466     {
467         char **tab = NULL;
468         char *entry;
469         unsigned num = 0;
470
471         rewinddir( dir );
472
473         while( ( entry = utf8_readdir( dir ) ) != NULL )
474         {
475             char **newtab;
476
477             if( !select( entry ) )
478             {
479                 free( entry );
480                 continue;
481             }
482
483             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
484             if( newtab == NULL )
485             {
486                 free( entry );
487                 goto error;
488             }
489             tab = newtab;
490             tab[num++] = entry;
491         }
492
493         if( compar != NULL )
494             qsort( tab, num, sizeof( tab[0] ),
495                    (int (*)( const void *, const void *))compar );
496
497         *namelist = tab;
498         return num;
499
500     error:{
501         unsigned i;
502
503         for( i = 0; i < num; i++ )
504             free( tab[i] );
505         if( tab != NULL )
506             free( tab );
507         }
508     }
509     return -1;
510 }
511
512 int utf8_scandir( const char *dirname, char ***namelist,
513                   int (*select)( const char * ),
514                   int (*compar)( const char **, const char ** ) )
515 {
516     DIR *dir = utf8_opendir (dirname);
517     int val = -1;
518
519     if (dir != NULL)
520     {
521         val = utf8_loaddir (dir, namelist, select, compar);
522         closedir (dir);
523     }
524     return val;
525 }
526
527 static int utf8_statEx( const char *filename, struct stat *buf,
528                         vlc_bool_t deref )
529 {
530 #if defined (WIN32) || defined (UNDER_CE)
531     /* retrieve Windows OS version */
532     if( GetVersion() < 0x80000000 )
533     {
534         /* for Windows NT and above */
535         wchar_t wpath[MAX_PATH + 1];
536
537         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
538         {
539             errno = ENOENT;
540             return -1;
541         }
542         wpath[MAX_PATH] = L'\0';
543
544         return _wstati64( wpath, buf );
545     }
546 #endif
547 #ifdef HAVE_SYS_STAT_H
548     const char *local_name = ToLocale( filename );
549
550     if( local_name != NULL )
551     {
552         int res = deref ? stat( local_name, buf )
553                        : lstat( local_name, buf );
554         LocaleFree( local_name );
555         return res;
556     }
557     errno = ENOENT;
558 #endif
559     return -1;
560 }
561
562
563 int utf8_stat( const char *filename, struct stat *buf)
564 {
565     return utf8_statEx( filename, buf, VLC_TRUE );
566 }
567
568 int utf8_lstat( const char *filename, struct stat *buf)
569 {
570     return utf8_statEx( filename, buf, VLC_FALSE );
571 }
572
573 /**
574  * utf8_unlink: Calls unlink() after conversion of file name to OS locale
575  *
576  * @param filename a UTF-8 string with the name of the file you want to delete.
577  * @return A 0 return value indicates success. A -1 return value indicates an
578  *        error, and an error code is stored in errno
579  */
580 int utf8_unlink( const char *filename )
581 {
582 #if defined (WIN32) || defined (UNDER_CE)
583     if( GetVersion() < 0x80000000 )
584     {
585         /* for Windows NT and above */
586         wchar_t wpath[MAX_PATH + 1];
587
588         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
589         {
590             errno = ENOENT;
591             return -1;
592         }
593         wpath[MAX_PATH] = L'\0';
594
595         /*
596          * unlink() cannot open files with non-“ANSI” characters on Windows.
597          * We use _wunlink() instead.
598          */
599         return _wunlink( wpath );
600     }
601 #endif
602     const char *local_name = ToLocale( filename );
603
604     if( local_name == NULL )
605     {
606         errno = ENOENT;
607         return -1;
608     }
609
610     int ret = unlink( local_name );
611     LocaleFree( local_name );
612     return ret;
613 }
614
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 }