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, bool 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);
161 return (char *)string;
166 static inline char *locale_dup (const char *string, bool from)
168 #if defined (USE_ICONV)
170 return strdup (string);
171 return locale_fast (string, from);
172 #elif defined (USE_MB2MB)
173 return locale_fast (string, from);
176 return strdup (string);
181 * Releases (if needed) a localized or uniformized string.
182 * @param str non-NULL return value from FromLocale() or ToLocale().
184 void LocaleFree (const char *str)
186 #if defined (USE_ICONV)
187 if (!find_charset ())
189 #elif defined (USE_MB2MB)
198 * Converts a string from the system locale character encoding to UTF-8.
200 * @param locale nul-terminated string to convert
202 * @return a nul-terminated UTF-8 string, or NULL in case of error.
203 * To avoid memory leak, you have to pass the result to LocaleFree()
204 * when it is no longer needed.
206 char *FromLocale (const char *locale)
208 return locale_fast (locale, true);
212 * converts a string from the system locale character encoding to utf-8,
213 * the result is always allocated on the heap.
215 * @param locale nul-terminated string to convert
217 * @return a nul-terminated utf-8 string, or null in case of error.
218 * The result must be freed using free() - as with the strdup() function.
220 char *FromLocaleDup (const char *locale)
222 return locale_dup (locale, true);
227 * ToLocale: converts an UTF-8 string to local system encoding.
229 * @param utf8 nul-terminated string to be converted
231 * @return a nul-terminated string, or NULL in case of error.
232 * To avoid memory leak, you have to pass the result to LocaleFree()
233 * when it is no longer needed.
235 char *ToLocale (const char *utf8)
237 return locale_fast (utf8, false);
242 * converts a string from UTF-8 to the system locale character encoding,
243 * the result is always allocated on the heap.
245 * @param utf8 nul-terminated string to convert
247 * @return a nul-terminated string, or null in case of error.
248 * The result must be freed using free() - as with the strdup() function.
250 char *ToLocaleDup (const char *utf8)
252 return locale_dup (utf8, false);
257 * Opens a system file handle using UTF-8 paths.
259 * @param filename file path to open (with UTF-8 encoding)
260 * @param flags open() flags, see the C library open() documentation
261 * @param mode file permissions if creating a new file
262 * @return a file handle on success, -1 on error (see errno).
264 int utf8_open (const char *filename, int flags, mode_t mode)
266 #if defined (WIN32) || defined (UNDER_CE)
267 if (GetVersion() < 0x80000000)
269 /* for Windows NT and above */
270 wchar_t wpath[MAX_PATH + 1];
272 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
277 wpath[MAX_PATH] = L'\0';
280 * open() cannot open files with non-“ANSI” characters on Windows.
281 * We use _wopen() instead. Same thing for mkdir() and stat().
283 return _wopen (wpath, flags, mode);
286 const char *local_name = ToLocale (filename);
288 if (local_name == NULL)
294 int fd = open (local_name, flags, mode);
295 LocaleFree (local_name);
300 * Opens a FILE pointer using UTF-8 filenames.
301 * @param filename file path, using UTF-8 encoding
302 * @param mode fopen file open mode
303 * @return NULL on error, an open FILE pointer on success.
305 FILE *utf8_fopen (const char *filename, const char *mode)
307 int rwflags = 0, oflags = 0;
310 for (const char *ptr = mode; *ptr; ptr++)
326 oflags |= O_CREAT | O_TRUNC;
341 int fd = utf8_open (filename, rwflags | oflags, 0666);
345 if (append && (lseek (fd, 0, SEEK_END) == -1))
351 FILE *stream = fdopen (fd, mode);
359 * Creates a directory using UTF-8 paths.
361 * @param dirname a UTF-8 string with the name of the directory that you
363 * @param mode directory permissions
364 * @return 0 on success, -1 on error (see errno).
366 int utf8_mkdir( const char *dirname, mode_t mode )
368 #if defined (UNDER_CE) || defined (WIN32)
371 wchar_t wname[MAX_PATH + 1];
372 char mod[MAX_PATH + 1];
375 /* Convert '/' into '\' */
376 for( i = 0; *dirname; i++ )
379 return -1; /* overflow */
381 if( *dirname == '/' )
390 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
395 wname[MAX_PATH] = L'\0';
397 if( CreateDirectoryW( wname, NULL ) == 0 )
399 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
407 char *locname = ToLocale( dirname );
410 if( locname == NULL )
415 res = mkdir( locname, mode );
417 LocaleFree( locname );
423 * Opens a DIR pointer using UTF-8 paths
425 * @param dirname UTF-8 representation of the directory name
426 * @return a pointer to the DIR struct, or NULL in case of error.
427 * Release with standard closedir().
429 DIR *utf8_opendir( const char *dirname )
432 wchar_t wname[MAX_PATH + 1];
434 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
436 wname[MAX_PATH] = L'\0';
437 return (DIR *)vlc_wopendir (wname);
440 const char *local_name = ToLocale( dirname );
442 if( local_name != NULL )
444 DIR *dir = opendir( local_name );
445 LocaleFree( local_name );
455 * Reads the next file name from an open directory.
457 * @param dir The directory that is being read
459 * @return a UTF-8 string of the directory entry.
460 * Use free() to free this memory.
462 char *utf8_readdir( DIR *dir )
465 struct _wdirent *ent = vlc_wreaddir (dir);
469 return FromWide (ent->d_name);
473 ent = readdir( (DIR *)dir );
477 return vlc_fix_readdir( ent->d_name );
481 static int dummy_select( const char *str )
488 * Does the same as utf8_scandir(), but takes an open directory pointer
489 * instead of a directory path.
491 int utf8_loaddir( DIR *dir, char ***namelist,
492 int (*select)( const char * ),
493 int (*compar)( const char **, const char ** ) )
496 select = dummy_select;
508 while( ( entry = utf8_readdir( dir ) ) != NULL )
512 if( !select( entry ) )
518 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
529 qsort( tab, num, sizeof( tab[0] ),
530 (int (*)( const void *, const void *))compar );
538 for( i = 0; i < num; i++ )
548 * Selects file entries from a directory, as GNU C scandir(), yet using
551 * @param dirname UTF-8 diretory path
552 * @param pointer [OUT] pointer set, on succesful completion, to the address
553 * of a table of UTF-8 filenames. All filenames must be freed with free().
554 * The table itself must be freed with free() as well.
556 * @return How many file names were selected (possibly 0),
557 * or -1 in case of error.
559 int utf8_scandir( const char *dirname, char ***namelist,
560 int (*select)( const char * ),
561 int (*compar)( const char **, const char ** ) )
563 DIR *dir = utf8_opendir (dirname);
568 val = utf8_loaddir (dir, namelist, select, compar);
574 static int utf8_statEx( const char *filename, struct stat *buf,
577 #if defined (WIN32) || defined (UNDER_CE)
578 /* retrieve Windows OS version */
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';
591 return _wstati64( wpath, buf );
594 #ifdef HAVE_SYS_STAT_H
595 const char *local_name = ToLocale( filename );
597 if( local_name != NULL )
599 int res = deref ? stat( local_name, buf )
600 : lstat( local_name, buf );
601 LocaleFree( local_name );
610 * Finds file/inode informations, as stat().
611 * Consider usign fstat() instead, if possible.
613 * @param filename UTF-8 file path
615 int utf8_stat( const char *filename, struct stat *buf)
617 return utf8_statEx( filename, buf, true );
621 * Finds file/inode informations, as lstat().
622 * Consider usign fstat() instead, if possible.
624 * @param filename UTF-8 file path
626 int utf8_lstat( const char *filename, struct stat *buf)
628 return utf8_statEx( filename, buf, false );
634 * @param filename a UTF-8 string with the name of the file you want to delete.
635 * @return A 0 return value indicates success. A -1 return value indicates an
636 * error, and an error code is stored in errno
638 int utf8_unlink( const char *filename )
640 #if defined (WIN32) || defined (UNDER_CE)
641 if( GetVersion() < 0x80000000 )
643 /* for Windows NT and above */
644 wchar_t wpath[MAX_PATH + 1];
646 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
651 wpath[MAX_PATH] = L'\0';
654 * unlink() cannot open files with non-“ANSI” characters on Windows.
655 * We use _wunlink() instead.
657 return _wunlink( wpath );
660 const char *local_name = ToLocale( filename );
662 if( local_name == NULL )
668 int ret = unlink( local_name );
669 LocaleFree( local_name );
676 * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
677 * appropriate conversion to local encoding.
679 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
682 int res = vasprintf( &utf8, fmt, ap );
686 *str = ToLocaleDup( utf8 );
692 * Formats an UTF-8 string as vfprintf(), then print it, with
693 * appropriate conversion to local encoding.
695 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
698 int res = utf8_vasprintf( &str, fmt, ap );
702 fputs( str, stream );
708 * Formats an UTF-8 string as fprintf(), then print it, with
709 * appropriate conversion to local encoding.
711 int utf8_fprintf( FILE *stream, const char *fmt, ... )
717 res = utf8_vfprintf( stream, fmt, ap );
723 static char *CheckUTF8( char *str, char rep )
725 uint8_t *ptr = (uint8_t *)str;
726 assert (str != NULL);
736 for (int i = 0; i < 7; i++)
737 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
745 case 0: // 7-bit ASCII character -> OK
749 case -1: // 1111111x -> error
750 case 1: // continuation byte -> error
754 assert (charlen >= 2);
756 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
757 for (int i = 1; i < charlen; i++)
759 assert (cp < (1 << 26));
762 if ((c == '\0') // unexpected end of string
763 || ((c >> 6) != 2)) // not a continuation byte
766 cp = (cp << 6) | (ptr[i] & 0x3f);
769 if (cp < 128) // overlong (special case for ASCII)
771 if (cp < (1u << (5 * charlen - 3))) // overlong
788 * Replaces invalid/overlong UTF-8 sequences with question marks.
789 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
790 * so we don't try that, even though it would be less disruptive.
792 * @return str if it was valid UTF-8, NULL if not.
794 char *EnsureUTF8( char *str )
796 return CheckUTF8( str, '?' );
801 * Checks whether a string is a valid UTF-8 byte sequence.
803 * @param str nul-terminated string to be checked
805 * @return str if it was valid UTF-8, NULL if not.
807 const char *IsUTF8( const char *str )
809 return CheckUTF8( (char *)str, 0 );