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