1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2004-2006 the VideoLAN team
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
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 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 General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, 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>
38 #include <vlc_strings.h>
39 #include "../libvlc.h"
56 #if defined( UNDER_CE )
58 #elif defined( WIN32 )
59 # include <winsock2.h>
61 # include <sys/socket.h>
65 /* We need HUGE buffer otherwise TCP throughput is very limited */
66 #define HTTPD_CL_BUFSIZE 1000000
68 #define HTTPD_CL_BUFSIZE 10000
71 static void httpd_ClientClean( httpd_client_t *cl );
82 /* each host run in his own thread */
92 /* address/port and socket for listening at connections */
101 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
102 * This will slow down the url research but make my live easier
103 * All url will have their cb trigger, but only the first one can answer
109 httpd_client_t **client;
130 httpd_callback_sys_t *p_sys;
131 } catch[HTTPD_MSG_MAX];
137 HTTPD_CLIENT_RECEIVING,
138 HTTPD_CLIENT_RECEIVE_DONE,
140 HTTPD_CLIENT_SENDING,
141 HTTPD_CLIENT_SEND_DONE,
143 HTTPD_CLIENT_WAITING,
147 HTTPD_CLIENT_TLS_HS_IN,
148 HTTPD_CLIENT_TLS_HS_OUT
154 HTTPD_CLIENT_FILE, /* default */
155 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
156 HTTPD_CLIENT_BIDIR, /* check for reading and get data from cb */
159 struct httpd_client_t
169 int b_read_waiting; /* stop as soon as possible sending */
171 mtime_t i_activity_date;
172 mtime_t i_activity_timeout;
174 /* buffer for reading header */
180 httpd_message_t query; /* client -> httpd */
181 httpd_message_t answer; /* httpd -> client */
184 tls_session_t *p_tls;
188 /*****************************************************************************
190 *****************************************************************************/
193 const char psz_ext[8];
194 const char *psz_mime;
197 { ".htm", "text/html" },
198 { ".html", "text/html" },
199 { ".txt", "text/plain" },
200 { ".xml", "text/xml" },
201 { ".dtd", "text/dtd" },
203 { ".css", "text/css" },
206 { ".gif", "image/gif" },
207 { ".jpe", "image/jpeg" },
208 { ".jpg", "image/jpeg" },
209 { ".jpeg", "image/jpeg" },
210 { ".png", "image/png" },
211 /* same as modules/mux/mpjpeg.c here: */
212 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
215 { ".avi", "video/avi" },
216 { ".asf", "video/x-ms-asf" },
217 { ".m1a", "audio/mpeg" },
218 { ".m2a", "audio/mpeg" },
219 { ".m1v", "video/mpeg" },
220 { ".m2v", "video/mpeg" },
221 { ".mp2", "audio/mpeg" },
222 { ".mp3", "audio/mpeg" },
223 { ".mpa", "audio/mpeg" },
224 { ".mpg", "video/mpeg" },
225 { ".mpeg", "video/mpeg" },
226 { ".mpe", "video/mpeg" },
227 { ".mov", "video/quicktime" },
228 { ".moov", "video/quicktime" },
229 { ".oga", "audio/ogg" },
230 { ".ogg", "application/ogg" },
231 { ".ogm", "application/ogg" },
232 { ".ogv", "video/ogg" },
233 { ".ogx", "application/ogg" },
234 { ".spx", "audio/ogg" },
235 { ".wav", "audio/wav" },
236 { ".wma", "audio/x-ms-wma" },
237 { ".wmv", "video/x-ms-wmv" },
244 static const char *httpd_MimeFromUrl( const char *psz_url )
249 psz_ext = strrchr( psz_url, '.' );
254 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
256 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
258 return http_mime[i].psz_mime;
262 return "application/octet-stream";
269 const char psz_reason[36];
272 static const http_status_info http_reason[] =
274 /*{ 100, "Continue" },
275 { 101, "Switching Protocols" },*/
277 /*{ 201, "Created" },
279 { 203, "Non-authoritative information" },
280 { 204, "No content" },
281 { 205, "Reset content" },
282 { 206, "Partial content" },
283 { 250, "Low on storage space" },
284 { 300, "Multiple choices" },*/
285 { 301, "Moved permanently" },
286 /*{ 302, "Moved temporarily" },
287 { 303, "See other" },
288 { 304, "Not modified" },
289 { 305, "Use proxy" },
290 { 307, "Temporary redirect" },
291 { 400, "Bad request" },*/
292 { 401, "Unauthorized" },
293 /*{ 402, "Payment Required" },*/
294 { 403, "Forbidden" },
295 { 404, "Not found" },
296 { 405, "Method not allowed" },
297 /*{ 406, "Not acceptable" },
298 { 407, "Proxy authentication required" },
299 { 408, "Request time-out" },
302 { 411, "Length required" },
303 { 412, "Precondition failed" },
304 { 413, "Request entity too large" },
305 { 414, "Request-URI too large" },
306 { 415, "Unsupported media Type" },
307 { 416, "Requested range not satisfiable" },
308 { 417, "Expectation failed" },
309 { 451, "Parameter not understood" },
310 { 452, "Conference not found" },
311 { 453, "Not enough bandwidth" },*/
312 { 454, "Session not found" },
313 /*{ 455, "Method not valid in this State" },*/
314 { 456, "Header field not valid for resource" },
315 /*{ 457, "Invalid range" },
316 { 458, "Read-only parameter" },*/
317 { 459, "Aggregate operation not allowed" },
318 { 460, "Non-aggregate operation not allowed" },
319 { 461, "Unsupported transport" },
320 /*{ 462, "Destination unreachable" },*/
321 { 500, "Internal server error" },
322 { 501, "Not implemented" },
323 /*{ 502, "Bad gateway" },*/
324 { 503, "Service unavailable" },
325 /*{ 504, "Gateway time-out" },*/
326 { 505, "Protocol version not supported" },
327 { 551, "Option not supported" },
331 static const char psz_fallback_reason[5][16] =
332 { "Continue", "OK", "Found", "Client error", "Server error" };
334 static const char *httpd_ReasonFromCode( unsigned i_code )
336 const http_status_info *p;
338 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
340 for (p = http_reason; i_code > p->i_code; p++);
342 if( p->i_code == i_code )
343 return p->psz_reason;
345 return psz_fallback_reason[(i_code / 100) - 1];
349 static size_t httpd_HtmlError (char **body, int code, const char *url)
351 const char *errname = httpd_ReasonFromCode (code);
352 assert (errname != NULL);
354 int res = asprintf (body,
355 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
356 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
357 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
358 "<html lang=\"en\">\n"
360 "<title>%s</title>\n"
363 "<h1>%d %s%s%s%s</h1>\n"
365 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
367 "</html>\n", errname, code, errname,
368 (url ? " (" : ""), (url ?: ""), (url ? ")" : ""));
380 /*****************************************************************************
381 * High Level Functions: httpd_file_t
382 *****************************************************************************/
390 httpd_file_callback_t pf_fill;
391 httpd_file_sys_t *p_sys;
396 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
397 httpd_message_t *answer, const httpd_message_t *query )
399 httpd_file_t *file = (httpd_file_t*)p_sys;
400 uint8_t **pp_body, *p_body;
401 const char *psz_connection;
402 int *pi_body, i_body;
404 if( answer == NULL || query == NULL )
408 answer->i_proto = HTTPD_PROTO_HTTP;
409 answer->i_version= 1;
410 answer->i_type = HTTPD_MSG_ANSWER;
412 answer->i_status = 200;
414 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
415 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
417 if( query->i_type != HTTPD_MSG_HEAD )
419 pp_body = &answer->p_body;
420 pi_body = &answer->i_body;
424 /* The file still needs to be executed. */
431 if( query->i_type == HTTPD_MSG_POST )
433 /* msg_Warn not supported */
436 uint8_t *psz_args = query->psz_args;
437 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
439 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
444 /* We respect client request */
445 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
446 if( psz_connection != NULL )
448 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
451 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
456 httpd_file_t *httpd_FileNew( httpd_host_t *host,
457 const char *psz_url, const char *psz_mime,
458 const char *psz_user, const char *psz_password,
459 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
460 httpd_file_sys_t *p_sys )
462 httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
464 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
465 psz_password, p_acl )
472 file->psz_url = strdup( psz_url );
473 if( psz_mime && *psz_mime )
475 file->psz_mime = strdup( psz_mime );
479 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
482 file->pf_fill = pf_fill;
485 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
486 (httpd_callback_sys_t*)file );
487 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
488 (httpd_callback_sys_t*)file );
489 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
490 (httpd_callback_sys_t*)file );
495 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
497 httpd_file_sys_t *p_sys = file->p_sys;
499 httpd_UrlDelete( file->url );
501 free( file->psz_url );
502 free( file->psz_mime );
509 /*****************************************************************************
510 * High Level Functions: httpd_handler_t (for CGIs)
511 *****************************************************************************/
512 struct httpd_handler_t
516 httpd_handler_callback_t pf_fill;
517 httpd_handler_sys_t *p_sys;
522 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
523 httpd_message_t *answer, const httpd_message_t *query )
525 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
526 char psz_remote_addr[NI_MAXNUMERICHOST];
528 if( answer == NULL || query == NULL )
532 answer->i_proto = HTTPD_PROTO_NONE;
533 answer->i_type = HTTPD_MSG_ANSWER;
535 /* We do it ourselves, thanks */
536 answer->i_status = 0;
538 if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
539 *psz_remote_addr = '\0';
541 uint8_t *psz_args = query->psz_args;
542 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
543 query->i_type, query->p_body, query->i_body,
544 psz_remote_addr, NULL,
545 &answer->p_body, &answer->i_body );
547 if( query->i_type == HTTPD_MSG_HEAD )
549 char *p = (char *)answer->p_body;
551 /* Looks for end of header (i.e. one empty line) */
552 while ( (p = strchr( p, '\r' )) != NULL )
554 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
555 && p[3] && p[3] == '\n' )
564 answer->i_body = strlen((char*)answer->p_body) + 1;
565 answer->p_body = realloc( answer->p_body, answer->i_body );
569 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
571 int i_status, i_headers;
572 char *psz_headers, *psz_new;
573 const char *psz_status;
575 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
578 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
579 if( *psz_headers ) psz_headers++;
580 if( *psz_headers ) psz_headers++;
581 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
586 psz_headers = (char *)answer->p_body;
587 i_headers = answer->i_body;
590 psz_status = httpd_ReasonFromCode( i_status );
591 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
592 + strlen(psz_status) + i_headers - 1;
593 psz_new = (char *)malloc( answer->i_body + 1);
594 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
595 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
596 free( answer->p_body );
597 answer->p_body = (uint8_t *)psz_new;
603 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
604 const char *psz_user,
605 const char *psz_password,
606 const vlc_acl_t *p_acl,
607 httpd_handler_callback_t pf_fill,
608 httpd_handler_sys_t *p_sys )
610 httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
612 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
613 psz_password, p_acl )
620 handler->pf_fill = pf_fill;
621 handler->p_sys = p_sys;
623 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
624 (httpd_callback_sys_t*)handler );
625 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
626 (httpd_callback_sys_t*)handler );
627 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
628 (httpd_callback_sys_t*)handler );
633 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
635 httpd_handler_sys_t *p_sys = handler->p_sys;
636 httpd_UrlDelete( handler->url );
641 /*****************************************************************************
642 * High Level Functions: httpd_redirect_t
643 *****************************************************************************/
644 struct httpd_redirect_t
650 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
651 httpd_client_t *cl, httpd_message_t *answer,
652 const httpd_message_t *query )
654 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
658 if( answer == NULL || query == NULL )
662 answer->i_proto = HTTPD_PROTO_HTTP;
663 answer->i_version= 1;
664 answer->i_type = HTTPD_MSG_ANSWER;
665 answer->i_status = 301;
667 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
668 answer->p_body = (unsigned char *)p_body;
670 /* XXX check if it's ok or we need to set an absolute url */
671 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
673 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
678 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
679 const char *psz_url_src )
681 httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
683 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
688 rdir->psz_dst = strdup( psz_url_dst );
690 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
691 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
692 (httpd_callback_sys_t*)rdir );
693 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
694 (httpd_callback_sys_t*)rdir );
695 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
696 (httpd_callback_sys_t*)rdir );
697 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
698 (httpd_callback_sys_t*)rdir );
702 void httpd_RedirectDelete( httpd_redirect_t *rdir )
704 httpd_UrlDelete( rdir->url );
705 free( rdir->psz_dst );
709 /*****************************************************************************
710 * High Level Funtions: httpd_stream_t
711 *****************************************************************************/
712 struct httpd_stream_t
719 /* Header to send as first packet */
723 /* circular buffer */
724 int i_buffer_size; /* buffer size, can't be reallocated smaller */
725 uint8_t *p_buffer; /* buffer */
726 int64_t i_buffer_pos; /* absolute position from begining */
727 int64_t i_buffer_last_pos; /* a new connection will start with that */
730 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
731 httpd_client_t *cl, httpd_message_t *answer,
732 const httpd_message_t *query )
734 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
736 if( answer == NULL || query == NULL || cl == NULL )
741 if( answer->i_body_offset > 0 )
747 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
748 answer->i_body_offset );
751 if( answer->i_body_offset >= stream->i_buffer_pos )
753 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
754 return VLC_EGENERIC; /* wait, no data available */
756 if( answer->i_body_offset + stream->i_buffer_size <
757 stream->i_buffer_pos )
759 /* this client isn't fast enough */
761 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
762 answer->i_body_offset, stream->i_buffer_last_pos );
764 answer->i_body_offset = stream->i_buffer_last_pos;
767 i_pos = answer->i_body_offset % stream->i_buffer_size;
768 i_write = stream->i_buffer_pos - answer->i_body_offset;
769 if( i_write > HTTPD_CL_BUFSIZE )
771 i_write = HTTPD_CL_BUFSIZE;
773 else if( i_write <= 0 )
775 return VLC_EGENERIC; /* wait, no data available */
778 /* Don't go past the end of the circular buffer */
779 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
781 /* using HTTPD_MSG_ANSWER -> data available */
782 answer->i_proto = HTTPD_PROTO_HTTP;
783 answer->i_version= 0;
784 answer->i_type = HTTPD_MSG_ANSWER;
786 answer->i_body = i_write;
787 answer->p_body = malloc( i_write );
788 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
790 answer->i_body_offset += i_write;
796 answer->i_proto = HTTPD_PROTO_HTTP;
797 answer->i_version= 0;
798 answer->i_type = HTTPD_MSG_ANSWER;
800 answer->i_status = 200;
802 if( query->i_type != HTTPD_MSG_HEAD )
804 httpd_ClientModeStream( cl );
805 vlc_mutex_lock( &stream->lock );
806 /* Send the header */
807 if( stream->i_header > 0 )
809 answer->i_body = stream->i_header;
810 answer->p_body = malloc( stream->i_header );
811 memcpy( answer->p_body, stream->p_header, stream->i_header );
813 answer->i_body_offset = stream->i_buffer_last_pos;
814 vlc_mutex_unlock( &stream->lock );
818 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
819 answer->i_body_offset = 0;
822 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
824 bool b_xplaystream = false;
827 httpd_MsgAdd( answer, "Content-type", "%s",
828 "application/octet-stream" );
829 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
830 httpd_MsgAdd( answer, "Pragma", "no-cache" );
831 httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
832 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
834 /* Check if there is a xPlayStrm=1 */
835 for( i = 0; i < query->i_name; i++ )
837 if( !strcasecmp( query->name[i], "Pragma" ) &&
838 strstr( query->value[i], "xPlayStrm=1" ) )
840 b_xplaystream = true;
846 answer->i_body_offset = 0;
851 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
853 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
858 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
859 const char *psz_url, const char *psz_mime,
860 const char *psz_user, const char *psz_password,
861 const vlc_acl_t *p_acl )
863 httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
865 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
866 psz_password, p_acl )
872 vlc_mutex_init( &stream->lock );
873 if( psz_mime && *psz_mime )
875 stream->psz_mime = strdup( psz_mime );
879 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
881 stream->i_header = 0;
882 stream->p_header = NULL;
883 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
884 stream->p_buffer = malloc( stream->i_buffer_size );
885 /* We set to 1 to make life simpler
886 * (this way i_body_offset can never be 0) */
887 stream->i_buffer_pos = 1;
888 stream->i_buffer_last_pos = 1;
890 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
891 (httpd_callback_sys_t*)stream );
892 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
893 (httpd_callback_sys_t*)stream );
894 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
895 (httpd_callback_sys_t*)stream );
900 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
902 vlc_mutex_lock( &stream->lock );
903 free( stream->p_header );
904 stream->p_header = NULL;
906 stream->i_header = i_data;
909 stream->p_header = malloc( i_data );
910 memcpy( stream->p_header, p_data, i_data );
912 vlc_mutex_unlock( &stream->lock );
917 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
922 if( i_data < 0 || p_data == NULL )
926 vlc_mutex_lock( &stream->lock );
928 /* save this pointer (to be used by new connection) */
929 stream->i_buffer_last_pos = stream->i_buffer_pos;
931 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
937 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
939 /* Ok, we can't go past the end of our buffer */
940 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
942 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
947 stream->i_buffer_pos += i_data;
949 vlc_mutex_unlock( &stream->lock );
953 void httpd_StreamDelete( httpd_stream_t *stream )
955 httpd_UrlDelete( stream->url );
956 vlc_mutex_destroy( &stream->lock );
957 free( stream->psz_mime );
958 free( stream->p_header );
959 free( stream->p_buffer );
963 /*****************************************************************************
965 *****************************************************************************/
966 static void* httpd_HostThread( vlc_object_t * );
968 /* create a new host */
969 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
972 return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
976 static const char psz_object_type[] = "http server";
978 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
980 const char *psz_cert, const char *psz_key,
981 const char *psz_ca, const char *psz_crl )
987 vlc_value_t lockval, ptrval;
990 if( psz_hostname == NULL )
993 psz_host = strdup( psz_hostname );
994 if( psz_host == NULL )
997 /* to be sure to avoid multiple creation */
998 var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
999 var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
1000 vlc_mutex_lock( lockval.p_address );
1001 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1005 msg_Info( p_this, "creating httpd" );
1006 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1011 vlc_mutex_unlock( lockval.p_address );
1019 ptrval.p_address = httpd;
1020 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1021 vlc_object_hold( httpd );
1022 vlc_object_attach( httpd, p_this->p_libvlc );
1025 /* verify if it already exist */
1026 for( i = httpd->i_host - 1; i >= 0; i-- )
1028 host = httpd->host[i];
1030 /* cannot mix TLS and non-TLS hosts */
1031 if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1032 || ( host->i_port != i_port )
1033 || strcmp( host->psz_hostname, psz_hostname ) )
1036 /* Increase existing matching host reference count.
1037 * The reference count is written under both the global httpd and the
1038 * host lock. It is read with either or both locks held. The global
1039 * lock is always acquired first. */
1040 vlc_mutex_lock( &host->lock );
1042 vlc_mutex_unlock( &host->lock );
1044 vlc_mutex_unlock( lockval.p_address );
1050 /* determine TLS configuration */
1051 if ( psz_cert != NULL )
1053 p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1054 if ( p_tls == NULL )
1056 msg_Err( p_this, "TLS initialization error" );
1060 if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1062 msg_Err( p_this, "TLS CA error" );
1066 if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1068 msg_Err( p_this, "TLS CRL error" );
1075 /* create the new host */
1076 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1082 host->httpd = httpd;
1083 vlc_mutex_init( &host->lock );
1084 vlc_cond_init( &host->wait );
1087 host->fds = net_ListenTCP( p_this, psz_host, i_port );
1088 if( host->fds == NULL )
1090 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1093 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1095 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1097 msg_Err( host, "signaling pipe error: %m" );
1101 host->i_port = i_port;
1102 host->psz_hostname = psz_host;
1107 host->client = NULL;
1109 host->p_tls = p_tls;
1111 /* create the thread */
1112 if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1113 VLC_THREAD_PRIORITY_LOW, false ) )
1115 msg_Err( p_this, "cannot spawn http host thread" );
1119 /* now add it to httpd */
1120 TAB_APPEND( httpd->i_host, httpd->host, host );
1121 vlc_mutex_unlock( lockval.p_address );
1127 if( httpd->i_host <= 0 )
1129 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1130 vlc_object_release( httpd );
1131 vlc_object_detach( httpd );
1132 vlc_object_release( httpd );
1134 vlc_mutex_unlock( lockval.p_address );
1138 net_ListenClose( host->fds );
1139 vlc_cond_destroy( &host->wait );
1140 vlc_mutex_destroy( &host->lock );
1141 vlc_object_release( host );
1145 tls_ServerDelete( p_tls );
1151 void httpd_HostDelete( httpd_host_t *host )
1153 httpd_t *httpd = host->httpd;
1154 vlc_value_t lockval;
1157 var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1158 vlc_mutex_lock( lockval.p_address );
1160 vlc_mutex_lock( &host->lock );
1162 if( host->i_ref == 0 )
1163 vlc_cond_signal( &host->wait );
1164 vlc_mutex_unlock( &host->lock );
1165 if( host->i_ref > 0 )
1168 vlc_mutex_unlock( lockval.p_address );
1169 msg_Dbg( host, "httpd_HostDelete: host still used" );
1172 TAB_REMOVE( httpd->i_host, httpd->host, host );
1174 vlc_object_kill( host );
1175 vlc_thread_join( host );
1177 msg_Dbg( host, "HTTP host removed" );
1179 for( i = 0; i < host->i_url; i++ )
1181 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1183 for( i = 0; i < host->i_client; i++ )
1185 httpd_client_t *cl = host->client[i];
1186 msg_Warn( host, "client still connected" );
1187 httpd_ClientClean( cl );
1188 TAB_REMOVE( host->i_client, host->client, cl );
1194 if( host->p_tls != NULL)
1195 tls_ServerDelete( host->p_tls );
1197 net_ListenClose( host->fds );
1198 free( host->psz_hostname );
1200 vlc_cond_destroy( &host->wait );
1201 vlc_mutex_destroy( &host->lock );
1202 vlc_object_release( host );
1204 vlc_object_release( httpd );
1205 if( httpd->i_host <= 0 )
1207 msg_Dbg( httpd, "no host left, stopping httpd" );
1209 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1210 vlc_object_detach( httpd );
1211 vlc_object_release( httpd );
1214 vlc_mutex_unlock( lockval.p_address );
1217 /* register a new url */
1218 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1219 const char *psz_user, const char *psz_password,
1220 const vlc_acl_t *p_acl, bool b_check )
1225 assert( psz_url != NULL );
1227 vlc_mutex_lock( &host->lock );
1230 for( i = 0; i < host->i_url; i++ )
1232 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1234 msg_Warn( host->httpd,
1235 "cannot add '%s' (url already defined)", psz_url );
1236 vlc_mutex_unlock( &host->lock );
1242 url = malloc( sizeof( httpd_url_t ) );
1245 vlc_mutex_init( &url->lock );
1246 url->psz_url = strdup( psz_url );
1247 url->psz_user = strdup( psz_user ? psz_user : "" );
1248 url->psz_password = strdup( psz_password ? psz_password : "" );
1249 url->p_acl = ACL_Duplicate( host, p_acl );
1250 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1252 url->catch[i].cb = NULL;
1253 url->catch[i].p_sys = NULL;
1256 TAB_APPEND( host->i_url, host->url, url );
1257 vlc_cond_signal( &host->wait );
1258 vlc_mutex_unlock( &host->lock );
1263 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1264 const char *psz_user, const char *psz_password,
1265 const vlc_acl_t *p_acl )
1267 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1268 psz_password, p_acl, false );
1271 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1272 const char *psz_user, const char *psz_password,
1273 const vlc_acl_t *p_acl )
1275 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1276 psz_password, p_acl, true );
1279 /* register callback on a url */
1280 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1281 httpd_callback_sys_t *p_sys )
1283 vlc_mutex_lock( &url->lock );
1284 url->catch[i_msg].cb = cb;
1285 url->catch[i_msg].p_sys= p_sys;
1286 vlc_mutex_unlock( &url->lock );
1292 void httpd_UrlDelete( httpd_url_t *url )
1294 httpd_host_t *host = url->host;
1297 vlc_mutex_lock( &host->lock );
1298 TAB_REMOVE( host->i_url, host->url, url );
1300 vlc_mutex_destroy( &url->lock );
1301 free( url->psz_url );
1302 free( url->psz_user );
1303 free( url->psz_password );
1304 ACL_Destroy( url->p_acl );
1306 for( i = 0; i < host->i_client; i++ )
1308 httpd_client_t *client = host->client[i];
1310 if( client->url == url )
1312 /* TODO complete it */
1313 msg_Warn( host, "force closing connections" );
1314 httpd_ClientClean( client );
1315 TAB_REMOVE( host->i_client, host->client, client );
1321 vlc_mutex_unlock( &host->lock );
1324 static void httpd_MsgInit( httpd_message_t *msg )
1327 msg->i_type = HTTPD_MSG_NONE;
1328 msg->i_proto = HTTPD_PROTO_NONE;
1329 msg->i_version = -1; /* FIXME */
1333 msg->psz_url = NULL;
1334 msg->psz_args = NULL;
1336 msg->i_channel = -1;
1343 msg->i_body_offset = 0;
1348 static void httpd_MsgClean( httpd_message_t *msg )
1352 free( msg->psz_url );
1353 free( msg->psz_args );
1354 for( i = 0; i < msg->i_name; i++ )
1356 free( msg->name[i] );
1357 free( msg->value[i] );
1361 free( msg->p_body );
1362 httpd_MsgInit( msg );
1365 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1369 for( i = 0; i < msg->i_name; i++ )
1371 if( !strcasecmp( msg->name[i], name ))
1373 return msg->value[i];
1379 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1384 va_start( args, psz_value );
1385 if( vasprintf( &value, psz_value, args ) == -1 )
1392 name = strdup( name );
1399 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1400 TAB_APPEND( msg->i_value, msg->value, value );
1403 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1405 cl->i_state = HTTPD_CLIENT_RECEIVING;
1406 cl->i_activity_date = now;
1407 cl->i_activity_timeout = INT64_C(10000000);
1408 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1410 cl->p_buffer = malloc( cl->i_buffer_size );
1411 cl->i_mode = HTTPD_CLIENT_FILE;
1412 cl->b_read_waiting = false;
1414 httpd_MsgInit( &cl->query );
1415 httpd_MsgInit( &cl->answer );
1418 void httpd_ClientModeStream( httpd_client_t *cl )
1420 cl->i_mode = HTTPD_CLIENT_STREAM;
1423 void httpd_ClientModeBidir( httpd_client_t *cl )
1425 cl->i_mode = HTTPD_CLIENT_BIDIR;
1428 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1430 return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1433 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1435 return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1438 static void httpd_ClientClean( httpd_client_t *cl )
1442 if( cl->p_tls != NULL )
1443 tls_ServerSessionClose( cl->p_tls );
1444 net_Close( cl->fd );
1448 httpd_MsgClean( &cl->answer );
1449 httpd_MsgClean( &cl->query );
1451 free( cl->p_buffer );
1452 cl->p_buffer = NULL;
1455 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1457 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1459 if( !cl ) return NULL;
1466 httpd_ClientInit( cl, now );
1472 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1474 tls_session_t *p_tls;
1479 val = p_tls ? tls_Recv (p_tls, p, i_len)
1480 : recv (cl->fd, p, i_len, 0);
1481 while (val == -1 && errno == EINTR);
1486 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1488 tls_session_t *p_tls;
1493 val = p_tls ? tls_Send( p_tls, p, i_len )
1494 : send (cl->fd, p, i_len, 0);
1495 while (val == -1 && errno == EINTR);
1502 const char name[16];
1508 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1509 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1510 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1511 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1512 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1513 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1514 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1515 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1516 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1517 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1518 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1522 static void httpd_ClientRecv( httpd_client_t *cl )
1526 /* ignore leading whites */
1527 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1528 ( cl->i_buffer == 0 ) )
1532 i_len = httpd_NetRecv( cl, &c, 1 );
1534 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1536 cl->p_buffer[0] = c;
1541 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1543 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1544 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1548 cl->i_buffer += i_len;
1551 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1553 /* Interleaved RTP over RTSP */
1554 cl->query.i_proto = HTTPD_PROTO_RTSP;
1555 cl->query.i_type = HTTPD_MSG_CHANNEL;
1556 cl->query.i_channel = cl->p_buffer[1];
1557 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1558 cl->query.p_body = malloc( cl->query.i_body );
1560 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1563 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1564 * this is the maximum we can ask at this point. */
1565 if( cl->i_buffer >= 7 )
1567 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1569 cl->query.i_proto = HTTPD_PROTO_HTTP;
1570 cl->query.i_type = HTTPD_MSG_ANSWER;
1572 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1574 cl->query.i_proto = HTTPD_PROTO_RTSP;
1575 cl->query.i_type = HTTPD_MSG_ANSWER;
1579 /* We need the full request line to determine the protocol. */
1580 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1581 cl->query.i_type = HTTPD_MSG_NONE;
1585 else if( cl->query.i_body > 0 )
1587 /* we are reading the body of a request or a channel */
1588 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1589 cl->query.i_body - cl->i_buffer );
1592 cl->i_buffer += i_len;
1594 if( cl->i_buffer >= cl->query.i_body )
1596 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1601 /* we are reading a header -> char by char */
1604 if( cl->i_buffer == cl->i_buffer_size )
1606 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1607 if( newbuf == NULL )
1613 cl->p_buffer = newbuf;
1614 cl->i_buffer_size += 1024;
1617 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1624 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1625 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1627 /* Request line is now complete */
1628 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1631 assert( cl->query.i_type == HTTPD_MSG_NONE );
1633 if( p == NULL ) /* no URI: evil guy */
1635 i_len = 0; /* drop connection */
1640 p++; /* skips extra spaces */
1643 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1644 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1646 i_len = 0; /* not supported currently -> drop */
1651 p++; /* skips extra spaces ever again */
1654 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1655 if( len < 7 ) /* foreign protocol */
1656 i_len = 0; /* I don't understand -> drop */
1658 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1660 cl->query.i_proto = HTTPD_PROTO_HTTP;
1661 cl->query.i_version = atoi( p + 7 );
1664 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1666 cl->query.i_proto = HTTPD_PROTO_RTSP;
1667 cl->query.i_version = atoi( p + 7 );
1670 if( memcmp( p, "HTTP/", 5 ) == 0 )
1672 const uint8_t sorry[] =
1673 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1674 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1675 i_len = 0; /* drop */
1678 if( memcmp( p, "RTSP/", 5 ) == 0 )
1680 const uint8_t sorry[] =
1681 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1682 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1683 i_len = 0; /* drop */
1685 else /* yet another foreign protocol */
1692 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1693 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1697 /* we have finished the header so parse it and set i_body */
1698 cl->p_buffer[cl->i_buffer] = '\0';
1700 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1703 * assume strlen( "HTTP/1.x" ) = 8
1705 cl->query.i_status =
1706 strtol( (char *)&cl->p_buffer[8],
1716 cl->query.i_type = HTTPD_MSG_NONE;
1718 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1720 for( i = 0; msg_type[i].name[0]; i++ )
1722 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1723 strlen( msg_type[i].name ) ) )
1725 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1726 cl->query.i_type = msg_type[i].i_type;
1727 if( cl->query.i_proto != msg_type[i].i_proto )
1730 cl->query.i_proto = HTTPD_PROTO_NONE;
1731 cl->query.i_type = HTTPD_MSG_NONE;
1738 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1740 cl->query.i_proto = HTTPD_PROTO_HTTP;
1742 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1744 cl->query.i_proto = HTTPD_PROTO_RTSP;
1756 p2 = strchr( p, ' ' );
1761 if( !strncasecmp( p, ( cl->query.i_proto
1762 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1763 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1764 { /* Skip hier-part of URL (if present) */
1765 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1766 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1767 { /* see RFC3986 §3.2 */
1769 while( *p && !strchr( "/?#", *p ) ) p++;
1772 cl->query.psz_url = strdup( p );
1773 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1776 cl->query.psz_args = (uint8_t *)strdup( p3 );
1783 p = strchr( p, '\n' );
1787 while( *p == '\n' || *p == '\r' )
1791 while( p && *p != '\0' )
1794 char *eol = p = strchr( p, '\n' );
1797 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1802 if( ( colon = strchr( line, ':' ) ) )
1808 while( *colon == ' ' )
1812 name = strdup( line );
1813 value = strdup( colon );
1815 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1816 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1818 if( !strcasecmp( name, "Content-Length" ) )
1820 cl->query.i_body = atol( value );
1827 while( *p == '\n' || *p == '\r' )
1834 if( cl->query.i_body > 0 )
1836 /* TODO Mhh, handle the case client will only send a
1837 * request and close the connection
1838 * to mark and of body (probably only RTSP) */
1839 cl->query.p_body = malloc( cl->query.i_body );
1844 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1850 /* check if the client is to be set to dead */
1851 #if defined( WIN32 ) || defined( UNDER_CE )
1852 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1854 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1857 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1859 /* connection closed -> end of data */
1860 if( cl->query.i_body > 0 )
1862 cl->query.i_body = cl->i_buffer;
1864 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1868 cl->i_state = HTTPD_CLIENT_DEAD;
1872 /* XXX: for QT I have to disable timeout. Try to find why */
1873 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1874 cl->i_activity_timeout = 0;
1876 #if 0 /* Debugging only */
1877 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1881 fprintf( stderr, "received new request\n" );
1882 fprintf( stderr, " - proto=%s\n",
1883 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1884 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1885 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1886 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1888 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1889 cl->query.psz_status );
1891 else if( cl->query.i_type != HTTPD_MSG_NONE )
1893 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1895 for( i = 0; i < cl->query.i_name; i++ )
1897 fprintf( stderr, " - option name='%s' value='%s'\n",
1898 cl->query.name[i], cl->query.value[i] );
1904 static void httpd_ClientSend( httpd_client_t *cl )
1909 if( cl->i_buffer < 0 )
1911 /* We need to create the header */
1914 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1916 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1917 for( i = 0; i < cl->answer.i_name; i++ )
1919 i_size += strlen( cl->answer.name[i] ) + 2 +
1920 strlen( cl->answer.value[i] ) + 2;
1923 if( cl->i_buffer_size < i_size )
1925 cl->i_buffer_size = i_size;
1926 free( cl->p_buffer );
1927 cl->p_buffer = malloc( i_size );
1929 p = (char *)cl->p_buffer;
1931 p += sprintf( p, "%s.%u %d %s\r\n",
1932 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1933 cl->answer.i_version,
1934 cl->answer.i_status, psz_status );
1935 for( i = 0; i < cl->answer.i_name; i++ )
1937 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1938 cl->answer.value[i] );
1940 p += sprintf( p, "\r\n" );
1943 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1945 /*fprintf( stderr, "sending answer\n" );
1946 fprintf( stderr, "%s", cl->p_buffer );*/
1949 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1950 cl->i_buffer_size - cl->i_buffer );
1953 cl->i_buffer += i_len;
1955 if( cl->i_buffer >= cl->i_buffer_size )
1957 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1958 !cl->b_read_waiting )
1960 /* catch more body data */
1961 int i_msg = cl->query.i_type;
1962 int64_t i_offset = cl->answer.i_body_offset;
1964 httpd_MsgClean( &cl->answer );
1965 cl->answer.i_body_offset = i_offset;
1967 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1968 &cl->answer, &cl->query );
1971 if( cl->answer.i_body > 0 )
1973 /* send the body data */
1974 free( cl->p_buffer );
1975 cl->p_buffer = cl->answer.p_body;
1976 cl->i_buffer_size = cl->answer.i_body;
1979 cl->answer.i_body = 0;
1980 cl->answer.p_body = NULL;
1985 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1991 #if defined( WIN32 ) || defined( UNDER_CE )
1992 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1994 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1998 cl->i_state = HTTPD_CLIENT_DEAD;
2003 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2005 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2008 cl->i_state = HTTPD_CLIENT_RECEIVING;
2012 cl->i_state = HTTPD_CLIENT_DEAD;
2017 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2021 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2023 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2026 cl->i_state = HTTPD_CLIENT_RECEIVING;
2030 cl->i_state = HTTPD_CLIENT_DEAD;
2035 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2040 static void* httpd_HostThread( vlc_object_t *p_this )
2042 httpd_host_t *host = (httpd_host_t *)p_this;
2043 tls_session_t *p_tls = NULL;
2044 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2045 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2046 int canc = vlc_savecancel ();
2047 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2051 /* prepare a new TLS session */
2052 if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2053 p_tls = tls_ServerSessionPrepare( host->p_tls );
2055 struct pollfd ufd[host->nfd + host->i_client + 1];
2057 for( nfd = 0; nfd < host->nfd; nfd++ )
2059 ufd[nfd].fd = host->fds[nfd];
2060 ufd[nfd].events = POLLIN;
2061 ufd[nfd].revents = 0;
2064 /* add all socket that should be read/write and close dead connection */
2065 vlc_mutex_lock( &host->lock );
2066 while( host->i_url <= 0 && host->i_ref > 0 )
2067 vlc_cond_wait( &host->wait, &host->lock );
2069 mtime_t now = mdate();
2070 bool b_low_delay = false;
2072 for(int i_client = 0; i_client < host->i_client; i_client++ )
2074 httpd_client_t *cl = host->client[i_client];
2075 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2076 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2077 ( cl->i_activity_timeout > 0 &&
2078 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2080 httpd_ClientClean( cl );
2081 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2082 TAB_REMOVE( host->i_client, host->client, cl );
2088 struct pollfd *pufd = ufd + nfd;
2089 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2092 pufd->events = pufd->revents = 0;
2094 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2095 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2097 pufd->events = POLLIN;
2099 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2100 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2102 pufd->events = POLLOUT;
2104 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2106 httpd_message_t *answer = &cl->answer;
2107 httpd_message_t *query = &cl->query;
2108 int i_msg = query->i_type;
2110 httpd_MsgInit( answer );
2112 /* Handle what we received */
2113 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2114 (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2116 /* we can only receive request from client when not
2119 cl->i_state = HTTPD_CLIENT_DEAD;
2121 else if( i_msg == HTTPD_MSG_ANSWER )
2123 /* We are in BIDIR mode, trigger the callback and then
2124 * check for new data */
2125 if( cl->url && cl->url->catch[i_msg].cb )
2127 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2130 cl->i_state = HTTPD_CLIENT_WAITING;
2132 else if( i_msg == HTTPD_MSG_CHANNEL )
2134 /* We are in BIDIR mode, trigger the callback and then
2135 * check for new data */
2136 if( cl->url && cl->url->catch[i_msg].cb )
2138 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2141 cl->i_state = HTTPD_CLIENT_WAITING;
2143 else if( i_msg == HTTPD_MSG_OPTIONS )
2146 answer->i_type = HTTPD_MSG_ANSWER;
2147 answer->i_proto = query->i_proto;
2148 answer->i_status = 200;
2150 answer->p_body = NULL;
2152 httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2153 httpd_MsgAdd( answer, "Content-Length", "0" );
2155 switch( query->i_proto )
2157 case HTTPD_PROTO_HTTP:
2158 answer->i_version = 1;
2159 httpd_MsgAdd( answer, "Allow",
2160 "GET,HEAD,POST,OPTIONS" );
2163 case HTTPD_PROTO_RTSP:
2166 answer->i_version = 0;
2168 p = httpd_MsgGet( query, "Cseq" );
2170 httpd_MsgAdd( answer, "Cseq", "%s", p );
2171 p = httpd_MsgGet( query, "Timestamp" );
2173 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2175 p = httpd_MsgGet( query, "Require" );
2178 answer->i_status = 551;
2179 httpd_MsgAdd( query, "Unsupported", "%s", p );
2182 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2183 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2188 cl->i_buffer = -1; /* Force the creation of the answer in
2189 * httpd_ClientSend */
2190 cl->i_state = HTTPD_CLIENT_SENDING;
2192 else if( i_msg == HTTPD_MSG_NONE )
2194 if( query->i_proto == HTTPD_PROTO_NONE )
2197 cl->i_state = HTTPD_CLIENT_DEAD;
2204 answer->i_proto = query->i_proto ;
2205 answer->i_type = HTTPD_MSG_ANSWER;
2206 answer->i_version= 0;
2207 answer->i_status = 501;
2209 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2210 answer->p_body = (uint8_t *)p;
2211 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2213 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2214 cl->i_state = HTTPD_CLIENT_SENDING;
2219 bool b_auth_failed = false;
2220 bool b_hosts_failed = false;
2222 /* Search the url and trigger callbacks */
2223 for(int i = 0; i < host->i_url; i++ )
2225 httpd_url_t *url = host->url[i];
2227 if( !strcmp( url->psz_url, query->psz_url ) )
2229 if( url->catch[i_msg].cb )
2231 if( answer && ( url->p_acl != NULL ) )
2233 char ip[NI_MAXNUMERICHOST];
2235 if( ( httpd_ClientIP( cl, ip ) == NULL )
2236 || ACL_Check( url->p_acl, ip ) )
2238 b_hosts_failed = true;
2243 if( answer && ( *url->psz_user || *url->psz_password ) )
2245 /* create the headers */
2246 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2247 char *user = NULL, *pass = NULL;
2250 && !strncasecmp( b64, "BASIC", 5 ) )
2253 while( *b64 == ' ' )
2256 user = vlc_b64_decode( b64 );
2259 pass = strchr (user, ':');
2265 if ((user == NULL) || (pass == NULL)
2266 || strcmp (user, url->psz_user)
2267 || strcmp (pass, url->psz_password))
2269 httpd_MsgAdd( answer,
2271 "Basic realm=\"%s\"",
2273 /* We fail for all url */
2274 b_auth_failed = true;
2282 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2284 if( answer->i_proto == HTTPD_PROTO_NONE )
2286 /* Raw answer from a CGI */
2287 cl->i_buffer = cl->i_buffer_size;
2292 /* only one url can answer */
2294 if( cl->url == NULL )
2307 answer->i_proto = query->i_proto;
2308 answer->i_type = HTTPD_MSG_ANSWER;
2309 answer->i_version= 0;
2311 if( b_hosts_failed )
2313 answer->i_status = 403;
2315 else if( b_auth_failed )
2317 answer->i_status = 401;
2321 /* no url registered */
2322 answer->i_status = 404;
2325 answer->i_body = httpd_HtmlError (&p,
2328 answer->p_body = (uint8_t *)p;
2330 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2331 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2332 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2335 cl->i_state = HTTPD_CLIENT_SENDING;
2338 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2340 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2342 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2343 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2344 bool b_connection = false;
2345 bool b_keepalive = false;
2346 bool b_query = false;
2349 if( psz_connection )
2351 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2352 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2357 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2360 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2361 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2362 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2363 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2364 !b_query && !b_connection ) )
2366 httpd_MsgClean( &cl->query );
2367 httpd_MsgInit( &cl->query );
2370 cl->i_buffer_size = 1000;
2371 free( cl->p_buffer );
2372 cl->p_buffer = malloc( cl->i_buffer_size );
2373 cl->i_state = HTTPD_CLIENT_RECEIVING;
2377 cl->i_state = HTTPD_CLIENT_DEAD;
2379 httpd_MsgClean( &cl->answer );
2381 else if( cl->b_read_waiting )
2383 /* we have a message waiting for us to read it */
2384 httpd_MsgClean( &cl->answer );
2385 httpd_MsgClean( &cl->query );
2388 cl->i_buffer_size = 1000;
2389 free( cl->p_buffer );
2390 cl->p_buffer = malloc( cl->i_buffer_size );
2391 cl->i_state = HTTPD_CLIENT_RECEIVING;
2392 cl->b_read_waiting = false;
2396 int64_t i_offset = cl->answer.i_body_offset;
2397 httpd_MsgClean( &cl->answer );
2399 cl->answer.i_body_offset = i_offset;
2400 free( cl->p_buffer );
2401 cl->p_buffer = NULL;
2403 cl->i_buffer_size = 0;
2405 cl->i_state = HTTPD_CLIENT_WAITING;
2408 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2410 int64_t i_offset = cl->answer.i_body_offset;
2411 int i_msg = cl->query.i_type;
2413 httpd_MsgInit( &cl->answer );
2414 cl->answer.i_body_offset = i_offset;
2416 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2417 &cl->answer, &cl->query );
2418 if( cl->answer.i_type != HTTPD_MSG_NONE )
2420 /* we have new data, so re-enter send mode */
2422 cl->p_buffer = cl->answer.p_body;
2423 cl->i_buffer_size = cl->answer.i_body;
2424 cl->answer.p_body = NULL;
2425 cl->answer.i_body = 0;
2426 cl->i_state = HTTPD_CLIENT_SENDING;
2430 /* Special for BIDIR mode we also check reading */
2431 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2432 cl->i_state == HTTPD_CLIENT_SENDING )
2434 pufd->events |= POLLIN;
2437 if (pufd->events != 0)
2442 vlc_mutex_unlock( &host->lock );
2445 ufd[nfd].events = POLLIN;
2446 ufd[nfd].revents = 0;
2449 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2450 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2455 /* Kernel on low memory or a bug: pace */
2456 msg_Err( host, "polling error: %m" );
2463 if( ufd[nfd - 1].revents )
2466 /* Handle client sockets */
2467 vlc_mutex_lock( &host->lock );
2470 for( int i_client = 0; i_client < host->i_client; i_client++ )
2472 httpd_client_t *cl = host->client[i_client];
2473 const struct pollfd *pufd = &ufd[nfd];
2475 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2477 if( cl->fd != pufd->fd )
2478 continue; // we were not waiting for this client
2480 if( pufd->revents == 0 )
2481 continue; // no event received
2483 cl->i_activity_date = now;
2485 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2487 httpd_ClientRecv( cl );
2489 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2491 httpd_ClientSend( cl );
2493 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2495 httpd_ClientTlsHsIn( cl );
2497 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2499 httpd_ClientTlsHsOut( cl );
2502 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2503 cl->i_state == HTTPD_CLIENT_SENDING &&
2504 (pufd->revents & POLLIN) )
2506 cl->b_read_waiting = true;
2509 vlc_mutex_unlock( &host->lock );
2511 /* Handle server sockets (accept new connections) */
2512 for( nfd = 0; nfd < host->nfd; nfd++ )
2516 int fd = ufd[nfd].fd;
2518 assert (fd == host->fds[nfd]);
2520 if( ufd[nfd].revents == 0 )
2524 fd = accept (fd, NULL, NULL);
2528 net_SetupSocket (fd);
2531 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2534 msg_Err( host, "Rejecting TLS connection" );
2540 case 1: /* missing input - most likely */
2541 i_state = HTTPD_CLIENT_TLS_HS_IN;
2544 case 2: /* missing output */
2545 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2549 if( (p_tls == NULL) != (host->p_tls == NULL) )
2550 break; // wasted TLS session, cannot accept() anymore
2553 stats_UpdateInteger( host, p_total_counter, 1, NULL );
2554 stats_UpdateInteger( host, p_active_counter, 1, NULL );
2555 cl = httpd_ClientNew( fd, p_tls, now );
2557 vlc_mutex_lock( &host->lock );
2558 TAB_APPEND( host->i_client, host->client, cl );
2559 vlc_mutex_unlock( &host->lock );
2561 cl->i_state = i_state; // override state for TLS
2563 if (host->p_tls != NULL)
2564 break; // cannot accept further without new TLS session
2570 tls_ServerSessionClose( p_tls );
2571 if( p_total_counter )
2572 stats_CounterClean( p_total_counter );
2573 if( p_active_counter )
2574 stats_CounterClean( p_active_counter );
2575 vlc_restorecancel (canc);