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