]> git.sesse.net Git - vlc/blob - src/misc/httpd.c
* Merged trunk changeset 9283 to 0.8.1 branch.
[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     /* set this new socket non-block */
1558 #if defined( WIN32 ) || defined( UNDER_CE )
1559     {
1560         unsigned long i_dummy = 1;
1561         ioctlsocket( fd, FIONBIO, &i_dummy );
1562     }
1563 #else
1564     fcntl( fd, F_SETFL, O_NONBLOCK );
1565 #endif
1566     cl->i_ref   = 0;
1567     cl->fd      = fd;
1568     memcpy( &cl->sock, sock, sizeof( cl->sock ) );
1569     cl->i_sock_size = i_sock_size;
1570     cl->url     = NULL;
1571     cl->p_tls = p_tls;
1572
1573     httpd_ClientInit( cl );
1574
1575     return cl;
1576 }
1577
1578
1579 static int httpd_NetRecv( httpd_client_t *cl, char *p, int i_len )
1580 {
1581     tls_session_t *p_tls;
1582     
1583     p_tls = cl->p_tls;
1584     if( p_tls != NULL)
1585         return tls_Recv( p_tls, p, i_len );
1586
1587     return recv( cl->fd, p, i_len, 0 );
1588 }
1589
1590
1591 static int httpd_NetSend( httpd_client_t *cl, const char *p, int i_len )
1592 {
1593     tls_session_t *p_tls;
1594
1595     p_tls = cl->p_tls;
1596     if( p_tls != NULL)
1597         return tls_Send( p_tls, p, i_len );
1598
1599     return send( cl->fd, p, i_len, 0 );
1600 }
1601
1602
1603 static void httpd_ClientRecv( httpd_client_t *cl )
1604 {
1605     int i_len;
1606
1607     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1608     {
1609         /* enought to see if it's rtp over rtsp or RTSP/HTTP */
1610         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1611                                4 - cl->i_buffer );
1612         if( i_len > 0 )
1613         {
1614             cl->i_buffer += i_len;
1615         }
1616
1617         if( cl->i_buffer >= 4 )
1618         {
1619             fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );
1620             /* detect type */
1621             if( cl->p_buffer[0] == '$' )
1622             {
1623                 /* RTSP (rtp over rtsp) */
1624                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1625                 cl->query.i_type  = HTTPD_MSG_CHANNEL;
1626                 cl->query.i_channel = cl->p_buffer[1];
1627                 cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1628                 cl->query.p_body  = malloc( cl->query.i_body );
1629
1630                 cl->i_buffer      = 0;
1631             }
1632             else if( !strncmp( cl->p_buffer, "HTTP", 4 ) )
1633             {
1634                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1635                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1636             }
1637             else if( !strncmp( cl->p_buffer, "RTSP", 4 ) )
1638             {
1639                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1640                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1641             }
1642             else if( !strncmp( cl->p_buffer, "GET", 3 ) ||
1643                      !strncmp( cl->p_buffer, "HEAD", 4 ) ||
1644                      !strncmp( cl->p_buffer, "POST", 4 ) )
1645             {
1646                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1647                 cl->query.i_type  = HTTPD_MSG_NONE;
1648             }
1649             else
1650             {
1651                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1652                 cl->query.i_type  = HTTPD_MSG_NONE;
1653             }
1654         }
1655     }
1656     else if( cl->query.i_body > 0 )
1657     {
1658         /* we are reading the body of a request or a channel */
1659         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1660                                cl->query.i_body - cl->i_buffer );
1661         if( i_len > 0 )
1662         {
1663             cl->i_buffer += i_len;
1664         }
1665         if( cl->i_buffer >= cl->query.i_body )
1666         {
1667             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1668         }
1669     }
1670     else
1671     {
1672         /* we are reading a header -> char by char */
1673         for( ;; )
1674         {
1675             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1676             if( i_len <= 0 )
1677             {
1678                 break;
1679             }
1680             cl->i_buffer++;
1681
1682             if( cl->i_buffer + 1 >= cl->i_buffer_size )
1683             {
1684                 cl->i_buffer_size += 1024;
1685                 cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
1686             }
1687             if( ( cl->i_buffer >= 2 && !strncmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1688                 ( cl->i_buffer >= 4 && !strncmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1689             {
1690                 char *p;
1691
1692                 /* we have finished the header so parse it and set i_body */
1693                 cl->p_buffer[cl->i_buffer] = '\0';
1694
1695                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1696                 {
1697                     cl->query.i_status =
1698                         strtol( &cl->p_buffer[strlen( "HTTP/1.x" )], &p, 0 );
1699                     while( *p == ' ' )
1700                     {
1701                         p++;
1702                     }
1703                     cl->query.psz_status = strdup( p );
1704                 }
1705                 else
1706                 {
1707                     static const struct
1708                     {
1709                         char *name;
1710                         int  i_type;
1711                         int  i_proto;
1712                     }
1713                     msg_type[] =
1714                     {
1715                         { "GET",        HTTPD_MSG_GET,  HTTPD_PROTO_HTTP },
1716                         { "HEAD",       HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1717                         { "POST",       HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1718
1719                         { "OPTIONS",    HTTPD_MSG_OPTIONS,  HTTPD_PROTO_RTSP },
1720                         { "DESCRIBE",   HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1721                         { "SETUP",      HTTPD_MSG_SETUP,    HTTPD_PROTO_RTSP },
1722                         { "PLAY",       HTTPD_MSG_PLAY,     HTTPD_PROTO_RTSP },
1723                         { "PAUSE",      HTTPD_MSG_PAUSE,    HTTPD_PROTO_RTSP },
1724                         { "TEARDOWN",   HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1725
1726                         { NULL,         HTTPD_MSG_NONE,     HTTPD_PROTO_NONE }
1727                     };
1728                     int  i;
1729
1730                     p = NULL;
1731                     cl->query.i_type = HTTPD_MSG_NONE;
1732
1733                     fprintf( stderr, "received new request=%s\n", cl->p_buffer);
1734
1735                     for( i = 0; msg_type[i].name != NULL; i++ )
1736                     {
1737                         if( !strncmp( cl->p_buffer, msg_type[i].name,
1738                                       strlen( msg_type[i].name ) ) )
1739                         {
1740                             p = &cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1741                             cl->query.i_type = msg_type[i].i_type;
1742                             if( cl->query.i_proto != msg_type[i].i_proto )
1743                             {
1744                                 p = NULL;
1745                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1746                                 cl->query.i_type = HTTPD_MSG_NONE;
1747                             }
1748                             break;
1749                         }
1750                     }
1751                     if( p == NULL )
1752                     {
1753                         if( strstr( cl->p_buffer, "HTTP/1." ) )
1754                         {
1755                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1756                         }
1757                         else if( strstr( cl->p_buffer, "RTSP/1." ) )
1758                         {
1759                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1760                         }
1761                     }
1762                     else
1763                     {
1764                         char *p2;
1765                         char *p3;
1766
1767                         while( *p == ' ' )
1768                         {
1769                             p++;
1770                         }
1771                         p2 = strchr( p, ' ' );
1772                         if( p2 )
1773                         {
1774                             *p2++ = '\0';
1775                         }
1776                         if( !strncasecmp( p, "rtsp:", 5 ) )
1777                         {
1778                             /* for rtsp url, you have rtsp://localhost:port/path */
1779                             p += 5;
1780                             while( *p == '/' ) p++;
1781                             while( *p && *p != '/' ) p++;
1782                         }
1783                         cl->query.psz_url = strdup( p );
1784                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1785                         {
1786                             *p3++ = '\0';
1787                             cl->query.psz_args = strdup( p3 );
1788                         }
1789                         if( p2 )
1790                         {
1791                             while( *p2 == ' ' )
1792                             {
1793                                 p2++;
1794                             }
1795                             if( !strncasecmp( p2, "HTTP/1.", 7 ) )
1796                             {
1797                                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1798                                 cl->query.i_version = atoi( p2+7 );
1799                             }
1800                             else if( !strncasecmp( p2, "RTSP/1.", 7 ) )
1801                             {
1802                                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1803                                 cl->query.i_version = atoi( p2+7 );
1804                             }
1805                         }
1806                         p = p2;
1807                     }
1808                 }
1809                 if( p )
1810                 {
1811                     p = strchr( p, '\n' );
1812                 }
1813                 if( p )
1814                 {
1815                     while( *p == '\n' || *p == '\r' )
1816                     {
1817                         p++;
1818                     }
1819                     while( p && *p != '\0' )
1820                     {
1821                         char *line = p;
1822                         char *eol = p = strchr( p, '\n' );
1823                         char *colon;
1824
1825                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1826                         {
1827                             *eol-- = '\0';
1828                         }
1829
1830                         if( ( colon = strchr( line, ':' ) ) )
1831                         {
1832                             char *name;
1833                             char *value;
1834
1835                             *colon++ = '\0';
1836                             while( *colon == ' ' )
1837                             {
1838                                 colon++;
1839                             }
1840                             name = strdup( line );
1841                             value = strdup( colon );
1842
1843                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1844                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1845
1846                             if( !strcasecmp( name, "Content-Length" ) )
1847                             {
1848                                 cl->query.i_body = atol( value );
1849                             }
1850                         }
1851
1852                         if( p )
1853                         {
1854                             p++;
1855                             while( *p == '\n' || *p == '\r' )
1856                             {
1857                                 p++;
1858                             }
1859                         }
1860                     }
1861                 }
1862                 if( cl->query.i_body > 0 )
1863                 {
1864                     /* TODO Mhh, handle the case client will only send a request and close the connection
1865                      * to mark and of body (probably only RTSP) */
1866                     cl->query.p_body = malloc( cl->query.i_body );
1867                     cl->i_buffer = 0;
1868                 }
1869                 else
1870                 {
1871                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1872                 }
1873             }
1874         }
1875     }
1876
1877     /* check if the client is to be set to dead */
1878 #if defined( WIN32 ) || defined( UNDER_CE )
1879     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1880 #else
1881     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1882 #endif
1883     {
1884         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1885         {
1886             /* connection closed -> end of data */
1887             if( cl->query.i_body > 0 )
1888             {
1889                 cl->query.i_body = cl->i_buffer;
1890             }
1891             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1892         }
1893         else
1894         {
1895             cl->i_state = HTTPD_CLIENT_DEAD;
1896         }
1897     }
1898     cl->i_activity_date = mdate();
1899
1900     /* XXX: for QT I have to disable timeout. Try to find why */
1901     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1902         cl->i_activity_timeout = 0;
1903
1904     /* Debugging only */
1905     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1906     {
1907         int i;
1908
1909         fprintf( stderr, "received new request\n" );
1910         fprintf( stderr, "  - proto=%s\n",
1911                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1912         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1913         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1914         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1915         {
1916             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1917                      cl->query.psz_status );
1918         }
1919         else if( cl->query.i_type != HTTPD_MSG_NONE )
1920         {
1921             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1922         }
1923         for( i = 0; i < cl->query.i_name; i++ )
1924         {
1925             fprintf( stderr, "  - option name='%s' value='%s'\n",
1926                      cl->query.name[i], cl->query.value[i] );
1927         }
1928     }
1929 }
1930
1931
1932 static void httpd_ClientSend( httpd_client_t *cl )
1933 {
1934     int i;
1935     int i_len;
1936
1937     if( cl->i_buffer < 0 )
1938     {
1939         /* We need to create the header */
1940         int i_size = 0;
1941         char *p;
1942
1943         i_size = strlen( "HTTP/1.") + 10 + 10 +
1944                  strlen( cl->answer.psz_status ? cl->answer.psz_status : "" ) + 5;
1945         for( i = 0; i < cl->answer.i_name; i++ )
1946         {
1947             i_size += strlen( cl->answer.name[i] ) + 2 +
1948                       strlen( cl->answer.value[i] ) + 2;
1949         }
1950
1951         if( cl->i_buffer_size < i_size )
1952         {
1953             cl->i_buffer_size = i_size;
1954             free( cl->p_buffer );
1955             cl->p_buffer = malloc( i_size );
1956         }
1957         p = cl->p_buffer;
1958
1959         p += sprintf( p, "%s/1.%d %d %s\r\n",
1960                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP" : "RTSP",
1961                       cl->answer.i_version,
1962                       cl->answer.i_status, cl->answer.psz_status );
1963         for( i = 0; i < cl->answer.i_name; i++ )
1964         {
1965             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1966                           cl->answer.value[i] );
1967         }
1968         p += sprintf( p, "\r\n" );
1969
1970         cl->i_buffer = 0;
1971         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1972
1973         fprintf( stderr, "sending answer\n" );
1974         fprintf( stderr, "%s",  cl->p_buffer );
1975     }
1976
1977     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1978                            cl->i_buffer_size - cl->i_buffer );
1979     if( i_len > 0 )
1980     {
1981         cl->i_activity_date = mdate();
1982         cl->i_buffer += i_len;
1983
1984         if( cl->i_buffer >= cl->i_buffer_size )
1985         {
1986             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1987                 !cl->b_read_waiting )
1988             {
1989                 /* catch more body data */
1990                 int     i_msg = cl->query.i_type;
1991                 int64_t i_offset = cl->answer.i_body_offset;
1992
1993                 httpd_MsgClean( &cl->answer );
1994                 cl->answer.i_body_offset = i_offset;
1995
1996                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1997                                           &cl->answer, &cl->query );
1998             }
1999
2000             if( cl->answer.i_body > 0 )
2001             {
2002                 /* send the body data */
2003                 free( cl->p_buffer );
2004                 cl->p_buffer = cl->answer.p_body;
2005                 cl->i_buffer_size = cl->answer.i_body;
2006                 cl->i_buffer = 0;
2007
2008                 cl->answer.i_body = 0;
2009                 cl->answer.p_body = NULL;
2010             }
2011             else
2012             {
2013                 /* send finished */
2014                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
2015             }
2016         }
2017     }
2018     else
2019     {
2020 #if defined( WIN32 ) || defined( UNDER_CE )
2021         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
2022 #else
2023         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
2024 #endif
2025         {
2026             /* error */
2027             cl->i_state = HTTPD_CLIENT_DEAD;
2028         }
2029     }
2030 }
2031
2032 static void httpd_HostThread( httpd_host_t *host )
2033 {
2034     tls_session_t *p_tls = NULL;
2035
2036     while( !host->b_die )
2037     {
2038         struct timeval  timeout;
2039         fd_set          fds_read;
2040         fd_set          fds_write;
2041         int             i_handle_max = 0;
2042         int             i_ret;
2043         int             i_client;
2044         int             b_low_delay = 0;
2045
2046         if( host->i_url <= 0 )
2047         {
2048             /* 0.2s */
2049             msleep( 200000 );
2050             continue;
2051         }
2052
2053         /* built a set of handle to select */
2054         FD_ZERO( &fds_read );
2055         FD_ZERO( &fds_write );
2056
2057         FD_SET( host->fd, &fds_read );
2058         i_handle_max = host->fd;
2059
2060         /* prepare a new TLS session */
2061         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2062             p_tls = tls_ServerSessionPrepare( host->p_tls );
2063
2064         /* add all socket that should be read/write and close dead connection */
2065         vlc_mutex_lock( &host->lock );
2066         for( i_client = 0; i_client < host->i_client; i_client++ )
2067         {
2068             httpd_client_t *cl = host->client[i_client];
2069
2070             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2071                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2072                   ( cl->i_activity_timeout > 0 &&
2073                     cl->i_activity_date+cl->i_activity_timeout < mdate()) ) ) )
2074             {
2075                 char *ip;
2076
2077                 // FIXME: it sucks to allocate memory on the stack for debug
2078                 ip = httpd_ClientIP( cl );
2079                 msg_Dbg( host, "connection closed(%s)",
2080                          (ip != NULL) ? ip : "unknown" );
2081                 free( ip );
2082
2083                 httpd_ClientClean( cl );
2084                 TAB_REMOVE( host->i_client, host->client, cl );
2085                 free( cl );
2086                 i_client--;
2087                 continue;
2088             }
2089             else if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2090             {
2091                 FD_SET( cl->fd, &fds_read );
2092                 i_handle_max = __MAX( i_handle_max, cl->fd );
2093             }
2094             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2095             {
2096                 FD_SET( cl->fd, &fds_write );
2097                 i_handle_max = __MAX( i_handle_max, cl->fd );
2098             }
2099             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2100             {
2101                 httpd_message_t *answer = &cl->answer;
2102                 httpd_message_t *query  = &cl->query;
2103                 int i_msg = query->i_type;
2104
2105                 httpd_MsgInit( answer );
2106
2107                 /* Handle what we received */
2108                 if( cl->i_mode != HTTPD_CLIENT_BIDIR &&
2109                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2110                 {
2111                     /* we can only receive request from client when not
2112                      * in BIDIR mode */
2113                     cl->url     = NULL;
2114                     cl->i_state = HTTPD_CLIENT_DEAD;
2115                 }
2116                 else if( i_msg == HTTPD_MSG_ANSWER )
2117                 {
2118                     /* We are in BIDIR mode, trigger the callback and then
2119                      * check for new data */
2120                     if( cl->url && cl->url->catch[i_msg].cb )
2121                     {
2122                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2123                                                   cl, NULL, query );
2124                     }
2125                     cl->i_state = HTTPD_CLIENT_WAITING;
2126                 }
2127                 else if( i_msg == HTTPD_MSG_CHANNEL )
2128                 {
2129                     /* We are in BIDIR mode, trigger the callback and then
2130                      * check for new data */
2131                     if( cl->url && cl->url->catch[i_msg].cb )
2132                     {
2133                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2134                                                   cl, NULL, query );
2135                     }
2136                     cl->i_state = HTTPD_CLIENT_WAITING;
2137                 }
2138                 else if( i_msg == HTTPD_MSG_OPTIONS )
2139                 {
2140                     int i_cseq;
2141
2142                     /* unimplemented */
2143                     answer->i_proto  = query->i_proto ;
2144                     answer->i_type   = HTTPD_MSG_ANSWER;
2145                     answer->i_version= 0;
2146                     answer->i_status = 200;
2147                     answer->psz_status = strdup( "Ok" );
2148
2149                     answer->i_body = 0;
2150                     answer->p_body = NULL;
2151
2152                     i_cseq = atoi( httpd_MsgGet( query, "Cseq" ) );
2153                     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
2154                     httpd_MsgAdd( answer, "Server", "VLC Server" );
2155                     httpd_MsgAdd( answer, "Public", "DESCRIBE, SETUP, "
2156                                  "TEARDOWN, PLAY, PAUSE" );
2157                     httpd_MsgAdd( answer, "Content-Length", "%d",
2158                                   answer->i_body );
2159
2160                     cl->i_buffer = -1;  /* Force the creation of the answer in
2161                                          * httpd_ClientSend */
2162                     cl->i_state = HTTPD_CLIENT_SENDING;
2163                 }
2164                 else if( i_msg == HTTPD_MSG_NONE )
2165                 {
2166                     if( query->i_proto == HTTPD_PROTO_NONE )
2167                     {
2168                         cl->url = NULL;
2169                         cl->i_state = HTTPD_CLIENT_DEAD;
2170                     }
2171                     else
2172                     {
2173                         uint8_t *p;
2174
2175                         /* unimplemented */
2176                         answer->i_proto  = query->i_proto ;
2177                         answer->i_type   = HTTPD_MSG_ANSWER;
2178                         answer->i_version= 0;
2179                         answer->i_status = 501;
2180                         answer->psz_status = strdup( "Unimplemented" );
2181
2182                         p = answer->p_body = malloc( 1000 );
2183
2184                         p += sprintf( p, "<html>\n" );
2185                         p += sprintf( p, "<head>\n" );
2186                         p += sprintf( p, "<title>Error 501</title>\n" );
2187                         p += sprintf( p, "</head>\n" );
2188                         p += sprintf( p, "<body>\n" );
2189                         p += sprintf( p, "<h1><center> 501 Unimplemented</center></h1>\n" );
2190                         p += sprintf( p, "<hr />\n" );
2191                         p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2192                         p += sprintf( p, "</body>\n" );
2193                         p += sprintf( p, "</html>\n" );
2194
2195                         answer->i_body = p - answer->p_body;
2196                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2197
2198                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2199                         cl->i_state = HTTPD_CLIENT_SENDING;
2200                     }
2201                 }
2202                 else
2203                 {
2204                     vlc_bool_t b_auth_failed = VLC_FALSE;
2205                     int i;
2206
2207                     /* Search the url and trigger callbacks */
2208                     for( i = 0; i < host->i_url; i++ )
2209                     {
2210                         httpd_url_t *url = host->url[i];
2211
2212                         if( !strcmp( url->psz_url, query->psz_url ) )
2213                         {
2214                             if( url->catch[i_msg].cb )
2215                             {
2216                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2217                                 {
2218                                     /* create the headers */
2219                                     char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2220                                     char *auth;
2221                                     char *id;
2222
2223                                     asprintf( &id, "%s:%s", url->psz_user, url->psz_password );
2224                                     auth = malloc( strlen(b64) + 1 );
2225
2226                                     if( !strncasecmp( b64, "BASIC", 5 ) )
2227                                     {
2228                                         b64 += 5;
2229                                         while( *b64 == ' ' )
2230                                         {
2231                                             b64++;
2232                                         }
2233                                         b64_decode( auth, b64 );
2234                                     }
2235                                     else
2236                                     {
2237                                         strcpy( auth, "" );
2238                                     }
2239                                     if( strcmp( id, auth ) )
2240                                     {
2241                                         httpd_MsgAdd( answer, "WWW-Authenticate", "Basic realm=\"%s\"", url->psz_user );
2242                                         /* We fail for all url */
2243                                         b_auth_failed = VLC_TRUE;
2244                                         free( id );
2245                                         free( auth );
2246                                         break;
2247                                     }
2248
2249                                     free( id );
2250                                     free( auth );
2251                                 }
2252
2253                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2254                                 {
2255                                     /* only one url can answer */
2256                                     answer = NULL;
2257                                     if( cl->url == NULL )
2258                                     {
2259                                         cl->url = url;
2260                                     }
2261                                 }
2262                             }
2263                         }
2264                     }
2265                     if( answer )
2266                     {
2267                         uint8_t *p;
2268
2269                         answer->i_proto  = query->i_proto;
2270                         answer->i_type   = HTTPD_MSG_ANSWER;
2271                         answer->i_version= 0;
2272                         p = answer->p_body = malloc( 1000 + strlen(query->psz_url) );
2273
2274                         if( b_auth_failed )
2275                         {
2276                             answer->i_status = 401;
2277                             answer->psz_status = strdup( "Authorization Required" );
2278
2279                             p += sprintf( p, "<html>\n" );
2280                             p += sprintf( p, "<head>\n" );
2281                             p += sprintf( p, "<title>Error 401</title>\n" );
2282                             p += sprintf( p, "</head>\n" );
2283                             p += sprintf( p, "<body>\n" );
2284                             p += sprintf( p, "<h1><center> 401 Authorization Required (%s)</center></h1>\n", query->psz_url );
2285                             p += sprintf( p, "<hr />\n" );
2286                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2287                             p += sprintf( p, "</body>\n" );
2288                             p += sprintf( p, "</html>\n" );
2289                         }
2290                         else
2291                         {
2292                             /* no url registered */
2293                             answer->i_status = 404;
2294                             answer->psz_status = strdup( "Not found" );
2295
2296                             p += sprintf( p, "<html>\n" );
2297                             p += sprintf( p, "<head>\n" );
2298                             p += sprintf( p, "<title>Error 404</title>\n" );
2299                             p += sprintf( p, "</head>\n" );
2300                             p += sprintf( p, "<body>\n" );
2301                             p += sprintf( p, "<h1><center> 404 Resource not found(%s)</center></h1>\n", query->psz_url );
2302                             p += sprintf( p, "<hr />\n" );
2303                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2304                             p += sprintf( p, "</body>\n" );
2305                             p += sprintf( p, "</html>\n" );
2306                         }
2307
2308                         answer->i_body = p - answer->p_body;
2309                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2310                     }
2311                     cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2312                     cl->i_state = HTTPD_CLIENT_SENDING;
2313                 }
2314             }
2315             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2316             {
2317                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2318                 {
2319                     cl->url = NULL;
2320                     if( ( cl->query.i_proto == HTTPD_PROTO_HTTP &&
2321                           ( ( cl->answer.i_version == 0 && !strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Keep-Alive" ) ) ||
2322                             ( cl->answer.i_version == 1 &&  strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) ) ) ||
2323                         ( cl->query.i_proto == HTTPD_PROTO_RTSP &&
2324                           strcasecmp( httpd_MsgGet( &cl->query, "Connection" ), "Close" ) &&
2325                           strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) )
2326                     {
2327                         httpd_MsgClean( &cl->query );
2328                         httpd_MsgInit( &cl->query );
2329
2330                         cl->i_buffer = 0;
2331                         cl->i_buffer_size = 1000;
2332                         free( cl->p_buffer );
2333                         cl->p_buffer = malloc( cl->i_buffer_size );
2334                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2335                     }
2336                     else
2337                     {
2338                         cl->i_state = HTTPD_CLIENT_DEAD;
2339                     }
2340                     httpd_MsgClean( &cl->answer );
2341                 }
2342                 else if( cl->b_read_waiting )
2343                 {
2344                     /* we have a message waiting for us to read it */
2345                     httpd_MsgClean( &cl->answer );
2346                     httpd_MsgClean( &cl->query );
2347
2348                     cl->i_buffer = 0;
2349                     cl->i_buffer_size = 1000;
2350                     free( cl->p_buffer );
2351                     cl->p_buffer = malloc( cl->i_buffer_size );
2352                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2353                     cl->b_read_waiting = VLC_FALSE;
2354                 }
2355                 else
2356                 {
2357                     int64_t i_offset = cl->answer.i_body_offset;
2358                     httpd_MsgClean( &cl->answer );
2359
2360                     cl->answer.i_body_offset = i_offset;
2361                     free( cl->p_buffer );
2362                     cl->p_buffer = NULL;
2363                     cl->i_buffer = 0;
2364                     cl->i_buffer_size = 0;
2365
2366                     cl->i_state = HTTPD_CLIENT_WAITING;
2367                 }
2368             }
2369             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2370             {
2371                 int64_t i_offset = cl->answer.i_body_offset;
2372                 int     i_msg = cl->query.i_type;
2373
2374                 httpd_MsgInit( &cl->answer );
2375                 cl->answer.i_body_offset = i_offset;
2376
2377                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2378                                           &cl->answer, &cl->query );
2379                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2380                 {
2381                     /* we have new data, so reenter send mode */
2382                     cl->i_buffer      = 0;
2383                     cl->p_buffer      = cl->answer.p_body;
2384                     cl->i_buffer_size = cl->answer.i_body;
2385                     cl->answer.p_body = NULL;
2386                     cl->answer.i_body = 0;
2387                     cl->i_state = HTTPD_CLIENT_SENDING;
2388                 }
2389                 else
2390                 {
2391                     /* we shouldn't wait too long */
2392                     b_low_delay = VLC_TRUE;
2393                 }
2394             }
2395
2396             /* Special for BIDIR mode we also check reading */
2397             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2398                 cl->i_state == HTTPD_CLIENT_SENDING )
2399             {
2400                 FD_SET( cl->fd, &fds_read );
2401                 i_handle_max = __MAX( i_handle_max, cl->fd );
2402             }
2403         }
2404         vlc_mutex_unlock( &host->lock );
2405
2406         /* we will wait 100ms or 20ms (not too big 'cause HTTPD_CLIENT_WAITING) */
2407         timeout.tv_sec = 0;
2408         timeout.tv_usec = b_low_delay ? 20000 : 100000;
2409
2410         i_ret = select( i_handle_max + 1,
2411                         &fds_read, &fds_write, NULL, &timeout );
2412
2413         if( i_ret == -1 && errno != EINTR )
2414         {
2415             msg_Warn( host, "cannot select sockets" );
2416             msleep( 1000 );
2417             continue;
2418         }
2419         else if( i_ret <= 0 )
2420         {
2421             continue;
2422         }
2423
2424         /* accept new connections */
2425         if( FD_ISSET( host->fd, &fds_read ) )
2426         {
2427             int     i_sock_size = sizeof( struct sockaddr_storage );
2428             struct  sockaddr_storage sock;
2429             int     fd;
2430
2431             fd = accept( host->fd, (struct sockaddr *)&sock, &i_sock_size );
2432             if( fd >= 0 )
2433             {
2434                 if( p_tls != NULL)
2435                 {
2436                     p_tls = tls_SessionHandshake( p_tls, fd );
2437                     if ( p_tls == NULL )
2438                     {
2439                         msg_Err( host, "Rejecting TLS connection" );
2440                         net_Close( fd );
2441                         fd = -1;
2442                     }
2443                 }
2444                 
2445                 if( fd >= 0 )
2446                 {
2447                     char *ip;
2448                     httpd_client_t *cl;
2449
2450                     cl = httpd_ClientNew( fd, &sock, i_sock_size, p_tls );
2451                     p_tls = NULL;
2452                     vlc_mutex_lock( &host->lock );
2453                     TAB_APPEND( host->i_client, host->client, cl );
2454                     vlc_mutex_unlock( &host->lock );
2455
2456     
2457                     // FIXME: it sucks to allocate memory for debug
2458                     ip = httpd_ClientIP( cl );
2459                     msg_Dbg( host, "new connection (%s)",
2460                              ip != NULL ? ip : "unknown" );
2461                     if( ip != NULL)
2462                         free( ip );
2463                 }
2464             }
2465         }
2466         /* now try all others socket */
2467         vlc_mutex_lock( &host->lock );
2468         for( i_client = 0; i_client < host->i_client; i_client++ )
2469         {
2470             httpd_client_t *cl = host->client[i_client];
2471             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2472             {
2473                 httpd_ClientRecv( cl );
2474             }
2475             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2476             {
2477                 httpd_ClientSend( cl );
2478             }
2479
2480             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2481                 cl->i_state == HTTPD_CLIENT_SENDING &&
2482                 FD_ISSET( cl->fd, &fds_read ) )
2483             {
2484                 cl->b_read_waiting = VLC_TRUE;
2485             }
2486         }
2487         vlc_mutex_unlock( &host->lock );
2488     }
2489 }
2490
2491 #ifndef HAVE_GETADDRINFO
2492 static int BuildAddr( struct sockaddr_in * p_socket,
2493                       const char * psz_address, int i_port )
2494 {
2495     /* Reset struct */
2496     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
2497     p_socket->sin_family = AF_INET;                                /* family */
2498     p_socket->sin_port = htons( (uint16_t)i_port );
2499     if( !*psz_address )
2500     {
2501         p_socket->sin_addr.s_addr = INADDR_ANY;
2502     }
2503     else
2504     {
2505         struct hostent    * p_hostent;
2506
2507         /* Try to convert address directly from in_addr - this will work if
2508          * psz_address is dotted decimal. */
2509 #ifdef HAVE_ARPA_INET_H
2510         if( !inet_aton( psz_address, &p_socket->sin_addr ) )
2511 #else
2512         p_socket->sin_addr.s_addr = inet_addr( psz_address );
2513
2514 /*        if( p_socket->sin_addr.s_addr == INADDR_NONE )*/
2515         if( p_socket->sin_addr.s_addr == INADDR_BROADCAST )
2516 #endif
2517         {
2518             /* We have a fqdn, try to find its address */
2519             if ( (p_hostent = gethostbyname( psz_address )) == NULL )
2520             {
2521                 return( -1 );
2522             }
2523
2524             /* Copy the first address of the host in the socket address */
2525             memcpy( &((struct sockaddr_in *)p_socket)->sin_addr, p_hostent->h_addr_list[0],
2526                      p_hostent->h_length );
2527         }
2528     }
2529     return( 0 );
2530 }
2531 #endif
2532
2533 static int GetAddrPort( const struct sockaddr_storage *p_ss )
2534 {
2535     int i_port = 0;
2536
2537     switch (p_ss->ss_family)
2538     {
2539 #ifdef AF_INET6
2540         case AF_INET6:
2541             i_port = ((const struct sockaddr_in6 *)p_ss)->sin6_port;
2542             break;
2543 #endif
2544
2545         case AF_INET:
2546             i_port = ((const struct sockaddr_in *)p_ss)->sin_port;
2547             break;
2548             
2549         default:
2550             return -1;
2551     }
2552     
2553     return ntohs( i_port );
2554 }
2555
2556 #else /* ENABLE_HTTPD */
2557
2558 /* We just define an empty wrapper */
2559 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2560                                 tls_server_t *d )
2561 {
2562     msg_Err( a, "HTTP daemon support is disabled" );
2563     return 0;
2564 }
2565 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2566 {
2567     msg_Err( a, "HTTP daemon support is disabled" );
2568     return 0;
2569 }
2570 void httpd_HostDelete( httpd_host_t *a ){}
2571 httpd_url_t *httpd_UrlNew( httpd_host_t *a, char *b ){ return 0; }
2572 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *a, char *b, char *c,
2573                                  char *d ){ return 0; }
2574 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2575                     httpd_callback_sys_t *d ){ return 0; }
2576 void httpd_UrlDelete( httpd_url_t *a ){}
2577
2578 char *httpd_ClientIP( httpd_client_t *a ){ return 0; }
2579 void httpd_ClientModeStream( httpd_client_t *a ){}
2580 void httpd_ClientModeBidir( httpd_client_t *a ){}
2581
2582 void httpd_FileDelete( httpd_file_t *a ){}
2583 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2584                              char *e, httpd_file_callback_t f,
2585                              httpd_file_sys_t *g ){ return 0; }
2586
2587 void httpd_RedirectDelete( httpd_redirect_t *a ){}
2588 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2589                                      char *b, char *c ){ return 0; }
2590
2591 void httpd_StreamDelete( httpd_stream_t *a ){}
2592 int  httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2593 int  httpd_StreamSend  ( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2594 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2595                                  char *d, char *e ){ return 0; }
2596
2597 void httpd_MsgInit ( httpd_message_t *a ){}
2598 void httpd_MsgAdd  ( httpd_message_t *a, char *b, char *c, ... ){}
2599 char *httpd_MsgGet ( httpd_message_t *a, char *b ){ return 0; }
2600 void httpd_MsgClean( httpd_message_t *a ){}
2601
2602 #endif /* ENABLE_HTTPD */