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