1 /*****************************************************************************
2 * libc.c: Extra libc function for some systems.
3 *****************************************************************************
4 * Copyright (C) 2002-2006 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Samuel Hocevar <sam@zoy.org>
9 * Gildas Bazin <gbazin@videolan.org>
10 * Derk-Jan Hartman <hartman at videolan dot org>
11 * Christophe Massiot <massiot@via.ecp.fr>
12 * Rémi Denis-Courmont <rem à videolan.org>
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27 *****************************************************************************/
32 #include <vlc_common.h>
42 #if defined(HAVE_ICONV)
53 # include <sys/time.h>
56 # include <sys/wait.h>
58 # include <sys/socket.h>
59 # include <sys/poll.h>
62 #if defined(WIN32) || defined(UNDER_CE)
67 # define WIN32_LEAN_AND_MEAN
71 /******************************************************************************
72 * strcasestr: find a substring (little) in another substring (big)
73 * Case sensitive. Return NULL if not found, return big if little == null
74 *****************************************************************************/
75 char * vlc_strcasestr( const char *psz_big, const char *psz_little )
77 #if defined (HAVE_STRCASESTR) || defined (HAVE_STRISTR)
78 return strcasestr (psz_big, psz_little);
80 char *p_pos = (char *)psz_big;
82 if( !psz_big || !psz_little || !*psz_little ) return p_pos;
86 if( toupper( *p_pos ) == toupper( *psz_little ) )
88 char * psz_cur1 = p_pos + 1;
89 char * psz_cur2 = (char *)psz_little + 1;
90 while( *psz_cur1 && *psz_cur2 &&
91 toupper( *psz_cur1 ) == toupper( *psz_cur2 ) )
96 if( !*psz_cur2 ) return p_pos;
104 /*****************************************************************************
105 * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
106 * when called with an empty argument or just '\'
107 *****************************************************************************/
111 typedef struct vlc_DIR
115 struct _wdirent dd_dir;
119 void *vlc_wopendir( const wchar_t *wpath )
121 vlc_DIR *p_dir = NULL;
122 _WDIR *p_real_dir = NULL;
124 if ( wpath == NULL || wpath[0] == '\0'
125 || (wcscmp (wpath, L"\\") == 0) )
127 /* Special mode to list drive letters */
128 p_dir = malloc( sizeof(vlc_DIR) );
131 p_dir->p_real_dir = NULL;
132 #if defined(UNDER_CE)
133 p_dir->i_drives = NULL;
135 p_dir->i_drives = GetLogicalDrives();
137 return (void *)p_dir;
140 p_real_dir = _wopendir( wpath );
141 if ( p_real_dir == NULL )
144 p_dir = malloc( sizeof(vlc_DIR) );
147 _wclosedir( p_real_dir );
150 p_dir->p_real_dir = p_real_dir;
152 assert (wpath[0]); // wpath[1] is defined
153 p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
154 return (void *)p_dir;
157 struct _wdirent *vlc_wreaddir( void *_p_dir )
159 vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
162 if ( p_dir->p_real_dir != NULL )
164 if ( p_dir->b_insert_back )
166 /* Adds "..", gruik! */
167 p_dir->dd_dir.d_ino = 0;
168 p_dir->dd_dir.d_reclen = 0;
169 p_dir->dd_dir.d_namlen = 2;
170 wcscpy( p_dir->dd_dir.d_name, L".." );
171 p_dir->b_insert_back = false;
172 return &p_dir->dd_dir;
175 return _wreaddir( p_dir->p_real_dir );
178 /* Drive letters mode */
179 i_drives = p_dir->i_drives;
181 swprintf( p_dir->dd_dir.d_name, L"\\");
182 p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
186 return NULL; /* end */
188 for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
189 if ( i_drives & 1 ) break;
192 return NULL; /* this should not happen */
194 swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
195 p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
196 p_dir->i_drives &= ~(1UL << i);
198 return &p_dir->dd_dir;
201 void vlc_rewinddir( void *_p_dir )
203 vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
205 if ( p_dir->p_real_dir != NULL )
206 _wrewinddir( p_dir->p_real_dir );
210 /* This one is in the libvlccore exported symbol list */
211 int vlc_wclosedir( void *_p_dir )
214 vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
217 if ( p_dir->p_real_dir != NULL )
218 i_ret = _wclosedir( p_dir->p_real_dir );
223 return closedir( _p_dir );
228 * In-tree plugins share their gettext domain with LibVLC.
230 char *vlc_gettext( const char *msgid )
233 return dgettext( PACKAGE_NAME, msgid );
235 return (char *)msgid;
239 /*****************************************************************************
240 * count_utf8_string: returns the number of characters in the string.
241 *****************************************************************************/
242 static int count_utf8_string( const char *psz_string )
244 int i = 0, i_count = 0;
245 while( psz_string[ i ] != 0 )
247 if( ((unsigned char *)psz_string)[ i ] < 0x80UL ) i_count++;
253 /*****************************************************************************
254 * wraptext: inserts \n at convenient places to wrap the text.
255 * Returns the modified string in a new buffer.
256 *****************************************************************************/
257 char *vlc_wraptext( const char *psz_text, int i_line )
260 char *psz_line, *psz_new_text;
262 psz_line = psz_new_text = strdup( psz_text );
264 i_len = count_utf8_string( psz_text );
266 while( i_len > i_line )
268 /* Look if there is a newline somewhere. */
269 char *psz_parser = psz_line;
271 while( i_count <= i_line && *psz_parser != '\n' )
273 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
277 if( *psz_parser == '\n' )
279 i_len -= (i_count + 1);
280 psz_line = psz_parser + 1;
284 /* Find the furthest space. */
285 while( psz_parser > psz_line && *psz_parser != ' ' )
287 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
291 if( *psz_parser == ' ' )
294 i_len -= (i_count + 1);
295 psz_line = psz_parser + 1;
299 /* Wrapping has failed. Find the first space or newline */
300 while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
302 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
306 if( i_count < i_len ) *psz_parser = '\n';
307 i_len -= (i_count + 1);
308 psz_line = psz_parser + 1;
314 /*****************************************************************************
316 *****************************************************************************/
317 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
319 #if defined(HAVE_ICONV)
320 return iconv_open( tocode, fromcode );
322 return (vlc_iconv_t)(-1);
326 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
327 char **outbuf, size_t *outbytesleft )
329 #if defined(HAVE_ICONV)
330 return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
331 outbuf, outbytesleft );
337 int vlc_iconv_close( vlc_iconv_t cd )
339 #if defined(HAVE_ICONV)
340 return iconv_close( cd );
346 /*****************************************************************************
348 * (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
349 *****************************************************************************/
350 bool vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
351 uint64_t i_nom, uint64_t i_den, uint64_t i_max )
363 i_gcd = GCD( i_nom, i_den );
367 if( i_max == 0 ) i_max = INT64_C(0xFFFFFFFF);
369 if( i_nom > i_max || i_den > i_max )
371 uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
376 uint64_t i_x = i_nom / i_den;
377 uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
378 uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
380 if( i_a2n > i_max || i_a2d > i_max ) break;
384 i_a0_num = i_a1_num; i_a0_den = i_a1_den;
385 i_a1_num = i_a2n; i_a1_den = i_a2d;
386 if( i_nom == 0 ) break;
387 i_x = i_nom; i_nom = i_den; i_den = i_x;
399 /*************************************************************************
400 * vlc_execve: Execute an external program with a given environment,
401 * wait until it finishes and return its standard output
402 *************************************************************************/
403 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
404 char *const *ppsz_env, const char *psz_cwd,
405 const char *p_in, size_t i_in,
406 char **pp_data, size_t *pi_data )
408 (void)i_argc; // <-- hmph
410 # define BUFSIZE 1024
411 int fds[2], i_status;
413 if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
417 if ((fds[0] > 2) && (fds[1] > 2))
423 msg_Err (p_object, "unable to fork (%m)");
432 pthread_sigmask (SIG_SETMASK, &set, NULL);
435 * Like it or not, close can fail (and not only with EBADF)
437 if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
438 && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
439 && (open ("/dev/null", O_RDONLY) == 2)
440 && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
441 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
455 shutdown (fds[0], SHUT_WR);
457 while (!p_object->b_die)
459 struct pollfd ufd[1];
460 memset (ufd, 0, sizeof (ufd));
462 ufd[0].events = POLLIN;
465 ufd[0].events |= POLLOUT;
467 if (poll (ufd, 1, 10) <= 0)
470 if (ufd[0].revents & ~POLLOUT)
472 char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
474 break; /* safely abort */
478 ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
483 shutdown (fds[0], SHUT_RD);
491 if (ufd[0].revents & POLLOUT)
493 ssize_t val = write (fds[0], p_in, i_in);
499 shutdown (fds[0], SHUT_WR);
511 while (waitpid (pid, &i_status, 0) == -1);
513 if (WIFEXITED (i_status))
515 i_status = WEXITSTATUS (i_status);
517 msg_Warn (p_object, "child %s (PID %d) exited with error code %d",
518 ppsz_argv[0], (int)pid, i_status);
521 if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
523 i_status = WTERMSIG (i_status);
524 msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
525 ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
528 #elif defined( WIN32 ) && !defined( UNDER_CE )
529 SECURITY_ATTRIBUTES saAttr;
530 PROCESS_INFORMATION piProcInfo;
531 STARTUPINFO siStartInfo;
532 BOOL bFuncRetn = FALSE;
533 HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
535 char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
539 /* Set the bInheritHandle flag so pipe handles are inherited. */
540 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
541 saAttr.bInheritHandle = TRUE;
542 saAttr.lpSecurityDescriptor = NULL;
544 /* Create a pipe for the child process's STDOUT. */
545 if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
547 msg_Err( p_object, "stdout pipe creation failed" );
551 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
552 SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
554 /* Create a pipe for the child process's STDIN. */
555 if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
557 msg_Err( p_object, "stdin pipe creation failed" );
561 /* Ensure the write handle to the pipe for STDIN is not inherited. */
562 SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
564 /* Set up members of the PROCESS_INFORMATION structure. */
565 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
567 /* Set up members of the STARTUPINFO structure. */
568 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
569 siStartInfo.cb = sizeof(STARTUPINFO);
570 siStartInfo.hStdError = hChildStdoutWr;
571 siStartInfo.hStdOutput = hChildStdoutWr;
572 siStartInfo.hStdInput = hChildStdinRd;
573 siStartInfo.wShowWindow = SW_HIDE;
574 siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
576 /* Set up the command line. */
577 psz_cmd = malloc(32768);
582 ppsz_parser = &ppsz_argv[0];
583 while ( ppsz_parser[0] != NULL && i_size > 0 )
585 /* Protect the last argument with quotes ; the other arguments
586 * are supposed to be already protected because they have been
587 * passed as a command-line option. */
588 if ( ppsz_parser[1] == NULL )
590 strncat( psz_cmd, "\"", i_size );
593 strncat( psz_cmd, *ppsz_parser, i_size );
594 i_size -= strlen( *ppsz_parser );
595 if ( ppsz_parser[1] == NULL )
597 strncat( psz_cmd, "\"", i_size );
600 strncat( psz_cmd, " ", i_size );
605 /* Set up the environment. */
606 p = p_env = malloc(32768);
614 ppsz_parser = &ppsz_env[0];
615 while ( *ppsz_parser != NULL && i_size > 0 )
617 memcpy( p, *ppsz_parser,
618 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
619 p += strlen(*ppsz_parser) + 1;
620 i_size -= strlen(*ppsz_parser) + 1;
625 /* Create the child process. */
626 bFuncRetn = CreateProcess( NULL,
627 psz_cmd, // command line
628 NULL, // process security attributes
629 NULL, // primary thread security attributes
630 TRUE, // handles are inherited
634 &siStartInfo, // STARTUPINFO pointer
635 &piProcInfo ); // receives PROCESS_INFORMATION
640 if ( bFuncRetn == 0 )
642 msg_Err( p_object, "child creation failed" );
646 /* Read from a file and write its contents to a pipe. */
647 while ( i_in > 0 && !p_object->b_die )
650 if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
656 /* Close the pipe handle so the child process stops reading. */
657 CloseHandle(hChildStdinWr);
659 /* Close the write end of the pipe before reading from the
660 * read end of the pipe. */
661 CloseHandle(hChildStdoutWr);
663 /* Read output from the child process. */
668 *pp_data = malloc( 1025 ); /* +1 for \0 */
670 while ( !p_object->b_die )
673 if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
678 *pp_data = realloc( *pp_data, *pi_data + 1025 );
681 while ( !p_object->b_die
682 && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
683 && i_status != STILL_ACTIVE )
686 CloseHandle(piProcInfo.hProcess);
687 CloseHandle(piProcInfo.hThread);
691 "child %s returned with error code %ld",
692 ppsz_argv[0], i_status );
695 msg_Err( p_object, "vlc_execve called but no implementation is available" );
700 if (*pp_data == NULL)
703 (*pp_data)[*pi_data] = '\0';