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 */
100 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
101 * This will slow down the url research but make my live easier
102 * All url will have their cb trigger, but only the first one can answer
108 httpd_client_t **client;
129 httpd_callback_sys_t *p_sys;
130 } catch[HTTPD_MSG_MAX];
136 HTTPD_CLIENT_RECEIVING,
137 HTTPD_CLIENT_RECEIVE_DONE,
139 HTTPD_CLIENT_SENDING,
140 HTTPD_CLIENT_SEND_DONE,
142 HTTPD_CLIENT_WAITING,
146 HTTPD_CLIENT_TLS_HS_IN,
147 HTTPD_CLIENT_TLS_HS_OUT
153 HTTPD_CLIENT_FILE, /* default */
154 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
155 HTTPD_CLIENT_BIDIR, /* check for reading and get data from cb */
158 struct httpd_client_t
168 int b_read_waiting; /* stop as soon as possible sending */
170 mtime_t i_activity_date;
171 mtime_t i_activity_timeout;
173 /* buffer for reading header */
179 httpd_message_t query; /* client -> httpd */
180 httpd_message_t answer; /* httpd -> client */
183 tls_session_t *p_tls;
187 /*****************************************************************************
189 *****************************************************************************/
192 const char psz_ext[8];
193 const char *psz_mime;
196 { ".htm", "text/html" },
197 { ".html", "text/html" },
198 { ".txt", "text/plain" },
199 { ".xml", "text/xml" },
200 { ".dtd", "text/dtd" },
202 { ".css", "text/css" },
205 { ".gif", "image/gif" },
206 { ".jpe", "image/jpeg" },
207 { ".jpg", "image/jpeg" },
208 { ".jpeg", "image/jpeg" },
209 { ".png", "image/png" },
210 /* same as modules/mux/mpjpeg.c here: */
211 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
214 { ".avi", "video/avi" },
215 { ".asf", "video/x-ms-asf" },
216 { ".m1a", "audio/mpeg" },
217 { ".m2a", "audio/mpeg" },
218 { ".m1v", "video/mpeg" },
219 { ".m2v", "video/mpeg" },
220 { ".mp2", "audio/mpeg" },
221 { ".mp3", "audio/mpeg" },
222 { ".mpa", "audio/mpeg" },
223 { ".mpg", "video/mpeg" },
224 { ".mpeg", "video/mpeg" },
225 { ".mpe", "video/mpeg" },
226 { ".mov", "video/quicktime" },
227 { ".moov", "video/quicktime" },
228 { ".oga", "audio/ogg" },
229 { ".ogg", "application/ogg" },
230 { ".ogm", "application/ogg" },
231 { ".ogv", "video/ogg" },
232 { ".spx", "audio/ogg" },
233 { ".wav", "audio/wav" },
234 { ".wma", "audio/x-ms-wma" },
235 { ".wmv", "video/x-ms-wmv" },
242 static const char *httpd_MimeFromUrl( const char *psz_url )
247 psz_ext = strrchr( psz_url, '.' );
252 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
254 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
256 return http_mime[i].psz_mime;
260 return "application/octet-stream";
267 const char psz_reason[36];
270 static const http_status_info http_reason[] =
272 /*{ 100, "Continue" },
273 { 101, "Switching Protocols" },*/
275 /*{ 201, "Created" },
277 { 203, "Non-authoritative information" },
278 { 204, "No content" },
279 { 205, "Reset content" },
280 { 206, "Partial content" },
281 { 250, "Low on storage space" },
282 { 300, "Multiple choices" },*/
283 { 301, "Moved permanently" },
284 /*{ 302, "Moved temporarily" },
285 { 303, "See other" },
286 { 304, "Not modified" },
287 { 305, "Use proxy" },
288 { 307, "Temporary redirect" },
289 { 400, "Bad request" },*/
290 { 401, "Unauthorized" },
291 /*{ 402, "Payment Required" },*/
292 { 403, "Forbidden" },
293 { 404, "Not found" },
294 { 405, "Method not allowed" },
295 /*{ 406, "Not acceptable" },
296 { 407, "Proxy authentication required" },
297 { 408, "Request time-out" },
300 { 411, "Length required" },
301 { 412, "Precondition failed" },
302 { 413, "Request entity too large" },
303 { 414, "Request-URI too large" },
304 { 415, "Unsupported media Type" },
305 { 416, "Requested range not satisfiable" },
306 { 417, "Expectation failed" },
307 { 451, "Parameter not understood" },
308 { 452, "Conference not found" },
309 { 453, "Not enough bandwidth" },*/
310 { 454, "Session not found" },
311 /*{ 455, "Method not valid in this State" },*/
312 { 456, "Header field not valid for resource" },
313 /*{ 457, "Invalid range" },
314 { 458, "Read-only parameter" },*/
315 { 459, "Aggregate operation not allowed" },
316 { 460, "Non-aggregate operation not allowed" },
317 { 461, "Unsupported transport" },
318 /*{ 462, "Destination unreachable" },*/
319 { 500, "Internal server error" },
320 { 501, "Not implemented" },
321 /*{ 502, "Bad gateway" },*/
322 { 503, "Service unavailable" },
323 /*{ 504, "Gateway time-out" },*/
324 { 505, "Protocol version not supported" },
325 { 551, "Option not supported" },
329 static const char psz_fallback_reason[5][16] =
330 { "Continue", "OK", "Found", "Client error", "Server error" };
332 static const char *httpd_ReasonFromCode( unsigned i_code )
334 const http_status_info *p;
336 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
338 for (p = http_reason; i_code > p->i_code; p++);
340 if( p->i_code == i_code )
341 return p->psz_reason;
343 return psz_fallback_reason[(i_code / 100) - 1];
347 static size_t httpd_HtmlError (char **body, int code, const char *url)
349 const char *errname = httpd_ReasonFromCode (code);
350 assert (errname != NULL);
352 int res = asprintf (body,
353 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
354 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
355 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
356 "<html lang=\"en\">\n"
358 "<title>%s</title>\n"
361 "<h1>%d %s%s%s%s</h1>\n"
363 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
365 "</html>\n", errname, code, errname,
366 (url ? " (" : ""), (url ?: ""), (url ? ")" : ""));
378 /*****************************************************************************
379 * High Level Functions: httpd_file_t
380 *****************************************************************************/
388 httpd_file_callback_t pf_fill;
389 httpd_file_sys_t *p_sys;
394 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
395 httpd_message_t *answer, const httpd_message_t *query )
397 httpd_file_t *file = (httpd_file_t*)p_sys;
398 uint8_t **pp_body, *p_body;
399 const char *psz_connection;
400 int *pi_body, i_body;
402 if( answer == NULL || query == NULL )
406 answer->i_proto = HTTPD_PROTO_HTTP;
407 answer->i_version= 1;
408 answer->i_type = HTTPD_MSG_ANSWER;
410 answer->i_status = 200;
412 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
413 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
415 if( query->i_type != HTTPD_MSG_HEAD )
417 pp_body = &answer->p_body;
418 pi_body = &answer->i_body;
422 /* The file still needs to be executed. */
429 if( query->i_type == HTTPD_MSG_POST )
431 /* msg_Warn not supported */
434 uint8_t *psz_args = query->psz_args;
435 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
437 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
442 /* We respect client request */
443 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
444 if( psz_connection != NULL )
446 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
449 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
454 httpd_file_t *httpd_FileNew( httpd_host_t *host,
455 const char *psz_url, const char *psz_mime,
456 const char *psz_user, const char *psz_password,
457 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
458 httpd_file_sys_t *p_sys )
460 httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
462 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
463 psz_password, p_acl )
470 file->psz_url = strdup( psz_url );
471 if( psz_mime && *psz_mime )
473 file->psz_mime = strdup( psz_mime );
477 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
480 file->pf_fill = pf_fill;
483 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
484 (httpd_callback_sys_t*)file );
485 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
486 (httpd_callback_sys_t*)file );
487 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
488 (httpd_callback_sys_t*)file );
493 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
495 httpd_file_sys_t *p_sys = file->p_sys;
497 httpd_UrlDelete( file->url );
499 free( file->psz_url );
500 free( file->psz_mime );
507 /*****************************************************************************
508 * High Level Functions: httpd_handler_t (for CGIs)
509 *****************************************************************************/
510 struct httpd_handler_t
514 httpd_handler_callback_t pf_fill;
515 httpd_handler_sys_t *p_sys;
520 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
521 httpd_message_t *answer, const httpd_message_t *query )
523 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
524 char psz_remote_addr[NI_MAXNUMERICHOST];
526 if( answer == NULL || query == NULL )
530 answer->i_proto = HTTPD_PROTO_NONE;
531 answer->i_type = HTTPD_MSG_ANSWER;
533 /* We do it ourselves, thanks */
534 answer->i_status = 0;
536 if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
537 *psz_remote_addr = '\0';
539 uint8_t *psz_args = query->psz_args;
540 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
541 query->i_type, query->p_body, query->i_body,
542 psz_remote_addr, NULL,
543 &answer->p_body, &answer->i_body );
545 if( query->i_type == HTTPD_MSG_HEAD )
547 char *p = (char *)answer->p_body;
549 /* Looks for end of header (i.e. one empty line) */
550 while ( (p = strchr( p, '\r' )) != NULL )
552 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
553 && p[3] && p[3] == '\n' )
562 answer->i_body = strlen((char*)answer->p_body) + 1;
563 answer->p_body = realloc( answer->p_body, answer->i_body );
567 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
569 int i_status, i_headers;
570 char *psz_headers, *psz_new;
571 const char *psz_status;
573 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
576 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
577 if( *psz_headers ) psz_headers++;
578 if( *psz_headers ) psz_headers++;
579 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
584 psz_headers = (char *)answer->p_body;
585 i_headers = answer->i_body;
588 psz_status = httpd_ReasonFromCode( i_status );
589 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
590 + strlen(psz_status) + i_headers - 1;
591 psz_new = (char *)malloc( answer->i_body + 1);
592 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
593 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
594 free( answer->p_body );
595 answer->p_body = (uint8_t *)psz_new;
601 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
602 const char *psz_user,
603 const char *psz_password,
604 const vlc_acl_t *p_acl,
605 httpd_handler_callback_t pf_fill,
606 httpd_handler_sys_t *p_sys )
608 httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
610 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
611 psz_password, p_acl )
618 handler->pf_fill = pf_fill;
619 handler->p_sys = p_sys;
621 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
622 (httpd_callback_sys_t*)handler );
623 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
624 (httpd_callback_sys_t*)handler );
625 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
626 (httpd_callback_sys_t*)handler );
631 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
633 httpd_handler_sys_t *p_sys = handler->p_sys;
634 httpd_UrlDelete( handler->url );
639 /*****************************************************************************
640 * High Level Functions: httpd_redirect_t
641 *****************************************************************************/
642 struct httpd_redirect_t
648 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
649 httpd_client_t *cl, httpd_message_t *answer,
650 const httpd_message_t *query )
652 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
656 if( answer == NULL || query == NULL )
660 answer->i_proto = HTTPD_PROTO_HTTP;
661 answer->i_version= 1;
662 answer->i_type = HTTPD_MSG_ANSWER;
663 answer->i_status = 301;
665 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
666 answer->p_body = (unsigned char *)p_body;
668 /* XXX check if it's ok or we need to set an absolute url */
669 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
671 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
676 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
677 const char *psz_url_src )
679 httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
681 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
686 rdir->psz_dst = strdup( psz_url_dst );
688 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
689 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
690 (httpd_callback_sys_t*)rdir );
691 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
692 (httpd_callback_sys_t*)rdir );
693 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
694 (httpd_callback_sys_t*)rdir );
695 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
696 (httpd_callback_sys_t*)rdir );
700 void httpd_RedirectDelete( httpd_redirect_t *rdir )
702 httpd_UrlDelete( rdir->url );
703 free( rdir->psz_dst );
707 /*****************************************************************************
708 * High Level Funtions: httpd_stream_t
709 *****************************************************************************/
710 struct httpd_stream_t
717 /* Header to send as first packet */
721 /* circular buffer */
722 int i_buffer_size; /* buffer size, can't be reallocated smaller */
723 uint8_t *p_buffer; /* buffer */
724 int64_t i_buffer_pos; /* absolute position from begining */
725 int64_t i_buffer_last_pos; /* a new connection will start with that */
728 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
729 httpd_client_t *cl, httpd_message_t *answer,
730 const httpd_message_t *query )
732 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
734 if( answer == NULL || query == NULL || cl == NULL )
739 if( answer->i_body_offset > 0 )
745 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
746 answer->i_body_offset );
749 if( answer->i_body_offset >= stream->i_buffer_pos )
751 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
752 return VLC_EGENERIC; /* wait, no data available */
754 if( answer->i_body_offset + stream->i_buffer_size <
755 stream->i_buffer_pos )
757 /* this client isn't fast enough */
759 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
760 answer->i_body_offset, stream->i_buffer_last_pos );
762 answer->i_body_offset = stream->i_buffer_last_pos;
765 i_pos = answer->i_body_offset % stream->i_buffer_size;
766 i_write = stream->i_buffer_pos - answer->i_body_offset;
767 if( i_write > HTTPD_CL_BUFSIZE )
769 i_write = HTTPD_CL_BUFSIZE;
771 else if( i_write <= 0 )
773 return VLC_EGENERIC; /* wait, no data available */
776 /* Don't go past the end of the circular buffer */
777 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
779 /* using HTTPD_MSG_ANSWER -> data available */
780 answer->i_proto = HTTPD_PROTO_HTTP;
781 answer->i_version= 0;
782 answer->i_type = HTTPD_MSG_ANSWER;
784 answer->i_body = i_write;
785 answer->p_body = malloc( i_write );
786 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
788 answer->i_body_offset += i_write;
794 answer->i_proto = HTTPD_PROTO_HTTP;
795 answer->i_version= 0;
796 answer->i_type = HTTPD_MSG_ANSWER;
798 answer->i_status = 200;
800 if( query->i_type != HTTPD_MSG_HEAD )
802 httpd_ClientModeStream( cl );
803 vlc_mutex_lock( &stream->lock );
804 /* Send the header */
805 if( stream->i_header > 0 )
807 answer->i_body = stream->i_header;
808 answer->p_body = malloc( stream->i_header );
809 memcpy( answer->p_body, stream->p_header, stream->i_header );
811 answer->i_body_offset = stream->i_buffer_last_pos;
812 vlc_mutex_unlock( &stream->lock );
816 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
817 answer->i_body_offset = 0;
820 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
822 bool b_xplaystream = false;
825 httpd_MsgAdd( answer, "Content-type", "%s",
826 "application/octet-stream" );
827 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
828 httpd_MsgAdd( answer, "Pragma", "no-cache" );
829 httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
830 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
832 /* Check if there is a xPlayStrm=1 */
833 for( i = 0; i < query->i_name; i++ )
835 if( !strcasecmp( query->name[i], "Pragma" ) &&
836 strstr( query->value[i], "xPlayStrm=1" ) )
838 b_xplaystream = true;
844 answer->i_body_offset = 0;
849 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
851 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
856 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
857 const char *psz_url, const char *psz_mime,
858 const char *psz_user, const char *psz_password,
859 const vlc_acl_t *p_acl )
861 httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
863 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
864 psz_password, p_acl )
870 vlc_mutex_init( &stream->lock );
871 if( psz_mime && *psz_mime )
873 stream->psz_mime = strdup( psz_mime );
877 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
879 stream->i_header = 0;
880 stream->p_header = NULL;
881 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
882 stream->p_buffer = malloc( stream->i_buffer_size );
883 /* We set to 1 to make life simpler
884 * (this way i_body_offset can never be 0) */
885 stream->i_buffer_pos = 1;
886 stream->i_buffer_last_pos = 1;
888 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
889 (httpd_callback_sys_t*)stream );
890 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
891 (httpd_callback_sys_t*)stream );
892 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
893 (httpd_callback_sys_t*)stream );
898 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
900 vlc_mutex_lock( &stream->lock );
901 free( stream->p_header );
902 stream->p_header = NULL;
904 stream->i_header = i_data;
907 stream->p_header = malloc( i_data );
908 memcpy( stream->p_header, p_data, i_data );
910 vlc_mutex_unlock( &stream->lock );
915 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
920 if( i_data < 0 || p_data == NULL )
924 vlc_mutex_lock( &stream->lock );
926 /* save this pointer (to be used by new connection) */
927 stream->i_buffer_last_pos = stream->i_buffer_pos;
929 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
935 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
937 /* Ok, we can't go past the end of our buffer */
938 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
940 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
945 stream->i_buffer_pos += i_data;
947 vlc_mutex_unlock( &stream->lock );
951 void httpd_StreamDelete( httpd_stream_t *stream )
953 httpd_UrlDelete( stream->url );
954 vlc_mutex_destroy( &stream->lock );
955 free( stream->psz_mime );
956 free( stream->p_header );
957 free( stream->p_buffer );
961 /*****************************************************************************
963 *****************************************************************************/
964 static void* httpd_HostThread( vlc_object_t * );
966 /* create a new host */
967 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
970 return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
974 static const char psz_object_type[] = "http server";
976 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
978 const char *psz_cert, const char *psz_key,
979 const char *psz_ca, const char *psz_crl )
985 vlc_value_t lockval, ptrval;
988 if( psz_hostname == NULL )
991 psz_host = strdup( psz_hostname );
992 if( psz_host == NULL )
995 /* to be sure to avoid multiple creation */
996 var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
997 var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
998 vlc_mutex_lock( lockval.p_address );
999 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1003 msg_Info( p_this, "creating httpd" );
1004 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1009 vlc_mutex_unlock( lockval.p_address );
1017 ptrval.p_address = httpd;
1018 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1019 vlc_object_hold( httpd );
1020 vlc_object_attach( httpd, p_this->p_libvlc );
1023 /* verify if it already exist */
1024 for( i = httpd->i_host - 1; i >= 0; i-- )
1026 host = httpd->host[i];
1028 /* cannot mix TLS and non-TLS hosts */
1029 if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1030 || ( host->i_port != i_port )
1031 || strcmp( host->psz_hostname, psz_hostname ) )
1037 vlc_mutex_unlock( lockval.p_address );
1043 /* determine TLS configuration */
1044 if ( psz_cert != NULL )
1046 p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1047 if ( p_tls == NULL )
1049 msg_Err( p_this, "TLS initialization error" );
1053 if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1055 msg_Err( p_this, "TLS CA error" );
1059 if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1061 msg_Err( p_this, "TLS CRL error" );
1068 /* create the new host */
1069 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1075 vlc_object_lock( host );
1076 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1078 msg_Err( host, "signaling pipe error: %m" );
1079 vlc_object_unlock( host );
1082 vlc_object_unlock( host );
1084 host->httpd = httpd;
1085 vlc_mutex_init( &host->lock );
1088 host->fds = net_ListenTCP( p_this, psz_host, i_port );
1089 if( host->fds == NULL )
1091 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1094 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1096 host->i_port = i_port;
1097 host->psz_hostname = psz_host;
1102 host->client = NULL;
1104 host->p_tls = p_tls;
1106 /* create the thread */
1107 if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1108 VLC_THREAD_PRIORITY_LOW, false ) )
1110 msg_Err( p_this, "cannot spawn http host thread" );
1114 /* now add it to httpd */
1115 TAB_APPEND( httpd->i_host, httpd->host, host );
1116 vlc_mutex_unlock( lockval.p_address );
1122 if( httpd->i_host <= 0 )
1124 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1125 vlc_object_release( httpd );
1126 vlc_object_detach( httpd );
1127 vlc_object_release( httpd );
1129 vlc_mutex_unlock( lockval.p_address );
1133 net_ListenClose( host->fds );
1134 vlc_mutex_destroy( &host->lock );
1135 vlc_object_release( host );
1139 tls_ServerDelete( p_tls );
1145 void httpd_HostDelete( httpd_host_t *host )
1147 httpd_t *httpd = host->httpd;
1148 vlc_value_t lockval;
1151 var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1152 vlc_mutex_lock( lockval.p_address );
1155 if( host->i_ref > 0 )
1158 vlc_mutex_unlock( lockval.p_address );
1159 msg_Dbg( host, "httpd_HostDelete: host still used" );
1162 TAB_REMOVE( httpd->i_host, httpd->host, host );
1164 vlc_object_kill( host );
1165 vlc_thread_join( host );
1167 msg_Dbg( host, "HTTP host removed" );
1169 for( i = 0; i < host->i_url; i++ )
1171 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1173 for( i = 0; i < host->i_client; i++ )
1175 httpd_client_t *cl = host->client[i];
1176 msg_Warn( host, "client still connected" );
1177 httpd_ClientClean( cl );
1178 TAB_REMOVE( host->i_client, host->client, cl );
1184 if( host->p_tls != NULL)
1185 tls_ServerDelete( host->p_tls );
1187 net_ListenClose( host->fds );
1188 free( host->psz_hostname );
1190 vlc_mutex_destroy( &host->lock );
1191 vlc_object_release( host );
1193 vlc_object_release( httpd );
1194 if( httpd->i_host <= 0 )
1196 msg_Dbg( httpd, "no host left, stopping httpd" );
1198 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1199 vlc_object_detach( httpd );
1200 vlc_object_release( httpd );
1203 vlc_mutex_unlock( lockval.p_address );
1206 /* register a new url */
1207 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1208 const char *psz_user, const char *psz_password,
1209 const vlc_acl_t *p_acl, bool b_check )
1214 assert( psz_url != NULL );
1216 vlc_mutex_lock( &host->lock );
1219 for( i = 0; i < host->i_url; i++ )
1221 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1223 msg_Warn( host->httpd,
1224 "cannot add '%s' (url already defined)", psz_url );
1225 vlc_mutex_unlock( &host->lock );
1231 url = malloc( sizeof( httpd_url_t ) );
1234 vlc_mutex_init( &url->lock );
1235 url->psz_url = strdup( psz_url );
1236 url->psz_user = strdup( psz_user ? psz_user : "" );
1237 url->psz_password = strdup( psz_password ? psz_password : "" );
1238 url->p_acl = ACL_Duplicate( host, p_acl );
1239 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1241 url->catch[i].cb = NULL;
1242 url->catch[i].p_sys = NULL;
1245 TAB_APPEND( host->i_url, host->url, url );
1246 vlc_mutex_unlock( &host->lock );
1251 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1252 const char *psz_user, const char *psz_password,
1253 const vlc_acl_t *p_acl )
1255 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1256 psz_password, p_acl, false );
1259 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1260 const char *psz_user, const char *psz_password,
1261 const vlc_acl_t *p_acl )
1263 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1264 psz_password, p_acl, true );
1267 /* register callback on a url */
1268 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1269 httpd_callback_sys_t *p_sys )
1271 vlc_mutex_lock( &url->lock );
1272 url->catch[i_msg].cb = cb;
1273 url->catch[i_msg].p_sys= p_sys;
1274 vlc_mutex_unlock( &url->lock );
1280 void httpd_UrlDelete( httpd_url_t *url )
1282 httpd_host_t *host = url->host;
1285 vlc_mutex_lock( &host->lock );
1286 TAB_REMOVE( host->i_url, host->url, url );
1288 vlc_mutex_destroy( &url->lock );
1289 free( url->psz_url );
1290 free( url->psz_user );
1291 free( url->psz_password );
1292 ACL_Destroy( url->p_acl );
1294 for( i = 0; i < host->i_client; i++ )
1296 httpd_client_t *client = host->client[i];
1298 if( client->url == url )
1300 /* TODO complete it */
1301 msg_Warn( host, "force closing connections" );
1302 httpd_ClientClean( client );
1303 TAB_REMOVE( host->i_client, host->client, client );
1309 vlc_mutex_unlock( &host->lock );
1312 static void httpd_MsgInit( httpd_message_t *msg )
1315 msg->i_type = HTTPD_MSG_NONE;
1316 msg->i_proto = HTTPD_PROTO_NONE;
1317 msg->i_version = -1; /* FIXME */
1321 msg->psz_url = NULL;
1322 msg->psz_args = NULL;
1324 msg->i_channel = -1;
1331 msg->i_body_offset = 0;
1336 static void httpd_MsgClean( httpd_message_t *msg )
1340 free( msg->psz_url );
1341 free( msg->psz_args );
1342 for( i = 0; i < msg->i_name; i++ )
1344 free( msg->name[i] );
1345 free( msg->value[i] );
1349 free( msg->p_body );
1350 httpd_MsgInit( msg );
1353 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1357 for( i = 0; i < msg->i_name; i++ )
1359 if( !strcasecmp( msg->name[i], name ))
1361 return msg->value[i];
1367 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1372 va_start( args, psz_value );
1373 if( vasprintf( &value, psz_value, args ) == -1 )
1380 name = strdup( name );
1387 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1388 TAB_APPEND( msg->i_value, msg->value, value );
1391 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1393 cl->i_state = HTTPD_CLIENT_RECEIVING;
1394 cl->i_activity_date = now;
1395 cl->i_activity_timeout = INT64_C(10000000);
1396 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1398 cl->p_buffer = malloc( cl->i_buffer_size );
1399 cl->i_mode = HTTPD_CLIENT_FILE;
1400 cl->b_read_waiting = false;
1402 httpd_MsgInit( &cl->query );
1403 httpd_MsgInit( &cl->answer );
1406 void httpd_ClientModeStream( httpd_client_t *cl )
1408 cl->i_mode = HTTPD_CLIENT_STREAM;
1411 void httpd_ClientModeBidir( httpd_client_t *cl )
1413 cl->i_mode = HTTPD_CLIENT_BIDIR;
1416 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1418 return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1421 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1423 return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1426 static void httpd_ClientClean( httpd_client_t *cl )
1430 if( cl->p_tls != NULL )
1431 tls_ServerSessionClose( cl->p_tls );
1432 net_Close( cl->fd );
1436 httpd_MsgClean( &cl->answer );
1437 httpd_MsgClean( &cl->query );
1439 free( cl->p_buffer );
1440 cl->p_buffer = NULL;
1443 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1445 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1447 if( !cl ) return NULL;
1454 httpd_ClientInit( cl, now );
1460 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1462 tls_session_t *p_tls;
1467 val = p_tls ? tls_Recv (p_tls, p, i_len)
1468 : recv (cl->fd, p, i_len, 0);
1469 while (val == -1 && errno == EINTR);
1474 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1476 tls_session_t *p_tls;
1481 val = p_tls ? tls_Send( p_tls, p, i_len )
1482 : send (cl->fd, p, i_len, 0);
1483 while (val == -1 && errno == EINTR);
1490 const char name[16];
1496 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1497 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1498 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1499 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1500 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1501 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1502 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1503 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1504 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1505 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1506 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1510 static void httpd_ClientRecv( httpd_client_t *cl )
1514 /* ignore leading whites */
1515 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1516 ( cl->i_buffer == 0 ) )
1520 i_len = httpd_NetRecv( cl, &c, 1 );
1522 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1524 cl->p_buffer[0] = c;
1529 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1531 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1532 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1536 cl->i_buffer += i_len;
1539 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1541 /* Interleaved RTP over RTSP */
1542 cl->query.i_proto = HTTPD_PROTO_RTSP;
1543 cl->query.i_type = HTTPD_MSG_CHANNEL;
1544 cl->query.i_channel = cl->p_buffer[1];
1545 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1546 cl->query.p_body = malloc( cl->query.i_body );
1548 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1551 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1552 * this is the maximum we can ask at this point. */
1553 if( cl->i_buffer >= 7 )
1555 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1557 cl->query.i_proto = HTTPD_PROTO_HTTP;
1558 cl->query.i_type = HTTPD_MSG_ANSWER;
1560 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1562 cl->query.i_proto = HTTPD_PROTO_RTSP;
1563 cl->query.i_type = HTTPD_MSG_ANSWER;
1567 /* We need the full request line to determine the protocol. */
1568 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1569 cl->query.i_type = HTTPD_MSG_NONE;
1573 else if( cl->query.i_body > 0 )
1575 /* we are reading the body of a request or a channel */
1576 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1577 cl->query.i_body - cl->i_buffer );
1580 cl->i_buffer += i_len;
1582 if( cl->i_buffer >= cl->query.i_body )
1584 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1589 /* we are reading a header -> char by char */
1592 if( cl->i_buffer == cl->i_buffer_size )
1594 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1595 if( newbuf == NULL )
1601 cl->p_buffer = newbuf;
1602 cl->i_buffer_size += 1024;
1605 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1612 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1613 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1615 /* Request line is now complete */
1616 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1619 assert( cl->query.i_type == HTTPD_MSG_NONE );
1621 if( p == NULL ) /* no URI: evil guy */
1623 i_len = 0; /* drop connection */
1628 p++; /* skips extra spaces */
1631 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1632 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1634 i_len = 0; /* not supported currently -> drop */
1639 p++; /* skips extra spaces ever again */
1642 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1643 if( len < 7 ) /* foreign protocol */
1644 i_len = 0; /* I don't understand -> drop */
1646 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1648 cl->query.i_proto = HTTPD_PROTO_HTTP;
1649 cl->query.i_version = atoi( p + 7 );
1652 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1654 cl->query.i_proto = HTTPD_PROTO_RTSP;
1655 cl->query.i_version = atoi( p + 7 );
1658 if( memcmp( p, "HTTP/", 5 ) == 0 )
1660 const uint8_t sorry[] =
1661 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1662 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1663 i_len = 0; /* drop */
1666 if( memcmp( p, "RTSP/", 5 ) == 0 )
1668 const uint8_t sorry[] =
1669 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1670 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1671 i_len = 0; /* drop */
1673 else /* yet another foreign protocol */
1680 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1681 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1685 /* we have finished the header so parse it and set i_body */
1686 cl->p_buffer[cl->i_buffer] = '\0';
1688 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1691 * assume strlen( "HTTP/1.x" ) = 8
1693 cl->query.i_status =
1694 strtol( (char *)&cl->p_buffer[8],
1704 cl->query.i_type = HTTPD_MSG_NONE;
1706 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1708 for( i = 0; msg_type[i].name[0]; i++ )
1710 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1711 strlen( msg_type[i].name ) ) )
1713 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1714 cl->query.i_type = msg_type[i].i_type;
1715 if( cl->query.i_proto != msg_type[i].i_proto )
1718 cl->query.i_proto = HTTPD_PROTO_NONE;
1719 cl->query.i_type = HTTPD_MSG_NONE;
1726 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1728 cl->query.i_proto = HTTPD_PROTO_HTTP;
1730 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1732 cl->query.i_proto = HTTPD_PROTO_RTSP;
1744 p2 = strchr( p, ' ' );
1749 if( !strncasecmp( p, ( cl->query.i_proto
1750 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1751 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1752 { /* Skip hier-part of URL (if present) */
1753 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1754 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1755 { /* see RFC3986 §3.2 */
1757 while( *p && !strchr( "/?#", *p ) ) p++;
1760 cl->query.psz_url = strdup( p );
1761 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1764 cl->query.psz_args = (uint8_t *)strdup( p3 );
1771 p = strchr( p, '\n' );
1775 while( *p == '\n' || *p == '\r' )
1779 while( p && *p != '\0' )
1782 char *eol = p = strchr( p, '\n' );
1785 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1790 if( ( colon = strchr( line, ':' ) ) )
1796 while( *colon == ' ' )
1800 name = strdup( line );
1801 value = strdup( colon );
1803 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1804 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1806 if( !strcasecmp( name, "Content-Length" ) )
1808 cl->query.i_body = atol( value );
1815 while( *p == '\n' || *p == '\r' )
1822 if( cl->query.i_body > 0 )
1824 /* TODO Mhh, handle the case client will only send a
1825 * request and close the connection
1826 * to mark and of body (probably only RTSP) */
1827 cl->query.p_body = malloc( cl->query.i_body );
1832 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1838 /* check if the client is to be set to dead */
1839 #if defined( WIN32 ) || defined( UNDER_CE )
1840 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1842 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1845 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1847 /* connection closed -> end of data */
1848 if( cl->query.i_body > 0 )
1850 cl->query.i_body = cl->i_buffer;
1852 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1856 cl->i_state = HTTPD_CLIENT_DEAD;
1860 /* XXX: for QT I have to disable timeout. Try to find why */
1861 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1862 cl->i_activity_timeout = 0;
1864 #if 0 /* Debugging only */
1865 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1869 fprintf( stderr, "received new request\n" );
1870 fprintf( stderr, " - proto=%s\n",
1871 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1872 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1873 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1874 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1876 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1877 cl->query.psz_status );
1879 else if( cl->query.i_type != HTTPD_MSG_NONE )
1881 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1883 for( i = 0; i < cl->query.i_name; i++ )
1885 fprintf( stderr, " - option name='%s' value='%s'\n",
1886 cl->query.name[i], cl->query.value[i] );
1892 static void httpd_ClientSend( httpd_client_t *cl )
1897 if( cl->i_buffer < 0 )
1899 /* We need to create the header */
1902 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1904 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1905 for( i = 0; i < cl->answer.i_name; i++ )
1907 i_size += strlen( cl->answer.name[i] ) + 2 +
1908 strlen( cl->answer.value[i] ) + 2;
1911 if( cl->i_buffer_size < i_size )
1913 cl->i_buffer_size = i_size;
1914 free( cl->p_buffer );
1915 cl->p_buffer = malloc( i_size );
1917 p = (char *)cl->p_buffer;
1919 p += sprintf( p, "%s.%u %d %s\r\n",
1920 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1921 cl->answer.i_version,
1922 cl->answer.i_status, psz_status );
1923 for( i = 0; i < cl->answer.i_name; i++ )
1925 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1926 cl->answer.value[i] );
1928 p += sprintf( p, "\r\n" );
1931 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1933 /*fprintf( stderr, "sending answer\n" );
1934 fprintf( stderr, "%s", cl->p_buffer );*/
1937 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1938 cl->i_buffer_size - cl->i_buffer );
1941 cl->i_buffer += i_len;
1943 if( cl->i_buffer >= cl->i_buffer_size )
1945 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1946 !cl->b_read_waiting )
1948 /* catch more body data */
1949 int i_msg = cl->query.i_type;
1950 int64_t i_offset = cl->answer.i_body_offset;
1952 httpd_MsgClean( &cl->answer );
1953 cl->answer.i_body_offset = i_offset;
1955 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1956 &cl->answer, &cl->query );
1959 if( cl->answer.i_body > 0 )
1961 /* send the body data */
1962 free( cl->p_buffer );
1963 cl->p_buffer = cl->answer.p_body;
1964 cl->i_buffer_size = cl->answer.i_body;
1967 cl->answer.i_body = 0;
1968 cl->answer.p_body = NULL;
1973 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1979 #if defined( WIN32 ) || defined( UNDER_CE )
1980 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1982 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1986 cl->i_state = HTTPD_CLIENT_DEAD;
1991 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1993 switch( tls_SessionContinueHandshake( cl->p_tls ) )
1996 cl->i_state = HTTPD_CLIENT_RECEIVING;
2000 cl->i_state = HTTPD_CLIENT_DEAD;
2005 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2009 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2011 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2014 cl->i_state = HTTPD_CLIENT_RECEIVING;
2018 cl->i_state = HTTPD_CLIENT_DEAD;
2023 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2028 static void* httpd_HostThread( vlc_object_t *p_this )
2030 httpd_host_t *host = (httpd_host_t *)p_this;
2031 tls_session_t *p_tls = NULL;
2032 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2033 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2036 int canc = vlc_savecancel ();
2039 vlc_object_lock( host );
2040 evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2041 b_die = !vlc_object_alive( host );
2042 vlc_object_unlock( host );
2046 if( host->i_url <= 0 )
2048 /* 0.2s (FIXME: use a condition variable) */
2053 /* prepare a new TLS session */
2054 if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2055 p_tls = tls_ServerSessionPrepare( host->p_tls );
2057 struct pollfd ufd[host->nfd + host->i_client + 1];
2059 for( nfd = 0; nfd < host->nfd; nfd++ )
2061 ufd[nfd].fd = host->fds[nfd];
2062 ufd[nfd].events = POLLIN;
2063 ufd[nfd].revents = 0;
2066 /* add all socket that should be read/write and close dead connection */
2067 vlc_mutex_lock( &host->lock );
2068 mtime_t now = mdate();
2069 bool b_low_delay = false;
2071 for(int i_client = 0; i_client < host->i_client; i_client++ )
2073 httpd_client_t *cl = host->client[i_client];
2074 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2075 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2076 ( cl->i_activity_timeout > 0 &&
2077 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2079 httpd_ClientClean( cl );
2080 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2081 TAB_REMOVE( host->i_client, host->client, cl );
2087 struct pollfd *pufd = ufd + nfd;
2088 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2091 pufd->events = pufd->revents = 0;
2093 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2094 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2096 pufd->events = POLLIN;
2098 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2099 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2101 pufd->events = POLLOUT;
2103 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2105 httpd_message_t *answer = &cl->answer;
2106 httpd_message_t *query = &cl->query;
2107 int i_msg = query->i_type;
2109 httpd_MsgInit( answer );
2111 /* Handle what we received */
2112 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2113 (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2115 /* we can only receive request from client when not
2118 cl->i_state = HTTPD_CLIENT_DEAD;
2120 else if( i_msg == HTTPD_MSG_ANSWER )
2122 /* We are in BIDIR mode, trigger the callback and then
2123 * check for new data */
2124 if( cl->url && cl->url->catch[i_msg].cb )
2126 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2129 cl->i_state = HTTPD_CLIENT_WAITING;
2131 else if( i_msg == HTTPD_MSG_CHANNEL )
2133 /* We are in BIDIR mode, trigger the callback and then
2134 * check for new data */
2135 if( cl->url && cl->url->catch[i_msg].cb )
2137 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2140 cl->i_state = HTTPD_CLIENT_WAITING;
2142 else if( i_msg == HTTPD_MSG_OPTIONS )
2145 answer->i_type = HTTPD_MSG_ANSWER;
2146 answer->i_proto = query->i_proto;
2147 answer->i_status = 200;
2149 answer->p_body = NULL;
2151 httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2152 httpd_MsgAdd( answer, "Content-Length", "0" );
2154 switch( query->i_proto )
2156 case HTTPD_PROTO_HTTP:
2157 answer->i_version = 1;
2158 httpd_MsgAdd( answer, "Allow",
2159 "GET,HEAD,POST,OPTIONS" );
2162 case HTTPD_PROTO_RTSP:
2165 answer->i_version = 0;
2167 p = httpd_MsgGet( query, "Cseq" );
2169 httpd_MsgAdd( answer, "Cseq", "%s", p );
2170 p = httpd_MsgGet( query, "Timestamp" );
2172 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2174 p = httpd_MsgGet( query, "Require" );
2177 answer->i_status = 551;
2178 httpd_MsgAdd( query, "Unsupported", "%s", p );
2181 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2182 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2187 cl->i_buffer = -1; /* Force the creation of the answer in
2188 * httpd_ClientSend */
2189 cl->i_state = HTTPD_CLIENT_SENDING;
2191 else if( i_msg == HTTPD_MSG_NONE )
2193 if( query->i_proto == HTTPD_PROTO_NONE )
2196 cl->i_state = HTTPD_CLIENT_DEAD;
2203 answer->i_proto = query->i_proto ;
2204 answer->i_type = HTTPD_MSG_ANSWER;
2205 answer->i_version= 0;
2206 answer->i_status = 501;
2208 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2209 answer->p_body = (uint8_t *)p;
2210 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2212 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2213 cl->i_state = HTTPD_CLIENT_SENDING;
2218 bool b_auth_failed = false;
2219 bool b_hosts_failed = false;
2221 /* Search the url and trigger callbacks */
2222 for(int i = 0; i < host->i_url; i++ )
2224 httpd_url_t *url = host->url[i];
2226 if( !strcmp( url->psz_url, query->psz_url ) )
2228 if( url->catch[i_msg].cb )
2230 if( answer && ( url->p_acl != NULL ) )
2232 char ip[NI_MAXNUMERICHOST];
2234 if( ( httpd_ClientIP( cl, ip ) == NULL )
2235 || ACL_Check( url->p_acl, ip ) )
2237 b_hosts_failed = true;
2242 if( answer && ( *url->psz_user || *url->psz_password ) )
2244 /* create the headers */
2245 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2246 char *user = NULL, *pass = NULL;
2249 && !strncasecmp( b64, "BASIC", 5 ) )
2252 while( *b64 == ' ' )
2255 user = vlc_b64_decode( b64 );
2258 pass = strchr (user, ':');
2264 if ((user == NULL) || (pass == NULL)
2265 || strcmp (user, url->psz_user)
2266 || strcmp (pass, url->psz_password))
2268 httpd_MsgAdd( answer,
2270 "Basic realm=\"%s\"",
2272 /* We fail for all url */
2273 b_auth_failed = true;
2281 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2283 if( answer->i_proto == HTTPD_PROTO_NONE )
2285 /* Raw answer from a CGI */
2286 cl->i_buffer = cl->i_buffer_size;
2291 /* only one url can answer */
2293 if( cl->url == NULL )
2306 answer->i_proto = query->i_proto;
2307 answer->i_type = HTTPD_MSG_ANSWER;
2308 answer->i_version= 0;
2310 if( b_hosts_failed )
2312 answer->i_status = 403;
2314 else if( b_auth_failed )
2316 answer->i_status = 401;
2320 /* no url registered */
2321 answer->i_status = 404;
2324 answer->i_body = httpd_HtmlError (&p,
2327 answer->p_body = (uint8_t *)p;
2329 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2330 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2331 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2334 cl->i_state = HTTPD_CLIENT_SENDING;
2337 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2339 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2341 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2342 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2343 bool b_connection = false;
2344 bool b_keepalive = false;
2345 bool b_query = false;
2348 if( psz_connection )
2350 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2351 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2356 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2359 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2360 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2361 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2362 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2363 !b_query && !b_connection ) )
2365 httpd_MsgClean( &cl->query );
2366 httpd_MsgInit( &cl->query );
2369 cl->i_buffer_size = 1000;
2370 free( cl->p_buffer );
2371 cl->p_buffer = malloc( cl->i_buffer_size );
2372 cl->i_state = HTTPD_CLIENT_RECEIVING;
2376 cl->i_state = HTTPD_CLIENT_DEAD;
2378 httpd_MsgClean( &cl->answer );
2380 else if( cl->b_read_waiting )
2382 /* we have a message waiting for us to read it */
2383 httpd_MsgClean( &cl->answer );
2384 httpd_MsgClean( &cl->query );
2387 cl->i_buffer_size = 1000;
2388 free( cl->p_buffer );
2389 cl->p_buffer = malloc( cl->i_buffer_size );
2390 cl->i_state = HTTPD_CLIENT_RECEIVING;
2391 cl->b_read_waiting = false;
2395 int64_t i_offset = cl->answer.i_body_offset;
2396 httpd_MsgClean( &cl->answer );
2398 cl->answer.i_body_offset = i_offset;
2399 free( cl->p_buffer );
2400 cl->p_buffer = NULL;
2402 cl->i_buffer_size = 0;
2404 cl->i_state = HTTPD_CLIENT_WAITING;
2407 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2409 int64_t i_offset = cl->answer.i_body_offset;
2410 int i_msg = cl->query.i_type;
2412 httpd_MsgInit( &cl->answer );
2413 cl->answer.i_body_offset = i_offset;
2415 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2416 &cl->answer, &cl->query );
2417 if( cl->answer.i_type != HTTPD_MSG_NONE )
2419 /* we have new data, so re-enter send mode */
2421 cl->p_buffer = cl->answer.p_body;
2422 cl->i_buffer_size = cl->answer.i_body;
2423 cl->answer.p_body = NULL;
2424 cl->answer.i_body = 0;
2425 cl->i_state = HTTPD_CLIENT_SENDING;
2429 /* Special for BIDIR mode we also check reading */
2430 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2431 cl->i_state == HTTPD_CLIENT_SENDING )
2433 pufd->events |= POLLIN;
2436 if (pufd->events != 0)
2441 vlc_mutex_unlock( &host->lock );
2444 ufd[nfd].events = POLLIN;
2445 ufd[nfd].revents = 0;
2448 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2449 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2454 /* Kernel on low memory or a bug: pace */
2455 msg_Err( host, "polling error: %m" );
2462 vlc_object_lock( host );
2463 if( ufd[nfd - 1].revents )
2465 b_die = !vlc_object_alive( host );
2467 vlc_object_wait( host );
2469 vlc_object_unlock( host );
2471 /* Handle client sockets */
2472 vlc_mutex_lock( &host->lock );
2475 for( int i_client = 0; i_client < host->i_client; i_client++ )
2477 httpd_client_t *cl = host->client[i_client];
2478 const struct pollfd *pufd = &ufd[nfd];
2480 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2482 if( cl->fd != pufd->fd )
2483 continue; // we were not waiting for this client
2485 if( pufd->revents == 0 )
2486 continue; // no event received
2488 cl->i_activity_date = now;
2490 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2492 httpd_ClientRecv( cl );
2494 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2496 httpd_ClientSend( cl );
2498 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2500 httpd_ClientTlsHsIn( cl );
2502 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2504 httpd_ClientTlsHsOut( cl );
2507 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2508 cl->i_state == HTTPD_CLIENT_SENDING &&
2509 (pufd->revents & POLLIN) )
2511 cl->b_read_waiting = true;
2514 vlc_mutex_unlock( &host->lock );
2516 /* Handle server sockets (accept new connections) */
2517 for( nfd = 0; nfd < host->nfd; nfd++ )
2521 int fd = ufd[nfd].fd;
2523 assert (fd == host->fds[nfd]);
2525 if( ufd[nfd].revents == 0 )
2529 fd = accept (fd, NULL, NULL);
2533 net_SetupSocket (fd);
2536 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2539 msg_Err( host, "Rejecting TLS connection" );
2545 case 1: /* missing input - most likely */
2546 i_state = HTTPD_CLIENT_TLS_HS_IN;
2549 case 2: /* missing output */
2550 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2554 if( (p_tls == NULL) != (host->p_tls == NULL) )
2555 break; // wasted TLS session, cannot accept() anymore
2558 stats_UpdateInteger( host, p_total_counter, 1, NULL );
2559 stats_UpdateInteger( host, p_active_counter, 1, NULL );
2560 cl = httpd_ClientNew( fd, p_tls, now );
2562 vlc_mutex_lock( &host->lock );
2563 TAB_APPEND( host->i_client, host->client, cl );
2564 vlc_mutex_unlock( &host->lock );
2566 cl->i_state = i_state; // override state for TLS
2568 if (host->p_tls != NULL)
2569 break; // cannot accept further without new TLS session
2575 tls_ServerSessionClose( p_tls );
2576 if( p_total_counter )
2577 stats_CounterClean( p_total_counter );
2578 if( p_active_counter )
2579 stats_CounterClean( p_active_counter );
2580 vlc_restorecancel (canc);