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