]> git.sesse.net Git - vlc/blob - modules/control/http/http.c
GetNonEmptyString simplification
[vlc] / modules / control / http / http.c
1 /*****************************************************************************
2  * http.c : HTTP/HTTPS Remote control interface
3  *****************************************************************************
4  * Copyright (C) 2001-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Laurent Aimar <fenrir@via.ecp.fr>
9  *          Christophe Massiot <massiot@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #include "http.h"
27
28 /*****************************************************************************
29  * Module descriptor
30  *****************************************************************************/
31 static int  Open ( vlc_object_t * );
32 static void Close( vlc_object_t * );
33
34 #define HOST_TEXT N_( "Host address" )
35 #define HOST_LONGTEXT N_( \
36     "Address and port the HTTP interface will listen on. It defaults to " \
37     "all network interfaces (0.0.0.0)." \
38     " If you want the HTTP interface to be available only on the local " \
39     "machine, enter 127.0.0.1" )
40 #define SRC_TEXT N_( "Source directory" )
41 #define SRC_LONGTEXT N_( "Source directory" )
42 #define CHARSET_TEXT N_( "Charset" )
43 #define CHARSET_LONGTEXT N_( \
44         "Charset declared in Content-Type header (default UTF-8)." )
45 #define HANDLERS_TEXT N_( "Handlers" )
46 #define HANDLERS_LONGTEXT N_( \
47         "List of handler extensions and executable paths (for instance: " \
48         "php=/usr/bin/php,pl=/usr/bin/perl)." )
49 #define ART_TEXT N_( "Export album art as /art." )
50 #define ART_LONGTEXT N_( \
51         "Allow exporting album art for current playlist items at the " \
52         "/art and /art?id=<id> URLs." )
53 #define CERT_TEXT N_( "Certificate file" )
54 #define CERT_LONGTEXT N_( "HTTP interface x509 PEM certificate file " \
55                           "(enables SSL)." )
56 #define KEY_TEXT N_( "Private key file" )
57 #define KEY_LONGTEXT N_( "HTTP interface x509 PEM private key file." )
58 #define CA_TEXT N_( "Root CA file" )
59 #define CA_LONGTEXT N_( "HTTP interface x509 PEM trusted root CA " \
60                         "certificates file." )
61 #define CRL_TEXT N_( "CRL file" )
62 #define CRL_LONGTEXT N_( "HTTP interace Certificates Revocation List file." )
63
64 vlc_module_begin();
65     set_shortname( _("HTTP"));
66     set_description( _("HTTP remote control interface") );
67     set_category( CAT_INTERFACE );
68     set_subcategory( SUBCAT_INTERFACE_MAIN );
69         add_string ( "http-host", NULL, NULL, HOST_TEXT, HOST_LONGTEXT, VLC_TRUE );
70         add_string ( "http-src",  NULL, NULL, SRC_TEXT,  SRC_LONGTEXT,  VLC_TRUE );
71         add_string ( "http-charset", "UTF-8", NULL, CHARSET_TEXT, CHARSET_LONGTEXT, VLC_TRUE );
72 #if defined( HAVE_FORK ) || defined( WIN32 )
73         add_string ( "http-handlers", NULL, NULL, HANDLERS_TEXT, HANDLERS_LONGTEXT, VLC_TRUE );
74 #endif
75         add_bool   ( "http-album-art", 1, NULL, ART_TEXT, ART_LONGTEXT, VLC_TRUE );
76         set_section( N_("HTTP SSL" ), 0 );
77         add_string ( "http-intf-cert", NULL, NULL, CERT_TEXT, CERT_LONGTEXT, VLC_TRUE );
78         add_string ( "http-intf-key",  NULL, NULL, KEY_TEXT,  KEY_LONGTEXT,  VLC_TRUE );
79         add_string ( "http-intf-ca",   NULL, NULL, CA_TEXT,   CA_LONGTEXT,   VLC_TRUE );
80         add_string ( "http-intf-crl",  NULL, NULL, CRL_TEXT,  CRL_LONGTEXT,  VLC_TRUE );
81     set_capability( "interface", 0 );
82     set_callbacks( Open, Close );
83 vlc_module_end();
84
85
86 /*****************************************************************************
87  * Local prototypes
88  *****************************************************************************/
89 static void Run          ( intf_thread_t *p_intf );
90 int  E_(ArtCallback)( httpd_handler_sys_t *p_args,
91                           httpd_handler_t *p_handler, char *_p_url,
92                           uint8_t *_p_request, int i_type,
93                           uint8_t *_p_in, int i_in,
94                           char *psz_remote_addr, char *psz_remote_host,
95                           uint8_t **pp_data, int *pi_data );
96
97 /*****************************************************************************
98  * Local functions
99  *****************************************************************************/
100 #if !defined(__APPLE__) && !defined(SYS_BEOS) && !defined(WIN32)
101 static int DirectoryCheck( const char *psz_dir )
102 {
103     DIR           *p_dir;
104
105 #ifdef HAVE_SYS_STAT_H
106     struct stat   stat_info;
107
108     if( ( utf8_stat( psz_dir, &stat_info ) == -1 )
109       || !S_ISDIR( stat_info.st_mode ) )
110     {
111         return VLC_EGENERIC;
112     }
113 #endif
114
115     if( ( p_dir = utf8_opendir( psz_dir ) ) == NULL )
116     {
117         return VLC_EGENERIC;
118     }
119     closedir( p_dir );
120
121     return VLC_SUCCESS;
122 }
123 #endif
124
125
126 /*****************************************************************************
127  * Activate: initialize and create stuff
128  *****************************************************************************/
129 static int Open( vlc_object_t *p_this )
130 {
131     intf_thread_t *p_intf = (intf_thread_t*)p_this;
132     intf_sys_t    *p_sys;
133     char          *psz_address;
134     const char    *psz_cert = NULL, *psz_key = NULL, *psz_ca = NULL,
135                   *psz_crl = NULL;
136     int           i_port       = 0;
137     char          *psz_src;
138
139     psz_address = var_GetNonEmptyString(p_intf->p_libvlc, "http-host");
140     if( psz_address != NULL )
141     {
142         char *psz_parser = strchr( psz_address, ':' );
143         if( psz_parser )
144         {
145             *psz_parser++ = '\0';
146             i_port = atoi( psz_parser );
147         }
148     }
149     else
150         psz_address = strdup("");
151
152     p_intf->p_sys = p_sys = malloc( sizeof( intf_sys_t ) );
153     if( !p_intf->p_sys )
154     {
155         return( VLC_ENOMEM );
156     }
157     p_sys->p_playlist = NULL;
158     p_sys->p_input    = NULL;
159     p_sys->p_vlm      = NULL;
160     p_sys->psz_address = psz_address;
161     p_sys->i_port     = i_port;
162
163     /* determine Content-Type value for HTML pages */
164     psz_src = config_GetPsz( p_intf, "http-charset" );
165     if( psz_src == NULL || !*psz_src )
166     {
167         if( psz_src != NULL ) free( psz_src );
168         psz_src = strdup("UTF-8");
169     }
170
171     p_sys->psz_html_type = malloc( 20 + strlen( psz_src ) );
172     if( p_sys->psz_html_type == NULL )
173     {
174         free( p_sys->psz_address );
175         free( p_sys );
176         free( psz_src );
177         return VLC_ENOMEM ;
178     }
179     sprintf( p_sys->psz_html_type, "text/html; charset=%s", psz_src );
180     msg_Dbg( p_intf, "using charset=%s", psz_src );
181
182     if( strcmp( psz_src, "UTF-8" ) )
183     {
184         char psz_encoding[strlen( psz_src ) + sizeof( "//translit")];
185         sprintf( psz_encoding, "%s//translit", psz_src);
186
187         p_sys->iconv_from_utf8 = vlc_iconv_open( psz_encoding, "UTF-8" );
188         if( p_sys->iconv_from_utf8 == (vlc_iconv_t)-1 )
189             msg_Warn( p_intf, "unable to perform charset conversion to %s",
190                       psz_encoding );
191         else
192         {
193             p_sys->iconv_to_utf8 = vlc_iconv_open( "UTF-8", psz_src );
194             if( p_sys->iconv_to_utf8 == (vlc_iconv_t)-1 )
195                 msg_Warn( p_intf,
196                           "unable to perform charset conversion from %s",
197                           psz_src );
198         }
199     }
200     else
201     {
202         p_sys->iconv_from_utf8 = p_sys->iconv_to_utf8 = (vlc_iconv_t)-1;
203     }
204
205     p_sys->psz_charset = psz_src;
206     psz_src = NULL;
207
208     /* determine file handler associations */
209     p_sys->i_handlers = 0;
210     p_sys->pp_handlers = NULL;
211 #if defined( HAVE_FORK ) || defined( WIN32 )
212     psz_src = config_GetPsz( p_intf, "http-handlers" );
213     if( psz_src != NULL && *psz_src )
214     {
215         char *p = psz_src;
216         while( p != NULL )
217         {
218             http_association_t *p_handler;
219             char *psz_ext = p;
220             char *psz_program, *psz_options;
221             p = strchr( p, '=' );
222             if( p == NULL ) break;
223             *p++ = '\0';
224             psz_program = p;
225             p = strchr( p, ',' );
226             if( p != NULL )
227                 *p++ = '\0';
228
229             p_handler = malloc( sizeof( http_association_t ) );
230             p_handler->psz_ext = strdup( psz_ext );
231             psz_options = E_(FirstWord)( psz_program, psz_program );
232             p_handler->i_argc = 0;
233             p_handler->ppsz_argv = NULL;
234             TAB_APPEND( p_handler->i_argc, p_handler->ppsz_argv,
235                         strdup( psz_program ) );
236             while( psz_options != NULL && *psz_options )
237             {
238                 char *psz_next = E_(FirstWord)( psz_options, psz_options );
239                 TAB_APPEND( p_handler->i_argc, p_handler->ppsz_argv,
240                             strdup( psz_options ) );
241                 psz_options = psz_next;
242             }
243             /* NULL will be appended later on */
244
245             TAB_APPEND( p_sys->i_handlers, p_sys->pp_handlers, p_handler );
246         }
247     }
248     if( psz_src != NULL )
249         free( psz_src );
250 #endif
251
252     /* determine SSL configuration */
253     psz_cert = config_GetPsz( p_intf, "http-intf-cert" );
254     if ( psz_cert != NULL )
255     {
256         msg_Dbg( p_intf, "enabling TLS for HTTP interface (cert file: %s)",
257                  psz_cert );
258         psz_key = var_GetNonEmptyString( p_intf, "http-intf-key" );
259         psz_ca = var_GetNonEmptyString( p_intf, "http-intf-ca" );
260         psz_crl = var_GetNonEmptyString( p_intf, "http-intf-crl" );
261
262         if( i_port <= 0 )
263             i_port = 8443;
264     }
265     else
266     {
267         if( i_port <= 0 )
268             i_port= 8080;
269     }
270
271     msg_Dbg( p_intf, "base %s:%d", psz_address, i_port );
272
273     p_sys->p_httpd_host = httpd_TLSHostNew( VLC_OBJECT(p_intf), psz_address,
274                                             i_port, psz_cert, psz_key, psz_ca,
275                                             psz_crl );
276     if( p_sys->p_httpd_host == NULL )
277     {
278         msg_Err( p_intf, "cannot listen on %s:%d", psz_address, i_port );
279         free( p_sys->psz_html_type );
280         free( p_sys->psz_address );
281         free( p_sys );
282         return VLC_EGENERIC;
283     }
284     else
285     {
286         char psz_tmp[NI_MAXHOST + 6];
287
288         /* Ugly hack to run several HTTP servers on different ports */
289         snprintf( psz_tmp, sizeof (psz_tmp), "%s:%d", psz_address, i_port + 1 );
290         var_Create(p_intf->p_libvlc, "http-host", VLC_VAR_STRING );
291         var_SetString( p_intf->p_libvlc, "http-host", psz_tmp );
292     }
293
294     p_sys->i_files  = 0;
295     p_sys->pp_files = NULL;
296
297 #if defined(__APPLE__) || defined(SYS_BEOS) || defined(WIN32)
298     if ( ( psz_src = config_GetPsz( p_intf, "http-src" )) == NULL )
299     {
300         const char * psz_vlcpath = config_GetDataDir();
301         psz_src = malloc( strlen(psz_vlcpath) + strlen("/http" ) + 1 );
302         if( !psz_src ) return VLC_ENOMEM;
303         sprintf( psz_src, "%s/http", psz_vlcpath );
304     }
305 #else
306     psz_src = config_GetPsz( p_intf, "http-src" );
307
308     if( ( psz_src == NULL ) || ( *psz_src == '\0' ) )
309     {
310         static char const* ppsz_paths[] = {
311             "share/http",
312             "../share/http",
313             DATA_PATH"/http",
314             NULL
315         };
316         unsigned i;
317
318         if( psz_src != NULL )
319         {
320             free( psz_src );
321             psz_src = NULL;
322         }
323
324         for( i = 0; ppsz_paths[i] != NULL; i++ )
325             if( !DirectoryCheck( ppsz_paths[i] ) )
326             {
327                 psz_src = strdup( ppsz_paths[i] );
328                 break;
329             }
330     }
331 #endif
332
333     if( !psz_src || *psz_src == '\0' )
334     {
335         msg_Err( p_intf, "invalid web interface source directory" );
336         goto failed;
337     }
338
339     /* remove trainling \ or / */
340     if( psz_src[strlen( psz_src ) - 1] == '\\' ||
341         psz_src[strlen( psz_src ) - 1] == '/' )
342     {
343         psz_src[strlen( psz_src ) - 1] = '\0';
344     }
345
346     E_(ParseDirectory)( p_intf, psz_src, psz_src );
347
348     if( config_GetInt( p_intf, "http-album-art" ) )
349     {
350         /* FIXME: we're leaking h */
351         httpd_handler_sys_t *h = malloc( sizeof( httpd_handler_sys_t ) );
352         if( !h )
353         {
354             msg_Err( p_intf, "not enough memory to allocate album art handler" );
355             goto failed;
356         }
357         h->file.p_intf = p_intf;
358         h->file.file = NULL;
359         h->file.name = NULL;
360         /* TODO: use ACL and login/password stuff here too */
361         h->p_handler = httpd_HandlerNew( p_sys->p_httpd_host,
362                                          "/art", NULL, NULL, NULL,
363                                          E_(ArtCallback), h );
364         TAB_APPEND( p_sys->i_handlers, p_sys->pp_handlers, h->p_handler );
365     }
366
367     if( p_sys->i_files <= 0 )
368     {
369         msg_Err( p_intf, "cannot find any file in directory %s", psz_src );
370         goto failed;
371     }
372     p_intf->pf_run = Run;
373     free( psz_src );
374
375     return VLC_SUCCESS;
376
377 failed:
378     free( psz_src );
379     free( p_sys->pp_files );
380     httpd_HostDelete( p_sys->p_httpd_host );
381     free( p_sys->psz_address );
382     free( p_sys->psz_html_type );
383     if( p_sys->iconv_from_utf8 != (vlc_iconv_t)-1 )
384         vlc_iconv_close( p_sys->iconv_from_utf8 );
385     if( p_sys->iconv_to_utf8 != (vlc_iconv_t)-1 )
386         vlc_iconv_close( p_sys->iconv_to_utf8 );
387     free( p_sys );
388     return VLC_EGENERIC;
389 }
390
391 /*****************************************************************************
392  * Close: destroy interface
393  *****************************************************************************/
394 static void Close ( vlc_object_t *p_this )
395 {
396     intf_thread_t *p_intf = (intf_thread_t *)p_this;
397     intf_sys_t    *p_sys = p_intf->p_sys;
398
399     int i;
400
401     if( p_sys->p_vlm )
402     {
403         vlm_Delete( p_sys->p_vlm );
404     }
405     for( i = 0; i < p_sys->i_files; i++ )
406     {
407         if( p_sys->pp_files[i]->b_handler )
408             httpd_HandlerDelete( ((httpd_handler_sys_t *)p_sys->pp_files[i])->p_handler );
409         else
410             httpd_FileDelete( p_sys->pp_files[i]->p_file );
411         if( p_sys->pp_files[i]->p_redir )
412             httpd_RedirectDelete( p_sys->pp_files[i]->p_redir );
413         if( p_sys->pp_files[i]->p_redir2 )
414             httpd_RedirectDelete( p_sys->pp_files[i]->p_redir2 );
415
416         free( p_sys->pp_files[i]->file );
417         free( p_sys->pp_files[i]->name );
418         free( p_sys->pp_files[i] );
419     }
420     if( p_sys->pp_files )
421     {
422         free( p_sys->pp_files );
423     }
424     for( i = 0; i < p_sys->i_handlers; i++ )
425     {
426         http_association_t *p_handler = p_sys->pp_handlers[i];
427         int j;
428         free( p_handler->psz_ext );
429         for( j = 0; j < p_handler->i_argc; j++ )
430             free( p_handler->ppsz_argv[j] );
431         if( p_handler->i_argc )
432             free( p_handler->ppsz_argv );
433         free( p_handler );
434     }
435     if( p_sys->i_handlers )
436         free( p_sys->pp_handlers );
437     httpd_HostDelete( p_sys->p_httpd_host );
438     free( p_sys->psz_address );
439     free( p_sys->psz_html_type );
440
441     if( p_sys->iconv_from_utf8 != (vlc_iconv_t)-1 )
442         vlc_iconv_close( p_sys->iconv_from_utf8 );
443     if( p_sys->iconv_to_utf8 != (vlc_iconv_t)-1 )
444         vlc_iconv_close( p_sys->iconv_to_utf8 );
445     free( p_sys );
446 }
447
448 /*****************************************************************************
449  * Run: http interface thread
450  *****************************************************************************/
451 static void Run( intf_thread_t *p_intf )
452 {
453     intf_sys_t     *p_sys = p_intf->p_sys;
454
455     while( !intf_ShouldDie( p_intf ) )
456     {
457         /* get the playlist */
458         if( p_sys->p_playlist == NULL )
459         {
460             p_sys->p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );
461         }
462
463         /* Manage the input part */
464         if( p_sys->p_input == NULL )
465         {
466             if( p_sys->p_playlist )
467             {
468                 p_sys->p_input = p_sys->p_playlist->p_input;
469             }
470         }
471         else if( p_sys->p_input->b_dead || p_sys->p_input->b_die )
472         {
473             p_sys->p_input = NULL;
474         }
475
476
477         /* Wait a bit */
478         msleep( INTF_IDLE_SLEEP );
479     }
480
481     if( p_sys->p_input )
482     {
483         vlc_object_release( p_sys->p_input );
484         p_sys->p_input = NULL;
485     }
486
487     if( p_sys->p_playlist )
488     {
489         vlc_object_release( p_sys->p_playlist );
490         p_sys->p_playlist = NULL;
491     }
492 }
493
494 /****************************************************************************
495  * HttpCallback:
496  ****************************************************************************
497  * a file with b_html is parsed and all "macro" replaced
498  ****************************************************************************/
499 static void Callback404( httpd_file_sys_t *p_args, char **pp_data,
500                          int *pi_data )
501 {
502     char *p = *pp_data = malloc( 10240 );
503     if( !p )
504     {
505         return;
506     }
507     p += sprintf( p, "Content-Type: text/html\n" );
508     p += sprintf( p, "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" );
509     p += sprintf( p, "<head>\n" );
510     p += sprintf( p, "<title>Error loading %s</title>\n", p_args->file );
511     p += sprintf( p, "</head>\n" );
512     p += sprintf( p, "<body>\n" );
513     p += sprintf( p, "<h1><center>Error loading %s for %s</center></h1>\n", p_args->file, p_args->name );
514     p += sprintf( p, "<a href=\"http://www.videolan.org/\">VideoLAN</a>\n" );
515     p += sprintf( p, "</body>\n" );
516     p += sprintf( p, "</html>\n" );
517
518     *pi_data = strlen( *pp_data );
519 }
520
521 static void ParseExecute( httpd_file_sys_t *p_args, char *p_buffer,
522                           int i_buffer, char *p_request,
523                           char **pp_data, int *pi_data )
524 {
525     int i_request = p_request != NULL ? strlen( p_request ) : 0;
526     char *dst;
527     vlc_value_t val;
528     char position[4]; /* percentage */
529     char time[12]; /* in seconds */
530     char length[12]; /* in seconds */
531     audio_volume_t i_volume;
532     char volume[5];
533     const char *state;
534     char stats[20];
535
536 #define p_sys p_args->p_intf->p_sys
537     if( p_sys->p_input )
538     {
539         var_Get( p_sys->p_input, "position", &val);
540         sprintf( position, "%d" , (int)((val.f_float) * 100.0));
541         var_Get( p_sys->p_input, "time", &val);
542         sprintf( time, I64Fi, (int64_t)val.i_time / I64C(1000000) );
543         var_Get( p_sys->p_input, "length", &val);
544         sprintf( length, I64Fi, (int64_t)val.i_time / I64C(1000000) );
545
546         var_Get( p_sys->p_input, "state", &val );
547         if( val.i_int == PLAYING_S )
548         {
549             state = "playing";
550         }
551         else if( val.i_int == OPENING_S )
552         {
553             state = "opening/connecting";
554         }
555         else if( val.i_int == BUFFERING_S )
556         {
557             state = "buffering";
558         }
559         else if( val.i_int == PAUSE_S )
560         {
561             state = "paused";
562         }
563         else
564         {
565             state = "stop";
566         }
567     }
568     else
569     {
570         sprintf( position, "%d", 0 );
571         sprintf( time, "%d", 0 );
572         sprintf( length, "%d", 0 );
573         state = "stop";
574     }
575 #undef p_sys
576
577     aout_VolumeGet( p_args->p_intf, &i_volume );
578     sprintf( volume, "%d", (int)i_volume );
579
580     p_args->vars = E_(mvar_New)( "variables", "" );
581     E_(mvar_AppendNewVar)( p_args->vars, "url_param",
582                            i_request > 0 ? "1" : "0" );
583     E_(mvar_AppendNewVar)( p_args->vars, "url_value", p_request );
584     E_(mvar_AppendNewVar)( p_args->vars, "version", VLC_Version() );
585     E_(mvar_AppendNewVar)( p_args->vars, "copyright", COPYRIGHT_MESSAGE );
586     E_(mvar_AppendNewVar)( p_args->vars, "vlc_compile_by", VLC_CompileBy() );
587     E_(mvar_AppendNewVar)( p_args->vars, "vlc_compile_host",
588                            VLC_CompileHost() );
589     E_(mvar_AppendNewVar)( p_args->vars, "vlc_compile_domain",
590                            VLC_CompileDomain() );
591     E_(mvar_AppendNewVar)( p_args->vars, "vlc_compiler", VLC_Compiler() );
592     E_(mvar_AppendNewVar)( p_args->vars, "vlc_changeset", VLC_Changeset() );
593     E_(mvar_AppendNewVar)( p_args->vars, "stream_position", position );
594     E_(mvar_AppendNewVar)( p_args->vars, "stream_time", time );
595     E_(mvar_AppendNewVar)( p_args->vars, "stream_length", length );
596     E_(mvar_AppendNewVar)( p_args->vars, "volume", volume );
597     E_(mvar_AppendNewVar)( p_args->vars, "stream_state", state );
598     E_(mvar_AppendNewVar)( p_args->vars, "charset", ((intf_sys_t *)p_args->p_intf->p_sys)->psz_charset );
599
600     /* Stats */
601 #define p_sys p_args->p_intf->p_sys
602     if( p_sys->p_input )
603     {
604         /* FIXME: Workarround a stupid assert in input_GetItem */
605         input_item_t *p_item = p_sys->p_input && p_sys->p_input->p
606                                ? input_GetItem( p_sys->p_input )
607                                : NULL;
608
609         if( p_item )
610         {
611             vlc_mutex_lock( &p_item->p_stats->lock );
612 #define STATS_INT( n ) sprintf( stats, "%d", p_item->p_stats->i_ ## n ); \
613                        E_(mvar_AppendNewVar)( p_args->vars, #n, stats );
614 #define STATS_FLOAT( n ) sprintf( stats, "%f", p_item->p_stats->f_ ## n ); \
615                        E_(mvar_AppendNewVar)( p_args->vars, #n, stats );
616             STATS_INT( read_bytes )
617             STATS_FLOAT( input_bitrate )
618             STATS_INT( demux_read_bytes )
619             STATS_FLOAT( demux_bitrate )
620             STATS_INT( decoded_video )
621             STATS_INT( displayed_pictures )
622             STATS_INT( lost_pictures )
623             STATS_INT( decoded_audio )
624             STATS_INT( played_abuffers )
625             STATS_INT( lost_abuffers )
626             STATS_INT( sent_packets )
627             STATS_INT( sent_bytes )
628             STATS_FLOAT( send_bitrate )
629 #undef STATS_INT
630 #undef STATS_FLOAT
631             vlc_mutex_unlock( &p_item->p_stats->lock );
632         }
633     }
634 #undef p_sys
635
636     E_(SSInit)( &p_args->stack );
637
638     /* allocate output */
639     *pi_data = i_buffer + 1000;
640     dst = *pp_data = malloc( *pi_data );
641
642     /* we parse executing all  <vlc /> macros */
643     E_(Execute)( p_args, p_request, i_request, pp_data, pi_data, &dst,
644                  &p_buffer[0], &p_buffer[i_buffer] );
645
646     *dst     = '\0';
647     *pi_data = dst - *pp_data;
648
649     E_(SSClean)( &p_args->stack );
650     E_(mvar_Delete)( p_args->vars );
651 }
652
653 int  E_(HttpCallback)( httpd_file_sys_t *p_args,
654                        httpd_file_t *p_file,
655                        uint8_t *_p_request,
656                        uint8_t **_pp_data, int *pi_data )
657 {
658     char *p_request = (char *)_p_request;
659     char **pp_data = (char **)_pp_data;
660     FILE *f;
661
662     if( ( f = utf8_fopen( p_args->file, "r" ) ) == NULL )
663     {
664         Callback404( p_args, pp_data, pi_data );
665         return VLC_SUCCESS;
666     }
667
668     if( !p_args->b_html )
669     {
670         E_(FileLoad)( f, pp_data, pi_data );
671     }
672     else
673     {
674         int  i_buffer;
675         char *p_buffer;
676
677         /* first we load in a temporary buffer */
678         E_(FileLoad)( f, &p_buffer, &i_buffer );
679
680         ParseExecute( p_args, p_buffer, i_buffer, p_request, pp_data, pi_data );
681
682         free( p_buffer );
683     }
684
685     fclose( f );
686
687     return VLC_SUCCESS;
688 }
689
690 /****************************************************************************
691  * HandlerCallback:
692  ****************************************************************************
693  * call the external handler and parse vlc macros if Content-Type is HTML
694  ****************************************************************************/
695 int  E_(HandlerCallback)( httpd_handler_sys_t *p_args,
696                           httpd_handler_t *p_handler, char *_p_url,
697                           uint8_t *_p_request, int i_type,
698                           uint8_t *_p_in, int i_in,
699                           char *psz_remote_addr, char *psz_remote_host,
700                           uint8_t **_pp_data, int *pi_data )
701 {
702     char *p_url = (char *)_p_url;
703     char *p_request = (char *)_p_request;
704     char **pp_data = (char **)_pp_data;
705     char *p_in = (char *)p_in;
706     int i_request = p_request != NULL ? strlen( p_request ) : 0;
707     char *p;
708     int i_env = 0;
709     char **ppsz_env = NULL;
710     char *psz_tmp;
711     char sep;
712     size_t i_buffer;
713     char *p_buffer;
714     char *psz_cwd, *psz_file = NULL;
715     int i_ret;
716
717 #ifdef WIN32
718     sep = '\\';
719 #else
720     sep = '/';
721 #endif
722
723     /* Create environment for the CGI */
724     TAB_APPEND( i_env, ppsz_env, strdup("GATEWAY_INTERFACE=CGI/1.1") );
725     TAB_APPEND( i_env, ppsz_env, strdup("SERVER_PROTOCOL=HTTP/1.1") );
726     TAB_APPEND( i_env, ppsz_env, strdup("SERVER_SOFTWARE=" COPYRIGHT_MESSAGE) );
727
728     switch( i_type )
729     {
730     case HTTPD_MSG_GET:
731         TAB_APPEND( i_env, ppsz_env, strdup("REQUEST_METHOD=GET") );
732         break;
733     case HTTPD_MSG_POST:
734         TAB_APPEND( i_env, ppsz_env, strdup("REQUEST_METHOD=POST") );
735         break;
736     case HTTPD_MSG_HEAD:
737         TAB_APPEND( i_env, ppsz_env, strdup("REQUEST_METHOD=HEAD") );
738         break;
739     default:
740         break;
741     }
742
743     if( i_request )
744     {
745         psz_tmp = malloc( sizeof("QUERY_STRING=") + i_request );
746         sprintf( psz_tmp, "QUERY_STRING=%s", p_request );
747         TAB_APPEND( i_env, ppsz_env, psz_tmp );
748
749         psz_tmp = malloc( sizeof("REQUEST_URI=?") + strlen(p_url)
750                            + i_request );
751         sprintf( psz_tmp, "REQUEST_URI=%s?%s", p_url, p_request );
752         TAB_APPEND( i_env, ppsz_env, psz_tmp );
753     }
754     else
755     {
756         psz_tmp = malloc( sizeof("REQUEST_URI=") + strlen(p_url) );
757         sprintf( psz_tmp, "REQUEST_URI=%s", p_url );
758         TAB_APPEND( i_env, ppsz_env, psz_tmp );
759     }
760
761     psz_tmp = malloc( sizeof("SCRIPT_NAME=") + strlen(p_url) );
762     sprintf( psz_tmp, "SCRIPT_NAME=%s", p_url );
763     TAB_APPEND( i_env, ppsz_env, psz_tmp );
764
765 #define p_sys p_args->file.p_intf->p_sys
766     psz_tmp = malloc( sizeof("SERVER_NAME=") + strlen(p_sys->psz_address) );
767     sprintf( psz_tmp, "SERVER_NAME=%s", p_sys->psz_address );
768     TAB_APPEND( i_env, ppsz_env, psz_tmp );
769
770     psz_tmp = malloc( sizeof("SERVER_PORT=") + 5 );
771     sprintf( psz_tmp, "SERVER_PORT=%u", p_sys->i_port );
772     TAB_APPEND( i_env, ppsz_env, psz_tmp );
773 #undef p_sys
774
775     p = getenv( "PATH" );
776     if( p != NULL )
777     {
778         psz_tmp = malloc( sizeof("PATH=") + strlen(p) );
779         sprintf( psz_tmp, "PATH=%s", p );
780         TAB_APPEND( i_env, ppsz_env, psz_tmp );
781     }
782
783 #ifdef WIN32
784     p = getenv( "windir" );
785     if( p != NULL )
786     {
787         psz_tmp = malloc( sizeof("SYSTEMROOT=") + strlen(p) );
788         sprintf( psz_tmp, "SYSTEMROOT=%s", p );
789         TAB_APPEND( i_env, ppsz_env, psz_tmp );
790     }
791 #endif
792
793     if( psz_remote_addr != NULL && *psz_remote_addr )
794     {
795         psz_tmp = malloc( sizeof("REMOTE_ADDR=") + strlen(psz_remote_addr) );
796         sprintf( psz_tmp, "REMOTE_ADDR=%s", psz_remote_addr );
797         TAB_APPEND( i_env, ppsz_env, psz_tmp );
798     }
799
800     if( psz_remote_host != NULL && *psz_remote_host )
801     {
802         psz_tmp = malloc( sizeof("REMOTE_HOST=") + strlen(psz_remote_host) );
803         sprintf( psz_tmp, "REMOTE_HOST=%s", psz_remote_host );
804         TAB_APPEND( i_env, ppsz_env, psz_tmp );
805     }
806
807     if( i_in )
808     {
809         p = p_in;
810         for ( ; ; )
811         {
812             if( !strncasecmp( p, "Content-Type: ", strlen("Content-Type: ") ) )
813             {
814                 char *end = strchr( p, '\r' );
815                 if( end == NULL )
816                     break;
817                 *end = '\0';
818                 psz_tmp = malloc( sizeof("CONTENT_TYPE=") + strlen(p) );
819                 sprintf( psz_tmp, "CONTENT_TYPE=%s", p );
820                 TAB_APPEND( i_env, ppsz_env, psz_tmp );
821                 *end = '\r';
822             }
823             if( !strncasecmp( p, "Content-Length: ",
824                               strlen("Content-Length: ") ) )
825             {
826                 char *end = strchr( p, '\r' );
827                 if( end == NULL )
828                     break;
829                 *end = '\0';
830                 psz_tmp = malloc( sizeof("CONTENT_LENGTH=") + strlen(p) );
831                 sprintf( psz_tmp, "CONTENT_LENGTH=%s", p );
832                 TAB_APPEND( i_env, ppsz_env, psz_tmp );
833                 *end = '\r';
834             }
835
836             p = strchr( p, '\n' );
837             if( p == NULL || p[1] == '\r' )
838             {
839                 p = NULL;
840                 break;
841             }
842             p++;
843         }
844     }
845
846     psz_file = strrchr( p_args->file.file, sep );
847     if( psz_file != NULL )
848     {
849         psz_file++;
850         psz_tmp = malloc( sizeof("SCRIPT_FILENAME=") + strlen(psz_file) );
851         sprintf( psz_tmp, "SCRIPT_FILENAME=%s", psz_file );
852         TAB_APPEND( i_env, ppsz_env, psz_tmp );
853
854         TAB_APPEND( p_args->p_association->i_argc,
855                     p_args->p_association->ppsz_argv, psz_file );
856     }
857
858     TAB_APPEND( i_env, ppsz_env, NULL );
859
860     TAB_APPEND( p_args->p_association->i_argc, p_args->p_association->ppsz_argv,
861                 NULL );
862
863     psz_tmp = strdup( p_args->file.file );
864     p = strrchr( psz_tmp, sep );
865     if( p != NULL )
866     {
867         *p = '\0';
868         psz_cwd = psz_tmp;
869     }
870     else
871     {
872         free( psz_tmp );
873         psz_cwd = NULL;
874     }
875
876     i_ret = vlc_execve( p_args->file.p_intf, p_args->p_association->i_argc,
877                         p_args->p_association->ppsz_argv, ppsz_env, psz_cwd,
878                         (char *)p_in, i_in, &p_buffer, &i_buffer );
879     TAB_REMOVE( p_args->p_association->i_argc, p_args->p_association->ppsz_argv,
880                 NULL );
881     TAB_REMOVE( p_args->p_association->i_argc, p_args->p_association->ppsz_argv,
882                 psz_file );
883     if( psz_cwd != NULL )
884         free( psz_cwd );
885     while( i_env )
886         TAB_REMOVE( i_env, ppsz_env, ppsz_env[0] );
887
888     if( i_ret == -1 )
889     {
890         Callback404( (httpd_file_sys_t *)p_args, pp_data, pi_data );
891         return VLC_SUCCESS;
892     }
893     p = p_buffer;
894     while( strncasecmp( p, "Content-Type: text/html",
895                         strlen("Content-Type: text/html") ) )
896     {
897         p = strchr( p, '\n' );
898         if( p == NULL || p[1] == '\r' )
899         {
900             p = NULL;
901             break;
902         }
903         p++;
904     }
905
906     if( p == NULL )
907     {
908         *pp_data = p_buffer;
909         *pi_data = i_buffer;
910     }
911     else
912     {
913         ParseExecute( (httpd_file_sys_t *)p_args, p_buffer, i_buffer,
914                       p_request, pp_data, pi_data );
915
916         free( p_buffer );
917     }
918
919     return VLC_SUCCESS;
920 }
921
922 int  E_(ArtCallback)( httpd_handler_sys_t *p_args,
923                           httpd_handler_t *p_handler, char *_p_url,
924                           uint8_t *p_request, int i_type,
925                           uint8_t *p_in, int i_in,
926                           char *psz_remote_addr, char *psz_remote_host,
927                           uint8_t **pp_data, int *pi_data )
928 {
929     char *psz_art = NULL;
930     intf_thread_t *p_intf = p_args->file.p_intf;
931     intf_sys_t *p_sys = p_intf->p_sys;
932     char psz_id[16];
933     input_item_t *p_item = NULL;
934     int i_id;
935
936     psz_id[0] = '\0';
937     if( p_request )
938         E_(ExtractURIValue)( (char *)p_request, "id", psz_id, 15 );
939     i_id = atoi( psz_id );
940     if( i_id )
941     {
942         playlist_item_t *p_pl_item = playlist_ItemGetById( p_sys->p_playlist,
943                                                            i_id, VLC_FALSE );
944         if( p_pl_item )
945             p_item = p_pl_item->p_input;
946     }
947     else
948     {
949         /* FIXME: Workarround a stupid assert in input_GetItem */
950         if( p_sys->p_input && p_sys->p_input->p )
951             p_item = input_GetItem( p_sys->p_input );
952     }
953
954     if( p_item )
955     {
956         psz_art = input_item_GetArtURL( p_item );
957     }
958
959     if( psz_art && !strncmp( psz_art, "file://", strlen( "file://" ) ) )
960     {
961         FILE *f;
962         char *psz_ext;
963         char *psz_header;
964         char *p_data = NULL;
965         int i_header_size, i_data;
966
967         if( ( f = utf8_fopen( psz_art + strlen( "file://" ), "r" ) ) == NULL )
968         {
969             msg_Dbg( p_intf, "Couldn't open album art file %s",
970                      psz_art + strlen( "file://" ) );
971             Callback404( &p_args->file, (char**)pp_data, pi_data );
972             free( psz_art );
973             return VLC_SUCCESS;
974         }
975
976         E_(FileLoad)( f, &p_data, &i_data );
977
978         fclose( f );
979
980         psz_ext = strrchr( psz_art, '.' );
981         if( psz_ext ) psz_ext++;
982
983 #define HEADER  "Content-Type: image/%s\n" \
984                 "Content-Length: %d\n" \
985                 "\n"
986         i_header_size = asprintf( &psz_header, HEADER, psz_ext, i_data );
987 #undef HEADER
988
989         *pi_data = i_header_size + i_data;
990         *pp_data = (uint8_t*)malloc( *pi_data );
991         memcpy( *pp_data, psz_header, i_header_size );
992         memcpy( *pp_data+i_header_size, p_data, i_data );
993         free( psz_header );
994         free( p_data );
995     }
996     else
997     {
998         msg_Dbg( p_intf, "No album art found" );
999         Callback404( &p_args->file, (char**)pp_data, pi_data );
1000     }
1001
1002     free( psz_art );
1003
1004     return VLC_SUCCESS;
1005 }