]> git.sesse.net Git - vlc/blob - src/extras/libc.c
Start moving replacement functions to a 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  * 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 )
76 {
77 #if defined (HAVE_STRCASESTR) || defined (HAVE_STRISTR)
78     return strcasestr (psz_big, psz_little);
79 #else
80     char *p_pos = (char *)psz_big;
81
82     if( !psz_big || !psz_little || !*psz_little ) return p_pos;
83  
84     while( *p_pos )
85     {
86         if( toupper( *p_pos ) == toupper( *psz_little ) )
87         {
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 ) )
92             {
93                 psz_cur1++;
94                 psz_cur2++;
95             }
96             if( !*psz_cur2 ) return p_pos;
97         }
98         p_pos++;
99     }
100     return NULL;
101 #endif
102 }
103
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  *****************************************************************************/
108 #if defined(WIN32)
109 #   include <assert.h>
110
111 typedef struct vlc_DIR
112 {
113     _WDIR *p_real_dir;
114     int i_drives;
115     struct _wdirent dd_dir;
116     bool b_insert_back;
117 } vlc_DIR;
118
119 void *vlc_wopendir( const wchar_t *wpath )
120 {
121     vlc_DIR *p_dir = NULL;
122     _WDIR *p_real_dir = NULL;
123
124     if ( wpath == NULL || wpath[0] == '\0'
125           || (wcscmp (wpath, L"\\") == 0) )
126     {
127         /* Special mode to list drive letters */
128         p_dir = malloc( sizeof(vlc_DIR) );
129         if( !p_dir )
130             return NULL;
131         p_dir->p_real_dir = NULL;
132 #if defined(UNDER_CE)
133         p_dir->i_drives = NULL;
134 #else
135         p_dir->i_drives = GetLogicalDrives();
136 #endif
137         return (void *)p_dir;
138     }
139
140     p_real_dir = _wopendir( wpath );
141     if ( p_real_dir == NULL )
142         return NULL;
143
144     p_dir = malloc( sizeof(vlc_DIR) );
145     if( !p_dir )
146     {
147         _wclosedir( p_real_dir );
148         return NULL;
149     }
150     p_dir->p_real_dir = p_real_dir;
151
152     assert (wpath[0]); // wpath[1] is defined
153     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
154     return (void *)p_dir;
155 }
156
157 struct _wdirent *vlc_wreaddir( void *_p_dir )
158 {
159     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
160     DWORD i_drives;
161
162     if ( p_dir->p_real_dir != NULL )
163     {
164         if ( p_dir->b_insert_back )
165         {
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;
173         }
174
175         return _wreaddir( p_dir->p_real_dir );
176     }
177
178     /* Drive letters mode */
179     i_drives = p_dir->i_drives;
180 #ifdef UNDER_CE
181     swprintf( p_dir->dd_dir.d_name, L"\\");
182     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
183 #else
184     unsigned int i;
185     if ( !i_drives )
186         return NULL; /* end */
187
188     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
189         if ( i_drives & 1 ) break;
190
191     if ( i >= 26 )
192         return NULL; /* this should not happen */
193
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);
197 #endif
198     return &p_dir->dd_dir;
199 }
200
201 void vlc_rewinddir( void *_p_dir )
202 {
203     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
204
205     if ( p_dir->p_real_dir != NULL )
206         _wrewinddir( p_dir->p_real_dir );
207 }
208 #endif
209
210 /* This one is in the libvlccore exported symbol list */
211 int vlc_wclosedir( void *_p_dir )
212 {
213 #if defined(WIN32)
214     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
215     int i_ret = 0;
216
217     if ( p_dir->p_real_dir != NULL )
218         i_ret = _wclosedir( p_dir->p_real_dir );
219
220     free( p_dir );
221     return i_ret;
222 #else
223     return closedir( _p_dir );
224 #endif
225 }
226
227 /**
228  * In-tree plugins share their gettext domain with LibVLC.
229  */
230 char *vlc_gettext( const char *msgid )
231 {
232 #ifdef ENABLE_NLS
233     return dgettext( PACKAGE_NAME, msgid );
234 #else
235     return (char *)msgid;
236 #endif
237 }
238
239 /*****************************************************************************
240  * count_utf8_string: returns the number of characters in the string.
241  *****************************************************************************/
242 static int count_utf8_string( const char *psz_string )
243 {
244     int i = 0, i_count = 0;
245     while( psz_string[ i ] != 0 )
246     {
247         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
248         i++;
249     }
250     return i_count;
251 }
252
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 )
258 {
259     int i_len;
260     char *psz_line, *psz_new_text;
261
262     psz_line = psz_new_text = strdup( psz_text );
263
264     i_len = count_utf8_string( psz_text );
265
266     while( i_len > i_line )
267     {
268         /* Look if there is a newline somewhere. */
269         char *psz_parser = psz_line;
270         int i_count = 0;
271         while( i_count <= i_line && *psz_parser != '\n' )
272         {
273             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
274             psz_parser++;
275             i_count++;
276         }
277         if( *psz_parser == '\n' )
278         {
279             i_len -= (i_count + 1);
280             psz_line = psz_parser + 1;
281             continue;
282         }
283
284         /* Find the furthest space. */
285         while( psz_parser > psz_line && *psz_parser != ' ' )
286         {
287             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
288             psz_parser--;
289             i_count--;
290         }
291         if( *psz_parser == ' ' )
292         {
293             *psz_parser = '\n';
294             i_len -= (i_count + 1);
295             psz_line = psz_parser + 1;
296             continue;
297         }
298
299         /* Wrapping has failed. Find the first space or newline */
300         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
301         {
302             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
303             psz_parser++;
304             i_count++;
305         }
306         if( i_count < i_len ) *psz_parser = '\n';
307         i_len -= (i_count + 1);
308         psz_line = psz_parser + 1;
309     }
310
311     return psz_new_text;
312 }
313
314 /*****************************************************************************
315  * iconv wrapper
316  *****************************************************************************/
317 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
318 {
319 #if defined(HAVE_ICONV)
320     return iconv_open( tocode, fromcode );
321 #else
322     return (vlc_iconv_t)(-1);
323 #endif
324 }
325
326 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
327                   char **outbuf, size_t *outbytesleft )
328 {
329 #if defined(HAVE_ICONV)
330     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
331                   outbuf, outbytesleft );
332 #else
333     abort ();
334 #endif
335 }
336
337 int vlc_iconv_close( vlc_iconv_t cd )
338 {
339 #if defined(HAVE_ICONV)
340     return iconv_close( cd );
341 #else
342     abort ();
343 #endif
344 }
345
346 /*****************************************************************************
347  * reduce a fraction
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 )
352 {
353     bool b_exact = 1;
354     uint64_t i_gcd;
355
356     if( i_den == 0 )
357     {
358         *pi_dst_nom = 0;
359         *pi_dst_den = 1;
360         return 1;
361     }
362
363     i_gcd = GCD( i_nom, i_den );
364     i_nom /= i_gcd;
365     i_den /= i_gcd;
366
367     if( i_max == 0 ) i_max = INT64_C(0xFFFFFFFF);
368
369     if( i_nom > i_max || i_den > i_max )
370     {
371         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
372         b_exact = 0;
373
374         for( ; ; )
375         {
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;
379
380             if( i_a2n > i_max || i_a2d > i_max ) break;
381
382             i_nom %= i_den;
383
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;
388         }
389         i_nom = i_a1_num;
390         i_den = i_a1_den;
391     }
392
393     *pi_dst_nom = i_nom;
394     *pi_dst_den = i_den;
395
396     return b_exact;
397 }
398
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 )
407 {
408     (void)i_argc; // <-- hmph
409 #ifdef HAVE_FORK
410 # define BUFSIZE 1024
411     int fds[2], i_status;
412
413     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
414         return -1;
415
416     pid_t pid = -1;
417     if ((fds[0] > 2) && (fds[1] > 2))
418         pid = fork ();
419
420     switch (pid)
421     {
422         case -1:
423             msg_Err (p_object, "unable to fork (%m)");
424             close (fds[0]);
425             close (fds[1]);
426             return -1;
427
428         case 0:
429         {
430             sigset_t set;
431             sigemptyset (&set);
432             pthread_sigmask (SIG_SETMASK, &set, NULL);
433
434             /* NOTE:
435              * Like it or not, close can fail (and not only with EBADF)
436              */
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);
442
443             exit (EXIT_FAILURE);
444         }
445     }
446
447     close (fds[1]);
448
449     *pi_data = 0;
450     if (*pp_data)
451         free (*pp_data);
452     *pp_data = NULL;
453
454     if (i_in == 0)
455         shutdown (fds[0], SHUT_WR);
456
457     while (!p_object->b_die)
458     {
459         struct pollfd ufd[1];
460         memset (ufd, 0, sizeof (ufd));
461         ufd[0].fd = fds[0];
462         ufd[0].events = POLLIN;
463
464         if (i_in > 0)
465             ufd[0].events |= POLLOUT;
466
467         if (poll (ufd, 1, 10) <= 0)
468             continue;
469
470         if (ufd[0].revents & ~POLLOUT)
471         {
472             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
473             if (ptr == NULL)
474                 break; /* safely abort */
475
476             *pp_data = ptr;
477
478             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
479             switch (val)
480             {
481                 case -1:
482                 case 0:
483                     shutdown (fds[0], SHUT_RD);
484                     break;
485
486                 default:
487                     *pi_data += val;
488             }
489         }
490
491         if (ufd[0].revents & POLLOUT)
492         {
493             ssize_t val = write (fds[0], p_in, i_in);
494             switch (val)
495             {
496                 case -1:
497                 case 0:
498                     i_in = 0;
499                     shutdown (fds[0], SHUT_WR);
500                     break;
501
502                 default:
503                     i_in -= val;
504                     p_in += val;
505             }
506         }
507     }
508
509     close (fds[0]);
510
511     while (waitpid (pid, &i_status, 0) == -1);
512
513     if (WIFEXITED (i_status))
514     {
515         i_status = WEXITSTATUS (i_status);
516         if (i_status)
517             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
518                       ppsz_argv[0], (int)pid, i_status);
519     }
520     else
521     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
522     {
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));
526     }
527
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;
534     DWORD i_status;
535     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
536     char **ppsz_parser;
537     int i_size;
538
539     /* Set the bInheritHandle flag so pipe handles are inherited. */
540     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
541     saAttr.bInheritHandle = TRUE;
542     saAttr.lpSecurityDescriptor = NULL;
543
544     /* Create a pipe for the child process's STDOUT. */
545     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
546     {
547         msg_Err( p_object, "stdout pipe creation failed" );
548         return -1;
549     }
550
551     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
552     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
553
554     /* Create a pipe for the child process's STDIN. */
555     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
556     {
557         msg_Err( p_object, "stdin pipe creation failed" );
558         return -1;
559     }
560
561     /* Ensure the write handle to the pipe for STDIN is not inherited. */
562     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
563
564     /* Set up members of the PROCESS_INFORMATION structure. */
565     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
566
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;
575
576     /* Set up the command line. */
577     psz_cmd = malloc(32768);
578     if( !psz_cmd )
579         return -1;
580     psz_cmd[0] = '\0';
581     i_size = 32768;
582     ppsz_parser = &ppsz_argv[0];
583     while ( ppsz_parser[0] != NULL && i_size > 0 )
584     {
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 )
589         {
590             strncat( psz_cmd, "\"", i_size );
591             i_size--;
592         }
593         strncat( psz_cmd, *ppsz_parser, i_size );
594         i_size -= strlen( *ppsz_parser );
595         if ( ppsz_parser[1] == NULL )
596         {
597             strncat( psz_cmd, "\"", i_size );
598             i_size--;
599         }
600         strncat( psz_cmd, " ", i_size );
601         i_size--;
602         ppsz_parser++;
603     }
604
605     /* Set up the environment. */
606     p = p_env = malloc(32768);
607     if( !p )
608     {
609         free( psz_cmd );
610         return -1;
611     }
612
613     i_size = 32768;
614     ppsz_parser = &ppsz_env[0];
615     while ( *ppsz_parser != NULL && i_size > 0 )
616     {
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;
621         ppsz_parser++;
622     }
623     *p = '\0';
624
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
631           0,             // creation flags
632           p_env,
633           psz_cwd,
634           &siStartInfo,  // STARTUPINFO pointer
635           &piProcInfo ); // receives PROCESS_INFORMATION
636
637     free( psz_cmd );
638     free( p_env );
639
640     if ( bFuncRetn == 0 )
641     {
642         msg_Err( p_object, "child creation failed" );
643         return -1;
644     }
645
646     /* Read from a file and write its contents to a pipe. */
647     while ( i_in > 0 && !p_object->b_die )
648     {
649         DWORD i_written;
650         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
651             break;
652         i_in -= i_written;
653         p_in += i_written;
654     }
655
656     /* Close the pipe handle so the child process stops reading. */
657     CloseHandle(hChildStdinWr);
658
659     /* Close the write end of the pipe before reading from the
660      * read end of the pipe. */
661     CloseHandle(hChildStdoutWr);
662
663     /* Read output from the child process. */
664     *pi_data = 0;
665     if( *pp_data )
666         free( pp_data );
667     *pp_data = NULL;
668     *pp_data = malloc( 1025 );  /* +1 for \0 */
669
670     while ( !p_object->b_die )
671     {
672         DWORD i_read;
673         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
674                         NULL )
675               || i_read == 0 )
676             break;
677         *pi_data += i_read;
678         *pp_data = realloc( *pp_data, *pi_data + 1025 );
679     }
680
681     while ( !p_object->b_die
682              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
683              && i_status != STILL_ACTIVE )
684         msleep( 10000 );
685
686     CloseHandle(piProcInfo.hProcess);
687     CloseHandle(piProcInfo.hThread);
688
689     if ( i_status )
690         msg_Warn( p_object,
691                   "child %s returned with error code %ld",
692                   ppsz_argv[0], i_status );
693
694 #else
695     msg_Err( p_object, "vlc_execve called but no implementation is available" );
696     return -1;
697
698 #endif
699
700     if (*pp_data == NULL)
701         return -1;
702
703     (*pp_data)[*pi_data] = '\0';
704     return 0;
705 }