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>
41 #include "../libvlc.h"
54 #if defined( UNDER_CE )
56 #elif defined( WIN32 )
57 # include <winsock2.h>
59 # include <sys/socket.h>
63 /* We need HUGE buffer otherwise TCP throughput is very limited */
64 #define HTTPD_CL_BUFSIZE 1000000
66 #define HTTPD_CL_BUFSIZE 10000
69 static void httpd_ClientClean( httpd_client_t *cl );
71 /* each host run in his own thread */
79 /* address/port and socket for listening at connections */
88 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
89 * This will slow down the url research but make my live easier
90 * All url will have their cb trigger, but only the first one can answer
96 httpd_client_t **client;
99 vlc_tls_creds_t *p_tls;
116 httpd_callback_sys_t *p_sys;
117 } catch[HTTPD_MSG_MAX];
123 HTTPD_CLIENT_RECEIVING,
124 HTTPD_CLIENT_RECEIVE_DONE,
126 HTTPD_CLIENT_SENDING,
127 HTTPD_CLIENT_SEND_DONE,
129 HTTPD_CLIENT_WAITING,
133 HTTPD_CLIENT_TLS_HS_IN,
134 HTTPD_CLIENT_TLS_HS_OUT
140 HTTPD_CLIENT_FILE, /* default */
141 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
144 struct httpd_client_t
155 mtime_t i_activity_date;
156 mtime_t i_activity_timeout;
158 /* buffer for reading header */
164 httpd_message_t query; /* client -> httpd */
165 httpd_message_t answer; /* httpd -> client */
172 /*****************************************************************************
174 *****************************************************************************/
177 const char psz_ext[8];
178 const char *psz_mime;
181 { ".htm", "text/html" },
182 { ".html", "text/html" },
183 { ".txt", "text/plain" },
184 { ".xml", "text/xml" },
185 { ".dtd", "text/dtd" },
187 { ".css", "text/css" },
190 { ".gif", "image/gif" },
191 { ".jpe", "image/jpeg" },
192 { ".jpg", "image/jpeg" },
193 { ".jpeg", "image/jpeg" },
194 { ".png", "image/png" },
195 /* same as modules/mux/mpjpeg.c here: */
196 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
199 { ".avi", "video/avi" },
200 { ".asf", "video/x-ms-asf" },
201 { ".m1a", "audio/mpeg" },
202 { ".m2a", "audio/mpeg" },
203 { ".m1v", "video/mpeg" },
204 { ".m2v", "video/mpeg" },
205 { ".mp2", "audio/mpeg" },
206 { ".mp3", "audio/mpeg" },
207 { ".mpa", "audio/mpeg" },
208 { ".mpg", "video/mpeg" },
209 { ".mpeg", "video/mpeg" },
210 { ".mpe", "video/mpeg" },
211 { ".mov", "video/quicktime" },
212 { ".moov", "video/quicktime" },
213 { ".oga", "audio/ogg" },
214 { ".ogg", "application/ogg" },
215 { ".ogm", "application/ogg" },
216 { ".ogv", "video/ogg" },
217 { ".ogx", "application/ogg" },
218 { ".spx", "audio/ogg" },
219 { ".wav", "audio/wav" },
220 { ".wma", "audio/x-ms-wma" },
221 { ".wmv", "video/x-ms-wmv" },
228 static const char *httpd_MimeFromUrl( const char *psz_url )
233 psz_ext = strrchr( psz_url, '.' );
238 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
240 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
242 return http_mime[i].psz_mime;
246 return "application/octet-stream";
253 const char psz_reason[36];
256 static const http_status_info http_reason[] =
258 /*{ 100, "Continue" },
259 { 101, "Switching Protocols" },*/
261 /*{ 201, "Created" },
263 { 203, "Non-authoritative information" },
264 { 204, "No content" },
265 { 205, "Reset content" },
266 { 206, "Partial content" },
267 { 250, "Low on storage space" },
268 { 300, "Multiple choices" },*/
269 { 301, "Moved permanently" },
270 /*{ 302, "Moved temporarily" },
271 { 303, "See other" },
272 { 304, "Not modified" },
273 { 305, "Use proxy" },
274 { 307, "Temporary redirect" },
275 { 400, "Bad request" },*/
276 { 401, "Unauthorized" },
277 /*{ 402, "Payment Required" },*/
278 { 403, "Forbidden" },
279 { 404, "Not found" },
280 { 405, "Method not allowed" },
281 /*{ 406, "Not acceptable" },
282 { 407, "Proxy authentication required" },
283 { 408, "Request time-out" },
286 { 411, "Length required" },
287 { 412, "Precondition failed" },
288 { 413, "Request entity too large" },
289 { 414, "Request-URI too large" },
290 { 415, "Unsupported media Type" },
291 { 416, "Requested range not satisfiable" },
292 { 417, "Expectation failed" },
293 { 451, "Parameter not understood" },
294 { 452, "Conference not found" },
295 { 453, "Not enough bandwidth" },*/
296 { 454, "Session not found" },
297 { 455, "Method not valid in this State" },
298 { 456, "Header field not valid for resource" },
299 { 457, "Invalid range" },
300 /*{ 458, "Read-only parameter" },*/
301 { 459, "Aggregate operation not allowed" },
302 { 460, "Non-aggregate operation not allowed" },
303 { 461, "Unsupported transport" },
304 /*{ 462, "Destination unreachable" },*/
305 { 500, "Internal server error" },
306 { 501, "Not implemented" },
307 /*{ 502, "Bad gateway" },*/
308 { 503, "Service unavailable" },
309 /*{ 504, "Gateway time-out" },*/
310 { 505, "Protocol version not supported" },
311 { 551, "Option not supported" },
315 static const char psz_fallback_reason[5][16] =
316 { "Continue", "OK", "Found", "Client error", "Server error" };
318 static const char *httpd_ReasonFromCode( unsigned i_code )
320 const http_status_info *p;
322 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
324 for (p = http_reason; i_code > p->i_code; p++);
326 if( p->i_code == i_code )
327 return p->psz_reason;
329 return psz_fallback_reason[(i_code / 100) - 1];
333 static size_t httpd_HtmlError (char **body, int code, const char *url)
335 const char *errname = httpd_ReasonFromCode (code);
336 assert (errname != NULL);
338 int res = asprintf (body,
339 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
340 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
341 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
342 "<html lang=\"en\">\n"
344 "<title>%s</title>\n"
347 "<h1>%d %s%s%s%s</h1>\n"
349 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
351 "</html>\n", errname, code, errname,
352 (url ? " (" : ""), (url ? url : ""), (url ? ")" : ""));
364 /*****************************************************************************
365 * High Level Functions: httpd_file_t
366 *****************************************************************************/
374 httpd_file_callback_t pf_fill;
375 httpd_file_sys_t *p_sys;
380 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
381 httpd_message_t *answer, const httpd_message_t *query )
383 httpd_file_t *file = (httpd_file_t*)p_sys;
384 uint8_t **pp_body, *p_body;
385 const char *psz_connection;
386 int *pi_body, i_body;
388 if( answer == NULL || query == NULL )
392 answer->i_proto = HTTPD_PROTO_HTTP;
393 answer->i_version= 1;
394 answer->i_type = HTTPD_MSG_ANSWER;
396 answer->i_status = 200;
398 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
399 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
401 if( query->i_type != HTTPD_MSG_HEAD )
403 pp_body = &answer->p_body;
404 pi_body = &answer->i_body;
408 /* The file still needs to be executed. */
415 if( query->i_type == HTTPD_MSG_POST )
417 /* msg_Warn not supported */
420 uint8_t *psz_args = query->psz_args;
421 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
423 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
428 /* We respect client request */
429 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
430 if( psz_connection != NULL )
432 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
435 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
440 httpd_file_t *httpd_FileNew( httpd_host_t *host,
441 const char *psz_url, const char *psz_mime,
442 const char *psz_user, const char *psz_password,
443 httpd_file_callback_t pf_fill,
444 httpd_file_sys_t *p_sys )
446 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
448 file->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
449 if( file->url == NULL )
455 file->psz_url = strdup( psz_url );
456 if( psz_mime && *psz_mime )
458 file->psz_mime = strdup( psz_mime );
462 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
465 file->pf_fill = pf_fill;
468 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
469 (httpd_callback_sys_t*)file );
470 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
471 (httpd_callback_sys_t*)file );
472 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
473 (httpd_callback_sys_t*)file );
478 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
480 httpd_file_sys_t *p_sys = file->p_sys;
482 httpd_UrlDelete( file->url );
484 free( file->psz_url );
485 free( file->psz_mime );
492 /*****************************************************************************
493 * High Level Functions: httpd_handler_t (for CGIs)
494 *****************************************************************************/
495 struct httpd_handler_t
499 httpd_handler_callback_t pf_fill;
500 httpd_handler_sys_t *p_sys;
505 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
506 httpd_message_t *answer, const httpd_message_t *query )
508 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
509 char psz_remote_addr[NI_MAXNUMERICHOST];
511 if( answer == NULL || query == NULL )
515 answer->i_proto = HTTPD_PROTO_NONE;
516 answer->i_type = HTTPD_MSG_ANSWER;
518 /* We do it ourselves, thanks */
519 answer->i_status = 0;
521 if( httpd_ClientIP( cl, psz_remote_addr, NULL ) == NULL )
522 *psz_remote_addr = '\0';
524 uint8_t *psz_args = query->psz_args;
525 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
526 query->i_type, query->p_body, query->i_body,
527 psz_remote_addr, NULL,
528 &answer->p_body, &answer->i_body );
530 if( query->i_type == HTTPD_MSG_HEAD )
532 char *p = (char *)answer->p_body;
534 /* Looks for end of header (i.e. one empty line) */
535 while ( (p = strchr( p, '\r' )) != NULL )
537 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
538 && p[3] && p[3] == '\n' )
547 answer->i_body = strlen((char*)answer->p_body) + 1;
548 answer->p_body = xrealloc( answer->p_body, answer->i_body );
552 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
554 int i_status, i_headers;
555 char *psz_headers, *psz_new;
556 const char *psz_status;
558 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
561 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
562 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
563 if( *psz_headers == '\n' ) psz_headers++;
564 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
569 psz_headers = (char *)answer->p_body;
570 i_headers = answer->i_body;
573 psz_status = httpd_ReasonFromCode( i_status );
574 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
575 + strlen(psz_status) + i_headers - 1;
576 psz_new = (char *)xmalloc( answer->i_body + 1);
577 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
578 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
579 free( answer->p_body );
580 answer->p_body = (uint8_t *)psz_new;
586 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
587 const char *psz_user,
588 const char *psz_password,
589 httpd_handler_callback_t pf_fill,
590 httpd_handler_sys_t *p_sys )
592 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
594 handler->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
595 if( handler->url == NULL )
601 handler->pf_fill = pf_fill;
602 handler->p_sys = p_sys;
604 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
605 (httpd_callback_sys_t*)handler );
606 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
607 (httpd_callback_sys_t*)handler );
608 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
609 (httpd_callback_sys_t*)handler );
614 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
616 httpd_handler_sys_t *p_sys = handler->p_sys;
617 httpd_UrlDelete( handler->url );
622 /*****************************************************************************
623 * High Level Functions: httpd_redirect_t
624 *****************************************************************************/
625 struct httpd_redirect_t
631 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
632 httpd_client_t *cl, httpd_message_t *answer,
633 const httpd_message_t *query )
635 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
639 if( answer == NULL || query == NULL )
643 answer->i_proto = HTTPD_PROTO_HTTP;
644 answer->i_version= 1;
645 answer->i_type = HTTPD_MSG_ANSWER;
646 answer->i_status = 301;
648 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
649 answer->p_body = (unsigned char *)p_body;
651 /* XXX check if it's ok or we need to set an absolute url */
652 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
654 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
659 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
660 const char *psz_url_src )
662 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
664 rdir->url = httpd_UrlNew( host, psz_url_src, NULL, NULL );
665 if( rdir->url == NULL )
670 rdir->psz_dst = strdup( psz_url_dst );
672 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
673 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
674 (httpd_callback_sys_t*)rdir );
675 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
676 (httpd_callback_sys_t*)rdir );
677 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
678 (httpd_callback_sys_t*)rdir );
679 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
680 (httpd_callback_sys_t*)rdir );
684 void httpd_RedirectDelete( httpd_redirect_t *rdir )
686 httpd_UrlDelete( rdir->url );
687 free( rdir->psz_dst );
691 /*****************************************************************************
692 * High Level Funtions: httpd_stream_t
693 *****************************************************************************/
694 struct httpd_stream_t
701 /* Header to send as first packet */
705 /* circular buffer */
706 int i_buffer_size; /* buffer size, can't be reallocated smaller */
707 uint8_t *p_buffer; /* buffer */
708 int64_t i_buffer_pos; /* absolute position from begining */
709 int64_t i_buffer_last_pos; /* a new connection will start with that */
712 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
713 httpd_client_t *cl, httpd_message_t *answer,
714 const httpd_message_t *query )
716 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
718 if( answer == NULL || query == NULL || cl == NULL )
723 if( answer->i_body_offset > 0 )
729 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
730 answer->i_body_offset );
733 if( answer->i_body_offset >= stream->i_buffer_pos )
735 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
736 return VLC_EGENERIC; /* wait, no data available */
738 if( answer->i_body_offset + stream->i_buffer_size <
739 stream->i_buffer_pos )
741 /* this client isn't fast enough */
743 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
744 answer->i_body_offset, stream->i_buffer_last_pos );
746 answer->i_body_offset = stream->i_buffer_last_pos;
749 i_pos = answer->i_body_offset % stream->i_buffer_size;
750 i_write = stream->i_buffer_pos - answer->i_body_offset;
751 if( i_write > HTTPD_CL_BUFSIZE )
753 i_write = HTTPD_CL_BUFSIZE;
755 else if( i_write <= 0 )
757 return VLC_EGENERIC; /* wait, no data available */
760 /* Don't go past the end of the circular buffer */
761 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
763 /* using HTTPD_MSG_ANSWER -> data available */
764 answer->i_proto = HTTPD_PROTO_HTTP;
765 answer->i_version= 0;
766 answer->i_type = HTTPD_MSG_ANSWER;
768 answer->i_body = i_write;
769 answer->p_body = xmalloc( i_write );
770 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
772 answer->i_body_offset += i_write;
778 answer->i_proto = HTTPD_PROTO_HTTP;
779 answer->i_version= 0;
780 answer->i_type = HTTPD_MSG_ANSWER;
782 answer->i_status = 200;
784 if( query->i_type != HTTPD_MSG_HEAD )
786 cl->b_stream_mode = true;
787 vlc_mutex_lock( &stream->lock );
788 /* Send the header */
789 if( stream->i_header > 0 )
791 answer->i_body = stream->i_header;
792 answer->p_body = xmalloc( stream->i_header );
793 memcpy( answer->p_body, stream->p_header, stream->i_header );
795 answer->i_body_offset = stream->i_buffer_last_pos;
796 vlc_mutex_unlock( &stream->lock );
800 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
801 answer->i_body_offset = 0;
804 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
806 bool b_xplaystream = false;
809 httpd_MsgAdd( answer, "Content-type", "%s",
810 "application/octet-stream" );
811 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
812 httpd_MsgAdd( answer, "Pragma", "no-cache" );
813 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
814 vlc_mrand48()&0x7fff );
815 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
817 /* Check if there is a xPlayStrm=1 */
818 for( i = 0; i < query->i_name; i++ )
820 if( !strcasecmp( query->name[i], "Pragma" ) &&
821 strstr( query->value[i], "xPlayStrm=1" ) )
823 b_xplaystream = true;
829 answer->i_body_offset = 0;
834 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
836 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
841 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
842 const char *psz_url, const char *psz_mime,
843 const char *psz_user, const char *psz_password )
845 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
847 stream->url = httpd_UrlNew( host, psz_url, psz_user, psz_password );
848 if( stream->url == NULL )
853 vlc_mutex_init( &stream->lock );
854 if( psz_mime && *psz_mime )
856 stream->psz_mime = strdup( psz_mime );
860 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
862 stream->i_header = 0;
863 stream->p_header = NULL;
864 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
865 stream->p_buffer = xmalloc( stream->i_buffer_size );
866 /* We set to 1 to make life simpler
867 * (this way i_body_offset can never be 0) */
868 stream->i_buffer_pos = 1;
869 stream->i_buffer_last_pos = 1;
871 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
872 (httpd_callback_sys_t*)stream );
873 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
874 (httpd_callback_sys_t*)stream );
875 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
876 (httpd_callback_sys_t*)stream );
881 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
883 vlc_mutex_lock( &stream->lock );
884 free( stream->p_header );
885 stream->p_header = NULL;
887 stream->i_header = i_data;
890 stream->p_header = xmalloc( i_data );
891 memcpy( stream->p_header, p_data, i_data );
893 vlc_mutex_unlock( &stream->lock );
898 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
903 if( i_data < 0 || p_data == NULL )
907 vlc_mutex_lock( &stream->lock );
909 /* save this pointer (to be used by new connection) */
910 stream->i_buffer_last_pos = stream->i_buffer_pos;
912 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
918 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
920 /* Ok, we can't go past the end of our buffer */
921 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
923 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
928 stream->i_buffer_pos += i_data;
930 vlc_mutex_unlock( &stream->lock );
934 void httpd_StreamDelete( httpd_stream_t *stream )
936 httpd_UrlDelete( stream->url );
937 vlc_mutex_destroy( &stream->lock );
938 free( stream->psz_mime );
939 free( stream->p_header );
940 free( stream->p_buffer );
944 /*****************************************************************************
946 *****************************************************************************/
947 static void* httpd_HostThread( void * );
948 static httpd_host_t *httpd_HostCreate( vlc_object_t *, const char *,
949 const char *, vlc_tls_creds_t * );
951 /* create a new host */
952 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
954 return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
957 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
959 char *cert = var_InheritString( obj, "http-cert" );
962 msg_Err( obj, "HTTP/TLS certificate not specified!" );
966 char *key = var_InheritString( obj, "http-key" );
967 vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
971 msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
972 cert, (key != NULL) ? key : cert );
980 char *ca = var_InheritString( obj, "http-ca" );
983 if( vlc_tls_ServerAddCA( tls, ca ) )
985 msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
992 char *crl = var_InheritString( obj, "http-crl" );
995 if( vlc_tls_ServerAddCRL( tls, crl ) )
997 msg_Err( obj, "TLS CRL error (%s)", crl );
1004 return httpd_HostCreate( obj, "http-host", "https-port", tls );
1007 vlc_tls_ServerDelete( tls );
1011 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
1013 return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
1020 httpd_host_t **host;
1022 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
1024 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
1025 const char *hostvar,
1026 const char *portvar,
1027 vlc_tls_creds_t *p_tls )
1030 char *hostname = var_InheritString( p_this, hostvar );
1031 unsigned port = var_InheritInteger( p_this, portvar );
1034 vlc_UrlParse( &url, hostname, 0 );
1036 if( url.i_port != 0 )
1038 msg_Err( p_this, "Ignoring port %d (using %d)", url.i_port, port );
1039 msg_Info( p_this, "Specify port %d separately with the "
1040 "%s option instead.", url.i_port, portvar );
1043 /* to be sure to avoid multiple creation */
1044 vlc_mutex_lock( &httpd.mutex );
1046 /* verify if it already exist */
1047 for( int i = 0; i < httpd.i_host; i++ )
1049 host = httpd.host[i];
1051 /* cannot mix TLS and non-TLS hosts */
1052 if( host->port != port
1053 || (host->p_tls != NULL) != (p_tls != NULL) )
1056 /* Increase existing matching host reference count.
1057 * The reference count is written under both the global httpd and the
1058 * host lock. It is read with either or both locks held. The global
1059 * lock is always acquired first. */
1060 vlc_mutex_lock( &host->lock );
1062 vlc_mutex_unlock( &host->lock );
1064 vlc_mutex_unlock( &httpd.mutex );
1065 vlc_UrlClean( &url );
1067 vlc_tls_ServerDelete( p_tls );
1071 /* create the new host */
1072 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1077 vlc_mutex_init( &host->lock );
1078 vlc_cond_init( &host->wait );
1081 host->fds = net_ListenTCP( p_this, url.psz_host, port );
1082 if( host->fds == NULL )
1084 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1087 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1089 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1091 msg_Err( host, "signaling pipe error: %m" );
1099 host->client = NULL;
1100 host->p_tls = p_tls;
1102 /* create the thread */
1103 if( vlc_clone( &host->thread, httpd_HostThread, host,
1104 VLC_THREAD_PRIORITY_LOW ) )
1106 msg_Err( p_this, "cannot spawn http host thread" );
1110 /* now add it to httpd */
1111 TAB_APPEND( httpd.i_host, httpd.host, host );
1112 vlc_mutex_unlock( &httpd.mutex );
1114 vlc_UrlClean( &url );
1119 vlc_mutex_unlock( &httpd.mutex );
1123 net_ListenClose( host->fds );
1124 vlc_cond_destroy( &host->wait );
1125 vlc_mutex_destroy( &host->lock );
1126 vlc_object_release( host );
1129 vlc_UrlClean( &url );
1132 vlc_tls_ServerDelete( p_tls );
1138 void httpd_HostDelete( httpd_host_t *host )
1141 bool delete = false;
1143 vlc_mutex_lock( &httpd.mutex );
1145 vlc_mutex_lock( &host->lock );
1147 if( host->i_ref == 0 )
1149 vlc_cond_signal( &host->wait );
1152 vlc_mutex_unlock( &host->lock );
1156 vlc_mutex_unlock( &httpd.mutex );
1157 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1160 TAB_REMOVE( httpd.i_host, httpd.host, host );
1162 vlc_object_kill( host );
1163 vlc_join( host->thread, NULL );
1165 msg_Dbg( host, "HTTP host removed" );
1167 for( i = 0; i < host->i_url; i++ )
1169 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1171 for( i = 0; i < host->i_client; i++ )
1173 httpd_client_t *cl = host->client[i];
1174 msg_Warn( host, "client still connected" );
1175 httpd_ClientClean( cl );
1176 TAB_REMOVE( host->i_client, host->client, cl );
1182 if( host->p_tls != NULL)
1183 vlc_tls_ServerDelete( host->p_tls );
1185 net_ListenClose( host->fds );
1186 vlc_cond_destroy( &host->wait );
1187 vlc_mutex_destroy( &host->lock );
1188 vlc_object_release( host );
1189 vlc_mutex_unlock( &httpd.mutex );
1192 /* register a new url */
1193 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1194 const char *psz_user, const char *psz_password )
1198 assert( psz_url != NULL );
1200 vlc_mutex_lock( &host->lock );
1201 for( int i = 0; i < host->i_url; i++ )
1203 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1206 "cannot add '%s' (url already defined)", psz_url );
1207 vlc_mutex_unlock( &host->lock );
1212 url = xmalloc( sizeof( httpd_url_t ) );
1215 vlc_mutex_init( &url->lock );
1216 url->psz_url = strdup( psz_url );
1217 url->psz_user = strdup( psz_user ? psz_user : "" );
1218 url->psz_password = strdup( psz_password ? psz_password : "" );
1219 for( int i = 0; i < HTTPD_MSG_MAX; i++ )
1221 url->catch[i].cb = NULL;
1222 url->catch[i].p_sys = NULL;
1225 TAB_APPEND( host->i_url, host->url, url );
1226 vlc_cond_signal( &host->wait );
1227 vlc_mutex_unlock( &host->lock );
1232 /* register callback on a url */
1233 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1234 httpd_callback_sys_t *p_sys )
1236 vlc_mutex_lock( &url->lock );
1237 url->catch[i_msg].cb = cb;
1238 url->catch[i_msg].p_sys= p_sys;
1239 vlc_mutex_unlock( &url->lock );
1245 void httpd_UrlDelete( httpd_url_t *url )
1247 httpd_host_t *host = url->host;
1250 vlc_mutex_lock( &host->lock );
1251 TAB_REMOVE( host->i_url, host->url, url );
1253 vlc_mutex_destroy( &url->lock );
1254 free( url->psz_url );
1255 free( url->psz_user );
1256 free( url->psz_password );
1258 for( i = 0; i < host->i_client; i++ )
1260 httpd_client_t *client = host->client[i];
1262 if( client->url == url )
1264 /* TODO complete it */
1265 msg_Warn( host, "force closing connections" );
1266 httpd_ClientClean( client );
1267 TAB_REMOVE( host->i_client, host->client, client );
1273 vlc_mutex_unlock( &host->lock );
1276 static void httpd_MsgInit( httpd_message_t *msg )
1279 msg->i_type = HTTPD_MSG_NONE;
1280 msg->i_proto = HTTPD_PROTO_NONE;
1281 msg->i_version = -1; /* FIXME */
1285 msg->psz_url = NULL;
1286 msg->psz_args = NULL;
1293 msg->i_body_offset = 0;
1298 static void httpd_MsgClean( httpd_message_t *msg )
1302 free( msg->psz_url );
1303 free( msg->psz_args );
1304 for( i = 0; i < msg->i_name; i++ )
1306 free( msg->name[i] );
1307 free( msg->value[i] );
1311 free( msg->p_body );
1312 httpd_MsgInit( msg );
1315 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1319 for( i = 0; i < msg->i_name; i++ )
1321 if( !strcasecmp( msg->name[i], name ))
1323 return msg->value[i];
1329 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1334 va_start( args, psz_value );
1335 if( us_vasprintf( &value, psz_value, args ) == -1 )
1342 name = strdup( name );
1349 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1350 TAB_APPEND( msg->i_value, msg->value, value );
1353 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1355 cl->i_state = HTTPD_CLIENT_RECEIVING;
1356 cl->i_activity_date = now;
1357 cl->i_activity_timeout = INT64_C(10000000);
1358 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1360 cl->p_buffer = xmalloc( cl->i_buffer_size );
1361 cl->b_stream_mode = false;
1363 httpd_MsgInit( &cl->query );
1364 httpd_MsgInit( &cl->answer );
1367 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1369 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1372 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1374 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1377 static void httpd_ClientClean( httpd_client_t *cl )
1381 if( cl->p_tls != NULL )
1382 vlc_tls_ServerSessionDelete( cl->p_tls );
1383 net_Close( cl->fd );
1387 httpd_MsgClean( &cl->answer );
1388 httpd_MsgClean( &cl->query );
1390 free( cl->p_buffer );
1391 cl->p_buffer = NULL;
1394 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1396 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1398 if( !cl ) return NULL;
1405 httpd_ClientInit( cl, now );
1411 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1418 val = p_tls ? tls_Recv (p_tls, p, i_len)
1419 : recv (cl->fd, p, i_len, 0);
1420 while (val == -1 && errno == EINTR);
1425 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1432 val = p_tls ? tls_Send( p_tls, p, i_len )
1433 : send (cl->fd, p, i_len, 0);
1434 while (val == -1 && errno == EINTR);
1441 const char name[16];
1447 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1448 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1449 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1450 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1451 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1452 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1453 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1454 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1455 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1456 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1457 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1461 static void httpd_ClientRecv( httpd_client_t *cl )
1465 /* ignore leading whites */
1466 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1467 ( cl->i_buffer == 0 ) )
1471 i_len = httpd_NetRecv( cl, &c, 1 );
1473 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1475 cl->p_buffer[0] = c;
1480 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1482 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1483 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1487 cl->i_buffer += i_len;
1490 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1491 * this is the maximum we can ask at this point. */
1492 if( cl->i_buffer >= 7 )
1494 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1496 cl->query.i_proto = HTTPD_PROTO_HTTP;
1497 cl->query.i_type = HTTPD_MSG_ANSWER;
1499 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1501 cl->query.i_proto = HTTPD_PROTO_RTSP;
1502 cl->query.i_type = HTTPD_MSG_ANSWER;
1506 /* We need the full request line to determine the protocol. */
1507 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1508 cl->query.i_type = HTTPD_MSG_NONE;
1512 else if( cl->query.i_body > 0 )
1514 /* we are reading the body of a request or a channel */
1515 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1516 cl->query.i_body - cl->i_buffer );
1519 cl->i_buffer += i_len;
1521 if( cl->i_buffer >= cl->query.i_body )
1523 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1528 /* we are reading a header -> char by char */
1531 if( cl->i_buffer == cl->i_buffer_size )
1533 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1534 if( newbuf == NULL )
1540 cl->p_buffer = newbuf;
1541 cl->i_buffer_size += 1024;
1544 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1551 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1552 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1554 /* Request line is now complete */
1555 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1558 assert( cl->query.i_type == HTTPD_MSG_NONE );
1560 if( p == NULL ) /* no URI: evil guy */
1562 i_len = 0; /* drop connection */
1567 p++; /* skips extra spaces */
1570 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1571 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1573 i_len = 0; /* not supported currently -> drop */
1578 p++; /* skips extra spaces ever again */
1581 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1582 if( len < 7 ) /* foreign protocol */
1583 i_len = 0; /* I don't understand -> drop */
1585 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1587 cl->query.i_proto = HTTPD_PROTO_HTTP;
1588 cl->query.i_version = atoi( p + 7 );
1591 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1593 cl->query.i_proto = HTTPD_PROTO_RTSP;
1594 cl->query.i_version = atoi( p + 7 );
1597 if( memcmp( p, "HTTP/", 5 ) == 0 )
1599 const uint8_t sorry[] =
1600 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1601 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1602 i_len = 0; /* drop */
1605 if( memcmp( p, "RTSP/", 5 ) == 0 )
1607 const uint8_t sorry[] =
1608 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1609 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1610 i_len = 0; /* drop */
1612 else /* yet another foreign protocol */
1619 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1620 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1624 /* we have finished the header so parse it and set i_body */
1625 cl->p_buffer[cl->i_buffer] = '\0';
1627 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1630 * assume strlen( "HTTP/1.x" ) = 8
1632 cl->query.i_status =
1633 strtol( (char *)&cl->p_buffer[8],
1643 cl->query.i_type = HTTPD_MSG_NONE;
1645 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1647 for( i = 0; msg_type[i].name[0]; i++ )
1649 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1650 strlen( msg_type[i].name ) ) )
1652 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1653 cl->query.i_type = msg_type[i].i_type;
1654 if( cl->query.i_proto != msg_type[i].i_proto )
1657 cl->query.i_proto = HTTPD_PROTO_NONE;
1658 cl->query.i_type = HTTPD_MSG_NONE;
1665 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1667 cl->query.i_proto = HTTPD_PROTO_HTTP;
1669 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1671 cl->query.i_proto = HTTPD_PROTO_RTSP;
1683 p2 = strchr( p, ' ' );
1688 if( !strncasecmp( p, ( cl->query.i_proto
1689 == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1690 { /* Skip hier-part of URL (if present) */
1692 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1693 { /* see RFC3986 §3.2 */
1695 p += strcspn( p, "/?#" );
1699 if( !strncasecmp( p, ( cl->query.i_proto
1700 == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1701 { /* Skip hier-part of URL (if present) */
1703 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1704 { /* see RFC3986 §3.2 */
1706 p += strcspn( p, "/?#" );
1710 cl->query.psz_url = strdup( p );
1711 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1714 cl->query.psz_args = (uint8_t *)strdup( p3 );
1721 p = strchr( p, '\n' );
1725 while( *p == '\n' || *p == '\r' )
1729 while( p && *p != '\0' )
1732 char *eol = p = strchr( p, '\n' );
1735 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1740 if( ( colon = strchr( line, ':' ) ) )
1746 while( *colon == ' ' )
1750 name = strdup( line );
1751 value = strdup( colon );
1753 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1754 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1756 if( !strcasecmp( name, "Content-Length" ) )
1758 cl->query.i_body = atol( value );
1765 while( *p == '\n' || *p == '\r' )
1772 if( cl->query.i_body > 0 )
1774 /* TODO Mhh, handle the case where the client only
1775 * sends a request and closes the connection to
1776 * mark the end of the body (probably only RTSP) */
1777 cl->query.p_body = malloc( cl->query.i_body );
1779 if ( cl->query.p_body == NULL )
1781 switch (cl->query.i_proto)
1783 case HTTPD_PROTO_HTTP:
1785 const uint8_t sorry[] =
1786 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1787 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1790 case HTTPD_PROTO_RTSP:
1792 const uint8_t sorry[] =
1793 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1794 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1800 i_len = 0; /* drop */
1806 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1812 /* check if the client is to be set to dead */
1813 #if defined( WIN32 ) || defined( UNDER_CE )
1814 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1816 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1819 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1821 /* connection closed -> end of data */
1822 if( cl->query.i_body > 0 )
1824 cl->query.i_body = cl->i_buffer;
1826 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1830 cl->i_state = HTTPD_CLIENT_DEAD;
1834 /* XXX: for QT I have to disable timeout. Try to find why */
1835 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1836 cl->i_activity_timeout = 0;
1838 #if 0 /* Debugging only */
1839 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1843 fprintf( stderr, "received new request\n" );
1844 fprintf( stderr, " - proto=%s\n",
1845 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1846 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1847 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1848 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1850 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1851 cl->query.psz_status );
1853 else if( cl->query.i_type != HTTPD_MSG_NONE )
1855 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1857 for( i = 0; i < cl->query.i_name; i++ )
1859 fprintf( stderr, " - option name='%s' value='%s'\n",
1860 cl->query.name[i], cl->query.value[i] );
1866 static void httpd_ClientSend( httpd_client_t *cl )
1871 if( cl->i_buffer < 0 )
1873 /* We need to create the header */
1876 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1878 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1879 for( i = 0; i < cl->answer.i_name; i++ )
1881 i_size += strlen( cl->answer.name[i] ) + 2 +
1882 strlen( cl->answer.value[i] ) + 2;
1885 if( cl->i_buffer_size < i_size )
1887 cl->i_buffer_size = i_size;
1888 free( cl->p_buffer );
1889 cl->p_buffer = xmalloc( i_size );
1891 p = (char *)cl->p_buffer;
1893 p += sprintf( p, "%s.%u %d %s\r\n",
1894 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1895 cl->answer.i_version,
1896 cl->answer.i_status, psz_status );
1897 for( i = 0; i < cl->answer.i_name; i++ )
1899 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1900 cl->answer.value[i] );
1902 p += sprintf( p, "\r\n" );
1905 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1907 /*fprintf( stderr, "sending answer\n" );
1908 fprintf( stderr, "%s", cl->p_buffer );*/
1911 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1912 cl->i_buffer_size - cl->i_buffer );
1915 cl->i_buffer += i_len;
1917 if( cl->i_buffer >= cl->i_buffer_size )
1919 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 )
1921 /* catch more body data */
1922 int i_msg = cl->query.i_type;
1923 int64_t i_offset = cl->answer.i_body_offset;
1925 httpd_MsgClean( &cl->answer );
1926 cl->answer.i_body_offset = i_offset;
1928 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1929 &cl->answer, &cl->query );
1932 if( cl->answer.i_body > 0 )
1934 /* send the body data */
1935 free( cl->p_buffer );
1936 cl->p_buffer = cl->answer.p_body;
1937 cl->i_buffer_size = cl->answer.i_body;
1940 cl->answer.i_body = 0;
1941 cl->answer.p_body = NULL;
1946 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1952 #if defined( WIN32 ) || defined( UNDER_CE )
1953 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1955 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1959 cl->i_state = HTTPD_CLIENT_DEAD;
1964 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1966 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1969 cl->i_state = HTTPD_CLIENT_RECEIVING;
1973 cl->i_state = HTTPD_CLIENT_DEAD;
1978 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1982 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1984 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1987 cl->i_state = HTTPD_CLIENT_RECEIVING;
1991 cl->i_state = HTTPD_CLIENT_DEAD;
1996 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2001 static void* httpd_HostThread( void *data )
2003 httpd_host_t *host = data;
2004 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2008 struct pollfd ufd[host->nfd + host->i_client + 1];
2010 for( nfd = 0; nfd < host->nfd; nfd++ )
2012 ufd[nfd].fd = host->fds[nfd];
2013 ufd[nfd].events = POLLIN;
2014 ufd[nfd].revents = 0;
2017 /* add all socket that should be read/write and close dead connection */
2018 vlc_mutex_lock( &host->lock );
2019 while( host->i_url <= 0 && host->i_ref > 0 )
2020 vlc_cond_wait( &host->wait, &host->lock );
2022 mtime_t now = mdate();
2023 bool b_low_delay = false;
2025 for(int i_client = 0; i_client < host->i_client; i_client++ )
2027 httpd_client_t *cl = host->client[i_client];
2028 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2029 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2030 ( cl->i_activity_timeout > 0 &&
2031 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2033 httpd_ClientClean( cl );
2034 TAB_REMOVE( host->i_client, host->client, cl );
2040 struct pollfd *pufd = ufd + nfd;
2041 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2044 pufd->events = pufd->revents = 0;
2046 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2047 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2049 pufd->events = POLLIN;
2051 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2052 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2054 pufd->events = POLLOUT;
2056 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2058 httpd_message_t *answer = &cl->answer;
2059 httpd_message_t *query = &cl->query;
2060 int i_msg = query->i_type;
2062 httpd_MsgInit( answer );
2064 /* Handle what we received */
2065 if( i_msg == HTTPD_MSG_ANSWER )
2068 cl->i_state = HTTPD_CLIENT_DEAD;
2070 else if( i_msg == HTTPD_MSG_OPTIONS )
2073 answer->i_type = HTTPD_MSG_ANSWER;
2074 answer->i_proto = query->i_proto;
2075 answer->i_status = 200;
2077 answer->p_body = NULL;
2079 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2080 httpd_MsgAdd( answer, "Content-Length", "0" );
2082 switch( query->i_proto )
2084 case HTTPD_PROTO_HTTP:
2085 answer->i_version = 1;
2086 httpd_MsgAdd( answer, "Allow",
2087 "GET,HEAD,POST,OPTIONS" );
2090 case HTTPD_PROTO_RTSP:
2093 answer->i_version = 0;
2095 p = httpd_MsgGet( query, "Cseq" );
2097 httpd_MsgAdd( answer, "Cseq", "%s", p );
2098 p = httpd_MsgGet( query, "Timestamp" );
2100 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2102 p = httpd_MsgGet( query, "Require" );
2105 answer->i_status = 551;
2106 httpd_MsgAdd( query, "Unsupported", "%s", p );
2109 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2110 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2115 cl->i_buffer = -1; /* Force the creation of the answer in
2116 * httpd_ClientSend */
2117 cl->i_state = HTTPD_CLIENT_SENDING;
2119 else if( i_msg == HTTPD_MSG_NONE )
2121 if( query->i_proto == HTTPD_PROTO_NONE )
2124 cl->i_state = HTTPD_CLIENT_DEAD;
2131 answer->i_proto = query->i_proto ;
2132 answer->i_type = HTTPD_MSG_ANSWER;
2133 answer->i_version= 0;
2134 answer->i_status = 501;
2136 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2137 answer->p_body = (uint8_t *)p;
2138 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2140 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2141 cl->i_state = HTTPD_CLIENT_SENDING;
2146 bool b_auth_failed = false;
2148 /* Search the url and trigger callbacks */
2149 for(int i = 0; i < host->i_url; i++ )
2151 httpd_url_t *url = host->url[i];
2153 if( !strcmp( url->psz_url, query->psz_url ) )
2155 if( url->catch[i_msg].cb )
2157 if( answer && ( *url->psz_user || *url->psz_password ) )
2159 /* create the headers */
2160 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2161 char *user = NULL, *pass = NULL;
2164 && !strncasecmp( b64, "BASIC", 5 ) )
2167 while( *b64 == ' ' )
2170 user = vlc_b64_decode( b64 );
2173 pass = strchr (user, ':');
2179 if ((user == NULL) || (pass == NULL)
2180 || strcmp (user, url->psz_user)
2181 || strcmp (pass, url->psz_password))
2183 httpd_MsgAdd( answer,
2185 "Basic realm=\"VLC stream\"" );
2186 /* We fail for all url */
2187 b_auth_failed = true;
2195 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2197 if( answer->i_proto == HTTPD_PROTO_NONE )
2199 /* Raw answer from a CGI */
2200 cl->i_buffer = cl->i_buffer_size;
2205 /* only one url can answer */
2207 if( cl->url == NULL )
2220 answer->i_proto = query->i_proto;
2221 answer->i_type = HTTPD_MSG_ANSWER;
2222 answer->i_version= 0;
2226 answer->i_status = 401;
2230 /* no url registered */
2231 answer->i_status = 404;
2234 answer->i_body = httpd_HtmlError (&p,
2237 answer->p_body = (uint8_t *)p;
2239 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2240 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2241 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2244 cl->i_state = HTTPD_CLIENT_SENDING;
2247 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2249 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2251 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2252 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2253 bool b_connection = false;
2254 bool b_keepalive = false;
2255 bool b_query = false;
2258 if( psz_connection )
2260 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2261 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2266 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2269 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2270 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2271 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2272 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2273 !b_query && !b_connection ) )
2275 httpd_MsgClean( &cl->query );
2276 httpd_MsgInit( &cl->query );
2279 cl->i_buffer_size = 1000;
2280 free( cl->p_buffer );
2281 cl->p_buffer = xmalloc( cl->i_buffer_size );
2282 cl->i_state = HTTPD_CLIENT_RECEIVING;
2286 cl->i_state = HTTPD_CLIENT_DEAD;
2288 httpd_MsgClean( &cl->answer );
2292 int64_t i_offset = cl->answer.i_body_offset;
2293 httpd_MsgClean( &cl->answer );
2295 cl->answer.i_body_offset = i_offset;
2296 free( cl->p_buffer );
2297 cl->p_buffer = NULL;
2299 cl->i_buffer_size = 0;
2301 cl->i_state = HTTPD_CLIENT_WAITING;
2304 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2306 int64_t i_offset = cl->answer.i_body_offset;
2307 int i_msg = cl->query.i_type;
2309 httpd_MsgInit( &cl->answer );
2310 cl->answer.i_body_offset = i_offset;
2312 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2313 &cl->answer, &cl->query );
2314 if( cl->answer.i_type != HTTPD_MSG_NONE )
2316 /* we have new data, so re-enter send mode */
2318 cl->p_buffer = cl->answer.p_body;
2319 cl->i_buffer_size = cl->answer.i_body;
2320 cl->answer.p_body = NULL;
2321 cl->answer.i_body = 0;
2322 cl->i_state = HTTPD_CLIENT_SENDING;
2326 if (pufd->events != 0)
2331 vlc_mutex_unlock( &host->lock );
2334 ufd[nfd].events = POLLIN;
2335 ufd[nfd].revents = 0;
2338 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2339 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2344 /* Kernel on low memory or a bug: pace */
2345 msg_Err( host, "polling error: %m" );
2352 if( ufd[nfd - 1].revents )
2355 /* Handle client sockets */
2356 vlc_mutex_lock( &host->lock );
2359 for( int i_client = 0; i_client < host->i_client; i_client++ )
2361 httpd_client_t *cl = host->client[i_client];
2362 const struct pollfd *pufd = &ufd[nfd];
2364 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2366 if( cl->fd != pufd->fd )
2367 continue; // we were not waiting for this client
2369 if( pufd->revents == 0 )
2370 continue; // no event received
2372 cl->i_activity_date = now;
2374 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2376 httpd_ClientRecv( cl );
2378 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2380 httpd_ClientSend( cl );
2382 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2384 httpd_ClientTlsHsIn( cl );
2386 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2388 httpd_ClientTlsHsOut( cl );
2391 vlc_mutex_unlock( &host->lock );
2393 /* Handle server sockets (accept new connections) */
2394 for( nfd = 0; nfd < host->nfd; nfd++ )
2398 int fd = ufd[nfd].fd;
2400 assert (fd == host->fds[nfd]);
2402 if( ufd[nfd].revents == 0 )
2406 fd = vlc_accept (fd, NULL, NULL, true);
2409 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2410 &(int){ 1 }, sizeof(int));
2414 if( host->p_tls != NULL )
2416 p_tls = vlc_tls_ServerSessionCreate( host->p_tls, fd );
2417 switch( vlc_tls_ServerSessionHandshake( p_tls ) )
2420 msg_Err( host, "Rejecting TLS connection" );
2421 /* p_tls is destroyed implicitly */
2427 case 1: /* missing input - most likely */
2428 i_state = HTTPD_CLIENT_TLS_HS_IN;
2431 case 2: /* missing output */
2432 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2439 cl = httpd_ClientNew( fd, p_tls, now );
2440 vlc_mutex_lock( &host->lock );
2441 TAB_APPEND( host->i_client, host->client, cl );
2442 vlc_mutex_unlock( &host->lock );
2444 cl->i_state = i_state; // override state for TLS