]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Improved recognition of selected bookmarks for deletion.
[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 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
896 httpd_host_t *vlc_rtsp_HostNew(vlc_object_t *p_this)
897 {
898     return httpd_HostCreate(p_this, "rtsp-host", "rtsp-port", NULL);
899 }
900
901 static struct httpd
902 {
903     vlc_mutex_t  mutex;
904
905     httpd_host_t **host;
906     int          i_host;
907 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
908
909 static httpd_host_t *httpd_HostCreate(vlc_object_t *p_this,
910                                        const char *hostvar,
911                                        const char *portvar,
912                                        vlc_tls_creds_t *p_tls)
913 {
914     httpd_host_t *host;
915     char *hostname = var_InheritString(p_this, hostvar);
916     unsigned port = var_InheritInteger(p_this, portvar);
917
918     vlc_url_t url;
919     vlc_UrlParse(&url, hostname, 0);
920     free(hostname);
921     if (url.i_port != 0) {
922         msg_Err(p_this, "Ignoring port %d (using %d)", url.i_port, port);
923         msg_Info(p_this, "Specify port %d separately with the "
924                           "%s option instead.", url.i_port, portvar);
925     }
926
927     /* to be sure to avoid multiple creation */
928     vlc_mutex_lock(&httpd.mutex);
929
930     /* verify if it already exist */
931     for (int i = 0; i < httpd.i_host; i++) {
932         host = httpd.host[i];
933
934         /* cannot mix TLS and non-TLS hosts */
935         if (host->port != port
936          || (host->p_tls != NULL) != (p_tls != NULL))
937             continue;
938
939         /* Increase existing matching host reference count.
940          * The reference count is written under both the global httpd and the
941          * host lock. It is read with either or both locks held. The global
942          * lock is always acquired first. */
943         vlc_mutex_lock(&host->lock);
944         host->i_ref++;
945         vlc_mutex_unlock(&host->lock);
946
947         vlc_mutex_unlock(&httpd.mutex);
948         vlc_UrlClean(&url);
949         vlc_tls_Delete(p_tls);
950         return host;
951     }
952
953     /* create the new host */
954     host = (httpd_host_t *)vlc_custom_create(p_this, sizeof (*host),
955                                               "http host");
956     if (!host)
957         goto error;
958
959     vlc_mutex_init(&host->lock);
960     vlc_cond_init(&host->wait);
961     host->i_ref = 1;
962
963     host->fds = net_ListenTCP(p_this, url.psz_host, port);
964     if (!host->fds) {
965         msg_Err(p_this, "cannot create socket(s) for HTTP host");
966         goto error;
967     }
968     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
969
970     if (vlc_object_waitpipe(VLC_OBJECT(host)) == -1) {
971         msg_Err(host, "signaling pipe error: %s", vlc_strerror_c(errno));
972         goto error;
973     }
974
975     host->port     = port;
976     host->i_url    = 0;
977     host->url      = NULL;
978     host->i_client = 0;
979     host->client   = NULL;
980     host->p_tls    = p_tls;
981
982     /* create the thread */
983     if (vlc_clone(&host->thread, httpd_HostThread, host,
984                    VLC_THREAD_PRIORITY_LOW)) {
985         msg_Err(p_this, "cannot spawn http host thread");
986         goto error;
987     }
988
989     /* now add it to httpd */
990     TAB_APPEND(httpd.i_host, httpd.host, host);
991     vlc_mutex_unlock(&httpd.mutex);
992
993     vlc_UrlClean(&url);
994
995     return host;
996
997 error:
998     vlc_mutex_unlock(&httpd.mutex);
999
1000     if (host) {
1001         net_ListenClose(host->fds);
1002         vlc_cond_destroy(&host->wait);
1003         vlc_mutex_destroy(&host->lock);
1004         vlc_object_release(host);
1005     }
1006
1007     vlc_UrlClean(&url);
1008     vlc_tls_Delete(p_tls);
1009     return NULL;
1010 }
1011
1012 /* delete a host */
1013 void httpd_HostDelete(httpd_host_t *host)
1014 {
1015     bool delete = false;
1016
1017     vlc_mutex_lock(&httpd.mutex);
1018
1019     vlc_mutex_lock(&host->lock);
1020     host->i_ref--;
1021     if (host->i_ref == 0)
1022         delete = true;
1023     vlc_mutex_unlock(&host->lock);
1024     if (!delete) {
1025         /* still used */
1026         vlc_mutex_unlock(&httpd.mutex);
1027         msg_Dbg(host, "httpd_HostDelete: host still in use");
1028         return;
1029     }
1030     TAB_REMOVE(httpd.i_host, httpd.host, host);
1031
1032     vlc_cancel(host->thread);
1033     vlc_join(host->thread, NULL);
1034
1035     msg_Dbg(host, "HTTP host removed");
1036
1037     for (int i = 0; i < host->i_url; i++)
1038         msg_Err(host, "url still registered: %s", host->url[i]->psz_url);
1039
1040     for (int i = 0; i < host->i_client; i++) {
1041         httpd_client_t *cl = host->client[i];
1042         msg_Warn(host, "client still connected");
1043         httpd_ClientClean(cl);
1044         TAB_REMOVE(host->i_client, host->client, cl);
1045         free(cl);
1046         i--;
1047         /* TODO */
1048     }
1049
1050     vlc_tls_Delete(host->p_tls);
1051     net_ListenClose(host->fds);
1052     vlc_cond_destroy(&host->wait);
1053     vlc_mutex_destroy(&host->lock);
1054     vlc_object_release(host);
1055     vlc_mutex_unlock(&httpd.mutex);
1056 }
1057
1058 /* register a new url */
1059 httpd_url_t *httpd_UrlNew(httpd_host_t *host, const char *psz_url,
1060                            const char *psz_user, const char *psz_password)
1061 {
1062     httpd_url_t *url;
1063
1064     assert(psz_url);
1065
1066     vlc_mutex_lock(&host->lock);
1067     for (int i = 0; i < host->i_url; i++)
1068         if (!strcmp(psz_url, host->url[i]->psz_url)) {
1069             msg_Warn(host, "cannot add '%s' (url already defined)", psz_url);
1070             vlc_mutex_unlock(&host->lock);
1071             return NULL;
1072         }
1073
1074     url = xmalloc(sizeof(httpd_url_t));
1075     url->host = host;
1076
1077     vlc_mutex_init(&url->lock);
1078     url->psz_url = xstrdup(psz_url);
1079     url->psz_user = xstrdup(psz_user ? psz_user : "");
1080     url->psz_password = xstrdup(psz_password ? psz_password : "");
1081     for (int i = 0; i < HTTPD_MSG_MAX; i++) {
1082         url->catch[i].cb = NULL;
1083         url->catch[i].p_sys = NULL;
1084     }
1085
1086     TAB_APPEND(host->i_url, host->url, url);
1087     vlc_cond_signal(&host->wait);
1088     vlc_mutex_unlock(&host->lock);
1089
1090     return url;
1091 }
1092
1093 /* register callback on a url */
1094 int httpd_UrlCatch(httpd_url_t *url, int i_msg, httpd_callback_t cb,
1095                     httpd_callback_sys_t *p_sys)
1096 {
1097     vlc_mutex_lock(&url->lock);
1098     url->catch[i_msg].cb   = cb;
1099     url->catch[i_msg].p_sys= p_sys;
1100     vlc_mutex_unlock(&url->lock);
1101
1102     return VLC_SUCCESS;
1103 }
1104
1105 /* delete a url */
1106 void httpd_UrlDelete(httpd_url_t *url)
1107 {
1108     httpd_host_t *host = url->host;
1109
1110     vlc_mutex_lock(&host->lock);
1111     TAB_REMOVE(host->i_url, host->url, url);
1112
1113     vlc_mutex_destroy(&url->lock);
1114     free(url->psz_url);
1115     free(url->psz_user);
1116     free(url->psz_password);
1117
1118     for (int i = 0; i < host->i_client; i++) {
1119         httpd_client_t *client = host->client[i];
1120
1121         if (client->url != url)
1122             continue;
1123
1124         /* TODO complete it */
1125         msg_Warn(host, "force closing connections");
1126         httpd_ClientClean(client);
1127         TAB_REMOVE(host->i_client, host->client, client);
1128         free(client);
1129         i--;
1130     }
1131     free(url);
1132     vlc_mutex_unlock(&host->lock);
1133 }
1134
1135 static void httpd_MsgInit(httpd_message_t *msg)
1136 {
1137     msg->cl         = NULL;
1138     msg->i_type     = HTTPD_MSG_NONE;
1139     msg->i_proto    = HTTPD_PROTO_NONE;
1140     msg->i_version  = -1; /* FIXME */
1141
1142     msg->i_status   = 0;
1143
1144     msg->psz_url    = NULL;
1145     msg->psz_args   = NULL;
1146
1147     msg->i_headers  = 0;
1148     msg->p_headers  = NULL;
1149
1150     msg->i_body_offset = 0;
1151     msg->i_body        = 0;
1152     msg->p_body        = NULL;
1153 }
1154
1155 static void httpd_MsgClean(httpd_message_t *msg)
1156 {
1157     free(msg->psz_url);
1158     free(msg->psz_args);
1159     for (size_t i = 0; i < msg->i_headers; i++) {
1160         free(msg->p_headers[i].name);
1161         free(msg->p_headers[i].value);
1162     }
1163     free(msg->p_headers);
1164     free(msg->p_body);
1165     httpd_MsgInit(msg);
1166 }
1167
1168 const char *httpd_MsgGet(const httpd_message_t *msg, const char *name)
1169 {
1170     for (size_t i = 0; i < msg->i_headers; i++)
1171         if (!strcasecmp(msg->p_headers[i].name, name))
1172             return msg->p_headers[i].value;
1173     return NULL;
1174 }
1175
1176 void httpd_MsgAdd(httpd_message_t *msg, const char *name, const char *psz_value, ...)
1177 {
1178     httpd_header *p_tmp = realloc(msg->p_headers, sizeof(httpd_header) * (msg->i_headers + 1));
1179     if (!p_tmp)
1180         return;
1181
1182     msg->p_headers = p_tmp;
1183
1184     httpd_header *h = &msg->p_headers[msg->i_headers];
1185     h->name = strdup(name);
1186     if (!h->name)
1187         return;
1188
1189     h->value = NULL;
1190
1191     va_list args;
1192     va_start(args, psz_value);
1193     int ret = us_vasprintf(&h->value, psz_value, args);
1194     va_end(args);
1195
1196     if (ret == -1) {
1197         free(h->name);
1198         return;
1199     }
1200
1201     msg->i_headers++;
1202 }
1203
1204 static void httpd_ClientInit(httpd_client_t *cl, mtime_t now)
1205 {
1206     cl->i_state = HTTPD_CLIENT_RECEIVING;
1207     cl->i_activity_date = now;
1208     cl->i_activity_timeout = INT64_C(10000000);
1209     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1210     cl->i_buffer = 0;
1211     cl->p_buffer = xmalloc(cl->i_buffer_size);
1212     cl->i_keyframe_wait_to_pass = -1;
1213     cl->b_stream_mode = false;
1214
1215     httpd_MsgInit(&cl->query);
1216     httpd_MsgInit(&cl->answer);
1217 }
1218
1219 char* httpd_ClientIP(const httpd_client_t *cl, char *ip, int *port)
1220 {
1221     return net_GetPeerAddress(cl->fd, ip, port) ? NULL : ip;
1222 }
1223
1224 char* httpd_ServerIP(const httpd_client_t *cl, char *ip, int *port)
1225 {
1226     return net_GetSockAddress(cl->fd, ip, port) ? NULL : ip;
1227 }
1228
1229 static void httpd_ClientClean(httpd_client_t *cl)
1230 {
1231     if (cl->fd >= 0) {
1232         if (cl->p_tls)
1233             vlc_tls_SessionDelete(cl->p_tls);
1234         net_Close(cl->fd);
1235         cl->fd = -1;
1236     }
1237
1238     httpd_MsgClean(&cl->answer);
1239     httpd_MsgClean(&cl->query);
1240
1241     free(cl->p_buffer);
1242     cl->p_buffer = NULL;
1243 }
1244
1245 static httpd_client_t *httpd_ClientNew(int fd, vlc_tls_t *p_tls, mtime_t now)
1246 {
1247     httpd_client_t *cl = malloc(sizeof(httpd_client_t));
1248
1249     if (!cl) return NULL;
1250
1251     cl->i_ref   = 0;
1252     cl->fd      = fd;
1253     cl->url     = NULL;
1254     cl->p_tls = p_tls;
1255
1256     httpd_ClientInit(cl, now);
1257     if (p_tls)
1258         cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1259
1260     return cl;
1261 }
1262
1263 static
1264 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1265 {
1266     vlc_tls_t *p_tls;
1267     ssize_t val;
1268
1269     p_tls = cl->p_tls;
1270     do
1271         val = p_tls ? tls_Recv (p_tls, p, i_len)
1272                     : recv (cl->fd, p, i_len, 0);
1273     while (val == -1 && errno == EINTR);
1274     return val;
1275 }
1276
1277 static
1278 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1279 {
1280     vlc_tls_t *p_tls;
1281     ssize_t val;
1282
1283     p_tls = cl->p_tls;
1284     do
1285         val = p_tls ? tls_Send(p_tls, p, i_len)
1286                     : send (cl->fd, p, i_len, 0);
1287     while (val == -1 && errno == EINTR);
1288     return val;
1289 }
1290
1291
1292 static const struct
1293 {
1294     const char name[16];
1295     int  i_type;
1296     int  i_proto;
1297 }
1298 msg_type[] =
1299 {
1300     { "OPTIONS",       HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1301     { "DESCRIBE",      HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1302     { "SETUP",         HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1303     { "PLAY",          HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1304     { "PAUSE",         HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1305     { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1306     { "TEARDOWN",      HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1307     { "GET",           HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1308     { "HEAD",          HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1309     { "POST",          HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1310     { "",              HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1311 };
1312
1313
1314 static void httpd_ClientRecv(httpd_client_t *cl)
1315 {
1316     int i_len;
1317
1318     /* ignore leading whites */
1319     if (cl->query.i_proto == HTTPD_PROTO_NONE && cl->i_buffer == 0) {
1320         unsigned char c;
1321
1322         i_len = httpd_NetRecv(cl, &c, 1);
1323
1324         if (i_len > 0 && !strchr("\r\n\t ", c)) {
1325             cl->p_buffer[0] = c;
1326             cl->i_buffer++;
1327         }
1328     } else if (cl->query.i_proto == HTTPD_PROTO_NONE) {
1329         /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1330         i_len = httpd_NetRecv(cl, &cl->p_buffer[cl->i_buffer],
1331                                7 - cl->i_buffer);
1332         if (i_len > 0)
1333             cl->i_buffer += i_len;
1334
1335         /* The smallest legal request is 7 bytes ("GET /\r\n"),
1336          * this is the maximum we can ask at this point. */
1337         if (cl->i_buffer >= 7) {
1338             if (!memcmp(cl->p_buffer, "HTTP/1.", 7)) {
1339                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1340                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1341             } else if (!memcmp(cl->p_buffer, "RTSP/1.", 7)) {
1342                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1343                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1344             } else {
1345                 /* We need the full request line to determine the protocol. */
1346                 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1347                 cl->query.i_type  = HTTPD_MSG_NONE;
1348             }
1349         }
1350     } else if (cl->query.i_body > 0) {
1351         /* we are reading the body of a request or a channel */
1352         assert (cl->query.p_body != NULL);
1353         i_len = httpd_NetRecv(cl, &cl->query.p_body[cl->i_buffer],
1354                                cl->query.i_body - cl->i_buffer);
1355         if (i_len > 0)
1356             cl->i_buffer += i_len;
1357
1358         if (cl->i_buffer >= cl->query.i_body)
1359             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1360     } else for (;;) { /* we are reading a header -> char by char */
1361         if (cl->i_buffer == cl->i_buffer_size) {
1362             uint8_t *newbuf = realloc(cl->p_buffer, cl->i_buffer_size + 1024);
1363             if (!newbuf) {
1364                 i_len = 0;
1365                 break;
1366             }
1367
1368             cl->p_buffer = newbuf;
1369             cl->i_buffer_size += 1024;
1370         }
1371
1372         i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1);
1373         if (i_len <= 0)
1374             break;
1375
1376         cl->i_buffer++;
1377
1378         if ((cl->query.i_proto == HTTPD_PROTO_HTTP0)
1379                 && (cl->p_buffer[cl->i_buffer - 1] == '\n'))
1380         {
1381             /* Request line is now complete */
1382             const char *p = memchr(cl->p_buffer, ' ', cl->i_buffer);
1383             size_t len;
1384
1385             assert(cl->query.i_type == HTTPD_MSG_NONE);
1386
1387             if (!p) { /* no URI: evil guy */
1388                 i_len = 0; /* drop connection */
1389                 break;
1390             }
1391
1392             do
1393                 p++; /* skips extra spaces */
1394             while (*p == ' ');
1395
1396             p = memchr(p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p);
1397             if (!p) { /* no explicit protocol: HTTP/0.9 */
1398                 i_len = 0; /* not supported currently -> drop */
1399                 break;
1400             }
1401
1402             do
1403                 p++; /* skips extra spaces ever again */
1404             while (*p == ' ');
1405
1406             len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1407             if (len < 7) /* foreign protocol */
1408                 i_len = 0; /* I don't understand -> drop */
1409             else if (!memcmp(p, "HTTP/1.", 7)) {
1410                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1411                 cl->query.i_version = atoi(p + 7);
1412             } else if (!memcmp(p, "RTSP/1.", 7)) {
1413                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1414                 cl->query.i_version = atoi(p + 7);
1415             } else if (!memcmp(p, "HTTP/", 5)) {
1416                 const uint8_t sorry[] =
1417                     "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1418                 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1419                 i_len = 0; /* drop */
1420             } else if (!memcmp(p, "RTSP/", 5)) {
1421                 const uint8_t sorry[] =
1422                     "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1423                 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1424                 i_len = 0; /* drop */
1425             } else /* yet another foreign protocol */
1426                 i_len = 0;
1427
1428             if (i_len == 0)
1429                 break;
1430         }
1431
1432         if ((cl->i_buffer >= 2 && !memcmp(&cl->p_buffer[cl->i_buffer-2], "\n\n", 2))||
1433                 (cl->i_buffer >= 4 && !memcmp(&cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4)))
1434         {
1435             char *p;
1436
1437             /* we have finished the header so parse it and set i_body */
1438             cl->p_buffer[cl->i_buffer] = '\0';
1439
1440             if (cl->query.i_type == HTTPD_MSG_ANSWER) {
1441                 /* FIXME:
1442                  * assume strlen("HTTP/1.x") = 8
1443                  */
1444                 cl->query.i_status =
1445                     strtol((char *)&cl->p_buffer[8],
1446                             &p, 0);
1447                 while (*p == ' ')
1448                     p++;
1449             } else {
1450                 p = NULL;
1451                 cl->query.i_type = HTTPD_MSG_NONE;
1452
1453                 for (unsigned i = 0; msg_type[i].name[0]; i++)
1454                     if (!strncmp((char *)cl->p_buffer, msg_type[i].name,
1455                                 strlen(msg_type[i].name))) {
1456                         p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1457                         cl->query.i_type = msg_type[i].i_type;
1458                         if (cl->query.i_proto != msg_type[i].i_proto) {
1459                             p = NULL;
1460                             cl->query.i_proto = HTTPD_PROTO_NONE;
1461                             cl->query.i_type = HTTPD_MSG_NONE;
1462                         }
1463                         break;
1464                     }
1465
1466                 if (!p) {
1467                     if (strstr((char *)cl->p_buffer, "HTTP/1."))
1468                         cl->query.i_proto = HTTPD_PROTO_HTTP;
1469                     else if (strstr((char *)cl->p_buffer, "RTSP/1."))
1470                         cl->query.i_proto = HTTPD_PROTO_RTSP;
1471                 } else {
1472                     char *p2;
1473                     char *p3;
1474
1475                     while (*p == ' ')
1476                         p++;
1477
1478                     p2 = strchr(p, ' ');
1479                     if (p2)
1480                         *p2++ = '\0';
1481
1482                     if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "http:" : "rtsp:", 5)) {
1483                         /* Skip hier-part of URL (if present) */
1484                         p += 5;
1485                         if (!strncmp(p, "//", 2)) { /* skip authority */
1486                             /* see RFC3986 §3.2 */
1487                             p += 2;
1488                             p += strcspn(p, "/?#");
1489                         }
1490                     }
1491                     else if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "https:" : "rtsps:", 6)) {
1492                         /* Skip hier-part of URL (if present) */
1493                         p += 6;
1494                         if (!strncmp(p, "//", 2)) { /* skip authority */
1495                             /* see RFC3986 §3.2 */
1496                             p += 2;
1497                             p += strcspn(p, "/?#");
1498                         }
1499                     }
1500
1501                     cl->query.psz_url = strdup(p);
1502                     if ((p3 = strchr(cl->query.psz_url, '?')) ) {
1503                         *p3++ = '\0';
1504                         cl->query.psz_args = (uint8_t *)strdup(p3);
1505                     }
1506                     p = p2;
1507                 }
1508             }
1509             if (p)
1510                 p = strchr(p, '\n');
1511
1512             if (p) {
1513                 while (*p == '\n' || *p == '\r')
1514                     p++;
1515
1516                 while (p && *p) {
1517                     char *line = p;
1518                     char *eol = p = strchr(p, '\n');
1519                     char *colon;
1520
1521                     while (eol && eol >= line && (*eol == '\n' || *eol == '\r'))
1522                         *eol-- = '\0';
1523
1524                     if ((colon = strchr(line, ':'))) {
1525                         *colon++ = '\0';
1526                         while (*colon == ' ')
1527                             colon++;
1528                         httpd_MsgAdd(&cl->query, line, "%s", colon);
1529
1530                         if (!strcasecmp(line, "Content-Length"))
1531                             cl->query.i_body = atol(colon);
1532                     }
1533
1534                     if (p) {
1535                         p++;
1536                         while (*p == '\n' || *p == '\r')
1537                             p++;
1538                     }
1539                 }
1540             }
1541             if (cl->query.i_body > 0) {
1542                 /* TODO Mhh, handle the case where the client only
1543                  * sends a request and closes the connection to
1544                  * mark the end of the body (probably only RTSP) */
1545                 if (cl->query.i_body >= 65536)
1546                     cl->query.p_body = malloc(cl->query.i_body);
1547                 else
1548                     cl->query.p_body = NULL;
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[] = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1554                             httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1555                             break;
1556                         }
1557                         case HTTPD_PROTO_RTSP: {
1558                             const uint8_t sorry[] = "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1559                             httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1560                             break;
1561                         }
1562                         default:
1563                             vlc_assert_unreachable();
1564                     }
1565                     i_len = 0; /* drop */
1566                 }
1567                 break;
1568             } else
1569                 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1570         }
1571     }
1572
1573     /* check if the client is to be set to dead */
1574 #if defined(_WIN32)
1575     if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1576 #else
1577     if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1578 #endif
1579     {
1580         if (cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE) {
1581             /* connection closed -> end of data */
1582             if (cl->query.i_body > 0)
1583                 cl->query.i_body = cl->i_buffer;
1584             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1585         }
1586         else
1587             cl->i_state = HTTPD_CLIENT_DEAD;
1588     }
1589
1590     /* XXX: for QT I have to disable timeout. Try to find why */
1591     if (cl->query.i_proto == HTTPD_PROTO_RTSP)
1592         cl->i_activity_timeout = 0;
1593 }
1594
1595 static void httpd_ClientSend(httpd_client_t *cl)
1596 {
1597     int i_len;
1598
1599     if (cl->i_buffer < 0) {
1600         /* We need to create the header */
1601         int i_size = 0;
1602         char *p;
1603         const char *psz_status = httpd_ReasonFromCode(cl->answer.i_status);
1604
1605         i_size = strlen("HTTP/1.") + 10 + 10 + strlen(psz_status) + 5;
1606         for (size_t i = 0; i < cl->answer.i_headers; i++)
1607             i_size += strlen(cl->answer.p_headers[i].name) + 2 +
1608                       strlen(cl->answer.p_headers[i].value) + 2;
1609
1610         if (cl->i_buffer_size < i_size) {
1611             cl->i_buffer_size = i_size;
1612             free(cl->p_buffer);
1613             cl->p_buffer = xmalloc(i_size);
1614         }
1615         p = (char *)cl->p_buffer;
1616
1617         p += sprintf(p, "%s.%u %d %s\r\n",
1618                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1619                       cl->answer.i_version,
1620                       cl->answer.i_status, psz_status);
1621         for (size_t i = 0; i < cl->answer.i_headers; i++)
1622             p += sprintf(p, "%s: %s\r\n", cl->answer.p_headers[i].name,
1623                           cl->answer.p_headers[i].value);
1624         p += sprintf(p, "\r\n");
1625
1626         cl->i_buffer = 0;
1627         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1628     }
1629
1630     i_len = httpd_NetSend(cl, &cl->p_buffer[cl->i_buffer],
1631                            cl->i_buffer_size - cl->i_buffer);
1632     if (i_len >= 0) {
1633         cl->i_buffer += i_len;
1634
1635         if (cl->i_buffer >= cl->i_buffer_size) {
1636             if (cl->answer.i_body == 0  && cl->answer.i_body_offset > 0) {
1637                 /* catch more body data */
1638                 int     i_msg = cl->query.i_type;
1639                 int64_t i_offset = cl->answer.i_body_offset;
1640
1641                 httpd_MsgClean(&cl->answer);
1642                 cl->answer.i_body_offset = i_offset;
1643
1644                 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1645                                           &cl->answer, &cl->query);
1646             }
1647
1648             if (cl->answer.i_body > 0) {
1649                 /* send the body data */
1650                 free(cl->p_buffer);
1651                 cl->p_buffer = cl->answer.p_body;
1652                 cl->i_buffer_size = cl->answer.i_body;
1653                 cl->i_buffer = 0;
1654
1655                 cl->answer.i_body = 0;
1656                 cl->answer.p_body = NULL;
1657             } else /* send finished */
1658                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1659         }
1660     } else {
1661 #if defined(_WIN32)
1662         if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1663 #else
1664         if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1665 #endif
1666         {
1667             /* error */
1668             cl->i_state = HTTPD_CLIENT_DEAD;
1669         }
1670     }
1671 }
1672
1673 static void httpd_ClientTlsHandshake(httpd_client_t *cl)
1674 {
1675     switch (vlc_tls_SessionHandshake(cl->p_tls, NULL, NULL, NULL))
1676     {
1677         case -1: cl->i_state = HTTPD_CLIENT_DEAD;       break;
1678         case 0:  cl->i_state = HTTPD_CLIENT_RECEIVING;  break;
1679         case 1:  cl->i_state = HTTPD_CLIENT_TLS_HS_IN;  break;
1680         case 2:  cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1681     }
1682 }
1683
1684 static bool httpdAuthOk(const char *user, const char *pass, const char *b64)
1685 {
1686     if (!*user && !*pass)
1687         return true;
1688
1689     if (!b64)
1690         return false;
1691
1692     if (strncasecmp(b64, "BASIC", 5))
1693         return false;
1694
1695     b64 += 5;
1696     while (*b64 == ' ')
1697         b64++;
1698
1699     char *given_user = vlc_b64_decode(b64);
1700     if (!given_user)
1701         return false;
1702
1703     char *given_pass = NULL;
1704     given_pass = strchr (given_user, ':');
1705     if (!given_pass)
1706         goto auth_failed;
1707
1708     *given_pass++ = '\0';
1709
1710     if (strcmp (given_user, user))
1711         goto auth_failed;
1712
1713     if (strcmp (given_pass, pass))
1714         goto auth_failed;
1715
1716     free(given_user);
1717     return true;
1718
1719 auth_failed:
1720     free(given_user);
1721     return false;
1722 }
1723
1724 static void httpdLoop(httpd_host_t *host)
1725 {
1726     struct pollfd ufd[host->nfd + host->i_client];
1727     unsigned nfd;
1728     for (nfd = 0; nfd < host->nfd; nfd++) {
1729         ufd[nfd].fd = host->fds[nfd];
1730         ufd[nfd].events = POLLIN;
1731         ufd[nfd].revents = 0;
1732     }
1733
1734     /* add all socket that should be read/write and close dead connection */
1735     while (host->i_url <= 0) {
1736         mutex_cleanup_push(&host->lock);
1737         vlc_cond_wait(&host->wait, &host->lock);
1738         vlc_cleanup_pop();
1739     }
1740
1741     mtime_t now = mdate();
1742     bool b_low_delay = false;
1743
1744     int canc = vlc_savecancel();
1745     for (int i_client = 0; i_client < host->i_client; i_client++) {
1746         int64_t i_offset;
1747         httpd_client_t *cl = host->client[i_client];
1748         if (cl->i_ref < 0 || (cl->i_ref == 0 &&
1749                     (cl->i_state == HTTPD_CLIENT_DEAD ||
1750                       (cl->i_activity_timeout > 0 &&
1751                         cl->i_activity_date+cl->i_activity_timeout < now)))) {
1752             httpd_ClientClean(cl);
1753             TAB_REMOVE(host->i_client, host->client, cl);
1754             free(cl);
1755             i_client--;
1756             continue;
1757         }
1758
1759         struct pollfd *pufd = ufd + nfd;
1760         assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1761
1762         pufd->fd = cl->fd;
1763         pufd->events = pufd->revents = 0;
1764
1765         switch (cl->i_state) {
1766             case HTTPD_CLIENT_RECEIVING:
1767             case HTTPD_CLIENT_TLS_HS_IN:
1768                 pufd->events = POLLIN;
1769                 break;
1770
1771             case HTTPD_CLIENT_SENDING:
1772             case HTTPD_CLIENT_TLS_HS_OUT:
1773                 pufd->events = POLLOUT;
1774                 break;
1775
1776             case HTTPD_CLIENT_RECEIVE_DONE: {
1777                 httpd_message_t *answer = &cl->answer;
1778                 httpd_message_t *query  = &cl->query;
1779
1780                 httpd_MsgInit(answer);
1781
1782                 /* Handle what we received */
1783                 switch (query->i_type) {
1784                     case HTTPD_MSG_ANSWER:
1785                         cl->url     = NULL;
1786                         cl->i_state = HTTPD_CLIENT_DEAD;
1787                         break;
1788
1789                     case HTTPD_MSG_OPTIONS:
1790                         answer->i_type   = HTTPD_MSG_ANSWER;
1791                         answer->i_proto  = query->i_proto;
1792                         answer->i_status = 200;
1793                         answer->i_body = 0;
1794                         answer->p_body = NULL;
1795
1796                         httpd_MsgAdd(answer, "Server", "VLC/%s", VERSION);
1797                         httpd_MsgAdd(answer, "Content-Length", "0");
1798
1799                         switch(query->i_proto) {
1800                         case HTTPD_PROTO_HTTP:
1801                             answer->i_version = 1;
1802                             httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
1803                             break;
1804
1805                         case HTTPD_PROTO_RTSP:
1806                             answer->i_version = 0;
1807
1808                             const char *p = httpd_MsgGet(query, "Cseq");
1809                             if (p)
1810                                 httpd_MsgAdd(answer, "Cseq", "%s", p);
1811                             p = httpd_MsgGet(query, "Timestamp");
1812                             if (p)
1813                                 httpd_MsgAdd(answer, "Timestamp", "%s", p);
1814
1815                             p = httpd_MsgGet(query, "Require");
1816                             if (p) {
1817                                 answer->i_status = 551;
1818                                 httpd_MsgAdd(query, "Unsupported", "%s", p);
1819                             }
1820
1821                             httpd_MsgAdd(answer, "Public", "DESCRIBE,SETUP,"
1822                                     "TEARDOWN,PLAY,PAUSE,GET_PARAMETER");
1823                             break;
1824                         }
1825
1826                         cl->i_buffer = -1;  /* Force the creation of the answer in
1827                                              * httpd_ClientSend */
1828                         cl->i_state = HTTPD_CLIENT_SENDING;
1829                         break;
1830
1831                     case HTTPD_MSG_NONE:
1832                         if (query->i_proto == HTTPD_PROTO_NONE) {
1833                             cl->url = NULL;
1834                             cl->i_state = HTTPD_CLIENT_DEAD;
1835                         } else {
1836                             /* unimplemented */
1837                             answer->i_proto  = query->i_proto ;
1838                             answer->i_type   = HTTPD_MSG_ANSWER;
1839                             answer->i_version= 0;
1840                             answer->i_status = 501;
1841
1842                             char *p;
1843                             answer->i_body = httpd_HtmlError (&p, 501, NULL);
1844                             answer->p_body = (uint8_t *)p;
1845                             httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1846
1847                             cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
1848                             cl->i_state = HTTPD_CLIENT_SENDING;
1849                         }
1850                         break;
1851
1852                     default: {
1853                         int i_msg = query->i_type;
1854                         bool b_auth_failed = false;
1855
1856                         /* Search the url and trigger callbacks */
1857                         for (int i = 0; i < host->i_url; i++) {
1858                             httpd_url_t *url = host->url[i];
1859
1860                             if (strcmp(url->psz_url, query->psz_url))
1861                                 continue;
1862                             if (!url->catch[i_msg].cb)
1863                                 continue;
1864
1865                             if (answer) {
1866                                 b_auth_failed = !httpdAuthOk(url->psz_user,
1867                                    url->psz_password,
1868                                    httpd_MsgGet(query, "Authorization")); /* BASIC id */
1869                                 if (b_auth_failed)
1870                                    break;
1871                             }
1872
1873                             if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
1874                                 continue;
1875
1876                             if (answer->i_proto == HTTPD_PROTO_NONE)
1877                                 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
1878                             else
1879                                 cl->i_buffer = -1;
1880
1881                             /* only one url can answer */
1882                             answer = NULL;
1883                             if (!cl->url)
1884                                 cl->url = url;
1885                         }
1886
1887                         if (answer) {
1888                             answer->i_proto  = query->i_proto;
1889                             answer->i_type   = HTTPD_MSG_ANSWER;
1890                             answer->i_version= 0;
1891
1892                            if (b_auth_failed) {
1893                                 httpd_MsgAdd(answer, "WWW-Authenticate",
1894                                         "Basic realm=\"VLC stream\"");
1895                                 answer->i_status = 401;
1896                             } else
1897                                 answer->i_status = 404; /* no url registered */
1898
1899                             char *p;
1900                             answer->i_body = httpd_HtmlError (&p, answer->i_status,
1901                                     query->psz_url);
1902                             answer->p_body = (uint8_t *)p;
1903
1904                             cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
1905                             httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1906                             httpd_MsgAdd(answer, "Content-Type", "%s", "text/html");
1907                         }
1908
1909                         cl->i_state = HTTPD_CLIENT_SENDING;
1910                     }
1911                 }
1912                 break;
1913             }
1914
1915             case HTTPD_CLIENT_SEND_DONE:
1916                 if (!cl->b_stream_mode || cl->answer.i_body_offset == 0) {
1917                     const char *psz_connection = httpd_MsgGet(&cl->answer, "Connection");
1918                     const char *psz_query = httpd_MsgGet(&cl->query, "Connection");
1919                     bool b_connection = false;
1920                     bool b_keepalive = false;
1921                     bool b_query = false;
1922
1923                     cl->url = NULL;
1924                     if (psz_connection) {
1925                         b_connection = (strcasecmp(psz_connection, "Close") == 0);
1926                         b_keepalive = (strcasecmp(psz_connection, "Keep-Alive") == 0);
1927                     }
1928
1929                     if (psz_query)
1930                         b_query = (strcasecmp(psz_query, "Close") == 0);
1931
1932                     if (((cl->query.i_proto == HTTPD_PROTO_HTTP) &&
1933                                 ((cl->query.i_version == 0 && b_keepalive) ||
1934                                   (cl->query.i_version == 1 && !b_connection))) ||
1935                             ((cl->query.i_proto == HTTPD_PROTO_RTSP) &&
1936                               !b_query && !b_connection)) {
1937                         httpd_MsgClean(&cl->query);
1938                         httpd_MsgInit(&cl->query);
1939
1940                         cl->i_buffer = 0;
1941                         cl->i_buffer_size = 1000;
1942                         free(cl->p_buffer);
1943                         cl->p_buffer = xmalloc(cl->i_buffer_size);
1944                         cl->i_state = HTTPD_CLIENT_RECEIVING;
1945                     } else
1946                         cl->i_state = HTTPD_CLIENT_DEAD;
1947                     httpd_MsgClean(&cl->answer);
1948                 } else {
1949                     i_offset = cl->answer.i_body_offset;
1950                     httpd_MsgClean(&cl->answer);
1951
1952                     cl->answer.i_body_offset = i_offset;
1953                     free(cl->p_buffer);
1954                     cl->p_buffer = NULL;
1955                     cl->i_buffer = 0;
1956                     cl->i_buffer_size = 0;
1957
1958                     cl->i_state = HTTPD_CLIENT_WAITING;
1959                 }
1960                 break;
1961
1962             case HTTPD_CLIENT_WAITING:
1963                 i_offset = cl->answer.i_body_offset;
1964                 int i_msg = cl->query.i_type;
1965
1966                 httpd_MsgInit(&cl->answer);
1967                 cl->answer.i_body_offset = i_offset;
1968
1969                 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1970                         &cl->answer, &cl->query);
1971                 if (cl->answer.i_type != HTTPD_MSG_NONE) {
1972                     /* we have new data, so re-enter send mode */
1973                     cl->i_buffer      = 0;
1974                     cl->p_buffer      = cl->answer.p_body;
1975                     cl->i_buffer_size = cl->answer.i_body;
1976                     cl->answer.p_body = NULL;
1977                     cl->answer.i_body = 0;
1978                     cl->i_state = HTTPD_CLIENT_SENDING;
1979                 }
1980         }
1981
1982         if (pufd->events != 0)
1983             nfd++;
1984         else
1985             b_low_delay = true;
1986     }
1987     vlc_mutex_unlock(&host->lock);
1988     vlc_restorecancel(canc);
1989
1990     /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
1991     int ret = poll(ufd, nfd, b_low_delay ? 20 : -1);
1992
1993     canc = vlc_savecancel();
1994     vlc_mutex_lock(&host->lock);
1995     switch(ret) {
1996         case -1:
1997             if (errno != EINTR) {
1998                 /* Kernel on low memory or a bug: pace */
1999                 msg_Err(host, "polling error: %s", vlc_strerror_c(errno));
2000                 msleep(100000);
2001             }
2002         case 0:
2003             vlc_restorecancel(canc);
2004             return;
2005     }
2006
2007     /* Handle client sockets */
2008     now = mdate();
2009     nfd = host->nfd;
2010
2011     for (int i_client = 0; i_client < host->i_client; i_client++) {
2012         httpd_client_t *cl = host->client[i_client];
2013         const struct pollfd *pufd = &ufd[nfd];
2014
2015         assert(pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])]);
2016
2017         if (cl->fd != pufd->fd)
2018             continue; // we were not waiting for this client
2019         ++nfd;
2020         if (pufd->revents == 0)
2021             continue; // no event received
2022
2023         cl->i_activity_date = now;
2024
2025         switch (cl->i_state) {
2026             case HTTPD_CLIENT_RECEIVING: httpd_ClientRecv(cl); break;
2027             case HTTPD_CLIENT_SENDING:   httpd_ClientSend(cl); break;
2028             case HTTPD_CLIENT_TLS_HS_IN:
2029             case HTTPD_CLIENT_TLS_HS_OUT: httpd_ClientTlsHandshake(cl); break;
2030         }
2031     }
2032
2033     /* Handle server sockets (accept new connections) */
2034     for (nfd = 0; nfd < host->nfd; nfd++) {
2035         httpd_client_t *cl;
2036         int fd = ufd[nfd].fd;
2037
2038         assert (fd == host->fds[nfd]);
2039
2040         if (ufd[nfd].revents == 0)
2041             continue;
2042
2043         /* */
2044         fd = vlc_accept (fd, NULL, NULL, true);
2045         if (fd == -1)
2046             continue;
2047         setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2048                 &(int){ 1 }, sizeof(int));
2049
2050         vlc_tls_t *p_tls;
2051
2052         if (host->p_tls != NULL)
2053         {
2054             const char *alpn[] = { "http/1.1", NULL };
2055
2056             p_tls = vlc_tls_SessionCreate(host->p_tls, fd, NULL, alpn);
2057         }
2058         else
2059             p_tls = NULL;
2060
2061         cl = httpd_ClientNew(fd, p_tls, now);
2062
2063         TAB_APPEND(host->i_client, host->client, cl);
2064     }
2065
2066     vlc_restorecancel(canc);
2067 }
2068
2069 static void* httpd_HostThread(void *data)
2070 {
2071     httpd_host_t *host = data;
2072
2073     vlc_mutex_lock(&host->lock);
2074     while (host->i_ref > 0)
2075         httpdLoop(host);
2076     vlc_mutex_unlock(&host->lock);
2077     return NULL;
2078 }
2079
2080 int httpd_StreamSetHTTPHeaders(httpd_stream_t * p_stream, httpd_header * p_headers, size_t i_headers)
2081 {
2082     if (!p_stream)
2083         return VLC_EGENERIC;
2084
2085     vlc_mutex_lock(&p_stream->lock);
2086     if (p_stream->p_http_headers) {
2087         for (size_t i = 0; i < p_stream->i_http_headers; i++) {
2088             free(p_stream->p_http_headers[i].name);
2089             free(p_stream->p_http_headers[i].value);
2090         }
2091         free(p_stream->p_http_headers);
2092         p_stream->p_http_headers = NULL;
2093         p_stream->i_http_headers = 0;
2094     }
2095
2096     if (!p_headers || !i_headers) {
2097         vlc_mutex_unlock(&p_stream->lock);
2098         return VLC_SUCCESS;
2099     }
2100
2101     p_stream->p_http_headers = malloc(sizeof(httpd_header) * i_headers);
2102     if (!p_stream->p_http_headers) {
2103         vlc_mutex_unlock(&p_stream->lock);
2104         return VLC_ENOMEM;
2105     }
2106
2107     size_t j = 0;
2108     for (size_t i = 0; i < i_headers; i++) {
2109         if (unlikely(!p_headers[i].name || !p_headers[i].value))
2110             continue;
2111
2112         p_stream->p_http_headers[j].name = strdup(p_headers[i].name);
2113         p_stream->p_http_headers[j].value = strdup(p_headers[i].value);
2114
2115         if (unlikely(!p_stream->p_http_headers[j].name ||
2116                       !p_stream->p_http_headers[j].value)) {
2117             free(p_stream->p_http_headers[j].name);
2118             free(p_stream->p_http_headers[j].value);
2119             break;
2120         }
2121         j++;
2122     }
2123     p_stream->i_http_headers = j;
2124     vlc_mutex_unlock(&p_stream->lock);
2125     return VLC_SUCCESS;
2126 }