cf_filters: remove -miphoneos-version-min=9.0 OBJCFLAGS
[vlc.git] / src / network / httpd.c
blob3e27406b5ce854059302214ced87554795e1a2c1
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;
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 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
351 httpd_MsgAdd(answer, "Connection", "close");
353 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
355 return VLC_SUCCESS;
358 httpd_file_t *httpd_FileNew(httpd_host_t *host,
359 const char *psz_url, const char *psz_mime,
360 const char *psz_user, const char *psz_password,
361 httpd_file_callback_t pf_fill,
362 httpd_file_sys_t *p_sys)
364 const char *mime = psz_mime;
365 if (mime == NULL || mime[0] == '\0')
366 mime = vlc_mime_Ext2Mime(psz_url);
368 size_t mimelen = strlen(mime);
369 httpd_file_t *file = malloc(sizeof(*file) + mimelen);
370 if (unlikely(file == NULL))
371 return NULL;
373 file->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
374 if (!file->url) {
375 free(file);
376 return NULL;
379 file->pf_fill = pf_fill;
380 file->p_sys = p_sys;
381 memcpy(file->mime, mime, mimelen + 1);
383 httpd_UrlCatch(file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
384 (httpd_callback_sys_t*)file);
385 httpd_UrlCatch(file->url, HTTPD_MSG_GET, httpd_FileCallBack,
386 (httpd_callback_sys_t*)file);
387 httpd_UrlCatch(file->url, HTTPD_MSG_POST, httpd_FileCallBack,
388 (httpd_callback_sys_t*)file);
390 return file;
393 httpd_file_sys_t *httpd_FileDelete(httpd_file_t *file)
395 httpd_file_sys_t *p_sys = file->p_sys;
397 httpd_UrlDelete(file->url);
398 free(file);
399 return p_sys;
402 /*****************************************************************************
403 * High Level Functions: httpd_handler_t (for CGIs)
404 *****************************************************************************/
405 struct httpd_handler_t
407 httpd_url_t *url;
409 httpd_handler_callback_t pf_fill;
410 void *p_sys;
414 static int
415 httpd_HandlerCallBack(httpd_callback_sys_t *p_sys, httpd_client_t *cl,
416 httpd_message_t *answer, const httpd_message_t *query)
418 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
419 char psz_remote_addr[NI_MAXNUMERICHOST];
421 if (!answer || !query)
422 return VLC_SUCCESS;
424 answer->i_proto = HTTPD_PROTO_NONE;
425 answer->i_type = HTTPD_MSG_ANSWER;
427 /* We do it ourselves, thanks */
428 answer->i_status = 0;
430 if (!httpd_ClientIP(cl, psz_remote_addr, NULL))
431 *psz_remote_addr = '\0';
433 uint8_t *psz_args = query->psz_args;
434 handler->pf_fill(handler->p_sys, handler, query->psz_url, psz_args,
435 query->i_type, query->p_body, query->i_body,
436 psz_remote_addr, NULL,
437 &answer->p_body, &answer->i_body);
439 if (query->i_type == HTTPD_MSG_HEAD) {
440 char *p = (char *)answer->p_body;
442 /* Looks for end of header (i.e. one empty line) */
443 while ((p = strchr(p, '\r')))
444 if (p[1] == '\n' && p[2] == '\r' && p[3] == '\n')
445 break;
447 if (p) {
448 p[4] = '\0';
449 answer->i_body = strlen((char*)answer->p_body) + 1;
450 answer->p_body = xrealloc(answer->p_body, answer->i_body);
454 if (strncmp((char *)answer->p_body, "HTTP/1.", 7)) {
455 int i_status, i_headers;
456 char *psz_headers, *psz_new;
457 const char *psz_status;
459 if (!strncmp((char *)answer->p_body, "Status: ", 8)) {
460 /* Apache-style */
461 i_status = strtol((char *)&answer->p_body[8], &psz_headers, 0);
462 if (*psz_headers == '\r' || *psz_headers == '\n') psz_headers++;
463 if (*psz_headers == '\n') psz_headers++;
464 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
465 } else {
466 i_status = 200;
467 psz_headers = (char *)answer->p_body;
468 i_headers = answer->i_body;
471 psz_status = httpd_ReasonFromCode(i_status);
472 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
473 + strlen(psz_status) + i_headers - 1;
474 psz_new = (char *)xmalloc(answer->i_body + 1);
475 sprintf(psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status);
476 memcpy(&psz_new[strlen(psz_new)], psz_headers, i_headers);
477 free(answer->p_body);
478 answer->p_body = (uint8_t *)psz_new;
481 return VLC_SUCCESS;
484 httpd_handler_t *httpd_HandlerNew(httpd_host_t *host, const char *psz_url,
485 const char *psz_user,
486 const char *psz_password,
487 httpd_handler_callback_t pf_fill,
488 void *p_sys)
490 httpd_handler_t *handler = malloc(sizeof(*handler));
491 if (!handler)
492 return NULL;
494 handler->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
495 if (!handler->url) {
496 free(handler);
497 return NULL;
500 handler->pf_fill = pf_fill;
501 handler->p_sys = p_sys;
503 httpd_UrlCatch(handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
504 (httpd_callback_sys_t*)handler);
505 httpd_UrlCatch(handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
506 (httpd_callback_sys_t*)handler);
507 httpd_UrlCatch(handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
508 (httpd_callback_sys_t*)handler);
510 return handler;
513 void *httpd_HandlerDelete(httpd_handler_t *handler)
515 void *p_sys = handler->p_sys;
516 httpd_UrlDelete(handler->url);
517 free(handler);
518 return p_sys;
521 /*****************************************************************************
522 * High Level Functions: httpd_redirect_t
523 *****************************************************************************/
524 struct httpd_redirect_t
526 httpd_url_t *url;
527 char dst[1];
530 static int httpd_RedirectCallBack(httpd_callback_sys_t *p_sys,
531 httpd_client_t *cl, httpd_message_t *answer,
532 const httpd_message_t *query)
534 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
535 char *p_body;
536 (void)cl;
538 if (!answer || !query)
539 return VLC_SUCCESS;
541 answer->i_proto = HTTPD_PROTO_HTTP;
542 answer->i_version= 1;
543 answer->i_type = HTTPD_MSG_ANSWER;
544 answer->i_status = 301;
546 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->dst);
547 answer->p_body = (unsigned char *)p_body;
549 /* XXX check if it's ok or we need to set an absolute url */
550 httpd_MsgAdd(answer, "Location", "%s", rdir->dst);
552 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
554 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
555 httpd_MsgAdd(answer, "Connection", "close");
557 return VLC_SUCCESS;
560 httpd_redirect_t *httpd_RedirectNew(httpd_host_t *host, const char *psz_url_dst,
561 const char *psz_url_src)
563 size_t dstlen = strlen(psz_url_dst);
565 httpd_redirect_t *rdir = malloc(sizeof(*rdir) + dstlen);
566 if (unlikely(rdir == NULL))
567 return NULL;
569 rdir->url = httpd_UrlNew(host, psz_url_src, NULL, NULL);
570 if (!rdir->url) {
571 free(rdir);
572 return NULL;
574 memcpy(rdir->dst, psz_url_dst, dstlen + 1);
576 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
577 httpd_UrlCatch(rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
578 (httpd_callback_sys_t*)rdir);
579 httpd_UrlCatch(rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
580 (httpd_callback_sys_t*)rdir);
581 httpd_UrlCatch(rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
582 (httpd_callback_sys_t*)rdir);
583 httpd_UrlCatch(rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
584 (httpd_callback_sys_t*)rdir);
586 return rdir;
588 void httpd_RedirectDelete(httpd_redirect_t *rdir)
590 httpd_UrlDelete(rdir->url);
591 free(rdir);
594 /*****************************************************************************
595 * High Level Funtions: httpd_stream_t
596 *****************************************************************************/
597 struct httpd_stream_t
599 vlc_mutex_t lock;
600 httpd_url_t *url;
602 char *psz_mime;
604 /* Header to send as first packet */
605 uint8_t *p_header;
606 int i_header;
608 /* Some muxes, in particular the avformat mux, can mark given blocks
609 * as keyframes, to ensure that the stream starts with one.
610 * (This is particularly important for WebM streaming to certain
611 * browsers.) Store if we've ever seen any such keyframe blocks,
612 * and if so, the byte position of the start of the last one. */
613 bool b_has_keyframes;
614 int64_t i_last_keyframe_seen_pos;
616 /* circular buffer */
617 int i_buffer_size; /* buffer size, can't be reallocated smaller */
618 uint8_t *p_buffer; /* buffer */
619 int64_t i_buffer_pos; /* absolute position from beginning */
620 int64_t i_buffer_last_pos; /* a new connection will start with that */
622 /* custom headers */
623 size_t i_http_headers;
624 httpd_header * p_http_headers;
627 static int httpd_StreamCallBack(httpd_callback_sys_t *p_sys,
628 httpd_client_t *cl, httpd_message_t *answer,
629 const httpd_message_t *query)
631 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
633 if (!answer || !query || !cl)
634 return VLC_SUCCESS;
636 if (answer->i_body_offset > 0) {
637 int i_pos;
639 if (answer->i_body_offset >= stream->i_buffer_pos)
640 return VLC_EGENERIC; /* wait, no data available */
642 if (cl->i_keyframe_wait_to_pass >= 0) {
643 if (stream->i_last_keyframe_seen_pos <= cl->i_keyframe_wait_to_pass)
644 /* still waiting for the next keyframe */
645 return VLC_EGENERIC;
647 /* seek to the new keyframe */
648 answer->i_body_offset = stream->i_last_keyframe_seen_pos;
649 cl->i_keyframe_wait_to_pass = -1;
652 if (answer->i_body_offset + stream->i_buffer_size < stream->i_buffer_pos)
653 answer->i_body_offset = stream->i_buffer_last_pos; /* this client isn't fast enough */
655 i_pos = answer->i_body_offset % stream->i_buffer_size;
656 int64_t i_write = stream->i_buffer_pos - answer->i_body_offset;
658 if (i_write > HTTPD_CL_BUFSIZE)
659 i_write = HTTPD_CL_BUFSIZE;
660 else if (i_write <= 0)
661 return VLC_EGENERIC; /* wait, no data available */
663 /* Don't go past the end of the circular buffer */
664 i_write = __MIN(i_write, stream->i_buffer_size - i_pos);
666 /* using HTTPD_MSG_ANSWER -> data available */
667 answer->i_proto = HTTPD_PROTO_HTTP;
668 answer->i_version= 0;
669 answer->i_type = HTTPD_MSG_ANSWER;
671 answer->i_body = i_write;
672 answer->p_body = xmalloc(i_write);
673 memcpy(answer->p_body, &stream->p_buffer[i_pos], i_write);
675 answer->i_body_offset += i_write;
677 return VLC_SUCCESS;
678 } else {
679 answer->i_proto = HTTPD_PROTO_HTTP;
680 answer->i_version= 0;
681 answer->i_type = HTTPD_MSG_ANSWER;
683 answer->i_status = 200;
685 bool b_has_content_type = false;
686 bool b_has_cache_control = false;
688 vlc_mutex_lock(&stream->lock);
689 for (size_t i = 0; i < stream->i_http_headers; i++)
690 if (strncasecmp(stream->p_http_headers[i].name, "Content-Length", 14)) {
691 httpd_MsgAdd(answer, stream->p_http_headers[i].name, "%s",
692 stream->p_http_headers[i].value);
694 if (!strncasecmp(stream->p_http_headers[i].name, "Content-Type", 12))
695 b_has_content_type = true;
696 else if (!strncasecmp(stream->p_http_headers[i].name, "Cache-Control", 13))
697 b_has_cache_control = true;
699 vlc_mutex_unlock(&stream->lock);
701 if (query->i_type != HTTPD_MSG_HEAD) {
702 cl->b_stream_mode = true;
703 vlc_mutex_lock(&stream->lock);
704 /* Send the header */
705 if (stream->i_header > 0) {
706 answer->i_body = stream->i_header;
707 answer->p_body = xmalloc(stream->i_header);
708 memcpy(answer->p_body, stream->p_header, stream->i_header);
710 answer->i_body_offset = stream->i_buffer_last_pos;
711 if (stream->b_has_keyframes)
712 cl->i_keyframe_wait_to_pass = stream->i_last_keyframe_seen_pos;
713 else
714 cl->i_keyframe_wait_to_pass = -1;
715 vlc_mutex_unlock(&stream->lock);
716 } else {
717 httpd_MsgAdd(answer, "Content-Length", "0");
718 answer->i_body_offset = 0;
721 /* FIXME: move to http access_output */
722 if (!strcmp(stream->psz_mime, "video/x-ms-asf-stream")) {
723 bool b_xplaystream = false;
725 httpd_MsgAdd(answer, "Content-type", "application/octet-stream");
726 httpd_MsgAdd(answer, "Server", "Cougar 4.1.0.3921");
727 httpd_MsgAdd(answer, "Pragma", "no-cache");
728 httpd_MsgAdd(answer, "Pragma", "client-id=%lu",
729 vlc_mrand48()&0x7fff);
730 httpd_MsgAdd(answer, "Pragma", "features=\"broadcast\"");
732 /* Check if there is a xPlayStrm=1 */
733 for (size_t i = 0; i < query->i_headers; i++)
734 if (!strcasecmp(query->p_headers[i].name, "Pragma") &&
735 strstr(query->p_headers[i].value, "xPlayStrm=1"))
736 b_xplaystream = true;
738 if (!b_xplaystream)
739 answer->i_body_offset = 0;
740 } else if (!b_has_content_type)
741 httpd_MsgAdd(answer, "Content-type", "%s", stream->psz_mime);
743 if (!b_has_cache_control)
744 httpd_MsgAdd(answer, "Cache-Control", "no-cache");
746 httpd_MsgAdd(answer, "Connection", "close");
748 return VLC_SUCCESS;
752 httpd_stream_t *httpd_StreamNew(httpd_host_t *host,
753 const char *psz_url, const char *psz_mime,
754 const char *psz_user, const char *psz_password)
756 httpd_stream_t *stream = malloc(sizeof(*stream));
757 if (!stream)
758 return NULL;
760 stream->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
761 if (!stream->url) {
762 free(stream);
763 return NULL;
766 vlc_mutex_init(&stream->lock);
767 if (psz_mime == NULL || psz_mime[0] == '\0')
768 psz_mime = vlc_mime_Ext2Mime(psz_url);
769 stream->psz_mime = xstrdup(psz_mime);
771 stream->i_header = 0;
772 stream->p_header = NULL;
773 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
774 stream->p_buffer = xmalloc(stream->i_buffer_size);
775 /* We set to 1 to make life simpler
776 * (this way i_body_offset can never be 0) */
777 stream->i_buffer_pos = 1;
778 stream->i_buffer_last_pos = 1;
779 stream->b_has_keyframes = false;
780 stream->i_last_keyframe_seen_pos = 0;
781 stream->i_http_headers = 0;
782 stream->p_http_headers = NULL;
784 httpd_UrlCatch(stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
785 (httpd_callback_sys_t*)stream);
786 httpd_UrlCatch(stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
787 (httpd_callback_sys_t*)stream);
788 httpd_UrlCatch(stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
789 (httpd_callback_sys_t*)stream);
791 return stream;
794 int httpd_StreamHeader(httpd_stream_t *stream, uint8_t *p_data, int i_data)
796 vlc_mutex_lock(&stream->lock);
797 free(stream->p_header);
798 stream->p_header = NULL;
800 stream->i_header = i_data;
801 if (i_data > 0) {
802 stream->p_header = xmalloc(i_data);
803 memcpy(stream->p_header, p_data, i_data);
805 vlc_mutex_unlock(&stream->lock);
807 return VLC_SUCCESS;
810 static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data)
812 int i_pos = stream->i_buffer_pos % stream->i_buffer_size;
813 int i_count = i_data;
814 while (i_count > 0) {
815 int i_copy = __MIN(i_count, stream->i_buffer_size - i_pos);
817 /* Ok, we can't go past the end of our buffer */
818 memcpy(&stream->p_buffer[i_pos], p_data, i_copy);
820 i_pos = (i_pos + i_copy) % stream->i_buffer_size;
821 i_count -= i_copy;
822 p_data += i_copy;
825 stream->i_buffer_pos += i_data;
828 int httpd_StreamSend(httpd_stream_t *stream, const block_t *p_block)
830 if (!p_block || !p_block->p_buffer)
831 return VLC_SUCCESS;
833 vlc_mutex_lock(&stream->lock);
835 /* save this pointer (to be used by new connection) */
836 stream->i_buffer_last_pos = stream->i_buffer_pos;
838 if (p_block->i_flags & BLOCK_FLAG_TYPE_I) {
839 stream->b_has_keyframes = true;
840 stream->i_last_keyframe_seen_pos = stream->i_buffer_pos;
843 httpd_AppendData(stream, p_block->p_buffer, p_block->i_buffer);
845 vlc_mutex_unlock(&stream->lock);
846 return VLC_SUCCESS;
849 void httpd_StreamDelete(httpd_stream_t *stream)
851 httpd_UrlDelete(stream->url);
852 for (size_t i = 0; i < stream->i_http_headers; i++) {
853 free(stream->p_http_headers[i].name);
854 free(stream->p_http_headers[i].value);
856 free(stream->p_http_headers);
857 vlc_mutex_destroy(&stream->lock);
858 free(stream->psz_mime);
859 free(stream->p_header);
860 free(stream->p_buffer);
861 free(stream);
864 /*****************************************************************************
865 * Low level
866 *****************************************************************************/
867 static void* httpd_HostThread(void *);
868 static httpd_host_t *httpd_HostCreate(vlc_object_t *, const char *,
869 const char *, vlc_tls_creds_t *);
871 /* create a new host */
872 httpd_host_t *vlc_http_HostNew(vlc_object_t *p_this)
874 return httpd_HostCreate(p_this, "http-host", "http-port", NULL);
877 httpd_host_t *vlc_https_HostNew(vlc_object_t *obj)
879 char *cert = var_InheritString(obj, "http-cert");
880 if (!cert) {
881 msg_Err(obj, "HTTP/TLS certificate not specified!");
882 return NULL;
885 char *key = var_InheritString(obj, "http-key");
886 vlc_tls_creds_t *tls = vlc_tls_ServerCreate(obj, cert, key);
888 if (!tls) {
889 msg_Err(obj, "HTTP/TLS certificate error (%s and %s)",
890 cert, key ? key : cert);
891 free(key);
892 free(cert);
893 return NULL;
895 free(key);
896 free(cert);
898 return httpd_HostCreate(obj, "http-host", "https-port", tls);
901 httpd_host_t *vlc_rtsp_HostNew(vlc_object_t *p_this)
903 return httpd_HostCreate(p_this, "rtsp-host", "rtsp-port", NULL);
906 static struct httpd
908 vlc_mutex_t mutex;
910 httpd_host_t **host;
911 int i_host;
912 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
914 static httpd_host_t *httpd_HostCreate(vlc_object_t *p_this,
915 const char *hostvar,
916 const char *portvar,
917 vlc_tls_creds_t *p_tls)
919 httpd_host_t *host;
920 char *hostname = var_InheritString(p_this, hostvar);
921 unsigned port = var_InheritInteger(p_this, portvar);
923 vlc_url_t url;
924 vlc_UrlParse(&url, hostname);
925 free(hostname);
926 if (url.i_port != 0) {
927 msg_Err(p_this, "Ignoring port %d (using %d)", url.i_port, port);
928 msg_Info(p_this, "Specify port %d separately with the "
929 "%s option instead.", url.i_port, portvar);
932 /* to be sure to avoid multiple creation */
933 vlc_mutex_lock(&httpd.mutex);
935 /* verify if it already exist */
936 for (int i = 0; i < httpd.i_host; i++) {
937 host = httpd.host[i];
939 /* cannot mix TLS and non-TLS hosts */
940 if (host->port != port
941 || (host->p_tls != NULL) != (p_tls != NULL))
942 continue;
944 /* Increase existing matching host reference count.
945 * The reference count is written under both the global httpd and the
946 * host lock. It is read with either or both locks held. The global
947 * lock is always acquired first. */
948 vlc_mutex_lock(&host->lock);
949 host->i_ref++;
950 vlc_mutex_unlock(&host->lock);
952 vlc_mutex_unlock(&httpd.mutex);
953 vlc_UrlClean(&url);
954 vlc_tls_Delete(p_tls);
955 return host;
958 /* create the new host */
959 host = (httpd_host_t *)vlc_custom_create(p_this, sizeof (*host),
960 "http host");
961 if (!host)
962 goto error;
964 vlc_mutex_init(&host->lock);
965 vlc_cond_init(&host->wait);
966 host->i_ref = 1;
968 host->fds = net_ListenTCP(p_this, url.psz_host, port);
969 if (!host->fds) {
970 msg_Err(p_this, "cannot create socket(s) for HTTP host");
971 goto error;
973 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
975 host->port = port;
976 host->i_url = 0;
977 host->url = NULL;
978 host->i_client = 0;
979 host->client = NULL;
980 host->p_tls = p_tls;
982 /* create the thread */
983 if (vlc_clone(&host->thread, httpd_HostThread, host,
984 VLC_THREAD_PRIORITY_LOW)) {
985 msg_Err(p_this, "cannot spawn http host thread");
986 goto error;
989 /* now add it to httpd */
990 TAB_APPEND(httpd.i_host, httpd.host, host);
991 vlc_mutex_unlock(&httpd.mutex);
993 vlc_UrlClean(&url);
995 return host;
997 error:
998 vlc_mutex_unlock(&httpd.mutex);
1000 if (host) {
1001 net_ListenClose(host->fds);
1002 vlc_cond_destroy(&host->wait);
1003 vlc_mutex_destroy(&host->lock);
1004 vlc_object_release(host);
1007 vlc_UrlClean(&url);
1008 vlc_tls_Delete(p_tls);
1009 return NULL;
1012 /* delete a host */
1013 void httpd_HostDelete(httpd_host_t *host)
1015 bool delete = false;
1017 vlc_mutex_lock(&httpd.mutex);
1019 vlc_mutex_lock(&host->lock);
1020 host->i_ref--;
1021 if (host->i_ref == 0)
1022 delete = true;
1023 vlc_mutex_unlock(&host->lock);
1024 if (!delete) {
1025 /* still used */
1026 vlc_mutex_unlock(&httpd.mutex);
1027 msg_Dbg(host, "httpd_HostDelete: host still in use");
1028 return;
1030 TAB_REMOVE(httpd.i_host, httpd.host, host);
1032 vlc_cancel(host->thread);
1033 vlc_join(host->thread, NULL);
1035 msg_Dbg(host, "HTTP host removed");
1037 for (int i = 0; i < host->i_url; i++)
1038 msg_Err(host, "url still registered: %s", host->url[i]->psz_url);
1040 for (int i = 0; i < host->i_client; i++) {
1041 msg_Warn(host, "client still connected");
1042 httpd_ClientDestroy(host->client[i]);
1044 TAB_CLEAN(host->i_client, host->client);
1046 vlc_tls_Delete(host->p_tls);
1047 net_ListenClose(host->fds);
1048 vlc_cond_destroy(&host->wait);
1049 vlc_mutex_destroy(&host->lock);
1050 vlc_object_release(host);
1051 vlc_mutex_unlock(&httpd.mutex);
1054 /* register a new url */
1055 httpd_url_t *httpd_UrlNew(httpd_host_t *host, const char *psz_url,
1056 const char *psz_user, const char *psz_password)
1058 httpd_url_t *url;
1060 assert(psz_url);
1062 vlc_mutex_lock(&host->lock);
1063 for (int i = 0; i < host->i_url; i++)
1064 if (!strcmp(psz_url, host->url[i]->psz_url)) {
1065 msg_Warn(host, "cannot add '%s' (url already defined)", psz_url);
1066 vlc_mutex_unlock(&host->lock);
1067 return NULL;
1070 url = xmalloc(sizeof(httpd_url_t));
1071 url->host = host;
1073 vlc_mutex_init(&url->lock);
1074 url->psz_url = xstrdup(psz_url);
1075 url->psz_user = xstrdup(psz_user ? psz_user : "");
1076 url->psz_password = xstrdup(psz_password ? psz_password : "");
1077 for (int i = 0; i < HTTPD_MSG_MAX; i++) {
1078 url->catch[i].cb = NULL;
1079 url->catch[i].p_sys = NULL;
1082 TAB_APPEND(host->i_url, host->url, url);
1083 vlc_cond_signal(&host->wait);
1084 vlc_mutex_unlock(&host->lock);
1086 return url;
1089 /* register callback on a url */
1090 int httpd_UrlCatch(httpd_url_t *url, int i_msg, httpd_callback_t cb,
1091 httpd_callback_sys_t *p_sys)
1093 vlc_mutex_lock(&url->lock);
1094 url->catch[i_msg].cb = cb;
1095 url->catch[i_msg].p_sys= p_sys;
1096 vlc_mutex_unlock(&url->lock);
1098 return VLC_SUCCESS;
1101 /* delete a url */
1102 void httpd_UrlDelete(httpd_url_t *url)
1104 httpd_host_t *host = url->host;
1106 vlc_mutex_lock(&host->lock);
1107 TAB_REMOVE(host->i_url, host->url, url);
1109 vlc_mutex_destroy(&url->lock);
1110 free(url->psz_url);
1111 free(url->psz_user);
1112 free(url->psz_password);
1114 for (int i = 0; i < host->i_client; i++) {
1115 httpd_client_t *client = host->client[i];
1117 if (client->url != url)
1118 continue;
1120 /* TODO complete it */
1121 msg_Warn(host, "force closing connections");
1122 TAB_REMOVE(host->i_client, host->client, client);
1123 httpd_ClientDestroy(client);
1124 i--;
1126 free(url);
1127 vlc_mutex_unlock(&host->lock);
1130 static void httpd_MsgInit(httpd_message_t *msg)
1132 msg->cl = NULL;
1133 msg->i_type = HTTPD_MSG_NONE;
1134 msg->i_proto = HTTPD_PROTO_NONE;
1135 msg->i_version = -1; /* FIXME */
1137 msg->i_status = 0;
1139 msg->psz_url = NULL;
1140 msg->psz_args = NULL;
1142 msg->i_headers = 0;
1143 msg->p_headers = NULL;
1145 msg->i_body_offset = 0;
1146 msg->i_body = 0;
1147 msg->p_body = NULL;
1150 static void httpd_MsgClean(httpd_message_t *msg)
1152 free(msg->psz_url);
1153 free(msg->psz_args);
1154 for (size_t i = 0; i < msg->i_headers; i++) {
1155 free(msg->p_headers[i].name);
1156 free(msg->p_headers[i].value);
1158 free(msg->p_headers);
1159 free(msg->p_body);
1160 httpd_MsgInit(msg);
1163 const char *httpd_MsgGet(const httpd_message_t *msg, const char *name)
1165 for (size_t i = 0; i < msg->i_headers; i++)
1166 if (!strcasecmp(msg->p_headers[i].name, name))
1167 return msg->p_headers[i].value;
1168 return NULL;
1171 void httpd_MsgAdd(httpd_message_t *msg, const char *name, const char *psz_value, ...)
1173 httpd_header *p_tmp = realloc(msg->p_headers, sizeof(httpd_header) * (msg->i_headers + 1));
1174 if (!p_tmp)
1175 return;
1177 msg->p_headers = p_tmp;
1179 httpd_header *h = &msg->p_headers[msg->i_headers];
1180 h->name = strdup(name);
1181 if (!h->name)
1182 return;
1184 h->value = NULL;
1186 va_list args;
1187 va_start(args, psz_value);
1188 int ret = us_vasprintf(&h->value, psz_value, args);
1189 va_end(args);
1191 if (ret == -1) {
1192 free(h->name);
1193 return;
1196 msg->i_headers++;
1199 static void httpd_ClientInit(httpd_client_t *cl, mtime_t now)
1201 cl->i_state = HTTPD_CLIENT_RECEIVING;
1202 cl->i_activity_date = now;
1203 cl->i_activity_timeout = INT64_C(10000000);
1204 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1205 cl->i_buffer = 0;
1206 cl->p_buffer = xmalloc(cl->i_buffer_size);
1207 cl->i_keyframe_wait_to_pass = -1;
1208 cl->b_stream_mode = false;
1210 httpd_MsgInit(&cl->query);
1211 httpd_MsgInit(&cl->answer);
1214 char* httpd_ClientIP(const httpd_client_t *cl, char *ip, int *port)
1216 return net_GetPeerAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1219 char* httpd_ServerIP(const httpd_client_t *cl, char *ip, int *port)
1221 return net_GetSockAddress(vlc_tls_GetFD(cl->sock), ip, port) ? NULL : ip;
1224 static void httpd_ClientDestroy(httpd_client_t *cl)
1226 vlc_tls_Close(cl->sock);
1227 httpd_MsgClean(&cl->answer);
1228 httpd_MsgClean(&cl->query);
1230 free(cl->p_buffer);
1231 free(cl);
1234 static httpd_client_t *httpd_ClientNew(vlc_tls_t *sock, mtime_t now)
1236 httpd_client_t *cl = malloc(sizeof(httpd_client_t));
1238 if (!cl) return NULL;
1240 cl->i_ref = 0;
1241 cl->sock = sock;
1242 cl->url = NULL;
1244 httpd_ClientInit(cl, now);
1245 return cl;
1248 static
1249 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1251 vlc_tls_t *sock = cl->sock;
1252 struct iovec iov = { .iov_base = p, .iov_len = i_len };
1253 return sock->readv(sock, &iov, 1);
1256 static
1257 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1259 vlc_tls_t *sock = cl->sock;
1260 const struct iovec iov = { .iov_base = (void *)p, .iov_len = i_len };
1261 return sock->writev(sock, &iov, 1);
1265 static const struct
1267 const char name[16];
1268 int i_type;
1269 int i_proto;
1271 msg_type[] =
1273 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1274 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1275 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1276 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1277 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1278 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1279 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1280 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1281 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1282 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1283 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1287 static void httpd_ClientRecv(httpd_client_t *cl)
1289 int i_len;
1291 /* ignore leading whites */
1292 if (cl->query.i_proto == HTTPD_PROTO_NONE && cl->i_buffer == 0) {
1293 unsigned char c;
1295 i_len = httpd_NetRecv(cl, &c, 1);
1297 if (i_len > 0 && !strchr("\r\n\t ", c)) {
1298 cl->p_buffer[0] = c;
1299 cl->i_buffer++;
1301 } else if (cl->query.i_proto == HTTPD_PROTO_NONE) {
1302 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1303 i_len = httpd_NetRecv(cl, &cl->p_buffer[cl->i_buffer],
1304 7 - cl->i_buffer);
1305 if (i_len > 0)
1306 cl->i_buffer += i_len;
1308 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1309 * this is the maximum we can ask at this point. */
1310 if (cl->i_buffer >= 7) {
1311 if (!memcmp(cl->p_buffer, "HTTP/1.", 7)) {
1312 cl->query.i_proto = HTTPD_PROTO_HTTP;
1313 cl->query.i_type = HTTPD_MSG_ANSWER;
1314 } else if (!memcmp(cl->p_buffer, "RTSP/1.", 7)) {
1315 cl->query.i_proto = HTTPD_PROTO_RTSP;
1316 cl->query.i_type = HTTPD_MSG_ANSWER;
1317 } else {
1318 /* We need the full request line to determine the protocol. */
1319 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1320 cl->query.i_type = HTTPD_MSG_NONE;
1323 } else if (cl->query.i_body > 0) {
1324 /* we are reading the body of a request or a channel */
1325 assert (cl->query.p_body != NULL);
1326 i_len = httpd_NetRecv(cl, &cl->query.p_body[cl->i_buffer],
1327 cl->query.i_body - cl->i_buffer);
1328 if (i_len > 0)
1329 cl->i_buffer += i_len;
1331 if (cl->i_buffer >= cl->query.i_body)
1332 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1333 } else for (;;) { /* we are reading a header -> char by char */
1334 if (cl->i_buffer == cl->i_buffer_size) {
1335 uint8_t *newbuf = realloc(cl->p_buffer, cl->i_buffer_size + 1024);
1336 if (!newbuf) {
1337 i_len = 0;
1338 break;
1341 cl->p_buffer = newbuf;
1342 cl->i_buffer_size += 1024;
1345 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1);
1346 if (i_len <= 0)
1347 break;
1349 cl->i_buffer++;
1351 if ((cl->query.i_proto == HTTPD_PROTO_HTTP0)
1352 && (cl->p_buffer[cl->i_buffer - 1] == '\n'))
1354 /* Request line is now complete */
1355 const char *p = memchr(cl->p_buffer, ' ', cl->i_buffer);
1356 size_t len;
1358 assert(cl->query.i_type == HTTPD_MSG_NONE);
1360 if (!p) { /* no URI: evil guy */
1361 i_len = 0; /* drop connection */
1362 break;
1366 p++; /* skips extra spaces */
1367 while (*p == ' ');
1369 p = memchr(p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p);
1370 if (!p) { /* no explicit protocol: HTTP/0.9 */
1371 i_len = 0; /* not supported currently -> drop */
1372 break;
1376 p++; /* skips extra spaces ever again */
1377 while (*p == ' ');
1379 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1380 if (len < 7) /* foreign protocol */
1381 i_len = 0; /* I don't understand -> drop */
1382 else if (!memcmp(p, "HTTP/1.", 7)) {
1383 cl->query.i_proto = HTTPD_PROTO_HTTP;
1384 cl->query.i_version = atoi(p + 7);
1385 } else if (!memcmp(p, "RTSP/1.", 7)) {
1386 cl->query.i_proto = HTTPD_PROTO_RTSP;
1387 cl->query.i_version = atoi(p + 7);
1388 } else if (!memcmp(p, "HTTP/", 5)) {
1389 const uint8_t sorry[] =
1390 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1391 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1392 i_len = 0; /* drop */
1393 } else if (!memcmp(p, "RTSP/", 5)) {
1394 const uint8_t sorry[] =
1395 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1396 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1397 i_len = 0; /* drop */
1398 } else /* yet another foreign protocol */
1399 i_len = 0;
1401 if (i_len == 0)
1402 break;
1405 if ((cl->i_buffer >= 2 && !memcmp(&cl->p_buffer[cl->i_buffer-2], "\n\n", 2))||
1406 (cl->i_buffer >= 4 && !memcmp(&cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4)))
1408 char *p;
1410 /* we have finished the header so parse it and set i_body */
1411 cl->p_buffer[cl->i_buffer] = '\0';
1413 if (cl->query.i_type == HTTPD_MSG_ANSWER) {
1414 /* FIXME:
1415 * assume strlen("HTTP/1.x") = 8
1417 cl->query.i_status =
1418 strtol((char *)&cl->p_buffer[8],
1419 &p, 0);
1420 while (*p == ' ')
1421 p++;
1422 } else {
1423 p = NULL;
1424 cl->query.i_type = HTTPD_MSG_NONE;
1426 for (unsigned i = 0; msg_type[i].name[0]; i++)
1427 if (!strncmp((char *)cl->p_buffer, msg_type[i].name,
1428 strlen(msg_type[i].name))) {
1429 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1430 cl->query.i_type = msg_type[i].i_type;
1431 if (cl->query.i_proto != msg_type[i].i_proto) {
1432 p = NULL;
1433 cl->query.i_proto = HTTPD_PROTO_NONE;
1434 cl->query.i_type = HTTPD_MSG_NONE;
1436 break;
1439 if (!p) {
1440 if (strstr((char *)cl->p_buffer, "HTTP/1."))
1441 cl->query.i_proto = HTTPD_PROTO_HTTP;
1442 else if (strstr((char *)cl->p_buffer, "RTSP/1."))
1443 cl->query.i_proto = HTTPD_PROTO_RTSP;
1444 } else {
1445 char *p2;
1446 char *p3;
1448 while (*p == ' ')
1449 p++;
1451 p2 = strchr(p, ' ');
1452 if (p2)
1453 *p2++ = '\0';
1455 if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "http:" : "rtsp:", 5)) {
1456 /* Skip hier-part of URL (if present) */
1457 p += 5;
1458 if (!strncmp(p, "//", 2)) { /* skip authority */
1459 /* see RFC3986 §3.2 */
1460 p += 2;
1461 p += strcspn(p, "/?#");
1464 else if (!strncasecmp(p, (cl->query.i_proto == HTTPD_PROTO_HTTP) ? "https:" : "rtsps:", 6)) {
1465 /* Skip hier-part of URL (if present) */
1466 p += 6;
1467 if (!strncmp(p, "//", 2)) { /* skip authority */
1468 /* see RFC3986 §3.2 */
1469 p += 2;
1470 p += strcspn(p, "/?#");
1474 cl->query.psz_url = strdup(p);
1475 if ((p3 = strchr(cl->query.psz_url, '?')) ) {
1476 *p3++ = '\0';
1477 cl->query.psz_args = (uint8_t *)strdup(p3);
1479 p = p2;
1482 if (p)
1483 p = strchr(p, '\n');
1485 if (p) {
1486 while (*p == '\n' || *p == '\r')
1487 p++;
1489 while (p && *p) {
1490 char *line = p;
1491 char *eol = p = strchr(p, '\n');
1492 char *colon;
1494 while (eol && eol >= line && (*eol == '\n' || *eol == '\r'))
1495 *eol-- = '\0';
1497 if ((colon = strchr(line, ':'))) {
1498 *colon++ = '\0';
1499 while (*colon == ' ')
1500 colon++;
1501 httpd_MsgAdd(&cl->query, line, "%s", colon);
1503 if (!strcasecmp(line, "Content-Length"))
1504 cl->query.i_body = atol(colon);
1507 if (p) {
1508 p++;
1509 while (*p == '\n' || *p == '\r')
1510 p++;
1514 if (cl->query.i_body > 0) {
1515 /* TODO Mhh, handle the case where the client only
1516 * sends a request and closes the connection to
1517 * mark the end of the body (probably only RTSP) */
1518 if (cl->query.i_body < 65536)
1519 cl->query.p_body = malloc(cl->query.i_body);
1520 else
1521 cl->query.p_body = NULL;
1522 cl->i_buffer = 0;
1523 if (!cl->query.p_body) {
1524 switch (cl->query.i_proto) {
1525 case HTTPD_PROTO_HTTP: {
1526 const uint8_t sorry[] = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1527 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1528 break;
1530 case HTTPD_PROTO_RTSP: {
1531 const uint8_t sorry[] = "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1532 httpd_NetSend(cl, sorry, sizeof(sorry) - 1);
1533 break;
1535 default:
1536 vlc_assert_unreachable();
1538 i_len = 0; /* drop */
1540 break;
1541 } else
1542 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1546 /* check if the client is to be set to dead */
1547 #if defined(_WIN32)
1548 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1549 #else
1550 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1551 #endif
1553 if (cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE) {
1554 /* connection closed -> end of data */
1555 if (cl->query.i_body > 0)
1556 cl->query.i_body = cl->i_buffer;
1557 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1559 else
1560 cl->i_state = HTTPD_CLIENT_DEAD;
1563 /* XXX: for QT I have to disable timeout. Try to find why */
1564 if (cl->query.i_proto == HTTPD_PROTO_RTSP)
1565 cl->i_activity_timeout = 0;
1568 static void httpd_ClientSend(httpd_client_t *cl)
1570 int i_len;
1572 if (cl->i_buffer < 0) {
1573 /* We need to create the header */
1574 int i_size = 0;
1575 char *p;
1576 const char *psz_status = httpd_ReasonFromCode(cl->answer.i_status);
1578 i_size = strlen("HTTP/1.") + 10 + 10 + strlen(psz_status) + 5;
1579 for (size_t i = 0; i < cl->answer.i_headers; i++)
1580 i_size += strlen(cl->answer.p_headers[i].name) + 2 +
1581 strlen(cl->answer.p_headers[i].value) + 2;
1583 if (cl->i_buffer_size < i_size) {
1584 cl->i_buffer_size = i_size;
1585 free(cl->p_buffer);
1586 cl->p_buffer = xmalloc(i_size);
1588 p = (char *)cl->p_buffer;
1590 p += sprintf(p, "%s.%u %d %s\r\n",
1591 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1592 cl->answer.i_version,
1593 cl->answer.i_status, psz_status);
1594 for (size_t i = 0; i < cl->answer.i_headers; i++)
1595 p += sprintf(p, "%s: %s\r\n", cl->answer.p_headers[i].name,
1596 cl->answer.p_headers[i].value);
1597 p += sprintf(p, "\r\n");
1599 cl->i_buffer = 0;
1600 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1603 i_len = httpd_NetSend(cl, &cl->p_buffer[cl->i_buffer],
1604 cl->i_buffer_size - cl->i_buffer);
1605 if (i_len >= 0) {
1606 cl->i_buffer += i_len;
1608 if (cl->i_buffer >= cl->i_buffer_size) {
1609 if (cl->answer.i_body == 0 && cl->answer.i_body_offset > 0) {
1610 /* catch more body data */
1611 int i_msg = cl->query.i_type;
1612 int64_t i_offset = cl->answer.i_body_offset;
1614 httpd_MsgClean(&cl->answer);
1615 cl->answer.i_body_offset = i_offset;
1617 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1618 &cl->answer, &cl->query);
1621 if (cl->answer.i_body > 0) {
1622 /* send the body data */
1623 free(cl->p_buffer);
1624 cl->p_buffer = cl->answer.p_body;
1625 cl->i_buffer_size = cl->answer.i_body;
1626 cl->i_buffer = 0;
1628 cl->answer.i_body = 0;
1629 cl->answer.p_body = NULL;
1630 } else /* send finished */
1631 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1633 } else {
1634 #if defined(_WIN32)
1635 if ((i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_len == 0))
1636 #else
1637 if ((i_len < 0 && errno != EAGAIN) || (i_len == 0))
1638 #endif
1640 /* error */
1641 cl->i_state = HTTPD_CLIENT_DEAD;
1646 static void httpd_ClientTlsHandshake(httpd_host_t *host, httpd_client_t *cl)
1648 switch (vlc_tls_SessionHandshake(host->p_tls, cl->sock))
1650 case -1: cl->i_state = HTTPD_CLIENT_DEAD; break;
1651 case 0: cl->i_state = HTTPD_CLIENT_RECEIVING; break;
1652 case 1: cl->i_state = HTTPD_CLIENT_TLS_HS_IN; break;
1653 case 2: cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1657 static bool httpdAuthOk(const char *user, const char *pass, const char *b64)
1659 if (!*user && !*pass)
1660 return true;
1662 if (!b64)
1663 return false;
1665 if (strncasecmp(b64, "BASIC", 5))
1666 return false;
1668 b64 += 5;
1669 while (*b64 == ' ')
1670 b64++;
1672 char *given_user = vlc_b64_decode(b64);
1673 if (!given_user)
1674 return false;
1676 char *given_pass = NULL;
1677 given_pass = strchr (given_user, ':');
1678 if (!given_pass)
1679 goto auth_failed;
1681 *given_pass++ = '\0';
1683 if (strcmp (given_user, user))
1684 goto auth_failed;
1686 if (strcmp (given_pass, pass))
1687 goto auth_failed;
1689 free(given_user);
1690 return true;
1692 auth_failed:
1693 free(given_user);
1694 return false;
1697 static void httpdLoop(httpd_host_t *host)
1699 struct pollfd ufd[host->nfd + host->i_client];
1700 unsigned nfd;
1701 for (nfd = 0; nfd < host->nfd; nfd++) {
1702 ufd[nfd].fd = host->fds[nfd];
1703 ufd[nfd].events = POLLIN;
1704 ufd[nfd].revents = 0;
1707 /* add all socket that should be read/write and close dead connection */
1708 while (host->i_url <= 0) {
1709 mutex_cleanup_push(&host->lock);
1710 vlc_cond_wait(&host->wait, &host->lock);
1711 vlc_cleanup_pop();
1714 mtime_t now = mdate();
1715 bool b_low_delay = false;
1717 int canc = vlc_savecancel();
1718 for (int i_client = 0; i_client < host->i_client; i_client++) {
1719 int64_t i_offset;
1720 httpd_client_t *cl = host->client[i_client];
1721 if (cl->i_ref < 0 || (cl->i_ref == 0 &&
1722 (cl->i_state == HTTPD_CLIENT_DEAD ||
1723 (cl->i_activity_timeout > 0 &&
1724 cl->i_activity_date+cl->i_activity_timeout < now)))) {
1725 TAB_REMOVE(host->i_client, host->client, cl);
1726 i_client--;
1727 httpd_ClientDestroy(cl);
1728 continue;
1731 struct pollfd *pufd = ufd + nfd;
1732 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1734 pufd->fd = vlc_tls_GetFD(cl->sock);
1735 pufd->events = pufd->revents = 0;
1737 switch (cl->i_state) {
1738 case HTTPD_CLIENT_RECEIVING:
1739 case HTTPD_CLIENT_TLS_HS_IN:
1740 pufd->events = POLLIN;
1741 break;
1743 case HTTPD_CLIENT_SENDING:
1744 case HTTPD_CLIENT_TLS_HS_OUT:
1745 pufd->events = POLLOUT;
1746 break;
1748 case HTTPD_CLIENT_RECEIVE_DONE: {
1749 httpd_message_t *answer = &cl->answer;
1750 httpd_message_t *query = &cl->query;
1752 httpd_MsgInit(answer);
1754 /* Handle what we received */
1755 switch (query->i_type) {
1756 case HTTPD_MSG_ANSWER:
1757 cl->url = NULL;
1758 cl->i_state = HTTPD_CLIENT_DEAD;
1759 break;
1761 case HTTPD_MSG_OPTIONS:
1762 answer->i_type = HTTPD_MSG_ANSWER;
1763 answer->i_proto = query->i_proto;
1764 answer->i_status = 200;
1765 answer->i_body = 0;
1766 answer->p_body = NULL;
1768 httpd_MsgAdd(answer, "Server", "VLC/%s", VERSION);
1769 httpd_MsgAdd(answer, "Content-Length", "0");
1771 switch(query->i_proto) {
1772 case HTTPD_PROTO_HTTP:
1773 answer->i_version = 1;
1774 httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
1775 break;
1777 case HTTPD_PROTO_RTSP:
1778 answer->i_version = 0;
1780 const char *p = httpd_MsgGet(query, "Cseq");
1781 if (p)
1782 httpd_MsgAdd(answer, "Cseq", "%s", p);
1783 p = httpd_MsgGet(query, "Timestamp");
1784 if (p)
1785 httpd_MsgAdd(answer, "Timestamp", "%s", p);
1787 p = httpd_MsgGet(query, "Require");
1788 if (p) {
1789 answer->i_status = 551;
1790 httpd_MsgAdd(query, "Unsupported", "%s", p);
1793 httpd_MsgAdd(answer, "Public", "DESCRIBE,SETUP,"
1794 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER");
1795 break;
1798 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
1799 httpd_MsgAdd(answer, "Connection", "close");
1801 cl->i_buffer = -1; /* Force the creation of the answer in
1802 * httpd_ClientSend */
1803 cl->i_state = HTTPD_CLIENT_SENDING;
1804 break;
1806 case HTTPD_MSG_NONE:
1807 if (query->i_proto == HTTPD_PROTO_NONE) {
1808 cl->url = NULL;
1809 cl->i_state = HTTPD_CLIENT_DEAD;
1810 } else {
1811 /* unimplemented */
1812 answer->i_proto = query->i_proto ;
1813 answer->i_type = HTTPD_MSG_ANSWER;
1814 answer->i_version= 0;
1815 answer->i_status = 501;
1817 char *p;
1818 answer->i_body = httpd_HtmlError (&p, 501, NULL);
1819 answer->p_body = (uint8_t *)p;
1820 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1821 httpd_MsgAdd(answer, "Connection", "close");
1823 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1824 cl->i_state = HTTPD_CLIENT_SENDING;
1826 break;
1828 default: {
1829 int i_msg = query->i_type;
1830 bool b_auth_failed = false;
1832 /* Search the url and trigger callbacks */
1833 for (int i = 0; i < host->i_url; i++) {
1834 httpd_url_t *url = host->url[i];
1836 if (strcmp(url->psz_url, query->psz_url))
1837 continue;
1838 if (!url->catch[i_msg].cb)
1839 continue;
1841 if (answer) {
1842 b_auth_failed = !httpdAuthOk(url->psz_user,
1843 url->psz_password,
1844 httpd_MsgGet(query, "Authorization")); /* BASIC id */
1845 if (b_auth_failed)
1846 break;
1849 if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
1850 continue;
1852 if (answer->i_proto == HTTPD_PROTO_NONE)
1853 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
1854 else
1855 cl->i_buffer = -1;
1857 /* only one url can answer */
1858 answer = NULL;
1859 if (!cl->url)
1860 cl->url = url;
1863 if (answer) {
1864 answer->i_proto = query->i_proto;
1865 answer->i_type = HTTPD_MSG_ANSWER;
1866 answer->i_version= 0;
1868 if (b_auth_failed) {
1869 httpd_MsgAdd(answer, "WWW-Authenticate",
1870 "Basic realm=\"VLC stream\"");
1871 answer->i_status = 401;
1872 } else
1873 answer->i_status = 404; /* no url registered */
1875 char *p;
1876 answer->i_body = httpd_HtmlError (&p, answer->i_status,
1877 query->psz_url);
1878 answer->p_body = (uint8_t *)p;
1880 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
1881 httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
1882 httpd_MsgAdd(answer, "Content-Type", "%s", "text/html");
1883 if (httpd_MsgGet(&cl->query, "Connection") != NULL)
1884 httpd_MsgAdd(answer, "Connection", "close");
1887 cl->i_state = HTTPD_CLIENT_SENDING;
1890 break;
1893 case HTTPD_CLIENT_SEND_DONE:
1894 if (!cl->b_stream_mode || cl->answer.i_body_offset == 0) {
1895 bool do_close = false;
1897 cl->url = NULL;
1899 if (cl->query.i_proto != HTTPD_PROTO_HTTP
1900 || cl->query.i_version > 0)
1902 const char *psz_connection = httpd_MsgGet(&cl->answer,
1903 "Connection");
1904 if (psz_connection != NULL)
1905 do_close = !strcasecmp(psz_connection, "close");
1907 else
1908 do_close = true;
1910 if (!do_close) {
1911 httpd_MsgClean(&cl->query);
1912 httpd_MsgInit(&cl->query);
1914 cl->i_buffer = 0;
1915 cl->i_buffer_size = 1000;
1916 free(cl->p_buffer);
1917 cl->p_buffer = xmalloc(cl->i_buffer_size);
1918 cl->i_state = HTTPD_CLIENT_RECEIVING;
1919 } else
1920 cl->i_state = HTTPD_CLIENT_DEAD;
1921 httpd_MsgClean(&cl->answer);
1922 } else {
1923 i_offset = cl->answer.i_body_offset;
1924 httpd_MsgClean(&cl->answer);
1926 cl->answer.i_body_offset = i_offset;
1927 free(cl->p_buffer);
1928 cl->p_buffer = NULL;
1929 cl->i_buffer = 0;
1930 cl->i_buffer_size = 0;
1932 cl->i_state = HTTPD_CLIENT_WAITING;
1934 break;
1936 case HTTPD_CLIENT_WAITING:
1937 i_offset = cl->answer.i_body_offset;
1938 int i_msg = cl->query.i_type;
1940 httpd_MsgInit(&cl->answer);
1941 cl->answer.i_body_offset = i_offset;
1943 cl->url->catch[i_msg].cb(cl->url->catch[i_msg].p_sys, cl,
1944 &cl->answer, &cl->query);
1945 if (cl->answer.i_type != HTTPD_MSG_NONE) {
1946 /* we have new data, so re-enter send mode */
1947 cl->i_buffer = 0;
1948 cl->p_buffer = cl->answer.p_body;
1949 cl->i_buffer_size = cl->answer.i_body;
1950 cl->answer.p_body = NULL;
1951 cl->answer.i_body = 0;
1952 cl->i_state = HTTPD_CLIENT_SENDING;
1956 if (pufd->events != 0)
1957 nfd++;
1958 else
1959 b_low_delay = true;
1961 vlc_mutex_unlock(&host->lock);
1962 vlc_restorecancel(canc);
1964 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
1965 while (poll(ufd, nfd, b_low_delay ? 20 : -1) < 0)
1967 if (errno != EINTR)
1968 msg_Err(host, "polling error: %s", vlc_strerror_c(errno));
1971 canc = vlc_savecancel();
1972 vlc_mutex_lock(&host->lock);
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,
2063 const httpd_header *p_headers, size_t i_headers)
2065 if (!p_stream)
2066 return VLC_EGENERIC;
2068 vlc_mutex_lock(&p_stream->lock);
2069 if (p_stream->p_http_headers) {
2070 for (size_t i = 0; i < p_stream->i_http_headers; i++) {
2071 free(p_stream->p_http_headers[i].name);
2072 free(p_stream->p_http_headers[i].value);
2074 free(p_stream->p_http_headers);
2075 p_stream->p_http_headers = NULL;
2076 p_stream->i_http_headers = 0;
2079 if (!p_headers || !i_headers) {
2080 vlc_mutex_unlock(&p_stream->lock);
2081 return VLC_SUCCESS;
2084 p_stream->p_http_headers = vlc_alloc(i_headers, sizeof(httpd_header));
2085 if (!p_stream->p_http_headers) {
2086 vlc_mutex_unlock(&p_stream->lock);
2087 return VLC_ENOMEM;
2090 size_t j = 0;
2091 for (size_t i = 0; i < i_headers; i++) {
2092 if (unlikely(!p_headers[i].name || !p_headers[i].value))
2093 continue;
2095 p_stream->p_http_headers[j].name = strdup(p_headers[i].name);
2096 p_stream->p_http_headers[j].value = strdup(p_headers[i].value);
2098 if (unlikely(!p_stream->p_http_headers[j].name ||
2099 !p_stream->p_http_headers[j].value)) {
2100 free(p_stream->p_http_headers[j].name);
2101 free(p_stream->p_http_headers[j].value);
2102 break;
2104 j++;
2106 p_stream->i_http_headers = j;
2107 vlc_mutex_unlock(&p_stream->lock);
2108 return VLC_SUCCESS;