1 /*****************************************************************************
2 * filesystem.c: File system helpers
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2008 Rémi Denis-Courmont
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
34 #include "libvlc.h" /* vlc_mkdir */
41 #include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
53 # include <winsock2.h>
61 # include <sys/socket.h>
65 # define lstat( a, b ) stat(a, b)
69 static int convert_path (const char *restrict path, wchar_t *restrict wpath)
71 if (!MultiByteToWideChar (CP_UTF8, 0, path, -1, wpath, MAX_PATH))
76 wpath[MAX_PATH] = L'\0';
79 # define CONVERT_PATH(path, wpath, err) \
80 wchar_t wpath[MAX_PATH+1]; \
81 if (convert_path (path, wpath)) \
86 * Opens a system file handle.
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.
94 int vlc_open (const char *filename, int flags, ...)
96 unsigned int mode = 0;
101 mode = va_arg (ap, unsigned int);
109 /*_open translates to wchar internally on WinCE*/
110 return _open (filename, flags, mode);
111 #elif defined (WIN32)
113 * open() cannot open files with non-“ANSI” characters on Windows.
114 * We use _wopen() instead. Same thing for mkdir() and stat().
116 CONVERT_PATH(filename, wpath, -1);
117 return _wopen (wpath, flags, mode);
120 const char *local_name = ToLocale (filename);
122 if (local_name == NULL)
128 int fd = open (local_name, flags, mode);
131 fcntl (fd, F_SETFD, FD_CLOEXEC);
134 LocaleFree (local_name);
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.
144 FILE *vlc_fopen (const char *filename, const char *mode)
146 int rwflags = 0, oflags = 0;
149 for (const char *ptr = mode; *ptr; ptr++)
165 oflags |= O_CREAT | O_TRUNC;
180 int fd = vlc_open (filename, rwflags | oflags, 0666);
184 if (append && (lseek (fd, 0, SEEK_END) == -1))
190 FILE *stream = fdopen (fd, mode);
198 * Opens a system file handle relative to an existing directory handle.
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.
207 int vlc_openat (int dir, const char *filename, int flags, ...)
209 unsigned int mode = 0;
212 va_start (ap, flags);
214 mode = va_arg (ap, unsigned int);
221 const char *local_name = ToLocale (filename);
222 if (local_name == NULL)
228 #ifdef HAVE_FDOPENDIR
229 int fd = openat (dir, local_name, flags, mode);
232 fcntl (fd, F_SETFD, FD_CLOEXEC);
239 LocaleFree (local_name);
245 * Creates a directory using UTF-8 paths.
247 * @param dirname a UTF-8 string with the name of the directory that you
249 * @param mode directory permissions
250 * @return 0 on success, -1 on error (see errno).
252 int vlc_mkdir( const char *dirname, mode_t mode )
254 #if defined (UNDER_CE)
256 /* mkdir converts internally to wchar */
257 return _mkdir(dirname);
258 #elif defined (WIN32)
260 CONVERT_PATH (dirname, wpath, -1);
261 return _wmkdir (wpath);
264 char *locname = ToLocale( dirname );
267 if( locname == NULL )
272 res = mkdir( locname, mode );
274 LocaleFree( locname );
280 * Opens a DIR pointer.
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().
286 DIR *vlc_opendir( const char *dirname )
289 CONVERT_PATH (dirname, wpath, NULL);
290 return (DIR *)vlc_wopendir (wpath);
293 const char *local_name = ToLocale( dirname );
295 if( local_name != NULL )
297 DIR *dir = opendir( local_name );
298 LocaleFree( local_name );
308 * Reads the next file name from an open directory.
310 * @param dir The directory that is being read
312 * @return a UTF-8 string of the directory entry.
313 * Use free() to free this memory.
315 char *vlc_readdir( DIR *dir )
318 struct _wdirent *ent = vlc_wreaddir (dir);
322 return FromWide (ent->d_name);
326 ent = readdir( (DIR *)dir );
330 return vlc_fix_readdir( ent->d_name );
334 static int dummy_select( const char *str )
341 * Does the same as vlc_scandir(), but takes an open directory pointer
342 * instead of a directory path.
344 int vlc_loaddir( DIR *dir, char ***namelist,
345 int (*select)( const char * ),
346 int (*compar)( const char **, const char ** ) )
349 select = dummy_select;
361 while( ( entry = vlc_readdir( dir ) ) != NULL )
365 if( !select( entry ) )
371 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
382 qsort( tab, num, sizeof( tab[0] ),
383 (int (*)( const void *, const void *))compar );
391 for( i = 0; i < num; i++ )
400 * Selects file entries from a directory, as GNU C scandir().
402 * @param dirname UTF-8 diretory path
403 * @param pointer [OUT] pointer set, on succesful completion, to the address
404 * of a table of UTF-8 filenames. All filenames must be freed with free().
405 * The table itself must be freed with free() as well.
407 * @return How many file names were selected (possibly 0),
408 * or -1 in case of error.
410 int vlc_scandir( const char *dirname, char ***namelist,
411 int (*select)( const char * ),
412 int (*compar)( const char **, const char ** ) )
414 DIR *dir = vlc_opendir (dirname);
419 val = vlc_loaddir (dir, namelist, select, compar);
425 static int vlc_statEx( const char *filename, struct stat *buf,
429 /*_stat translates to wchar internally on WinCE*/
430 return _stat( filename, buf );
431 #elif defined (WIN32)
432 CONVERT_PATH (filename, wpath, -1);
433 return _wstati64 (wpath, buf);
436 #ifdef HAVE_SYS_STAT_H
437 const char *local_name = ToLocale( filename );
439 if( local_name != NULL )
441 int res = deref ? stat( local_name, buf )
442 : lstat( local_name, buf );
443 LocaleFree( local_name );
452 * Finds file/inode informations, as stat().
453 * Consider using fstat() instead, if possible.
455 * @param filename UTF-8 file path
457 int vlc_stat( const char *filename, struct stat *buf)
459 return vlc_statEx( filename, buf, true );
463 * Finds file/inode informations, as lstat().
464 * Consider using fstat() instead, if possible.
466 * @param filename UTF-8 file path
468 int vlc_lstat( const char *filename, struct stat *buf)
470 return vlc_statEx( filename, buf, false );
476 * @param filename a UTF-8 string with the name of the file you want to delete.
477 * @return A 0 return value indicates success. A -1 return value indicates an
478 * error, and an error code is stored in errno
480 int vlc_unlink( const char *filename )
483 /*_open translates to wchar internally on WinCE*/
484 return _unlink( filename );
485 #elif defined (WIN32)
486 CONVERT_PATH (filename, wpath, -1);
487 return _wunlink (wpath);
490 const char *local_name = ToLocale( filename );
492 if( local_name == NULL )
498 int ret = unlink( local_name );
499 LocaleFree( local_name );
504 * Moves a file atomically. This only works within a single file system.
506 * @param oldpath path to the file before the move
507 * @param newpath intended path to the file after the move
508 * @return A 0 return value indicates success. A -1 return value indicates an
509 * error, and an error code is stored in errno
511 int vlc_rename (const char *oldpath, const char *newpath)
514 CONVERT_PATH (oldpath, wold, -1);
515 CONVERT_PATH (newpath, wnew, -1);
517 /* FIXME: errno support */
518 if (MoveFileW (wold, wnew))
523 return _wrename (wold, wnew);
527 const char *lo = ToLocale (oldpath);
531 const char *ln = ToLocale (newpath);
540 int ret = rename (lo, ln);
546 int vlc_mkstemp( char *template )
548 static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
549 static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
554 /* Check template validity */
555 const size_t i_length = strlen( template );
556 char *psz_rand = &template[i_length-6];
558 if( i_length < 6 || strcmp( psz_rand, "XXXXXX" ) )
565 for( int i = 0; i < 256; i++ )
567 /* Create a pseudo random file name */
570 vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
571 for( int j = 0; j < 6; j++ )
572 psz_rand[j] = digits[pi_rand[j] % i_digits];
575 int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
578 if( errno != EEXIST )
587 # define dup(fd) (fd, -1)
591 * Duplicates a file descriptor. The new file descriptor has the close-on-exec
592 * descriptor flag set.
593 * @return a new file descriptor or -1
595 int vlc_dup (int oldfd)
600 /* Unfortunately, dup3() works like dup2(), not like plain dup(). So we
601 * need such contortion to find the new file descriptor while preserving
602 * thread safety of the file descriptor table. */
603 newfd = vlc_open ("/dev/null", O_RDONLY);
604 if (likely(newfd != -1))
606 if (likely(dup3 (oldfd, newfd, O_CLOEXEC) == newfd))
614 if (likely(newfd != -1))
615 fcntl (newfd, F_SETFD, FD_CLOEXEC);
620 #include <vlc_network.h>
623 * Creates a socket file descriptor. The new file descriptor has the
624 * close-on-exec flag set.
625 * @param pf protocol family
626 * @param type socket type
627 * @param proto network protocol
628 * @param nonblock true to create a non-blocking socket
629 * @return a new file descriptor or -1
631 int vlc_socket (int pf, int type, int proto, bool nonblock)
636 type |= SOCK_CLOEXEC;
638 type |= SOCK_NONBLOCK;
639 fd = socket (pf, type, proto);
640 if (fd != -1 || errno != EINVAL)
643 type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
646 fd = socket (pf, type, proto);
651 fcntl (fd, F_SETFD, FD_CLOEXEC);
653 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
656 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
662 * Accepts an inbound connection request on a listening socket.
663 * The new file descriptor has the close-on-exec flag set.
664 * @param lfd listening socket file descriptor
665 * @param addr pointer to the peer address or NULL [OUT]
666 * @param alen pointer to the length of the peer address or NULL [OUT]
667 * @param nonblock whether to put the new socket in non-blocking mode
668 * @return a new file descriptor, or -1 on error.
670 int vlc_accept (int lfd, struct sockaddr *addr, socklen_t *alen, bool nonblock)
673 int flags = SOCK_CLOEXEC;
675 flags |= SOCK_NONBLOCK;
679 int fd = accept4 (lfd, addr, alen, flags);
683 while (errno == EINTR);
694 int fd = accept (lfd, addr, alen);
698 fcntl (fd, F_SETFD, FD_CLOEXEC);
700 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
703 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
708 while (errno == EINTR);