]> git.sesse.net Git - vlc/blob - src/network/httpd.c
dash: read skips bytes when p_read is NULL
[vlc] / src / network / httpd.c
1 /*****************************************************************************
2  * httpd.c
3  *****************************************************************************
4  * Copyright (C) 2004-2006 VLC authors and VideoLAN
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 it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * 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 <vlc_url.h>
42 #include "../libvlc.h"
43
44 #include <string.h>
45 #include <errno.h>
46
47 #ifdef HAVE_UNISTD_H
48 #   include <unistd.h>
49 #endif
50
51 #ifdef HAVE_POLL
52 # include <poll.h>
53 #endif
54
55 #if defined( UNDER_CE )
56 #   include <winsock.h>
57 #elif defined( WIN32 )
58 #   include <winsock2.h>
59 #else
60 #   include <sys/socket.h>
61 #endif
62
63 #if defined( WIN32 )
64 /* We need HUGE buffer otherwise TCP throughput is very limited */
65 #define HTTPD_CL_BUFSIZE 1000000
66 #else
67 #define HTTPD_CL_BUFSIZE 10000
68 #endif
69
70 static void httpd_ClientClean( httpd_client_t *cl );
71
72 /* each host run in his own thread */
73 struct httpd_host_t
74 {
75     VLC_COMMON_MEMBERS
76
77     /* ref count */
78     unsigned    i_ref;
79
80     /* address/port and socket for listening at connections */
81     int         *fds;
82     unsigned     nfd;
83     unsigned     port;
84
85     vlc_thread_t thread;
86     vlc_mutex_t lock;
87     vlc_cond_t  wait;
88
89     /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
90      * This will slow down the url research but make my live easier
91      * All url will have their cb trigger, but only the first one can answer
92      * */
93     int         i_url;
94     httpd_url_t **url;
95
96     int            i_client;
97     httpd_client_t **client;
98
99     /* TLS data */
100     vlc_tls_creds_t *p_tls;
101 };
102
103
104 struct httpd_url_t
105 {
106     httpd_host_t *host;
107
108     vlc_mutex_t lock;
109
110     char      *psz_url;
111     char      *psz_user;
112     char      *psz_password;
113     vlc_acl_t *p_acl;
114
115     struct
116     {
117         httpd_callback_t     cb;
118         httpd_callback_sys_t *p_sys;
119     } catch[HTTPD_MSG_MAX];
120 };
121
122 /* status */
123 enum
124 {
125     HTTPD_CLIENT_RECEIVING,
126     HTTPD_CLIENT_RECEIVE_DONE,
127
128     HTTPD_CLIENT_SENDING,
129     HTTPD_CLIENT_SEND_DONE,
130
131     HTTPD_CLIENT_WAITING,
132
133     HTTPD_CLIENT_DEAD,
134
135     HTTPD_CLIENT_TLS_HS_IN,
136     HTTPD_CLIENT_TLS_HS_OUT
137 };
138
139 /* mode */
140 enum
141 {
142     HTTPD_CLIENT_FILE,      /* default */
143     HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
144 };
145
146 struct httpd_client_t
147 {
148     httpd_url_t *url;
149
150     int     i_ref;
151
152     int     fd;
153
154     bool    b_stream_mode;
155     uint8_t i_state;
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             cl->b_stream_mode = true;
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 *, const char *,
955                                        const char *, vlc_tls_creds_t * );
956
957 /* create a new host */
958 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
959 {
960     return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
961 }
962
963 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
964 {
965     char *cert = var_InheritString( obj, "http-cert" );
966     if( cert == NULL )
967     {
968         msg_Err( obj, "HTTP/TLS certificate not specified!" );
969         return NULL;
970     }
971
972     char *key = var_InheritString( obj, "http-key" );
973     vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
974
975     if( tls == NULL )
976     {
977         msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
978                  cert, (key != NULL) ? key : cert );
979         free( key );
980         free( cert );
981         return NULL;
982     }
983     free( key );
984     free( cert );
985
986     char *ca = var_InheritString( obj, "http-ca" );
987     if( ca != NULL )
988     {
989         if( vlc_tls_ServerAddCA( tls, ca ) )
990         {
991             msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
992             free( ca );
993             goto error;
994         }
995         free( ca );
996     }
997
998     char *crl = var_InheritString( obj, "http-crl" );
999     if( crl != NULL )
1000     {
1001         if( vlc_tls_ServerAddCRL( tls, crl ) )
1002         {
1003             msg_Err( obj, "TLS CRL error (%s)", crl );
1004             free( crl );
1005             goto error;
1006         }
1007         free( crl );
1008     }
1009
1010     return httpd_HostCreate( obj, "http-host", "https-port", tls );
1011
1012 error:
1013     vlc_tls_ServerDelete( tls );
1014     return NULL;
1015 }
1016
1017 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
1018 {
1019     return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
1020 }
1021
1022 static struct httpd_t
1023 {
1024     vlc_mutex_t  mutex;
1025
1026     httpd_host_t **host;
1027     int          i_host;
1028 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
1029
1030 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
1031                                        const char *hostvar,
1032                                        const char *portvar,
1033                                        vlc_tls_creds_t *p_tls )
1034 {
1035     httpd_host_t *host;
1036     char *hostname = var_InheritString( p_this, hostvar );
1037     unsigned port = var_InheritInteger( p_this, portvar );
1038
1039     vlc_url_t url;
1040     vlc_UrlParse( &url, hostname, 0 );
1041     free( hostname );
1042     if( url.i_port != 0 )
1043     {
1044         msg_Err( p_this, "Ignoring port %d (using %d)", url.i_port, port );
1045         msg_Info( p_this, "Specify port %d separately with the "
1046                           "%s option instead.", url.i_port, portvar );
1047     }
1048
1049     /* to be sure to avoid multiple creation */
1050     vlc_mutex_lock( &httpd.mutex );
1051
1052     /* verify if it already exist */
1053     for( int i = 0; i < httpd.i_host; i++ )
1054     {
1055         host = httpd.host[i];
1056
1057         /* cannot mix TLS and non-TLS hosts */
1058         if( host->port != port
1059          || (host->p_tls != NULL) != (p_tls != NULL) )
1060             continue;
1061
1062         /* Increase existing matching host reference count.
1063          * The reference count is written under both the global httpd and the
1064          * host lock. It is read with either or both locks held. The global
1065          * lock is always acquired first. */
1066         vlc_mutex_lock( &host->lock );
1067         host->i_ref++;
1068         vlc_mutex_unlock( &host->lock );
1069
1070         vlc_mutex_unlock( &httpd.mutex );
1071         vlc_UrlClean( &url );
1072         if( p_tls != NULL )
1073             vlc_tls_ServerDelete( p_tls );
1074         return host;
1075     }
1076
1077     /* create the new host */
1078     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1079                                               "http host" );
1080     if (host == NULL)
1081         goto error;
1082
1083     vlc_mutex_init( &host->lock );
1084     vlc_cond_init( &host->wait );
1085     host->i_ref = 1;
1086
1087     host->fds = net_ListenTCP( p_this, url.psz_host, 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     if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1096     {
1097         msg_Err( host, "signaling pipe error: %m" );
1098         goto error;
1099     }
1100
1101     host->port     = port;
1102     host->i_url    = 0;
1103     host->url      = NULL;
1104     host->i_client = 0;
1105     host->client   = NULL;
1106     host->p_tls    = p_tls;
1107
1108     /* create the thread */
1109     if( vlc_clone( &host->thread, httpd_HostThread, host,
1110                    VLC_THREAD_PRIORITY_LOW ) )
1111     {
1112         msg_Err( p_this, "cannot spawn http host thread" );
1113         goto error;
1114     }
1115
1116     /* now add it to httpd */
1117     TAB_APPEND( httpd.i_host, httpd.host, host );
1118     vlc_mutex_unlock( &httpd.mutex );
1119
1120     vlc_UrlClean( &url );
1121
1122     return host;
1123
1124 error:
1125     vlc_mutex_unlock( &httpd.mutex );
1126
1127     if( host != NULL )
1128     {
1129         net_ListenClose( host->fds );
1130         vlc_cond_destroy( &host->wait );
1131         vlc_mutex_destroy( &host->lock );
1132         vlc_object_release( host );
1133     }
1134
1135     vlc_UrlClean( &url );
1136
1137     if( p_tls != NULL )
1138         vlc_tls_ServerDelete( p_tls );
1139
1140     return NULL;
1141 }
1142
1143 /* delete a host */
1144 void httpd_HostDelete( httpd_host_t *host )
1145 {
1146     int i;
1147     bool delete = false;
1148
1149     vlc_mutex_lock( &httpd.mutex );
1150
1151     vlc_mutex_lock( &host->lock );
1152     host->i_ref--;
1153     if( host->i_ref == 0 )
1154     {
1155         vlc_cond_signal( &host->wait );
1156         delete = true;
1157     }
1158     vlc_mutex_unlock( &host->lock );
1159     if( !delete )
1160     {
1161         /* still used */
1162         vlc_mutex_unlock( &httpd.mutex );
1163         msg_Dbg( host, "httpd_HostDelete: host still in use" );
1164         return;
1165     }
1166     TAB_REMOVE( httpd.i_host, httpd.host, host );
1167
1168     vlc_object_kill( host );
1169     vlc_join( host->thread, NULL );
1170
1171     msg_Dbg( host, "HTTP host removed" );
1172
1173     for( i = 0; i < host->i_url; i++ )
1174     {
1175         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1176     }
1177     for( i = 0; i < host->i_client; i++ )
1178     {
1179         httpd_client_t *cl = host->client[i];
1180         msg_Warn( host, "client still connected" );
1181         httpd_ClientClean( cl );
1182         TAB_REMOVE( host->i_client, host->client, cl );
1183         free( cl );
1184         i--;
1185         /* TODO */
1186     }
1187
1188     if( host->p_tls != NULL)
1189         vlc_tls_ServerDelete( host->p_tls );
1190
1191     net_ListenClose( host->fds );
1192     vlc_cond_destroy( &host->wait );
1193     vlc_mutex_destroy( &host->lock );
1194     vlc_object_release( host );
1195     vlc_mutex_unlock( &httpd.mutex );
1196 }
1197
1198 /* register a new url */
1199 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1200                                          const char *psz_user, const char *psz_password,
1201                                          const vlc_acl_t *p_acl, bool b_check )
1202 {
1203     httpd_url_t *url;
1204     int         i;
1205
1206     assert( psz_url != NULL );
1207
1208     vlc_mutex_lock( &host->lock );
1209     if( b_check )
1210     {
1211         for( i = 0; i < host->i_url; i++ )
1212         {
1213             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1214             {
1215                 msg_Warn( host,
1216                           "cannot add '%s' (url already defined)", psz_url );
1217                 vlc_mutex_unlock( &host->lock );
1218                 return NULL;
1219             }
1220         }
1221     }
1222
1223     url = xmalloc( sizeof( httpd_url_t ) );
1224     url->host = host;
1225
1226     vlc_mutex_init( &url->lock );
1227     url->psz_url = strdup( psz_url );
1228     url->psz_user = strdup( psz_user ? psz_user : "" );
1229     url->psz_password = strdup( psz_password ? psz_password : "" );
1230     url->p_acl = ACL_Duplicate( host, p_acl );
1231     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1232     {
1233         url->catch[i].cb = NULL;
1234         url->catch[i].p_sys = NULL;
1235     }
1236
1237     TAB_APPEND( host->i_url, host->url, url );
1238     vlc_cond_signal( &host->wait );
1239     vlc_mutex_unlock( &host->lock );
1240
1241     return url;
1242 }
1243
1244 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1245                            const char *psz_user, const char *psz_password,
1246                            const vlc_acl_t *p_acl )
1247 {
1248     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1249                                 psz_password, p_acl, false );
1250 }
1251
1252 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1253                                  const char *psz_user, const char *psz_password,
1254                                  const vlc_acl_t *p_acl )
1255 {
1256     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1257                                 psz_password, p_acl, true );
1258 }
1259
1260 /* register callback on a url */
1261 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1262                     httpd_callback_sys_t *p_sys )
1263 {
1264     vlc_mutex_lock( &url->lock );
1265     url->catch[i_msg].cb   = cb;
1266     url->catch[i_msg].p_sys= p_sys;
1267     vlc_mutex_unlock( &url->lock );
1268
1269     return VLC_SUCCESS;
1270 }
1271
1272 /* delete a url */
1273 void httpd_UrlDelete( httpd_url_t *url )
1274 {
1275     httpd_host_t *host = url->host;
1276     int          i;
1277
1278     vlc_mutex_lock( &host->lock );
1279     TAB_REMOVE( host->i_url, host->url, url );
1280
1281     vlc_mutex_destroy( &url->lock );
1282     free( url->psz_url );
1283     free( url->psz_user );
1284     free( url->psz_password );
1285     ACL_Destroy( url->p_acl );
1286
1287     for( i = 0; i < host->i_client; i++ )
1288     {
1289         httpd_client_t *client = host->client[i];
1290
1291         if( client->url == url )
1292         {
1293             /* TODO complete it */
1294             msg_Warn( host, "force closing connections" );
1295             httpd_ClientClean( client );
1296             TAB_REMOVE( host->i_client, host->client, client );
1297             free( client );
1298             i--;
1299         }
1300     }
1301     free( url );
1302     vlc_mutex_unlock( &host->lock );
1303 }
1304
1305 static void httpd_MsgInit( httpd_message_t *msg )
1306 {
1307     msg->cl         = NULL;
1308     msg->i_type     = HTTPD_MSG_NONE;
1309     msg->i_proto    = HTTPD_PROTO_NONE;
1310     msg->i_version  = -1; /* FIXME */
1311
1312     msg->i_status   = 0;
1313
1314     msg->psz_url    = NULL;
1315     msg->psz_args   = NULL;
1316
1317     msg->i_name     = 0;
1318     msg->name       = NULL;
1319     msg->i_value    = 0;
1320     msg->value      = NULL;
1321
1322     msg->i_body_offset = 0;
1323     msg->i_body        = 0;
1324     msg->p_body        = NULL;
1325 }
1326
1327 static void httpd_MsgClean( httpd_message_t *msg )
1328 {
1329     int i;
1330
1331     free( msg->psz_url );
1332     free( msg->psz_args );
1333     for( i = 0; i < msg->i_name; i++ )
1334     {
1335         free( msg->name[i] );
1336         free( msg->value[i] );
1337     }
1338     free( msg->name );
1339     free( msg->value );
1340     free( msg->p_body );
1341     httpd_MsgInit( msg );
1342 }
1343
1344 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1345 {
1346     int i;
1347
1348     for( i = 0; i < msg->i_name; i++ )
1349     {
1350         if( !strcasecmp( msg->name[i], name ))
1351         {
1352             return msg->value[i];
1353         }
1354     }
1355     return NULL;
1356 }
1357
1358 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1359 {
1360     va_list args;
1361     char *value = NULL;
1362
1363     va_start( args, psz_value );
1364     if( us_vasprintf( &value, psz_value, args ) == -1 )
1365         value = NULL;
1366     va_end( args );
1367
1368     if( value == NULL )
1369         return;
1370
1371     name = strdup( name );
1372     if( name == NULL )
1373     {
1374         free( value );
1375         return;
1376     }
1377
1378     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1379     TAB_APPEND( msg->i_value, msg->value, value );
1380 }
1381
1382 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1383 {
1384     cl->i_state = HTTPD_CLIENT_RECEIVING;
1385     cl->i_activity_date = now;
1386     cl->i_activity_timeout = INT64_C(10000000);
1387     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1388     cl->i_buffer = 0;
1389     cl->p_buffer = xmalloc( cl->i_buffer_size );
1390     cl->b_stream_mode = false;
1391
1392     httpd_MsgInit( &cl->query );
1393     httpd_MsgInit( &cl->answer );
1394 }
1395
1396 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1397 {
1398     return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1399 }
1400
1401 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1402 {
1403     return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1404 }
1405
1406 static void httpd_ClientClean( httpd_client_t *cl )
1407 {
1408     if( cl->fd >= 0 )
1409     {
1410         if( cl->p_tls != NULL )
1411             vlc_tls_ServerSessionDelete( cl->p_tls );
1412         net_Close( cl->fd );
1413         cl->fd = -1;
1414     }
1415
1416     httpd_MsgClean( &cl->answer );
1417     httpd_MsgClean( &cl->query );
1418
1419     free( cl->p_buffer );
1420     cl->p_buffer = NULL;
1421 }
1422
1423 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1424 {
1425     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1426
1427     if( !cl ) return NULL;
1428
1429     cl->i_ref   = 0;
1430     cl->fd      = fd;
1431     cl->url     = NULL;
1432     cl->p_tls = p_tls;
1433
1434     httpd_ClientInit( cl, now );
1435
1436     return cl;
1437 }
1438
1439 static
1440 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1441 {
1442     vlc_tls_t *p_tls;
1443     ssize_t val;
1444
1445     p_tls = cl->p_tls;
1446     do
1447         val = p_tls ? tls_Recv (p_tls, p, i_len)
1448                     : recv (cl->fd, p, i_len, 0);
1449     while (val == -1 && errno == EINTR);
1450     return val;
1451 }
1452
1453 static
1454 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1455 {
1456     vlc_tls_t *p_tls;
1457     ssize_t val;
1458
1459     p_tls = cl->p_tls;
1460     do
1461         val = p_tls ? tls_Send( p_tls, p, i_len )
1462                     : send (cl->fd, p, i_len, 0);
1463     while (val == -1 && errno == EINTR);
1464     return val;
1465 }
1466
1467
1468 static const struct
1469 {
1470     const char name[16];
1471     int  i_type;
1472     int  i_proto;
1473 }
1474 msg_type[] =
1475 {
1476     { "OPTIONS",       HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1477     { "DESCRIBE",      HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1478     { "SETUP",         HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1479     { "PLAY",          HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1480     { "PAUSE",         HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1481     { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1482     { "TEARDOWN",      HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1483     { "GET",           HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1484     { "HEAD",          HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1485     { "POST",          HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1486     { "",              HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1487 };
1488
1489
1490 static void httpd_ClientRecv( httpd_client_t *cl )
1491 {
1492     int i_len;
1493
1494     /* ignore leading whites */
1495     if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1496         ( cl->i_buffer == 0 ) )
1497     {
1498         unsigned char c;
1499
1500         i_len = httpd_NetRecv( cl, &c, 1 );
1501
1502         if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1503         {
1504             cl->p_buffer[0] = c;
1505             cl->i_buffer++;
1506         }
1507     }
1508     else
1509     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1510     {
1511         /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1512         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1513                                7 - cl->i_buffer );
1514         if( i_len > 0 )
1515         {
1516             cl->i_buffer += i_len;
1517         }
1518
1519         /* The smallest legal request is 7 bytes ("GET /\r\n"),
1520          * this is the maximum we can ask at this point. */
1521         if( cl->i_buffer >= 7 )
1522         {
1523             if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1524             {
1525                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1526                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1527             }
1528             else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1529             {
1530                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1531                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1532             }
1533             else
1534             {
1535                 /* We need the full request line to determine the protocol. */
1536                 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1537                 cl->query.i_type  = HTTPD_MSG_NONE;
1538             }
1539         }
1540     }
1541     else if( cl->query.i_body > 0 )
1542     {
1543         /* we are reading the body of a request or a channel */
1544         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1545                                cl->query.i_body - cl->i_buffer );
1546         if( i_len > 0 )
1547         {
1548             cl->i_buffer += i_len;
1549         }
1550         if( cl->i_buffer >= cl->query.i_body )
1551         {
1552             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1553         }
1554     }
1555     else
1556     {
1557         /* we are reading a header -> char by char */
1558         for( ;; )
1559         {
1560             if( cl->i_buffer == cl->i_buffer_size )
1561             {
1562                 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1563                 if( newbuf == NULL )
1564                 {
1565                     i_len = 0;
1566                     break;
1567                 }
1568
1569                 cl->p_buffer = newbuf;
1570                 cl->i_buffer_size += 1024;
1571             }
1572
1573             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1574             if( i_len <= 0 )
1575             {
1576                 break;
1577             }
1578             cl->i_buffer++;
1579
1580             if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1581              && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1582             {
1583                 /* Request line is now complete */
1584                 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1585                 size_t len;
1586
1587                 assert( cl->query.i_type == HTTPD_MSG_NONE );
1588
1589                 if( p == NULL ) /* no URI: evil guy */
1590                 {
1591                     i_len = 0; /* drop connection */
1592                     break;
1593                 }
1594
1595                 do
1596                     p++; /* skips extra spaces */
1597                 while( *p == ' ' );
1598
1599                 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1600                 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1601                 {
1602                     i_len = 0; /* not supported currently -> drop */
1603                     break;
1604                 }
1605
1606                 do
1607                     p++; /* skips extra spaces ever again */
1608                 while( *p == ' ' );
1609
1610                 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1611                 if( len < 7 ) /* foreign protocol */
1612                     i_len = 0; /* I don't understand -> drop */
1613                 else
1614                 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1615                 {
1616                     cl->query.i_proto = HTTPD_PROTO_HTTP;
1617                     cl->query.i_version = atoi( p + 7 );
1618                 }
1619                 else
1620                 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1621                 {
1622                     cl->query.i_proto = HTTPD_PROTO_RTSP;
1623                     cl->query.i_version = atoi( p + 7 );
1624                 }
1625                 else
1626                 if( memcmp( p, "HTTP/", 5 ) == 0 )
1627                 {
1628                     const uint8_t sorry[] =
1629                        "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1630                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1631                     i_len = 0; /* drop */
1632                 }
1633                 else
1634                 if( memcmp( p, "RTSP/", 5 ) == 0 )
1635                 {
1636                     const uint8_t sorry[] =
1637                         "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1638                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1639                     i_len = 0; /* drop */
1640                 }
1641                 else /* yet another foreign protocol */
1642                     i_len = 0;
1643
1644                 if( i_len == 0 )
1645                     break;
1646             }
1647
1648             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1649                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1650             {
1651                 char *p;
1652
1653                 /* we have finished the header so parse it and set i_body */
1654                 cl->p_buffer[cl->i_buffer] = '\0';
1655
1656                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1657                 {
1658                     /* FIXME:
1659                      * assume strlen( "HTTP/1.x" ) = 8
1660                      */
1661                     cl->query.i_status =
1662                         strtol( (char *)&cl->p_buffer[8],
1663                                 &p, 0 );
1664                     while( *p == ' ' )
1665                         p++;
1666                 }
1667                 else
1668                 {
1669                     unsigned i;
1670
1671                     p = NULL;
1672                     cl->query.i_type = HTTPD_MSG_NONE;
1673
1674                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1675
1676                     for( i = 0; msg_type[i].name[0]; i++ )
1677                     {
1678                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1679                                       strlen( msg_type[i].name ) ) )
1680                         {
1681                             p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1682                             cl->query.i_type = msg_type[i].i_type;
1683                             if( cl->query.i_proto != msg_type[i].i_proto )
1684                             {
1685                                 p = NULL;
1686                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1687                                 cl->query.i_type = HTTPD_MSG_NONE;
1688                             }
1689                             break;
1690                         }
1691                     }
1692                     if( p == NULL )
1693                     {
1694                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1695                         {
1696                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1697                         }
1698                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1699                         {
1700                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1701                         }
1702                     }
1703                     else
1704                     {
1705                         char *p2;
1706                         char *p3;
1707
1708                         while( *p == ' ' )
1709                         {
1710                             p++;
1711                         }
1712                         p2 = strchr( p, ' ' );
1713                         if( p2 )
1714                         {
1715                             *p2++ = '\0';
1716                         }
1717                         if( !strncasecmp( p, ( cl->query.i_proto
1718                              == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1719                         {   /* Skip hier-part of URL (if present) */
1720                             p += 5;
1721                             if( !strncmp( p, "//", 2 ) ) /* skip authority */
1722                             {   /* see RFC3986 §3.2 */
1723                                 p += 2;
1724                                 p += strcspn( p, "/?#" );
1725                             }
1726                         }
1727                         else
1728                         if( !strncasecmp( p, ( cl->query.i_proto
1729                              == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1730                         {   /* Skip hier-part of URL (if present) */
1731                             p += 6;
1732                             if( !strncmp( p, "//", 2 ) ) /* skip authority */
1733                             {   /* see RFC3986 §3.2 */
1734                                 p += 2;
1735                                 p += strcspn( p, "/?#" );
1736                             }
1737                         }
1738
1739                         cl->query.psz_url = strdup( p );
1740                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1741                         {
1742                             *p3++ = '\0';
1743                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1744                         }
1745                         p = p2;
1746                     }
1747                 }
1748                 if( p )
1749                 {
1750                     p = strchr( p, '\n' );
1751                 }
1752                 if( p )
1753                 {
1754                     while( *p == '\n' || *p == '\r' )
1755                     {
1756                         p++;
1757                     }
1758                     while( p && *p != '\0' )
1759                     {
1760                         char *line = p;
1761                         char *eol = p = strchr( p, '\n' );
1762                         char *colon;
1763
1764                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1765                         {
1766                             *eol-- = '\0';
1767                         }
1768
1769                         if( ( colon = strchr( line, ':' ) ) )
1770                         {
1771                             char *name;
1772                             char *value;
1773
1774                             *colon++ = '\0';
1775                             while( *colon == ' ' )
1776                             {
1777                                 colon++;
1778                             }
1779                             name = strdup( line );
1780                             value = strdup( colon );
1781
1782                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1783                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1784
1785                             if( !strcasecmp( name, "Content-Length" ) )
1786                             {
1787                                 cl->query.i_body = atol( value );
1788                             }
1789                         }
1790
1791                         if( p )
1792                         {
1793                             p++;
1794                             while( *p == '\n' || *p == '\r' )
1795                             {
1796                                 p++;
1797                             }
1798                         }
1799                     }
1800                 }
1801                 if( cl->query.i_body > 0 )
1802                 {
1803                     /* TODO Mhh, handle the case where the client only
1804                      * sends a request and closes the connection to
1805                      * mark the end of the body (probably only RTSP) */
1806                     cl->query.p_body = malloc( cl->query.i_body );
1807                     cl->i_buffer = 0;
1808                     if ( cl->query.p_body == NULL )
1809                     {
1810                         switch (cl->query.i_proto)
1811                         {
1812                             case HTTPD_PROTO_HTTP:
1813                             {
1814                                 const uint8_t sorry[] =
1815                             "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1816                                 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1817                                 break;
1818                             }
1819                             case HTTPD_PROTO_RTSP:
1820                             {
1821                                 const uint8_t sorry[] =
1822                             "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1823                                 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1824                                 break;
1825                             }
1826                             default:
1827                                 assert( 0 );
1828                         }
1829                         i_len = 0; /* drop */
1830                     }
1831                     break;
1832                 }
1833                 else
1834                 {
1835                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1836                 }
1837             }
1838         }
1839     }
1840
1841     /* check if the client is to be set to dead */
1842 #if defined( WIN32 ) || defined( UNDER_CE )
1843     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1844 #else
1845     if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1846 #endif
1847     {
1848         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1849         {
1850             /* connection closed -> end of data */
1851             if( cl->query.i_body > 0 )
1852             {
1853                 cl->query.i_body = cl->i_buffer;
1854             }
1855             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1856         }
1857         else
1858         {
1859             cl->i_state = HTTPD_CLIENT_DEAD;
1860         }
1861     }
1862
1863     /* XXX: for QT I have to disable timeout. Try to find why */
1864     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1865         cl->i_activity_timeout = 0;
1866
1867 #if 0 /* Debugging only */
1868     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1869     {
1870         int i;
1871
1872         fprintf( stderr, "received new request\n" );
1873         fprintf( stderr, "  - proto=%s\n",
1874                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1875         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1876         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1877         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1878         {
1879             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1880                      cl->query.psz_status );
1881         }
1882         else if( cl->query.i_type != HTTPD_MSG_NONE )
1883         {
1884             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1885         }
1886         for( i = 0; i < cl->query.i_name; i++ )
1887         {
1888             fprintf( stderr, "  - option name='%s' value='%s'\n",
1889                      cl->query.name[i], cl->query.value[i] );
1890         }
1891     }
1892 #endif
1893 }
1894
1895 static void httpd_ClientSend( httpd_client_t *cl )
1896 {
1897     int i;
1898     int i_len;
1899
1900     if( cl->i_buffer < 0 )
1901     {
1902         /* We need to create the header */
1903         int i_size = 0;
1904         char *p;
1905         const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1906
1907         i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1908         for( i = 0; i < cl->answer.i_name; i++ )
1909         {
1910             i_size += strlen( cl->answer.name[i] ) + 2 +
1911                       strlen( cl->answer.value[i] ) + 2;
1912         }
1913
1914         if( cl->i_buffer_size < i_size )
1915         {
1916             cl->i_buffer_size = i_size;
1917             free( cl->p_buffer );
1918             cl->p_buffer = xmalloc( i_size );
1919         }
1920         p = (char *)cl->p_buffer;
1921
1922         p += sprintf( p, "%s.%u %d %s\r\n",
1923                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1924                       cl->answer.i_version,
1925                       cl->answer.i_status, psz_status );
1926         for( i = 0; i < cl->answer.i_name; i++ )
1927         {
1928             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1929                           cl->answer.value[i] );
1930         }
1931         p += sprintf( p, "\r\n" );
1932
1933         cl->i_buffer = 0;
1934         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1935
1936         /*fprintf( stderr, "sending answer\n" );
1937         fprintf( stderr, "%s",  cl->p_buffer );*/
1938     }
1939
1940     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1941                            cl->i_buffer_size - cl->i_buffer );
1942     if( i_len >= 0 )
1943     {
1944         cl->i_buffer += i_len;
1945
1946         if( cl->i_buffer >= cl->i_buffer_size )
1947         {
1948             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 )
1949             {
1950                 /* catch more body data */
1951                 int     i_msg = cl->query.i_type;
1952                 int64_t i_offset = cl->answer.i_body_offset;
1953
1954                 httpd_MsgClean( &cl->answer );
1955                 cl->answer.i_body_offset = i_offset;
1956
1957                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1958                                           &cl->answer, &cl->query );
1959             }
1960
1961             if( cl->answer.i_body > 0 )
1962             {
1963                 /* send the body data */
1964                 free( cl->p_buffer );
1965                 cl->p_buffer = cl->answer.p_body;
1966                 cl->i_buffer_size = cl->answer.i_body;
1967                 cl->i_buffer = 0;
1968
1969                 cl->answer.i_body = 0;
1970                 cl->answer.p_body = NULL;
1971             }
1972             else
1973             {
1974                 /* send finished */
1975                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1976             }
1977         }
1978     }
1979     else
1980     {
1981 #if defined( WIN32 ) || defined( UNDER_CE )
1982         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1983 #else
1984         if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1985 #endif
1986         {
1987             /* error */
1988             cl->i_state = HTTPD_CLIENT_DEAD;
1989         }
1990     }
1991 }
1992
1993 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1994 {
1995     switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1996     {
1997         case 0:
1998             cl->i_state = HTTPD_CLIENT_RECEIVING;
1999             break;
2000
2001         case -1:
2002             cl->i_state = HTTPD_CLIENT_DEAD;
2003             cl->p_tls = NULL;
2004             break;
2005
2006         case 2:
2007             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2008     }
2009 }
2010
2011 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2012 {
2013     switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
2014     {
2015         case 0:
2016             cl->i_state = HTTPD_CLIENT_RECEIVING;
2017             break;
2018
2019         case -1:
2020             cl->i_state = HTTPD_CLIENT_DEAD;
2021             cl->p_tls = NULL;
2022             break;
2023
2024         case 1:
2025             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2026             break;
2027     }
2028 }
2029
2030 static void* httpd_HostThread( void *data )
2031 {
2032     httpd_host_t *host = data;
2033     int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2034
2035     for( ;; )
2036     {
2037         struct pollfd ufd[host->nfd + host->i_client + 1];
2038         unsigned nfd;
2039         for( nfd = 0; nfd < host->nfd; nfd++ )
2040         {
2041             ufd[nfd].fd = host->fds[nfd];
2042             ufd[nfd].events = POLLIN;
2043             ufd[nfd].revents = 0;
2044         }
2045
2046         /* add all socket that should be read/write and close dead connection */
2047         vlc_mutex_lock( &host->lock );
2048         while( host->i_url <= 0 && host->i_ref > 0 )
2049             vlc_cond_wait( &host->wait, &host->lock );
2050
2051         mtime_t now = mdate();
2052         bool b_low_delay = false;
2053
2054         for(int i_client = 0; i_client < host->i_client; i_client++ )
2055         {
2056             httpd_client_t *cl = host->client[i_client];
2057             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2058                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2059                   ( cl->i_activity_timeout > 0 &&
2060                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2061             {
2062                 httpd_ClientClean( cl );
2063                 TAB_REMOVE( host->i_client, host->client, cl );
2064                 free( cl );
2065                 i_client--;
2066                 continue;
2067             }
2068
2069             struct pollfd *pufd = ufd + nfd;
2070             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2071
2072             pufd->fd = cl->fd;
2073             pufd->events = pufd->revents = 0;
2074
2075             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2076                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2077             {
2078                 pufd->events = POLLIN;
2079             }
2080             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2081                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2082             {
2083                 pufd->events = POLLOUT;
2084             }
2085             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2086             {
2087                 httpd_message_t *answer = &cl->answer;
2088                 httpd_message_t *query  = &cl->query;
2089                 int i_msg = query->i_type;
2090
2091                 httpd_MsgInit( answer );
2092
2093                 /* Handle what we received */
2094                 if( i_msg == HTTPD_MSG_ANSWER )
2095                 {
2096                     cl->url     = NULL;
2097                     cl->i_state = HTTPD_CLIENT_DEAD;
2098                 }
2099                 else if( i_msg == HTTPD_MSG_OPTIONS )
2100                 {
2101
2102                     answer->i_type   = HTTPD_MSG_ANSWER;
2103                     answer->i_proto  = query->i_proto;
2104                     answer->i_status = 200;
2105                     answer->i_body = 0;
2106                     answer->p_body = NULL;
2107
2108                     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2109                     httpd_MsgAdd( answer, "Content-Length", "0" );
2110
2111                     switch( query->i_proto )
2112                     {
2113                         case HTTPD_PROTO_HTTP:
2114                             answer->i_version = 1;
2115                             httpd_MsgAdd( answer, "Allow",
2116                                           "GET,HEAD,POST,OPTIONS" );
2117                             break;
2118
2119                         case HTTPD_PROTO_RTSP:
2120                         {
2121                             const char *p;
2122                             answer->i_version = 0;
2123
2124                             p = httpd_MsgGet( query, "Cseq" );
2125                             if( p != NULL )
2126                                 httpd_MsgAdd( answer, "Cseq", "%s", p );
2127                             p = httpd_MsgGet( query, "Timestamp" );
2128                             if( p != NULL )
2129                                 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2130
2131                             p = httpd_MsgGet( query, "Require" );
2132                             if( p != NULL )
2133                             {
2134                                 answer->i_status = 551;
2135                                 httpd_MsgAdd( query, "Unsupported", "%s", p );
2136                             }
2137
2138                             httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2139                                           "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2140                             break;
2141                         }
2142                     }
2143
2144                     cl->i_buffer = -1;  /* Force the creation of the answer in
2145                                          * httpd_ClientSend */
2146                     cl->i_state = HTTPD_CLIENT_SENDING;
2147                 }
2148                 else if( i_msg == HTTPD_MSG_NONE )
2149                 {
2150                     if( query->i_proto == HTTPD_PROTO_NONE )
2151                     {
2152                         cl->url = NULL;
2153                         cl->i_state = HTTPD_CLIENT_DEAD;
2154                     }
2155                     else
2156                     {
2157                         char *p;
2158
2159                         /* unimplemented */
2160                         answer->i_proto  = query->i_proto ;
2161                         answer->i_type   = HTTPD_MSG_ANSWER;
2162                         answer->i_version= 0;
2163                         answer->i_status = 501;
2164
2165                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2166                         answer->p_body = (uint8_t *)p;
2167                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2168
2169                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2170                         cl->i_state = HTTPD_CLIENT_SENDING;
2171                     }
2172                 }
2173                 else
2174                 {
2175                     bool b_auth_failed = false;
2176                     bool b_hosts_failed = false;
2177
2178                     /* Search the url and trigger callbacks */
2179                     for(int i = 0; i < host->i_url; i++ )
2180                     {
2181                         httpd_url_t *url = host->url[i];
2182
2183                         if( !strcmp( url->psz_url, query->psz_url ) )
2184                         {
2185                             if( url->catch[i_msg].cb )
2186                             {
2187                                 if( answer && ( url->p_acl != NULL ) )
2188                                 {
2189                                     char ip[NI_MAXNUMERICHOST];
2190
2191                                     if( ( httpd_ClientIP( cl, ip, NULL ) == NULL )
2192                                      || ACL_Check( url->p_acl, ip ) )
2193                                     {
2194                                         b_hosts_failed = true;
2195                                         break;
2196                                     }
2197                                 }
2198
2199                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2200                                 {
2201                                     /* create the headers */
2202                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2203                                     char *user = NULL, *pass = NULL;
2204
2205                                     if( b64 != NULL
2206                                      && !strncasecmp( b64, "BASIC", 5 ) )
2207                                     {
2208                                         b64 += 5;
2209                                         while( *b64 == ' ' )
2210                                             b64++;
2211
2212                                         user = vlc_b64_decode( b64 );
2213                                         if (user != NULL)
2214                                         {
2215                                             pass = strchr (user, ':');
2216                                             if (pass != NULL)
2217                                                 *pass++ = '\0';
2218                                         }
2219                                     }
2220
2221                                     if ((user == NULL) || (pass == NULL)
2222                                      || strcmp (user, url->psz_user)
2223                                      || strcmp (pass, url->psz_password))
2224                                     {
2225                                         httpd_MsgAdd( answer,
2226                                                       "WWW-Authenticate",
2227                                                       "Basic realm=\"VLC stream\"" );
2228                                         /* We fail for all url */
2229                                         b_auth_failed = true;
2230                                         free( user );
2231                                         break;
2232                                     }
2233
2234                                     free( user );
2235                                 }
2236
2237                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2238                                 {
2239                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2240                                     {
2241                                         /* Raw answer from a CGI */
2242                                         cl->i_buffer = cl->i_buffer_size;
2243                                     }
2244                                     else
2245                                         cl->i_buffer = -1;
2246
2247                                     /* only one url can answer */
2248                                     answer = NULL;
2249                                     if( cl->url == NULL )
2250                                     {
2251                                         cl->url = url;
2252                                     }
2253                                 }
2254                             }
2255                         }
2256                     }
2257
2258                     if( answer )
2259                     {
2260                         char *p;
2261
2262                         answer->i_proto  = query->i_proto;
2263                         answer->i_type   = HTTPD_MSG_ANSWER;
2264                         answer->i_version= 0;
2265
2266                         if( b_hosts_failed )
2267                         {
2268                             answer->i_status = 403;
2269                         }
2270                         else if( b_auth_failed )
2271                         {
2272                             answer->i_status = 401;
2273                         }
2274                         else
2275                         {
2276                             /* no url registered */
2277                             answer->i_status = 404;
2278                         }
2279
2280                         answer->i_body = httpd_HtmlError (&p,
2281                                                           answer->i_status,
2282                                                           query->psz_url);
2283                         answer->p_body = (uint8_t *)p;
2284
2285                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2286                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2287                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2288                     }
2289
2290                     cl->i_state = HTTPD_CLIENT_SENDING;
2291                 }
2292             }
2293             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2294             {
2295                 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2296                 {
2297                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2298                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2299                     bool b_connection = false;
2300                     bool b_keepalive = false;
2301                     bool b_query = false;
2302
2303                     cl->url = NULL;
2304                     if( psz_connection )
2305                     {
2306                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2307                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2308                     }
2309
2310                     if( psz_query )
2311                     {
2312                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2313                     }
2314
2315                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2316                           ( ( cl->query.i_version == 0 && b_keepalive ) ||
2317                             ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2318                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2319                           !b_query && !b_connection ) )
2320                     {
2321                         httpd_MsgClean( &cl->query );
2322                         httpd_MsgInit( &cl->query );
2323
2324                         cl->i_buffer = 0;
2325                         cl->i_buffer_size = 1000;
2326                         free( cl->p_buffer );
2327                         cl->p_buffer = xmalloc( cl->i_buffer_size );
2328                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2329                     }
2330                     else
2331                     {
2332                         cl->i_state = HTTPD_CLIENT_DEAD;
2333                     }
2334                     httpd_MsgClean( &cl->answer );
2335                 }
2336                 else
2337                 {
2338                     int64_t i_offset = cl->answer.i_body_offset;
2339                     httpd_MsgClean( &cl->answer );
2340
2341                     cl->answer.i_body_offset = i_offset;
2342                     free( cl->p_buffer );
2343                     cl->p_buffer = NULL;
2344                     cl->i_buffer = 0;
2345                     cl->i_buffer_size = 0;
2346
2347                     cl->i_state = HTTPD_CLIENT_WAITING;
2348                 }
2349             }
2350             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2351             {
2352                 int64_t i_offset = cl->answer.i_body_offset;
2353                 int     i_msg = cl->query.i_type;
2354
2355                 httpd_MsgInit( &cl->answer );
2356                 cl->answer.i_body_offset = i_offset;
2357
2358                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2359                                           &cl->answer, &cl->query );
2360                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2361                 {
2362                     /* we have new data, so re-enter send mode */
2363                     cl->i_buffer      = 0;
2364                     cl->p_buffer      = cl->answer.p_body;
2365                     cl->i_buffer_size = cl->answer.i_body;
2366                     cl->answer.p_body = NULL;
2367                     cl->answer.i_body = 0;
2368                     cl->i_state = HTTPD_CLIENT_SENDING;
2369                 }
2370             }
2371
2372             if (pufd->events != 0)
2373                 nfd++;
2374             else
2375                 b_low_delay = true;
2376         }
2377         vlc_mutex_unlock( &host->lock );
2378
2379         ufd[nfd].fd = evfd;
2380         ufd[nfd].events = POLLIN;
2381         ufd[nfd].revents = 0;
2382         nfd++;
2383
2384         /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2385         switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2386         {
2387             case -1:
2388                 if (errno != EINTR)
2389                 {
2390                     /* Kernel on low memory or a bug: pace */
2391                     msg_Err( host, "polling error: %m" );
2392                     msleep( 100000 );
2393                 }
2394             case 0:
2395                 continue;
2396         }
2397
2398         if( ufd[nfd - 1].revents )
2399             break;
2400
2401         /* Handle client sockets */
2402         vlc_mutex_lock( &host->lock );
2403         now = mdate();
2404         nfd = host->nfd;
2405         for( int i_client = 0; i_client < host->i_client; i_client++ )
2406         {
2407             httpd_client_t *cl = host->client[i_client];
2408             const struct pollfd *pufd = &ufd[nfd];
2409
2410             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2411
2412             if( cl->fd != pufd->fd )
2413                 continue; // we were not waiting for this client
2414             ++nfd;
2415             if( pufd->revents == 0 )
2416                 continue; // no event received
2417
2418             cl->i_activity_date = now;
2419
2420             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2421             {
2422                 httpd_ClientRecv( cl );
2423             }
2424             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2425             {
2426                 httpd_ClientSend( cl );
2427             }
2428             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2429             {
2430                 httpd_ClientTlsHsIn( cl );
2431             }
2432             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2433             {
2434                 httpd_ClientTlsHsOut( cl );
2435             }
2436         }
2437         vlc_mutex_unlock( &host->lock );
2438
2439         /* Handle server sockets (accept new connections) */
2440         for( nfd = 0; nfd < host->nfd; nfd++ )
2441         {
2442             httpd_client_t *cl;
2443             int i_state = -1;
2444             int fd = ufd[nfd].fd;
2445
2446             assert (fd == host->fds[nfd]);
2447
2448             if( ufd[nfd].revents == 0 )
2449                 continue;
2450
2451             /* */
2452             fd = vlc_accept (fd, NULL, NULL, true);
2453             if (fd == -1)
2454                 continue;
2455             setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2456                         &(int){ 1 }, sizeof(int));
2457
2458             vlc_tls_t *p_tls;
2459
2460             if( host->p_tls != NULL )
2461             {
2462                 p_tls = vlc_tls_ServerSessionCreate( host->p_tls, fd );
2463                 switch( vlc_tls_ServerSessionHandshake( p_tls ) )
2464                 {
2465                     case -1:
2466                         msg_Err( host, "Rejecting TLS connection" );
2467                         /* p_tls is destroyed implicitly */
2468                         net_Close( fd );
2469                         fd = -1;
2470                         p_tls = NULL;
2471                         continue;
2472
2473                     case 1: /* missing input - most likely */
2474                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2475                         break;
2476
2477                     case 2: /* missing output */
2478                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2479                         break;
2480                 }
2481             }
2482             else
2483                 p_tls = NULL;
2484
2485             cl = httpd_ClientNew( fd, p_tls, now );
2486             vlc_mutex_lock( &host->lock );
2487             TAB_APPEND( host->i_client, host->client, cl );
2488             vlc_mutex_unlock( &host->lock );
2489             if( i_state != -1 )
2490                 cl->i_state = i_state; // override state for TLS
2491         }
2492
2493     }
2494
2495     return NULL;
2496 }