]> git.sesse.net Git - vlc/blob - src/misc/httpd.c
* modules/control/http.c: Added support for .hosts files detailing hosts
[vlc] / src / misc / httpd.c
1 /*****************************************************************************
2  * httpd.c
3  *****************************************************************************
4  * Copyright (C) 2004-2005 VideoLAN
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         char *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 /*
1335  * FIXME: use vlc_getnameinfo
1336  */
1337 char* httpd_ClientIP( httpd_client_t *cl )
1338 {
1339 #ifdef HAVE_GETNAMEINFO
1340     char sz_ip[INET6_ADDRSTRLEN + 2];
1341     int i;
1342
1343     if( (cl->sock.ss_family == AF_INET6) &&
1344         IN6_IS_ADDR_V4MAPPED( &((const struct sockaddr_in6 *)
1345                               &cl->sock)->sin6_addr) )
1346     {
1347         /* If client is using IPv4 but server is using IPv6 */
1348         struct sockaddr_in a;
1349         
1350         memset( &a, 0, sizeof( a ) );
1351         a.sin_family = AF_INET;
1352         a.sin_port = ((const struct sockaddr_in6 *)&cl->sock)->sin6_port;
1353         a.sin_addr.s_addr = ((const uint32_t *)&((const struct sockaddr_in6 *)
1354                             &cl->sock)->sin6_addr)[3];
1355         i = getnameinfo( (const struct sockaddr *)&a, sizeof( a ),
1356                          &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST );
1357     }
1358     else
1359         i = getnameinfo( (const struct sockaddr *)&cl->sock, cl->i_sock_size,
1360                          &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0,
1361                          NI_NUMERICHOST );
1362
1363     if( i != 0 )
1364         /* FIXME: msg_Err */
1365         return NULL;
1366         
1367     if( strchr( &sz_ip[1], ':' ) != NULL )
1368     {
1369         *sz_ip = '[';
1370         i = strlen( sz_ip );
1371         sz_ip[i++] = ']';
1372         sz_ip[i] = '\0';
1373        
1374         return strdup( sz_ip );
1375     }
1376     
1377     return strdup( &sz_ip[1] );
1378
1379 #else
1380     /* FIXME not thread safe */
1381     return strdup( inet_ntoa( ((const struct sockaddr_in *)&cl->sock)->sin_addr ) );
1382 #endif
1383 }
1384
1385 static void httpd_ClientClean( httpd_client_t *cl )
1386 {
1387     if( cl->fd >= 0 )
1388     {
1389         if( cl->p_tls != NULL )
1390             tls_ServerSessionClose( cl->p_tls );
1391         net_Close( cl->fd );
1392         cl->fd = -1;
1393     }
1394
1395     httpd_MsgClean( &cl->answer );
1396     httpd_MsgClean( &cl->query );
1397
1398     if( cl->p_buffer )
1399     {
1400         free( cl->p_buffer );
1401         cl->p_buffer = NULL;
1402     }
1403 }
1404
1405 static httpd_client_t *httpd_ClientNew( int fd, struct sockaddr_storage *sock,
1406                                         int i_sock_size,
1407                                         tls_session_t *p_tls )
1408 {
1409     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1410     cl->i_ref   = 0;
1411     cl->fd      = fd;
1412     memcpy( &cl->sock, sock, sizeof( cl->sock ) );
1413     cl->i_sock_size = i_sock_size;
1414     cl->url     = NULL;
1415     cl->p_tls = p_tls;
1416
1417     httpd_ClientInit( cl );
1418
1419     return cl;
1420 }
1421
1422
1423 static int httpd_NetRecv( httpd_client_t *cl, char *p, int i_len )
1424 {
1425     tls_session_t *p_tls;
1426     
1427     p_tls = cl->p_tls;
1428     if( p_tls != NULL)
1429         return tls_Recv( p_tls, p, i_len );
1430
1431     return recv( cl->fd, p, i_len, 0 );
1432 }
1433
1434
1435 static int httpd_NetSend( httpd_client_t *cl, const char *p, int i_len )
1436 {
1437     tls_session_t *p_tls;
1438
1439     p_tls = cl->p_tls;
1440     if( p_tls != NULL)
1441         return tls_Send( p_tls, p, i_len );
1442
1443     return send( cl->fd, p, i_len, 0 );
1444 }
1445
1446
1447 static void httpd_ClientRecv( httpd_client_t *cl )
1448 {
1449     int i_len;
1450
1451     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1452     {
1453         /* enought to see if it's rtp over rtsp or RTSP/HTTP */
1454         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1455                                4 - cl->i_buffer );
1456         if( i_len > 0 )
1457         {
1458             cl->i_buffer += i_len;
1459         }
1460
1461         if( cl->i_buffer >= 4 )
1462         {
1463             /*fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );*/
1464             /* detect type */
1465             if( cl->p_buffer[0] == '$' )
1466             {
1467                 /* RTSP (rtp over rtsp) */
1468                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1469                 cl->query.i_type  = HTTPD_MSG_CHANNEL;
1470                 cl->query.i_channel = cl->p_buffer[1];
1471                 cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1472                 cl->query.p_body  = malloc( cl->query.i_body );
1473
1474                 cl->i_buffer      = 0;
1475             }
1476             else if( !strncmp( cl->p_buffer, "HTTP", 4 ) )
1477             {
1478                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1479                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1480             }
1481             else if( !strncmp( cl->p_buffer, "RTSP", 4 ) )
1482             {
1483                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1484                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1485             }
1486             else if( !strncmp( cl->p_buffer, "GET", 3 ) ||
1487                      !strncmp( cl->p_buffer, "HEAD", 4 ) ||
1488                      !strncmp( cl->p_buffer, "POST", 4 ) )
1489             {
1490                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1491                 cl->query.i_type  = HTTPD_MSG_NONE;
1492             }
1493             else
1494             {
1495                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1496                 cl->query.i_type  = HTTPD_MSG_NONE;
1497             }
1498         }
1499     }
1500     else if( cl->query.i_body > 0 )
1501     {
1502         /* we are reading the body of a request or a channel */
1503         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1504                                cl->query.i_body - cl->i_buffer );
1505         if( i_len > 0 )
1506         {
1507             cl->i_buffer += i_len;
1508         }
1509         if( cl->i_buffer >= cl->query.i_body )
1510         {
1511             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1512         }
1513     }
1514     else
1515     {
1516         /* we are reading a header -> char by char */
1517         for( ;; )
1518         {
1519             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1520             if( i_len <= 0 )
1521             {
1522                 break;
1523             }
1524             cl->i_buffer++;
1525
1526             if( cl->i_buffer + 1 >= cl->i_buffer_size )
1527             {
1528                 cl->i_buffer_size += 1024;
1529                 cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
1530             }
1531             if( ( cl->i_buffer >= 2 && !strncmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1532                 ( cl->i_buffer >= 4 && !strncmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1533             {
1534                 char *p;
1535
1536                 /* we have finished the header so parse it and set i_body */
1537                 cl->p_buffer[cl->i_buffer] = '\0';
1538
1539                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1540                 {
1541                     cl->query.i_status =
1542                         strtol( &cl->p_buffer[strlen( "HTTP/1.x" )], &p, 0 );
1543                     while( *p == ' ' )
1544                     {
1545                         p++;
1546                     }
1547                     cl->query.psz_status = strdup( p );
1548                 }
1549                 else
1550                 {
1551                     static const struct
1552                     {
1553                         char *name;
1554                         int  i_type;
1555                         int  i_proto;
1556                     }
1557                     msg_type[] =
1558                     {
1559                         { "GET",        HTTPD_MSG_GET,  HTTPD_PROTO_HTTP },
1560                         { "HEAD",       HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
1561                         { "POST",       HTTPD_MSG_POST, HTTPD_PROTO_HTTP },
1562
1563                         { "OPTIONS",    HTTPD_MSG_OPTIONS,  HTTPD_PROTO_RTSP },
1564                         { "DESCRIBE",   HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
1565                         { "SETUP",      HTTPD_MSG_SETUP,    HTTPD_PROTO_RTSP },
1566                         { "PLAY",       HTTPD_MSG_PLAY,     HTTPD_PROTO_RTSP },
1567                         { "PAUSE",      HTTPD_MSG_PAUSE,    HTTPD_PROTO_RTSP },
1568                         { "TEARDOWN",   HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },
1569
1570                         { NULL,         HTTPD_MSG_NONE,     HTTPD_PROTO_NONE }
1571                     };
1572                     int  i;
1573
1574                     p = NULL;
1575                     cl->query.i_type = HTTPD_MSG_NONE;
1576
1577                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1578
1579                     for( i = 0; msg_type[i].name != NULL; i++ )
1580                     {
1581                         if( !strncmp( cl->p_buffer, msg_type[i].name,
1582                                       strlen( msg_type[i].name ) ) )
1583                         {
1584                             p = &cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1585                             cl->query.i_type = msg_type[i].i_type;
1586                             if( cl->query.i_proto != msg_type[i].i_proto )
1587                             {
1588                                 p = NULL;
1589                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1590                                 cl->query.i_type = HTTPD_MSG_NONE;
1591                             }
1592                             break;
1593                         }
1594                     }
1595                     if( p == NULL )
1596                     {
1597                         if( strstr( cl->p_buffer, "HTTP/1." ) )
1598                         {
1599                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1600                         }
1601                         else if( strstr( cl->p_buffer, "RTSP/1." ) )
1602                         {
1603                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1604                         }
1605                     }
1606                     else
1607                     {
1608                         char *p2;
1609                         char *p3;
1610
1611                         while( *p == ' ' )
1612                         {
1613                             p++;
1614                         }
1615                         p2 = strchr( p, ' ' );
1616                         if( p2 )
1617                         {
1618                             *p2++ = '\0';
1619                         }
1620                         if( !strncasecmp( p, "rtsp:", 5 ) )
1621                         {
1622                             /* for rtsp url, you have rtsp://localhost:port/path */
1623                             p += 5;
1624                             while( *p == '/' ) p++;
1625                             while( *p && *p != '/' ) p++;
1626                         }
1627                         cl->query.psz_url = strdup( p );
1628                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1629                         {
1630                             *p3++ = '\0';
1631                             cl->query.psz_args = strdup( p3 );
1632                         }
1633                         if( p2 )
1634                         {
1635                             while( *p2 == ' ' )
1636                             {
1637                                 p2++;
1638                             }
1639                             if( !strncasecmp( p2, "HTTP/1.", 7 ) )
1640                             {
1641                                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1642                                 cl->query.i_version = atoi( p2+7 );
1643                             }
1644                             else if( !strncasecmp( p2, "RTSP/1.", 7 ) )
1645                             {
1646                                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1647                                 cl->query.i_version = atoi( p2+7 );
1648                             }
1649                         }
1650                         p = p2;
1651                     }
1652                 }
1653                 if( p )
1654                 {
1655                     p = strchr( p, '\n' );
1656                 }
1657                 if( p )
1658                 {
1659                     while( *p == '\n' || *p == '\r' )
1660                     {
1661                         p++;
1662                     }
1663                     while( p && *p != '\0' )
1664                     {
1665                         char *line = p;
1666                         char *eol = p = strchr( p, '\n' );
1667                         char *colon;
1668
1669                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1670                         {
1671                             *eol-- = '\0';
1672                         }
1673
1674                         if( ( colon = strchr( line, ':' ) ) )
1675                         {
1676                             char *name;
1677                             char *value;
1678
1679                             *colon++ = '\0';
1680                             while( *colon == ' ' )
1681                             {
1682                                 colon++;
1683                             }
1684                             name = strdup( line );
1685                             value = strdup( colon );
1686
1687                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1688                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1689
1690                             if( !strcasecmp( name, "Content-Length" ) )
1691                             {
1692                                 cl->query.i_body = atol( value );
1693                             }
1694                         }
1695
1696                         if( p )
1697                         {
1698                             p++;
1699                             while( *p == '\n' || *p == '\r' )
1700                             {
1701                                 p++;
1702                             }
1703                         }
1704                     }
1705                 }
1706                 if( cl->query.i_body > 0 )
1707                 {
1708                     /* TODO Mhh, handle the case client will only send a request and close the connection
1709                      * to mark and of body (probably only RTSP) */
1710                     cl->query.p_body = malloc( cl->query.i_body );
1711                     cl->i_buffer = 0;
1712                 }
1713                 else
1714                 {
1715                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1716                 }
1717             }
1718         }
1719     }
1720
1721     /* check if the client is to be set to dead */
1722 #if defined( WIN32 ) || defined( UNDER_CE )
1723     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1724 #else
1725     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1726 #endif
1727     {
1728         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1729         {
1730             /* connection closed -> end of data */
1731             if( cl->query.i_body > 0 )
1732             {
1733                 cl->query.i_body = cl->i_buffer;
1734             }
1735             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1736         }
1737         else
1738         {
1739             cl->i_state = HTTPD_CLIENT_DEAD;
1740         }
1741     }
1742     cl->i_activity_date = mdate();
1743
1744     /* XXX: for QT I have to disable timeout. Try to find why */
1745     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1746         cl->i_activity_timeout = 0;
1747
1748     /* Debugging only */
1749     /*if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1750     {
1751         int i;
1752
1753         fprintf( stderr, "received new request\n" );
1754         fprintf( stderr, "  - proto=%s\n",
1755                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1756         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1757         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1758         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1759         {
1760             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1761                      cl->query.psz_status );
1762         }
1763         else if( cl->query.i_type != HTTPD_MSG_NONE )
1764         {
1765             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1766         }
1767         for( i = 0; i < cl->query.i_name; i++ )
1768         {
1769             fprintf( stderr, "  - option name='%s' value='%s'\n",
1770                      cl->query.name[i], cl->query.value[i] );
1771         }
1772     }*/
1773 }
1774
1775
1776 static void httpd_ClientSend( httpd_client_t *cl )
1777 {
1778     int i;
1779     int i_len;
1780
1781     if( cl->i_buffer < 0 )
1782     {
1783         /* We need to create the header */
1784         int i_size = 0;
1785         char *p;
1786
1787         i_size = strlen( "HTTP/1.") + 10 + 10 +
1788                  strlen( cl->answer.psz_status ? cl->answer.psz_status : "" ) + 5;
1789         for( i = 0; i < cl->answer.i_name; i++ )
1790         {
1791             i_size += strlen( cl->answer.name[i] ) + 2 +
1792                       strlen( cl->answer.value[i] ) + 2;
1793         }
1794
1795         if( cl->i_buffer_size < i_size )
1796         {
1797             cl->i_buffer_size = i_size;
1798             free( cl->p_buffer );
1799             cl->p_buffer = malloc( i_size );
1800         }
1801         p = cl->p_buffer;
1802
1803         p += sprintf( p, "%s/1.%d %d %s\r\n",
1804                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP" : "RTSP",
1805                       cl->answer.i_version,
1806                       cl->answer.i_status, cl->answer.psz_status );
1807         for( i = 0; i < cl->answer.i_name; i++ )
1808         {
1809             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1810                           cl->answer.value[i] );
1811         }
1812         p += sprintf( p, "\r\n" );
1813
1814         cl->i_buffer = 0;
1815         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1816
1817         /*fprintf( stderr, "sending answer\n" );
1818         fprintf( stderr, "%s",  cl->p_buffer );*/
1819     }
1820
1821     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1822                            cl->i_buffer_size - cl->i_buffer );
1823     if( i_len > 0 )
1824     {
1825         cl->i_activity_date = mdate();
1826         cl->i_buffer += i_len;
1827
1828         if( cl->i_buffer >= cl->i_buffer_size )
1829         {
1830             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1831                 !cl->b_read_waiting )
1832             {
1833                 /* catch more body data */
1834                 int     i_msg = cl->query.i_type;
1835                 int64_t i_offset = cl->answer.i_body_offset;
1836
1837                 httpd_MsgClean( &cl->answer );
1838                 cl->answer.i_body_offset = i_offset;
1839
1840                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1841                                           &cl->answer, &cl->query );
1842             }
1843
1844             if( cl->answer.i_body > 0 )
1845             {
1846                 /* send the body data */
1847                 free( cl->p_buffer );
1848                 cl->p_buffer = cl->answer.p_body;
1849                 cl->i_buffer_size = cl->answer.i_body;
1850                 cl->i_buffer = 0;
1851
1852                 cl->answer.i_body = 0;
1853                 cl->answer.p_body = NULL;
1854             }
1855             else
1856             {
1857                 /* send finished */
1858                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1859             }
1860         }
1861     }
1862     else
1863     {
1864 #if defined( WIN32 ) || defined( UNDER_CE )
1865         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1866 #else
1867         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1868 #endif
1869         {
1870             /* error */
1871             cl->i_state = HTTPD_CLIENT_DEAD;
1872         }
1873     }
1874 }
1875
1876 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1877 {
1878     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1879     {
1880         case 0:
1881             cl->i_state = HTTPD_CLIENT_RECEIVING;
1882             break;
1883
1884         case -1:
1885             cl->i_state = HTTPD_CLIENT_DEAD;
1886             cl->p_tls = NULL;
1887             break;
1888
1889         case 2:
1890             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1891     }
1892 }
1893
1894 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1895 {
1896     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1897     {
1898         case 0:
1899             cl->i_state = HTTPD_CLIENT_RECEIVING;
1900             break;
1901
1902         case -1:
1903             cl->i_state = HTTPD_CLIENT_DEAD;
1904             cl->p_tls = NULL;
1905             break;
1906
1907         case 1:
1908             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
1909             break;
1910     }
1911 }
1912
1913 static void httpd_HostThread( httpd_host_t *host )
1914 {
1915     tls_session_t *p_tls = NULL;
1916
1917     while( !host->b_die )
1918     {
1919         struct timeval  timeout;
1920         fd_set          fds_read;
1921         fd_set          fds_write;
1922         /* FIXME: (too) many int variables */
1923         int             fd, i_fd;
1924         int             i_handle_max = 0;
1925         int             i_ret;
1926         int             i_client;
1927         int             b_low_delay = 0;
1928
1929         if( host->i_url <= 0 )
1930         {
1931             /* 0.2s */
1932             msleep( 200000 );
1933             continue;
1934         }
1935
1936         /* built a set of handle to select */
1937         FD_ZERO( &fds_read );
1938         FD_ZERO( &fds_write );
1939
1940         i_handle_max = -1;
1941
1942         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
1943         {
1944             FD_SET( fd, &fds_read );
1945             if( fd > i_handle_max )
1946                 i_handle_max = fd;
1947         }
1948
1949         /* prepare a new TLS session */
1950         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
1951             p_tls = tls_ServerSessionPrepare( host->p_tls );
1952
1953         /* add all socket that should be read/write and close dead connection */
1954         vlc_mutex_lock( &host->lock );
1955         for( i_client = 0; i_client < host->i_client; i_client++ )
1956         {
1957             httpd_client_t *cl = host->client[i_client];
1958
1959             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1960                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1961                   ( cl->i_activity_timeout > 0 &&
1962                     cl->i_activity_date+cl->i_activity_timeout < mdate()) ) ) )
1963             {
1964                 char *ip;
1965
1966                 // FIXME: it sucks to allocate memory on the stack for debug
1967                 ip = httpd_ClientIP( cl );
1968                 msg_Dbg( host, "connection closed(%s)",
1969                          (ip != NULL) ? ip : "unknown" );
1970                 free( ip );
1971
1972                 httpd_ClientClean( cl );
1973                 TAB_REMOVE( host->i_client, host->client, cl );
1974                 free( cl );
1975                 i_client--;
1976                 continue;
1977             }
1978             else if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
1979                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
1980             {
1981                 FD_SET( cl->fd, &fds_read );
1982                 i_handle_max = __MAX( i_handle_max, cl->fd );
1983             }
1984             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
1985                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
1986             {
1987                 FD_SET( cl->fd, &fds_write );
1988                 i_handle_max = __MAX( i_handle_max, cl->fd );
1989             }
1990             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1991             {
1992                 httpd_message_t *answer = &cl->answer;
1993                 httpd_message_t *query  = &cl->query;
1994                 int i_msg = query->i_type;
1995
1996                 httpd_MsgInit( answer );
1997
1998                 /* Handle what we received */
1999                 if( cl->i_mode != HTTPD_CLIENT_BIDIR &&
2000                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2001                 {
2002                     /* we can only receive request from client when not
2003                      * in BIDIR mode */
2004                     cl->url     = NULL;
2005                     cl->i_state = HTTPD_CLIENT_DEAD;
2006                 }
2007                 else if( i_msg == HTTPD_MSG_ANSWER )
2008                 {
2009                     /* We are in BIDIR mode, trigger the callback and then
2010                      * check for new data */
2011                     if( cl->url && cl->url->catch[i_msg].cb )
2012                     {
2013                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2014                                                   cl, NULL, query );
2015                     }
2016                     cl->i_state = HTTPD_CLIENT_WAITING;
2017                 }
2018                 else if( i_msg == HTTPD_MSG_CHANNEL )
2019                 {
2020                     /* We are in BIDIR mode, trigger the callback and then
2021                      * check for new data */
2022                     if( cl->url && cl->url->catch[i_msg].cb )
2023                     {
2024                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2025                                                   cl, NULL, query );
2026                     }
2027                     cl->i_state = HTTPD_CLIENT_WAITING;
2028                 }
2029                 else if( i_msg == HTTPD_MSG_OPTIONS )
2030                 {
2031                     int i_cseq;
2032
2033                     /* unimplemented */
2034                     answer->i_proto  = query->i_proto ;
2035                     answer->i_type   = HTTPD_MSG_ANSWER;
2036                     answer->i_version= 0;
2037                     answer->i_status = 200;
2038                     answer->psz_status = strdup( "Ok" );
2039
2040                     answer->i_body = 0;
2041                     answer->p_body = NULL;
2042
2043                     i_cseq = atoi( httpd_MsgGet( query, "Cseq" ) );
2044                     httpd_MsgAdd( answer, "Cseq", "%d", i_cseq );
2045                     httpd_MsgAdd( answer, "Server", "VLC Server" );
2046                     httpd_MsgAdd( answer, "Public", "DESCRIBE, SETUP, "
2047                                  "TEARDOWN, PLAY, PAUSE" );
2048                     httpd_MsgAdd( answer, "Content-Length", "%d",
2049                                   answer->i_body );
2050
2051                     cl->i_buffer = -1;  /* Force the creation of the answer in
2052                                          * httpd_ClientSend */
2053                     cl->i_state = HTTPD_CLIENT_SENDING;
2054                 }
2055                 else if( i_msg == HTTPD_MSG_NONE )
2056                 {
2057                     if( query->i_proto == HTTPD_PROTO_NONE )
2058                     {
2059                         cl->url = NULL;
2060                         cl->i_state = HTTPD_CLIENT_DEAD;
2061                     }
2062                     else
2063                     {
2064                         uint8_t *p;
2065
2066                         /* unimplemented */
2067                         answer->i_proto  = query->i_proto ;
2068                         answer->i_type   = HTTPD_MSG_ANSWER;
2069                         answer->i_version= 0;
2070                         answer->i_status = 501;
2071                         answer->psz_status = strdup( "Unimplemented" );
2072
2073                         p = answer->p_body = malloc( 1000 );
2074
2075                         p += sprintf( p, "<html>\n" );
2076                         p += sprintf( p, "<head>\n" );
2077                         p += sprintf( p, "<title>Error 501</title>\n" );
2078                         p += sprintf( p, "</head>\n" );
2079                         p += sprintf( p, "<body>\n" );
2080                         p += sprintf( p, "<h1><center> 501 Unimplemented</center></h1>\n" );
2081                         p += sprintf( p, "<hr />\n" );
2082                         p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2083                         p += sprintf( p, "</body>\n" );
2084                         p += sprintf( p, "</html>\n" );
2085
2086                         answer->i_body = p - answer->p_body;
2087                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2088
2089                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2090                         cl->i_state = HTTPD_CLIENT_SENDING;
2091                     }
2092                 }
2093                 else
2094                 {
2095                     vlc_bool_t b_auth_failed = VLC_FALSE;
2096                     vlc_bool_t b_hosts_failed = VLC_FALSE;
2097                     int i;
2098
2099                     /* Search the url and trigger callbacks */
2100                     for( i = 0; i < host->i_url; i++ )
2101                     {
2102                         httpd_url_t *url = host->url[i];
2103
2104                         if( !strcmp( url->psz_url, query->psz_url ) )
2105                         {
2106                             if( url->catch[i_msg].cb )
2107                             {
2108                                 if( answer && url->i_hosts )
2109                                 {
2110                                     char *ip = httpd_ClientIP( cl );
2111                                     if( ip != NULL )
2112                                     {
2113                                         if( net_CheckIP( host, ip,
2114                                                          url->ppsz_hosts,
2115                                                          url->i_hosts ) <= 0 )
2116                                         {
2117                                             b_hosts_failed = VLC_TRUE;
2118                                             free( ip );
2119                                             break;
2120                                         }
2121                                         free( ip );
2122                                     }
2123                                 }
2124
2125                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2126                                 {
2127                                     /* create the headers */
2128                                     char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2129                                     char *auth;
2130                                     char *id;
2131
2132                                     asprintf( &id, "%s:%s", url->psz_user, url->psz_password );
2133                                     auth = malloc( strlen(b64) + 1 );
2134
2135                                     if( !strncasecmp( b64, "BASIC", 5 ) )
2136                                     {
2137                                         b64 += 5;
2138                                         while( *b64 == ' ' )
2139                                         {
2140                                             b64++;
2141                                         }
2142                                         b64_decode( auth, b64 );
2143                                     }
2144                                     else
2145                                     {
2146                                         strcpy( auth, "" );
2147                                     }
2148                                     if( strcmp( id, auth ) )
2149                                     {
2150                                         httpd_MsgAdd( answer, "WWW-Authenticate", "Basic realm=\"%s\"", url->psz_user );
2151                                         /* We fail for all url */
2152                                         b_auth_failed = VLC_TRUE;
2153                                         free( id );
2154                                         free( auth );
2155                                         break;
2156                                     }
2157
2158                                     free( id );
2159                                     free( auth );
2160                                 }
2161
2162                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2163                                 {
2164                                     /* only one url can answer */
2165                                     answer = NULL;
2166                                     if( cl->url == NULL )
2167                                     {
2168                                         cl->url = url;
2169                                     }
2170                                 }
2171                             }
2172                         }
2173                     }
2174                     if( answer )
2175                     {
2176                         uint8_t *p;
2177
2178                         answer->i_proto  = query->i_proto;
2179                         answer->i_type   = HTTPD_MSG_ANSWER;
2180                         answer->i_version= 0;
2181                         p = answer->p_body = malloc( 1000 + strlen(query->psz_url) );
2182
2183                         if( b_hosts_failed )
2184                         {
2185                             answer->i_status = 403;
2186                             answer->psz_status = strdup( "Forbidden" );
2187
2188                             p += sprintf( p, "<html>\n" );
2189                             p += sprintf( p, "<head>\n" );
2190                             p += sprintf( p, "<title>Error 403</title>\n" );
2191                             p += sprintf( p, "</head>\n" );
2192                             p += sprintf( p, "<body>\n" );
2193                             p += sprintf( p, "<h1><center> 403 Forbidden (%s)</center></h1>\n", query->psz_url );
2194                             p += sprintf( p, "<hr />\n" );
2195                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2196                             p += sprintf( p, "</body>\n" );
2197                             p += sprintf( p, "</html>\n" );
2198                         }
2199                         else if( b_auth_failed )
2200                         {
2201                             answer->i_status = 401;
2202                             answer->psz_status = strdup( "Authorization Required" );
2203
2204                             p += sprintf( p, "<html>\n" );
2205                             p += sprintf( p, "<head>\n" );
2206                             p += sprintf( p, "<title>Error 401</title>\n" );
2207                             p += sprintf( p, "</head>\n" );
2208                             p += sprintf( p, "<body>\n" );
2209                             p += sprintf( p, "<h1><center> 401 Authorization Required (%s)</center></h1>\n", query->psz_url );
2210                             p += sprintf( p, "<hr />\n" );
2211                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2212                             p += sprintf( p, "</body>\n" );
2213                             p += sprintf( p, "</html>\n" );
2214                         }
2215                         else
2216                         {
2217                             /* no url registered */
2218                             answer->i_status = 404;
2219                             answer->psz_status = strdup( "Not found" );
2220
2221                             p += sprintf( p, "<html>\n" );
2222                             p += sprintf( p, "<head>\n" );
2223                             p += sprintf( p, "<title>Error 404</title>\n" );
2224                             p += sprintf( p, "</head>\n" );
2225                             p += sprintf( p, "<body>\n" );
2226                             p += sprintf( p, "<h1><center> 404 Resource not found(%s)</center></h1>\n", query->psz_url );
2227                             p += sprintf( p, "<hr />\n" );
2228                             p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
2229                             p += sprintf( p, "</body>\n" );
2230                             p += sprintf( p, "</html>\n" );
2231                         }
2232
2233                         answer->i_body = p - answer->p_body;
2234                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2235                     }
2236                     cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2237                     cl->i_state = HTTPD_CLIENT_SENDING;
2238                 }
2239             }
2240             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2241             {
2242                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2243                 {
2244                     cl->url = NULL;
2245                     if( ( cl->query.i_proto == HTTPD_PROTO_HTTP &&
2246                           ( ( cl->answer.i_version == 0 && !strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Keep-Alive" ) ) ||
2247                             ( cl->answer.i_version == 1 &&  strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) ) ) ||
2248                         ( cl->query.i_proto == HTTPD_PROTO_RTSP &&
2249                           strcasecmp( httpd_MsgGet( &cl->query, "Connection" ), "Close" ) &&
2250                           strcasecmp( httpd_MsgGet( &cl->answer, "Connection" ), "Close" ) ) )
2251                     {
2252                         httpd_MsgClean( &cl->query );
2253                         httpd_MsgInit( &cl->query );
2254
2255                         cl->i_buffer = 0;
2256                         cl->i_buffer_size = 1000;
2257                         free( cl->p_buffer );
2258                         cl->p_buffer = malloc( cl->i_buffer_size );
2259                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2260                     }
2261                     else
2262                     {
2263                         cl->i_state = HTTPD_CLIENT_DEAD;
2264                     }
2265                     httpd_MsgClean( &cl->answer );
2266                 }
2267                 else if( cl->b_read_waiting )
2268                 {
2269                     /* we have a message waiting for us to read it */
2270                     httpd_MsgClean( &cl->answer );
2271                     httpd_MsgClean( &cl->query );
2272
2273                     cl->i_buffer = 0;
2274                     cl->i_buffer_size = 1000;
2275                     free( cl->p_buffer );
2276                     cl->p_buffer = malloc( cl->i_buffer_size );
2277                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2278                     cl->b_read_waiting = VLC_FALSE;
2279                 }
2280                 else
2281                 {
2282                     int64_t i_offset = cl->answer.i_body_offset;
2283                     httpd_MsgClean( &cl->answer );
2284
2285                     cl->answer.i_body_offset = i_offset;
2286                     free( cl->p_buffer );
2287                     cl->p_buffer = NULL;
2288                     cl->i_buffer = 0;
2289                     cl->i_buffer_size = 0;
2290
2291                     cl->i_state = HTTPD_CLIENT_WAITING;
2292                 }
2293             }
2294             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2295             {
2296                 int64_t i_offset = cl->answer.i_body_offset;
2297                 int     i_msg = cl->query.i_type;
2298
2299                 httpd_MsgInit( &cl->answer );
2300                 cl->answer.i_body_offset = i_offset;
2301
2302                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2303                                           &cl->answer, &cl->query );
2304                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2305                 {
2306                     /* we have new data, so reenter send mode */
2307                     cl->i_buffer      = 0;
2308                     cl->p_buffer      = cl->answer.p_body;
2309                     cl->i_buffer_size = cl->answer.i_body;
2310                     cl->answer.p_body = NULL;
2311                     cl->answer.i_body = 0;
2312                     cl->i_state = HTTPD_CLIENT_SENDING;
2313                 }
2314                 else
2315                 {
2316                     /* we shouldn't wait too long */
2317                     b_low_delay = VLC_TRUE;
2318                 }
2319             }
2320
2321             /* Special for BIDIR mode we also check reading */
2322             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2323                 cl->i_state == HTTPD_CLIENT_SENDING )
2324             {
2325                 FD_SET( cl->fd, &fds_read );
2326                 i_handle_max = __MAX( i_handle_max, cl->fd );
2327             }
2328         }
2329         vlc_mutex_unlock( &host->lock );
2330
2331         /* we will wait 100ms or 20ms (not too big 'cause HTTPD_CLIENT_WAITING) */
2332         timeout.tv_sec = 0;
2333         timeout.tv_usec = b_low_delay ? 20000 : 100000;
2334
2335         i_ret = select( i_handle_max + 1,
2336                         &fds_read, &fds_write, NULL, &timeout );
2337
2338         if( i_ret == -1 && errno != EINTR )
2339         {
2340             msg_Warn( host, "cannot select sockets" );
2341             msleep( 1000 );
2342             continue;
2343         }
2344         else if( i_ret <= 0 )
2345         {
2346             continue;
2347         }
2348
2349         /* accept new connections */
2350         for( i_fd = 0; (fd = host->fd[i_fd]) != -1; i_fd++ )
2351         {
2352             if( FD_ISSET( fd, &fds_read ) )
2353             {
2354                 int     i_sock_size = sizeof( struct sockaddr_storage );
2355                 struct  sockaddr_storage sock;
2356     
2357                 fd = accept( fd, (struct sockaddr *)&sock, &i_sock_size );
2358                 if( fd >= 0 )
2359                 {
2360                     int i_state = 0;
2361     
2362                     /* set this new socket non-block */
2363     #if defined( WIN32 ) || defined( UNDER_CE )
2364                     {
2365                         unsigned long i_dummy = 1;
2366                         ioctlsocket( fd, FIONBIO, &i_dummy );
2367                     }
2368     #else
2369                     fcntl( fd, F_SETFL, O_NONBLOCK );
2370     #endif
2371     
2372                     if( p_tls != NULL)
2373                     {
2374                         switch ( tls_ServerSessionHandshake( p_tls, fd ) )
2375                         {
2376                             case -1:
2377                                 msg_Err( host, "Rejecting TLS connection" );
2378                                 net_Close( fd );
2379                                 fd = -1;
2380                                 p_tls = NULL;
2381                                 break;
2382     
2383                             case 1: /* missing input - most likely */
2384                                 i_state = HTTPD_CLIENT_TLS_HS_IN;
2385                                 break;
2386     
2387                             case 2: /* missing output */
2388                                 i_state = HTTPD_CLIENT_TLS_HS_OUT;
2389                                 break;
2390                         }
2391                     }
2392                     
2393                     if( fd >= 0 )
2394                     {
2395                         char *ip;
2396                         httpd_client_t *cl;
2397     
2398                         cl = httpd_ClientNew( fd, &sock, i_sock_size, p_tls );
2399                         p_tls = NULL;
2400                         vlc_mutex_lock( &host->lock );
2401                         TAB_APPEND( host->i_client, host->client, cl );
2402                         vlc_mutex_unlock( &host->lock );
2403     
2404                         if( i_state != 0 )
2405                             cl->i_state = i_state; // override state for TLS
2406     
2407                         // FIXME: it sucks to allocate memory for debug
2408                         ip = httpd_ClientIP( cl );
2409                         msg_Dbg( host, "new connection (%s)",
2410                                 ip != NULL ? ip : "unknown" );
2411                         if( ip != NULL )
2412                             free( ip );
2413                     }
2414                 }
2415             }
2416         }
2417
2418         /* now try all others socket */
2419         vlc_mutex_lock( &host->lock );
2420         for( i_client = 0; i_client < host->i_client; i_client++ )
2421         {
2422             httpd_client_t *cl = host->client[i_client];
2423             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2424             {
2425                 httpd_ClientRecv( cl );
2426             }
2427             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2428             {
2429                 httpd_ClientSend( cl );
2430             }
2431             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2432             {
2433                 httpd_ClientTlsHsIn( cl );
2434             }
2435             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2436             {
2437                 httpd_ClientTlsHsOut( cl );
2438             }
2439
2440             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2441                 cl->i_state == HTTPD_CLIENT_SENDING &&
2442                 FD_ISSET( cl->fd, &fds_read ) )
2443             {
2444                 cl->b_read_waiting = VLC_TRUE;
2445             }
2446         }
2447         vlc_mutex_unlock( &host->lock );
2448     }
2449
2450     if( p_tls != NULL )
2451         tls_ServerSessionClose( p_tls );
2452 }
2453
2454 #else /* ENABLE_HTTPD */
2455
2456 /* We just define an empty wrapper */
2457 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2458                                 tls_server_t *d )
2459 {
2460     msg_Err( a, "HTTP daemon support is disabled" );
2461     return 0;
2462 }
2463 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2464 {
2465     msg_Err( a, "HTTP daemon support is disabled" );
2466     return 0;
2467 }
2468 void httpd_HostDelete( httpd_host_t *a ){}
2469 httpd_url_t *httpd_UrlNew( httpd_host_t *a, char *b ){ return 0; }
2470 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *a, char *b, char *c,
2471                                  char *d ){ return 0; }
2472 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2473                     httpd_callback_sys_t *d ){ return 0; }
2474 void httpd_UrlDelete( httpd_url_t *a ){}
2475
2476 char *httpd_ClientIP( httpd_client_t *a ){ return 0; }
2477 void httpd_ClientModeStream( httpd_client_t *a ){}
2478 void httpd_ClientModeBidir( httpd_client_t *a ){}
2479
2480 void httpd_FileDelete( httpd_file_t *a ){}
2481 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2482                              char *e, httpd_file_callback_t f,
2483                              httpd_file_sys_t *g ){ return 0; }
2484
2485 void httpd_RedirectDelete( httpd_redirect_t *a ){}
2486 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2487                                      char *b, char *c ){ return 0; }
2488
2489 void httpd_StreamDelete( httpd_stream_t *a ){}
2490 int  httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2491 int  httpd_StreamSend  ( httpd_stream_t *a, uint8_t *b, int c ){ return 0; }
2492 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2493                                  char *d, char *e ){ return 0; }
2494
2495 void httpd_MsgInit ( httpd_message_t *a ){}
2496 void httpd_MsgAdd  ( httpd_message_t *a, char *b, char *c, ... ){}
2497 char *httpd_MsgGet ( httpd_message_t *a, char *b ){ return 0; }
2498 void httpd_MsgClean( httpd_message_t *a ){}
2499
2500 #endif /* ENABLE_HTTPD */