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