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