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