]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Set non-blocking mode on accepted sockets
[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 #include <vlc/vlc.h>
27
28 #ifdef ENABLE_HTTPD
29
30 #include <assert.h>
31
32 #include <vlc_httpd.h>
33 #include <vlc_network.h>
34 #include <vlc_tls.h>
35 #include <vlc_acl.h>
36 #include <vlc_strings.h>
37 #include "../libvlc.h"
38
39 #include <string.h>
40 #include <errno.h>
41
42 #ifdef HAVE_UNISTD_H
43 #   include <unistd.h>
44 #endif
45
46 #ifdef HAVE_FCNTL_H
47 #   include <fcntl.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     int         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_mutex_t lock;
97
98     /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
99      * This will slow down the url research but make my live easier
100      * All url will have their cb trigger, but only the first one can answer
101      * */
102     int         i_url;
103     httpd_url_t **url;
104
105     int            i_client;
106     httpd_client_t **client;
107
108     /* TLS data */
109     tls_server_t *p_tls;
110 };
111
112
113 struct httpd_url_t
114 {
115     httpd_host_t *host;
116
117     vlc_mutex_t lock;
118
119     char      *psz_url;
120     char      *psz_user;
121     char      *psz_password;
122     vlc_acl_t *p_acl;
123
124     struct
125     {
126         httpd_callback_t     cb;
127         httpd_callback_sys_t *p_sys;
128     } catch[HTTPD_MSG_MAX];
129 };
130
131 /* status */
132 enum
133 {
134     HTTPD_CLIENT_RECEIVING,
135     HTTPD_CLIENT_RECEIVE_DONE,
136
137     HTTPD_CLIENT_SENDING,
138     HTTPD_CLIENT_SEND_DONE,
139
140     HTTPD_CLIENT_WAITING,
141
142     HTTPD_CLIENT_DEAD,
143
144     HTTPD_CLIENT_TLS_HS_IN,
145     HTTPD_CLIENT_TLS_HS_OUT
146 };
147
148 /* mode */
149 enum
150 {
151     HTTPD_CLIENT_FILE,      /* default */
152     HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
153     HTTPD_CLIENT_BIDIR,     /* check for reading and get data from cb */
154 };
155
156 struct httpd_client_t
157 {
158     httpd_url_t *url;
159
160     int     i_ref;
161
162     int     fd;
163
164     int     i_mode;
165     int     i_state;
166     int     b_read_waiting; /* stop as soon as possible sending */
167
168     mtime_t i_activity_date;
169     mtime_t i_activity_timeout;
170
171     /* buffer for reading header */
172     int     i_buffer_size;
173     int     i_buffer;
174     uint8_t *p_buffer;
175
176     /* */
177     httpd_message_t query;  /* client -> httpd */
178     httpd_message_t answer; /* httpd -> client */
179
180     /* TLS data */
181     tls_session_t *p_tls;
182 };
183
184
185 /*****************************************************************************
186  * Various functions
187  *****************************************************************************/
188 static struct
189 {
190     const char psz_ext[8];
191     const char *psz_mime;
192 } http_mime[] =
193 {
194     { ".htm",   "text/html" },
195     { ".html",  "text/html" },
196     { ".txt",   "text/plain" },
197     { ".xml",   "text/xml" },
198     { ".dtd",   "text/dtd" },
199
200     { ".css",   "text/css" },
201
202     /* image mime */
203     { ".gif",   "image/gif" },
204     { ".jpe",   "image/jpeg" },
205     { ".jpg",   "image/jpeg" },
206     { ".jpeg",  "image/jpeg" },
207     { ".png",   "image/png" },
208     { ".mpjpeg","multipart/x-mixed-replace; boundary=This Random String" },
209
210     /* media mime */
211     { ".avi",   "video/avi" },
212     { ".asf",   "video/x-ms-asf" },
213     { ".m1a",   "audio/mpeg" },
214     { ".m2a",   "audio/mpeg" },
215     { ".m1v",   "video/mpeg" },
216     { ".m2v",   "video/mpeg" },
217     { ".mp2",   "audio/mpeg" },
218     { ".mp3",   "audio/mpeg" },
219     { ".mpa",   "audio/mpeg" },
220     { ".mpg",   "video/mpeg" },
221     { ".mpeg",  "video/mpeg" },
222     { ".mpe",   "video/mpeg" },
223     { ".mov",   "video/quicktime" },
224     { ".moov",  "video/quicktime" },
225     { ".ogg",   "application/ogg" },
226     { ".ogm",   "application/ogg" },
227     { ".wav",   "audio/wav" },
228     { ".wma",   "audio/x-ms-wma" },
229     { ".wmv",   "video/x-ms-wmv" },
230
231
232     /* end */
233     { "",       "" }
234 };
235
236 static const char *httpd_MimeFromUrl( const char *psz_url )
237 {
238
239     char *psz_ext;
240
241     psz_ext = strrchr( psz_url, '.' );
242     if( psz_ext )
243     {
244         int i;
245
246         for( i = 0; http_mime[i].psz_ext[0] ; i++ )
247         {
248             if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
249             {
250                 return http_mime[i].psz_mime;
251             }
252         }
253     }
254     return "application/octet-stream";
255 }
256
257
258 typedef struct
259 {
260     unsigned   i_code;
261     const char psz_reason[36];
262 } http_status_info;
263
264 static const http_status_info http_reason[] =
265 {
266   /*{ 100, "Continue" },
267     { 101, "Switching Protocols" },*/
268     { 200, "OK" },
269   /*{ 201, "Created" },
270     { 202, "Accepted" },
271     { 203, "Non-authoritative information" },
272     { 204, "No content" },
273     { 205, "Reset content" },
274     { 206, "Partial content" },
275     { 250, "Low on storage space" },
276     { 300, "Multiple choices" },*/
277     { 301, "Moved permanently" },
278   /*{ 302, "Moved temporarily" },
279     { 303, "See other" },
280     { 304, "Not modified" },
281     { 305, "Use proxy" },
282     { 307, "Temporary redirect" },
283     { 400, "Bad request" },*/
284     { 401, "Unauthorized" },
285   /*{ 402, "Payment Required" },*/
286     { 403, "Forbidden" },
287     { 404, "Not found" },
288     { 405, "Method not allowed" },
289   /*{ 406, "Not acceptable" },
290     { 407, "Proxy authentication required" },
291     { 408, "Request time-out" },
292     { 409, "Conflict" },
293     { 410, "Gone" },
294     { 411, "Length required" },
295     { 412, "Precondition failed" },
296     { 413, "Request entity too large" },
297     { 414, "Request-URI too large" },
298     { 415, "Unsupported media Type" },
299     { 416, "Requested range not satisfiable" },
300     { 417, "Expectation failed" },
301     { 451, "Parameter not understood" },
302     { 452, "Conference not found" },
303     { 453, "Not enough bandwidth" },*/
304     { 454, "Session not found" },
305   /*{ 455, "Method not valid in this State" },*/
306     { 456, "Header field not valid for resource" },
307   /*{ 457, "Invalid range" },
308     { 458, "Read-only parameter" },*/
309     { 459, "Aggregate operation not allowed" },
310     { 460, "Non-aggregate operation not allowed" },
311     { 461, "Unsupported transport" },
312   /*{ 462, "Destination unreachable" },*/
313     { 500, "Internal server error" },
314     { 501, "Not implemented" },
315   /*{ 502, "Bad gateway" },*/
316     { 503, "Service unavailable" },
317   /*{ 504, "Gateway time-out" },*/
318     { 505, "Protocol version not supported" },
319     { 551, "Option not supported" },
320     { 999, "" }
321 };
322
323 static const char psz_fallback_reason[5][16] =
324 { "Continue", "OK", "Found", "Client error", "Server error" };
325
326 static const char *httpd_ReasonFromCode( unsigned i_code )
327 {
328     const http_status_info *p;
329
330     assert( ( i_code >= 100 ) && ( i_code <= 599 ) );
331
332     for (p = http_reason; i_code > p->i_code; p++);
333
334     if( p->i_code == i_code )
335         return p->psz_reason;
336
337     return psz_fallback_reason[(i_code / 100) - 1];
338 }
339
340
341 static size_t httpd_HtmlError (char **body, int code, const char *url)
342 {
343     const char *errname = httpd_ReasonFromCode (code);
344     assert (errname != NULL);
345
346     int res = asprintf (body,
347         "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
348         "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
349         " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
350         "<html lang=\"en\">\n"
351         "<head>\n"
352         "<title>%s</title>\n"
353         "</head>\n"
354         "<body>\n"
355         "<h1>%d %s%s%s%s</h1>\n"
356         "<hr />\n"
357         "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
358         "</body>\n"
359         "</html>\n", errname, code, errname,
360         (url ? " (" : ""), (url ?: ""), (url ? ")" : ""));
361
362     if (res == -1)
363     {
364         *body = NULL;
365         return 0;
366     }
367
368     return (size_t)res;
369 }
370
371
372 /*****************************************************************************
373  * High Level Functions: httpd_file_t
374  *****************************************************************************/
375 struct httpd_file_t
376 {
377     httpd_url_t *url;
378
379     char *psz_url;
380     char *psz_mime;
381
382     httpd_file_callback_t pf_fill;
383     httpd_file_sys_t      *p_sys;
384
385 };
386
387 static int
388 httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
389                     httpd_message_t *answer, const httpd_message_t *query )
390 {
391     httpd_file_t *file = (httpd_file_t*)p_sys;
392     uint8_t *psz_args = query->psz_args;
393     uint8_t **pp_body, *p_body;
394     const char *psz_connection;
395     int *pi_body, i_body;
396
397     if( answer == NULL || query == NULL )
398     {
399         return VLC_SUCCESS;
400     }
401     answer->i_proto  = HTTPD_PROTO_HTTP;
402     answer->i_version= 1;
403     answer->i_type   = HTTPD_MSG_ANSWER;
404
405     answer->i_status = 200;
406
407     httpd_MsgAdd( answer, "Content-type",  "%s", file->psz_mime );
408     httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
409
410     if( query->i_type != HTTPD_MSG_HEAD )
411     {
412         pp_body = &answer->p_body;
413         pi_body = &answer->i_body;
414     }
415     else
416     {
417         /* The file still needs to be executed. */
418         p_body = NULL;
419         i_body = 0;
420         pp_body = &p_body;
421         pi_body = &i_body;
422     }
423
424     if( query->i_type == HTTPD_MSG_POST )
425     {
426         /* msg_Warn not supported */
427     }
428
429     file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );
430
431     if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
432     {
433         free( p_body );
434     }
435
436     /* We respect client request */
437     psz_connection = httpd_MsgGet( &cl->query, "Connection" );
438     if( psz_connection != NULL )
439     {
440         httpd_MsgAdd( answer, "Connection", "%s", psz_connection );
441     }
442
443     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
444
445     return VLC_SUCCESS;
446 }
447
448 httpd_file_t *httpd_FileNew( httpd_host_t *host,
449                              const char *psz_url, const char *psz_mime,
450                              const char *psz_user, const char *psz_password,
451                              const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
452                              httpd_file_sys_t *p_sys )
453 {
454     httpd_file_t *file = malloc( sizeof( httpd_file_t ) );
455
456     if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
457                                           psz_password, p_acl )
458         ) == NULL )
459     {
460         free( file );
461         return NULL;
462     }
463
464     file->psz_url  = strdup( psz_url );
465     if( psz_mime && *psz_mime )
466     {
467         file->psz_mime = strdup( psz_mime );
468     }
469     else
470     {
471         file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
472     }
473
474     file->pf_fill = pf_fill;
475     file->p_sys   = p_sys;
476
477     httpd_UrlCatch( file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
478                     (httpd_callback_sys_t*)file );
479     httpd_UrlCatch( file->url, HTTPD_MSG_GET,  httpd_FileCallBack,
480                     (httpd_callback_sys_t*)file );
481     httpd_UrlCatch( file->url, HTTPD_MSG_POST, httpd_FileCallBack,
482                     (httpd_callback_sys_t*)file );
483
484     return file;
485 }
486
487 httpd_file_sys_t *httpd_FileDelete( httpd_file_t *file )
488 {
489     httpd_file_sys_t *p_sys = file->p_sys;
490
491     httpd_UrlDelete( file->url );
492
493     free( file->psz_url );
494     free( file->psz_mime );
495
496     free( file );
497
498     return p_sys;
499 }
500
501 /*****************************************************************************
502  * High Level Functions: httpd_handler_t (for CGIs)
503  *****************************************************************************/
504 struct httpd_handler_t
505 {
506     httpd_url_t *url;
507
508     httpd_handler_callback_t pf_fill;
509     httpd_handler_sys_t      *p_sys;
510
511 };
512
513 static int
514 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
515                        httpd_message_t *answer, const httpd_message_t *query )
516 {
517     httpd_handler_t *handler = (httpd_handler_t*)p_sys;
518     uint8_t *psz_args = query->psz_args;
519     char psz_remote_addr[NI_MAXNUMERICHOST];
520
521     if( answer == NULL || query == NULL )
522     {
523         return VLC_SUCCESS;
524     }
525     answer->i_proto  = HTTPD_PROTO_NONE;
526     answer->i_type   = HTTPD_MSG_ANSWER;
527
528     /* We do it ourselves, thanks */
529     answer->i_status = 0;
530
531     if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
532         *psz_remote_addr = '\0';
533
534     handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
535                       query->i_type, query->p_body, query->i_body,
536                       psz_remote_addr, NULL,
537                       &answer->p_body, &answer->i_body );
538
539     if( query->i_type == HTTPD_MSG_HEAD )
540     {
541         char *p = (char *)answer->p_body;
542
543         /* Looks for end of header (i.e. one empty line) */
544         while ( (p = strchr( p, '\r' )) != NULL )
545         {
546             if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
547                  && p[3] && p[3] == '\n' )
548             {
549                 break;
550             }
551         }
552
553         if( p != NULL )
554         {
555             p[4] = '\0';
556             answer->i_body = strlen((char*)answer->p_body) + 1;
557             answer->p_body = realloc( answer->p_body, answer->i_body );
558         }
559     }
560
561     if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
562     {
563         int i_status, i_headers;
564         char *psz_headers, *psz_new;
565         const char *psz_status;
566
567         if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
568         {
569             /* Apache-style */
570             i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
571             if( *psz_headers ) psz_headers++;
572             if( *psz_headers ) psz_headers++;
573             i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
574         }
575         else
576         {
577             i_status = 200;
578             psz_headers = (char *)answer->p_body;
579             i_headers = answer->i_body;
580         }
581
582         psz_status = httpd_ReasonFromCode( i_status );
583         answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
584                         + strlen(psz_status) + i_headers - 1;
585         psz_new = (char *)malloc( answer->i_body + 1);
586         sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
587         memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
588         free( answer->p_body );
589         answer->p_body = (uint8_t *)psz_new;
590     }
591
592     return VLC_SUCCESS;
593 }
594
595 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
596                                    const char *psz_user,
597                                    const char *psz_password,
598                                    const vlc_acl_t *p_acl,
599                                    httpd_handler_callback_t pf_fill,
600                                    httpd_handler_sys_t *p_sys )
601 {
602     httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
603
604     if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
605                                              psz_password, p_acl )
606         ) == NULL )
607     {
608         free( handler );
609         return NULL;
610     }
611
612     handler->pf_fill = pf_fill;
613     handler->p_sys   = p_sys;
614
615     httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
616                     (httpd_callback_sys_t*)handler );
617     httpd_UrlCatch( handler->url, HTTPD_MSG_GET,  httpd_HandlerCallBack,
618                     (httpd_callback_sys_t*)handler );
619     httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
620                     (httpd_callback_sys_t*)handler );
621
622     return handler;
623 }
624
625 httpd_handler_sys_t *httpd_HandlerDelete( httpd_handler_t *handler )
626 {
627     httpd_handler_sys_t *p_sys = handler->p_sys;
628     httpd_UrlDelete( handler->url );
629     free( handler );
630     return p_sys;
631 }
632
633 /*****************************************************************************
634  * High Level Functions: httpd_redirect_t
635  *****************************************************************************/
636 struct httpd_redirect_t
637 {
638     httpd_url_t *url;
639     char        *psz_dst;
640 };
641
642 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
643                                    httpd_client_t *cl, httpd_message_t *answer,
644                                    const httpd_message_t *query )
645 {
646     httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
647     char *p_body;
648     (void)cl;
649
650     if( answer == NULL || query == NULL )
651     {
652         return VLC_SUCCESS;
653     }
654     answer->i_proto  = HTTPD_PROTO_HTTP;
655     answer->i_version= 1;
656     answer->i_type   = HTTPD_MSG_ANSWER;
657     answer->i_status = 301;
658
659     answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
660     answer->p_body = (unsigned char *)p_body;
661
662     /* XXX check if it's ok or we need to set an absolute url */
663     httpd_MsgAdd( answer, "Location",  "%s", rdir->psz_dst );
664
665     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
666
667     return VLC_SUCCESS;
668 }
669
670 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
671                                      const char *psz_url_src )
672 {
673     httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
674
675     if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
676     {
677         free( rdir );
678         return NULL;
679     }
680     rdir->psz_dst = strdup( psz_url_dst );
681
682     /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
683     httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
684                     (httpd_callback_sys_t*)rdir );
685     httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
686                     (httpd_callback_sys_t*)rdir );
687     httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
688                     (httpd_callback_sys_t*)rdir );
689     httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
690                     (httpd_callback_sys_t*)rdir );
691
692     return rdir;
693 }
694 void httpd_RedirectDelete( httpd_redirect_t *rdir )
695 {
696     httpd_UrlDelete( rdir->url );
697     free( rdir->psz_dst );
698     free( rdir );
699 }
700
701 /*****************************************************************************
702  * High Level Funtions: httpd_stream_t
703  *****************************************************************************/
704 struct httpd_stream_t
705 {
706     vlc_mutex_t lock;
707     httpd_url_t *url;
708
709     char    *psz_mime;
710
711     /* Header to send as first packet */
712     uint8_t *p_header;
713     int     i_header;
714
715     /* circular buffer */
716     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
717     uint8_t     *p_buffer;          /* buffer */
718     int64_t     i_buffer_pos;       /* absolute position from begining */
719     int64_t     i_buffer_last_pos;  /* a new connection will start with that */
720 };
721
722 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
723                                  httpd_client_t *cl, httpd_message_t *answer,
724                                  const httpd_message_t *query )
725 {
726     httpd_stream_t *stream = (httpd_stream_t*)p_sys;
727
728     if( answer == NULL || query == NULL || cl == NULL )
729     {
730         return VLC_SUCCESS;
731     }
732
733     if( answer->i_body_offset > 0 )
734     {
735         int64_t i_write;
736         int     i_pos;
737
738 #if 0
739         fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
740                  answer->i_body_offset );
741 #endif
742
743         if( answer->i_body_offset >= stream->i_buffer_pos )
744         {
745             /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
746             return VLC_EGENERIC;    /* wait, no data available */
747         }
748         if( answer->i_body_offset + stream->i_buffer_size <
749             stream->i_buffer_pos )
750         {
751             /* this client isn't fast enough */
752 #if 0
753             fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
754                      answer->i_body_offset, stream->i_buffer_last_pos );
755 #endif
756             answer->i_body_offset = stream->i_buffer_last_pos;
757         }
758
759         i_pos   = answer->i_body_offset % stream->i_buffer_size;
760         i_write = stream->i_buffer_pos - answer->i_body_offset;
761         if( i_write > HTTPD_CL_BUFSIZE )
762         {
763             i_write = HTTPD_CL_BUFSIZE;
764         }
765         else if( i_write <= 0 )
766         {
767             return VLC_EGENERIC;    /* wait, no data available */
768         }
769
770         /* Don't go past the end of the circular buffer */
771         i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
772
773         /* using HTTPD_MSG_ANSWER -> data available */
774         answer->i_proto  = HTTPD_PROTO_HTTP;
775         answer->i_version= 0;
776         answer->i_type   = HTTPD_MSG_ANSWER;
777
778         answer->i_body = i_write;
779         answer->p_body = malloc( i_write );
780         memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
781
782         answer->i_body_offset += i_write;
783
784         return VLC_SUCCESS;
785     }
786     else
787     {
788         answer->i_proto  = HTTPD_PROTO_HTTP;
789         answer->i_version= 0;
790         answer->i_type   = HTTPD_MSG_ANSWER;
791
792         answer->i_status = 200;
793
794         if( query->i_type != HTTPD_MSG_HEAD )
795         {
796             httpd_ClientModeStream( cl );
797             vlc_mutex_lock( &stream->lock );
798             /* Send the header */
799             if( stream->i_header > 0 )
800             {
801                 answer->i_body = stream->i_header;
802                 answer->p_body = malloc( stream->i_header );
803                 memcpy( answer->p_body, stream->p_header, stream->i_header );
804             }
805             answer->i_body_offset = stream->i_buffer_last_pos;
806             vlc_mutex_unlock( &stream->lock );
807         }
808         else
809         {
810             httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
811             answer->i_body_offset = 0;
812         }
813
814         if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
815         {
816             vlc_bool_t b_xplaystream = VLC_FALSE;
817             int i;
818
819             httpd_MsgAdd( answer, "Content-type", "%s",
820                           "application/octet-stream" );
821             httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
822             httpd_MsgAdd( answer, "Pragma", "no-cache" );
823             httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
824             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
825
826             /* Check if there is a xPlayStrm=1 */
827             for( i = 0; i < query->i_name; i++ )
828             {
829                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
830                     strstr( query->value[i], "xPlayStrm=1" ) )
831                 {
832                     b_xplaystream = VLC_TRUE;
833                 }
834             }
835
836             if( !b_xplaystream )
837             {
838                 answer->i_body_offset = 0;
839             }
840         }
841         else
842         {
843             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
844         }
845         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
846         return VLC_SUCCESS;
847     }
848 }
849
850 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
851                                  const char *psz_url, const char *psz_mime,
852                                  const char *psz_user, const char *psz_password,
853                                  const vlc_acl_t *p_acl )
854 {
855     httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
856
857     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
858                                             psz_password, p_acl )
859         ) == NULL )
860     {
861         free( stream );
862         return NULL;
863     }
864     vlc_mutex_init( host, &stream->lock );
865     if( psz_mime && *psz_mime )
866     {
867         stream->psz_mime = strdup( psz_mime );
868     }
869     else
870     {
871         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
872     }
873     stream->i_header = 0;
874     stream->p_header = NULL;
875     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
876     stream->p_buffer = malloc( stream->i_buffer_size );
877     /* We set to 1 to make life simpler
878      * (this way i_body_offset can never be 0) */
879     stream->i_buffer_pos = 1;
880     stream->i_buffer_last_pos = 1;
881
882     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
883                     (httpd_callback_sys_t*)stream );
884     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
885                     (httpd_callback_sys_t*)stream );
886     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
887                     (httpd_callback_sys_t*)stream );
888
889     return stream;
890 }
891
892 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
893 {
894     vlc_mutex_lock( &stream->lock );
895     if( stream->p_header )
896     {
897         free( stream->p_header );
898         stream->p_header = NULL;
899     }
900     stream->i_header = i_data;
901     if( i_data > 0 )
902     {
903         stream->p_header = malloc( i_data );
904         memcpy( stream->p_header, p_data, i_data );
905     }
906     vlc_mutex_unlock( &stream->lock );
907
908     return VLC_SUCCESS;
909 }
910
911 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
912 {
913     int i_count;
914     int i_pos;
915
916     if( i_data < 0 || p_data == NULL )
917     {
918         return VLC_SUCCESS;
919     }
920     vlc_mutex_lock( &stream->lock );
921
922     /* save this pointer (to be used by new connection) */
923     stream->i_buffer_last_pos = stream->i_buffer_pos;
924
925     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
926     i_count = i_data;
927     while( i_count > 0)
928     {
929         int i_copy;
930
931         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
932
933         /* Ok, we can't go past the end of our buffer */
934         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
935
936         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
937         i_count -= i_copy;
938         p_data  += i_copy;
939     }
940
941     stream->i_buffer_pos += i_data;
942
943     vlc_mutex_unlock( &stream->lock );
944     return VLC_SUCCESS;
945 }
946
947 void httpd_StreamDelete( httpd_stream_t *stream )
948 {
949     httpd_UrlDelete( stream->url );
950     vlc_mutex_destroy( &stream->lock );
951     if( stream->psz_mime ) free( stream->psz_mime );
952     if( stream->p_header ) free( stream->p_header );
953     if( stream->p_buffer ) free( stream->p_buffer );
954     free( stream );
955 }
956
957 /*****************************************************************************
958  * Low level
959  *****************************************************************************/
960 static void httpd_HostThread( httpd_host_t * );
961
962 /* create a new host */
963 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
964                              int i_port )
965 {
966     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
967                            );
968 }
969
970 static const char psz_object_type[] = "http server";
971
972 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
973                                 int i_port,
974                                 const char *psz_cert, const char *psz_key,
975                                 const char *psz_ca, const char *psz_crl )
976 {
977     httpd_t      *httpd;
978     httpd_host_t *host;
979     tls_server_t *p_tls;
980     char *psz_host;
981     vlc_value_t  lockval;
982     int i;
983
984     if( psz_hostname == NULL )
985         psz_hostname = "";
986
987     psz_host = strdup( psz_hostname );
988     if( psz_host == NULL )
989     {
990         msg_Err( p_this, "memory error" );
991         return NULL;
992     }
993
994     /* to be sure to avoid multiple creation */
995     var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
996     var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
997     vlc_mutex_lock( lockval.p_address );
998
999     if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
1000     {
1001         msg_Info( p_this, "creating httpd" );
1002         httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
1003                                               VLC_OBJECT_HTTPD,
1004                                               psz_object_type );
1005         if (httpd == NULL)
1006         {
1007             vlc_mutex_unlock( lockval.p_address );
1008             free( psz_host );
1009             return NULL;
1010         }
1011
1012         httpd->i_host = 0;
1013         httpd->host   = NULL;
1014
1015         vlc_object_yield( httpd );
1016         vlc_object_attach( httpd, p_this->p_libvlc );
1017     }
1018
1019     /* verify if it already exist */
1020     for( i = httpd->i_host - 1; i >= 0; i-- )
1021     {
1022         host = httpd->host[i];
1023
1024         /* cannot mix TLS and non-TLS hosts */
1025         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1026          || ( host->i_port != i_port )
1027          || strcmp( host->psz_hostname, psz_hostname ) )
1028             continue;
1029
1030         /* yep found */
1031         host->i_ref++;
1032
1033         vlc_mutex_unlock( lockval.p_address );
1034         return host;
1035     }
1036
1037     host = NULL;
1038
1039     /* determine TLS configuration */
1040     if ( psz_cert != NULL )
1041     {
1042         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1043         if ( p_tls == NULL )
1044         {
1045             msg_Err( p_this, "TLS initialization error" );
1046             goto error;
1047         }
1048
1049         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1050         {
1051             msg_Err( p_this, "TLS CA error" );
1052             goto error;
1053         }
1054
1055         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1056         {
1057             msg_Err( p_this, "TLS CRL error" );
1058             goto error;
1059         }
1060     }
1061     else
1062         p_tls = NULL;
1063
1064     /* create the new host */
1065     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1066                                               VLC_OBJECT_HTTPD_HOST,
1067                                               psz_object_type );
1068     if (host == NULL)
1069         goto error;
1070
1071     vlc_object_lock( host );
1072     if( vlc_object_waitpipe( VLC_OBJECT( host ) ) == -1 )
1073     {
1074         msg_Err( host, "signaling pipe error: %m" );
1075         vlc_object_unlock( host );
1076         goto error;
1077     }
1078     vlc_object_unlock( host );
1079
1080     host->httpd = httpd;
1081     vlc_mutex_init( httpd, &host->lock );
1082     host->i_ref = 1;
1083
1084     host->fds = net_ListenTCP( p_this, psz_host, i_port );
1085     if( host->fds == NULL )
1086     {
1087         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1088         goto error;
1089     }
1090     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1091
1092     host->i_port = i_port;
1093     host->psz_hostname = psz_host;
1094
1095     host->i_url     = 0;
1096     host->url       = NULL;
1097     host->i_client  = 0;
1098     host->client    = NULL;
1099
1100     host->p_tls = p_tls;
1101
1102     /* create the thread */
1103     if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1104                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1105     {
1106         msg_Err( p_this, "cannot spawn http host thread" );
1107         goto error;
1108     }
1109
1110     /* now add it to httpd */
1111     TAB_APPEND( httpd->i_host, httpd->host, host );
1112     vlc_mutex_unlock( lockval.p_address );
1113
1114     return host;
1115
1116 error:
1117     free( psz_host );
1118     if( httpd->i_host <= 0 )
1119     {
1120         vlc_object_release( httpd );
1121         vlc_object_detach( httpd );
1122         vlc_object_destroy( httpd );
1123     }
1124     vlc_mutex_unlock( lockval.p_address );
1125
1126     if( host != NULL )
1127     {
1128         net_ListenClose( host->fds );
1129         vlc_mutex_destroy( &host->lock );
1130         vlc_object_destroy( host );
1131     }
1132
1133     if( p_tls != NULL )
1134         tls_ServerDelete( p_tls );
1135
1136     return NULL;
1137 }
1138
1139 /* delete a host */
1140 void httpd_HostDelete( httpd_host_t *host )
1141 {
1142     httpd_t *httpd = host->httpd;
1143     vlc_value_t lockval;
1144     int i;
1145
1146     var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1147     vlc_mutex_lock( lockval.p_address );
1148
1149     host->i_ref--;
1150     if( host->i_ref > 0 )
1151     {
1152         /* still used */
1153         vlc_mutex_unlock( lockval.p_address );
1154         msg_Dbg( host, "httpd_HostDelete: host still used" );
1155         return;
1156     }
1157     TAB_REMOVE( httpd->i_host, httpd->host, host );
1158
1159     vlc_object_kill( host );
1160     vlc_thread_join( host );
1161
1162     msg_Dbg( host, "HTTP host removed" );
1163
1164     for( i = 0; i < host->i_url; i++ )
1165     {
1166         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1167     }
1168     for( i = 0; i < host->i_client; i++ )
1169     {
1170         httpd_client_t *cl = host->client[i];
1171         msg_Warn( host, "client still connected" );
1172         httpd_ClientClean( cl );
1173         TAB_REMOVE( host->i_client, host->client, cl );
1174         free( cl );
1175         i--;
1176         /* TODO */
1177     }
1178
1179     if( host->p_tls != NULL)
1180         tls_ServerDelete( host->p_tls );
1181
1182     net_ListenClose( host->fds );
1183     free( host->psz_hostname );
1184
1185     vlc_mutex_destroy( &host->lock );
1186     vlc_object_destroy( host );
1187
1188     vlc_object_release( httpd );
1189     if( httpd->i_host <= 0 )
1190     {
1191         msg_Dbg( httpd, "no host left, stopping httpd" );
1192         vlc_object_detach( httpd );
1193         vlc_object_destroy( httpd );
1194     }
1195     vlc_mutex_unlock( lockval.p_address );
1196 }
1197
1198 /* register a new url */
1199 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1200                                          const char *psz_user, const char *psz_password,
1201                                          const vlc_acl_t *p_acl, vlc_bool_t b_check )
1202 {
1203     httpd_url_t *url;
1204     int         i;
1205
1206     assert( psz_url != NULL );
1207
1208     vlc_mutex_lock( &host->lock );
1209     if( b_check )
1210     {
1211         for( i = 0; i < host->i_url; i++ )
1212         {
1213             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1214             {
1215                 msg_Warn( host->httpd,
1216                           "cannot add '%s' (url already defined)", psz_url );
1217                 vlc_mutex_unlock( &host->lock );
1218                 return NULL;
1219             }
1220         }
1221     }
1222
1223     url = malloc( sizeof( httpd_url_t ) );
1224     url->host = host;
1225
1226     vlc_mutex_init( host->httpd, &url->lock );
1227     url->psz_url = strdup( psz_url );
1228     url->psz_user = strdup( psz_user ? psz_user : "" );
1229     url->psz_password = strdup( psz_password ? psz_password : "" );
1230     url->p_acl = ACL_Duplicate( host, p_acl );
1231     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1232     {
1233         url->catch[i].cb = NULL;
1234         url->catch[i].p_sys = NULL;
1235     }
1236
1237     TAB_APPEND( host->i_url, host->url, url );
1238     vlc_mutex_unlock( &host->lock );
1239
1240     return url;
1241 }
1242
1243 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1244                            const char *psz_user, const char *psz_password,
1245                            const vlc_acl_t *p_acl )
1246 {
1247     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1248                                 psz_password, p_acl, VLC_FALSE );
1249 }
1250
1251 httpd_url_t *httpd_UrlNewUnique( 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, VLC_TRUE );
1257 }
1258
1259 /* register callback on a url */
1260 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1261                     httpd_callback_sys_t *p_sys )
1262 {
1263     vlc_mutex_lock( &url->lock );
1264     url->catch[i_msg].cb   = cb;
1265     url->catch[i_msg].p_sys= p_sys;
1266     vlc_mutex_unlock( &url->lock );
1267
1268     return VLC_SUCCESS;
1269 }
1270
1271 /* delete an url */
1272 void httpd_UrlDelete( httpd_url_t *url )
1273 {
1274     httpd_host_t *host = url->host;
1275     int          i;
1276
1277     vlc_mutex_lock( &host->lock );
1278     TAB_REMOVE( host->i_url, host->url, url );
1279
1280     vlc_mutex_destroy( &url->lock );
1281     free( url->psz_url );
1282     free( url->psz_user );
1283     free( url->psz_password );
1284     ACL_Destroy( url->p_acl );
1285
1286     for( i = 0; i < host->i_client; i++ )
1287     {
1288         httpd_client_t *client = host->client[i];
1289
1290         if( client->url == url )
1291         {
1292             /* TODO complete it */
1293             msg_Warn( host, "force closing connections" );
1294             httpd_ClientClean( client );
1295             TAB_REMOVE( host->i_client, host->client, client );
1296             free( client );
1297             i--;
1298         }
1299     }
1300     free( url );
1301     vlc_mutex_unlock( &host->lock );
1302 }
1303
1304 void httpd_MsgInit( httpd_message_t *msg )
1305 {
1306     msg->cl         = NULL;
1307     msg->i_type     = HTTPD_MSG_NONE;
1308     msg->i_proto    = HTTPD_PROTO_NONE;
1309     msg->i_version  = -1; /* FIXME */
1310
1311     msg->i_status   = 0;
1312
1313     msg->psz_url    = NULL;
1314     msg->psz_args   = NULL;
1315
1316     msg->i_channel  = -1;
1317
1318     msg->i_name     = 0;
1319     msg->name       = NULL;
1320     msg->i_value    = 0;
1321     msg->value      = NULL;
1322
1323     msg->i_body_offset = 0;
1324     msg->i_body        = 0;
1325     msg->p_body        = NULL;
1326 }
1327
1328 void httpd_MsgClean( httpd_message_t *msg )
1329 {
1330     int i;
1331
1332     if( msg->psz_url )
1333     {
1334         free( msg->psz_url );
1335     }
1336     if( msg->psz_args )
1337     {
1338         free( msg->psz_args );
1339     }
1340     for( i = 0; i < msg->i_name; i++ )
1341     {
1342         free( msg->name[i] );
1343         free( msg->value[i] );
1344     }
1345     if( msg->name )
1346     {
1347         free( msg->name );
1348     }
1349     if( msg->value )
1350     {
1351         free( msg->value );
1352     }
1353     if( msg->p_body )
1354     {
1355         free( msg->p_body );
1356     }
1357     httpd_MsgInit( msg );
1358 }
1359
1360 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1361 {
1362     int i;
1363
1364     for( i = 0; i < msg->i_name; i++ )
1365     {
1366         if( !strcasecmp( msg->name[i], name ))
1367         {
1368             return msg->value[i];
1369         }
1370     }
1371     return NULL;
1372 }
1373
1374 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1375 {
1376     va_list args;
1377     char *value = NULL;
1378
1379     va_start( args, psz_value );
1380     if( vasprintf( &value, psz_value, args ) == -1 )
1381         value = NULL;
1382     va_end( args );
1383
1384     if( value == NULL )
1385         return;
1386
1387     name = strdup( name );
1388     if( name == NULL )
1389     {
1390         free( value );
1391         return;
1392     }
1393
1394     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1395     TAB_APPEND( msg->i_value, msg->value, value );
1396 }
1397
1398 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1399 {
1400     cl->i_state = HTTPD_CLIENT_RECEIVING;
1401     cl->i_activity_date = now;
1402     cl->i_activity_timeout = I64C(10000000);
1403     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1404     cl->i_buffer = 0;
1405     cl->p_buffer = malloc( cl->i_buffer_size );
1406     cl->i_mode   = HTTPD_CLIENT_FILE;
1407     cl->b_read_waiting = VLC_FALSE;
1408
1409     httpd_MsgInit( &cl->query );
1410     httpd_MsgInit( &cl->answer );
1411 }
1412
1413 void httpd_ClientModeStream( httpd_client_t *cl )
1414 {
1415     cl->i_mode   = HTTPD_CLIENT_STREAM;
1416 }
1417
1418 void httpd_ClientModeBidir( httpd_client_t *cl )
1419 {
1420     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1421 }
1422
1423 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1424 {
1425     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1426 }
1427
1428 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1429 {
1430     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1431 }
1432
1433 static void httpd_ClientClean( httpd_client_t *cl )
1434 {
1435     if( cl->fd >= 0 )
1436     {
1437         if( cl->p_tls != NULL )
1438             tls_ServerSessionClose( cl->p_tls );
1439         net_Close( cl->fd );
1440         cl->fd = -1;
1441     }
1442
1443     httpd_MsgClean( &cl->answer );
1444     httpd_MsgClean( &cl->query );
1445
1446     if( cl->p_buffer )
1447     {
1448         free( cl->p_buffer );
1449         cl->p_buffer = NULL;
1450     }
1451 }
1452
1453 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1454 {
1455     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1456
1457     if( !cl ) return NULL;
1458
1459     cl->i_ref   = 0;
1460     cl->fd      = fd;
1461     cl->url     = NULL;
1462     cl->p_tls = p_tls;
1463
1464     httpd_ClientInit( cl, now );
1465
1466     return cl;
1467 }
1468
1469 static int httpd_NetRecv( httpd_client_t *cl, uint8_t *p, int i_len )
1470 {
1471     tls_session_t *p_tls;
1472
1473     p_tls = cl->p_tls;
1474     if( p_tls != NULL)
1475         return tls_Recv( p_tls, p, i_len );
1476
1477     return recv( cl->fd, p, i_len, 0 );
1478 }
1479
1480 static int httpd_NetSend( httpd_client_t *cl, const uint8_t *p, int i_len )
1481 {
1482     tls_session_t *p_tls;
1483
1484     p_tls = cl->p_tls;
1485     if( p_tls != NULL)
1486         return tls_Send( p_tls, p, i_len );
1487
1488     return send( cl->fd, p, i_len, 0 );
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  = malloc( 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, "rtsp:", 5 ) )
1754                         {
1755                             /* for rtsp url, you have rtsp://localhost:port/path */
1756                             p += 5;
1757                             while( *p == '/' ) p++;
1758                             while( *p && *p != '/' ) p++;
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 && errno != EINTR ) || ( 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 && errno != EINTR ) || ( 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( httpd_host_t *host )
2029 {
2030     tls_session_t *p_tls = NULL;
2031     counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2032     counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
2033     int evfd;
2034     vlc_bool_t b_die;
2035
2036     vlc_object_lock( host );
2037     evfd = vlc_object_waitpipe( VLC_OBJECT( host ) );
2038     b_die = !vlc_object_alive( host );
2039     vlc_object_unlock( host );
2040
2041     while( !b_die )
2042     {
2043         if( host->i_url <= 0 )
2044         {
2045             /* 0.2s (FIXME: use a condition variable) */
2046             msleep( 200000 );
2047             continue;
2048         }
2049
2050         /* prepare a new TLS session */
2051         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
2052             p_tls = tls_ServerSessionPrepare( host->p_tls );
2053
2054         struct pollfd ufd[host->nfd + host->i_client + 1];
2055         unsigned nfd;
2056         for( nfd = 0; nfd < host->nfd; nfd++ )
2057         {
2058             ufd[nfd].fd = host->fds[nfd];
2059             ufd[nfd].events = POLLIN;
2060             ufd[nfd].revents = 0;
2061         }
2062
2063         /* add all socket that should be read/write and close dead connection */
2064         vlc_mutex_lock( &host->lock );
2065         mtime_t now = mdate();
2066         vlc_bool_t b_low_delay = VLC_FALSE;
2067
2068         for(int i_client = 0; i_client < host->i_client; i_client++ )
2069         {
2070             httpd_client_t *cl = host->client[i_client];
2071             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
2072                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
2073                   ( cl->i_activity_timeout > 0 &&
2074                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
2075             {
2076                 httpd_ClientClean( cl );
2077                 stats_UpdateInteger( host, p_active_counter, -1, NULL );
2078                 TAB_REMOVE( host->i_client, host->client, cl );
2079                 free( cl );
2080                 i_client--;
2081                 continue;
2082             }
2083
2084             struct pollfd *pufd = ufd + nfd;
2085             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
2086
2087             pufd->fd = cl->fd;
2088             pufd->events = pufd->revents = 0;
2089
2090             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
2091                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
2092             {
2093                 pufd->events = POLLIN;
2094             }
2095             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
2096                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
2097             {
2098                 pufd->events = POLLOUT;
2099             }
2100             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2101             {
2102                 httpd_message_t *answer = &cl->answer;
2103                 httpd_message_t *query  = &cl->query;
2104                 int i_msg = query->i_type;
2105
2106                 httpd_MsgInit( answer );
2107
2108                 /* Handle what we received */
2109                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2110                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2111                 {
2112                     /* we can only receive request from client when not
2113                      * in BIDIR mode */
2114                     cl->url     = NULL;
2115                     cl->i_state = HTTPD_CLIENT_DEAD;
2116                 }
2117                 else if( i_msg == HTTPD_MSG_ANSWER )
2118                 {
2119                     /* We are in BIDIR mode, trigger the callback and then
2120                      * check for new data */
2121                     if( cl->url && cl->url->catch[i_msg].cb )
2122                     {
2123                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2124                                                   cl, NULL, query );
2125                     }
2126                     cl->i_state = HTTPD_CLIENT_WAITING;
2127                 }
2128                 else if( i_msg == HTTPD_MSG_CHANNEL )
2129                 {
2130                     /* We are in BIDIR mode, trigger the callback and then
2131                      * check for new data */
2132                     if( cl->url && cl->url->catch[i_msg].cb )
2133                     {
2134                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2135                                                   cl, NULL, query );
2136                     }
2137                     cl->i_state = HTTPD_CLIENT_WAITING;
2138                 }
2139                 else if( i_msg == HTTPD_MSG_OPTIONS )
2140                 {
2141
2142                     answer->i_type   = HTTPD_MSG_ANSWER;
2143                     answer->i_proto  = query->i_proto;
2144                     answer->i_status = 200;
2145                     answer->i_body = 0;
2146                     answer->p_body = NULL;
2147
2148                     httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2149                     httpd_MsgAdd( answer, "Content-Length", "0" );
2150
2151                     switch( query->i_proto )
2152                     {
2153                         case HTTPD_PROTO_HTTP:
2154                             answer->i_version = 1;
2155                             httpd_MsgAdd( answer, "Allow",
2156                                           "GET,HEAD,POST,OPTIONS" );
2157                             break;
2158
2159                         case HTTPD_PROTO_RTSP:
2160                         {
2161                             const char *p;
2162                             answer->i_version = 0;
2163
2164                             p = httpd_MsgGet( query, "Cseq" );
2165                             if( p != NULL )
2166                                 httpd_MsgAdd( answer, "Cseq", "%s", p );
2167                             p = httpd_MsgGet( query, "Timestamp" );
2168                             if( p != NULL )
2169                                 httpd_MsgAdd( answer, "Timestamp", "%s", p );
2170
2171                             p = httpd_MsgGet( query, "Require" );
2172                             if( p != NULL )
2173                             {
2174                                 answer->i_status = 551;
2175                                 httpd_MsgAdd( query, "Unsupported", "%s", p );
2176                             }
2177
2178                             httpd_MsgAdd( answer, "Public", "DESCRIBE,SETUP,"
2179                                           "TEARDOWN,PLAY,PAUSE,GET_PARAMETER" );
2180                             break;
2181                         }
2182                     }
2183
2184                     cl->i_buffer = -1;  /* Force the creation of the answer in
2185                                          * httpd_ClientSend */
2186                     cl->i_state = HTTPD_CLIENT_SENDING;
2187                 }
2188                 else if( i_msg == HTTPD_MSG_NONE )
2189                 {
2190                     if( query->i_proto == HTTPD_PROTO_NONE )
2191                     {
2192                         cl->url = NULL;
2193                         cl->i_state = HTTPD_CLIENT_DEAD;
2194                     }
2195                     else
2196                     {
2197                         char *p;
2198
2199                         /* unimplemented */
2200                         answer->i_proto  = query->i_proto ;
2201                         answer->i_type   = HTTPD_MSG_ANSWER;
2202                         answer->i_version= 0;
2203                         answer->i_status = 501;
2204
2205                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2206                         answer->p_body = (uint8_t *)p;
2207                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2208
2209                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2210                         cl->i_state = HTTPD_CLIENT_SENDING;
2211                     }
2212                 }
2213                 else
2214                 {
2215                     vlc_bool_t b_auth_failed = VLC_FALSE;
2216                     vlc_bool_t b_hosts_failed = VLC_FALSE;
2217
2218                     /* Search the url and trigger callbacks */
2219                     for(int i = 0; i < host->i_url; i++ )
2220                     {
2221                         httpd_url_t *url = host->url[i];
2222
2223                         if( !strcmp( url->psz_url, query->psz_url ) )
2224                         {
2225                             if( url->catch[i_msg].cb )
2226                             {
2227                                 if( answer && ( url->p_acl != NULL ) )
2228                                 {
2229                                     char ip[NI_MAXNUMERICHOST];
2230
2231                                     if( ( httpd_ClientIP( cl, ip ) == NULL )
2232                                      || ACL_Check( url->p_acl, ip ) )
2233                                     {
2234                                         b_hosts_failed = VLC_TRUE;
2235                                         break;
2236                                     }
2237                                 }
2238
2239                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2240                                 {
2241                                     /* create the headers */
2242                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2243                                     char *user = NULL, *pass = NULL;
2244
2245                                     if( b64 != NULL
2246                                      && !strncasecmp( b64, "BASIC", 5 ) )
2247                                     {
2248                                         b64 += 5;
2249                                         while( *b64 == ' ' )
2250                                             b64++;
2251
2252                                         user = vlc_b64_decode( b64 );
2253                                         if (user != NULL)
2254                                         {
2255                                             pass = strchr (user, ':');
2256                                             if (pass != NULL)
2257                                                 *pass++ = '\0';
2258                                         }
2259                                     }
2260
2261                                     if ((user == NULL) || (pass == NULL)
2262                                      || strcmp (user, url->psz_user)
2263                                      || strcmp (pass, url->psz_password))
2264                                     {
2265                                         httpd_MsgAdd( answer,
2266                                                       "WWW-Authenticate",
2267                                                       "Basic realm=\"%s\"",
2268                                                       url->psz_user );
2269                                         /* We fail for all url */
2270                                         b_auth_failed = VLC_TRUE;
2271                                         free( user );
2272                                         break;
2273                                     }
2274
2275                                     free( user );
2276                                 }
2277
2278                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2279                                 {
2280                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2281                                     {
2282                                         /* Raw answer from a CGI */
2283                                         cl->i_buffer = cl->i_buffer_size;
2284                                     }
2285                                     else
2286                                         cl->i_buffer = -1;
2287
2288                                     /* only one url can answer */
2289                                     answer = NULL;
2290                                     if( cl->url == NULL )
2291                                     {
2292                                         cl->url = url;
2293                                     }
2294                                 }
2295                             }
2296                         }
2297                     }
2298
2299                     if( answer )
2300                     {
2301                         char *p;
2302
2303                         answer->i_proto  = query->i_proto;
2304                         answer->i_type   = HTTPD_MSG_ANSWER;
2305                         answer->i_version= 0;
2306
2307                         if( b_hosts_failed )
2308                         {
2309                             answer->i_status = 403;
2310                         }
2311                         else if( b_auth_failed )
2312                         {
2313                             answer->i_status = 401;
2314                         }
2315                         else
2316                         {
2317                             /* no url registered */
2318                             answer->i_status = 404;
2319                         }
2320
2321                         answer->i_body = httpd_HtmlError (&p,
2322                                                           answer->i_status,
2323                                                           query->psz_url);
2324                         answer->p_body = (uint8_t *)p;
2325
2326                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2327                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2328                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2329                     }
2330
2331                     cl->i_state = HTTPD_CLIENT_SENDING;
2332                 }
2333             }
2334             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2335             {
2336                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2337                 {
2338                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2339                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2340                     vlc_bool_t b_connection = VLC_FALSE;
2341                     vlc_bool_t b_keepalive = VLC_FALSE;
2342                     vlc_bool_t b_query = VLC_FALSE;
2343
2344                     cl->url = NULL;
2345                     if( psz_connection )
2346                     {
2347                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2348                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2349                     }
2350
2351                     if( psz_query )
2352                     {
2353                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2354                     }
2355
2356                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2357                           ( ( cl->answer.i_version == 0 && b_keepalive ) ||
2358                             ( cl->answer.i_version == 1 && !b_connection ) ) ) ||
2359                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2360                           !b_query && !b_connection ) )
2361                     {
2362                         httpd_MsgClean( &cl->query );
2363                         httpd_MsgInit( &cl->query );
2364
2365                         cl->i_buffer = 0;
2366                         cl->i_buffer_size = 1000;
2367                         free( cl->p_buffer );
2368                         cl->p_buffer = malloc( cl->i_buffer_size );
2369                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2370                     }
2371                     else
2372                     {
2373                         cl->i_state = HTTPD_CLIENT_DEAD;
2374                     }
2375                     httpd_MsgClean( &cl->answer );
2376                 }
2377                 else if( cl->b_read_waiting )
2378                 {
2379                     /* we have a message waiting for us to read it */
2380                     httpd_MsgClean( &cl->answer );
2381                     httpd_MsgClean( &cl->query );
2382
2383                     cl->i_buffer = 0;
2384                     cl->i_buffer_size = 1000;
2385                     free( cl->p_buffer );
2386                     cl->p_buffer = malloc( cl->i_buffer_size );
2387                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2388                     cl->b_read_waiting = VLC_FALSE;
2389                 }
2390                 else
2391                 {
2392                     int64_t i_offset = cl->answer.i_body_offset;
2393                     httpd_MsgClean( &cl->answer );
2394
2395                     cl->answer.i_body_offset = i_offset;
2396                     free( cl->p_buffer );
2397                     cl->p_buffer = NULL;
2398                     cl->i_buffer = 0;
2399                     cl->i_buffer_size = 0;
2400
2401                     cl->i_state = HTTPD_CLIENT_WAITING;
2402                 }
2403             }
2404             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2405             {
2406                 int64_t i_offset = cl->answer.i_body_offset;
2407                 int     i_msg = cl->query.i_type;
2408
2409                 httpd_MsgInit( &cl->answer );
2410                 cl->answer.i_body_offset = i_offset;
2411
2412                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2413                                           &cl->answer, &cl->query );
2414                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2415                 {
2416                     /* we have new data, so re-enter send mode */
2417                     cl->i_buffer      = 0;
2418                     cl->p_buffer      = cl->answer.p_body;
2419                     cl->i_buffer_size = cl->answer.i_body;
2420                     cl->answer.p_body = NULL;
2421                     cl->answer.i_body = 0;
2422                     cl->i_state = HTTPD_CLIENT_SENDING;
2423                 }
2424             }
2425
2426             /* Special for BIDIR mode we also check reading */
2427             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2428                 cl->i_state == HTTPD_CLIENT_SENDING )
2429             {
2430                 pufd->events |= POLLIN;
2431             }
2432
2433             if (pufd->events != 0)
2434                 nfd++;
2435             else
2436                 b_low_delay = VLC_TRUE;
2437         }
2438         vlc_mutex_unlock( &host->lock );
2439
2440         ufd[nfd].fd = evfd;
2441         ufd[nfd].events = POLLIN;
2442         ufd[nfd].revents = 0;
2443         nfd++;
2444
2445         /* we will wait 20ms (not too big) if HTTPD_CLIENT_WAITING */
2446         switch( poll( ufd, nfd, b_low_delay ? 20 : -1) )
2447         {
2448             case -1:
2449                 if (errno != EINTR)
2450                 {
2451                     /* Kernel on low memory or a bug: pace */
2452                     msg_Err( host, "polling error: %m" );
2453                     msleep( 100000 );
2454                 }
2455             case 0:
2456                 continue;
2457         }
2458
2459         vlc_object_lock( host );
2460         if( ufd[nfd - 1].revents )
2461             b_die = vlc_object_wait( host );
2462         vlc_object_unlock( host );
2463
2464         /* Handle client sockets */
2465         vlc_mutex_lock( &host->lock );
2466         now = mdate();
2467         for( int i_client = 0; i_client < host->i_client; i_client++ )
2468         {
2469             httpd_client_t *cl = host->client[i_client];
2470             const struct pollfd *pufd = &ufd[host->nfd + i_client];
2471
2472             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2473
2474             if( cl->fd != pufd->fd )
2475                 continue; // we were not waiting for this client
2476             if( pufd->revents == 0 )
2477                 continue; // no event received
2478
2479             cl->i_activity_date = now;
2480
2481             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2482             {
2483                 httpd_ClientRecv( cl );
2484             }
2485             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2486             {
2487                 httpd_ClientSend( cl );
2488             }
2489             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2490             {
2491                 httpd_ClientTlsHsIn( cl );
2492             }
2493             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2494             {
2495                 httpd_ClientTlsHsOut( cl );
2496             }
2497
2498             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2499                 cl->i_state == HTTPD_CLIENT_SENDING &&
2500                 (pufd->revents & POLLIN) )
2501             {
2502                 cl->b_read_waiting = VLC_TRUE;
2503             }
2504         }
2505         vlc_mutex_unlock( &host->lock );
2506
2507         /* Handle server sockets (accept new connections) */
2508         for( nfd = 0; nfd < host->nfd; nfd++ )
2509         {
2510             httpd_client_t *cl;
2511             int i_state = -1;
2512             int fd = ufd[nfd].fd;
2513
2514             assert (fd == host->fds[nfd]);
2515
2516             if( ufd[nfd].revents == 0 )
2517                 continue;
2518
2519             /* */
2520             fd = accept (fd, NULL, NULL);
2521             if (fd == -1)
2522                 continue;
2523
2524             net_SetupSocket (fd);
2525             if( p_tls != NULL )
2526             {
2527                 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2528                 {
2529                     case -1:
2530                         msg_Err( host, "Rejecting TLS connection" );
2531                         net_Close( fd );
2532                         fd = -1;
2533                         p_tls = NULL;
2534                         break;
2535
2536                     case 1: /* missing input - most likely */
2537                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2538                         break;
2539
2540                     case 2: /* missing output */
2541                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2542                         break;
2543                 }
2544
2545                 if( (p_tls == NULL) != (host->p_tls == NULL) )
2546                     break; // wasted TLS session, cannot accept() anymore
2547             }
2548
2549             stats_UpdateInteger( host, p_total_counter, 1, NULL );
2550             stats_UpdateInteger( host, p_active_counter, 1, NULL );
2551             cl = httpd_ClientNew( fd, p_tls, now );
2552             p_tls = NULL;
2553             vlc_mutex_lock( &host->lock );
2554             TAB_APPEND( host->i_client, host->client, cl );
2555             vlc_mutex_unlock( &host->lock );
2556             if( i_state != -1 )
2557                 cl->i_state = i_state; // override state for TLS
2558
2559             if (host->p_tls != NULL)
2560                 break; // cannot accept further without new TLS session
2561         }
2562
2563     }
2564
2565     if( p_tls != NULL )
2566         tls_ServerSessionClose( p_tls );
2567     if( p_total_counter )
2568         stats_CounterClean( p_total_counter );
2569     if( p_active_counter )
2570         stats_CounterClean( p_active_counter );
2571 }
2572
2573 #else /* ENABLE_HTTPD */
2574
2575 /* We just define an empty wrapper */
2576 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2577                                 tls_server_t *d )
2578 {
2579     msg_Err( a, "HTTP daemon support is disabled" );
2580     return NULL;
2581 }
2582
2583 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2584 {
2585     msg_Err( a, "HTTP daemon support is disabled" );
2586     return NULL;
2587 }
2588
2589 void httpd_HostDelete( httpd_host_t *a )
2590 {
2591 }
2592
2593 httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
2594                            char *psz_user, char *psz_password,
2595                            const vlc_acl_t *p_acl )
2596 {
2597     return NULL;
2598 }
2599
2600 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
2601                                  char *psz_user, char *psz_password,
2602                                  const vlc_acl_t *p_acl )
2603 {
2604     return NULL;
2605 }
2606
2607 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2608                     httpd_callback_sys_t *d )
2609 {
2610     return 0;
2611 }
2612
2613 void httpd_UrlDelete( httpd_url_t *a )
2614 {
2615 }
2616
2617 char* httpd_ClientIP( httpd_client_t *cl, char *psz_ip )
2618 {
2619     return NULL;
2620 }
2621
2622 char* httpd_ServerIP( httpd_client_t *cl, char *psz_ip )
2623 {
2624     return NULL;
2625 }
2626
2627 void httpd_ClientModeStream( httpd_client_t *a )
2628 {
2629 }
2630
2631 void httpd_ClientModeBidir( httpd_client_t *a )
2632 {
2633 }
2634
2635 void httpd_FileDelete( httpd_file_t *a )
2636 {
2637 }
2638
2639 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2640                              char *e, httpd_file_callback_t f,
2641                              httpd_file_sys_t *g )
2642 {
2643     return NULL;
2644 }
2645
2646 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
2647                                    const char *psz_user,
2648                                    const char *psz_password,
2649                                    const vlc_acl_t *p_acl,
2650                                    httpd_handler_callback_t pf_fill,
2651                                    httpd_handler_sys_t *p_sys )
2652 {
2653     return NULL;
2654 }
2655
2656 void httpd_HandlerDelete( httpd_handler_t *handler )
2657 {
2658 }
2659
2660 void httpd_RedirectDelete( httpd_redirect_t *a )
2661 {
2662 }
2663
2664 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2665                                      char *b, char *c )
2666 {
2667     return NULL;
2668 }
2669
2670 void httpd_StreamDelete( httpd_stream_t *a )
2671 {
2672 }
2673
2674 int httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c )
2675 {
2676     return 0;
2677 }
2678
2679 int httpd_StreamSend ( httpd_stream_t *a, uint8_t *b, int c )
2680 {
2681     return 0;
2682 }
2683
2684 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2685                                  char *d, char *e )
2686 {
2687     return NULL;
2688 }
2689
2690 void httpd_MsgInit ( httpd_message_t *a )
2691 {
2692 }
2693
2694 void httpd_MsgAdd  ( httpd_message_t *a, const char *b, const char *c, ... )
2695 {
2696 }
2697
2698 const char *httpd_MsgGet ( httpd_message_t *a, const char *b )
2699 {
2700     return "";
2701 }
2702
2703 void httpd_MsgClean( httpd_message_t *a )
2704 {
2705 }
2706
2707 #endif /* ENABLE_HTTPD */