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>
39 #include <vlc_strings.h>
41 #include "../libvlc.h"
54 #if defined( UNDER_CE )
56 #elif defined( WIN32 )
57 # include <winsock2.h>
59 # include <sys/socket.h>
63 /* We need HUGE buffer otherwise TCP throughput is very limited */
64 #define HTTPD_CL_BUFSIZE 1000000
66 #define HTTPD_CL_BUFSIZE 10000
69 static void httpd_ClientClean( httpd_client_t *cl );
80 /* each host run in his own thread */
90 /* address/port and socket for listening at connections */
100 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
101 * This will slow down the url research but make my live easier
102 * All url will have their cb trigger, but only the first one can answer
108 httpd_client_t **client;
129 httpd_callback_sys_t *p_sys;
130 } catch[HTTPD_MSG_MAX];
136 HTTPD_CLIENT_RECEIVING,
137 HTTPD_CLIENT_RECEIVE_DONE,
139 HTTPD_CLIENT_SENDING,
140 HTTPD_CLIENT_SEND_DONE,
142 HTTPD_CLIENT_WAITING,
146 HTTPD_CLIENT_TLS_HS_IN,
147 HTTPD_CLIENT_TLS_HS_OUT
153 HTTPD_CLIENT_FILE, /* default */
154 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
155 HTTPD_CLIENT_BIDIR, /* check for reading and get data from cb */
158 struct httpd_client_t
168 int b_read_waiting; /* stop as soon as possible sending */
170 mtime_t i_activity_date;
171 mtime_t i_activity_timeout;
173 /* buffer for reading header */
179 httpd_message_t query; /* client -> httpd */
180 httpd_message_t answer; /* httpd -> client */
183 tls_session_t *p_tls;
187 /*****************************************************************************
189 *****************************************************************************/
192 const char psz_ext[8];
193 const char *psz_mime;
196 { ".htm", "text/html" },
197 { ".html", "text/html" },
198 { ".txt", "text/plain" },
199 { ".xml", "text/xml" },
200 { ".dtd", "text/dtd" },
202 { ".css", "text/css" },
205 { ".gif", "image/gif" },
206 { ".jpe", "image/jpeg" },
207 { ".jpg", "image/jpeg" },
208 { ".jpeg", "image/jpeg" },
209 { ".png", "image/png" },
210 /* same as modules/mux/mpjpeg.c here: */
211 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
214 { ".avi", "video/avi" },
215 { ".asf", "video/x-ms-asf" },
216 { ".m1a", "audio/mpeg" },
217 { ".m2a", "audio/mpeg" },
218 { ".m1v", "video/mpeg" },
219 { ".m2v", "video/mpeg" },
220 { ".mp2", "audio/mpeg" },
221 { ".mp3", "audio/mpeg" },
222 { ".mpa", "audio/mpeg" },
223 { ".mpg", "video/mpeg" },
224 { ".mpeg", "video/mpeg" },
225 { ".mpe", "video/mpeg" },
226 { ".mov", "video/quicktime" },
227 { ".moov", "video/quicktime" },
228 { ".oga", "audio/ogg" },
229 { ".ogg", "application/ogg" },
230 { ".ogm", "application/ogg" },
231 { ".ogv", "video/ogg" },
232 { ".ogx", "application/ogg" },
233 { ".spx", "audio/ogg" },
234 { ".wav", "audio/wav" },
235 { ".wma", "audio/x-ms-wma" },
236 { ".wmv", "video/x-ms-wmv" },
243 static const char *httpd_MimeFromUrl( const char *psz_url )
248 psz_ext = strrchr( psz_url, '.' );
253 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
255 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
257 return http_mime[i].psz_mime;
261 return "application/octet-stream";
268 const char psz_reason[36];
271 static const http_status_info http_reason[] =
273 /*{ 100, "Continue" },
274 { 101, "Switching Protocols" },*/
276 /*{ 201, "Created" },
278 { 203, "Non-authoritative information" },
279 { 204, "No content" },
280 { 205, "Reset content" },
281 { 206, "Partial content" },
282 { 250, "Low on storage space" },
283 { 300, "Multiple choices" },*/
284 { 301, "Moved permanently" },
285 /*{ 302, "Moved temporarily" },
286 { 303, "See other" },
287 { 304, "Not modified" },
288 { 305, "Use proxy" },
289 { 307, "Temporary redirect" },
290 { 400, "Bad request" },*/
291 { 401, "Unauthorized" },
292 /*{ 402, "Payment Required" },*/
293 { 403, "Forbidden" },
294 { 404, "Not found" },
295 { 405, "Method not allowed" },
296 /*{ 406, "Not acceptable" },
297 { 407, "Proxy authentication required" },
298 { 408, "Request time-out" },
301 { 411, "Length required" },
302 { 412, "Precondition failed" },
303 { 413, "Request entity too large" },
304 { 414, "Request-URI too large" },
305 { 415, "Unsupported media Type" },
306 { 416, "Requested range not satisfiable" },
307 { 417, "Expectation failed" },
308 { 451, "Parameter not understood" },
309 { 452, "Conference not found" },
310 { 453, "Not enough bandwidth" },*/
311 { 454, "Session not found" },
312 /*{ 455, "Method not valid in this State" },*/
313 { 456, "Header field not valid for resource" },
314 /*{ 457, "Invalid range" },
315 { 458, "Read-only parameter" },*/
316 { 459, "Aggregate operation not allowed" },
317 { 460, "Non-aggregate operation not allowed" },
318 { 461, "Unsupported transport" },
319 /*{ 462, "Destination unreachable" },*/
320 { 500, "Internal server error" },
321 { 501, "Not implemented" },
322 /*{ 502, "Bad gateway" },*/
323 { 503, "Service unavailable" },
324 /*{ 504, "Gateway time-out" },*/
325 { 505, "Protocol version not supported" },
326 { 551, "Option not supported" },
330 static const char psz_fallback_reason[5][16] =
331 { "Continue", "OK", "Found", "Client error", "Server error" };
333 static const char *httpd_ReasonFromCode( unsigned i_code )
335 const http_status_info *p;
337 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
339 for (p = http_reason; i_code > p->i_code; p++);
341 if( p->i_code == i_code )
342 return p->psz_reason;
344 return psz_fallback_reason[(i_code / 100) - 1];
348 static size_t httpd_HtmlError (char **body, int code, const char *url)
350 const char *errname = httpd_ReasonFromCode (code);
351 assert (errname != NULL);
353 int res = asprintf (body,
354 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
355 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
356 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
357 "<html lang=\"en\">\n"
359 "<title>%s</title>\n"
362 "<h1>%d %s%s%s%s</h1>\n"
364 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
366 "</html>\n", errname, code, errname,
367 (url ? " (" : ""), (url ? url : ""), (url ? ")" : ""));
379 /*****************************************************************************
380 * High Level Functions: httpd_file_t
381 *****************************************************************************/
389 httpd_file_callback_t pf_fill;
390 httpd_file_sys_t *p_sys;
395 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
396 httpd_message_t *answer, const httpd_message_t *query )
398 httpd_file_t *file = (httpd_file_t*)p_sys;
399 uint8_t **pp_body, *p_body;
400 const char *psz_connection;
401 int *pi_body, i_body;
403 if( answer == NULL || query == NULL )
407 answer->i_proto = HTTPD_PROTO_HTTP;
408 answer->i_version= 1;
409 answer->i_type = HTTPD_MSG_ANSWER;
411 answer->i_status = 200;
413 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
414 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
416 if( query->i_type != HTTPD_MSG_HEAD )
418 pp_body = &answer->p_body;
419 pi_body = &answer->i_body;
423 /* The file still needs to be executed. */
430 if( query->i_type == HTTPD_MSG_POST )
432 /* msg_Warn not supported */
435 uint8_t *psz_args = query->psz_args;
436 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
438 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
443 /* We respect client request */
444 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
445 if( psz_connection != NULL )
447 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
450 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
455 httpd_file_t *httpd_FileNew( httpd_host_t *host,
456 const char *psz_url, const char *psz_mime,
457 const char *psz_user, const char *psz_password,
458 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
459 httpd_file_sys_t *p_sys )
461 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
463 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
464 psz_password, p_acl )
471 file->psz_url = strdup( psz_url );
472 if( psz_mime && *psz_mime )
474 file->psz_mime = strdup( psz_mime );
478 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
481 file->pf_fill = pf_fill;
484 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
485 (httpd_callback_sys_t*)file );
486 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
487 (httpd_callback_sys_t*)file );
488 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
489 (httpd_callback_sys_t*)file );
494 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
496 httpd_file_sys_t *p_sys = file->p_sys;
498 httpd_UrlDelete( file->url );
500 free( file->psz_url );
501 free( file->psz_mime );
508 /*****************************************************************************
509 * High Level Functions: httpd_handler_t (for CGIs)
510 *****************************************************************************/
511 struct httpd_handler_t
515 httpd_handler_callback_t pf_fill;
516 httpd_handler_sys_t *p_sys;
521 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
522 httpd_message_t *answer, const httpd_message_t *query )
524 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
525 char psz_remote_addr[NI_MAXNUMERICHOST];
527 if( answer == NULL || query == NULL )
531 answer->i_proto = HTTPD_PROTO_NONE;
532 answer->i_type = HTTPD_MSG_ANSWER;
534 /* We do it ourselves, thanks */
535 answer->i_status = 0;
537 if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
538 *psz_remote_addr = '\0';
540 uint8_t *psz_args = query->psz_args;
541 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
542 query->i_type, query->p_body, query->i_body,
543 psz_remote_addr, NULL,
544 &answer->p_body, &answer->i_body );
546 if( query->i_type == HTTPD_MSG_HEAD )
548 char *p = (char *)answer->p_body;
550 /* Looks for end of header (i.e. one empty line) */
551 while ( (p = strchr( p, '\r' )) != NULL )
553 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
554 && p[3] && p[3] == '\n' )
563 answer->i_body = strlen((char*)answer->p_body) + 1;
564 answer->p_body = xrealloc( answer->p_body, answer->i_body );
568 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
570 int i_status, i_headers;
571 char *psz_headers, *psz_new;
572 const char *psz_status;
574 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
577 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
578 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
579 if( *psz_headers == '\n' ) psz_headers++;
580 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
585 psz_headers = (char *)answer->p_body;
586 i_headers = answer->i_body;
589 psz_status = httpd_ReasonFromCode( i_status );
590 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
591 + strlen(psz_status) + i_headers - 1;
592 psz_new = (char *)xmalloc( answer->i_body + 1);
593 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
594 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
595 free( answer->p_body );
596 answer->p_body = (uint8_t *)psz_new;
602 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
603 const char *psz_user,
604 const char *psz_password,
605 const vlc_acl_t *p_acl,
606 httpd_handler_callback_t pf_fill,
607 httpd_handler_sys_t *p_sys )
609 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
611 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
612 psz_password, p_acl )
619 handler->pf_fill = pf_fill;
620 handler->p_sys = p_sys;
622 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
623 (httpd_callback_sys_t*)handler );
624 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
625 (httpd_callback_sys_t*)handler );
626 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
627 (httpd_callback_sys_t*)handler );
632 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
634 httpd_handler_sys_t *p_sys = handler->p_sys;
635 httpd_UrlDelete( handler->url );
640 /*****************************************************************************
641 * High Level Functions: httpd_redirect_t
642 *****************************************************************************/
643 struct httpd_redirect_t
649 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
650 httpd_client_t *cl, httpd_message_t *answer,
651 const httpd_message_t *query )
653 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
657 if( answer == NULL || query == NULL )
661 answer->i_proto = HTTPD_PROTO_HTTP;
662 answer->i_version= 1;
663 answer->i_type = HTTPD_MSG_ANSWER;
664 answer->i_status = 301;
666 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
667 answer->p_body = (unsigned char *)p_body;
669 /* XXX check if it's ok or we need to set an absolute url */
670 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
672 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
677 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
678 const char *psz_url_src )
680 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
682 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
687 rdir->psz_dst = strdup( psz_url_dst );
689 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
690 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
691 (httpd_callback_sys_t*)rdir );
692 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
693 (httpd_callback_sys_t*)rdir );
694 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
695 (httpd_callback_sys_t*)rdir );
696 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
697 (httpd_callback_sys_t*)rdir );
701 void httpd_RedirectDelete( httpd_redirect_t *rdir )
703 httpd_UrlDelete( rdir->url );
704 free( rdir->psz_dst );
708 /*****************************************************************************
709 * High Level Funtions: httpd_stream_t
710 *****************************************************************************/
711 struct httpd_stream_t
718 /* Header to send as first packet */
722 /* circular buffer */
723 int i_buffer_size; /* buffer size, can't be reallocated smaller */
724 uint8_t *p_buffer; /* buffer */
725 int64_t i_buffer_pos; /* absolute position from begining */
726 int64_t i_buffer_last_pos; /* a new connection will start with that */
729 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
730 httpd_client_t *cl, httpd_message_t *answer,
731 const httpd_message_t *query )
733 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
735 if( answer == NULL || query == NULL || cl == NULL )
740 if( answer->i_body_offset > 0 )
746 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
747 answer->i_body_offset );
750 if( answer->i_body_offset >= stream->i_buffer_pos )
752 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
753 return VLC_EGENERIC; /* wait, no data available */
755 if( answer->i_body_offset + stream->i_buffer_size <
756 stream->i_buffer_pos )
758 /* this client isn't fast enough */
760 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
761 answer->i_body_offset, stream->i_buffer_last_pos );
763 answer->i_body_offset = stream->i_buffer_last_pos;
766 i_pos = answer->i_body_offset % stream->i_buffer_size;
767 i_write = stream->i_buffer_pos - answer->i_body_offset;
768 if( i_write > HTTPD_CL_BUFSIZE )
770 i_write = HTTPD_CL_BUFSIZE;
772 else if( i_write <= 0 )
774 return VLC_EGENERIC; /* wait, no data available */
777 /* Don't go past the end of the circular buffer */
778 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
780 /* using HTTPD_MSG_ANSWER -> data available */
781 answer->i_proto = HTTPD_PROTO_HTTP;
782 answer->i_version= 0;
783 answer->i_type = HTTPD_MSG_ANSWER;
785 answer->i_body = i_write;
786 answer->p_body = xmalloc( i_write );
787 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
789 answer->i_body_offset += i_write;
795 answer->i_proto = HTTPD_PROTO_HTTP;
796 answer->i_version= 0;
797 answer->i_type = HTTPD_MSG_ANSWER;
799 answer->i_status = 200;
801 if( query->i_type != HTTPD_MSG_HEAD )
803 httpd_ClientModeStream( cl );
804 vlc_mutex_lock( &stream->lock );
805 /* Send the header */
806 if( stream->i_header > 0 )
808 answer->i_body = stream->i_header;
809 answer->p_body = xmalloc( stream->i_header );
810 memcpy( answer->p_body, stream->p_header, stream->i_header );
812 answer->i_body_offset = stream->i_buffer_last_pos;
813 vlc_mutex_unlock( &stream->lock );
817 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
818 answer->i_body_offset = 0;
821 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
823 bool b_xplaystream = false;
826 httpd_MsgAdd( answer, "Content-type", "%s",
827 "application/octet-stream" );
828 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
829 httpd_MsgAdd( answer, "Pragma", "no-cache" );
830 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
831 vlc_mrand48()&0x7fff );
832 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
834 /* Check if there is a xPlayStrm=1 */
835 for( i = 0; i < query->i_name; i++ )
837 if( !strcasecmp( query->name[i], "Pragma" ) &&
838 strstr( query->value[i], "xPlayStrm=1" ) )
840 b_xplaystream = true;
846 answer->i_body_offset = 0;
851 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
853 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
858 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
859 const char *psz_url, const char *psz_mime,
860 const char *psz_user, const char *psz_password,
861 const vlc_acl_t *p_acl )
863 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
865 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
866 psz_password, p_acl )
872 vlc_mutex_init( &stream->lock );
873 if( psz_mime && *psz_mime )
875 stream->psz_mime = strdup( psz_mime );
879 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
881 stream->i_header = 0;
882 stream->p_header = NULL;
883 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
884 stream->p_buffer = xmalloc( stream->i_buffer_size );
885 /* We set to 1 to make life simpler
886 * (this way i_body_offset can never be 0) */
887 stream->i_buffer_pos = 1;
888 stream->i_buffer_last_pos = 1;
890 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
891 (httpd_callback_sys_t*)stream );
892 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
893 (httpd_callback_sys_t*)stream );
894 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
895 (httpd_callback_sys_t*)stream );
900 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
902 vlc_mutex_lock( &stream->lock );
903 free( stream->p_header );
904 stream->p_header = NULL;
906 stream->i_header = i_data;
909 stream->p_header = xmalloc( i_data );
910 memcpy( stream->p_header, p_data, i_data );
912 vlc_mutex_unlock( &stream->lock );
917 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
922 if( i_data < 0 || p_data == NULL )
926 vlc_mutex_lock( &stream->lock );
928 /* save this pointer (to be used by new connection) */
929 stream->i_buffer_last_pos = stream->i_buffer_pos;
931 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
937 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
939 /* Ok, we can't go past the end of our buffer */
940 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
942 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
947 stream->i_buffer_pos += i_data;
949 vlc_mutex_unlock( &stream->lock );
953 void httpd_StreamDelete( httpd_stream_t *stream )
955 httpd_UrlDelete( stream->url );
956 vlc_mutex_destroy( &stream->lock );
957 free( stream->psz_mime );
958 free( stream->p_header );
959 free( stream->p_buffer );
963 /*****************************************************************************
965 *****************************************************************************/
966 static void* httpd_HostThread( void * );
968 /* create a new host */
969 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
972 return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
976 static const char psz_object_type[] = "http server";
977 static vlc_mutex_t httpd_mutex = VLC_STATIC_MUTEX;
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 )
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 vlc_mutex_lock( &httpd_mutex );
1000 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1004 msg_Info( p_this, "creating httpd" );
1005 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1010 vlc_mutex_unlock( &httpd_mutex );
1018 ptrval.p_address = httpd;
1019 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1020 vlc_object_attach( httpd, p_this->p_libvlc );
1023 /* verify if it already exist */
1024 for( i = httpd->i_host - 1; i >= 0; i-- )
1026 host = httpd->host[i];
1028 /* cannot mix TLS and non-TLS hosts */
1029 if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1030 || ( host->i_port != i_port )
1031 || strcmp( host->psz_hostname, psz_hostname ) )
1034 /* Increase existing matching host reference count.
1035 * The reference count is written under both the global httpd and the
1036 * host lock. It is read with either or both locks held. The global
1037 * lock is always acquired first. */
1038 vlc_mutex_lock( &host->lock );
1040 vlc_mutex_unlock( &host->lock );
1042 vlc_mutex_unlock( &httpd_mutex );
1048 /* determine TLS configuration */
1049 if ( psz_cert != NULL )
1051 p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1052 if ( p_tls == NULL )
1054 msg_Err( p_this, "TLS initialization error" );
1058 if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1060 msg_Err( p_this, "TLS CA error" );
1064 if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1066 msg_Err( p_this, "TLS CRL error" );
1073 /* create the new host */
1074 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1080 host->httpd = httpd;
1081 vlc_mutex_init( &host->lock );
1082 vlc_cond_init( &host->wait );
1085 vlc_object_attach( host, p_this );
1087 host->fds = net_ListenTCP( p_this, psz_host, i_port );
1088 if( host->fds == NULL )
1090 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1093 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1095 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1097 msg_Err( host, "signaling pipe error: %m" );
1101 host->i_port = i_port;
1102 host->psz_hostname = psz_host;
1107 host->client = NULL;
1109 host->p_tls = p_tls;
1111 /* create the thread */
1112 if( vlc_clone( &host->thread, httpd_HostThread, host,
1113 VLC_THREAD_PRIORITY_LOW ) )
1115 msg_Err( p_this, "cannot spawn http host thread" );
1119 /* now add it to httpd */
1120 TAB_APPEND( httpd->i_host, httpd->host, host );
1121 vlc_mutex_unlock( &httpd_mutex );
1127 if( httpd->i_host <= 0 )
1129 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
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_release( httpd );
1211 vlc_mutex_unlock( &httpd_mutex );
1214 /* register a new url */
1215 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1216 const char *psz_user, const char *psz_password,
1217 const vlc_acl_t *p_acl, bool b_check )
1222 assert( psz_url != NULL );
1224 vlc_mutex_lock( &host->lock );
1227 for( i = 0; i < host->i_url; i++ )
1229 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1231 msg_Warn( host->httpd,
1232 "cannot add '%s' (url already defined)", psz_url );
1233 vlc_mutex_unlock( &host->lock );
1239 url = xmalloc( sizeof( httpd_url_t ) );
1242 vlc_mutex_init( &url->lock );
1243 url->psz_url = strdup( psz_url );
1244 url->psz_user = strdup( psz_user ? psz_user : "" );
1245 url->psz_password = strdup( psz_password ? psz_password : "" );
1246 url->p_acl = ACL_Duplicate( host, p_acl );
1247 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1249 url->catch[i].cb = NULL;
1250 url->catch[i].p_sys = NULL;
1253 TAB_APPEND( host->i_url, host->url, url );
1254 vlc_cond_signal( &host->wait );
1255 vlc_mutex_unlock( &host->lock );
1260 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1261 const char *psz_user, const char *psz_password,
1262 const vlc_acl_t *p_acl )
1264 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1265 psz_password, p_acl, false );
1268 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1269 const char *psz_user, const char *psz_password,
1270 const vlc_acl_t *p_acl )
1272 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1273 psz_password, p_acl, true );
1276 /* register callback on a url */
1277 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1278 httpd_callback_sys_t *p_sys )
1280 vlc_mutex_lock( &url->lock );
1281 url->catch[i_msg].cb = cb;
1282 url->catch[i_msg].p_sys= p_sys;
1283 vlc_mutex_unlock( &url->lock );
1289 void httpd_UrlDelete( httpd_url_t *url )
1291 httpd_host_t *host = url->host;
1294 vlc_mutex_lock( &host->lock );
1295 TAB_REMOVE( host->i_url, host->url, url );
1297 vlc_mutex_destroy( &url->lock );
1298 free( url->psz_url );
1299 free( url->psz_user );
1300 free( url->psz_password );
1301 ACL_Destroy( url->p_acl );
1303 for( i = 0; i < host->i_client; i++ )
1305 httpd_client_t *client = host->client[i];
1307 if( client->url == url )
1309 /* TODO complete it */
1310 msg_Warn( host, "force closing connections" );
1311 httpd_ClientClean( client );
1312 TAB_REMOVE( host->i_client, host->client, client );
1318 vlc_mutex_unlock( &host->lock );
1321 static void httpd_MsgInit( httpd_message_t *msg )
1324 msg->i_type = HTTPD_MSG_NONE;
1325 msg->i_proto = HTTPD_PROTO_NONE;
1326 msg->i_version = -1; /* FIXME */
1330 msg->psz_url = NULL;
1331 msg->psz_args = NULL;
1333 msg->i_channel = -1;
1340 msg->i_body_offset = 0;
1345 static void httpd_MsgClean( httpd_message_t *msg )
1349 free( msg->psz_url );
1350 free( msg->psz_args );
1351 for( i = 0; i < msg->i_name; i++ )
1353 free( msg->name[i] );
1354 free( msg->value[i] );
1358 free( msg->p_body );
1359 httpd_MsgInit( msg );
1362 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1366 for( i = 0; i < msg->i_name; i++ )
1368 if( !strcasecmp( msg->name[i], name ))
1370 return msg->value[i];
1376 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1381 va_start( args, psz_value );
1382 if( vasprintf( &value, psz_value, args ) == -1 )
1389 name = strdup( name );
1396 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1397 TAB_APPEND( msg->i_value, msg->value, value );
1400 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1402 cl->i_state = HTTPD_CLIENT_RECEIVING;
1403 cl->i_activity_date = now;
1404 cl->i_activity_timeout = INT64_C(10000000);
1405 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1407 cl->p_buffer = xmalloc( cl->i_buffer_size );
1408 cl->i_mode = HTTPD_CLIENT_FILE;
1409 cl->b_read_waiting = false;
1411 httpd_MsgInit( &cl->query );
1412 httpd_MsgInit( &cl->answer );
1415 void httpd_ClientModeStream( httpd_client_t *cl )
1417 cl->i_mode = HTTPD_CLIENT_STREAM;
1420 void httpd_ClientModeBidir( httpd_client_t *cl )
1422 cl->i_mode = HTTPD_CLIENT_BIDIR;
1425 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1427 return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1430 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1432 return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1435 static void httpd_ClientClean( httpd_client_t *cl )
1439 if( cl->p_tls != NULL )
1440 tls_ServerSessionClose( cl->p_tls );
1441 net_Close( cl->fd );
1445 httpd_MsgClean( &cl->answer );
1446 httpd_MsgClean( &cl->query );
1448 free( cl->p_buffer );
1449 cl->p_buffer = NULL;
1452 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1454 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1456 if( !cl ) return NULL;
1463 httpd_ClientInit( cl, now );
1469 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1471 tls_session_t *p_tls;
1476 val = p_tls ? tls_Recv (p_tls, p, i_len)
1477 : recv (cl->fd, p, i_len, 0);
1478 while (val == -1 && errno == EINTR);
1483 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1485 tls_session_t *p_tls;
1490 val = p_tls ? tls_Send( p_tls, p, i_len )
1491 : send (cl->fd, p, i_len, 0);
1492 while (val == -1 && errno == EINTR);
1499 const char name[16];
1505 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1506 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1507 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1508 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1509 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1510 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1511 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1512 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1513 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1514 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1515 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1519 static void httpd_ClientRecv( httpd_client_t *cl )
1523 /* ignore leading whites */
1524 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1525 ( cl->i_buffer == 0 ) )
1529 i_len = httpd_NetRecv( cl, &c, 1 );
1531 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1533 cl->p_buffer[0] = c;
1538 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1540 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1541 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1545 cl->i_buffer += i_len;
1548 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1550 /* Interleaved RTP over RTSP */
1551 cl->query.i_proto = HTTPD_PROTO_RTSP;
1552 cl->query.i_type = HTTPD_MSG_CHANNEL;
1553 cl->query.i_channel = cl->p_buffer[1];
1554 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1555 cl->query.p_body = xmalloc( cl->query.i_body );
1557 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1560 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1561 * this is the maximum we can ask at this point. */
1562 if( cl->i_buffer >= 7 )
1564 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1566 cl->query.i_proto = HTTPD_PROTO_HTTP;
1567 cl->query.i_type = HTTPD_MSG_ANSWER;
1569 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1571 cl->query.i_proto = HTTPD_PROTO_RTSP;
1572 cl->query.i_type = HTTPD_MSG_ANSWER;
1576 /* We need the full request line to determine the protocol. */
1577 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1578 cl->query.i_type = HTTPD_MSG_NONE;
1582 else if( cl->query.i_body > 0 )
1584 /* we are reading the body of a request or a channel */
1585 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1586 cl->query.i_body - cl->i_buffer );
1589 cl->i_buffer += i_len;
1591 if( cl->i_buffer >= cl->query.i_body )
1593 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1598 /* we are reading a header -> char by char */
1601 if( cl->i_buffer == cl->i_buffer_size )
1603 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1604 if( newbuf == NULL )
1610 cl->p_buffer = newbuf;
1611 cl->i_buffer_size += 1024;
1614 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1621 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1622 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1624 /* Request line is now complete */
1625 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1628 assert( cl->query.i_type == HTTPD_MSG_NONE );
1630 if( p == NULL ) /* no URI: evil guy */
1632 i_len = 0; /* drop connection */
1637 p++; /* skips extra spaces */
1640 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1641 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1643 i_len = 0; /* not supported currently -> drop */
1648 p++; /* skips extra spaces ever again */
1651 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1652 if( len < 7 ) /* foreign protocol */
1653 i_len = 0; /* I don't understand -> drop */
1655 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1657 cl->query.i_proto = HTTPD_PROTO_HTTP;
1658 cl->query.i_version = atoi( p + 7 );
1661 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1663 cl->query.i_proto = HTTPD_PROTO_RTSP;
1664 cl->query.i_version = atoi( p + 7 );
1667 if( memcmp( p, "HTTP/", 5 ) == 0 )
1669 const uint8_t sorry[] =
1670 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1671 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1672 i_len = 0; /* drop */
1675 if( memcmp( p, "RTSP/", 5 ) == 0 )
1677 const uint8_t sorry[] =
1678 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1679 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1680 i_len = 0; /* drop */
1682 else /* yet another foreign protocol */
1689 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1690 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1694 /* we have finished the header so parse it and set i_body */
1695 cl->p_buffer[cl->i_buffer] = '\0';
1697 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1700 * assume strlen( "HTTP/1.x" ) = 8
1702 cl->query.i_status =
1703 strtol( (char *)&cl->p_buffer[8],
1713 cl->query.i_type = HTTPD_MSG_NONE;
1715 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1717 for( i = 0; msg_type[i].name[0]; i++ )
1719 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1720 strlen( msg_type[i].name ) ) )
1722 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1723 cl->query.i_type = msg_type[i].i_type;
1724 if( cl->query.i_proto != msg_type[i].i_proto )
1727 cl->query.i_proto = HTTPD_PROTO_NONE;
1728 cl->query.i_type = HTTPD_MSG_NONE;
1735 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1737 cl->query.i_proto = HTTPD_PROTO_HTTP;
1739 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1741 cl->query.i_proto = HTTPD_PROTO_RTSP;
1753 p2 = strchr( p, ' ' );
1758 if( !strncasecmp( p, ( cl->query.i_proto
1759 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1760 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1761 { /* Skip hier-part of URL (if present) */
1762 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1763 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1764 { /* see RFC3986 §3.2 */
1766 while( *p && !strchr( "/?#", *p ) ) p++;
1769 cl->query.psz_url = strdup( p );
1770 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1773 cl->query.psz_args = (uint8_t *)strdup( p3 );
1780 p = strchr( p, '\n' );
1784 while( *p == '\n' || *p == '\r' )
1788 while( p && *p != '\0' )
1791 char *eol = p = strchr( p, '\n' );
1794 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1799 if( ( colon = strchr( line, ':' ) ) )
1805 while( *colon == ' ' )
1809 name = strdup( line );
1810 value = strdup( colon );
1812 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1813 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1815 if( !strcasecmp( name, "Content-Length" ) )
1817 cl->query.i_body = atol( value );
1824 while( *p == '\n' || *p == '\r' )
1831 if( cl->query.i_body > 0 )
1833 /* TODO Mhh, handle the case client will only send a
1834 * request and close the connection
1835 * to mark and of body (probably only RTSP) */
1836 cl->query.p_body = xmalloc( cl->query.i_body );
1841 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1847 /* check if the client is to be set to dead */
1848 #if defined( WIN32 ) || defined( UNDER_CE )
1849 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1851 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1854 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1856 /* connection closed -> end of data */
1857 if( cl->query.i_body > 0 )
1859 cl->query.i_body = cl->i_buffer;
1861 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1865 cl->i_state = HTTPD_CLIENT_DEAD;
1869 /* XXX: for QT I have to disable timeout. Try to find why */
1870 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1871 cl->i_activity_timeout = 0;
1873 #if 0 /* Debugging only */
1874 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1878 fprintf( stderr, "received new request\n" );
1879 fprintf( stderr, " - proto=%s\n",
1880 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1881 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1882 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1883 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1885 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1886 cl->query.psz_status );
1888 else if( cl->query.i_type != HTTPD_MSG_NONE )
1890 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1892 for( i = 0; i < cl->query.i_name; i++ )
1894 fprintf( stderr, " - option name='%s' value='%s'\n",
1895 cl->query.name[i], cl->query.value[i] );
1901 static void httpd_ClientSend( httpd_client_t *cl )
1906 if( cl->i_buffer < 0 )
1908 /* We need to create the header */
1911 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1913 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1914 for( i = 0; i < cl->answer.i_name; i++ )
1916 i_size += strlen( cl->answer.name[i] ) + 2 +
1917 strlen( cl->answer.value[i] ) + 2;
1920 if( cl->i_buffer_size < i_size )
1922 cl->i_buffer_size = i_size;
1923 free( cl->p_buffer );
1924 cl->p_buffer = xmalloc( i_size );
1926 p = (char *)cl->p_buffer;
1928 p += sprintf( p, "%s.%u %d %s\r\n",
1929 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1930 cl->answer.i_version,
1931 cl->answer.i_status, psz_status );
1932 for( i = 0; i < cl->answer.i_name; i++ )
1934 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1935 cl->answer.value[i] );
1937 p += sprintf( p, "\r\n" );
1940 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1942 /*fprintf( stderr, "sending answer\n" );
1943 fprintf( stderr, "%s", cl->p_buffer );*/
1946 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1947 cl->i_buffer_size - cl->i_buffer );
1950 cl->i_buffer += i_len;
1952 if( cl->i_buffer >= cl->i_buffer_size )
1954 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1955 !cl->b_read_waiting )
1957 /* catch more body data */
1958 int i_msg = cl->query.i_type;
1959 int64_t i_offset = cl->answer.i_body_offset;
1961 httpd_MsgClean( &cl->answer );
1962 cl->answer.i_body_offset = i_offset;
1964 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1965 &cl->answer, &cl->query );
1968 if( cl->answer.i_body > 0 )
1970 /* send the body data */
1971 free( cl->p_buffer );
1972 cl->p_buffer = cl->answer.p_body;
1973 cl->i_buffer_size = cl->answer.i_body;
1976 cl->answer.i_body = 0;
1977 cl->answer.p_body = NULL;
1982 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1988 #if defined( WIN32 ) || defined( UNDER_CE )
1989 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1991 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1995 cl->i_state = HTTPD_CLIENT_DEAD;
2000 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2002 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2005 cl->i_state = HTTPD_CLIENT_RECEIVING;
2009 cl->i_state = HTTPD_CLIENT_DEAD;
2014 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2018 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2020 switch( tls_SessionContinueHandshake( cl->p_tls ) )
2023 cl->i_state = HTTPD_CLIENT_RECEIVING;
2027 cl->i_state = HTTPD_CLIENT_DEAD;
2032 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2037 static void* httpd_HostThread( void *data )
2039 httpd_host_t *host = data;
2040 tls_session_t *p_tls = NULL;
2041 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2042 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2043 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2047 /* prepare a new TLS session */
2048 if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2049 p_tls = tls_ServerSessionPrepare( host->p_tls );
2051 struct pollfd ufd[host->nfd + host->i_client + 1];
2053 for( nfd = 0; nfd < host->nfd; nfd++ )
2055 ufd[nfd].fd = host->fds[nfd];
2056 ufd[nfd].events = POLLIN;
2057 ufd[nfd].revents = 0;
2060 /* add all socket that should be read/write and close dead connection */
2061 vlc_mutex_lock( &host->lock );
2062 while( host->i_url <= 0 && host->i_ref > 0 )
2063 vlc_cond_wait( &host->wait, &host->lock );
2065 mtime_t now = mdate();
2066 bool b_low_delay = false;
2068 for(int i_client = 0; i_client < host->i_client; i_client++ )
2070 httpd_client_t *cl = host->client[i_client];
2071 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2072 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2073 ( cl->i_activity_timeout > 0 &&
2074 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2076 httpd_ClientClean( cl );
2077 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2078 TAB_REMOVE( host->i_client, host->client, cl );
2084 struct pollfd *pufd = ufd + nfd;
2085 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2088 pufd->events = pufd->revents = 0;
2090 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2091 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2093 pufd->events = POLLIN;
2095 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2096 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2098 pufd->events = POLLOUT;
2100 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2102 httpd_message_t *answer = &cl->answer;
2103 httpd_message_t *query = &cl->query;
2104 int i_msg = query->i_type;
2106 httpd_MsgInit( answer );
2108 /* Handle what we received */
2109 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2110 (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2112 /* we can only receive request from client when not
2115 cl->i_state = HTTPD_CLIENT_DEAD;
2117 else if( i_msg == HTTPD_MSG_ANSWER )
2119 /* We are in BIDIR mode, trigger the callback and then
2120 * check for new data */
2121 if( cl->url && cl->url->catch[i_msg].cb )
2123 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2126 cl->i_state = HTTPD_CLIENT_WAITING;
2128 else if( i_msg == HTTPD_MSG_CHANNEL )
2130 /* We are in BIDIR mode, trigger the callback and then
2131 * check for new data */
2132 if( cl->url && cl->url->catch[i_msg].cb )
2134 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2137 cl->i_state = HTTPD_CLIENT_WAITING;
2139 else if( i_msg == HTTPD_MSG_OPTIONS )
2142 answer->i_type = HTTPD_MSG_ANSWER;
2143 answer->i_proto = query->i_proto;
2144 answer->i_status = 200;
2146 answer->p_body = NULL;
2148 httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2149 httpd_MsgAdd( answer, "Content-Length", "0" );
2151 switch( query->i_proto )
2153 case HTTPD_PROTO_HTTP:
2154 answer->i_version = 1;
2155 httpd_MsgAdd( answer, "Allow",
2156 "GET,HEAD,POST,OPTIONS" );
2159 case HTTPD_PROTO_RTSP:
2162 answer->i_version = 0;
2164 p = httpd_MsgGet( query, "Cseq" );
2166 httpd_MsgAdd( answer, "Cseq", "%s", p );
2167 p = httpd_MsgGet( query, "Timestamp" );
2169 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2171 p = httpd_MsgGet( query, "Require" );
2174 answer->i_status = 551;
2175 httpd_MsgAdd( query, "Unsupported", "%s", p );
2178 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2179 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2184 cl->i_buffer = -1; /* Force the creation of the answer in
2185 * httpd_ClientSend */
2186 cl->i_state = HTTPD_CLIENT_SENDING;
2188 else if( i_msg == HTTPD_MSG_NONE )
2190 if( query->i_proto == HTTPD_PROTO_NONE )
2193 cl->i_state = HTTPD_CLIENT_DEAD;
2200 answer->i_proto = query->i_proto ;
2201 answer->i_type = HTTPD_MSG_ANSWER;
2202 answer->i_version= 0;
2203 answer->i_status = 501;
2205 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2206 answer->p_body = (uint8_t *)p;
2207 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2209 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2210 cl->i_state = HTTPD_CLIENT_SENDING;
2215 bool b_auth_failed = false;
2216 bool b_hosts_failed = false;
2218 /* Search the url and trigger callbacks */
2219 for(int i = 0; i < host->i_url; i++ )
2221 httpd_url_t *url = host->url[i];
2223 if( !strcmp( url->psz_url, query->psz_url ) )
2225 if( url->catch[i_msg].cb )
2227 if( answer && ( url->p_acl != NULL ) )
2229 char ip[NI_MAXNUMERICHOST];
2231 if( ( httpd_ClientIP( cl, ip ) == NULL )
2232 || ACL_Check( url->p_acl, ip ) )
2234 b_hosts_failed = true;
2239 if( answer && ( *url->psz_user || *url->psz_password ) )
2241 /* create the headers */
2242 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2243 char *user = NULL, *pass = NULL;
2246 && !strncasecmp( b64, "BASIC", 5 ) )
2249 while( *b64 == ' ' )
2252 user = vlc_b64_decode( b64 );
2255 pass = strchr (user, ':');
2261 if ((user == NULL) || (pass == NULL)
2262 || strcmp (user, url->psz_user)
2263 || strcmp (pass, url->psz_password))
2265 httpd_MsgAdd( answer,
2267 "Basic realm=\"VLC stream\"" );
2268 /* We fail for all url */
2269 b_auth_failed = true;
2277 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2279 if( answer->i_proto == HTTPD_PROTO_NONE )
2281 /* Raw answer from a CGI */
2282 cl->i_buffer = cl->i_buffer_size;
2287 /* only one url can answer */
2289 if( cl->url == NULL )
2302 answer->i_proto = query->i_proto;
2303 answer->i_type = HTTPD_MSG_ANSWER;
2304 answer->i_version= 0;
2306 if( b_hosts_failed )
2308 answer->i_status = 403;
2310 else if( b_auth_failed )
2312 answer->i_status = 401;
2316 /* no url registered */
2317 answer->i_status = 404;
2320 answer->i_body = httpd_HtmlError (&p,
2323 answer->p_body = (uint8_t *)p;
2325 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2326 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2327 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2330 cl->i_state = HTTPD_CLIENT_SENDING;
2333 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2335 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2337 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2338 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2339 bool b_connection = false;
2340 bool b_keepalive = false;
2341 bool b_query = false;
2344 if( psz_connection )
2346 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2347 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2352 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2355 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2356 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2357 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2358 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2359 !b_query && !b_connection ) )
2361 httpd_MsgClean( &cl->query );
2362 httpd_MsgInit( &cl->query );
2365 cl->i_buffer_size = 1000;
2366 free( cl->p_buffer );
2367 cl->p_buffer = xmalloc( cl->i_buffer_size );
2368 cl->i_state = HTTPD_CLIENT_RECEIVING;
2372 cl->i_state = HTTPD_CLIENT_DEAD;
2374 httpd_MsgClean( &cl->answer );
2376 else if( cl->b_read_waiting )
2378 /* we have a message waiting for us to read it */
2379 httpd_MsgClean( &cl->answer );
2380 httpd_MsgClean( &cl->query );
2383 cl->i_buffer_size = 1000;
2384 free( cl->p_buffer );
2385 cl->p_buffer = xmalloc( cl->i_buffer_size );
2386 cl->i_state = HTTPD_CLIENT_RECEIVING;
2387 cl->b_read_waiting = false;
2391 int64_t i_offset = cl->answer.i_body_offset;
2392 httpd_MsgClean( &cl->answer );
2394 cl->answer.i_body_offset = i_offset;
2395 free( cl->p_buffer );
2396 cl->p_buffer = NULL;
2398 cl->i_buffer_size = 0;
2400 cl->i_state = HTTPD_CLIENT_WAITING;
2403 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2405 int64_t i_offset = cl->answer.i_body_offset;
2406 int i_msg = cl->query.i_type;
2408 httpd_MsgInit( &cl->answer );
2409 cl->answer.i_body_offset = i_offset;
2411 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2412 &cl->answer, &cl->query );
2413 if( cl->answer.i_type != HTTPD_MSG_NONE )
2415 /* we have new data, so re-enter send mode */
2417 cl->p_buffer = cl->answer.p_body;
2418 cl->i_buffer_size = cl->answer.i_body;
2419 cl->answer.p_body = NULL;
2420 cl->answer.i_body = 0;
2421 cl->i_state = HTTPD_CLIENT_SENDING;
2425 /* Special for BIDIR mode we also check reading */
2426 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2427 cl->i_state == HTTPD_CLIENT_SENDING )
2429 pufd->events |= POLLIN;
2432 if (pufd->events != 0)
2437 vlc_mutex_unlock( &host->lock );
2440 ufd[nfd].events = POLLIN;
2441 ufd[nfd].revents = 0;
2444 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2445 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2450 /* Kernel on low memory or a bug: pace */
2451 msg_Err( host, "polling error: %m" );
2458 if( ufd[nfd - 1].revents )
2461 /* Handle client sockets */
2462 vlc_mutex_lock( &host->lock );
2465 for( int i_client = 0; i_client < host->i_client; i_client++ )
2467 httpd_client_t *cl = host->client[i_client];
2468 const struct pollfd *pufd = &ufd[nfd];
2470 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2472 if( cl->fd != pufd->fd )
2473 continue; // we were not waiting for this client
2475 if( pufd->revents == 0 )
2476 continue; // no event received
2478 cl->i_activity_date = now;
2480 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2482 httpd_ClientRecv( cl );
2484 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2486 httpd_ClientSend( cl );
2488 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2490 httpd_ClientTlsHsIn( cl );
2492 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2494 httpd_ClientTlsHsOut( cl );
2497 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2498 cl->i_state == HTTPD_CLIENT_SENDING &&
2499 (pufd->revents & POLLIN) )
2501 cl->b_read_waiting = true;
2504 vlc_mutex_unlock( &host->lock );
2506 /* Handle server sockets (accept new connections) */
2507 for( nfd = 0; nfd < host->nfd; nfd++ )
2511 int fd = ufd[nfd].fd;
2513 assert (fd == host->fds[nfd]);
2515 if( ufd[nfd].revents == 0 )
2519 fd = vlc_accept (fd, NULL, NULL, true);
2522 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2523 &(int){ 1 }, sizeof(int));
2527 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2530 msg_Err( host, "Rejecting TLS connection" );
2536 case 1: /* missing input - most likely */
2537 i_state = HTTPD_CLIENT_TLS_HS_IN;
2540 case 2: /* missing output */
2541 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2545 if( (p_tls == NULL) != (host->p_tls == NULL) )
2546 break; // wasted TLS session, cannot accept() anymore
2549 stats_UpdateInteger( host, p_total_counter, 1, NULL );
2550 stats_UpdateInteger( host, p_active_counter, 1, NULL );
2551 cl = httpd_ClientNew( fd, p_tls, now );
2553 vlc_mutex_lock( &host->lock );
2554 TAB_APPEND( host->i_client, host->client, cl );
2555 vlc_mutex_unlock( &host->lock );
2557 cl->i_state = i_state; // override state for TLS
2559 if (host->p_tls != NULL)
2560 break; // cannot accept further without new TLS session
2566 tls_ServerSessionClose( p_tls );
2567 if( p_total_counter )
2568 stats_CounterClean( p_total_counter );
2569 if( p_active_counter )
2570 stats_CounterClean( p_active_counter );