codec: dvbsub: remove usage of bs_show
[vlc.git] / src / network / httpd.c
blob3d7ae0405daf3d826964e13de3ae1393d2e509ab
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 <stdatomic.h>
32 #include <vlc_common.h>
33 #include <vlc_httpd.h>
35 #include <assert.h>
37 #include <vlc_list.h>
38 #include <vlc_network.h>
39 #include <vlc_tls.h>
40 #include <vlc_strings.h>
41 #include <vlc_rand.h>
42 #include <vlc_charset.h>
43 #include <vlc_url.h>
44 #include <vlc_mime.h>
45 #include <vlc_block.h>
46 #include "../libvlc.h"
48 #include <string.h>
49 #include <errno.h>
50 #include <unistd.h>
51 #ifdef HAVE_SYS_UIO_H
52 # include <sys/uio.h>
53 #endif
55 #ifdef HAVE_POLL
56 # include <poll.h>
57 #endif
59 #if defined(_WIN32)
60 # include <winsock2.h>
61 #elif defined(HAVE_SYS_SOCKET_H)
62 # include <sys/socket.h>
63 #endif
65 #if defined(_WIN32)
66 /* We need HUGE buffer otherwise TCP throughput is very limited */
67 #define HTTPD_CL_BUFSIZE 1000000
68 #else
69 #define HTTPD_CL_BUFSIZE 10000
70 #endif
72 static void httpd_ClientDestroy(httpd_client_t *cl);
73 static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data);
75 /* each host run in his own thread */
76 struct httpd_host_t
78 struct vlc_common_members obj;
79 struct vlc_list node;
81 /* ref count */
82 atomic_uint ref;
84 /* address/port and socket for listening at connections */
85 int *fds;
86 unsigned nfd;
87 unsigned port;
89 vlc_thread_t thread;
90 vlc_mutex_t lock;
91 vlc_cond_t wait;
93 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
94 * This will slow down the url research but make my live easier
95 * All url will have their cb trigger, but only the first one can answer
96 * */
97 struct vlc_list urls;
99 size_t client_count;
100 struct vlc_list clients;
102 /* TLS data */
103 vlc_tls_creds_t *p_tls;
107 struct httpd_url_t
109 httpd_host_t *host;
110 struct vlc_list node;
111 vlc_mutex_t lock;
113 char *psz_url;
114 char *psz_user;
115 char *psz_password;
117 struct
119 httpd_callback_t cb;
120 httpd_callback_sys_t *p_sys;
121 } catch[HTTPD_MSG_MAX];
124 /* status */
125 enum
127 HTTPD_CLIENT_RECEIVING,
128 HTTPD_CLIENT_RECEIVE_DONE,
130 HTTPD_CLIENT_SENDING,
131 HTTPD_CLIENT_SEND_DONE,
133 HTTPD_CLIENT_WAITING,
135 HTTPD_CLIENT_DEAD,
137 HTTPD_CLIENT_TLS_HS_IN,
138 HTTPD_CLIENT_TLS_HS_OUT
141 struct httpd_client_t
143 httpd_url_t *url;
144 vlc_tls_t *sock;
146 struct vlc_list node;
148 bool b_stream_mode;
149 uint8_t i_state;
151 vlc_tick_t i_activity_date;
152 vlc_tick_t i_activity_timeout;
154 /* buffer for reading header */
155 int i_buffer_size;
156 int i_buffer;
157 uint8_t *p_buffer;
160 * If waiting for a keyframe, this is the position (in bytes) of the
161 * last keyframe the stream saw before this client connected.
162 * Otherwise, -1.
164 int64_t i_keyframe_wait_to_pass;
166 /* */
167 httpd_message_t query; /* client -> httpd */
168 httpd_message_t answer; /* httpd -> client */
172 /*****************************************************************************
173 * Various functions
174 *****************************************************************************/
175 static const char *httpd_ReasonFromCode(unsigned i_code)
177 typedef struct
179 unsigned i_code;
180 const char psz_reason[36];
181 } http_status_info;
183 static const http_status_info http_reason[] =
185 /*{ 100, "Continue" },
186 { 101, "Switching Protocols" },*/
187 { 200, "OK" },
188 /*{ 201, "Created" },
189 { 202, "Accepted" },
190 { 203, "Non-authoritative information" },
191 { 204, "No content" },
192 { 205, "Reset content" },
193 { 206, "Partial content" },
194 { 250, "Low on storage space" },
195 { 300, "Multiple choices" },*/
196 { 301, "Moved permanently" },
197 /*{ 302, "Moved temporarily" },
198 { 303, "See other" },
199 { 304, "Not modified" },
200 { 305, "Use proxy" },
201 { 307, "Temporary redirect" },
202 { 400, "Bad request" },*/
203 { 401, "Unauthorized" },
204 /*{ 402, "Payment Required" },*/
205 { 403, "Forbidden" },
206 { 404, "Not found" },
207 { 405, "Method not allowed" },
208 /*{ 406, "Not acceptable" },
209 { 407, "Proxy authentication required" },
210 { 408, "Request time-out" },
211 { 409, "Conflict" },
212 { 410, "Gone" },
213 { 411, "Length required" },
214 { 412, "Precondition failed" },
215 { 413, "Request entity too large" },
216 { 414, "Request-URI too large" },
217 { 415, "Unsupported media Type" },
218 { 416, "Requested range not satisfiable" },
219 { 417, "Expectation failed" },
220 { 451, "Parameter not understood" },
221 { 452, "Conference not found" },
222 { 453, "Not enough bandwidth" },*/
223 { 454, "Session not found" },
224 { 455, "Method not valid in this State" },
225 { 456, "Header field not valid for resource" },
226 { 457, "Invalid range" },
227 /*{ 458, "Read-only parameter" },*/
228 { 459, "Aggregate operation not allowed" },
229 { 460, "Non-aggregate operation not allowed" },
230 { 461, "Unsupported transport" },
231 /*{ 462, "Destination unreachable" },*/
232 { 500, "Internal server error" },
233 { 501, "Not implemented" },
234 /*{ 502, "Bad gateway" },*/
235 { 503, "Service unavailable" },
236 /*{ 504, "Gateway time-out" },*/
237 { 505, "Protocol version not supported" },
238 { 551, "Option not supported" },
239 { 999, "" }
242 static const char psz_fallback_reason[5][16] = {
243 "Continue", "OK", "Found", "Client error", "Server error"
246 assert((i_code >= 100) && (i_code <= 599));
248 const http_status_info *p = http_reason;
249 while (i_code < p->i_code)
250 p++;
252 if (p->i_code == i_code)
253 return p->psz_reason;
255 return psz_fallback_reason[(i_code / 100) - 1];
258 static size_t httpd_HtmlError (char **body, int code, const char *url)
260 const char *errname = httpd_ReasonFromCode (code);
261 assert (errname);
263 char *url_Encoded = vlc_xml_encode (url ? url : "");
265 int res = asprintf (body,
266 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
267 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
268 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
269 "<html lang=\"en\">\n"
270 "<head>\n"
271 "<title>%s</title>\n"
272 "</head>\n"
273 "<body>\n"
274 "<h1>%d %s%s%s%s</h1>\n"
275 "<hr />\n"
276 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
277 "</body>\n"
278 "</html>\n", errname, code, errname,
279 (url_Encoded ? " (" : ""), (url_Encoded ? url_Encoded : ""), (url_Encoded ? ")" : ""));
281 free (url_Encoded);
283 if (res == -1) {
284 *body = NULL;
285 return 0;
288 return (size_t)res;
292 /*****************************************************************************
293 * High Level Functions: httpd_file_t
294 *****************************************************************************/
295 struct httpd_file_t
297 httpd_url_t *url;
298 httpd_file_callback_t pf_fill;
299 httpd_file_sys_t *p_sys;
300 char mime[1];
303 static int
304 httpd_FileCallBack(httpd_callback_sys_t *p_sys, httpd_client_t *cl,
305 httpd_message_t *answer, const httpd_message_t *query)
307 httpd_file_t *file = (httpd_file_t*)p_sys;
308 uint8_t **pp_body, *p_body;
309 int *pi_body, i_body;
311 if (!answer || !query )
312 return VLC_SUCCESS;
314 answer->i_proto = HTTPD_PROTO_HTTP;
315 answer->i_version= 1;
316 answer->i_type = HTTPD_MSG_ANSWER;
318 answer->i_status = 200;
320 httpd_MsgAdd(answer, "Content-type", "%s", file->mime);
321 httpd_MsgAdd(answer, "Cache-Control", "%s", "no-cache");
323 if (query->i_type != HTTPD_MSG_HEAD) {
324 pp_body = &answer->p_body;
325 pi_body = &answer->i_body;
326 } else {
327 /* The file still needs to be executed. */
328 p_body = NULL;
329 i_body = 0;
330 pp_body = &p_body;
331 pi_body = &i_body;
334 if (query->i_type == HTTPD_MSG_POST) {
335 /* msg_Warn not supported */
338 uint8_t *psz_args = query->psz_args;
339 file->pf_fill(file->p_sys, file, psz_args, pp_body, pi_body);
341 if (query->i_type == HTTPD_MSG_HEAD)
342 free(p_body);
344 /* We respect client request */
345 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
346 httpd_MsgAdd(answer, "Connection", "close");
348 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
350 return VLC_SUCCESS;
353 httpd_file_t *httpd_FileNew(httpd_host_t *host,
354 const char *psz_url, const char *psz_mime,
355 const char *psz_user, const char *psz_password,
356 httpd_file_callback_t pf_fill,
357 httpd_file_sys_t *p_sys)
359 const char *mime = psz_mime;
360 if (mime == NULL || mime[0] == '\0')
361 mime = vlc_mime_Ext2Mime(psz_url);
363 size_t mimelen = strlen(mime);
364 httpd_file_t *file = malloc(sizeof(*file) + mimelen);
365 if (unlikely(file == NULL))
366 return NULL;
368 file->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
369 if (!file->url) {
370 free(file);
371 return NULL;
374 file->pf_fill = pf_fill;
375 file->p_sys = p_sys;
376 memcpy(file->mime, mime, mimelen + 1);
378 httpd_UrlCatch(file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
379 (httpd_callback_sys_t*)file);
380 httpd_UrlCatch(file->url, HTTPD_MSG_GET, httpd_FileCallBack,
381 (httpd_callback_sys_t*)file);
382 httpd_UrlCatch(file->url, HTTPD_MSG_POST, httpd_FileCallBack,
383 (httpd_callback_sys_t*)file);
385 return file;
388 httpd_file_sys_t *httpd_FileDelete(httpd_file_t *file)
390 httpd_file_sys_t *p_sys = file->p_sys;
392 httpd_UrlDelete(file->url);
393 free(file);
394 return p_sys;
397 /*****************************************************************************
398 * High Level Functions: httpd_handler_t (for CGIs)
399 *****************************************************************************/
400 struct httpd_handler_t
402 httpd_url_t *url;
404 httpd_handler_callback_t pf_fill;
405 void *p_sys;
409 static int
410 httpd_HandlerCallBack(httpd_callback_sys_t *p_sys, httpd_client_t *cl,
411 httpd_message_t *answer, const httpd_message_t *query)
413 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
414 char psz_remote_addr[NI_MAXNUMERICHOST];
416 if (!answer || !query)
417 return VLC_SUCCESS;
419 answer->i_proto = HTTPD_PROTO_NONE;
420 answer->i_type = HTTPD_MSG_ANSWER;
422 /* We do it ourselves, thanks */
423 answer->i_status = 0;
425 if (!httpd_ClientIP(cl, psz_remote_addr, NULL))
426 *psz_remote_addr = '\0';
428 uint8_t *psz_args = query->psz_args;
429 handler->pf_fill(handler->p_sys, handler, query->psz_url, psz_args,
430 query->i_type, query->p_body, query->i_body,
431 psz_remote_addr, NULL,
432 &answer->p_body, &answer->i_body);
434 if (query->i_type == HTTPD_MSG_HEAD) {
435 char *p = (char *)answer->p_body;
437 /* Looks for end of header (i.e. one empty line) */
438 while ((p = strchr(p, '\r')))
439 if (p[1] == '\n' && p[2] == '\r' && p[3] == '\n')
440 break;
442 if (p) {
443 p[4] = '\0';
444 answer->i_body = strlen((char*)answer->p_body) + 1;
445 answer->p_body = xrealloc(answer->p_body, answer->i_body);
449 if (strncmp((char *)answer->p_body, "HTTP/1.", 7)) {
450 int i_status, i_headers;
451 char *psz_headers, *psz_new;
452 const char *psz_status;
454 if (!strncmp((char *)answer->p_body, "Status: ", 8)) {
455 /* Apache-style */
456 i_status = strtol((char *)&answer->p_body[8], &psz_headers, 0);
457 if (*psz_headers == '\r' || *psz_headers == '\n') psz_headers++;
458 if (*psz_headers == '\n') psz_headers++;
459 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
460 } else {
461 i_status = 200;
462 psz_headers = (char *)answer->p_body;
463 i_headers = answer->i_body;
466 psz_status = httpd_ReasonFromCode(i_status);
467 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
468 + strlen(psz_status) + i_headers - 1;
469 psz_new = (char *)xmalloc(answer->i_body + 1);
470 sprintf(psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status);
471 memcpy(&psz_new[strlen(psz_new)], psz_headers, i_headers);
472 free(answer->p_body);
473 answer->p_body = (uint8_t *)psz_new;
476 return VLC_SUCCESS;
479 httpd_handler_t *httpd_HandlerNew(httpd_host_t *host, const char *psz_url,
480 const char *psz_user,
481 const char *psz_password,
482 httpd_handler_callback_t pf_fill,
483 void *p_sys)
485 httpd_handler_t *handler = malloc(sizeof(*handler));
486 if (!handler)
487 return NULL;
489 handler->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
490 if (!handler->url) {
491 free(handler);
492 return NULL;
495 handler->pf_fill = pf_fill;
496 handler->p_sys = p_sys;
498 httpd_UrlCatch(handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
499 (httpd_callback_sys_t*)handler);
500 httpd_UrlCatch(handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
501 (httpd_callback_sys_t*)handler);
502 httpd_UrlCatch(handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
503 (httpd_callback_sys_t*)handler);
505 return handler;
508 void *httpd_HandlerDelete(httpd_handler_t *handler)
510 void *p_sys = handler->p_sys;
511 httpd_UrlDelete(handler->url);
512 free(handler);
513 return p_sys;
516 /*****************************************************************************
517 * High Level Functions: httpd_redirect_t
518 *****************************************************************************/
519 struct httpd_redirect_t
521 httpd_url_t *url;
522 char dst[1];
525 static int httpd_RedirectCallBack(httpd_callback_sys_t *p_sys,
526 httpd_client_t *cl, httpd_message_t *answer,
527 const httpd_message_t *query)
529 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
530 char *p_body;
531 (void)cl;
533 if (!answer || !query)
534 return VLC_SUCCESS;
536 answer->i_proto = HTTPD_PROTO_HTTP;
537 answer->i_version= 1;
538 answer->i_type = HTTPD_MSG_ANSWER;
539 answer->i_status = 301;
541 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->dst);
542 answer->p_body = (unsigned char *)p_body;
544 /* XXX check if it's ok or we need to set an absolute url */
545 httpd_MsgAdd(answer, "Location", "%s", rdir->dst);
547 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
549 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
550 httpd_MsgAdd(answer, "Connection", "close");
552 return VLC_SUCCESS;
555 httpd_redirect_t *httpd_RedirectNew(httpd_host_t *host, const char *psz_url_dst,
556 const char *psz_url_src)
558 size_t dstlen = strlen(psz_url_dst);
560 httpd_redirect_t *rdir = malloc(sizeof(*rdir) + dstlen);
561 if (unlikely(rdir == NULL))
562 return NULL;
564 rdir->url = httpd_UrlNew(host, psz_url_src, NULL, NULL);
565 if (!rdir->url) {
566 free(rdir);
567 return NULL;
569 memcpy(rdir->dst, psz_url_dst, dstlen + 1);
571 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
572 httpd_UrlCatch(rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
573 (httpd_callback_sys_t*)rdir);
574 httpd_UrlCatch(rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
575 (httpd_callback_sys_t*)rdir);
576 httpd_UrlCatch(rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
577 (httpd_callback_sys_t*)rdir);
578 httpd_UrlCatch(rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
579 (httpd_callback_sys_t*)rdir);
581 return rdir;
583 void httpd_RedirectDelete(httpd_redirect_t *rdir)
585 httpd_UrlDelete(rdir->url);
586 free(rdir);
589 /*****************************************************************************
590 * High Level Funtions: httpd_stream_t
591 *****************************************************************************/
592 struct httpd_stream_t
594 vlc_mutex_t lock;
595 httpd_url_t *url;
597 char *psz_mime;
599 /* Header to send as first packet */
600 uint8_t *p_header;
601 int i_header;
603 /* Some muxes, in particular the avformat mux, can mark given blocks
604 * as keyframes, to ensure that the stream starts with one.
605 * (This is particularly important for WebM streaming to certain
606 * browsers.) Store if we've ever seen any such keyframe blocks,
607 * and if so, the byte position of the start of the last one. */
608 bool b_has_keyframes;
609 int64_t i_last_keyframe_seen_pos;
611 /* circular buffer */
612 int i_buffer_size; /* buffer size, can't be reallocated smaller */
613 uint8_t *p_buffer; /* buffer */
614 int64_t i_buffer_pos; /* absolute position from beginning */
615 int64_t i_buffer_last_pos; /* a new connection will start with that */
617 /* custom headers */
618 size_t i_http_headers;
619 httpd_header * p_http_headers;
622 static int httpd_StreamCallBack(httpd_callback_sys_t *p_sys,
623 httpd_client_t *cl, httpd_message_t *answer,
624 const httpd_message_t *query)
626 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
628 if (!answer || !query || !cl)
629 return VLC_SUCCESS;
631 if (answer->i_body_offset > 0) {
632 int i_pos;
634 if (answer->i_body_offset >= stream->i_buffer_pos)
635 return VLC_EGENERIC; /* wait, no data available */
637 if (cl->i_keyframe_wait_to_pass >= 0) {
638 if (stream->i_last_keyframe_seen_pos <= cl->i_keyframe_wait_to_pass)
639 /* still waiting for the next keyframe */
640 return VLC_EGENERIC;
642 /* seek to the new keyframe */
643 answer->i_body_offset = stream->i_last_keyframe_seen_pos;
644 cl->i_keyframe_wait_to_pass = -1;
647 if (answer->i_body_offset + stream->i_buffer_size < stream->i_buffer_pos)
648 answer->i_body_offset = stream->i_buffer_last_pos; /* this client isn't fast enough */
650 i_pos = answer->i_body_offset % stream->i_buffer_size;
651 int64_t i_write = stream->i_buffer_pos - answer->i_body_offset;
653 if (i_write > HTTPD_CL_BUFSIZE)
654 i_write = HTTPD_CL_BUFSIZE;
655 else if (i_write <= 0)
656 return VLC_EGENERIC; /* wait, no data available */
658 /* Don't go past the end of the circular buffer */
659 i_write = __MIN(i_write, stream->i_buffer_size - i_pos);
661 /* using HTTPD_MSG_ANSWER -> data available */
662 answer->i_proto = HTTPD_PROTO_HTTP;
663 answer->i_version= 0;
664 answer->i_type = HTTPD_MSG_ANSWER;
666 answer->i_body = i_write;
667 answer->p_body = xmalloc(i_write);
668 memcpy(answer->p_body, &stream->p_buffer[i_pos], i_write);
670 answer->i_body_offset += i_write;
672 return VLC_SUCCESS;
673 } else {
674 answer->i_proto = HTTPD_PROTO_HTTP;
675 answer->i_version= 0;
676 answer->i_type = HTTPD_MSG_ANSWER;
678 answer->i_status = 200;
680 bool b_has_content_type = false;
681 bool b_has_cache_control = false;
683 vlc_mutex_lock(&stream->lock);
684 for (size_t i = 0; i < stream->i_http_headers; i++)
685 if (strncasecmp(stream->p_http_headers[i].name, "Content-Length", 14)) {
686 httpd_MsgAdd(answer, stream->p_http_headers[i].name, "%s",
687 stream->p_http_headers[i].value);
689 if (!strncasecmp(stream->p_http_headers[i].name, "Content-Type", 12))
690 b_has_content_type = true;
691 else if (!strncasecmp(stream->p_http_headers[i].name, "Cache-Control", 13))
692 b_has_cache_control = true;
694 vlc_mutex_unlock(&stream->lock);
696 if (query->i_type != HTTPD_MSG_HEAD) {
697 cl->b_stream_mode = true;
698 vlc_mutex_lock(&stream->lock);
699 /* Send the header */
700 if (stream->i_header > 0) {
701 answer->i_body = stream->i_header;
702 answer->p_body = xmalloc(stream->i_header);
703 memcpy(answer->p_body, stream->p_header, stream->i_header);
705 answer->i_body_offset = stream->i_buffer_last_pos;
706 if (stream->b_has_keyframes)
707 cl->i_keyframe_wait_to_pass = stream->i_last_keyframe_seen_pos;
708 else
709 cl->i_keyframe_wait_to_pass = -1;
710 vlc_mutex_unlock(&stream->lock);
711 } else {
712 httpd_MsgAdd(answer, "Content-Length", "0");
713 answer->i_body_offset = 0;
716 /* FIXME: move to http access_output */
717 if (!strcmp(stream->psz_mime, "video/x-ms-asf-stream")) {
718 bool b_xplaystream = false;
720 httpd_MsgAdd(answer, "Content-type", "application/octet-stream");
721 httpd_MsgAdd(answer, "Server", "Cougar 4.1.0.3921");
722 httpd_MsgAdd(answer, "Pragma", "no-cache");
723 httpd_MsgAdd(answer, "Pragma", "client-id=%lu",
724 vlc_mrand48()&0x7fff);
725 httpd_MsgAdd(answer, "Pragma", "features=\"broadcast\"");
727 /* Check if there is a xPlayStrm=1 */
728 for (size_t i = 0; i < query->i_headers; i++)
729 if (!strcasecmp(query->p_headers[i].name, "Pragma") &&
730 strstr(query->p_headers[i].value, "xPlayStrm=1"))
731 b_xplaystream = true;
733 if (!b_xplaystream)
734 answer->i_body_offset = 0;
735 } else if (!b_has_content_type)
736 httpd_MsgAdd(answer, "Content-type", "%s", stream->psz_mime);
738 if (!b_has_cache_control)
739 httpd_MsgAdd(answer, "Cache-Control", "no-cache");
741 httpd_MsgAdd(answer, "Connection", "close");
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;
904 struct vlc_list hosts;
905 } httpd = { VLC_STATIC_MUTEX, VLC_LIST_INITIALIZER(&httpd.hosts) };
907 static httpd_host_t *httpd_HostCreate(vlc_object_t *p_this,
908 const char *hostvar,
909 const char *portvar,
910 vlc_tls_creds_t *p_tls)
912 httpd_host_t *host;
913 unsigned port = var_InheritInteger(p_this, portvar);
915 /* to be sure to avoid multiple creation */
916 vlc_mutex_lock(&httpd.mutex);
918 /* verify if it already exist */
919 vlc_list_foreach(host, &httpd.hosts, node) {
920 /* cannot mix TLS and non-TLS hosts */
921 if (host->port != port
922 || (host->p_tls != NULL) != (p_tls != NULL))
923 continue;
925 /* Increase existing matching host reference count. */
926 atomic_fetch_add_explicit(&host->ref, 1, memory_order_relaxed);
928 vlc_mutex_unlock(&httpd.mutex);
929 vlc_tls_Delete(p_tls);
930 return host;
933 /* create the new host */
934 host = (httpd_host_t *)vlc_custom_create(p_this, sizeof (*host),
935 "http host");
936 if (!host)
937 goto error;
939 vlc_mutex_init(&host->lock);
940 vlc_cond_init(&host->wait);
941 atomic_init(&host->ref, 1);
943 char *hostname = var_InheritString(p_this, hostvar);
945 host->fds = net_ListenTCP(p_this, hostname, port);
946 free(hostname);
948 if (!host->fds) {
949 msg_Err(p_this, "cannot create socket(s) for HTTP host");
950 goto error;
952 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
954 host->port = port;
955 vlc_list_init(&host->urls);
956 host->client_count = 0;
957 vlc_list_init(&host->clients);
958 host->p_tls = p_tls;
960 /* create the thread */
961 if (vlc_clone(&host->thread, httpd_HostThread, host,
962 VLC_THREAD_PRIORITY_LOW)) {
963 msg_Err(p_this, "cannot spawn http host thread");
964 goto error;
967 /* now add it to httpd */
968 vlc_list_append(&host->node, &httpd.hosts);
969 vlc_mutex_unlock(&httpd.mutex);
971 return host;
973 error:
974 vlc_mutex_unlock(&httpd.mutex);
976 if (host) {
977 net_ListenClose(host->fds);
978 vlc_cond_destroy(&host->wait);
979 vlc_mutex_destroy(&host->lock);
980 vlc_object_release(host);
983 vlc_tls_Delete(p_tls);
984 return NULL;
987 /* delete a host */
988 void httpd_HostDelete(httpd_host_t *host)
990 httpd_client_t *client;
992 vlc_mutex_lock(&httpd.mutex);
994 if (atomic_fetch_sub_explicit(&host->ref, 1, memory_order_relaxed) > 1) {
995 /* still used */
996 vlc_mutex_unlock(&httpd.mutex);
997 msg_Dbg(host, "httpd_HostDelete: host still in use");
998 return;
1001 vlc_list_remove(&host->node);
1002 vlc_cancel(host->thread);
1003 vlc_join(host->thread, NULL);
1005 msg_Dbg(host, "HTTP host removed");
1007 vlc_list_foreach(client, &host->clients, node) {
1008 msg_Warn(host, "client still connected");
1009 httpd_ClientDestroy(client);
1012 assert(vlc_list_is_empty(&host->urls));
1013 vlc_tls_Delete(host->p_tls);
1014 net_ListenClose(host->fds);
1015 vlc_cond_destroy(&host->wait);
1016 vlc_mutex_destroy(&host->lock);
1017 vlc_object_release(host);
1018 vlc_mutex_unlock(&httpd.mutex);
1021 /* register a new url */
1022 httpd_url_t *httpd_UrlNew(httpd_host_t *host, const char *psz_url,
1023 const char *psz_user, const char *psz_password)
1025 httpd_url_t *url;
1027 assert(psz_url);
1029 vlc_mutex_lock(&host->lock);
1030 vlc_list_foreach(url, &host->urls, node)
1031 if (!strcmp(psz_url, url->psz_url)) {
1032 msg_Warn(host, "cannot add '%s' (url already defined)", psz_url);
1033 vlc_mutex_unlock(&host->lock);
1034 return NULL;
1037 url = malloc(sizeof (*url));
1038 if (unlikely(url == NULL)) {
1039 vlc_mutex_unlock(&host->lock);
1040 return NULL;
1043 url->host = host;
1045 vlc_mutex_init(&url->lock);
1046 url->psz_url = xstrdup(psz_url);
1047 url->psz_user = xstrdup(psz_user ? psz_user : "");
1048 url->psz_password = xstrdup(psz_password ? psz_password : "");
1049 for (int i = 0; i < HTTPD_MSG_MAX; i++) {
1050 url->catch[i].cb = NULL;
1051 url->catch[i].p_sys = NULL;
1054 vlc_list_append(&url->node, &host->urls);
1055 vlc_cond_signal(&host->wait);
1056 vlc_mutex_unlock(&host->lock);
1058 return url;
1061 /* register callback on a url */
1062 int httpd_UrlCatch(httpd_url_t *url, int i_msg, httpd_callback_t cb,
1063 httpd_callback_sys_t *p_sys)
1065 vlc_mutex_lock(&url->lock);
1066 url->catch[i_msg].cb = cb;
1067 url->catch[i_msg].p_sys= p_sys;
1068 vlc_mutex_unlock(&url->lock);
1070 return VLC_SUCCESS;
1073 /* delete a url */
1074 void httpd_UrlDelete(httpd_url_t *url)
1076 httpd_host_t *host = url->host;
1077 httpd_client_t *client;
1079 vlc_mutex_lock(&host->lock);
1080 vlc_list_remove(&url->node);
1082 vlc_mutex_destroy(&url->lock);
1083 free(url->psz_url);
1084 free(url->psz_user);
1085 free(url->psz_password);
1087 vlc_list_foreach(client, &host->clients, node) {
1088 if (client->url != url)
1089 continue;
1091 /* TODO complete it */
1092 msg_Warn(host, "force closing connections");
1093 host->client_count--;
1094 httpd_ClientDestroy(client);
1096 free(url);
1097 vlc_mutex_unlock(&host->lock);
1100 static void httpd_MsgInit(httpd_message_t *msg)
1102 msg->cl = NULL;
1103 msg->i_type = HTTPD_MSG_NONE;
1104 msg->i_proto = HTTPD_PROTO_NONE;
1105 msg->i_version = -1; /* FIXME */
1107 msg->i_status = 0;
1109 msg->psz_url = NULL;
1110 msg->psz_args = NULL;
1112 msg->i_headers = 0;
1113 msg->p_headers = NULL;
1115 msg->i_body_offset = 0;
1116 msg->i_body = 0;
1117 msg->p_body = NULL;
1120 static void httpd_MsgClean(httpd_message_t *msg)
1122 free(msg->psz_url);
1123 free(msg->psz_args);
1124 for (size_t i = 0; i < msg->i_headers; i++) {
1125 free(msg->p_headers[i].name);
1126 free(msg->p_headers[i].value);
1128 free(msg->p_headers);
1129 free(msg->p_body);
1130 httpd_MsgInit(msg);
1133 const char *httpd_MsgGet(const httpd_message_t *msg, const char *name)
1135 for (size_t i = 0; i < msg->i_headers; i++)
1136 if (!strcasecmp(msg->p_headers[i].name, name))
1137 return msg->p_headers[i].value;
1138 return NULL;
1141 void httpd_MsgAdd(httpd_message_t *msg, const char *name, const char *psz_value, ...)
1143 httpd_header *p_tmp = realloc(msg->p_headers, sizeof(httpd_header) * (msg->i_headers + 1));
1144 if (!p_tmp)
1145 return;
1147 msg->p_headers = p_tmp;
1149 httpd_header *h = &msg->p_headers[msg->i_headers];
1150 h->name = strdup(name);
1151 if (!h->name)
1152 return;
1154 h->value = NULL;
1156 va_list args;
1157 va_start(args, psz_value);
1158 int ret = us_vasprintf(&h->value, psz_value, args);
1159 va_end(args);
1161 if (ret == -1) {
1162 free(h->name);
1163 return;
1166 msg->i_headers++;
1169 static void httpd_ClientInit(httpd_client_t *cl, vlc_tick_t now)
1171 cl->i_state = HTTPD_CLIENT_RECEIVING;
1172 cl->i_activity_date = now;
1173 cl->i_activity_timeout = VLC_TICK_FROM_SEC(10);
1174 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1175 cl->i_buffer = 0;
1176 cl->p_buffer = xmalloc(cl->i_buffer_size);
1177 cl->i_keyframe_wait_to_pass = -1;
1178 cl->b_stream_mode = false;
1180 httpd_MsgInit(&cl->query);
1181 httpd_MsgInit(&cl->answer);
1184 char* httpd_ClientIP(const httpd_client_t *cl, char *ip, int *port)
1186 return net_GetPeerAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1189 char* httpd_ServerIP(const httpd_client_t *cl, char *ip, int *port)
1191 return net_GetSockAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1194 static void httpd_ClientDestroy(httpd_client_t *cl)
1196 vlc_list_remove(&cl->node);
1197 vlc_tls_Close(cl->sock);
1198 httpd_MsgClean(&cl->answer);
1199 httpd_MsgClean(&cl->query);
1201 free(cl->p_buffer);
1202 free(cl);
1205 static httpd_client_t *httpd_ClientNew(vlc_tls_t *sock, vlc_tick_t now)
1207 httpd_client_t *cl = malloc(sizeof(httpd_client_t));
1209 if (!cl) return NULL;
1211 cl->sock = sock;
1212 cl->url = NULL;
1214 httpd_ClientInit(cl, now);
1215 return cl;
1218 static
1219 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1221 vlc_tls_t *sock = cl->sock;
1222 struct iovec iov = { .iov_base = p, .iov_len = i_len };
1223 return sock->ops->readv(sock, &iov, 1);
1226 static
1227 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1229 vlc_tls_t *sock = cl->sock;
1230 const struct iovec iov = { .iov_base = (void *)p, .iov_len = i_len };
1231 return sock->ops->writev(sock, &iov, 1);
1235 static const struct
1237 const char name[16];
1238 int i_type;
1239 int i_proto;
1241 msg_type[] =
1243 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1244 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1245 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1246 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1247 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1248 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1249 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1250 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1251 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1252 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1253 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1257 static void httpd_ClientRecv(httpd_client_t *cl)
1259 int i_len;
1261 /* ignore leading whites */
1262 if (cl->query.i_proto == HTTPD_PROTO_NONE && cl->i_buffer == 0) {
1263 unsigned char c;
1265 i_len = httpd_NetRecv(cl, &c, 1);
1267 if (i_len > 0 && !strchr("\r\n\t ", c)) {
1268 cl->p_buffer[0] = c;
1269 cl->i_buffer++;
1271 } else if (cl->query.i_proto == HTTPD_PROTO_NONE) {
1272 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1273 i_len = httpd_NetRecv(cl, &cl->p_buffer[cl->i_buffer],
1274 7 - cl->i_buffer);
1275 if (i_len > 0)
1276 cl->i_buffer += i_len;
1278 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1279 * this is the maximum we can ask at this point. */
1280 if (cl->i_buffer >= 7) {
1281 if (!memcmp(cl->p_buffer, "HTTP/1.", 7)) {
1282 cl->query.i_proto = HTTPD_PROTO_HTTP;
1283 cl->query.i_type = HTTPD_MSG_ANSWER;
1284 } else if (!memcmp(cl->p_buffer, "RTSP/1.", 7)) {
1285 cl->query.i_proto = HTTPD_PROTO_RTSP;
1286 cl->query.i_type = HTTPD_MSG_ANSWER;
1287 } else {
1288 /* We need the full request line to determine the protocol. */
1289 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1290 cl->query.i_type = HTTPD_MSG_NONE;
1293 } else if (cl->query.i_body > 0) {
1294 /* we are reading the body of a request or a channel */
1295 assert (cl->query.p_body != NULL);
1296 i_len = httpd_NetRecv(cl, &cl->query.p_body[cl->i_buffer],
1297 cl->query.i_body - cl->i_buffer);
1298 if (i_len > 0)
1299 cl->i_buffer += i_len;
1301 if (cl->i_buffer >= cl->query.i_body)
1302 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1303 } else for (;;) { /* we are reading a header -> char by char */
1304 if (cl->i_buffer == cl->i_buffer_size) {
1305 // Allocate an extra byte for the termination null byte
1306 uint8_t *newbuf = realloc(cl->p_buffer, cl->i_buffer_size + 1025);
1307 if (!newbuf) {
1308 i_len = 0;
1309 break;
1312 cl->p_buffer = newbuf;
1313 cl->i_buffer_size += 1024;
1316 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1);
1317 if (i_len <= 0)
1318 break;
1320 cl->i_buffer++;
1322 if ((cl->query.i_proto == HTTPD_PROTO_HTTP0)
1323 && (cl->p_buffer[cl->i_buffer - 1] == '\n'))
1325 /* Request line is now complete */
1326 const char *p = memchr(cl->p_buffer, ' ', cl->i_buffer);
1327 size_t len;
1329 assert(cl->query.i_type == HTTPD_MSG_NONE);
1331 if (!p) { /* no URI: evil guy */
1332 i_len = 0; /* drop connection */
1333 break;
1337 p++; /* skips extra spaces */
1338 while (*p == ' ');
1340 p = memchr(p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p);
1341 if (!p) { /* no explicit protocol: HTTP/0.9 */
1342 i_len = 0; /* not supported currently -> drop */
1343 break;
1347 p++; /* skips extra spaces ever again */
1348 while (*p == ' ');
1350 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1351 if (len < 7) /* foreign protocol */
1352 i_len = 0; /* I don't understand -> drop */
1353 else if (!memcmp(p, "HTTP/1.", 7)) {
1354 cl->query.i_proto = HTTPD_PROTO_HTTP;
1355 cl->query.i_version = atoi(p + 7);
1356 } else if (!memcmp(p, "RTSP/1.", 7)) {
1357 cl->query.i_proto = HTTPD_PROTO_RTSP;
1358 cl->query.i_version = atoi(p + 7);
1359 } else if (!memcmp(p, "HTTP/", 5)) {
1360 const uint8_t sorry[] =
1361 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1362 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1363 i_len = 0; /* drop */
1364 } else if (!memcmp(p, "RTSP/", 5)) {
1365 const uint8_t sorry[] =
1366 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1367 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1368 i_len = 0; /* drop */
1369 } else /* yet another foreign protocol */
1370 i_len = 0;
1372 if (i_len == 0)
1373 break;
1376 if ((cl->i_buffer >= 2 && !memcmp(&cl->p_buffer[cl->i_buffer-2], "\n\n", 2))||
1377 (cl->i_buffer >= 4 && !memcmp(&cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4)))
1379 char *p;
1381 /* we have finished the header so parse it and set i_body */
1382 cl->p_buffer[cl->i_buffer] = '\0';
1384 if (cl->query.i_type == HTTPD_MSG_ANSWER) {
1385 /* FIXME:
1386 * assume strlen("HTTP/1.x") = 8
1388 cl->query.i_status =
1389 strtol((char *)&cl->p_buffer[8],
1390 &p, 0);
1391 while (*p == ' ')
1392 p++;
1393 } else {
1394 p = NULL;
1395 cl->query.i_type = HTTPD_MSG_NONE;
1397 for (unsigned i = 0; msg_type[i].name[0]; i++)
1398 if (!strncmp((char *)cl->p_buffer, msg_type[i].name,
1399 strlen(msg_type[i].name))) {
1400 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1401 cl->query.i_type = msg_type[i].i_type;
1402 if (cl->query.i_proto != msg_type[i].i_proto) {
1403 p = NULL;
1404 cl->query.i_proto = HTTPD_PROTO_NONE;
1405 cl->query.i_type = HTTPD_MSG_NONE;
1407 break;
1410 if (!p) {
1411 if (strstr((char *)cl->p_buffer, "HTTP/1."))
1412 cl->query.i_proto = HTTPD_PROTO_HTTP;
1413 else if (strstr((char *)cl->p_buffer, "RTSP/1."))
1414 cl->query.i_proto = HTTPD_PROTO_RTSP;
1415 } else {
1416 char *p2;
1417 char *p3;
1419 while (*p == ' ')
1420 p++;
1422 p2 = strchr(p, ' ');
1423 if (p2)
1424 *p2++ = '\0';
1426 if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "http:" : "rtsp:", 5)) {
1427 /* Skip hier-part of URL (if present) */
1428 p += 5;
1429 if (!strncmp(p, "//", 2)) { /* skip authority */
1430 /* see RFC3986 §3.2 */
1431 p += 2;
1432 p += strcspn(p, "/?#");
1435 else if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "https:" : "rtsps:", 6)) {
1436 /* Skip hier-part of URL (if present) */
1437 p += 6;
1438 if (!strncmp(p, "//", 2)) { /* skip authority */
1439 /* see RFC3986 §3.2 */
1440 p += 2;
1441 p += strcspn(p, "/?#");
1445 if(cl->query.psz_url == NULL) {
1446 cl->query.psz_url = strdup(p);
1447 if ((p3 = strchr(cl->query.psz_url, '?')) ) {
1448 *p3++ = '\0';
1449 cl->query.psz_args = (uint8_t *)strdup(p3);
1452 p = p2;
1455 if (p)
1456 p = strchr(p, '\n');
1458 if (p) {
1459 while (*p == '\n' || *p == '\r')
1460 p++;
1462 while (p && *p) {
1463 char *line = p;
1464 char *eol = p = strchr(p, '\n');
1465 char *colon;
1467 while (eol && eol >= line && (*eol == '\n' || *eol == '\r'))
1468 *eol-- = '\0';
1470 if ((colon = strchr(line, ':'))) {
1471 *colon++ = '\0';
1472 while (*colon == ' ')
1473 colon++;
1474 httpd_MsgAdd(&cl->query, line, "%s", colon);
1476 if (!strcasecmp(line, "Content-Length"))
1477 cl->query.i_body = atol(colon);
1480 if (p) {
1481 p++;
1482 while (*p == '\n' || *p == '\r')
1483 p++;
1487 if (cl->query.i_body > 0) {
1488 /* TODO Mhh, handle the case where the client only
1489 * sends a request and closes the connection to
1490 * mark the end of the body (probably only RTSP) */
1491 if (cl->query.i_body < 65536)
1492 cl->query.p_body = malloc(cl->query.i_body);
1493 else
1494 cl->query.p_body = NULL;
1495 cl->i_buffer = 0;
1496 if (!cl->query.p_body) {
1497 switch (cl->query.i_proto) {
1498 case HTTPD_PROTO_HTTP: {
1499 const uint8_t sorry[] = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1500 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1501 break;
1503 case HTTPD_PROTO_RTSP: {
1504 const uint8_t sorry[] = "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1505 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1506 break;
1508 default:
1509 vlc_assert_unreachable();
1511 i_len = 0; /* drop */
1513 break;
1514 } else
1515 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1519 /* check if the client is to be set to dead */
1520 #if defined(_WIN32)
1521 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1522 #else
1523 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1524 #endif
1526 if (cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE) {
1527 /* connection closed -> end of data */
1528 if (cl->query.i_body > 0)
1529 cl->query.i_body = cl->i_buffer;
1530 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1532 else
1533 cl->i_state = HTTPD_CLIENT_DEAD;
1536 /* XXX: for QT I have to disable timeout. Try to find why */
1537 if (cl->query.i_proto == HTTPD_PROTO_RTSP)
1538 cl->i_activity_timeout = 0;
1541 static void httpd_ClientSend(httpd_client_t *cl)
1543 int i_len;
1545 if (cl->i_buffer < 0) {
1546 /* We need to create the header */
1547 int i_size = 0;
1548 char *p;
1549 const char *psz_status = httpd_ReasonFromCode(cl->answer.i_status);
1551 i_size = strlen("HTTP/1.") + 10 + 10 + strlen(psz_status) + 5;
1552 for (size_t i = 0; i < cl->answer.i_headers; i++)
1553 i_size += strlen(cl->answer.p_headers[i].name) + 2 +
1554 strlen(cl->answer.p_headers[i].value) + 2;
1556 if (cl->i_buffer_size < i_size) {
1557 cl->i_buffer_size = i_size;
1558 free(cl->p_buffer);
1559 cl->p_buffer = xmalloc(i_size);
1561 p = (char *)cl->p_buffer;
1563 p += sprintf(p, "%s.%" PRIu8 " %d %s\r\n",
1564 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1565 cl->answer.i_version,
1566 cl->answer.i_status, psz_status);
1567 for (size_t i = 0; i < cl->answer.i_headers; i++)
1568 p += sprintf(p, "%s: %s\r\n", cl->answer.p_headers[i].name,
1569 cl->answer.p_headers[i].value);
1570 p += sprintf(p, "\r\n");
1572 cl->i_buffer = 0;
1573 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1576 i_len = httpd_NetSend(cl, &cl->p_buffer[cl->i_buffer],
1577 cl->i_buffer_size - cl->i_buffer);
1578 if (i_len >= 0) {
1579 cl->i_buffer += i_len;
1581 if (cl->i_buffer >= cl->i_buffer_size) {
1582 if (cl->answer.i_body == 0 && cl->answer.i_body_offset > 0) {
1583 /* catch more body data */
1584 int i_msg = cl->query.i_type;
1585 int64_t i_offset = cl->answer.i_body_offset;
1587 httpd_MsgClean(&cl->answer);
1588 cl->answer.i_body_offset = i_offset;
1590 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1591 &cl->answer, &cl->query);
1594 if (cl->answer.i_body > 0) {
1595 /* send the body data */
1596 free(cl->p_buffer);
1597 cl->p_buffer = cl->answer.p_body;
1598 cl->i_buffer_size = cl->answer.i_body;
1599 cl->i_buffer = 0;
1601 cl->answer.i_body = 0;
1602 cl->answer.p_body = NULL;
1603 } else /* send finished */
1604 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1606 } else {
1607 #if defined(_WIN32)
1608 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1609 #else
1610 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1611 #endif
1613 /* error */
1614 cl->i_state = HTTPD_CLIENT_DEAD;
1619 static void httpd_ClientTlsHandshake(httpd_host_t *host, httpd_client_t *cl)
1621 switch (vlc_tls_SessionHandshake(host->p_tls, cl->sock))
1623 case -1: cl->i_state = HTTPD_CLIENT_DEAD; break;
1624 case 0: cl->i_state = HTTPD_CLIENT_RECEIVING; break;
1625 case 1: cl->i_state = HTTPD_CLIENT_TLS_HS_IN; break;
1626 case 2: cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1630 static bool httpdAuthOk(const char *user, const char *pass, const char *b64)
1632 if (!*user && !*pass)
1633 return true;
1635 if (!b64)
1636 return false;
1638 if (strncasecmp(b64, "BASIC", 5))
1639 return false;
1641 b64 += 5;
1642 while (*b64 == ' ')
1643 b64++;
1645 char *given_user = vlc_b64_decode(b64);
1646 if (!given_user)
1647 return false;
1649 char *given_pass = NULL;
1650 given_pass = strchr (given_user, ':');
1651 if (!given_pass)
1652 goto auth_failed;
1654 *given_pass++ = '\0';
1656 if (strcmp (given_user, user))
1657 goto auth_failed;
1659 if (strcmp (given_pass, pass))
1660 goto auth_failed;
1662 free(given_user);
1663 return true;
1665 auth_failed:
1666 free(given_user);
1667 return false;
1670 static void httpdLoop(httpd_host_t *host)
1672 struct pollfd ufd[host->nfd + host->client_count];
1673 unsigned nfd;
1674 for (nfd = 0; nfd < host->nfd; nfd++) {
1675 ufd[nfd].fd = host->fds[nfd];
1676 ufd[nfd].events = POLLIN;
1677 ufd[nfd].revents = 0;
1680 vlc_mutex_lock(&host->lock);
1681 /* add all socket that should be read/write and close dead connection */
1682 while (vlc_list_is_empty(&host->urls)) {
1683 mutex_cleanup_push(&host->lock);
1684 vlc_cond_wait(&host->wait, &host->lock);
1685 vlc_cleanup_pop();
1688 vlc_tick_t now = vlc_tick_now();
1689 bool b_low_delay = false;
1690 httpd_client_t *cl;
1692 int canc = vlc_savecancel();
1693 vlc_list_foreach(cl, &host->clients, node) {
1694 int64_t i_offset;
1696 if (cl->i_state == HTTPD_CLIENT_DEAD
1697 || (cl->i_activity_timeout > 0
1698 && cl->i_activity_date + cl->i_activity_timeout < now)) {
1699 host->client_count--;
1700 httpd_ClientDestroy(cl);
1701 continue;
1704 struct pollfd *pufd = ufd + nfd;
1705 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1707 pufd->fd = vlc_tls_GetFD(cl->sock);
1708 pufd->events = pufd->revents = 0;
1710 switch (cl->i_state) {
1711 case HTTPD_CLIENT_RECEIVING:
1712 case HTTPD_CLIENT_TLS_HS_IN:
1713 pufd->events = POLLIN;
1714 break;
1716 case HTTPD_CLIENT_SENDING:
1717 case HTTPD_CLIENT_TLS_HS_OUT:
1718 pufd->events = POLLOUT;
1719 break;
1721 case HTTPD_CLIENT_RECEIVE_DONE: {
1722 httpd_message_t *answer = &cl->answer;
1723 httpd_message_t *query = &cl->query;
1725 httpd_MsgInit(answer);
1727 /* Handle what we received */
1728 switch (query->i_type) {
1729 case HTTPD_MSG_ANSWER:
1730 cl->url = NULL;
1731 cl->i_state = HTTPD_CLIENT_DEAD;
1732 break;
1734 case HTTPD_MSG_OPTIONS:
1735 answer->i_type = HTTPD_MSG_ANSWER;
1736 answer->i_proto = query->i_proto;
1737 answer->i_status = 200;
1738 answer->i_body = 0;
1739 answer->p_body = NULL;
1741 httpd_MsgAdd(answer, "Server", "VLC/%s", VERSION);
1742 httpd_MsgAdd(answer, "Content-Length", "0");
1744 switch(query->i_proto) {
1745 case HTTPD_PROTO_HTTP:
1746 answer->i_version = 1;
1747 httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
1748 break;
1750 case HTTPD_PROTO_RTSP:
1751 answer->i_version = 0;
1753 const char *p = httpd_MsgGet(query, "Cseq");
1754 if (p)
1755 httpd_MsgAdd(answer, "Cseq", "%s", p);
1756 p = httpd_MsgGet(query, "Timestamp");
1757 if (p)
1758 httpd_MsgAdd(answer, "Timestamp", "%s", p);
1760 p = httpd_MsgGet(query, "Require");
1761 if (p) {
1762 answer->i_status = 551;
1763 httpd_MsgAdd(query, "Unsupported", "%s", p);
1766 httpd_MsgAdd(answer, "Public", "DESCRIBE,SETUP,"
1767 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER");
1768 break;
1771 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
1772 httpd_MsgAdd(answer, "Connection", "close");
1774 cl->i_buffer = -1; /* Force the creation of the answer in
1775 * httpd_ClientSend */
1776 cl->i_state = HTTPD_CLIENT_SENDING;
1777 break;
1779 case HTTPD_MSG_NONE:
1780 if (query->i_proto == HTTPD_PROTO_NONE) {
1781 cl->url = NULL;
1782 cl->i_state = HTTPD_CLIENT_DEAD;
1783 } else {
1784 /* unimplemented */
1785 answer->i_proto = query->i_proto ;
1786 answer->i_type = HTTPD_MSG_ANSWER;
1787 answer->i_version= 0;
1788 answer->i_status = 501;
1790 char *p;
1791 answer->i_body = httpd_HtmlError (&p, 501, NULL);
1792 answer->p_body = (uint8_t *)p;
1793 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1794 httpd_MsgAdd(answer, "Connection", "close");
1796 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1797 cl->i_state = HTTPD_CLIENT_SENDING;
1799 break;
1801 default: {
1802 httpd_url_t *url;
1803 int i_msg = query->i_type;
1804 bool b_auth_failed = false;
1806 /* Search the url and trigger callbacks */
1807 vlc_list_foreach(url, &host->urls, node) {
1808 if (strcmp(url->psz_url, query->psz_url))
1809 continue;
1810 if (!url->catch[i_msg].cb)
1811 continue;
1813 if (answer) {
1814 b_auth_failed = !httpdAuthOk(url->psz_user,
1815 url->psz_password,
1816 httpd_MsgGet(query, "Authorization")); /* BASIC id */
1817 if (b_auth_failed)
1818 break;
1821 if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
1822 continue;
1824 if (answer->i_proto == HTTPD_PROTO_NONE)
1825 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
1826 else
1827 cl->i_buffer = -1;
1829 /* only one url can answer */
1830 answer = NULL;
1831 if (!cl->url)
1832 cl->url = url;
1835 if (answer) {
1836 answer->i_proto = query->i_proto;
1837 answer->i_type = HTTPD_MSG_ANSWER;
1838 answer->i_version= 0;
1840 if (b_auth_failed) {
1841 httpd_MsgAdd(answer, "WWW-Authenticate",
1842 "Basic realm=\"VLC stream\"");
1843 answer->i_status = 401;
1844 } else
1845 answer->i_status = 404; /* no url registered */
1847 char *p;
1848 answer->i_body = httpd_HtmlError (&p, answer->i_status,
1849 query->psz_url);
1850 answer->p_body = (uint8_t *)p;
1852 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1853 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1854 httpd_MsgAdd(answer, "Content-Type", "%s", "text/html");
1855 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
1856 httpd_MsgAdd(answer, "Connection", "close");
1859 cl->i_state = HTTPD_CLIENT_SENDING;
1862 break;
1865 case HTTPD_CLIENT_SEND_DONE:
1866 if (!cl->b_stream_mode || cl->answer.i_body_offset == 0) {
1867 bool do_close = false;
1869 cl->url = NULL;
1871 if (cl->query.i_proto != HTTPD_PROTO_HTTP
1872 || cl->query.i_version > 0)
1874 const char *psz_connection = httpd_MsgGet(&cl->answer,
1875 "Connection");
1876 if (psz_connection != NULL)
1877 do_close = !strcasecmp(psz_connection, "close");
1879 else
1880 do_close = true;
1882 if (!do_close) {
1883 httpd_MsgClean(&cl->query);
1884 httpd_MsgInit(&cl->query);
1886 cl->i_buffer = 0;
1887 cl->i_buffer_size = 1000;
1888 free(cl->p_buffer);
1889 // Allocate an extra byte for the null terminating byte
1890 cl->p_buffer = xmalloc(cl->i_buffer_size + 1);
1891 cl->i_state = HTTPD_CLIENT_RECEIVING;
1892 } else
1893 cl->i_state = HTTPD_CLIENT_DEAD;
1894 httpd_MsgClean(&cl->answer);
1895 } else {
1896 i_offset = cl->answer.i_body_offset;
1897 httpd_MsgClean(&cl->answer);
1899 cl->answer.i_body_offset = i_offset;
1900 free(cl->p_buffer);
1901 cl->p_buffer = NULL;
1902 cl->i_buffer = 0;
1903 cl->i_buffer_size = 0;
1905 cl->i_state = HTTPD_CLIENT_WAITING;
1907 break;
1909 case HTTPD_CLIENT_WAITING:
1910 i_offset = cl->answer.i_body_offset;
1911 int i_msg = cl->query.i_type;
1913 httpd_MsgInit(&cl->answer);
1914 cl->answer.i_body_offset = i_offset;
1916 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1917 &cl->answer, &cl->query);
1918 if (cl->answer.i_type != HTTPD_MSG_NONE) {
1919 /* we have new data, so re-enter send mode */
1920 cl->i_buffer = 0;
1921 cl->p_buffer = cl->answer.p_body;
1922 cl->i_buffer_size = cl->answer.i_body;
1923 cl->answer.p_body = NULL;
1924 cl->answer.i_body = 0;
1925 cl->i_state = HTTPD_CLIENT_SENDING;
1929 if (pufd->events != 0)
1930 nfd++;
1931 else
1932 b_low_delay = true;
1934 vlc_mutex_unlock(&host->lock);
1935 vlc_restorecancel(canc);
1937 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
1938 while (poll(ufd, nfd, b_low_delay ? 20 : -1) < 0)
1940 if (errno != EINTR)
1941 msg_Err(host, "polling error: %s", vlc_strerror_c(errno));
1944 canc = vlc_savecancel();
1945 vlc_mutex_lock(&host->lock);
1947 /* Handle client sockets */
1948 now = vlc_tick_now();
1949 nfd = host->nfd;
1951 vlc_list_foreach(cl, &host->clients, node) {
1952 const struct pollfd *pufd = &ufd[nfd];
1954 assert(pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])]);
1956 if (vlc_tls_GetFD(cl->sock) != pufd->fd)
1957 continue; // we were not waiting for this client
1958 ++nfd;
1959 if (pufd->revents == 0)
1960 continue; // no event received
1962 cl->i_activity_date = now;
1964 switch (cl->i_state) {
1965 case HTTPD_CLIENT_RECEIVING: httpd_ClientRecv(cl); break;
1966 case HTTPD_CLIENT_SENDING: httpd_ClientSend(cl); break;
1967 case HTTPD_CLIENT_TLS_HS_IN:
1968 case HTTPD_CLIENT_TLS_HS_OUT:
1969 httpd_ClientTlsHandshake(host, cl);
1970 break;
1974 /* Handle server sockets (accept new connections) */
1975 for (nfd = 0; nfd < host->nfd; nfd++) {
1976 int fd = ufd[nfd].fd;
1978 assert (fd == host->fds[nfd]);
1980 if (ufd[nfd].revents == 0)
1981 continue;
1983 /* */
1984 fd = vlc_accept (fd, NULL, NULL, true);
1985 if (fd == -1)
1986 continue;
1987 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1988 &(int){ 1 }, sizeof(int));
1990 vlc_tls_t *sk = vlc_tls_SocketOpen(fd);
1991 if (unlikely(sk == NULL))
1993 vlc_close(fd);
1994 continue;
1997 if (host->p_tls != NULL)
1999 const char *alpn[] = { "http/1.1", NULL };
2000 vlc_tls_t *tls;
2002 tls = vlc_tls_ServerSessionCreate(host->p_tls, sk, alpn);
2003 if (tls == NULL)
2005 vlc_tls_SessionDelete(sk);
2006 continue;
2008 sk = tls;
2011 cl = httpd_ClientNew(sk, now);
2013 if (host->p_tls != NULL)
2014 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2016 host->client_count++;
2017 vlc_list_append(&cl->node, &host->clients);
2020 vlc_mutex_unlock(&host->lock);
2021 vlc_restorecancel(canc);
2024 static void* httpd_HostThread(void *data)
2026 httpd_host_t *host = data;
2028 while (atomic_load_explicit(&host->ref, memory_order_relaxed) > 0)
2029 httpdLoop(host);
2030 return NULL;
2033 int httpd_StreamSetHTTPHeaders(httpd_stream_t * p_stream,
2034 const httpd_header *p_headers, size_t i_headers)
2036 if (!p_stream)
2037 return VLC_EGENERIC;
2039 vlc_mutex_lock(&p_stream->lock);
2040 if (p_stream->p_http_headers) {
2041 for (size_t i = 0; i < p_stream->i_http_headers; i++) {
2042 free(p_stream->p_http_headers[i].name);
2043 free(p_stream->p_http_headers[i].value);
2045 free(p_stream->p_http_headers);
2046 p_stream->p_http_headers = NULL;
2047 p_stream->i_http_headers = 0;
2050 if (!p_headers || !i_headers) {
2051 vlc_mutex_unlock(&p_stream->lock);
2052 return VLC_SUCCESS;
2055 p_stream->p_http_headers = vlc_alloc(i_headers, sizeof(httpd_header));
2056 if (!p_stream->p_http_headers) {
2057 vlc_mutex_unlock(&p_stream->lock);
2058 return VLC_ENOMEM;
2061 size_t j = 0;
2062 for (size_t i = 0; i < i_headers; i++) {
2063 if (unlikely(!p_headers[i].name || !p_headers[i].value))
2064 continue;
2066 p_stream->p_http_headers[j].name = strdup(p_headers[i].name);
2067 p_stream->p_http_headers[j].value = strdup(p_headers[i].value);
2069 if (unlikely(!p_stream->p_http_headers[j].name ||
2070 !p_stream->p_http_headers[j].value)) {
2071 free(p_stream->p_http_headers[j].name);
2072 free(p_stream->p_http_headers[j].value);
2073 break;
2075 j++;
2077 p_stream->i_http_headers = j;
2078 vlc_mutex_unlock(&p_stream->lock);
2079 return VLC_SUCCESS;