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