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