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