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