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 *****************************************************************************/
32 #include <vlc_common.h>
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)
170 #if defined (USE_ICONV)
172 return strdup (string);
173 return locale_fast (string, from);
174 #elif defined (USE_MB2MB)
175 return locale_fast (string, from);
178 return strdup (string);
183 * Releases (if needed) a localized or uniformized string.
184 * @param str non-NULL return value from FromLocale() or ToLocale().
186 void LocaleFree (const char *str)
188 #if defined (USE_ICONV)
189 if (!find_charset ())
191 #elif defined (USE_MB2MB)
200 * Converts a string from the system locale character encoding to UTF-8.
202 * @param locale nul-terminated string to convert
204 * @return a nul-terminated UTF-8 string, or NULL in case of error.
205 * To avoid memory leak, you have to pass the result to LocaleFree()
206 * when it is no longer needed.
208 char *FromLocale (const char *locale)
210 return locale_fast (locale, true);
214 * converts a string from the system locale character encoding to utf-8,
215 * the result is always allocated on the heap.
217 * @param locale nul-terminated string to convert
219 * @return a nul-terminated utf-8 string, or null in case of error.
220 * The result must be freed using free() - as with the strdup() function.
222 char *FromLocaleDup (const char *locale)
224 return locale_dup (locale, true);
229 * ToLocale: converts an UTF-8 string to local system encoding.
231 * @param utf8 nul-terminated string to be converted
233 * @return a nul-terminated string, or NULL in case of error.
234 * To avoid memory leak, you have to pass the result to LocaleFree()
235 * when it is no longer needed.
237 char *ToLocale (const char *utf8)
239 return locale_fast (utf8, false);
244 * converts a string from UTF-8 to the system locale character encoding,
245 * the result is always allocated on the heap.
247 * @param utf8 nul-terminated string to convert
249 * @return a nul-terminated string, or null in case of error.
250 * The result must be freed using free() - as with the strdup() function.
252 char *ToLocaleDup (const char *utf8)
254 return locale_dup (utf8, false);
259 * Opens a system file handle using UTF-8 paths.
261 * @param filename file path to open (with UTF-8 encoding)
262 * @param flags open() flags, see the C library open() documentation
263 * @param mode file permissions if creating a new file
264 * @return a file handle on success, -1 on error (see errno).
266 int utf8_open (const char *filename, int flags, mode_t mode)
268 #if defined (WIN32) || defined (UNDER_CE)
269 if (GetVersion() < 0x80000000)
271 /* for Windows NT and above */
272 wchar_t wpath[MAX_PATH + 1];
274 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
279 wpath[MAX_PATH] = L'\0';
282 * open() cannot open files with non-“ANSI” characters on Windows.
283 * We use _wopen() instead. Same thing for mkdir() and stat().
285 return _wopen (wpath, flags, mode);
288 const char *local_name = ToLocale (filename);
290 if (local_name == NULL)
296 int fd = open (local_name, flags, mode);
297 LocaleFree (local_name);
302 * Opens a FILE pointer using UTF-8 filenames.
303 * @param filename file path, using UTF-8 encoding
304 * @param mode fopen file open mode
305 * @return NULL on error, an open FILE pointer on success.
307 FILE *utf8_fopen (const char *filename, const char *mode)
309 int rwflags = 0, oflags = 0;
312 for (const char *ptr = mode; *ptr; ptr++)
328 oflags |= O_CREAT | O_TRUNC;
343 int fd = utf8_open (filename, rwflags | oflags, 0666);
347 if (append && (lseek (fd, 0, SEEK_END) == -1))
353 FILE *stream = fdopen (fd, mode);
361 * Creates a directory using UTF-8 paths.
363 * @param dirname a UTF-8 string with the name of the directory that you
365 * @param mode directory permissions
366 * @return 0 on success, -1 on error (see errno).
368 int utf8_mkdir( const char *dirname, mode_t mode )
370 #if defined (UNDER_CE) || defined (WIN32)
373 wchar_t wname[MAX_PATH + 1];
374 char mod[MAX_PATH + 1];
377 /* Convert '/' into '\' */
378 for( i = 0; *dirname; i++ )
381 return -1; /* overflow */
383 if( *dirname == '/' )
392 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
397 wname[MAX_PATH] = L'\0';
399 if( CreateDirectoryW( wname, NULL ) == 0 )
401 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
409 char *locname = ToLocale( dirname );
412 if( locname == NULL )
417 res = mkdir( locname, mode );
419 LocaleFree( locname );
425 * Opens a DIR pointer using UTF-8 paths
427 * @param dirname UTF-8 representation of the directory name
428 * @return a pointer to the DIR struct, or NULL in case of error.
429 * Release with standard closedir().
431 DIR *utf8_opendir( const char *dirname )
434 wchar_t wname[MAX_PATH + 1];
436 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
438 wname[MAX_PATH] = L'\0';
439 return (DIR *)vlc_wopendir (wname);
442 const char *local_name = ToLocale( dirname );
444 if( local_name != NULL )
446 DIR *dir = opendir( local_name );
447 LocaleFree( local_name );
457 * Reads the next file name from an open directory.
459 * @param dir The directory that is being read
461 * @return a UTF-8 string of the directory entry.
462 * Use free() to free this memory.
464 char *utf8_readdir( DIR *dir )
467 struct _wdirent *ent = vlc_wreaddir (dir);
471 return FromWide (ent->d_name);
475 ent = readdir( (DIR *)dir );
479 return vlc_fix_readdir( ent->d_name );
483 static int dummy_select( const char *str )
490 * Does the same as utf8_scandir(), but takes an open directory pointer
491 * instead of a directory path.
493 int utf8_loaddir( DIR *dir, char ***namelist,
494 int (*select)( const char * ),
495 int (*compar)( const char **, const char ** ) )
498 select = dummy_select;
510 while( ( entry = utf8_readdir( dir ) ) != NULL )
514 if( !select( entry ) )
520 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
531 qsort( tab, num, sizeof( tab[0] ),
532 (int (*)( const void *, const void *))compar );
540 for( i = 0; i < num; i++ )
550 * Selects file entries from a directory, as GNU C scandir(), yet using
553 * @param dirname UTF-8 diretory path
554 * @param pointer [OUT] pointer set, on succesful completion, to the address
555 * of a table of UTF-8 filenames. All filenames must be freed with free().
556 * The table itself must be freed with free() as well.
558 * @return How many file names were selected (possibly 0),
559 * or -1 in case of error.
561 int utf8_scandir( const char *dirname, char ***namelist,
562 int (*select)( const char * ),
563 int (*compar)( const char **, const char ** ) )
565 DIR *dir = utf8_opendir (dirname);
570 val = utf8_loaddir (dir, namelist, select, compar);
576 static int utf8_statEx( const char *filename, struct stat *buf,
579 #if defined (WIN32) || defined (UNDER_CE)
580 /* retrieve Windows OS version */
581 if( GetVersion() < 0x80000000 )
583 /* for Windows NT and above */
584 wchar_t wpath[MAX_PATH + 1];
586 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
591 wpath[MAX_PATH] = L'\0';
593 return _wstati64( wpath, buf );
596 #ifdef HAVE_SYS_STAT_H
597 const char *local_name = ToLocale( filename );
599 if( local_name != NULL )
601 int res = deref ? stat( local_name, buf )
602 : lstat( local_name, buf );
603 LocaleFree( local_name );
612 * Finds file/inode informations, as stat().
613 * Consider usign fstat() instead, if possible.
615 * @param filename UTF-8 file path
617 int utf8_stat( const char *filename, struct stat *buf)
619 return utf8_statEx( filename, buf, true );
623 * Finds file/inode informations, as lstat().
624 * Consider usign fstat() instead, if possible.
626 * @param filename UTF-8 file path
628 int utf8_lstat( const char *filename, struct stat *buf)
630 return utf8_statEx( filename, buf, false );
636 * @param filename a UTF-8 string with the name of the file you want to delete.
637 * @return A 0 return value indicates success. A -1 return value indicates an
638 * error, and an error code is stored in errno
640 int utf8_unlink( const char *filename )
642 #if defined (WIN32) || defined (UNDER_CE)
643 if( GetVersion() < 0x80000000 )
645 /* for Windows NT and above */
646 wchar_t wpath[MAX_PATH + 1];
648 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
653 wpath[MAX_PATH] = L'\0';
656 * unlink() cannot open files with non-“ANSI” characters on Windows.
657 * We use _wunlink() instead.
659 return _wunlink( wpath );
662 const char *local_name = ToLocale( filename );
664 if( local_name == NULL )
670 int ret = unlink( local_name );
671 LocaleFree( local_name );
678 * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
679 * appropriate conversion to local encoding.
681 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
684 int res = vasprintf( &utf8, fmt, ap );
688 *str = ToLocaleDup( utf8 );
694 * Formats an UTF-8 string as vfprintf(), then print it, with
695 * appropriate conversion to local encoding.
697 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
700 int res = utf8_vasprintf( &str, fmt, ap );
704 fputs( str, stream );
710 * Formats an UTF-8 string as fprintf(), then print it, with
711 * appropriate conversion to local encoding.
713 int utf8_fprintf( FILE *stream, const char *fmt, ... )
719 res = utf8_vfprintf( stream, fmt, ap );
725 static char *CheckUTF8( char *str, char rep )
727 uint8_t *ptr = (uint8_t *)str;
728 assert (str != NULL);
738 for (int i = 0; i < 7; i++)
739 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
747 case 0: // 7-bit ASCII character -> OK
751 case -1: // 1111111x -> error
752 case 1: // continuation byte -> error
756 assert (charlen >= 2);
758 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
759 for (int i = 1; i < charlen; i++)
761 assert (cp < (1 << 26));
764 if ((c == '\0') // unexpected end of string
765 || ((c >> 6) != 2)) // not a continuation byte
768 cp = (cp << 6) | (ptr[i] & 0x3f);
771 if (cp < 128) // overlong (special case for ASCII)
773 if (cp < (1u << (5 * charlen - 3))) // overlong
790 * Replaces invalid/overlong UTF-8 sequences with question marks.
791 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
792 * so we don't try that, even though it would be less disruptive.
794 * @return str if it was valid UTF-8, NULL if not.
796 char *EnsureUTF8( char *str )
798 return CheckUTF8( str, '?' );
803 * Checks whether a string is a valid UTF-8 byte sequence.
805 * @param str nul-terminated string to be checked
807 * @return str if it was valid UTF-8, NULL if not.
809 const char *IsUTF8( const char *str )
811 return CheckUTF8( (char *)str, 0 );