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