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_mutex_unlock( &host->lock );
1153 vlc_mutex_unlock( &httpd.mutex );
1154 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1157 TAB_REMOVE( httpd.i_host, httpd.host, host );
1159 vlc_cancel( host->thread );
1160 vlc_join( host->thread, NULL );
1162 msg_Dbg( host, "HTTP host removed" );
1164 for( i = 0; i < host->i_url; i++ )
1166 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1168 for( i = 0; i < host->i_client; i++ )
1170 httpd_client_t *cl = host->client[i];
1171 msg_Warn( host, "client still connected" );
1172 httpd_ClientClean( cl );
1173 TAB_REMOVE( host->i_client, host->client, cl );
1179 if( host->p_tls != NULL)
1180 vlc_tls_ServerDelete( host->p_tls );
1182 net_ListenClose( host->fds );
1183 vlc_cond_destroy( &host->wait );
1184 vlc_mutex_destroy( &host->lock );
1185 vlc_object_release( host );
1186 vlc_mutex_unlock( &httpd.mutex );
1189 /* register a new url */
1190 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1191 const char *psz_user, const char *psz_password )
1195 assert( psz_url != NULL );
1197 vlc_mutex_lock( &host->lock );
1198 for( int i = 0; i < host->i_url; i++ )
1200 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1203 "cannot add '%s' (url already defined)", psz_url );
1204 vlc_mutex_unlock( &host->lock );
1209 url = xmalloc( sizeof( httpd_url_t ) );
1212 vlc_mutex_init( &url->lock );
1213 url->psz_url = strdup( psz_url );
1214 url->psz_user = strdup( psz_user ? psz_user : "" );
1215 url->psz_password = strdup( psz_password ? psz_password : "" );
1216 for( int i = 0; i < HTTPD_MSG_MAX; i++ )
1218 url->catch[i].cb = NULL;
1219 url->catch[i].p_sys = NULL;
1222 TAB_APPEND( host->i_url, host->url, url );
1223 vlc_cond_signal( &host->wait );
1224 vlc_mutex_unlock( &host->lock );
1229 /* register callback on a url */
1230 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1231 httpd_callback_sys_t *p_sys )
1233 vlc_mutex_lock( &url->lock );
1234 url->catch[i_msg].cb = cb;
1235 url->catch[i_msg].p_sys= p_sys;
1236 vlc_mutex_unlock( &url->lock );
1242 void httpd_UrlDelete( httpd_url_t *url )
1244 httpd_host_t *host = url->host;
1247 vlc_mutex_lock( &host->lock );
1248 TAB_REMOVE( host->i_url, host->url, url );
1250 vlc_mutex_destroy( &url->lock );
1251 free( url->psz_url );
1252 free( url->psz_user );
1253 free( url->psz_password );
1255 for( i = 0; i < host->i_client; i++ )
1257 httpd_client_t *client = host->client[i];
1259 if( client->url == url )
1261 /* TODO complete it */
1262 msg_Warn( host, "force closing connections" );
1263 httpd_ClientClean( client );
1264 TAB_REMOVE( host->i_client, host->client, client );
1270 vlc_mutex_unlock( &host->lock );
1273 static void httpd_MsgInit( httpd_message_t *msg )
1276 msg->i_type = HTTPD_MSG_NONE;
1277 msg->i_proto = HTTPD_PROTO_NONE;
1278 msg->i_version = -1; /* FIXME */
1282 msg->psz_url = NULL;
1283 msg->psz_args = NULL;
1290 msg->i_body_offset = 0;
1295 static void httpd_MsgClean( httpd_message_t *msg )
1299 free( msg->psz_url );
1300 free( msg->psz_args );
1301 for( i = 0; i < msg->i_name; i++ )
1303 free( msg->name[i] );
1304 free( msg->value[i] );
1308 free( msg->p_body );
1309 httpd_MsgInit( msg );
1312 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1316 for( i = 0; i < msg->i_name; i++ )
1318 if( !strcasecmp( msg->name[i], name ))
1320 return msg->value[i];
1326 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1331 va_start( args, psz_value );
1332 if( us_vasprintf( &value, psz_value, args ) == -1 )
1339 name = strdup( name );
1346 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1347 TAB_APPEND( msg->i_value, msg->value, value );
1350 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1352 cl->i_state = HTTPD_CLIENT_RECEIVING;
1353 cl->i_activity_date = now;
1354 cl->i_activity_timeout = INT64_C(10000000);
1355 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1357 cl->p_buffer = xmalloc( cl->i_buffer_size );
1358 cl->b_stream_mode = false;
1360 httpd_MsgInit( &cl->query );
1361 httpd_MsgInit( &cl->answer );
1364 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1366 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1369 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1371 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1374 static void httpd_ClientClean( httpd_client_t *cl )
1378 if( cl->p_tls != NULL )
1379 vlc_tls_ServerSessionDelete( cl->p_tls );
1380 net_Close( cl->fd );
1384 httpd_MsgClean( &cl->answer );
1385 httpd_MsgClean( &cl->query );
1387 free( cl->p_buffer );
1388 cl->p_buffer = NULL;
1391 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1393 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1395 if( !cl ) return NULL;
1402 httpd_ClientInit( cl, now );
1408 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1415 val = p_tls ? tls_Recv (p_tls, p, i_len)
1416 : recv (cl->fd, p, i_len, 0);
1417 while (val == -1 && errno == EINTR);
1422 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1429 val = p_tls ? tls_Send( p_tls, p, i_len )
1430 : send (cl->fd, p, i_len, 0);
1431 while (val == -1 && errno == EINTR);
1438 const char name[16];
1444 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1445 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1446 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1447 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1448 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1449 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1450 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1451 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1452 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1453 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1454 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1458 static void httpd_ClientRecv( httpd_client_t *cl )
1462 /* ignore leading whites */
1463 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1464 ( cl->i_buffer == 0 ) )
1468 i_len = httpd_NetRecv( cl, &c, 1 );
1470 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1472 cl->p_buffer[0] = c;
1477 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1479 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1480 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1484 cl->i_buffer += i_len;
1487 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1488 * this is the maximum we can ask at this point. */
1489 if( cl->i_buffer >= 7 )
1491 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1493 cl->query.i_proto = HTTPD_PROTO_HTTP;
1494 cl->query.i_type = HTTPD_MSG_ANSWER;
1496 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1498 cl->query.i_proto = HTTPD_PROTO_RTSP;
1499 cl->query.i_type = HTTPD_MSG_ANSWER;
1503 /* We need the full request line to determine the protocol. */
1504 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1505 cl->query.i_type = HTTPD_MSG_NONE;
1509 else if( cl->query.i_body > 0 )
1511 /* we are reading the body of a request or a channel */
1512 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1513 cl->query.i_body - cl->i_buffer );
1516 cl->i_buffer += i_len;
1518 if( cl->i_buffer >= cl->query.i_body )
1520 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1525 /* we are reading a header -> char by char */
1528 if( cl->i_buffer == cl->i_buffer_size )
1530 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1531 if( newbuf == NULL )
1537 cl->p_buffer = newbuf;
1538 cl->i_buffer_size += 1024;
1541 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1548 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1549 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1551 /* Request line is now complete */
1552 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1555 assert( cl->query.i_type == HTTPD_MSG_NONE );
1557 if( p == NULL ) /* no URI: evil guy */
1559 i_len = 0; /* drop connection */
1564 p++; /* skips extra spaces */
1567 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1568 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1570 i_len = 0; /* not supported currently -> drop */
1575 p++; /* skips extra spaces ever again */
1578 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1579 if( len < 7 ) /* foreign protocol */
1580 i_len = 0; /* I don't understand -> drop */
1582 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1584 cl->query.i_proto = HTTPD_PROTO_HTTP;
1585 cl->query.i_version = atoi( p + 7 );
1588 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1590 cl->query.i_proto = HTTPD_PROTO_RTSP;
1591 cl->query.i_version = atoi( p + 7 );
1594 if( memcmp( p, "HTTP/", 5 ) == 0 )
1596 const uint8_t sorry[] =
1597 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1598 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1599 i_len = 0; /* drop */
1602 if( memcmp( p, "RTSP/", 5 ) == 0 )
1604 const uint8_t sorry[] =
1605 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1606 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1607 i_len = 0; /* drop */
1609 else /* yet another foreign protocol */
1616 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1617 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1621 /* we have finished the header so parse it and set i_body */
1622 cl->p_buffer[cl->i_buffer] = '\0';
1624 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1627 * assume strlen( "HTTP/1.x" ) = 8
1629 cl->query.i_status =
1630 strtol( (char *)&cl->p_buffer[8],
1640 cl->query.i_type = HTTPD_MSG_NONE;
1642 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1644 for( i = 0; msg_type[i].name[0]; i++ )
1646 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1647 strlen( msg_type[i].name ) ) )
1649 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1650 cl->query.i_type = msg_type[i].i_type;
1651 if( cl->query.i_proto != msg_type[i].i_proto )
1654 cl->query.i_proto = HTTPD_PROTO_NONE;
1655 cl->query.i_type = HTTPD_MSG_NONE;
1662 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1664 cl->query.i_proto = HTTPD_PROTO_HTTP;
1666 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1668 cl->query.i_proto = HTTPD_PROTO_RTSP;
1680 p2 = strchr( p, ' ' );
1685 if( !strncasecmp( p, ( cl->query.i_proto
1686 == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1687 { /* Skip hier-part of URL (if present) */
1689 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1690 { /* see RFC3986 §3.2 */
1692 p += strcspn( p, "/?#" );
1696 if( !strncasecmp( p, ( cl->query.i_proto
1697 == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1698 { /* Skip hier-part of URL (if present) */
1700 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1701 { /* see RFC3986 §3.2 */
1703 p += strcspn( p, "/?#" );
1707 cl->query.psz_url = strdup( p );
1708 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1711 cl->query.psz_args = (uint8_t *)strdup( p3 );
1718 p = strchr( p, '\n' );
1722 while( *p == '\n' || *p == '\r' )
1726 while( p && *p != '\0' )
1729 char *eol = p = strchr( p, '\n' );
1732 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1737 if( ( colon = strchr( line, ':' ) ) )
1743 while( *colon == ' ' )
1747 name = strdup( line );
1748 value = strdup( colon );
1750 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1751 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1753 if( !strcasecmp( name, "Content-Length" ) )
1755 cl->query.i_body = atol( value );
1762 while( *p == '\n' || *p == '\r' )
1769 if( cl->query.i_body > 0 )
1771 /* TODO Mhh, handle the case where the client only
1772 * sends a request and closes the connection to
1773 * mark the end of the body (probably only RTSP) */
1774 cl->query.p_body = malloc( cl->query.i_body );
1776 if ( cl->query.p_body == NULL )
1778 switch (cl->query.i_proto)
1780 case HTTPD_PROTO_HTTP:
1782 const uint8_t sorry[] =
1783 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1784 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1787 case HTTPD_PROTO_RTSP:
1789 const uint8_t sorry[] =
1790 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1791 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1797 i_len = 0; /* drop */
1803 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1809 /* check if the client is to be set to dead */
1810 #if defined( WIN32 ) || defined( UNDER_CE )
1811 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1813 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1816 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1818 /* connection closed -> end of data */
1819 if( cl->query.i_body > 0 )
1821 cl->query.i_body = cl->i_buffer;
1823 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1827 cl->i_state = HTTPD_CLIENT_DEAD;
1831 /* XXX: for QT I have to disable timeout. Try to find why */
1832 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1833 cl->i_activity_timeout = 0;
1835 #if 0 /* Debugging only */
1836 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1840 fprintf( stderr, "received new request\n" );
1841 fprintf( stderr, " - proto=%s\n",
1842 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1843 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1844 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1845 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1847 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1848 cl->query.psz_status );
1850 else if( cl->query.i_type != HTTPD_MSG_NONE )
1852 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1854 for( i = 0; i < cl->query.i_name; i++ )
1856 fprintf( stderr, " - option name='%s' value='%s'\n",
1857 cl->query.name[i], cl->query.value[i] );
1863 static void httpd_ClientSend( httpd_client_t *cl )
1868 if( cl->i_buffer < 0 )
1870 /* We need to create the header */
1873 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1875 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1876 for( i = 0; i < cl->answer.i_name; i++ )
1878 i_size += strlen( cl->answer.name[i] ) + 2 +
1879 strlen( cl->answer.value[i] ) + 2;
1882 if( cl->i_buffer_size < i_size )
1884 cl->i_buffer_size = i_size;
1885 free( cl->p_buffer );
1886 cl->p_buffer = xmalloc( i_size );
1888 p = (char *)cl->p_buffer;
1890 p += sprintf( p, "%s.%u %d %s\r\n",
1891 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1892 cl->answer.i_version,
1893 cl->answer.i_status, psz_status );
1894 for( i = 0; i < cl->answer.i_name; i++ )
1896 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1897 cl->answer.value[i] );
1899 p += sprintf( p, "\r\n" );
1902 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1904 /*fprintf( stderr, "sending answer\n" );
1905 fprintf( stderr, "%s", cl->p_buffer );*/
1908 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1909 cl->i_buffer_size - cl->i_buffer );
1912 cl->i_buffer += i_len;
1914 if( cl->i_buffer >= cl->i_buffer_size )
1916 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 )
1918 /* catch more body data */
1919 int i_msg = cl->query.i_type;
1920 int64_t i_offset = cl->answer.i_body_offset;
1922 httpd_MsgClean( &cl->answer );
1923 cl->answer.i_body_offset = i_offset;
1925 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1926 &cl->answer, &cl->query );
1929 if( cl->answer.i_body > 0 )
1931 /* send the body data */
1932 free( cl->p_buffer );
1933 cl->p_buffer = cl->answer.p_body;
1934 cl->i_buffer_size = cl->answer.i_body;
1937 cl->answer.i_body = 0;
1938 cl->answer.p_body = NULL;
1943 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1949 #if defined( WIN32 ) || defined( UNDER_CE )
1950 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1952 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1956 cl->i_state = HTTPD_CLIENT_DEAD;
1961 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1963 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1966 cl->i_state = HTTPD_CLIENT_RECEIVING;
1970 cl->i_state = HTTPD_CLIENT_DEAD;
1975 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1979 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1981 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1984 cl->i_state = HTTPD_CLIENT_RECEIVING;
1988 cl->i_state = HTTPD_CLIENT_DEAD;
1993 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
1998 static void* httpd_HostThread( void *data )
2000 httpd_host_t *host = data;
2001 int canc = vlc_savecancel();
2003 vlc_mutex_lock( &host->lock );
2004 while( host->i_ref > 0 )
2006 struct pollfd ufd[host->nfd + host->i_client];
2008 for( nfd = 0; nfd < host->nfd; nfd++ )
2010 ufd[nfd].fd = host->fds[nfd];
2011 ufd[nfd].events = POLLIN;
2012 ufd[nfd].revents = 0;
2015 /* add all socket that should be read/write and close dead connection */
2016 while( host->i_url <= 0 )
2018 mutex_cleanup_push( &host->lock );
2019 vlc_restorecancel( canc );
2020 vlc_cond_wait( &host->wait, &host->lock );
2021 canc = vlc_savecancel();
2025 mtime_t now = mdate();
2026 bool b_low_delay = false;
2028 for(int i_client = 0; i_client < host->i_client; i_client++ )
2030 httpd_client_t *cl = host->client[i_client];
2031 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2032 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2033 ( cl->i_activity_timeout > 0 &&
2034 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2036 httpd_ClientClean( cl );
2037 TAB_REMOVE( host->i_client, host->client, cl );
2043 struct pollfd *pufd = ufd + nfd;
2044 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2047 pufd->events = pufd->revents = 0;
2049 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2050 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2052 pufd->events = POLLIN;
2054 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2055 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2057 pufd->events = POLLOUT;
2059 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2061 httpd_message_t *answer = &cl->answer;
2062 httpd_message_t *query = &cl->query;
2063 int i_msg = query->i_type;
2065 httpd_MsgInit( answer );
2067 /* Handle what we received */
2068 if( i_msg == HTTPD_MSG_ANSWER )
2071 cl->i_state = HTTPD_CLIENT_DEAD;
2073 else if( i_msg == HTTPD_MSG_OPTIONS )
2076 answer->i_type = HTTPD_MSG_ANSWER;
2077 answer->i_proto = query->i_proto;
2078 answer->i_status = 200;
2080 answer->p_body = NULL;
2082 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2083 httpd_MsgAdd( answer, "Content-Length", "0" );
2085 switch( query->i_proto )
2087 case HTTPD_PROTO_HTTP:
2088 answer->i_version = 1;
2089 httpd_MsgAdd( answer, "Allow",
2090 "GET,HEAD,POST,OPTIONS" );
2093 case HTTPD_PROTO_RTSP:
2096 answer->i_version = 0;
2098 p = httpd_MsgGet( query, "Cseq" );
2100 httpd_MsgAdd( answer, "Cseq", "%s", p );
2101 p = httpd_MsgGet( query, "Timestamp" );
2103 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2105 p = httpd_MsgGet( query, "Require" );
2108 answer->i_status = 551;
2109 httpd_MsgAdd( query, "Unsupported", "%s", p );
2112 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2113 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2118 cl->i_buffer = -1; /* Force the creation of the answer in
2119 * httpd_ClientSend */
2120 cl->i_state = HTTPD_CLIENT_SENDING;
2122 else if( i_msg == HTTPD_MSG_NONE )
2124 if( query->i_proto == HTTPD_PROTO_NONE )
2127 cl->i_state = HTTPD_CLIENT_DEAD;
2134 answer->i_proto = query->i_proto ;
2135 answer->i_type = HTTPD_MSG_ANSWER;
2136 answer->i_version= 0;
2137 answer->i_status = 501;
2139 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2140 answer->p_body = (uint8_t *)p;
2141 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2143 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2144 cl->i_state = HTTPD_CLIENT_SENDING;
2149 bool b_auth_failed = false;
2151 /* Search the url and trigger callbacks */
2152 for(int i = 0; i < host->i_url; i++ )
2154 httpd_url_t *url = host->url[i];
2156 if( !strcmp( url->psz_url, query->psz_url ) )
2158 if( url->catch[i_msg].cb )
2160 if( answer && ( *url->psz_user || *url->psz_password ) )
2162 /* create the headers */
2163 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2164 char *user = NULL, *pass = NULL;
2167 && !strncasecmp( b64, "BASIC", 5 ) )
2170 while( *b64 == ' ' )
2173 user = vlc_b64_decode( b64 );
2176 pass = strchr (user, ':');
2182 if ((user == NULL) || (pass == NULL)
2183 || strcmp (user, url->psz_user)
2184 || strcmp (pass, url->psz_password))
2186 httpd_MsgAdd( answer,
2188 "Basic realm=\"VLC stream\"" );
2189 /* We fail for all url */
2190 b_auth_failed = true;
2198 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2200 if( answer->i_proto == HTTPD_PROTO_NONE )
2202 /* Raw answer from a CGI */
2203 cl->i_buffer = cl->i_buffer_size;
2208 /* only one url can answer */
2210 if( cl->url == NULL )
2223 answer->i_proto = query->i_proto;
2224 answer->i_type = HTTPD_MSG_ANSWER;
2225 answer->i_version= 0;
2229 answer->i_status = 401;
2233 /* no url registered */
2234 answer->i_status = 404;
2237 answer->i_body = httpd_HtmlError (&p,
2240 answer->p_body = (uint8_t *)p;
2242 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2243 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2244 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2247 cl->i_state = HTTPD_CLIENT_SENDING;
2250 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2252 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2254 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2255 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2256 bool b_connection = false;
2257 bool b_keepalive = false;
2258 bool b_query = false;
2261 if( psz_connection )
2263 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2264 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2269 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2272 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2273 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2274 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2275 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2276 !b_query && !b_connection ) )
2278 httpd_MsgClean( &cl->query );
2279 httpd_MsgInit( &cl->query );
2282 cl->i_buffer_size = 1000;
2283 free( cl->p_buffer );
2284 cl->p_buffer = xmalloc( cl->i_buffer_size );
2285 cl->i_state = HTTPD_CLIENT_RECEIVING;
2289 cl->i_state = HTTPD_CLIENT_DEAD;
2291 httpd_MsgClean( &cl->answer );
2295 int64_t i_offset = cl->answer.i_body_offset;
2296 httpd_MsgClean( &cl->answer );
2298 cl->answer.i_body_offset = i_offset;
2299 free( cl->p_buffer );
2300 cl->p_buffer = NULL;
2302 cl->i_buffer_size = 0;
2304 cl->i_state = HTTPD_CLIENT_WAITING;
2307 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2309 int64_t i_offset = cl->answer.i_body_offset;
2310 int i_msg = cl->query.i_type;
2312 httpd_MsgInit( &cl->answer );
2313 cl->answer.i_body_offset = i_offset;
2315 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2316 &cl->answer, &cl->query );
2317 if( cl->answer.i_type != HTTPD_MSG_NONE )
2319 /* we have new data, so re-enter send mode */
2321 cl->p_buffer = cl->answer.p_body;
2322 cl->i_buffer_size = cl->answer.i_body;
2323 cl->answer.p_body = NULL;
2324 cl->answer.i_body = 0;
2325 cl->i_state = HTTPD_CLIENT_SENDING;
2329 if (pufd->events != 0)
2334 vlc_mutex_unlock( &host->lock );
2335 vlc_restorecancel( canc );
2337 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2338 int ret = poll( ufd, nfd, b_low_delay ? 20 : -1 );
2340 canc = vlc_savecancel();
2341 vlc_mutex_lock( &host->lock );
2347 /* Kernel on low memory or a bug: pace */
2348 msg_Err( host, "polling error: %m" );
2355 /* Handle client sockets */
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 );
2392 /* Handle server sockets (accept new connections) */
2393 for( nfd = 0; nfd < host->nfd; nfd++ )
2397 int fd = ufd[nfd].fd;
2399 assert (fd == host->fds[nfd]);
2401 if( ufd[nfd].revents == 0 )
2405 fd = vlc_accept (fd, NULL, NULL, true);
2408 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2409 &(int){ 1 }, sizeof(int));
2413 if( host->p_tls != NULL )
2415 p_tls = vlc_tls_ServerSessionCreate( host->p_tls, fd );
2416 switch( vlc_tls_ServerSessionHandshake( p_tls ) )
2419 msg_Err( host, "Rejecting TLS connection" );
2420 /* p_tls is destroyed implicitly */
2426 case 1: /* missing input - most likely */
2427 i_state = HTTPD_CLIENT_TLS_HS_IN;
2430 case 2: /* missing output */
2431 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2438 cl = httpd_ClientNew( fd, p_tls, now );
2439 TAB_APPEND( host->i_client, host->client, cl );
2441 cl->i_state = i_state; // override state for TLS
2444 vlc_mutex_unlock( &host->lock );