]> git.sesse.net Git - vlc/blob - src/misc/httpd.c
Support for re-using the same TLS/SSL httpd hosts for multiple stream ouputs;
[vlc] / src / misc / httpd.c
1 /*****************************************************************************
2  * httpd.c
3  *****************************************************************************
4  * Copyright (C) 2004-2005 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          RĂ©mi Denis-Courmont <rem # videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 #include <stdlib.h>
26 #include <vlc/vlc.h>
27
28 #ifdef ENABLE_HTTPD
29
30 #include "vlc_httpd.h"
31 #include "network.h"
32 #include "vlc_tls.h"
33
34 #include <string.h>
35 #include <errno.h>
36
37 #ifdef HAVE_UNISTD_H
38 #   include <unistd.h>
39 #endif
40
41 #ifdef HAVE_FCNTL_H
42 #   include <fcntl.h>
43 #endif
44
45 #if defined( UNDER_CE )
46 #   include <winsock.h>
47 #elif defined( WIN32 )
48 #   include <winsock2.h>
49 #   include <ws2tcpip.h>
50 #else
51 #   include <netdb.h>                                         /* hostent ... */
52 #   include <sys/socket.h>
53 /* FIXME: should not be needed */
54 #   include <netinet/in.h>
55 #   ifdef HAVE_ARPA_INET_H
56 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
57 #   endif
58 #endif
59
60 #if 0
61 typedef struct httpd_t          httpd_t;
62
63 typedef struct httpd_host_t     httpd_host_t;
64 typedef struct httpd_url_t      httpd_url_t;
65 typedef struct httpd_client_t   httpd_client_t;
66
67 enum
68 {
69     HTTPD_MSG_NONE,
70
71     /* answer */
72     HTTPD_MSG_ANSWER,
73
74     /* channel communication */
75     HTTPD_MSG_CHANNEL,
76
77     /* http request */
78     HTTPD_MSG_GET,
79     HTTPD_MSG_HEAD,
80     HTTPD_MSG_POST,
81
82     /* rtsp request */
83     HTTPD_MSG_OPTIONS,
84     HTTPD_MSG_DESCRIBE,
85     HTTPD_MSG_SETUP,
86     HTTPD_MSG_PLAY,
87     HTTPD_MSG_PAUSE,
88     HTTPD_MSG_TEARDOWN,
89
90     /* just to track the count of MSG */
91     HTTPD_MSG_MAX
92 };
93
94 enum
95 {
96     HTTPD_PROTO_NONE,
97     HTTPD_PROTO_HTTP,
98     HTTPD_PROTO_RTSP,
99 };
100
101 typedef struct
102 {
103     httpd_client_t *cl; /* NULL if not throught a connection e vlc internal */
104
105     int     i_type;
106     int     i_proto;
107     int     i_version;
108
109     /* for an answer */
110     int     i_status;
111     char    *psz_status;
112
113     /* for a query */
114     char    *psz_url;
115     char    *psz_args;  /* FIXME find a clean way to handle GET(psz_args) and POST(body) through the same code */
116
117     /* for rtp over rtsp */
118     int     i_channel;
119
120     /* options */
121     int     i_name;
122     char    **name;
123     int     i_value;
124     char    **value;
125
126     /* body */
127     int64_t i_body_offset;
128     int     i_body;
129     uint8_t *p_body;
130
131 } httpd_message_t;
132
133 typedef struct httpd_callback_sys_t httpd_callback_sys_t;
134 /* answer could be null, int this case no answer is requested */
135 typedef int (*httpd_callback_t)( httpd_callback_sys_t *, httpd_client_t *, httpd_message_t *answer, httpd_message_t *query );
136
137
138 /* create a new host */
139 httpd_host_t *httpd_HostNew( vlc_object_t *, char *psz_host, int i_port );
140 /* delete a host */
141 void          httpd_HostDelete( httpd_host_t * );
142
143 /* register a new url */
144 httpd_url_t *httpd_UrlNew( httpd_host_t *, char *psz_url );
145 /* register callback on a url */
146 int          httpd_UrlCatch( httpd_url_t *, int i_msg,
147                              httpd_callback_t, httpd_callback_sys_t * );
148 /* delete an url */
149 void         httpd_UrlDelete( httpd_url_t * );
150
151
152 void httpd_ClientModeStream( httpd_client_t *cl );
153 void httpd_ClientModeBidir( httpd_client_t *cl );
154 static void httpd_ClientClean( httpd_client_t *cl );
155
156 /* High level */
157 typedef struct httpd_file_t     httpd_file_t;
158 typedef struct httpd_file_sys_t httpd_file_sys_t;
159 typedef int (*httpd_file_callback_t)( httpd_file_sys_t*, httpd_file_t *, uint8_t *psz_request, uint8_t **pp_data, int *pi_data );
160 httpd_file_t *httpd_FileNew( httpd_host_t *,
161                              char *psz_url, char *psz_mime,
162                              char *psz_user, char *psz_password,
163                              httpd_file_callback_t pf_fill,
164                              httpd_file_sys_t *p_sys );
165 void         httpd_FileDelete( httpd_file_t * );
166
167 typedef struct httpd_redirect_t httpd_redirect_t;
168 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *, char *psz_url_dst, char *psz_url_src );
169 void              httpd_RedirectDelete( httpd_redirect_t * );
170
171 #if 0
172 typedef struct httpd_stream_t httpd_stream_t;
173 httpd_stream_t *httpd_StreamNew( httpd_host_t * );
174 int             httpd_StreamHeader( httpd_stream_t *, uint8_t *p_data, int i_data );
175 int             httpd_StreamSend( httpd_stream_t *, uint8_t *p_data, int i_data );
176 void            httpd_StreamDelete( httpd_stream_t * );
177 #endif
178
179 /* Msg functions facilities */
180 void         httpd_MsgInit( httpd_message_t * );
181 void         httpd_MsgAdd( httpd_message_t *, char *psz_name, char *psz_value, ... );
182 /* return "" if not found. The string is not allocated */
183 char        *httpd_MsgGet( httpd_message_t *, char *psz_name );
184 void         httpd_MsgClean( httpd_message_t * );
185 #endif
186
187 #if 0
188 struct httpd_t
189 {
190     VLC_COMMON_MEMBERS
191
192     /* vlc_mutex_t  lock; */
193     int          i_host;
194     httpd_host_t **host;
195 };
196 #endif
197
198 static void httpd_ClientClean( httpd_client_t *cl );
199
200 /* each host run in his own thread */
201 struct httpd_host_t
202 {
203     VLC_COMMON_MEMBERS
204
205     httpd_t     *httpd;
206
207     /* ref count */
208     int         i_ref;
209
210     /* address/port and socket for listening at connections */
211     char        *psz_hostname;
212     int         i_port;
213     int         *fd;
214
215     vlc_mutex_t lock;
216
217     /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
218      * This will slow down the url research but make my live easier
219      * All url will have their cb trigger, but only the first one can answer
220      * */
221     int         i_url;
222     httpd_url_t **url;
223
224     int            i_client;
225     httpd_client_t **client;
226     
227     /* TLS data */
228     tls_server_t *p_tls;
229 };
230
231 struct httpd_url_t
232 {
233     httpd_host_t *host;
234
235     vlc_mutex_t lock;
236
237     char    *psz_url;
238     char    *psz_user;
239     char    *psz_password;
240
241     struct
242     {
243         httpd_callback_t     cb;
244         httpd_callback_sys_t *p_sys;
245     } catch[HTTPD_MSG_MAX];
246 };
247
248 /* status */
249 enum
250 {
251     HTTPD_CLIENT_RECEIVING,
252     HTTPD_CLIENT_RECEIVE_DONE,
253
254     HTTPD_CLIENT_SENDING,
255     HTTPD_CLIENT_SEND_DONE,
256
257     HTTPD_CLIENT_WAITING,
258
259     HTTPD_CLIENT_DEAD,
260
261     HTTPD_CLIENT_TLS_HS_IN,
262     HTTPD_CLIENT_TLS_HS_OUT
263 };
264 /* mode */
265 enum
266 {
267     HTTPD_CLIENT_FILE,      /* default */
268     HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
269     HTTPD_CLIENT_BIDIR,     /* check for reading and get data from cb */
270 };
271
272 struct httpd_client_t
273 {
274     httpd_url_t *url;
275
276     int     i_ref;
277
278     struct  sockaddr_storage sock;
279     int     i_sock_size;
280     int     fd;
281
282     int     i_mode;
283     int     i_state;
284     int     b_read_waiting; /* stop as soon as possible sending */
285
286     mtime_t i_activity_date;
287     mtime_t i_activity_timeout;
288
289     /* buffer for reading header */
290     int     i_buffer_size;
291     int     i_buffer;
292     uint8_t *p_buffer;
293
294     /* */
295     httpd_message_t query;  /* client -> httpd */
296     httpd_message_t answer; /* httpd -> client */
297     
298     /* TLS data */
299     tls_session_t *p_tls;
300 };
301
302
303 /*****************************************************************************
304  * Various functions
305  *****************************************************************************/
306 /*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
307 static void b64_decode( char *dest, char *src )
308 {
309     int  i_level;
310     int  last = 0;
311     int  b64[256] = {
312         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
313         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
314         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
315         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
316         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
317         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
318         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
319         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
320         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
321         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
322         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
323         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
324         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
325         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
326         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
327         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
328         };
329
330     for( i_level = 0; *src != '\0'; src++ )
331     {
332         int  c;
333
334         c = b64[(unsigned int)*src];
335         if( c == -1 )
336         {
337             continue;
338         }
339
340         switch( i_level )
341         {
342             case 0:
343                 i_level++;
344                 break;
345             case 1:
346                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
347                 i_level++;
348                 break;
349             case 2:
350                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
351                 i_level++;
352                 break;
353             case 3:
354                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
355                 i_level = 0;
356         }
357         last = c;
358     }
359
360     *dest = '\0';
361 }
362
363 static struct
364 {
365     char *psz_ext;
366     char *psz_mime;
367 } http_mime[] =
368 {
369     { ".htm",   "text/html" },
370     { ".html",  "text/html" },
371     { ".txt",   "text/plain" },
372     { ".xml",   "text/xml" },
373     { ".dtd",   "text/dtd" },
374
375     { ".css",   "text/css" },
376
377     /* image mime */
378     { ".gif",   "image/gif" },
379     { ".jpe",   "image/jpeg" },
380     { ".jpg",   "image/jpeg" },
381     { ".jpeg",  "image/jpeg" },
382     { ".png",   "image/png" },
383     { ".mpjpeg","multipart/x-mixed-replace; boundary=This Random String" },
384
385     /* media mime */
386     { ".avi",   "video/avi" },
387     { ".asf",   "video/x-ms-asf" },
388     { ".m1a",   "audio/mpeg" },
389     { ".m2a",   "audio/mpeg" },
390     { ".m1v",   "video/mpeg" },
391     { ".m2v",   "video/mpeg" },
392     { ".mp2",   "audio/mpeg" },
393     { ".mp3",   "audio/mpeg" },
394     { ".mpa",   "audio/mpeg" },
395     { ".mpg",   "video/mpeg" },
396     { ".mpeg",  "video/mpeg" },
397     { ".mpe",   "video/mpeg" },
398     { ".mov",   "video/quicktime" },
399     { ".moov",  "video/quicktime" },
400     { ".ogg",   "application/ogg" },
401     { ".ogm",   "application/ogg" },
402     { ".wav",   "audio/wav" },
403     { ".wma",   "audio/x-ms-wma" },
404     { ".wmv",   "video/x-ms-wmv" },
405
406
407     /* end */
408     { NULL,     NULL }
409 };
410 static char *httpd_MimeFromUrl( char *psz_url )
411 {
412
413     char *psz_ext;
414
415     psz_ext = strrchr( psz_url, '.' );
416     if( psz_ext )
417     {
418         int i;
419
420         for( i = 0; http_mime[i].psz_ext != NULL ; i++ )
421         {
422             if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
423             {
424                 return http_mime[i].psz_mime;
425             }
426         }
427     }
428     return "application/octet-stream";
429 }
430
431 /*****************************************************************************
432  * High Level Funtions: httpd_file_t
433  *****************************************************************************/
434 struct httpd_file_t
435 {
436     httpd_url_t *url;
437
438     char *psz_url;
439     char *psz_mime;
440
441     httpd_file_callback_t pf_fill;
442     httpd_file_sys_t      *p_sys;
443
444 };
445
446
447 static int httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl, httpd_message_t *answer, httpd_message_t *query )
448 {
449     httpd_file_t *file = (httpd_file_t*)p_sys;
450
451     if( answer == NULL || query == NULL )
452     {
453         return VLC_SUCCESS;
454     }
455     answer->i_proto  = HTTPD_PROTO_HTTP;
456     answer->i_version= query->i_version;
457     answer->i_type   = HTTPD_MSG_ANSWER;
458
459     answer->i_status = 200;
460     answer->psz_status = strdup( "OK" );
461
462     httpd_MsgAdd( answer, "Content-type",  "%s", file->psz_mime );
463     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
464
465     if( query->i_type != HTTPD_MSG_HEAD )
466     {
467         char *psz_args = query->psz_args;
468         if( query->i_type == HTTPD_MSG_POST )
469         {
470             /* Check that */
471             psz_args = query->p_body;
472         }
473         file->pf_fill( file->p_sys, file, psz_args, &answer->p_body,
474                        &answer->i_body );
475     }
476     /* We respect client request */
477     if( strcmp( httpd_MsgGet( &cl->query, "Connection" ), "" ) )
478     {
479         httpd_MsgAdd( answer, "Connection",
480                       httpd_MsgGet( &cl->query, "Connection" ) );
481     }
482
483     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
484
485     return VLC_SUCCESS;
486 }
487
488
489 httpd_file_t *httpd_FileNew( httpd_host_t *host,
490                              char *psz_url, char *psz_mime,
491                              char *psz_user, char *psz_password,
492                              httpd_file_callback_t pf_fill,
493                              httpd_file_sys_t *p_sys )
494 {
495     httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
496
497     if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
498                                           psz_password ) ) == NULL )
499     {
500         free( file );
501         return NULL;
502     }
503
504     file->psz_url  = strdup( psz_url );
505     if( psz_mime && *psz_mime )
506     {
507         file->psz_mime = strdup( psz_mime );
508     }
509     else
510     {
511         file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
512     }
513
514     file->pf_fill = pf_fill;
515     file->p_sys   = p_sys;
516
517     httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
518                     (httpd_callback_sys_t*)file );
519     httpd_UrlCatch( file->url, HTTPD_MSG_GET,  httpd_FileCallBack,
520                     (httpd_callback_sys_t*)file );
521     httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
522                     (httpd_callback_sys_t*)file );
523
524     return file;
525 }
526
527 void httpd_FileDelete( httpd_file_t *file )
528 {
529     httpd_UrlDelete( file->url );
530
531     free( file->psz_url );
532     free( file->psz_mime );
533
534     free( file );
535 }
536
537 /*****************************************************************************
538  * High Level Funtions: httpd_redirect_t
539  *****************************************************************************/
540 struct httpd_redirect_t
541 {
542     httpd_url_t *url;
543     char        *psz_dst;
544 };
545
546 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
547                                    httpd_client_t *cl, httpd_message_t *answer,
548                                    httpd_message_t *query )
549 {
550     httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
551     uint8_t *p;
552
553     if( answer == NULL || query == NULL )
554     {
555         return VLC_SUCCESS;
556     }
557     answer->i_proto  = query->i_proto;
558     answer->i_version= query->i_version;
559     answer->i_type   = HTTPD_MSG_ANSWER;
560     answer->i_status = 301;
561     answer->psz_status = strdup( "Moved Permanently" );
562
563     p = answer->p_body = malloc( 1000 + strlen( rdir->psz_dst ) );
564     p += sprintf( p, "<html>\n" );
565     p += sprintf( p, "<head>\n" );
566     p += sprintf( p, "<title>Redirection</title>\n" );
567     p += sprintf( p, "</head>\n" );
568     p += sprintf( p, "<body>\n" );
569     p += sprintf( p, "<h1><center>You should be <a href=\"%s\">redirected</a></center></h1>\n", rdir->psz_dst );
570     p += sprintf( p, "<hr />\n" );
571     p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
572     p += sprintf( p, "</body>\n" );
573     p += sprintf( p, "</html>\n" );
574     answer->i_body = p - answer->p_body;
575
576     /* XXX check if it's ok or we need to set an absolute url */
577     httpd_MsgAdd( answer, "Location",  "%s", rdir->psz_dst );
578
579     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
580
581     return VLC_SUCCESS;
582 }
583
584 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, char *psz_url_dst,
585                                      char *psz_url_src )
586 {
587     httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
588
589     if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL ) ) )
590     {
591         free( rdir );
592         return NULL;
593     }
594     rdir->psz_dst = strdup( psz_url_dst );
595
596     /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
597     httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
598                     (httpd_callback_sys_t*)rdir );
599     httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
600                     (httpd_callback_sys_t*)rdir );
601     httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
602                     (httpd_callback_sys_t*)rdir );
603     httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
604                     (httpd_callback_sys_t*)rdir );
605
606     return rdir;
607 }
608 void httpd_RedirectDelete( httpd_redirect_t *rdir )
609 {
610     httpd_UrlDelete( rdir->url );
611     free( rdir->psz_dst );
612     free( rdir );
613 }
614
615 /*****************************************************************************
616  * High Level Funtions: httpd_stream_t
617  *****************************************************************************/
618 struct httpd_stream_t
619 {
620     vlc_mutex_t lock;
621     httpd_url_t *url;
622
623     char    *psz_mime;
624
625     /* Header to send as first packet */
626     uint8_t *p_header;
627     int     i_header;
628
629     /* circular buffer */
630     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
631     uint8_t     *p_buffer;          /* buffer */
632     int64_t     i_buffer_pos;       /* absolute position from begining */
633     int64_t     i_buffer_last_pos;  /* a new connection will start with that */
634 };
635
636 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
637                                  httpd_client_t *cl, httpd_message_t *answer,
638                                  httpd_message_t *query )
639 {
640     httpd_stream_t *stream = (httpd_stream_t*)p_sys;
641
642     if( answer == NULL || query == NULL || cl == NULL )
643     {
644         return VLC_SUCCESS;
645     }
646     if( answer->i_body_offset > 0 )
647     {
648         int64_t i_write;
649         int     i_pos;
650
651 #if 0
652         fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
653                  answer->i_body_offset );
654 #endif
655
656         if( answer->i_body_offset >= stream->i_buffer_pos )
657         {
658             /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
659             return VLC_EGENERIC;    /* wait, no data available */
660         }
661         if( answer->i_body_offset + stream->i_buffer_size <
662             stream->i_buffer_pos )
663         {
664             /* this client isn't fast enough */
665             fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
666                      answer->i_body_offset, stream->i_buffer_last_pos );
667             answer->i_body_offset = stream->i_buffer_last_pos;
668         }
669
670         i_pos   = answer->i_body_offset % stream->i_buffer_size;
671         i_write = stream->i_buffer_pos - answer->i_body_offset;
672         if( i_write > 10000 )
673         {
674             i_write = 10000;
675         }
676         else if( i_write <= 0 )
677         {
678             return VLC_EGENERIC;    /* wait, no data available */
679         }
680
681         /* Don't go past the end of the circular buffer */
682         i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
683
684         /* using HTTPD_MSG_ANSWER -> data available */
685         answer->i_proto  = HTTPD_PROTO_HTTP;
686         answer->i_version= 0;
687         answer->i_type   = HTTPD_MSG_ANSWER;
688
689         answer->i_body = i_write;
690         answer->p_body = malloc( i_write );
691         memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
692
693         answer->i_body_offset += i_write;
694
695         return VLC_SUCCESS;
696     }
697     else
698     {
699         answer->i_proto  = HTTPD_PROTO_HTTP;
700         answer->i_version= 0;
701         answer->i_type   = HTTPD_MSG_ANSWER;
702
703         answer->i_status = 200;
704         answer->psz_status = strdup( "OK" );
705
706         if( query->i_type != HTTPD_MSG_HEAD )
707         {
708             httpd_ClientModeStream( cl );
709             vlc_mutex_lock( &stream->lock );
710             /* Send the header */
711             if( stream->i_header > 0 )
712             {
713                 answer->i_body = stream->i_header;
714                 answer->p_body = malloc( stream->i_header );
715                 memcpy( answer->p_body, stream->p_header, stream->i_header );
716             }
717             answer->i_body_offset = stream->i_buffer_last_pos;
718             vlc_mutex_unlock( &stream->lock );
719         }
720         else
721         {
722             httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
723             answer->i_body_offset = 0;
724         }
725
726         if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
727         {
728             vlc_bool_t b_xplaystream = VLC_FALSE;
729             int i;
730
731             httpd_MsgAdd( answer, "Content-type", "%s",
732                           "application/octet-stream" );
733             httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
734             httpd_MsgAdd( answer, "Pragma", "no-cache" );
735             httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
736             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
737
738             /* Check if there is a xPlayStrm=1 */
739             for( i = 0; i < query->i_name; i++ )
740             {
741                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
742                     strstr( query->value[i], "xPlayStrm=1" ) )
743                 {
744                     b_xplaystream = VLC_TRUE;
745                 }
746             }
747
748             if( !b_xplaystream )
749             {
750                 answer->i_body_offset = 0;
751             }
752         }
753         else
754         {
755             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
756         }
757         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
758         return VLC_SUCCESS;
759     }
760 }
761
762 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
763                                  char *psz_url, char *psz_mime,
764                                  char *psz_user, char *psz_password )
765 {
766     httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
767
768     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
769                                             psz_password ) ) == NULL )
770     {
771         free( stream );
772         return NULL;
773     }
774     vlc_mutex_init( host, &stream->lock );
775     if( psz_mime && *psz_mime )
776     {
777         stream->psz_mime = strdup( psz_mime );
778     }
779     else
780     {
781         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
782     }
783     stream->i_header = 0;
784     stream->p_header = NULL;
785     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
786     stream->p_buffer = malloc( stream->i_buffer_size );
787     /* We set to 1 to make life simpler
788      * (this way i_body_offset can never be 0) */
789     stream->i_buffer_pos = 1;
790     stream->i_buffer_last_pos = 1;
791
792     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
793                     (httpd_callback_sys_t*)stream );
794     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
795                     (httpd_callback_sys_t*)stream );
796     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
797                     (httpd_callback_sys_t*)stream );
798
799     return stream;
800 }
801
802 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
803 {
804     vlc_mutex_lock( &stream->lock );
805     if( stream->p_header )
806     {
807         free( stream->p_header );
808         stream->p_header = NULL;
809     }
810     stream->i_header = i_data;
811     if( i_data > 0 )
812     {
813         stream->p_header = malloc( i_data );
814         memcpy( stream->p_header, p_data, i_data );
815     }
816     vlc_mutex_unlock( &stream->lock );
817
818     return VLC_SUCCESS;
819 }
820
821 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
822 {
823     int i_count;
824     int i_pos;
825
826     if( i_data < 0 || p_data == NULL )
827     {
828         return VLC_SUCCESS;
829     }
830     vlc_mutex_lock( &stream->lock );
831
832     /* save this pointer (to be used by new connection) */
833     stream->i_buffer_last_pos = stream->i_buffer_pos;
834
835     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
836     i_count = i_data;
837     while( i_count > 0)
838     {
839         int i_copy;
840
841         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
842
843         /* Ok, we can't go past the end of our buffer */
844         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
845
846         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
847         i_count -= i_copy;
848         p_data  += i_copy;
849     }
850
851     stream->i_buffer_pos += i_data;
852
853     vlc_mutex_unlock( &stream->lock );
854     return VLC_SUCCESS;
855 }
856
857 void httpd_StreamDelete( httpd_stream_t *stream )
858 {
859     httpd_UrlDelete( stream->url );
860     vlc_mutex_destroy( &stream->lock );
861     if( stream->psz_mime ) free( stream->psz_mime );
862     if( stream->p_header ) free( stream->p_header );
863     if( stream->p_buffer ) free( stream->p_buffer );
864     free( stream );
865 }
866
867
868 /*****************************************************************************
869  * Low level
870  *****************************************************************************/
871 static void httpd_HostThread( httpd_host_t * );
872
873 /* create a new host */
874 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
875                              int i_port )
876 {
877     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
878                            );
879 }
880
881 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
882                                 int i_port,
883                                 const char *psz_cert, const char *psz_key,
884                                 const char *psz_ca, const char *psz_crl )
885 {
886     httpd_t      *httpd;
887     httpd_host_t *host;
888     tls_server_t *p_tls;
889     char *psz_host;
890     vlc_value_t  lockval;
891     int i;
892
893     psz_host = strdup( psz_hostname );
894     if( psz_host == NULL )
895     {
896         msg_Err( p_this, "memory error" );
897         return NULL;
898     }
899
900     /* to be sure to avoid multiple creation */
901     var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
902     var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
903     vlc_mutex_lock( lockval.p_address );
904
905     if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
906     {
907         msg_Info( p_this, "creating httpd" );
908         if( ( httpd = vlc_object_create( p_this, VLC_OBJECT_HTTPD ) ) == NULL )
909         {
910             vlc_mutex_unlock( lockval.p_address );
911             free( psz_host );
912             return NULL;
913         }
914
915         httpd->i_host = 0;
916         httpd->host   = NULL;
917
918         vlc_object_yield( httpd );
919         vlc_object_attach( httpd, p_this->p_vlc );
920     }
921
922     /* verify if it already exist */
923     for( i = httpd->i_host - 1; i >= 0; i-- )
924     {
925         host = httpd->host[i];
926
927         /* cannot mix TLS and non-TLS hosts */
928         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
929          || ( host->i_port != i_port )
930          || strcmp( host->psz_hostname, psz_hostname ) )
931             continue;
932
933         /* yep found */
934         host->i_ref++;
935
936         vlc_mutex_unlock( lockval.p_address );
937         return host;
938     }
939
940     host = NULL;
941
942     /* determine TLS configuration */
943     if ( psz_cert != NULL )
944     {
945         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
946         if ( p_tls == NULL )
947         {
948             msg_Err( p_this, "TLS initialization error" );
949             goto error;
950         }
951
952         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
953         {
954             msg_Err( p_this, "TLS CA error" );
955             goto error;
956         }
957
958         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
959         {
960             msg_Err( p_this, "TLS CRL error" );
961             goto error;
962         }
963     }
964     else
965         p_tls = NULL;
966
967     /* create the new host */
968     host = vlc_object_create( p_this, sizeof( httpd_host_t ) );
969     host->httpd = httpd;
970     vlc_mutex_init( httpd, &host->lock );
971     host->i_ref = 1;
972
973     host->fd = net_ListenTCP( p_this, psz_host, i_port );
974     if( host->fd == NULL )
975     {
976         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
977         goto error;
978     }
979        
980     host->i_port = i_port;
981     host->psz_hostname = psz_host;
982
983     host->i_url     = 0;
984     host->url       = NULL;
985     host->i_client  = 0;
986     host->client    = NULL;
987
988     host->p_tls = p_tls;
989
990     /* create the thread */
991     if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
992                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
993     {
994         msg_Err( p_this, "cannot spawn http host thread" );
995         goto error;
996     }
997
998     /* now add it to httpd */
999     TAB_APPEND( httpd->i_host, httpd->host, host );
1000     vlc_mutex_unlock( lockval.p_address );
1001
1002     return host;
1003
1004 error:
1005     free( psz_host );
1006     if( httpd->i_host <= 0 )
1007     {
1008         vlc_object_release( httpd );
1009         vlc_object_detach( httpd );
1010         vlc_object_destroy( httpd );
1011     }
1012     vlc_mutex_unlock( lockval.p_address );
1013
1014     if( host != NULL )
1015     {
1016         net_ListenClose( host->fd );
1017         vlc_mutex_destroy( &host->lock );
1018         vlc_object_destroy( host );
1019     }
1020
1021     if( p_tls != NULL )
1022         tls_ServerDelete( p_tls );
1023
1024     return NULL;
1025 }
1026
1027 /* delete a host */
1028 void httpd_HostDelete( httpd_host_t *host )
1029 {
1030     httpd_t *httpd = host->httpd;
1031     vlc_value_t lockval;
1032     int i;
1033
1034     msg_Dbg( host, "httpd_HostDelete" );
1035
1036     var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1037     vlc_mutex_lock( lockval.p_address );
1038
1039     host->i_ref--;
1040     if( host->i_ref > 0 )
1041     {
1042         /* still used */
1043         vlc_mutex_unlock( lockval.p_address );
1044         msg_Dbg( host, "httpd_HostDelete: host still used" );
1045         return;
1046     }
1047     TAB_REMOVE( httpd->i_host, httpd->host, host );
1048
1049     msg_Dbg( host, "httpd_HostDelete: host removed from http" );
1050
1051     host->b_die = 1;
1052     vlc_thread_join( host );
1053
1054     msg_Dbg( host, "httpd_HostDelete: host thread joined" );
1055
1056     for( i = 0; i < host->i_url; i++ )
1057     {
1058         msg_Err( host, "url still registered:%s", host->url[i]->psz_url );
1059     }
1060     for( i = 0; i < host->i_client; i++ )
1061     {
1062         httpd_client_t *cl = host->client[i];
1063         msg_Warn( host, "client still connected" );
1064         httpd_ClientClean( cl );
1065         TAB_REMOVE( host->i_client, host->client, cl );
1066         free( cl );
1067         i--;
1068         /* TODO */
1069     }
1070
1071     if( host->p_tls != NULL)
1072         tls_ServerDelete( host->p_tls );
1073
1074     net_ListenClose( host->fd );
1075     free( host->psz_hostname );
1076
1077     vlc_mutex_destroy( &host->lock );
1078     vlc_object_destroy( host );
1079
1080     if( httpd->i_host <= 0 )
1081     {
1082         msg_Info( httpd, "httpd doesn't reference any host, deleting" );
1083         vlc_object_release( httpd );
1084         vlc_object_detach( httpd );
1085         vlc_object_destroy( httpd );
1086     }
1087     vlc_mutex_unlock( lockval.p_address );
1088 }
1089
1090 /* register a new url */
1091 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, char *psz_url,
1092                                          char *psz_user, char *psz_password,
1093                                          vlc_bool_t b_check )
1094 {
1095     httpd_url_t *url;
1096     int         i;
1097
1098     vlc_mutex_lock( &host->lock );
1099     if( b_check )
1100     {
1101         for( i = 0; i < host->i_url; i++ )
1102         {
1103             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1104             {
1105                 msg_Warn( host->httpd,
1106                           "cannot add '%s' (url already defined)", psz_url );
1107                 vlc_mutex_unlock( &host->lock );
1108                 return NULL;
1109             }
1110         }
1111     }
1112
1113     url = malloc( sizeof( httpd_url_t ) );
1114     url->host = host;
1115
1116     vlc_mutex_init( host->httpd, &url->lock );
1117     url->psz_url = strdup( psz_url );
1118     url->psz_user = strdup( psz_user ? psz_user : "" );
1119     url->psz_password = strdup( psz_password ? psz_password : "" );
1120     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1121     {
1122         url->catch[i].cb = NULL;
1123         url->catch[i].p_sys = NULL;
1124     }
1125
1126     TAB_APPEND( host->i_url, host->url, url );
1127     vlc_mutex_unlock( &host->lock );
1128
1129     return url;
1130 }
1131
1132 httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
1133                            char *psz_user, char *psz_password )
1134 {
1135     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1136                                 psz_password, VLC_FALSE );
1137 }
1138
1139 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
1140                                  char *psz_user, char *psz_password )
1141 {
1142     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1143                                 psz_password, VLC_TRUE );
1144 }
1145
1146 /* register callback on a url */
1147 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1148                     httpd_callback_sys_t *p_sys )
1149 {
1150     vlc_mutex_lock( &url->lock );
1151     url->catch[i_msg].cb   = cb;
1152     url->catch[i_msg].p_sys= p_sys;
1153     vlc_mutex_unlock( &url->lock );
1154
1155     return VLC_SUCCESS;
1156 }
1157
1158
1159 /* delete an url */
1160 void httpd_UrlDelete( httpd_url_t *url )
1161 {
1162     httpd_host_t *host = url->host;
1163     int          i;
1164
1165     vlc_mutex_lock( &host->lock );
1166     TAB_REMOVE( host->i_url, host->url, url );
1167
1168     vlc_mutex_destroy( &url->lock );
1169     free( url->psz_url );
1170     free( url->psz_user );
1171     free( url->psz_password );
1172
1173     for( i = 0; i < host->i_client; i++ )
1174     {
1175         httpd_client_t *client = host->client[i];
1176
1177         if( client->url == url )
1178         {
1179             /* TODO complete it */
1180             msg_Warn( host, "force closing connections" );
1181             httpd_ClientClean( client );
1182             TAB_REMOVE( host->i_client, host->client, client );
1183             free( client );
1184             i--;
1185         }
1186     }
1187     free( url );
1188     vlc_mutex_unlock( &host->lock );
1189 }
1190
1191 void httpd_MsgInit( httpd_message_t *msg )
1192 {
1193     msg->cl         = NULL;
1194     msg->i_type     = HTTPD_MSG_NONE;
1195     msg->i_proto    = HTTPD_PROTO_NONE;
1196     msg->i_version  = -1;
1197
1198     msg->i_status   = 0;
1199     msg->psz_status = NULL;
1200
1201     msg->psz_url = NULL;
1202     msg->psz_args = NULL;
1203
1204     msg->i_channel = -1;
1205
1206     msg->i_name = 0;
1207     msg->name   = NULL;
1208     msg->i_value= 0;
1209     msg->value  = NULL;
1210
1211     msg->i_body_offset = 0;
1212     msg->i_body        = 0;
1213     msg->p_body        = 0;
1214 }
1215
1216 void httpd_MsgClean( httpd_message_t *msg )
1217 {
1218     int i;
1219
1220     if( msg->psz_status )
1221     {
1222         free( msg->psz_status );
1223     }
1224     if( msg->psz_url )
1225     {
1226         free( msg->psz_url );
1227     }
1228     if( msg->psz_args )
1229     {
1230         free( msg->psz_args );
1231     }
1232     for( i = 0; i < msg->i_name; i++ )
1233     {
1234         free( msg->name[i] );
1235         free( msg->value[i] );
1236     }
1237     if( msg->name )
1238     {
1239         free( msg->name );
1240     }
1241     if( msg->value )
1242     {
1243         free( msg->value );
1244     }
1245     if( msg->p_body )
1246     {
1247         free( msg->p_body );
1248     }
1249     httpd_MsgInit( msg );
1250 }
1251
1252 char *httpd_MsgGet( httpd_message_t *msg, char *name )
1253 {
1254     int i;
1255
1256     for( i = 0; i < msg->i_name; i++ )
1257     {
1258         if( !strcasecmp( msg->name[i], name ))
1259         {
1260             return msg->value[i];
1261         }
1262     }
1263     return "";
1264 }
1265 void httpd_MsgAdd( httpd_message_t *msg, char *name, char *psz_value, ... )
1266 {
1267     va_list args;
1268     char *value = NULL;
1269
1270     va_start( args, psz_value );
1271 #if defined(HAVE_VASPRINTF) && !defined(SYS_DARWIN) && !defined(SYS_BEOS)
1272     vasprintf( &value, psz_value, args );
1273 #else
1274     {
1275         int i_size = strlen( psz_value ) + 4096;    /* FIXME stupid system */
1276         value = calloc( i_size, sizeof( char ) );
1277         vsnprintf( value, i_size, psz_value, args );
1278         value[i_size - 1] = 0;
1279     }
1280 #endif
1281     va_end( args );
1282
1283     name = strdup( name );
1284
1285     TAB_APPEND( msg->i_name,  msg->name,  name );
1286     TAB_APPEND( msg->i_value, msg->value, value );
1287 }
1288
1289 static void httpd_ClientInit( httpd_client_t *cl )
1290 {
1291     cl->i_state = HTTPD_CLIENT_RECEIVING;
1292     cl->i_activity_date = mdate();
1293     cl->i_activity_timeout = I64C(10000000);
1294     cl->i_buffer_size = 10000;
1295     cl->i_buffer = 0;
1296     cl->p_buffer = malloc( cl->i_buffer_size );
1297     cl->i_mode   = HTTPD_CLIENT_FILE;
1298     cl->b_read_waiting = VLC_FALSE;
1299
1300     httpd_MsgInit( &cl->query );
1301     httpd_MsgInit( &cl->answer );
1302 }
1303
1304 void httpd_ClientModeStream( httpd_client_t *cl )
1305 {
1306     cl->i_mode   = HTTPD_CLIENT_STREAM;
1307 }
1308
1309 void httpd_ClientModeBidir( httpd_client_t *cl )
1310 {
1311     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1312 }
1313
1314 /*
1315  * FIXME: use vlc_getnameinfo
1316  */
1317 char* httpd_ClientIP( httpd_client_t *cl )
1318 {
1319 #ifdef HAVE_GETNAMEINFO
1320     char sz_ip[INET6_ADDRSTRLEN + 2];
1321     int i;
1322
1323     if( (cl->sock.ss_family == AF_INET6) &&
1324         IN6_IS_ADDR_V4MAPPED( &((const struct sockaddr_in6 *)
1325                               &cl->sock)->sin6_addr) )
1326     {
1327         /* If client is using IPv4 but server is using IPv6 */
1328         struct sockaddr_in a;
1329         
1330         memset( &a, 0, sizeof( a ) );
1331         a.sin_family = AF_INET;
1332         a.sin_port = ((const struct sockaddr_in6 *)&cl->sock)->sin6_port;
1333         a.sin_addr.s_addr = ((const uint32_t *)&((const struct sockaddr_in6 *)
1334                             &cl->sock)->sin6_addr)[3];
1335         i = getnameinfo( (const struct sockaddr *)&a, sizeof( a ),
1336                          &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST );
1337     }
1338     else
1339         i = getnameinfo( (const struct sockaddr *)&cl->sock, cl->i_sock_size,
1340                          &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0,
1341                          NI_NUMERICHOST );
1342
1343     if( i != 0 )
1344         /* FIXME: msg_Err */
1345         return NULL;
1346         
1347     if( strchr( &sz_ip[1], ':' ) != NULL )
1348     {
1349         *sz_ip = '[';
1350         i = strlen( sz_ip );
1351         sz_ip[i++] = ']';
1352         sz_ip[i] = '\0';
1353        
1354         return strdup( sz_ip );
1355     }
1356     
1357     return strdup( &sz_ip[1] );
1358
1359 #else
1360     /* FIXME not thread safe */
1361     return strdup( inet_ntoa( ((const struct sockaddr_in *)&cl->sock)->sin_addr ) );
1362 #endif
1363 }
1364
1365 static void httpd_ClientClean( httpd_client_t *cl )
1366 {
1367     if( cl->fd >= 0 )
1368     {
1369         if( cl->p_tls != NULL )
1370             tls_ServerSessionClose( cl->p_tls );
1371         net_Close( cl->fd );
1372         cl->fd = -1;
1373     }
1374
1375     httpd_MsgClean( &cl->answer );
1376     httpd_MsgClean( &cl->query );
1377
1378     if( cl->p_buffer )
1379     {
1380         free( cl->p_buffer );
1381         cl->p_buffer = NULL;
1382     }
1383 }
1384
1385 static httpd_client_t *httpd_ClientNew( int fd, struct sockaddr_storage *sock,
1386                                         int i_sock_size,
1387                                         tls_session_t *p_tls )
1388 {
1389     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1390     cl->i_ref   = 0;
1391     cl->fd      = fd;
1392     memcpy( &cl->sock, sock, sizeof( cl->sock ) );
1393     cl->i_sock_size = i_sock_size;
1394     cl->url     = NULL;
1395     cl->p_tls = p_tls;
1396
1397     httpd_ClientInit( cl );
1398
1399     return cl;
1400 }
1401
1402
1403 static int httpd_NetRecv( httpd_client_t *cl, char *p, int i_len )
1404 {
1405     tls_session_t *p_tls;
1406     
1407     p_tls = cl->p_tls;
1408     if( p_tls != NULL)
1409         return tls_Recv( p_tls, p, i_len );
1410
1411     return recv( cl->fd, p, i_len, 0 );
1412 }
1413
1414
1415 static int httpd_NetSend( httpd_client_t *cl, const char *p, int i_len )
1416 {
1417     tls_session_t *p_tls;
1418
1419     p_tls = cl->p_tls;
1420     if( p_tls != NULL)
1421         return tls_Send( p_tls, p, i_len );
1422
1423     return send( cl->fd, p, i_len, 0 );
1424 }
1425
1426
1427 static void httpd_ClientRecv( httpd_client_t *cl )
1428 {
1429     int i_len;
1430
1431     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1432     {
1433         /* enought to see if it's rtp over rtsp or RTSP/HTTP */
1434         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1435                                4 - cl->i_buffer );
1436         if( i_len > 0 )
1437         {
1438             cl->i_buffer += i_len;
1439         }
1440
1441         if( cl->i_buffer >= 4 )
1442         {
1443             /*fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );*/
1444             /* detect type */
1445             if( cl->p_buffer[0] == '$' )
1446             {
1447                 /* RTSP (rtp over rtsp) */
1448                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1449                 cl->query.i_type  = HTTPD_MSG_CHANNEL;
1450                 cl->query.i_channel = cl->p_buffer[1];
1451                 cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1452                 cl->query.p_body  = malloc( cl->query.i_body );
1453
1454                 cl->i_buffer      = 0;
1455             }
1456             else if( !strncmp( cl->p_buffer, "HTTP", 4 ) )
1457             {
1458                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1459                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1460             }
1461             else if( !strncmp( cl->p_buffer, "RTSP", 4 ) )
1462             {
1463                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1464                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1465             }
1466             else if( !strncmp( cl->p_buffer, "GET", 3 ) ||
1467                      !strncmp( cl->p_buffer, "HEAD", 4 ) ||
1468                      !strncmp( cl->p_buffer, "POST", 4 ) )
1469             {
1470                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1471                 cl->query.i_type  = HTTPD_MSG_NONE;
1472             }
1473             else
1474             {
1475                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1476                 cl->query.i_type  = HTTPD_MSG_NONE;
1477             }
1478         }
1479     }
1480     else if( cl->query.i_body > 0 )
1481     {
1482         /* we are reading the body of a request or a channel */
1483         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1484                                cl->query.i_body - cl->i_buffer );
1485         if( i_len > 0 )
1486         {
1487             cl->i_buffer += i_len;
1488         }
1489         if( cl->i_buffer >= cl->query.i_body )
1490         {
1491             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1492         }
1493     }
1494     else
1495     {
1496         /* we are reading a header -> char by char */
1497         for( ;; )
1498         {
1499             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1500             if( i_len <= 0 )
1501             {
1502                 break;
1503             }
1504             cl->i_buffer++;
1505
1506             if( cl->i_buffer + 1 >= cl->i_buffer_size )
1507             {
1508                 cl->i_buffer_size += 1024;
1509                 cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
1510             }
1511             if( ( cl->i_buffer >= 2 && !strncmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1512                 ( cl->i_buffer >= 4 && !strncmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1513             {
1514                 char *p;
1515
1516                 /* we have finished the header so parse it and set i_body */
1517                 cl->p_buffer[cl->i_buffer] = '\0';
1518
1519                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1520                 {
1521                     cl->query.i_status =
1522                         strtol( &cl->p_buffer[strlen( "HTTP/1.x" )], &p, 0 );
1523                     while( *p == ' ' )
1524                     {
1525                         p++;
1526                     }
1527                     cl->query.psz_status = strdup( p );
1528                 }
1529                 else
1530                 {
1531                     static const struct
1532                     {
1533                         char *name;
1534                         int  i_type;
1535                         int  i_proto;
1536                     }
1537                     msg_type[] =
1538                     {
1539                         { "GET",        HTTPD_MSG_GET,  HTTPD_PROTO_HTTP },
1540                         { "HEAD",       HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1541                         { "POST",       HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1542
1543                         { "OPTIONS",    HTTPD_MSG_OPTIONS,  HTTPD_PROTO_RTSP },
1544                         { "DESCRIBE",   HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1545                         { "SETUP",      HTTPD_MSG_SETUP,    HTTPD_PROTO_RTSP },
1546                         { "PLAY",       HTTPD_MSG_PLAY,     HTTPD_PROTO_RTSP },
1547                         { "PAUSE",      HTTPD_MSG_PAUSE,    HTTPD_PROTO_RTSP },
1548                         { "TEARDOWN",   HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1549
1550                         { NULL,         HTTPD_MSG_NONE,     HTTPD_PROTO_NONE }
1551                     };
1552                     int  i;
1553
1554                     p = NULL;
1555                     cl->query.i_type = HTTPD_MSG_NONE;
1556
1557                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1558
1559                     for( i = 0; msg_type[i].name != NULL; i++ )
1560                     {
1561                         if( !strncmp( cl->p_buffer, msg_type[i].name,
1562                                       strlen( msg_type[i].name ) ) )
1563                         {
1564                             p = &cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1565                             cl->query.i_type = msg_type[i].i_type;
1566                             if( cl->query.i_proto != msg_type[i].i_proto )
1567                             {
1568                                 p = NULL;
1569                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1570                                 cl->query.i_type = HTTPD_MSG_NONE;
1571                             }
1572                             break;
1573                         }
1574                     }
1575                     if( p == NULL )
1576                     {
1577                         if( strstr( cl->p_buffer, "HTTP/1." ) )
1578                         {
1579                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1580                         }
1581                         else if( strstr( cl->p_buffer, "RTSP/1." ) )
1582                         {
1583                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1584                         }
1585                     }
1586                     else
1587                     {
1588                         char *p2;
1589                         char *p3;
1590
1591                         while( *p == ' ' )
1592                         {
1593                             p++;
1594                         }
1595                         p2 = strchr( p, ' ' );
1596                         if( p2 )
1597                         {
1598                             *p2++ = '\0';
1599                         }
1600                         if( !strncasecmp( p, "rtsp:", 5 ) )
1601                         {
1602                             /* for rtsp url, you have rtsp://localhost:port/path */
1603                             p += 5;
1604                             while( *p == '/' ) p++;
1605                             while( *p && *p != '/' ) p++;
1606                         }
1607                         cl->query.psz_url = strdup( p );
1608                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1609                         {
1610                             *p3++ = '\0';
1611                             cl->query.psz_args = strdup( p3 );
1612                         }
1613                         if( p2 )
1614                         {
1615                             while( *p2 == ' ' )
1616                             {
1617                                 p2++;
1618                             }
1619                             if( !strncasecmp( p2, "HTTP/1.", 7 ) )
1620                             {
1621                                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1622                                 cl->query.i_version = atoi( p2+7 );
1623                             }
1624                             else if( !strncasecmp( p2, "RTSP/1.", 7 ) )
1625                             {
1626                                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1627                                 cl->query.i_version = atoi( p2+7 );
1628                             }
1629                         }
1630                         p = p2;
1631                     }
1632                 }
1633                 if( p )
1634                 {
1635                     p = strchr( p, '\n' );
1636                 }
1637                 if( p )
1638                 {
1639                     while( *p == '\n' || *p == '\r' )
1640                     {
1641                         p++;
1642                     }
1643                     while( p && *p != '\0' )
1644                     {
1645                         char *line = p;
1646                         char *eol = p = strchr( p, '\n' );
1647                         char *colon;
1648
1649                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1650                         {
1651                             *eol-- = '\0';
1652                         }
1653
1654                         if( ( colon = strchr( line, ':' ) ) )
1655                         {
1656                             char *name;
1657                             char *value;
1658
1659                             *colon++ = '\0';
1660                             while( *colon == ' ' )
1661                             {
1662                                 colon++;
1663                             }
1664                             name = strdup( line );
1665                             value = strdup( colon );
1666
1667                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1668                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1669
1670                             if( !strcasecmp( name, "Content-Length" ) )
1671                             {
1672                                 cl->query.i_body = atol( value );
1673                             }
1674                         }
1675
1676                         if( p )
1677                         {
1678                             p++;
1679                             while( *p == '\n' || *p == '\r' )
1680                             {
1681                                 p++;
1682                             }
1683                         }
1684                     }
1685                 }
1686                 if( cl->query.i_body > 0 )
1687                 {
1688                     /* TODO Mhh, handle the case client will only send a request and close the connection
1689                      * to mark and of body (probably only RTSP) */
1690                     cl->query.p_body = malloc( cl->query.i_body );
1691                     cl->i_buffer = 0;
1692                 }
1693                 else
1694                 {
1695                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1696                 }
1697             }
1698         }
1699     }
1700
1701     /* check if the client is to be set to dead */
1702 #if defined( WIN32 ) || defined( UNDER_CE )
1703     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1704 #else
1705     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1706 #endif
1707     {
1708         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1709         {
1710             /* connection closed -> end of data */
1711             if( cl->query.i_body > 0 )
1712             {
1713                 cl->query.i_body = cl->i_buffer;
1714             }
1715             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1716         }
1717         else
1718         {
1719             cl->i_state = HTTPD_CLIENT_DEAD;
1720         }
1721     }
1722     cl->i_activity_date = mdate();
1723
1724     /* XXX: for QT I have to disable timeout. Try to find why */
1725     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1726         cl->i_activity_timeout = 0;
1727
1728     /* Debugging only */
1729     /*if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1730     {
1731         int i;
1732
1733         fprintf( stderr, "received new request\n" );
1734         fprintf( stderr, "  - proto=%s\n",
1735                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1736         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1737         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1738         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1739         {
1740             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1741                      cl->query.psz_status );
1742         }
1743         else if( cl->query.i_type != HTTPD_MSG_NONE )
1744         {
1745             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1746         }
1747         for( i = 0; i < cl->query.i_name; i++ )
1748         {
1749             fprintf( stderr, "  - option name='%s' value='%s'\n",
1750                      cl->query.name[i], cl->query.value[i] );
1751         }
1752     }*/
1753 }
1754
1755
1756 static void httpd_ClientSend( httpd_client_t *cl )
1757 {
1758     int i;
1759     int i_len;
1760
1761     if( cl->i_buffer < 0 )
1762     {
1763         /* We need to create the header */
1764         int i_size = 0;
1765         char *p;
1766
1767         i_size = strlen( "HTTP/1.") + 10 + 10 +
1768                  strlen( cl->answer.psz_status ? cl->answer.psz_status : "" ) + 5;
1769         for( i = 0; i < cl->answer.i_name; i++ )
1770         {
1771             i_size += strlen( cl->answer.name[i] ) + 2 +
1772                       strlen( cl->answer.value[i] ) + 2;
1773         }
1774
1775         if( cl->i_buffer_size < i_size )
1776         {
1777             cl->i_buffer_size = i_size;
1778             free( cl->p_buffer );
1779             cl->p_buffer = malloc( i_size );
1780         }
1781         p = cl->p_buffer;
1782
1783         p += sprintf( p, "%s/1.%d %d %s\r\n",
1784                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP" : "RTSP",
1785                       cl->answer.i_version,
1786                       cl->answer.i_status, cl->answer.psz_status );
1787         for( i = 0; i < cl->answer.i_name; i++ )
1788         {
1789             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1790                           cl->answer.value[i] );
1791         }
1792         p += sprintf( p, "\r\n" );
1793
1794         cl->i_buffer = 0;
1795         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1796
1797         /*fprintf( stderr, "sending answer\n" );
1798         fprintf( stderr, "%s",  cl->p_buffer );*/
1799     }
1800
1801     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1802                            cl->i_buffer_size - cl->i_buffer );
1803     if( i_len > 0 )
1804     {
1805         cl->i_activity_date = mdate();
1806         cl->i_buffer += i_len;
1807
1808         if( cl->i_buffer >= cl->i_buffer_size )
1809         {
1810             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1811                 !cl->b_read_waiting )
1812             {
1813                 /* catch more body data */
1814                 int     i_msg = cl->query.i_type;
1815                 int64_t i_offset = cl->answer.i_body_offset;
1816
1817                 httpd_MsgClean( &cl->answer );
1818                 cl->answer.i_body_offset = i_offset;
1819
1820                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1821                                           &cl->answer, &cl->query );
1822             }
1823
1824             if( cl->answer.i_body > 0 )
1825             {
1826                 /* send the body data */
1827                 free( cl->p_buffer );
1828                 cl->p_buffer = cl->answer.p_body;
1829                 cl->i_buffer_size = cl->answer.i_body;
1830                 cl->i_buffer = 0;
1831
1832                 cl->answer.i_body = 0;
1833                 cl->answer.p_body = NULL;
1834             }
1835             else
1836             {
1837                 /* send finished */
1838                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1839             }
1840         }
1841     }
1842     else
1843     {
1844 #if defined( WIN32 ) || defined( UNDER_CE )
1845         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1846 #else
1847         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1848 #endif
1849         {
1850             /* error */
1851             cl->i_state = HTTPD_CLIENT_DEAD;
1852         }
1853     }
1854 }
1855
1856 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1857 {
1858     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1859     {
1860         case 0:
1861             cl->i_state = HTTPD_CLIENT_RECEIVING;
1862             break;
1863
1864         case -1:
1865             cl->i_state = HTTPD_CLIENT_DEAD;
1866             cl->p_tls = NULL;
1867             break;
1868
1869         case 2:
1870             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1871     }
1872 }
1873
1874 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1875 {
1876     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1877     {
1878         case 0:
1879             cl->i_state = HTTPD_CLIENT_RECEIVING;
1880             break;
1881
1882         case -1:
1883             cl->i_state = HTTPD_CLIENT_DEAD;
1884             cl->p_tls = NULL;
1885             break;
1886
1887         case 1:
1888             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
1889             break;
1890     }
1891 }
1892
1893 static void httpd_HostThread( httpd_host_t *host )
1894 {
1895     tls_session_t *p_tls = NULL;
1896
1897     while( !host->b_die )
1898     {
1899         struct timeval  timeout;
1900         fd_set          fds_read;
1901         fd_set          fds_write;
1902         /* FIXME: (too) many int variables */
1903         int             fd, i_fd;
1904         int             i_handle_max = 0;
1905         int             i_ret;
1906         int             i_client;
1907         int             b_low_delay = 0;
1908
1909         if( host->i_url <= 0 )
1910         {
1911             /* 0.2s */
1912             msleep( 200000 );
1913             continue;
1914         }
1915
1916         /* built a set of handle to select */
1917         FD_ZERO( &fds_read );
1918         FD_ZERO( &fds_write );
1919
1920         i_handle_max = -1;
1921
1922         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
1923         {
1924             FD_SET( fd, &fds_read );
1925             if( fd > i_handle_max )
1926                 i_handle_max = fd;
1927         }
1928
1929         /* prepare a new TLS session */
1930         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
1931             p_tls = tls_ServerSessionPrepare( host->p_tls );
1932
1933         /* add all socket that should be read/write and close dead connection */
1934         vlc_mutex_lock( &host->lock );
1935         for( i_client = 0; i_client < host->i_client; i_client++ )
1936         {
1937             httpd_client_t *cl = host->client[i_client];
1938
1939             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1940                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1941                   ( cl->i_activity_timeout > 0 &&
1942                     cl->i_activity_date+cl->i_activity_timeout < mdate()) ) ) )
1943             {
1944                 char *ip;
1945
1946                 // FIXME: it sucks to allocate memory on the stack for debug
1947                 ip = httpd_ClientIP( cl );
1948                 msg_Dbg( host, "connection closed(%s)",
1949                          (ip != NULL) ? ip : "unknown" );
1950                 free( ip );
1951
1952                 httpd_ClientClean( cl );
1953                 TAB_REMOVE( host->i_client, host->client, cl );
1954                 free( cl );
1955                 i_client--;
1956                 continue;
1957             }
1958             else if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
1959                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
1960             {
1961                 FD_SET( cl->fd, &fds_read );
1962                 i_handle_max = __MAX( i_handle_max, cl->fd );
1963             }
1964             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
1965                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
1966             {
1967                 FD_SET( cl->fd, &fds_write );
1968                 i_handle_max = __MAX( i_handle_max, cl->fd );
1969             }
1970             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1971             {
1972                 httpd_message_t *answer = &cl->answer;
1973                 httpd_message_t *query  = &cl->query;
1974                 int i_msg = query->i_type;
1975
1976                 httpd_MsgInit( answer );
1977
1978                 /* Handle what we received */
1979                 if( cl->i_mode != HTTPD_CLIENT_BIDIR &&
1980                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
1981                 {
1982                     /* we can only receive request from client when not
1983                      * in BIDIR mode */
1984                     cl->url     = NULL;
1985                     cl->i_state = HTTPD_CLIENT_DEAD;
1986                 }
1987                 else if( i_msg == HTTPD_MSG_ANSWER )
1988                 {
1989                     /* We are in BIDIR mode, trigger the callback and then
1990                      * check for new data */
1991                     if( cl->url && cl->url->catch[i_msg].cb )
1992                     {
1993                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
1994                                                   cl, NULL, query );
1995                     }
1996                     cl->i_state = HTTPD_CLIENT_WAITING;
1997                 }
1998                 else if( i_msg == HTTPD_MSG_CHANNEL )
1999                 {
2000                     /* We are in BIDIR mode, trigger the callback and then
2001                      * check for new data */
2002                     if( cl->url && cl->url->catch[i_msg].cb )
2003                     {
2004                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2005                                                   cl, NULL, query );
2006                     }
2007                     cl->i_state = HTTPD_CLIENT_WAITING;
2008                 }
2009                 else if( i_msg == HTTPD_MSG_OPTIONS )
2010                 {
2011                     int i_cseq;
2012
2013                     /* unimplemented */
2014                     answer->i_proto  = query->i_proto ;
2015                     answer->i_type   = HTTPD_MSG_ANSWER;
2016                     answer->i_version= 0;
2017                     answer->i_status = 200;
2018                     answer->psz_status = strdup( "Ok" );
2019
2020                     answer->i_body = 0;
2021                     answer->p_body = NULL;
2022
2023                     i_cseq = atoi( httpd_MsgGet( query, "Cseq" ) );
2024                     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
2025                     httpd_MsgAdd( answer, "Server", "VLC Server" );
2026                     httpd_MsgAdd( answer, "Public", "DESCRIBE, SETUP, "
2027                                  "TEARDOWN, PLAY, PAUSE" );
2028                     httpd_MsgAdd( answer, "Content-Length", "%d",
2029                                   answer->i_body );
2030
2031                     cl->i_buffer = -1;  /* Force the creation of the answer in
2032                                          * httpd_ClientSend */
2033                     cl->i_state = HTTPD_CLIENT_SENDING;
2034                 }
2035                 else if( i_msg == HTTPD_MSG_NONE )
2036                 {
2037                     if( query->i_proto == HTTPD_PROTO_NONE )
2038                     {
2039                         cl->url = NULL;
2040                         cl->i_state = HTTPD_CLIENT_DEAD;
2041                     }
2042                     else
2043                     {
2044                         uint8_t *p;
2045
2046                         /* unimplemented */
2047                         answer->i_proto  = query->i_proto ;
2048                         answer->i_type   = HTTPD_MSG_ANSWER;
2049                         answer->i_version= 0;
2050                         answer->i_status = 501;
2051                         answer->psz_status = strdup( "Unimplemented" );
2052
2053                         p = answer->p_body = malloc( 1000 );
2054
2055                         p += sprintf( p, "<html>\n" );
2056                         p += sprintf( p, "<head>\n" );
2057                         p += sprintf( p, "<title>Error 501</title>\n" );
2058                         p += sprintf( p, "</head>\n" );
2059                         p += sprintf( p, "<body>\n" );
2060                         p += sprintf( p, "<h1><center> 501 Unimplemented</center></h1>\n" );
2061                         p += sprintf( p, "<hr />\n" );
2062                         p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2063                         p += sprintf( p, "</body>\n" );
2064                         p += sprintf( p, "</html>\n" );
2065
2066                         answer->i_body = p - answer->p_body;
2067                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2068
2069                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2070                         cl->i_state = HTTPD_CLIENT_SENDING;
2071                     }
2072                 }
2073                 else
2074                 {
2075                     vlc_bool_t b_auth_failed = VLC_FALSE;
2076                     int i;
2077
2078                     /* Search the url and trigger callbacks */
2079                     for( i = 0; i < host->i_url; i++ )
2080                     {
2081                         httpd_url_t *url = host->url[i];
2082
2083                         if( !strcmp( url->psz_url, query->psz_url ) )
2084                         {
2085                             if( url->catch[i_msg].cb )
2086                             {
2087                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2088                                 {
2089                                     /* create the headers */
2090                                     char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2091                                     char *auth;
2092                                     char *id;
2093
2094                                     asprintf( &id, "%s:%s", url->psz_user, url->psz_password );
2095                                     auth = malloc( strlen(b64) + 1 );
2096
2097                                     if( !strncasecmp( b64, "BASIC", 5 ) )
2098                                     {
2099                                         b64 += 5;
2100                                         while( *b64 == ' ' )
2101                                         {
2102                                             b64++;
2103                                         }
2104                                         b64_decode( auth, b64 );
2105                                     }
2106                                     else
2107                                     {
2108                                         strcpy( auth, "" );
2109                                     }
2110                                     if( strcmp( id, auth ) )
2111                                     {
2112                                         httpd_MsgAdd( answer, "WWW-Authenticate", "Basic realm=\"%s\"", url->psz_user );
2113                                         /* We fail for all url */
2114                                         b_auth_failed = VLC_TRUE;
2115                                         free( id );
2116                                         free( auth );
2117                                         break;
2118                                     }
2119
2120                                     free( id );
2121                                     free( auth );
2122                                 }
2123
2124                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2125                                 {
2126                                     /* only one url can answer */
2127                                     answer = NULL;
2128                                     if( cl->url == NULL )
2129                                     {
2130                                         cl->url = url;
2131                                     }
2132                                 }
2133                             }
2134                         }
2135                     }
2136                     if( answer )
2137                     {
2138                         uint8_t *p;
2139
2140                         answer->i_proto  = query->i_proto;
2141                         answer->i_type   = HTTPD_MSG_ANSWER;
2142                         answer->i_version= 0;
2143                         p = answer->p_body = malloc( 1000 + strlen(query->psz_url) );
2144
2145                         if( b_auth_failed )
2146                         {
2147                             answer->i_status = 401;
2148                             answer->psz_status = strdup( "Authorization Required" );
2149
2150                             p += sprintf( p, "<html>\n" );
2151                             p += sprintf( p, "<head>\n" );
2152                             p += sprintf( p, "<title>Error 401</title>\n" );
2153                             p += sprintf( p, "</head>\n" );
2154                             p += sprintf( p, "<body>\n" );
2155                             p += sprintf( p, "<h1><center> 401 Authorization Required (%s)</center></h1>\n", query->psz_url );
2156                             p += sprintf( p, "<hr />\n" );
2157                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2158                             p += sprintf( p, "</body>\n" );
2159                             p += sprintf( p, "</html>\n" );
2160                         }
2161                         else
2162                         {
2163                             /* no url registered */
2164                             answer->i_status = 404;
2165                             answer->psz_status = strdup( "Not found" );
2166
2167                             p += sprintf( p, "<html>\n" );
2168                             p += sprintf( p, "<head>\n" );
2169                             p += sprintf( p, "<title>Error 404</title>\n" );
2170                             p += sprintf( p, "</head>\n" );
2171                             p += sprintf( p, "<body>\n" );
2172                             p += sprintf( p, "<h1><center> 404 Resource not found(%s)</center></h1>\n", query->psz_url );
2173                             p += sprintf( p, "<hr />\n" );
2174                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2175                             p += sprintf( p, "</body>\n" );
2176                             p += sprintf( p, "</html>\n" );
2177                         }
2178
2179                         answer->i_body = p - answer->p_body;
2180                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2181                     }
2182                     cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2183                     cl->i_state = HTTPD_CLIENT_SENDING;
2184                 }
2185             }
2186             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2187             {
2188                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2189                 {
2190                     cl->url = NULL;
2191                     if( ( cl->query.i_proto == HTTPD_PROTO_HTTP &&
2192                           ( ( cl->answer.i_version == 0 && !strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Keep-Alive" ) ) ||
2193                             ( cl->answer.i_version == 1 &&  strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) ) ) ||
2194                         ( cl->query.i_proto == HTTPD_PROTO_RTSP &&
2195                           strcasecmp( httpd_MsgGet( &cl->query, "Connection" ), "Close" ) &&
2196                           strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) )
2197                     {
2198                         httpd_MsgClean( &cl->query );
2199                         httpd_MsgInit( &cl->query );
2200
2201                         cl->i_buffer = 0;
2202                         cl->i_buffer_size = 1000;
2203                         free( cl->p_buffer );
2204                         cl->p_buffer = malloc( cl->i_buffer_size );
2205                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2206                     }
2207                     else
2208                     {
2209                         cl->i_state = HTTPD_CLIENT_DEAD;
2210                     }
2211                     httpd_MsgClean( &cl->answer );
2212                 }
2213                 else if( cl->b_read_waiting )
2214                 {
2215                     /* we have a message waiting for us to read it */
2216                     httpd_MsgClean( &cl->answer );
2217                     httpd_MsgClean( &cl->query );
2218
2219                     cl->i_buffer = 0;
2220                     cl->i_buffer_size = 1000;
2221                     free( cl->p_buffer );
2222                     cl->p_buffer = malloc( cl->i_buffer_size );
2223                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2224                     cl->b_read_waiting = VLC_FALSE;
2225                 }
2226                 else
2227                 {
2228                     int64_t i_offset = cl->answer.i_body_offset;
2229                     httpd_MsgClean( &cl->answer );
2230
2231                     cl->answer.i_body_offset = i_offset;
2232                     free( cl->p_buffer );
2233                     cl->p_buffer = NULL;
2234                     cl->i_buffer = 0;
2235                     cl->i_buffer_size = 0;
2236
2237                     cl->i_state = HTTPD_CLIENT_WAITING;
2238                 }
2239             }
2240             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2241             {
2242                 int64_t i_offset = cl->answer.i_body_offset;
2243                 int     i_msg = cl->query.i_type;
2244
2245                 httpd_MsgInit( &cl->answer );
2246                 cl->answer.i_body_offset = i_offset;
2247
2248                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2249                                           &cl->answer, &cl->query );
2250                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2251                 {
2252                     /* we have new data, so reenter send mode */
2253                     cl->i_buffer      = 0;
2254                     cl->p_buffer      = cl->answer.p_body;
2255                     cl->i_buffer_size = cl->answer.i_body;
2256                     cl->answer.p_body = NULL;
2257                     cl->answer.i_body = 0;
2258                     cl->i_state = HTTPD_CLIENT_SENDING;
2259                 }
2260                 else
2261                 {
2262                     /* we shouldn't wait too long */
2263                     b_low_delay = VLC_TRUE;
2264                 }
2265             }
2266
2267             /* Special for BIDIR mode we also check reading */
2268             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2269                 cl->i_state == HTTPD_CLIENT_SENDING )
2270             {
2271                 FD_SET( cl->fd, &fds_read );
2272                 i_handle_max = __MAX( i_handle_max, cl->fd );
2273             }
2274         }
2275         vlc_mutex_unlock( &host->lock );
2276
2277         /* we will wait 100ms or 20ms (not too big 'cause HTTPD_CLIENT_WAITING) */
2278         timeout.tv_sec = 0;
2279         timeout.tv_usec = b_low_delay ? 20000 : 100000;
2280
2281         i_ret = select( i_handle_max + 1,
2282                         &fds_read, &fds_write, NULL, &timeout );
2283
2284         if( i_ret == -1 && errno != EINTR )
2285         {
2286             msg_Warn( host, "cannot select sockets" );
2287             msleep( 1000 );
2288             continue;
2289         }
2290         else if( i_ret <= 0 )
2291         {
2292             continue;
2293         }
2294
2295         /* accept new connections */
2296         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
2297         {
2298             if( FD_ISSET( fd, &fds_read ) )
2299             {
2300                 int     i_sock_size = sizeof( struct sockaddr_storage );
2301                 struct  sockaddr_storage sock;
2302     
2303                 fd = accept( fd, (struct sockaddr *)&sock, &i_sock_size );
2304                 if( fd >= 0 )
2305                 {
2306                     int i_state = 0;
2307     
2308                     /* set this new socket non-block */
2309     #if defined( WIN32 ) || defined( UNDER_CE )
2310                     {
2311                         unsigned long i_dummy = 1;
2312                         ioctlsocket( fd, FIONBIO, &i_dummy );
2313                     }
2314     #else
2315                     fcntl( fd, F_SETFL, O_NONBLOCK );
2316     #endif
2317     
2318                     if( p_tls != NULL)
2319                     {
2320                         switch ( tls_ServerSessionHandshake( p_tls, fd ) )
2321                         {
2322                             case -1:
2323                                 msg_Err( host, "Rejecting TLS connection" );
2324                                 net_Close( fd );
2325                                 fd = -1;
2326                                 p_tls = NULL;
2327                                 break;
2328     
2329                             case 1: /* missing input - most likely */
2330                                 i_state = HTTPD_CLIENT_TLS_HS_IN;
2331                                 break;
2332     
2333                             case 2: /* missing output */
2334                                 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2335                                 break;
2336                         }
2337                     }
2338                     
2339                     if( fd >= 0 )
2340                     {
2341                         char *ip;
2342                         httpd_client_t *cl;
2343     
2344                         cl = httpd_ClientNew( fd, &sock, i_sock_size, p_tls );
2345                         p_tls = NULL;
2346                         vlc_mutex_lock( &host->lock );
2347                         TAB_APPEND( host->i_client, host->client, cl );
2348                         vlc_mutex_unlock( &host->lock );
2349     
2350                         if( i_state != 0 )
2351                             cl->i_state = i_state; // override state for TLS
2352     
2353                         // FIXME: it sucks to allocate memory for debug
2354                         ip = httpd_ClientIP( cl );
2355                         msg_Dbg( host, "new connection (%s)",
2356                                 ip != NULL ? ip : "unknown" );
2357                         if( ip != NULL)
2358                             free( ip );
2359                     }
2360                 }
2361             }
2362         }
2363
2364         /* now try all others socket */
2365         vlc_mutex_lock( &host->lock );
2366         for( i_client = 0; i_client < host->i_client; i_client++ )
2367         {
2368             httpd_client_t *cl = host->client[i_client];
2369             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2370             {
2371                 httpd_ClientRecv( cl );
2372             }
2373             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2374             {
2375                 httpd_ClientSend( cl );
2376             }
2377             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2378             {
2379                 httpd_ClientTlsHsIn( cl );
2380             }
2381             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2382             {
2383                 httpd_ClientTlsHsOut( cl );
2384             }
2385
2386             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2387                 cl->i_state == HTTPD_CLIENT_SENDING &&
2388                 FD_ISSET( cl->fd, &fds_read ) )
2389             {
2390                 cl->b_read_waiting = VLC_TRUE;
2391             }
2392         }
2393         vlc_mutex_unlock( &host->lock );
2394     }
2395
2396     if( p_tls != NULL )
2397         tls_ServerSessionClose( p_tls );
2398 }
2399
2400 #else /* ENABLE_HTTPD */
2401
2402 /* We just define an empty wrapper */
2403 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2404                                 tls_server_t *d )
2405 {
2406     msg_Err( a, "HTTP daemon support is disabled" );
2407     return 0;
2408 }
2409 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2410 {
2411     msg_Err( a, "HTTP daemon support is disabled" );
2412     return 0;
2413 }
2414 void httpd_HostDelete( httpd_host_t *a ){}
2415 httpd_url_t *httpd_UrlNew( httpd_host_t *a, char *b ){ return 0; }
2416 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *a, char *b, char *c,
2417                                  char *d ){ return 0; }
2418 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2419                     httpd_callback_sys_t *d ){ return 0; }
2420 void httpd_UrlDelete( httpd_url_t *a ){}
2421
2422 char *httpd_ClientIP( httpd_client_t *a ){ return 0; }
2423 void httpd_ClientModeStream( httpd_client_t *a ){}
2424 void httpd_ClientModeBidir( httpd_client_t *a ){}
2425
2426 void httpd_FileDelete( httpd_file_t *a ){}
2427 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2428                              char *e, httpd_file_callback_t f,
2429                              httpd_file_sys_t *g ){ return 0; }
2430
2431 void httpd_RedirectDelete( httpd_redirect_t *a ){}
2432 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2433                                      char *b, char *c ){ return 0; }
2434
2435 void httpd_StreamDelete( httpd_stream_t *a ){}
2436 int  httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2437 int  httpd_StreamSend  ( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2438 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2439                                  char *d, char *e ){ return 0; }
2440
2441 void httpd_MsgInit ( httpd_message_t *a ){}
2442 void httpd_MsgAdd  ( httpd_message_t *a, char *b, char *c, ... ){}
2443 char *httpd_MsgGet ( httpd_message_t *a, char *b ){ return 0; }
2444 void httpd_MsgClean( httpd_message_t *a ){}
2445
2446 #endif /* ENABLE_HTTPD */