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 : ""), (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 = xmalloc( 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 = xrealloc( 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 == '\r' || *psz_headers == '\n' ) psz_headers++;
581 if( *psz_headers == '\n' ) 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 *)xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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";
978 static vlc_mutex_t httpd_mutex = VLC_STATIC_MUTEX;
980 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
982 const char *psz_cert, const char *psz_key,
983 const char *psz_ca, const char *psz_crl )
992 if( psz_hostname == NULL )
995 psz_host = strdup( psz_hostname );
996 if( psz_host == NULL )
999 /* to be sure to avoid multiple creation */
1000 vlc_mutex_lock( &httpd_mutex );
1001 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1005 msg_Info( p_this, "creating httpd" );
1006 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1011 vlc_mutex_unlock( &httpd_mutex );
1019 ptrval.p_address = httpd;
1020 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1021 vlc_object_attach( httpd, p_this->p_libvlc );
1024 /* verify if it already exist */
1025 for( i = httpd->i_host - 1; i >= 0; i-- )
1027 host = httpd->host[i];
1029 /* cannot mix TLS and non-TLS hosts */
1030 if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1031 || ( host->i_port != i_port )
1032 || strcmp( host->psz_hostname, psz_hostname ) )
1035 /* Increase existing matching host reference count.
1036 * The reference count is written under both the global httpd and the
1037 * host lock. It is read with either or both locks held. The global
1038 * lock is always acquired first. */
1039 vlc_mutex_lock( &host->lock );
1041 vlc_mutex_unlock( &host->lock );
1043 vlc_mutex_unlock( &httpd_mutex );
1049 /* determine TLS configuration */
1050 if ( psz_cert != NULL )
1052 p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1053 if ( p_tls == NULL )
1055 msg_Err( p_this, "TLS initialization error" );
1059 if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1061 msg_Err( p_this, "TLS CA error" );
1065 if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1067 msg_Err( p_this, "TLS CRL error" );
1074 /* create the new host */
1075 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1081 host->httpd = httpd;
1082 vlc_mutex_init( &host->lock );
1083 vlc_cond_init( &host->wait );
1086 host->fds = net_ListenTCP( p_this, psz_host, i_port );
1087 if( host->fds == NULL )
1089 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1092 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1094 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1096 msg_Err( host, "signaling pipe error: %m" );
1100 host->i_port = i_port;
1101 host->psz_hostname = psz_host;
1106 host->client = NULL;
1108 host->p_tls = p_tls;
1110 /* create the thread */
1111 if( vlc_clone( &host->thread, httpd_HostThread, host,
1112 VLC_THREAD_PRIORITY_LOW ) )
1114 msg_Err( p_this, "cannot spawn http host thread" );
1118 /* now add it to httpd */
1119 TAB_APPEND( httpd->i_host, httpd->host, host );
1120 vlc_mutex_unlock( &httpd_mutex );
1126 if( httpd->i_host <= 0 )
1128 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1129 vlc_object_detach( httpd );
1130 vlc_object_release( httpd );
1132 vlc_mutex_unlock( &httpd_mutex );
1136 net_ListenClose( host->fds );
1137 vlc_cond_destroy( &host->wait );
1138 vlc_mutex_destroy( &host->lock );
1139 vlc_object_release( host );
1143 tls_ServerDelete( p_tls );
1149 void httpd_HostDelete( httpd_host_t *host )
1151 httpd_t *httpd = host->httpd;
1153 bool delete = false;
1155 vlc_mutex_lock( &httpd_mutex );
1157 vlc_mutex_lock( &host->lock );
1159 if( host->i_ref == 0 )
1161 vlc_cond_signal( &host->wait );
1164 vlc_mutex_unlock( &host->lock );
1168 vlc_mutex_unlock( &httpd_mutex );
1169 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1172 TAB_REMOVE( httpd->i_host, httpd->host, host );
1174 vlc_object_kill( host );
1175 vlc_join( host->thread, NULL );
1177 msg_Dbg( host, "HTTP host removed" );
1179 for( i = 0; i < host->i_url; i++ )
1181 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1183 for( i = 0; i < host->i_client; i++ )
1185 httpd_client_t *cl = host->client[i];
1186 msg_Warn( host, "client still connected" );
1187 httpd_ClientClean( cl );
1188 TAB_REMOVE( host->i_client, host->client, cl );
1194 if( host->p_tls != NULL)
1195 tls_ServerDelete( host->p_tls );
1197 net_ListenClose( host->fds );
1198 free( host->psz_hostname );
1200 vlc_cond_destroy( &host->wait );
1201 vlc_mutex_destroy( &host->lock );
1202 vlc_object_release( host );
1204 if( httpd->i_host <= 0 )
1206 msg_Dbg( httpd, "no hosts left, stopping httpd" );
1208 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1209 vlc_object_detach( httpd );
1210 vlc_object_release( httpd );
1212 vlc_mutex_unlock( &httpd_mutex );
1215 /* register a new url */
1216 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1217 const char *psz_user, const char *psz_password,
1218 const vlc_acl_t *p_acl, bool b_check )
1223 assert( psz_url != NULL );
1225 vlc_mutex_lock( &host->lock );
1228 for( i = 0; i < host->i_url; i++ )
1230 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1232 msg_Warn( host->httpd,
1233 "cannot add '%s' (url already defined)", psz_url );
1234 vlc_mutex_unlock( &host->lock );
1240 url = xmalloc( sizeof( httpd_url_t ) );
1243 vlc_mutex_init( &url->lock );
1244 url->psz_url = strdup( psz_url );
1245 url->psz_user = strdup( psz_user ? psz_user : "" );
1246 url->psz_password = strdup( psz_password ? psz_password : "" );
1247 url->p_acl = ACL_Duplicate( host, p_acl );
1248 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1250 url->catch[i].cb = NULL;
1251 url->catch[i].p_sys = NULL;
1254 TAB_APPEND( host->i_url, host->url, url );
1255 vlc_cond_signal( &host->wait );
1256 vlc_mutex_unlock( &host->lock );
1261 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1262 const char *psz_user, const char *psz_password,
1263 const vlc_acl_t *p_acl )
1265 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1266 psz_password, p_acl, false );
1269 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1270 const char *psz_user, const char *psz_password,
1271 const vlc_acl_t *p_acl )
1273 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1274 psz_password, p_acl, true );
1277 /* register callback on a url */
1278 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1279 httpd_callback_sys_t *p_sys )
1281 vlc_mutex_lock( &url->lock );
1282 url->catch[i_msg].cb = cb;
1283 url->catch[i_msg].p_sys= p_sys;
1284 vlc_mutex_unlock( &url->lock );
1290 void httpd_UrlDelete( httpd_url_t *url )
1292 httpd_host_t *host = url->host;
1295 vlc_mutex_lock( &host->lock );
1296 TAB_REMOVE( host->i_url, host->url, url );
1298 vlc_mutex_destroy( &url->lock );
1299 free( url->psz_url );
1300 free( url->psz_user );
1301 free( url->psz_password );
1302 ACL_Destroy( url->p_acl );
1304 for( i = 0; i < host->i_client; i++ )
1306 httpd_client_t *client = host->client[i];
1308 if( client->url == url )
1310 /* TODO complete it */
1311 msg_Warn( host, "force closing connections" );
1312 httpd_ClientClean( client );
1313 TAB_REMOVE( host->i_client, host->client, client );
1319 vlc_mutex_unlock( &host->lock );
1322 static void httpd_MsgInit( httpd_message_t *msg )
1325 msg->i_type = HTTPD_MSG_NONE;
1326 msg->i_proto = HTTPD_PROTO_NONE;
1327 msg->i_version = -1; /* FIXME */
1331 msg->psz_url = NULL;
1332 msg->psz_args = NULL;
1334 msg->i_channel = -1;
1341 msg->i_body_offset = 0;
1346 static void httpd_MsgClean( httpd_message_t *msg )
1350 free( msg->psz_url );
1351 free( msg->psz_args );
1352 for( i = 0; i < msg->i_name; i++ )
1354 free( msg->name[i] );
1355 free( msg->value[i] );
1359 free( msg->p_body );
1360 httpd_MsgInit( msg );
1363 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1367 for( i = 0; i < msg->i_name; i++ )
1369 if( !strcasecmp( msg->name[i], name ))
1371 return msg->value[i];
1377 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1382 va_start( args, psz_value );
1383 if( vasprintf( &value, psz_value, args ) == -1 )
1390 name = strdup( name );
1397 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1398 TAB_APPEND( msg->i_value, msg->value, value );
1401 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1403 cl->i_state = HTTPD_CLIENT_RECEIVING;
1404 cl->i_activity_date = now;
1405 cl->i_activity_timeout = INT64_C(10000000);
1406 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1408 cl->p_buffer = xmalloc( cl->i_buffer_size );
1409 cl->i_mode = HTTPD_CLIENT_FILE;
1410 cl->b_read_waiting = false;
1412 httpd_MsgInit( &cl->query );
1413 httpd_MsgInit( &cl->answer );
1416 void httpd_ClientModeStream( httpd_client_t *cl )
1418 cl->i_mode = HTTPD_CLIENT_STREAM;
1421 void httpd_ClientModeBidir( httpd_client_t *cl )
1423 cl->i_mode = HTTPD_CLIENT_BIDIR;
1426 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1428 return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1431 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1433 return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1436 static void httpd_ClientClean( httpd_client_t *cl )
1440 if( cl->p_tls != NULL )
1441 tls_ServerSessionClose( cl->p_tls );
1442 net_Close( cl->fd );
1446 httpd_MsgClean( &cl->answer );
1447 httpd_MsgClean( &cl->query );
1449 free( cl->p_buffer );
1450 cl->p_buffer = NULL;
1453 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1455 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1457 if( !cl ) return NULL;
1464 httpd_ClientInit( cl, now );
1470 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1472 tls_session_t *p_tls;
1477 val = p_tls ? tls_Recv (p_tls, p, i_len)
1478 : recv (cl->fd, p, i_len, 0);
1479 while (val == -1 && errno == EINTR);
1484 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1486 tls_session_t *p_tls;
1491 val = p_tls ? tls_Send( p_tls, p, i_len )
1492 : send (cl->fd, p, i_len, 0);
1493 while (val == -1 && errno == EINTR);
1500 const char name[16];
1506 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1507 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1508 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1509 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1510 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1511 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1512 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1513 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1514 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1515 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1516 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1520 static void httpd_ClientRecv( httpd_client_t *cl )
1524 /* ignore leading whites */
1525 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1526 ( cl->i_buffer == 0 ) )
1530 i_len = httpd_NetRecv( cl, &c, 1 );
1532 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1534 cl->p_buffer[0] = c;
1539 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1541 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1542 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1546 cl->i_buffer += i_len;
1549 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1551 /* Interleaved RTP over RTSP */
1552 cl->query.i_proto = HTTPD_PROTO_RTSP;
1553 cl->query.i_type = HTTPD_MSG_CHANNEL;
1554 cl->query.i_channel = cl->p_buffer[1];
1555 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1556 cl->query.p_body = xmalloc( cl->query.i_body );
1558 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1561 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1562 * this is the maximum we can ask at this point. */
1563 if( cl->i_buffer >= 7 )
1565 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1567 cl->query.i_proto = HTTPD_PROTO_HTTP;
1568 cl->query.i_type = HTTPD_MSG_ANSWER;
1570 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1572 cl->query.i_proto = HTTPD_PROTO_RTSP;
1573 cl->query.i_type = HTTPD_MSG_ANSWER;
1577 /* We need the full request line to determine the protocol. */
1578 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1579 cl->query.i_type = HTTPD_MSG_NONE;
1583 else if( cl->query.i_body > 0 )
1585 /* we are reading the body of a request or a channel */
1586 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1587 cl->query.i_body - cl->i_buffer );
1590 cl->i_buffer += i_len;
1592 if( cl->i_buffer >= cl->query.i_body )
1594 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1599 /* we are reading a header -> char by char */
1602 if( cl->i_buffer == cl->i_buffer_size )
1604 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1605 if( newbuf == NULL )
1611 cl->p_buffer = newbuf;
1612 cl->i_buffer_size += 1024;
1615 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1622 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1623 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1625 /* Request line is now complete */
1626 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1629 assert( cl->query.i_type == HTTPD_MSG_NONE );
1631 if( p == NULL ) /* no URI: evil guy */
1633 i_len = 0; /* drop connection */
1638 p++; /* skips extra spaces */
1641 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1642 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1644 i_len = 0; /* not supported currently -> drop */
1649 p++; /* skips extra spaces ever again */
1652 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1653 if( len < 7 ) /* foreign protocol */
1654 i_len = 0; /* I don't understand -> drop */
1656 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1658 cl->query.i_proto = HTTPD_PROTO_HTTP;
1659 cl->query.i_version = atoi( p + 7 );
1662 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1664 cl->query.i_proto = HTTPD_PROTO_RTSP;
1665 cl->query.i_version = atoi( p + 7 );
1668 if( memcmp( p, "HTTP/", 5 ) == 0 )
1670 const uint8_t sorry[] =
1671 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1672 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1673 i_len = 0; /* drop */
1676 if( memcmp( p, "RTSP/", 5 ) == 0 )
1678 const uint8_t sorry[] =
1679 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1680 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1681 i_len = 0; /* drop */
1683 else /* yet another foreign protocol */
1690 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1691 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1695 /* we have finished the header so parse it and set i_body */
1696 cl->p_buffer[cl->i_buffer] = '\0';
1698 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1701 * assume strlen( "HTTP/1.x" ) = 8
1703 cl->query.i_status =
1704 strtol( (char *)&cl->p_buffer[8],
1714 cl->query.i_type = HTTPD_MSG_NONE;
1716 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1718 for( i = 0; msg_type[i].name[0]; i++ )
1720 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1721 strlen( msg_type[i].name ) ) )
1723 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1724 cl->query.i_type = msg_type[i].i_type;
1725 if( cl->query.i_proto != msg_type[i].i_proto )
1728 cl->query.i_proto = HTTPD_PROTO_NONE;
1729 cl->query.i_type = HTTPD_MSG_NONE;
1736 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1738 cl->query.i_proto = HTTPD_PROTO_HTTP;
1740 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1742 cl->query.i_proto = HTTPD_PROTO_RTSP;
1754 p2 = strchr( p, ' ' );
1759 if( !strncasecmp( p, ( cl->query.i_proto
1760 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1761 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1762 { /* Skip hier-part of URL (if present) */
1763 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1764 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1765 { /* see RFC3986 §3.2 */
1767 while( *p && !strchr( "/?#", *p ) ) p++;
1770 cl->query.psz_url = strdup( p );
1771 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1774 cl->query.psz_args = (uint8_t *)strdup( p3 );
1781 p = strchr( p, '\n' );
1785 while( *p == '\n' || *p == '\r' )
1789 while( p && *p != '\0' )
1792 char *eol = p = strchr( p, '\n' );
1795 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1800 if( ( colon = strchr( line, ':' ) ) )
1806 while( *colon == ' ' )
1810 name = strdup( line );
1811 value = strdup( colon );
1813 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1814 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1816 if( !strcasecmp( name, "Content-Length" ) )
1818 cl->query.i_body = atol( value );
1825 while( *p == '\n' || *p == '\r' )
1832 if( cl->query.i_body > 0 )
1834 /* TODO Mhh, handle the case client will only send a
1835 * request and close the connection
1836 * to mark and of body (probably only RTSP) */
1837 cl->query.p_body = xmalloc( cl->query.i_body );
1842 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1848 /* check if the client is to be set to dead */
1849 #if defined( WIN32 ) || defined( UNDER_CE )
1850 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1852 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1855 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1857 /* connection closed -> end of data */
1858 if( cl->query.i_body > 0 )
1860 cl->query.i_body = cl->i_buffer;
1862 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1866 cl->i_state = HTTPD_CLIENT_DEAD;
1870 /* XXX: for QT I have to disable timeout. Try to find why */
1871 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1872 cl->i_activity_timeout = 0;
1874 #if 0 /* Debugging only */
1875 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1879 fprintf( stderr, "received new request\n" );
1880 fprintf( stderr, " - proto=%s\n",
1881 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1882 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1883 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1884 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1886 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1887 cl->query.psz_status );
1889 else if( cl->query.i_type != HTTPD_MSG_NONE )
1891 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1893 for( i = 0; i < cl->query.i_name; i++ )
1895 fprintf( stderr, " - option name='%s' value='%s'\n",
1896 cl->query.name[i], cl->query.value[i] );
1902 static void httpd_ClientSend( httpd_client_t *cl )
1907 if( cl->i_buffer < 0 )
1909 /* We need to create the header */
1912 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1914 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1915 for( i = 0; i < cl->answer.i_name; i++ )
1917 i_size += strlen( cl->answer.name[i] ) + 2 +
1918 strlen( cl->answer.value[i] ) + 2;
1921 if( cl->i_buffer_size < i_size )
1923 cl->i_buffer_size = i_size;
1924 free( cl->p_buffer );
1925 cl->p_buffer = xmalloc( i_size );
1927 p = (char *)cl->p_buffer;
1929 p += sprintf( p, "%s.%u %d %s\r\n",
1930 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1931 cl->answer.i_version,
1932 cl->answer.i_status, psz_status );
1933 for( i = 0; i < cl->answer.i_name; i++ )
1935 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1936 cl->answer.value[i] );
1938 p += sprintf( p, "\r\n" );
1941 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1943 /*fprintf( stderr, "sending answer\n" );
1944 fprintf( stderr, "%s", cl->p_buffer );*/
1947 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1948 cl->i_buffer_size - cl->i_buffer );
1951 cl->i_buffer += i_len;
1953 if( cl->i_buffer >= cl->i_buffer_size )
1955 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1956 !cl->b_read_waiting )
1958 /* catch more body data */
1959 int i_msg = cl->query.i_type;
1960 int64_t i_offset = cl->answer.i_body_offset;
1962 httpd_MsgClean( &cl->answer );
1963 cl->answer.i_body_offset = i_offset;
1965 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1966 &cl->answer, &cl->query );
1969 if( cl->answer.i_body > 0 )
1971 /* send the body data */
1972 free( cl->p_buffer );
1973 cl->p_buffer = cl->answer.p_body;
1974 cl->i_buffer_size = cl->answer.i_body;
1977 cl->answer.i_body = 0;
1978 cl->answer.p_body = NULL;
1983 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1989 #if defined( WIN32 ) || defined( UNDER_CE )
1990 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1992 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1996 cl->i_state = HTTPD_CLIENT_DEAD;
2001 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2003 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2006 cl->i_state = HTTPD_CLIENT_RECEIVING;
2010 cl->i_state = HTTPD_CLIENT_DEAD;
2015 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2019 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2021 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2024 cl->i_state = HTTPD_CLIENT_RECEIVING;
2028 cl->i_state = HTTPD_CLIENT_DEAD;
2033 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2038 static void* httpd_HostThread( void *data )
2040 httpd_host_t *host = data;
2041 tls_session_t *p_tls = NULL;
2042 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2043 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2044 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2048 /* prepare a new TLS session */
2049 if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2050 p_tls = tls_ServerSessionPrepare( host->p_tls );
2052 struct pollfd ufd[host->nfd + host->i_client + 1];
2054 for( nfd = 0; nfd < host->nfd; nfd++ )
2056 ufd[nfd].fd = host->fds[nfd];
2057 ufd[nfd].events = POLLIN;
2058 ufd[nfd].revents = 0;
2061 /* add all socket that should be read/write and close dead connection */
2062 vlc_mutex_lock( &host->lock );
2063 while( host->i_url <= 0 && host->i_ref > 0 )
2064 vlc_cond_wait( &host->wait, &host->lock );
2066 mtime_t now = mdate();
2067 bool b_low_delay = false;
2069 for(int i_client = 0; i_client < host->i_client; i_client++ )
2071 httpd_client_t *cl = host->client[i_client];
2072 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2073 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2074 ( cl->i_activity_timeout > 0 &&
2075 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2077 httpd_ClientClean( cl );
2078 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2079 TAB_REMOVE( host->i_client, host->client, cl );
2085 struct pollfd *pufd = ufd + nfd;
2086 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2089 pufd->events = pufd->revents = 0;
2091 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2092 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2094 pufd->events = POLLIN;
2096 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2097 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2099 pufd->events = POLLOUT;
2101 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2103 httpd_message_t *answer = &cl->answer;
2104 httpd_message_t *query = &cl->query;
2105 int i_msg = query->i_type;
2107 httpd_MsgInit( answer );
2109 /* Handle what we received */
2110 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2111 (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2113 /* we can only receive request from client when not
2116 cl->i_state = HTTPD_CLIENT_DEAD;
2118 else if( i_msg == HTTPD_MSG_ANSWER )
2120 /* We are in BIDIR mode, trigger the callback and then
2121 * check for new data */
2122 if( cl->url && cl->url->catch[i_msg].cb )
2124 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2127 cl->i_state = HTTPD_CLIENT_WAITING;
2129 else if( i_msg == HTTPD_MSG_CHANNEL )
2131 /* We are in BIDIR mode, trigger the callback and then
2132 * check for new data */
2133 if( cl->url && cl->url->catch[i_msg].cb )
2135 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2138 cl->i_state = HTTPD_CLIENT_WAITING;
2140 else if( i_msg == HTTPD_MSG_OPTIONS )
2143 answer->i_type = HTTPD_MSG_ANSWER;
2144 answer->i_proto = query->i_proto;
2145 answer->i_status = 200;
2147 answer->p_body = NULL;
2149 httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2150 httpd_MsgAdd( answer, "Content-Length", "0" );
2152 switch( query->i_proto )
2154 case HTTPD_PROTO_HTTP:
2155 answer->i_version = 1;
2156 httpd_MsgAdd( answer, "Allow",
2157 "GET,HEAD,POST,OPTIONS" );
2160 case HTTPD_PROTO_RTSP:
2163 answer->i_version = 0;
2165 p = httpd_MsgGet( query, "Cseq" );
2167 httpd_MsgAdd( answer, "Cseq", "%s", p );
2168 p = httpd_MsgGet( query, "Timestamp" );
2170 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2172 p = httpd_MsgGet( query, "Require" );
2175 answer->i_status = 551;
2176 httpd_MsgAdd( query, "Unsupported", "%s", p );
2179 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2180 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2185 cl->i_buffer = -1; /* Force the creation of the answer in
2186 * httpd_ClientSend */
2187 cl->i_state = HTTPD_CLIENT_SENDING;
2189 else if( i_msg == HTTPD_MSG_NONE )
2191 if( query->i_proto == HTTPD_PROTO_NONE )
2194 cl->i_state = HTTPD_CLIENT_DEAD;
2201 answer->i_proto = query->i_proto ;
2202 answer->i_type = HTTPD_MSG_ANSWER;
2203 answer->i_version= 0;
2204 answer->i_status = 501;
2206 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2207 answer->p_body = (uint8_t *)p;
2208 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2210 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2211 cl->i_state = HTTPD_CLIENT_SENDING;
2216 bool b_auth_failed = false;
2217 bool b_hosts_failed = false;
2219 /* Search the url and trigger callbacks */
2220 for(int i = 0; i < host->i_url; i++ )
2222 httpd_url_t *url = host->url[i];
2224 if( !strcmp( url->psz_url, query->psz_url ) )
2226 if( url->catch[i_msg].cb )
2228 if( answer && ( url->p_acl != NULL ) )
2230 char ip[NI_MAXNUMERICHOST];
2232 if( ( httpd_ClientIP( cl, ip ) == NULL )
2233 || ACL_Check( url->p_acl, ip ) )
2235 b_hosts_failed = true;
2240 if( answer && ( *url->psz_user || *url->psz_password ) )
2242 /* create the headers */
2243 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2244 char *user = NULL, *pass = NULL;
2247 && !strncasecmp( b64, "BASIC", 5 ) )
2250 while( *b64 == ' ' )
2253 user = vlc_b64_decode( b64 );
2256 pass = strchr (user, ':');
2262 if ((user == NULL) || (pass == NULL)
2263 || strcmp (user, url->psz_user)
2264 || strcmp (pass, url->psz_password))
2266 httpd_MsgAdd( answer,
2268 "Basic realm=\"VLC stream\"" );
2269 /* We fail for all url */
2270 b_auth_failed = true;
2278 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2280 if( answer->i_proto == HTTPD_PROTO_NONE )
2282 /* Raw answer from a CGI */
2283 cl->i_buffer = cl->i_buffer_size;
2288 /* only one url can answer */
2290 if( cl->url == NULL )
2303 answer->i_proto = query->i_proto;
2304 answer->i_type = HTTPD_MSG_ANSWER;
2305 answer->i_version= 0;
2307 if( b_hosts_failed )
2309 answer->i_status = 403;
2311 else if( b_auth_failed )
2313 answer->i_status = 401;
2317 /* no url registered */
2318 answer->i_status = 404;
2321 answer->i_body = httpd_HtmlError (&p,
2324 answer->p_body = (uint8_t *)p;
2326 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2327 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2328 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2331 cl->i_state = HTTPD_CLIENT_SENDING;
2334 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2336 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2338 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2339 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2340 bool b_connection = false;
2341 bool b_keepalive = false;
2342 bool b_query = false;
2345 if( psz_connection )
2347 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2348 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2353 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2356 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2357 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2358 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2359 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2360 !b_query && !b_connection ) )
2362 httpd_MsgClean( &cl->query );
2363 httpd_MsgInit( &cl->query );
2366 cl->i_buffer_size = 1000;
2367 free( cl->p_buffer );
2368 cl->p_buffer = xmalloc( cl->i_buffer_size );
2369 cl->i_state = HTTPD_CLIENT_RECEIVING;
2373 cl->i_state = HTTPD_CLIENT_DEAD;
2375 httpd_MsgClean( &cl->answer );
2377 else if( cl->b_read_waiting )
2379 /* we have a message waiting for us to read it */
2380 httpd_MsgClean( &cl->answer );
2381 httpd_MsgClean( &cl->query );
2384 cl->i_buffer_size = 1000;
2385 free( cl->p_buffer );
2386 cl->p_buffer = xmalloc( cl->i_buffer_size );
2387 cl->i_state = HTTPD_CLIENT_RECEIVING;
2388 cl->b_read_waiting = false;
2392 int64_t i_offset = cl->answer.i_body_offset;
2393 httpd_MsgClean( &cl->answer );
2395 cl->answer.i_body_offset = i_offset;
2396 free( cl->p_buffer );
2397 cl->p_buffer = NULL;
2399 cl->i_buffer_size = 0;
2401 cl->i_state = HTTPD_CLIENT_WAITING;
2404 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2406 int64_t i_offset = cl->answer.i_body_offset;
2407 int i_msg = cl->query.i_type;
2409 httpd_MsgInit( &cl->answer );
2410 cl->answer.i_body_offset = i_offset;
2412 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2413 &cl->answer, &cl->query );
2414 if( cl->answer.i_type != HTTPD_MSG_NONE )
2416 /* we have new data, so re-enter send mode */
2418 cl->p_buffer = cl->answer.p_body;
2419 cl->i_buffer_size = cl->answer.i_body;
2420 cl->answer.p_body = NULL;
2421 cl->answer.i_body = 0;
2422 cl->i_state = HTTPD_CLIENT_SENDING;
2426 /* Special for BIDIR mode we also check reading */
2427 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2428 cl->i_state == HTTPD_CLIENT_SENDING )
2430 pufd->events |= POLLIN;
2433 if (pufd->events != 0)
2438 vlc_mutex_unlock( &host->lock );
2441 ufd[nfd].events = POLLIN;
2442 ufd[nfd].revents = 0;
2445 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2446 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2451 /* Kernel on low memory or a bug: pace */
2452 msg_Err( host, "polling error: %m" );
2459 if( ufd[nfd - 1].revents )
2462 /* Handle client sockets */
2463 vlc_mutex_lock( &host->lock );
2466 for( int i_client = 0; i_client < host->i_client; i_client++ )
2468 httpd_client_t *cl = host->client[i_client];
2469 const struct pollfd *pufd = &ufd[nfd];
2471 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2473 if( cl->fd != pufd->fd )
2474 continue; // we were not waiting for this client
2476 if( pufd->revents == 0 )
2477 continue; // no event received
2479 cl->i_activity_date = now;
2481 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2483 httpd_ClientRecv( cl );
2485 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2487 httpd_ClientSend( cl );
2489 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2491 httpd_ClientTlsHsIn( cl );
2493 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2495 httpd_ClientTlsHsOut( cl );
2498 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2499 cl->i_state == HTTPD_CLIENT_SENDING &&
2500 (pufd->revents & POLLIN) )
2502 cl->b_read_waiting = true;
2505 vlc_mutex_unlock( &host->lock );
2507 /* Handle server sockets (accept new connections) */
2508 for( nfd = 0; nfd < host->nfd; nfd++ )
2512 int fd = ufd[nfd].fd;
2514 assert (fd == host->fds[nfd]);
2516 if( ufd[nfd].revents == 0 )
2521 fd = accept4 (fd, NULL, NULL, SOCK_CLOEXEC);
2522 if (fd == -1 && errno == ENOSYS)
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 );