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