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 *****************************************************************************/
183 const char psz_reason[36];
186 static const http_status_info http_reason[] =
188 /*{ 100, "Continue" },
189 { 101, "Switching Protocols" },*/
191 /*{ 201, "Created" },
193 { 203, "Non-authoritative information" },
194 { 204, "No content" },
195 { 205, "Reset content" },
196 { 206, "Partial content" },
197 { 250, "Low on storage space" },
198 { 300, "Multiple choices" },*/
199 { 301, "Moved permanently" },
200 /*{ 302, "Moved temporarily" },
201 { 303, "See other" },
202 { 304, "Not modified" },
203 { 305, "Use proxy" },
204 { 307, "Temporary redirect" },
205 { 400, "Bad request" },*/
206 { 401, "Unauthorized" },
207 /*{ 402, "Payment Required" },*/
208 { 403, "Forbidden" },
209 { 404, "Not found" },
210 { 405, "Method not allowed" },
211 /*{ 406, "Not acceptable" },
212 { 407, "Proxy authentication required" },
213 { 408, "Request time-out" },
216 { 411, "Length required" },
217 { 412, "Precondition failed" },
218 { 413, "Request entity too large" },
219 { 414, "Request-URI too large" },
220 { 415, "Unsupported media Type" },
221 { 416, "Requested range not satisfiable" },
222 { 417, "Expectation failed" },
223 { 451, "Parameter not understood" },
224 { 452, "Conference not found" },
225 { 453, "Not enough bandwidth" },*/
226 { 454, "Session not found" },
227 { 455, "Method not valid in this State" },
228 { 456, "Header field not valid for resource" },
229 { 457, "Invalid range" },
230 /*{ 458, "Read-only parameter" },*/
231 { 459, "Aggregate operation not allowed" },
232 { 460, "Non-aggregate operation not allowed" },
233 { 461, "Unsupported transport" },
234 /*{ 462, "Destination unreachable" },*/
235 { 500, "Internal server error" },
236 { 501, "Not implemented" },
237 /*{ 502, "Bad gateway" },*/
238 { 503, "Service unavailable" },
239 /*{ 504, "Gateway time-out" },*/
240 { 505, "Protocol version not supported" },
241 { 551, "Option not supported" },
245 static const char psz_fallback_reason[5][16] =
246 { "Continue", "OK", "Found", "Client error", "Server error" };
248 static const char *httpd_ReasonFromCode( unsigned i_code )
250 const http_status_info *p;
252 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
254 for (p = http_reason; i_code > p->i_code; p++);
256 if( p->i_code == i_code )
257 return p->psz_reason;
259 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 int res = asprintf (body,
269 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
270 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
271 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
272 "<html lang=\"en\">\n"
274 "<title>%s</title>\n"
277 "<h1>%d %s%s%s%s</h1>\n"
279 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
281 "</html>\n", errname, code, errname,
282 (url ? " (" : ""), (url ? url : ""), (url ? ")" : ""));
294 /*****************************************************************************
295 * High Level Functions: httpd_file_t
296 *****************************************************************************/
304 httpd_file_callback_t pf_fill;
305 httpd_file_sys_t *p_sys;
310 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
311 httpd_message_t *answer, const httpd_message_t *query )
313 httpd_file_t *file = (httpd_file_t*)p_sys;
314 uint8_t **pp_body, *p_body;
315 const char *psz_connection;
316 int *pi_body, i_body;
318 if( answer == NULL || query == NULL )
322 answer->i_proto = HTTPD_PROTO_HTTP;
323 answer->i_version= 1;
324 answer->i_type = HTTPD_MSG_ANSWER;
326 answer->i_status = 200;
328 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
329 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
331 if( query->i_type != HTTPD_MSG_HEAD )
333 pp_body = &answer->p_body;
334 pi_body = &answer->i_body;
338 /* The file still needs to be executed. */
345 if( query->i_type == HTTPD_MSG_POST )
347 /* msg_Warn not supported */
350 uint8_t *psz_args = query->psz_args;
351 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
353 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
358 /* We respect client request */
359 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
360 if( psz_connection != NULL )
362 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
365 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
370 httpd_file_t *httpd_FileNew( httpd_host_t *host,
371 const char *psz_url, const char *psz_mime,
372 const char *psz_user, const char *psz_password,
373 httpd_file_callback_t pf_fill,
374 httpd_file_sys_t *p_sys )
376 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
378 file->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
379 if( file->url == NULL )
385 file->psz_url = strdup( psz_url );
386 if( psz_mime && *psz_mime )
388 file->psz_mime = strdup( psz_mime );
392 file->psz_mime = strdup( vlc_mime_Ext2Mime( psz_url ) );
395 file->pf_fill = pf_fill;
398 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
399 (httpd_callback_sys_t*)file );
400 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
401 (httpd_callback_sys_t*)file );
402 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
403 (httpd_callback_sys_t*)file );
408 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
410 httpd_file_sys_t *p_sys = file->p_sys;
412 httpd_UrlDelete( file->url );
414 free( file->psz_url );
415 free( file->psz_mime );
422 /*****************************************************************************
423 * High Level Functions: httpd_handler_t (for CGIs)
424 *****************************************************************************/
425 struct httpd_handler_t
429 httpd_handler_callback_t pf_fill;
430 httpd_handler_sys_t *p_sys;
435 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
436 httpd_message_t *answer, const httpd_message_t *query )
438 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
439 char psz_remote_addr[NI_MAXNUMERICHOST];
441 if( answer == NULL || query == NULL )
445 answer->i_proto = HTTPD_PROTO_NONE;
446 answer->i_type = HTTPD_MSG_ANSWER;
448 /* We do it ourselves, thanks */
449 answer->i_status = 0;
451 if( httpd_ClientIP( cl, psz_remote_addr, NULL ) == NULL )
452 *psz_remote_addr = '\0';
454 uint8_t *psz_args = query->psz_args;
455 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
456 query->i_type, query->p_body, query->i_body,
457 psz_remote_addr, NULL,
458 &answer->p_body, &answer->i_body );
460 if( query->i_type == HTTPD_MSG_HEAD )
462 char *p = (char *)answer->p_body;
464 /* Looks for end of header (i.e. one empty line) */
465 while ( (p = strchr( p, '\r' )) != NULL )
467 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
468 && p[3] && p[3] == '\n' )
477 answer->i_body = strlen((char*)answer->p_body) + 1;
478 answer->p_body = xrealloc( answer->p_body, answer->i_body );
482 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
484 int i_status, i_headers;
485 char *psz_headers, *psz_new;
486 const char *psz_status;
488 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
491 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
492 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
493 if( *psz_headers == '\n' ) psz_headers++;
494 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
499 psz_headers = (char *)answer->p_body;
500 i_headers = answer->i_body;
503 psz_status = httpd_ReasonFromCode( i_status );
504 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
505 + strlen(psz_status) + i_headers - 1;
506 psz_new = (char *)xmalloc( answer->i_body + 1);
507 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
508 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
509 free( answer->p_body );
510 answer->p_body = (uint8_t *)psz_new;
516 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
517 const char *psz_user,
518 const char *psz_password,
519 httpd_handler_callback_t pf_fill,
520 httpd_handler_sys_t *p_sys )
522 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
524 handler->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
525 if( handler->url == NULL )
531 handler->pf_fill = pf_fill;
532 handler->p_sys = p_sys;
534 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
535 (httpd_callback_sys_t*)handler );
536 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
537 (httpd_callback_sys_t*)handler );
538 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
539 (httpd_callback_sys_t*)handler );
544 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
546 httpd_handler_sys_t *p_sys = handler->p_sys;
547 httpd_UrlDelete( handler->url );
552 /*****************************************************************************
553 * High Level Functions: httpd_redirect_t
554 *****************************************************************************/
555 struct httpd_redirect_t
561 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
562 httpd_client_t *cl, httpd_message_t *answer,
563 const httpd_message_t *query )
565 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
569 if( answer == NULL || query == NULL )
573 answer->i_proto = HTTPD_PROTO_HTTP;
574 answer->i_version= 1;
575 answer->i_type = HTTPD_MSG_ANSWER;
576 answer->i_status = 301;
578 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
579 answer->p_body = (unsigned char *)p_body;
581 /* XXX check if it's ok or we need to set an absolute url */
582 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
584 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
589 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
590 const char *psz_url_src )
592 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
594 rdir->url = httpd_UrlNew( host, psz_url_src, NULL, NULL );
595 if( rdir->url == NULL )
600 rdir->psz_dst = strdup( psz_url_dst );
602 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
603 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
604 (httpd_callback_sys_t*)rdir );
605 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
606 (httpd_callback_sys_t*)rdir );
607 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
608 (httpd_callback_sys_t*)rdir );
609 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
610 (httpd_callback_sys_t*)rdir );
614 void httpd_RedirectDelete( httpd_redirect_t *rdir )
616 httpd_UrlDelete( rdir->url );
617 free( rdir->psz_dst );
621 /*****************************************************************************
622 * High Level Funtions: httpd_stream_t
623 *****************************************************************************/
624 struct httpd_stream_t
631 /* Header to send as first packet */
635 /* Some muxes, in particular the avformat mux, can mark given blocks
636 * as keyframes, to ensure that the stream starts with one.
637 * (This is particularly important for WebM streaming to certain
638 * browsers.) Store if we've ever seen any such keyframe blocks,
639 * and if so, the byte position of the start of the last one. */
640 bool b_has_keyframes;
641 int64_t i_last_keyframe_seen_pos;
643 /* circular buffer */
644 int i_buffer_size; /* buffer size, can't be reallocated smaller */
645 uint8_t *p_buffer; /* buffer */
646 int64_t i_buffer_pos; /* absolute position from begining */
647 int64_t i_buffer_last_pos; /* a new connection will start with that */
650 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
651 httpd_client_t *cl, httpd_message_t *answer,
652 const httpd_message_t *query )
654 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
656 if( answer == NULL || query == NULL || cl == NULL )
661 if( answer->i_body_offset > 0 )
667 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
668 answer->i_body_offset );
671 if( answer->i_body_offset >= stream->i_buffer_pos )
673 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
674 return VLC_EGENERIC; /* wait, no data available */
676 if( cl->i_keyframe_wait_to_pass >= 0 )
678 if( stream->i_last_keyframe_seen_pos <= cl->i_keyframe_wait_to_pass )
679 /* still waiting for the next keyframe */
682 /* seek to the new keyframe */
683 answer->i_body_offset = stream->i_last_keyframe_seen_pos;
684 cl->i_keyframe_wait_to_pass = -1;
686 if( answer->i_body_offset + stream->i_buffer_size <
687 stream->i_buffer_pos )
689 /* this client isn't fast enough */
691 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
692 answer->i_body_offset, stream->i_buffer_last_pos );
694 answer->i_body_offset = stream->i_buffer_last_pos;
697 i_pos = answer->i_body_offset % stream->i_buffer_size;
698 i_write = stream->i_buffer_pos - answer->i_body_offset;
699 if( i_write > HTTPD_CL_BUFSIZE )
701 i_write = HTTPD_CL_BUFSIZE;
703 else if( i_write <= 0 )
705 return VLC_EGENERIC; /* wait, no data available */
708 /* Don't go past the end of the circular buffer */
709 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
711 /* using HTTPD_MSG_ANSWER -> data available */
712 answer->i_proto = HTTPD_PROTO_HTTP;
713 answer->i_version= 0;
714 answer->i_type = HTTPD_MSG_ANSWER;
716 answer->i_body = i_write;
717 answer->p_body = xmalloc( i_write );
718 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
720 answer->i_body_offset += i_write;
726 answer->i_proto = HTTPD_PROTO_HTTP;
727 answer->i_version= 0;
728 answer->i_type = HTTPD_MSG_ANSWER;
730 answer->i_status = 200;
732 if( query->i_type != HTTPD_MSG_HEAD )
734 cl->b_stream_mode = true;
735 vlc_mutex_lock( &stream->lock );
736 /* Send the header */
737 if( stream->i_header > 0 )
739 answer->i_body = stream->i_header;
740 answer->p_body = xmalloc( stream->i_header );
741 memcpy( answer->p_body, stream->p_header, stream->i_header );
743 answer->i_body_offset = stream->i_buffer_last_pos;
744 if( stream->b_has_keyframes )
745 cl->i_keyframe_wait_to_pass = stream->i_last_keyframe_seen_pos;
747 cl->i_keyframe_wait_to_pass = -1;
748 vlc_mutex_unlock( &stream->lock );
752 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
753 answer->i_body_offset = 0;
756 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
758 bool b_xplaystream = false;
761 httpd_MsgAdd( answer, "Content-type", "%s",
762 "application/octet-stream" );
763 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
764 httpd_MsgAdd( answer, "Pragma", "no-cache" );
765 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
766 vlc_mrand48()&0x7fff );
767 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
769 /* Check if there is a xPlayStrm=1 */
770 for( i = 0; i < query->i_name; i++ )
772 if( !strcasecmp( query->name[i], "Pragma" ) &&
773 strstr( query->value[i], "xPlayStrm=1" ) )
775 b_xplaystream = true;
781 answer->i_body_offset = 0;
786 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
788 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
793 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
794 const char *psz_url, const char *psz_mime,
795 const char *psz_user, const char *psz_password )
797 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
799 stream->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
800 if( stream->url == NULL )
805 vlc_mutex_init( &stream->lock );
806 if( psz_mime && *psz_mime )
808 stream->psz_mime = strdup( psz_mime );
812 stream->psz_mime = strdup( vlc_mime_Ext2Mime( psz_url ) );
814 stream->i_header = 0;
815 stream->p_header = NULL;
816 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
817 stream->p_buffer = xmalloc( stream->i_buffer_size );
818 /* We set to 1 to make life simpler
819 * (this way i_body_offset can never be 0) */
820 stream->i_buffer_pos = 1;
821 stream->i_buffer_last_pos = 1;
822 stream->b_has_keyframes = false;
823 stream->i_last_keyframe_seen_pos = 0;
825 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
826 (httpd_callback_sys_t*)stream );
827 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
828 (httpd_callback_sys_t*)stream );
829 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
830 (httpd_callback_sys_t*)stream );
835 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
837 vlc_mutex_lock( &stream->lock );
838 free( stream->p_header );
839 stream->p_header = NULL;
841 stream->i_header = i_data;
844 stream->p_header = xmalloc( i_data );
845 memcpy( stream->p_header, p_data, i_data );
847 vlc_mutex_unlock( &stream->lock );
852 static void httpd_AppendData( httpd_stream_t *stream, uint8_t *p_data, int i_data )
854 int i_pos = stream->i_buffer_pos % stream->i_buffer_size;
855 int i_count = i_data;
860 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
862 /* Ok, we can't go past the end of our buffer */
863 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
865 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
870 stream->i_buffer_pos += i_data;
873 int httpd_StreamSend( httpd_stream_t *stream, const block_t *p_block )
875 if( p_block == NULL || p_block->p_buffer == NULL )
879 vlc_mutex_lock( &stream->lock );
881 /* save this pointer (to be used by new connection) */
882 stream->i_buffer_last_pos = stream->i_buffer_pos;
884 if( p_block->i_flags & BLOCK_FLAG_TYPE_I )
886 stream->b_has_keyframes = true;
887 stream->i_last_keyframe_seen_pos = stream->i_buffer_pos;
890 httpd_AppendData( stream, p_block->p_buffer, p_block->i_buffer );
892 vlc_mutex_unlock( &stream->lock );
896 void httpd_StreamDelete( httpd_stream_t *stream )
898 httpd_UrlDelete( stream->url );
899 vlc_mutex_destroy( &stream->lock );
900 free( stream->psz_mime );
901 free( stream->p_header );
902 free( stream->p_buffer );
906 /*****************************************************************************
908 *****************************************************************************/
909 static void* httpd_HostThread( void * );
910 static httpd_host_t *httpd_HostCreate( vlc_object_t *, const char *,
911 const char *, vlc_tls_creds_t * );
913 /* create a new host */
914 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
916 return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
919 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
921 char *cert = var_InheritString( obj, "http-cert" );
924 msg_Err( obj, "HTTP/TLS certificate not specified!" );
928 char *key = var_InheritString( obj, "http-key" );
929 vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
933 msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
934 cert, (key != NULL) ? key : cert );
942 char *ca = var_InheritString( obj, "http-ca" );
945 if( vlc_tls_ServerAddCA( tls, ca ) )
947 msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
954 char *crl = var_InheritString( obj, "http-crl" );
957 if( vlc_tls_ServerAddCRL( tls, crl ) )
959 msg_Err( obj, "TLS CRL error (%s)", crl );
966 return httpd_HostCreate( obj, "http-host", "https-port", tls );
969 vlc_tls_Delete( tls );
973 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
975 return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
984 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
986 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
989 vlc_tls_creds_t *p_tls )
992 char *hostname = var_InheritString( p_this, hostvar );
993 unsigned port = var_InheritInteger( p_this, portvar );
996 vlc_UrlParse( &url, hostname, 0 );
998 if( url.i_port != 0 )
1000 msg_Err( p_this, "Ignoring port %d (using %d)", url.i_port, port );
1001 msg_Info( p_this, "Specify port %d separately with the "
1002 "%s option instead.", url.i_port, portvar );
1005 /* to be sure to avoid multiple creation */
1006 vlc_mutex_lock( &httpd.mutex );
1008 /* verify if it already exist */
1009 for( int i = 0; i < httpd.i_host; i++ )
1011 host = httpd.host[i];
1013 /* cannot mix TLS and non-TLS hosts */
1014 if( host->port != port
1015 || (host->p_tls != NULL) != (p_tls != NULL) )
1018 /* Increase existing matching host reference count.
1019 * The reference count is written under both the global httpd and the
1020 * host lock. It is read with either or both locks held. The global
1021 * lock is always acquired first. */
1022 vlc_mutex_lock( &host->lock );
1024 vlc_mutex_unlock( &host->lock );
1026 vlc_mutex_unlock( &httpd.mutex );
1027 vlc_UrlClean( &url );
1028 vlc_tls_Delete( p_tls );
1032 /* create the new host */
1033 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1038 vlc_mutex_init( &host->lock );
1039 vlc_cond_init( &host->wait );
1042 host->fds = net_ListenTCP( p_this, url.psz_host, port );
1043 if( host->fds == NULL )
1045 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1048 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1050 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1052 msg_Err( host, "signaling pipe error: %s", vlc_strerror_c(errno) );
1060 host->client = NULL;
1061 host->p_tls = p_tls;
1063 /* create the thread */
1064 if( vlc_clone( &host->thread, httpd_HostThread, host,
1065 VLC_THREAD_PRIORITY_LOW ) )
1067 msg_Err( p_this, "cannot spawn http host thread" );
1071 /* now add it to httpd */
1072 TAB_APPEND( httpd.i_host, httpd.host, host );
1073 vlc_mutex_unlock( &httpd.mutex );
1075 vlc_UrlClean( &url );
1080 vlc_mutex_unlock( &httpd.mutex );
1084 net_ListenClose( host->fds );
1085 vlc_cond_destroy( &host->wait );
1086 vlc_mutex_destroy( &host->lock );
1087 vlc_object_release( host );
1090 vlc_UrlClean( &url );
1091 vlc_tls_Delete( p_tls );
1096 void httpd_HostDelete( httpd_host_t *host )
1099 bool delete = false;
1101 vlc_mutex_lock( &httpd.mutex );
1103 vlc_mutex_lock( &host->lock );
1105 if( host->i_ref == 0 )
1107 vlc_mutex_unlock( &host->lock );
1111 vlc_mutex_unlock( &httpd.mutex );
1112 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1115 TAB_REMOVE( httpd.i_host, httpd.host, host );
1117 vlc_cancel( host->thread );
1118 vlc_join( host->thread, NULL );
1120 msg_Dbg( host, "HTTP host removed" );
1122 for( i = 0; i < host->i_url; i++ )
1124 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1126 for( i = 0; i < host->i_client; i++ )
1128 httpd_client_t *cl = host->client[i];
1129 msg_Warn( host, "client still connected" );
1130 httpd_ClientClean( cl );
1131 TAB_REMOVE( host->i_client, host->client, cl );
1137 vlc_tls_Delete( host->p_tls );
1138 net_ListenClose( host->fds );
1139 vlc_cond_destroy( &host->wait );
1140 vlc_mutex_destroy( &host->lock );
1141 vlc_object_release( host );
1142 vlc_mutex_unlock( &httpd.mutex );
1145 /* register a new url */
1146 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1147 const char *psz_user, const char *psz_password )
1151 assert( psz_url != NULL );
1153 vlc_mutex_lock( &host->lock );
1154 for( int i = 0; i < host->i_url; i++ )
1156 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1159 "cannot add '%s' (url already defined)", psz_url );
1160 vlc_mutex_unlock( &host->lock );
1165 url = xmalloc( sizeof( httpd_url_t ) );
1168 vlc_mutex_init( &url->lock );
1169 url->psz_url = strdup( psz_url );
1170 url->psz_user = strdup( psz_user ? psz_user : "" );
1171 url->psz_password = strdup( psz_password ? psz_password : "" );
1172 for( int i = 0; i < HTTPD_MSG_MAX; i++ )
1174 url->catch[i].cb = NULL;
1175 url->catch[i].p_sys = NULL;
1178 TAB_APPEND( host->i_url, host->url, url );
1179 vlc_cond_signal( &host->wait );
1180 vlc_mutex_unlock( &host->lock );
1185 /* register callback on a url */
1186 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1187 httpd_callback_sys_t *p_sys )
1189 vlc_mutex_lock( &url->lock );
1190 url->catch[i_msg].cb = cb;
1191 url->catch[i_msg].p_sys= p_sys;
1192 vlc_mutex_unlock( &url->lock );
1198 void httpd_UrlDelete( httpd_url_t *url )
1200 httpd_host_t *host = url->host;
1203 vlc_mutex_lock( &host->lock );
1204 TAB_REMOVE( host->i_url, host->url, url );
1206 vlc_mutex_destroy( &url->lock );
1207 free( url->psz_url );
1208 free( url->psz_user );
1209 free( url->psz_password );
1211 for( i = 0; i < host->i_client; i++ )
1213 httpd_client_t *client = host->client[i];
1215 if( client->url == url )
1217 /* TODO complete it */
1218 msg_Warn( host, "force closing connections" );
1219 httpd_ClientClean( client );
1220 TAB_REMOVE( host->i_client, host->client, client );
1226 vlc_mutex_unlock( &host->lock );
1229 static void httpd_MsgInit( httpd_message_t *msg )
1232 msg->i_type = HTTPD_MSG_NONE;
1233 msg->i_proto = HTTPD_PROTO_NONE;
1234 msg->i_version = -1; /* FIXME */
1238 msg->psz_url = NULL;
1239 msg->psz_args = NULL;
1246 msg->i_body_offset = 0;
1251 static void httpd_MsgClean( httpd_message_t *msg )
1255 free( msg->psz_url );
1256 free( msg->psz_args );
1257 for( i = 0; i < msg->i_name; i++ )
1259 free( msg->name[i] );
1260 free( msg->value[i] );
1264 free( msg->p_body );
1265 httpd_MsgInit( msg );
1268 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1272 for( i = 0; i < msg->i_name; i++ )
1274 if( !strcasecmp( msg->name[i], name ))
1276 return msg->value[i];
1282 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1287 va_start( args, psz_value );
1288 if( us_vasprintf( &value, psz_value, args ) == -1 )
1295 name = strdup( name );
1302 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1303 TAB_APPEND( msg->i_value, msg->value, value );
1306 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1308 cl->i_state = HTTPD_CLIENT_RECEIVING;
1309 cl->i_activity_date = now;
1310 cl->i_activity_timeout = INT64_C(10000000);
1311 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1313 cl->p_buffer = xmalloc( cl->i_buffer_size );
1314 cl->i_keyframe_wait_to_pass = -1;
1315 cl->b_stream_mode = false;
1317 httpd_MsgInit( &cl->query );
1318 httpd_MsgInit( &cl->answer );
1321 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1323 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1326 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1328 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1331 static void httpd_ClientClean( httpd_client_t *cl )
1335 if( cl->p_tls != NULL )
1336 vlc_tls_SessionDelete( cl->p_tls );
1337 net_Close( cl->fd );
1341 httpd_MsgClean( &cl->answer );
1342 httpd_MsgClean( &cl->query );
1344 free( cl->p_buffer );
1345 cl->p_buffer = NULL;
1348 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1350 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1352 if( !cl ) return NULL;
1359 httpd_ClientInit( cl, now );
1361 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1367 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1374 val = p_tls ? tls_Recv (p_tls, p, i_len)
1375 : recv (cl->fd, p, i_len, 0);
1376 while (val == -1 && errno == EINTR);
1381 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1388 val = p_tls ? tls_Send( p_tls, p, i_len )
1389 : send (cl->fd, p, i_len, 0);
1390 while (val == -1 && errno == EINTR);
1397 const char name[16];
1403 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1404 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1405 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1406 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1407 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1408 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1409 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1410 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1411 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1412 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1413 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1417 static void httpd_ClientRecv( httpd_client_t *cl )
1421 /* ignore leading whites */
1422 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1423 ( cl->i_buffer == 0 ) )
1427 i_len = httpd_NetRecv( cl, &c, 1 );
1429 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1431 cl->p_buffer[0] = c;
1436 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1438 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1439 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1443 cl->i_buffer += i_len;
1446 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1447 * this is the maximum we can ask at this point. */
1448 if( cl->i_buffer >= 7 )
1450 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1452 cl->query.i_proto = HTTPD_PROTO_HTTP;
1453 cl->query.i_type = HTTPD_MSG_ANSWER;
1455 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1457 cl->query.i_proto = HTTPD_PROTO_RTSP;
1458 cl->query.i_type = HTTPD_MSG_ANSWER;
1462 /* We need the full request line to determine the protocol. */
1463 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1464 cl->query.i_type = HTTPD_MSG_NONE;
1468 else if( cl->query.i_body > 0 )
1470 /* we are reading the body of a request or a channel */
1471 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1472 cl->query.i_body - cl->i_buffer );
1475 cl->i_buffer += i_len;
1477 if( cl->i_buffer >= cl->query.i_body )
1479 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1484 /* we are reading a header -> char by char */
1487 if( cl->i_buffer == cl->i_buffer_size )
1489 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1490 if( newbuf == NULL )
1496 cl->p_buffer = newbuf;
1497 cl->i_buffer_size += 1024;
1500 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1507 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1508 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1510 /* Request line is now complete */
1511 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1514 assert( cl->query.i_type == HTTPD_MSG_NONE );
1516 if( p == NULL ) /* no URI: evil guy */
1518 i_len = 0; /* drop connection */
1523 p++; /* skips extra spaces */
1526 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1527 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1529 i_len = 0; /* not supported currently -> drop */
1534 p++; /* skips extra spaces ever again */
1537 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1538 if( len < 7 ) /* foreign protocol */
1539 i_len = 0; /* I don't understand -> drop */
1541 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1543 cl->query.i_proto = HTTPD_PROTO_HTTP;
1544 cl->query.i_version = atoi( p + 7 );
1547 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1549 cl->query.i_proto = HTTPD_PROTO_RTSP;
1550 cl->query.i_version = atoi( p + 7 );
1553 if( memcmp( p, "HTTP/", 5 ) == 0 )
1555 const uint8_t sorry[] =
1556 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1557 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1558 i_len = 0; /* drop */
1561 if( memcmp( p, "RTSP/", 5 ) == 0 )
1563 const uint8_t sorry[] =
1564 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1565 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1566 i_len = 0; /* drop */
1568 else /* yet another foreign protocol */
1575 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1576 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1580 /* we have finished the header so parse it and set i_body */
1581 cl->p_buffer[cl->i_buffer] = '\0';
1583 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1586 * assume strlen( "HTTP/1.x" ) = 8
1588 cl->query.i_status =
1589 strtol( (char *)&cl->p_buffer[8],
1599 cl->query.i_type = HTTPD_MSG_NONE;
1601 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1603 for( i = 0; msg_type[i].name[0]; i++ )
1605 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1606 strlen( msg_type[i].name ) ) )
1608 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1609 cl->query.i_type = msg_type[i].i_type;
1610 if( cl->query.i_proto != msg_type[i].i_proto )
1613 cl->query.i_proto = HTTPD_PROTO_NONE;
1614 cl->query.i_type = HTTPD_MSG_NONE;
1621 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1623 cl->query.i_proto = HTTPD_PROTO_HTTP;
1625 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1627 cl->query.i_proto = HTTPD_PROTO_RTSP;
1639 p2 = strchr( p, ' ' );
1644 if( !strncasecmp( p, ( cl->query.i_proto
1645 == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1646 { /* Skip hier-part of URL (if present) */
1648 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1649 { /* see RFC3986 §3.2 */
1651 p += strcspn( p, "/?#" );
1655 if( !strncasecmp( p, ( cl->query.i_proto
1656 == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1657 { /* Skip hier-part of URL (if present) */
1659 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1660 { /* see RFC3986 §3.2 */
1662 p += strcspn( p, "/?#" );
1666 cl->query.psz_url = strdup( p );
1667 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1670 cl->query.psz_args = (uint8_t *)strdup( p3 );
1677 p = strchr( p, '\n' );
1681 while( *p == '\n' || *p == '\r' )
1685 while( p && *p != '\0' )
1688 char *eol = p = strchr( p, '\n' );
1691 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1696 if( ( colon = strchr( line, ':' ) ) )
1702 while( *colon == ' ' )
1706 name = strdup( line );
1707 value = strdup( colon );
1709 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1710 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1712 if( !strcasecmp( name, "Content-Length" ) )
1714 cl->query.i_body = atol( value );
1721 while( *p == '\n' || *p == '\r' )
1728 if( cl->query.i_body > 0 )
1730 /* TODO Mhh, handle the case where the client only
1731 * sends a request and closes the connection to
1732 * mark the end of the body (probably only RTSP) */
1733 cl->query.p_body = malloc( cl->query.i_body );
1735 if ( cl->query.p_body == NULL ) {
1736 switch (cl->query.i_proto) {
1737 case HTTPD_PROTO_HTTP: {
1738 const uint8_t sorry[] =
1739 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1740 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1743 case HTTPD_PROTO_RTSP: {
1744 const uint8_t sorry[] =
1745 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1746 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1752 i_len = 0; /* drop */
1758 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1764 /* check if the client is to be set to dead */
1765 #if defined( _WIN32 )
1766 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1768 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1771 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1773 /* connection closed -> end of data */
1774 if( cl->query.i_body > 0 )
1776 cl->query.i_body = cl->i_buffer;
1778 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1782 cl->i_state = HTTPD_CLIENT_DEAD;
1786 /* XXX: for QT I have to disable timeout. Try to find why */
1787 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1788 cl->i_activity_timeout = 0;
1790 #if 0 /* Debugging only */
1791 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1795 fprintf( stderr, "received new request\n" );
1796 fprintf( stderr, " - proto=%s\n",
1797 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1798 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1799 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1800 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1802 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1803 cl->query.psz_status );
1805 else if( cl->query.i_type != HTTPD_MSG_NONE )
1807 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1809 for( i = 0; i < cl->query.i_name; i++ )
1811 fprintf( stderr, " - option name='%s' value='%s'\n",
1812 cl->query.name[i], cl->query.value[i] );
1818 static void httpd_ClientSend( httpd_client_t *cl )
1823 if( cl->i_buffer < 0 )
1825 /* We need to create the header */
1828 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1830 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1831 for( i = 0; i < cl->answer.i_name; i++ )
1833 i_size += strlen( cl->answer.name[i] ) + 2 +
1834 strlen( cl->answer.value[i] ) + 2;
1837 if( cl->i_buffer_size < i_size )
1839 cl->i_buffer_size = i_size;
1840 free( cl->p_buffer );
1841 cl->p_buffer = xmalloc( i_size );
1843 p = (char *)cl->p_buffer;
1845 p += sprintf( p, "%s.%u %d %s\r\n",
1846 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1847 cl->answer.i_version,
1848 cl->answer.i_status, psz_status );
1849 for( i = 0; i < cl->answer.i_name; i++ )
1851 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1852 cl->answer.value[i] );
1854 p += sprintf( p, "\r\n" );
1857 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1859 /*fprintf( stderr, "sending answer\n" );
1860 fprintf( stderr, "%s", cl->p_buffer );*/
1863 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1864 cl->i_buffer_size - cl->i_buffer );
1867 cl->i_buffer += i_len;
1869 if( cl->i_buffer >= cl->i_buffer_size )
1871 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 )
1873 /* catch more body data */
1874 int i_msg = cl->query.i_type;
1875 int64_t i_offset = cl->answer.i_body_offset;
1877 httpd_MsgClean( &cl->answer );
1878 cl->answer.i_body_offset = i_offset;
1880 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1881 &cl->answer, &cl->query );
1884 if( cl->answer.i_body > 0 )
1886 /* send the body data */
1887 free( cl->p_buffer );
1888 cl->p_buffer = cl->answer.p_body;
1889 cl->i_buffer_size = cl->answer.i_body;
1892 cl->answer.i_body = 0;
1893 cl->answer.p_body = NULL;
1898 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1904 #if defined( _WIN32 )
1905 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1907 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1911 cl->i_state = HTTPD_CLIENT_DEAD;
1916 static void httpd_ClientTlsHandshake( httpd_client_t *cl )
1918 switch( vlc_tls_SessionHandshake( cl->p_tls, NULL, NULL ) ) {
1919 case -1: cl->i_state = HTTPD_CLIENT_DEAD; break;
1920 case 0: cl->i_state = HTTPD_CLIENT_RECEIVING; break;
1921 case 1: cl->i_state = HTTPD_CLIENT_TLS_HS_IN; break;
1922 case 2: cl->i_state = HTTPD_CLIENT_TLS_HS_OUT; break;
1926 static void httpdLoop(httpd_host_t *host)
1928 struct pollfd ufd[host->nfd + host->i_client];
1930 for( nfd = 0; nfd < host->nfd; nfd++ )
1932 ufd[nfd].fd = host->fds[nfd];
1933 ufd[nfd].events = POLLIN;
1934 ufd[nfd].revents = 0;
1937 /* add all socket that should be read/write and close dead connection */
1938 while( host->i_url <= 0 )
1940 mutex_cleanup_push( &host->lock );
1941 vlc_cond_wait( &host->wait, &host->lock );
1945 mtime_t now = mdate();
1946 bool b_low_delay = false;
1948 int canc = vlc_savecancel();
1949 for(int i_client = 0; i_client < host->i_client; i_client++ )
1952 httpd_client_t *cl = host->client[i_client];
1953 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1954 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1955 ( cl->i_activity_timeout > 0 &&
1956 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
1958 httpd_ClientClean( cl );
1959 TAB_REMOVE( host->i_client, host->client, cl );
1965 struct pollfd *pufd = ufd + nfd;
1966 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1969 pufd->events = pufd->revents = 0;
1971 switch (cl->i_state) {
1972 case HTTPD_CLIENT_RECEIVING:
1973 case HTTPD_CLIENT_TLS_HS_IN:
1974 pufd->events = POLLIN;
1977 case HTTPD_CLIENT_SENDING:
1978 case HTTPD_CLIENT_TLS_HS_OUT:
1979 pufd->events = POLLOUT;
1982 case HTTPD_CLIENT_RECEIVE_DONE: {
1983 httpd_message_t *answer = &cl->answer;
1984 httpd_message_t *query = &cl->query;
1986 httpd_MsgInit( answer );
1988 /* Handle what we received */
1989 switch (query->i_type) {
1990 case HTTPD_MSG_ANSWER:
1992 cl->i_state = HTTPD_CLIENT_DEAD;
1995 case HTTPD_MSG_OPTIONS:
1996 answer->i_type = HTTPD_MSG_ANSWER;
1997 answer->i_proto = query->i_proto;
1998 answer->i_status = 200;
2000 answer->p_body = NULL;
2002 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2003 httpd_MsgAdd( answer, "Content-Length", "0" );
2005 switch( query->i_proto )
2007 case HTTPD_PROTO_HTTP:
2008 answer->i_version = 1;
2009 httpd_MsgAdd(answer, "Allow", "GET,HEAD,POST,OPTIONS");
2012 case HTTPD_PROTO_RTSP:
2013 answer->i_version = 0;
2015 const char *p = httpd_MsgGet( query, "Cseq" );
2017 httpd_MsgAdd( answer, "Cseq", "%s", p );
2018 p = httpd_MsgGet( query, "Timestamp" );
2020 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2022 p = httpd_MsgGet( query, "Require" );
2024 answer->i_status = 551;
2025 httpd_MsgAdd( query, "Unsupported", "%s", p );
2028 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2029 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2033 cl->i_buffer = -1; /* Force the creation of the answer in
2034 * httpd_ClientSend */
2035 cl->i_state = HTTPD_CLIENT_SENDING;
2038 case HTTPD_MSG_NONE:
2039 if( query->i_proto == HTTPD_PROTO_NONE ) {
2041 cl->i_state = HTTPD_CLIENT_DEAD;
2045 answer->i_proto = query->i_proto ;
2046 answer->i_type = HTTPD_MSG_ANSWER;
2047 answer->i_version= 0;
2048 answer->i_status = 501;
2051 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2052 answer->p_body = (uint8_t *)p;
2053 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2055 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2056 cl->i_state = HTTPD_CLIENT_SENDING;
2061 int i_msg = query->i_type;
2062 bool b_auth_failed = false;
2064 /* Search the url and trigger callbacks */
2065 for(int i = 0; i < host->i_url; i++ ) {
2066 httpd_url_t *url = host->url[i];
2068 if (strcmp(url->psz_url, query->psz_url))
2070 if (!url->catch[i_msg].cb)
2073 if (answer && (*url->psz_user || *url->psz_password)) {
2074 /* create the headers */
2075 const char *b64 = httpd_MsgGet(query, "Authorization"); /* BASIC id */
2076 char *user = NULL, *pass = NULL;
2078 if (b64 && !strncasecmp(b64, "BASIC", 5)) {
2083 user = vlc_b64_decode( b64 );
2085 pass = strchr (user, ':');
2091 if (!user || strcmp (user, url->psz_user) ||
2092 !pass || strcmp (pass, url->psz_password)) {
2093 httpd_MsgAdd( answer, "WWW-Authenticate",
2094 "Basic realm=\"VLC stream\"" );
2095 b_auth_failed = true; /* We fail for all url */
2103 if (url->catch[i_msg].cb(url->catch[i_msg].p_sys, cl, answer, query))
2106 if( answer->i_proto == HTTPD_PROTO_NONE )
2107 cl->i_buffer = cl->i_buffer_size; /* Raw answer from a CGI */
2111 /* only one url can answer */
2113 if( cl->url == NULL )
2118 answer->i_proto = query->i_proto;
2119 answer->i_type = HTTPD_MSG_ANSWER;
2120 answer->i_version= 0;
2123 answer->i_status = 401;
2125 answer->i_status = 404; /* no url registered */
2128 answer->i_body = httpd_HtmlError (&p, answer->i_status,
2130 answer->p_body = (uint8_t *)p;
2132 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2133 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2134 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2137 cl->i_state = HTTPD_CLIENT_SENDING;
2143 case HTTPD_CLIENT_SEND_DONE:
2144 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2146 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2147 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2148 bool b_connection = false;
2149 bool b_keepalive = false;
2150 bool b_query = false;
2153 if( psz_connection )
2155 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2156 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2161 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2164 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2165 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2166 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2167 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2168 !b_query && !b_connection ) )
2170 httpd_MsgClean( &cl->query );
2171 httpd_MsgInit( &cl->query );
2174 cl->i_buffer_size = 1000;
2175 free( cl->p_buffer );
2176 cl->p_buffer = xmalloc( cl->i_buffer_size );
2177 cl->i_state = HTTPD_CLIENT_RECEIVING;
2181 cl->i_state = HTTPD_CLIENT_DEAD;
2183 httpd_MsgClean( &cl->answer );
2187 i_offset = cl->answer.i_body_offset;
2188 httpd_MsgClean( &cl->answer );
2190 cl->answer.i_body_offset = i_offset;
2191 free( cl->p_buffer );
2192 cl->p_buffer = NULL;
2194 cl->i_buffer_size = 0;
2196 cl->i_state = HTTPD_CLIENT_WAITING;
2200 case HTTPD_CLIENT_WAITING:
2201 i_offset = cl->answer.i_body_offset;
2202 int i_msg = cl->query.i_type;
2204 httpd_MsgInit( &cl->answer );
2205 cl->answer.i_body_offset = i_offset;
2207 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2208 &cl->answer, &cl->query );
2209 if( cl->answer.i_type != HTTPD_MSG_NONE )
2211 /* we have new data, so re-enter send mode */
2213 cl->p_buffer = cl->answer.p_body;
2214 cl->i_buffer_size = cl->answer.i_body;
2215 cl->answer.p_body = NULL;
2216 cl->answer.i_body = 0;
2217 cl->i_state = HTTPD_CLIENT_SENDING;
2221 if (pufd->events != 0)
2226 vlc_mutex_unlock( &host->lock );
2227 vlc_restorecancel( canc );
2229 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2230 int ret = poll( ufd, nfd, b_low_delay ? 20 : -1 );
2232 canc = vlc_savecancel();
2233 vlc_mutex_lock( &host->lock );
2236 if (errno != EINTR) {
2237 /* Kernel on low memory or a bug: pace */
2238 msg_Err( host, "polling error: %s", vlc_strerror_c(errno) );
2242 vlc_restorecancel( canc );
2246 /* Handle client sockets */
2250 for( int i_client = 0; i_client < host->i_client; i_client++ )
2252 httpd_client_t *cl = host->client[i_client];
2253 const struct pollfd *pufd = &ufd[nfd];
2255 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2257 if( cl->fd != pufd->fd )
2258 continue; // we were not waiting for this client
2260 if( pufd->revents == 0 )
2261 continue; // no event received
2263 cl->i_activity_date = now;
2265 switch (cl->i_state) {
2266 case HTTPD_CLIENT_RECEIVING: httpd_ClientRecv( cl ); break;
2267 case HTTPD_CLIENT_SENDING: httpd_ClientSend( cl ); break;
2268 case HTTPD_CLIENT_TLS_HS_IN:
2269 case HTTPD_CLIENT_TLS_HS_OUT: httpd_ClientTlsHandshake( cl ); break;
2273 /* Handle server sockets (accept new connections) */
2274 for( nfd = 0; nfd < host->nfd; nfd++ )
2277 int fd = ufd[nfd].fd;
2279 assert (fd == host->fds[nfd]);
2281 if( ufd[nfd].revents == 0 )
2285 fd = vlc_accept (fd, NULL, NULL, true);
2288 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2289 &(int){ 1 }, sizeof(int));
2293 if( host->p_tls != NULL )
2294 p_tls = vlc_tls_SessionCreate( host->p_tls, fd, NULL );
2298 cl = httpd_ClientNew( fd, p_tls, now );
2300 TAB_APPEND( host->i_client, host->client, cl );
2303 vlc_restorecancel(canc);
2306 static void* httpd_HostThread( void *data )
2308 httpd_host_t *host = data;
2310 vlc_mutex_lock( &host->lock );
2311 while( host->i_ref > 0 )
2313 vlc_mutex_unlock( &host->lock );