]> git.sesse.net Git - vlc/blob - src/text/filesystem.c
Use var_Inherit* instead of var_CreateGet*.
[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 #include <dirent.h>
44 #ifdef HAVE_SYS_STAT_H
45 # include <sys/stat.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 # include <fcntl.h>
49 #endif
50 #ifdef WIN32
51 # include <io.h>
52 # include <winsock2.h>
53 # ifndef UNDER_CE
54 #  include <direct.h>
55 # else
56 #  include <tchar.h>
57 # endif
58 #else
59 # include <unistd.h>
60 # include <sys/socket.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  * Opens a system file handle relative to an existing directory handle.
198  *
199  * @param dir directory file descriptor
200  * @param filename file path to open (with UTF-8 encoding)
201  * @param flags open() flags, see the C library open() documentation
202  * @return a file handle on success, -1 on error (see errno).
203  * @note Contrary to standard open(), this function returns file handles
204  * with the close-on-exec flag enabled.
205  */
206 int vlc_openat (int dir, const char *filename, int flags, ...)
207 {
208     unsigned int mode = 0;
209     va_list ap;
210
211     va_start (ap, flags);
212     if (flags & O_CREAT)
213         mode = va_arg (ap, unsigned int);
214     va_end (ap);
215
216 #ifdef O_CLOEXEC
217     flags |= O_CLOEXEC;
218 #endif
219
220     const char *local_name = ToLocale (filename);
221     if (local_name == NULL)
222     {
223         errno = ENOENT;
224         return -1;
225     }
226
227 #ifdef HAVE_OPENAT
228     int fd = openat (dir, local_name, flags, mode);
229 # ifdef HAVE_FCNTL
230     if (fd != -1)
231         fcntl (fd, F_SETFD, FD_CLOEXEC);
232 # endif
233 #else
234     int fd = -1;
235     errno = ENOSYS;
236 #endif
237
238     LocaleFree (local_name);
239     return fd;
240 }
241
242
243 /**
244  * Creates a directory using UTF-8 paths.
245  *
246  * @param dirname a UTF-8 string with the name of the directory that you
247  *        want to create.
248  * @param mode directory permissions
249  * @return 0 on success, -1 on error (see errno).
250  */
251 int vlc_mkdir( const char *dirname, mode_t mode )
252 {
253 #if defined (UNDER_CE)
254     (void) mode;
255     /* mkdir converts internally to wchar */
256     return _mkdir(dirname);
257 #elif defined (WIN32)
258     (void) mode;
259     CONVERT_PATH (dirname, wpath, -1);
260     return _wmkdir (wpath);
261
262 #else
263     char *locname = ToLocale( dirname );
264     int res;
265
266     if( locname == NULL )
267     {
268         errno = ENOENT;
269         return -1;
270     }
271     res = mkdir( locname, mode );
272
273     LocaleFree( locname );
274     return res;
275 #endif
276 }
277
278 /**
279  * Opens a DIR pointer.
280  *
281  * @param dirname UTF-8 representation of the directory name
282  * @return a pointer to the DIR struct, or NULL in case of error.
283  * Release with standard closedir().
284  */
285 DIR *vlc_opendir( const char *dirname )
286 {
287 #ifdef WIN32
288     CONVERT_PATH (dirname, wpath, NULL);
289     return (DIR *)vlc_wopendir (wpath);
290
291 #else
292     const char *local_name = ToLocale( dirname );
293
294     if( local_name != NULL )
295     {
296         DIR *dir = opendir( local_name );
297         LocaleFree( local_name );
298         return dir;
299     }
300 #endif
301
302     errno = ENOENT;
303     return NULL;
304 }
305
306 /**
307  * Reads the next file name from an open directory.
308  *
309  * @param dir The directory that is being read
310  *
311  * @return a UTF-8 string of the directory entry. Use free() to release it.
312  * If there are no more entries in the directory, NULL is returned.
313  * If an error occurs, errno is set and NULL is returned.
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     /* Beware that readdir_r() assumes <buf> is large enough to hold the result
325      * dirent including the file name. A buffer overflow could occur otherwise.
326      * In particular, pathconf() and _POSIX_NAME_MAX cannot be used here. */
327     struct dirent *ent;
328     char *path = NULL;
329
330     long len = fpathconf (dirfd (dir), _PC_NAME_MAX);
331     if (len == -1)
332     {
333 #ifdef NAME_MAX
334         len = NAME_MAX;
335 #else
336         errno = ENOMEM;
337         return NULL; // OS is broken. There is no sane way to fix this.
338 #endif
339     }
340     len += offsetof (struct dirent, d_name) + 1;
341
342     struct dirent *buf = malloc (len);
343     if (unlikely(buf == NULL))
344         return NULL;
345
346     int val = readdir_r (dir, buf, &ent);
347     if (val != 0)
348         errno = val;
349     else if (ent != NULL)
350         path = vlc_fix_readdir (ent->d_name);
351     free (buf);
352     return path;
353 #endif
354 }
355
356 static int dummy_select( const char *str )
357 {
358     (void)str;
359     return 1;
360 }
361
362 /**
363  * Does the same as vlc_scandir(), but takes an open directory pointer
364  * instead of a directory path.
365  */
366 int vlc_loaddir( DIR *dir, char ***namelist,
367                   int (*select)( const char * ),
368                   int (*compar)( const char **, const char ** ) )
369 {
370     assert (dir);
371
372     if (select == NULL)
373         select = dummy_select;
374
375     char **tab = NULL;
376     unsigned num = 0;
377
378     rewinddir (dir);
379
380     for (unsigned size = 0;;)
381     {
382         errno = 0;
383         char *entry = vlc_readdir (dir);
384         if (entry == NULL)
385         {
386             if (errno)
387                 goto error;
388             break;
389         }
390
391         if (!select (entry))
392         {
393             free (entry);
394             continue;
395         }
396
397         if (num >= size)
398         {
399             size = size ? (2 * size) : 16;
400             char **newtab = realloc (tab, sizeof (*tab) * (size));
401
402             if (unlikely(newtab == NULL))
403             {
404                 free (entry);
405                 goto error;
406             }
407             tab = newtab;
408         }
409
410         tab[num++] = entry;
411     }
412
413     if (compar != NULL)
414         qsort (tab, num, sizeof (*tab),
415                (int (*)( const void *, const void *))compar);
416     *namelist = tab;
417     return num;
418
419 error:
420     for (unsigned i = 0; i < num; i++)
421         free (tab[i]);
422     free (tab);
423     return -1;
424 }
425
426 /**
427  * Selects file entries from a directory, as GNU C scandir().
428  *
429  * @param dirname UTF-8 diretory path
430  * @param pointer [OUT] pointer set, on successful completion, to the address
431  * of a table of UTF-8 filenames. All filenames must be freed with free().
432  * The table itself must be freed with free() as well.
433  *
434  * @return How many file names were selected (possibly 0),
435  * or -1 in case of error.
436  */
437 int vlc_scandir( const char *dirname, char ***namelist,
438                   int (*select)( const char * ),
439                   int (*compar)( const char **, const char ** ) )
440 {
441     DIR *dir = vlc_opendir (dirname);
442     int val = -1;
443
444     if (dir != NULL)
445     {
446         val = vlc_loaddir (dir, namelist, select, compar);
447         closedir (dir);
448     }
449     return val;
450 }
451
452 static int vlc_statEx( const char *filename, struct stat *buf,
453                         bool deref )
454 {
455 #ifdef UNDER_CE
456     /*_stat translates to wchar internally on WinCE*/
457     return _stat( filename, buf );
458 #elif defined (WIN32)
459     CONVERT_PATH (filename, wpath, -1);
460     return _wstati64 (wpath, buf);
461
462 #endif
463 #ifdef HAVE_SYS_STAT_H
464     const char *local_name = ToLocale( filename );
465
466     if( local_name != NULL )
467     {
468         int res = deref ? stat( local_name, buf )
469                        : lstat( local_name, buf );
470         LocaleFree( local_name );
471         return res;
472     }
473     errno = ENOENT;
474 #endif
475     return -1;
476 }
477
478 /**
479  * Finds file/inode information, as stat().
480  * Consider using fstat() instead, if possible.
481  *
482  * @param filename UTF-8 file path
483  */
484 int vlc_stat( const char *filename, struct stat *buf)
485 {
486     return vlc_statEx( filename, buf, true );
487 }
488
489 /**
490  * Finds file/inode information, as lstat().
491  * Consider using fstat() instead, if possible.
492  *
493  * @param filename UTF-8 file path
494  */
495 int vlc_lstat( const char *filename, struct stat *buf)
496 {
497     return vlc_statEx( filename, buf, false );
498 }
499
500 /**
501  * Removes a file.
502  *
503  * @param filename a UTF-8 string with the name of the file you want to delete.
504  * @return A 0 return value indicates success. A -1 return value indicates an
505  *        error, and an error code is stored in errno
506  */
507 int vlc_unlink( const char *filename )
508 {
509 #ifdef UNDER_CE
510     /*_open translates to wchar internally on WinCE*/
511     return _unlink( filename );
512 #elif defined (WIN32)
513     CONVERT_PATH (filename, wpath, -1);
514     return _wunlink (wpath);
515
516 #endif
517     const char *local_name = ToLocale( filename );
518
519     if( local_name == NULL )
520     {
521         errno = ENOENT;
522         return -1;
523     }
524
525     int ret = unlink( local_name );
526     LocaleFree( local_name );
527     return ret;
528 }
529
530 /**
531  * Moves a file atomically. This only works within a single file system.
532  *
533  * @param oldpath path to the file before the move
534  * @param newpath intended path to the file after the move
535  * @return A 0 return value indicates success. A -1 return value indicates an
536  *        error, and an error code is stored in errno
537  */
538 int vlc_rename (const char *oldpath, const char *newpath)
539 {
540 #if defined (WIN32)
541     CONVERT_PATH (oldpath, wold, -1);
542     CONVERT_PATH (newpath, wnew, -1);
543 # ifdef UNDER_CE
544     /* FIXME: errno support */
545     if (MoveFileW (wold, wnew))
546         return 0;
547     else
548         return -1;
549 #else
550     if (_wrename (wold, wnew) && errno == EACCES)
551     {   /* Windows does not allow atomic file replacement */
552         if (_wremove (wnew))
553         {
554             errno = EACCES; /* restore errno */
555             return -1;
556         }
557         if (_wrename (wold, wnew))
558             return -1;
559     }
560     return 0;
561 #endif
562
563 #endif
564     const char *lo = ToLocale (oldpath);
565     if (lo == NULL)
566         goto error;
567
568     const char *ln = ToLocale (newpath);
569     if (ln == NULL)
570     {
571         LocaleFree (lo);
572 error:
573         errno = ENOENT;
574         return -1;
575     }
576
577     int ret = rename (lo, ln);
578     LocaleFree (lo);
579     LocaleFree (ln);
580     return ret;
581 }
582
583 int vlc_mkstemp( char *template )
584 {
585     static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
586     static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
587
588     /* */
589     assert( template );
590
591     /* Check template validity */
592     const size_t i_length = strlen( template );
593     char *psz_rand = &template[i_length-6];
594
595     if( i_length < 6 || strcmp( psz_rand, "XXXXXX" ) )
596     {
597         errno = EINVAL;
598         return -1;
599     }
600
601     /* */
602     for( int i = 0; i < 256; i++ )
603     {
604         /* Create a pseudo random file name */
605         uint8_t pi_rand[6];
606
607         vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
608         for( int j = 0; j < 6; j++ )
609             psz_rand[j] = digits[pi_rand[j] % i_digits];
610
611         /* */
612         int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
613         if( fd >= 0 )
614             return fd;
615         if( errno != EEXIST )
616             return -1;
617     }
618
619     errno = EEXIST;
620     return -1;
621 }
622
623 #ifdef UNDER_CE
624 # define dup(fd) (fd, -1)
625 #endif
626
627 /**
628  * Duplicates a file descriptor. The new file descriptor has the close-on-exec
629  * descriptor flag set.
630  * @return a new file descriptor or -1
631  */
632 int vlc_dup (int oldfd)
633 {
634     int newfd;
635
636 #ifdef HAVE_DUP3
637     /* Unfortunately, dup3() works like dup2(), not like plain dup(). So we
638      * need such contortion to find the new file descriptor while preserving
639      * thread safety of the file descriptor table. */
640     newfd = vlc_open ("/dev/null", O_RDONLY);
641     if (likely(newfd != -1))
642     {
643         if (likely(dup3 (oldfd, newfd, O_CLOEXEC) == newfd))
644             return newfd;
645         close (newfd);
646     }
647 #endif
648
649     newfd = dup (oldfd);
650 #ifdef HAVE_FCNTL
651     if (likely(newfd != -1))
652         fcntl (newfd, F_SETFD, FD_CLOEXEC);
653 #endif
654     return newfd;
655 }
656
657 #include <vlc_network.h>
658
659 /**
660  * Creates a socket file descriptor. The new file descriptor has the
661  * close-on-exec flag set.
662  * @param pf protocol family
663  * @param type socket type
664  * @param proto network protocol
665  * @param nonblock true to create a non-blocking socket
666  * @return a new file descriptor or -1
667  */
668 int vlc_socket (int pf, int type, int proto, bool nonblock)
669 {
670     int fd;
671
672 #ifdef SOCK_CLOEXEC
673     type |= SOCK_CLOEXEC;
674     if (nonblock)
675         type |= SOCK_NONBLOCK;
676     fd = socket (pf, type, proto);
677     if (fd != -1 || errno != EINVAL)
678         return fd;
679
680     type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
681 #endif
682
683     fd = socket (pf, type, proto);
684     if (fd == -1)
685         return -1;
686
687 #ifndef WIN32
688     fcntl (fd, F_SETFD, FD_CLOEXEC);
689     if (nonblock)
690         fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
691 #else
692     if (nonblock)
693         ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
694 #endif
695     return fd;
696 }
697
698 /**
699  * Accepts an inbound connection request on a listening socket.
700  * The new file descriptor has the close-on-exec flag set.
701  * @param lfd listening socket file descriptor
702  * @param addr pointer to the peer address or NULL [OUT]
703  * @param alen pointer to the length of the peer address or NULL [OUT]
704  * @param nonblock whether to put the new socket in non-blocking mode
705  * @return a new file descriptor, or -1 on error.
706  */
707 int vlc_accept (int lfd, struct sockaddr *addr, socklen_t *alen, bool nonblock)
708 {
709 #ifdef HAVE_ACCEPT4
710     int flags = SOCK_CLOEXEC;
711     if (nonblock)
712         flags |= SOCK_NONBLOCK;
713
714     do
715     {
716         int fd = accept4 (lfd, addr, alen, flags);
717         if (fd != -1)
718             return fd;
719     }
720     while (errno == EINTR);
721
722     if (errno != ENOSYS)
723         return -1;
724 #endif
725 #ifdef WIN32
726     errno = 0;
727 #endif
728
729     do
730     {
731         int fd = accept (lfd, addr, alen);
732         if (fd != -1)
733         {
734 #ifndef WIN32
735             fcntl (fd, F_SETFD, FD_CLOEXEC);
736             if (nonblock)
737                 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
738 #else
739             if (nonblock)
740                 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
741 #endif
742             return fd;
743         }
744     }
745     while (errno == EINTR);
746
747     return -1;
748 }