1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2006 Rémi Denis-Courmont
8 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
29 #include <vlc_charset.h>
30 #include "libvlc.h" /* utf8_mkdir */
38 #include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
58 # define lstat( a, b ) stat(a, b)
62 /* Define this if the OS always use UTF-8 internally */
63 # define ASSUME_UTF8 1
66 #if defined (ASSUME_UTF8)
68 #elif defined (WIN32) || defined (UNDER_CE)
70 #elif defined (HAVE_ICONV)
73 # error No UTF8 charset conversion implemented on this platform!
76 #if defined (USE_ICONV)
77 static char charset[sizeof ("CSISO11SWEDISHFORNAMES//translit")] = "";
79 static void find_charset_once (void)
82 if (vlc_current_charset (&psz_charset)
83 || (psz_charset == NULL)
84 || (strcmp (psz_charset, "ASCII") == 0)
85 || ((size_t)snprintf (charset, sizeof (charset), "%s//translit",
86 psz_charset) >= sizeof (charset)))
87 strcpy (charset, "UTF-8");
92 static int find_charset (void)
94 static pthread_once_t once = PTHREAD_ONCE_INIT;
95 pthread_once (&once, find_charset_once);
96 return !strcmp (charset, "UTF-8");
101 static char *locale_fast (const char *string, vlc_bool_t from)
103 #if defined (USE_ICONV)
105 return (char *)string;
107 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
108 from ? charset : "UTF-8");
109 if (hd == (vlc_iconv_t)(-1))
110 return strdup (string); /* Uho! */
112 const char *iptr = string;
113 size_t inb = strlen (string);
114 size_t outb = inb * 6 + 1;
115 char output[outb], *optr = output;
120 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
126 vlc_iconv (hd, NULL, NULL, NULL, NULL);
129 vlc_iconv_close (hd);
132 assert (*iptr == '\0');
133 assert (*optr == '\0');
134 assert (strlen (output) == (size_t)(optr - output));
135 return strdup (output);
136 #elif defined (USE_MB2MB)
143 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
144 0, string, -1, NULL, 0);
147 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
148 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, NULL, 0, NULL, NULL);
153 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len, NULL, NULL);
156 return (char *)string;
161 static inline char *locale_dup (const char *string, vlc_bool_t from)
163 #if defined (USE_ICONV)
165 return strdup (string);
166 return locale_fast (string, from);
167 #elif defined (USE_MB2MB)
168 return locale_fast (string, from);
170 return strdup (string);
175 void LocaleFree (const char *str)
177 #if defined (USE_ICONV)
178 if (!find_charset ())
180 #elif defined (USE_MB2MB)
187 * FromLocale: converts a locale string to UTF-8
189 * @param locale nul-terminated string to be converted
191 * @return a nul-terminated UTF-8 string, or NULL in case of error.
192 * To avoid memory leak, you have to pass the result to LocaleFree()
193 * when it is no longer needed.
195 char *FromLocale (const char *locale)
197 return locale_fast (locale, VLC_TRUE);
200 char *FromLocaleDup (const char *locale)
202 return locale_dup (locale, VLC_TRUE);
207 * ToLocale: converts a UTF-8 string to local system encoding.
209 * @param utf8 nul-terminated string to be converted
211 * @return a nul-terminated string, or NULL in case of error.
212 * To avoid memory leak, you have to pass the result to LocaleFree()
213 * when it is no longer needed.
215 char *ToLocale (const char *utf8)
217 return locale_fast (utf8, VLC_FALSE);
221 static char *ToLocaleDup (const char *utf8)
223 return locale_dup (utf8, VLC_FALSE);
228 * utf8_open: open() wrapper for UTF-8 filenames
230 int utf8_open (const char *filename, int flags, mode_t mode)
232 #if defined (WIN32) || defined (UNDER_CE)
233 if (GetVersion() < 0x80000000)
235 /* for Windows NT and above */
236 wchar_t wpath[MAX_PATH + 1];
238 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
243 wpath[MAX_PATH] = L'\0';
246 * open() cannot open files with non-“ANSI” characters on Windows.
247 * We use _wopen() instead. Same thing for mkdir() and stat().
249 return _wopen (wpath, flags, mode);
252 const char *local_name = ToLocale (filename);
254 if (local_name == NULL)
260 int fd = open (local_name, flags, mode);
261 LocaleFree (local_name);
266 * utf8_fopen: fopen() wrapper for UTF-8 filenames
268 FILE *utf8_fopen (const char *filename, const char *mode)
270 int rwflags = 0, oflags = 0;
271 vlc_bool_t append = VLC_FALSE;
273 for (const char *ptr = mode; *ptr; ptr++)
289 oflags |= O_CREAT | O_TRUNC;
304 int fd = utf8_open (filename, rwflags | oflags, 0666);
308 if (append && (lseek (fd, 0, SEEK_END) == -1))
314 FILE *stream = fdopen (fd, mode);
322 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
324 * @param dirname a UTF-8 string with the name of the directory that you
326 * @return A 0 return value indicates success. A -1 return value indicates an
327 * error, and an error code is stored in errno
329 int utf8_mkdir( const char *dirname, mode_t mode )
331 #if defined (UNDER_CE) || defined (WIN32)
332 wchar_t wname[MAX_PATH + 1];
333 char mod[MAX_PATH + 1];
336 /* Convert '/' into '\' */
337 for( i = 0; *dirname; i++ )
340 return -1; /* overflow */
342 if( *dirname == '/' )
351 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
356 wname[MAX_PATH] = L'\0';
358 if( CreateDirectoryW( wname, NULL ) == 0 )
360 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
368 char *locname = ToLocale( dirname );
371 if( locname == NULL )
376 res = mkdir( locname, mode );
378 LocaleFree( locname );
384 * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
386 * @param dirname UTF-8 representation of the directory name
388 * @return a pointer to the DIR struct. Release with closedir().
390 DIR *utf8_opendir( const char *dirname )
393 wchar_t wname[MAX_PATH + 1];
395 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
397 wname[MAX_PATH] = L'\0';
398 return (DIR *)vlc_wopendir (wname);
401 const char *local_name = ToLocale( dirname );
403 if( local_name != NULL )
405 DIR *dir = opendir( local_name );
406 LocaleFree( local_name );
416 * utf8_readdir: a readdir wrapper that returns the name of the next entry
417 * in the directory as a UTF-8 string.
419 * @param dir The directory that is being read
421 * @return a UTF-8 string of the directory entry. Use free() to free this memory.
423 char *utf8_readdir( DIR *dir )
426 struct _wdirent *ent = vlc_wreaddir (dir);
430 return FromWide (ent->d_name);
434 ent = readdir( (DIR *)dir );
438 return vlc_fix_readdir( ent->d_name );
442 static int dummy_select( const char *str )
448 int utf8_loaddir( DIR *dir, char ***namelist,
449 int (*select)( const char * ),
450 int (*compar)( const char **, const char ** ) )
453 select = dummy_select;
465 while( ( entry = utf8_readdir( dir ) ) != NULL )
469 if( !select( entry ) )
475 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
486 qsort( tab, num, sizeof( tab[0] ),
487 (int (*)( const void *, const void *))compar );
495 for( i = 0; i < num; i++ )
504 int utf8_scandir( const char *dirname, char ***namelist,
505 int (*select)( const char * ),
506 int (*compar)( const char **, const char ** ) )
508 DIR *dir = utf8_opendir (dirname);
513 val = utf8_loaddir (dir, namelist, select, compar);
519 static int utf8_statEx( const char *filename, struct stat *buf,
522 #if defined (WIN32) || defined (UNDER_CE)
523 /* retrieve Windows OS version */
524 if( GetVersion() < 0x80000000 )
526 /* for Windows NT and above */
527 wchar_t wpath[MAX_PATH + 1];
529 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
534 wpath[MAX_PATH] = L'\0';
536 return _wstati64( wpath, buf );
539 #ifdef HAVE_SYS_STAT_H
540 const char *local_name = ToLocale( filename );
542 if( local_name != NULL )
544 int res = deref ? stat( local_name, buf )
545 : lstat( local_name, buf );
546 LocaleFree( local_name );
555 int utf8_stat( const char *filename, struct stat *buf)
557 return utf8_statEx( filename, buf, VLC_TRUE );
560 int utf8_lstat( const char *filename, struct stat *buf)
562 return utf8_statEx( filename, buf, VLC_FALSE );
566 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
568 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
571 int res = vasprintf( &utf8, fmt, ap );
575 *str = ToLocaleDup( utf8 );
580 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
583 int res = utf8_vasprintf( &str, fmt, ap );
587 fputs( str, stream );
592 int utf8_fprintf( FILE *stream, const char *fmt, ... )
598 res = utf8_vfprintf( stream, fmt, ap );
604 static char *CheckUTF8( char *str, char rep )
606 uint8_t *ptr = (uint8_t *)str;
607 assert (str != NULL);
617 for (int i = 0; i < 7; i++)
618 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
626 case 0: // 7-bit ASCII character -> OK
630 case -1: // 1111111x -> error
631 case 1: // continuation byte -> error
635 assert (charlen >= 2);
637 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
638 for (int i = 1; i < charlen; i++)
640 assert (cp < (1 << 26));
643 if ((c == '\0') // unexpected end of string
644 || ((c >> 6) != 2)) // not a continuation byte
647 cp = (cp << 6) | (ptr[i] & 0x3f);
650 if (cp < 128) // overlong (special case for ASCII)
652 if (cp < (1u << (5 * charlen - 3))) // overlong
669 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
670 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
671 * so we don't try that, even though it would be less disruptive.
673 * @return str if it was valid UTF-8, NULL if not.
675 char *EnsureUTF8( char *str )
677 return CheckUTF8( str, '?' );
682 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
684 * @param str nul-terminated string to be checked
686 * @return str if it was valid UTF-8, NULL if not.
688 const char *IsUTF8( const char *str )
690 return CheckUTF8( (char *)str, 0 );