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