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