]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Remove duplication and do the NULL text before dereferencing (CID 232)
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33 #include "libvlc.h" /* utf8_mkdir */
34
35 #include <assert.h>
36
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <errno.h>
41 #include <sys/types.h>
42 #ifdef HAVE_DIRENT_H
43 #  include <dirent.h>
44 #endif
45 #ifdef UNDER_CE
46 #  include <tchar.h>
47 #endif
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
50 #endif
51 #ifdef HAVE_FCNTL_H
52 # include <fcntl.h>
53 #endif
54 #ifdef WIN32
55 # include <io.h>
56 #else
57 # include <unistd.h>
58 #endif
59
60 #ifndef HAVE_LSTAT
61 # define lstat( a, b ) stat(a, b)
62 #endif
63
64 #ifdef __APPLE__
65 /* Define this if the OS always use UTF-8 internally */
66 # define ASSUME_UTF8 1
67 #endif
68
69 #if defined (ASSUME_UTF8)
70 /* Cool */
71 #elif defined (WIN32) || defined (UNDER_CE)
72 # define USE_MB2MB 1
73 #elif defined (HAVE_ICONV)
74 # define USE_ICONV 1
75 #else
76 # error No UTF8 charset conversion implemented on this platform!
77 #endif
78
79 #if defined (USE_ICONV)
80 # include <langinfo.h>
81 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
82
83 static void find_charset_once (void)
84 {
85     strlcpy (charset, nl_langinfo (CODESET), sizeof (charset));
86     if (!strcasecmp (charset, "ASCII")
87      || !strcasecmp (charset, "ANSI_X3.4-1968"))
88         strcpy (charset, "UTF-8"); /* superset... */
89 }
90
91 static int find_charset (void)
92 {
93     static pthread_once_t once = PTHREAD_ONCE_INIT;
94     pthread_once (&once, find_charset_once);
95     return !strcasecmp (charset, "UTF-8");
96 }
97 #endif
98
99
100 static char *locale_fast (const char *string, bool from)
101 {
102     if( string == NULL )
103         return NULL;
104
105 #if defined (USE_ICONV)
106     if (find_charset ())
107         return (char *)string;
108
109     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
110                                      from ? charset : "UTF-8");
111     if (hd == (vlc_iconv_t)(-1))
112         return NULL; /* Uho! */
113
114     const char *iptr = string;
115     size_t inb = strlen (string);
116     size_t outb = inb * 6 + 1;
117     char output[outb], *optr = output;
118
119     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
120     {
121         *optr++ = '?';
122         outb--;
123         iptr++;
124         inb--;
125         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
126     }
127     *optr = '\0';
128     vlc_iconv_close (hd);
129
130     assert (inb == 0);
131     assert (*iptr == '\0');
132     assert (*optr == '\0');
133     assert (strlen (output) == (size_t)(optr - output));
134     return strdup (output);
135 #elif defined (USE_MB2MB)
136     char *out;
137     int len;
138
139     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
140                                    0, string, -1, NULL, 0);
141     wchar_t wide[len];
142
143     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
144     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
145                                    NULL, 0, NULL, NULL);
146     out = malloc (len);
147     if (out == NULL)
148         return NULL;
149
150     WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
151                          NULL, NULL);
152     return out;
153 #else
154     (void)from;
155     return (char *)string;
156 #endif
157 }
158
159
160 static inline char *locale_dup (const char *string, bool from)
161 {
162     assert( string );
163
164 #if defined (USE_ICONV)
165     if (find_charset ())
166         return strdup (string);
167     return locale_fast (string, from);
168 #elif defined (USE_MB2MB)
169     return locale_fast (string, from);
170 #else
171     (void)from;
172     return strdup (string);
173 #endif
174 }
175
176 /**
177  * Releases (if needed) a localized or uniformized string.
178  * @param str non-NULL return value from FromLocale() or ToLocale().
179  */
180 void LocaleFree (const char *str)
181 {
182 #if defined (USE_ICONV)
183     if (!find_charset ())
184         free ((char *)str);
185 #elif defined (USE_MB2MB)
186     free ((char *)str);
187 #else
188     (void)str;
189 #endif
190 }
191
192
193 /**
194  * Converts a string from the system locale character encoding to UTF-8.
195  *
196  * @param locale nul-terminated string to convert
197  *
198  * @return a nul-terminated UTF-8 string, or NULL in case of error.
199  * To avoid memory leak, you have to pass the result to LocaleFree()
200  * when it is no longer needed.
201  */
202 char *FromLocale (const char *locale)
203 {
204     return locale_fast (locale, true);
205 }
206
207 /**
208  * converts a string from the system locale character encoding to utf-8,
209  * the result is always allocated on the heap.
210  *
211  * @param locale nul-terminated string to convert
212  *
213  * @return a nul-terminated utf-8 string, or null in case of error.
214  * The result must be freed using free() - as with the strdup() function.
215  */
216 char *FromLocaleDup (const char *locale)
217 {
218     return locale_dup (locale, true);
219 }
220
221
222 /**
223  * ToLocale: converts an UTF-8 string to local system encoding.
224  *
225  * @param utf8 nul-terminated string to be converted
226  *
227  * @return a nul-terminated string, or NULL in case of error.
228  * To avoid memory leak, you have to pass the result to LocaleFree()
229  * when it is no longer needed.
230  */
231 char *ToLocale (const char *utf8)
232 {
233     return locale_fast (utf8, false);
234 }
235
236
237 /**
238  * converts a string from UTF-8 to the system locale character encoding,
239  * the result is always allocated on the heap.
240  *
241  * @param utf8 nul-terminated string to convert
242  *
243  * @return a nul-terminated string, or null in case of error.
244  * The result must be freed using free() - as with the strdup() function.
245  */
246 char *ToLocaleDup (const char *utf8)
247 {
248     return locale_dup (utf8, false);
249 }
250
251
252 /**
253  * Opens a system file handle using UTF-8 paths.
254  *
255  * @param filename file path to open (with UTF-8 encoding)
256  * @param flags open() flags, see the C library open() documentation
257  * @param mode file permissions if creating a new file
258  * @return a file handle on success, -1 on error (see errno).
259  */
260 int utf8_open (const char *filename, int flags, mode_t mode)
261 {
262 #ifdef UNDER_CE
263     /*_open translates to wchar internally on WinCE*/
264     return _open (filename, flags, mode);
265 #elif defined (WIN32)
266     /* for Windows NT and above */
267     wchar_t wpath[MAX_PATH + 1];
268
269     if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
270     {
271         errno = ENOENT;
272         return -1;
273     }
274     wpath[MAX_PATH] = L'\0';
275
276     /*
277         * open() cannot open files with non-“ANSI” characters on Windows.
278         * We use _wopen() instead. Same thing for mkdir() and stat().
279         */
280     return _wopen (wpath, flags, mode);
281
282 #endif
283     const char *local_name = ToLocale (filename);
284
285     if (local_name == NULL)
286     {
287         errno = ENOENT;
288         return -1;
289     }
290
291     int fd = open (local_name, flags, mode);
292     LocaleFree (local_name);
293     return fd;
294 }
295
296 /**
297  * Opens a FILE pointer using UTF-8 filenames.
298  * @param filename file path, using UTF-8 encoding
299  * @param mode fopen file open mode
300  * @return NULL on error, an open FILE pointer on success.
301  */
302 FILE *utf8_fopen (const char *filename, const char *mode)
303 {
304     int rwflags = 0, oflags = 0;
305     bool append = false;
306
307     for (const char *ptr = mode; *ptr; ptr++)
308     {
309         switch (*ptr)
310         {
311             case 'r':
312                 rwflags = O_RDONLY;
313                 break;
314
315             case 'a':
316                 rwflags = O_WRONLY;
317                 oflags |= O_CREAT;
318                 append = true;
319                 break;
320
321             case 'w':
322                 rwflags = O_WRONLY;
323                 oflags |= O_CREAT | O_TRUNC;
324                 break;
325
326             case '+':
327                 rwflags = O_RDWR;
328                 break;
329
330 #ifdef O_TEXT
331             case 't':
332                 oflags |= O_TEXT;
333                 break;
334 #endif
335         }
336     }
337
338     int fd = utf8_open (filename, rwflags | oflags, 0666);
339     if (fd == -1)
340         return NULL;
341
342     if (append && (lseek (fd, 0, SEEK_END) == -1))
343     {
344         close (fd);
345         return NULL;
346     }
347
348     FILE *stream = fdopen (fd, mode);
349     if (stream == NULL)
350         close (fd);
351
352     return stream;
353 }
354
355 /**
356  * Creates a directory using UTF-8 paths.
357  *
358  * @param dirname a UTF-8 string with the name of the directory that you
359  *        want to create.
360  * @param mode directory permissions
361  * @return 0 on success, -1 on error (see errno).
362  */
363 int utf8_mkdir( const char *dirname, mode_t mode )
364 {
365 #if defined (UNDER_CE) || defined (WIN32)
366     VLC_UNUSED( mode );
367
368     wchar_t wname[MAX_PATH + 1];
369     char mod[MAX_PATH + 1];
370     int i;
371
372     /* Convert '/' into '\' */
373     for( i = 0; *dirname; i++ )
374     {
375         if( i == MAX_PATH )
376             return -1; /* overflow */
377
378         if( *dirname == '/' )
379             mod[i] = '\\';
380         else
381             mod[i] = *dirname;
382         dirname++;
383
384     }
385     mod[i] = 0;
386
387     if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
388     {
389         errno = ENOENT;
390         return -1;
391     }
392     wname[MAX_PATH] = L'\0';
393
394     if( CreateDirectoryW( wname, NULL ) == 0 )
395     {
396         if( GetLastError( ) == ERROR_ALREADY_EXISTS )
397             errno = EEXIST;
398         else
399             errno = ENOENT;
400         return -1;
401     }
402     return 0;
403 #else
404     char *locname = ToLocale( dirname );
405     int res;
406
407     if( locname == NULL )
408     {
409         errno = ENOENT;
410         return -1;
411     }
412     res = mkdir( locname, mode );
413
414     LocaleFree( locname );
415     return res;
416 #endif
417 }
418
419 /**
420  * Opens a DIR pointer using UTF-8 paths
421  *
422  * @param dirname UTF-8 representation of the directory name
423  * @return a pointer to the DIR struct, or NULL in case of error.
424  * Release with standard closedir().
425  */
426 DIR *utf8_opendir( const char *dirname )
427 {
428 #ifdef WIN32
429     wchar_t wname[MAX_PATH + 1];
430
431     if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
432     {
433         wname[MAX_PATH] = L'\0';
434         return (DIR *)vlc_wopendir (wname);
435     }
436 #else
437     const char *local_name = ToLocale( dirname );
438
439     if( local_name != NULL )
440     {
441         DIR *dir = opendir( local_name );
442         LocaleFree( local_name );
443         return dir;
444     }
445 #endif
446
447     errno = ENOENT;
448     return NULL;
449 }
450
451 /**
452  * Reads the next file name from an open directory.
453  *
454  * @param dir The directory that is being read
455  *
456  * @return a UTF-8 string of the directory entry.
457  * Use free() to free this memory.
458  */
459 char *utf8_readdir( DIR *dir )
460 {
461 #ifdef WIN32
462     struct _wdirent *ent = vlc_wreaddir (dir);
463     if (ent == NULL)
464         return NULL;
465
466     return FromWide (ent->d_name);
467 #else
468     struct dirent *ent;
469
470     ent = readdir( (DIR *)dir );
471     if( ent == NULL )
472         return NULL;
473
474     return vlc_fix_readdir( ent->d_name );
475 #endif
476 }
477
478 static int dummy_select( const char *str )
479 {
480     (void)str;
481     return 1;
482 }
483
484 /**
485  * Does the same as utf8_scandir(), but takes an open directory pointer
486  * instead of a directory path.
487  */
488 int utf8_loaddir( DIR *dir, char ***namelist,
489                   int (*select)( const char * ),
490                   int (*compar)( const char **, const char ** ) )
491 {
492     if( select == NULL )
493         select = dummy_select;
494
495     if( dir == NULL )
496         return -1;
497     else
498     {
499         char **tab = NULL;
500         char *entry;
501         unsigned num = 0;
502
503         rewinddir( dir );
504
505         while( ( entry = utf8_readdir( dir ) ) != NULL )
506         {
507             char **newtab;
508
509             if( !select( entry ) )
510             {
511                 free( entry );
512                 continue;
513             }
514
515             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
516             if( newtab == NULL )
517             {
518                 free( entry );
519                 goto error;
520             }
521             tab = newtab;
522             tab[num++] = entry;
523         }
524
525         if( compar != NULL )
526             qsort( tab, num, sizeof( tab[0] ),
527                    (int (*)( const void *, const void *))compar );
528
529         *namelist = tab;
530         return num;
531
532     error:{
533         unsigned i;
534
535         for( i = 0; i < num; i++ )
536             free( tab[i] );
537         if( tab != NULL )
538             free( tab );
539         }
540     }
541     return -1;
542 }
543
544 /**
545  * Selects file entries from a directory, as GNU C scandir(), yet using
546  * UTF-8 file names.
547  *
548  * @param dirname UTF-8 diretory path
549  * @param pointer [OUT] pointer set, on succesful completion, to the address
550  * of a table of UTF-8 filenames. All filenames must be freed with free().
551  * The table itself must be freed with free() as well.
552  *
553  * @return How many file names were selected (possibly 0),
554  * or -1 in case of error.
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                         bool deref )
573 {
574 #ifdef UNDER_CE
575     /*_stat translates to wchar internally on WinCE*/
576     return _stat( filename, buf );
577 #elif defined (WIN32)
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  * Finds file/inode informations, as stat().
608  * Consider usign fstat() instead, if possible.
609  *
610  * @param filename UTF-8 file path
611  */
612 int utf8_stat( const char *filename, struct stat *buf)
613 {
614     return utf8_statEx( filename, buf, true );
615 }
616
617 /**
618  * Finds file/inode informations, as lstat().
619  * Consider usign fstat() instead, if possible.
620  *
621  * @param filename UTF-8 file path
622  */
623 int utf8_lstat( const char *filename, struct stat *buf)
624 {
625     return utf8_statEx( filename, buf, false );
626 }
627
628 /**
629  * Removes a file.
630  *
631  * @param filename a UTF-8 string with the name of the file you want to delete.
632  * @return A 0 return value indicates success. A -1 return value indicates an
633  *        error, and an error code is stored in errno
634  */
635 int utf8_unlink( const char *filename )
636 {
637 #ifdef UNDER_CE
638     /*_open translates to wchar internally on WinCE*/
639     return _unlink( filename );
640 #elif defined (WIN32)
641     /* for Windows NT and above */
642     wchar_t wpath[MAX_PATH + 1];
643
644     if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
645     {
646         errno = ENOENT;
647         return -1;
648     }
649     wpath[MAX_PATH] = L'\0';
650
651     /*
652         * unlink() cannot open files with non-“ANSI” characters on Windows.
653         * We use _wunlink() instead.
654         */
655     return _wunlink( wpath );
656 #endif
657     const char *local_name = ToLocale( filename );
658
659     if( local_name == NULL )
660     {
661         errno = ENOENT;
662         return -1;
663     }
664
665     int ret = unlink( local_name );
666     LocaleFree( local_name );
667     return ret;
668 }
669
670
671
672 /**
673  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
674  * appropriate conversion to local encoding.
675  */
676 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
677 {
678     char *utf8;
679     int res = vasprintf( &utf8, fmt, ap );
680     if( res == -1 )
681         return -1;
682
683     *str = ToLocaleDup( utf8 );
684     free( utf8 );
685     return res;
686 }
687
688 /**
689  * Formats an UTF-8 string as vfprintf(), then print it, with
690  * appropriate conversion to local encoding.
691  */
692 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
693 {
694     char *str;
695     int res = utf8_vasprintf( &str, fmt, ap );
696     if( res == -1 )
697         return -1;
698
699     fputs( str, stream );
700     free( str );
701     return res;
702 }
703
704 /**
705  * Formats an UTF-8 string as fprintf(), then print it, with
706  * appropriate conversion to local encoding.
707  */
708 int utf8_fprintf( FILE *stream, const char *fmt, ... )
709 {
710     va_list ap;
711     int res;
712
713     va_start( ap, fmt );
714     res = utf8_vfprintf( stream, fmt, ap );
715     va_end( ap );
716     return res;
717 }
718
719
720 static char *CheckUTF8( char *str, char rep )
721 {
722     uint8_t *ptr = (uint8_t *)str;
723     assert (str != NULL);
724
725     for (;;)
726     {
727         uint8_t c = ptr[0];
728         int charlen = -1;
729
730         if (c == '\0')
731             break;
732
733         for (int i = 0; i < 7; i++)
734             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
735             {
736                 charlen = i;
737                 break;
738             }
739
740         switch (charlen)
741         {
742             case 0: // 7-bit ASCII character -> OK
743                 ptr++;
744                 continue;
745
746             case -1: // 1111111x -> error
747             case 1: // continuation byte -> error
748                 goto error;
749         }
750
751         assert (charlen >= 2);
752
753         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
754         for (int i = 1; i < charlen; i++)
755         {
756             assert (cp < (1 << 26));
757             c = ptr[i];
758
759             if ((c == '\0') // unexpected end of string
760              || ((c >> 6) != 2)) // not a continuation byte
761                 goto error;
762
763             cp = (cp << 6) | (ptr[i] & 0x3f);
764         }
765
766         if (cp < 128) // overlong (special case for ASCII)
767             goto error;
768         if (cp < (1u << (5 * charlen - 3))) // overlong
769             goto error;
770
771         ptr += charlen;
772         continue;
773
774     error:
775         if (rep == 0)
776             return NULL;
777         *ptr++ = rep;
778         str = NULL;
779     }
780
781     return str;
782 }
783
784 /**
785  * Replaces invalid/overlong UTF-8 sequences with question marks.
786  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
787  * so we don't try that, even though it would be less disruptive.
788  *
789  * @return str if it was valid UTF-8, NULL if not.
790  */
791 char *EnsureUTF8( char *str )
792 {
793     return CheckUTF8( str, '?' );
794 }
795
796
797 /**
798  * Checks whether a string is a valid UTF-8 byte sequence.
799  *
800  * @param str nul-terminated string to be checked
801  *
802  * @return str if it was valid UTF-8, NULL if not.
803  */
804 const char *IsUTF8( const char *str )
805 {
806     return CheckUTF8( (char *)str, 0 );
807 }