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