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