]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Run-time CPU detection for ARM (meaning NEON)
[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 <vlc_rand.h>
40 #include <vlc_charset.h>
41 #include "../libvlc.h"
42
43 #include <string.h>
44 #include <errno.h>
45
46 #ifdef HAVE_UNISTD_H
47 #   include <unistd.h>
48 #endif
49
50 #ifdef HAVE_POLL
51 # include <poll.h>
52 #endif
53
54 #if defined( UNDER_CE )
55 #   include <winsock.h>
56 #elif defined( WIN32 )
57 #   include <winsock2.h>
58 #else
59 #   include <sys/socket.h>
60 #endif
61
62 #if defined( WIN32 )
63 /* We need HUGE buffer otherwise TCP throughput is very limited */
64 #define HTTPD_CL_BUFSIZE 1000000
65 #else
66 #define HTTPD_CL_BUFSIZE 10000
67 #endif
68
69 static void httpd_ClientClean( httpd_client_t *cl );
70
71 struct httpd_t
72 {
73     VLC_COMMON_MEMBERS
74
75     int          i_host;
76     httpd_host_t **host;
77 };
78
79
80 /* each host run in his own thread */
81 struct httpd_host_t
82 {
83     VLC_COMMON_MEMBERS
84
85     httpd_t     *httpd;
86
87     /* ref count */
88     unsigned    i_ref;
89
90     /* address/port and socket for listening at connections */
91     char        *psz_hostname;
92     int         i_port;
93     int         *fds;
94     unsigned     nfd;
95
96     vlc_thread_t thread;
97     vlc_mutex_t lock;
98     vlc_cond_t  wait;
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 : ""), (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 = xmalloc( 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 = xrealloc( 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 == '\r' || *psz_headers == '\n' ) psz_headers++;
579             if( *psz_headers == '\n' ) 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 *)xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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 = xmalloc( 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=%lu",
831                           vlc_mrand48()&0x7fff );
832             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
833
834             /* Check if there is a xPlayStrm=1 */
835             for( i = 0; i < query->i_name; i++ )
836             {
837                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
838                     strstr( query->value[i], "xPlayStrm=1" ) )
839                 {
840                     b_xplaystream = true;
841                 }
842             }
843
844             if( !b_xplaystream )
845             {
846                 answer->i_body_offset = 0;
847             }
848         }
849         else
850         {
851             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
852         }
853         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
854         return VLC_SUCCESS;
855     }
856 }
857
858 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
859                                  const char *psz_url, const char *psz_mime,
860                                  const char *psz_user, const char *psz_password,
861                                  const vlc_acl_t *p_acl )
862 {
863     httpd_stream_t *stream = xmalloc( sizeof( httpd_stream_t ) );
864
865     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
866                                             psz_password, p_acl )
867         ) == NULL )
868     {
869         free( stream );
870         return NULL;
871     }
872     vlc_mutex_init( &stream->lock );
873     if( psz_mime && *psz_mime )
874     {
875         stream->psz_mime = strdup( psz_mime );
876     }
877     else
878     {
879         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
880     }
881     stream->i_header = 0;
882     stream->p_header = NULL;
883     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
884     stream->p_buffer = xmalloc( stream->i_buffer_size );
885     /* We set to 1 to make life simpler
886      * (this way i_body_offset can never be 0) */
887     stream->i_buffer_pos = 1;
888     stream->i_buffer_last_pos = 1;
889
890     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
891                     (httpd_callback_sys_t*)stream );
892     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
893                     (httpd_callback_sys_t*)stream );
894     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
895                     (httpd_callback_sys_t*)stream );
896
897     return stream;
898 }
899
900 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
901 {
902     vlc_mutex_lock( &stream->lock );
903     free( stream->p_header );
904     stream->p_header = NULL;
905
906     stream->i_header = i_data;
907     if( i_data > 0 )
908     {
909         stream->p_header = xmalloc( i_data );
910         memcpy( stream->p_header, p_data, i_data );
911     }
912     vlc_mutex_unlock( &stream->lock );
913
914     return VLC_SUCCESS;
915 }
916
917 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
918 {
919     int i_count;
920     int i_pos;
921
922     if( i_data < 0 || p_data == NULL )
923     {
924         return VLC_SUCCESS;
925     }
926     vlc_mutex_lock( &stream->lock );
927
928     /* save this pointer (to be used by new connection) */
929     stream->i_buffer_last_pos = stream->i_buffer_pos;
930
931     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
932     i_count = i_data;
933     while( i_count > 0)
934     {
935         int i_copy;
936
937         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
938
939         /* Ok, we can't go past the end of our buffer */
940         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
941
942         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
943         i_count -= i_copy;
944         p_data  += i_copy;
945     }
946
947     stream->i_buffer_pos += i_data;
948
949     vlc_mutex_unlock( &stream->lock );
950     return VLC_SUCCESS;
951 }
952
953 void httpd_StreamDelete( httpd_stream_t *stream )
954 {
955     httpd_UrlDelete( stream->url );
956     vlc_mutex_destroy( &stream->lock );
957     free( stream->psz_mime );
958     free( stream->p_header );
959     free( stream->p_buffer );
960     free( stream );
961 }
962
963 /*****************************************************************************
964  * Low level
965  *****************************************************************************/
966 static void* httpd_HostThread( void * );
967
968 /* create a new host */
969 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
970                              int i_port )
971 {
972     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
973                            );
974 }
975
976 static const char psz_object_type[] = "http server";
977 static vlc_mutex_t httpd_mutex = VLC_STATIC_MUTEX;
978
979 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
980                                 int i_port,
981                                 const char *psz_cert, const char *psz_key,
982                                 const char *psz_ca, const char *psz_crl )
983 {
984     httpd_t      *httpd;
985     httpd_host_t *host;
986     tls_server_t *p_tls;
987     char *psz_host;
988     int i;
989
990     if( psz_hostname == NULL )
991         psz_hostname = "";
992
993     psz_host = strdup( psz_hostname );
994     if( psz_host == NULL )
995         return NULL;
996
997     /* to be sure to avoid multiple creation */
998     vlc_mutex_lock( &httpd_mutex );
999     httpd = libvlc_priv (p_this->p_libvlc)->p_httpd;
1000
1001     if( httpd == NULL )
1002     {
1003         msg_Info( p_this, "creating httpd" );
1004         httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1005                                               VLC_OBJECT_GENERIC,
1006                                               psz_object_type );
1007         if( httpd == NULL )
1008         {
1009             vlc_mutex_unlock( &httpd_mutex );
1010             free( psz_host );
1011             return NULL;
1012         }
1013
1014         httpd->i_host = 0;
1015         httpd->host   = NULL;
1016
1017         libvlc_priv (p_this->p_libvlc)->p_httpd = httpd;
1018     }
1019
1020     /* verify if it already exist */
1021     for( i = httpd->i_host - 1; i >= 0; i-- )
1022     {
1023         host = httpd->host[i];
1024
1025         /* cannot mix TLS and non-TLS hosts */
1026         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1027          || ( host->i_port != i_port )
1028          || strcmp( host->psz_hostname, psz_hostname ) )
1029             continue;
1030
1031         /* Increase existing matching host reference count.
1032          * The reference count is written under both the global httpd and the
1033          * host lock. It is read with either or both locks held. The global
1034          * lock is always acquired first. */
1035         vlc_mutex_lock( &host->lock );
1036         host->i_ref++;
1037         vlc_mutex_unlock( &host->lock );
1038
1039         vlc_mutex_unlock( &httpd_mutex );
1040         return host;
1041     }
1042
1043     host = NULL;
1044
1045     /* determine TLS configuration */
1046     if ( psz_cert != NULL )
1047     {
1048         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1049         if ( p_tls == NULL )
1050         {
1051             msg_Err( p_this, "TLS initialization error" );
1052             goto error;
1053         }
1054
1055         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1056         {
1057             msg_Err( p_this, "TLS CA error" );
1058             goto error;
1059         }
1060
1061         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1062         {
1063             msg_Err( p_this, "TLS CRL error" );
1064             goto error;
1065         }
1066     }
1067     else
1068         p_tls = NULL;
1069
1070     /* create the new host */
1071     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1072                                               VLC_OBJECT_GENERIC,
1073                                               psz_object_type );
1074     if (host == NULL)
1075         goto error;
1076
1077     host->httpd = httpd;
1078     vlc_mutex_init( &host->lock );
1079     vlc_cond_init( &host->wait );
1080     host->i_ref = 1;
1081
1082     host->fds = net_ListenTCP( p_this, psz_host, i_port );
1083     if( host->fds == NULL )
1084     {
1085         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1086         goto error;
1087     }
1088     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1089
1090     if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1091     {
1092         msg_Err( host, "signaling pipe error: %m" );
1093         goto error;
1094     }
1095
1096     host->i_port = i_port;
1097     host->psz_hostname = psz_host;
1098
1099     host->i_url     = 0;
1100     host->url       = NULL;
1101     host->i_client  = 0;
1102     host->client    = NULL;
1103
1104     host->p_tls = p_tls;
1105
1106     /* create the thread */
1107     if( vlc_clone( &host->thread, httpd_HostThread, host,
1108                    VLC_THREAD_PRIORITY_LOW ) )
1109     {
1110         msg_Err( p_this, "cannot spawn http host thread" );
1111         goto error;
1112     }
1113
1114     /* now add it to httpd */
1115     TAB_APPEND( httpd->i_host, httpd->host, host );
1116     vlc_mutex_unlock( &httpd_mutex );
1117
1118     return host;
1119
1120 error:
1121     free( psz_host );
1122     if( httpd->i_host <= 0 )
1123     {
1124         libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1125         vlc_object_release( httpd );
1126     }
1127     vlc_mutex_unlock( &httpd_mutex );
1128
1129     if( host != NULL )
1130     {
1131         net_ListenClose( host->fds );
1132         vlc_cond_destroy( &host->wait );
1133         vlc_mutex_destroy( &host->lock );
1134         vlc_object_release( host );
1135     }
1136
1137     if( p_tls != NULL )
1138         tls_ServerDelete( p_tls );
1139
1140     return NULL;
1141 }
1142
1143 /* delete a host */
1144 void httpd_HostDelete( httpd_host_t *host )
1145 {
1146     httpd_t *httpd = host->httpd;
1147     int i;
1148     bool delete = false;
1149
1150     vlc_mutex_lock( &httpd_mutex );
1151
1152     vlc_mutex_lock( &host->lock );
1153     host->i_ref--;
1154     if( host->i_ref == 0 )
1155     {
1156         vlc_cond_signal( &host->wait );
1157         delete = true;
1158     }
1159     vlc_mutex_unlock( &host->lock );
1160     if( !delete )
1161     {
1162         /* still used */
1163         vlc_mutex_unlock( &httpd_mutex );
1164         msg_Dbg( host, "httpd_HostDelete: host still in use" );
1165         return;
1166     }
1167     TAB_REMOVE( httpd->i_host, httpd->host, host );
1168
1169     vlc_object_kill( host );
1170     vlc_join( host->thread, NULL );
1171
1172     msg_Dbg( host, "HTTP host removed" );
1173
1174     for( i = 0; i < host->i_url; i++ )
1175     {
1176         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1177     }
1178     for( i = 0; i < host->i_client; i++ )
1179     {
1180         httpd_client_t *cl = host->client[i];
1181         msg_Warn( host, "client still connected" );
1182         httpd_ClientClean( cl );
1183         TAB_REMOVE( host->i_client, host->client, cl );
1184         free( cl );
1185         i--;
1186         /* TODO */
1187     }
1188
1189     if( host->p_tls != NULL)
1190         tls_ServerDelete( host->p_tls );
1191
1192     net_ListenClose( host->fds );
1193     free( host->psz_hostname );
1194
1195     vlc_cond_destroy( &host->wait );
1196     vlc_mutex_destroy( &host->lock );
1197     vlc_object_release( host );
1198
1199     if( httpd->i_host <= 0 )
1200     {
1201         msg_Dbg( httpd, "no hosts left, stopping httpd" );
1202
1203         libvlc_priv (httpd->p_libvlc)->p_httpd = NULL;
1204         vlc_object_release( httpd );
1205     }
1206     vlc_mutex_unlock( &httpd_mutex );
1207 }
1208
1209 /* register a new url */
1210 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1211                                          const char *psz_user, const char *psz_password,
1212                                          const vlc_acl_t *p_acl, bool b_check )
1213 {
1214     httpd_url_t *url;
1215     int         i;
1216
1217     assert( psz_url != NULL );
1218
1219     vlc_mutex_lock( &host->lock );
1220     if( b_check )
1221     {
1222         for( i = 0; i < host->i_url; i++ )
1223         {
1224             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1225             {
1226                 msg_Warn( host->httpd,
1227                           "cannot add '%s' (url already defined)", psz_url );
1228                 vlc_mutex_unlock( &host->lock );
1229                 return NULL;
1230             }
1231         }
1232     }
1233
1234     url = xmalloc( sizeof( httpd_url_t ) );
1235     url->host = host;
1236
1237     vlc_mutex_init( &url->lock );
1238     url->psz_url = strdup( psz_url );
1239     url->psz_user = strdup( psz_user ? psz_user : "" );
1240     url->psz_password = strdup( psz_password ? psz_password : "" );
1241     url->p_acl = ACL_Duplicate( host, p_acl );
1242     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1243     {
1244         url->catch[i].cb = NULL;
1245         url->catch[i].p_sys = NULL;
1246     }
1247
1248     TAB_APPEND( host->i_url, host->url, url );
1249     vlc_cond_signal( &host->wait );
1250     vlc_mutex_unlock( &host->lock );
1251
1252     return url;
1253 }
1254
1255 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1256                            const char *psz_user, const char *psz_password,
1257                            const vlc_acl_t *p_acl )
1258 {
1259     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1260                                 psz_password, p_acl, false );
1261 }
1262
1263 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1264                                  const char *psz_user, const char *psz_password,
1265                                  const vlc_acl_t *p_acl )
1266 {
1267     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1268                                 psz_password, p_acl, true );
1269 }
1270
1271 /* register callback on a url */
1272 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1273                     httpd_callback_sys_t *p_sys )
1274 {
1275     vlc_mutex_lock( &url->lock );
1276     url->catch[i_msg].cb   = cb;
1277     url->catch[i_msg].p_sys= p_sys;
1278     vlc_mutex_unlock( &url->lock );
1279
1280     return VLC_SUCCESS;
1281 }
1282
1283 /* delete a url */
1284 void httpd_UrlDelete( httpd_url_t *url )
1285 {
1286     httpd_host_t *host = url->host;
1287     int          i;
1288
1289     vlc_mutex_lock( &host->lock );
1290     TAB_REMOVE( host->i_url, host->url, url );
1291
1292     vlc_mutex_destroy( &url->lock );
1293     free( url->psz_url );
1294     free( url->psz_user );
1295     free( url->psz_password );
1296     ACL_Destroy( url->p_acl );
1297
1298     for( i = 0; i < host->i_client; i++ )
1299     {
1300         httpd_client_t *client = host->client[i];
1301
1302         if( client->url == url )
1303         {
1304             /* TODO complete it */
1305             msg_Warn( host, "force closing connections" );
1306             httpd_ClientClean( client );
1307             TAB_REMOVE( host->i_client, host->client, client );
1308             free( client );
1309             i--;
1310         }
1311     }
1312     free( url );
1313     vlc_mutex_unlock( &host->lock );
1314 }
1315
1316 static void httpd_MsgInit( httpd_message_t *msg )
1317 {
1318     msg->cl         = NULL;
1319     msg->i_type     = HTTPD_MSG_NONE;
1320     msg->i_proto    = HTTPD_PROTO_NONE;
1321     msg->i_version  = -1; /* FIXME */
1322
1323     msg->i_status   = 0;
1324
1325     msg->psz_url    = NULL;
1326     msg->psz_args   = NULL;
1327
1328     msg->i_channel  = -1;
1329
1330     msg->i_name     = 0;
1331     msg->name       = NULL;
1332     msg->i_value    = 0;
1333     msg->value      = NULL;
1334
1335     msg->i_body_offset = 0;
1336     msg->i_body        = 0;
1337     msg->p_body        = NULL;
1338 }
1339
1340 static void httpd_MsgClean( httpd_message_t *msg )
1341 {
1342     int i;
1343
1344     free( msg->psz_url );
1345     free( msg->psz_args );
1346     for( i = 0; i < msg->i_name; i++ )
1347     {
1348         free( msg->name[i] );
1349         free( msg->value[i] );
1350     }
1351     free( msg->name );
1352     free( msg->value );
1353     free( msg->p_body );
1354     httpd_MsgInit( msg );
1355 }
1356
1357 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1358 {
1359     int i;
1360
1361     for( i = 0; i < msg->i_name; i++ )
1362     {
1363         if( !strcasecmp( msg->name[i], name ))
1364         {
1365             return msg->value[i];
1366         }
1367     }
1368     return NULL;
1369 }
1370
1371 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1372 {
1373     va_list args;
1374     char *value = NULL;
1375
1376     va_start( args, psz_value );
1377     if( us_vasprintf( &value, psz_value, args ) == -1 )
1378         value = NULL;
1379     va_end( args );
1380
1381     if( value == NULL )
1382         return;
1383
1384     name = strdup( name );
1385     if( name == NULL )
1386     {
1387         free( value );
1388         return;
1389     }
1390
1391     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1392     TAB_APPEND( msg->i_value, msg->value, value );
1393 }
1394
1395 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1396 {
1397     cl->i_state = HTTPD_CLIENT_RECEIVING;
1398     cl->i_activity_date = now;
1399     cl->i_activity_timeout = INT64_C(10000000);
1400     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1401     cl->i_buffer = 0;
1402     cl->p_buffer = xmalloc( cl->i_buffer_size );
1403     cl->i_mode   = HTTPD_CLIENT_FILE;
1404     cl->b_read_waiting = false;
1405
1406     httpd_MsgInit( &cl->query );
1407     httpd_MsgInit( &cl->answer );
1408 }
1409
1410 void httpd_ClientModeStream( httpd_client_t *cl )
1411 {
1412     cl->i_mode   = HTTPD_CLIENT_STREAM;
1413 }
1414
1415 void httpd_ClientModeBidir( httpd_client_t *cl )
1416 {
1417     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1418 }
1419
1420 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1421 {
1422     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1423 }
1424
1425 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1426 {
1427     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1428 }
1429
1430 static void httpd_ClientClean( httpd_client_t *cl )
1431 {
1432     if( cl->fd >= 0 )
1433     {
1434         if( cl->p_tls != NULL )
1435             tls_ServerSessionClose( cl->p_tls );
1436         net_Close( cl->fd );
1437         cl->fd = -1;
1438     }
1439
1440     httpd_MsgClean( &cl->answer );
1441     httpd_MsgClean( &cl->query );
1442
1443     free( cl->p_buffer );
1444     cl->p_buffer = NULL;
1445 }
1446
1447 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1448 {
1449     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1450
1451     if( !cl ) return NULL;
1452
1453     cl->i_ref   = 0;
1454     cl->fd      = fd;
1455     cl->url     = NULL;
1456     cl->p_tls = p_tls;
1457
1458     httpd_ClientInit( cl, now );
1459
1460     return cl;
1461 }
1462
1463 static
1464 ssize_t httpd_NetRecv (httpd_client_t *cl, uint8_t *p, size_t i_len)
1465 {
1466     tls_session_t *p_tls;
1467     ssize_t val;
1468
1469     p_tls = cl->p_tls;
1470     do
1471         val = p_tls ? tls_Recv (p_tls, p, i_len)
1472                     : recv (cl->fd, p, i_len, 0);
1473     while (val == -1 && errno == EINTR);
1474     return val;
1475 }
1476
1477 static
1478 ssize_t httpd_NetSend (httpd_client_t *cl, const uint8_t *p, size_t i_len)
1479 {
1480     tls_session_t *p_tls;
1481     ssize_t val;
1482
1483     p_tls = cl->p_tls;
1484     do
1485         val = p_tls ? tls_Send( p_tls, p, i_len )
1486                     : send (cl->fd, p, i_len, 0);
1487     while (val == -1 && errno == EINTR);
1488     return val;
1489 }
1490
1491
1492 static const struct
1493 {
1494     const char name[16];
1495     int  i_type;
1496     int  i_proto;
1497 }
1498 msg_type[] =
1499 {
1500     { "OPTIONS",       HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1501     { "DESCRIBE",      HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1502     { "SETUP",         HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1503     { "PLAY",          HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1504     { "PAUSE",         HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1505     { "GET_PARAMETER", HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1506     { "TEARDOWN",      HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1507     { "GET",           HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1508     { "HEAD",          HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1509     { "POST",          HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1510     { "",              HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1511 };
1512
1513
1514 static void httpd_ClientRecv( httpd_client_t *cl )
1515 {
1516     int i_len;
1517
1518     /* ignore leading whites */
1519     if( ( cl->query.i_proto == HTTPD_PROTO_NONE ) &&
1520         ( cl->i_buffer == 0 ) )
1521     {
1522         unsigned char c;
1523
1524         i_len = httpd_NetRecv( cl, &c, 1 );
1525
1526         if( ( i_len > 0 ) && ( strchr( "\r\n\t ", c ) == NULL ) )
1527         {
1528             cl->p_buffer[0] = c;
1529             cl->i_buffer++;
1530         }
1531     }
1532     else
1533     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1534     {
1535         /* enough to see if it's Interleaved RTP over RTSP or RTSP/HTTP */
1536         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1537                                7 - cl->i_buffer );
1538         if( i_len > 0 )
1539         {
1540             cl->i_buffer += i_len;
1541         }
1542
1543         if( ( cl->i_buffer >= 4 ) && ( cl->p_buffer[0] == '$' ) )
1544         {
1545             /* Interleaved RTP over RTSP */
1546             cl->query.i_proto = HTTPD_PROTO_RTSP;
1547             cl->query.i_type  = HTTPD_MSG_CHANNEL;
1548             cl->query.i_channel = cl->p_buffer[1];
1549             cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1550             cl->query.p_body  = xmalloc( cl->query.i_body );
1551             cl->i_buffer      -= 4;
1552             memcpy( cl->query.p_body, cl->p_buffer + 4, cl->i_buffer );
1553         }
1554         else
1555         /* The smallest legal request is 7 bytes ("GET /\r\n"),
1556          * this is the maximum we can ask at this point. */
1557         if( cl->i_buffer >= 7 )
1558         {
1559             if( !memcmp( cl->p_buffer, "HTTP/1.", 7 ) )
1560             {
1561                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1562                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1563             }
1564             else if( !memcmp( cl->p_buffer, "RTSP/1.", 7 ) )
1565             {
1566                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1567                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1568             }
1569             else
1570             {
1571                 /* We need the full request line to determine the protocol. */
1572                 cl->query.i_proto = HTTPD_PROTO_HTTP0;
1573                 cl->query.i_type  = HTTPD_MSG_NONE;
1574             }
1575         }
1576     }
1577     else if( cl->query.i_body > 0 )
1578     {
1579         /* we are reading the body of a request or a channel */
1580         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1581                                cl->query.i_body - cl->i_buffer );
1582         if( i_len > 0 )
1583         {
1584             cl->i_buffer += i_len;
1585         }
1586         if( cl->i_buffer >= cl->query.i_body )
1587         {
1588             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1589         }
1590     }
1591     else
1592     {
1593         /* we are reading a header -> char by char */
1594         for( ;; )
1595         {
1596             if( cl->i_buffer == cl->i_buffer_size )
1597             {
1598                 uint8_t *newbuf = realloc( cl->p_buffer, cl->i_buffer_size + 1024 );
1599                 if( newbuf == NULL )
1600                 {
1601                     i_len = 0;
1602                     break;
1603                 }
1604
1605                 cl->p_buffer = newbuf;
1606                 cl->i_buffer_size += 1024;
1607             }
1608
1609             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1610             if( i_len <= 0 )
1611             {
1612                 break;
1613             }
1614             cl->i_buffer++;
1615
1616             if( ( cl->query.i_proto == HTTPD_PROTO_HTTP0 )
1617              && ( cl->p_buffer[cl->i_buffer - 1] == '\n' ) )
1618             {
1619                 /* Request line is now complete */
1620                 const char *p = memchr( cl->p_buffer, ' ', cl->i_buffer );
1621                 size_t len;
1622
1623                 assert( cl->query.i_type == HTTPD_MSG_NONE );
1624
1625                 if( p == NULL ) /* no URI: evil guy */
1626                 {
1627                     i_len = 0; /* drop connection */
1628                     break;
1629                 }
1630
1631                 do
1632                     p++; /* skips extra spaces */
1633                 while( *p == ' ' );
1634
1635                 p = memchr( p, ' ', ((char *)cl->p_buffer) + cl->i_buffer - p );
1636                 if( p == NULL ) /* no explicit protocol: HTTP/0.9 */
1637                 {
1638                     i_len = 0; /* not supported currently -> drop */
1639                     break;
1640                 }
1641
1642                 do
1643                     p++; /* skips extra spaces ever again */
1644                 while( *p == ' ' );
1645
1646                 len = ((char *)cl->p_buffer) + cl->i_buffer - p;
1647                 if( len < 7 ) /* foreign protocol */
1648                     i_len = 0; /* I don't understand -> drop */
1649                 else
1650                 if( memcmp( p, "HTTP/1.", 7 ) == 0 )
1651                 {
1652                     cl->query.i_proto = HTTPD_PROTO_HTTP;
1653                     cl->query.i_version = atoi( p + 7 );
1654                 }
1655                 else
1656                 if( memcmp( p, "RTSP/1.", 7 ) == 0 )
1657                 {
1658                     cl->query.i_proto = HTTPD_PROTO_RTSP;
1659                     cl->query.i_version = atoi( p + 7 );
1660                 }
1661                 else
1662                 if( memcmp( p, "HTTP/", 5 ) == 0 )
1663                 {
1664                     const uint8_t sorry[] =
1665                        "HTTP/1.1 505 Unknown HTTP version\r\n\r\n";
1666                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1667                     i_len = 0; /* drop */
1668                 }
1669                 else
1670                 if( memcmp( p, "RTSP/", 5 ) == 0 )
1671                 {
1672                     const uint8_t sorry[] =
1673                         "RTSP/1.0 505 Unknown RTSP version\r\n\r\n";
1674                     httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1675                     i_len = 0; /* drop */
1676                 }
1677                 else /* yet another foreign protocol */
1678                     i_len = 0;
1679
1680                 if( i_len == 0 )
1681                     break;
1682             }
1683
1684             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1685                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1686             {
1687                 char *p;
1688
1689                 /* we have finished the header so parse it and set i_body */
1690                 cl->p_buffer[cl->i_buffer] = '\0';
1691
1692                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1693                 {
1694                     /* FIXME:
1695                      * assume strlen( "HTTP/1.x" ) = 8
1696                      */
1697                     cl->query.i_status =
1698                         strtol( (char *)&cl->p_buffer[8],
1699                                 &p, 0 );
1700                     while( *p == ' ' )
1701                         p++;
1702                 }
1703                 else
1704                 {
1705                     unsigned i;
1706
1707                     p = NULL;
1708                     cl->query.i_type = HTTPD_MSG_NONE;
1709
1710                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1711
1712                     for( i = 0; msg_type[i].name[0]; i++ )
1713                     {
1714                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1715                                       strlen( msg_type[i].name ) ) )
1716                         {
1717                             p = (char *)&cl->p_buffer[strlen(msg_type[i].name) + 1 ];
1718                             cl->query.i_type = msg_type[i].i_type;
1719                             if( cl->query.i_proto != msg_type[i].i_proto )
1720                             {
1721                                 p = NULL;
1722                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1723                                 cl->query.i_type = HTTPD_MSG_NONE;
1724                             }
1725                             break;
1726                         }
1727                     }
1728                     if( p == NULL )
1729                     {
1730                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1731                         {
1732                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1733                         }
1734                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1735                         {
1736                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1737                         }
1738                     }
1739                     else
1740                     {
1741                         char *p2;
1742                         char *p3;
1743
1744                         while( *p == ' ' )
1745                         {
1746                             p++;
1747                         }
1748                         p2 = strchr( p, ' ' );
1749                         if( p2 )
1750                         {
1751                             *p2++ = '\0';
1752                         }
1753                         if( !strncasecmp( p, ( cl->query.i_proto
1754                                    == HTTPD_PROTO_HTTP ) ? "http" : "rtsp", 4 )
1755                          && p[4 + !!strchr( "sS", p[4] )] == ':' )
1756                         {   /* Skip hier-part of URL (if present) */
1757                             p = strchr( p, ':' ) + 1; /* skip URI scheme */
1758                             if( !strncmp( p, "//", 2 ) ) /* skip authority */
1759                             {   /* see RFC3986 §3.2 */
1760                                 p += 2;
1761                                 while( *p && !strchr( "/?#", *p ) ) p++;
1762                             }
1763                         }
1764                         cl->query.psz_url = strdup( p );
1765                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1766                         {
1767                             *p3++ = '\0';
1768                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1769                         }
1770                         p = p2;
1771                     }
1772                 }
1773                 if( p )
1774                 {
1775                     p = strchr( p, '\n' );
1776                 }
1777                 if( p )
1778                 {
1779                     while( *p == '\n' || *p == '\r' )
1780                     {
1781                         p++;
1782                     }
1783                     while( p && *p != '\0' )
1784                     {
1785                         char *line = p;
1786                         char *eol = p = strchr( p, '\n' );
1787                         char *colon;
1788
1789                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1790                         {
1791                             *eol-- = '\0';
1792                         }
1793
1794                         if( ( colon = strchr( line, ':' ) ) )
1795                         {
1796                             char *name;
1797                             char *value;
1798
1799                             *colon++ = '\0';
1800                             while( *colon == ' ' )
1801                             {
1802                                 colon++;
1803                             }
1804                             name = strdup( line );
1805                             value = strdup( colon );
1806
1807                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1808                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1809
1810                             if( !strcasecmp( name, "Content-Length" ) )
1811                             {
1812                                 cl->query.i_body = atol( value );
1813                             }
1814                         }
1815
1816                         if( p )
1817                         {
1818                             p++;
1819                             while( *p == '\n' || *p == '\r' )
1820                             {
1821                                 p++;
1822                             }
1823                         }
1824                     }
1825                 }
1826                 if( cl->query.i_body > 0 )
1827                 {
1828                     /* TODO Mhh, handle the case where the client only
1829                      * sends a request and closes the connection to
1830                      * mark the end of the body (probably only RTSP) */
1831                     cl->query.p_body = malloc( cl->query.i_body );
1832                     cl->i_buffer = 0;
1833                     if ( cl->query.p_body == NULL )
1834                     {
1835                         switch (cl->query.i_proto)
1836                         {
1837                             case HTTPD_PROTO_HTTP:
1838                             {
1839                                 const uint8_t sorry[] =
1840                             "HTTP/1.1 413 Request Entity Too Large\r\n\r\n";
1841                                 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1842                                 break;
1843                             }
1844                             case HTTPD_PROTO_RTSP:
1845                             {
1846                                 const uint8_t sorry[] =
1847                             "RTSP/1.0 413 Request Entity Too Large\r\n\r\n";
1848                                 httpd_NetSend( cl, sorry, sizeof( sorry ) - 1 );
1849                                 break;
1850                             }
1851                             default:
1852                                 assert( 0 );
1853                         }
1854                         i_len = 0; /* drop */
1855                     }
1856                     break;
1857                 }
1858                 else
1859                 {
1860                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1861                 }
1862             }
1863         }
1864     }
1865
1866     /* check if the client is to be set to dead */
1867 #if defined( WIN32 ) || defined( UNDER_CE )
1868     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1869 #else
1870     if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
1871 #endif
1872     {
1873         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1874         {
1875             /* connection closed -> end of data */
1876             if( cl->query.i_body > 0 )
1877             {
1878                 cl->query.i_body = cl->i_buffer;
1879             }
1880             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1881         }
1882         else
1883         {
1884             cl->i_state = HTTPD_CLIENT_DEAD;
1885         }
1886     }
1887
1888     /* XXX: for QT I have to disable timeout. Try to find why */
1889     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1890         cl->i_activity_timeout = 0;
1891
1892 #if 0 /* Debugging only */
1893     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1894     {
1895         int i;
1896
1897         fprintf( stderr, "received new request\n" );
1898         fprintf( stderr, "  - proto=%s\n",
1899                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1900         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1901         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1902         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1903         {
1904             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1905                      cl->query.psz_status );
1906         }
1907         else if( cl->query.i_type != HTTPD_MSG_NONE )
1908         {
1909             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1910         }
1911         for( i = 0; i < cl->query.i_name; i++ )
1912         {
1913             fprintf( stderr, "  - option name='%s' value='%s'\n",
1914                      cl->query.name[i], cl->query.value[i] );
1915         }
1916     }
1917 #endif
1918 }
1919
1920 static void httpd_ClientSend( httpd_client_t *cl )
1921 {
1922     int i;
1923     int i_len;
1924
1925     if( cl->i_buffer < 0 )
1926     {
1927         /* We need to create the header */
1928         int i_size = 0;
1929         char *p;
1930         const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1931
1932         i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1933         for( i = 0; i < cl->answer.i_name; i++ )
1934         {
1935             i_size += strlen( cl->answer.name[i] ) + 2 +
1936                       strlen( cl->answer.value[i] ) + 2;
1937         }
1938
1939         if( cl->i_buffer_size < i_size )
1940         {
1941             cl->i_buffer_size = i_size;
1942             free( cl->p_buffer );
1943             cl->p_buffer = xmalloc( i_size );
1944         }
1945         p = (char *)cl->p_buffer;
1946
1947         p += sprintf( p, "%s.%u %d %s\r\n",
1948                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1949                       cl->answer.i_version,
1950                       cl->answer.i_status, psz_status );
1951         for( i = 0; i < cl->answer.i_name; i++ )
1952         {
1953             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1954                           cl->answer.value[i] );
1955         }
1956         p += sprintf( p, "\r\n" );
1957
1958         cl->i_buffer = 0;
1959         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1960
1961         /*fprintf( stderr, "sending answer\n" );
1962         fprintf( stderr, "%s",  cl->p_buffer );*/
1963     }
1964
1965     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1966                            cl->i_buffer_size - cl->i_buffer );
1967     if( i_len >= 0 )
1968     {
1969         cl->i_buffer += i_len;
1970
1971         if( cl->i_buffer >= cl->i_buffer_size )
1972         {
1973             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1974                 !cl->b_read_waiting )
1975             {
1976                 /* catch more body data */
1977                 int     i_msg = cl->query.i_type;
1978                 int64_t i_offset = cl->answer.i_body_offset;
1979
1980                 httpd_MsgClean( &cl->answer );
1981                 cl->answer.i_body_offset = i_offset;
1982
1983                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1984                                           &cl->answer, &cl->query );
1985             }
1986
1987             if( cl->answer.i_body > 0 )
1988             {
1989                 /* send the body data */
1990                 free( cl->p_buffer );
1991                 cl->p_buffer = cl->answer.p_body;
1992                 cl->i_buffer_size = cl->answer.i_body;
1993                 cl->i_buffer = 0;
1994
1995                 cl->answer.i_body = 0;
1996                 cl->answer.p_body = NULL;
1997             }
1998             else
1999             {
2000                 /* send finished */
2001                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
2002             }
2003         }
2004     }
2005     else
2006     {
2007 #if defined( WIN32 ) || defined( UNDER_CE )
2008         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
2009 #else
2010         if( ( i_len < 0 && errno != EAGAIN ) || ( i_len == 0 ) )
2011 #endif
2012         {
2013             /* error */
2014             cl->i_state = HTTPD_CLIENT_DEAD;
2015         }
2016     }
2017 }
2018
2019 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
2020 {
2021     switch( tls_SessionContinueHandshake( cl->p_tls ) )
2022     {
2023         case 0:
2024             cl->i_state = HTTPD_CLIENT_RECEIVING;
2025             break;
2026
2027         case -1:
2028             cl->i_state = HTTPD_CLIENT_DEAD;
2029             cl->p_tls = NULL;
2030             break;
2031
2032         case 2:
2033             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
2034     }
2035 }
2036
2037 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
2038 {
2039     switch( tls_SessionContinueHandshake( cl->p_tls ) )
2040     {
2041         case 0:
2042             cl->i_state = HTTPD_CLIENT_RECEIVING;
2043             break;
2044
2045         case -1:
2046             cl->i_state = HTTPD_CLIENT_DEAD;
2047             cl->p_tls = NULL;
2048             break;
2049
2050         case 1:
2051             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
2052             break;
2053     }
2054 }
2055
2056 static void* httpd_HostThread( void *data )
2057 {
2058     httpd_host_t *host = data;
2059     tls_session_t *p_tls = NULL;
2060     counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2061     counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2062     int evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2063
2064     for( ;; )
2065     {
2066         /* prepare a new TLS session */
2067         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2068             p_tls = tls_ServerSessionPrepare( host->p_tls );
2069
2070         struct pollfd ufd[host->nfd + host->i_client + 1];
2071         unsigned nfd;
2072         for( nfd = 0; nfd < host->nfd; nfd++ )
2073         {
2074             ufd[nfd].fd = host->fds[nfd];
2075             ufd[nfd].events = POLLIN;
2076             ufd[nfd].revents = 0;
2077         }
2078
2079         /* add all socket that should be read/write and close dead connection */
2080         vlc_mutex_lock( &host->lock );
2081         while( host->i_url <= 0 && host->i_ref > 0 )
2082             vlc_cond_wait( &host->wait, &host->lock );
2083
2084         mtime_t now = mdate();
2085         bool b_low_delay = false;
2086
2087         for(int i_client = 0; i_client < host->i_client; i_client++ )
2088         {
2089             httpd_client_t *cl = host->client[i_client];
2090             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2091                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2092                   ( cl->i_activity_timeout > 0 &&
2093                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2094             {
2095                 httpd_ClientClean( cl );
2096                 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2097                 TAB_REMOVE( host->i_client, host->client, cl );
2098                 free( cl );
2099                 i_client--;
2100                 continue;
2101             }
2102
2103             struct pollfd *pufd = ufd + nfd;
2104             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2105
2106             pufd->fd = cl->fd;
2107             pufd->events = pufd->revents = 0;
2108
2109             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2110                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2111             {
2112                 pufd->events = POLLIN;
2113             }
2114             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2115                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2116             {
2117                 pufd->events = POLLOUT;
2118             }
2119             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2120             {
2121                 httpd_message_t *answer = &cl->answer;
2122                 httpd_message_t *query  = &cl->query;
2123                 int i_msg = query->i_type;
2124
2125                 httpd_MsgInit( answer );
2126
2127                 /* Handle what we received */
2128                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2129                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2130                 {
2131                     /* we can only receive request from client when not
2132                      * in BIDIR mode */
2133                     cl->url     = NULL;
2134                     cl->i_state = HTTPD_CLIENT_DEAD;
2135                 }
2136                 else if( i_msg == HTTPD_MSG_ANSWER )
2137                 {
2138                     /* We are in BIDIR mode, trigger the callback and then
2139                      * check for new data */
2140                     if( cl->url && cl->url->catch[i_msg].cb )
2141                     {
2142                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2143                                                   cl, NULL, query );
2144                     }
2145                     cl->i_state = HTTPD_CLIENT_WAITING;
2146                 }
2147                 else if( i_msg == HTTPD_MSG_CHANNEL )
2148                 {
2149                     /* We are in BIDIR mode, trigger the callback and then
2150                      * check for new data */
2151                     if( cl->url && cl->url->catch[i_msg].cb )
2152                     {
2153                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2154                                                   cl, NULL, query );
2155                     }
2156                     cl->i_state = HTTPD_CLIENT_WAITING;
2157                 }
2158                 else if( i_msg == HTTPD_MSG_OPTIONS )
2159                 {
2160
2161                     answer->i_type   = HTTPD_MSG_ANSWER;
2162                     answer->i_proto  = query->i_proto;
2163                     answer->i_status = 200;
2164                     answer->i_body = 0;
2165                     answer->p_body = NULL;
2166
2167                     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
2168                     httpd_MsgAdd( answer, "Content-Length", "0" );
2169
2170                     switch( query->i_proto )
2171                     {
2172                         case HTTPD_PROTO_HTTP:
2173                             answer->i_version = 1;
2174                             httpd_MsgAdd( answer, "Allow",
2175                                           "GET,HEAD,POST,OPTIONS" );
2176                             break;
2177
2178                         case HTTPD_PROTO_RTSP:
2179                         {
2180                             const char *p;
2181                             answer->i_version = 0;
2182
2183                             p = httpd_MsgGet( query, "Cseq" );
2184                             if( p != NULL )
2185                                 httpd_MsgAdd( answer, "Cseq", "%s", p );
2186                             p = httpd_MsgGet( query, "Timestamp" );
2187                             if( p != NULL )
2188                                 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2189
2190                             p = httpd_MsgGet( query, "Require" );
2191                             if( p != NULL )
2192                             {
2193                                 answer->i_status = 551;
2194                                 httpd_MsgAdd( query, "Unsupported", "%s", p );
2195                             }
2196
2197                             httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2198                                           "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2199                             break;
2200                         }
2201                     }
2202
2203                     cl->i_buffer = -1;  /* Force the creation of the answer in
2204                                          * httpd_ClientSend */
2205                     cl->i_state = HTTPD_CLIENT_SENDING;
2206                 }
2207                 else if( i_msg == HTTPD_MSG_NONE )
2208                 {
2209                     if( query->i_proto == HTTPD_PROTO_NONE )
2210                     {
2211                         cl->url = NULL;
2212                         cl->i_state = HTTPD_CLIENT_DEAD;
2213                     }
2214                     else
2215                     {
2216                         char *p;
2217
2218                         /* unimplemented */
2219                         answer->i_proto  = query->i_proto ;
2220                         answer->i_type   = HTTPD_MSG_ANSWER;
2221                         answer->i_version= 0;
2222                         answer->i_status = 501;
2223
2224                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2225                         answer->p_body = (uint8_t *)p;
2226                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2227
2228                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2229                         cl->i_state = HTTPD_CLIENT_SENDING;
2230                     }
2231                 }
2232                 else
2233                 {
2234                     bool b_auth_failed = false;
2235                     bool b_hosts_failed = false;
2236
2237                     /* Search the url and trigger callbacks */
2238                     for(int i = 0; i < host->i_url; i++ )
2239                     {
2240                         httpd_url_t *url = host->url[i];
2241
2242                         if( !strcmp( url->psz_url, query->psz_url ) )
2243                         {
2244                             if( url->catch[i_msg].cb )
2245                             {
2246                                 if( answer && ( url->p_acl != NULL ) )
2247                                 {
2248                                     char ip[NI_MAXNUMERICHOST];
2249
2250                                     if( ( httpd_ClientIP( cl, ip ) == NULL )
2251                                      || ACL_Check( url->p_acl, ip ) )
2252                                     {
2253                                         b_hosts_failed = true;
2254                                         break;
2255                                     }
2256                                 }
2257
2258                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2259                                 {
2260                                     /* create the headers */
2261                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2262                                     char *user = NULL, *pass = NULL;
2263
2264                                     if( b64 != NULL
2265                                      && !strncasecmp( b64, "BASIC", 5 ) )
2266                                     {
2267                                         b64 += 5;
2268                                         while( *b64 == ' ' )
2269                                             b64++;
2270
2271                                         user = vlc_b64_decode( b64 );
2272                                         if (user != NULL)
2273                                         {
2274                                             pass = strchr (user, ':');
2275                                             if (pass != NULL)
2276                                                 *pass++ = '\0';
2277                                         }
2278                                     }
2279
2280                                     if ((user == NULL) || (pass == NULL)
2281                                      || strcmp (user, url->psz_user)
2282                                      || strcmp (pass, url->psz_password))
2283                                     {
2284                                         httpd_MsgAdd( answer,
2285                                                       "WWW-Authenticate",
2286                                                       "Basic realm=\"VLC stream\"" );
2287                                         /* We fail for all url */
2288                                         b_auth_failed = true;
2289                                         free( user );
2290                                         break;
2291                                     }
2292
2293                                     free( user );
2294                                 }
2295
2296                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2297                                 {
2298                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2299                                     {
2300                                         /* Raw answer from a CGI */
2301                                         cl->i_buffer = cl->i_buffer_size;
2302                                     }
2303                                     else
2304                                         cl->i_buffer = -1;
2305
2306                                     /* only one url can answer */
2307                                     answer = NULL;
2308                                     if( cl->url == NULL )
2309                                     {
2310                                         cl->url = url;
2311                                     }
2312                                 }
2313                             }
2314                         }
2315                     }
2316
2317                     if( answer )
2318                     {
2319                         char *p;
2320
2321                         answer->i_proto  = query->i_proto;
2322                         answer->i_type   = HTTPD_MSG_ANSWER;
2323                         answer->i_version= 0;
2324
2325                         if( b_hosts_failed )
2326                         {
2327                             answer->i_status = 403;
2328                         }
2329                         else if( b_auth_failed )
2330                         {
2331                             answer->i_status = 401;
2332                         }
2333                         else
2334                         {
2335                             /* no url registered */
2336                             answer->i_status = 404;
2337                         }
2338
2339                         answer->i_body = httpd_HtmlError (&p,
2340                                                           answer->i_status,
2341                                                           query->psz_url);
2342                         answer->p_body = (uint8_t *)p;
2343
2344                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2345                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2346                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2347                     }
2348
2349                     cl->i_state = HTTPD_CLIENT_SENDING;
2350                 }
2351             }
2352             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2353             {
2354                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2355                 {
2356                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2357                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2358                     bool b_connection = false;
2359                     bool b_keepalive = false;
2360                     bool b_query = false;
2361
2362                     cl->url = NULL;
2363                     if( psz_connection )
2364                     {
2365                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2366                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2367                     }
2368
2369                     if( psz_query )
2370                     {
2371                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2372                     }
2373
2374                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2375                           ( ( cl->query.i_version == 0 && b_keepalive ) ||
2376                             ( cl->query.i_version == 1 && !b_connection ) ) ) ||
2377                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2378                           !b_query && !b_connection ) )
2379                     {
2380                         httpd_MsgClean( &cl->query );
2381                         httpd_MsgInit( &cl->query );
2382
2383                         cl->i_buffer = 0;
2384                         cl->i_buffer_size = 1000;
2385                         free( cl->p_buffer );
2386                         cl->p_buffer = xmalloc( cl->i_buffer_size );
2387                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2388                     }
2389                     else
2390                     {
2391                         cl->i_state = HTTPD_CLIENT_DEAD;
2392                     }
2393                     httpd_MsgClean( &cl->answer );
2394                 }
2395                 else if( cl->b_read_waiting )
2396                 {
2397                     /* we have a message waiting for us to read it */
2398                     httpd_MsgClean( &cl->answer );
2399                     httpd_MsgClean( &cl->query );
2400
2401                     cl->i_buffer = 0;
2402                     cl->i_buffer_size = 1000;
2403                     free( cl->p_buffer );
2404                     cl->p_buffer = xmalloc( cl->i_buffer_size );
2405                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2406                     cl->b_read_waiting = false;
2407                 }
2408                 else
2409                 {
2410                     int64_t i_offset = cl->answer.i_body_offset;
2411                     httpd_MsgClean( &cl->answer );
2412
2413                     cl->answer.i_body_offset = i_offset;
2414                     free( cl->p_buffer );
2415                     cl->p_buffer = NULL;
2416                     cl->i_buffer = 0;
2417                     cl->i_buffer_size = 0;
2418
2419                     cl->i_state = HTTPD_CLIENT_WAITING;
2420                 }
2421             }
2422             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2423             {
2424                 int64_t i_offset = cl->answer.i_body_offset;
2425                 int     i_msg = cl->query.i_type;
2426
2427                 httpd_MsgInit( &cl->answer );
2428                 cl->answer.i_body_offset = i_offset;
2429
2430                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2431                                           &cl->answer, &cl->query );
2432                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2433                 {
2434                     /* we have new data, so re-enter send mode */
2435                     cl->i_buffer      = 0;
2436                     cl->p_buffer      = cl->answer.p_body;
2437                     cl->i_buffer_size = cl->answer.i_body;
2438                     cl->answer.p_body = NULL;
2439                     cl->answer.i_body = 0;
2440                     cl->i_state = HTTPD_CLIENT_SENDING;
2441                 }
2442             }
2443
2444             /* Special for BIDIR mode we also check reading */
2445             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2446                 cl->i_state == HTTPD_CLIENT_SENDING )
2447             {
2448                 pufd->events |= POLLIN;
2449             }
2450
2451             if (pufd->events != 0)
2452                 nfd++;
2453             else
2454                 b_low_delay = true;
2455         }
2456         vlc_mutex_unlock( &host->lock );
2457
2458         ufd[nfd].fd = evfd;
2459         ufd[nfd].events = POLLIN;
2460         ufd[nfd].revents = 0;
2461         nfd++;
2462
2463         /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2464         switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2465         {
2466             case -1:
2467                 if (errno != EINTR)
2468                 {
2469                     /* Kernel on low memory or a bug: pace */
2470                     msg_Err( host, "polling error: %m" );
2471                     msleep( 100000 );
2472                 }
2473             case 0:
2474                 continue;
2475         }
2476
2477         if( ufd[nfd - 1].revents )
2478             break;
2479
2480         /* Handle client sockets */
2481         vlc_mutex_lock( &host->lock );
2482         now = mdate();
2483         nfd = host->nfd;
2484         for( int i_client = 0; i_client < host->i_client; i_client++ )
2485         {
2486             httpd_client_t *cl = host->client[i_client];
2487             const struct pollfd *pufd = &ufd[nfd];
2488
2489             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2490
2491             if( cl->fd != pufd->fd )
2492                 continue; // we were not waiting for this client
2493             ++nfd;
2494             if( pufd->revents == 0 )
2495                 continue; // no event received
2496
2497             cl->i_activity_date = now;
2498
2499             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2500             {
2501                 httpd_ClientRecv( cl );
2502             }
2503             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2504             {
2505                 httpd_ClientSend( cl );
2506             }
2507             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2508             {
2509                 httpd_ClientTlsHsIn( cl );
2510             }
2511             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2512             {
2513                 httpd_ClientTlsHsOut( cl );
2514             }
2515
2516             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2517                 cl->i_state == HTTPD_CLIENT_SENDING &&
2518                 (pufd->revents & POLLIN) )
2519             {
2520                 cl->b_read_waiting = true;
2521             }
2522         }
2523         vlc_mutex_unlock( &host->lock );
2524
2525         /* Handle server sockets (accept new connections) */
2526         for( nfd = 0; nfd < host->nfd; nfd++ )
2527         {
2528             httpd_client_t *cl;
2529             int i_state = -1;
2530             int fd = ufd[nfd].fd;
2531
2532             assert (fd == host->fds[nfd]);
2533
2534             if( ufd[nfd].revents == 0 )
2535                 continue;
2536
2537             /* */
2538             fd = vlc_accept (fd, NULL, NULL, true);
2539             if (fd == -1)
2540                 continue;
2541             setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
2542                         &(int){ 1 }, sizeof(int));
2543
2544             if( p_tls != NULL )
2545             {
2546                 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2547                 {
2548                     case -1:
2549                         msg_Err( host, "Rejecting TLS connection" );
2550                         net_Close( fd );
2551                         fd = -1;
2552                         p_tls = NULL;
2553                         break;
2554
2555                     case 1: /* missing input - most likely */
2556                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2557                         break;
2558
2559                     case 2: /* missing output */
2560                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2561                         break;
2562                 }
2563
2564                 if( (p_tls == NULL) != (host->p_tls == NULL) )
2565                     break; // wasted TLS session, cannot accept() anymore
2566             }
2567
2568             stats_UpdateInteger( host, p_total_counter, 1, NULL );
2569             stats_UpdateInteger( host, p_active_counter, 1, NULL );
2570             cl = httpd_ClientNew( fd, p_tls, now );
2571             p_tls = NULL;
2572             vlc_mutex_lock( &host->lock );
2573             TAB_APPEND( host->i_client, host->client, cl );
2574             vlc_mutex_unlock( &host->lock );
2575             if( i_state != -1 )
2576                 cl->i_state = i_state; // override state for TLS
2577
2578             if (host->p_tls != NULL)
2579                 break; // cannot accept further without new TLS session
2580         }
2581
2582     }
2583
2584     if( p_tls != NULL )
2585         tls_ServerSessionClose( p_tls );
2586     if( p_total_counter )
2587         stats_CounterClean( p_total_counter );
2588     if( p_active_counter )
2589         stats_CounterClean( p_active_counter );
2590     return NULL;
2591 }