]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Move core Win32 files to their own directory
[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 "../libvlc.h"
40
41 #include <string.h>
42 #include <errno.h>
43
44 #ifdef HAVE_UNISTD_H
45 #   include <unistd.h>
46 #endif
47
48 #ifdef HAVE_POLL
49 # include <poll.h>
50 #endif
51
52 #if defined( UNDER_CE )
53 #   include <winsock.h>
54 #elif defined( WIN32 )
55 #   include <winsock2.h>
56 #else
57 #   include <sys/socket.h>
58 #endif
59
60 #if defined( WIN32 )
61 /* We need HUGE buffer otherwise TCP throughput is very limited */
62 #define HTTPD_CL_BUFSIZE 1000000
63 #else
64 #define HTTPD_CL_BUFSIZE 10000
65 #endif
66
67 static void httpd_ClientClean( httpd_client_t *cl );
68
69 struct httpd_t
70 {
71     VLC_COMMON_MEMBERS
72
73     int          i_host;
74     httpd_host_t **host;
75 };
76
77
78 /* each host run in his own thread */
79 struct httpd_host_t
80 {
81     VLC_COMMON_MEMBERS
82
83     httpd_t     *httpd;
84
85     /* ref count */
86     unsigned    i_ref;
87
88     /* address/port and socket for listening at connections */
89     char        *psz_hostname;
90     int         i_port;
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     tls_server_t *p_tls;
110 };
111
112
113 struct httpd_url_t
114 {
115     httpd_host_t *host;
116
117     vlc_mutex_t lock;
118
119     char      *psz_url;
120     char      *psz_user;
121     char      *psz_password;
122     vlc_acl_t *p_acl;
123
124     struct
125     {
126         httpd_callback_t     cb;
127         httpd_callback_sys_t *p_sys;
128     } catch[HTTPD_MSG_MAX];
129 };
130
131 /* status */
132 enum
133 {
134     HTTPD_CLIENT_RECEIVING,
135     HTTPD_CLIENT_RECEIVE_DONE,
136
137     HTTPD_CLIENT_SENDING,
138     HTTPD_CLIENT_SEND_DONE,
139
140     HTTPD_CLIENT_WAITING,
141
142     HTTPD_CLIENT_DEAD,
143
144     HTTPD_CLIENT_TLS_HS_IN,
145     HTTPD_CLIENT_TLS_HS_OUT
146 };
147
148 /* mode */
149 enum
150 {
151     HTTPD_CLIENT_FILE,      /* default */
152     HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
153     HTTPD_CLIENT_BIDIR,     /* check for reading and get data from cb */
154 };
155
156 struct httpd_client_t
157 {
158     httpd_url_t *url;
159
160     int     i_ref;
161
162     int     fd;
163
164     int     i_mode;
165     int     i_state;
166     int     b_read_waiting; /* stop as soon as possible sending */
167
168     mtime_t i_activity_date;
169     mtime_t i_activity_timeout;
170
171     /* buffer for reading header */
172     int     i_buffer_size;
173     int     i_buffer;
174     uint8_t *p_buffer;
175
176     /* */
177     httpd_message_t query;  /* client -> httpd */
178     httpd_message_t answer; /* httpd -> client */
179
180     /* TLS data */
181     tls_session_t *p_tls;
182 };
183
184
185 /*****************************************************************************
186  * Various functions
187  *****************************************************************************/
188 static 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 )
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=%d", rand()&0x7fff );
829             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
830
831             /* Check if there is a xPlayStrm=1 */
832             for( i = 0; i < query->i_name; i++ )
833             {
834                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
835                     strstr( query->value[i], "xPlayStrm=1" ) )
836                 {
837                     b_xplaystream = true;
838                 }
839             }
840
841             if( !b_xplaystream )
842             {
843                 answer->i_body_offset = 0;
844             }
845         }
846         else
847         {
848             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
849         }
850         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
851         return VLC_SUCCESS;
852     }
853 }
854
855 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
856                                  const char *psz_url, const char *psz_mime,
857                                  const char *psz_user, const char *psz_password,
858                                  const vlc_acl_t *p_acl )
859 {
860     httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
861
862     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
863                                             psz_password, p_acl )
864         ) == NULL )
865     {
866         free( stream );
867         return NULL;
868     }
869     vlc_mutex_init( &stream->lock );
870     if( psz_mime && *psz_mime )
871     {
872         stream->psz_mime = strdup( psz_mime );
873     }
874     else
875     {
876         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
877     }
878     stream->i_header = 0;
879     stream->p_header = NULL;
880     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
881     stream->p_buffer = xmalloc( stream->i_buffer_size );
882     /* We set to 1 to make life simpler
883      * (this way i_body_offset can never be 0) */
884     stream->i_buffer_pos = 1;
885     stream->i_buffer_last_pos = 1;
886
887     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
888                     (httpd_callback_sys_t*)stream );
889     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
890                     (httpd_callback_sys_t*)stream );
891     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
892                     (httpd_callback_sys_t*)stream );
893
894     return stream;
895 }
896
897 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
898 {
899     vlc_mutex_lock( &stream->lock );
900     free( stream->p_header );
901     stream->p_header = NULL;
902
903     stream->i_header = i_data;
904     if( i_data > 0 )
905     {
906         stream->p_header = xmalloc( i_data );
907         memcpy( stream->p_header, p_data, i_data );
908     }
909     vlc_mutex_unlock( &stream->lock );
910
911     return VLC_SUCCESS;
912 }
913
914 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
915 {
916     int i_count;
917     int i_pos;
918
919     if( i_data < 0 || p_data == NULL )
920     {
921         return VLC_SUCCESS;
922     }
923     vlc_mutex_lock( &stream->lock );
924
925     /* save this pointer (to be used by new connection) */
926     stream->i_buffer_last_pos = stream->i_buffer_pos;
927
928     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
929     i_count = i_data;
930     while( i_count > 0)
931     {
932         int i_copy;
933
934         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
935
936         /* Ok, we can't go past the end of our buffer */
937         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
938
939         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
940         i_count -= i_copy;
941         p_data  += i_copy;
942     }
943
944     stream->i_buffer_pos += i_data;
945
946     vlc_mutex_unlock( &stream->lock );
947     return VLC_SUCCESS;
948 }
949
950 void httpd_StreamDelete( httpd_stream_t *stream )
951 {
952     httpd_UrlDelete( stream->url );
953     vlc_mutex_destroy( &stream->lock );
954     free( stream->psz_mime );
955     free( stream->p_header );
956     free( stream->p_buffer );
957     free( stream );
958 }
959
960 /*****************************************************************************
961  * Low level
962  *****************************************************************************/
963 static void* httpd_HostThread( void * );
964
965 /* create a new host */
966 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
967                              int i_port )
968 {
969     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
970                            );
971 }
972
973 static const char psz_object_type[] = "http server";
974 static vlc_mutex_t httpd_mutex = VLC_STATIC_MUTEX;
975
976 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
977                                 int i_port,
978                                 const char *psz_cert, const char *psz_key,
979                                 const char *psz_ca, const char *psz_crl )
980 {
981     httpd_t      *httpd;
982     httpd_host_t *host;
983     tls_server_t *p_tls;
984     char *psz_host;
985     vlc_value_t  ptrval;
986     int i;
987
988     if( psz_hostname == NULL )
989         psz_hostname = "";
990
991     psz_host = strdup( psz_hostname );
992     if( psz_host == NULL )
993         return NULL;
994
995     /* to be sure to avoid multiple creation */
996     vlc_mutex_lock( &httpd_mutex );
997     httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
998
999     if( httpd == NULL )
1000     {
1001         msg_Info( p_this, "creating httpd" );
1002         httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1003                                               VLC_OBJECT_GENERIC,
1004                                               psz_object_type );
1005         if( httpd == NULL )
1006         {
1007             vlc_mutex_unlock( &httpd_mutex );
1008             free( psz_host );
1009             return NULL;
1010         }
1011
1012         httpd->i_host = 0;
1013         httpd->host   = NULL;
1014
1015         ptrval.p_address = httpd;
1016         libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1017         vlc_object_attach( httpd, p_this->p_libvlc );
1018     }
1019
1020     /* verify if it already exist */
1021     for( i = httpd->i_host - 1; i >= 0; i-- )
1022     {
1023         host = httpd->host[i];
1024
1025         /* cannot mix TLS and non-TLS hosts */
1026         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1027          || ( host->i_port != i_port )
1028          || strcmp( host->psz_hostname, psz_hostname ) )
1029             continue;
1030
1031         /* Increase existing matching host reference count.
1032          * The reference count is written under both the global httpd and the
1033          * host lock. It is read with either or both locks held. The global
1034          * lock is always acquired first. */
1035         vlc_mutex_lock( &host->lock );
1036         host->i_ref++;
1037         vlc_mutex_unlock( &host->lock );
1038
1039         vlc_mutex_unlock( &httpd_mutex );
1040         return host;
1041     }
1042
1043     host = NULL;
1044
1045     /* determine TLS configuration */
1046     if ( psz_cert != NULL )
1047     {
1048         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1049         if ( p_tls == NULL )
1050         {
1051             msg_Err( p_this, "TLS initialization error" );
1052             goto error;
1053         }
1054
1055         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1056         {
1057             msg_Err( p_this, "TLS CA error" );
1058             goto error;
1059         }
1060
1061         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1062         {
1063             msg_Err( p_this, "TLS CRL error" );
1064             goto error;
1065         }
1066     }
1067     else
1068         p_tls = NULL;
1069
1070     /* create the new host */
1071     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1072                                               VLC_OBJECT_GENERIC,
1073                                               psz_object_type );
1074     if (host == NULL)
1075         goto error;
1076
1077     host->httpd = httpd;
1078     vlc_mutex_init( &host->lock );
1079     vlc_cond_init( &host->wait );
1080     host->i_ref = 1;
1081
1082     host->fds = net_ListenTCP( p_this, psz_host, i_port );
1083     if( host->fds == NULL )
1084     {
1085         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1086         goto error;
1087     }
1088     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1089
1090     if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1091     {
1092         msg_Err( host, "signaling pipe error: %m" );
1093         goto error;
1094     }
1095
1096     host->i_port = i_port;
1097     host->psz_hostname = psz_host;
1098
1099     host->i_url     = 0;
1100     host->url       = NULL;
1101     host->i_client  = 0;
1102     host->client    = NULL;
1103
1104     host->p_tls = p_tls;
1105
1106     /* create the thread */
1107     if( vlc_clone( &host->thread, httpd_HostThread, host,
1108                    VLC_THREAD_PRIORITY_LOW ) )
1109     {
1110         msg_Err( p_this, "cannot spawn http host thread" );
1111         goto error;
1112     }
1113
1114     /* now add it to httpd */
1115     TAB_APPEND( httpd->i_host, httpd->host, host );
1116     vlc_mutex_unlock( &httpd_mutex );
1117
1118     return host;
1119
1120 error:
1121     free( psz_host );
1122     if( httpd->i_host <= 0 )
1123     {
1124         libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1125         vlc_object_detach( httpd );
1126         vlc_object_release( httpd );
1127     }
1128     vlc_mutex_unlock( &httpd_mutex );
1129
1130     if( host != NULL )
1131     {
1132         net_ListenClose( host->fds );
1133         vlc_cond_destroy( &host->wait );
1134         vlc_mutex_destroy( &host->lock );
1135         vlc_object_release( host );
1136     }
1137
1138     if( p_tls != NULL )
1139         tls_ServerDelete( p_tls );
1140
1141     return NULL;
1142 }
1143
1144 /* delete a host */
1145 void httpd_HostDelete( httpd_host_t *host )
1146 {
1147     httpd_t *httpd = host->httpd;
1148     int i;
1149     bool delete = false;
1150
1151     vlc_mutex_lock( &httpd_mutex );
1152
1153     vlc_mutex_lock( &host->lock );
1154     host->i_ref--;
1155     if( host->i_ref == 0 )
1156     {
1157         vlc_cond_signal( &host->wait );
1158         delete = true;
1159     }
1160     vlc_mutex_unlock( &host->lock );
1161     if( !delete )
1162     {
1163         /* still used */
1164         vlc_mutex_unlock( &httpd_mutex );
1165         msg_Dbg( host, "httpd_HostDelete: host still in use" );
1166         return;
1167     }
1168     TAB_REMOVE( httpd->i_host, httpd->host, host );
1169
1170     vlc_object_kill( host );
1171     vlc_join( host->thread, NULL );
1172
1173     msg_Dbg( host, "HTTP host removed" );
1174
1175     for( i = 0; i < host->i_url; i++ )
1176     {
1177         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1178     }
1179     for( i = 0; i < host->i_client; i++ )
1180     {
1181         httpd_client_t *cl = host->client[i];
1182         msg_Warn( host, "client still connected" );
1183         httpd_ClientClean( cl );
1184         TAB_REMOVE( host->i_client, host->client, cl );
1185         free( cl );
1186         i--;
1187         /* TODO */
1188     }
1189
1190     if( host->p_tls != NULL)
1191         tls_ServerDelete( host->p_tls );
1192
1193     net_ListenClose( host->fds );
1194     free( host->psz_hostname );
1195
1196     vlc_cond_destroy( &host->wait );
1197     vlc_mutex_destroy( &host->lock );
1198     vlc_object_release( host );
1199
1200     if( httpd->i_host <= 0 )
1201     {
1202         msg_Dbg( httpd, "no hosts left, stopping httpd" );
1203
1204         libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1205         vlc_object_detach( httpd );
1206         vlc_object_release( httpd );
1207     }
1208     vlc_mutex_unlock( &httpd_mutex );
1209 }
1210
1211 /* register a new url */
1212 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1213                                          const char *psz_user, const char *psz_password,
1214                                          const vlc_acl_t *p_acl, bool b_check )
1215 {
1216     httpd_url_t *url;
1217     int         i;
1218
1219     assert( psz_url != NULL );
1220
1221     vlc_mutex_lock( &host->lock );
1222     if( b_check )
1223     {
1224         for( i = 0; i < host->i_url; i++ )
1225         {
1226             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1227             {
1228                 msg_Warn( host->httpd,
1229                           "cannot add '%s' (url already defined)", psz_url );
1230                 vlc_mutex_unlock( &host->lock );
1231                 return NULL;
1232             }
1233         }
1234     }
1235
1236     url = xmalloc( sizeof( httpd_url_t ) );
1237     url->host = host;
1238
1239     vlc_mutex_init( &url->lock );
1240     url->psz_url = strdup( psz_url );
1241     url->psz_user = strdup( psz_user ? psz_user : "" );
1242     url->psz_password = strdup( psz_password ? psz_password : "" );
1243     url->p_acl = ACL_Duplicate( host, p_acl );
1244     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1245     {
1246         url->catch[i].cb = NULL;
1247         url->catch[i].p_sys = NULL;
1248     }
1249
1250     TAB_APPEND( host->i_url, host->url, url );
1251     vlc_cond_signal( &host->wait );
1252     vlc_mutex_unlock( &host->lock );
1253
1254     return url;
1255 }
1256
1257 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1258                            const char *psz_user, const char *psz_password,
1259                            const vlc_acl_t *p_acl )
1260 {
1261     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1262                                 psz_password, p_acl, false );
1263 }
1264
1265 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1266                                  const char *psz_user, const char *psz_password,
1267                                  const vlc_acl_t *p_acl )
1268 {
1269     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1270                                 psz_password, p_acl, true );
1271 }
1272
1273 /* register callback on a url */
1274 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1275                     httpd_callback_sys_t *p_sys )
1276 {
1277     vlc_mutex_lock( &url->lock );
1278     url->catch[i_msg].cb   = cb;
1279     url->catch[i_msg].p_sys= p_sys;
1280     vlc_mutex_unlock( &url->lock );
1281
1282     return VLC_SUCCESS;
1283 }
1284
1285 /* delete an url */
1286 void httpd_UrlDelete( httpd_url_t *url )
1287 {
1288     httpd_host_t *host = url->host;
1289     int          i;
1290
1291     vlc_mutex_lock( &host->lock );
1292     TAB_REMOVE( host->i_url, host->url, url );
1293
1294     vlc_mutex_destroy( &url->lock );
1295     free( url->psz_url );
1296     free( url->psz_user );
1297     free( url->psz_password );
1298     ACL_Destroy( url->p_acl );
1299
1300     for( i = 0; i < host->i_client; i++ )
1301     {
1302         httpd_client_t *client = host->client[i];
1303
1304         if( client->url == url )
1305         {
1306             /* TODO complete it */
1307             msg_Warn( host, "force closing connections" );
1308             httpd_ClientClean( client );
1309             TAB_REMOVE( host->i_client, host->client, client );
1310             free( client );
1311             i--;
1312         }
1313     }
1314     free( url );
1315     vlc_mutex_unlock( &host->lock );
1316 }
1317
1318 static void httpd_MsgInit( httpd_message_t *msg )
1319 {
1320     msg->cl         = NULL;
1321     msg->i_type     = HTTPD_MSG_NONE;
1322     msg->i_proto    = HTTPD_PROTO_NONE;
1323     msg->i_version  = -1; /* FIXME */
1324
1325     msg->i_status   = 0;
1326
1327     msg->psz_url    = NULL;
1328     msg->psz_args   = NULL;
1329
1330     msg->i_channel  = -1;
1331
1332     msg->i_name     = 0;
1333     msg->name       = NULL;
1334     msg->i_value    = 0;
1335     msg->value      = NULL;
1336
1337     msg->i_body_offset = 0;
1338     msg->i_body        = 0;
1339     msg->p_body        = NULL;
1340 }
1341
1342 static void httpd_MsgClean( httpd_message_t *msg )
1343 {
1344     int i;
1345
1346     free( msg->psz_url );
1347     free( msg->psz_args );
1348     for( i = 0; i < msg->i_name; i++ )
1349     {
1350         free( msg->name[i] );
1351         free( msg->value[i] );
1352     }
1353     free( msg->name );
1354     free( msg->value );
1355     free( msg->p_body );
1356     httpd_MsgInit( msg );
1357 }
1358
1359 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1360 {
1361     int i;
1362
1363     for( i = 0; i < msg->i_name; i++ )
1364     {
1365         if( !strcasecmp( msg->name[i], name ))
1366         {
1367             return msg->value[i];
1368         }
1369     }
1370     return NULL;
1371 }
1372
1373 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1374 {
1375     va_list args;
1376     char *value = NULL;
1377
1378     va_start( args, psz_value );
1379     if( vasprintf( &value, psz_value, args ) == -1 )
1380         value = NULL;
1381     va_end( args );
1382
1383     if( value == NULL )
1384         return;
1385
1386     name = strdup( name );
1387     if( name == NULL )
1388     {
1389         free( value );
1390         return;
1391     }
1392
1393     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1394     TAB_APPEND( msg->i_value, msg->value, value );
1395 }
1396
1397 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1398 {
1399     cl->i_state = HTTPD_CLIENT_RECEIVING;
1400     cl->i_activity_date = now;
1401     cl->i_activity_timeout = INT64_C(10000000);
1402     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1403     cl->i_buffer = 0;
1404     cl->p_buffer = xmalloc( cl->i_buffer_size );
1405     cl->i_mode   = HTTPD_CLIENT_FILE;
1406     cl->b_read_waiting = false;
1407
1408     httpd_MsgInit( &cl->query );
1409     httpd_MsgInit( &cl->answer );
1410 }
1411
1412 void httpd_ClientModeStream( httpd_client_t *cl )
1413 {
1414     cl->i_mode   = HTTPD_CLIENT_STREAM;
1415 }
1416
1417 void httpd_ClientModeBidir( httpd_client_t *cl )
1418 {
1419     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1420 }
1421
1422 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1423 {
1424     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1425 }
1426
1427 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1428 {
1429     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1430 }
1431
1432 static void httpd_ClientClean( httpd_client_t *cl )
1433 {
1434     if( cl->fd >= 0 )
1435     {
1436         if( cl->p_tls != NULL )
1437             tls_ServerSessionClose( cl->p_tls );
1438         net_Close( cl->fd );
1439         cl->fd = -1;
1440     }
1441
1442     httpd_MsgClean( &cl->answer );
1443     httpd_MsgClean( &cl->query );
1444
1445     free( cl->p_buffer );
1446     cl->p_buffer = NULL;
1447 }
1448
1449 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1450 {
1451     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1452
1453     if( !cl ) return NULL;
1454
1455     cl->i_ref   = 0;
1456     cl->fd      = fd;
1457     cl->url     = NULL;
1458     cl->p_tls = p_tls;
1459
1460     httpd_ClientInit( cl, now );
1461
1462     return cl;
1463 }
1464
1465 static
1466 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1467 {
1468     tls_session_t *p_tls;
1469     ssize_t val;
1470
1471     p_tls = cl->p_tls;
1472     do
1473         val = p_tls ? tls_Recv (p_tls, p, i_len)
1474                     : recv (cl->fd, p, i_len, 0);
1475     while (val == -1 && errno == EINTR);
1476     return val;
1477 }
1478
1479 static
1480 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1481 {
1482     tls_session_t *p_tls;
1483     ssize_t val;
1484
1485     p_tls = cl->p_tls;
1486     do
1487         val = p_tls ? tls_Send( p_tls, p, i_len )
1488                     : send (cl->fd, p, i_len, 0);
1489     while (val == -1 && errno == EINTR);
1490     return val;
1491 }
1492
1493
1494 static const struct
1495 {
1496     const char name[16];
1497     int  i_type;
1498     int  i_proto;
1499 }
1500 msg_type[] =
1501 {
1502     { "OPTIONS",       HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1503     { "DESCRIBE",      HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1504     { "SETUP",         HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1505     { "PLAY",          HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1506     { "PAUSE",         HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1507     { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1508     { "TEARDOWN",      HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1509     { "GET",           HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1510     { "HEAD",          HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1511     { "POST",          HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1512     { "",              HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1513 };
1514
1515
1516 static void httpd_ClientRecv( httpd_client_t *cl )
1517 {
1518     int i_len;
1519
1520     /* ignore leading whites */
1521     if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1522         ( cl->i_buffer == 0 ) )
1523     {
1524         unsigned char c;
1525
1526         i_len = httpd_NetRecv( cl, &c, 1 );
1527
1528         if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1529         {
1530             cl->p_buffer[0] = c;
1531             cl->i_buffer++;
1532         }
1533     }
1534     else
1535     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1536     {
1537         /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1538         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1539                                7 - cl->i_buffer );
1540         if( i_len > 0 )
1541         {
1542             cl->i_buffer += i_len;
1543         }
1544
1545         if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1546         {
1547             /* Interleaved RTP over RTSP */
1548             cl->query.i_proto = HTTPD_PROTO_RTSP;
1549             cl->query.i_type  = HTTPD_MSG_CHANNEL;
1550             cl->query.i_channel = cl->p_buffer[1];
1551             cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1552             cl->query.p_body  = xmalloc( cl->query.i_body );
1553             cl->i_buffer      -= 4;
1554             memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1555         }
1556         else
1557         /* The smallest legal request is 7 bytes ("GET /\r\n"),
1558          * this is the maximum we can ask at this point. */
1559         if( cl->i_buffer >= 7 )
1560         {
1561             if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1562             {
1563                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1564                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1565             }
1566             else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1567             {
1568                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1569                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1570             }
1571             else
1572             {
1573                 /* We need the full request line to determine the protocol. */
1574                 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1575                 cl->query.i_type  = HTTPD_MSG_NONE;
1576             }
1577         }
1578     }
1579     else if( cl->query.i_body > 0 )
1580     {
1581         /* we are reading the body of a request or a channel */
1582         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1583                                cl->query.i_body - cl->i_buffer );
1584         if( i_len > 0 )
1585         {
1586             cl->i_buffer += i_len;
1587         }
1588         if( cl->i_buffer >= cl->query.i_body )
1589         {
1590             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1591         }
1592     }
1593     else
1594     {
1595         /* we are reading a header -> char by char */
1596         for( ;; )
1597         {
1598             if( cl->i_buffer == cl->i_buffer_size )
1599             {
1600                 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1601                 if( newbuf == NULL )
1602                 {
1603                     i_len = 0;
1604                     break;
1605                 }
1606
1607                 cl->p_buffer = newbuf;
1608                 cl->i_buffer_size += 1024;
1609             }
1610
1611             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1612             if( i_len <= 0 )
1613             {
1614                 break;
1615             }
1616             cl->i_buffer++;
1617
1618             if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1619              && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1620             {
1621                 /* Request line is now complete */
1622                 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1623                 size_t len;
1624
1625                 assert( cl->query.i_type == HTTPD_MSG_NONE );
1626
1627                 if( p == NULL ) /* no URI: evil guy */
1628                 {
1629                     i_len = 0; /* drop connection */
1630                     break;
1631                 }
1632
1633                 do
1634                     p++; /* skips extra spaces */
1635                 while( *p == ' ' );
1636
1637                 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1638                 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1639                 {
1640                     i_len = 0; /* not supported currently -> drop */
1641                     break;
1642                 }
1643
1644                 do
1645                     p++; /* skips extra spaces ever again */
1646                 while( *p == ' ' );
1647
1648                 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1649                 if( len < 7 ) /* foreign protocol */
1650                     i_len = 0; /* I don't understand -> drop */
1651                 else
1652                 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1653                 {
1654                     cl->query.i_proto = HTTPD_PROTO_HTTP;
1655                     cl->query.i_version = atoi( p + 7 );
1656                 }
1657                 else
1658                 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1659                 {
1660                     cl->query.i_proto = HTTPD_PROTO_RTSP;
1661                     cl->query.i_version = atoi( p + 7 );
1662                 }
1663                 else
1664                 if( memcmp( p, "HTTP/", 5 ) == 0 )
1665                 {
1666                     const uint8_t sorry[] =
1667                        "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1668                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1669                     i_len = 0; /* drop */
1670                 }
1671                 else
1672                 if( memcmp( p, "RTSP/", 5 ) == 0 )
1673                 {
1674                     const uint8_t sorry[] =
1675                         "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1676                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1677                     i_len = 0; /* drop */
1678                 }
1679                 else /* yet another foreign protocol */
1680                     i_len = 0;
1681
1682                 if( i_len == 0 )
1683                     break;
1684             }
1685
1686             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1687                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1688             {
1689                 char *p;
1690
1691                 /* we have finished the header so parse it and set i_body */
1692                 cl->p_buffer[cl->i_buffer] = '\0';
1693
1694                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1695                 {
1696                     /* FIXME:
1697                      * assume strlen( "HTTP/1.x" ) = 8
1698                      */
1699                     cl->query.i_status =
1700                         strtol( (char *)&cl->p_buffer[8],
1701                                 &p, 0 );
1702                     while( *p == ' ' )
1703                         p++;
1704                 }
1705                 else
1706                 {
1707                     unsigned i;
1708
1709                     p = NULL;
1710                     cl->query.i_type = HTTPD_MSG_NONE;
1711
1712                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1713
1714                     for( i = 0; msg_type[i].name[0]; i++ )
1715                     {
1716                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1717                                       strlen( msg_type[i].name ) ) )
1718                         {
1719                             p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1720                             cl->query.i_type = msg_type[i].i_type;
1721                             if( cl->query.i_proto != msg_type[i].i_proto )
1722                             {
1723                                 p = NULL;
1724                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1725                                 cl->query.i_type = HTTPD_MSG_NONE;
1726                             }
1727                             break;
1728                         }
1729                     }
1730                     if( p == NULL )
1731                     {
1732                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1733                         {
1734                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1735                         }
1736                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1737                         {
1738                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1739                         }
1740                     }
1741                     else
1742                     {
1743                         char *p2;
1744                         char *p3;
1745
1746                         while( *p == ' ' )
1747                         {
1748                             p++;
1749                         }
1750                         p2 = strchr( p, ' ' );
1751                         if( p2 )
1752                         {
1753                             *p2++ = '\0';
1754                         }
1755                         if( !strncasecmp( p, ( cl->query.i_proto
1756                                    == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1757                          && p[4 + !!strchr( "sS", p[4] )] == ':' )
1758                         {   /* Skip hier-part of URL (if present) */
1759                             p = strchr( p, ':' ) + 1; /* skip URI scheme */
1760                             if( !strncmp( p, "//", 2 ) ) /* skip authority */
1761                             {   /* see RFC3986 §3.2 */
1762                                 p += 2;
1763                                 while( *p && !strchr( "/?#", *p ) ) p++;
1764                             }
1765                         }
1766                         cl->query.psz_url = strdup( p );
1767                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1768                         {
1769                             *p3++ = '\0';
1770                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1771                         }
1772                         p = p2;
1773                     }
1774                 }
1775                 if( p )
1776                 {
1777                     p = strchr( p, '\n' );
1778                 }
1779                 if( p )
1780                 {
1781                     while( *p == '\n' || *p == '\r' )
1782                     {
1783                         p++;
1784                     }
1785                     while( p && *p != '\0' )
1786                     {
1787                         char *line = p;
1788                         char *eol = p = strchr( p, '\n' );
1789                         char *colon;
1790
1791                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1792                         {
1793                             *eol-- = '\0';
1794                         }
1795
1796                         if( ( colon = strchr( line, ':' ) ) )
1797                         {
1798                             char *name;
1799                             char *value;
1800
1801                             *colon++ = '\0';
1802                             while( *colon == ' ' )
1803                             {
1804                                 colon++;
1805                             }
1806                             name = strdup( line );
1807                             value = strdup( colon );
1808
1809                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1810                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1811
1812                             if( !strcasecmp( name, "Content-Length" ) )
1813                             {
1814                                 cl->query.i_body = atol( value );
1815                             }
1816                         }
1817
1818                         if( p )
1819                         {
1820                             p++;
1821                             while( *p == '\n' || *p == '\r' )
1822                             {
1823                                 p++;
1824                             }
1825                         }
1826                     }
1827                 }
1828                 if( cl->query.i_body > 0 )
1829                 {
1830                     /* TODO Mhh, handle the case client will only send a
1831                      * request and close the connection
1832                      * to mark and of body (probably only RTSP) */
1833                     cl->query.p_body = xmalloc( cl->query.i_body );
1834                     cl->i_buffer = 0;
1835                 }
1836                 else
1837                 {
1838                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1839                 }
1840             }
1841         }
1842     }
1843
1844     /* check if the client is to be set to dead */
1845 #if defined( WIN32 ) || defined( UNDER_CE )
1846     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1847 #else
1848     if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1849 #endif
1850     {
1851         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1852         {
1853             /* connection closed -> end of data */
1854             if( cl->query.i_body > 0 )
1855             {
1856                 cl->query.i_body = cl->i_buffer;
1857             }
1858             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1859         }
1860         else
1861         {
1862             cl->i_state = HTTPD_CLIENT_DEAD;
1863         }
1864     }
1865
1866     /* XXX: for QT I have to disable timeout. Try to find why */
1867     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1868         cl->i_activity_timeout = 0;
1869
1870 #if 0 /* Debugging only */
1871     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1872     {
1873         int i;
1874
1875         fprintf( stderr, "received new request\n" );
1876         fprintf( stderr, "  - proto=%s\n",
1877                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1878         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1879         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1880         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1881         {
1882             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1883                      cl->query.psz_status );
1884         }
1885         else if( cl->query.i_type != HTTPD_MSG_NONE )
1886         {
1887             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1888         }
1889         for( i = 0; i < cl->query.i_name; i++ )
1890         {
1891             fprintf( stderr, "  - option name='%s' value='%s'\n",
1892                      cl->query.name[i], cl->query.value[i] );
1893         }
1894     }
1895 #endif
1896 }
1897
1898 static void httpd_ClientSend( httpd_client_t *cl )
1899 {
1900     int i;
1901     int i_len;
1902
1903     if( cl->i_buffer < 0 )
1904     {
1905         /* We need to create the header */
1906         int i_size = 0;
1907         char *p;
1908         const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1909
1910         i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1911         for( i = 0; i < cl->answer.i_name; i++ )
1912         {
1913             i_size += strlen( cl->answer.name[i] ) + 2 +
1914                       strlen( cl->answer.value[i] ) + 2;
1915         }
1916
1917         if( cl->i_buffer_size < i_size )
1918         {
1919             cl->i_buffer_size = i_size;
1920             free( cl->p_buffer );
1921             cl->p_buffer = xmalloc( i_size );
1922         }
1923         p = (char *)cl->p_buffer;
1924
1925         p += sprintf( p, "%s.%u %d %s\r\n",
1926                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1927                       cl->answer.i_version,
1928                       cl->answer.i_status, psz_status );
1929         for( i = 0; i < cl->answer.i_name; i++ )
1930         {
1931             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1932                           cl->answer.value[i] );
1933         }
1934         p += sprintf( p, "\r\n" );
1935
1936         cl->i_buffer = 0;
1937         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1938
1939         /*fprintf( stderr, "sending answer\n" );
1940         fprintf( stderr, "%s",  cl->p_buffer );*/
1941     }
1942
1943     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1944                            cl->i_buffer_size - cl->i_buffer );
1945     if( i_len >= 0 )
1946     {
1947         cl->i_buffer += i_len;
1948
1949         if( cl->i_buffer >= cl->i_buffer_size )
1950         {
1951             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1952                 !cl->b_read_waiting )
1953             {
1954                 /* catch more body data */
1955                 int     i_msg = cl->query.i_type;
1956                 int64_t i_offset = cl->answer.i_body_offset;
1957
1958                 httpd_MsgClean( &cl->answer );
1959                 cl->answer.i_body_offset = i_offset;
1960
1961                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1962                                           &cl->answer, &cl->query );
1963             }
1964
1965             if( cl->answer.i_body > 0 )
1966             {
1967                 /* send the body data */
1968                 free( cl->p_buffer );
1969                 cl->p_buffer = cl->answer.p_body;
1970                 cl->i_buffer_size = cl->answer.i_body;
1971                 cl->i_buffer = 0;
1972
1973                 cl->answer.i_body = 0;
1974                 cl->answer.p_body = NULL;
1975             }
1976             else
1977             {
1978                 /* send finished */
1979                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1980             }
1981         }
1982     }
1983     else
1984     {
1985 #if defined( WIN32 ) || defined( UNDER_CE )
1986         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1987 #else
1988         if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1989 #endif
1990         {
1991             /* error */
1992             cl->i_state = HTTPD_CLIENT_DEAD;
1993         }
1994     }
1995 }
1996
1997 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1998 {
1999     switch( tls_SessionContinueHandshake( cl->p_tls ) )
2000     {
2001         case 0:
2002             cl->i_state = HTTPD_CLIENT_RECEIVING;
2003             break;
2004
2005         case -1:
2006             cl->i_state = HTTPD_CLIENT_DEAD;
2007             cl->p_tls = NULL;
2008             break;
2009
2010         case 2:
2011             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2012     }
2013 }
2014
2015 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2016 {
2017     switch( tls_SessionContinueHandshake( cl->p_tls ) )
2018     {
2019         case 0:
2020             cl->i_state = HTTPD_CLIENT_RECEIVING;
2021             break;
2022
2023         case -1:
2024             cl->i_state = HTTPD_CLIENT_DEAD;
2025             cl->p_tls = NULL;
2026             break;
2027
2028         case 1:
2029             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2030             break;
2031     }
2032 }
2033
2034 static void* httpd_HostThread( void *data )
2035 {
2036     httpd_host_t *host = data;
2037     tls_session_t *p_tls = NULL;
2038     counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2039     counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2040     int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2041
2042     for( ;; )
2043     {
2044         /* prepare a new TLS session */
2045         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2046             p_tls = tls_ServerSessionPrepare( host->p_tls );
2047
2048         struct pollfd ufd[host->nfd + host->i_client + 1];
2049         unsigned nfd;
2050         for( nfd = 0; nfd < host->nfd; nfd++ )
2051         {
2052             ufd[nfd].fd = host->fds[nfd];
2053             ufd[nfd].events = POLLIN;
2054             ufd[nfd].revents = 0;
2055         }
2056
2057         /* add all socket that should be read/write and close dead connection */
2058         vlc_mutex_lock( &host->lock );
2059         while( host->i_url <= 0 && host->i_ref > 0 )
2060             vlc_cond_wait( &host->wait, &host->lock );
2061
2062         mtime_t now = mdate();
2063         bool b_low_delay = false;
2064
2065         for(int i_client = 0; i_client < host->i_client; i_client++ )
2066         {
2067             httpd_client_t *cl = host->client[i_client];
2068             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2069                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2070                   ( cl->i_activity_timeout > 0 &&
2071                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2072             {
2073                 httpd_ClientClean( cl );
2074                 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2075                 TAB_REMOVE( host->i_client, host->client, cl );
2076                 free( cl );
2077                 i_client--;
2078                 continue;
2079             }
2080
2081             struct pollfd *pufd = ufd + nfd;
2082             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2083
2084             pufd->fd = cl->fd;
2085             pufd->events = pufd->revents = 0;
2086
2087             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2088                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2089             {
2090                 pufd->events = POLLIN;
2091             }
2092             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2093                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2094             {
2095                 pufd->events = POLLOUT;
2096             }
2097             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2098             {
2099                 httpd_message_t *answer = &cl->answer;
2100                 httpd_message_t *query  = &cl->query;
2101                 int i_msg = query->i_type;
2102
2103                 httpd_MsgInit( answer );
2104
2105                 /* Handle what we received */
2106                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2107                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2108                 {
2109                     /* we can only receive request from client when not
2110                      * in BIDIR mode */
2111                     cl->url     = NULL;
2112                     cl->i_state = HTTPD_CLIENT_DEAD;
2113                 }
2114                 else if( i_msg == HTTPD_MSG_ANSWER )
2115                 {
2116                     /* We are in BIDIR mode, trigger the callback and then
2117                      * check for new data */
2118                     if( cl->url && cl->url->catch[i_msg].cb )
2119                     {
2120                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2121                                                   cl, NULL, query );
2122                     }
2123                     cl->i_state = HTTPD_CLIENT_WAITING;
2124                 }
2125                 else if( i_msg == HTTPD_MSG_CHANNEL )
2126                 {
2127                     /* We are in BIDIR mode, trigger the callback and then
2128                      * check for new data */
2129                     if( cl->url && cl->url->catch[i_msg].cb )
2130                     {
2131                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2132                                                   cl, NULL, query );
2133                     }
2134                     cl->i_state = HTTPD_CLIENT_WAITING;
2135                 }
2136                 else if( i_msg == HTTPD_MSG_OPTIONS )
2137                 {
2138
2139                     answer->i_type   = HTTPD_MSG_ANSWER;
2140                     answer->i_proto  = query->i_proto;
2141                     answer->i_status = 200;
2142                     answer->i_body = 0;
2143                     answer->p_body = NULL;
2144
2145                     httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2146                     httpd_MsgAdd( answer, "Content-Length", "0" );
2147
2148                     switch( query->i_proto )
2149                     {
2150                         case HTTPD_PROTO_HTTP:
2151                             answer->i_version = 1;
2152                             httpd_MsgAdd( answer, "Allow",
2153                                           "GET,HEAD,POST,OPTIONS" );
2154                             break;
2155
2156                         case HTTPD_PROTO_RTSP:
2157                         {
2158                             const char *p;
2159                             answer->i_version = 0;
2160
2161                             p = httpd_MsgGet( query, "Cseq" );
2162                             if( p != NULL )
2163                                 httpd_MsgAdd( answer, "Cseq", "%s", p );
2164                             p = httpd_MsgGet( query, "Timestamp" );
2165                             if( p != NULL )
2166                                 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2167
2168                             p = httpd_MsgGet( query, "Require" );
2169                             if( p != NULL )
2170                             {
2171                                 answer->i_status = 551;
2172                                 httpd_MsgAdd( query, "Unsupported", "%s", p );
2173                             }
2174
2175                             httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2176                                           "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2177                             break;
2178                         }
2179                     }
2180
2181                     cl->i_buffer = -1;  /* Force the creation of the answer in
2182                                          * httpd_ClientSend */
2183                     cl->i_state = HTTPD_CLIENT_SENDING;
2184                 }
2185                 else if( i_msg == HTTPD_MSG_NONE )
2186                 {
2187                     if( query->i_proto == HTTPD_PROTO_NONE )
2188                     {
2189                         cl->url = NULL;
2190                         cl->i_state = HTTPD_CLIENT_DEAD;
2191                     }
2192                     else
2193                     {
2194                         char *p;
2195
2196                         /* unimplemented */
2197                         answer->i_proto  = query->i_proto ;
2198                         answer->i_type   = HTTPD_MSG_ANSWER;
2199                         answer->i_version= 0;
2200                         answer->i_status = 501;
2201
2202                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2203                         answer->p_body = (uint8_t *)p;
2204                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2205
2206                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2207                         cl->i_state = HTTPD_CLIENT_SENDING;
2208                     }
2209                 }
2210                 else
2211                 {
2212                     bool b_auth_failed = false;
2213                     bool b_hosts_failed = false;
2214
2215                     /* Search the url and trigger callbacks */
2216                     for(int i = 0; i < host->i_url; i++ )
2217                     {
2218                         httpd_url_t *url = host->url[i];
2219
2220                         if( !strcmp( url->psz_url, query->psz_url ) )
2221                         {
2222                             if( url->catch[i_msg].cb )
2223                             {
2224                                 if( answer && ( url->p_acl != NULL ) )
2225                                 {
2226                                     char ip[NI_MAXNUMERICHOST];
2227
2228                                     if( ( httpd_ClientIP( cl, ip ) == NULL )
2229                                      || ACL_Check( url->p_acl, ip ) )
2230                                     {
2231                                         b_hosts_failed = true;
2232                                         break;
2233                                     }
2234                                 }
2235
2236                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2237                                 {
2238                                     /* create the headers */
2239                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2240                                     char *user = NULL, *pass = NULL;
2241
2242                                     if( b64 != NULL
2243                                      && !strncasecmp( b64, "BASIC", 5 ) )
2244                                     {
2245                                         b64 += 5;
2246                                         while( *b64 == ' ' )
2247                                             b64++;
2248
2249                                         user = vlc_b64_decode( b64 );
2250                                         if (user != NULL)
2251                                         {
2252                                             pass = strchr (user, ':');
2253                                             if (pass != NULL)
2254                                                 *pass++ = '\0';
2255                                         }
2256                                     }
2257
2258                                     if ((user == NULL) || (pass == NULL)
2259                                      || strcmp (user, url->psz_user)
2260                                      || strcmp (pass, url->psz_password))
2261                                     {
2262                                         httpd_MsgAdd( answer,
2263                                                       "WWW-Authenticate",
2264                                                       "Basic realm=\"VLC stream\"" );
2265                                         /* We fail for all url */
2266                                         b_auth_failed = true;
2267                                         free( user );
2268                                         break;
2269                                     }
2270
2271                                     free( user );
2272                                 }
2273
2274                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2275                                 {
2276                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2277                                     {
2278                                         /* Raw answer from a CGI */
2279                                         cl->i_buffer = cl->i_buffer_size;
2280                                     }
2281                                     else
2282                                         cl->i_buffer = -1;
2283
2284                                     /* only one url can answer */
2285                                     answer = NULL;
2286                                     if( cl->url == NULL )
2287                                     {
2288                                         cl->url = url;
2289                                     }
2290                                 }
2291                             }
2292                         }
2293                     }
2294
2295                     if( answer )
2296                     {
2297                         char *p;
2298
2299                         answer->i_proto  = query->i_proto;
2300                         answer->i_type   = HTTPD_MSG_ANSWER;
2301                         answer->i_version= 0;
2302
2303                         if( b_hosts_failed )
2304                         {
2305                             answer->i_status = 403;
2306                         }
2307                         else if( b_auth_failed )
2308                         {
2309                             answer->i_status = 401;
2310                         }
2311                         else
2312                         {
2313                             /* no url registered */
2314                             answer->i_status = 404;
2315                         }
2316
2317                         answer->i_body = httpd_HtmlError (&p,
2318                                                           answer->i_status,
2319                                                           query->psz_url);
2320                         answer->p_body = (uint8_t *)p;
2321
2322                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2323                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2324                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2325                     }
2326
2327                     cl->i_state = HTTPD_CLIENT_SENDING;
2328                 }
2329             }
2330             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2331             {
2332                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2333                 {
2334                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2335                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2336                     bool b_connection = false;
2337                     bool b_keepalive = false;
2338                     bool b_query = false;
2339
2340                     cl->url = NULL;
2341                     if( psz_connection )
2342                     {
2343                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2344                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2345                     }
2346
2347                     if( psz_query )
2348                     {
2349                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2350                     }
2351
2352                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2353                           ( ( cl->query.i_version == 0 && b_keepalive ) ||
2354                             ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2355                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2356                           !b_query && !b_connection ) )
2357                     {
2358                         httpd_MsgClean( &cl->query );
2359                         httpd_MsgInit( &cl->query );
2360
2361                         cl->i_buffer = 0;
2362                         cl->i_buffer_size = 1000;
2363                         free( cl->p_buffer );
2364                         cl->p_buffer = xmalloc( cl->i_buffer_size );
2365                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2366                     }
2367                     else
2368                     {
2369                         cl->i_state = HTTPD_CLIENT_DEAD;
2370                     }
2371                     httpd_MsgClean( &cl->answer );
2372                 }
2373                 else if( cl->b_read_waiting )
2374                 {
2375                     /* we have a message waiting for us to read it */
2376                     httpd_MsgClean( &cl->answer );
2377                     httpd_MsgClean( &cl->query );
2378
2379                     cl->i_buffer = 0;
2380                     cl->i_buffer_size = 1000;
2381                     free( cl->p_buffer );
2382                     cl->p_buffer = xmalloc( cl->i_buffer_size );
2383                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2384                     cl->b_read_waiting = false;
2385                 }
2386                 else
2387                 {
2388                     int64_t i_offset = cl->answer.i_body_offset;
2389                     httpd_MsgClean( &cl->answer );
2390
2391                     cl->answer.i_body_offset = i_offset;
2392                     free( cl->p_buffer );
2393                     cl->p_buffer = NULL;
2394                     cl->i_buffer = 0;
2395                     cl->i_buffer_size = 0;
2396
2397                     cl->i_state = HTTPD_CLIENT_WAITING;
2398                 }
2399             }
2400             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2401             {
2402                 int64_t i_offset = cl->answer.i_body_offset;
2403                 int     i_msg = cl->query.i_type;
2404
2405                 httpd_MsgInit( &cl->answer );
2406                 cl->answer.i_body_offset = i_offset;
2407
2408                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2409                                           &cl->answer, &cl->query );
2410                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2411                 {
2412                     /* we have new data, so re-enter send mode */
2413                     cl->i_buffer      = 0;
2414                     cl->p_buffer      = cl->answer.p_body;
2415                     cl->i_buffer_size = cl->answer.i_body;
2416                     cl->answer.p_body = NULL;
2417                     cl->answer.i_body = 0;
2418                     cl->i_state = HTTPD_CLIENT_SENDING;
2419                 }
2420             }
2421
2422             /* Special for BIDIR mode we also check reading */
2423             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2424                 cl->i_state == HTTPD_CLIENT_SENDING )
2425             {
2426                 pufd->events |= POLLIN;
2427             }
2428
2429             if (pufd->events != 0)
2430                 nfd++;
2431             else
2432                 b_low_delay = true;
2433         }
2434         vlc_mutex_unlock( &host->lock );
2435
2436         ufd[nfd].fd = evfd;
2437         ufd[nfd].events = POLLIN;
2438         ufd[nfd].revents = 0;
2439         nfd++;
2440
2441         /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2442         switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2443         {
2444             case -1:
2445                 if (errno != EINTR)
2446                 {
2447                     /* Kernel on low memory or a bug: pace */
2448                     msg_Err( host, "polling error: %m" );
2449                     msleep( 100000 );
2450                 }
2451             case 0:
2452                 continue;
2453         }
2454
2455         if( ufd[nfd - 1].revents )
2456             break;
2457
2458         /* Handle client sockets */
2459         vlc_mutex_lock( &host->lock );
2460         now = mdate();
2461         nfd = host->nfd;
2462         for( int i_client = 0; i_client < host->i_client; i_client++ )
2463         {
2464             httpd_client_t *cl = host->client[i_client];
2465             const struct pollfd *pufd = &ufd[nfd];
2466
2467             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2468
2469             if( cl->fd != pufd->fd )
2470                 continue; // we were not waiting for this client
2471             ++nfd;
2472             if( pufd->revents == 0 )
2473                 continue; // no event received
2474
2475             cl->i_activity_date = now;
2476
2477             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2478             {
2479                 httpd_ClientRecv( cl );
2480             }
2481             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2482             {
2483                 httpd_ClientSend( cl );
2484             }
2485             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2486             {
2487                 httpd_ClientTlsHsIn( cl );
2488             }
2489             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2490             {
2491                 httpd_ClientTlsHsOut( cl );
2492             }
2493
2494             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2495                 cl->i_state == HTTPD_CLIENT_SENDING &&
2496                 (pufd->revents & POLLIN) )
2497             {
2498                 cl->b_read_waiting = true;
2499             }
2500         }
2501         vlc_mutex_unlock( &host->lock );
2502
2503         /* Handle server sockets (accept new connections) */
2504         for( nfd = 0; nfd < host->nfd; nfd++ )
2505         {
2506             httpd_client_t *cl;
2507             int i_state = -1;
2508             int fd = ufd[nfd].fd;
2509
2510             assert (fd == host->fds[nfd]);
2511
2512             if( ufd[nfd].revents == 0 )
2513                 continue;
2514
2515             /* */
2516 #ifdef HAVE_ACCEPT4
2517             fd = accept4 (fd, NULL, NULL, SOCK_CLOEXEC);
2518             if (fd == -1 && errno == ENOSYS)
2519 #endif
2520             fd = accept (fd, NULL, NULL);
2521             if (fd == -1)
2522                 continue;
2523
2524             net_SetupSocket (fd);
2525             if( p_tls != NULL )
2526             {
2527                 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2528                 {
2529                     case -1:
2530                         msg_Err( host, "Rejecting TLS connection" );
2531                         net_Close( fd );
2532                         fd = -1;
2533                         p_tls = NULL;
2534                         break;
2535
2536                     case 1: /* missing input - most likely */
2537                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2538                         break;
2539
2540                     case 2: /* missing output */
2541                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2542                         break;
2543                 }
2544
2545                 if( (p_tls == NULL) != (host->p_tls == NULL) )
2546                     break; // wasted TLS session, cannot accept() anymore
2547             }
2548
2549             stats_UpdateInteger( host, p_total_counter, 1, NULL );
2550             stats_UpdateInteger( host, p_active_counter, 1, NULL );
2551             cl = httpd_ClientNew( fd, p_tls, now );
2552             p_tls = NULL;
2553             vlc_mutex_lock( &host->lock );
2554             TAB_APPEND( host->i_client, host->client, cl );
2555             vlc_mutex_unlock( &host->lock );
2556             if( i_state != -1 )
2557                 cl->i_state = i_state; // override state for TLS
2558
2559             if (host->p_tls != NULL)
2560                 break; // cannot accept further without new TLS session
2561         }
2562
2563     }
2564
2565     if( p_tls != NULL )
2566         tls_ServerSessionClose( p_tls );
2567     if( p_total_counter )
2568         stats_CounterClean( p_total_counter );
2569     if( p_active_counter )
2570         stats_CounterClean( p_active_counter );
2571     return NULL;
2572 }