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