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 */
40 #include <limits.h> /* NAME_MAX */
41 #if !defined(NAME_MAX) && defined(_POSIX_NAME_MAX)
42 # define NAME_MAX _POSIX_NAME_MAX
45 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
55 # include <winsock2.h>
63 # include <sys/socket.h>
67 # define lstat( a, b ) stat(a, b)
71 static int convert_path (const char *restrict path, wchar_t *restrict wpath)
73 if (!MultiByteToWideChar (CP_UTF8, 0, path, -1, wpath, MAX_PATH))
78 wpath[MAX_PATH] = L'\0';
81 # define CONVERT_PATH(path, wpath, err) \
82 wchar_t wpath[MAX_PATH+1]; \
83 if (convert_path (path, wpath)) \
88 * Opens a system file handle.
90 * @param filename file path to open (with UTF-8 encoding)
91 * @param flags open() flags, see the C library open() documentation
92 * @return a file handle on success, -1 on error (see errno).
93 * @note Contrary to standard open(), this function returns file handles
94 * with the close-on-exec flag enabled.
96 int vlc_open (const char *filename, int flags, ...)
98 unsigned int mode = 0;
101 va_start (ap, flags);
103 mode = va_arg (ap, unsigned int);
111 /*_open translates to wchar internally on WinCE*/
112 return _open (filename, flags, mode);
113 #elif defined (WIN32)
115 * open() cannot open files with non-“ANSI” characters on Windows.
116 * We use _wopen() instead. Same thing for mkdir() and stat().
118 CONVERT_PATH(filename, wpath, -1);
119 return _wopen (wpath, flags, mode);
122 const char *local_name = ToLocale (filename);
124 if (local_name == NULL)
130 int fd = open (local_name, flags, mode);
133 fcntl (fd, F_SETFD, FD_CLOEXEC);
136 LocaleFree (local_name);
141 * Opens a FILE pointer.
142 * @param filename file path, using UTF-8 encoding
143 * @param mode fopen file open mode
144 * @return NULL on error, an open FILE pointer on success.
146 FILE *vlc_fopen (const char *filename, const char *mode)
148 int rwflags = 0, oflags = 0;
151 for (const char *ptr = mode; *ptr; ptr++)
167 oflags |= O_CREAT | O_TRUNC;
182 int fd = vlc_open (filename, rwflags | oflags, 0666);
186 if (append && (lseek (fd, 0, SEEK_END) == -1))
192 FILE *stream = fdopen (fd, mode);
200 * Opens a system file handle relative to an existing directory handle.
202 * @param dir directory file descriptor
203 * @param filename file path to open (with UTF-8 encoding)
204 * @param flags open() flags, see the C library open() documentation
205 * @return a file handle on success, -1 on error (see errno).
206 * @note Contrary to standard open(), this function returns file handles
207 * with the close-on-exec flag enabled.
209 int vlc_openat (int dir, const char *filename, int flags, ...)
211 unsigned int mode = 0;
214 va_start (ap, flags);
216 mode = va_arg (ap, unsigned int);
223 const char *local_name = ToLocale (filename);
224 if (local_name == NULL)
231 int fd = openat (dir, local_name, flags, mode);
234 fcntl (fd, F_SETFD, FD_CLOEXEC);
241 LocaleFree (local_name);
247 * Creates a directory using UTF-8 paths.
249 * @param dirname a UTF-8 string with the name of the directory that you
251 * @param mode directory permissions
252 * @return 0 on success, -1 on error (see errno).
254 int vlc_mkdir( const char *dirname, mode_t mode )
256 #if defined (UNDER_CE)
258 /* mkdir converts internally to wchar */
259 return _mkdir(dirname);
260 #elif defined (WIN32)
262 CONVERT_PATH (dirname, wpath, -1);
263 return _wmkdir (wpath);
266 char *locname = ToLocale( dirname );
269 if( locname == NULL )
274 res = mkdir( locname, mode );
276 LocaleFree( locname );
282 * Opens a DIR pointer.
284 * @param dirname UTF-8 representation of the directory name
285 * @return a pointer to the DIR struct, or NULL in case of error.
286 * Release with standard closedir().
288 DIR *vlc_opendir( const char *dirname )
291 CONVERT_PATH (dirname, wpath, NULL);
292 return (DIR *)vlc_wopendir (wpath);
295 const char *local_name = ToLocale( dirname );
297 if( local_name != NULL )
299 DIR *dir = opendir( local_name );
300 LocaleFree( local_name );
310 * Reads the next file name from an open directory.
312 * @param dir The directory that is being read
314 * @return a UTF-8 string of the directory entry.
315 * Use free() to free this memory.
317 char *vlc_readdir( DIR *dir )
320 struct _wdirent *ent = vlc_wreaddir (dir);
324 return FromWide (ent->d_name);
330 char buf[NAME_MAX + 1];
332 int val = readdir_r (dir, &buf.ent, &ent);
338 return ent ? vlc_fix_readdir( ent->d_name ) : NULL;
342 static int dummy_select( const char *str )
349 * Does the same as vlc_scandir(), but takes an open directory pointer
350 * instead of a directory path.
352 int vlc_loaddir( DIR *dir, char ***namelist,
353 int (*select)( const char * ),
354 int (*compar)( const char **, const char ** ) )
357 select = dummy_select;
369 while( ( entry = vlc_readdir( dir ) ) != NULL )
373 if( !select( entry ) )
379 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
390 qsort( tab, num, sizeof( tab[0] ),
391 (int (*)( const void *, const void *))compar );
399 for( i = 0; i < num; i++ )
408 * Selects file entries from a directory, as GNU C scandir().
410 * @param dirname UTF-8 diretory path
411 * @param pointer [OUT] pointer set, on successful completion, to the address
412 * of a table of UTF-8 filenames. All filenames must be freed with free().
413 * The table itself must be freed with free() as well.
415 * @return How many file names were selected (possibly 0),
416 * or -1 in case of error.
418 int vlc_scandir( const char *dirname, char ***namelist,
419 int (*select)( const char * ),
420 int (*compar)( const char **, const char ** ) )
422 DIR *dir = vlc_opendir (dirname);
427 val = vlc_loaddir (dir, namelist, select, compar);
433 static int vlc_statEx( const char *filename, struct stat *buf,
437 /*_stat translates to wchar internally on WinCE*/
438 return _stat( filename, buf );
439 #elif defined (WIN32)
440 CONVERT_PATH (filename, wpath, -1);
441 return _wstati64 (wpath, buf);
444 #ifdef HAVE_SYS_STAT_H
445 const char *local_name = ToLocale( filename );
447 if( local_name != NULL )
449 int res = deref ? stat( local_name, buf )
450 : lstat( local_name, buf );
451 LocaleFree( local_name );
460 * Finds file/inode information, as stat().
461 * Consider using fstat() instead, if possible.
463 * @param filename UTF-8 file path
465 int vlc_stat( const char *filename, struct stat *buf)
467 return vlc_statEx( filename, buf, true );
471 * Finds file/inode information, as lstat().
472 * Consider using fstat() instead, if possible.
474 * @param filename UTF-8 file path
476 int vlc_lstat( const char *filename, struct stat *buf)
478 return vlc_statEx( filename, buf, false );
484 * @param filename a UTF-8 string with the name of the file you want to delete.
485 * @return A 0 return value indicates success. A -1 return value indicates an
486 * error, and an error code is stored in errno
488 int vlc_unlink( const char *filename )
491 /*_open translates to wchar internally on WinCE*/
492 return _unlink( filename );
493 #elif defined (WIN32)
494 CONVERT_PATH (filename, wpath, -1);
495 return _wunlink (wpath);
498 const char *local_name = ToLocale( filename );
500 if( local_name == NULL )
506 int ret = unlink( local_name );
507 LocaleFree( local_name );
512 * Moves a file atomically. This only works within a single file system.
514 * @param oldpath path to the file before the move
515 * @param newpath intended path to the file after the move
516 * @return A 0 return value indicates success. A -1 return value indicates an
517 * error, and an error code is stored in errno
519 int vlc_rename (const char *oldpath, const char *newpath)
522 CONVERT_PATH (oldpath, wold, -1);
523 CONVERT_PATH (newpath, wnew, -1);
525 /* FIXME: errno support */
526 if (MoveFileW (wold, wnew))
531 if (_wrename (wold, wnew) && errno == EACCES)
532 { /* Windows does not allow atomic file replacement */
535 errno = EACCES; /* restore errno */
538 if (_wrename (wold, wnew))
545 const char *lo = ToLocale (oldpath);
549 const char *ln = ToLocale (newpath);
558 int ret = rename (lo, ln);
564 int vlc_mkstemp( char *template )
566 static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
567 static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
572 /* Check template validity */
573 const size_t i_length = strlen( template );
574 char *psz_rand = &template[i_length-6];
576 if( i_length < 6 || strcmp( psz_rand, "XXXXXX" ) )
583 for( int i = 0; i < 256; i++ )
585 /* Create a pseudo random file name */
588 vlc_rand_bytes( pi_rand, sizeof(pi_rand) );
589 for( int j = 0; j < 6; j++ )
590 psz_rand[j] = digits[pi_rand[j] % i_digits];
593 int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
596 if( errno != EEXIST )
605 # define dup(fd) (fd, -1)
609 * Duplicates a file descriptor. The new file descriptor has the close-on-exec
610 * descriptor flag set.
611 * @return a new file descriptor or -1
613 int vlc_dup (int oldfd)
618 /* Unfortunately, dup3() works like dup2(), not like plain dup(). So we
619 * need such contortion to find the new file descriptor while preserving
620 * thread safety of the file descriptor table. */
621 newfd = vlc_open ("/dev/null", O_RDONLY);
622 if (likely(newfd != -1))
624 if (likely(dup3 (oldfd, newfd, O_CLOEXEC) == newfd))
632 if (likely(newfd != -1))
633 fcntl (newfd, F_SETFD, FD_CLOEXEC);
638 #include <vlc_network.h>
641 * Creates a socket file descriptor. The new file descriptor has the
642 * close-on-exec flag set.
643 * @param pf protocol family
644 * @param type socket type
645 * @param proto network protocol
646 * @param nonblock true to create a non-blocking socket
647 * @return a new file descriptor or -1
649 int vlc_socket (int pf, int type, int proto, bool nonblock)
654 type |= SOCK_CLOEXEC;
656 type |= SOCK_NONBLOCK;
657 fd = socket (pf, type, proto);
658 if (fd != -1 || errno != EINVAL)
661 type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
664 fd = socket (pf, type, proto);
669 fcntl (fd, F_SETFD, FD_CLOEXEC);
671 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
674 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
680 * Accepts an inbound connection request on a listening socket.
681 * The new file descriptor has the close-on-exec flag set.
682 * @param lfd listening socket file descriptor
683 * @param addr pointer to the peer address or NULL [OUT]
684 * @param alen pointer to the length of the peer address or NULL [OUT]
685 * @param nonblock whether to put the new socket in non-blocking mode
686 * @return a new file descriptor, or -1 on error.
688 int vlc_accept (int lfd, struct sockaddr *addr, socklen_t *alen, bool nonblock)
691 int flags = SOCK_CLOEXEC;
693 flags |= SOCK_NONBLOCK;
697 int fd = accept4 (lfd, addr, alen, flags);
701 while (errno == EINTR);
712 int fd = accept (lfd, addr, alen);
716 fcntl (fd, F_SETFD, FD_CLOEXEC);
718 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
721 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
726 while (errno == EINTR);