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