]> git.sesse.net Git - vlc/blob - src/extras/libc.c
Added strnlen replacement (Untested)
[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 #include <vlc/vlc.h>
29
30 #include <string.h>                                              /* strdup() */
31 #include <stdlib.h>
32 #include <ctype.h>
33
34
35 #undef iconv_t
36 #undef iconv_open
37 #undef iconv
38 #undef iconv_close
39
40 #if defined(HAVE_ICONV)
41 #   include <iconv.h>
42 #endif
43
44 #ifdef HAVE_DIRENT_H
45 #   include <dirent.h>
46 #endif
47
48 #ifdef HAVE_FORK
49 #   include <sys/time.h>
50 #   include <unistd.h>
51 #   include <errno.h>
52 #   include <sys/wait.h>
53 #   include <fcntl.h>
54 #   include <sys/socket.h>
55 #   include <sys/poll.h>
56 #endif
57
58 #if defined(WIN32) || defined(UNDER_CE)
59 #   undef _wopendir
60 #   undef _wreaddir
61 #   undef _wclosedir
62 #   undef rewinddir
63 #   undef seekdir
64 #   undef telldir
65 #   define WIN32_LEAN_AND_MEAN
66 #   include <windows.h>
67 #endif
68
69 #ifdef UNDER_CE
70 #   define strcoll strcmp
71 #endif
72
73 /*****************************************************************************
74  * getenv: just in case, but it should never be called
75  *****************************************************************************/
76 #if !defined( HAVE_GETENV )
77 char *vlc_getenv( const char *name )
78 {
79     return NULL;
80 }
81 #endif
82
83 /*****************************************************************************
84  * strdup: returns a malloc'd copy of a string
85  *****************************************************************************/
86 #if !defined( HAVE_STRDUP )
87 char *vlc_strdup( const char *string )
88 {
89     return strndup( string, strlen( string ) );
90 }
91 #endif
92
93 /*****************************************************************************
94  * strndup: returns a malloc'd copy of at most n bytes of string
95  * Does anyone know whether or not it will be present in Jaguar?
96  *****************************************************************************/
97 #if !defined( HAVE_STRNDUP )
98 char *vlc_strndup( const char *string, size_t n )
99 {
100     char *psz;
101     size_t len = strlen( string );
102
103     len = __MIN( len, n );
104     psz = (char*)malloc( len + 1 );
105     if( psz != NULL )
106     {
107         memcpy( (void*)psz, (const void*)string, len );
108         psz[ len ] = 0;
109     }
110
111     return psz;
112 }
113 #endif
114
115 /*****************************************************************************
116  * strnlen: 
117  *****************************************************************************/
118 #if !defined( HAVE_STRNLEN )
119 size_t vlc_strnlen( const char *psz, size_t n )
120 {
121     const char *psz_end = memchr( psz, 0, n );
122     return psz_end ? ( psz_end - psz ) : n;
123 }
124 #endif
125
126 /*****************************************************************************
127  * strcasecmp: compare two strings ignoring case
128  *****************************************************************************/
129 #if !defined( HAVE_STRCASECMP ) && !defined( HAVE_STRICMP )
130 int vlc_strcasecmp( const char *s1, const char *s2 )
131 {
132     int c1, c2;
133     if( !s1 || !s2 ) return  -1;
134
135     while( *s1 && *s2 )
136     {
137         c1 = tolower(*s1);
138         c2 = tolower(*s2);
139
140         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
141         s1++; s2++;
142     }
143
144     if( !*s1 && !*s2 ) return 0;
145     else return (*s1 ? 1 : -1);
146 }
147 #endif
148
149 /*****************************************************************************
150  * strncasecmp: compare n chars from two strings ignoring case
151  *****************************************************************************/
152 #if !defined( HAVE_STRNCASECMP ) && !defined( HAVE_STRNICMP )
153 int vlc_strncasecmp( const char *s1, const char *s2, size_t n )
154 {
155     int c1, c2;
156     if( !s1 || !s2 ) return  -1;
157
158     while( n > 0 && *s1 && *s2 )
159     {
160         c1 = tolower(*s1);
161         c2 = tolower(*s2);
162
163         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
164         s1++; s2++; n--;
165     }
166
167     if( !n || (!*s1 && !*s2) ) return 0;
168     else return (*s1 ? 1 : -1);
169 }
170 #endif
171
172 /******************************************************************************
173  * strcasestr: find a substring (little) in another substring (big)
174  * Case sensitive. Return NULL if not found, return big if little == null
175  *****************************************************************************/
176 #if !defined( HAVE_STRCASESTR ) && !defined( HAVE_STRISTR )
177 char * vlc_strcasestr( const char *psz_big, const char *psz_little )
178 {
179     char *p_pos = (char *)psz_big;
180
181     if( !psz_big || !psz_little || !*psz_little ) return p_pos;
182  
183     while( *p_pos ) 
184     {
185         if( toupper( *p_pos ) == toupper( *psz_little ) )
186         {
187             char * psz_cur1 = p_pos + 1;
188             char * psz_cur2 = (char *)psz_little + 1;
189             while( *psz_cur1 && *psz_cur2 &&
190                    toupper( *psz_cur1 ) == toupper( *psz_cur2 ) )
191             {
192                 psz_cur1++;
193                 psz_cur2++;
194             }
195             if( !*psz_cur2 ) return p_pos;
196         }
197         p_pos++;
198     }
199     return NULL;
200 }
201 #endif
202
203 /*****************************************************************************
204  * vasprintf:
205  *****************************************************************************/
206 #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
207 int vlc_vasprintf(char **strp, const char *fmt, va_list ap)
208 {
209     /* Guess we need no more than 100 bytes. */
210     int     i_size = 100;
211     char    *p = malloc( i_size );
212     int     n;
213
214     if( p == NULL )
215     {
216         *strp = NULL;
217         return -1;
218     }
219
220     for( ;; )
221     {
222         /* Try to print in the allocated space. */
223         n = vsnprintf( p, i_size, fmt, ap );
224
225         /* If that worked, return the string. */
226         if (n > -1 && n < i_size)
227         {
228             *strp = p;
229             return strlen( p );
230         }
231         /* Else try again with more space. */
232         if (n > -1)    /* glibc 2.1 */
233         {
234            i_size = n+1; /* precisely what is needed */
235         }
236         else           /* glibc 2.0 */
237         {
238            i_size *= 2;  /* twice the old size */
239         }
240         if( (p = realloc( p, i_size ) ) == NULL)
241         {
242             *strp = NULL;
243             return -1;
244         }
245     }
246 }
247 #endif
248
249 /*****************************************************************************
250  * asprintf:
251  *****************************************************************************/
252 #if !defined(HAVE_ASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
253 int vlc_asprintf( char **strp, const char *fmt, ... )
254 {
255     va_list args;
256     int i_ret;
257
258     va_start( args, fmt );
259     i_ret = vasprintf( strp, fmt, args );
260     va_end( args );
261
262     return i_ret;
263 }
264 #endif
265
266 /*****************************************************************************
267  * atof: convert a string to a double.
268  *****************************************************************************/
269 #if !defined( HAVE_ATOF )
270 double vlc_atof( const char *nptr )
271 {
272     double f_result;
273     wchar_t *psz_tmp = NULL;
274     int i_len = strlen( nptr ) + 1;
275
276     psz_tmp = malloc( i_len * sizeof(wchar_t) );
277     if( !psz_tmp )
278         return NULL;
279     MultiByteToWideChar( CP_ACP, 0, nptr, -1, psz_tmp, i_len );
280     f_result = wcstod( psz_tmp, NULL );
281     free( psz_tmp );
282
283     return f_result;
284 }
285 #endif
286
287 /*****************************************************************************
288  * strtoll: convert a string to a 64 bits int.
289  *****************************************************************************/
290 #if !defined( HAVE_STRTOLL )
291 int64_t vlc_strtoll( const char *nptr, char **endptr, int base )
292 {
293     int64_t i_value = 0;
294     int sign = 1, newbase = base ? base : 10;
295
296     while( isspace(*nptr) ) nptr++;
297
298     if( *nptr == '-' )
299     {
300         sign = -1;
301         nptr++;
302     }
303
304     /* Try to detect base */
305     if( *nptr == '0' )
306     {
307         newbase = 8;
308         nptr++;
309
310         if( *nptr == 'x' )
311         {
312             newbase = 16;
313             nptr++;
314         }
315     }
316
317     if( base && newbase != base )
318     {
319         if( endptr ) *endptr = (char *)nptr;
320         return i_value;
321     }
322
323     switch( newbase )
324     {
325         case 10:
326             while( *nptr >= '0' && *nptr <= '9' )
327             {
328                 i_value *= 10;
329                 i_value += ( *nptr++ - '0' );
330             }
331             if( endptr ) *endptr = (char *)nptr;
332             break;
333
334         case 16:
335             while( (*nptr >= '0' && *nptr <= '9') ||
336                    (*nptr >= 'a' && *nptr <= 'f') ||
337                    (*nptr >= 'A' && *nptr <= 'F') )
338             {
339                 int i_valc = 0;
340                 if(*nptr >= '0' && *nptr <= '9') i_valc = *nptr - '0';
341                 else if(*nptr >= 'a' && *nptr <= 'f') i_valc = *nptr - 'a' +10;
342                 else if(*nptr >= 'A' && *nptr <= 'F') i_valc = *nptr - 'A' +10;
343                 i_value *= 16;
344                 i_value += i_valc;
345                 nptr++;
346             }
347             if( endptr ) *endptr = (char *)nptr;
348             break;
349
350         default:
351             i_value = strtol( nptr, endptr, newbase );
352             break;
353     }
354
355     return i_value * sign;
356 }
357 #endif
358
359 /*****************************************************************************
360  * atoll: convert a string to a 64 bits int.
361  *****************************************************************************/
362 #if !defined( HAVE_ATOLL )
363 int64_t vlc_atoll( const char *nptr )
364 {
365     return strtoll( nptr, (char **)NULL, 10 );
366 }
367 #endif
368
369 /*****************************************************************************
370  * lldiv: returns quotient and remainder
371  *****************************************************************************/
372 #if defined(SYS_BEOS) \
373  || (defined (__FreeBSD__) && (__FreeBSD__ < 5))
374 lldiv_t vlc_lldiv( long long numer, long long denom )
375 {
376     lldiv_t d;
377     d.quot = numer / denom;
378     d.rem  = numer % denom;
379     return d;
380 }
381 #endif
382
383
384 /**
385  * Copy a string to a sized buffer. The result is always nul-terminated
386  * (contrary to strncpy()).
387  *
388  * @param dest destination buffer
389  * @param src string to be copied
390  * @param len maximum number of characters to be copied plus one for the
391  * terminating nul.
392  *
393  * @return strlen(src)
394  */
395 #ifndef HAVE_STRLCPY
396 extern size_t vlc_strlcpy (char *tgt, const char *src, size_t bufsize)
397 {
398     size_t length;
399
400     for (length = 1; (length < bufsize) && *src; length++)
401         *tgt++ = *src++;
402
403     if (bufsize)
404         *tgt = '\0';
405
406     while (*src++)
407         length++;
408
409     return length - 1;
410 }
411 #endif
412
413 /*****************************************************************************
414  * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
415  * when called with an empty argument or just '\'
416  *****************************************************************************/
417 #if defined(WIN32) && !defined(UNDER_CE)
418 #   include <assert.h>
419
420 typedef struct vlc_DIR
421 {
422     _WDIR *p_real_dir;
423     int i_drives;
424     struct _wdirent dd_dir;
425     vlc_bool_t b_insert_back;
426 } vlc_DIR;
427
428 void *vlc_wopendir( const wchar_t *wpath )
429 {
430     vlc_DIR *p_dir = NULL;
431     _WDIR *p_real_dir = NULL;
432
433     if ( wpath == NULL || wpath[0] == '\0'
434           || (wcscmp (wpath, L"\\") == 0) )
435     {
436         /* Special mode to list drive letters */
437         p_dir = malloc( sizeof(vlc_DIR) );
438         if( !p_dir )
439             return NULL;
440         p_dir->p_real_dir = NULL;
441         p_dir->i_drives = GetLogicalDrives();
442         return (void *)p_dir;
443     }
444
445     p_real_dir = _wopendir( wpath );
446     if ( p_real_dir == NULL )
447         return NULL;
448
449     p_dir = malloc( sizeof(vlc_DIR) );
450     if( !p_dir )
451     {
452         _wclosedir( p_real_dir );
453         return NULL;
454     }
455     p_dir->p_real_dir = p_real_dir;
456
457     assert (wpath[0]); // wpath[1] is defined
458     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
459     return (void *)p_dir;
460 }
461
462 struct _wdirent *vlc_wreaddir( void *_p_dir )
463 {
464     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
465     unsigned int i;
466     DWORD i_drives;
467
468     if ( p_dir->p_real_dir != NULL )
469     {
470         if ( p_dir->b_insert_back )
471         {
472             /* Adds "..", gruik! */
473             p_dir->dd_dir.d_ino = 0;
474             p_dir->dd_dir.d_reclen = 0;
475             p_dir->dd_dir.d_namlen = 2;
476             wcscpy( p_dir->dd_dir.d_name, L".." );
477             p_dir->b_insert_back = VLC_FALSE;
478             return &p_dir->dd_dir;
479         }
480
481         return _wreaddir( p_dir->p_real_dir );
482     }
483
484     /* Drive letters mode */
485     i_drives = p_dir->i_drives;
486     if ( !i_drives )
487         return NULL; /* end */
488
489     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
490         if ( i_drives & 1 ) break;
491
492     if ( i >= 26 )
493         return NULL; /* this should not happen */
494
495     swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
496     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
497     p_dir->i_drives &= ~(1UL << i);
498     return &p_dir->dd_dir;
499 }
500
501 int vlc_wclosedir( void *_p_dir )
502 {
503     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
504     int i_ret = 0;
505
506     if ( p_dir->p_real_dir != NULL )
507         i_ret = _wclosedir( p_dir->p_real_dir );
508
509     free( p_dir );
510     return i_ret;
511 }
512
513 void vlc_rewinddir( void *_p_dir )
514 {
515     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
516
517     if ( p_dir->p_real_dir != NULL )
518         _wrewinddir( p_dir->p_real_dir );
519 }
520
521 void vlc_seekdir( void *_p_dir, long loc)
522 {
523     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
524
525     if ( p_dir->p_real_dir != NULL )
526         _wseekdir( p_dir->p_real_dir, loc );
527 }
528
529 long vlc_telldir( void *_p_dir )
530 {
531     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
532
533     if ( p_dir->p_real_dir != NULL )
534         return _wtelldir( p_dir->p_real_dir );
535     return 0;
536 }
537 #endif
538
539 /*****************************************************************************
540  * scandir: scan a directory alpha-sorted
541  *****************************************************************************/
542 #if !defined( HAVE_SCANDIR )
543 /* FIXME: I suspect this is dead code -> utf8_scandir */
544 #ifdef WIN32
545 # undef opendir
546 # undef readdir
547 # undef closedir
548 #endif
549 int vlc_alphasort( const struct dirent **a, const struct dirent **b )
550 {
551     return strcoll( (*a)->d_name, (*b)->d_name );
552 }
553
554 int vlc_scandir( const char *name, struct dirent ***namelist,
555                     int (*filter) ( const struct dirent * ),
556                     int (*compar) ( const struct dirent **,
557                                     const struct dirent ** ) )
558 {
559     DIR            * p_dir;
560     struct dirent  * p_content;
561     struct dirent ** pp_list;
562     int              ret, size;
563
564     if( !namelist || !( p_dir = opendir( name ) ) ) return -1;
565
566     ret     = 0;
567     pp_list = NULL;
568     while( ( p_content = readdir( p_dir ) ) )
569     {
570         if( filter && !filter( p_content ) )
571         {
572             continue;
573         }
574         pp_list = realloc( pp_list, ( ret + 1 ) * sizeof( struct dirent * ) );
575         size = sizeof( struct dirent ) + strlen( p_content->d_name ) + 1;
576         pp_list[ret] = malloc( size );
577         if( pp_list[ret] )
578         {
579             memcpy( pp_list[ret], p_content, size );
580             ret++;
581         }
582         else
583         {
584             /* Continuing is useless when no more memory can be allocted,
585              * so better return what we have found.
586              */
587             ret = -1;
588             break;
589         }
590     }
591
592     closedir( p_dir );
593
594     if( compar )
595     {
596         qsort( pp_list, ret, sizeof( struct dirent * ),
597                (int (*)(const void *, const void *)) compar );
598     }
599
600     *namelist = pp_list;
601     return ret;
602 }
603 #endif
604
605 #if defined (WIN32) || !defined (HAVE_SHARED_LIBVLC)
606 /*****************************************************************************
607  * dgettext: gettext for plugins.
608  *****************************************************************************/
609 char *vlc_dgettext( const char *package, const char *msgid )
610 {
611 #if defined( ENABLE_NLS ) \
612      && ( defined(HAVE_GETTEXT) || defined(HAVE_INCLUDED_GETTEXT) )
613     return dgettext( package, msgid );
614 #else
615     return (char *)msgid;
616 #endif
617 }
618 #endif
619
620 /*****************************************************************************
621  * count_utf8_string: returns the number of characters in the string.
622  *****************************************************************************/
623 static int count_utf8_string( const char *psz_string )
624 {
625     int i = 0, i_count = 0;
626     while( psz_string[ i ] != 0 )
627     {
628         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
629         i++;
630     }
631     return i_count;
632 }
633
634 /*****************************************************************************
635  * wraptext: inserts \n at convenient places to wrap the text.
636  *           Returns the modified string in a new buffer.
637  *****************************************************************************/
638 char *vlc_wraptext( const char *psz_text, int i_line )
639 {
640     int i_len;
641     char *psz_line, *psz_new_text;
642
643     psz_line = psz_new_text = strdup( psz_text );
644
645     i_len = count_utf8_string( psz_text );
646
647     while( i_len > i_line )
648     {
649         /* Look if there is a newline somewhere. */
650         char *psz_parser = psz_line;
651         int i_count = 0;
652         while( i_count <= i_line && *psz_parser != '\n' )
653         {
654             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
655             psz_parser++;
656             i_count++;
657         }
658         if( *psz_parser == '\n' )
659         {
660             i_len -= (i_count + 1);
661             psz_line = psz_parser + 1;
662             continue;
663         }
664
665         /* Find the furthest space. */
666         while( psz_parser > psz_line && *psz_parser != ' ' )
667         {
668             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
669             psz_parser--;
670             i_count--;
671         }
672         if( *psz_parser == ' ' )
673         {
674             *psz_parser = '\n';
675             i_len -= (i_count + 1);
676             psz_line = psz_parser + 1;
677             continue;
678         }
679
680         /* Wrapping has failed. Find the first space or newline */
681         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
682         {
683             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
684             psz_parser++;
685             i_count++;
686         }
687         if( i_count < i_len ) *psz_parser = '\n';
688         i_len -= (i_count + 1);
689         psz_line = psz_parser + 1;
690     }
691
692     return psz_new_text;
693 }
694
695 /*****************************************************************************
696  * iconv wrapper
697  *****************************************************************************/
698 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
699 {
700 #if defined(HAVE_ICONV)
701     return iconv_open( tocode, fromcode );
702 #else
703     return NULL;
704 #endif
705 }
706
707 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
708                   char **outbuf, size_t *outbytesleft )
709 {
710 #if defined(HAVE_ICONV)
711     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
712                   outbuf, outbytesleft );
713 #else
714     int i_bytes;
715
716     if (inbytesleft == NULL || outbytesleft == NULL)
717     {
718         return 0;
719     }
720
721     i_bytes = __MIN(*inbytesleft, *outbytesleft);
722     if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
723     memcpy( *outbuf, *inbuf, i_bytes );
724     inbuf += i_bytes;
725     outbuf += i_bytes;
726     inbytesleft -= i_bytes;
727     outbytesleft -= i_bytes;
728     return i_bytes;
729 #endif
730 }
731
732 int vlc_iconv_close( vlc_iconv_t cd )
733 {
734 #if defined(HAVE_ICONV)
735     return iconv_close( cd );
736 #else
737     return 0;
738 #endif
739 }
740
741 /*****************************************************************************
742  * reduce a fraction
743  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
744  *****************************************************************************/
745 vlc_bool_t vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
746                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
747 {
748     vlc_bool_t b_exact = 1;
749     uint64_t i_gcd;
750
751     if( i_den == 0 )
752     {
753         *pi_dst_nom = 0;
754         *pi_dst_den = 1;
755         return 1;
756     }
757
758     i_gcd = GCD( i_nom, i_den );
759     i_nom /= i_gcd;
760     i_den /= i_gcd;
761
762     if( i_max == 0 ) i_max = I64C(0xFFFFFFFF);
763
764     if( i_nom > i_max || i_den > i_max )
765     {
766         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
767         b_exact = 0;
768
769         for( ; ; )
770         {
771             uint64_t i_x = i_nom / i_den;
772             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
773             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
774
775             if( i_a2n > i_max || i_a2d > i_max ) break;
776
777             i_nom %= i_den;
778
779             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
780             i_a1_num = i_a2n; i_a1_den = i_a2d;
781             if( i_nom == 0 ) break;
782             i_x = i_nom; i_nom = i_den; i_den = i_x;
783         }
784         i_nom = i_a1_num;
785         i_den = i_a1_den;
786     }
787
788     *pi_dst_nom = i_nom;
789     *pi_dst_den = i_den;
790
791     return b_exact;
792 }
793
794 /*************************************************************************
795  * vlc_parse_cmdline: Command line parsing into elements.
796  *
797  * The command line is composed of space/tab separated arguments.
798  * Quotes can be used as argument delimiters and a backslash can be used to
799  * escape a quote.
800  *************************************************************************/
801 static void find_end_quote( char **s, char **ppsz_parser, int i_quote )
802 {
803     int i_bcount = 0;
804
805     while( **s )
806     {
807         if( **s == '\\' )
808         {
809             **ppsz_parser = **s;
810             (*ppsz_parser)++; (*s)++;
811             i_bcount++;
812         }
813         else if( **s == '"' || **s == '\'' )
814         {
815             /* Preceeded by a number of '\' which we erase. */
816             *ppsz_parser -= i_bcount / 2;
817             if( i_bcount & 1 )
818             {
819                 /* '\\' followed by a '"' or '\'' */
820                 *ppsz_parser -= 1;
821                 **ppsz_parser = **s;
822                 (*ppsz_parser)++; (*s)++;
823                 i_bcount = 0;
824                 continue;
825             }
826
827             if( **s == i_quote )
828             {
829                 /* End */
830                 return;
831             }
832             else
833             {
834                 /* Different quoting */
835                 int i_quote = **s;
836                 **ppsz_parser = **s;
837                 (*ppsz_parser)++; (*s)++;
838                 find_end_quote( s, ppsz_parser, i_quote );
839                 **ppsz_parser = **s;
840                 (*ppsz_parser)++; (*s)++;
841             }
842
843             i_bcount = 0;
844         }
845         else
846         {
847             /* A regular character */
848             **ppsz_parser = **s;
849             (*ppsz_parser)++; (*s)++;
850             i_bcount = 0;
851         }
852     }
853 }
854
855 char **vlc_parse_cmdline( const char *psz_cmdline, int *i_args )
856 {
857     int argc = 0;
858     char **argv = 0;
859     char *s, *psz_parser, *psz_arg, *psz_orig;
860     int i_bcount = 0;
861
862     if( !psz_cmdline ) return 0;
863     psz_orig = strdup( psz_cmdline );
864     psz_arg = psz_parser = s = psz_orig;
865
866     while( *s )
867     {
868         if( *s == '\t' || *s == ' ' )
869         {
870             /* We have a complete argument */
871             *psz_parser = 0;
872             TAB_APPEND( argc, argv, strdup(psz_arg) );
873
874             /* Skip trailing spaces/tabs */
875             do{ s++; } while( *s == '\t' || *s == ' ' );
876
877             /* New argument */
878             psz_arg = psz_parser = s;
879             i_bcount = 0;
880         }
881         else if( *s == '\\' )
882         {
883             *psz_parser++ = *s++;
884             i_bcount++;
885         }
886         else if( *s == '"' || *s == '\'' )
887         {
888             if( ( i_bcount & 1 ) == 0 )
889             {
890                 /* Preceeded by an even number of '\', this is half that
891                  * number of '\', plus a quote which we erase. */
892                 int i_quote = *s;
893                 psz_parser -= i_bcount / 2;
894                 s++;
895                 find_end_quote( &s, &psz_parser, i_quote );
896                 s++;
897             }
898             else
899             {
900                 /* Preceeded by an odd number of '\', this is half that
901                  * number of '\' followed by a '"' */
902                 psz_parser = psz_parser - i_bcount/2 - 1;
903                 *psz_parser++ = '"';
904                 s++;
905             }
906             i_bcount = 0;
907         }
908         else
909         {
910             /* A regular character */
911             *psz_parser++ = *s++;
912             i_bcount = 0;
913         }
914     }
915
916     /* Take care of the last arg */
917     if( *psz_arg )
918     {
919         *psz_parser = '\0';
920         TAB_APPEND( argc, argv, strdup(psz_arg) );
921     }
922
923     if( i_args ) *i_args = argc;
924     free( psz_orig );
925     return argv;
926 }
927
928 /*************************************************************************
929  * vlc_execve: Execute an external program with a given environment,
930  * wait until it finishes and return its standard output
931  *************************************************************************/
932 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
933                   char *const *ppsz_env, const char *psz_cwd,
934                   const char *p_in, size_t i_in,
935                   char **pp_data, size_t *pi_data )
936 {
937     (void)i_argc; // <-- hmph
938 #ifdef HAVE_FORK
939 # define BUFSIZE 1024
940     int fds[2], i_status;
941
942     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
943         return -1;
944
945     pid_t pid = -1;
946     if ((fds[0] > 2) && (fds[1] > 2))
947         pid = fork ();
948
949     switch (pid)
950     {
951         case -1:
952             msg_Err (p_object, "unable to fork (%s)", strerror (errno));
953             close (fds[0]);
954             close (fds[1]);
955             return -1;
956
957         case 0:
958             /* NOTE:
959              * Like it or not, close can fail (and not only with EBADF)
960              */
961             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
962              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
963              && (open ("/dev/null", O_RDONLY) == 2)
964              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
965                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
966
967             exit (1);
968     }
969
970     close (fds[1]);
971
972     *pi_data = 0;
973     if (*pp_data)
974         free (*pp_data);
975     *pp_data = NULL;
976
977     if (i_in == 0)
978         shutdown (fds[0], SHUT_WR);
979
980     while (!p_object->b_die)
981     {
982         struct pollfd ufd[1];
983         memset (ufd, 0, sizeof (ufd));
984         ufd[0].fd = fds[0];
985         ufd[0].events = POLLIN;
986
987         if (i_in > 0)
988             ufd[0].events |= POLLOUT;
989
990         if (poll (ufd, 1, 10) <= 0)
991             continue;
992
993         if (ufd[0].revents & ~POLLOUT)
994         {
995             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
996             if (ptr == NULL)
997                 break; /* safely abort */
998
999             *pp_data = ptr;
1000
1001             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
1002             switch (val)
1003             {
1004                 case -1:
1005                 case 0:
1006                     shutdown (fds[0], SHUT_RD);
1007                     break;
1008
1009                 default:
1010                     *pi_data += val;
1011             }
1012         }
1013
1014         if (ufd[0].revents & POLLOUT)
1015         {
1016             ssize_t val = write (fds[0], p_in, i_in);
1017             switch (val)
1018             {
1019                 case -1:
1020                 case 0:
1021                     i_in = 0;
1022                     shutdown (fds[0], SHUT_WR);
1023                     break;
1024
1025                 default:
1026                     i_in -= val;
1027                     p_in += val;
1028             }
1029         }
1030     }
1031
1032     close (fds[0]);
1033
1034     while (waitpid (pid, &i_status, 0) == -1);
1035
1036     if (WIFEXITED (i_status))
1037     {
1038         i_status = WEXITSTATUS (i_status);
1039         if (i_status)
1040             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
1041                       ppsz_argv[0], (int)pid, i_status);
1042     }
1043     else
1044     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
1045     {
1046         i_status = WTERMSIG (i_status);
1047         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
1048                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
1049     }
1050
1051 #elif defined( WIN32 ) && !defined( UNDER_CE )
1052     SECURITY_ATTRIBUTES saAttr;
1053     PROCESS_INFORMATION piProcInfo;
1054     STARTUPINFO siStartInfo;
1055     BOOL bFuncRetn = FALSE;
1056     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
1057     DWORD i_status;
1058     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
1059     char **ppsz_parser;
1060     int i_size;
1061
1062     /* Set the bInheritHandle flag so pipe handles are inherited. */
1063     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1064     saAttr.bInheritHandle = TRUE;
1065     saAttr.lpSecurityDescriptor = NULL;
1066
1067     /* Create a pipe for the child process's STDOUT. */
1068     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
1069     {
1070         msg_Err( p_object, "stdout pipe creation failed" );
1071         return -1;
1072     }
1073
1074     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
1075     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
1076
1077     /* Create a pipe for the child process's STDIN. */
1078     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
1079     {
1080         msg_Err( p_object, "stdin pipe creation failed" );
1081         return -1;
1082     }
1083
1084     /* Ensure the write handle to the pipe for STDIN is not inherited. */
1085     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
1086
1087     /* Set up members of the PROCESS_INFORMATION structure. */
1088     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1089
1090     /* Set up members of the STARTUPINFO structure. */
1091     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1092     siStartInfo.cb = sizeof(STARTUPINFO);
1093     siStartInfo.hStdError = hChildStdoutWr;
1094     siStartInfo.hStdOutput = hChildStdoutWr;
1095     siStartInfo.hStdInput = hChildStdinRd;
1096     siStartInfo.wShowWindow = SW_HIDE;
1097     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1098
1099     /* Set up the command line. */
1100     psz_cmd = malloc(32768);
1101     if( !psz_cmd )
1102         return -1;
1103     psz_cmd[0] = '\0';
1104     i_size = 32768;
1105     ppsz_parser = &ppsz_argv[0];
1106     while ( ppsz_parser[0] != NULL && i_size > 0 )
1107     {
1108         /* Protect the last argument with quotes ; the other arguments
1109          * are supposed to be already protected because they have been
1110          * passed as a command-line option. */
1111         if ( ppsz_parser[1] == NULL )
1112         {
1113             strncat( psz_cmd, "\"", i_size );
1114             i_size--;
1115         }
1116         strncat( psz_cmd, *ppsz_parser, i_size );
1117         i_size -= strlen( *ppsz_parser );
1118         if ( ppsz_parser[1] == NULL )
1119         {
1120             strncat( psz_cmd, "\"", i_size );
1121             i_size--;
1122         }
1123         strncat( psz_cmd, " ", i_size );
1124         i_size--;
1125         ppsz_parser++;
1126     }
1127
1128     /* Set up the environment. */
1129     p = p_env = malloc(32768);
1130     if( !p )
1131     {
1132         free( psz_cmd );
1133         return -1;
1134     }
1135
1136     i_size = 32768;
1137     ppsz_parser = &ppsz_env[0];
1138     while ( *ppsz_parser != NULL && i_size > 0 )
1139     {
1140         memcpy( p, *ppsz_parser,
1141                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
1142         p += strlen(*ppsz_parser) + 1;
1143         i_size -= strlen(*ppsz_parser) + 1;
1144         ppsz_parser++;
1145     }
1146     *p = '\0';
1147
1148     /* Create the child process. */
1149     bFuncRetn = CreateProcess( NULL,
1150           psz_cmd,       // command line
1151           NULL,          // process security attributes
1152           NULL,          // primary thread security attributes
1153           TRUE,          // handles are inherited
1154           0,             // creation flags
1155           p_env,
1156           psz_cwd,
1157           &siStartInfo,  // STARTUPINFO pointer
1158           &piProcInfo ); // receives PROCESS_INFORMATION
1159
1160     free( psz_cmd );
1161     free( p_env );
1162
1163     if ( bFuncRetn == 0 )
1164     {
1165         msg_Err( p_object, "child creation failed" );
1166         return -1;
1167     }
1168
1169     /* Read from a file and write its contents to a pipe. */
1170     while ( i_in > 0 && !p_object->b_die )
1171     {
1172         DWORD i_written;
1173         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
1174             break;
1175         i_in -= i_written;
1176         p_in += i_written;
1177     }
1178
1179     /* Close the pipe handle so the child process stops reading. */
1180     CloseHandle(hChildStdinWr);
1181
1182     /* Close the write end of the pipe before reading from the
1183      * read end of the pipe. */
1184     CloseHandle(hChildStdoutWr);
1185
1186     /* Read output from the child process. */
1187     *pi_data = 0;
1188     if( *pp_data )
1189         free( pp_data );
1190     *pp_data = NULL;
1191     *pp_data = malloc( 1025 );  /* +1 for \0 */
1192
1193     while ( !p_object->b_die )
1194     {
1195         DWORD i_read;
1196         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
1197                         NULL )
1198               || i_read == 0 )
1199             break;
1200         *pi_data += i_read;
1201         *pp_data = realloc( *pp_data, *pi_data + 1025 );
1202     }
1203
1204     while ( !p_object->b_die
1205              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
1206              && i_status != STILL_ACTIVE )
1207         msleep( 10000 );
1208
1209     CloseHandle(piProcInfo.hProcess);
1210     CloseHandle(piProcInfo.hThread);
1211
1212     if ( i_status )
1213         msg_Warn( p_object,
1214                   "child %s returned with error code %ld",
1215                   ppsz_argv[0], i_status );
1216
1217 #else
1218     msg_Err( p_object, "vlc_execve called but no implementation is available" );
1219     return -1;
1220
1221 #endif
1222
1223     if (*pp_data == NULL)
1224         return -1;
1225
1226     (*pp_data)[*pi_data] = '\0';
1227     return 0;
1228 }