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