]> git.sesse.net Git - vlc/blob - src/text/filesystem.c
vlc_readdir: thread-safety fix
[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 HAVE_SYS_STAT_H
46 # include <sys/stat.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 # include <fcntl.h>
50 #endif
51 #ifdef WIN32
52 # include <io.h>
53 # include <winsock2.h>
54 # ifndef UNDER_CE
55 #  include <direct.h>
56 # else
57 #  include <tchar.h>
58 # endif
59 #else
60 # include <unistd.h>
61 # include <sys/socket.h>
62 #endif
63
64 #ifndef HAVE_LSTAT
65 # define lstat( a, b ) stat(a, b)
66 #endif
67
68 #ifdef WIN32
69 static int convert_path (const char *restrict path, wchar_t *restrict wpath)
70 {
71     if (!MultiByteToWideChar (CP_UTF8, 0, path, -1, wpath, MAX_PATH))
72     {
73         errno = ENOENT;
74         return -1;
75     }
76     wpath[MAX_PATH] = L'\0';
77     return 0;
78 }
79 # define CONVERT_PATH(path, wpath, err) \
80   wchar_t wpath[MAX_PATH+1]; \
81   if (convert_path (path, wpath)) \
82       return (err)
83 #endif
84
85 /**
86  * Opens a system file handle.
87  *
88  * @param filename file path to open (with UTF-8 encoding)
89  * @param flags open() flags, see the C library open() documentation
90  * @return a file handle on success, -1 on error (see errno).
91  * @note Contrary to standard open(), this function returns file handles
92  * with the close-on-exec flag enabled.
93  */
94 int vlc_open (const char *filename, int flags, ...)
95 {
96     unsigned int mode = 0;
97     va_list ap;
98
99     va_start (ap, flags);
100     if (flags & O_CREAT)
101         mode = va_arg (ap, unsigned int);
102     va_end (ap);
103
104 #ifdef O_CLOEXEC
105     flags |= O_CLOEXEC;
106 #endif
107
108 #ifdef UNDER_CE
109     /*_open translates to wchar internally on WinCE*/
110     return _open (filename, flags, mode);
111 #elif defined (WIN32)
112     /*
113      * open() cannot open files with non-“ANSI” characters on Windows.
114      * We use _wopen() instead. Same thing for mkdir() and stat().
115      */
116     CONVERT_PATH(filename, wpath, -1);
117     return _wopen (wpath, flags, mode);
118
119 #endif
120     const char *local_name = ToLocale (filename);
121
122     if (local_name == NULL)
123     {
124         errno = ENOENT;
125         return -1;
126     }
127
128     int fd = open (local_name, flags, mode);
129 #ifdef HAVE_FCNTL
130     if (fd != -1)
131         fcntl (fd, F_SETFD, FD_CLOEXEC);
132 #endif
133
134     LocaleFree (local_name);
135     return fd;
136 }
137
138 /**
139  * Opens a FILE pointer.
140  * @param filename file path, using UTF-8 encoding
141  * @param mode fopen file open mode
142  * @return NULL on error, an open FILE pointer on success.
143  */
144 FILE *vlc_fopen (const char *filename, const char *mode)
145 {
146     int rwflags = 0, oflags = 0;
147     bool append = false;
148
149     for (const char *ptr = mode; *ptr; ptr++)
150     {
151         switch (*ptr)
152         {
153             case 'r':
154                 rwflags = O_RDONLY;
155                 break;
156
157             case 'a':
158                 rwflags = O_WRONLY;
159                 oflags |= O_CREAT;
160                 append = true;
161                 break;
162
163             case 'w':
164                 rwflags = O_WRONLY;
165                 oflags |= O_CREAT | O_TRUNC;
166                 break;
167
168             case '+':
169                 rwflags = O_RDWR;
170                 break;
171
172 #ifdef O_TEXT
173             case 't':
174                 oflags |= O_TEXT;
175                 break;
176 #endif
177         }
178     }
179
180     int fd = vlc_open (filename, rwflags | oflags, 0666);
181     if (fd == -1)
182         return NULL;
183
184     if (append && (lseek (fd, 0, SEEK_END) == -1))
185     {
186         close (fd);
187         return NULL;
188     }
189
190     FILE *stream = fdopen (fd, mode);
191     if (stream == NULL)
192         close (fd);
193
194     return stream;
195 }
196
197 /**
198  * Opens a system file handle relative to an existing directory handle.
199  *
200  * @param dir directory file descriptor
201  * @param filename file path to open (with UTF-8 encoding)
202  * @param flags open() flags, see the C library open() documentation
203  * @return a file handle on success, -1 on error (see errno).
204  * @note Contrary to standard open(), this function returns file handles
205  * with the close-on-exec flag enabled.
206  */
207 int vlc_openat (int dir, const char *filename, int flags, ...)
208 {
209     unsigned int mode = 0;
210     va_list ap;
211
212     va_start (ap, flags);
213     if (flags & O_CREAT)
214         mode = va_arg (ap, unsigned int);
215     va_end (ap);
216
217 #ifdef O_CLOEXEC
218     flags |= O_CLOEXEC;
219 #endif
220
221     const char *local_name = ToLocale (filename);
222     if (local_name == NULL)
223     {
224         errno = ENOENT;
225         return -1;
226     }
227
228 #ifdef HAVE_OPENAT
229     int fd = openat (dir, local_name, flags, mode);
230 # ifdef HAVE_FCNTL
231     if (fd != -1)
232         fcntl (fd, F_SETFD, FD_CLOEXEC);
233 # endif
234 #else
235     int fd = -1;
236     errno = ENOSYS;
237 #endif
238
239     LocaleFree (local_name);
240     return fd;
241 }
242
243
244 /**
245  * Creates a directory using UTF-8 paths.
246  *
247  * @param dirname a UTF-8 string with the name of the directory that you
248  *        want to create.
249  * @param mode directory permissions
250  * @return 0 on success, -1 on error (see errno).
251  */
252 int vlc_mkdir( const char *dirname, mode_t mode )
253 {
254 #if defined (UNDER_CE)
255     (void) mode;
256     /* mkdir converts internally to wchar */
257     return _mkdir(dirname);
258 #elif defined (WIN32)
259     (void) mode;
260     CONVERT_PATH (dirname, wpath, -1);
261     return _wmkdir (wpath);
262
263 #else
264     char *locname = ToLocale( dirname );
265     int res;
266
267     if( locname == NULL )
268     {
269         errno = ENOENT;
270         return -1;
271     }
272     res = mkdir( locname, mode );
273
274     LocaleFree( locname );
275     return res;
276 #endif
277 }
278
279 /**
280  * Opens a DIR pointer.
281  *
282  * @param dirname UTF-8 representation of the directory name
283  * @return a pointer to the DIR struct, or NULL in case of error.
284  * Release with standard closedir().
285  */
286 DIR *vlc_opendir( const char *dirname )
287 {
288 #ifdef WIN32
289     CONVERT_PATH (dirname, wpath, NULL);
290     return (DIR *)vlc_wopendir (wpath);
291
292 #else
293     const char *local_name = ToLocale( dirname );
294
295     if( local_name != NULL )
296     {
297         DIR *dir = opendir( local_name );
298         LocaleFree( local_name );
299         return dir;
300     }
301 #endif
302
303     errno = ENOENT;
304     return NULL;
305 }
306
307 /**
308  * Reads the next file name from an open directory.
309  *
310  * @param dir The directory that is being read
311  *
312  * @return a UTF-8 string of the directory entry.
313  * Use free() to free this memory.
314  */
315 char *vlc_readdir( DIR *dir )
316 {
317 #ifdef WIN32
318     struct _wdirent *ent = vlc_wreaddir (dir);
319     if (ent == NULL)
320         return NULL;
321
322     return FromWide (ent->d_name);
323 #else
324     struct dirent *ent;
325     struct
326     {
327         struct dirent ent;
328         char buf[NAME_MAX + 1];
329     } buf;
330     int val = readdir_r (dir, &buf.ent, &ent);
331     if (val)
332     {
333         errno = val;
334         return NULL;
335     }
336     return ent ? vlc_fix_readdir( ent->d_name ) : NULL;
337 #endif
338 }
339
340 static int dummy_select( const char *str )
341 {
342     (void)str;
343     return 1;
344 }
345
346 /**
347  * Does the same as vlc_scandir(), but takes an open directory pointer
348  * instead of a directory path.
349  */
350 int vlc_loaddir( DIR *dir, char ***namelist,
351                   int (*select)( const char * ),
352                   int (*compar)( const char **, const char ** ) )
353 {
354     if( select == NULL )
355         select = dummy_select;
356
357     if( dir == NULL )
358         return -1;
359     else
360     {
361         char **tab = NULL;
362         char *entry;
363         unsigned num = 0;
364
365         rewinddir( dir );
366
367         while( ( entry = vlc_readdir( dir ) ) != NULL )
368         {
369             char **newtab;
370
371             if( !select( entry ) )
372             {
373                 free( entry );
374                 continue;
375             }
376
377             newtab = realloc( tab, sizeof( char * ) * (num + 1) );
378             if( newtab == NULL )
379             {
380                 free( entry );
381                 goto error;
382             }
383             tab = newtab;
384             tab[num++] = entry;
385         }
386
387         if( compar != NULL )
388             qsort( tab, num, sizeof( tab[0] ),
389                    (int (*)( const void *, const void *))compar );
390
391         *namelist = tab;
392         return num;
393
394     error:{
395         unsigned i;
396
397         for( i = 0; i < num; i++ )
398             free( tab[i] );
399         free( tab );
400         }
401     }
402     return -1;
403 }
404
405 /**
406  * Selects file entries from a directory, as GNU C scandir().
407  *
408  * @param dirname UTF-8 diretory path
409  * @param pointer [OUT] pointer set, on succesful completion, to the address
410  * of a table of UTF-8 filenames. All filenames must be freed with free().
411  * The table itself must be freed with free() as well.
412  *
413  * @return How many file names were selected (possibly 0),
414  * or -1 in case of error.
415  */
416 int vlc_scandir( const char *dirname, char ***namelist,
417                   int (*select)( const char * ),
418                   int (*compar)( const char **, const char ** ) )
419 {
420     DIR *dir = vlc_opendir (dirname);
421     int val = -1;
422
423     if (dir != NULL)
424     {
425         val = vlc_loaddir (dir, namelist, select, compar);
426         closedir (dir);
427     }
428     return val;
429 }
430
431 static int vlc_statEx( const char *filename, struct stat *buf,
432                         bool deref )
433 {
434 #ifdef UNDER_CE
435     /*_stat translates to wchar internally on WinCE*/
436     return _stat( filename, buf );
437 #elif defined (WIN32)
438     CONVERT_PATH (filename, wpath, -1);
439     return _wstati64 (wpath, buf);
440
441 #endif
442 #ifdef HAVE_SYS_STAT_H
443     const char *local_name = ToLocale( filename );
444
445     if( local_name != NULL )
446     {
447         int res = deref ? stat( local_name, buf )
448                        : lstat( local_name, buf );
449         LocaleFree( local_name );
450         return res;
451     }
452     errno = ENOENT;
453 #endif
454     return -1;
455 }
456
457 /**
458  * Finds file/inode informations, as stat().
459  * Consider using fstat() instead, if possible.
460  *
461  * @param filename UTF-8 file path
462  */
463 int vlc_stat( const char *filename, struct stat *buf)
464 {
465     return vlc_statEx( filename, buf, true );
466 }
467
468 /**
469  * Finds file/inode informations, as lstat().
470  * Consider using fstat() instead, if possible.
471  *
472  * @param filename UTF-8 file path
473  */
474 int vlc_lstat( const char *filename, struct stat *buf)
475 {
476     return vlc_statEx( filename, buf, false );
477 }
478
479 /**
480  * Removes a file.
481  *
482  * @param filename a UTF-8 string with the name of the file you want to delete.
483  * @return A 0 return value indicates success. A -1 return value indicates an
484  *        error, and an error code is stored in errno
485  */
486 int vlc_unlink( const char *filename )
487 {
488 #ifdef UNDER_CE
489     /*_open translates to wchar internally on WinCE*/
490     return _unlink( filename );
491 #elif defined (WIN32)
492     CONVERT_PATH (filename, wpath, -1);
493     return _wunlink (wpath);
494
495 #endif
496     const char *local_name = ToLocale( filename );
497
498     if( local_name == NULL )
499     {
500         errno = ENOENT;
501         return -1;
502     }
503
504     int ret = unlink( local_name );
505     LocaleFree( local_name );
506     return ret;
507 }
508
509 /**
510  * Moves a file atomically. This only works within a single file system.
511  *
512  * @param oldpath path to the file before the move
513  * @param newpath intended path to the file after the move
514  * @return A 0 return value indicates success. A -1 return value indicates an
515  *        error, and an error code is stored in errno
516  */
517 int vlc_rename (const char *oldpath, const char *newpath)
518 {
519 #if defined (WIN32)
520     CONVERT_PATH (oldpath, wold, -1);
521     CONVERT_PATH (newpath, wnew, -1);
522 # ifdef UNDER_CE
523     /* FIXME: errno support */
524     if (MoveFileW (wold, wnew))
525         return 0;
526     else
527         return -1;
528 #else
529     if (_wrename (wold, wnew) && errno == EACCES)
530     {   /* Windows does not allow atomic file replacement */
531         if (_wremove (wnew))
532         {
533             errno = EACCES; /* restore errno */
534             return -1;
535         }
536         if (_wrename (wold, wnew))
537             return -1;
538     }
539     return 0;
540 #endif
541
542 #endif
543     const char *lo = ToLocale (oldpath);
544     if (lo == NULL)
545         goto error;
546
547     const char *ln = ToLocale (newpath);
548     if (ln == NULL)
549     {
550         LocaleFree (lo);
551 error:
552         errno = ENOENT;
553         return -1;
554     }
555
556     int ret = rename (lo, ln);
557     LocaleFree (lo);
558     LocaleFree (ln);
559     return ret;
560 }
561
562 int vlc_mkstemp( char *template )
563 {
564     static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
565     static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
566
567     /* */
568     assert( template );
569
570     /* Check template validity */
571     const size_t i_length = strlen( template );
572     char *psz_rand = &template[i_length-6];
573
574     if( i_length < 6 || strcmp( psz_rand, "XXXXXX" ) )
575     {
576         errno = EINVAL;
577         return -1;
578     }
579
580     /* */
581     for( int i = 0; i < 256; i++ )
582     {
583         /* Create a pseudo random file name */
584         uint8_t pi_rand[6];
585
586         vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
587         for( int j = 0; j < 6; j++ )
588             psz_rand[j] = digits[pi_rand[j] % i_digits];
589
590         /* */
591         int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
592         if( fd >= 0 )
593             return fd;
594         if( errno != EEXIST )
595             return -1;
596     }
597
598     errno = EEXIST;
599     return -1;
600 }
601
602 #ifdef UNDER_CE
603 # define dup(fd) (fd, -1)
604 #endif
605
606 /**
607  * Duplicates a file descriptor. The new file descriptor has the close-on-exec
608  * descriptor flag set.
609  * @return a new file descriptor or -1
610  */
611 int vlc_dup (int oldfd)
612 {
613     int newfd;
614
615 #ifdef HAVE_DUP3
616     /* Unfortunately, dup3() works like dup2(), not like plain dup(). So we
617      * need such contortion to find the new file descriptor while preserving
618      * thread safety of the file descriptor table. */
619     newfd = vlc_open ("/dev/null", O_RDONLY);
620     if (likely(newfd != -1))
621     {
622         if (likely(dup3 (oldfd, newfd, O_CLOEXEC) == newfd))
623             return newfd;
624         close (newfd);
625     }
626 #endif
627
628     newfd = dup (oldfd);
629 #ifdef HAVE_FCNTL
630     if (likely(newfd != -1))
631         fcntl (newfd, F_SETFD, FD_CLOEXEC);
632 #endif
633     return newfd;
634 }
635
636 #include <vlc_network.h>
637
638 /**
639  * Creates a socket file descriptor. The new file descriptor has the
640  * close-on-exec flag set.
641  * @param pf protocol family
642  * @param type socket type
643  * @param proto network protocol
644  * @param nonblock true to create a non-blocking socket
645  * @return a new file descriptor or -1
646  */
647 int vlc_socket (int pf, int type, int proto, bool nonblock)
648 {
649     int fd;
650
651 #ifdef SOCK_CLOEXEC
652     type |= SOCK_CLOEXEC;
653     if (nonblock)
654         type |= SOCK_NONBLOCK;
655     fd = socket (pf, type, proto);
656     if (fd != -1 || errno != EINVAL)
657         return fd;
658
659     type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
660 #endif
661
662     fd = socket (pf, type, proto);
663     if (fd == -1)
664         return -1;
665
666 #ifndef WIN32
667     fcntl (fd, F_SETFD, FD_CLOEXEC);
668     if (nonblock)
669         fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
670 #else
671     if (nonblock)
672         ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
673 #endif
674     return fd;
675 }
676
677 /**
678  * Accepts an inbound connection request on a listening socket.
679  * The new file descriptor has the close-on-exec flag set.
680  * @param lfd listening socket file descriptor
681  * @param addr pointer to the peer address or NULL [OUT]
682  * @param alen pointer to the length of the peer address or NULL [OUT]
683  * @param nonblock whether to put the new socket in non-blocking mode
684  * @return a new file descriptor, or -1 on error.
685  */
686 int vlc_accept (int lfd, struct sockaddr *addr, socklen_t *alen, bool nonblock)
687 {
688 #ifdef HAVE_ACCEPT4
689     int flags = SOCK_CLOEXEC;
690     if (nonblock)
691         flags |= SOCK_NONBLOCK;
692
693     do
694     {
695         int fd = accept4 (lfd, addr, alen, flags);
696         if (fd != -1)
697             return fd;
698     }
699     while (errno == EINTR);
700
701     if (errno != ENOSYS)
702         return -1;
703 #endif
704 #ifdef WIN32
705     errno = 0;
706 #endif
707
708     do
709     {
710         int fd = accept (lfd, addr, alen);
711         if (fd != -1)
712         {
713 #ifndef WIN32
714             fcntl (fd, F_SETFD, FD_CLOEXEC);
715             if (nonblock)
716                 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
717 #else
718             if (nonblock)
719                 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
720 #endif
721             return fd;
722         }
723     }
724     while (errno == EINTR);
725
726     return -1;
727 }