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