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