af4db3d6d37d07c713cd2792b7d4c8a04aca50ec
[vlc.git] / src / network / httpd.c
1 /*****************************************************************************
2  * httpd.c
3  *****************************************************************************
4  * Copyright (C) 2004-2006 the VideoLAN team
5  * Copyright © 2004-2007 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9  *          Rémi Denis-Courmont <rem # videolan.org>
10  *
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.
15  *
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.
20  *
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  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc/vlc.h>
31
32 #ifdef ENABLE_HTTPD
33
34 #include <assert.h>
35
36 #include <vlc_httpd.h>
37 #include <vlc_network.h>
38 #include <vlc_tls.h>
39 #include <vlc_acl.h>
40 #include <vlc_strings.h>
41 #include "../libvlc.h"
42
43 #include <string.h>
44 #include <errno.h>
45
46 #ifdef HAVE_UNISTD_H
47 #   include <unistd.h>
48 #endif
49
50 #ifdef HAVE_FCNTL_H
51 #   include <fcntl.h>
52 #endif
53
54 #ifdef HAVE_POLL
55 # include <poll.h>
56 #endif
57
58 #if defined( UNDER_CE )
59 #   include <winsock.h>
60 #elif defined( WIN32 )
61 #   include <winsock2.h>
62 #else
63 #   include <sys/socket.h>
64 #endif
65
66 #if defined( WIN32 )
67 /* We need HUGE buffer otherwise TCP throughput is very limited */
68 #define HTTPD_CL_BUFSIZE 1000000
69 #else
70 #define HTTPD_CL_BUFSIZE 10000
71 #endif
72
73 static void httpd_ClientClean( httpd_client_t *cl );
74
75 struct httpd_t
76 {
77     VLC_COMMON_MEMBERS
78
79     int          i_host;
80     httpd_host_t **host;
81 };
82
83
84 /* each host run in his own thread */
85 struct httpd_host_t
86 {
87     VLC_COMMON_MEMBERS
88
89     httpd_t     *httpd;
90
91     /* ref count */
92     int         i_ref;
93
94     /* address/port and socket for listening at connections */
95     char        *psz_hostname;
96     int         i_port;
97     int         *fds;
98     unsigned     nfd;
99
100     vlc_mutex_t lock;
101
102     /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
103      * This will slow down the url research but make my live easier
104      * All url will have their cb trigger, but only the first one can answer
105      * */
106     int         i_url;
107     httpd_url_t **url;
108
109     int            i_client;
110     httpd_client_t **client;
111
112     /* TLS data */
113     tls_server_t *p_tls;
114 };
115
116
117 struct httpd_url_t
118 {
119     httpd_host_t *host;
120
121     vlc_mutex_t lock;
122
123     char      *psz_url;
124     char      *psz_user;
125     char      *psz_password;
126     vlc_acl_t *p_acl;
127
128     struct
129     {
130         httpd_callback_t     cb;
131         httpd_callback_sys_t *p_sys;
132     } catch[HTTPD_MSG_MAX];
133 };
134
135 /* status */
136 enum
137 {
138     HTTPD_CLIENT_RECEIVING,
139     HTTPD_CLIENT_RECEIVE_DONE,
140
141     HTTPD_CLIENT_SENDING,
142     HTTPD_CLIENT_SEND_DONE,
143
144     HTTPD_CLIENT_WAITING,
145
146     HTTPD_CLIENT_DEAD,
147
148     HTTPD_CLIENT_TLS_HS_IN,
149     HTTPD_CLIENT_TLS_HS_OUT
150 };
151
152 /* mode */
153 enum
154 {
155     HTTPD_CLIENT_FILE,      /* default */
156     HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
157     HTTPD_CLIENT_BIDIR,     /* check for reading and get data from cb */
158 };
159
160 struct httpd_client_t
161 {
162     httpd_url_t *url;
163
164     int     i_ref;
165
166     int     fd;
167
168     int     i_mode;
169     int     i_state;
170     int     b_read_waiting; /* stop as soon as possible sending */
171
172     mtime_t i_activity_date;
173     mtime_t i_activity_timeout;
174
175     /* buffer for reading header */
176     int     i_buffer_size;
177     int     i_buffer;
178     uint8_t *p_buffer;
179
180     /* */
181     httpd_message_t query;  /* client -> httpd */
182     httpd_message_t answer; /* httpd -> client */
183
184     /* TLS data */
185     tls_session_t *p_tls;
186 };
187
188
189 /*****************************************************************************
190  * Various functions
191  *****************************************************************************/
192 static struct
193 {
194     const char psz_ext[8];
195     const char *psz_mime;
196 } http_mime[] =
197 {
198     { ".htm",   "text/html" },
199     { ".html",  "text/html" },
200     { ".txt",   "text/plain" },
201     { ".xml",   "text/xml" },
202     { ".dtd",   "text/dtd" },
203
204     { ".css",   "text/css" },
205
206     /* image mime */
207     { ".gif",   "image/gif" },
208     { ".jpe",   "image/jpeg" },
209     { ".jpg",   "image/jpeg" },
210     { ".jpeg",  "image/jpeg" },
211     { ".png",   "image/png" },
212     { ".mpjpeg","multipart/x-mixed-replace; boundary=This Random String" },
213
214     /* media mime */
215     { ".avi",   "video/avi" },
216     { ".asf",   "video/x-ms-asf" },
217     { ".m1a",   "audio/mpeg" },
218     { ".m2a",   "audio/mpeg" },
219     { ".m1v",   "video/mpeg" },
220     { ".m2v",   "video/mpeg" },
221     { ".mp2",   "audio/mpeg" },
222     { ".mp3",   "audio/mpeg" },
223     { ".mpa",   "audio/mpeg" },
224     { ".mpg",   "video/mpeg" },
225     { ".mpeg",  "video/mpeg" },
226     { ".mpe",   "video/mpeg" },
227     { ".mov",   "video/quicktime" },
228     { ".moov",  "video/quicktime" },
229     { ".ogg",   "application/ogg" },
230     { ".ogm",   "application/ogg" },
231     { ".wav",   "audio/wav" },
232     { ".wma",   "audio/x-ms-wma" },
233     { ".wmv",   "video/x-ms-wmv" },
234
235
236     /* end */
237     { "",       "" }
238 };
239
240 static const char *httpd_MimeFromUrl( const char *psz_url )
241 {
242
243     char *psz_ext;
244
245     psz_ext = strrchr( psz_url, '.' );
246     if( psz_ext )
247     {
248         int i;
249
250         for( i = 0; http_mime[i].psz_ext[0] ; i++ )
251         {
252             if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
253             {
254                 return http_mime[i].psz_mime;
255             }
256         }
257     }
258     return "application/octet-stream";
259 }
260
261
262 typedef struct
263 {
264     unsigned   i_code;
265     const char psz_reason[36];
266 } http_status_info;
267
268 static const http_status_info http_reason[] =
269 {
270   /*{ 100, "Continue" },
271     { 101, "Switching Protocols" },*/
272     { 200, "OK" },
273   /*{ 201, "Created" },
274     { 202, "Accepted" },
275     { 203, "Non-authoritative information" },
276     { 204, "No content" },
277     { 205, "Reset content" },
278     { 206, "Partial content" },
279     { 250, "Low on storage space" },
280     { 300, "Multiple choices" },*/
281     { 301, "Moved permanently" },
282   /*{ 302, "Moved temporarily" },
283     { 303, "See other" },
284     { 304, "Not modified" },
285     { 305, "Use proxy" },
286     { 307, "Temporary redirect" },
287     { 400, "Bad request" },*/
288     { 401, "Unauthorized" },
289   /*{ 402, "Payment Required" },*/
290     { 403, "Forbidden" },
291     { 404, "Not found" },
292     { 405, "Method not allowed" },
293   /*{ 406, "Not acceptable" },
294     { 407, "Proxy authentication required" },
295     { 408, "Request time-out" },
296     { 409, "Conflict" },
297     { 410, "Gone" },
298     { 411, "Length required" },
299     { 412, "Precondition failed" },
300     { 413, "Request entity too large" },
301     { 414, "Request-URI too large" },
302     { 415, "Unsupported media Type" },
303     { 416, "Requested range not satisfiable" },
304     { 417, "Expectation failed" },
305     { 451, "Parameter not understood" },
306     { 452, "Conference not found" },
307     { 453, "Not enough bandwidth" },*/
308     { 454, "Session not found" },
309   /*{ 455, "Method not valid in this State" },*/
310     { 456, "Header field not valid for resource" },
311   /*{ 457, "Invalid range" },
312     { 458, "Read-only parameter" },*/
313     { 459, "Aggregate operation not allowed" },
314     { 460, "Non-aggregate operation not allowed" },
315     { 461, "Unsupported transport" },
316   /*{ 462, "Destination unreachable" },*/
317     { 500, "Internal server error" },
318     { 501, "Not implemented" },
319   /*{ 502, "Bad gateway" },*/
320     { 503, "Service unavailable" },
321   /*{ 504, "Gateway time-out" },*/
322     { 505, "Protocol version not supported" },
323     { 551, "Option not supported" },
324     { 999, "" }
325 };
326
327 static const char psz_fallback_reason[5][16] =
328 { "Continue", "OK", "Found", "Client error", "Server error" };
329
330 static const char *httpd_ReasonFromCode( unsigned i_code )
331 {
332     const http_status_info *p;
333
334     assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
335
336     for (p = http_reason; i_code > p->i_code; p++);
337
338     if( p->i_code == i_code )
339         return p->psz_reason;
340
341     return psz_fallback_reason[(i_code / 100) - 1];
342 }
343
344
345 static size_t httpd_HtmlError (char **body, int code, const char *url)
346 {
347     const char *errname = httpd_ReasonFromCode (code);
348     assert (errname != NULL);
349
350     int res = asprintf (body,
351         "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
352         "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
353         " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
354         "<html lang=\"en\">\n"
355         "<head>\n"
356         "<title>%s</title>\n"
357         "</head>\n"
358         "<body>\n"
359         "<h1>%d %s%s%s%s</h1>\n"
360         "<hr />\n"
361         "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
362         "</body>\n"
363         "</html>\n", errname, code, errname,
364         (url ? " (" : ""), (url ?: ""), (url ? ")" : ""));
365
366     if (res == -1)
367     {
368         *body = NULL;
369         return 0;
370     }
371
372     return (size_t)res;
373 }
374
375
376 /*****************************************************************************
377  * High Level Functions: httpd_file_t
378  *****************************************************************************/
379 struct httpd_file_t
380 {
381     httpd_url_t *url;
382
383     char *psz_url;
384     char *psz_mime;
385
386     httpd_file_callback_t pf_fill;
387     httpd_file_sys_t      *p_sys;
388
389 };
390
391 static int
392 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
393                     httpd_message_t *answer, const httpd_message_t *query )
394 {
395     httpd_file_t *file = (httpd_file_t*)p_sys;
396     uint8_t *psz_args = query->psz_args;
397     uint8_t **pp_body, *p_body;
398     const char *psz_connection;
399     int *pi_body, i_body;
400
401     if( answer == NULL || query == NULL )
402     {
403         return VLC_SUCCESS;
404     }
405     answer->i_proto  = HTTPD_PROTO_HTTP;
406     answer->i_version= 1;
407     answer->i_type   = HTTPD_MSG_ANSWER;
408
409     answer->i_status = 200;
410
411     httpd_MsgAdd( answer, "Content-type",  "%s", file->psz_mime );
412     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
413
414     if( query->i_type != HTTPD_MSG_HEAD )
415     {
416         pp_body = &answer->p_body;
417         pi_body = &answer->i_body;
418     }
419     else
420     {
421         /* The file still needs to be executed. */
422         p_body = NULL;
423         i_body = 0;
424         pp_body = &p_body;
425         pi_body = &i_body;
426     }
427
428     if( query->i_type == HTTPD_MSG_POST )
429     {
430         /* msg_Warn not supported */
431     }
432
433     file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
434
435     if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
436     {
437         free( p_body );
438     }
439
440     /* We respect client request */
441     psz_connection = httpd_MsgGet( &cl->query, "Connection" );
442     if( psz_connection != NULL )
443     {
444         httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
445     }
446
447     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
448
449     return VLC_SUCCESS;
450 }
451
452 httpd_file_t *httpd_FileNew( httpd_host_t *host,
453                              const char *psz_url, const char *psz_mime,
454                              const char *psz_user, const char *psz_password,
455                              const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
456                              httpd_file_sys_t *p_sys )
457 {
458     httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
459
460     if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
461                                           psz_password, p_acl )
462         ) == NULL )
463     {
464         free( file );
465         return NULL;
466     }
467
468     file->psz_url  = strdup( psz_url );
469     if( psz_mime && *psz_mime )
470     {
471         file->psz_mime = strdup( psz_mime );
472     }
473     else
474     {
475         file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
476     }
477
478     file->pf_fill = pf_fill;
479     file->p_sys   = p_sys;
480
481     httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
482                     (httpd_callback_sys_t*)file );
483     httpd_UrlCatch( file->url, HTTPD_MSG_GET,  httpd_FileCallBack,
484                     (httpd_callback_sys_t*)file );
485     httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
486                     (httpd_callback_sys_t*)file );
487
488     return file;
489 }
490
491 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
492 {
493     httpd_file_sys_t *p_sys = file->p_sys;
494
495     httpd_UrlDelete( file->url );
496
497     free( file->psz_url );
498     free( file->psz_mime );
499
500     free( file );
501
502     return p_sys;
503 }
504
505 /*****************************************************************************
506  * High Level Functions: httpd_handler_t (for CGIs)
507  *****************************************************************************/
508 struct httpd_handler_t
509 {
510     httpd_url_t *url;
511
512     httpd_handler_callback_t pf_fill;
513     httpd_handler_sys_t      *p_sys;
514
515 };
516
517 static int
518 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
519                        httpd_message_t *answer, const httpd_message_t *query )
520 {
521     httpd_handler_t *handler = (httpd_handler_t*)p_sys;
522     uint8_t *psz_args = query->psz_args;
523     char psz_remote_addr[NI_MAXNUMERICHOST];
524
525     if( answer == NULL || query == NULL )
526     {
527         return VLC_SUCCESS;
528     }
529     answer->i_proto  = HTTPD_PROTO_NONE;
530     answer->i_type   = HTTPD_MSG_ANSWER;
531
532     /* We do it ourselves, thanks */
533     answer->i_status = 0;
534
535     if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
536         *psz_remote_addr = '\0';
537
538     handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
539                       query->i_type, query->p_body, query->i_body,
540                       psz_remote_addr, NULL,
541                       &answer->p_body, &answer->i_body );
542
543     if( query->i_type == HTTPD_MSG_HEAD )
544     {
545         char *p = (char *)answer->p_body;
546
547         /* Looks for end of header (i.e. one empty line) */
548         while ( (p = strchr( p, '\r' )) != NULL )
549         {
550             if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
551                  && p[3] && p[3] == '\n' )
552             {
553                 break;
554             }
555         }
556
557         if( p != NULL )
558         {
559             p[4] = '\0';
560             answer->i_body = strlen((char*)answer->p_body) + 1;
561             answer->p_body = realloc( answer->p_body, answer->i_body );
562         }
563     }
564
565     if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
566     {
567         int i_status, i_headers;
568         char *psz_headers, *psz_new;
569         const char *psz_status;
570
571         if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
572         {
573             /* Apache-style */
574             i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
575             if( *psz_headers ) psz_headers++;
576             if( *psz_headers ) psz_headers++;
577             i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
578         }
579         else
580         {
581             i_status = 200;
582             psz_headers = (char *)answer->p_body;
583             i_headers = answer->i_body;
584         }
585
586         psz_status = httpd_ReasonFromCode( i_status );
587         answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
588                         + strlen(psz_status) + i_headers - 1;
589         psz_new = (char *)malloc( answer->i_body + 1);
590         sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
591         memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
592         free( answer->p_body );
593         answer->p_body = (uint8_t *)psz_new;
594     }
595
596     return VLC_SUCCESS;
597 }
598
599 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
600                                    const char *psz_user,
601                                    const char *psz_password,
602                                    const vlc_acl_t *p_acl,
603                                    httpd_handler_callback_t pf_fill,
604                                    httpd_handler_sys_t *p_sys )
605 {
606     httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
607
608     if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
609                                              psz_password, p_acl )
610         ) == NULL )
611     {
612         free( handler );
613         return NULL;
614     }
615
616     handler->pf_fill = pf_fill;
617     handler->p_sys   = p_sys;
618
619     httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
620                     (httpd_callback_sys_t*)handler );
621     httpd_UrlCatch( handler->url, HTTPD_MSG_GET,  httpd_HandlerCallBack,
622                     (httpd_callback_sys_t*)handler );
623     httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
624                     (httpd_callback_sys_t*)handler );
625
626     return handler;
627 }
628
629 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
630 {
631     httpd_handler_sys_t *p_sys = handler->p_sys;
632     httpd_UrlDelete( handler->url );
633     free( handler );
634     return p_sys;
635 }
636
637 /*****************************************************************************
638  * High Level Functions: httpd_redirect_t
639  *****************************************************************************/
640 struct httpd_redirect_t
641 {
642     httpd_url_t *url;
643     char        *psz_dst;
644 };
645
646 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
647                                    httpd_client_t *cl, httpd_message_t *answer,
648                                    const httpd_message_t *query )
649 {
650     httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
651     char *p_body;
652     (void)cl;
653
654     if( answer == NULL || query == NULL )
655     {
656         return VLC_SUCCESS;
657     }
658     answer->i_proto  = HTTPD_PROTO_HTTP;
659     answer->i_version= 1;
660     answer->i_type   = HTTPD_MSG_ANSWER;
661     answer->i_status = 301;
662
663     answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
664     answer->p_body = (unsigned char *)p_body;
665
666     /* XXX check if it's ok or we need to set an absolute url */
667     httpd_MsgAdd( answer, "Location",  "%s", rdir->psz_dst );
668
669     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
670
671     return VLC_SUCCESS;
672 }
673
674 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
675                                      const char *psz_url_src )
676 {
677     httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
678
679     if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
680     {
681         free( rdir );
682         return NULL;
683     }
684     rdir->psz_dst = strdup( psz_url_dst );
685
686     /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
687     httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
688                     (httpd_callback_sys_t*)rdir );
689     httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
690                     (httpd_callback_sys_t*)rdir );
691     httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
692                     (httpd_callback_sys_t*)rdir );
693     httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
694                     (httpd_callback_sys_t*)rdir );
695
696     return rdir;
697 }
698 void httpd_RedirectDelete( httpd_redirect_t *rdir )
699 {
700     httpd_UrlDelete( rdir->url );
701     free( rdir->psz_dst );
702     free( rdir );
703 }
704
705 /*****************************************************************************
706  * High Level Funtions: httpd_stream_t
707  *****************************************************************************/
708 struct httpd_stream_t
709 {
710     vlc_mutex_t lock;
711     httpd_url_t *url;
712
713     char    *psz_mime;
714
715     /* Header to send as first packet */
716     uint8_t *p_header;
717     int     i_header;
718
719     /* circular buffer */
720     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
721     uint8_t     *p_buffer;          /* buffer */
722     int64_t     i_buffer_pos;       /* absolute position from begining */
723     int64_t     i_buffer_last_pos;  /* a new connection will start with that */
724 };
725
726 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
727                                  httpd_client_t *cl, httpd_message_t *answer,
728                                  const httpd_message_t *query )
729 {
730     httpd_stream_t *stream = (httpd_stream_t*)p_sys;
731
732     if( answer == NULL || query == NULL || cl == NULL )
733     {
734         return VLC_SUCCESS;
735     }
736
737     if( answer->i_body_offset > 0 )
738     {
739         int64_t i_write;
740         int     i_pos;
741
742 #if 0
743         fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
744                  answer->i_body_offset );
745 #endif
746
747         if( answer->i_body_offset >= stream->i_buffer_pos )
748         {
749             /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
750             return VLC_EGENERIC;    /* wait, no data available */
751         }
752         if( answer->i_body_offset + stream->i_buffer_size <
753             stream->i_buffer_pos )
754         {
755             /* this client isn't fast enough */
756 #if 0
757             fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
758                      answer->i_body_offset, stream->i_buffer_last_pos );
759 #endif
760             answer->i_body_offset = stream->i_buffer_last_pos;
761         }
762
763         i_pos   = answer->i_body_offset % stream->i_buffer_size;
764         i_write = stream->i_buffer_pos - answer->i_body_offset;
765         if( i_write > HTTPD_CL_BUFSIZE )
766         {
767             i_write = HTTPD_CL_BUFSIZE;
768         }
769         else if( i_write <= 0 )
770         {
771             return VLC_EGENERIC;    /* wait, no data available */
772         }
773
774         /* Don't go past the end of the circular buffer */
775         i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
776
777         /* using HTTPD_MSG_ANSWER -> data available */
778         answer->i_proto  = HTTPD_PROTO_HTTP;
779         answer->i_version= 0;
780         answer->i_type   = HTTPD_MSG_ANSWER;
781
782         answer->i_body = i_write;
783         answer->p_body = malloc( i_write );
784         memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
785
786         answer->i_body_offset += i_write;
787
788         return VLC_SUCCESS;
789     }
790     else
791     {
792         answer->i_proto  = HTTPD_PROTO_HTTP;
793         answer->i_version= 0;
794         answer->i_type   = HTTPD_MSG_ANSWER;
795
796         answer->i_status = 200;
797
798         if( query->i_type != HTTPD_MSG_HEAD )
799         {
800             httpd_ClientModeStream( cl );
801             vlc_mutex_lock( &stream->lock );
802             /* Send the header */
803             if( stream->i_header > 0 )
804             {
805                 answer->i_body = stream->i_header;
806                 answer->p_body = malloc( stream->i_header );
807                 memcpy( answer->p_body, stream->p_header, stream->i_header );
808             }
809             answer->i_body_offset = stream->i_buffer_last_pos;
810             vlc_mutex_unlock( &stream->lock );
811         }
812         else
813         {
814             httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
815             answer->i_body_offset = 0;
816         }
817
818         if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
819         {
820             vlc_bool_t b_xplaystream = VLC_FALSE;
821             int i;
822
823             httpd_MsgAdd( answer, "Content-type", "%s",
824                           "application/octet-stream" );
825             httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
826             httpd_MsgAdd( answer, "Pragma", "no-cache" );
827             httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
828             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
829
830             /* Check if there is a xPlayStrm=1 */
831             for( i = 0; i < query->i_name; i++ )
832             {
833                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
834                     strstr( query->value[i], "xPlayStrm=1" ) )
835                 {
836                     b_xplaystream = VLC_TRUE;
837                 }
838             }
839
840             if( !b_xplaystream )
841             {
842                 answer->i_body_offset = 0;
843             }
844         }
845         else
846         {
847             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
848         }
849         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
850         return VLC_SUCCESS;
851     }
852 }
853
854 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
855                                  const char *psz_url, const char *psz_mime,
856                                  const char *psz_user, const char *psz_password,
857                                  const vlc_acl_t *p_acl )
858 {
859     httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
860
861     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
862                                             psz_password, p_acl )
863         ) == NULL )
864     {
865         free( stream );
866         return NULL;
867     }
868     vlc_mutex_init( host, &stream->lock );
869     if( psz_mime && *psz_mime )
870     {
871         stream->psz_mime = strdup( psz_mime );
872     }
873     else
874     {
875         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
876     }
877     stream->i_header = 0;
878     stream->p_header = NULL;
879     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
880     stream->p_buffer = malloc( stream->i_buffer_size );
881     /* We set to 1 to make life simpler
882      * (this way i_body_offset can never be 0) */
883     stream->i_buffer_pos = 1;
884     stream->i_buffer_last_pos = 1;
885
886     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
887                     (httpd_callback_sys_t*)stream );
888     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
889                     (httpd_callback_sys_t*)stream );
890     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
891                     (httpd_callback_sys_t*)stream );
892
893     return stream;
894 }
895
896 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
897 {
898     vlc_mutex_lock( &stream->lock );
899     if( stream->p_header )
900     {
901         free( stream->p_header );
902         stream->p_header = NULL;
903     }
904     stream->i_header = i_data;
905     if( i_data > 0 )
906     {
907         stream->p_header = malloc( i_data );
908         memcpy( stream->p_header, p_data, i_data );
909     }
910     vlc_mutex_unlock( &stream->lock );
911
912     return VLC_SUCCESS;
913 }
914
915 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
916 {
917     int i_count;
918     int i_pos;
919
920     if( i_data < 0 || p_data == NULL )
921     {
922         return VLC_SUCCESS;
923     }
924     vlc_mutex_lock( &stream->lock );
925
926     /* save this pointer (to be used by new connection) */
927     stream->i_buffer_last_pos = stream->i_buffer_pos;
928
929     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
930     i_count = i_data;
931     while( i_count > 0)
932     {
933         int i_copy;
934
935         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
936
937         /* Ok, we can't go past the end of our buffer */
938         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
939
940         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
941         i_count -= i_copy;
942         p_data  += i_copy;
943     }
944
945     stream->i_buffer_pos += i_data;
946
947     vlc_mutex_unlock( &stream->lock );
948     return VLC_SUCCESS;
949 }
950
951 void httpd_StreamDelete( httpd_stream_t *stream )
952 {
953     httpd_UrlDelete( stream->url );
954     vlc_mutex_destroy( &stream->lock );
955     if( stream->psz_mime ) free( stream->psz_mime );
956     if( stream->p_header ) free( stream->p_header );
957     if( stream->p_buffer ) free( stream->p_buffer );
958     free( stream );
959 }
960
961 /*****************************************************************************
962  * Low level
963  *****************************************************************************/
964 static void httpd_HostThread( httpd_host_t * );
965
966 /* create a new host */
967 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
968                              int i_port )
969 {
970     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
971                            );
972 }
973
974 static const char psz_object_type[] = "http server";
975
976 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
977                                 int i_port,
978                                 const char *psz_cert, const char *psz_key,
979                                 const char *psz_ca, const char *psz_crl )
980 {
981     httpd_t      *httpd;
982     httpd_host_t *host;
983     tls_server_t *p_tls;
984     char *psz_host;
985     vlc_value_t  lockval;
986     int i;
987
988     if( psz_hostname == NULL )
989         psz_hostname = "";
990
991     psz_host = strdup( psz_hostname );
992     if( psz_host == NULL )
993     {
994         msg_Err( p_this, "memory error" );
995         return NULL;
996     }
997
998     /* to be sure to avoid multiple creation */
999     var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
1000     var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
1001     vlc_mutex_lock( lockval.p_address );
1002
1003     if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
1004     {
1005         msg_Info( p_this, "creating httpd" );
1006         httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1007                                               VLC_OBJECT_HTTPD,
1008                                               psz_object_type );
1009         if (httpd == NULL)
1010         {
1011             vlc_mutex_unlock( lockval.p_address );
1012             free( psz_host );
1013             return NULL;
1014         }
1015
1016         httpd->i_host = 0;
1017         httpd->host   = NULL;
1018
1019         vlc_object_yield( httpd );
1020         vlc_object_attach( httpd, p_this->p_libvlc );
1021     }
1022
1023     /* verify if it already exist */
1024     for( i = httpd->i_host - 1; i >= 0; i-- )
1025     {
1026         host = httpd->host[i];
1027
1028         /* cannot mix TLS and non-TLS hosts */
1029         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1030          || ( host->i_port != i_port )
1031          || strcmp( host->psz_hostname, psz_hostname ) )
1032             continue;
1033
1034         /* yep found */
1035         host->i_ref++;
1036
1037         vlc_mutex_unlock( lockval.p_address );
1038         return host;
1039     }
1040
1041     host = NULL;
1042
1043     /* determine TLS configuration */
1044     if ( psz_cert != NULL )
1045     {
1046         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1047         if ( p_tls == NULL )
1048         {
1049             msg_Err( p_this, "TLS initialization error" );
1050             goto error;
1051         }
1052
1053         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1054         {
1055             msg_Err( p_this, "TLS CA error" );
1056             goto error;
1057         }
1058
1059         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1060         {
1061             msg_Err( p_this, "TLS CRL error" );
1062             goto error;
1063         }
1064     }
1065     else
1066         p_tls = NULL;
1067
1068     /* create the new host */
1069     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1070                                               VLC_OBJECT_HTTPD_HOST,
1071                                               psz_object_type );
1072     if (host == NULL)
1073         goto error;
1074
1075     vlc_object_lock( host );
1076     if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1077     {
1078         msg_Err( host, "signaling pipe error: %m" );
1079         vlc_object_unlock( host );
1080         goto error;
1081     }
1082     vlc_object_unlock( host );
1083
1084     host->httpd = httpd;
1085     vlc_mutex_init( httpd, &host->lock );
1086     host->i_ref = 1;
1087
1088     host->fds = net_ListenTCP( p_this, psz_host, i_port );
1089     if( host->fds == NULL )
1090     {
1091         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1092         goto error;
1093     }
1094     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1095
1096     host->i_port = i_port;
1097     host->psz_hostname = psz_host;
1098
1099     host->i_url     = 0;
1100     host->url       = NULL;
1101     host->i_client  = 0;
1102     host->client    = NULL;
1103
1104     host->p_tls = p_tls;
1105
1106     /* create the thread */
1107     if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1108                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1109     {
1110         msg_Err( p_this, "cannot spawn http host thread" );
1111         goto error;
1112     }
1113
1114     /* now add it to httpd */
1115     TAB_APPEND( httpd->i_host, httpd->host, host );
1116     vlc_mutex_unlock( lockval.p_address );
1117
1118     return host;
1119
1120 error:
1121     free( psz_host );
1122     if( httpd->i_host <= 0 )
1123     {
1124         vlc_object_release( httpd );
1125         vlc_object_detach( httpd );
1126         vlc_object_destroy( httpd );
1127     }
1128     vlc_mutex_unlock( lockval.p_address );
1129
1130     if( host != NULL )
1131     {
1132         net_ListenClose( host->fds );
1133         vlc_mutex_destroy( &host->lock );
1134         vlc_object_destroy( host );
1135     }
1136
1137     if( p_tls != NULL )
1138         tls_ServerDelete( p_tls );
1139
1140     return NULL;
1141 }
1142
1143 /* delete a host */
1144 void httpd_HostDelete( httpd_host_t *host )
1145 {
1146     httpd_t *httpd = host->httpd;
1147     vlc_value_t lockval;
1148     int i;
1149
1150     var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1151     vlc_mutex_lock( lockval.p_address );
1152
1153     host->i_ref--;
1154     if( host->i_ref > 0 )
1155     {
1156         /* still used */
1157         vlc_mutex_unlock( lockval.p_address );
1158         msg_Dbg( host, "httpd_HostDelete: host still used" );
1159         return;
1160     }
1161     TAB_REMOVE( httpd->i_host, httpd->host, host );
1162
1163     vlc_object_kill( host );
1164     vlc_thread_join( host );
1165
1166     msg_Dbg( host, "HTTP host removed" );
1167
1168     for( i = 0; i < host->i_url; i++ )
1169     {
1170         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1171     }
1172     for( i = 0; i < host->i_client; i++ )
1173     {
1174         httpd_client_t *cl = host->client[i];
1175         msg_Warn( host, "client still connected" );
1176         httpd_ClientClean( cl );
1177         TAB_REMOVE( host->i_client, host->client, cl );
1178         free( cl );
1179         i--;
1180         /* TODO */
1181     }
1182
1183     if( host->p_tls != NULL)
1184         tls_ServerDelete( host->p_tls );
1185
1186     net_ListenClose( host->fds );
1187     free( host->psz_hostname );
1188
1189     vlc_mutex_destroy( &host->lock );
1190     vlc_object_destroy( host );
1191
1192     vlc_object_release( httpd );
1193     if( httpd->i_host <= 0 )
1194     {
1195         msg_Dbg( httpd, "no host left, stopping httpd" );
1196         vlc_object_detach( httpd );
1197         vlc_object_destroy( httpd );
1198     }
1199     vlc_mutex_unlock( lockval.p_address );
1200 }
1201
1202 /* register a new url */
1203 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1204                                          const char *psz_user, const char *psz_password,
1205                                          const vlc_acl_t *p_acl, vlc_bool_t b_check )
1206 {
1207     httpd_url_t *url;
1208     int         i;
1209
1210     assert( psz_url != NULL );
1211
1212     vlc_mutex_lock( &host->lock );
1213     if( b_check )
1214     {
1215         for( i = 0; i < host->i_url; i++ )
1216         {
1217             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1218             {
1219                 msg_Warn( host->httpd,
1220                           "cannot add '%s' (url already defined)", psz_url );
1221                 vlc_mutex_unlock( &host->lock );
1222                 return NULL;
1223             }
1224         }
1225     }
1226
1227     url = malloc( sizeof( httpd_url_t ) );
1228     url->host = host;
1229
1230     vlc_mutex_init( host->httpd, &url->lock );
1231     url->psz_url = strdup( psz_url );
1232     url->psz_user = strdup( psz_user ? psz_user : "" );
1233     url->psz_password = strdup( psz_password ? psz_password : "" );
1234     url->p_acl = ACL_Duplicate( host, p_acl );
1235     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1236     {
1237         url->catch[i].cb = NULL;
1238         url->catch[i].p_sys = NULL;
1239     }
1240
1241     TAB_APPEND( host->i_url, host->url, url );
1242     vlc_mutex_unlock( &host->lock );
1243
1244     return url;
1245 }
1246
1247 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1248                            const char *psz_user, const char *psz_password,
1249                            const vlc_acl_t *p_acl )
1250 {
1251     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1252                                 psz_password, p_acl, VLC_FALSE );
1253 }
1254
1255 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1256                                  const char *psz_user, const char *psz_password,
1257                                  const vlc_acl_t *p_acl )
1258 {
1259     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1260                                 psz_password, p_acl, VLC_TRUE );
1261 }
1262
1263 /* register callback on a url */
1264 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1265                     httpd_callback_sys_t *p_sys )
1266 {
1267     vlc_mutex_lock( &url->lock );
1268     url->catch[i_msg].cb   = cb;
1269     url->catch[i_msg].p_sys= p_sys;
1270     vlc_mutex_unlock( &url->lock );
1271
1272     return VLC_SUCCESS;
1273 }
1274
1275 /* delete an url */
1276 void httpd_UrlDelete( httpd_url_t *url )
1277 {
1278     httpd_host_t *host = url->host;
1279     int          i;
1280
1281     vlc_mutex_lock( &host->lock );
1282     TAB_REMOVE( host->i_url, host->url, url );
1283
1284     vlc_mutex_destroy( &url->lock );
1285     free( url->psz_url );
1286     free( url->psz_user );
1287     free( url->psz_password );
1288     ACL_Destroy( url->p_acl );
1289
1290     for( i = 0; i < host->i_client; i++ )
1291     {
1292         httpd_client_t *client = host->client[i];
1293
1294         if( client->url == url )
1295         {
1296             /* TODO complete it */
1297             msg_Warn( host, "force closing connections" );
1298             httpd_ClientClean( client );
1299             TAB_REMOVE( host->i_client, host->client, client );
1300             free( client );
1301             i--;
1302         }
1303     }
1304     free( url );
1305     vlc_mutex_unlock( &host->lock );
1306 }
1307
1308 void httpd_MsgInit( httpd_message_t *msg )
1309 {
1310     msg->cl         = NULL;
1311     msg->i_type     = HTTPD_MSG_NONE;
1312     msg->i_proto    = HTTPD_PROTO_NONE;
1313     msg->i_version  = -1; /* FIXME */
1314
1315     msg->i_status   = 0;
1316
1317     msg->psz_url    = NULL;
1318     msg->psz_args   = NULL;
1319
1320     msg->i_channel  = -1;
1321
1322     msg->i_name     = 0;
1323     msg->name       = NULL;
1324     msg->i_value    = 0;
1325     msg->value      = NULL;
1326
1327     msg->i_body_offset = 0;
1328     msg->i_body        = 0;
1329     msg->p_body        = NULL;
1330 }
1331
1332 void httpd_MsgClean( httpd_message_t *msg )
1333 {
1334     int i;
1335
1336     if( msg->psz_url )
1337     {
1338         free( msg->psz_url );
1339     }
1340     if( msg->psz_args )
1341     {
1342         free( msg->psz_args );
1343     }
1344     for( i = 0; i < msg->i_name; i++ )
1345     {
1346         free( msg->name[i] );
1347         free( msg->value[i] );
1348     }
1349     if( msg->name )
1350     {
1351         free( msg->name );
1352     }
1353     if( msg->value )
1354     {
1355         free( msg->value );
1356     }
1357     if( msg->p_body )
1358     {
1359         free( msg->p_body );
1360     }
1361     httpd_MsgInit( msg );
1362 }
1363
1364 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1365 {
1366     int i;
1367
1368     for( i = 0; i < msg->i_name; i++ )
1369     {
1370         if( !strcasecmp( msg->name[i], name ))
1371         {
1372             return msg->value[i];
1373         }
1374     }
1375     return NULL;
1376 }
1377
1378 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1379 {
1380     va_list args;
1381     char *value = NULL;
1382
1383     va_start( args, psz_value );
1384     if( vasprintf( &value, psz_value, args ) == -1 )
1385         value = NULL;
1386     va_end( args );
1387
1388     if( value == NULL )
1389         return;
1390
1391     name = strdup( name );
1392     if( name == NULL )
1393     {
1394         free( value );
1395         return;
1396     }
1397
1398     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1399     TAB_APPEND( msg->i_value, msg->value, value );
1400 }
1401
1402 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1403 {
1404     cl->i_state = HTTPD_CLIENT_RECEIVING;
1405     cl->i_activity_date = now;
1406     cl->i_activity_timeout = I64C(10000000);
1407     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1408     cl->i_buffer = 0;
1409     cl->p_buffer = malloc( cl->i_buffer_size );
1410     cl->i_mode   = HTTPD_CLIENT_FILE;
1411     cl->b_read_waiting = VLC_FALSE;
1412
1413     httpd_MsgInit( &cl->query );
1414     httpd_MsgInit( &cl->answer );
1415 }
1416
1417 void httpd_ClientModeStream( httpd_client_t *cl )
1418 {
1419     cl->i_mode   = HTTPD_CLIENT_STREAM;
1420 }
1421
1422 void httpd_ClientModeBidir( httpd_client_t *cl )
1423 {
1424     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1425 }
1426
1427 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1428 {
1429     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1430 }
1431
1432 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1433 {
1434     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1435 }
1436
1437 static void httpd_ClientClean( httpd_client_t *cl )
1438 {
1439     if( cl->fd >= 0 )
1440     {
1441         if( cl->p_tls != NULL )
1442             tls_ServerSessionClose( cl->p_tls );
1443         net_Close( cl->fd );
1444         cl->fd = -1;
1445     }
1446
1447     httpd_MsgClean( &cl->answer );
1448     httpd_MsgClean( &cl->query );
1449
1450     if( cl->p_buffer )
1451     {
1452         free( cl->p_buffer );
1453         cl->p_buffer = NULL;
1454     }
1455 }
1456
1457 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1458 {
1459     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1460
1461     if( !cl ) return NULL;
1462
1463     cl->i_ref   = 0;
1464     cl->fd      = fd;
1465     cl->url     = NULL;
1466     cl->p_tls = p_tls;
1467
1468     httpd_ClientInit( cl, now );
1469
1470     return cl;
1471 }
1472
1473 static int httpd_NetRecv( httpd_client_t *cl, uint8_t *p, int i_len )
1474 {
1475     tls_session_t *p_tls;
1476
1477     p_tls = cl->p_tls;
1478     if( p_tls != NULL)
1479         return tls_Recv( p_tls, p, i_len );
1480
1481     return recv( cl->fd, p, i_len, 0 );
1482 }
1483
1484 static int httpd_NetSend( httpd_client_t *cl, const uint8_t *p, int i_len )
1485 {
1486     tls_session_t *p_tls;
1487
1488     p_tls = cl->p_tls;
1489     if( p_tls != NULL)
1490         return tls_Send( p_tls, p, i_len );
1491
1492     return send( cl->fd, p, i_len, 0 );
1493 }
1494
1495
1496 static const struct
1497 {
1498     const char name[16];
1499     int  i_type;
1500     int  i_proto;
1501 }
1502 msg_type[] =
1503 {
1504     { "OPTIONS",       HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1505     { "DESCRIBE",      HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1506     { "SETUP",         HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1507     { "PLAY",          HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1508     { "PAUSE",         HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1509     { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1510     { "TEARDOWN",      HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1511     { "GET",           HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1512     { "HEAD",          HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1513     { "POST",          HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1514     { "",              HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1515 };
1516
1517
1518 static void httpd_ClientRecv( httpd_client_t *cl )
1519 {
1520     int i_len;
1521
1522     /* ignore leading whites */
1523     if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1524         ( cl->i_buffer == 0 ) )
1525     {
1526         unsigned char c;
1527
1528         i_len = httpd_NetRecv( cl, &c, 1 );
1529
1530         if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1531         {
1532             cl->p_buffer[0] = c;
1533             cl->i_buffer++;
1534         }
1535     }
1536     else
1537     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1538     {
1539         /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1540         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1541                                7 - cl->i_buffer );
1542         if( i_len > 0 )
1543         {
1544             cl->i_buffer += i_len;
1545         }
1546
1547         if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1548         {
1549             /* Interleaved RTP over RTSP */
1550             cl->query.i_proto = HTTPD_PROTO_RTSP;
1551             cl->query.i_type  = HTTPD_MSG_CHANNEL;
1552             cl->query.i_channel = cl->p_buffer[1];
1553             cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1554             cl->query.p_body  = malloc( cl->query.i_body );
1555             cl->i_buffer      -= 4;
1556             memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1557         }
1558         else
1559         /* The smallest legal request is 7 bytes ("GET /\r\n"),
1560          * this is the maximum we can ask at this point. */
1561         if( cl->i_buffer >= 7 )
1562         {
1563             if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1564             {
1565                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1566                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1567             }
1568             else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1569             {
1570                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1571                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1572             }
1573             else
1574             {
1575                 /* We need the full request line to determine the protocol. */
1576                 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1577                 cl->query.i_type  = HTTPD_MSG_NONE;
1578             }
1579         }
1580     }
1581     else if( cl->query.i_body > 0 )
1582     {
1583         /* we are reading the body of a request or a channel */
1584         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1585                                cl->query.i_body - cl->i_buffer );
1586         if( i_len > 0 )
1587         {
1588             cl->i_buffer += i_len;
1589         }
1590         if( cl->i_buffer >= cl->query.i_body )
1591         {
1592             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1593         }
1594     }
1595     else
1596     {
1597         /* we are reading a header -> char by char */
1598         for( ;; )
1599         {
1600             if( cl->i_buffer == cl->i_buffer_size )
1601             {
1602                 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1603                 if( newbuf == NULL )
1604                 {
1605                     i_len = 0;
1606                     break;
1607                 }
1608
1609                 cl->p_buffer = newbuf;
1610                 cl->i_buffer_size += 1024;
1611             }
1612
1613             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1614             if( i_len <= 0 )
1615             {
1616                 break;
1617             }
1618             cl->i_buffer++;
1619
1620             if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1621              && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1622             {
1623                 /* Request line is now complete */
1624                 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1625                 size_t len;
1626
1627                 assert( cl->query.i_type == HTTPD_MSG_NONE );
1628
1629                 if( p == NULL ) /* no URI: evil guy */
1630                 {
1631                     i_len = 0; /* drop connection */
1632                     break;
1633                 }
1634
1635                 do
1636                     p++; /* skips extra spaces */
1637                 while( *p == ' ' );
1638
1639                 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1640                 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1641                 {
1642                     i_len = 0; /* not supported currently -> drop */
1643                     break;
1644                 }
1645
1646                 do
1647                     p++; /* skips extra spaces ever again */
1648                 while( *p == ' ' );
1649
1650                 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1651                 if( len < 7 ) /* foreign protocol */
1652                     i_len = 0; /* I don't understand -> drop */
1653                 else
1654                 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1655                 {
1656                     cl->query.i_proto = HTTPD_PROTO_HTTP;
1657                     cl->query.i_version = atoi( p + 7 );
1658                 }
1659                 else
1660                 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1661                 {
1662                     cl->query.i_proto = HTTPD_PROTO_RTSP;
1663                     cl->query.i_version = atoi( p + 7 );
1664                 }
1665                 else
1666                 if( memcmp( p, "HTTP/", 5 ) == 0 )
1667                 {
1668                     const uint8_t sorry[] =
1669                        "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1670                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1671                     i_len = 0; /* drop */
1672                 }
1673                 else
1674                 if( memcmp( p, "RTSP/", 5 ) == 0 )
1675                 {
1676                     const uint8_t sorry[] =
1677                         "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1678                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1679                     i_len = 0; /* drop */
1680                 }
1681                 else /* yet another foreign protocol */
1682                     i_len = 0;
1683
1684                 if( i_len == 0 )
1685                     break;
1686             }
1687
1688             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1689                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1690             {
1691                 char *p;
1692
1693                 /* we have finished the header so parse it and set i_body */
1694                 cl->p_buffer[cl->i_buffer] = '\0';
1695
1696                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1697                 {
1698                     /* FIXME:
1699                      * assume strlen( "HTTP/1.x" ) = 8
1700                      */
1701                     cl->query.i_status =
1702                         strtol( (char *)&cl->p_buffer[8],
1703                                 &p, 0 );
1704                     while( *p == ' ' )
1705                         p++;
1706                 }
1707                 else
1708                 {
1709                     unsigned i;
1710
1711                     p = NULL;
1712                     cl->query.i_type = HTTPD_MSG_NONE;
1713
1714                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1715
1716                     for( i = 0; msg_type[i].name[0]; i++ )
1717                     {
1718                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1719                                       strlen( msg_type[i].name ) ) )
1720                         {
1721                             p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1722                             cl->query.i_type = msg_type[i].i_type;
1723                             if( cl->query.i_proto != msg_type[i].i_proto )
1724                             {
1725                                 p = NULL;
1726                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1727                                 cl->query.i_type = HTTPD_MSG_NONE;
1728                             }
1729                             break;
1730                         }
1731                     }
1732                     if( p == NULL )
1733                     {
1734                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1735                         {
1736                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1737                         }
1738                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1739                         {
1740                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1741                         }
1742                     }
1743                     else
1744                     {
1745                         char *p2;
1746                         char *p3;
1747
1748                         while( *p == ' ' )
1749                         {
1750                             p++;
1751                         }
1752                         p2 = strchr( p, ' ' );
1753                         if( p2 )
1754                         {
1755                             *p2++ = '\0';
1756                         }
1757                         if( !strncasecmp( p, "rtsp:", 5 ) )
1758                         {
1759                             /* for rtsp url, you have rtsp://localhost:port/path */
1760                             p += 5;
1761                             while( *p == '/' ) p++;
1762                             while( *p && *p != '/' ) p++;
1763                         }
1764                         cl->query.psz_url = strdup( p );
1765                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1766                         {
1767                             *p3++ = '\0';
1768                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1769                         }
1770                         p = p2;
1771                     }
1772                 }
1773                 if( p )
1774                 {
1775                     p = strchr( p, '\n' );
1776                 }
1777                 if( p )
1778                 {
1779                     while( *p == '\n' || *p == '\r' )
1780                     {
1781                         p++;
1782                     }
1783                     while( p && *p != '\0' )
1784                     {
1785                         char *line = p;
1786                         char *eol = p = strchr( p, '\n' );
1787                         char *colon;
1788
1789                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1790                         {
1791                             *eol-- = '\0';
1792                         }
1793
1794                         if( ( colon = strchr( line, ':' ) ) )
1795                         {
1796                             char *name;
1797                             char *value;
1798
1799                             *colon++ = '\0';
1800                             while( *colon == ' ' )
1801                             {
1802                                 colon++;
1803                             }
1804                             name = strdup( line );
1805                             value = strdup( colon );
1806
1807                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1808                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1809
1810                             if( !strcasecmp( name, "Content-Length" ) )
1811                             {
1812                                 cl->query.i_body = atol( value );
1813                             }
1814                         }
1815
1816                         if( p )
1817                         {
1818                             p++;
1819                             while( *p == '\n' || *p == '\r' )
1820                             {
1821                                 p++;
1822                             }
1823                         }
1824                     }
1825                 }
1826                 if( cl->query.i_body > 0 )
1827                 {
1828                     /* TODO Mhh, handle the case client will only send a
1829                      * request and close the connection
1830                      * to mark and of body (probably only RTSP) */
1831                     cl->query.p_body = malloc( cl->query.i_body );
1832                     cl->i_buffer = 0;
1833                 }
1834                 else
1835                 {
1836                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1837                 }
1838             }
1839         }
1840     }
1841
1842     /* check if the client is to be set to dead */
1843 #if defined( WIN32 ) || defined( UNDER_CE )
1844     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1845 #else
1846     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1847 #endif
1848     {
1849         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1850         {
1851             /* connection closed -> end of data */
1852             if( cl->query.i_body > 0 )
1853             {
1854                 cl->query.i_body = cl->i_buffer;
1855             }
1856             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1857         }
1858         else
1859         {
1860             cl->i_state = HTTPD_CLIENT_DEAD;
1861         }
1862     }
1863
1864     /* XXX: for QT I have to disable timeout. Try to find why */
1865     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1866         cl->i_activity_timeout = 0;
1867
1868 #if 0 /* Debugging only */
1869     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1870     {
1871         int i;
1872
1873         fprintf( stderr, "received new request\n" );
1874         fprintf( stderr, "  - proto=%s\n",
1875                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1876         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1877         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1878         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1879         {
1880             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1881                      cl->query.psz_status );
1882         }
1883         else if( cl->query.i_type != HTTPD_MSG_NONE )
1884         {
1885             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1886         }
1887         for( i = 0; i < cl->query.i_name; i++ )
1888         {
1889             fprintf( stderr, "  - option name='%s' value='%s'\n",
1890                      cl->query.name[i], cl->query.value[i] );
1891         }
1892     }
1893 #endif
1894 }
1895
1896 static void httpd_ClientSend( httpd_client_t *cl )
1897 {
1898     int i;
1899     int i_len;
1900
1901     if( cl->i_buffer < 0 )
1902     {
1903         /* We need to create the header */
1904         int i_size = 0;
1905         char *p;
1906         const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1907
1908         i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1909         for( i = 0; i < cl->answer.i_name; i++ )
1910         {
1911             i_size += strlen( cl->answer.name[i] ) + 2 +
1912                       strlen( cl->answer.value[i] ) + 2;
1913         }
1914
1915         if( cl->i_buffer_size < i_size )
1916         {
1917             cl->i_buffer_size = i_size;
1918             free( cl->p_buffer );
1919             cl->p_buffer = malloc( i_size );
1920         }
1921         p = (char *)cl->p_buffer;
1922
1923         p += sprintf( p, "%s.%u %d %s\r\n",
1924                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1925                       cl->answer.i_version,
1926                       cl->answer.i_status, psz_status );
1927         for( i = 0; i < cl->answer.i_name; i++ )
1928         {
1929             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1930                           cl->answer.value[i] );
1931         }
1932         p += sprintf( p, "\r\n" );
1933
1934         cl->i_buffer = 0;
1935         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1936
1937         /*fprintf( stderr, "sending answer\n" );
1938         fprintf( stderr, "%s",  cl->p_buffer );*/
1939     }
1940
1941     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1942                            cl->i_buffer_size - cl->i_buffer );
1943     if( i_len >= 0 )
1944     {
1945         cl->i_buffer += i_len;
1946
1947         if( cl->i_buffer >= cl->i_buffer_size )
1948         {
1949             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1950                 !cl->b_read_waiting )
1951             {
1952                 /* catch more body data */
1953                 int     i_msg = cl->query.i_type;
1954                 int64_t i_offset = cl->answer.i_body_offset;
1955
1956                 httpd_MsgClean( &cl->answer );
1957                 cl->answer.i_body_offset = i_offset;
1958
1959                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1960                                           &cl->answer, &cl->query );
1961             }
1962
1963             if( cl->answer.i_body > 0 )
1964             {
1965                 /* send the body data */
1966                 free( cl->p_buffer );
1967                 cl->p_buffer = cl->answer.p_body;
1968                 cl->i_buffer_size = cl->answer.i_body;
1969                 cl->i_buffer = 0;
1970
1971                 cl->answer.i_body = 0;
1972                 cl->answer.p_body = NULL;
1973             }
1974             else
1975             {
1976                 /* send finished */
1977                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1978             }
1979         }
1980     }
1981     else
1982     {
1983 #if defined( WIN32 ) || defined( UNDER_CE )
1984         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1985 #else
1986         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1987 #endif
1988         {
1989             /* error */
1990             cl->i_state = HTTPD_CLIENT_DEAD;
1991         }
1992     }
1993 }
1994
1995 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1996 {
1997     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1998     {
1999         case 0:
2000             cl->i_state = HTTPD_CLIENT_RECEIVING;
2001             break;
2002
2003         case -1:
2004             cl->i_state = HTTPD_CLIENT_DEAD;
2005             cl->p_tls = NULL;
2006             break;
2007
2008         case 2:
2009             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2010     }
2011 }
2012
2013 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2014 {
2015     switch( tls_SessionContinueHandshake( cl->p_tls ) )
2016     {
2017         case 0:
2018             cl->i_state = HTTPD_CLIENT_RECEIVING;
2019             break;
2020
2021         case -1:
2022             cl->i_state = HTTPD_CLIENT_DEAD;
2023             cl->p_tls = NULL;
2024             break;
2025
2026         case 1:
2027             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2028             break;
2029     }
2030 }
2031
2032 static void httpd_HostThread( httpd_host_t *host )
2033 {
2034     tls_session_t *p_tls = NULL;
2035     counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2036     counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2037     int evfd;
2038     vlc_bool_t b_die;
2039
2040     vlc_object_lock( host );
2041     evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2042     b_die = !vlc_object_alive( host );
2043     vlc_object_unlock( host );
2044
2045     while( !b_die )
2046     {
2047         if( host->i_url <= 0 )
2048         {
2049             /* 0.2s (FIXME: use a condition variable) */
2050             msleep( 200000 );
2051             continue;
2052         }
2053
2054         /* prepare a new TLS session */
2055         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2056             p_tls = tls_ServerSessionPrepare( host->p_tls );
2057
2058         struct pollfd ufd[host->nfd + host->i_client + 1];
2059         unsigned nfd;
2060         for( nfd = 0; nfd < host->nfd; nfd++ )
2061         {
2062             ufd[nfd].fd = host->fds[nfd];
2063             ufd[nfd].events = POLLIN;
2064             ufd[nfd].revents = 0;
2065         }
2066
2067         /* add all socket that should be read/write and close dead connection */
2068         vlc_mutex_lock( &host->lock );
2069         mtime_t now = mdate();
2070         vlc_bool_t b_low_delay = VLC_FALSE;
2071
2072         for(int i_client = 0; i_client < host->i_client; i_client++ )
2073         {
2074             httpd_client_t *cl = host->client[i_client];
2075             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2076                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2077                   ( cl->i_activity_timeout > 0 &&
2078                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2079             {
2080                 httpd_ClientClean( cl );
2081                 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2082                 TAB_REMOVE( host->i_client, host->client, cl );
2083                 free( cl );
2084                 i_client--;
2085                 continue;
2086             }
2087
2088             struct pollfd *pufd = ufd + nfd;
2089             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2090
2091             pufd->fd = cl->fd;
2092             pufd->events = pufd->revents = 0;
2093
2094             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2095                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2096             {
2097                 pufd->events = POLLIN;
2098             }
2099             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2100                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2101             {
2102                 pufd->events = POLLOUT;
2103             }
2104             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2105             {
2106                 httpd_message_t *answer = &cl->answer;
2107                 httpd_message_t *query  = &cl->query;
2108                 int i_msg = query->i_type;
2109
2110                 httpd_MsgInit( answer );
2111
2112                 /* Handle what we received */
2113                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2114                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2115                 {
2116                     /* we can only receive request from client when not
2117                      * in BIDIR mode */
2118                     cl->url     = NULL;
2119                     cl->i_state = HTTPD_CLIENT_DEAD;
2120                 }
2121                 else if( i_msg == HTTPD_MSG_ANSWER )
2122                 {
2123                     /* We are in BIDIR mode, trigger the callback and then
2124                      * check for new data */
2125                     if( cl->url && cl->url->catch[i_msg].cb )
2126                     {
2127                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2128                                                   cl, NULL, query );
2129                     }
2130                     cl->i_state = HTTPD_CLIENT_WAITING;
2131                 }
2132                 else if( i_msg == HTTPD_MSG_CHANNEL )
2133                 {
2134                     /* We are in BIDIR mode, trigger the callback and then
2135                      * check for new data */
2136                     if( cl->url && cl->url->catch[i_msg].cb )
2137                     {
2138                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2139                                                   cl, NULL, query );
2140                     }
2141                     cl->i_state = HTTPD_CLIENT_WAITING;
2142                 }
2143                 else if( i_msg == HTTPD_MSG_OPTIONS )
2144                 {
2145
2146                     answer->i_type   = HTTPD_MSG_ANSWER;
2147                     answer->i_proto  = query->i_proto;
2148                     answer->i_status = 200;
2149                     answer->i_body = 0;
2150                     answer->p_body = NULL;
2151
2152                     httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2153                     httpd_MsgAdd( answer, "Content-Length", "0" );
2154
2155                     switch( query->i_proto )
2156                     {
2157                         case HTTPD_PROTO_HTTP:
2158                             answer->i_version = 1;
2159                             httpd_MsgAdd( answer, "Allow",
2160                                           "GET,HEAD,POST,OPTIONS" );
2161                             break;
2162
2163                         case HTTPD_PROTO_RTSP:
2164                         {
2165                             const char *p;
2166                             answer->i_version = 0;
2167
2168                             p = httpd_MsgGet( query, "Cseq" );
2169                             if( p != NULL )
2170                                 httpd_MsgAdd( answer, "Cseq", "%s", p );
2171                             p = httpd_MsgGet( query, "Timestamp" );
2172                             if( p != NULL )
2173                                 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2174
2175                             p = httpd_MsgGet( query, "Require" );
2176                             if( p != NULL )
2177                             {
2178                                 answer->i_status = 551;
2179                                 httpd_MsgAdd( query, "Unsupported", "%s", p );
2180                             }
2181
2182                             httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2183                                           "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2184                             break;
2185                         }
2186                     }
2187
2188                     cl->i_buffer = -1;  /* Force the creation of the answer in
2189                                          * httpd_ClientSend */
2190                     cl->i_state = HTTPD_CLIENT_SENDING;
2191                 }
2192                 else if( i_msg == HTTPD_MSG_NONE )
2193                 {
2194                     if( query->i_proto == HTTPD_PROTO_NONE )
2195                     {
2196                         cl->url = NULL;
2197                         cl->i_state = HTTPD_CLIENT_DEAD;
2198                     }
2199                     else
2200                     {
2201                         char *p;
2202
2203                         /* unimplemented */
2204                         answer->i_proto  = query->i_proto ;
2205                         answer->i_type   = HTTPD_MSG_ANSWER;
2206                         answer->i_version= 0;
2207                         answer->i_status = 501;
2208
2209                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2210                         answer->p_body = (uint8_t *)p;
2211                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2212
2213                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2214                         cl->i_state = HTTPD_CLIENT_SENDING;
2215                     }
2216                 }
2217                 else
2218                 {
2219                     vlc_bool_t b_auth_failed = VLC_FALSE;
2220                     vlc_bool_t b_hosts_failed = VLC_FALSE;
2221
2222                     /* Search the url and trigger callbacks */
2223                     for(int i = 0; i < host->i_url; i++ )
2224                     {
2225                         httpd_url_t *url = host->url[i];
2226
2227                         if( !strcmp( url->psz_url, query->psz_url ) )
2228                         {
2229                             if( url->catch[i_msg].cb )
2230                             {
2231                                 if( answer && ( url->p_acl != NULL ) )
2232                                 {
2233                                     char ip[NI_MAXNUMERICHOST];
2234
2235                                     if( ( httpd_ClientIP( cl, ip ) == NULL )
2236                                      || ACL_Check( url->p_acl, ip ) )
2237                                     {
2238                                         b_hosts_failed = VLC_TRUE;
2239                                         break;
2240                                     }
2241                                 }
2242
2243                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2244                                 {
2245                                     /* create the headers */
2246                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2247                                     char *user = NULL, *pass = NULL;
2248
2249                                     if( b64 != NULL
2250                                      && !strncasecmp( b64, "BASIC", 5 ) )
2251                                     {
2252                                         b64 += 5;
2253                                         while( *b64 == ' ' )
2254                                             b64++;
2255
2256                                         user = vlc_b64_decode( b64 );
2257                                         if (user != NULL)
2258                                         {
2259                                             pass = strchr (user, ':');
2260                                             if (pass != NULL)
2261                                                 *pass++ = '\0';
2262                                         }
2263                                     }
2264
2265                                     if ((user == NULL) || (pass == NULL)
2266                                      || strcmp (user, url->psz_user)
2267                                      || strcmp (pass, url->psz_password))
2268                                     {
2269                                         httpd_MsgAdd( answer,
2270                                                       "WWW-Authenticate",
2271                                                       "Basic realm=\"%s\"",
2272                                                       url->psz_user );
2273                                         /* We fail for all url */
2274                                         b_auth_failed = VLC_TRUE;
2275                                         free( user );
2276                                         break;
2277                                     }
2278
2279                                     free( user );
2280                                 }
2281
2282                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2283                                 {
2284                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2285                                     {
2286                                         /* Raw answer from a CGI */
2287                                         cl->i_buffer = cl->i_buffer_size;
2288                                     }
2289                                     else
2290                                         cl->i_buffer = -1;
2291
2292                                     /* only one url can answer */
2293                                     answer = NULL;
2294                                     if( cl->url == NULL )
2295                                     {
2296                                         cl->url = url;
2297                                     }
2298                                 }
2299                             }
2300                         }
2301                     }
2302
2303                     if( answer )
2304                     {
2305                         char *p;
2306
2307                         answer->i_proto  = query->i_proto;
2308                         answer->i_type   = HTTPD_MSG_ANSWER;
2309                         answer->i_version= 0;
2310
2311                         if( b_hosts_failed )
2312                         {
2313                             answer->i_status = 403;
2314                         }
2315                         else if( b_auth_failed )
2316                         {
2317                             answer->i_status = 401;
2318                         }
2319                         else
2320                         {
2321                             /* no url registered */
2322                             answer->i_status = 404;
2323                         }
2324
2325                         answer->i_body = httpd_HtmlError (&p,
2326                                                           answer->i_status,
2327                                                           query->psz_url);
2328                         answer->p_body = (uint8_t *)p;
2329
2330                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2331                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2332                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2333                     }
2334
2335                     cl->i_state = HTTPD_CLIENT_SENDING;
2336                 }
2337             }
2338             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2339             {
2340                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2341                 {
2342                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2343                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2344                     vlc_bool_t b_connection = VLC_FALSE;
2345                     vlc_bool_t b_keepalive = VLC_FALSE;
2346                     vlc_bool_t b_query = VLC_FALSE;
2347
2348                     cl->url = NULL;
2349                     if( psz_connection )
2350                     {
2351                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2352                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2353                     }
2354
2355                     if( psz_query )
2356                     {
2357                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2358                     }
2359
2360                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2361                           ( ( cl->answer.i_version == 0 && b_keepalive ) ||
2362                             ( cl->answer.i_version == 1 && !b_connection ) ) ) ||
2363                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2364                           !b_query && !b_connection ) )
2365                     {
2366                         httpd_MsgClean( &cl->query );
2367                         httpd_MsgInit( &cl->query );
2368
2369                         cl->i_buffer = 0;
2370                         cl->i_buffer_size = 1000;
2371                         free( cl->p_buffer );
2372                         cl->p_buffer = malloc( cl->i_buffer_size );
2373                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2374                     }
2375                     else
2376                     {
2377                         cl->i_state = HTTPD_CLIENT_DEAD;
2378                     }
2379                     httpd_MsgClean( &cl->answer );
2380                 }
2381                 else if( cl->b_read_waiting )
2382                 {
2383                     /* we have a message waiting for us to read it */
2384                     httpd_MsgClean( &cl->answer );
2385                     httpd_MsgClean( &cl->query );
2386
2387                     cl->i_buffer = 0;
2388                     cl->i_buffer_size = 1000;
2389                     free( cl->p_buffer );
2390                     cl->p_buffer = malloc( cl->i_buffer_size );
2391                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2392                     cl->b_read_waiting = VLC_FALSE;
2393                 }
2394                 else
2395                 {
2396                     int64_t i_offset = cl->answer.i_body_offset;
2397                     httpd_MsgClean( &cl->answer );
2398
2399                     cl->answer.i_body_offset = i_offset;
2400                     free( cl->p_buffer );
2401                     cl->p_buffer = NULL;
2402                     cl->i_buffer = 0;
2403                     cl->i_buffer_size = 0;
2404
2405                     cl->i_state = HTTPD_CLIENT_WAITING;
2406                 }
2407             }
2408             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2409             {
2410                 int64_t i_offset = cl->answer.i_body_offset;
2411                 int     i_msg = cl->query.i_type;
2412
2413                 httpd_MsgInit( &cl->answer );
2414                 cl->answer.i_body_offset = i_offset;
2415
2416                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2417                                           &cl->answer, &cl->query );
2418                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2419                 {
2420                     /* we have new data, so re-enter send mode */
2421                     cl->i_buffer      = 0;
2422                     cl->p_buffer      = cl->answer.p_body;
2423                     cl->i_buffer_size = cl->answer.i_body;
2424                     cl->answer.p_body = NULL;
2425                     cl->answer.i_body = 0;
2426                     cl->i_state = HTTPD_CLIENT_SENDING;
2427                 }
2428             }
2429
2430             /* Special for BIDIR mode we also check reading */
2431             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2432                 cl->i_state == HTTPD_CLIENT_SENDING )
2433             {
2434                 pufd->events |= POLLIN;
2435             }
2436
2437             if (pufd->events != 0)
2438                 nfd++;
2439             else
2440                 b_low_delay = VLC_TRUE;
2441         }
2442         vlc_mutex_unlock( &host->lock );
2443
2444         ufd[nfd].fd = evfd;
2445         ufd[nfd].events = POLLIN;
2446         ufd[nfd].revents = 0;
2447         nfd++;
2448
2449         /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2450         switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2451         {
2452             case -1:
2453                 if (errno != EINTR)
2454                 {
2455                     /* Kernel on low memory or a bug: pace */
2456                     msg_Err( host, "polling error: %m" );
2457                     msleep( 100000 );
2458                 }
2459             case 0:
2460                 continue;
2461         }
2462
2463         vlc_object_lock( host );
2464         if( ufd[nfd - 1].revents )
2465             b_die = vlc_object_wait( host );
2466         vlc_object_unlock( host );
2467
2468         /* Handle client sockets */
2469         vlc_mutex_lock( &host->lock );
2470         now = mdate();
2471         for( int i_client = 0; i_client < host->i_client; i_client++ )
2472         {
2473             httpd_client_t *cl = host->client[i_client];
2474             const struct pollfd *pufd = &ufd[host->nfd + i_client];
2475
2476             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2477
2478             if( cl->fd != pufd->fd )
2479                 continue; // we were not waiting for this client
2480             if( pufd->revents == 0 )
2481                 continue; // no event received
2482
2483             cl->i_activity_date = now;
2484
2485             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2486             {
2487                 httpd_ClientRecv( cl );
2488             }
2489             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2490             {
2491                 httpd_ClientSend( cl );
2492             }
2493             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2494             {
2495                 httpd_ClientTlsHsIn( cl );
2496             }
2497             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2498             {
2499                 httpd_ClientTlsHsOut( cl );
2500             }
2501
2502             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2503                 cl->i_state == HTTPD_CLIENT_SENDING &&
2504                 (pufd->revents & POLLIN) )
2505             {
2506                 cl->b_read_waiting = VLC_TRUE;
2507             }
2508         }
2509         vlc_mutex_unlock( &host->lock );
2510
2511         /* Handle server sockets (accept new connections) */
2512         for( nfd = 0; nfd < host->nfd; nfd++ )
2513         {
2514             httpd_client_t *cl;
2515             int i_state = -1;
2516             int fd = ufd[nfd].fd;
2517
2518             assert (fd == host->fds[nfd]);
2519
2520             if( ufd[nfd].revents == 0 )
2521                 continue;
2522
2523             /* */
2524             fd = accept (fd, NULL, NULL);
2525             if (fd == -1)
2526                 continue;
2527
2528             net_SetupSocket (fd);
2529             if( p_tls != NULL )
2530             {
2531                 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2532                 {
2533                     case -1:
2534                         msg_Err( host, "Rejecting TLS connection" );
2535                         net_Close( fd );
2536                         fd = -1;
2537                         p_tls = NULL;
2538                         break;
2539
2540                     case 1: /* missing input - most likely */
2541                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2542                         break;
2543
2544                     case 2: /* missing output */
2545                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2546                         break;
2547                 }
2548
2549                 if( (p_tls == NULL) != (host->p_tls == NULL) )
2550                     break; // wasted TLS session, cannot accept() anymore
2551             }
2552
2553             stats_UpdateInteger( host, p_total_counter, 1, NULL );
2554             stats_UpdateInteger( host, p_active_counter, 1, NULL );
2555             cl = httpd_ClientNew( fd, p_tls, now );
2556             p_tls = NULL;
2557             vlc_mutex_lock( &host->lock );
2558             TAB_APPEND( host->i_client, host->client, cl );
2559             vlc_mutex_unlock( &host->lock );
2560             if( i_state != -1 )
2561                 cl->i_state = i_state; // override state for TLS
2562
2563             if (host->p_tls != NULL)
2564                 break; // cannot accept further without new TLS session
2565         }
2566
2567     }
2568
2569     if( p_tls != NULL )
2570         tls_ServerSessionClose( p_tls );
2571     if( p_total_counter )
2572         stats_CounterClean( p_total_counter );
2573     if( p_active_counter )
2574         stats_CounterClean( p_active_counter );
2575 }
2576
2577 #else /* ENABLE_HTTPD */
2578
2579 /* We just define an empty wrapper */
2580 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2581                                 tls_server_t *d )
2582 {
2583     msg_Err( a, "HTTP daemon support is disabled" );
2584     return NULL;
2585 }
2586
2587 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2588 {
2589     msg_Err( a, "HTTP daemon support is disabled" );
2590     return NULL;
2591 }
2592
2593 void httpd_HostDelete( httpd_host_t *a )
2594 {
2595 }
2596
2597 httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
2598                            char *psz_user, char *psz_password,
2599                            const vlc_acl_t *p_acl )
2600 {
2601     return NULL;
2602 }
2603
2604 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
2605                                  char *psz_user, char *psz_password,
2606                                  const vlc_acl_t *p_acl )
2607 {
2608     return NULL;
2609 }
2610
2611 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2612                     httpd_callback_sys_t *d )
2613 {
2614     return 0;
2615 }
2616
2617 void httpd_UrlDelete( httpd_url_t *a )
2618 {
2619 }
2620
2621 char* httpd_ClientIP( httpd_client_t *cl, char *psz_ip )
2622 {
2623     return NULL;
2624 }
2625
2626 char* httpd_ServerIP( httpd_client_t *cl, char *psz_ip )
2627 {
2628     return NULL;
2629 }
2630
2631 void httpd_ClientModeStream( httpd_client_t *a )
2632 {
2633 }
2634
2635 void httpd_ClientModeBidir( httpd_client_t *a )
2636 {
2637 }
2638
2639 void httpd_FileDelete( httpd_file_t *a )
2640 {
2641 }
2642
2643 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2644                              char *e, httpd_file_callback_t f,
2645                              httpd_file_sys_t *g )
2646 {
2647     return NULL;
2648 }
2649
2650 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
2651                                    const char *psz_user,
2652                                    const char *psz_password,
2653                                    const vlc_acl_t *p_acl,
2654                                    httpd_handler_callback_t pf_fill,
2655                                    httpd_handler_sys_t *p_sys )
2656 {
2657     return NULL;
2658 }
2659
2660 void httpd_HandlerDelete( httpd_handler_t *handler )
2661 {
2662 }
2663
2664 void httpd_RedirectDelete( httpd_redirect_t *a )
2665 {
2666 }
2667
2668 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2669                                      char *b, char *c )
2670 {
2671     return NULL;
2672 }
2673
2674 void httpd_StreamDelete( httpd_stream_t *a )
2675 {
2676 }
2677
2678 int httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c )
2679 {
2680     return 0;
2681 }
2682
2683 int httpd_StreamSend ( httpd_stream_t *a, uint8_t *b, int c )
2684 {
2685     return 0;
2686 }
2687
2688 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2689                                  char *d, char *e )
2690 {
2691     return NULL;
2692 }
2693
2694 void httpd_MsgInit ( httpd_message_t *a )
2695 {
2696 }
2697
2698 void httpd_MsgAdd  ( httpd_message_t *a, const char *b, const char *c, ... )
2699 {
2700 }
2701
2702 const char *httpd_MsgGet ( httpd_message_t *a, const char *b )
2703 {
2704     return "";
2705 }
2706
2707 void httpd_MsgClean( httpd_message_t *a )
2708 {
2709 }
2710
2711 #endif /* ENABLE_HTTPD */