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