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