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