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