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