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