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