1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2008 Rémi Denis-Courmont
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33 #include "libvlc.h" /* utf8_mkdir */
41 #include <sys/types.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
61 # define lstat( a, b ) stat(a, b)
65 /* Define this if the OS always use UTF-8 internally */
66 # define ASSUME_UTF8 1
69 #if defined (ASSUME_UTF8)
71 #elif defined (WIN32) || defined (UNDER_CE)
73 #elif defined (HAVE_ICONV)
76 # error No UTF8 charset conversion implemented on this platform!
79 #if defined (USE_ICONV)
80 # include <langinfo.h>
81 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
83 static void find_charset_once (void)
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... */
91 static int find_charset (void)
93 static pthread_once_t once = PTHREAD_ONCE_INIT;
94 pthread_once (&once, find_charset_once);
95 return !strcasecmp (charset, "UTF-8");
100 static char *locale_fast (const char *string, bool from)
102 #if defined (USE_ICONV)
104 return (char *)string;
106 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
107 from ? charset : "UTF-8");
108 if (hd == (vlc_iconv_t)(-1))
109 return NULL; /* Uho! */
111 const char *iptr = string;
112 size_t inb = strlen (string);
113 size_t outb = inb * 6 + 1;
114 char output[outb], *optr = output;
119 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
125 vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
128 vlc_iconv_close (hd);
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)
142 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
143 0, string, -1, NULL, 0);
146 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
147 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
148 NULL, 0, NULL, NULL);
153 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
158 return (char *)string;
163 static inline char *locale_dup (const char *string, bool 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);
175 return strdup (string);
180 * Releases (if needed) a localized or uniformized string.
181 * @param str non-NULL return value from FromLocale() or ToLocale().
183 void LocaleFree (const char *str)
185 #if defined (USE_ICONV)
186 if (!find_charset ())
188 #elif defined (USE_MB2MB)
197 * Converts a string from the system locale character encoding to UTF-8.
199 * @param locale nul-terminated string to convert
201 * @return a nul-terminated UTF-8 string, or NULL in case of error.
202 * To avoid memory leak, you have to pass the result to LocaleFree()
203 * when it is no longer needed.
205 char *FromLocale (const char *locale)
207 return locale_fast (locale, true);
211 * converts a string from the system locale character encoding to utf-8,
212 * the result is always allocated on the heap.
214 * @param locale nul-terminated string to convert
216 * @return a nul-terminated utf-8 string, or null in case of error.
217 * The result must be freed using free() - as with the strdup() function.
219 char *FromLocaleDup (const char *locale)
221 return locale_dup (locale, true);
226 * ToLocale: converts an UTF-8 string to local system encoding.
228 * @param utf8 nul-terminated string to be converted
230 * @return a nul-terminated string, or NULL in case of error.
231 * To avoid memory leak, you have to pass the result to LocaleFree()
232 * when it is no longer needed.
234 char *ToLocale (const char *utf8)
236 return locale_fast (utf8, false);
241 * converts a string from UTF-8 to the system locale character encoding,
242 * the result is always allocated on the heap.
244 * @param utf8 nul-terminated string to convert
246 * @return a nul-terminated string, or null in case of error.
247 * The result must be freed using free() - as with the strdup() function.
249 char *ToLocaleDup (const char *utf8)
251 return locale_dup (utf8, false);
256 * Opens a system file handle using UTF-8 paths.
258 * @param filename file path to open (with UTF-8 encoding)
259 * @param flags open() flags, see the C library open() documentation
260 * @param mode file permissions if creating a new file
261 * @return a file handle on success, -1 on error (see errno).
263 int utf8_open (const char *filename, int flags, mode_t mode)
265 #if defined (WIN32) || defined (UNDER_CE)
266 if (GetVersion() < 0x80000000)
268 /* for Windows NT and above */
269 wchar_t wpath[MAX_PATH + 1];
271 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
276 wpath[MAX_PATH] = L'\0';
279 * open() cannot open files with non-“ANSI” characters on Windows.
280 * We use _wopen() instead. Same thing for mkdir() and stat().
282 return _wopen (wpath, flags, mode);
285 const char *local_name = ToLocale (filename);
287 if (local_name == NULL)
293 int fd = open (local_name, flags, mode);
294 LocaleFree (local_name);
299 * Opens a FILE pointer using UTF-8 filenames.
300 * @param filename file path, using UTF-8 encoding
301 * @param mode fopen file open mode
302 * @return NULL on error, an open FILE pointer on success.
304 FILE *utf8_fopen (const char *filename, const char *mode)
306 int rwflags = 0, oflags = 0;
309 for (const char *ptr = mode; *ptr; ptr++)
325 oflags |= O_CREAT | O_TRUNC;
340 int fd = utf8_open (filename, rwflags | oflags, 0666);
344 if (append && (lseek (fd, 0, SEEK_END) == -1))
350 FILE *stream = fdopen (fd, mode);
358 * Creates a directory using UTF-8 paths.
360 * @param dirname a UTF-8 string with the name of the directory that you
362 * @param mode directory permissions
363 * @return 0 on success, -1 on error (see errno).
365 int utf8_mkdir( const char *dirname, mode_t mode )
367 #if defined (UNDER_CE) || defined (WIN32)
370 wchar_t wname[MAX_PATH + 1];
371 char mod[MAX_PATH + 1];
374 /* Convert '/' into '\' */
375 for( i = 0; *dirname; i++ )
378 return -1; /* overflow */
380 if( *dirname == '/' )
389 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
394 wname[MAX_PATH] = L'\0';
396 if( CreateDirectoryW( wname, NULL ) == 0 )
398 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
406 char *locname = ToLocale( dirname );
409 if( locname == NULL )
414 res = mkdir( locname, mode );
416 LocaleFree( locname );
422 * Opens a DIR pointer using UTF-8 paths
424 * @param dirname UTF-8 representation of the directory name
425 * @return a pointer to the DIR struct, or NULL in case of error.
426 * Release with standard closedir().
428 DIR *utf8_opendir( const char *dirname )
431 wchar_t wname[MAX_PATH + 1];
433 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
435 wname[MAX_PATH] = L'\0';
436 return (DIR *)vlc_wopendir (wname);
439 const char *local_name = ToLocale( dirname );
441 if( local_name != NULL )
443 DIR *dir = opendir( local_name );
444 LocaleFree( local_name );
454 * Reads the next file name from an open directory.
456 * @param dir The directory that is being read
458 * @return a UTF-8 string of the directory entry.
459 * Use free() to free this memory.
461 char *utf8_readdir( DIR *dir )
464 struct _wdirent *ent = vlc_wreaddir (dir);
468 return FromWide (ent->d_name);
472 ent = readdir( (DIR *)dir );
476 return vlc_fix_readdir( ent->d_name );
480 static int dummy_select( const char *str )
487 * Does the same as utf8_scandir(), but takes an open directory pointer
488 * instead of a directory path.
490 int utf8_loaddir( DIR *dir, char ***namelist,
491 int (*select)( const char * ),
492 int (*compar)( const char **, const char ** ) )
495 select = dummy_select;
507 while( ( entry = utf8_readdir( dir ) ) != NULL )
511 if( !select( entry ) )
517 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
528 qsort( tab, num, sizeof( tab[0] ),
529 (int (*)( const void *, const void *))compar );
537 for( i = 0; i < num; i++ )
547 * Selects file entries from a directory, as GNU C scandir(), yet using
550 * @param dirname UTF-8 diretory path
551 * @param pointer [OUT] pointer set, on succesful completion, to the address
552 * of a table of UTF-8 filenames. All filenames must be freed with free().
553 * The table itself must be freed with free() as well.
555 * @return How many file names were selected (possibly 0),
556 * or -1 in case of error.
558 int utf8_scandir( const char *dirname, char ***namelist,
559 int (*select)( const char * ),
560 int (*compar)( const char **, const char ** ) )
562 DIR *dir = utf8_opendir (dirname);
567 val = utf8_loaddir (dir, namelist, select, compar);
573 static int utf8_statEx( const char *filename, struct stat *buf,
576 #if defined (WIN32) || defined (UNDER_CE)
577 /* retrieve Windows OS version */
578 if( GetVersion() < 0x80000000 )
580 /* for Windows NT and above */
581 wchar_t wpath[MAX_PATH + 1];
583 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
588 wpath[MAX_PATH] = L'\0';
590 return _wstati64( wpath, buf );
593 #ifdef HAVE_SYS_STAT_H
594 const char *local_name = ToLocale( filename );
596 if( local_name != NULL )
598 int res = deref ? stat( local_name, buf )
599 : lstat( local_name, buf );
600 LocaleFree( local_name );
609 * Finds file/inode informations, as stat().
610 * Consider usign fstat() instead, if possible.
612 * @param filename UTF-8 file path
614 int utf8_stat( const char *filename, struct stat *buf)
616 return utf8_statEx( filename, buf, true );
620 * Finds file/inode informations, as lstat().
621 * Consider usign fstat() instead, if possible.
623 * @param filename UTF-8 file path
625 int utf8_lstat( const char *filename, struct stat *buf)
627 return utf8_statEx( filename, buf, false );
633 * @param filename a UTF-8 string with the name of the file you want to delete.
634 * @return A 0 return value indicates success. A -1 return value indicates an
635 * error, and an error code is stored in errno
637 int utf8_unlink( const char *filename )
639 #if defined (WIN32) || defined (UNDER_CE)
640 if( GetVersion() < 0x80000000 )
642 /* for Windows NT and above */
643 wchar_t wpath[MAX_PATH + 1];
645 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
650 wpath[MAX_PATH] = L'\0';
653 * unlink() cannot open files with non-“ANSI” characters on Windows.
654 * We use _wunlink() instead.
656 return _wunlink( wpath );
659 const char *local_name = ToLocale( filename );
661 if( local_name == NULL )
667 int ret = unlink( local_name );
668 LocaleFree( local_name );
675 * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
676 * appropriate conversion to local encoding.
678 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
681 int res = vasprintf( &utf8, fmt, ap );
685 *str = ToLocaleDup( utf8 );
691 * Formats an UTF-8 string as vfprintf(), then print it, with
692 * appropriate conversion to local encoding.
694 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
697 int res = utf8_vasprintf( &str, fmt, ap );
701 fputs( str, stream );
707 * Formats an UTF-8 string as fprintf(), then print it, with
708 * appropriate conversion to local encoding.
710 int utf8_fprintf( FILE *stream, const char *fmt, ... )
716 res = utf8_vfprintf( stream, fmt, ap );
722 static char *CheckUTF8( char *str, char rep )
724 uint8_t *ptr = (uint8_t *)str;
725 assert (str != NULL);
735 for (int i = 0; i < 7; i++)
736 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
744 case 0: // 7-bit ASCII character -> OK
748 case -1: // 1111111x -> error
749 case 1: // continuation byte -> error
753 assert (charlen >= 2);
755 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
756 for (int i = 1; i < charlen; i++)
758 assert (cp < (1 << 26));
761 if ((c == '\0') // unexpected end of string
762 || ((c >> 6) != 2)) // not a continuation byte
765 cp = (cp << 6) | (ptr[i] & 0x3f);
768 if (cp < 128) // overlong (special case for ASCII)
770 if (cp < (1u << (5 * charlen - 3))) // overlong
787 * Replaces invalid/overlong UTF-8 sequences with question marks.
788 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
789 * so we don't try that, even though it would be less disruptive.
791 * @return str if it was valid UTF-8, NULL if not.
793 char *EnsureUTF8( char *str )
795 return CheckUTF8( str, '?' );
800 * Checks whether a string is a valid UTF-8 byte sequence.
802 * @param str nul-terminated string to be checked
804 * @return str if it was valid UTF-8, NULL if not.
806 const char *IsUTF8( const char *str )
808 return CheckUTF8( (char *)str, 0 );