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