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