1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2004-2006 VLC authors and VideoLAN
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 it
12 * under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with this program; if not, write to the Free Software Foundation,
23 * 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>
40 #include <vlc_charset.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 );
71 /* each host run in his own thread */
79 /* address/port and socket for listening at connections */
88 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
89 * This will slow down the url research but make my live easier
90 * All url will have their cb trigger, but only the first one can answer
96 httpd_client_t **client;
99 vlc_tls_creds_t *p_tls;
117 httpd_callback_sys_t *p_sys;
118 } catch[HTTPD_MSG_MAX];
124 HTTPD_CLIENT_RECEIVING,
125 HTTPD_CLIENT_RECEIVE_DONE,
127 HTTPD_CLIENT_SENDING,
128 HTTPD_CLIENT_SEND_DONE,
130 HTTPD_CLIENT_WAITING,
134 HTTPD_CLIENT_TLS_HS_IN,
135 HTTPD_CLIENT_TLS_HS_OUT
141 HTTPD_CLIENT_FILE, /* default */
142 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
145 struct httpd_client_t
156 mtime_t i_activity_date;
157 mtime_t i_activity_timeout;
159 /* buffer for reading header */
165 httpd_message_t query; /* client -> httpd */
166 httpd_message_t answer; /* httpd -> client */
173 /*****************************************************************************
175 *****************************************************************************/
178 const char psz_ext[8];
179 const char *psz_mime;
182 { ".htm", "text/html" },
183 { ".html", "text/html" },
184 { ".txt", "text/plain" },
185 { ".xml", "text/xml" },
186 { ".dtd", "text/dtd" },
188 { ".css", "text/css" },
191 { ".gif", "image/gif" },
192 { ".jpe", "image/jpeg" },
193 { ".jpg", "image/jpeg" },
194 { ".jpeg", "image/jpeg" },
195 { ".png", "image/png" },
196 /* same as modules/mux/mpjpeg.c here: */
197 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
200 { ".avi", "video/avi" },
201 { ".asf", "video/x-ms-asf" },
202 { ".m1a", "audio/mpeg" },
203 { ".m2a", "audio/mpeg" },
204 { ".m1v", "video/mpeg" },
205 { ".m2v", "video/mpeg" },
206 { ".mp2", "audio/mpeg" },
207 { ".mp3", "audio/mpeg" },
208 { ".mpa", "audio/mpeg" },
209 { ".mpg", "video/mpeg" },
210 { ".mpeg", "video/mpeg" },
211 { ".mpe", "video/mpeg" },
212 { ".mov", "video/quicktime" },
213 { ".moov", "video/quicktime" },
214 { ".oga", "audio/ogg" },
215 { ".ogg", "application/ogg" },
216 { ".ogm", "application/ogg" },
217 { ".ogv", "video/ogg" },
218 { ".ogx", "application/ogg" },
219 { ".spx", "audio/ogg" },
220 { ".wav", "audio/wav" },
221 { ".wma", "audio/x-ms-wma" },
222 { ".wmv", "video/x-ms-wmv" },
229 static const char *httpd_MimeFromUrl( const char *psz_url )
234 psz_ext = strrchr( psz_url, '.' );
239 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
241 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
243 return http_mime[i].psz_mime;
247 return "application/octet-stream";
254 const char psz_reason[36];
257 static const http_status_info http_reason[] =
259 /*{ 100, "Continue" },
260 { 101, "Switching Protocols" },*/
262 /*{ 201, "Created" },
264 { 203, "Non-authoritative information" },
265 { 204, "No content" },
266 { 205, "Reset content" },
267 { 206, "Partial content" },
268 { 250, "Low on storage space" },
269 { 300, "Multiple choices" },*/
270 { 301, "Moved permanently" },
271 /*{ 302, "Moved temporarily" },
272 { 303, "See other" },
273 { 304, "Not modified" },
274 { 305, "Use proxy" },
275 { 307, "Temporary redirect" },
276 { 400, "Bad request" },*/
277 { 401, "Unauthorized" },
278 /*{ 402, "Payment Required" },*/
279 { 403, "Forbidden" },
280 { 404, "Not found" },
281 { 405, "Method not allowed" },
282 /*{ 406, "Not acceptable" },
283 { 407, "Proxy authentication required" },
284 { 408, "Request time-out" },
287 { 411, "Length required" },
288 { 412, "Precondition failed" },
289 { 413, "Request entity too large" },
290 { 414, "Request-URI too large" },
291 { 415, "Unsupported media Type" },
292 { 416, "Requested range not satisfiable" },
293 { 417, "Expectation failed" },
294 { 451, "Parameter not understood" },
295 { 452, "Conference not found" },
296 { 453, "Not enough bandwidth" },*/
297 { 454, "Session not found" },
298 { 455, "Method not valid in this State" },
299 { 456, "Header field not valid for resource" },
300 { 457, "Invalid range" },
301 /*{ 458, "Read-only parameter" },*/
302 { 459, "Aggregate operation not allowed" },
303 { 460, "Non-aggregate operation not allowed" },
304 { 461, "Unsupported transport" },
305 /*{ 462, "Destination unreachable" },*/
306 { 500, "Internal server error" },
307 { 501, "Not implemented" },
308 /*{ 502, "Bad gateway" },*/
309 { 503, "Service unavailable" },
310 /*{ 504, "Gateway time-out" },*/
311 { 505, "Protocol version not supported" },
312 { 551, "Option not supported" },
316 static const char psz_fallback_reason[5][16] =
317 { "Continue", "OK", "Found", "Client error", "Server error" };
319 static const char *httpd_ReasonFromCode( unsigned i_code )
321 const http_status_info *p;
323 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
325 for (p = http_reason; i_code > p->i_code; p++);
327 if( p->i_code == i_code )
328 return p->psz_reason;
330 return psz_fallback_reason[(i_code / 100) - 1];
334 static size_t httpd_HtmlError (char **body, int code, const char *url)
336 const char *errname = httpd_ReasonFromCode (code);
337 assert (errname != NULL);
339 int res = asprintf (body,
340 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
341 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
342 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
343 "<html lang=\"en\">\n"
345 "<title>%s</title>\n"
348 "<h1>%d %s%s%s%s</h1>\n"
350 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
352 "</html>\n", errname, code, errname,
353 (url ? " (" : ""), (url ? url : ""), (url ? ")" : ""));
365 /*****************************************************************************
366 * High Level Functions: httpd_file_t
367 *****************************************************************************/
375 httpd_file_callback_t pf_fill;
376 httpd_file_sys_t *p_sys;
381 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
382 httpd_message_t *answer, const httpd_message_t *query )
384 httpd_file_t *file = (httpd_file_t*)p_sys;
385 uint8_t **pp_body, *p_body;
386 const char *psz_connection;
387 int *pi_body, i_body;
389 if( answer == NULL || query == NULL )
393 answer->i_proto = HTTPD_PROTO_HTTP;
394 answer->i_version= 1;
395 answer->i_type = HTTPD_MSG_ANSWER;
397 answer->i_status = 200;
399 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
400 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
402 if( query->i_type != HTTPD_MSG_HEAD )
404 pp_body = &answer->p_body;
405 pi_body = &answer->i_body;
409 /* The file still needs to be executed. */
416 if( query->i_type == HTTPD_MSG_POST )
418 /* msg_Warn not supported */
421 uint8_t *psz_args = query->psz_args;
422 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
424 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
429 /* We respect client request */
430 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
431 if( psz_connection != NULL )
433 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
436 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
441 httpd_file_t *httpd_FileNew( httpd_host_t *host,
442 const char *psz_url, const char *psz_mime,
443 const char *psz_user, const char *psz_password,
444 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
445 httpd_file_sys_t *p_sys )
447 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
449 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
450 psz_password, p_acl )
457 file->psz_url = strdup( psz_url );
458 if( psz_mime && *psz_mime )
460 file->psz_mime = strdup( psz_mime );
464 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
467 file->pf_fill = pf_fill;
470 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
471 (httpd_callback_sys_t*)file );
472 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
473 (httpd_callback_sys_t*)file );
474 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
475 (httpd_callback_sys_t*)file );
480 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
482 httpd_file_sys_t *p_sys = file->p_sys;
484 httpd_UrlDelete( file->url );
486 free( file->psz_url );
487 free( file->psz_mime );
494 /*****************************************************************************
495 * High Level Functions: httpd_handler_t (for CGIs)
496 *****************************************************************************/
497 struct httpd_handler_t
501 httpd_handler_callback_t pf_fill;
502 httpd_handler_sys_t *p_sys;
507 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
508 httpd_message_t *answer, const httpd_message_t *query )
510 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
511 char psz_remote_addr[NI_MAXNUMERICHOST];
513 if( answer == NULL || query == NULL )
517 answer->i_proto = HTTPD_PROTO_NONE;
518 answer->i_type = HTTPD_MSG_ANSWER;
520 /* We do it ourselves, thanks */
521 answer->i_status = 0;
523 if( httpd_ClientIP( cl, psz_remote_addr, NULL ) == NULL )
524 *psz_remote_addr = '\0';
526 uint8_t *psz_args = query->psz_args;
527 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
528 query->i_type, query->p_body, query->i_body,
529 psz_remote_addr, NULL,
530 &answer->p_body, &answer->i_body );
532 if( query->i_type == HTTPD_MSG_HEAD )
534 char *p = (char *)answer->p_body;
536 /* Looks for end of header (i.e. one empty line) */
537 while ( (p = strchr( p, '\r' )) != NULL )
539 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
540 && p[3] && p[3] == '\n' )
549 answer->i_body = strlen((char*)answer->p_body) + 1;
550 answer->p_body = xrealloc( answer->p_body, answer->i_body );
554 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
556 int i_status, i_headers;
557 char *psz_headers, *psz_new;
558 const char *psz_status;
560 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
563 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
564 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
565 if( *psz_headers == '\n' ) psz_headers++;
566 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
571 psz_headers = (char *)answer->p_body;
572 i_headers = answer->i_body;
575 psz_status = httpd_ReasonFromCode( i_status );
576 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
577 + strlen(psz_status) + i_headers - 1;
578 psz_new = (char *)xmalloc( answer->i_body + 1);
579 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
580 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
581 free( answer->p_body );
582 answer->p_body = (uint8_t *)psz_new;
588 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
589 const char *psz_user,
590 const char *psz_password,
591 const vlc_acl_t *p_acl,
592 httpd_handler_callback_t pf_fill,
593 httpd_handler_sys_t *p_sys )
595 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
597 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
598 psz_password, p_acl )
605 handler->pf_fill = pf_fill;
606 handler->p_sys = p_sys;
608 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
609 (httpd_callback_sys_t*)handler );
610 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
611 (httpd_callback_sys_t*)handler );
612 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
613 (httpd_callback_sys_t*)handler );
618 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
620 httpd_handler_sys_t *p_sys = handler->p_sys;
621 httpd_UrlDelete( handler->url );
626 /*****************************************************************************
627 * High Level Functions: httpd_redirect_t
628 *****************************************************************************/
629 struct httpd_redirect_t
635 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
636 httpd_client_t *cl, httpd_message_t *answer,
637 const httpd_message_t *query )
639 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
643 if( answer == NULL || query == NULL )
647 answer->i_proto = HTTPD_PROTO_HTTP;
648 answer->i_version= 1;
649 answer->i_type = HTTPD_MSG_ANSWER;
650 answer->i_status = 301;
652 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
653 answer->p_body = (unsigned char *)p_body;
655 /* XXX check if it's ok or we need to set an absolute url */
656 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
658 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
663 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
664 const char *psz_url_src )
666 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
668 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
673 rdir->psz_dst = strdup( psz_url_dst );
675 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
676 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
677 (httpd_callback_sys_t*)rdir );
678 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
679 (httpd_callback_sys_t*)rdir );
680 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
681 (httpd_callback_sys_t*)rdir );
682 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
683 (httpd_callback_sys_t*)rdir );
687 void httpd_RedirectDelete( httpd_redirect_t *rdir )
689 httpd_UrlDelete( rdir->url );
690 free( rdir->psz_dst );
694 /*****************************************************************************
695 * High Level Funtions: httpd_stream_t
696 *****************************************************************************/
697 struct httpd_stream_t
704 /* Header to send as first packet */
708 /* circular buffer */
709 int i_buffer_size; /* buffer size, can't be reallocated smaller */
710 uint8_t *p_buffer; /* buffer */
711 int64_t i_buffer_pos; /* absolute position from begining */
712 int64_t i_buffer_last_pos; /* a new connection will start with that */
715 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
716 httpd_client_t *cl, httpd_message_t *answer,
717 const httpd_message_t *query )
719 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
721 if( answer == NULL || query == NULL || cl == NULL )
726 if( answer->i_body_offset > 0 )
732 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
733 answer->i_body_offset );
736 if( answer->i_body_offset >= stream->i_buffer_pos )
738 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
739 return VLC_EGENERIC; /* wait, no data available */
741 if( answer->i_body_offset + stream->i_buffer_size <
742 stream->i_buffer_pos )
744 /* this client isn't fast enough */
746 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
747 answer->i_body_offset, stream->i_buffer_last_pos );
749 answer->i_body_offset = stream->i_buffer_last_pos;
752 i_pos = answer->i_body_offset % stream->i_buffer_size;
753 i_write = stream->i_buffer_pos - answer->i_body_offset;
754 if( i_write > HTTPD_CL_BUFSIZE )
756 i_write = HTTPD_CL_BUFSIZE;
758 else if( i_write <= 0 )
760 return VLC_EGENERIC; /* wait, no data available */
763 /* Don't go past the end of the circular buffer */
764 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
766 /* using HTTPD_MSG_ANSWER -> data available */
767 answer->i_proto = HTTPD_PROTO_HTTP;
768 answer->i_version= 0;
769 answer->i_type = HTTPD_MSG_ANSWER;
771 answer->i_body = i_write;
772 answer->p_body = xmalloc( i_write );
773 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
775 answer->i_body_offset += i_write;
781 answer->i_proto = HTTPD_PROTO_HTTP;
782 answer->i_version= 0;
783 answer->i_type = HTTPD_MSG_ANSWER;
785 answer->i_status = 200;
787 if( query->i_type != HTTPD_MSG_HEAD )
789 cl->b_stream_mode = true;
790 vlc_mutex_lock( &stream->lock );
791 /* Send the header */
792 if( stream->i_header > 0 )
794 answer->i_body = stream->i_header;
795 answer->p_body = xmalloc( stream->i_header );
796 memcpy( answer->p_body, stream->p_header, stream->i_header );
798 answer->i_body_offset = stream->i_buffer_last_pos;
799 vlc_mutex_unlock( &stream->lock );
803 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
804 answer->i_body_offset = 0;
807 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
809 bool b_xplaystream = false;
812 httpd_MsgAdd( answer, "Content-type", "%s",
813 "application/octet-stream" );
814 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
815 httpd_MsgAdd( answer, "Pragma", "no-cache" );
816 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
817 vlc_mrand48()&0x7fff );
818 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
820 /* Check if there is a xPlayStrm=1 */
821 for( i = 0; i < query->i_name; i++ )
823 if( !strcasecmp( query->name[i], "Pragma" ) &&
824 strstr( query->value[i], "xPlayStrm=1" ) )
826 b_xplaystream = true;
832 answer->i_body_offset = 0;
837 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
839 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
844 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
845 const char *psz_url, const char *psz_mime,
846 const char *psz_user, const char *psz_password,
847 const vlc_acl_t *p_acl )
849 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
851 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
852 psz_password, p_acl )
858 vlc_mutex_init( &stream->lock );
859 if( psz_mime && *psz_mime )
861 stream->psz_mime = strdup( psz_mime );
865 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
867 stream->i_header = 0;
868 stream->p_header = NULL;
869 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
870 stream->p_buffer = xmalloc( stream->i_buffer_size );
871 /* We set to 1 to make life simpler
872 * (this way i_body_offset can never be 0) */
873 stream->i_buffer_pos = 1;
874 stream->i_buffer_last_pos = 1;
876 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
877 (httpd_callback_sys_t*)stream );
878 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
879 (httpd_callback_sys_t*)stream );
880 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
881 (httpd_callback_sys_t*)stream );
886 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
888 vlc_mutex_lock( &stream->lock );
889 free( stream->p_header );
890 stream->p_header = NULL;
892 stream->i_header = i_data;
895 stream->p_header = xmalloc( i_data );
896 memcpy( stream->p_header, p_data, i_data );
898 vlc_mutex_unlock( &stream->lock );
903 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
908 if( i_data < 0 || p_data == NULL )
912 vlc_mutex_lock( &stream->lock );
914 /* save this pointer (to be used by new connection) */
915 stream->i_buffer_last_pos = stream->i_buffer_pos;
917 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
923 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
925 /* Ok, we can't go past the end of our buffer */
926 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
928 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
933 stream->i_buffer_pos += i_data;
935 vlc_mutex_unlock( &stream->lock );
939 void httpd_StreamDelete( httpd_stream_t *stream )
941 httpd_UrlDelete( stream->url );
942 vlc_mutex_destroy( &stream->lock );
943 free( stream->psz_mime );
944 free( stream->p_header );
945 free( stream->p_buffer );
949 /*****************************************************************************
951 *****************************************************************************/
952 static void* httpd_HostThread( void * );
953 static httpd_host_t *httpd_HostCreate( vlc_object_t *, const char *,
954 const char *, vlc_tls_creds_t * );
956 /* create a new host */
957 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
959 return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
962 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
964 char *cert = var_InheritString( obj, "http-cert" );
967 msg_Err( obj, "HTTP/TLS certificate not specified!" );
971 char *key = var_InheritString( obj, "http-key" );
972 vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
976 msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
977 cert, (key != NULL) ? key : cert );
985 char *ca = var_InheritString( obj, "http-ca" );
988 if( vlc_tls_ServerAddCA( tls, ca ) )
990 msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
997 char *crl = var_InheritString( obj, "http-crl" );
1000 if( vlc_tls_ServerAddCRL( tls, crl ) )
1002 msg_Err( obj, "TLS CRL error (%s)", crl );
1009 return httpd_HostCreate( obj, "http-host", "https-port", tls );
1012 vlc_tls_ServerDelete( tls );
1016 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
1018 return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
1021 static struct httpd_t
1025 httpd_host_t **host;
1027 } httpd = { VLC_STATIC_MUTEX, NULL, 0 };
1029 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
1030 const char *hostvar,
1031 const char *portvar,
1032 vlc_tls_creds_t *p_tls )
1035 unsigned port = var_InheritInteger( p_this, portvar );
1037 /* to be sure to avoid multiple creation */
1038 vlc_mutex_lock( &httpd.mutex );
1040 /* verify if it already exist */
1041 for( int i = 0; i < httpd.i_host; i++ )
1043 host = httpd.host[i];
1045 /* cannot mix TLS and non-TLS hosts */
1046 if( host->port != port
1047 || (host->p_tls != NULL) != (p_tls != NULL) )
1050 /* Increase existing matching host reference count.
1051 * The reference count is written under both the global httpd and the
1052 * host lock. It is read with either or both locks held. The global
1053 * lock is always acquired first. */
1054 vlc_mutex_lock( &host->lock );
1056 vlc_mutex_unlock( &host->lock );
1058 vlc_mutex_unlock( &httpd.mutex );
1060 vlc_tls_ServerDelete( p_tls );
1066 /* create the new host */
1067 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1072 vlc_mutex_init( &host->lock );
1073 vlc_cond_init( &host->wait );
1076 char *hostname = var_InheritString( p_this, hostvar );
1077 host->fds = net_ListenTCP( p_this, hostname, port );
1079 if( host->fds == NULL )
1081 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1084 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1086 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1088 msg_Err( host, "signaling pipe error: %m" );
1096 host->client = NULL;
1097 host->p_tls = p_tls;
1099 /* create the thread */
1100 if( vlc_clone( &host->thread, httpd_HostThread, host,
1101 VLC_THREAD_PRIORITY_LOW ) )
1103 msg_Err( p_this, "cannot spawn http host thread" );
1107 /* now add it to httpd */
1108 TAB_APPEND( httpd.i_host, httpd.host, host );
1109 vlc_mutex_unlock( &httpd.mutex );
1114 vlc_mutex_unlock( &httpd.mutex );
1118 net_ListenClose( host->fds );
1119 vlc_cond_destroy( &host->wait );
1120 vlc_mutex_destroy( &host->lock );
1121 vlc_object_release( host );
1125 vlc_tls_ServerDelete( p_tls );
1131 void httpd_HostDelete( httpd_host_t *host )
1134 bool delete = false;
1136 vlc_mutex_lock( &httpd.mutex );
1138 vlc_mutex_lock( &host->lock );
1140 if( host->i_ref == 0 )
1142 vlc_cond_signal( &host->wait );
1145 vlc_mutex_unlock( &host->lock );
1149 vlc_mutex_unlock( &httpd.mutex );
1150 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1153 TAB_REMOVE( httpd.i_host, httpd.host, host );
1155 vlc_object_kill( host );
1156 vlc_join( host->thread, NULL );
1158 msg_Dbg( host, "HTTP host removed" );
1160 for( i = 0; i < host->i_url; i++ )
1162 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1164 for( i = 0; i < host->i_client; i++ )
1166 httpd_client_t *cl = host->client[i];
1167 msg_Warn( host, "client still connected" );
1168 httpd_ClientClean( cl );
1169 TAB_REMOVE( host->i_client, host->client, cl );
1175 if( host->p_tls != NULL)
1176 vlc_tls_ServerDelete( host->p_tls );
1178 net_ListenClose( host->fds );
1179 vlc_cond_destroy( &host->wait );
1180 vlc_mutex_destroy( &host->lock );
1181 vlc_object_release( host );
1182 vlc_mutex_unlock( &httpd.mutex );
1185 /* register a new url */
1186 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1187 const char *psz_user, const char *psz_password,
1188 const vlc_acl_t *p_acl, bool b_check )
1193 assert( psz_url != NULL );
1195 vlc_mutex_lock( &host->lock );
1198 for( i = 0; i < host->i_url; i++ )
1200 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1203 "cannot add '%s' (url already defined)", psz_url );
1204 vlc_mutex_unlock( &host->lock );
1210 url = xmalloc( sizeof( httpd_url_t ) );
1213 vlc_mutex_init( &url->lock );
1214 url->psz_url = strdup( psz_url );
1215 url->psz_user = strdup( psz_user ? psz_user : "" );
1216 url->psz_password = strdup( psz_password ? psz_password : "" );
1217 url->p_acl = ACL_Duplicate( host, p_acl );
1218 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1220 url->catch[i].cb = NULL;
1221 url->catch[i].p_sys = NULL;
1224 TAB_APPEND( host->i_url, host->url, url );
1225 vlc_cond_signal( &host->wait );
1226 vlc_mutex_unlock( &host->lock );
1231 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1232 const char *psz_user, const char *psz_password,
1233 const vlc_acl_t *p_acl )
1235 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1236 psz_password, p_acl, false );
1239 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1240 const char *psz_user, const char *psz_password,
1241 const vlc_acl_t *p_acl )
1243 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1244 psz_password, p_acl, true );
1247 /* register callback on a url */
1248 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1249 httpd_callback_sys_t *p_sys )
1251 vlc_mutex_lock( &url->lock );
1252 url->catch[i_msg].cb = cb;
1253 url->catch[i_msg].p_sys= p_sys;
1254 vlc_mutex_unlock( &url->lock );
1260 void httpd_UrlDelete( httpd_url_t *url )
1262 httpd_host_t *host = url->host;
1265 vlc_mutex_lock( &host->lock );
1266 TAB_REMOVE( host->i_url, host->url, url );
1268 vlc_mutex_destroy( &url->lock );
1269 free( url->psz_url );
1270 free( url->psz_user );
1271 free( url->psz_password );
1272 ACL_Destroy( url->p_acl );
1274 for( i = 0; i < host->i_client; i++ )
1276 httpd_client_t *client = host->client[i];
1278 if( client->url == url )
1280 /* TODO complete it */
1281 msg_Warn( host, "force closing connections" );
1282 httpd_ClientClean( client );
1283 TAB_REMOVE( host->i_client, host->client, client );
1289 vlc_mutex_unlock( &host->lock );
1292 static void httpd_MsgInit( httpd_message_t *msg )
1295 msg->i_type = HTTPD_MSG_NONE;
1296 msg->i_proto = HTTPD_PROTO_NONE;
1297 msg->i_version = -1; /* FIXME */
1301 msg->psz_url = NULL;
1302 msg->psz_args = NULL;
1309 msg->i_body_offset = 0;
1314 static void httpd_MsgClean( httpd_message_t *msg )
1318 free( msg->psz_url );
1319 free( msg->psz_args );
1320 for( i = 0; i < msg->i_name; i++ )
1322 free( msg->name[i] );
1323 free( msg->value[i] );
1327 free( msg->p_body );
1328 httpd_MsgInit( msg );
1331 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1335 for( i = 0; i < msg->i_name; i++ )
1337 if( !strcasecmp( msg->name[i], name ))
1339 return msg->value[i];
1345 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1350 va_start( args, psz_value );
1351 if( us_vasprintf( &value, psz_value, args ) == -1 )
1358 name = strdup( name );
1365 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1366 TAB_APPEND( msg->i_value, msg->value, value );
1369 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1371 cl->i_state = HTTPD_CLIENT_RECEIVING;
1372 cl->i_activity_date = now;
1373 cl->i_activity_timeout = INT64_C(10000000);
1374 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1376 cl->p_buffer = xmalloc( cl->i_buffer_size );
1377 cl->b_stream_mode = false;
1379 httpd_MsgInit( &cl->query );
1380 httpd_MsgInit( &cl->answer );
1383 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1385 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1388 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1390 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1393 static void httpd_ClientClean( httpd_client_t *cl )
1397 if( cl->p_tls != NULL )
1398 vlc_tls_ServerSessionDelete( cl->p_tls );
1399 net_Close( cl->fd );
1403 httpd_MsgClean( &cl->answer );
1404 httpd_MsgClean( &cl->query );
1406 free( cl->p_buffer );
1407 cl->p_buffer = NULL;
1410 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1412 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1414 if( !cl ) return NULL;
1421 httpd_ClientInit( cl, now );
1427 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1434 val = p_tls ? tls_Recv (p_tls, p, i_len)
1435 : recv (cl->fd, p, i_len, 0);
1436 while (val == -1 && errno == EINTR);
1441 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1448 val = p_tls ? tls_Send( p_tls, p, i_len )
1449 : send (cl->fd, p, i_len, 0);
1450 while (val == -1 && errno == EINTR);
1457 const char name[16];
1463 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1464 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1465 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1466 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1467 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1468 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1469 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1470 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1471 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1472 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1473 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1477 static void httpd_ClientRecv( httpd_client_t *cl )
1481 /* ignore leading whites */
1482 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1483 ( cl->i_buffer == 0 ) )
1487 i_len = httpd_NetRecv( cl, &c, 1 );
1489 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1491 cl->p_buffer[0] = c;
1496 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1498 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1499 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1503 cl->i_buffer += i_len;
1506 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1507 * this is the maximum we can ask at this point. */
1508 if( cl->i_buffer >= 7 )
1510 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1512 cl->query.i_proto = HTTPD_PROTO_HTTP;
1513 cl->query.i_type = HTTPD_MSG_ANSWER;
1515 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1517 cl->query.i_proto = HTTPD_PROTO_RTSP;
1518 cl->query.i_type = HTTPD_MSG_ANSWER;
1522 /* We need the full request line to determine the protocol. */
1523 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1524 cl->query.i_type = HTTPD_MSG_NONE;
1528 else if( cl->query.i_body > 0 )
1530 /* we are reading the body of a request or a channel */
1531 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1532 cl->query.i_body - cl->i_buffer );
1535 cl->i_buffer += i_len;
1537 if( cl->i_buffer >= cl->query.i_body )
1539 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1544 /* we are reading a header -> char by char */
1547 if( cl->i_buffer == cl->i_buffer_size )
1549 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1550 if( newbuf == NULL )
1556 cl->p_buffer = newbuf;
1557 cl->i_buffer_size += 1024;
1560 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1567 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1568 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1570 /* Request line is now complete */
1571 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1574 assert( cl->query.i_type == HTTPD_MSG_NONE );
1576 if( p == NULL ) /* no URI: evil guy */
1578 i_len = 0; /* drop connection */
1583 p++; /* skips extra spaces */
1586 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1587 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1589 i_len = 0; /* not supported currently -> drop */
1594 p++; /* skips extra spaces ever again */
1597 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1598 if( len < 7 ) /* foreign protocol */
1599 i_len = 0; /* I don't understand -> drop */
1601 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1603 cl->query.i_proto = HTTPD_PROTO_HTTP;
1604 cl->query.i_version = atoi( p + 7 );
1607 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1609 cl->query.i_proto = HTTPD_PROTO_RTSP;
1610 cl->query.i_version = atoi( p + 7 );
1613 if( memcmp( p, "HTTP/", 5 ) == 0 )
1615 const uint8_t sorry[] =
1616 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1617 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1618 i_len = 0; /* drop */
1621 if( memcmp( p, "RTSP/", 5 ) == 0 )
1623 const uint8_t sorry[] =
1624 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1625 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1626 i_len = 0; /* drop */
1628 else /* yet another foreign protocol */
1635 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1636 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1640 /* we have finished the header so parse it and set i_body */
1641 cl->p_buffer[cl->i_buffer] = '\0';
1643 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1646 * assume strlen( "HTTP/1.x" ) = 8
1648 cl->query.i_status =
1649 strtol( (char *)&cl->p_buffer[8],
1659 cl->query.i_type = HTTPD_MSG_NONE;
1661 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1663 for( i = 0; msg_type[i].name[0]; i++ )
1665 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1666 strlen( msg_type[i].name ) ) )
1668 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1669 cl->query.i_type = msg_type[i].i_type;
1670 if( cl->query.i_proto != msg_type[i].i_proto )
1673 cl->query.i_proto = HTTPD_PROTO_NONE;
1674 cl->query.i_type = HTTPD_MSG_NONE;
1681 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1683 cl->query.i_proto = HTTPD_PROTO_HTTP;
1685 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1687 cl->query.i_proto = HTTPD_PROTO_RTSP;
1699 p2 = strchr( p, ' ' );
1704 if( !strncasecmp( p, ( cl->query.i_proto
1705 == HTTPD_PROTO_HTTP ) ? "http:" : "rtsp:", 5 ) )
1706 { /* Skip hier-part of URL (if present) */
1708 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1709 { /* see RFC3986 §3.2 */
1711 p += strcspn( p, "/?#" );
1715 if( !strncasecmp( p, ( cl->query.i_proto
1716 == HTTPD_PROTO_HTTP ) ? "https:" : "rtsps:", 6 ) )
1717 { /* Skip hier-part of URL (if present) */
1719 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1720 { /* see RFC3986 §3.2 */
1722 p += strcspn( p, "/?#" );
1726 cl->query.psz_url = strdup( p );
1727 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1730 cl->query.psz_args = (uint8_t *)strdup( p3 );
1737 p = strchr( p, '\n' );
1741 while( *p == '\n' || *p == '\r' )
1745 while( p && *p != '\0' )
1748 char *eol = p = strchr( p, '\n' );
1751 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1756 if( ( colon = strchr( line, ':' ) ) )
1762 while( *colon == ' ' )
1766 name = strdup( line );
1767 value = strdup( colon );
1769 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1770 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1772 if( !strcasecmp( name, "Content-Length" ) )
1774 cl->query.i_body = atol( value );
1781 while( *p == '\n' || *p == '\r' )
1788 if( cl->query.i_body > 0 )
1790 /* TODO Mhh, handle the case where the client only
1791 * sends a request and closes the connection to
1792 * mark the end of the body (probably only RTSP) */
1793 cl->query.p_body = malloc( cl->query.i_body );
1795 if ( cl->query.p_body == NULL )
1797 switch (cl->query.i_proto)
1799 case HTTPD_PROTO_HTTP:
1801 const uint8_t sorry[] =
1802 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1803 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1806 case HTTPD_PROTO_RTSP:
1808 const uint8_t sorry[] =
1809 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1810 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1816 i_len = 0; /* drop */
1822 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1828 /* check if the client is to be set to dead */
1829 #if defined( WIN32 ) || defined( UNDER_CE )
1830 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1832 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1835 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1837 /* connection closed -> end of data */
1838 if( cl->query.i_body > 0 )
1840 cl->query.i_body = cl->i_buffer;
1842 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1846 cl->i_state = HTTPD_CLIENT_DEAD;
1850 /* XXX: for QT I have to disable timeout. Try to find why */
1851 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1852 cl->i_activity_timeout = 0;
1854 #if 0 /* Debugging only */
1855 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1859 fprintf( stderr, "received new request\n" );
1860 fprintf( stderr, " - proto=%s\n",
1861 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1862 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1863 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1864 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1866 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1867 cl->query.psz_status );
1869 else if( cl->query.i_type != HTTPD_MSG_NONE )
1871 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1873 for( i = 0; i < cl->query.i_name; i++ )
1875 fprintf( stderr, " - option name='%s' value='%s'\n",
1876 cl->query.name[i], cl->query.value[i] );
1882 static void httpd_ClientSend( httpd_client_t *cl )
1887 if( cl->i_buffer < 0 )
1889 /* We need to create the header */
1892 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1894 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1895 for( i = 0; i < cl->answer.i_name; i++ )
1897 i_size += strlen( cl->answer.name[i] ) + 2 +
1898 strlen( cl->answer.value[i] ) + 2;
1901 if( cl->i_buffer_size < i_size )
1903 cl->i_buffer_size = i_size;
1904 free( cl->p_buffer );
1905 cl->p_buffer = xmalloc( i_size );
1907 p = (char *)cl->p_buffer;
1909 p += sprintf( p, "%s.%u %d %s\r\n",
1910 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1911 cl->answer.i_version,
1912 cl->answer.i_status, psz_status );
1913 for( i = 0; i < cl->answer.i_name; i++ )
1915 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1916 cl->answer.value[i] );
1918 p += sprintf( p, "\r\n" );
1921 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1923 /*fprintf( stderr, "sending answer\n" );
1924 fprintf( stderr, "%s", cl->p_buffer );*/
1927 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1928 cl->i_buffer_size - cl->i_buffer );
1931 cl->i_buffer += i_len;
1933 if( cl->i_buffer >= cl->i_buffer_size )
1935 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 )
1937 /* catch more body data */
1938 int i_msg = cl->query.i_type;
1939 int64_t i_offset = cl->answer.i_body_offset;
1941 httpd_MsgClean( &cl->answer );
1942 cl->answer.i_body_offset = i_offset;
1944 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1945 &cl->answer, &cl->query );
1948 if( cl->answer.i_body > 0 )
1950 /* send the body data */
1951 free( cl->p_buffer );
1952 cl->p_buffer = cl->answer.p_body;
1953 cl->i_buffer_size = cl->answer.i_body;
1956 cl->answer.i_body = 0;
1957 cl->answer.p_body = NULL;
1962 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1968 #if defined( WIN32 ) || defined( UNDER_CE )
1969 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1971 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1975 cl->i_state = HTTPD_CLIENT_DEAD;
1980 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1982 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
1985 cl->i_state = HTTPD_CLIENT_RECEIVING;
1989 cl->i_state = HTTPD_CLIENT_DEAD;
1994 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1998 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2000 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
2003 cl->i_state = HTTPD_CLIENT_RECEIVING;
2007 cl->i_state = HTTPD_CLIENT_DEAD;
2012 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2017 static void* httpd_HostThread( void *data )
2019 httpd_host_t *host = data;
2020 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2021 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2022 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2026 struct pollfd ufd[host->nfd + host->i_client + 1];
2028 for( nfd = 0; nfd < host->nfd; nfd++ )
2030 ufd[nfd].fd = host->fds[nfd];
2031 ufd[nfd].events = POLLIN;
2032 ufd[nfd].revents = 0;
2035 /* add all socket that should be read/write and close dead connection */
2036 vlc_mutex_lock( &host->lock );
2037 while( host->i_url <= 0 && host->i_ref > 0 )
2038 vlc_cond_wait( &host->wait, &host->lock );
2040 mtime_t now = mdate();
2041 bool b_low_delay = false;
2043 for(int i_client = 0; i_client < host->i_client; i_client++ )
2045 httpd_client_t *cl = host->client[i_client];
2046 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2047 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2048 ( cl->i_activity_timeout > 0 &&
2049 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2051 httpd_ClientClean( cl );
2052 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2053 TAB_REMOVE( host->i_client, host->client, cl );
2059 struct pollfd *pufd = ufd + nfd;
2060 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2063 pufd->events = pufd->revents = 0;
2065 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2066 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2068 pufd->events = POLLIN;
2070 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2071 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2073 pufd->events = POLLOUT;
2075 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2077 httpd_message_t *answer = &cl->answer;
2078 httpd_message_t *query = &cl->query;
2079 int i_msg = query->i_type;
2081 httpd_MsgInit( answer );
2083 /* Handle what we received */
2084 if( i_msg == HTTPD_MSG_ANSWER )
2087 cl->i_state = HTTPD_CLIENT_DEAD;
2089 else if( i_msg == HTTPD_MSG_OPTIONS )
2092 answer->i_type = HTTPD_MSG_ANSWER;
2093 answer->i_proto = query->i_proto;
2094 answer->i_status = 200;
2096 answer->p_body = NULL;
2098 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2099 httpd_MsgAdd( answer, "Content-Length", "0" );
2101 switch( query->i_proto )
2103 case HTTPD_PROTO_HTTP:
2104 answer->i_version = 1;
2105 httpd_MsgAdd( answer, "Allow",
2106 "GET,HEAD,POST,OPTIONS" );
2109 case HTTPD_PROTO_RTSP:
2112 answer->i_version = 0;
2114 p = httpd_MsgGet( query, "Cseq" );
2116 httpd_MsgAdd( answer, "Cseq", "%s", p );
2117 p = httpd_MsgGet( query, "Timestamp" );
2119 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2121 p = httpd_MsgGet( query, "Require" );
2124 answer->i_status = 551;
2125 httpd_MsgAdd( query, "Unsupported", "%s", p );
2128 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2129 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2134 cl->i_buffer = -1; /* Force the creation of the answer in
2135 * httpd_ClientSend */
2136 cl->i_state = HTTPD_CLIENT_SENDING;
2138 else if( i_msg == HTTPD_MSG_NONE )
2140 if( query->i_proto == HTTPD_PROTO_NONE )
2143 cl->i_state = HTTPD_CLIENT_DEAD;
2150 answer->i_proto = query->i_proto ;
2151 answer->i_type = HTTPD_MSG_ANSWER;
2152 answer->i_version= 0;
2153 answer->i_status = 501;
2155 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2156 answer->p_body = (uint8_t *)p;
2157 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2159 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2160 cl->i_state = HTTPD_CLIENT_SENDING;
2165 bool b_auth_failed = false;
2166 bool b_hosts_failed = false;
2168 /* Search the url and trigger callbacks */
2169 for(int i = 0; i < host->i_url; i++ )
2171 httpd_url_t *url = host->url[i];
2173 if( !strcmp( url->psz_url, query->psz_url ) )
2175 if( url->catch[i_msg].cb )
2177 if( answer && ( url->p_acl != NULL ) )
2179 char ip[NI_MAXNUMERICHOST];
2181 if( ( httpd_ClientIP( cl, ip, NULL ) == NULL )
2182 || ACL_Check( url->p_acl, ip ) )
2184 b_hosts_failed = true;
2189 if( answer && ( *url->psz_user || *url->psz_password ) )
2191 /* create the headers */
2192 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2193 char *user = NULL, *pass = NULL;
2196 && !strncasecmp( b64, "BASIC", 5 ) )
2199 while( *b64 == ' ' )
2202 user = vlc_b64_decode( b64 );
2205 pass = strchr (user, ':');
2211 if ((user == NULL) || (pass == NULL)
2212 || strcmp (user, url->psz_user)
2213 || strcmp (pass, url->psz_password))
2215 httpd_MsgAdd( answer,
2217 "Basic realm=\"VLC stream\"" );
2218 /* We fail for all url */
2219 b_auth_failed = true;
2227 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2229 if( answer->i_proto == HTTPD_PROTO_NONE )
2231 /* Raw answer from a CGI */
2232 cl->i_buffer = cl->i_buffer_size;
2237 /* only one url can answer */
2239 if( cl->url == NULL )
2252 answer->i_proto = query->i_proto;
2253 answer->i_type = HTTPD_MSG_ANSWER;
2254 answer->i_version= 0;
2256 if( b_hosts_failed )
2258 answer->i_status = 403;
2260 else if( b_auth_failed )
2262 answer->i_status = 401;
2266 /* no url registered */
2267 answer->i_status = 404;
2270 answer->i_body = httpd_HtmlError (&p,
2273 answer->p_body = (uint8_t *)p;
2275 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2276 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2277 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2280 cl->i_state = HTTPD_CLIENT_SENDING;
2283 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2285 if( !cl->b_stream_mode || cl->answer.i_body_offset == 0 )
2287 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2288 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2289 bool b_connection = false;
2290 bool b_keepalive = false;
2291 bool b_query = false;
2294 if( psz_connection )
2296 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2297 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2302 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2305 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2306 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2307 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2308 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2309 !b_query && !b_connection ) )
2311 httpd_MsgClean( &cl->query );
2312 httpd_MsgInit( &cl->query );
2315 cl->i_buffer_size = 1000;
2316 free( cl->p_buffer );
2317 cl->p_buffer = xmalloc( cl->i_buffer_size );
2318 cl->i_state = HTTPD_CLIENT_RECEIVING;
2322 cl->i_state = HTTPD_CLIENT_DEAD;
2324 httpd_MsgClean( &cl->answer );
2328 int64_t i_offset = cl->answer.i_body_offset;
2329 httpd_MsgClean( &cl->answer );
2331 cl->answer.i_body_offset = i_offset;
2332 free( cl->p_buffer );
2333 cl->p_buffer = NULL;
2335 cl->i_buffer_size = 0;
2337 cl->i_state = HTTPD_CLIENT_WAITING;
2340 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2342 int64_t i_offset = cl->answer.i_body_offset;
2343 int i_msg = cl->query.i_type;
2345 httpd_MsgInit( &cl->answer );
2346 cl->answer.i_body_offset = i_offset;
2348 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2349 &cl->answer, &cl->query );
2350 if( cl->answer.i_type != HTTPD_MSG_NONE )
2352 /* we have new data, so re-enter send mode */
2354 cl->p_buffer = cl->answer.p_body;
2355 cl->i_buffer_size = cl->answer.i_body;
2356 cl->answer.p_body = NULL;
2357 cl->answer.i_body = 0;
2358 cl->i_state = HTTPD_CLIENT_SENDING;
2362 if (pufd->events != 0)
2367 vlc_mutex_unlock( &host->lock );
2370 ufd[nfd].events = POLLIN;
2371 ufd[nfd].revents = 0;
2374 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2375 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2380 /* Kernel on low memory or a bug: pace */
2381 msg_Err( host, "polling error: %m" );
2388 if( ufd[nfd - 1].revents )
2391 /* Handle client sockets */
2392 vlc_mutex_lock( &host->lock );
2395 for( int i_client = 0; i_client < host->i_client; i_client++ )
2397 httpd_client_t *cl = host->client[i_client];
2398 const struct pollfd *pufd = &ufd[nfd];
2400 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2402 if( cl->fd != pufd->fd )
2403 continue; // we were not waiting for this client
2405 if( pufd->revents == 0 )
2406 continue; // no event received
2408 cl->i_activity_date = now;
2410 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2412 httpd_ClientRecv( cl );
2414 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2416 httpd_ClientSend( cl );
2418 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2420 httpd_ClientTlsHsIn( cl );
2422 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2424 httpd_ClientTlsHsOut( cl );
2427 vlc_mutex_unlock( &host->lock );
2429 /* Handle server sockets (accept new connections) */
2430 for( nfd = 0; nfd < host->nfd; nfd++ )
2434 int fd = ufd[nfd].fd;
2436 assert (fd == host->fds[nfd]);
2438 if( ufd[nfd].revents == 0 )
2442 fd = vlc_accept (fd, NULL, NULL, true);
2445 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2446 &(int){ 1 }, sizeof(int));
2450 if( host->p_tls != NULL )
2452 p_tls = vlc_tls_ServerSessionCreate( host->p_tls, fd );
2453 switch( vlc_tls_ServerSessionHandshake( p_tls ) )
2456 msg_Err( host, "Rejecting TLS connection" );
2457 /* p_tls is destroyed implicitly */
2463 case 1: /* missing input - most likely */
2464 i_state = HTTPD_CLIENT_TLS_HS_IN;
2467 case 2: /* missing output */
2468 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2475 stats_UpdateInteger( host, p_total_counter, 1, NULL );
2476 stats_UpdateInteger( host, p_active_counter, 1, NULL );
2477 cl = httpd_ClientNew( fd, p_tls, now );
2478 vlc_mutex_lock( &host->lock );
2479 TAB_APPEND( host->i_client, host->client, cl );
2480 vlc_mutex_unlock( &host->lock );
2482 cl->i_state = i_state; // override state for TLS
2487 if( p_total_counter )
2488 stats_CounterClean( p_total_counter );
2489 if( p_active_counter )
2490 stats_CounterClean( p_active_counter );