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