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 *****************************************************************************/
33 #include <vlc_charset.h>
34 #include "libvlc.h" /* utf8_mkdir */
42 #include <sys/types.h>
49 #ifdef HAVE_SYS_STAT_H
50 # include <sys/stat.h>
62 # define lstat( a, b ) stat(a, b)
66 /* Define this if the OS always use UTF-8 internally */
67 # define ASSUME_UTF8 1
70 #if defined (ASSUME_UTF8)
72 #elif defined (WIN32) || defined (UNDER_CE)
74 #elif defined (HAVE_ICONV)
77 # error No UTF8 charset conversion implemented on this platform!
80 #if defined (USE_ICONV)
81 static char charset[sizeof ("CSISO11SWEDISHFORNAMES//translit")] = "";
83 static void find_charset_once (void)
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");
96 static int find_charset (void)
98 static pthread_once_t once = PTHREAD_ONCE_INIT;
99 pthread_once (&once, find_charset_once);
100 return !strcmp (charset, "UTF-8");
105 static char *locale_fast (const char *string, vlc_bool_t from)
107 #if defined (USE_ICONV)
109 return (char *)string;
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! */
116 const char *iptr = string;
117 size_t inb = strlen (string);
118 size_t outb = inb * 6 + 1;
119 char output[outb], *optr = output;
124 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
130 vlc_iconv (hd, NULL, NULL, NULL, NULL);
133 vlc_iconv_close (hd);
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)
147 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
148 0, string, -1, NULL, 0);
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);
157 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len, NULL, NULL);
160 return (char *)string;
165 static inline char *locale_dup (const char *string, vlc_bool_t from)
167 #if defined (USE_ICONV)
169 return strdup (string);
170 return locale_fast (string, from);
171 #elif defined (USE_MB2MB)
172 return locale_fast (string, from);
174 return strdup (string);
179 void LocaleFree (const char *str)
181 #if defined (USE_ICONV)
182 if (!find_charset ())
184 #elif defined (USE_MB2MB)
191 * FromLocale: converts a locale string to UTF-8
193 * @param locale nul-terminated string to be converted
195 * @return a nul-terminated UTF-8 string, or NULL in case of error.
196 * To avoid memory leak, you have to pass the result to LocaleFree()
197 * when it is no longer needed.
199 char *FromLocale (const char *locale)
201 return locale_fast (locale, VLC_TRUE);
204 char *FromLocaleDup (const char *locale)
206 return locale_dup (locale, VLC_TRUE);
211 * ToLocale: converts a UTF-8 string to local system encoding.
213 * @param utf8 nul-terminated string to be converted
215 * @return a nul-terminated string, or NULL in case of error.
216 * To avoid memory leak, you have to pass the result to LocaleFree()
217 * when it is no longer needed.
219 char *ToLocale (const char *utf8)
221 return locale_fast (utf8, VLC_FALSE);
225 static char *ToLocaleDup (const char *utf8)
227 return locale_dup (utf8, VLC_FALSE);
232 * utf8_open: open() wrapper for UTF-8 filenames
234 int utf8_open (const char *filename, int flags, mode_t mode)
236 #if defined (WIN32) || defined (UNDER_CE)
237 if (GetVersion() < 0x80000000)
239 /* for Windows NT and above */
240 wchar_t wpath[MAX_PATH + 1];
242 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
247 wpath[MAX_PATH] = L'\0';
250 * open() cannot open files with non-“ANSI” characters on Windows.
251 * We use _wopen() instead. Same thing for mkdir() and stat().
253 return _wopen (wpath, flags, mode);
256 const char *local_name = ToLocale (filename);
258 if (local_name == NULL)
264 int fd = open (local_name, flags, mode);
265 LocaleFree (local_name);
270 * utf8_fopen: fopen() wrapper for UTF-8 filenames
272 FILE *utf8_fopen (const char *filename, const char *mode)
274 int rwflags = 0, oflags = 0;
275 vlc_bool_t append = VLC_FALSE;
277 for (const char *ptr = mode; *ptr; ptr++)
293 oflags |= O_CREAT | O_TRUNC;
308 int fd = utf8_open (filename, rwflags | oflags, 0666);
312 if (append && (lseek (fd, 0, SEEK_END) == -1))
318 FILE *stream = fdopen (fd, mode);
326 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
328 * @param dirname a UTF-8 string with the name of the directory that you
330 * @return A 0 return value indicates success. A -1 return value indicates an
331 * error, and an error code is stored in errno
333 int utf8_mkdir( const char *dirname, mode_t mode )
335 #if defined (UNDER_CE) || defined (WIN32)
336 wchar_t wname[MAX_PATH + 1];
337 char mod[MAX_PATH + 1];
340 /* Convert '/' into '\' */
341 for( i = 0; *dirname; i++ )
344 return -1; /* overflow */
346 if( *dirname == '/' )
355 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
360 wname[MAX_PATH] = L'\0';
362 if( CreateDirectoryW( wname, NULL ) == 0 )
364 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
372 char *locname = ToLocale( dirname );
375 if( locname == NULL )
380 res = mkdir( locname, mode );
382 LocaleFree( locname );
388 * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
390 * @param dirname UTF-8 representation of the directory name
392 * @return a pointer to the DIR struct. Release with closedir().
394 DIR *utf8_opendir( const char *dirname )
397 wchar_t wname[MAX_PATH + 1];
399 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
401 wname[MAX_PATH] = L'\0';
402 return (DIR *)vlc_wopendir (wname);
405 const char *local_name = ToLocale( dirname );
407 if( local_name != NULL )
409 DIR *dir = opendir( local_name );
410 LocaleFree( local_name );
420 * utf8_readdir: a readdir wrapper that returns the name of the next entry
421 * in the directory as a UTF-8 string.
423 * @param dir The directory that is being read
425 * @return a UTF-8 string of the directory entry. Use free() to free this memory.
427 char *utf8_readdir( DIR *dir )
430 struct _wdirent *ent = vlc_wreaddir (dir);
434 return FromWide (ent->d_name);
438 ent = readdir( (DIR *)dir );
442 return vlc_fix_readdir( ent->d_name );
446 static int dummy_select( const char *str )
452 int utf8_loaddir( DIR *dir, char ***namelist,
453 int (*select)( const char * ),
454 int (*compar)( const char **, const char ** ) )
457 select = dummy_select;
469 while( ( entry = utf8_readdir( dir ) ) != NULL )
473 if( !select( entry ) )
479 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
490 qsort( tab, num, sizeof( tab[0] ),
491 (int (*)( const void *, const void *))compar );
499 for( i = 0; i < num; i++ )
508 int utf8_scandir( const char *dirname, char ***namelist,
509 int (*select)( const char * ),
510 int (*compar)( const char **, const char ** ) )
512 DIR *dir = utf8_opendir (dirname);
517 val = utf8_loaddir (dir, namelist, select, compar);
523 static int utf8_statEx( const char *filename, struct stat *buf,
526 #if defined (WIN32) || defined (UNDER_CE)
527 /* retrieve Windows OS version */
528 if( GetVersion() < 0x80000000 )
530 /* for Windows NT and above */
531 wchar_t wpath[MAX_PATH + 1];
533 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
538 wpath[MAX_PATH] = L'\0';
540 return _wstati64( wpath, buf );
543 #ifdef HAVE_SYS_STAT_H
544 const char *local_name = ToLocale( filename );
546 if( local_name != NULL )
548 int res = deref ? stat( local_name, buf )
549 : lstat( local_name, buf );
550 LocaleFree( local_name );
559 int utf8_stat( const char *filename, struct stat *buf)
561 return utf8_statEx( filename, buf, VLC_TRUE );
564 int utf8_lstat( const char *filename, struct stat *buf)
566 return utf8_statEx( filename, buf, VLC_FALSE );
570 * utf8_unlink: Calls unlink() after conversion of file name to OS locale
572 * @param filename a UTF-8 string with the name of the file you want to delete.
573 * @return A 0 return value indicates success. A -1 return value indicates an
574 * error, and an error code is stored in errno
576 int utf8_unlink( const char *filename )
578 #if defined (WIN32) || defined (UNDER_CE)
579 if( GetVersion() < 0x80000000 )
581 /* for Windows NT and above */
582 wchar_t wpath[MAX_PATH + 1];
584 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
589 wpath[MAX_PATH] = L'\0';
592 * unlink() cannot open files with non-“ANSI” characters on Windows.
593 * We use _wunlink() instead.
595 return _wunlink( wpath );
598 const char *local_name = ToLocale( filename );
600 if( local_name == NULL )
606 int ret = unlink( local_name );
607 LocaleFree( local_name );
614 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
616 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
619 int res = vasprintf( &utf8, fmt, ap );
623 *str = ToLocaleDup( utf8 );
628 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
631 int res = utf8_vasprintf( &str, fmt, ap );
635 fputs( str, stream );
640 int utf8_fprintf( FILE *stream, const char *fmt, ... )
646 res = utf8_vfprintf( stream, fmt, ap );
652 static char *CheckUTF8( char *str, char rep )
654 uint8_t *ptr = (uint8_t *)str;
655 assert (str != NULL);
665 for (int i = 0; i < 7; i++)
666 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
674 case 0: // 7-bit ASCII character -> OK
678 case -1: // 1111111x -> error
679 case 1: // continuation byte -> error
683 assert (charlen >= 2);
685 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
686 for (int i = 1; i < charlen; i++)
688 assert (cp < (1 << 26));
691 if ((c == '\0') // unexpected end of string
692 || ((c >> 6) != 2)) // not a continuation byte
695 cp = (cp << 6) | (ptr[i] & 0x3f);
698 if (cp < 128) // overlong (special case for ASCII)
700 if (cp < (1u << (5 * charlen - 3))) // overlong
717 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
718 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
719 * so we don't try that, even though it would be less disruptive.
721 * @return str if it was valid UTF-8, NULL if not.
723 char *EnsureUTF8( char *str )
725 return CheckUTF8( str, '?' );
730 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
732 * @param str nul-terminated string to be checked
734 * @return str if it was valid UTF-8, NULL if not.
736 const char *IsUTF8( const char *str )
738 return CheckUTF8( (char *)str, 0 );