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