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