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