]> git.sesse.net Git - vlc/blob - src/text/filesystem.c
Add some fallback for language we have a translation
[vlc] / src / text / filesystem.c
1 /*****************************************************************************
2  * filesystem.c: File system helpers
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33 #include "libvlc.h" /* utf8_mkdir */
34 #include <vlc_rand.h>
35
36 #include <assert.h>
37
38 #include <stdio.h>
39 #include <errno.h>
40 #include <sys/types.h>
41 #ifdef HAVE_DIRENT_H
42 #  include <dirent.h>
43 #endif
44 #ifdef UNDER_CE
45 #  include <tchar.h>
46 #endif
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 # include <fcntl.h>
52 #endif
53 #ifdef WIN32
54 # include <io.h>
55 # ifndef UNDER_CE
56 #  include <direct.h>
57 # endif
58 #else
59 # include <unistd.h>
60 #endif
61
62 #ifndef HAVE_LSTAT
63 # define lstat( a, b ) stat(a, b)
64 #endif
65
66 #ifdef WIN32
67 static int convert_path (const char *restrict path, wchar_t *restrict wpath)
68 {
69     if (!MultiByteToWideChar (CP_UTF8, 0, path, -1, wpath, MAX_PATH))
70     {
71         errno = ENOENT;
72         return -1;
73     }
74     wpath[MAX_PATH] = L'\0';
75     return 0;
76 }
77 # define CONVERT_PATH(path, wpath, err) \
78   wchar_t wpath[MAX_PATH+1]; \
79   if (convert_path (path, wpath)) \
80       return (err)
81 #endif
82
83 /**
84  * Opens a system file handle.
85  *
86  * @param filename file path to open (with UTF-8 encoding)
87  * @param flags open() flags, see the C library open() documentation
88  * @return a file handle on success, -1 on error (see errno).
89  * @note Contrary to standard open(), this function returns file handles
90  * with the close-on-exec flag enabled.
91  */
92 int utf8_open (const char *filename, int flags, ...)
93 {
94     unsigned int mode = 0;
95     va_list ap;
96
97     va_start (ap, flags);
98     if (flags & O_CREAT)
99         mode = va_arg (ap, unsigned int);
100     va_end (ap);
101
102 #ifdef UNDER_CE
103     /*_open translates to wchar internally on WinCE*/
104     return _open (filename, flags, mode);
105 #elif defined (WIN32)
106     /*
107      * open() cannot open files with non-“ANSI” characters on Windows.
108      * We use _wopen() instead. Same thing for mkdir() and stat().
109      */
110     CONVERT_PATH(filename, wpath, -1);
111     return _wopen (wpath, flags, mode);
112
113 #endif
114     const char *local_name = ToLocale (filename);
115
116     if (local_name == NULL)
117     {
118         errno = ENOENT;
119         return -1;
120     }
121
122     int fd;
123
124 #ifdef O_CLOEXEC
125     fd = open (local_name, flags | O_CLOEXEC, mode);
126     if (fd == -1 && errno == EINVAL)
127 #endif
128     {
129         fd = open (local_name, flags, mode);
130 #ifdef HAVE_FCNTL
131         if (fd != -1)
132         {
133             int flags = fcntl (fd, F_GETFD);
134             fcntl (fd, F_SETFD, FD_CLOEXEC | ((flags != -1) ? flags : 0));
135         }
136 #endif
137     }
138
139     LocaleFree (local_name);
140     return fd;
141 }
142
143 /**
144  * Opens a FILE pointer.
145  * @param filename file path, using UTF-8 encoding
146  * @param mode fopen file open mode
147  * @return NULL on error, an open FILE pointer on success.
148  */
149 FILE *utf8_fopen (const char *filename, const char *mode)
150 {
151     int rwflags = 0, oflags = 0;
152     bool append = false;
153
154     for (const char *ptr = mode; *ptr; ptr++)
155     {
156         switch (*ptr)
157         {
158             case 'r':
159                 rwflags = O_RDONLY;
160                 break;
161
162             case 'a':
163                 rwflags = O_WRONLY;
164                 oflags |= O_CREAT;
165                 append = true;
166                 break;
167
168             case 'w':
169                 rwflags = O_WRONLY;
170                 oflags |= O_CREAT | O_TRUNC;
171                 break;
172
173             case '+':
174                 rwflags = O_RDWR;
175                 break;
176
177 #ifdef O_TEXT
178             case 't':
179                 oflags |= O_TEXT;
180                 break;
181 #endif
182         }
183     }
184
185     int fd = utf8_open (filename, rwflags | oflags, 0666);
186     if (fd == -1)
187         return NULL;
188
189     if (append && (lseek (fd, 0, SEEK_END) == -1))
190     {
191         close (fd);
192         return NULL;
193     }
194
195     FILE *stream = fdopen (fd, mode);
196     if (stream == NULL)
197         close (fd);
198
199     return stream;
200 }
201
202 /**
203  * Creates a directory using UTF-8 paths.
204  *
205  * @param dirname a UTF-8 string with the name of the directory that you
206  *        want to create.
207  * @param mode directory permissions
208  * @return 0 on success, -1 on error (see errno).
209  */
210 int utf8_mkdir( const char *dirname, mode_t mode )
211 {
212 #if defined (UNDER_CE)
213     (void) mode;
214     /* mkdir converts internally to wchar */
215     return _mkdir(dirname);
216 #elif defined (WIN32)
217     (void) mode;
218     CONVERT_PATH (dirname, wpath, -1);
219     return _wmkdir (wpath);
220
221 #else
222     char *locname = ToLocale( dirname );
223     int res;
224
225     if( locname == NULL )
226     {
227         errno = ENOENT;
228         return -1;
229     }
230     res = mkdir( locname, mode );
231
232     LocaleFree( locname );
233     return res;
234 #endif
235 }
236
237 /**
238  * Opens a DIR pointer.
239  *
240  * @param dirname UTF-8 representation of the directory name
241  * @return a pointer to the DIR struct, or NULL in case of error.
242  * Release with standard closedir().
243  */
244 DIR *utf8_opendir( const char *dirname )
245 {
246 #ifdef WIN32
247     CONVERT_PATH (dirname, wpath, NULL);
248     return (DIR *)vlc_wopendir (wpath);
249
250 #else
251     const char *local_name = ToLocale( dirname );
252
253     if( local_name != NULL )
254     {
255         DIR *dir = opendir( local_name );
256         LocaleFree( local_name );
257         return dir;
258     }
259 #endif
260
261     errno = ENOENT;
262     return NULL;
263 }
264
265 /**
266  * Reads the next file name from an open directory.
267  *
268  * @param dir The directory that is being read
269  *
270  * @return a UTF-8 string of the directory entry.
271  * Use free() to free this memory.
272  */
273 char *utf8_readdir( DIR *dir )
274 {
275 #ifdef WIN32
276     struct _wdirent *ent = vlc_wreaddir (dir);
277     if (ent == NULL)
278         return NULL;
279
280     return FromWide (ent->d_name);
281 #else
282     struct dirent *ent;
283
284     ent = readdir( (DIR *)dir );
285     if( ent == NULL )
286         return NULL;
287
288     return vlc_fix_readdir( ent->d_name );
289 #endif
290 }
291
292 static int dummy_select( const char *str )
293 {
294     (void)str;
295     return 1;
296 }
297
298 /**
299  * Does the same as utf8_scandir(), but takes an open directory pointer
300  * instead of a directory path.
301  */
302 int utf8_loaddir( DIR *dir, char ***namelist,
303                   int (*select)( const char * ),
304                   int (*compar)( const char **, const char ** ) )
305 {
306     if( select == NULL )
307         select = dummy_select;
308
309     if( dir == NULL )
310         return -1;
311     else
312     {
313         char **tab = NULL;
314         char *entry;
315         unsigned num = 0;
316
317         rewinddir( dir );
318
319         while( ( entry = utf8_readdir( dir ) ) != NULL )
320         {
321             char **newtab;
322
323             if( !select( entry ) )
324             {
325                 free( entry );
326                 continue;
327             }
328
329             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
330             if( newtab == NULL )
331             {
332                 free( entry );
333                 goto error;
334             }
335             tab = newtab;
336             tab[num++] = entry;
337         }
338
339         if( compar != NULL )
340             qsort( tab, num, sizeof( tab[0] ),
341                    (int (*)( const void *, const void *))compar );
342
343         *namelist = tab;
344         return num;
345
346     error:{
347         unsigned i;
348
349         for( i = 0; i < num; i++ )
350             free( tab[i] );
351         free( tab );
352         }
353     }
354     return -1;
355 }
356
357 /**
358  * Selects file entries from a directory, as GNU C scandir().
359  *
360  * @param dirname UTF-8 diretory path
361  * @param pointer [OUT] pointer set, on succesful completion, to the address
362  * of a table of UTF-8 filenames. All filenames must be freed with free().
363  * The table itself must be freed with free() as well.
364  *
365  * @return How many file names were selected (possibly 0),
366  * or -1 in case of error.
367  */
368 int utf8_scandir( const char *dirname, char ***namelist,
369                   int (*select)( const char * ),
370                   int (*compar)( const char **, const char ** ) )
371 {
372     DIR *dir = utf8_opendir (dirname);
373     int val = -1;
374
375     if (dir != NULL)
376     {
377         val = utf8_loaddir (dir, namelist, select, compar);
378         closedir (dir);
379     }
380     return val;
381 }
382
383 static int utf8_statEx( const char *filename, struct stat *buf,
384                         bool deref )
385 {
386 #ifdef UNDER_CE
387     /*_stat translates to wchar internally on WinCE*/
388     return _stat( filename, buf );
389 #elif defined (WIN32)
390     CONVERT_PATH (filename, wpath, -1);
391     return _wstati64 (wpath, buf);
392
393 #endif
394 #ifdef HAVE_SYS_STAT_H
395     const char *local_name = ToLocale( filename );
396
397     if( local_name != NULL )
398     {
399         int res = deref ? stat( local_name, buf )
400                        : lstat( local_name, buf );
401         LocaleFree( local_name );
402         return res;
403     }
404     errno = ENOENT;
405 #endif
406     return -1;
407 }
408
409 /**
410  * Finds file/inode informations, as stat().
411  * Consider using fstat() instead, if possible.
412  *
413  * @param filename UTF-8 file path
414  */
415 int utf8_stat( const char *filename, struct stat *buf)
416 {
417     return utf8_statEx( filename, buf, true );
418 }
419
420 /**
421  * Finds file/inode informations, as lstat().
422  * Consider using fstat() instead, if possible.
423  *
424  * @param filename UTF-8 file path
425  */
426 int utf8_lstat( const char *filename, struct stat *buf)
427 {
428     return utf8_statEx( filename, buf, false );
429 }
430
431 /**
432  * Removes a file.
433  *
434  * @param filename a UTF-8 string with the name of the file you want to delete.
435  * @return A 0 return value indicates success. A -1 return value indicates an
436  *        error, and an error code is stored in errno
437  */
438 int utf8_unlink( const char *filename )
439 {
440 #ifdef UNDER_CE
441     /*_open translates to wchar internally on WinCE*/
442     return _unlink( filename );
443 #elif defined (WIN32)
444     CONVERT_PATH (filename, wpath, -1);
445     return _wunlink (wpath);
446
447 #endif
448     const char *local_name = ToLocale( filename );
449
450     if( local_name == NULL )
451     {
452         errno = ENOENT;
453         return -1;
454     }
455
456     int ret = unlink( local_name );
457     LocaleFree( local_name );
458     return ret;
459 }
460
461 /**
462  * Moves a file atomically. This only works within a single file system.
463  *
464  * @param oldpath path to the file before the move
465  * @param newpath intended path to the file after the move
466  * @return A 0 return value indicates success. A -1 return value indicates an
467  *        error, and an error code is stored in errno
468  */
469 int utf8_rename (const char *oldpath, const char *newpath)
470 {
471 #if defined (WIN32)
472     CONVERT_PATH (oldpath, wold, -1);
473     CONVERT_PATH (newpath, wnew, -1);
474 # ifdef UNDER_CE
475     /* FIXME: errno support */
476     if (MoveFileW (wold, wnew))
477         return 0;
478     else
479         return -1;
480 #else
481     return _wrename (wold, wnew);
482 #endif
483
484 #endif
485     const char *lo = ToLocale (oldpath);
486     if (lo == NULL)
487         goto error;
488
489     const char *ln = ToLocale (newpath);
490     if (ln == NULL)
491     {
492         LocaleFree (lo);
493 error:
494         errno = ENOENT;
495         return -1;
496     }
497
498     int ret = rename (lo, ln);
499     LocaleFree (lo);
500     LocaleFree (ln);
501     return ret;
502 }
503
504 int utf8_mkstemp( char *template )
505 {
506     static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
507     static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
508
509     /* */
510     assert( template );
511
512     /* Check template validity */
513     const size_t i_length = strlen( template );
514     char *psz_rand = &template[i_length-6];
515
516     if( i_length < 6 || strcmp( psz_rand, "XXXXXX" ) )
517     {
518         errno = EINVAL;
519         return -1;
520     }
521
522     /* */
523     for( int i = 0; i < 256; i++ )
524     {
525         /* Create a pseudo random file name */
526         uint8_t pi_rand[6];
527
528         vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
529         for( int j = 0; j < 6; j++ )
530             psz_rand[j] = digits[pi_rand[j] % i_digits];
531
532         /* */
533         int fd = utf8_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
534         if( fd >= 0 )
535             return fd;
536         if( errno != EEXIST )
537             return -1;
538     }
539
540     errno = EEXIST;
541     return -1;
542 }
543