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 */
102 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
103 * This will slow down the url research but make my live easier
104 * All url will have their cb trigger, but only the first one can answer
110 httpd_client_t **client;
131 httpd_callback_sys_t *p_sys;
132 } catch[HTTPD_MSG_MAX];
138 HTTPD_CLIENT_RECEIVING,
139 HTTPD_CLIENT_RECEIVE_DONE,
141 HTTPD_CLIENT_SENDING,
142 HTTPD_CLIENT_SEND_DONE,
144 HTTPD_CLIENT_WAITING,
148 HTTPD_CLIENT_TLS_HS_IN,
149 HTTPD_CLIENT_TLS_HS_OUT
155 HTTPD_CLIENT_FILE, /* default */
156 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
157 HTTPD_CLIENT_BIDIR, /* check for reading and get data from cb */
160 struct httpd_client_t
170 int b_read_waiting; /* stop as soon as possible sending */
172 mtime_t i_activity_date;
173 mtime_t i_activity_timeout;
175 /* buffer for reading header */
181 httpd_message_t query; /* client -> httpd */
182 httpd_message_t answer; /* httpd -> client */
185 tls_session_t *p_tls;
189 /*****************************************************************************
191 *****************************************************************************/
194 const char psz_ext[8];
195 const char *psz_mime;
198 { ".htm", "text/html" },
199 { ".html", "text/html" },
200 { ".txt", "text/plain" },
201 { ".xml", "text/xml" },
202 { ".dtd", "text/dtd" },
204 { ".css", "text/css" },
207 { ".gif", "image/gif" },
208 { ".jpe", "image/jpeg" },
209 { ".jpg", "image/jpeg" },
210 { ".jpeg", "image/jpeg" },
211 { ".png", "image/png" },
212 /* same as modules/mux/mpjpeg.c here: */
213 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
216 { ".avi", "video/avi" },
217 { ".asf", "video/x-ms-asf" },
218 { ".m1a", "audio/mpeg" },
219 { ".m2a", "audio/mpeg" },
220 { ".m1v", "video/mpeg" },
221 { ".m2v", "video/mpeg" },
222 { ".mp2", "audio/mpeg" },
223 { ".mp3", "audio/mpeg" },
224 { ".mpa", "audio/mpeg" },
225 { ".mpg", "video/mpeg" },
226 { ".mpeg", "video/mpeg" },
227 { ".mpe", "video/mpeg" },
228 { ".mov", "video/quicktime" },
229 { ".moov", "video/quicktime" },
230 { ".oga", "audio/ogg" },
231 { ".ogg", "application/ogg" },
232 { ".ogm", "application/ogg" },
233 { ".ogv", "video/ogg" },
234 { ".ogx", "application/ogg" },
235 { ".spx", "audio/ogg" },
236 { ".wav", "audio/wav" },
237 { ".wma", "audio/x-ms-wma" },
238 { ".wmv", "video/x-ms-wmv" },
245 static const char *httpd_MimeFromUrl( const char *psz_url )
250 psz_ext = strrchr( psz_url, '.' );
255 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
257 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
259 return http_mime[i].psz_mime;
263 return "application/octet-stream";
270 const char psz_reason[36];
273 static const http_status_info http_reason[] =
275 /*{ 100, "Continue" },
276 { 101, "Switching Protocols" },*/
278 /*{ 201, "Created" },
280 { 203, "Non-authoritative information" },
281 { 204, "No content" },
282 { 205, "Reset content" },
283 { 206, "Partial content" },
284 { 250, "Low on storage space" },
285 { 300, "Multiple choices" },*/
286 { 301, "Moved permanently" },
287 /*{ 302, "Moved temporarily" },
288 { 303, "See other" },
289 { 304, "Not modified" },
290 { 305, "Use proxy" },
291 { 307, "Temporary redirect" },
292 { 400, "Bad request" },*/
293 { 401, "Unauthorized" },
294 /*{ 402, "Payment Required" },*/
295 { 403, "Forbidden" },
296 { 404, "Not found" },
297 { 405, "Method not allowed" },
298 /*{ 406, "Not acceptable" },
299 { 407, "Proxy authentication required" },
300 { 408, "Request time-out" },
303 { 411, "Length required" },
304 { 412, "Precondition failed" },
305 { 413, "Request entity too large" },
306 { 414, "Request-URI too large" },
307 { 415, "Unsupported media Type" },
308 { 416, "Requested range not satisfiable" },
309 { 417, "Expectation failed" },
310 { 451, "Parameter not understood" },
311 { 452, "Conference not found" },
312 { 453, "Not enough bandwidth" },*/
313 { 454, "Session not found" },
314 /*{ 455, "Method not valid in this State" },*/
315 { 456, "Header field not valid for resource" },
316 /*{ 457, "Invalid range" },
317 { 458, "Read-only parameter" },*/
318 { 459, "Aggregate operation not allowed" },
319 { 460, "Non-aggregate operation not allowed" },
320 { 461, "Unsupported transport" },
321 /*{ 462, "Destination unreachable" },*/
322 { 500, "Internal server error" },
323 { 501, "Not implemented" },
324 /*{ 502, "Bad gateway" },*/
325 { 503, "Service unavailable" },
326 /*{ 504, "Gateway time-out" },*/
327 { 505, "Protocol version not supported" },
328 { 551, "Option not supported" },
332 static const char psz_fallback_reason[5][16] =
333 { "Continue", "OK", "Found", "Client error", "Server error" };
335 static const char *httpd_ReasonFromCode( unsigned i_code )
337 const http_status_info *p;
339 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
341 for (p = http_reason; i_code > p->i_code; p++);
343 if( p->i_code == i_code )
344 return p->psz_reason;
346 return psz_fallback_reason[(i_code / 100) - 1];
350 static size_t httpd_HtmlError (char **body, int code, const char *url)
352 const char *errname = httpd_ReasonFromCode (code);
353 assert (errname != NULL);
355 int res = asprintf (body,
356 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
357 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
358 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
359 "<html lang=\"en\">\n"
361 "<title>%s</title>\n"
364 "<h1>%d %s%s%s%s</h1>\n"
366 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
368 "</html>\n", errname, code, errname,
369 (url ? " (" : ""), (url ?: ""), (url ? ")" : ""));
381 /*****************************************************************************
382 * High Level Functions: httpd_file_t
383 *****************************************************************************/
391 httpd_file_callback_t pf_fill;
392 httpd_file_sys_t *p_sys;
397 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
398 httpd_message_t *answer, const httpd_message_t *query )
400 httpd_file_t *file = (httpd_file_t*)p_sys;
401 uint8_t **pp_body, *p_body;
402 const char *psz_connection;
403 int *pi_body, i_body;
405 if( answer == NULL || query == NULL )
409 answer->i_proto = HTTPD_PROTO_HTTP;
410 answer->i_version= 1;
411 answer->i_type = HTTPD_MSG_ANSWER;
413 answer->i_status = 200;
415 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
416 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
418 if( query->i_type != HTTPD_MSG_HEAD )
420 pp_body = &answer->p_body;
421 pi_body = &answer->i_body;
425 /* The file still needs to be executed. */
432 if( query->i_type == HTTPD_MSG_POST )
434 /* msg_Warn not supported */
437 uint8_t *psz_args = query->psz_args;
438 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
440 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
445 /* We respect client request */
446 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
447 if( psz_connection != NULL )
449 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
452 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
457 httpd_file_t *httpd_FileNew( httpd_host_t *host,
458 const char *psz_url, const char *psz_mime,
459 const char *psz_user, const char *psz_password,
460 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
461 httpd_file_sys_t *p_sys )
463 httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
465 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
466 psz_password, p_acl )
473 file->psz_url = strdup( psz_url );
474 if( psz_mime && *psz_mime )
476 file->psz_mime = strdup( psz_mime );
480 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
483 file->pf_fill = pf_fill;
486 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
487 (httpd_callback_sys_t*)file );
488 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
489 (httpd_callback_sys_t*)file );
490 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
491 (httpd_callback_sys_t*)file );
496 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
498 httpd_file_sys_t *p_sys = file->p_sys;
500 httpd_UrlDelete( file->url );
502 free( file->psz_url );
503 free( file->psz_mime );
510 /*****************************************************************************
511 * High Level Functions: httpd_handler_t (for CGIs)
512 *****************************************************************************/
513 struct httpd_handler_t
517 httpd_handler_callback_t pf_fill;
518 httpd_handler_sys_t *p_sys;
523 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
524 httpd_message_t *answer, const httpd_message_t *query )
526 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
527 char psz_remote_addr[NI_MAXNUMERICHOST];
529 if( answer == NULL || query == NULL )
533 answer->i_proto = HTTPD_PROTO_NONE;
534 answer->i_type = HTTPD_MSG_ANSWER;
536 /* We do it ourselves, thanks */
537 answer->i_status = 0;
539 if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
540 *psz_remote_addr = '\0';
542 uint8_t *psz_args = query->psz_args;
543 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
544 query->i_type, query->p_body, query->i_body,
545 psz_remote_addr, NULL,
546 &answer->p_body, &answer->i_body );
548 if( query->i_type == HTTPD_MSG_HEAD )
550 char *p = (char *)answer->p_body;
552 /* Looks for end of header (i.e. one empty line) */
553 while ( (p = strchr( p, '\r' )) != NULL )
555 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
556 && p[3] && p[3] == '\n' )
565 answer->i_body = strlen((char*)answer->p_body) + 1;
566 answer->p_body = realloc( answer->p_body, answer->i_body );
570 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
572 int i_status, i_headers;
573 char *psz_headers, *psz_new;
574 const char *psz_status;
576 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
579 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
580 if( *psz_headers ) psz_headers++;
581 if( *psz_headers ) psz_headers++;
582 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
587 psz_headers = (char *)answer->p_body;
588 i_headers = answer->i_body;
591 psz_status = httpd_ReasonFromCode( i_status );
592 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
593 + strlen(psz_status) + i_headers - 1;
594 psz_new = (char *)malloc( answer->i_body + 1);
595 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
596 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
597 free( answer->p_body );
598 answer->p_body = (uint8_t *)psz_new;
604 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
605 const char *psz_user,
606 const char *psz_password,
607 const vlc_acl_t *p_acl,
608 httpd_handler_callback_t pf_fill,
609 httpd_handler_sys_t *p_sys )
611 httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
613 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
614 psz_password, p_acl )
621 handler->pf_fill = pf_fill;
622 handler->p_sys = p_sys;
624 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
625 (httpd_callback_sys_t*)handler );
626 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
627 (httpd_callback_sys_t*)handler );
628 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
629 (httpd_callback_sys_t*)handler );
634 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
636 httpd_handler_sys_t *p_sys = handler->p_sys;
637 httpd_UrlDelete( handler->url );
642 /*****************************************************************************
643 * High Level Functions: httpd_redirect_t
644 *****************************************************************************/
645 struct httpd_redirect_t
651 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
652 httpd_client_t *cl, httpd_message_t *answer,
653 const httpd_message_t *query )
655 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
659 if( answer == NULL || query == NULL )
663 answer->i_proto = HTTPD_PROTO_HTTP;
664 answer->i_version= 1;
665 answer->i_type = HTTPD_MSG_ANSWER;
666 answer->i_status = 301;
668 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
669 answer->p_body = (unsigned char *)p_body;
671 /* XXX check if it's ok or we need to set an absolute url */
672 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
674 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
679 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
680 const char *psz_url_src )
682 httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
684 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
689 rdir->psz_dst = strdup( psz_url_dst );
691 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
692 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
693 (httpd_callback_sys_t*)rdir );
694 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
695 (httpd_callback_sys_t*)rdir );
696 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
697 (httpd_callback_sys_t*)rdir );
698 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
699 (httpd_callback_sys_t*)rdir );
703 void httpd_RedirectDelete( httpd_redirect_t *rdir )
705 httpd_UrlDelete( rdir->url );
706 free( rdir->psz_dst );
710 /*****************************************************************************
711 * High Level Funtions: httpd_stream_t
712 *****************************************************************************/
713 struct httpd_stream_t
720 /* Header to send as first packet */
724 /* circular buffer */
725 int i_buffer_size; /* buffer size, can't be reallocated smaller */
726 uint8_t *p_buffer; /* buffer */
727 int64_t i_buffer_pos; /* absolute position from begining */
728 int64_t i_buffer_last_pos; /* a new connection will start with that */
731 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
732 httpd_client_t *cl, httpd_message_t *answer,
733 const httpd_message_t *query )
735 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
737 if( answer == NULL || query == NULL || cl == NULL )
742 if( answer->i_body_offset > 0 )
748 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
749 answer->i_body_offset );
752 if( answer->i_body_offset >= stream->i_buffer_pos )
754 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
755 return VLC_EGENERIC; /* wait, no data available */
757 if( answer->i_body_offset + stream->i_buffer_size <
758 stream->i_buffer_pos )
760 /* this client isn't fast enough */
762 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
763 answer->i_body_offset, stream->i_buffer_last_pos );
765 answer->i_body_offset = stream->i_buffer_last_pos;
768 i_pos = answer->i_body_offset % stream->i_buffer_size;
769 i_write = stream->i_buffer_pos - answer->i_body_offset;
770 if( i_write > HTTPD_CL_BUFSIZE )
772 i_write = HTTPD_CL_BUFSIZE;
774 else if( i_write <= 0 )
776 return VLC_EGENERIC; /* wait, no data available */
779 /* Don't go past the end of the circular buffer */
780 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
782 /* using HTTPD_MSG_ANSWER -> data available */
783 answer->i_proto = HTTPD_PROTO_HTTP;
784 answer->i_version= 0;
785 answer->i_type = HTTPD_MSG_ANSWER;
787 answer->i_body = i_write;
788 answer->p_body = malloc( i_write );
789 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
791 answer->i_body_offset += i_write;
797 answer->i_proto = HTTPD_PROTO_HTTP;
798 answer->i_version= 0;
799 answer->i_type = HTTPD_MSG_ANSWER;
801 answer->i_status = 200;
803 if( query->i_type != HTTPD_MSG_HEAD )
805 httpd_ClientModeStream( cl );
806 vlc_mutex_lock( &stream->lock );
807 /* Send the header */
808 if( stream->i_header > 0 )
810 answer->i_body = stream->i_header;
811 answer->p_body = malloc( stream->i_header );
812 memcpy( answer->p_body, stream->p_header, stream->i_header );
814 answer->i_body_offset = stream->i_buffer_last_pos;
815 vlc_mutex_unlock( &stream->lock );
819 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
820 answer->i_body_offset = 0;
823 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
825 bool b_xplaystream = false;
828 httpd_MsgAdd( answer, "Content-type", "%s",
829 "application/octet-stream" );
830 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
831 httpd_MsgAdd( answer, "Pragma", "no-cache" );
832 httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
833 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
835 /* Check if there is a xPlayStrm=1 */
836 for( i = 0; i < query->i_name; i++ )
838 if( !strcasecmp( query->name[i], "Pragma" ) &&
839 strstr( query->value[i], "xPlayStrm=1" ) )
841 b_xplaystream = true;
847 answer->i_body_offset = 0;
852 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
854 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
859 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
860 const char *psz_url, const char *psz_mime,
861 const char *psz_user, const char *psz_password,
862 const vlc_acl_t *p_acl )
864 httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
866 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
867 psz_password, p_acl )
873 vlc_mutex_init( &stream->lock );
874 if( psz_mime && *psz_mime )
876 stream->psz_mime = strdup( psz_mime );
880 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
882 stream->i_header = 0;
883 stream->p_header = NULL;
884 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
885 stream->p_buffer = malloc( stream->i_buffer_size );
886 /* We set to 1 to make life simpler
887 * (this way i_body_offset can never be 0) */
888 stream->i_buffer_pos = 1;
889 stream->i_buffer_last_pos = 1;
891 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
892 (httpd_callback_sys_t*)stream );
893 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
894 (httpd_callback_sys_t*)stream );
895 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
896 (httpd_callback_sys_t*)stream );
901 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
903 vlc_mutex_lock( &stream->lock );
904 free( stream->p_header );
905 stream->p_header = NULL;
907 stream->i_header = i_data;
910 stream->p_header = malloc( i_data );
911 memcpy( stream->p_header, p_data, i_data );
913 vlc_mutex_unlock( &stream->lock );
918 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
923 if( i_data < 0 || p_data == NULL )
927 vlc_mutex_lock( &stream->lock );
929 /* save this pointer (to be used by new connection) */
930 stream->i_buffer_last_pos = stream->i_buffer_pos;
932 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
938 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
940 /* Ok, we can't go past the end of our buffer */
941 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
943 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
948 stream->i_buffer_pos += i_data;
950 vlc_mutex_unlock( &stream->lock );
954 void httpd_StreamDelete( httpd_stream_t *stream )
956 httpd_UrlDelete( stream->url );
957 vlc_mutex_destroy( &stream->lock );
958 free( stream->psz_mime );
959 free( stream->p_header );
960 free( stream->p_buffer );
964 /*****************************************************************************
966 *****************************************************************************/
967 static void* httpd_HostThread( void * );
969 /* create a new host */
970 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
973 return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
977 static const char psz_object_type[] = "http server";
979 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
981 const char *psz_cert, const char *psz_key,
982 const char *psz_ca, const char *psz_crl )
988 vlc_value_t lockval, ptrval;
991 if( psz_hostname == NULL )
994 psz_host = strdup( psz_hostname );
995 if( psz_host == NULL )
998 /* to be sure to avoid multiple creation */
999 var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
1000 var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
1001 vlc_mutex_lock( lockval.p_address );
1002 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1006 msg_Info( p_this, "creating httpd" );
1007 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1012 vlc_mutex_unlock( lockval.p_address );
1020 ptrval.p_address = httpd;
1021 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1022 vlc_object_hold( httpd );
1023 vlc_object_attach( httpd, p_this->p_libvlc );
1026 /* verify if it already exist */
1027 for( i = httpd->i_host - 1; i >= 0; i-- )
1029 host = httpd->host[i];
1031 /* cannot mix TLS and non-TLS hosts */
1032 if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1033 || ( host->i_port != i_port )
1034 || strcmp( host->psz_hostname, psz_hostname ) )
1037 /* Increase existing matching host reference count.
1038 * The reference count is written under both the global httpd and the
1039 * host lock. It is read with either or both locks held. The global
1040 * lock is always acquired first. */
1041 vlc_mutex_lock( &host->lock );
1043 vlc_mutex_unlock( &host->lock );
1045 vlc_mutex_unlock( lockval.p_address );
1051 /* determine TLS configuration */
1052 if ( psz_cert != NULL )
1054 p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1055 if ( p_tls == NULL )
1057 msg_Err( p_this, "TLS initialization error" );
1061 if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1063 msg_Err( p_this, "TLS CA error" );
1067 if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1069 msg_Err( p_this, "TLS CRL error" );
1076 /* create the new host */
1077 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1083 host->httpd = httpd;
1084 vlc_mutex_init( &host->lock );
1085 vlc_cond_init( &host->wait );
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 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1098 msg_Err( host, "signaling pipe error: %m" );
1102 host->i_port = i_port;
1103 host->psz_hostname = psz_host;
1108 host->client = NULL;
1110 host->p_tls = p_tls;
1112 /* create the thread */
1113 if( vlc_clone( &host->thread, httpd_HostThread, host,
1114 VLC_THREAD_PRIORITY_LOW ) )
1116 msg_Err( p_this, "cannot spawn http host thread" );
1120 /* now add it to httpd */
1121 TAB_APPEND( httpd->i_host, httpd->host, host );
1122 vlc_mutex_unlock( lockval.p_address );
1128 if( httpd->i_host <= 0 )
1130 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1131 vlc_object_release( httpd );
1132 vlc_object_detach( httpd );
1133 vlc_object_release( httpd );
1135 vlc_mutex_unlock( lockval.p_address );
1139 net_ListenClose( host->fds );
1140 vlc_cond_destroy( &host->wait );
1141 vlc_mutex_destroy( &host->lock );
1142 vlc_object_release( host );
1146 tls_ServerDelete( p_tls );
1152 void httpd_HostDelete( httpd_host_t *host )
1154 httpd_t *httpd = host->httpd;
1155 vlc_value_t lockval;
1158 var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1159 vlc_mutex_lock( lockval.p_address );
1161 vlc_mutex_lock( &host->lock );
1163 if( host->i_ref == 0 )
1164 vlc_cond_signal( &host->wait );
1165 vlc_mutex_unlock( &host->lock );
1166 if( host->i_ref > 0 )
1169 vlc_mutex_unlock( lockval.p_address );
1170 msg_Dbg( host, "httpd_HostDelete: host still used" );
1173 TAB_REMOVE( httpd->i_host, httpd->host, host );
1175 vlc_object_kill( host );
1176 vlc_join( host->thread, NULL );
1178 msg_Dbg( host, "HTTP host removed" );
1180 for( i = 0; i < host->i_url; i++ )
1182 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1184 for( i = 0; i < host->i_client; i++ )
1186 httpd_client_t *cl = host->client[i];
1187 msg_Warn( host, "client still connected" );
1188 httpd_ClientClean( cl );
1189 TAB_REMOVE( host->i_client, host->client, cl );
1195 if( host->p_tls != NULL)
1196 tls_ServerDelete( host->p_tls );
1198 net_ListenClose( host->fds );
1199 free( host->psz_hostname );
1201 vlc_cond_destroy( &host->wait );
1202 vlc_mutex_destroy( &host->lock );
1203 vlc_object_release( host );
1205 vlc_object_release( httpd );
1206 if( httpd->i_host <= 0 )
1208 msg_Dbg( httpd, "no host left, stopping httpd" );
1210 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1211 vlc_object_detach( httpd );
1212 vlc_object_release( httpd );
1215 vlc_mutex_unlock( lockval.p_address );
1218 /* register a new url */
1219 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1220 const char *psz_user, const char *psz_password,
1221 const vlc_acl_t *p_acl, bool b_check )
1226 assert( psz_url != NULL );
1228 vlc_mutex_lock( &host->lock );
1231 for( i = 0; i < host->i_url; i++ )
1233 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1235 msg_Warn( host->httpd,
1236 "cannot add '%s' (url already defined)", psz_url );
1237 vlc_mutex_unlock( &host->lock );
1243 url = malloc( sizeof( httpd_url_t ) );
1246 vlc_mutex_init( &url->lock );
1247 url->psz_url = strdup( psz_url );
1248 url->psz_user = strdup( psz_user ? psz_user : "" );
1249 url->psz_password = strdup( psz_password ? psz_password : "" );
1250 url->p_acl = ACL_Duplicate( host, p_acl );
1251 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1253 url->catch[i].cb = NULL;
1254 url->catch[i].p_sys = NULL;
1257 TAB_APPEND( host->i_url, host->url, url );
1258 vlc_cond_signal( &host->wait );
1259 vlc_mutex_unlock( &host->lock );
1264 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1265 const char *psz_user, const char *psz_password,
1266 const vlc_acl_t *p_acl )
1268 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1269 psz_password, p_acl, false );
1272 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1273 const char *psz_user, const char *psz_password,
1274 const vlc_acl_t *p_acl )
1276 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1277 psz_password, p_acl, true );
1280 /* register callback on a url */
1281 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1282 httpd_callback_sys_t *p_sys )
1284 vlc_mutex_lock( &url->lock );
1285 url->catch[i_msg].cb = cb;
1286 url->catch[i_msg].p_sys= p_sys;
1287 vlc_mutex_unlock( &url->lock );
1293 void httpd_UrlDelete( httpd_url_t *url )
1295 httpd_host_t *host = url->host;
1298 vlc_mutex_lock( &host->lock );
1299 TAB_REMOVE( host->i_url, host->url, url );
1301 vlc_mutex_destroy( &url->lock );
1302 free( url->psz_url );
1303 free( url->psz_user );
1304 free( url->psz_password );
1305 ACL_Destroy( url->p_acl );
1307 for( i = 0; i < host->i_client; i++ )
1309 httpd_client_t *client = host->client[i];
1311 if( client->url == url )
1313 /* TODO complete it */
1314 msg_Warn( host, "force closing connections" );
1315 httpd_ClientClean( client );
1316 TAB_REMOVE( host->i_client, host->client, client );
1322 vlc_mutex_unlock( &host->lock );
1325 static void httpd_MsgInit( httpd_message_t *msg )
1328 msg->i_type = HTTPD_MSG_NONE;
1329 msg->i_proto = HTTPD_PROTO_NONE;
1330 msg->i_version = -1; /* FIXME */
1334 msg->psz_url = NULL;
1335 msg->psz_args = NULL;
1337 msg->i_channel = -1;
1344 msg->i_body_offset = 0;
1349 static void httpd_MsgClean( httpd_message_t *msg )
1353 free( msg->psz_url );
1354 free( msg->psz_args );
1355 for( i = 0; i < msg->i_name; i++ )
1357 free( msg->name[i] );
1358 free( msg->value[i] );
1362 free( msg->p_body );
1363 httpd_MsgInit( msg );
1366 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1370 for( i = 0; i < msg->i_name; i++ )
1372 if( !strcasecmp( msg->name[i], name ))
1374 return msg->value[i];
1380 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1385 va_start( args, psz_value );
1386 if( vasprintf( &value, psz_value, args ) == -1 )
1393 name = strdup( name );
1400 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1401 TAB_APPEND( msg->i_value, msg->value, value );
1404 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1406 cl->i_state = HTTPD_CLIENT_RECEIVING;
1407 cl->i_activity_date = now;
1408 cl->i_activity_timeout = INT64_C(10000000);
1409 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1411 cl->p_buffer = malloc( cl->i_buffer_size );
1412 cl->i_mode = HTTPD_CLIENT_FILE;
1413 cl->b_read_waiting = false;
1415 httpd_MsgInit( &cl->query );
1416 httpd_MsgInit( &cl->answer );
1419 void httpd_ClientModeStream( httpd_client_t *cl )
1421 cl->i_mode = HTTPD_CLIENT_STREAM;
1424 void httpd_ClientModeBidir( httpd_client_t *cl )
1426 cl->i_mode = HTTPD_CLIENT_BIDIR;
1429 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1431 return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1434 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1436 return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1439 static void httpd_ClientClean( httpd_client_t *cl )
1443 if( cl->p_tls != NULL )
1444 tls_ServerSessionClose( cl->p_tls );
1445 net_Close( cl->fd );
1449 httpd_MsgClean( &cl->answer );
1450 httpd_MsgClean( &cl->query );
1452 free( cl->p_buffer );
1453 cl->p_buffer = NULL;
1456 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1458 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1460 if( !cl ) return NULL;
1467 httpd_ClientInit( cl, now );
1473 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1475 tls_session_t *p_tls;
1480 val = p_tls ? tls_Recv (p_tls, p, i_len)
1481 : recv (cl->fd, p, i_len, 0);
1482 while (val == -1 && errno == EINTR);
1487 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1489 tls_session_t *p_tls;
1494 val = p_tls ? tls_Send( p_tls, p, i_len )
1495 : send (cl->fd, p, i_len, 0);
1496 while (val == -1 && errno == EINTR);
1503 const char name[16];
1509 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1510 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1511 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1512 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1513 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1514 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1515 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1516 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1517 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1518 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1519 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1523 static void httpd_ClientRecv( httpd_client_t *cl )
1527 /* ignore leading whites */
1528 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1529 ( cl->i_buffer == 0 ) )
1533 i_len = httpd_NetRecv( cl, &c, 1 );
1535 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1537 cl->p_buffer[0] = c;
1542 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1544 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1545 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1549 cl->i_buffer += i_len;
1552 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1554 /* Interleaved RTP over RTSP */
1555 cl->query.i_proto = HTTPD_PROTO_RTSP;
1556 cl->query.i_type = HTTPD_MSG_CHANNEL;
1557 cl->query.i_channel = cl->p_buffer[1];
1558 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1559 cl->query.p_body = malloc( cl->query.i_body );
1561 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1564 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1565 * this is the maximum we can ask at this point. */
1566 if( cl->i_buffer >= 7 )
1568 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1570 cl->query.i_proto = HTTPD_PROTO_HTTP;
1571 cl->query.i_type = HTTPD_MSG_ANSWER;
1573 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1575 cl->query.i_proto = HTTPD_PROTO_RTSP;
1576 cl->query.i_type = HTTPD_MSG_ANSWER;
1580 /* We need the full request line to determine the protocol. */
1581 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1582 cl->query.i_type = HTTPD_MSG_NONE;
1586 else if( cl->query.i_body > 0 )
1588 /* we are reading the body of a request or a channel */
1589 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1590 cl->query.i_body - cl->i_buffer );
1593 cl->i_buffer += i_len;
1595 if( cl->i_buffer >= cl->query.i_body )
1597 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1602 /* we are reading a header -> char by char */
1605 if( cl->i_buffer == cl->i_buffer_size )
1607 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1608 if( newbuf == NULL )
1614 cl->p_buffer = newbuf;
1615 cl->i_buffer_size += 1024;
1618 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1625 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1626 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1628 /* Request line is now complete */
1629 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1632 assert( cl->query.i_type == HTTPD_MSG_NONE );
1634 if( p == NULL ) /* no URI: evil guy */
1636 i_len = 0; /* drop connection */
1641 p++; /* skips extra spaces */
1644 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1645 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1647 i_len = 0; /* not supported currently -> drop */
1652 p++; /* skips extra spaces ever again */
1655 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1656 if( len < 7 ) /* foreign protocol */
1657 i_len = 0; /* I don't understand -> drop */
1659 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1661 cl->query.i_proto = HTTPD_PROTO_HTTP;
1662 cl->query.i_version = atoi( p + 7 );
1665 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1667 cl->query.i_proto = HTTPD_PROTO_RTSP;
1668 cl->query.i_version = atoi( p + 7 );
1671 if( memcmp( p, "HTTP/", 5 ) == 0 )
1673 const uint8_t sorry[] =
1674 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1675 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1676 i_len = 0; /* drop */
1679 if( memcmp( p, "RTSP/", 5 ) == 0 )
1681 const uint8_t sorry[] =
1682 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1683 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1684 i_len = 0; /* drop */
1686 else /* yet another foreign protocol */
1693 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1694 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1698 /* we have finished the header so parse it and set i_body */
1699 cl->p_buffer[cl->i_buffer] = '\0';
1701 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1704 * assume strlen( "HTTP/1.x" ) = 8
1706 cl->query.i_status =
1707 strtol( (char *)&cl->p_buffer[8],
1717 cl->query.i_type = HTTPD_MSG_NONE;
1719 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1721 for( i = 0; msg_type[i].name[0]; i++ )
1723 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1724 strlen( msg_type[i].name ) ) )
1726 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1727 cl->query.i_type = msg_type[i].i_type;
1728 if( cl->query.i_proto != msg_type[i].i_proto )
1731 cl->query.i_proto = HTTPD_PROTO_NONE;
1732 cl->query.i_type = HTTPD_MSG_NONE;
1739 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1741 cl->query.i_proto = HTTPD_PROTO_HTTP;
1743 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1745 cl->query.i_proto = HTTPD_PROTO_RTSP;
1757 p2 = strchr( p, ' ' );
1762 if( !strncasecmp( p, ( cl->query.i_proto
1763 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1764 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1765 { /* Skip hier-part of URL (if present) */
1766 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1767 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1768 { /* see RFC3986 §3.2 */
1770 while( *p && !strchr( "/?#", *p ) ) p++;
1773 cl->query.psz_url = strdup( p );
1774 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1777 cl->query.psz_args = (uint8_t *)strdup( p3 );
1784 p = strchr( p, '\n' );
1788 while( *p == '\n' || *p == '\r' )
1792 while( p && *p != '\0' )
1795 char *eol = p = strchr( p, '\n' );
1798 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1803 if( ( colon = strchr( line, ':' ) ) )
1809 while( *colon == ' ' )
1813 name = strdup( line );
1814 value = strdup( colon );
1816 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1817 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1819 if( !strcasecmp( name, "Content-Length" ) )
1821 cl->query.i_body = atol( value );
1828 while( *p == '\n' || *p == '\r' )
1835 if( cl->query.i_body > 0 )
1837 /* TODO Mhh, handle the case client will only send a
1838 * request and close the connection
1839 * to mark and of body (probably only RTSP) */
1840 cl->query.p_body = malloc( cl->query.i_body );
1845 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1851 /* check if the client is to be set to dead */
1852 #if defined( WIN32 ) || defined( UNDER_CE )
1853 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1855 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1858 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1860 /* connection closed -> end of data */
1861 if( cl->query.i_body > 0 )
1863 cl->query.i_body = cl->i_buffer;
1865 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1869 cl->i_state = HTTPD_CLIENT_DEAD;
1873 /* XXX: for QT I have to disable timeout. Try to find why */
1874 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1875 cl->i_activity_timeout = 0;
1877 #if 0 /* Debugging only */
1878 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1882 fprintf( stderr, "received new request\n" );
1883 fprintf( stderr, " - proto=%s\n",
1884 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1885 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1886 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1887 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1889 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1890 cl->query.psz_status );
1892 else if( cl->query.i_type != HTTPD_MSG_NONE )
1894 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1896 for( i = 0; i < cl->query.i_name; i++ )
1898 fprintf( stderr, " - option name='%s' value='%s'\n",
1899 cl->query.name[i], cl->query.value[i] );
1905 static void httpd_ClientSend( httpd_client_t *cl )
1910 if( cl->i_buffer < 0 )
1912 /* We need to create the header */
1915 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1917 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1918 for( i = 0; i < cl->answer.i_name; i++ )
1920 i_size += strlen( cl->answer.name[i] ) + 2 +
1921 strlen( cl->answer.value[i] ) + 2;
1924 if( cl->i_buffer_size < i_size )
1926 cl->i_buffer_size = i_size;
1927 free( cl->p_buffer );
1928 cl->p_buffer = malloc( i_size );
1930 p = (char *)cl->p_buffer;
1932 p += sprintf( p, "%s.%u %d %s\r\n",
1933 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1934 cl->answer.i_version,
1935 cl->answer.i_status, psz_status );
1936 for( i = 0; i < cl->answer.i_name; i++ )
1938 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1939 cl->answer.value[i] );
1941 p += sprintf( p, "\r\n" );
1944 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1946 /*fprintf( stderr, "sending answer\n" );
1947 fprintf( stderr, "%s", cl->p_buffer );*/
1950 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1951 cl->i_buffer_size - cl->i_buffer );
1954 cl->i_buffer += i_len;
1956 if( cl->i_buffer >= cl->i_buffer_size )
1958 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1959 !cl->b_read_waiting )
1961 /* catch more body data */
1962 int i_msg = cl->query.i_type;
1963 int64_t i_offset = cl->answer.i_body_offset;
1965 httpd_MsgClean( &cl->answer );
1966 cl->answer.i_body_offset = i_offset;
1968 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1969 &cl->answer, &cl->query );
1972 if( cl->answer.i_body > 0 )
1974 /* send the body data */
1975 free( cl->p_buffer );
1976 cl->p_buffer = cl->answer.p_body;
1977 cl->i_buffer_size = cl->answer.i_body;
1980 cl->answer.i_body = 0;
1981 cl->answer.p_body = NULL;
1986 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1992 #if defined( WIN32 ) || defined( UNDER_CE )
1993 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1995 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1999 cl->i_state = HTTPD_CLIENT_DEAD;
2004 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2006 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2009 cl->i_state = HTTPD_CLIENT_RECEIVING;
2013 cl->i_state = HTTPD_CLIENT_DEAD;
2018 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2022 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2024 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2027 cl->i_state = HTTPD_CLIENT_RECEIVING;
2031 cl->i_state = HTTPD_CLIENT_DEAD;
2036 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2041 static void* httpd_HostThread( void *data )
2043 httpd_host_t *host = data;
2044 tls_session_t *p_tls = NULL;
2045 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2046 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
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 );