]> git.sesse.net Git - vlc/blob - src/extras/libc.c
Move remaining replacement to static import library
[vlc] / src / extras / libc.c
1 /*****************************************************************************
2  * libc.c: Extra libc function for some systems.
3  *****************************************************************************
4  * Copyright (C) 2002-2006 the VideoLAN team
5  * $Id$
6  *
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>
13  *
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.
18  *
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.
23  *
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  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33
34 #include <ctype.h>
35
36
37 #undef iconv_t
38 #undef iconv_open
39 #undef iconv
40 #undef iconv_close
41
42 #if defined(HAVE_ICONV)
43 #   include <iconv.h>
44 #endif
45
46 #ifdef HAVE_DIRENT_H
47 #   include <dirent.h>
48 #endif
49
50 #include <signal.h>
51
52 #ifdef HAVE_FORK
53 #   include <sys/time.h>
54 #   include <unistd.h>
55 #   include <errno.h>
56 #   include <sys/wait.h>
57 #   include <fcntl.h>
58 #   include <sys/socket.h>
59 #   include <sys/poll.h>
60 #endif
61
62 #if defined(WIN32) || defined(UNDER_CE)
63 #   undef _wopendir
64 #   undef _wreaddir
65 #   undef _wclosedir
66 #   undef rewinddir
67 #   define WIN32_LEAN_AND_MEAN
68 #   include <windows.h>
69 #endif
70
71 /*****************************************************************************
72  * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
73  * when called with an empty argument or just '\'
74  *****************************************************************************/
75 #if defined(WIN32)
76 #   include <assert.h>
77
78 typedef struct vlc_DIR
79 {
80     _WDIR *p_real_dir;
81     int i_drives;
82     struct _wdirent dd_dir;
83     bool b_insert_back;
84 } vlc_DIR;
85
86 void *vlc_wopendir( const wchar_t *wpath )
87 {
88     vlc_DIR *p_dir = NULL;
89     _WDIR *p_real_dir = NULL;
90
91     if ( wpath == NULL || wpath[0] == '\0'
92           || (wcscmp (wpath, L"\\") == 0) )
93     {
94         /* Special mode to list drive letters */
95         p_dir = malloc( sizeof(vlc_DIR) );
96         if( !p_dir )
97             return NULL;
98         p_dir->p_real_dir = NULL;
99 #if defined(UNDER_CE)
100         p_dir->i_drives = NULL;
101 #else
102         p_dir->i_drives = GetLogicalDrives();
103 #endif
104         return (void *)p_dir;
105     }
106
107     p_real_dir = _wopendir( wpath );
108     if ( p_real_dir == NULL )
109         return NULL;
110
111     p_dir = malloc( sizeof(vlc_DIR) );
112     if( !p_dir )
113     {
114         _wclosedir( p_real_dir );
115         return NULL;
116     }
117     p_dir->p_real_dir = p_real_dir;
118
119     assert (wpath[0]); // wpath[1] is defined
120     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
121     return (void *)p_dir;
122 }
123
124 struct _wdirent *vlc_wreaddir( void *_p_dir )
125 {
126     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
127     DWORD i_drives;
128
129     if ( p_dir->p_real_dir != NULL )
130     {
131         if ( p_dir->b_insert_back )
132         {
133             /* Adds "..", gruik! */
134             p_dir->dd_dir.d_ino = 0;
135             p_dir->dd_dir.d_reclen = 0;
136             p_dir->dd_dir.d_namlen = 2;
137             wcscpy( p_dir->dd_dir.d_name, L".." );
138             p_dir->b_insert_back = false;
139             return &p_dir->dd_dir;
140         }
141
142         return _wreaddir( p_dir->p_real_dir );
143     }
144
145     /* Drive letters mode */
146     i_drives = p_dir->i_drives;
147 #ifdef UNDER_CE
148     swprintf( p_dir->dd_dir.d_name, L"\\");
149     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
150 #else
151     unsigned int i;
152     if ( !i_drives )
153         return NULL; /* end */
154
155     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
156         if ( i_drives & 1 ) break;
157
158     if ( i >= 26 )
159         return NULL; /* this should not happen */
160
161     swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
162     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
163     p_dir->i_drives &= ~(1UL << i);
164 #endif
165     return &p_dir->dd_dir;
166 }
167
168 void vlc_rewinddir( void *_p_dir )
169 {
170     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
171
172     if ( p_dir->p_real_dir != NULL )
173         _wrewinddir( p_dir->p_real_dir );
174 }
175 #endif
176
177 /* This one is in the libvlccore exported symbol list */
178 int vlc_wclosedir( void *_p_dir )
179 {
180 #if defined(WIN32)
181     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
182     int i_ret = 0;
183
184     if ( p_dir->p_real_dir != NULL )
185         i_ret = _wclosedir( p_dir->p_real_dir );
186
187     free( p_dir );
188     return i_ret;
189 #else
190     return closedir( _p_dir );
191 #endif
192 }
193
194 /**
195  * In-tree plugins share their gettext domain with LibVLC.
196  */
197 char *vlc_gettext( const char *msgid )
198 {
199 #ifdef ENABLE_NLS
200     return dgettext( PACKAGE_NAME, msgid );
201 #else
202     return (char *)msgid;
203 #endif
204 }
205
206 /*****************************************************************************
207  * count_utf8_string: returns the number of characters in the string.
208  *****************************************************************************/
209 static int count_utf8_string( const char *psz_string )
210 {
211     int i = 0, i_count = 0;
212     while( psz_string[ i ] != 0 )
213     {
214         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
215         i++;
216     }
217     return i_count;
218 }
219
220 /*****************************************************************************
221  * wraptext: inserts \n at convenient places to wrap the text.
222  *           Returns the modified string in a new buffer.
223  *****************************************************************************/
224 char *vlc_wraptext( const char *psz_text, int i_line )
225 {
226     int i_len;
227     char *psz_line, *psz_new_text;
228
229     psz_line = psz_new_text = strdup( psz_text );
230
231     i_len = count_utf8_string( psz_text );
232
233     while( i_len > i_line )
234     {
235         /* Look if there is a newline somewhere. */
236         char *psz_parser = psz_line;
237         int i_count = 0;
238         while( i_count <= i_line && *psz_parser != '\n' )
239         {
240             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
241             psz_parser++;
242             i_count++;
243         }
244         if( *psz_parser == '\n' )
245         {
246             i_len -= (i_count + 1);
247             psz_line = psz_parser + 1;
248             continue;
249         }
250
251         /* Find the furthest space. */
252         while( psz_parser > psz_line && *psz_parser != ' ' )
253         {
254             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
255             psz_parser--;
256             i_count--;
257         }
258         if( *psz_parser == ' ' )
259         {
260             *psz_parser = '\n';
261             i_len -= (i_count + 1);
262             psz_line = psz_parser + 1;
263             continue;
264         }
265
266         /* Wrapping has failed. Find the first space or newline */
267         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
268         {
269             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
270             psz_parser++;
271             i_count++;
272         }
273         if( i_count < i_len ) *psz_parser = '\n';
274         i_len -= (i_count + 1);
275         psz_line = psz_parser + 1;
276     }
277
278     return psz_new_text;
279 }
280
281 /*****************************************************************************
282  * iconv wrapper
283  *****************************************************************************/
284 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
285 {
286 #if defined(HAVE_ICONV)
287     return iconv_open( tocode, fromcode );
288 #else
289     return (vlc_iconv_t)(-1);
290 #endif
291 }
292
293 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
294                   char **outbuf, size_t *outbytesleft )
295 {
296 #if defined(HAVE_ICONV)
297     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
298                   outbuf, outbytesleft );
299 #else
300     abort ();
301 #endif
302 }
303
304 int vlc_iconv_close( vlc_iconv_t cd )
305 {
306 #if defined(HAVE_ICONV)
307     return iconv_close( cd );
308 #else
309     abort ();
310 #endif
311 }
312
313 /*****************************************************************************
314  * reduce a fraction
315  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
316  *****************************************************************************/
317 bool vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
318                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
319 {
320     bool b_exact = 1;
321     uint64_t i_gcd;
322
323     if( i_den == 0 )
324     {
325         *pi_dst_nom = 0;
326         *pi_dst_den = 1;
327         return 1;
328     }
329
330     i_gcd = GCD( i_nom, i_den );
331     i_nom /= i_gcd;
332     i_den /= i_gcd;
333
334     if( i_max == 0 ) i_max = INT64_C(0xFFFFFFFF);
335
336     if( i_nom > i_max || i_den > i_max )
337     {
338         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
339         b_exact = 0;
340
341         for( ; ; )
342         {
343             uint64_t i_x = i_nom / i_den;
344             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
345             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
346
347             if( i_a2n > i_max || i_a2d > i_max ) break;
348
349             i_nom %= i_den;
350
351             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
352             i_a1_num = i_a2n; i_a1_den = i_a2d;
353             if( i_nom == 0 ) break;
354             i_x = i_nom; i_nom = i_den; i_den = i_x;
355         }
356         i_nom = i_a1_num;
357         i_den = i_a1_den;
358     }
359
360     *pi_dst_nom = i_nom;
361     *pi_dst_den = i_den;
362
363     return b_exact;
364 }
365
366 /*************************************************************************
367  * vlc_execve: Execute an external program with a given environment,
368  * wait until it finishes and return its standard output
369  *************************************************************************/
370 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
371                   char *const *ppsz_env, const char *psz_cwd,
372                   const char *p_in, size_t i_in,
373                   char **pp_data, size_t *pi_data )
374 {
375     (void)i_argc; // <-- hmph
376 #ifdef HAVE_FORK
377 # define BUFSIZE 1024
378     int fds[2], i_status;
379
380     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
381         return -1;
382
383     pid_t pid = -1;
384     if ((fds[0] > 2) && (fds[1] > 2))
385         pid = fork ();
386
387     switch (pid)
388     {
389         case -1:
390             msg_Err (p_object, "unable to fork (%m)");
391             close (fds[0]);
392             close (fds[1]);
393             return -1;
394
395         case 0:
396         {
397             sigset_t set;
398             sigemptyset (&set);
399             pthread_sigmask (SIG_SETMASK, &set, NULL);
400
401             /* NOTE:
402              * Like it or not, close can fail (and not only with EBADF)
403              */
404             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
405              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
406              && (open ("/dev/null", O_RDONLY) == 2)
407              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
408                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
409
410             exit (EXIT_FAILURE);
411         }
412     }
413
414     close (fds[1]);
415
416     *pi_data = 0;
417     if (*pp_data)
418         free (*pp_data);
419     *pp_data = NULL;
420
421     if (i_in == 0)
422         shutdown (fds[0], SHUT_WR);
423
424     while (!p_object->b_die)
425     {
426         struct pollfd ufd[1];
427         memset (ufd, 0, sizeof (ufd));
428         ufd[0].fd = fds[0];
429         ufd[0].events = POLLIN;
430
431         if (i_in > 0)
432             ufd[0].events |= POLLOUT;
433
434         if (poll (ufd, 1, 10) <= 0)
435             continue;
436
437         if (ufd[0].revents & ~POLLOUT)
438         {
439             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
440             if (ptr == NULL)
441                 break; /* safely abort */
442
443             *pp_data = ptr;
444
445             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
446             switch (val)
447             {
448                 case -1:
449                 case 0:
450                     shutdown (fds[0], SHUT_RD);
451                     break;
452
453                 default:
454                     *pi_data += val;
455             }
456         }
457
458         if (ufd[0].revents & POLLOUT)
459         {
460             ssize_t val = write (fds[0], p_in, i_in);
461             switch (val)
462             {
463                 case -1:
464                 case 0:
465                     i_in = 0;
466                     shutdown (fds[0], SHUT_WR);
467                     break;
468
469                 default:
470                     i_in -= val;
471                     p_in += val;
472             }
473         }
474     }
475
476     close (fds[0]);
477
478     while (waitpid (pid, &i_status, 0) == -1);
479
480     if (WIFEXITED (i_status))
481     {
482         i_status = WEXITSTATUS (i_status);
483         if (i_status)
484             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
485                       ppsz_argv[0], (int)pid, i_status);
486     }
487     else
488     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
489     {
490         i_status = WTERMSIG (i_status);
491         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
492                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
493     }
494
495 #elif defined( WIN32 ) && !defined( UNDER_CE )
496     SECURITY_ATTRIBUTES saAttr;
497     PROCESS_INFORMATION piProcInfo;
498     STARTUPINFO siStartInfo;
499     BOOL bFuncRetn = FALSE;
500     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
501     DWORD i_status;
502     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
503     char **ppsz_parser;
504     int i_size;
505
506     /* Set the bInheritHandle flag so pipe handles are inherited. */
507     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
508     saAttr.bInheritHandle = TRUE;
509     saAttr.lpSecurityDescriptor = NULL;
510
511     /* Create a pipe for the child process's STDOUT. */
512     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
513     {
514         msg_Err( p_object, "stdout pipe creation failed" );
515         return -1;
516     }
517
518     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
519     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
520
521     /* Create a pipe for the child process's STDIN. */
522     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
523     {
524         msg_Err( p_object, "stdin pipe creation failed" );
525         return -1;
526     }
527
528     /* Ensure the write handle to the pipe for STDIN is not inherited. */
529     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
530
531     /* Set up members of the PROCESS_INFORMATION structure. */
532     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
533
534     /* Set up members of the STARTUPINFO structure. */
535     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
536     siStartInfo.cb = sizeof(STARTUPINFO);
537     siStartInfo.hStdError = hChildStdoutWr;
538     siStartInfo.hStdOutput = hChildStdoutWr;
539     siStartInfo.hStdInput = hChildStdinRd;
540     siStartInfo.wShowWindow = SW_HIDE;
541     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
542
543     /* Set up the command line. */
544     psz_cmd = malloc(32768);
545     if( !psz_cmd )
546         return -1;
547     psz_cmd[0] = '\0';
548     i_size = 32768;
549     ppsz_parser = &ppsz_argv[0];
550     while ( ppsz_parser[0] != NULL && i_size > 0 )
551     {
552         /* Protect the last argument with quotes ; the other arguments
553          * are supposed to be already protected because they have been
554          * passed as a command-line option. */
555         if ( ppsz_parser[1] == NULL )
556         {
557             strncat( psz_cmd, "\"", i_size );
558             i_size--;
559         }
560         strncat( psz_cmd, *ppsz_parser, i_size );
561         i_size -= strlen( *ppsz_parser );
562         if ( ppsz_parser[1] == NULL )
563         {
564             strncat( psz_cmd, "\"", i_size );
565             i_size--;
566         }
567         strncat( psz_cmd, " ", i_size );
568         i_size--;
569         ppsz_parser++;
570     }
571
572     /* Set up the environment. */
573     p = p_env = malloc(32768);
574     if( !p )
575     {
576         free( psz_cmd );
577         return -1;
578     }
579
580     i_size = 32768;
581     ppsz_parser = &ppsz_env[0];
582     while ( *ppsz_parser != NULL && i_size > 0 )
583     {
584         memcpy( p, *ppsz_parser,
585                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
586         p += strlen(*ppsz_parser) + 1;
587         i_size -= strlen(*ppsz_parser) + 1;
588         ppsz_parser++;
589     }
590     *p = '\0';
591
592     /* Create the child process. */
593     bFuncRetn = CreateProcess( NULL,
594           psz_cmd,       // command line
595           NULL,          // process security attributes
596           NULL,          // primary thread security attributes
597           TRUE,          // handles are inherited
598           0,             // creation flags
599           p_env,
600           psz_cwd,
601           &siStartInfo,  // STARTUPINFO pointer
602           &piProcInfo ); // receives PROCESS_INFORMATION
603
604     free( psz_cmd );
605     free( p_env );
606
607     if ( bFuncRetn == 0 )
608     {
609         msg_Err( p_object, "child creation failed" );
610         return -1;
611     }
612
613     /* Read from a file and write its contents to a pipe. */
614     while ( i_in > 0 && !p_object->b_die )
615     {
616         DWORD i_written;
617         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
618             break;
619         i_in -= i_written;
620         p_in += i_written;
621     }
622
623     /* Close the pipe handle so the child process stops reading. */
624     CloseHandle(hChildStdinWr);
625
626     /* Close the write end of the pipe before reading from the
627      * read end of the pipe. */
628     CloseHandle(hChildStdoutWr);
629
630     /* Read output from the child process. */
631     *pi_data = 0;
632     if( *pp_data )
633         free( pp_data );
634     *pp_data = NULL;
635     *pp_data = malloc( 1025 );  /* +1 for \0 */
636
637     while ( !p_object->b_die )
638     {
639         DWORD i_read;
640         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
641                         NULL )
642               || i_read == 0 )
643             break;
644         *pi_data += i_read;
645         *pp_data = realloc( *pp_data, *pi_data + 1025 );
646     }
647
648     while ( !p_object->b_die
649              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
650              && i_status != STILL_ACTIVE )
651         msleep( 10000 );
652
653     CloseHandle(piProcInfo.hProcess);
654     CloseHandle(piProcInfo.hThread);
655
656     if ( i_status )
657         msg_Warn( p_object,
658                   "child %s returned with error code %ld",
659                   ppsz_argv[0], i_status );
660
661 #else
662     msg_Err( p_object, "vlc_execve called but no implementation is available" );
663     return -1;
664
665 #endif
666
667     if (*pp_data == NULL)
668         return -1;
669
670     (*pp_data)[*pi_data] = '\0';
671     return 0;
672 }