codec: spudec: force osd start time for forced spu overlays
[vlc.git] / src / network / httpd.c
blob233c01e89dfeec2a3e6a3182fe084afdf92be5a4
1 /*****************************************************************************
2 * httpd.c
3 *****************************************************************************
4 * Copyright (C) 2004-2006 VLC authors and VideoLAN
5 * Copyright © 2004-2007 Rémi Denis-Courmont
6 * $Id$
8 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9 * Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <vlc_common.h>
31 #include <vlc_httpd.h>
33 #include <assert.h>
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"
45 #include <string.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #ifdef HAVE_SYS_UIO_H
49 # include <sys/uio.h>
50 #endif
52 #ifdef HAVE_POLL
53 # include <poll.h>
54 #endif
56 #if defined(_WIN32)
57 # include <winsock2.h>
58 #else
59 # include <sys/socket.h>
60 #endif
62 #if defined(_WIN32)
63 /* We need HUGE buffer otherwise TCP throughput is very limited */
64 #define HTTPD_CL_BUFSIZE 1000000
65 #else
66 #define HTTPD_CL_BUFSIZE 10000
67 #endif
69 static void httpd_ClientDestroy(httpd_client_t *cl);
70 static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data);
72 /* each host run in his own thread */
73 struct httpd_host_t
75 VLC_COMMON_MEMBERS
77 /* ref count */
78 unsigned i_ref;
80 /* address/port and socket for listening at connections */
81 int *fds;
82 unsigned nfd;
83 unsigned port;
85 vlc_thread_t thread;
86 vlc_mutex_t lock;
87 vlc_cond_t wait;
89 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
90 * This will slow down the url research but make my live easier
91 * All url will have their cb trigger, but only the first one can answer
92 * */
93 int i_url;
94 httpd_url_t **url;
96 int i_client;
97 httpd_client_t **client;
99 /* TLS data */
100 vlc_tls_creds_t *p_tls;
104 struct httpd_url_t
106 httpd_host_t *host;
108 vlc_mutex_t lock;
110 char *psz_url;
111 char *psz_user;
112 char *psz_password;
114 struct
116 httpd_callback_t cb;
117 httpd_callback_sys_t *p_sys;
118 } catch[HTTPD_MSG_MAX];
121 /* status */
122 enum
124 HTTPD_CLIENT_RECEIVING,
125 HTTPD_CLIENT_RECEIVE_DONE,
127 HTTPD_CLIENT_SENDING,
128 HTTPD_CLIENT_SEND_DONE,
130 HTTPD_CLIENT_WAITING,
132 HTTPD_CLIENT_DEAD,
134 HTTPD_CLIENT_TLS_HS_IN,
135 HTTPD_CLIENT_TLS_HS_OUT
138 /* mode */
139 enum
141 HTTPD_CLIENT_FILE, /* default */
142 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
145 struct httpd_client_t
147 httpd_url_t *url;
148 vlc_tls_t *sock;
150 int i_ref;
152 bool b_stream_mode;
153 uint8_t i_state;
155 mtime_t i_activity_date;
156 mtime_t i_activity_timeout;
158 /* buffer for reading header */
159 int i_buffer_size;
160 int i_buffer;
161 uint8_t *p_buffer;
164 * If waiting for a keyframe, this is the position (in bytes) of the
165 * last keyframe the stream saw before this client connected.
166 * Otherwise, -1.
168 int64_t i_keyframe_wait_to_pass;
170 /* */
171 httpd_message_t query; /* client -> httpd */
172 httpd_message_t answer; /* httpd -> client */
177 /*****************************************************************************
178 * Various functions
179 *****************************************************************************/
180 static const char *httpd_ReasonFromCode(unsigned i_code)
182 typedef struct
184 unsigned i_code;
185 const char psz_reason[36];
186 } http_status_info;
188 static const http_status_info http_reason[] =
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, "" }
247 static const char psz_fallback_reason[5][16] = {
248 "Continue", "OK", "Found", "Client error", "Server error"
251 assert((i_code >= 100) && (i_code <= 599));
253 const http_status_info *p = http_reason;
254 while (i_code < p->i_code)
255 p++;
257 if (p->i_code == i_code)
258 return p->psz_reason;
260 return psz_fallback_reason[(i_code / 100) - 1];
263 static size_t httpd_HtmlError (char **body, int code, const char *url)
265 const char *errname = httpd_ReasonFromCode (code);
266 assert (errname);
268 char *url_Encoded = vlc_xml_encode (url ? url : "");
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 ? ")" : ""));
286 free (url_Encoded);
288 if (res == -1) {
289 *body = NULL;
290 return 0;
293 return (size_t)res;
297 /*****************************************************************************
298 * High Level Functions: httpd_file_t
299 *****************************************************************************/
300 struct httpd_file_t
302 httpd_url_t *url;
303 httpd_file_callback_t pf_fill;
304 httpd_file_sys_t *p_sys;
305 char mime[1];
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)
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;
316 if (!answer || !query )
317 return VLC_SUCCESS;
319 answer->i_proto = HTTPD_PROTO_HTTP;
320 answer->i_version= 1;
321 answer->i_type = HTTPD_MSG_ANSWER;
323 answer->i_status = 200;
325 httpd_MsgAdd(answer, "Content-type", "%s", file->mime);
326 httpd_MsgAdd(answer, "Cache-Control", "%s", "no-cache");
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;
339 if (query->i_type == HTTPD_MSG_POST) {
340 /* msg_Warn not supported */
343 uint8_t *psz_args = query->psz_args;
344 file->pf_fill(file->p_sys, file, psz_args, pp_body, pi_body);
346 if (query->i_type == HTTPD_MSG_HEAD)
347 free(p_body);
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);
354 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
356 return VLC_SUCCESS;
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)
365 const char *mime = psz_mime;
366 if (mime == NULL || mime[0] == '\0')
367 mime = vlc_mime_Ext2Mime(psz_url);
369 size_t mimelen = strlen(mime);
370 httpd_file_t *file = malloc(sizeof(*file) + mimelen);
371 if (unlikely(file == NULL))
372 return NULL;
374 file->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
375 if (!file->url) {
376 free(file);
377 return NULL;
380 file->pf_fill = pf_fill;
381 file->p_sys = p_sys;
382 memcpy(file->mime, mime, mimelen + 1);
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);
391 return file;
394 httpd_file_sys_t *httpd_FileDelete(httpd_file_t *file)
396 httpd_file_sys_t *p_sys = file->p_sys;
398 httpd_UrlDelete(file->url);
399 free(file);
400 return p_sys;
403 /*****************************************************************************
404 * High Level Functions: httpd_handler_t (for CGIs)
405 *****************************************************************************/
406 struct httpd_handler_t
408 httpd_url_t *url;
410 httpd_handler_callback_t pf_fill;
411 void *p_sys;
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)
419 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
420 char psz_remote_addr[NI_MAXNUMERICHOST];
422 if (!answer || !query)
423 return VLC_SUCCESS;
425 answer->i_proto = HTTPD_PROTO_NONE;
426 answer->i_type = HTTPD_MSG_ANSWER;
428 /* We do it ourselves, thanks */
429 answer->i_status = 0;
431 if (!httpd_ClientIP(cl, psz_remote_addr, NULL))
432 *psz_remote_addr = '\0';
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);
440 if (query->i_type == HTTPD_MSG_HEAD) {
441 char *p = (char *)answer->p_body;
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;
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);
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;
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;
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;
482 return VLC_SUCCESS;
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 void *p_sys)
491 httpd_handler_t *handler = malloc(sizeof(*handler));
492 if (!handler)
493 return NULL;
495 handler->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
496 if (!handler->url) {
497 free(handler);
498 return NULL;
501 handler->pf_fill = pf_fill;
502 handler->p_sys = p_sys;
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);
511 return handler;
514 void *httpd_HandlerDelete(httpd_handler_t *handler)
516 void *p_sys = handler->p_sys;
517 httpd_UrlDelete(handler->url);
518 free(handler);
519 return p_sys;
522 /*****************************************************************************
523 * High Level Functions: httpd_redirect_t
524 *****************************************************************************/
525 struct httpd_redirect_t
527 httpd_url_t *url;
528 char dst[1];
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)
535 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
536 char *p_body;
537 (void)cl;
539 if (!answer || !query)
540 return VLC_SUCCESS;
542 answer->i_proto = HTTPD_PROTO_HTTP;
543 answer->i_version= 1;
544 answer->i_type = HTTPD_MSG_ANSWER;
545 answer->i_status = 301;
547 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->dst);
548 answer->p_body = (unsigned char *)p_body;
550 /* XXX check if it's ok or we need to set an absolute url */
551 httpd_MsgAdd(answer, "Location", "%s", rdir->dst);
553 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
555 return VLC_SUCCESS;
558 httpd_redirect_t *httpd_RedirectNew(httpd_host_t *host, const char *psz_url_dst,
559 const char *psz_url_src)
561 size_t dstlen = strlen(psz_url_dst);
563 httpd_redirect_t *rdir = malloc(sizeof(*rdir) + dstlen);
564 if (unlikely(rdir == NULL))
565 return NULL;
567 rdir->url = httpd_UrlNew(host, psz_url_src, NULL, NULL);
568 if (!rdir->url) {
569 free(rdir);
570 return NULL;
572 memcpy(rdir->dst, psz_url_dst, dstlen + 1);
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);
584 return rdir;
586 void httpd_RedirectDelete(httpd_redirect_t *rdir)
588 httpd_UrlDelete(rdir->url);
589 free(rdir);
592 /*****************************************************************************
593 * High Level Funtions: httpd_stream_t
594 *****************************************************************************/
595 struct httpd_stream_t
597 vlc_mutex_t lock;
598 httpd_url_t *url;
600 char *psz_mime;
602 /* Header to send as first packet */
603 uint8_t *p_header;
604 int i_header;
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;
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 beginning */
618 int64_t i_buffer_last_pos; /* a new connection will start with that */
620 /* custom headers */
621 size_t i_http_headers;
622 httpd_header * p_http_headers;
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)
629 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
631 if (!answer || !query || !cl)
632 return VLC_SUCCESS;
634 if (answer->i_body_offset > 0) {
635 int i_pos;
637 if (answer->i_body_offset >= stream->i_buffer_pos)
638 return VLC_EGENERIC; /* wait, no data available */
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;
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;
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 */
653 i_pos = answer->i_body_offset % stream->i_buffer_size;
654 int64_t i_write = stream->i_buffer_pos - answer->i_body_offset;
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 */
661 /* Don't go past the end of the circular buffer */
662 i_write = __MIN(i_write, stream->i_buffer_size - i_pos);
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;
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);
673 answer->i_body_offset += i_write;
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;
681 answer->i_status = 200;
683 bool b_has_content_type = false;
684 bool b_has_cache_control = false;
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);
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;
697 vlc_mutex_unlock(&stream->lock);
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);
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;
719 /* FIXME: move to http access_output */
720 if (!strcmp(stream->psz_mime, "video/x-ms-asf-stream")) {
721 bool b_xplaystream = false;
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\"");
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;
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);
741 if (!b_has_cache_control)
742 httpd_MsgAdd(answer, "Cache-Control", "no-cache");
743 return VLC_SUCCESS;
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)
751 httpd_stream_t *stream = malloc(sizeof(*stream));
752 if (!stream)
753 return NULL;
755 stream->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
756 if (!stream->url) {
757 free(stream);
758 return NULL;
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);
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;
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);
786 return stream;
789 int httpd_StreamHeader(httpd_stream_t *stream, uint8_t *p_data, int i_data)
791 vlc_mutex_lock(&stream->lock);
792 free(stream->p_header);
793 stream->p_header = NULL;
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);
800 vlc_mutex_unlock(&stream->lock);
802 return VLC_SUCCESS;
805 static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data)
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);
812 /* Ok, we can't go past the end of our buffer */
813 memcpy(&stream->p_buffer[i_pos], p_data, i_copy);
815 i_pos = (i_pos + i_copy) % stream->i_buffer_size;
816 i_count -= i_copy;
817 p_data += i_copy;
820 stream->i_buffer_pos += i_data;
823 int httpd_StreamSend(httpd_stream_t *stream, const block_t *p_block)
825 if (!p_block || !p_block->p_buffer)
826 return VLC_SUCCESS;
828 vlc_mutex_lock(&stream->lock);
830 /* save this pointer (to be used by new connection) */
831 stream->i_buffer_last_pos = stream->i_buffer_pos;
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;
838 httpd_AppendData(stream, p_block->p_buffer, p_block->i_buffer);
840 vlc_mutex_unlock(&stream->lock);
841 return VLC_SUCCESS;
844 void httpd_StreamDelete(httpd_stream_t *stream)
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);
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);
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 *);
866 /* create a new host */
867 httpd_host_t *vlc_http_HostNew(vlc_object_t *p_this)
869 return httpd_HostCreate(p_this, "http-host", "http-port", NULL);
872 httpd_host_t *vlc_https_HostNew(vlc_object_t *obj)
874 char *cert = var_InheritString(obj, "http-cert");
875 if (!cert) {
876 msg_Err(obj, "HTTP/TLS certificate not specified!");
877 return NULL;
880 char *key = var_InheritString(obj, "http-key");
881 vlc_tls_creds_t *tls = vlc_tls_ServerCreate(obj, cert, key);
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;
890 free(key);
891 free(cert);
893 return httpd_HostCreate(obj, "http-host", "https-port", tls);
896 httpd_host_t *vlc_rtsp_HostNew(vlc_object_t *p_this)
898 return httpd_HostCreate(p_this, "rtsp-host", "rtsp-port", NULL);
901 static struct httpd
903 vlc_mutex_t mutex;
905 httpd_host_t **host;
906 int i_host;
907 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
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)
914 httpd_host_t *host;
915 char *hostname = var_InheritString(p_this, hostvar);
916 unsigned port = var_InheritInteger(p_this, portvar);
918 vlc_url_t url;
919 vlc_UrlParse(&url, hostname);
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);
927 /* to be sure to avoid multiple creation */
928 vlc_mutex_lock(&httpd.mutex);
930 /* verify if it already exist */
931 for (int i = 0; i < httpd.i_host; i++) {
932 host = httpd.host[i];
934 /* cannot mix TLS and non-TLS hosts */
935 if (host->port != port
936 || (host->p_tls != NULL) != (p_tls != NULL))
937 continue;
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);
947 vlc_mutex_unlock(&httpd.mutex);
948 vlc_UrlClean(&url);
949 vlc_tls_Delete(p_tls);
950 return host;
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;
959 vlc_mutex_init(&host->lock);
960 vlc_cond_init(&host->wait);
961 host->i_ref = 1;
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;
968 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
970 host->port = port;
971 host->i_url = 0;
972 host->url = NULL;
973 host->i_client = 0;
974 host->client = NULL;
975 host->p_tls = p_tls;
977 /* create the thread */
978 if (vlc_clone(&host->thread, httpd_HostThread, host,
979 VLC_THREAD_PRIORITY_LOW)) {
980 msg_Err(p_this, "cannot spawn http host thread");
981 goto error;
984 /* now add it to httpd */
985 TAB_APPEND(httpd.i_host, httpd.host, host);
986 vlc_mutex_unlock(&httpd.mutex);
988 vlc_UrlClean(&url);
990 return host;
992 error:
993 vlc_mutex_unlock(&httpd.mutex);
995 if (host) {
996 net_ListenClose(host->fds);
997 vlc_cond_destroy(&host->wait);
998 vlc_mutex_destroy(&host->lock);
999 vlc_object_release(host);
1002 vlc_UrlClean(&url);
1003 vlc_tls_Delete(p_tls);
1004 return NULL;
1007 /* delete a host */
1008 void httpd_HostDelete(httpd_host_t *host)
1010 bool delete = false;
1012 vlc_mutex_lock(&httpd.mutex);
1014 vlc_mutex_lock(&host->lock);
1015 host->i_ref--;
1016 if (host->i_ref == 0)
1017 delete = true;
1018 vlc_mutex_unlock(&host->lock);
1019 if (!delete) {
1020 /* still used */
1021 vlc_mutex_unlock(&httpd.mutex);
1022 msg_Dbg(host, "httpd_HostDelete: host still in use");
1023 return;
1025 TAB_REMOVE(httpd.i_host, httpd.host, host);
1027 vlc_cancel(host->thread);
1028 vlc_join(host->thread, NULL);
1030 msg_Dbg(host, "HTTP host removed");
1032 for (int i = 0; i < host->i_url; i++)
1033 msg_Err(host, "url still registered: %s", host->url[i]->psz_url);
1035 for (int i = 0; i < host->i_client; i++) {
1036 msg_Warn(host, "client still connected");
1037 httpd_ClientDestroy(host->client[i]);
1039 TAB_CLEAN(host->i_client, host->client);
1041 vlc_tls_Delete(host->p_tls);
1042 net_ListenClose(host->fds);
1043 vlc_cond_destroy(&host->wait);
1044 vlc_mutex_destroy(&host->lock);
1045 vlc_object_release(host);
1046 vlc_mutex_unlock(&httpd.mutex);
1049 /* register a new url */
1050 httpd_url_t *httpd_UrlNew(httpd_host_t *host, const char *psz_url,
1051 const char *psz_user, const char *psz_password)
1053 httpd_url_t *url;
1055 assert(psz_url);
1057 vlc_mutex_lock(&host->lock);
1058 for (int i = 0; i < host->i_url; i++)
1059 if (!strcmp(psz_url, host->url[i]->psz_url)) {
1060 msg_Warn(host, "cannot add '%s' (url already defined)", psz_url);
1061 vlc_mutex_unlock(&host->lock);
1062 return NULL;
1065 url = xmalloc(sizeof(httpd_url_t));
1066 url->host = host;
1068 vlc_mutex_init(&url->lock);
1069 url->psz_url = xstrdup(psz_url);
1070 url->psz_user = xstrdup(psz_user ? psz_user : "");
1071 url->psz_password = xstrdup(psz_password ? psz_password : "");
1072 for (int i = 0; i < HTTPD_MSG_MAX; i++) {
1073 url->catch[i].cb = NULL;
1074 url->catch[i].p_sys = NULL;
1077 TAB_APPEND(host->i_url, host->url, url);
1078 vlc_cond_signal(&host->wait);
1079 vlc_mutex_unlock(&host->lock);
1081 return url;
1084 /* register callback on a url */
1085 int httpd_UrlCatch(httpd_url_t *url, int i_msg, httpd_callback_t cb,
1086 httpd_callback_sys_t *p_sys)
1088 vlc_mutex_lock(&url->lock);
1089 url->catch[i_msg].cb = cb;
1090 url->catch[i_msg].p_sys= p_sys;
1091 vlc_mutex_unlock(&url->lock);
1093 return VLC_SUCCESS;
1096 /* delete a url */
1097 void httpd_UrlDelete(httpd_url_t *url)
1099 httpd_host_t *host = url->host;
1101 vlc_mutex_lock(&host->lock);
1102 TAB_REMOVE(host->i_url, host->url, url);
1104 vlc_mutex_destroy(&url->lock);
1105 free(url->psz_url);
1106 free(url->psz_user);
1107 free(url->psz_password);
1109 for (int i = 0; i < host->i_client; i++) {
1110 httpd_client_t *client = host->client[i];
1112 if (client->url != url)
1113 continue;
1115 /* TODO complete it */
1116 msg_Warn(host, "force closing connections");
1117 TAB_REMOVE(host->i_client, host->client, client);
1118 httpd_ClientDestroy(client);
1119 i--;
1121 free(url);
1122 vlc_mutex_unlock(&host->lock);
1125 static void httpd_MsgInit(httpd_message_t *msg)
1127 msg->cl = NULL;
1128 msg->i_type = HTTPD_MSG_NONE;
1129 msg->i_proto = HTTPD_PROTO_NONE;
1130 msg->i_version = -1; /* FIXME */
1132 msg->i_status = 0;
1134 msg->psz_url = NULL;
1135 msg->psz_args = NULL;
1137 msg->i_headers = 0;
1138 msg->p_headers = NULL;
1140 msg->i_body_offset = 0;
1141 msg->i_body = 0;
1142 msg->p_body = NULL;
1145 static void httpd_MsgClean(httpd_message_t *msg)
1147 free(msg->psz_url);
1148 free(msg->psz_args);
1149 for (size_t i = 0; i < msg->i_headers; i++) {
1150 free(msg->p_headers[i].name);
1151 free(msg->p_headers[i].value);
1153 free(msg->p_headers);
1154 free(msg->p_body);
1155 httpd_MsgInit(msg);
1158 const char *httpd_MsgGet(const httpd_message_t *msg, const char *name)
1160 for (size_t i = 0; i < msg->i_headers; i++)
1161 if (!strcasecmp(msg->p_headers[i].name, name))
1162 return msg->p_headers[i].value;
1163 return NULL;
1166 void httpd_MsgAdd(httpd_message_t *msg, const char *name, const char *psz_value, ...)
1168 httpd_header *p_tmp = realloc(msg->p_headers, sizeof(httpd_header) * (msg->i_headers + 1));
1169 if (!p_tmp)
1170 return;
1172 msg->p_headers = p_tmp;
1174 httpd_header *h = &msg->p_headers[msg->i_headers];
1175 h->name = strdup(name);
1176 if (!h->name)
1177 return;
1179 h->value = NULL;
1181 va_list args;
1182 va_start(args, psz_value);
1183 int ret = us_vasprintf(&h->value, psz_value, args);
1184 va_end(args);
1186 if (ret == -1) {
1187 free(h->name);
1188 return;
1191 msg->i_headers++;
1194 static void httpd_ClientInit(httpd_client_t *cl, mtime_t now)
1196 cl->i_state = HTTPD_CLIENT_RECEIVING;
1197 cl->i_activity_date = now;
1198 cl->i_activity_timeout = INT64_C(10000000);
1199 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1200 cl->i_buffer = 0;
1201 cl->p_buffer = xmalloc(cl->i_buffer_size);
1202 cl->i_keyframe_wait_to_pass = -1;
1203 cl->b_stream_mode = false;
1205 httpd_MsgInit(&cl->query);
1206 httpd_MsgInit(&cl->answer);
1209 char* httpd_ClientIP(const httpd_client_t *cl, char *ip, int *port)
1211 return net_GetPeerAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1214 char* httpd_ServerIP(const httpd_client_t *cl, char *ip, int *port)
1216 return net_GetSockAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1219 static void httpd_ClientDestroy(httpd_client_t *cl)
1221 vlc_tls_Close(cl->sock);
1222 httpd_MsgClean(&cl->answer);
1223 httpd_MsgClean(&cl->query);
1225 free(cl->p_buffer);
1226 free(cl);
1229 static httpd_client_t *httpd_ClientNew(vlc_tls_t *sock, mtime_t now)
1231 httpd_client_t *cl = malloc(sizeof(httpd_client_t));
1233 if (!cl) return NULL;
1235 cl->i_ref = 0;
1236 cl->sock = sock;
1237 cl->url = NULL;
1239 httpd_ClientInit(cl, now);
1240 return cl;
1243 static
1244 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1246 vlc_tls_t *sock = cl->sock;
1247 struct iovec iov = { .iov_base = p, .iov_len = i_len };
1248 return sock->readv(sock, &iov, 1);
1251 static
1252 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1254 vlc_tls_t *sock = cl->sock;
1255 const struct iovec iov = { .iov_base = (void *)p, .iov_len = i_len };
1256 return sock->writev(sock, &iov, 1);
1260 static const struct
1262 const char name[16];
1263 int i_type;
1264 int i_proto;
1266 msg_type[] =
1268 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1269 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1270 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1271 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1272 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1273 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1274 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1275 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1276 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1277 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1278 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1282 static void httpd_ClientRecv(httpd_client_t *cl)
1284 int i_len;
1286 /* ignore leading whites */
1287 if (cl->query.i_proto == HTTPD_PROTO_NONE && cl->i_buffer == 0) {
1288 unsigned char c;
1290 i_len = httpd_NetRecv(cl, &c, 1);
1292 if (i_len > 0 && !strchr("\r\n\t ", c)) {
1293 cl->p_buffer[0] = c;
1294 cl->i_buffer++;
1296 } else if (cl->query.i_proto == HTTPD_PROTO_NONE) {
1297 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1298 i_len = httpd_NetRecv(cl, &cl->p_buffer[cl->i_buffer],
1299 7 - cl->i_buffer);
1300 if (i_len > 0)
1301 cl->i_buffer += i_len;
1303 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1304 * this is the maximum we can ask at this point. */
1305 if (cl->i_buffer >= 7) {
1306 if (!memcmp(cl->p_buffer, "HTTP/1.", 7)) {
1307 cl->query.i_proto = HTTPD_PROTO_HTTP;
1308 cl->query.i_type = HTTPD_MSG_ANSWER;
1309 } else if (!memcmp(cl->p_buffer, "RTSP/1.", 7)) {
1310 cl->query.i_proto = HTTPD_PROTO_RTSP;
1311 cl->query.i_type = HTTPD_MSG_ANSWER;
1312 } else {
1313 /* We need the full request line to determine the protocol. */
1314 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1315 cl->query.i_type = HTTPD_MSG_NONE;
1318 } else if (cl->query.i_body > 0) {
1319 /* we are reading the body of a request or a channel */
1320 assert (cl->query.p_body != NULL);
1321 i_len = httpd_NetRecv(cl, &cl->query.p_body[cl->i_buffer],
1322 cl->query.i_body - cl->i_buffer);
1323 if (i_len > 0)
1324 cl->i_buffer += i_len;
1326 if (cl->i_buffer >= cl->query.i_body)
1327 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1328 } else for (;;) { /* we are reading a header -> char by char */
1329 if (cl->i_buffer == cl->i_buffer_size) {
1330 uint8_t *newbuf = realloc(cl->p_buffer, cl->i_buffer_size + 1024);
1331 if (!newbuf) {
1332 i_len = 0;
1333 break;
1336 cl->p_buffer = newbuf;
1337 cl->i_buffer_size += 1024;
1340 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1);
1341 if (i_len <= 0)
1342 break;
1344 cl->i_buffer++;
1346 if ((cl->query.i_proto == HTTPD_PROTO_HTTP0)
1347 && (cl->p_buffer[cl->i_buffer - 1] == '\n'))
1349 /* Request line is now complete */
1350 const char *p = memchr(cl->p_buffer, ' ', cl->i_buffer);
1351 size_t len;
1353 assert(cl->query.i_type == HTTPD_MSG_NONE);
1355 if (!p) { /* no URI: evil guy */
1356 i_len = 0; /* drop connection */
1357 break;
1361 p++; /* skips extra spaces */
1362 while (*p == ' ');
1364 p = memchr(p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p);
1365 if (!p) { /* no explicit protocol: HTTP/0.9 */
1366 i_len = 0; /* not supported currently -> drop */
1367 break;
1371 p++; /* skips extra spaces ever again */
1372 while (*p == ' ');
1374 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1375 if (len < 7) /* foreign protocol */
1376 i_len = 0; /* I don't understand -> drop */
1377 else if (!memcmp(p, "HTTP/1.", 7)) {
1378 cl->query.i_proto = HTTPD_PROTO_HTTP;
1379 cl->query.i_version = atoi(p + 7);
1380 } else if (!memcmp(p, "RTSP/1.", 7)) {
1381 cl->query.i_proto = HTTPD_PROTO_RTSP;
1382 cl->query.i_version = atoi(p + 7);
1383 } else if (!memcmp(p, "HTTP/", 5)) {
1384 const uint8_t sorry[] =
1385 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1386 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1387 i_len = 0; /* drop */
1388 } else if (!memcmp(p, "RTSP/", 5)) {
1389 const uint8_t sorry[] =
1390 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1391 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1392 i_len = 0; /* drop */
1393 } else /* yet another foreign protocol */
1394 i_len = 0;
1396 if (i_len == 0)
1397 break;
1400 if ((cl->i_buffer >= 2 && !memcmp(&cl->p_buffer[cl->i_buffer-2], "\n\n", 2))||
1401 (cl->i_buffer >= 4 && !memcmp(&cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4)))
1403 char *p;
1405 /* we have finished the header so parse it and set i_body */
1406 cl->p_buffer[cl->i_buffer] = '\0';
1408 if (cl->query.i_type == HTTPD_MSG_ANSWER) {
1409 /* FIXME:
1410 * assume strlen("HTTP/1.x") = 8
1412 cl->query.i_status =
1413 strtol((char *)&cl->p_buffer[8],
1414 &p, 0);
1415 while (*p == ' ')
1416 p++;
1417 } else {
1418 p = NULL;
1419 cl->query.i_type = HTTPD_MSG_NONE;
1421 for (unsigned i = 0; msg_type[i].name[0]; i++)
1422 if (!strncmp((char *)cl->p_buffer, msg_type[i].name,
1423 strlen(msg_type[i].name))) {
1424 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1425 cl->query.i_type = msg_type[i].i_type;
1426 if (cl->query.i_proto != msg_type[i].i_proto) {
1427 p = NULL;
1428 cl->query.i_proto = HTTPD_PROTO_NONE;
1429 cl->query.i_type = HTTPD_MSG_NONE;
1431 break;
1434 if (!p) {
1435 if (strstr((char *)cl->p_buffer, "HTTP/1."))
1436 cl->query.i_proto = HTTPD_PROTO_HTTP;
1437 else if (strstr((char *)cl->p_buffer, "RTSP/1."))
1438 cl->query.i_proto = HTTPD_PROTO_RTSP;
1439 } else {
1440 char *p2;
1441 char *p3;
1443 while (*p == ' ')
1444 p++;
1446 p2 = strchr(p, ' ');
1447 if (p2)
1448 *p2++ = '\0';
1450 if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "http:" : "rtsp:", 5)) {
1451 /* Skip hier-part of URL (if present) */
1452 p += 5;
1453 if (!strncmp(p, "//", 2)) { /* skip authority */
1454 /* see RFC3986 §3.2 */
1455 p += 2;
1456 p += strcspn(p, "/?#");
1459 else if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "https:" : "rtsps:", 6)) {
1460 /* Skip hier-part of URL (if present) */
1461 p += 6;
1462 if (!strncmp(p, "//", 2)) { /* skip authority */
1463 /* see RFC3986 §3.2 */
1464 p += 2;
1465 p += strcspn(p, "/?#");
1469 cl->query.psz_url = strdup(p);
1470 if ((p3 = strchr(cl->query.psz_url, '?')) ) {
1471 *p3++ = '\0';
1472 cl->query.psz_args = (uint8_t *)strdup(p3);
1474 p = p2;
1477 if (p)
1478 p = strchr(p, '\n');
1480 if (p) {
1481 while (*p == '\n' || *p == '\r')
1482 p++;
1484 while (p && *p) {
1485 char *line = p;
1486 char *eol = p = strchr(p, '\n');
1487 char *colon;
1489 while (eol && eol >= line && (*eol == '\n' || *eol == '\r'))
1490 *eol-- = '\0';
1492 if ((colon = strchr(line, ':'))) {
1493 *colon++ = '\0';
1494 while (*colon == ' ')
1495 colon++;
1496 httpd_MsgAdd(&cl->query, line, "%s", colon);
1498 if (!strcasecmp(line, "Content-Length"))
1499 cl->query.i_body = atol(colon);
1502 if (p) {
1503 p++;
1504 while (*p == '\n' || *p == '\r')
1505 p++;
1509 if (cl->query.i_body > 0) {
1510 /* TODO Mhh, handle the case where the client only
1511 * sends a request and closes the connection to
1512 * mark the end of the body (probably only RTSP) */
1513 if (cl->query.i_body >= 65536)
1514 cl->query.p_body = malloc(cl->query.i_body);
1515 else
1516 cl->query.p_body = NULL;
1517 cl->i_buffer = 0;
1518 if (!cl->query.p_body) {
1519 switch (cl->query.i_proto) {
1520 case HTTPD_PROTO_HTTP: {
1521 const uint8_t sorry[] = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1522 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1523 break;
1525 case HTTPD_PROTO_RTSP: {
1526 const uint8_t sorry[] = "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1527 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1528 break;
1530 default:
1531 vlc_assert_unreachable();
1533 i_len = 0; /* drop */
1535 break;
1536 } else
1537 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1541 /* check if the client is to be set to dead */
1542 #if defined(_WIN32)
1543 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1544 #else
1545 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1546 #endif
1548 if (cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE) {
1549 /* connection closed -> end of data */
1550 if (cl->query.i_body > 0)
1551 cl->query.i_body = cl->i_buffer;
1552 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1554 else
1555 cl->i_state = HTTPD_CLIENT_DEAD;
1558 /* XXX: for QT I have to disable timeout. Try to find why */
1559 if (cl->query.i_proto == HTTPD_PROTO_RTSP)
1560 cl->i_activity_timeout = 0;
1563 static void httpd_ClientSend(httpd_client_t *cl)
1565 int i_len;
1567 if (cl->i_buffer < 0) {
1568 /* We need to create the header */
1569 int i_size = 0;
1570 char *p;
1571 const char *psz_status = httpd_ReasonFromCode(cl->answer.i_status);
1573 i_size = strlen("HTTP/1.") + 10 + 10 + strlen(psz_status) + 5;
1574 for (size_t i = 0; i < cl->answer.i_headers; i++)
1575 i_size += strlen(cl->answer.p_headers[i].name) + 2 +
1576 strlen(cl->answer.p_headers[i].value) + 2;
1578 if (cl->i_buffer_size < i_size) {
1579 cl->i_buffer_size = i_size;
1580 free(cl->p_buffer);
1581 cl->p_buffer = xmalloc(i_size);
1583 p = (char *)cl->p_buffer;
1585 p += sprintf(p, "%s.%u %d %s\r\n",
1586 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1587 cl->answer.i_version,
1588 cl->answer.i_status, psz_status);
1589 for (size_t i = 0; i < cl->answer.i_headers; i++)
1590 p += sprintf(p, "%s: %s\r\n", cl->answer.p_headers[i].name,
1591 cl->answer.p_headers[i].value);
1592 p += sprintf(p, "\r\n");
1594 cl->i_buffer = 0;
1595 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1598 i_len = httpd_NetSend(cl, &cl->p_buffer[cl->i_buffer],
1599 cl->i_buffer_size - cl->i_buffer);
1600 if (i_len >= 0) {
1601 cl->i_buffer += i_len;
1603 if (cl->i_buffer >= cl->i_buffer_size) {
1604 if (cl->answer.i_body == 0 && cl->answer.i_body_offset > 0) {
1605 /* catch more body data */
1606 int i_msg = cl->query.i_type;
1607 int64_t i_offset = cl->answer.i_body_offset;
1609 httpd_MsgClean(&cl->answer);
1610 cl->answer.i_body_offset = i_offset;
1612 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1613 &cl->answer, &cl->query);
1616 if (cl->answer.i_body > 0) {
1617 /* send the body data */
1618 free(cl->p_buffer);
1619 cl->p_buffer = cl->answer.p_body;
1620 cl->i_buffer_size = cl->answer.i_body;
1621 cl->i_buffer = 0;
1623 cl->answer.i_body = 0;
1624 cl->answer.p_body = NULL;
1625 } else /* send finished */
1626 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1628 } else {
1629 #if defined(_WIN32)
1630 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1631 #else
1632 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1633 #endif
1635 /* error */
1636 cl->i_state = HTTPD_CLIENT_DEAD;
1641 static void httpd_ClientTlsHandshake(httpd_host_t *host, httpd_client_t *cl)
1643 switch (vlc_tls_SessionHandshake(host->p_tls, cl->sock))
1645 case -1: cl->i_state = HTTPD_CLIENT_DEAD; break;
1646 case 0: cl->i_state = HTTPD_CLIENT_RECEIVING; break;
1647 case 1: cl->i_state = HTTPD_CLIENT_TLS_HS_IN; break;
1648 case 2: cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1652 static bool httpdAuthOk(const char *user, const char *pass, const char *b64)
1654 if (!*user && !*pass)
1655 return true;
1657 if (!b64)
1658 return false;
1660 if (strncasecmp(b64, "BASIC", 5))
1661 return false;
1663 b64 += 5;
1664 while (*b64 == ' ')
1665 b64++;
1667 char *given_user = vlc_b64_decode(b64);
1668 if (!given_user)
1669 return false;
1671 char *given_pass = NULL;
1672 given_pass = strchr (given_user, ':');
1673 if (!given_pass)
1674 goto auth_failed;
1676 *given_pass++ = '\0';
1678 if (strcmp (given_user, user))
1679 goto auth_failed;
1681 if (strcmp (given_pass, pass))
1682 goto auth_failed;
1684 free(given_user);
1685 return true;
1687 auth_failed:
1688 free(given_user);
1689 return false;
1692 static void httpdLoop(httpd_host_t *host)
1694 struct pollfd ufd[host->nfd + host->i_client];
1695 unsigned nfd;
1696 for (nfd = 0; nfd < host->nfd; nfd++) {
1697 ufd[nfd].fd = host->fds[nfd];
1698 ufd[nfd].events = POLLIN;
1699 ufd[nfd].revents = 0;
1702 /* add all socket that should be read/write and close dead connection */
1703 while (host->i_url <= 0) {
1704 mutex_cleanup_push(&host->lock);
1705 vlc_cond_wait(&host->wait, &host->lock);
1706 vlc_cleanup_pop();
1709 mtime_t now = mdate();
1710 bool b_low_delay = false;
1712 int canc = vlc_savecancel();
1713 for (int i_client = 0; i_client < host->i_client; i_client++) {
1714 int64_t i_offset;
1715 httpd_client_t *cl = host->client[i_client];
1716 if (cl->i_ref < 0 || (cl->i_ref == 0 &&
1717 (cl->i_state == HTTPD_CLIENT_DEAD ||
1718 (cl->i_activity_timeout > 0 &&
1719 cl->i_activity_date+cl->i_activity_timeout < now)))) {
1720 TAB_REMOVE(host->i_client, host->client, cl);
1721 i_client--;
1722 httpd_ClientDestroy(cl);
1723 continue;
1726 struct pollfd *pufd = ufd + nfd;
1727 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1729 pufd->fd = vlc_tls_GetFD(cl->sock);
1730 pufd->events = pufd->revents = 0;
1732 switch (cl->i_state) {
1733 case HTTPD_CLIENT_RECEIVING:
1734 case HTTPD_CLIENT_TLS_HS_IN:
1735 pufd->events = POLLIN;
1736 break;
1738 case HTTPD_CLIENT_SENDING:
1739 case HTTPD_CLIENT_TLS_HS_OUT:
1740 pufd->events = POLLOUT;
1741 break;
1743 case HTTPD_CLIENT_RECEIVE_DONE: {
1744 httpd_message_t *answer = &cl->answer;
1745 httpd_message_t *query = &cl->query;
1747 httpd_MsgInit(answer);
1749 /* Handle what we received */
1750 switch (query->i_type) {
1751 case HTTPD_MSG_ANSWER:
1752 cl->url = NULL;
1753 cl->i_state = HTTPD_CLIENT_DEAD;
1754 break;
1756 case HTTPD_MSG_OPTIONS:
1757 answer->i_type = HTTPD_MSG_ANSWER;
1758 answer->i_proto = query->i_proto;
1759 answer->i_status = 200;
1760 answer->i_body = 0;
1761 answer->p_body = NULL;
1763 httpd_MsgAdd(answer, "Server", "VLC/%s", VERSION);
1764 httpd_MsgAdd(answer, "Content-Length", "0");
1766 switch(query->i_proto) {
1767 case HTTPD_PROTO_HTTP:
1768 answer->i_version = 1;
1769 httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
1770 break;
1772 case HTTPD_PROTO_RTSP:
1773 answer->i_version = 0;
1775 const char *p = httpd_MsgGet(query, "Cseq");
1776 if (p)
1777 httpd_MsgAdd(answer, "Cseq", "%s", p);
1778 p = httpd_MsgGet(query, "Timestamp");
1779 if (p)
1780 httpd_MsgAdd(answer, "Timestamp", "%s", p);
1782 p = httpd_MsgGet(query, "Require");
1783 if (p) {
1784 answer->i_status = 551;
1785 httpd_MsgAdd(query, "Unsupported", "%s", p);
1788 httpd_MsgAdd(answer, "Public", "DESCRIBE,SETUP,"
1789 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER");
1790 break;
1793 cl->i_buffer = -1; /* Force the creation of the answer in
1794 * httpd_ClientSend */
1795 cl->i_state = HTTPD_CLIENT_SENDING;
1796 break;
1798 case HTTPD_MSG_NONE:
1799 if (query->i_proto == HTTPD_PROTO_NONE) {
1800 cl->url = NULL;
1801 cl->i_state = HTTPD_CLIENT_DEAD;
1802 } else {
1803 /* unimplemented */
1804 answer->i_proto = query->i_proto ;
1805 answer->i_type = HTTPD_MSG_ANSWER;
1806 answer->i_version= 0;
1807 answer->i_status = 501;
1809 char *p;
1810 answer->i_body = httpd_HtmlError (&p, 501, NULL);
1811 answer->p_body = (uint8_t *)p;
1812 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1814 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1815 cl->i_state = HTTPD_CLIENT_SENDING;
1817 break;
1819 default: {
1820 int i_msg = query->i_type;
1821 bool b_auth_failed = false;
1823 /* Search the url and trigger callbacks */
1824 for (int i = 0; i < host->i_url; i++) {
1825 httpd_url_t *url = host->url[i];
1827 if (strcmp(url->psz_url, query->psz_url))
1828 continue;
1829 if (!url->catch[i_msg].cb)
1830 continue;
1832 if (answer) {
1833 b_auth_failed = !httpdAuthOk(url->psz_user,
1834 url->psz_password,
1835 httpd_MsgGet(query, "Authorization")); /* BASIC id */
1836 if (b_auth_failed)
1837 break;
1840 if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
1841 continue;
1843 if (answer->i_proto == HTTPD_PROTO_NONE)
1844 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
1845 else
1846 cl->i_buffer = -1;
1848 /* only one url can answer */
1849 answer = NULL;
1850 if (!cl->url)
1851 cl->url = url;
1854 if (answer) {
1855 answer->i_proto = query->i_proto;
1856 answer->i_type = HTTPD_MSG_ANSWER;
1857 answer->i_version= 0;
1859 if (b_auth_failed) {
1860 httpd_MsgAdd(answer, "WWW-Authenticate",
1861 "Basic realm=\"VLC stream\"");
1862 answer->i_status = 401;
1863 } else
1864 answer->i_status = 404; /* no url registered */
1866 char *p;
1867 answer->i_body = httpd_HtmlError (&p, answer->i_status,
1868 query->psz_url);
1869 answer->p_body = (uint8_t *)p;
1871 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1872 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1873 httpd_MsgAdd(answer, "Content-Type", "%s", "text/html");
1876 cl->i_state = HTTPD_CLIENT_SENDING;
1879 break;
1882 case HTTPD_CLIENT_SEND_DONE:
1883 if (!cl->b_stream_mode || cl->answer.i_body_offset == 0) {
1884 const char *psz_connection = httpd_MsgGet(&cl->answer, "Connection");
1885 const char *psz_query = httpd_MsgGet(&cl->query, "Connection");
1886 bool b_connection = false;
1887 bool b_keepalive = false;
1888 bool b_query = false;
1890 cl->url = NULL;
1891 if (psz_connection) {
1892 b_connection = (strcasecmp(psz_connection, "Close") == 0);
1893 b_keepalive = (strcasecmp(psz_connection, "Keep-Alive") == 0);
1896 if (psz_query)
1897 b_query = (strcasecmp(psz_query, "Close") == 0);
1899 if (((cl->query.i_proto == HTTPD_PROTO_HTTP) &&
1900 ((cl->query.i_version == 0 && b_keepalive) ||
1901 (cl->query.i_version == 1 && !b_connection))) ||
1902 ((cl->query.i_proto == HTTPD_PROTO_RTSP) &&
1903 !b_query && !b_connection)) {
1904 httpd_MsgClean(&cl->query);
1905 httpd_MsgInit(&cl->query);
1907 cl->i_buffer = 0;
1908 cl->i_buffer_size = 1000;
1909 free(cl->p_buffer);
1910 cl->p_buffer = xmalloc(cl->i_buffer_size);
1911 cl->i_state = HTTPD_CLIENT_RECEIVING;
1912 } else
1913 cl->i_state = HTTPD_CLIENT_DEAD;
1914 httpd_MsgClean(&cl->answer);
1915 } else {
1916 i_offset = cl->answer.i_body_offset;
1917 httpd_MsgClean(&cl->answer);
1919 cl->answer.i_body_offset = i_offset;
1920 free(cl->p_buffer);
1921 cl->p_buffer = NULL;
1922 cl->i_buffer = 0;
1923 cl->i_buffer_size = 0;
1925 cl->i_state = HTTPD_CLIENT_WAITING;
1927 break;
1929 case HTTPD_CLIENT_WAITING:
1930 i_offset = cl->answer.i_body_offset;
1931 int i_msg = cl->query.i_type;
1933 httpd_MsgInit(&cl->answer);
1934 cl->answer.i_body_offset = i_offset;
1936 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1937 &cl->answer, &cl->query);
1938 if (cl->answer.i_type != HTTPD_MSG_NONE) {
1939 /* we have new data, so re-enter send mode */
1940 cl->i_buffer = 0;
1941 cl->p_buffer = cl->answer.p_body;
1942 cl->i_buffer_size = cl->answer.i_body;
1943 cl->answer.p_body = NULL;
1944 cl->answer.i_body = 0;
1945 cl->i_state = HTTPD_CLIENT_SENDING;
1949 if (pufd->events != 0)
1950 nfd++;
1951 else
1952 b_low_delay = true;
1954 vlc_mutex_unlock(&host->lock);
1955 vlc_restorecancel(canc);
1957 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
1958 int ret = poll(ufd, nfd, b_low_delay ? 20 : -1);
1960 canc = vlc_savecancel();
1961 vlc_mutex_lock(&host->lock);
1962 switch(ret) {
1963 case -1:
1964 if (errno != EINTR) {
1965 /* Kernel on low memory or a bug: pace */
1966 msg_Err(host, "polling error: %s", vlc_strerror_c(errno));
1967 msleep(100000);
1969 case 0:
1970 vlc_restorecancel(canc);
1971 return;
1974 /* Handle client sockets */
1975 now = mdate();
1976 nfd = host->nfd;
1978 for (int i_client = 0; i_client < host->i_client; i_client++) {
1979 httpd_client_t *cl = host->client[i_client];
1980 const struct pollfd *pufd = &ufd[nfd];
1982 assert(pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])]);
1984 if (vlc_tls_GetFD(cl->sock) != pufd->fd)
1985 continue; // we were not waiting for this client
1986 ++nfd;
1987 if (pufd->revents == 0)
1988 continue; // no event received
1990 cl->i_activity_date = now;
1992 switch (cl->i_state) {
1993 case HTTPD_CLIENT_RECEIVING: httpd_ClientRecv(cl); break;
1994 case HTTPD_CLIENT_SENDING: httpd_ClientSend(cl); break;
1995 case HTTPD_CLIENT_TLS_HS_IN:
1996 case HTTPD_CLIENT_TLS_HS_OUT:
1997 httpd_ClientTlsHandshake(host, cl);
1998 break;
2002 /* Handle server sockets (accept new connections) */
2003 for (nfd = 0; nfd < host->nfd; nfd++) {
2004 httpd_client_t *cl;
2005 int fd = ufd[nfd].fd;
2007 assert (fd == host->fds[nfd]);
2009 if (ufd[nfd].revents == 0)
2010 continue;
2012 /* */
2013 fd = vlc_accept (fd, NULL, NULL, true);
2014 if (fd == -1)
2015 continue;
2016 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2017 &(int){ 1 }, sizeof(int));
2019 vlc_tls_t *sk = vlc_tls_SocketOpen(fd);
2020 if (unlikely(sk == NULL))
2022 vlc_close(fd);
2023 continue;
2026 if (host->p_tls != NULL)
2028 const char *alpn[] = { "http/1.1", NULL };
2029 vlc_tls_t *tls;
2031 tls = vlc_tls_ServerSessionCreate(host->p_tls, sk, alpn);
2032 if (tls == NULL)
2034 vlc_tls_SessionDelete(sk);
2035 continue;
2037 sk = tls;
2040 cl = httpd_ClientNew(sk, now);
2042 if (host->p_tls != NULL)
2043 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2045 TAB_APPEND(host->i_client, host->client, cl);
2048 vlc_restorecancel(canc);
2051 static void* httpd_HostThread(void *data)
2053 httpd_host_t *host = data;
2055 vlc_mutex_lock(&host->lock);
2056 while (host->i_ref > 0)
2057 httpdLoop(host);
2058 vlc_mutex_unlock(&host->lock);
2059 return NULL;
2062 int httpd_StreamSetHTTPHeaders(httpd_stream_t * p_stream, httpd_header * p_headers, size_t i_headers)
2064 if (!p_stream)
2065 return VLC_EGENERIC;
2067 vlc_mutex_lock(&p_stream->lock);
2068 if (p_stream->p_http_headers) {
2069 for (size_t i = 0; i < p_stream->i_http_headers; i++) {
2070 free(p_stream->p_http_headers[i].name);
2071 free(p_stream->p_http_headers[i].value);
2073 free(p_stream->p_http_headers);
2074 p_stream->p_http_headers = NULL;
2075 p_stream->i_http_headers = 0;
2078 if (!p_headers || !i_headers) {
2079 vlc_mutex_unlock(&p_stream->lock);
2080 return VLC_SUCCESS;
2083 p_stream->p_http_headers = malloc(sizeof(httpd_header) * i_headers);
2084 if (!p_stream->p_http_headers) {
2085 vlc_mutex_unlock(&p_stream->lock);
2086 return VLC_ENOMEM;
2089 size_t j = 0;
2090 for (size_t i = 0; i < i_headers; i++) {
2091 if (unlikely(!p_headers[i].name || !p_headers[i].value))
2092 continue;
2094 p_stream->p_http_headers[j].name = strdup(p_headers[i].name);
2095 p_stream->p_http_headers[j].value = strdup(p_headers[i].value);
2097 if (unlikely(!p_stream->p_http_headers[j].name ||
2098 !p_stream->p_http_headers[j].value)) {
2099 free(p_stream->p_http_headers[j].name);
2100 free(p_stream->p_http_headers[j].value);
2101 break;
2103 j++;
2105 p_stream->i_http_headers = j;
2106 vlc_mutex_unlock(&p_stream->lock);
2107 return VLC_SUCCESS;