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