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