1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2004-2006 VLC authors and VideoLAN
5 * Copyright © 2004-2007 Rémi Denis-Courmont
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 *****************************************************************************/
30 #include <vlc_common.h>
31 #include <vlc_httpd.h>
35 #include <vlc_network.h>
37 #include <vlc_strings.h>
39 #include <vlc_charset.h>
42 #include <vlc_block.h>
43 #include "../libvlc.h"
54 # include <winsock2.h>
56 # include <sys/socket.h>
60 /* We need HUGE buffer otherwise TCP throughput is very limited */
61 #define HTTPD_CL_BUFSIZE 1000000
63 #define HTTPD_CL_BUFSIZE 10000
66 static void httpd_ClientClean( httpd_client_t *cl );
67 static void httpd_AppendData( httpd_stream_t *stream, uint8_t *p_data, int i_data );
69 /* each host run in his own thread */
77 /* address/port and socket for listening at connections */
86 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
87 * This will slow down the url research but make my live easier
88 * All url will have their cb trigger, but only the first one can answer
94 httpd_client_t **client;
97 vlc_tls_creds_t *p_tls;
114 httpd_callback_sys_t *p_sys;
115 } catch[HTTPD_MSG_MAX];
121 HTTPD_CLIENT_RECEIVING,
122 HTTPD_CLIENT_RECEIVE_DONE,
124 HTTPD_CLIENT_SENDING,
125 HTTPD_CLIENT_SEND_DONE,
127 HTTPD_CLIENT_WAITING,
131 HTTPD_CLIENT_TLS_HS_IN,
132 HTTPD_CLIENT_TLS_HS_OUT
138 HTTPD_CLIENT_FILE, /* default */
139 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
142 struct httpd_client_t
153 mtime_t i_activity_date;
154 mtime_t i_activity_timeout;
156 /* buffer for reading header */
162 * If waiting for a keyframe, this is the position (in bytes) of the
163 * last keyframe the stream saw before this client connected.
166 int64_t i_keyframe_wait_to_pass;
169 httpd_message_t query; /* client -> httpd */
170 httpd_message_t answer; /* httpd -> client */
177 /*****************************************************************************
179 *****************************************************************************/
180 static const char *httpd_ReasonFromCode( unsigned i_code )
185 const char psz_reason[36];
188 static const http_status_info http_reason[] =
190 /*{ 100, "Continue" },
191 { 101, "Switching Protocols" },*/
193 /*{ 201, "Created" },
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" },
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" },
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)
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 != NULL);
268 char *url_Encoded = convert_xml_special_chars (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"
276 "<title>%s</title>\n"
279 "<h1>%d %s%s%s%s</h1>\n"
281 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
283 "</html>\n", errname, code, errname,
284 (url_Encoded ? " (" : ""), (url_Encoded ? url_Encoded : ""), (url_Encoded ? ")" : ""));
298 /*****************************************************************************
299 * High Level Functions: httpd_file_t
300 *****************************************************************************/
308 httpd_file_callback_t pf_fill;
309 httpd_file_sys_t *p_sys;
314 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
315 httpd_message_t *answer, const httpd_message_t *query )
317 httpd_file_t *file = (httpd_file_t*)p_sys;
318 uint8_t **pp_body, *p_body;
319 const char *psz_connection;
320 int *pi_body, i_body;
322 if( answer == NULL || query == NULL )
326 answer->i_proto = HTTPD_PROTO_HTTP;
327 answer->i_version= 1;
328 answer->i_type = HTTPD_MSG_ANSWER;
330 answer->i_status = 200;
332 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
333 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
335 if( query->i_type != HTTPD_MSG_HEAD )
337 pp_body = &answer->p_body;
338 pi_body = &answer->i_body;
342 /* The file still needs to be executed. */
349 if( query->i_type == HTTPD_MSG_POST )
351 /* msg_Warn not supported */
354 uint8_t *psz_args = query->psz_args;
355 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
357 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
362 /* We respect client request */
363 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
364 if( psz_connection != NULL )
366 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
369 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
374 httpd_file_t *httpd_FileNew( httpd_host_t *host,
375 const char *psz_url, const char *psz_mime,
376 const char *psz_user, const char *psz_password,
377 httpd_file_callback_t pf_fill,
378 httpd_file_sys_t *p_sys )
380 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
382 file->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
383 if( file->url == NULL )
389 file->psz_url = strdup( psz_url );
390 if( psz_mime && *psz_mime )
392 file->psz_mime = strdup( psz_mime );
396 file->psz_mime = strdup( vlc_mime_Ext2Mime( psz_url ) );
399 file->pf_fill = pf_fill;
402 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
403 (httpd_callback_sys_t*)file );
404 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
405 (httpd_callback_sys_t*)file );
406 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
407 (httpd_callback_sys_t*)file );
412 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
414 httpd_file_sys_t *p_sys = file->p_sys;
416 httpd_UrlDelete( file->url );
418 free( file->psz_url );
419 free( file->psz_mime );
426 /*****************************************************************************
427 * High Level Functions: httpd_handler_t (for CGIs)
428 *****************************************************************************/
429 struct httpd_handler_t
433 httpd_handler_callback_t pf_fill;
434 httpd_handler_sys_t *p_sys;
439 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
440 httpd_message_t *answer, const httpd_message_t *query )
442 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
443 char psz_remote_addr[NI_MAXNUMERICHOST];
445 if( answer == NULL || query == NULL )
449 answer->i_proto = HTTPD_PROTO_NONE;
450 answer->i_type = HTTPD_MSG_ANSWER;
452 /* We do it ourselves, thanks */
453 answer->i_status = 0;
455 if( httpd_ClientIP( cl, psz_remote_addr, NULL ) == NULL )
456 *psz_remote_addr = '\0';
458 uint8_t *psz_args = query->psz_args;
459 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
460 query->i_type, query->p_body, query->i_body,
461 psz_remote_addr, NULL,
462 &answer->p_body, &answer->i_body );
464 if( query->i_type == HTTPD_MSG_HEAD )
466 char *p = (char *)answer->p_body;
468 /* Looks for end of header (i.e. one empty line) */
469 while ( (p = strchr( p, '\r' )) != NULL )
471 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
472 && p[3] && p[3] == '\n' )
481 answer->i_body = strlen((char*)answer->p_body) + 1;
482 answer->p_body = xrealloc( answer->p_body, answer->i_body );
486 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
488 int i_status, i_headers;
489 char *psz_headers, *psz_new;
490 const char *psz_status;
492 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
495 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
496 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
497 if( *psz_headers == '\n' ) psz_headers++;
498 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
503 psz_headers = (char *)answer->p_body;
504 i_headers = answer->i_body;
507 psz_status = httpd_ReasonFromCode( i_status );
508 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
509 + strlen(psz_status) + i_headers - 1;
510 psz_new = (char *)xmalloc( answer->i_body + 1);
511 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
512 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
513 free( answer->p_body );
514 answer->p_body = (uint8_t *)psz_new;
520 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
521 const char *psz_user,
522 const char *psz_password,
523 httpd_handler_callback_t pf_fill,
524 httpd_handler_sys_t *p_sys )
526 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
528 handler->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
529 if( handler->url == NULL )
535 handler->pf_fill = pf_fill;
536 handler->p_sys = p_sys;
538 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
539 (httpd_callback_sys_t*)handler );
540 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
541 (httpd_callback_sys_t*)handler );
542 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
543 (httpd_callback_sys_t*)handler );
548 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
550 httpd_handler_sys_t *p_sys = handler->p_sys;
551 httpd_UrlDelete( handler->url );
556 /*****************************************************************************
557 * High Level Functions: httpd_redirect_t
558 *****************************************************************************/
559 struct httpd_redirect_t
565 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
566 httpd_client_t *cl, httpd_message_t *answer,
567 const httpd_message_t *query )
569 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
573 if( answer == NULL || query == NULL )
577 answer->i_proto = HTTPD_PROTO_HTTP;
578 answer->i_version= 1;
579 answer->i_type = HTTPD_MSG_ANSWER;
580 answer->i_status = 301;
582 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
583 answer->p_body = (unsigned char *)p_body;
585 /* XXX check if it's ok or we need to set an absolute url */
586 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
588 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
593 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
594 const char *psz_url_src )
596 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
598 rdir->url = httpd_UrlNew( host, psz_url_src, NULL, NULL );
599 if( rdir->url == NULL )
604 rdir->psz_dst = strdup( psz_url_dst );
606 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
607 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
608 (httpd_callback_sys_t*)rdir );
609 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
610 (httpd_callback_sys_t*)rdir );
611 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
612 (httpd_callback_sys_t*)rdir );
613 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
614 (httpd_callback_sys_t*)rdir );
618 void httpd_RedirectDelete( httpd_redirect_t *rdir )
620 httpd_UrlDelete( rdir->url );
621 free( rdir->psz_dst );
625 /*****************************************************************************
626 * High Level Funtions: httpd_stream_t
627 *****************************************************************************/
628 struct httpd_stream_t
635 /* Header to send as first packet */
639 /* Some muxes, in particular the avformat mux, can mark given blocks
640 * as keyframes, to ensure that the stream starts with one.
641 * (This is particularly important for WebM streaming to certain
642 * browsers.) Store if we've ever seen any such keyframe blocks,
643 * and if so, the byte position of the start of the last one. */
644 bool b_has_keyframes;
645 int64_t i_last_keyframe_seen_pos;
647 /* circular buffer */
648 int i_buffer_size; /* buffer size, can't be reallocated smaller */
649 uint8_t *p_buffer; /* buffer */
650 int64_t i_buffer_pos; /* absolute position from begining */
651 int64_t i_buffer_last_pos; /* a new connection will start with that */
654 size_t i_http_headers;
655 httpd_header * p_http_headers;
658 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
659 httpd_client_t *cl, httpd_message_t *answer,
660 const httpd_message_t *query )
662 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
664 if( answer == NULL || query == NULL || cl == NULL )
669 if( answer->i_body_offset > 0 )
674 if( answer->i_body_offset >= stream->i_buffer_pos )
676 return VLC_EGENERIC; /* wait, no data available */
678 if( cl->i_keyframe_wait_to_pass >= 0 )
680 if( stream->i_last_keyframe_seen_pos <= cl->i_keyframe_wait_to_pass )
681 /* still waiting for the next keyframe */
684 /* seek to the new keyframe */
685 answer->i_body_offset = stream->i_last_keyframe_seen_pos;
686 cl->i_keyframe_wait_to_pass = -1;
688 if( answer->i_body_offset + stream->i_buffer_size <
689 stream->i_buffer_pos )
691 /* this client isn't fast enough */
692 answer->i_body_offset = stream->i_buffer_last_pos;
695 i_pos = answer->i_body_offset % stream->i_buffer_size;
696 i_write = stream->i_buffer_pos - answer->i_body_offset;
697 if( i_write > HTTPD_CL_BUFSIZE )
699 i_write = HTTPD_CL_BUFSIZE;
701 else if( i_write <= 0 )
703 return VLC_EGENERIC; /* wait, no data available */
706 /* Don't go past the end of the circular buffer */
707 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
709 /* using HTTPD_MSG_ANSWER -> data available */
710 answer->i_proto = HTTPD_PROTO_HTTP;
711 answer->i_version= 0;
712 answer->i_type = HTTPD_MSG_ANSWER;
714 answer->i_body = i_write;
715 answer->p_body = xmalloc( i_write );
716 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
718 answer->i_body_offset += i_write;
724 answer->i_proto = HTTPD_PROTO_HTTP;
725 answer->i_version= 0;
726 answer->i_type = HTTPD_MSG_ANSWER;
728 answer->i_status = 200;
730 bool b_has_content_type = false;
731 bool b_has_cache_control = false;
733 vlc_mutex_lock( &stream->lock );
734 for( size_t i = 0; i < stream->i_http_headers; i++ )
736 if( strncasecmp( stream->p_http_headers[i].name, "Content-Length", 14 ) )
738 httpd_MsgAdd( answer, stream->p_http_headers[i].name,
739 stream->p_http_headers[i].value );
741 if( !strncasecmp( stream->p_http_headers[i].name, "Content-Type", 12 ) )
742 b_has_content_type = true;
743 else if( !strncasecmp( stream->p_http_headers[i].name, "Cache-Control", 13 ) )
744 b_has_cache_control = true;
747 vlc_mutex_unlock( &stream->lock );
749 if( query->i_type != HTTPD_MSG_HEAD )
751 cl->b_stream_mode = true;
752 vlc_mutex_lock( &stream->lock );
753 /* Send the header */
754 if( stream->i_header > 0 )
756 answer->i_body = stream->i_header;
757 answer->p_body = xmalloc( stream->i_header );
758 memcpy( answer->p_body, stream->p_header, stream->i_header );
760 answer->i_body_offset = stream->i_buffer_last_pos;
761 if( stream->b_has_keyframes )
762 cl->i_keyframe_wait_to_pass = stream->i_last_keyframe_seen_pos;
764 cl->i_keyframe_wait_to_pass = -1;
765 vlc_mutex_unlock( &stream->lock );
769 httpd_MsgAdd( answer, "Content-Length", "0" );
770 answer->i_body_offset = 0;
773 /* FIXME: move to http access_output */
774 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
776 bool b_xplaystream = false;
778 httpd_MsgAdd( answer, "Content-type", "application/octet-stream" );
779 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
780 httpd_MsgAdd( answer, "Pragma", "no-cache" );
781 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
782 vlc_mrand48()&0x7fff );
783 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
785 /* Check if there is a xPlayStrm=1 */
786 for( size_t i = 0; i < query->i_headers; i++ )
788 if( !strcasecmp( query->p_headers[i].name, "Pragma" ) &&
789 strstr( query->p_headers[i].value, "xPlayStrm=1" ) )
791 b_xplaystream = true;
797 answer->i_body_offset = 0;
800 else if( !b_has_content_type )
802 httpd_MsgAdd( answer, "Content-type", stream->psz_mime );
804 if( !b_has_cache_control )
805 httpd_MsgAdd( answer, "Cache-Control", "no-cache" );
810 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
811 const char *psz_url, const char *psz_mime,
812 const char *psz_user, const char *psz_password )
814 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
816 stream->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
817 if( stream->url == NULL )
822 vlc_mutex_init( &stream->lock );
823 if( psz_mime && *psz_mime )
825 stream->psz_mime = strdup( psz_mime );
829 stream->psz_mime = strdup( vlc_mime_Ext2Mime( psz_url ) );
831 stream->i_header = 0;
832 stream->p_header = NULL;
833 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
834 stream->p_buffer = xmalloc( stream->i_buffer_size );
835 /* We set to 1 to make life simpler
836 * (this way i_body_offset can never be 0) */
837 stream->i_buffer_pos = 1;
838 stream->i_buffer_last_pos = 1;
839 stream->b_has_keyframes = false;
840 stream->i_last_keyframe_seen_pos = 0;
841 stream->i_http_headers = 0;
842 stream->p_http_headers = NULL;
844 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
845 (httpd_callback_sys_t*)stream );
846 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
847 (httpd_callback_sys_t*)stream );
848 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
849 (httpd_callback_sys_t*)stream );
854 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
856 vlc_mutex_lock( &stream->lock );
857 free( stream->p_header );
858 stream->p_header = NULL;
860 stream->i_header = i_data;
863 stream->p_header = xmalloc( i_data );
864 memcpy( stream->p_header, p_data, i_data );
866 vlc_mutex_unlock( &stream->lock );
871 static void httpd_AppendData( httpd_stream_t *stream, uint8_t *p_data, int i_data )
873 int i_pos = stream->i_buffer_pos % stream->i_buffer_size;
874 int i_count = i_data;
879 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
881 /* Ok, we can't go past the end of our buffer */
882 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
884 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
889 stream->i_buffer_pos += i_data;
892 int httpd_StreamSend( httpd_stream_t *stream, const block_t *p_block )
894 if( p_block == NULL || p_block->p_buffer == NULL )
898 vlc_mutex_lock( &stream->lock );
900 /* save this pointer (to be used by new connection) */
901 stream->i_buffer_last_pos = stream->i_buffer_pos;
903 if( p_block->i_flags & BLOCK_FLAG_TYPE_I )
905 stream->b_has_keyframes = true;
906 stream->i_last_keyframe_seen_pos = stream->i_buffer_pos;
909 httpd_AppendData( stream, p_block->p_buffer, p_block->i_buffer );
911 vlc_mutex_unlock( &stream->lock );
915 void httpd_StreamDelete( httpd_stream_t *stream )
917 httpd_UrlDelete( stream->url );
918 for( size_t i = 0; i < stream->i_http_headers; i++ )
920 free( stream->p_http_headers[i].name );
921 free( stream->p_http_headers[i].value );
923 free( stream->p_http_headers );
924 vlc_mutex_destroy( &stream->lock );
925 free( stream->psz_mime );
926 free( stream->p_header );
927 free( stream->p_buffer );
931 /*****************************************************************************
933 *****************************************************************************/
934 static void* httpd_HostThread( void * );
935 static httpd_host_t *httpd_HostCreate( vlc_object_t *, const char *,
936 const char *, vlc_tls_creds_t * );
938 /* create a new host */
939 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
941 return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
944 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
946 char *cert = var_InheritString( obj, "http-cert" );
949 msg_Err( obj, "HTTP/TLS certificate not specified!" );
953 char *key = var_InheritString( obj, "http-key" );
954 vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
958 msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
959 cert, (key != NULL) ? key : cert );
967 char *ca = var_InheritString( obj, "http-ca" );
970 if( vlc_tls_ServerAddCA( tls, ca ) )
972 msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
979 char *crl = var_InheritString( obj, "http-crl" );
982 if( vlc_tls_ServerAddCRL( tls, crl ) )
984 msg_Err( obj, "TLS CRL error (%s)", crl );
991 return httpd_HostCreate( obj, "http-host", "https-port", tls );
994 vlc_tls_Delete( tls );
998 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
1000 return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
1007 httpd_host_t **host;
1009 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
1011 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
1012 const char *hostvar,
1013 const char *portvar,
1014 vlc_tls_creds_t *p_tls )
1017 char *hostname = var_InheritString( p_this, hostvar );
1018 unsigned port = var_InheritInteger( p_this, portvar );
1021 vlc_UrlParse( &url, hostname, 0 );
1023 if( url.i_port != 0 )
1025 msg_Err( p_this, "Ignoring port %d (using %d)", url.i_port, port );
1026 msg_Info( p_this, "Specify port %d separately with the "
1027 "%s option instead.", url.i_port, portvar );
1030 /* to be sure to avoid multiple creation */
1031 vlc_mutex_lock( &httpd.mutex );
1033 /* verify if it already exist */
1034 for( int i = 0; i < httpd.i_host; i++ )
1036 host = httpd.host[i];
1038 /* cannot mix TLS and non-TLS hosts */
1039 if( host->port != port
1040 || (host->p_tls != NULL) != (p_tls != NULL) )
1043 /* Increase existing matching host reference count.
1044 * The reference count is written under both the global httpd and the
1045 * host lock. It is read with either or both locks held. The global
1046 * lock is always acquired first. */
1047 vlc_mutex_lock( &host->lock );
1049 vlc_mutex_unlock( &host->lock );
1051 vlc_mutex_unlock( &httpd.mutex );
1052 vlc_UrlClean( &url );
1053 vlc_tls_Delete( p_tls );
1057 /* create the new host */
1058 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1063 vlc_mutex_init( &host->lock );
1064 vlc_cond_init( &host->wait );
1067 host->fds = net_ListenTCP( p_this, url.psz_host, port );
1068 if( host->fds == NULL )
1070 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1073 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1075 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1077 msg_Err( host, "signaling pipe error: %s", vlc_strerror_c(errno) );
1085 host->client = NULL;
1086 host->p_tls = p_tls;
1088 /* create the thread */
1089 if( vlc_clone( &host->thread, httpd_HostThread, host,
1090 VLC_THREAD_PRIORITY_LOW ) )
1092 msg_Err( p_this, "cannot spawn http host thread" );
1096 /* now add it to httpd */
1097 TAB_APPEND( httpd.i_host, httpd.host, host );
1098 vlc_mutex_unlock( &httpd.mutex );
1100 vlc_UrlClean( &url );
1105 vlc_mutex_unlock( &httpd.mutex );
1109 net_ListenClose( host->fds );
1110 vlc_cond_destroy( &host->wait );
1111 vlc_mutex_destroy( &host->lock );
1112 vlc_object_release( host );
1115 vlc_UrlClean( &url );
1116 vlc_tls_Delete( p_tls );
1121 void httpd_HostDelete( httpd_host_t *host )
1123 bool delete = false;
1125 vlc_mutex_lock( &httpd.mutex );
1127 vlc_mutex_lock( &host->lock );
1129 if( host->i_ref == 0 )
1131 vlc_mutex_unlock( &host->lock );
1135 vlc_mutex_unlock( &httpd.mutex );
1136 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1139 TAB_REMOVE( httpd.i_host, httpd.host, host );
1141 vlc_cancel( host->thread );
1142 vlc_join( host->thread, NULL );
1144 msg_Dbg( host, "HTTP host removed" );
1146 for( int i = 0; i < host->i_url; i++ )
1148 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1150 for( int i = 0; i < host->i_client; i++ )
1152 httpd_client_t *cl = host->client[i];
1153 msg_Warn( host, "client still connected" );
1154 httpd_ClientClean( cl );
1155 TAB_REMOVE( host->i_client, host->client, cl );
1161 vlc_tls_Delete( host->p_tls );
1162 net_ListenClose( host->fds );
1163 vlc_cond_destroy( &host->wait );
1164 vlc_mutex_destroy( &host->lock );
1165 vlc_object_release( host );
1166 vlc_mutex_unlock( &httpd.mutex );
1169 /* register a new url */
1170 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1171 const char *psz_user, const char *psz_password )
1175 assert( psz_url != NULL );
1177 vlc_mutex_lock( &host->lock );
1178 for( int i = 0; i < host->i_url; i++ )
1180 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1183 "cannot add '%s' (url already defined)", psz_url );
1184 vlc_mutex_unlock( &host->lock );
1189 url = xmalloc( sizeof( httpd_url_t ) );
1192 vlc_mutex_init( &url->lock );
1193 url->psz_url = strdup( psz_url );
1194 url->psz_user = strdup( psz_user ? psz_user : "" );
1195 url->psz_password = strdup( psz_password ? psz_password : "" );
1196 for( int i = 0; i < HTTPD_MSG_MAX; i++ )
1198 url->catch[i].cb = NULL;
1199 url->catch[i].p_sys = NULL;
1202 TAB_APPEND( host->i_url, host->url, url );
1203 vlc_cond_signal( &host->wait );
1204 vlc_mutex_unlock( &host->lock );
1209 /* register callback on a url */
1210 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1211 httpd_callback_sys_t *p_sys )
1213 vlc_mutex_lock( &url->lock );
1214 url->catch[i_msg].cb = cb;
1215 url->catch[i_msg].p_sys= p_sys;
1216 vlc_mutex_unlock( &url->lock );
1222 void httpd_UrlDelete( httpd_url_t *url )
1224 httpd_host_t *host = url->host;
1226 vlc_mutex_lock( &host->lock );
1227 TAB_REMOVE( host->i_url, host->url, url );
1229 vlc_mutex_destroy( &url->lock );
1230 free( url->psz_url );
1231 free( url->psz_user );
1232 free( url->psz_password );
1234 for( int i = 0; i < host->i_client; i++ )
1236 httpd_client_t *client = host->client[i];
1238 if( client->url == url )
1240 /* TODO complete it */
1241 msg_Warn( host, "force closing connections" );
1242 httpd_ClientClean( client );
1243 TAB_REMOVE( host->i_client, host->client, client );
1249 vlc_mutex_unlock( &host->lock );
1252 static void httpd_MsgInit( httpd_message_t *msg )
1255 msg->i_type = HTTPD_MSG_NONE;
1256 msg->i_proto = HTTPD_PROTO_NONE;
1257 msg->i_version = -1; /* FIXME */
1261 msg->psz_url = NULL;
1262 msg->psz_args = NULL;
1265 msg->p_headers = NULL;
1267 msg->i_body_offset = 0;
1272 static void httpd_MsgClean( httpd_message_t *msg )
1274 free( msg->psz_url );
1275 free( msg->psz_args );
1276 for( size_t i = 0; i < msg->i_headers; i++ )
1278 free( msg->p_headers[i].name );
1279 free( msg->p_headers[i].value );
1281 free( msg->p_headers );
1282 free( msg->p_body );
1283 httpd_MsgInit( msg );
1286 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1288 for( size_t i = 0; i < msg->i_headers; i++ )
1290 if( !strcasecmp( msg->p_headers[i].name, name ))
1292 return msg->p_headers[i].value;
1298 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1300 httpd_header *p_tmp = realloc( msg->p_headers, sizeof(httpd_header) * (msg->i_headers + 1));
1304 msg->p_headers = p_tmp;
1306 httpd_header *h = &msg->p_headers[msg->i_headers];
1307 h->name = strdup(name);
1314 va_start( args, psz_value );
1315 int ret = us_vasprintf(&h->value, psz_value, args);
1326 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1328 cl->i_state = HTTPD_CLIENT_RECEIVING;
1329 cl->i_activity_date = now;
1330 cl->i_activity_timeout = INT64_C(10000000);
1331 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1333 cl->p_buffer = xmalloc( cl->i_buffer_size );
1334 cl->i_keyframe_wait_to_pass = -1;
1335 cl->b_stream_mode = false;
1337 httpd_MsgInit( &cl->query );
1338 httpd_MsgInit( &cl->answer );
1341 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1343 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1346 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1348 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1351 static void httpd_ClientClean( httpd_client_t *cl )
1355 if( cl->p_tls != NULL )
1356 vlc_tls_SessionDelete( cl->p_tls );
1357 net_Close( cl->fd );
1361 httpd_MsgClean( &cl->answer );
1362 httpd_MsgClean( &cl->query );
1364 free( cl->p_buffer );
1365 cl->p_buffer = NULL;
1368 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1370 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1372 if( !cl ) return NULL;
1379 httpd_ClientInit( cl, now );
1381 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1387 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1394 val = p_tls ? tls_Recv (p_tls, p, i_len)
1395 : recv (cl->fd, p, i_len, 0);
1396 while (val == -1 && errno == EINTR);
1401 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1408 val = p_tls ? tls_Send( p_tls, p, i_len )
1409 : send (cl->fd, p, i_len, 0);
1410 while (val == -1 && errno == EINTR);
1417 const char name[16];
1423 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1424 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1425 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1426 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1427 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1428 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1429 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1430 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1431 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1432 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1433 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1437 static void httpd_ClientRecv( httpd_client_t *cl )
1441 /* ignore leading whites */
1442 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1443 ( cl->i_buffer == 0 ) )
1447 i_len = httpd_NetRecv( cl, &c, 1 );
1449 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1451 cl->p_buffer[0] = c;
1456 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1458 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1459 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1463 cl->i_buffer += i_len;
1466 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1467 * this is the maximum we can ask at this point. */
1468 if( cl->i_buffer >= 7 )
1470 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1472 cl->query.i_proto = HTTPD_PROTO_HTTP;
1473 cl->query.i_type = HTTPD_MSG_ANSWER;
1475 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1477 cl->query.i_proto = HTTPD_PROTO_RTSP;
1478 cl->query.i_type = HTTPD_MSG_ANSWER;
1482 /* We need the full request line to determine the protocol. */
1483 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1484 cl->query.i_type = HTTPD_MSG_NONE;
1488 else if( cl->query.i_body > 0 )
1490 /* we are reading the body of a request or a channel */
1491 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1492 cl->query.i_body - cl->i_buffer );
1495 cl->i_buffer += i_len;
1497 if( cl->i_buffer >= cl->query.i_body )
1499 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1504 /* we are reading a header -> char by char */
1507 if( cl->i_buffer == cl->i_buffer_size )
1509 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1510 if( newbuf == NULL )
1516 cl->p_buffer = newbuf;
1517 cl->i_buffer_size += 1024;
1520 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1527 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1528 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1530 /* Request line is now complete */
1531 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1534 assert( cl->query.i_type == HTTPD_MSG_NONE );
1536 if( p == NULL ) /* no URI: evil guy */
1538 i_len = 0; /* drop connection */
1543 p++; /* skips extra spaces */
1546 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1547 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1549 i_len = 0; /* not supported currently -> drop */
1554 p++; /* skips extra spaces ever again */
1557 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1558 if( len < 7 ) /* foreign protocol */
1559 i_len = 0; /* I don't understand -> drop */
1561 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1563 cl->query.i_proto = HTTPD_PROTO_HTTP;
1564 cl->query.i_version = atoi( p + 7 );
1567 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1569 cl->query.i_proto = HTTPD_PROTO_RTSP;
1570 cl->query.i_version = atoi( p + 7 );
1573 if( memcmp( p, "HTTP/", 5 ) == 0 )
1575 const uint8_t sorry[] =
1576 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1577 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1578 i_len = 0; /* drop */
1581 if( memcmp( p, "RTSP/", 5 ) == 0 )
1583 const uint8_t sorry[] =
1584 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1585 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1586 i_len = 0; /* drop */
1588 else /* yet another foreign protocol */
1595 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1596 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1600 /* we have finished the header so parse it and set i_body */
1601 cl->p_buffer[cl->i_buffer] = '\0';
1603 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1606 * assume strlen( "HTTP/1.x" ) = 8
1608 cl->query.i_status =
1609 strtol( (char *)&cl->p_buffer[8],
1617 cl->query.i_type = HTTPD_MSG_NONE;
1619 for( unsigned i = 0; msg_type[i].name[0]; i++ )
1621 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1622 strlen( msg_type[i].name ) ) )
1624 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1625 cl->query.i_type = msg_type[i].i_type;
1626 if( cl->query.i_proto != msg_type[i].i_proto )
1629 cl->query.i_proto = HTTPD_PROTO_NONE;
1630 cl->query.i_type = HTTPD_MSG_NONE;
1637 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1639 cl->query.i_proto = HTTPD_PROTO_HTTP;
1641 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1643 cl->query.i_proto = HTTPD_PROTO_RTSP;
1655 p2 = strchr( p, ' ' );
1660 if( !strncasecmp( p, ( cl->query.i_proto
1661 == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1662 { /* Skip hier-part of URL (if present) */
1664 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1665 { /* see RFC3986 §3.2 */
1667 p += strcspn( p, "/?#" );
1671 if( !strncasecmp( p, ( cl->query.i_proto
1672 == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1673 { /* Skip hier-part of URL (if present) */
1675 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1676 { /* see RFC3986 §3.2 */
1678 p += strcspn( p, "/?#" );
1682 cl->query.psz_url = strdup( p );
1683 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1686 cl->query.psz_args = (uint8_t *)strdup( p3 );
1693 p = strchr( p, '\n' );
1697 while( *p == '\n' || *p == '\r' )
1701 while( p && *p != '\0' )
1704 char *eol = p = strchr( p, '\n' );
1707 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1712 if( ( colon = strchr( line, ':' ) ) )
1715 while( *colon == ' ' )
1719 httpd_MsgAdd( &cl->query, line, colon );
1721 if( !strcasecmp( line, "Content-Length" ) )
1723 cl->query.i_body = atol( colon );
1730 while( *p == '\n' || *p == '\r' )
1737 if( cl->query.i_body > 0 )
1739 /* TODO Mhh, handle the case where the client only
1740 * sends a request and closes the connection to
1741 * mark the end of the body (probably only RTSP) */
1742 cl->query.p_body = malloc( cl->query.i_body );
1744 if ( cl->query.p_body == NULL ) {
1745 switch (cl->query.i_proto) {
1746 case HTTPD_PROTO_HTTP: {
1747 const uint8_t sorry[] =
1748 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1749 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1752 case HTTPD_PROTO_RTSP: {
1753 const uint8_t sorry[] =
1754 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1755 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1761 i_len = 0; /* drop */
1767 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1773 /* check if the client is to be set to dead */
1774 #if defined( _WIN32 )
1775 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1777 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1780 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1782 /* connection closed -> end of data */
1783 if( cl->query.i_body > 0 )
1785 cl->query.i_body = cl->i_buffer;
1787 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1791 cl->i_state = HTTPD_CLIENT_DEAD;
1795 /* XXX: for QT I have to disable timeout. Try to find why */
1796 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1797 cl->i_activity_timeout = 0;
1800 static void httpd_ClientSend( httpd_client_t *cl )
1804 if( cl->i_buffer < 0 )
1806 /* We need to create the header */
1809 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1811 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1812 for( size_t i = 0; i < cl->answer.i_headers; i++ )
1814 i_size += strlen( cl->answer.p_headers[i].name ) + 2 +
1815 strlen( cl->answer.p_headers[i].value ) + 2;
1818 if( cl->i_buffer_size < i_size )
1820 cl->i_buffer_size = i_size;
1821 free( cl->p_buffer );
1822 cl->p_buffer = xmalloc( i_size );
1824 p = (char *)cl->p_buffer;
1826 p += sprintf( p, "%s.%u %d %s\r\n",
1827 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1828 cl->answer.i_version,
1829 cl->answer.i_status, psz_status );
1830 for( size_t i = 0; i < cl->answer.i_headers; i++ )
1832 p += sprintf( p, "%s: %s\r\n", cl->answer.p_headers[i].name,
1833 cl->answer.p_headers[i].value );
1835 p += sprintf( p, "\r\n" );
1838 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1841 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1842 cl->i_buffer_size - cl->i_buffer );
1845 cl->i_buffer += i_len;
1847 if( cl->i_buffer >= cl->i_buffer_size )
1849 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 )
1851 /* catch more body data */
1852 int i_msg = cl->query.i_type;
1853 int64_t i_offset = cl->answer.i_body_offset;
1855 httpd_MsgClean( &cl->answer );
1856 cl->answer.i_body_offset = i_offset;
1858 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1859 &cl->answer, &cl->query );
1862 if( cl->answer.i_body > 0 )
1864 /* send the body data */
1865 free( cl->p_buffer );
1866 cl->p_buffer = cl->answer.p_body;
1867 cl->i_buffer_size = cl->answer.i_body;
1870 cl->answer.i_body = 0;
1871 cl->answer.p_body = NULL;
1876 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1882 #if defined( _WIN32 )
1883 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1885 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1889 cl->i_state = HTTPD_CLIENT_DEAD;
1894 static void httpd_ClientTlsHandshake( httpd_client_t *cl )
1896 switch( vlc_tls_SessionHandshake( cl->p_tls, NULL, NULL ) ) {
1897 case -1: cl->i_state = HTTPD_CLIENT_DEAD; break;
1898 case 0: cl->i_state = HTTPD_CLIENT_RECEIVING; break;
1899 case 1: cl->i_state = HTTPD_CLIENT_TLS_HS_IN; break;
1900 case 2: cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1904 static bool httpdAuthOk(const char *user, const char *pass, const char *b64)
1906 if (!*user && !*pass)
1912 if (strncasecmp(b64, "BASIC", 5))
1919 char *given_user = vlc_b64_decode(b64);
1923 char *given_pass = NULL;
1924 given_pass = strchr (given_user, ':');
1928 *given_pass++ = '\0';
1930 if (strcmp (given_user, user))
1933 if (strcmp (given_pass, pass))
1944 static void httpdLoop(httpd_host_t *host)
1946 struct pollfd ufd[host->nfd + host->i_client];
1948 for( nfd = 0; nfd < host->nfd; nfd++ )
1950 ufd[nfd].fd = host->fds[nfd];
1951 ufd[nfd].events = POLLIN;
1952 ufd[nfd].revents = 0;
1955 /* add all socket that should be read/write and close dead connection */
1956 while( host->i_url <= 0 )
1958 mutex_cleanup_push( &host->lock );
1959 vlc_cond_wait( &host->wait, &host->lock );
1963 mtime_t now = mdate();
1964 bool b_low_delay = false;
1966 int canc = vlc_savecancel();
1967 for(int i_client = 0; i_client < host->i_client; i_client++ )
1970 httpd_client_t *cl = host->client[i_client];
1971 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1972 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1973 ( cl->i_activity_timeout > 0 &&
1974 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
1976 httpd_ClientClean( cl );
1977 TAB_REMOVE( host->i_client, host->client, cl );
1983 struct pollfd *pufd = ufd + nfd;
1984 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1987 pufd->events = pufd->revents = 0;
1989 switch (cl->i_state) {
1990 case HTTPD_CLIENT_RECEIVING:
1991 case HTTPD_CLIENT_TLS_HS_IN:
1992 pufd->events = POLLIN;
1995 case HTTPD_CLIENT_SENDING:
1996 case HTTPD_CLIENT_TLS_HS_OUT:
1997 pufd->events = POLLOUT;
2000 case HTTPD_CLIENT_RECEIVE_DONE: {
2001 httpd_message_t *answer = &cl->answer;
2002 httpd_message_t *query = &cl->query;
2004 httpd_MsgInit( answer );
2006 /* Handle what we received */
2007 switch (query->i_type) {
2008 case HTTPD_MSG_ANSWER:
2010 cl->i_state = HTTPD_CLIENT_DEAD;
2013 case HTTPD_MSG_OPTIONS:
2014 answer->i_type = HTTPD_MSG_ANSWER;
2015 answer->i_proto = query->i_proto;
2016 answer->i_status = 200;
2018 answer->p_body = NULL;
2020 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2021 httpd_MsgAdd( answer, "Content-Length", "0" );
2023 switch( query->i_proto )
2025 case HTTPD_PROTO_HTTP:
2026 answer->i_version = 1;
2027 httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
2030 case HTTPD_PROTO_RTSP:
2031 answer->i_version = 0;
2033 const char *p = httpd_MsgGet( query, "Cseq" );
2035 httpd_MsgAdd( answer, "Cseq", "%s", p );
2036 p = httpd_MsgGet( query, "Timestamp" );
2038 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2040 p = httpd_MsgGet( query, "Require" );
2042 answer->i_status = 551;
2043 httpd_MsgAdd( query, "Unsupported", "%s", p );
2046 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2047 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2051 cl->i_buffer = -1; /* Force the creation of the answer in
2052 * httpd_ClientSend */
2053 cl->i_state = HTTPD_CLIENT_SENDING;
2056 case HTTPD_MSG_NONE:
2057 if( query->i_proto == HTTPD_PROTO_NONE ) {
2059 cl->i_state = HTTPD_CLIENT_DEAD;
2062 answer->i_proto = query->i_proto ;
2063 answer->i_type = HTTPD_MSG_ANSWER;
2064 answer->i_version= 0;
2065 answer->i_status = 501;
2068 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2069 answer->p_body = (uint8_t *)p;
2070 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2072 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2073 cl->i_state = HTTPD_CLIENT_SENDING;
2078 int i_msg = query->i_type;
2079 bool b_auth_failed = false;
2081 /* Search the url and trigger callbacks */
2082 for(int i = 0; i < host->i_url; i++ ) {
2083 httpd_url_t *url = host->url[i];
2085 if (strcmp(url->psz_url, query->psz_url))
2087 if (!url->catch[i_msg].cb)
2091 b_auth_failed = !httpdAuthOk(url->psz_user,
2093 httpd_MsgGet(query, "Authorization")); /* BASIC id */
2098 if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
2101 if( answer->i_proto == HTTPD_PROTO_NONE )
2102 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
2106 /* only one url can answer */
2108 if( cl->url == NULL )
2113 answer->i_proto = query->i_proto;
2114 answer->i_type = HTTPD_MSG_ANSWER;
2115 answer->i_version= 0;
2117 if( b_auth_failed ) {
2118 httpd_MsgAdd( answer, "WWW-Authenticate",
2119 "Basic realm=\"VLC stream\"" );
2120 answer->i_status = 401;
2122 answer->i_status = 404; /* no url registered */
2125 answer->i_body = httpd_HtmlError (&p, answer->i_status,
2127 answer->p_body = (uint8_t *)p;
2129 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2130 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2131 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2134 cl->i_state = HTTPD_CLIENT_SENDING;
2140 case HTTPD_CLIENT_SEND_DONE:
2141 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2143 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2144 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2145 bool b_connection = false;
2146 bool b_keepalive = false;
2147 bool b_query = false;
2150 if( psz_connection )
2152 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2153 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2158 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2161 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2162 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2163 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2164 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2165 !b_query && !b_connection ) )
2167 httpd_MsgClean( &cl->query );
2168 httpd_MsgInit( &cl->query );
2171 cl->i_buffer_size = 1000;
2172 free( cl->p_buffer );
2173 cl->p_buffer = xmalloc( cl->i_buffer_size );
2174 cl->i_state = HTTPD_CLIENT_RECEIVING;
2178 cl->i_state = HTTPD_CLIENT_DEAD;
2180 httpd_MsgClean( &cl->answer );
2184 i_offset = cl->answer.i_body_offset;
2185 httpd_MsgClean( &cl->answer );
2187 cl->answer.i_body_offset = i_offset;
2188 free( cl->p_buffer );
2189 cl->p_buffer = NULL;
2191 cl->i_buffer_size = 0;
2193 cl->i_state = HTTPD_CLIENT_WAITING;
2197 case HTTPD_CLIENT_WAITING:
2198 i_offset = cl->answer.i_body_offset;
2199 int i_msg = cl->query.i_type;
2201 httpd_MsgInit( &cl->answer );
2202 cl->answer.i_body_offset = i_offset;
2204 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2205 &cl->answer, &cl->query );
2206 if( cl->answer.i_type != HTTPD_MSG_NONE )
2208 /* we have new data, so re-enter send mode */
2210 cl->p_buffer = cl->answer.p_body;
2211 cl->i_buffer_size = cl->answer.i_body;
2212 cl->answer.p_body = NULL;
2213 cl->answer.i_body = 0;
2214 cl->i_state = HTTPD_CLIENT_SENDING;
2218 if (pufd->events != 0)
2223 vlc_mutex_unlock( &host->lock );
2224 vlc_restorecancel( canc );
2226 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2227 int ret = poll( ufd, nfd, b_low_delay ? 20 : -1 );
2229 canc = vlc_savecancel();
2230 vlc_mutex_lock( &host->lock );
2233 if (errno != EINTR) {
2234 /* Kernel on low memory or a bug: pace */
2235 msg_Err( host, "polling error: %s", vlc_strerror_c(errno) );
2239 vlc_restorecancel( canc );
2243 /* Handle client sockets */
2247 for( int i_client = 0; i_client < host->i_client; i_client++ )
2249 httpd_client_t *cl = host->client[i_client];
2250 const struct pollfd *pufd = &ufd[nfd];
2252 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2254 if( cl->fd != pufd->fd )
2255 continue; // we were not waiting for this client
2257 if( pufd->revents == 0 )
2258 continue; // no event received
2260 cl->i_activity_date = now;
2262 switch (cl->i_state) {
2263 case HTTPD_CLIENT_RECEIVING: httpd_ClientRecv( cl ); break;
2264 case HTTPD_CLIENT_SENDING: httpd_ClientSend( cl ); break;
2265 case HTTPD_CLIENT_TLS_HS_IN:
2266 case HTTPD_CLIENT_TLS_HS_OUT: httpd_ClientTlsHandshake( cl ); break;
2270 /* Handle server sockets (accept new connections) */
2271 for( nfd = 0; nfd < host->nfd; nfd++ )
2274 int fd = ufd[nfd].fd;
2276 assert (fd == host->fds[nfd]);
2278 if( ufd[nfd].revents == 0 )
2282 fd = vlc_accept (fd, NULL, NULL, true);
2285 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2286 &(int){ 1 }, sizeof(int));
2290 if( host->p_tls != NULL )
2291 p_tls = vlc_tls_SessionCreate( host->p_tls, fd, NULL );
2295 cl = httpd_ClientNew( fd, p_tls, now );
2297 TAB_APPEND( host->i_client, host->client, cl );
2300 vlc_restorecancel(canc);
2303 static void* httpd_HostThread( void *data )
2305 httpd_host_t *host = data;
2307 vlc_mutex_lock( &host->lock );
2308 while( host->i_ref > 0 )
2310 vlc_mutex_unlock( &host->lock );
2314 int httpd_StreamSetHTTPHeaders(httpd_stream_t * p_stream, httpd_header * p_headers, size_t i_headers )
2317 return VLC_EGENERIC;
2319 vlc_mutex_lock( &p_stream->lock );
2320 if( p_stream->p_http_headers )
2322 for( size_t i = 0; i < p_stream->i_http_headers; i++)
2324 free( p_stream->p_http_headers[i].name );
2325 free( p_stream->p_http_headers[i].value );
2327 free( p_stream->p_http_headers );
2328 p_stream->p_http_headers = NULL;
2329 p_stream->i_http_headers = 0;
2332 if( !p_headers || !i_headers )
2334 vlc_mutex_unlock( &p_stream->lock );
2338 p_stream->p_http_headers = malloc(sizeof(httpd_header) * i_headers );
2339 if( !p_stream->p_http_headers )
2341 vlc_mutex_unlock( &p_stream->lock );
2346 for( size_t i = 0; i < i_headers; i++ )
2348 if( unlikely( !p_headers[i].name || !p_headers[i].value ) )
2351 p_stream->p_http_headers[j].name = strdup( p_headers[i].name );
2352 p_stream->p_http_headers[j].value = strdup( p_headers[i].value );
2354 if( unlikely( !p_stream->p_http_headers[j].name ||
2355 !p_stream->p_http_headers[j].value ) )
2357 free( p_stream->p_http_headers[j].name );
2358 free( p_stream->p_http_headers[j].value );
2363 p_stream->i_http_headers = j;
2364 vlc_mutex_unlock( &p_stream->lock );