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