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