]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Fix crash on UTF-8 systems in previous commit
[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 #if defined (USE_ICONV)
76 static char charset[sizeof ("CSISO11SWEDISHFORNAMES//translit")] = "";
77
78 static void find_charset_once (void)
79 {
80     char *psz_charset;
81     if (vlc_current_charset (&psz_charset)
82      || (psz_charset == NULL)
83      || ((size_t)snprintf (charset, sizeof (charset), "%s//translit",
84                            psz_charset) >= sizeof (charset)))
85         strcpy (charset, "UTF-8");
86
87     free (psz_charset);
88 }
89
90 static int find_charset (void)
91 {
92     static pthread_once_t once = PTHREAD_ONCE_INIT;
93     pthread_once (&once, find_charset_once);
94     return !strcmp (charset, "UTF-8");
95 }
96 #endif
97
98
99 static char *locale_fast (const char *string, vlc_bool_t from)
100 {
101 #if defined (USE_ICONV)
102     if (find_charset ())
103         return (char *)string;
104
105     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
106                                      from ? charset : "UTF-8");
107     if (hd == (vlc_iconv_t)(-1))
108         return strdup (string); /* Uho! */
109
110     const char *iptr = string;
111     size_t inb = strlen (string);
112     size_t outb = inb * 6 + 1;
113     char output[outb], *optr = output;
114
115     if (string == NULL)
116         return NULL;
117
118     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
119     {
120         *optr++ = '?';
121         outb--;
122         iptr++;
123         inb--;
124         vlc_iconv (hd, NULL, NULL, NULL, NULL);
125     }
126     *optr = '\0';
127     vlc_iconv_close (hd);
128
129     assert (inb == 0);
130     assert (*iptr == '\0');
131     assert (*optr == '\0');
132     assert (strlen (output) == (size_t)(optr - output));
133     return strdup (output);
134 #elif defined (USE_MB2MB)
135     char *out;
136     int len;
137
138     if (string == NULL)
139         return NULL;
140
141     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
142                                    0, string, -1, NULL, 0);
143     wchar_t wide[len];
144
145     MultiByteToWideChar (from ? CP_UTF8 : CP_ACP, 0, string, -1, wide, len);
146     len = 1 + WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
147     out = malloc (len);
148     if (out == NULL)
149         return NULL;
150
151     WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
152     return out;
153 #else
154     return (char *)string;
155 #endif
156 }
157
158
159 static inline char *locale_dup (const char *string, vlc_bool_t from)
160 {
161 #if defined (USE_ICONV)
162     if (find_charset ())
163         return strdup (string);
164     return locale_fast (string, from);
165 #elif defined (USE_MB2MB)
166     return locale_fast (string, from);
167 #else
168     return strdup (string);
169 #endif
170 }
171
172
173 void LocaleFree (const char *str)
174 {
175 #if defined (USE_ICONV)
176     if (!find_charset ())
177         free ((char *)str);
178 #elif defined (USE_MB2MB)
179     free ((char *)str);
180 #endif
181 }
182
183
184 /**
185  * FromLocale: converts a locale string to UTF-8
186  *
187  * @param locale nul-terminated string to be converted
188  *
189  * @return a nul-terminated UTF-8 string, or NULL in case of error.
190  * To avoid memory leak, you have to pass the result to LocaleFree()
191  * when it is no longer needed.
192  */
193 char *FromLocale (const char *locale)
194 {
195     return locale_fast (locale, VLC_TRUE);
196 }
197
198 char *FromLocaleDup (const char *locale)
199 {
200     return locale_dup (locale, VLC_TRUE);
201 }
202
203
204 /**
205  * ToLocale: converts a UTF-8 string to local system encoding.
206  *
207  * @param utf8 nul-terminated string to be converted
208  *
209  * @return a nul-terminated string, or NULL in case of error.
210  * To avoid memory leak, you have to pass the result to LocaleFree()
211  * when it is no longer needed.
212  */
213 char *ToLocale (const char *utf8)
214 {
215     return locale_fast (utf8, VLC_FALSE);
216 }
217
218
219 static char *ToLocaleDup (const char *utf8)
220 {
221     return locale_dup (utf8, VLC_FALSE);
222 }
223
224
225 /**
226  * utf8_open: open() wrapper for UTF-8 filenames
227  */
228 int utf8_open (const char *filename, int flags, mode_t mode)
229 {
230 #if defined (WIN32) || defined (UNDER_CE)
231     if (GetVersion() < 0x80000000)
232     {
233         /* for Windows NT and above */
234         wchar_t wpath[MAX_PATH + 1];
235
236         if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
237         {
238             errno = ENOENT;
239             return -1;
240         }
241         wpath[MAX_PATH] = L'\0';
242
243         /*
244          * open() cannot open files with non-“ANSI” characters on Windows.
245          * We use _wopen() instead. Same thing for mkdir() and stat().
246          */
247         return _wopen (wpath, flags, mode);
248     }
249 #endif
250     const char *local_name = ToLocale (filename);
251
252     if (local_name == NULL)
253     {
254         errno = ENOENT;
255         return -1;
256     }
257
258     int fd = open (local_name, flags, mode);
259     LocaleFree (local_name);
260     return fd;
261 }
262
263 /**
264  * utf8_fopen: fopen() wrapper for UTF-8 filenames
265  */
266 FILE *utf8_fopen (const char *filename, const char *mode)
267 {
268     int rwflags = 0, oflags = 0;
269     vlc_bool_t append = VLC_FALSE;
270
271     for (const char *ptr = mode; *ptr; ptr++)
272     {
273         switch (*ptr)
274         {
275             case 'r':
276                 rwflags = O_RDONLY;
277                 break;
278
279             case 'a':
280                 rwflags = O_WRONLY;
281                 oflags |= O_CREAT;
282                 append = VLC_TRUE;
283                 break;
284
285             case 'w':
286                 rwflags = O_WRONLY;
287                 oflags |= O_CREAT | O_TRUNC;
288                 break;
289
290             case '+':
291                 rwflags = O_RDWR;
292                 break;
293
294 #ifdef O_TEXT
295             case 't':
296                 oflags |= O_TEXT;
297                 break;
298 #endif
299         }
300     }
301
302     int fd = utf8_open (filename, rwflags | oflags, 0666);
303     if (fd == -1)
304         return NULL;
305
306     if (append && (lseek (fd, 0, SEEK_END) == -1))
307     {
308         close (fd);
309         return NULL;
310     }
311
312     FILE *stream = fdopen (fd, mode);
313     if (stream == NULL)
314         close (fd);
315
316     return stream;
317 }
318
319 /**
320  * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
321  *
322  * @param dirname a UTF-8 string with the name of the directory that you
323  *        want to create.
324  * @return A 0 return value indicates success. A -1 return value indicates an
325  *        error, and an error code is stored in errno
326  */
327 int utf8_mkdir( const char *dirname )
328 {
329 #if defined (UNDER_CE) || defined (WIN32)
330     wchar_t wname[MAX_PATH + 1];
331     char mod[MAX_PATH + 1];
332     int i;
333
334     /* Convert '/' into '\' */
335     for( i = 0; *dirname; i++ )
336     {
337         if( i == MAX_PATH )
338             return -1; /* overflow */
339
340         if( *dirname == '/' )
341             mod[i] = '\\';
342         else
343             mod[i] = *dirname;
344         dirname++;
345
346     }
347     mod[i] = 0;
348
349     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
350     {
351         errno = ENOENT;
352         return -1;
353     }
354     wname[MAX_PATH] = L'\0';
355
356     if( CreateDirectoryW( wname, NULL ) == 0 )
357     {
358         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
359             errno = EEXIST;
360         else
361             errno = ENOENT;
362         return -1;
363     }
364     return 0;
365 #else
366     char *locname = ToLocale( dirname );
367     int res;
368
369     if( locname == NULL )
370     {
371         errno = ENOENT;
372         return -1;
373     }
374     res = mkdir( locname, 0755 );
375
376     LocaleFree( locname );
377     return res;
378 #endif
379 }
380
381 /**
382  * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
383  *
384  * @param dirname UTF-8 representation of the directory name
385  *
386  * @return a pointer to the DIR struct. Release with closedir().
387  */
388 DIR *utf8_opendir( const char *dirname )
389 {
390 #ifdef WIN32
391     wchar_t wname[MAX_PATH + 1];
392
393     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
394     {
395         wname[MAX_PATH] = L'\0';
396         return (DIR *)vlc_wopendir (wname);
397     }
398 #else
399     const char *local_name = ToLocale( dirname );
400
401     if( local_name != NULL )
402     {
403         DIR *dir = opendir( local_name );
404         LocaleFree( local_name );
405         return dir;
406     }
407 #endif
408
409     errno = ENOENT;
410     return NULL;
411 }
412
413 /**
414  * utf8_readdir: a readdir wrapper that returns the name of the next entry
415  *     in the directory as a UTF-8 string.
416  *
417  * @param dir The directory that is being read
418  *
419  * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
420  */
421 char *utf8_readdir( DIR *dir )
422 {
423 #ifdef WIN32
424     struct _wdirent *ent = vlc_wreaddir (dir);
425     if (ent == NULL)
426         return NULL;
427
428     return FromWide (ent->d_name);
429 #else
430     struct dirent *ent;
431
432     ent = readdir( (DIR *)dir );
433     if( ent == NULL )
434         return NULL;
435
436     return vlc_fix_readdir( ent->d_name );
437 #endif
438 }
439
440 static int dummy_select( const char *str )
441 {
442     (void)str;
443     return 1;
444 }
445
446 int utf8_loaddir( DIR *dir, char ***namelist,
447                   int (*select)( const char * ),
448                   int (*compar)( const char **, const char ** ) )
449 {
450     if( select == NULL )
451         select = dummy_select;
452
453     if( dir == NULL )
454         return -1;
455     else
456     {
457         char **tab = NULL;
458         char *entry;
459         unsigned num = 0;
460
461         rewinddir( dir );
462
463         while( ( entry = utf8_readdir( dir ) ) != NULL )
464         {
465             char **newtab;
466
467             if( !select( entry ) )
468             {
469                 free( entry );
470                 continue;
471             }
472
473             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
474             if( newtab == NULL )
475             {
476                 free( entry );
477                 goto error;
478             }
479             tab = newtab;
480             tab[num++] = entry;
481         }
482
483         if( compar != NULL )
484             qsort( tab, num, sizeof( tab[0] ),
485                    (int (*)( const void *, const void *))compar );
486
487         *namelist = tab;
488         return num;
489
490     error:{
491         unsigned i;
492
493         for( i = 0; i < num; i++ )
494             free( tab[i] );
495         if( tab != NULL )
496             free( tab );
497         }
498     }
499     return -1;
500 }
501
502 int utf8_scandir( const char *dirname, char ***namelist,
503                   int (*select)( const char * ),
504                   int (*compar)( const char **, const char ** ) )
505 {
506     DIR *dir = utf8_opendir (dirname);
507     int val = -1;
508
509     if (dir != NULL)
510     {
511         val = utf8_loaddir (dir, namelist, select, compar);
512         closedir (dir);
513     }
514     return val;
515 }
516
517 static int utf8_statEx( const char *filename, struct stat *buf,
518                         vlc_bool_t deref )
519 {
520 #if defined (WIN32) || defined (UNDER_CE)
521     /* retrieve Windows OS version */
522     if( GetVersion() < 0x80000000 )
523     {
524         /* for Windows NT and above */
525         wchar_t wpath[MAX_PATH + 1];
526
527         if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
528         {
529             errno = ENOENT;
530             return -1;
531         }
532         wpath[MAX_PATH] = L'\0';
533
534         return _wstati64( wpath, buf );
535     }
536 #endif
537 #ifdef HAVE_SYS_STAT_H
538     const char *local_name = ToLocale( filename );
539
540     if( local_name != NULL )
541     {
542         int res = deref ? stat( local_name, buf )
543                        : lstat( local_name, buf );
544         LocaleFree( local_name );
545         return res;
546     }
547     errno = ENOENT;
548 #endif
549     return -1;
550 }
551
552
553 int utf8_stat( const char *filename, struct stat *buf)
554 {
555     return utf8_statEx( filename, buf, VLC_TRUE );
556 }
557
558 int utf8_lstat( const char *filename, struct stat *buf)
559 {
560     return utf8_statEx( filename, buf, VLC_FALSE );
561 }
562
563 /**
564  * utf8_*printf: *printf with conversion from UTF-8 to local encoding
565  */
566 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
567 {
568     char *utf8;
569     int res = vasprintf( &utf8, fmt, ap );
570     if( res == -1 )
571         return -1;
572
573     *str = ToLocaleDup( utf8 );
574     free( utf8 );
575     return res;
576 }
577
578 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
579 {
580     char *str;
581     int res = utf8_vasprintf( &str, fmt, ap );
582     if( res == -1 )
583         return -1;
584
585     fputs( str, stream );
586     free( str );
587     return res;
588 }
589
590 int utf8_fprintf( FILE *stream, const char *fmt, ... )
591 {
592     va_list ap;
593     int res;
594
595     va_start( ap, fmt );
596     res = utf8_vfprintf( stream, fmt, ap );
597     va_end( ap );
598     return res;
599 }
600
601
602 static char *CheckUTF8( char *str, char rep )
603 {
604     uint8_t *ptr = (uint8_t *)str;
605     assert (str != NULL);
606
607     for (;;)
608     {
609         uint8_t c = ptr[0];
610         int charlen = -1;
611
612         if (c == '\0')
613             break;
614
615         for (int i = 0; i < 7; i++)
616             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
617             {
618                 charlen = i;
619                 break;
620             }
621
622         switch (charlen)
623         {
624             case 0: // 7-bit ASCII character -> OK
625                 ptr++;
626                 continue;
627
628             case -1: // 1111111x -> error
629             case 1: // continuation byte -> error
630                 goto error;
631         }
632
633         assert (charlen >= 2);
634
635         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
636         for (int i = 1; i < charlen; i++)
637         {
638             assert (cp < (1 << 26));
639             c = ptr[i];
640
641             if ((c == '\0') // unexpected end of string
642              || ((c >> 6) != 2)) // not a continuation byte
643                 goto error;
644
645             cp = (cp << 6) | (ptr[i] & 0x3f);
646         }
647
648         if (cp < 128) // overlong (special case for ASCII)
649             goto error;
650         if (cp < (1u << (5 * charlen - 3))) // overlong
651             goto error;
652
653         ptr += charlen;
654         continue;
655
656     error:
657         if (rep == 0)
658             return NULL;
659         *ptr++ = rep;
660         str = NULL;
661     }
662
663     return str;
664 }
665
666 /**
667  * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
668  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
669  * so we don't try that, even though it would be less disruptive.
670  *
671  * @return str if it was valid UTF-8, NULL if not.
672  */
673 char *EnsureUTF8( char *str )
674 {
675     return CheckUTF8( str, '?' );
676 }
677
678
679 /**
680  * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
681  *
682  * @param str nul-terminated string to be checked
683  *
684  * @return str if it was valid UTF-8, NULL if not.
685  */
686 const char *IsUTF8( const char *str )
687 {
688     return CheckUTF8( (char *)str, 0 );
689 }