]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Const fixes
[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 *restrict dest, const char *restrict 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     const char *psz_connection;
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;
536         const char *psz_status;
537
538         if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
539         {
540             /* Apache-style */
541             i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
542             if( *psz_headers ) psz_headers++;
543             if( *psz_headers ) psz_headers++;
544             i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
545         }
546         else
547         {
548             i_status = 200;
549             psz_headers = (char *)answer->p_body;
550             i_headers = answer->i_body;
551         }
552         switch( i_status )
553         {
554         case 200:
555             psz_status = "OK";
556             break;
557         case 401:
558             psz_status = "Unauthorized";
559             break;
560         default:
561             if( (i_status < 0) || (i_status > 999) )
562                 i_status = 500;
563             psz_status = "Undefined";
564             break;
565         }
566         answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
567                         + strlen(psz_status) + i_headers - 1;
568         psz_new = (char *)malloc( answer->i_body + 1);
569         sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
570         memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
571         free( answer->p_body );
572         answer->p_body = (uint8_t *)psz_new;
573     }
574
575     return VLC_SUCCESS;
576 }
577
578 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
579                                    const char *psz_user,
580                                    const char *psz_password,
581                                    const vlc_acl_t *p_acl,
582                                    httpd_handler_callback_t pf_fill,
583                                    httpd_handler_sys_t *p_sys )
584 {
585     httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
586
587     if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
588                                              psz_password, p_acl )
589         ) == NULL )
590     {
591         free( handler );
592         return NULL;
593     }
594
595     handler->pf_fill = pf_fill;
596     handler->p_sys   = p_sys;
597
598     httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
599                     (httpd_callback_sys_t*)handler );
600     httpd_UrlCatch( handler->url, HTTPD_MSG_GET,  httpd_HandlerCallBack,
601                     (httpd_callback_sys_t*)handler );
602     httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
603                     (httpd_callback_sys_t*)handler );
604
605     return handler;
606 }
607
608 void httpd_HandlerDelete( httpd_handler_t *handler )
609 {
610     httpd_UrlDelete( handler->url );
611     free( handler );
612 }
613
614 /*****************************************************************************
615  * High Level Functions: httpd_redirect_t
616  *****************************************************************************/
617 struct httpd_redirect_t
618 {
619     httpd_url_t *url;
620     char        *psz_dst;
621 };
622
623 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
624                                    httpd_client_t *cl, httpd_message_t *answer,
625                                    httpd_message_t *query )
626 {
627     httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
628     char *p_body;
629
630     if( answer == NULL || query == NULL )
631     {
632         return VLC_SUCCESS;
633     }
634     answer->i_proto  = query->i_proto;
635     answer->i_version= query->i_version;
636     answer->i_type   = HTTPD_MSG_ANSWER;
637     answer->i_status = 301;
638     answer->psz_status = strdup( "Moved Permanently" );
639
640     answer->i_body = asprintf( &p_body,
641         "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
642         "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
643         "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
644         "<html>\n"
645         "<head>\n"
646         "<title>Redirection</title>\n"
647         "</head>\n"
648         "<body>\n"
649         "<h1>You should be "
650         "<a href=\"%s\">redirected</a></h1>\n"
651         "<hr />\n"
652         "<p><a href=\"http://www.videolan.org\">VideoLAN</a>\n</p>"
653         "<hr />\n"
654         "</body>\n"
655         "</html>\n", rdir->psz_dst );
656     answer->p_body = (unsigned char *)p_body;
657
658     /* XXX check if it's ok or we need to set an absolute url */
659     httpd_MsgAdd( answer, "Location",  "%s", rdir->psz_dst );
660
661     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
662
663     return VLC_SUCCESS;
664 }
665
666 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
667                                      const char *psz_url_src )
668 {
669     httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
670
671     if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
672     {
673         free( rdir );
674         return NULL;
675     }
676     rdir->psz_dst = strdup( psz_url_dst );
677
678     /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
679     httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
680                     (httpd_callback_sys_t*)rdir );
681     httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
682                     (httpd_callback_sys_t*)rdir );
683     httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
684                     (httpd_callback_sys_t*)rdir );
685     httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
686                     (httpd_callback_sys_t*)rdir );
687
688     return rdir;
689 }
690 void httpd_RedirectDelete( httpd_redirect_t *rdir )
691 {
692     httpd_UrlDelete( rdir->url );
693     free( rdir->psz_dst );
694     free( rdir );
695 }
696
697 /*****************************************************************************
698  * High Level Funtions: httpd_stream_t
699  *****************************************************************************/
700 struct httpd_stream_t
701 {
702     vlc_mutex_t lock;
703     httpd_url_t *url;
704
705     char    *psz_mime;
706
707     /* Header to send as first packet */
708     uint8_t *p_header;
709     int     i_header;
710
711     /* circular buffer */
712     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
713     uint8_t     *p_buffer;          /* buffer */
714     int64_t     i_buffer_pos;       /* absolute position from begining */
715     int64_t     i_buffer_last_pos;  /* a new connection will start with that */
716 };
717
718 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
719                                  httpd_client_t *cl, httpd_message_t *answer,
720                                  httpd_message_t *query )
721 {
722     httpd_stream_t *stream = (httpd_stream_t*)p_sys;
723
724     if( answer == NULL || query == NULL || cl == NULL )
725     {
726         return VLC_SUCCESS;
727     }
728
729     if( answer->i_body_offset > 0 )
730     {
731         int64_t i_write;
732         int     i_pos;
733
734 #if 0
735         fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
736                  answer->i_body_offset );
737 #endif
738
739         if( answer->i_body_offset >= stream->i_buffer_pos )
740         {
741             /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
742             return VLC_EGENERIC;    /* wait, no data available */
743         }
744         if( answer->i_body_offset + stream->i_buffer_size <
745             stream->i_buffer_pos )
746         {
747             /* this client isn't fast enough */
748 #if 0
749             fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
750                      answer->i_body_offset, stream->i_buffer_last_pos );
751 #endif
752             answer->i_body_offset = stream->i_buffer_last_pos;
753         }
754
755         i_pos   = answer->i_body_offset % stream->i_buffer_size;
756         i_write = stream->i_buffer_pos - answer->i_body_offset;
757         if( i_write > HTTPD_CL_BUFSIZE )
758         {
759             i_write = HTTPD_CL_BUFSIZE;
760         }
761         else if( i_write <= 0 )
762         {
763             return VLC_EGENERIC;    /* wait, no data available */
764         }
765
766         /* Don't go past the end of the circular buffer */
767         i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
768
769         /* using HTTPD_MSG_ANSWER -> data available */
770         answer->i_proto  = HTTPD_PROTO_HTTP;
771         answer->i_version= 0;
772         answer->i_type   = HTTPD_MSG_ANSWER;
773
774         answer->i_body = i_write;
775         answer->p_body = malloc( i_write );
776         memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
777
778         answer->i_body_offset += i_write;
779
780         return VLC_SUCCESS;
781     }
782     else
783     {
784         answer->i_proto  = HTTPD_PROTO_HTTP;
785         answer->i_version= 0;
786         answer->i_type   = HTTPD_MSG_ANSWER;
787
788         answer->i_status = 200;
789         answer->psz_status = strdup( "OK" );
790
791         if( query->i_type != HTTPD_MSG_HEAD )
792         {
793             httpd_ClientModeStream( cl );
794             vlc_mutex_lock( &stream->lock );
795             /* Send the header */
796             if( stream->i_header > 0 )
797             {
798                 answer->i_body = stream->i_header;
799                 answer->p_body = malloc( stream->i_header );
800                 memcpy( answer->p_body, stream->p_header, stream->i_header );
801             }
802             answer->i_body_offset = stream->i_buffer_last_pos;
803             vlc_mutex_unlock( &stream->lock );
804         }
805         else
806         {
807             httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
808             answer->i_body_offset = 0;
809         }
810
811         if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
812         {
813             vlc_bool_t b_xplaystream = VLC_FALSE;
814             int i;
815
816             httpd_MsgAdd( answer, "Content-type", "%s",
817                           "application/octet-stream" );
818             httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
819             httpd_MsgAdd( answer, "Pragma", "no-cache" );
820             httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
821             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
822
823             /* Check if there is a xPlayStrm=1 */
824             for( i = 0; i < query->i_name; i++ )
825             {
826                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
827                     strstr( query->value[i], "xPlayStrm=1" ) )
828                 {
829                     b_xplaystream = VLC_TRUE;
830                 }
831             }
832
833             if( !b_xplaystream )
834             {
835                 answer->i_body_offset = 0;
836             }
837         }
838         else
839         {
840             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
841         }
842         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
843         return VLC_SUCCESS;
844     }
845 }
846
847 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
848                                  const char *psz_url, const char *psz_mime,
849                                  const char *psz_user, const char *psz_password,
850                                  const vlc_acl_t *p_acl )
851 {
852     httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
853
854     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
855                                             psz_password, p_acl )
856         ) == NULL )
857     {
858         free( stream );
859         return NULL;
860     }
861     vlc_mutex_init( host, &stream->lock );
862     if( psz_mime && *psz_mime )
863     {
864         stream->psz_mime = strdup( psz_mime );
865     }
866     else
867     {
868         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
869     }
870     stream->i_header = 0;
871     stream->p_header = NULL;
872     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
873     stream->p_buffer = malloc( stream->i_buffer_size );
874     /* We set to 1 to make life simpler
875      * (this way i_body_offset can never be 0) */
876     stream->i_buffer_pos = 1;
877     stream->i_buffer_last_pos = 1;
878
879     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
880                     (httpd_callback_sys_t*)stream );
881     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
882                     (httpd_callback_sys_t*)stream );
883     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
884                     (httpd_callback_sys_t*)stream );
885
886     return stream;
887 }
888
889 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
890 {
891     vlc_mutex_lock( &stream->lock );
892     if( stream->p_header )
893     {
894         free( stream->p_header );
895         stream->p_header = NULL;
896     }
897     stream->i_header = i_data;
898     if( i_data > 0 )
899     {
900         stream->p_header = malloc( i_data );
901         memcpy( stream->p_header, p_data, i_data );
902     }
903     vlc_mutex_unlock( &stream->lock );
904
905     return VLC_SUCCESS;
906 }
907
908 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
909 {
910     int i_count;
911     int i_pos;
912
913     if( i_data < 0 || p_data == NULL )
914     {
915         return VLC_SUCCESS;
916     }
917     vlc_mutex_lock( &stream->lock );
918
919     /* save this pointer (to be used by new connection) */
920     stream->i_buffer_last_pos = stream->i_buffer_pos;
921
922     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
923     i_count = i_data;
924     while( i_count > 0)
925     {
926         int i_copy;
927
928         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
929
930         /* Ok, we can't go past the end of our buffer */
931         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
932
933         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
934         i_count -= i_copy;
935         p_data  += i_copy;
936     }
937
938     stream->i_buffer_pos += i_data;
939
940     vlc_mutex_unlock( &stream->lock );
941     return VLC_SUCCESS;
942 }
943
944 void httpd_StreamDelete( httpd_stream_t *stream )
945 {
946     httpd_UrlDelete( stream->url );
947     vlc_mutex_destroy( &stream->lock );
948     if( stream->psz_mime ) free( stream->psz_mime );
949     if( stream->p_header ) free( stream->p_header );
950     if( stream->p_buffer ) free( stream->p_buffer );
951     free( stream );
952 }
953
954 /*****************************************************************************
955  * Low level
956  *****************************************************************************/
957 static void httpd_HostThread( httpd_host_t * );
958
959 /* create a new host */
960 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
961                              int i_port )
962 {
963     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
964                            );
965 }
966
967 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
968                                 int i_port,
969                                 const char *psz_cert, const char *psz_key,
970                                 const char *psz_ca, const char *psz_crl )
971 {
972     httpd_t      *httpd;
973     httpd_host_t *host;
974     tls_server_t *p_tls;
975     char *psz_host;
976     vlc_value_t  lockval;
977     int i;
978
979     if( psz_hostname == NULL )
980         psz_hostname = "";
981
982     psz_host = strdup( psz_hostname );
983     if( psz_host == NULL )
984     {
985         msg_Err( p_this, "memory error" );
986         return NULL;
987     }
988
989     /* to be sure to avoid multiple creation */
990     var_Create( p_this->p_libvlc_global, "httpd_mutex", VLC_VAR_MUTEX );
991     var_Get( p_this->p_libvlc_global, "httpd_mutex", &lockval );
992     vlc_mutex_lock( lockval.p_address );
993
994     if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
995     {
996         msg_Info( p_this, "creating httpd" );
997         if( ( httpd = vlc_object_create( p_this, VLC_OBJECT_HTTPD ) ) == NULL )
998         {
999             vlc_mutex_unlock( lockval.p_address );
1000             free( psz_host );
1001             return NULL;
1002         }
1003
1004         httpd->i_host = 0;
1005         httpd->host   = NULL;
1006
1007         vlc_object_yield( httpd );
1008         vlc_object_attach( httpd, p_this->p_libvlc );
1009     }
1010
1011     /* verify if it already exist */
1012     for( i = httpd->i_host - 1; i >= 0; i-- )
1013     {
1014         host = httpd->host[i];
1015
1016         /* cannot mix TLS and non-TLS hosts */
1017         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1018          || ( host->i_port != i_port )
1019          || strcmp( host->psz_hostname, psz_hostname ) )
1020             continue;
1021
1022         /* yep found */
1023         host->i_ref++;
1024
1025         vlc_mutex_unlock( lockval.p_address );
1026         return host;
1027     }
1028
1029     host = NULL;
1030
1031     /* determine TLS configuration */
1032     if ( psz_cert != NULL )
1033     {
1034         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1035         if ( p_tls == NULL )
1036         {
1037             msg_Err( p_this, "TLS initialization error" );
1038             goto error;
1039         }
1040
1041         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1042         {
1043             msg_Err( p_this, "TLS CA error" );
1044             goto error;
1045         }
1046
1047         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1048         {
1049             msg_Err( p_this, "TLS CRL error" );
1050             goto error;
1051         }
1052     }
1053     else
1054         p_tls = NULL;
1055
1056     /* create the new host */
1057     host = vlc_object_create( p_this, VLC_OBJECT_HTTPD_HOST );
1058     host->httpd = httpd;
1059     vlc_mutex_init( httpd, &host->lock );
1060     host->i_ref = 1;
1061
1062     host->fd = net_ListenTCP( p_this, psz_host, i_port );
1063     if( host->fd == NULL )
1064     {
1065         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1066         goto error;
1067     }
1068
1069     host->i_port = i_port;
1070     host->psz_hostname = psz_host;
1071
1072     host->i_url     = 0;
1073     host->url       = NULL;
1074     host->i_client  = 0;
1075     host->client    = NULL;
1076
1077     host->p_tls = p_tls;
1078
1079     /* create the thread */
1080     if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1081                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1082     {
1083         msg_Err( p_this, "cannot spawn http host thread" );
1084         goto error;
1085     }
1086
1087     /* now add it to httpd */
1088     TAB_APPEND( httpd->i_host, httpd->host, host );
1089     vlc_mutex_unlock( lockval.p_address );
1090
1091     return host;
1092
1093 error:
1094     free( psz_host );
1095     if( httpd->i_host <= 0 )
1096     {
1097         vlc_object_release( httpd );
1098         vlc_object_detach( httpd );
1099         vlc_object_destroy( httpd );
1100     }
1101     vlc_mutex_unlock( lockval.p_address );
1102
1103     if( host != NULL )
1104     {
1105         net_ListenClose( host->fd );
1106         vlc_mutex_destroy( &host->lock );
1107         vlc_object_destroy( host );
1108     }
1109
1110     if( p_tls != NULL )
1111         tls_ServerDelete( p_tls );
1112
1113     return NULL;
1114 }
1115
1116 /* delete a host */
1117 void httpd_HostDelete( httpd_host_t *host )
1118 {
1119     httpd_t *httpd = host->httpd;
1120     vlc_value_t lockval;
1121     int i;
1122
1123     var_Get( httpd->p_libvlc_global, "httpd_mutex", &lockval );
1124     vlc_mutex_lock( lockval.p_address );
1125
1126     host->i_ref--;
1127     if( host->i_ref > 0 )
1128     {
1129         /* still used */
1130         vlc_mutex_unlock( lockval.p_address );
1131         msg_Dbg( host, "httpd_HostDelete: host still used" );
1132         return;
1133     }
1134     TAB_REMOVE( httpd->i_host, httpd->host, host );
1135
1136     host->b_die = 1;
1137     vlc_thread_join( host );
1138
1139     msg_Dbg( host, "HTTP host removed" );
1140
1141     for( i = 0; i < host->i_url; i++ )
1142     {
1143         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1144     }
1145     for( i = 0; i < host->i_client; i++ )
1146     {
1147         httpd_client_t *cl = host->client[i];
1148         msg_Warn( host, "client still connected" );
1149         httpd_ClientClean( cl );
1150         TAB_REMOVE( host->i_client, host->client, cl );
1151         free( cl );
1152         i--;
1153         /* TODO */
1154     }
1155
1156     if( host->p_tls != NULL)
1157         tls_ServerDelete( host->p_tls );
1158
1159     net_ListenClose( host->fd );
1160     free( host->psz_hostname );
1161
1162     vlc_mutex_destroy( &host->lock );
1163     vlc_object_destroy( host );
1164
1165     vlc_object_release( httpd );
1166     if( httpd->i_host <= 0 )
1167     {
1168         msg_Dbg( httpd, "no host left, stopping httpd" );
1169         vlc_object_detach( httpd );
1170         vlc_object_destroy( httpd );
1171     }
1172     vlc_mutex_unlock( lockval.p_address );
1173 }
1174
1175 /* register a new url */
1176 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1177                                          const char *psz_user, const char *psz_password,
1178                                          const vlc_acl_t *p_acl, vlc_bool_t b_check )
1179 {
1180     httpd_url_t *url;
1181     int         i;
1182
1183     vlc_mutex_lock( &host->lock );
1184     if( b_check )
1185     {
1186         for( i = 0; i < host->i_url; i++ )
1187         {
1188             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1189             {
1190                 msg_Warn( host->httpd,
1191                           "cannot add '%s' (url already defined)", psz_url );
1192                 vlc_mutex_unlock( &host->lock );
1193                 return NULL;
1194             }
1195         }
1196     }
1197
1198     url = malloc( sizeof( httpd_url_t ) );
1199     url->host = host;
1200
1201     vlc_mutex_init( host->httpd, &url->lock );
1202     url->psz_url = strdup( psz_url );
1203     url->psz_user = strdup( psz_user ? psz_user : "" );
1204     url->psz_password = strdup( psz_password ? psz_password : "" );
1205     url->p_acl = ACL_Duplicate( host, p_acl );
1206     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1207     {
1208         url->catch[i].cb = NULL;
1209         url->catch[i].p_sys = NULL;
1210     }
1211
1212     TAB_APPEND( host->i_url, host->url, url );
1213     vlc_mutex_unlock( &host->lock );
1214
1215     return url;
1216 }
1217
1218 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1219                            const char *psz_user, const char *psz_password,
1220                            const vlc_acl_t *p_acl )
1221 {
1222     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1223                                 psz_password, p_acl, VLC_FALSE );
1224 }
1225
1226 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1227                                  const char *psz_user, const char *psz_password,
1228                                  const vlc_acl_t *p_acl )
1229 {
1230     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1231                                 psz_password, p_acl, VLC_TRUE );
1232 }
1233
1234 /* register callback on a url */
1235 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1236                     httpd_callback_sys_t *p_sys )
1237 {
1238     vlc_mutex_lock( &url->lock );
1239     url->catch[i_msg].cb   = cb;
1240     url->catch[i_msg].p_sys= p_sys;
1241     vlc_mutex_unlock( &url->lock );
1242
1243     return VLC_SUCCESS;
1244 }
1245
1246 /* delete an url */
1247 void httpd_UrlDelete( httpd_url_t *url )
1248 {
1249     httpd_host_t *host = url->host;
1250     int          i;
1251
1252     vlc_mutex_lock( &host->lock );
1253     TAB_REMOVE( host->i_url, host->url, url );
1254
1255     vlc_mutex_destroy( &url->lock );
1256     free( url->psz_url );
1257     free( url->psz_user );
1258     free( url->psz_password );
1259     ACL_Destroy( url->p_acl );
1260
1261     for( i = 0; i < host->i_client; i++ )
1262     {
1263         httpd_client_t *client = host->client[i];
1264
1265         if( client->url == url )
1266         {
1267             /* TODO complete it */
1268             msg_Warn( host, "force closing connections" );
1269             httpd_ClientClean( client );
1270             TAB_REMOVE( host->i_client, host->client, client );
1271             free( client );
1272             i--;
1273         }
1274     }
1275     free( url );
1276     vlc_mutex_unlock( &host->lock );
1277 }
1278
1279 void httpd_MsgInit( httpd_message_t *msg )
1280 {
1281     msg->cl         = NULL;
1282     msg->i_type     = HTTPD_MSG_NONE;
1283     msg->i_proto    = HTTPD_PROTO_NONE;
1284     msg->i_version  = -1;
1285
1286     msg->i_status   = 0;
1287     msg->psz_status = NULL;
1288
1289     msg->psz_url    = NULL;
1290     msg->psz_args   = NULL;
1291
1292     msg->i_channel  = -1;
1293
1294     msg->i_name     = 0;
1295     msg->name       = NULL;
1296     msg->i_value    = 0;
1297     msg->value      = NULL;
1298
1299     msg->i_body_offset = 0;
1300     msg->i_body        = 0;
1301     msg->p_body        = 0;
1302 }
1303
1304 void httpd_MsgClean( httpd_message_t *msg )
1305 {
1306     int i;
1307
1308     if( msg->psz_status )
1309     {
1310         free( msg->psz_status );
1311     }
1312     if( msg->psz_url )
1313     {
1314         free( msg->psz_url );
1315     }
1316     if( msg->psz_args )
1317     {
1318         free( msg->psz_args );
1319     }
1320     for( i = 0; i < msg->i_name; i++ )
1321     {
1322         free( msg->name[i] );
1323         free( msg->value[i] );
1324     }
1325     if( msg->name )
1326     {
1327         free( msg->name );
1328     }
1329     if( msg->value )
1330     {
1331         free( msg->value );
1332     }
1333     if( msg->p_body )
1334     {
1335         free( msg->p_body );
1336     }
1337     httpd_MsgInit( msg );
1338 }
1339
1340 const char *httpd_MsgGet( httpd_message_t *msg, const char *name )
1341 {
1342     int i;
1343
1344     for( i = 0; i < msg->i_name; i++ )
1345     {
1346         if( !strcasecmp( msg->name[i], name ))
1347         {
1348             return msg->value[i];
1349         }
1350     }
1351     return NULL;
1352 }
1353
1354 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1355 {
1356     va_list args;
1357     char *value = NULL;
1358
1359     va_start( args, psz_value );
1360 #if defined(HAVE_VASPRINTF) && !defined(__APPLE__) && !defined(SYS_BEOS)
1361     vasprintf( &value, psz_value, args );
1362 #else
1363     {
1364         int i_size = strlen( psz_value ) + 4096;    /* FIXME stupid system */
1365         value = calloc( i_size, sizeof( char ) );
1366         vsnprintf( value, i_size, psz_value, args );
1367         value[i_size - 1] = 0;
1368     }
1369 #endif
1370     va_end( args );
1371
1372     name = strdup( name );
1373
1374     TAB_APPEND( msg->i_name,  msg->name,  name );
1375     TAB_APPEND( msg->i_value, msg->value, value );
1376 }
1377
1378 static void httpd_ClientInit( httpd_client_t *cl )
1379 {
1380     cl->i_state = HTTPD_CLIENT_RECEIVING;
1381     cl->i_activity_date = mdate();
1382     cl->i_activity_timeout = I64C(10000000);
1383     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1384     cl->i_buffer = 0;
1385     cl->p_buffer = malloc( cl->i_buffer_size );
1386     cl->i_mode   = HTTPD_CLIENT_FILE;
1387     cl->b_read_waiting = VLC_FALSE;
1388
1389     httpd_MsgInit( &cl->query );
1390     httpd_MsgInit( &cl->answer );
1391 }
1392
1393 void httpd_ClientModeStream( httpd_client_t *cl )
1394 {
1395     cl->i_mode   = HTTPD_CLIENT_STREAM;
1396 }
1397
1398 void httpd_ClientModeBidir( httpd_client_t *cl )
1399 {
1400     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1401 }
1402
1403 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1404 {
1405     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1406 }
1407
1408 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1409 {
1410     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1411 }
1412
1413 static void httpd_ClientClean( httpd_client_t *cl )
1414 {
1415     if( cl->fd >= 0 )
1416     {
1417         if( cl->p_tls != NULL )
1418             tls_ServerSessionClose( cl->p_tls );
1419         net_Close( cl->fd );
1420         cl->fd = -1;
1421     }
1422
1423     httpd_MsgClean( &cl->answer );
1424     httpd_MsgClean( &cl->query );
1425
1426     if( cl->p_buffer )
1427     {
1428         free( cl->p_buffer );
1429         cl->p_buffer = NULL;
1430     }
1431 }
1432
1433 static httpd_client_t *httpd_ClientNew( int fd, struct sockaddr_storage *sock,
1434                                         int i_sock_size,
1435                                         tls_session_t *p_tls )
1436 {
1437     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1438
1439     if( !cl ) return NULL;
1440
1441     cl->i_ref   = 0;
1442     cl->fd      = fd;
1443     memcpy( &cl->sock, sock, sizeof( cl->sock ) );
1444     cl->i_sock_size = i_sock_size;
1445     cl->url     = NULL;
1446     cl->p_tls = p_tls;
1447
1448     httpd_ClientInit( cl );
1449
1450     return cl;
1451 }
1452
1453 static int httpd_NetRecv( httpd_client_t *cl, uint8_t *p, int i_len )
1454 {
1455     tls_session_t *p_tls;
1456
1457     p_tls = cl->p_tls;
1458     if( p_tls != NULL)
1459         return tls_Recv( p_tls, p, i_len );
1460
1461     return recv( cl->fd, p, i_len, 0 );
1462 }
1463
1464 static int httpd_NetSend( httpd_client_t *cl, const uint8_t *p, int i_len )
1465 {
1466     tls_session_t *p_tls;
1467
1468     p_tls = cl->p_tls;
1469     if( p_tls != NULL)
1470         return tls_Send( p_tls, p, i_len );
1471
1472     return send( cl->fd, p, i_len, 0 );
1473 }
1474
1475 static void httpd_ClientRecv( httpd_client_t *cl )
1476 {
1477     int i_len;
1478
1479     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1480     {
1481         /* enough to see if it's rtp over rtsp or RTSP/HTTP */
1482         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1483                                4 - cl->i_buffer );
1484         if( i_len > 0 )
1485         {
1486             cl->i_buffer += i_len;
1487         }
1488
1489         if( cl->i_buffer >= 4 )
1490         {
1491             /*fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );*/
1492             /* detect type */
1493             if( cl->p_buffer[0] == '$' )
1494             {
1495                 /* RTSP (rtp over rtsp) */
1496                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1497                 cl->query.i_type  = HTTPD_MSG_CHANNEL;
1498                 cl->query.i_channel = cl->p_buffer[1];
1499                 cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1500                 cl->query.p_body  = malloc( cl->query.i_body );
1501
1502                 cl->i_buffer      = 0;
1503             }
1504             else if( !memcmp( cl->p_buffer, "HTTP", 4 ) )
1505             {
1506                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1507                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1508             }
1509             else if( !memcmp( cl->p_buffer, "RTSP", 4 ) )
1510             {
1511                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1512                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1513             }
1514             else if( !memcmp( cl->p_buffer, "GET ", 4 ) ||
1515                      !memcmp( cl->p_buffer, "HEAD", 4 ) ||
1516                      !memcmp( cl->p_buffer, "POST", 4 ) )
1517             {
1518                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1519                 cl->query.i_type  = HTTPD_MSG_NONE;
1520             }
1521             else
1522             {
1523                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1524                 cl->query.i_type  = HTTPD_MSG_NONE;
1525             }
1526         }
1527     }
1528     else if( cl->query.i_body > 0 )
1529     {
1530         /* we are reading the body of a request or a channel */
1531         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1532                                cl->query.i_body - cl->i_buffer );
1533         if( i_len > 0 )
1534         {
1535             cl->i_buffer += i_len;
1536         }
1537         if( cl->i_buffer >= cl->query.i_body )
1538         {
1539             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1540         }
1541     }
1542     else
1543     {
1544         /* we are reading a header -> char by char */
1545         for( ;; )
1546         {
1547             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1548             if( i_len <= 0 )
1549             {
1550                 break;
1551             }
1552             cl->i_buffer++;
1553
1554             if( cl->i_buffer + 1 >= cl->i_buffer_size )
1555             {
1556                 cl->i_buffer_size += 1024;
1557                 cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
1558             }
1559             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1560                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1561             {
1562                 char *p;
1563
1564                 /* we have finished the header so parse it and set i_body */
1565                 cl->p_buffer[cl->i_buffer] = '\0';
1566
1567                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1568                 {
1569                     /* FIXME:
1570                      * assume strlen( "HTTP/1.x" ) = 8
1571                      */
1572                     cl->query.i_status =
1573                         strtol( (char *)&cl->p_buffer[8],
1574                                 &p, 0 );
1575                     while( *p == ' ' )
1576                     {
1577                         p++;
1578                     }
1579                     cl->query.psz_status = strdup( p );
1580                 }
1581                 else
1582                 {
1583                     static const struct
1584                     {
1585                         const char *name;
1586                         int  i_type;
1587                         int  i_proto;
1588                     }
1589                     msg_type[] =
1590                     {
1591                         { "OPTIONS",        HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1592                         { "DESCRIBE",       HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1593                         { "SETUP",          HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1594                         { "PLAY",           HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1595                         { "PAUSE",          HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1596                         { "GET_PARAMETER",  HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1597                         { "TEARDOWN",       HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1598
1599                         { "GET",            HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1600                         { "HEAD",           HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1601                         { "POST",           HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1602
1603                         { NULL,             HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1604                     };
1605                     int  i;
1606
1607                     p = NULL;
1608                     cl->query.i_type = HTTPD_MSG_NONE;
1609
1610                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1611
1612                     for( i = 0; msg_type[i].name != NULL; i++ )
1613                     {
1614                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1615                                       strlen( msg_type[i].name ) ) )
1616                         {
1617                             p = (char *)&cl->p_buffer[strlen((char *)msg_type[i].name) + 1 ];
1618                             cl->query.i_type = msg_type[i].i_type;
1619                             if( cl->query.i_proto != msg_type[i].i_proto )
1620                             {
1621                                 p = NULL;
1622                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1623                                 cl->query.i_type = HTTPD_MSG_NONE;
1624                             }
1625                             break;
1626                         }
1627                     }
1628                     if( p == NULL )
1629                     {
1630                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1631                         {
1632                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1633                         }
1634                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1635                         {
1636                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1637                         }
1638                     }
1639                     else
1640                     {
1641                         char *p2;
1642                         char *p3;
1643
1644                         while( *p == ' ' )
1645                         {
1646                             p++;
1647                         }
1648                         p2 = strchr( p, ' ' );
1649                         if( p2 )
1650                         {
1651                             *p2++ = '\0';
1652                         }
1653                         if( !strncasecmp( p, "rtsp:", 5 ) )
1654                         {
1655                             /* for rtsp url, you have rtsp://localhost:port/path */
1656                             p += 5;
1657                             while( *p == '/' ) p++;
1658                             while( *p && *p != '/' ) p++;
1659                         }
1660                         cl->query.psz_url = strdup( p );
1661                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1662                         {
1663                             *p3++ = '\0';
1664                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1665                         }
1666                         if( p2 )
1667                         {
1668                             while( *p2 == ' ' )
1669                             {
1670                                 p2++;
1671                             }
1672                             if( !strncasecmp( p2, "HTTP/1.", 7 ) )
1673                             {
1674                                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1675                                 cl->query.i_version = atoi( p2+7 );
1676                             }
1677                             else if( !strncasecmp( p2, "RTSP/1.", 7 ) )
1678                             {
1679                                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1680                                 cl->query.i_version = atoi( p2+7 );
1681                             }
1682                         }
1683                         p = p2;
1684                     }
1685                 }
1686                 if( p )
1687                 {
1688                     p = strchr( p, '\n' );
1689                 }
1690                 if( p )
1691                 {
1692                     while( *p == '\n' || *p == '\r' )
1693                     {
1694                         p++;
1695                     }
1696                     while( p && *p != '\0' )
1697                     {
1698                         char *line = p;
1699                         char *eol = p = strchr( p, '\n' );
1700                         char *colon;
1701
1702                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1703                         {
1704                             *eol-- = '\0';
1705                         }
1706
1707                         if( ( colon = strchr( line, ':' ) ) )
1708                         {
1709                             char *name;
1710                             char *value;
1711
1712                             *colon++ = '\0';
1713                             while( *colon == ' ' )
1714                             {
1715                                 colon++;
1716                             }
1717                             name = strdup( line );
1718                             value = strdup( colon );
1719
1720                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1721                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1722
1723                             if( !strcasecmp( name, "Content-Length" ) )
1724                             {
1725                                 cl->query.i_body = atol( value );
1726                             }
1727                         }
1728
1729                         if( p )
1730                         {
1731                             p++;
1732                             while( *p == '\n' || *p == '\r' )
1733                             {
1734                                 p++;
1735                             }
1736                         }
1737                     }
1738                 }
1739                 if( cl->query.i_body > 0 )
1740                 {
1741                     /* TODO Mhh, handle the case client will only send a request and close the connection
1742                      * to mark and of body (probably only RTSP) */
1743                     cl->query.p_body = malloc( cl->query.i_body );
1744                     cl->i_buffer = 0;
1745                 }
1746                 else
1747                 {
1748                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1749                 }
1750             }
1751         }
1752     }
1753
1754     /* check if the client is to be set to dead */
1755 #if defined( WIN32 ) || defined( UNDER_CE )
1756     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1757 #else
1758     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1759 #endif
1760     {
1761         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1762         {
1763             /* connection closed -> end of data */
1764             if( cl->query.i_body > 0 )
1765             {
1766                 cl->query.i_body = cl->i_buffer;
1767             }
1768             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1769         }
1770         else
1771         {
1772             cl->i_state = HTTPD_CLIENT_DEAD;
1773         }
1774     }
1775     cl->i_activity_date = mdate();
1776
1777     /* XXX: for QT I have to disable timeout. Try to find why */
1778     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1779         cl->i_activity_timeout = 0;
1780
1781 #if 0 /* Debugging only */
1782     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1783     {
1784         int i;
1785
1786         fprintf( stderr, "received new request\n" );
1787         fprintf( stderr, "  - proto=%s\n",
1788                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1789         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1790         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1791         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1792         {
1793             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1794                      cl->query.psz_status );
1795         }
1796         else if( cl->query.i_type != HTTPD_MSG_NONE )
1797         {
1798             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1799         }
1800         for( i = 0; i < cl->query.i_name; i++ )
1801         {
1802             fprintf( stderr, "  - option name='%s' value='%s'\n",
1803                      cl->query.name[i], cl->query.value[i] );
1804         }
1805     }
1806 #endif
1807 }
1808
1809 static void httpd_ClientSend( httpd_client_t *cl )
1810 {
1811     int i;
1812     int i_len;
1813
1814     if( cl->i_buffer < 0 )
1815     {
1816         /* We need to create the header */
1817         int i_size = 0;
1818         char *p;
1819
1820         i_size = strlen( "HTTP/1.") + 10 + 10 +
1821                  strlen( cl->answer.psz_status ? cl->answer.psz_status : "" ) + 5;
1822         for( i = 0; i < cl->answer.i_name; i++ )
1823         {
1824             i_size += strlen( cl->answer.name[i] ) + 2 +
1825                       strlen( cl->answer.value[i] ) + 2;
1826         }
1827
1828         if( cl->i_buffer_size < i_size )
1829         {
1830             cl->i_buffer_size = i_size;
1831             free( cl->p_buffer );
1832             cl->p_buffer = malloc( i_size );
1833         }
1834         p = (char *)cl->p_buffer;
1835
1836         p += sprintf( p, "%s/1.%d %d %s\r\n",
1837                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP" : "RTSP",
1838                       cl->answer.i_version,
1839                       cl->answer.i_status, cl->answer.psz_status );
1840         for( i = 0; i < cl->answer.i_name; i++ )
1841         {
1842             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1843                           cl->answer.value[i] );
1844         }
1845         p += sprintf( p, "\r\n" );
1846
1847         cl->i_buffer = 0;
1848         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1849
1850         /*fprintf( stderr, "sending answer\n" );
1851         fprintf( stderr, "%s",  cl->p_buffer );*/
1852     }
1853
1854     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1855                            cl->i_buffer_size - cl->i_buffer );
1856     if( i_len >= 0 )
1857     {
1858         cl->i_activity_date = mdate();
1859         cl->i_buffer += i_len;
1860
1861         if( cl->i_buffer >= cl->i_buffer_size )
1862         {
1863             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1864                 !cl->b_read_waiting )
1865             {
1866                 /* catch more body data */
1867                 int     i_msg = cl->query.i_type;
1868                 int64_t i_offset = cl->answer.i_body_offset;
1869
1870                 httpd_MsgClean( &cl->answer );
1871                 cl->answer.i_body_offset = i_offset;
1872
1873                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1874                                           &cl->answer, &cl->query );
1875             }
1876
1877             if( cl->answer.i_body > 0 )
1878             {
1879                 /* send the body data */
1880                 free( cl->p_buffer );
1881                 cl->p_buffer = cl->answer.p_body;
1882                 cl->i_buffer_size = cl->answer.i_body;
1883                 cl->i_buffer = 0;
1884
1885                 cl->answer.i_body = 0;
1886                 cl->answer.p_body = NULL;
1887             }
1888             else
1889             {
1890                 /* send finished */
1891                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1892             }
1893         }
1894     }
1895     else
1896     {
1897 #if defined( WIN32 ) || defined( UNDER_CE )
1898         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1899 #else
1900         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1901 #endif
1902         {
1903             /* error */
1904             cl->i_state = HTTPD_CLIENT_DEAD;
1905         }
1906     }
1907 }
1908
1909 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1910 {
1911     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1912     {
1913         case 0:
1914             cl->i_state = HTTPD_CLIENT_RECEIVING;
1915             break;
1916
1917         case -1:
1918             cl->i_state = HTTPD_CLIENT_DEAD;
1919             cl->p_tls = NULL;
1920             break;
1921
1922         case 2:
1923             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1924     }
1925 }
1926
1927 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1928 {
1929     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1930     {
1931         case 0:
1932             cl->i_state = HTTPD_CLIENT_RECEIVING;
1933             break;
1934
1935         case -1:
1936             cl->i_state = HTTPD_CLIENT_DEAD;
1937             cl->p_tls = NULL;
1938             break;
1939
1940         case 1:
1941             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
1942             break;
1943     }
1944 }
1945
1946 static void httpd_HostThread( httpd_host_t *host )
1947 {
1948     tls_session_t *p_tls = NULL;
1949
1950     host->p_total_counter = stats_CounterCreate( host,
1951                                           VLC_VAR_INTEGER, STATS_COUNTER );
1952     host->p_active_counter = stats_CounterCreate( host,
1953                                           VLC_VAR_INTEGER, STATS_COUNTER );
1954
1955     while( !host->b_die )
1956     {
1957         struct timeval  timeout;
1958         fd_set          fds_read;
1959         fd_set          fds_write;
1960         /* FIXME: (too) many int variables */
1961         int             fd, i_fd;
1962         int             i_handle_max = 0;
1963         int             i_ret;
1964         int             i_client;
1965         int             b_low_delay = 0;
1966
1967         if( host->i_url <= 0 )
1968         {
1969             /* 0.2s */
1970             msleep( 200000 );
1971             continue;
1972         }
1973
1974         /* built a set of handle to select */
1975         FD_ZERO( &fds_read );
1976         FD_ZERO( &fds_write );
1977
1978         i_handle_max = -1;
1979
1980         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
1981         {
1982             FD_SET( fd, &fds_read );
1983             if( fd > i_handle_max )
1984                 i_handle_max = fd;
1985         }
1986
1987         /* prepare a new TLS session */
1988         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
1989             p_tls = tls_ServerSessionPrepare( host->p_tls );
1990
1991         /* add all socket that should be read/write and close dead connection */
1992         vlc_mutex_lock( &host->lock );
1993         for( i_client = 0; i_client < host->i_client; i_client++ )
1994         {
1995             httpd_client_t *cl = host->client[i_client];
1996
1997             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1998                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1999                   ( cl->i_activity_timeout > 0 &&
2000                     cl->i_activity_date+cl->i_activity_timeout < mdate()) ) ) )
2001             {
2002                 httpd_ClientClean( cl );
2003                 stats_UpdateInteger( host, host->p_active_counter, -1, NULL );
2004                 TAB_REMOVE( host->i_client, host->client, cl );
2005                 free( cl );
2006                 i_client--;
2007                 continue;
2008             }
2009             else if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2010                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2011             {
2012                 FD_SET( cl->fd, &fds_read );
2013                 i_handle_max = __MAX( i_handle_max, cl->fd );
2014             }
2015             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2016                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2017             {
2018                 FD_SET( cl->fd, &fds_write );
2019                 i_handle_max = __MAX( i_handle_max, cl->fd );
2020             }
2021             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2022             {
2023                 httpd_message_t *answer = &cl->answer;
2024                 httpd_message_t *query  = &cl->query;
2025                 int i_msg = query->i_type;
2026
2027                 httpd_MsgInit( answer );
2028
2029                 /* Handle what we received */
2030                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2031                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2032                 {
2033                     /* we can only receive request from client when not
2034                      * in BIDIR mode */
2035                     cl->url     = NULL;
2036                     cl->i_state = HTTPD_CLIENT_DEAD;
2037                 }
2038                 else if( i_msg == HTTPD_MSG_ANSWER )
2039                 {
2040                     /* We are in BIDIR mode, trigger the callback and then
2041                      * check for new data */
2042                     if( cl->url && cl->url->catch[i_msg].cb )
2043                     {
2044                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2045                                                   cl, NULL, query );
2046                     }
2047                     cl->i_state = HTTPD_CLIENT_WAITING;
2048                 }
2049                 else if( i_msg == HTTPD_MSG_CHANNEL )
2050                 {
2051                     /* We are in BIDIR mode, trigger the callback and then
2052                      * check for new data */
2053                     if( cl->url && cl->url->catch[i_msg].cb )
2054                     {
2055                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2056                                                   cl, NULL, query );
2057                     }
2058                     cl->i_state = HTTPD_CLIENT_WAITING;
2059                 }
2060                 else if( i_msg == HTTPD_MSG_OPTIONS )
2061                 {
2062                     const char *psz_cseq;
2063                     int i_cseq;
2064
2065                     /* unimplemented */
2066                     answer->i_proto  = query->i_proto ;
2067                     answer->i_type   = HTTPD_MSG_ANSWER;
2068                     answer->i_version= 0;
2069                     answer->i_status = 200;
2070                     answer->psz_status = strdup( "Ok" );
2071
2072                     answer->i_body = 0;
2073                     answer->p_body = NULL;
2074
2075                     psz_cseq = httpd_MsgGet( query, "Cseq" );
2076                     if( psz_cseq )
2077                         i_cseq = atoi( psz_cseq );
2078                     else
2079                         i_cseq = 0;
2080                     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
2081                     httpd_MsgAdd( answer, "Server", "VLC Server" );
2082                     httpd_MsgAdd( answer, "Public", "DESCRIBE, SETUP, "
2083                                  "TEARDOWN, PLAY, PAUSE" );
2084                     httpd_MsgAdd( answer, "Content-Length", "%d",
2085                                   answer->i_body );
2086
2087                     cl->i_buffer = -1;  /* Force the creation of the answer in
2088                                          * httpd_ClientSend */
2089                     cl->i_state = HTTPD_CLIENT_SENDING;
2090                 }
2091                 else if( i_msg == HTTPD_MSG_NONE )
2092                 {
2093                     if( query->i_proto == HTTPD_PROTO_NONE )
2094                     {
2095                         cl->url = NULL;
2096                         cl->i_state = HTTPD_CLIENT_DEAD;
2097                     }
2098                     else
2099                     {
2100                         uint8_t *p;
2101
2102                         /* unimplemented */
2103                         answer->i_proto  = query->i_proto ;
2104                         answer->i_type   = HTTPD_MSG_ANSWER;
2105                         answer->i_version= 0;
2106                         answer->i_status = 501;
2107                         answer->psz_status = strdup( "Unimplemented" );
2108
2109                         p = answer->p_body = malloc( 1000 );
2110
2111                         p += sprintf( (char *)p,
2112                             "<?xml version=\"1.0\" encoding=\"ascii\" ?>"
2113                             "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
2114                             "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
2115                             "<html>\n"
2116                             "<head>\n"
2117                             "<title>Error 501</title>\n"
2118                             "</head>\n"
2119                             "<body>\n"
2120                             "<h1>501 Unimplemented</h1>\n"
2121                             "<hr />\n"
2122                             "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
2123                             "</body>\n"
2124                             "</html>\n" );
2125
2126                         answer->i_body = p - answer->p_body;
2127                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2128
2129                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2130                         cl->i_state = HTTPD_CLIENT_SENDING;
2131                     }
2132                 }
2133                 else
2134                 {
2135                     vlc_bool_t b_auth_failed = VLC_FALSE;
2136                     vlc_bool_t b_hosts_failed = VLC_FALSE;
2137                     int i;
2138
2139                     /* Search the url and trigger callbacks */
2140                     for( i = 0; i < host->i_url; i++ )
2141                     {
2142                         httpd_url_t *url = host->url[i];
2143
2144                         if( !strcmp( url->psz_url, query->psz_url ) )
2145                         {
2146                             if( url->catch[i_msg].cb )
2147                             {
2148                                 if( answer && ( url->p_acl != NULL ) )
2149                                 {
2150                                     char ip[NI_MAXNUMERICHOST];
2151
2152                                     if( httpd_ClientIP( cl, ip ) != NULL )
2153                                     {
2154                                         if( ACL_Check( url->p_acl, ip ) )
2155                                         {
2156                                             b_hosts_failed = VLC_TRUE;
2157                                             break;
2158                                         }
2159                                     }
2160                                     else
2161                                         b_hosts_failed = VLC_TRUE;
2162                                 }
2163
2164                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2165                                 {
2166                                     /* create the headers */
2167                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2168                                     char *auth;
2169                                     char *id;
2170
2171                                     asprintf( &id, "%s:%s", url->psz_user, url->psz_password );
2172                                     if( b64 != NULL
2173                                          && !strncasecmp( b64, "BASIC", 5 ) )
2174                                     {
2175                                         b64 += 5;
2176                                         while( *b64 == ' ' )
2177                                         {
2178                                             b64++;
2179                                         }
2180                                         auth = malloc( strlen(b64) + 1 );
2181                                         b64_decode( auth, b64 );
2182                                     }
2183                                     else
2184                                     {
2185                                         auth = strdup( "" );
2186                                     }
2187
2188                                     if( strcmp( id, auth ) )
2189                                     {
2190                                         httpd_MsgAdd( answer, "WWW-Authenticate", "Basic realm=\"%s\"", url->psz_user );
2191                                         /* We fail for all url */
2192                                         b_auth_failed = VLC_TRUE;
2193                                         free( id );
2194                                         free( auth );
2195                                         break;
2196                                     }
2197
2198                                     free( id );
2199                                     free( auth );
2200                                 }
2201
2202                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2203                                 {
2204                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2205                                     {
2206                                         /* Raw answer from a CGI */
2207                                         cl->i_buffer = cl->i_buffer_size;
2208                                     }
2209                                     else
2210                                         cl->i_buffer = -1;
2211
2212                                     /* only one url can answer */
2213                                     answer = NULL;
2214                                     if( cl->url == NULL )
2215                                     {
2216                                         cl->url = url;
2217                                     }
2218                                 }
2219                             }
2220                         }
2221                     }
2222
2223                     if( answer )
2224                     {
2225                         uint8_t *p;
2226
2227                         answer->i_proto  = query->i_proto;
2228                         answer->i_type   = HTTPD_MSG_ANSWER;
2229                         answer->i_version= 0;
2230                         p = answer->p_body = malloc( 1000 + strlen(query->psz_url) );
2231
2232                         if( b_hosts_failed )
2233                         {
2234                             answer->i_status = 403;
2235                             answer->psz_status = strdup( "Forbidden" );
2236
2237                             /* FIXME: lots of code duplication */
2238                             p += sprintf( (char *)p,
2239                                 "<?xml version=\"1.0\" encoding=\"us-ascii\" ?>"
2240                                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
2241                                 "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
2242                                 "<html>\n"
2243                                 "<head>\n"
2244                                 "<title>Error 403</title>\n"
2245                                 "</head>\n"
2246                                 "<body>\n"
2247                                 "<h1>403 Forbidden (%s)</h1>\n"
2248                                 "<hr />\n"
2249                                 "<p><a href=\"http://www.videolan.org\">VideoLAN</a></p>\n"
2250                                 "</body>\n"
2251                                 "</html>\n", query->psz_url );
2252                         }
2253                         else if( b_auth_failed )
2254                         {
2255                             answer->i_status = 401;
2256                             answer->psz_status = strdup( "Authorization Required" );
2257
2258                             p += sprintf( (char *)p,
2259                                 "<?xml version=\"1.0\" encoding=\"us-ascii\" ?>"
2260                                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
2261                                 "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
2262                                 "<html>\n"
2263                                 "<head>\n"
2264                                 "<title>Error 401</title>\n"
2265                                 "</head>\n"
2266                                 "<body>\n"
2267                                 "<h1>401 Authorization Required (%s)</h1>\n"
2268                                 "<hr />\n"
2269                                 "<p><a href=\"http://www.videolan.org\">VideoLAN</a></p>\n"
2270                                 "</body>\n"
2271                                 "</html>\n", query->psz_url );
2272                         }
2273                         else
2274                         {
2275                             /* no url registered */
2276                             answer->i_status = 404;
2277                             answer->psz_status = strdup( "Not found" );
2278
2279                             p += sprintf( (char *)p,
2280                                 "<?xml version=\"1.0\" encoding=\"us-ascii\" ?>"
2281                                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
2282                                 "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
2283                                 "<html>\n"
2284                                 "<head>\n"
2285                                 "<title>Error 404</title>\n"
2286                                 "</head>\n"
2287                                 "<body>\n"
2288                                 "<h1>404 Resource not found(%s)</h1>\n"
2289                                 "<hr />\n"
2290                                 "<p><a href=\"http://www.videolan.org\"> VideoLAN</a></p>\n"
2291                                 "</body>\n"
2292                                 "</html>\n", query->psz_url );
2293                         }
2294
2295                         answer->i_body = p - answer->p_body;
2296                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2297                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2298                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2299                     }
2300
2301                     cl->i_state = HTTPD_CLIENT_SENDING;
2302                 }
2303             }
2304             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2305             {
2306                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2307                 {
2308                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2309                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2310                     vlc_bool_t b_connection = VLC_FALSE;
2311                     vlc_bool_t b_keepalive = VLC_FALSE;
2312                     vlc_bool_t b_query = VLC_FALSE;
2313
2314                     cl->url = NULL;
2315                     if( psz_connection )
2316                     {
2317                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2318                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2319                     }
2320
2321                     if( psz_query )
2322                     {
2323                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2324                     }
2325
2326                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2327                           ( ( cl->answer.i_version == 0 && b_keepalive ) ||
2328                             ( cl->answer.i_version == 1 && !b_connection ) ) ) ||
2329                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2330                           !b_query && !b_connection ) )
2331                     {
2332                         httpd_MsgClean( &cl->query );
2333                         httpd_MsgInit( &cl->query );
2334
2335                         cl->i_buffer = 0;
2336                         cl->i_buffer_size = 1000;
2337                         free( cl->p_buffer );
2338                         cl->p_buffer = malloc( cl->i_buffer_size );
2339                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2340                     }
2341                     else
2342                     {
2343                         cl->i_state = HTTPD_CLIENT_DEAD;
2344                     }
2345                     httpd_MsgClean( &cl->answer );
2346                 }
2347                 else if( cl->b_read_waiting )
2348                 {
2349                     /* we have a message waiting for us to read it */
2350                     httpd_MsgClean( &cl->answer );
2351                     httpd_MsgClean( &cl->query );
2352
2353                     cl->i_buffer = 0;
2354                     cl->i_buffer_size = 1000;
2355                     free( cl->p_buffer );
2356                     cl->p_buffer = malloc( cl->i_buffer_size );
2357                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2358                     cl->b_read_waiting = VLC_FALSE;
2359                 }
2360                 else
2361                 {
2362                     int64_t i_offset = cl->answer.i_body_offset;
2363                     httpd_MsgClean( &cl->answer );
2364
2365                     cl->answer.i_body_offset = i_offset;
2366                     free( cl->p_buffer );
2367                     cl->p_buffer = NULL;
2368                     cl->i_buffer = 0;
2369                     cl->i_buffer_size = 0;
2370
2371                     cl->i_state = HTTPD_CLIENT_WAITING;
2372                 }
2373             }
2374             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2375             {
2376                 int64_t i_offset = cl->answer.i_body_offset;
2377                 int     i_msg = cl->query.i_type;
2378
2379                 httpd_MsgInit( &cl->answer );
2380                 cl->answer.i_body_offset = i_offset;
2381
2382                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2383                                           &cl->answer, &cl->query );
2384                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2385                 {
2386                     /* we have new data, so reenter send mode */
2387                     cl->i_buffer      = 0;
2388                     cl->p_buffer      = cl->answer.p_body;
2389                     cl->i_buffer_size = cl->answer.i_body;
2390                     cl->answer.p_body = NULL;
2391                     cl->answer.i_body = 0;
2392                     cl->i_state = HTTPD_CLIENT_SENDING;
2393                 }
2394                 else
2395                 {
2396                     /* we shouldn't wait too long */
2397                     b_low_delay = VLC_TRUE;
2398                 }
2399             }
2400
2401             /* Special for BIDIR mode we also check reading */
2402             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2403                 cl->i_state == HTTPD_CLIENT_SENDING )
2404             {
2405                 FD_SET( cl->fd, &fds_read );
2406                 i_handle_max = __MAX( i_handle_max, cl->fd );
2407             }
2408         }
2409         vlc_mutex_unlock( &host->lock );
2410
2411         /* we will wait 100ms or 20ms (not too big 'cause HTTPD_CLIENT_WAITING) */
2412         timeout.tv_sec = 0;
2413         timeout.tv_usec = b_low_delay ? 20000 : 100000;
2414
2415         i_ret = select( i_handle_max + 1,
2416                         &fds_read, &fds_write, NULL, &timeout );
2417
2418         if( (i_ret == -1) && (errno != EINTR) )
2419         {
2420             msg_Warn( host, "select error: %s", net_strerror( net_errno ) );
2421             msleep( 1000 );
2422             continue;
2423         }
2424         else if( i_ret <= 0 )
2425         {
2426             continue;
2427         }
2428
2429         /* accept new connections */
2430         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
2431         {
2432             if( FD_ISSET( fd, &fds_read ) )
2433             {
2434                 socklen_t i_sock_size = sizeof( struct sockaddr_storage );
2435                 struct  sockaddr_storage sock;
2436
2437                 fd = accept( fd, (struct sockaddr *)&sock, &i_sock_size );
2438
2439                 if( fd >= 0 )
2440                 {
2441                     int i_state = 1;
2442
2443                     setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, &i_state, sizeof (i_state));
2444                     i_state = 0;
2445
2446                     /* set this new socket non-block */
2447 #if defined( WIN32 ) || defined( UNDER_CE )
2448                     {
2449                         unsigned long i_dummy = 1;
2450                         ioctlsocket( fd, FIONBIO, &i_dummy );
2451                     }
2452 #else
2453                     fcntl( fd, F_SETFD, FD_CLOEXEC );
2454                     {
2455                         int i_val = fcntl( fd, F_GETFL );
2456                         fcntl( fd, F_SETFL,
2457                                O_NONBLOCK | ((i_val != -1) ? i_val : 0) );
2458                     }
2459
2460                     if( fd >= FD_SETSIZE )
2461                     {
2462                         net_Close( fd );
2463                         fd = -1;
2464                     }
2465                     else
2466 #endif
2467                     if( p_tls != NULL)
2468                     {
2469                         switch ( tls_ServerSessionHandshake( p_tls, fd ) )
2470                         {
2471                             case -1:
2472                                 msg_Err( host, "Rejecting TLS connection" );
2473                                 net_Close( fd );
2474                                 fd = -1;
2475                                 p_tls = NULL;
2476                                 break;
2477
2478                             case 1: /* missing input - most likely */
2479                                 i_state = HTTPD_CLIENT_TLS_HS_IN;
2480                                 break;
2481
2482                             case 2: /* missing output */
2483                                 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2484                                 break;
2485                         }
2486                     }
2487
2488                     if( fd >= 0 )
2489                     {
2490                         httpd_client_t *cl;
2491                         char ip[NI_MAXNUMERICHOST];
2492                         stats_UpdateInteger( host, host->p_total_counter,
2493                                              1, NULL );
2494                         stats_UpdateInteger( host, host->p_active_counter,
2495                                              1, NULL );
2496                         cl = httpd_ClientNew( fd, &sock, i_sock_size, p_tls );
2497                         httpd_ClientIP( cl, ip );
2498                         msg_Dbg( host, "Connection from %s", ip );
2499                         p_tls = NULL;
2500                         vlc_mutex_lock( &host->lock );
2501                         TAB_APPEND( host->i_client, host->client, cl );
2502                         vlc_mutex_unlock( &host->lock );
2503
2504                         if( i_state != 0 )
2505                             cl->i_state = i_state; // override state for TLS
2506                     }
2507                 }
2508             }
2509         }
2510
2511         /* now try all others socket */
2512         vlc_mutex_lock( &host->lock );
2513         for( i_client = 0; i_client < host->i_client; i_client++ )
2514         {
2515             httpd_client_t *cl = host->client[i_client];
2516             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2517             {
2518                 httpd_ClientRecv( cl );
2519             }
2520             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2521             {
2522                 httpd_ClientSend( cl );
2523             }
2524             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2525             {
2526                 httpd_ClientTlsHsIn( cl );
2527             }
2528             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2529             {
2530                 httpd_ClientTlsHsOut( cl );
2531             }
2532
2533             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2534                 cl->i_state == HTTPD_CLIENT_SENDING &&
2535                 FD_ISSET( cl->fd, &fds_read ) )
2536             {
2537                 cl->b_read_waiting = VLC_TRUE;
2538             }
2539         }
2540         vlc_mutex_unlock( &host->lock );
2541     }
2542
2543     if( p_tls != NULL )
2544         tls_ServerSessionClose( p_tls );
2545 }
2546
2547 #else /* ENABLE_HTTPD */
2548
2549 /* We just define an empty wrapper */
2550 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2551                                 tls_server_t *d )
2552 {
2553     msg_Err( a, "HTTP daemon support is disabled" );
2554     return NULL;
2555 }
2556
2557 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2558 {
2559     msg_Err( a, "HTTP daemon support is disabled" );
2560     return NULL;
2561 }
2562
2563 void httpd_HostDelete( httpd_host_t *a )
2564 {
2565 }
2566
2567 httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
2568                            char *psz_user, char *psz_password,
2569                            const vlc_acl_t *p_acl )
2570 {
2571     return NULL;
2572 }
2573
2574 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
2575                                  char *psz_user, char *psz_password,
2576                                  const vlc_acl_t *p_acl )
2577 {
2578     return NULL;
2579 }
2580
2581 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2582                     httpd_callback_sys_t *d )
2583 {
2584     return 0;
2585 }
2586
2587 void httpd_UrlDelete( httpd_url_t *a )
2588 {
2589 }
2590
2591 char* httpd_ClientIP( httpd_client_t *cl, char *psz_ip )
2592 {
2593     return NULL;
2594 }
2595
2596 char* httpd_ServerIP( httpd_client_t *cl, char *psz_ip )
2597 {
2598     return NULL;
2599 }
2600
2601 void httpd_ClientModeStream( httpd_client_t *a )
2602 {
2603 }
2604
2605 void httpd_ClientModeBidir( httpd_client_t *a )
2606 {
2607 }
2608
2609 void httpd_FileDelete( httpd_file_t *a )
2610 {
2611 }
2612
2613 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2614                              char *e, httpd_file_callback_t f,
2615                              httpd_file_sys_t *g )
2616 {
2617     return NULL;
2618 }
2619
2620 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
2621                                    const char *psz_user,
2622                                    const char *psz_password,
2623                                    const vlc_acl_t *p_acl,
2624                                    httpd_handler_callback_t pf_fill,
2625                                    httpd_handler_sys_t *p_sys )
2626 {
2627     return NULL;
2628 }
2629
2630 void httpd_HandlerDelete( httpd_handler_t *handler )
2631 {
2632 }
2633
2634 void httpd_RedirectDelete( httpd_redirect_t *a )
2635 {
2636 }
2637
2638 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2639                                      char *b, char *c )
2640 {
2641     return NULL;
2642 }
2643
2644 void httpd_StreamDelete( httpd_stream_t *a )
2645 {
2646 }
2647
2648 int httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c )
2649 {
2650     return 0;
2651 }
2652
2653 int httpd_StreamSend ( httpd_stream_t *a, uint8_t *b, int c )
2654 {
2655     return 0;
2656 }
2657
2658 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2659                                  char *d, char *e )
2660 {
2661     return NULL;
2662 }
2663
2664 void httpd_MsgInit ( httpd_message_t *a )
2665 {
2666 }
2667
2668 void httpd_MsgAdd  ( httpd_message_t *a, const char *b, const char *c, ... )
2669 {
2670 }
2671
2672 const char *httpd_MsgGet ( httpd_message_t *a, const char *b )
2673 {
2674     return "";
2675 }
2676
2677 void httpd_MsgClean( httpd_message_t *a )
2678 {
2679 }
2680
2681 #endif /* ENABLE_HTTPD */