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