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