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