net: fix socket blocking if accept4 not available
[vlc/asuraparaju-public.git] / src / text / filesystem.c
blobe230f058c10178b8a45f107e50bf716c1d71d4dd
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 /*****************************************************************************
25 * Preamble
26 *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
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>
37 #include <assert.h>
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
64 #ifndef HAVE_LSTAT
65 # define lstat( a, b ) stat(a, b)
66 #endif
68 #ifdef WIN32
69 static int convert_path (const char *restrict path, wchar_t *restrict wpath)
71 if (!MultiByteToWideChar (CP_UTF8, 0, path, -1, wpath, MAX_PATH))
73 errno = ENOENT;
74 return -1;
76 wpath[MAX_PATH] = L'\0';
77 return 0;
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
85 /**
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;
97 va_list ap;
99 va_start (ap, flags);
100 if (flags & O_CREAT)
101 mode = va_arg (ap, unsigned int);
102 va_end (ap);
104 #ifdef O_CLOEXEC
105 flags |= O_CLOEXEC;
106 #endif
108 #ifdef UNDER_CE
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);
119 #endif
120 const char *local_name = ToLocale (filename);
122 if (local_name == NULL)
124 errno = ENOENT;
125 return -1;
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
134 LocaleFree (local_name);
135 return fd;
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;
147 bool append = false;
149 for (const char *ptr = mode; *ptr; ptr++)
151 switch (*ptr)
153 case 'r':
154 rwflags = O_RDONLY;
155 break;
157 case 'a':
158 rwflags = O_WRONLY;
159 oflags |= O_CREAT;
160 append = true;
161 break;
163 case 'w':
164 rwflags = O_WRONLY;
165 oflags |= O_CREAT | O_TRUNC;
166 break;
168 case '+':
169 rwflags = O_RDWR;
170 break;
172 #ifdef O_TEXT
173 case 't':
174 oflags |= O_TEXT;
175 break;
176 #endif
180 int fd = vlc_open (filename, rwflags | oflags, 0666);
181 if (fd == -1)
182 return NULL;
184 if (append && (lseek (fd, 0, SEEK_END) == -1))
186 close (fd);
187 return NULL;
190 FILE *stream = fdopen (fd, mode);
191 if (stream == NULL)
192 close (fd);
194 return stream;
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;
210 va_list ap;
212 va_start (ap, flags);
213 if (flags & O_CREAT)
214 mode = va_arg (ap, unsigned int);
215 va_end (ap);
217 #ifdef O_CLOEXEC
218 flags |= O_CLOEXEC;
219 #endif
221 const char *local_name = ToLocale (filename);
222 if (local_name == NULL)
224 errno = ENOENT;
225 return -1;
228 #ifdef HAVE_FDOPENDIR
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
239 LocaleFree (local_name);
240 return fd;
245 * Creates a directory using UTF-8 paths.
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).
252 int vlc_mkdir( const char *dirname, mode_t mode )
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);
263 #else
264 char *locname = ToLocale( dirname );
265 int res;
267 if( locname == NULL )
269 errno = ENOENT;
270 return -1;
272 res = mkdir( locname, mode );
274 LocaleFree( locname );
275 return res;
276 #endif
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 )
288 #ifdef WIN32
289 CONVERT_PATH (dirname, wpath, NULL);
290 return (DIR *)vlc_wopendir (wpath);
292 #else
293 const char *local_name = ToLocale( dirname );
295 if( local_name != NULL )
297 DIR *dir = opendir( local_name );
298 LocaleFree( local_name );
299 return dir;
301 #endif
303 errno = ENOENT;
304 return NULL;
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 )
317 #ifdef WIN32
318 struct _wdirent *ent = vlc_wreaddir (dir);
319 if (ent == NULL)
320 return NULL;
322 return FromWide (ent->d_name);
323 #else
324 struct dirent *ent;
326 ent = readdir( (DIR *)dir );
327 if( ent == NULL )
328 return NULL;
330 return vlc_fix_readdir( ent->d_name );
331 #endif
334 static int dummy_select( const char *str )
336 (void)str;
337 return 1;
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 ** ) )
348 if( select == NULL )
349 select = dummy_select;
351 if( dir == NULL )
352 return -1;
353 else
355 char **tab = NULL;
356 char *entry;
357 unsigned num = 0;
359 rewinddir( dir );
361 while( ( entry = vlc_readdir( dir ) ) != NULL )
363 char **newtab;
365 if( !select( entry ) )
367 free( entry );
368 continue;
371 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
372 if( newtab == NULL )
374 free( entry );
375 goto error;
377 tab = newtab;
378 tab[num++] = entry;
381 if( compar != NULL )
382 qsort( tab, num, sizeof( tab[0] ),
383 (int (*)( const void *, const void *))compar );
385 *namelist = tab;
386 return num;
388 error:{
389 unsigned i;
391 for( i = 0; i < num; i++ )
392 free( tab[i] );
393 free( tab );
396 return -1;
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);
415 int val = -1;
417 if (dir != NULL)
419 val = vlc_loaddir (dir, namelist, select, compar);
420 closedir (dir);
422 return val;
425 static int vlc_statEx( const char *filename, struct stat *buf,
426 bool deref )
428 #ifdef UNDER_CE
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);
435 #endif
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 );
444 return res;
446 errno = ENOENT;
447 #endif
448 return -1;
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 );
474 * Removes a file.
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 )
482 #ifdef UNDER_CE
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);
489 #endif
490 const char *local_name = ToLocale( filename );
492 if( local_name == NULL )
494 errno = ENOENT;
495 return -1;
498 int ret = unlink( local_name );
499 LocaleFree( local_name );
500 return ret;
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)
513 #if defined (WIN32)
514 CONVERT_PATH (oldpath, wold, -1);
515 CONVERT_PATH (newpath, wnew, -1);
516 # ifdef UNDER_CE
517 /* FIXME: errno support */
518 if (MoveFileW (wold, wnew))
519 return 0;
520 else
521 return -1;
522 #else
523 return _wrename (wold, wnew);
524 #endif
526 #endif
527 const char *lo = ToLocale (oldpath);
528 if (lo == NULL)
529 goto error;
531 const char *ln = ToLocale (newpath);
532 if (ln == NULL)
534 LocaleFree (lo);
535 error:
536 errno = ENOENT;
537 return -1;
540 int ret = rename (lo, ln);
541 LocaleFree (lo);
542 LocaleFree (ln);
543 return ret;
546 int vlc_mkstemp( char *template )
548 static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
549 static const int i_digits = sizeof(digits)/sizeof(*digits) - 1;
551 /* */
552 assert( template );
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" ) )
560 errno = EINVAL;
561 return -1;
564 /* */
565 for( int i = 0; i < 256; i++ )
567 /* Create a pseudo random file name */
568 uint8_t pi_rand[6];
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];
574 /* */
575 int fd = vlc_open( template, O_CREAT | O_EXCL | O_RDWR, 0600 );
576 if( fd >= 0 )
577 return fd;
578 if( errno != EEXIST )
579 return -1;
582 errno = EEXIST;
583 return -1;
586 #ifdef UNDER_CE
587 # define dup(fd) (fd, -1)
588 #endif
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)
597 int newfd;
599 #ifdef HAVE_DUP3
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))
607 return newfd;
608 close (newfd);
610 #endif
612 newfd = dup (oldfd);
613 #ifdef HAVE_FCNTL
614 if (likely(newfd != -1))
615 fcntl (newfd, F_SETFD, FD_CLOEXEC);
616 #endif
617 return newfd;
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)
633 int fd;
635 #ifdef SOCK_CLOEXEC
636 type |= SOCK_CLOEXEC;
637 if (nonblock)
638 type |= SOCK_NONBLOCK;
639 fd = socket (pf, type, proto);
640 if (fd != -1 || errno != EINVAL)
641 return fd;
643 type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
644 #endif
646 fd = socket (pf, type, proto);
647 if (fd == -1)
648 return -1;
650 #ifndef WIN32
651 fcntl (fd, F_SETFD, FD_CLOEXEC);
652 if (nonblock)
653 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
654 #else
655 if (nonblock)
656 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
657 #endif
658 return fd;
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)
672 #ifdef HAVE_ACCEPT4
673 int flags = SOCK_CLOEXEC;
674 if (nonblock)
675 flags |= SOCK_NONBLOCK;
679 int fd = accept4 (lfd, addr, alen, flags);
680 if (fd != -1)
681 return fd;
683 while (errno == EINTR);
685 if (errno != ENOSYS)
686 return -1;
687 #endif
688 #ifdef WIN32
689 errno = 0;
690 #endif
694 int fd = accept (lfd, addr, alen);
695 if (fd != -1)
697 #ifndef WIN32
698 fcntl (fd, F_SETFD, FD_CLOEXEC);
699 if (nonblock)
700 fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
701 #else
702 if (nonblock)
703 ioctlsocket (fd, FIONBIO, &(unsigned long){ 1 });
704 #endif
705 return fd;
708 while (errno == EINTR);
710 return -1;