1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2004-2006 the VideoLAN team
5 * Copyright © 2004-2007 Rémi Denis-Courmont
8 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9 * Rémi Denis-Courmont <rem # videolan.org>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 *****************************************************************************/
30 #include <vlc_common.h>
31 #include <vlc_httpd.h>
35 #include <vlc_network.h>
38 #include <vlc_strings.h>
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 );
80 /* each host run in his own thread */
90 /* address/port and socket for listening at connections */
98 /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
99 * This will slow down the url research but make my live easier
100 * All url will have their cb trigger, but only the first one can answer
106 httpd_client_t **client;
109 vlc_tls_creds_t *p_tls;
127 httpd_callback_sys_t *p_sys;
128 } catch[HTTPD_MSG_MAX];
134 HTTPD_CLIENT_RECEIVING,
135 HTTPD_CLIENT_RECEIVE_DONE,
137 HTTPD_CLIENT_SENDING,
138 HTTPD_CLIENT_SEND_DONE,
140 HTTPD_CLIENT_WAITING,
144 HTTPD_CLIENT_TLS_HS_IN,
145 HTTPD_CLIENT_TLS_HS_OUT
151 HTTPD_CLIENT_FILE, /* default */
152 HTTPD_CLIENT_STREAM, /* regulary get data from cb */
153 HTTPD_CLIENT_BIDIR, /* check for reading and get data from cb */
156 struct httpd_client_t
166 int b_read_waiting; /* stop as soon as possible sending */
168 mtime_t i_activity_date;
169 mtime_t i_activity_timeout;
171 /* buffer for reading header */
177 httpd_message_t query; /* client -> httpd */
178 httpd_message_t answer; /* httpd -> client */
185 /*****************************************************************************
187 *****************************************************************************/
190 const char psz_ext[8];
191 const char *psz_mime;
194 { ".htm", "text/html" },
195 { ".html", "text/html" },
196 { ".txt", "text/plain" },
197 { ".xml", "text/xml" },
198 { ".dtd", "text/dtd" },
200 { ".css", "text/css" },
203 { ".gif", "image/gif" },
204 { ".jpe", "image/jpeg" },
205 { ".jpg", "image/jpeg" },
206 { ".jpeg", "image/jpeg" },
207 { ".png", "image/png" },
208 /* same as modules/mux/mpjpeg.c here: */
209 { ".mpjpeg","multipart/x-mixed-replace; boundary=7b3cc56e5f51db803f790dad720ed50a" },
212 { ".avi", "video/avi" },
213 { ".asf", "video/x-ms-asf" },
214 { ".m1a", "audio/mpeg" },
215 { ".m2a", "audio/mpeg" },
216 { ".m1v", "video/mpeg" },
217 { ".m2v", "video/mpeg" },
218 { ".mp2", "audio/mpeg" },
219 { ".mp3", "audio/mpeg" },
220 { ".mpa", "audio/mpeg" },
221 { ".mpg", "video/mpeg" },
222 { ".mpeg", "video/mpeg" },
223 { ".mpe", "video/mpeg" },
224 { ".mov", "video/quicktime" },
225 { ".moov", "video/quicktime" },
226 { ".oga", "audio/ogg" },
227 { ".ogg", "application/ogg" },
228 { ".ogm", "application/ogg" },
229 { ".ogv", "video/ogg" },
230 { ".ogx", "application/ogg" },
231 { ".spx", "audio/ogg" },
232 { ".wav", "audio/wav" },
233 { ".wma", "audio/x-ms-wma" },
234 { ".wmv", "video/x-ms-wmv" },
241 static const char *httpd_MimeFromUrl( const char *psz_url )
246 psz_ext = strrchr( psz_url, '.' );
251 for( i = 0; http_mime[i].psz_ext[0] ; i++ )
253 if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
255 return http_mime[i].psz_mime;
259 return "application/octet-stream";
266 const char psz_reason[36];
269 static const http_status_info http_reason[] =
271 /*{ 100, "Continue" },
272 { 101, "Switching Protocols" },*/
274 /*{ 201, "Created" },
276 { 203, "Non-authoritative information" },
277 { 204, "No content" },
278 { 205, "Reset content" },
279 { 206, "Partial content" },
280 { 250, "Low on storage space" },
281 { 300, "Multiple choices" },*/
282 { 301, "Moved permanently" },
283 /*{ 302, "Moved temporarily" },
284 { 303, "See other" },
285 { 304, "Not modified" },
286 { 305, "Use proxy" },
287 { 307, "Temporary redirect" },
288 { 400, "Bad request" },*/
289 { 401, "Unauthorized" },
290 /*{ 402, "Payment Required" },*/
291 { 403, "Forbidden" },
292 { 404, "Not found" },
293 { 405, "Method not allowed" },
294 /*{ 406, "Not acceptable" },
295 { 407, "Proxy authentication required" },
296 { 408, "Request time-out" },
299 { 411, "Length required" },
300 { 412, "Precondition failed" },
301 { 413, "Request entity too large" },
302 { 414, "Request-URI too large" },
303 { 415, "Unsupported media Type" },
304 { 416, "Requested range not satisfiable" },
305 { 417, "Expectation failed" },
306 { 451, "Parameter not understood" },
307 { 452, "Conference not found" },
308 { 453, "Not enough bandwidth" },*/
309 { 454, "Session not found" },
310 { 455, "Method not valid in this State" },
311 { 456, "Header field not valid for resource" },
312 { 457, "Invalid range" },
313 /*{ 458, "Read-only parameter" },*/
314 { 459, "Aggregate operation not allowed" },
315 { 460, "Non-aggregate operation not allowed" },
316 { 461, "Unsupported transport" },
317 /*{ 462, "Destination unreachable" },*/
318 { 500, "Internal server error" },
319 { 501, "Not implemented" },
320 /*{ 502, "Bad gateway" },*/
321 { 503, "Service unavailable" },
322 /*{ 504, "Gateway time-out" },*/
323 { 505, "Protocol version not supported" },
324 { 551, "Option not supported" },
328 static const char psz_fallback_reason[5][16] =
329 { "Continue", "OK", "Found", "Client error", "Server error" };
331 static const char *httpd_ReasonFromCode( unsigned i_code )
333 const http_status_info *p;
335 assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
337 for (p = http_reason; i_code > p->i_code; p++);
339 if( p->i_code == i_code )
340 return p->psz_reason;
342 return psz_fallback_reason[(i_code / 100) - 1];
346 static size_t httpd_HtmlError (char **body, int code, const char *url)
348 const char *errname = httpd_ReasonFromCode (code);
349 assert (errname != NULL);
351 int res = asprintf (body,
352 "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
353 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
354 " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
355 "<html lang=\"en\">\n"
357 "<title>%s</title>\n"
360 "<h1>%d %s%s%s%s</h1>\n"
362 "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
364 "</html>\n", errname, code, errname,
365 (url ? " (" : ""), (url ? url : ""), (url ? ")" : ""));
377 /*****************************************************************************
378 * High Level Functions: httpd_file_t
379 *****************************************************************************/
387 httpd_file_callback_t pf_fill;
388 httpd_file_sys_t *p_sys;
393 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
394 httpd_message_t *answer, const httpd_message_t *query )
396 httpd_file_t *file = (httpd_file_t*)p_sys;
397 uint8_t **pp_body, *p_body;
398 const char *psz_connection;
399 int *pi_body, i_body;
401 if( answer == NULL || query == NULL )
405 answer->i_proto = HTTPD_PROTO_HTTP;
406 answer->i_version= 1;
407 answer->i_type = HTTPD_MSG_ANSWER;
409 answer->i_status = 200;
411 httpd_MsgAdd( answer, "Content-type", "%s", file->psz_mime );
412 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
414 if( query->i_type != HTTPD_MSG_HEAD )
416 pp_body = &answer->p_body;
417 pi_body = &answer->i_body;
421 /* The file still needs to be executed. */
428 if( query->i_type == HTTPD_MSG_POST )
430 /* msg_Warn not supported */
433 uint8_t *psz_args = query->psz_args;
434 file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
436 if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
441 /* We respect client request */
442 psz_connection = httpd_MsgGet( &cl->query, "Connection" );
443 if( psz_connection != NULL )
445 httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
448 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
453 httpd_file_t *httpd_FileNew( httpd_host_t *host,
454 const char *psz_url, const char *psz_mime,
455 const char *psz_user, const char *psz_password,
456 const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
457 httpd_file_sys_t *p_sys )
459 httpd_file_t *file = xmalloc( sizeof( httpd_file_t ) );
461 if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
462 psz_password, p_acl )
469 file->psz_url = strdup( psz_url );
470 if( psz_mime && *psz_mime )
472 file->psz_mime = strdup( psz_mime );
476 file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
479 file->pf_fill = pf_fill;
482 httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
483 (httpd_callback_sys_t*)file );
484 httpd_UrlCatch( file->url, HTTPD_MSG_GET, httpd_FileCallBack,
485 (httpd_callback_sys_t*)file );
486 httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
487 (httpd_callback_sys_t*)file );
492 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
494 httpd_file_sys_t *p_sys = file->p_sys;
496 httpd_UrlDelete( file->url );
498 free( file->psz_url );
499 free( file->psz_mime );
506 /*****************************************************************************
507 * High Level Functions: httpd_handler_t (for CGIs)
508 *****************************************************************************/
509 struct httpd_handler_t
513 httpd_handler_callback_t pf_fill;
514 httpd_handler_sys_t *p_sys;
519 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
520 httpd_message_t *answer, const httpd_message_t *query )
522 httpd_handler_t *handler = (httpd_handler_t*)p_sys;
523 char psz_remote_addr[NI_MAXNUMERICHOST];
525 if( answer == NULL || query == NULL )
529 answer->i_proto = HTTPD_PROTO_NONE;
530 answer->i_type = HTTPD_MSG_ANSWER;
532 /* We do it ourselves, thanks */
533 answer->i_status = 0;
535 if( httpd_ClientIP( cl, psz_remote_addr, NULL ) == NULL )
536 *psz_remote_addr = '\0';
538 uint8_t *psz_args = query->psz_args;
539 handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
540 query->i_type, query->p_body, query->i_body,
541 psz_remote_addr, NULL,
542 &answer->p_body, &answer->i_body );
544 if( query->i_type == HTTPD_MSG_HEAD )
546 char *p = (char *)answer->p_body;
548 /* Looks for end of header (i.e. one empty line) */
549 while ( (p = strchr( p, '\r' )) != NULL )
551 if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
552 && p[3] && p[3] == '\n' )
561 answer->i_body = strlen((char*)answer->p_body) + 1;
562 answer->p_body = xrealloc( answer->p_body, answer->i_body );
566 if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
568 int i_status, i_headers;
569 char *psz_headers, *psz_new;
570 const char *psz_status;
572 if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
575 i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
576 if( *psz_headers == '\r' || *psz_headers == '\n' ) psz_headers++;
577 if( *psz_headers == '\n' ) psz_headers++;
578 i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
583 psz_headers = (char *)answer->p_body;
584 i_headers = answer->i_body;
587 psz_status = httpd_ReasonFromCode( i_status );
588 answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
589 + strlen(psz_status) + i_headers - 1;
590 psz_new = (char *)xmalloc( answer->i_body + 1);
591 sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
592 memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
593 free( answer->p_body );
594 answer->p_body = (uint8_t *)psz_new;
600 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
601 const char *psz_user,
602 const char *psz_password,
603 const vlc_acl_t *p_acl,
604 httpd_handler_callback_t pf_fill,
605 httpd_handler_sys_t *p_sys )
607 httpd_handler_t *handler = xmalloc( sizeof( httpd_handler_t ) );
609 if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
610 psz_password, p_acl )
617 handler->pf_fill = pf_fill;
618 handler->p_sys = p_sys;
620 httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
621 (httpd_callback_sys_t*)handler );
622 httpd_UrlCatch( handler->url, HTTPD_MSG_GET, httpd_HandlerCallBack,
623 (httpd_callback_sys_t*)handler );
624 httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
625 (httpd_callback_sys_t*)handler );
630 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
632 httpd_handler_sys_t *p_sys = handler->p_sys;
633 httpd_UrlDelete( handler->url );
638 /*****************************************************************************
639 * High Level Functions: httpd_redirect_t
640 *****************************************************************************/
641 struct httpd_redirect_t
647 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
648 httpd_client_t *cl, httpd_message_t *answer,
649 const httpd_message_t *query )
651 httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
655 if( answer == NULL || query == NULL )
659 answer->i_proto = HTTPD_PROTO_HTTP;
660 answer->i_version= 1;
661 answer->i_type = HTTPD_MSG_ANSWER;
662 answer->i_status = 301;
664 answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
665 answer->p_body = (unsigned char *)p_body;
667 /* XXX check if it's ok or we need to set an absolute url */
668 httpd_MsgAdd( answer, "Location", "%s", rdir->psz_dst );
670 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
675 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
676 const char *psz_url_src )
678 httpd_redirect_t *rdir = xmalloc( sizeof( httpd_redirect_t ) );
680 if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
685 rdir->psz_dst = strdup( psz_url_dst );
687 /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
688 httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
689 (httpd_callback_sys_t*)rdir );
690 httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
691 (httpd_callback_sys_t*)rdir );
692 httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
693 (httpd_callback_sys_t*)rdir );
694 httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
695 (httpd_callback_sys_t*)rdir );
699 void httpd_RedirectDelete( httpd_redirect_t *rdir )
701 httpd_UrlDelete( rdir->url );
702 free( rdir->psz_dst );
706 /*****************************************************************************
707 * High Level Funtions: httpd_stream_t
708 *****************************************************************************/
709 struct httpd_stream_t
716 /* Header to send as first packet */
720 /* circular buffer */
721 int i_buffer_size; /* buffer size, can't be reallocated smaller */
722 uint8_t *p_buffer; /* buffer */
723 int64_t i_buffer_pos; /* absolute position from begining */
724 int64_t i_buffer_last_pos; /* a new connection will start with that */
727 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
728 httpd_client_t *cl, httpd_message_t *answer,
729 const httpd_message_t *query )
731 httpd_stream_t *stream = (httpd_stream_t*)p_sys;
733 if( answer == NULL || query == NULL || cl == NULL )
738 if( answer->i_body_offset > 0 )
744 fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
745 answer->i_body_offset );
748 if( answer->i_body_offset >= stream->i_buffer_pos )
750 /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
751 return VLC_EGENERIC; /* wait, no data available */
753 if( answer->i_body_offset + stream->i_buffer_size <
754 stream->i_buffer_pos )
756 /* this client isn't fast enough */
758 fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
759 answer->i_body_offset, stream->i_buffer_last_pos );
761 answer->i_body_offset = stream->i_buffer_last_pos;
764 i_pos = answer->i_body_offset % stream->i_buffer_size;
765 i_write = stream->i_buffer_pos - answer->i_body_offset;
766 if( i_write > HTTPD_CL_BUFSIZE )
768 i_write = HTTPD_CL_BUFSIZE;
770 else if( i_write <= 0 )
772 return VLC_EGENERIC; /* wait, no data available */
775 /* Don't go past the end of the circular buffer */
776 i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
778 /* using HTTPD_MSG_ANSWER -> data available */
779 answer->i_proto = HTTPD_PROTO_HTTP;
780 answer->i_version= 0;
781 answer->i_type = HTTPD_MSG_ANSWER;
783 answer->i_body = i_write;
784 answer->p_body = xmalloc( i_write );
785 memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
787 answer->i_body_offset += i_write;
793 answer->i_proto = HTTPD_PROTO_HTTP;
794 answer->i_version= 0;
795 answer->i_type = HTTPD_MSG_ANSWER;
797 answer->i_status = 200;
799 if( query->i_type != HTTPD_MSG_HEAD )
801 httpd_ClientModeStream( cl );
802 vlc_mutex_lock( &stream->lock );
803 /* Send the header */
804 if( stream->i_header > 0 )
806 answer->i_body = stream->i_header;
807 answer->p_body = xmalloc( stream->i_header );
808 memcpy( answer->p_body, stream->p_header, stream->i_header );
810 answer->i_body_offset = stream->i_buffer_last_pos;
811 vlc_mutex_unlock( &stream->lock );
815 httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
816 answer->i_body_offset = 0;
819 if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
821 bool b_xplaystream = false;
824 httpd_MsgAdd( answer, "Content-type", "%s",
825 "application/octet-stream" );
826 httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
827 httpd_MsgAdd( answer, "Pragma", "no-cache" );
828 httpd_MsgAdd( answer, "Pragma", "client-id=%lu",
829 vlc_mrand48()&0x7fff );
830 httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
832 /* Check if there is a xPlayStrm=1 */
833 for( i = 0; i < query->i_name; i++ )
835 if( !strcasecmp( query->name[i], "Pragma" ) &&
836 strstr( query->value[i], "xPlayStrm=1" ) )
838 b_xplaystream = true;
844 answer->i_body_offset = 0;
849 httpd_MsgAdd( answer, "Content-type", "%s", stream->psz_mime );
851 httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
856 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
857 const char *psz_url, const char *psz_mime,
858 const char *psz_user, const char *psz_password,
859 const vlc_acl_t *p_acl )
861 httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
863 if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
864 psz_password, p_acl )
870 vlc_mutex_init( &stream->lock );
871 if( psz_mime && *psz_mime )
873 stream->psz_mime = strdup( psz_mime );
877 stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
879 stream->i_header = 0;
880 stream->p_header = NULL;
881 stream->i_buffer_size = 5000000; /* 5 Mo per stream */
882 stream->p_buffer = xmalloc( stream->i_buffer_size );
883 /* We set to 1 to make life simpler
884 * (this way i_body_offset can never be 0) */
885 stream->i_buffer_pos = 1;
886 stream->i_buffer_last_pos = 1;
888 httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
889 (httpd_callback_sys_t*)stream );
890 httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
891 (httpd_callback_sys_t*)stream );
892 httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
893 (httpd_callback_sys_t*)stream );
898 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
900 vlc_mutex_lock( &stream->lock );
901 free( stream->p_header );
902 stream->p_header = NULL;
904 stream->i_header = i_data;
907 stream->p_header = xmalloc( i_data );
908 memcpy( stream->p_header, p_data, i_data );
910 vlc_mutex_unlock( &stream->lock );
915 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
920 if( i_data < 0 || p_data == NULL )
924 vlc_mutex_lock( &stream->lock );
926 /* save this pointer (to be used by new connection) */
927 stream->i_buffer_last_pos = stream->i_buffer_pos;
929 i_pos = stream->i_buffer_pos % stream->i_buffer_size;
935 i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
937 /* Ok, we can't go past the end of our buffer */
938 memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
940 i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
945 stream->i_buffer_pos += i_data;
947 vlc_mutex_unlock( &stream->lock );
951 void httpd_StreamDelete( httpd_stream_t *stream )
953 httpd_UrlDelete( stream->url );
954 vlc_mutex_destroy( &stream->lock );
955 free( stream->psz_mime );
956 free( stream->p_header );
957 free( stream->p_buffer );
961 /*****************************************************************************
963 *****************************************************************************/
964 static void* httpd_HostThread( void * );
965 static httpd_host_t *httpd_HostCreate( vlc_object_t *, const char *,
966 const char *, vlc_tls_creds_t * );
968 /* create a new host */
969 httpd_host_t *vlc_http_HostNew( vlc_object_t *p_this )
971 return httpd_HostCreate( p_this, "http-host", "http-port", NULL );
974 httpd_host_t *vlc_https_HostNew( vlc_object_t *obj )
976 char *cert = var_InheritString( obj, "http-cert" );
979 msg_Err( obj, "HTTP/TLS certificate not specified!" );
983 char *key = var_InheritString( obj, "http-key" );
984 vlc_tls_creds_t *tls = vlc_tls_ServerCreate( obj, cert, key );
988 msg_Err( obj, "HTTP/TLS certificate error (%s and %s)",
989 cert, (key != NULL) ? key : cert );
997 char *ca = var_InheritString( obj, "http-ca" );
1000 if( vlc_tls_ServerAddCA( tls, ca ) )
1002 msg_Err( obj, "HTTP/TLS CA error (%s)", ca );
1009 char *crl = var_InheritString( obj, "http-crl" );
1012 if( vlc_tls_ServerAddCRL( tls, crl ) )
1014 msg_Err( obj, "TLS CRL error (%s)", crl );
1021 return httpd_HostCreate( obj, "http-host", "https-port", tls );
1024 vlc_tls_ServerDelete( tls );
1028 httpd_host_t *vlc_rtsp_HostNew( vlc_object_t *p_this )
1030 return httpd_HostCreate( p_this, "rtsp-host", "rtsp-port", NULL );
1033 static vlc_mutex_t httpd_mutex = VLC_STATIC_MUTEX;
1035 static httpd_host_t *httpd_HostCreate( vlc_object_t *p_this,
1036 const char *hostvar,
1037 const char *portvar,
1038 vlc_tls_creds_t *p_tls )
1044 /* to be sure to avoid multiple creation */
1045 vlc_mutex_lock( &httpd_mutex );
1046 httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1050 msg_Info( p_this, "creating httpd" );
1051 httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1055 vlc_mutex_unlock( &httpd_mutex );
1062 libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1065 /* verify if it already exist */
1066 for( i = httpd->i_host - 1; i >= 0; i-- )
1068 host = httpd->host[i];
1070 /* cannot mix TLS and non-TLS hosts */
1071 if( ( httpd->host[i]->p_tls != NULL ) != ( p_tls != NULL ) )
1074 /* Increase existing matching host reference count.
1075 * The reference count is written under both the global httpd and the
1076 * host lock. It is read with either or both locks held. The global
1077 * lock is always acquired first. */
1078 vlc_mutex_lock( &host->lock );
1080 vlc_mutex_unlock( &host->lock );
1082 vlc_mutex_unlock( &httpd_mutex );
1084 vlc_tls_ServerDelete( p_tls );
1090 /* create the new host */
1091 host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1096 host->httpd = httpd;
1097 vlc_mutex_init( &host->lock );
1098 vlc_cond_init( &host->wait );
1101 char *hostname = var_InheritString( p_this->p_libvlc, hostvar );
1102 int port = var_InheritInteger( p_this->p_libvlc, portvar );
1103 host->fds = net_ListenTCP( p_this, hostname, port );
1105 if( host->fds == NULL )
1107 msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1110 for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1112 if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1114 msg_Err( host, "signaling pipe error: %m" );
1121 host->client = NULL;
1122 host->p_tls = p_tls;
1124 /* create the thread */
1125 if( vlc_clone( &host->thread, httpd_HostThread, host,
1126 VLC_THREAD_PRIORITY_LOW ) )
1128 msg_Err( p_this, "cannot spawn http host thread" );
1132 /* now add it to httpd */
1133 TAB_APPEND( httpd->i_host, httpd->host, host );
1134 vlc_mutex_unlock( &httpd_mutex );
1139 if( httpd->i_host <= 0 )
1141 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1142 vlc_object_release( httpd );
1144 vlc_mutex_unlock( &httpd_mutex );
1148 net_ListenClose( host->fds );
1149 vlc_cond_destroy( &host->wait );
1150 vlc_mutex_destroy( &host->lock );
1151 vlc_object_release( host );
1155 vlc_tls_ServerDelete( p_tls );
1161 void httpd_HostDelete( httpd_host_t *host )
1163 httpd_t *httpd = host->httpd;
1165 bool delete = false;
1167 vlc_mutex_lock( &httpd_mutex );
1169 vlc_mutex_lock( &host->lock );
1171 if( host->i_ref == 0 )
1173 vlc_cond_signal( &host->wait );
1176 vlc_mutex_unlock( &host->lock );
1180 vlc_mutex_unlock( &httpd_mutex );
1181 msg_Dbg( host, "httpd_HostDelete: host still in use" );
1184 TAB_REMOVE( httpd->i_host, httpd->host, host );
1186 vlc_object_kill( host );
1187 vlc_join( host->thread, NULL );
1189 msg_Dbg( host, "HTTP host removed" );
1191 for( i = 0; i < host->i_url; i++ )
1193 msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1195 for( i = 0; i < host->i_client; i++ )
1197 httpd_client_t *cl = host->client[i];
1198 msg_Warn( host, "client still connected" );
1199 httpd_ClientClean( cl );
1200 TAB_REMOVE( host->i_client, host->client, cl );
1206 if( host->p_tls != NULL)
1207 vlc_tls_ServerDelete( host->p_tls );
1209 net_ListenClose( host->fds );
1210 vlc_cond_destroy( &host->wait );
1211 vlc_mutex_destroy( &host->lock );
1212 vlc_object_release( host );
1214 if( httpd->i_host <= 0 )
1216 msg_Dbg( httpd, "no hosts left, stopping httpd" );
1218 libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1219 vlc_object_release( httpd );
1221 vlc_mutex_unlock( &httpd_mutex );
1224 /* register a new url */
1225 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1226 const char *psz_user, const char *psz_password,
1227 const vlc_acl_t *p_acl, bool b_check )
1232 assert( psz_url != NULL );
1234 vlc_mutex_lock( &host->lock );
1237 for( i = 0; i < host->i_url; i++ )
1239 if( !strcmp( psz_url, host->url[i]->psz_url ) )
1241 msg_Warn( host->httpd,
1242 "cannot add '%s' (url already defined)", psz_url );
1243 vlc_mutex_unlock( &host->lock );
1249 url = xmalloc( sizeof( httpd_url_t ) );
1252 vlc_mutex_init( &url->lock );
1253 url->psz_url = strdup( psz_url );
1254 url->psz_user = strdup( psz_user ? psz_user : "" );
1255 url->psz_password = strdup( psz_password ? psz_password : "" );
1256 url->p_acl = ACL_Duplicate( host, p_acl );
1257 for( i = 0; i < HTTPD_MSG_MAX; i++ )
1259 url->catch[i].cb = NULL;
1260 url->catch[i].p_sys = NULL;
1263 TAB_APPEND( host->i_url, host->url, url );
1264 vlc_cond_signal( &host->wait );
1265 vlc_mutex_unlock( &host->lock );
1270 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1271 const char *psz_user, const char *psz_password,
1272 const vlc_acl_t *p_acl )
1274 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1275 psz_password, p_acl, false );
1278 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1279 const char *psz_user, const char *psz_password,
1280 const vlc_acl_t *p_acl )
1282 return httpd_UrlNewPrivate( host, psz_url, psz_user,
1283 psz_password, p_acl, true );
1286 /* register callback on a url */
1287 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1288 httpd_callback_sys_t *p_sys )
1290 vlc_mutex_lock( &url->lock );
1291 url->catch[i_msg].cb = cb;
1292 url->catch[i_msg].p_sys= p_sys;
1293 vlc_mutex_unlock( &url->lock );
1299 void httpd_UrlDelete( httpd_url_t *url )
1301 httpd_host_t *host = url->host;
1304 vlc_mutex_lock( &host->lock );
1305 TAB_REMOVE( host->i_url, host->url, url );
1307 vlc_mutex_destroy( &url->lock );
1308 free( url->psz_url );
1309 free( url->psz_user );
1310 free( url->psz_password );
1311 ACL_Destroy( url->p_acl );
1313 for( i = 0; i < host->i_client; i++ )
1315 httpd_client_t *client = host->client[i];
1317 if( client->url == url )
1319 /* TODO complete it */
1320 msg_Warn( host, "force closing connections" );
1321 httpd_ClientClean( client );
1322 TAB_REMOVE( host->i_client, host->client, client );
1328 vlc_mutex_unlock( &host->lock );
1331 static void httpd_MsgInit( httpd_message_t *msg )
1334 msg->i_type = HTTPD_MSG_NONE;
1335 msg->i_proto = HTTPD_PROTO_NONE;
1336 msg->i_version = -1; /* FIXME */
1340 msg->psz_url = NULL;
1341 msg->psz_args = NULL;
1343 msg->i_channel = -1;
1350 msg->i_body_offset = 0;
1355 static void httpd_MsgClean( httpd_message_t *msg )
1359 free( msg->psz_url );
1360 free( msg->psz_args );
1361 for( i = 0; i < msg->i_name; i++ )
1363 free( msg->name[i] );
1364 free( msg->value[i] );
1368 free( msg->p_body );
1369 httpd_MsgInit( msg );
1372 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1376 for( i = 0; i < msg->i_name; i++ )
1378 if( !strcasecmp( msg->name[i], name ))
1380 return msg->value[i];
1386 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1391 va_start( args, psz_value );
1392 if( us_vasprintf( &value, psz_value, args ) == -1 )
1399 name = strdup( name );
1406 TAB_APPEND( msg->i_name, msg->name, (char*)name );
1407 TAB_APPEND( msg->i_value, msg->value, value );
1410 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1412 cl->i_state = HTTPD_CLIENT_RECEIVING;
1413 cl->i_activity_date = now;
1414 cl->i_activity_timeout = INT64_C(10000000);
1415 cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1417 cl->p_buffer = xmalloc( cl->i_buffer_size );
1418 cl->i_mode = HTTPD_CLIENT_FILE;
1419 cl->b_read_waiting = false;
1421 httpd_MsgInit( &cl->query );
1422 httpd_MsgInit( &cl->answer );
1425 void httpd_ClientModeStream( httpd_client_t *cl )
1427 cl->i_mode = HTTPD_CLIENT_STREAM;
1430 void httpd_ClientModeBidir( httpd_client_t *cl )
1432 cl->i_mode = HTTPD_CLIENT_BIDIR;
1435 char* httpd_ClientIP( const httpd_client_t *cl, char *ip, int *port )
1437 return net_GetPeerAddress( cl->fd, ip, port ) ? NULL : ip;
1440 char* httpd_ServerIP( const httpd_client_t *cl, char *ip, int *port )
1442 return net_GetSockAddress( cl->fd, ip, port ) ? NULL : ip;
1445 static void httpd_ClientClean( httpd_client_t *cl )
1449 if( cl->p_tls != NULL )
1450 vlc_tls_ServerSessionDelete( cl->p_tls );
1451 net_Close( cl->fd );
1455 httpd_MsgClean( &cl->answer );
1456 httpd_MsgClean( &cl->query );
1458 free( cl->p_buffer );
1459 cl->p_buffer = NULL;
1462 static httpd_client_t *httpd_ClientNew( int fd, vlc_tls_t *p_tls, mtime_t now )
1464 httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1466 if( !cl ) return NULL;
1473 httpd_ClientInit( cl, now );
1479 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1486 val = p_tls ? tls_Recv (p_tls, p, i_len)
1487 : recv (cl->fd, p, i_len, 0);
1488 while (val == -1 && errno == EINTR);
1493 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1500 val = p_tls ? tls_Send( p_tls, p, i_len )
1501 : send (cl->fd, p, i_len, 0);
1502 while (val == -1 && errno == EINTR);
1509 const char name[16];
1515 { "OPTIONS", HTTPD_MSG_OPTIONS, HTTPD_PROTO_RTSP },
1516 { "DESCRIBE", HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1517 { "SETUP", HTTPD_MSG_SETUP, HTTPD_PROTO_RTSP },
1518 { "PLAY", HTTPD_MSG_PLAY, HTTPD_PROTO_RTSP },
1519 { "PAUSE", HTTPD_MSG_PAUSE, HTTPD_PROTO_RTSP },
1520 { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1521 { "TEARDOWN", HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1522 { "GET", HTTPD_MSG_GET, HTTPD_PROTO_HTTP },
1523 { "HEAD", HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1524 { "POST", HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1525 { "", HTTPD_MSG_NONE, HTTPD_PROTO_NONE }
1529 static void httpd_ClientRecv( httpd_client_t *cl )
1533 /* ignore leading whites */
1534 if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1535 ( cl->i_buffer == 0 ) )
1539 i_len = httpd_NetRecv( cl, &c, 1 );
1541 if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1543 cl->p_buffer[0] = c;
1548 if( cl->query.i_proto == HTTPD_PROTO_NONE )
1550 /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1551 i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1555 cl->i_buffer += i_len;
1558 if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1560 /* Interleaved RTP over RTSP */
1561 cl->query.i_proto = HTTPD_PROTO_RTSP;
1562 cl->query.i_type = HTTPD_MSG_CHANNEL;
1563 cl->query.i_channel = cl->p_buffer[1];
1564 cl->query.i_body = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1565 cl->query.p_body = xmalloc( cl->query.i_body );
1567 memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1570 /* The smallest legal request is 7 bytes ("GET /\r\n"),
1571 * this is the maximum we can ask at this point. */
1572 if( cl->i_buffer >= 7 )
1574 if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1576 cl->query.i_proto = HTTPD_PROTO_HTTP;
1577 cl->query.i_type = HTTPD_MSG_ANSWER;
1579 else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1581 cl->query.i_proto = HTTPD_PROTO_RTSP;
1582 cl->query.i_type = HTTPD_MSG_ANSWER;
1586 /* We need the full request line to determine the protocol. */
1587 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1588 cl->query.i_type = HTTPD_MSG_NONE;
1592 else if( cl->query.i_body > 0 )
1594 /* we are reading the body of a request or a channel */
1595 i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1596 cl->query.i_body - cl->i_buffer );
1599 cl->i_buffer += i_len;
1601 if( cl->i_buffer >= cl->query.i_body )
1603 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1608 /* we are reading a header -> char by char */
1611 if( cl->i_buffer == cl->i_buffer_size )
1613 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1614 if( newbuf == NULL )
1620 cl->p_buffer = newbuf;
1621 cl->i_buffer_size += 1024;
1624 i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1631 if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1632 && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1634 /* Request line is now complete */
1635 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1638 assert( cl->query.i_type == HTTPD_MSG_NONE );
1640 if( p == NULL ) /* no URI: evil guy */
1642 i_len = 0; /* drop connection */
1647 p++; /* skips extra spaces */
1650 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1651 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1653 i_len = 0; /* not supported currently -> drop */
1658 p++; /* skips extra spaces ever again */
1661 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1662 if( len < 7 ) /* foreign protocol */
1663 i_len = 0; /* I don't understand -> drop */
1665 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1667 cl->query.i_proto = HTTPD_PROTO_HTTP;
1668 cl->query.i_version = atoi( p + 7 );
1671 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1673 cl->query.i_proto = HTTPD_PROTO_RTSP;
1674 cl->query.i_version = atoi( p + 7 );
1677 if( memcmp( p, "HTTP/", 5 ) == 0 )
1679 const uint8_t sorry[] =
1680 "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1681 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1682 i_len = 0; /* drop */
1685 if( memcmp( p, "RTSP/", 5 ) == 0 )
1687 const uint8_t sorry[] =
1688 "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1689 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1690 i_len = 0; /* drop */
1692 else /* yet another foreign protocol */
1699 if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1700 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1704 /* we have finished the header so parse it and set i_body */
1705 cl->p_buffer[cl->i_buffer] = '\0';
1707 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1710 * assume strlen( "HTTP/1.x" ) = 8
1712 cl->query.i_status =
1713 strtol( (char *)&cl->p_buffer[8],
1723 cl->query.i_type = HTTPD_MSG_NONE;
1725 /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1727 for( i = 0; msg_type[i].name[0]; i++ )
1729 if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1730 strlen( msg_type[i].name ) ) )
1732 p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1733 cl->query.i_type = msg_type[i].i_type;
1734 if( cl->query.i_proto != msg_type[i].i_proto )
1737 cl->query.i_proto = HTTPD_PROTO_NONE;
1738 cl->query.i_type = HTTPD_MSG_NONE;
1745 if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1747 cl->query.i_proto = HTTPD_PROTO_HTTP;
1749 else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1751 cl->query.i_proto = HTTPD_PROTO_RTSP;
1763 p2 = strchr( p, ' ' );
1768 if( !strncasecmp( p, ( cl->query.i_proto
1769 == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1770 && p[4 + !!strchr( "sS", p[4] )] == ':' )
1771 { /* Skip hier-part of URL (if present) */
1772 p = strchr( p, ':' ) + 1; /* skip URI scheme */
1773 if( !strncmp( p, "//", 2 ) ) /* skip authority */
1774 { /* see RFC3986 §3.2 */
1776 while( *p && !strchr( "/?#", *p ) ) p++;
1779 cl->query.psz_url = strdup( p );
1780 if( ( p3 = strchr( cl->query.psz_url, '?' ) ) )
1783 cl->query.psz_args = (uint8_t *)strdup( p3 );
1790 p = strchr( p, '\n' );
1794 while( *p == '\n' || *p == '\r' )
1798 while( p && *p != '\0' )
1801 char *eol = p = strchr( p, '\n' );
1804 while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1809 if( ( colon = strchr( line, ':' ) ) )
1815 while( *colon == ' ' )
1819 name = strdup( line );
1820 value = strdup( colon );
1822 TAB_APPEND( cl->query.i_name, cl->query.name, name );
1823 TAB_APPEND( cl->query.i_value,cl->query.value,value);
1825 if( !strcasecmp( name, "Content-Length" ) )
1827 cl->query.i_body = atol( value );
1834 while( *p == '\n' || *p == '\r' )
1841 if( cl->query.i_body > 0 )
1843 /* TODO Mhh, handle the case where the client only
1844 * sends a request and closes the connection to
1845 * mark the end of the body (probably only RTSP) */
1846 cl->query.p_body = malloc( cl->query.i_body );
1848 if ( cl->query.p_body == NULL )
1850 switch (cl->query.i_proto)
1852 case HTTPD_PROTO_HTTP:
1854 const uint8_t sorry[] =
1855 "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1856 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1859 case HTTPD_PROTO_RTSP:
1861 const uint8_t sorry[] =
1862 "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1863 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1869 i_len = 0; /* drop */
1875 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1881 /* check if the client is to be set to dead */
1882 #if defined( WIN32 ) || defined( UNDER_CE )
1883 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1885 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1888 if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1890 /* connection closed -> end of data */
1891 if( cl->query.i_body > 0 )
1893 cl->query.i_body = cl->i_buffer;
1895 cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1899 cl->i_state = HTTPD_CLIENT_DEAD;
1903 /* XXX: for QT I have to disable timeout. Try to find why */
1904 if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1905 cl->i_activity_timeout = 0;
1907 #if 0 /* Debugging only */
1908 if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1912 fprintf( stderr, "received new request\n" );
1913 fprintf( stderr, " - proto=%s\n",
1914 cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1915 fprintf( stderr, " - version=%d\n", cl->query.i_version );
1916 fprintf( stderr, " - msg=%d\n", cl->query.i_type );
1917 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1919 fprintf( stderr, " - answer=%d '%s'\n", cl->query.i_status,
1920 cl->query.psz_status );
1922 else if( cl->query.i_type != HTTPD_MSG_NONE )
1924 fprintf( stderr, " - url=%s\n", cl->query.psz_url );
1926 for( i = 0; i < cl->query.i_name; i++ )
1928 fprintf( stderr, " - option name='%s' value='%s'\n",
1929 cl->query.name[i], cl->query.value[i] );
1935 static void httpd_ClientSend( httpd_client_t *cl )
1940 if( cl->i_buffer < 0 )
1942 /* We need to create the header */
1945 const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1947 i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1948 for( i = 0; i < cl->answer.i_name; i++ )
1950 i_size += strlen( cl->answer.name[i] ) + 2 +
1951 strlen( cl->answer.value[i] ) + 2;
1954 if( cl->i_buffer_size < i_size )
1956 cl->i_buffer_size = i_size;
1957 free( cl->p_buffer );
1958 cl->p_buffer = xmalloc( i_size );
1960 p = (char *)cl->p_buffer;
1962 p += sprintf( p, "%s.%u %d %s\r\n",
1963 cl->answer.i_proto == HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1964 cl->answer.i_version,
1965 cl->answer.i_status, psz_status );
1966 for( i = 0; i < cl->answer.i_name; i++ )
1968 p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1969 cl->answer.value[i] );
1971 p += sprintf( p, "\r\n" );
1974 cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1976 /*fprintf( stderr, "sending answer\n" );
1977 fprintf( stderr, "%s", cl->p_buffer );*/
1980 i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1981 cl->i_buffer_size - cl->i_buffer );
1984 cl->i_buffer += i_len;
1986 if( cl->i_buffer >= cl->i_buffer_size )
1988 if( cl->answer.i_body == 0 && cl->answer.i_body_offset > 0 &&
1989 !cl->b_read_waiting )
1991 /* catch more body data */
1992 int i_msg = cl->query.i_type;
1993 int64_t i_offset = cl->answer.i_body_offset;
1995 httpd_MsgClean( &cl->answer );
1996 cl->answer.i_body_offset = i_offset;
1998 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1999 &cl->answer, &cl->query );
2002 if( cl->answer.i_body > 0 )
2004 /* send the body data */
2005 free( cl->p_buffer );
2006 cl->p_buffer = cl->answer.p_body;
2007 cl->i_buffer_size = cl->answer.i_body;
2010 cl->answer.i_body = 0;
2011 cl->answer.p_body = NULL;
2016 cl->i_state = HTTPD_CLIENT_SEND_DONE;
2022 #if defined( WIN32 ) || defined( UNDER_CE )
2023 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
2025 if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
2029 cl->i_state = HTTPD_CLIENT_DEAD;
2034 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2036 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
2039 cl->i_state = HTTPD_CLIENT_RECEIVING;
2043 cl->i_state = HTTPD_CLIENT_DEAD;
2048 cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2052 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2054 switch( vlc_tls_ServerSessionHandshake( cl->p_tls ) )
2057 cl->i_state = HTTPD_CLIENT_RECEIVING;
2061 cl->i_state = HTTPD_CLIENT_DEAD;
2066 cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2071 static void* httpd_HostThread( void *data )
2073 httpd_host_t *host = data;
2074 counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2075 counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2076 int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2080 struct pollfd ufd[host->nfd + host->i_client + 1];
2082 for( nfd = 0; nfd < host->nfd; nfd++ )
2084 ufd[nfd].fd = host->fds[nfd];
2085 ufd[nfd].events = POLLIN;
2086 ufd[nfd].revents = 0;
2089 /* add all socket that should be read/write and close dead connection */
2090 vlc_mutex_lock( &host->lock );
2091 while( host->i_url <= 0 && host->i_ref > 0 )
2092 vlc_cond_wait( &host->wait, &host->lock );
2094 mtime_t now = mdate();
2095 bool b_low_delay = false;
2097 for(int i_client = 0; i_client < host->i_client; i_client++ )
2099 httpd_client_t *cl = host->client[i_client];
2100 if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2101 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2102 ( cl->i_activity_timeout > 0 &&
2103 cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2105 httpd_ClientClean( cl );
2106 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2107 TAB_REMOVE( host->i_client, host->client, cl );
2113 struct pollfd *pufd = ufd + nfd;
2114 assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2117 pufd->events = pufd->revents = 0;
2119 if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2120 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2122 pufd->events = POLLIN;
2124 else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2125 || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2127 pufd->events = POLLOUT;
2129 else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2131 httpd_message_t *answer = &cl->answer;
2132 httpd_message_t *query = &cl->query;
2133 int i_msg = query->i_type;
2135 httpd_MsgInit( answer );
2137 /* Handle what we received */
2138 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2139 (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2141 /* we can only receive request from client when not
2144 cl->i_state = HTTPD_CLIENT_DEAD;
2146 else if( i_msg == HTTPD_MSG_ANSWER )
2148 /* We are in BIDIR mode, trigger the callback and then
2149 * check for new data */
2150 if( cl->url && cl->url->catch[i_msg].cb )
2152 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2155 cl->i_state = HTTPD_CLIENT_WAITING;
2157 else if( i_msg == HTTPD_MSG_CHANNEL )
2159 /* We are in BIDIR mode, trigger the callback and then
2160 * check for new data */
2161 if( cl->url && cl->url->catch[i_msg].cb )
2163 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2166 cl->i_state = HTTPD_CLIENT_WAITING;
2168 else if( i_msg == HTTPD_MSG_OPTIONS )
2171 answer->i_type = HTTPD_MSG_ANSWER;
2172 answer->i_proto = query->i_proto;
2173 answer->i_status = 200;
2175 answer->p_body = NULL;
2177 httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2178 httpd_MsgAdd( answer, "Content-Length", "0" );
2180 switch( query->i_proto )
2182 case HTTPD_PROTO_HTTP:
2183 answer->i_version = 1;
2184 httpd_MsgAdd( answer, "Allow",
2185 "GET,HEAD,POST,OPTIONS" );
2188 case HTTPD_PROTO_RTSP:
2191 answer->i_version = 0;
2193 p = httpd_MsgGet( query, "Cseq" );
2195 httpd_MsgAdd( answer, "Cseq", "%s", p );
2196 p = httpd_MsgGet( query, "Timestamp" );
2198 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2200 p = httpd_MsgGet( query, "Require" );
2203 answer->i_status = 551;
2204 httpd_MsgAdd( query, "Unsupported", "%s", p );
2207 httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2208 "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2213 cl->i_buffer = -1; /* Force the creation of the answer in
2214 * httpd_ClientSend */
2215 cl->i_state = HTTPD_CLIENT_SENDING;
2217 else if( i_msg == HTTPD_MSG_NONE )
2219 if( query->i_proto == HTTPD_PROTO_NONE )
2222 cl->i_state = HTTPD_CLIENT_DEAD;
2229 answer->i_proto = query->i_proto ;
2230 answer->i_type = HTTPD_MSG_ANSWER;
2231 answer->i_version= 0;
2232 answer->i_status = 501;
2234 answer->i_body = httpd_HtmlError (&p, 501, NULL);
2235 answer->p_body = (uint8_t *)p;
2236 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2238 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2239 cl->i_state = HTTPD_CLIENT_SENDING;
2244 bool b_auth_failed = false;
2245 bool b_hosts_failed = false;
2247 /* Search the url and trigger callbacks */
2248 for(int i = 0; i < host->i_url; i++ )
2250 httpd_url_t *url = host->url[i];
2252 if( !strcmp( url->psz_url, query->psz_url ) )
2254 if( url->catch[i_msg].cb )
2256 if( answer && ( url->p_acl != NULL ) )
2258 char ip[NI_MAXNUMERICHOST];
2260 if( ( httpd_ClientIP( cl, ip, NULL ) == NULL )
2261 || ACL_Check( url->p_acl, ip ) )
2263 b_hosts_failed = true;
2268 if( answer && ( *url->psz_user || *url->psz_password ) )
2270 /* create the headers */
2271 const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2272 char *user = NULL, *pass = NULL;
2275 && !strncasecmp( b64, "BASIC", 5 ) )
2278 while( *b64 == ' ' )
2281 user = vlc_b64_decode( b64 );
2284 pass = strchr (user, ':');
2290 if ((user == NULL) || (pass == NULL)
2291 || strcmp (user, url->psz_user)
2292 || strcmp (pass, url->psz_password))
2294 httpd_MsgAdd( answer,
2296 "Basic realm=\"VLC stream\"" );
2297 /* We fail for all url */
2298 b_auth_failed = true;
2306 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2308 if( answer->i_proto == HTTPD_PROTO_NONE )
2310 /* Raw answer from a CGI */
2311 cl->i_buffer = cl->i_buffer_size;
2316 /* only one url can answer */
2318 if( cl->url == NULL )
2331 answer->i_proto = query->i_proto;
2332 answer->i_type = HTTPD_MSG_ANSWER;
2333 answer->i_version= 0;
2335 if( b_hosts_failed )
2337 answer->i_status = 403;
2339 else if( b_auth_failed )
2341 answer->i_status = 401;
2345 /* no url registered */
2346 answer->i_status = 404;
2349 answer->i_body = httpd_HtmlError (&p,
2352 answer->p_body = (uint8_t *)p;
2354 cl->i_buffer = -1; /* Force the creation of the answer in httpd_ClientSend */
2355 httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2356 httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2359 cl->i_state = HTTPD_CLIENT_SENDING;
2362 else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2364 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2366 const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2367 const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2368 bool b_connection = false;
2369 bool b_keepalive = false;
2370 bool b_query = false;
2373 if( psz_connection )
2375 b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2376 b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2381 b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2384 if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2385 ( ( cl->query.i_version == 0 && b_keepalive ) ||
2386 ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2387 ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2388 !b_query && !b_connection ) )
2390 httpd_MsgClean( &cl->query );
2391 httpd_MsgInit( &cl->query );
2394 cl->i_buffer_size = 1000;
2395 free( cl->p_buffer );
2396 cl->p_buffer = xmalloc( cl->i_buffer_size );
2397 cl->i_state = HTTPD_CLIENT_RECEIVING;
2401 cl->i_state = HTTPD_CLIENT_DEAD;
2403 httpd_MsgClean( &cl->answer );
2405 else if( cl->b_read_waiting )
2407 /* we have a message waiting for us to read it */
2408 httpd_MsgClean( &cl->answer );
2409 httpd_MsgClean( &cl->query );
2412 cl->i_buffer_size = 1000;
2413 free( cl->p_buffer );
2414 cl->p_buffer = xmalloc( cl->i_buffer_size );
2415 cl->i_state = HTTPD_CLIENT_RECEIVING;
2416 cl->b_read_waiting = false;
2420 int64_t i_offset = cl->answer.i_body_offset;
2421 httpd_MsgClean( &cl->answer );
2423 cl->answer.i_body_offset = i_offset;
2424 free( cl->p_buffer );
2425 cl->p_buffer = NULL;
2427 cl->i_buffer_size = 0;
2429 cl->i_state = HTTPD_CLIENT_WAITING;
2432 else if( cl->i_state == HTTPD_CLIENT_WAITING )
2434 int64_t i_offset = cl->answer.i_body_offset;
2435 int i_msg = cl->query.i_type;
2437 httpd_MsgInit( &cl->answer );
2438 cl->answer.i_body_offset = i_offset;
2440 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2441 &cl->answer, &cl->query );
2442 if( cl->answer.i_type != HTTPD_MSG_NONE )
2444 /* we have new data, so re-enter send mode */
2446 cl->p_buffer = cl->answer.p_body;
2447 cl->i_buffer_size = cl->answer.i_body;
2448 cl->answer.p_body = NULL;
2449 cl->answer.i_body = 0;
2450 cl->i_state = HTTPD_CLIENT_SENDING;
2454 /* Special for BIDIR mode we also check reading */
2455 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2456 cl->i_state == HTTPD_CLIENT_SENDING )
2458 pufd->events |= POLLIN;
2461 if (pufd->events != 0)
2466 vlc_mutex_unlock( &host->lock );
2469 ufd[nfd].events = POLLIN;
2470 ufd[nfd].revents = 0;
2473 /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2474 switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2479 /* Kernel on low memory or a bug: pace */
2480 msg_Err( host, "polling error: %m" );
2487 if( ufd[nfd - 1].revents )
2490 /* Handle client sockets */
2491 vlc_mutex_lock( &host->lock );
2494 for( int i_client = 0; i_client < host->i_client; i_client++ )
2496 httpd_client_t *cl = host->client[i_client];
2497 const struct pollfd *pufd = &ufd[nfd];
2499 assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2501 if( cl->fd != pufd->fd )
2502 continue; // we were not waiting for this client
2504 if( pufd->revents == 0 )
2505 continue; // no event received
2507 cl->i_activity_date = now;
2509 if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2511 httpd_ClientRecv( cl );
2513 else if( cl->i_state == HTTPD_CLIENT_SENDING )
2515 httpd_ClientSend( cl );
2517 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2519 httpd_ClientTlsHsIn( cl );
2521 else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2523 httpd_ClientTlsHsOut( cl );
2526 if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2527 cl->i_state == HTTPD_CLIENT_SENDING &&
2528 (pufd->revents & POLLIN) )
2530 cl->b_read_waiting = true;
2533 vlc_mutex_unlock( &host->lock );
2535 /* Handle server sockets (accept new connections) */
2536 for( nfd = 0; nfd < host->nfd; nfd++ )
2540 int fd = ufd[nfd].fd;
2542 assert (fd == host->fds[nfd]);
2544 if( ufd[nfd].revents == 0 )
2548 fd = vlc_accept (fd, NULL, NULL, true);
2551 setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2552 &(int){ 1 }, sizeof(int));
2556 if( host->p_tls != NULL )
2558 p_tls = vlc_tls_ServerSessionCreate( host->p_tls, fd );
2559 switch( vlc_tls_ServerSessionHandshake( p_tls ) )
2562 msg_Err( host, "Rejecting TLS connection" );
2563 /* p_tls is destroyed implicitly */
2569 case 1: /* missing input - most likely */
2570 i_state = HTTPD_CLIENT_TLS_HS_IN;
2573 case 2: /* missing output */
2574 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2581 stats_UpdateInteger( host, p_total_counter, 1, NULL );
2582 stats_UpdateInteger( host, p_active_counter, 1, NULL );
2583 cl = httpd_ClientNew( fd, p_tls, now );
2584 vlc_mutex_lock( &host->lock );
2585 TAB_APPEND( host->i_client, host->client, cl );
2586 vlc_mutex_unlock( &host->lock );
2588 cl->i_state = i_state; // override state for TLS
2593 if( p_total_counter )
2594 stats_CounterClean( p_total_counter );
2595 if( p_active_counter )
2596 stats_CounterClean( p_active_counter );