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