]> git.sesse.net Git - vlc/blob - src/network/httpd.c
Don't claim to support HTTP 1.x where x > 1
[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= (query->i_version > 1) ? 1 : query->i_version;
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", 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 void httpd_FileDelete( httpd_file_t *file )
488 {
489     httpd_UrlDelete( file->url );
490
491     free( file->psz_url );
492     free( file->psz_mime );
493
494     free( file );
495 }
496
497 /*****************************************************************************
498  * High Level Functions: httpd_handler_t (for CGIs)
499  *****************************************************************************/
500 struct httpd_handler_t
501 {
502     httpd_url_t *url;
503
504     httpd_handler_callback_t pf_fill;
505     httpd_handler_sys_t      *p_sys;
506
507 };
508
509 static int
510 httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl,
511                        httpd_message_t *answer, const httpd_message_t *query )
512 {
513     httpd_handler_t *handler = (httpd_handler_t*)p_sys;
514     uint8_t *psz_args = query->psz_args;
515     char psz_remote_addr[NI_MAXNUMERICHOST];
516
517     if( answer == NULL || query == NULL )
518     {
519         return VLC_SUCCESS;
520     }
521     answer->i_proto  = HTTPD_PROTO_NONE;
522     answer->i_type   = HTTPD_MSG_ANSWER;
523
524     /* We do it ourselves, thanks */
525     answer->i_status = 0;
526
527     if( httpd_ClientIP( cl, psz_remote_addr ) == NULL )
528         *psz_remote_addr = '\0';
529
530     handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
531                       query->i_type, query->p_body, query->i_body,
532                       psz_remote_addr, NULL,
533                       &answer->p_body, &answer->i_body );
534
535     if( query->i_type == HTTPD_MSG_HEAD )
536     {
537         char *p = (char *)answer->p_body;
538         while ( (p = strchr( p, '\r' )) != NULL )
539         {
540             if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
541                  && p[3] && p[3] == '\n' )
542             {
543                 break;
544             }
545         }
546         if( p != NULL )
547         {
548             p[4] = '\0';
549             answer->i_body = strlen((char*)answer->p_body) + 1;
550             answer->p_body = realloc( answer->p_body, answer->i_body );
551         }
552     }
553
554     if( strncmp( (char *)answer->p_body, "HTTP/1.", 7 ) )
555     {
556         int i_status, i_headers;
557         char *psz_headers, *psz_new;
558         const char *psz_status;
559
560         if( !strncmp( (char *)answer->p_body, "Status: ", 8 ) )
561         {
562             /* Apache-style */
563             i_status = strtol( (char *)&answer->p_body[8], &psz_headers, 0 );
564             if( *psz_headers ) psz_headers++;
565             if( *psz_headers ) psz_headers++;
566             i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
567         }
568         else
569         {
570             i_status = 200;
571             psz_headers = (char *)answer->p_body;
572             i_headers = answer->i_body;
573         }
574
575         psz_status = httpd_ReasonFromCode( i_status );
576         answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
577                         + strlen(psz_status) + i_headers - 1;
578         psz_new = (char *)malloc( answer->i_body + 1);
579         sprintf( psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status );
580         memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
581         free( answer->p_body );
582         answer->p_body = (uint8_t *)psz_new;
583     }
584
585     return VLC_SUCCESS;
586 }
587
588 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
589                                    const char *psz_user,
590                                    const char *psz_password,
591                                    const vlc_acl_t *p_acl,
592                                    httpd_handler_callback_t pf_fill,
593                                    httpd_handler_sys_t *p_sys )
594 {
595     httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );
596
597     if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
598                                              psz_password, p_acl )
599         ) == NULL )
600     {
601         free( handler );
602         return NULL;
603     }
604
605     handler->pf_fill = pf_fill;
606     handler->p_sys   = p_sys;
607
608     httpd_UrlCatch( handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
609                     (httpd_callback_sys_t*)handler );
610     httpd_UrlCatch( handler->url, HTTPD_MSG_GET,  httpd_HandlerCallBack,
611                     (httpd_callback_sys_t*)handler );
612     httpd_UrlCatch( handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
613                     (httpd_callback_sys_t*)handler );
614
615     return handler;
616 }
617
618 void httpd_HandlerDelete( httpd_handler_t *handler )
619 {
620     httpd_UrlDelete( handler->url );
621     free( handler );
622 }
623
624 /*****************************************************************************
625  * High Level Functions: httpd_redirect_t
626  *****************************************************************************/
627 struct httpd_redirect_t
628 {
629     httpd_url_t *url;
630     char        *psz_dst;
631 };
632
633 static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
634                                    httpd_client_t *cl, httpd_message_t *answer,
635                                    const httpd_message_t *query )
636 {
637     httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
638     char *p_body;
639     (void)cl;
640
641     if( answer == NULL || query == NULL )
642     {
643         return VLC_SUCCESS;
644     }
645     answer->i_proto  = HTTPD_PROTO_HTTP;
646     answer->i_version= (query->i_version > 1) ? 1 : query->i_version;
647     answer->i_type   = HTTPD_MSG_ANSWER;
648     answer->i_status = 301;
649
650     answer->i_body = httpd_HtmlError (&p_body, 301, rdir->psz_dst);
651     answer->p_body = (unsigned char *)p_body;
652
653     /* XXX check if it's ok or we need to set an absolute url */
654     httpd_MsgAdd( answer, "Location",  "%s", rdir->psz_dst );
655
656     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
657
658     return VLC_SUCCESS;
659 }
660
661 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
662                                      const char *psz_url_src )
663 {
664     httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );
665
666     if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
667     {
668         free( rdir );
669         return NULL;
670     }
671     rdir->psz_dst = strdup( psz_url_dst );
672
673     /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
674     httpd_UrlCatch( rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
675                     (httpd_callback_sys_t*)rdir );
676     httpd_UrlCatch( rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
677                     (httpd_callback_sys_t*)rdir );
678     httpd_UrlCatch( rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
679                     (httpd_callback_sys_t*)rdir );
680     httpd_UrlCatch( rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
681                     (httpd_callback_sys_t*)rdir );
682
683     return rdir;
684 }
685 void httpd_RedirectDelete( httpd_redirect_t *rdir )
686 {
687     httpd_UrlDelete( rdir->url );
688     free( rdir->psz_dst );
689     free( rdir );
690 }
691
692 /*****************************************************************************
693  * High Level Funtions: httpd_stream_t
694  *****************************************************************************/
695 struct httpd_stream_t
696 {
697     vlc_mutex_t lock;
698     httpd_url_t *url;
699
700     char    *psz_mime;
701
702     /* Header to send as first packet */
703     uint8_t *p_header;
704     int     i_header;
705
706     /* circular buffer */
707     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
708     uint8_t     *p_buffer;          /* buffer */
709     int64_t     i_buffer_pos;       /* absolute position from begining */
710     int64_t     i_buffer_last_pos;  /* a new connection will start with that */
711 };
712
713 static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
714                                  httpd_client_t *cl, httpd_message_t *answer,
715                                  const httpd_message_t *query )
716 {
717     httpd_stream_t *stream = (httpd_stream_t*)p_sys;
718
719     if( answer == NULL || query == NULL || cl == NULL )
720     {
721         return VLC_SUCCESS;
722     }
723
724     if( answer->i_body_offset > 0 )
725     {
726         int64_t i_write;
727         int     i_pos;
728
729 #if 0
730         fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
731                  answer->i_body_offset );
732 #endif
733
734         if( answer->i_body_offset >= stream->i_buffer_pos )
735         {
736             /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
737             return VLC_EGENERIC;    /* wait, no data available */
738         }
739         if( answer->i_body_offset + stream->i_buffer_size <
740             stream->i_buffer_pos )
741         {
742             /* this client isn't fast enough */
743 #if 0
744             fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
745                      answer->i_body_offset, stream->i_buffer_last_pos );
746 #endif
747             answer->i_body_offset = stream->i_buffer_last_pos;
748         }
749
750         i_pos   = answer->i_body_offset % stream->i_buffer_size;
751         i_write = stream->i_buffer_pos - answer->i_body_offset;
752         if( i_write > HTTPD_CL_BUFSIZE )
753         {
754             i_write = HTTPD_CL_BUFSIZE;
755         }
756         else if( i_write <= 0 )
757         {
758             return VLC_EGENERIC;    /* wait, no data available */
759         }
760
761         /* Don't go past the end of the circular buffer */
762         i_write = __MIN( i_write, stream->i_buffer_size - i_pos );
763
764         /* using HTTPD_MSG_ANSWER -> data available */
765         answer->i_proto  = HTTPD_PROTO_HTTP;
766         answer->i_version= 0;
767         answer->i_type   = HTTPD_MSG_ANSWER;
768
769         answer->i_body = i_write;
770         answer->p_body = malloc( i_write );
771         memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );
772
773         answer->i_body_offset += i_write;
774
775         return VLC_SUCCESS;
776     }
777     else
778     {
779         answer->i_proto  = HTTPD_PROTO_HTTP;
780         answer->i_version= 0;
781         answer->i_type   = HTTPD_MSG_ANSWER;
782
783         answer->i_status = 200;
784
785         if( query->i_type != HTTPD_MSG_HEAD )
786         {
787             httpd_ClientModeStream( cl );
788             vlc_mutex_lock( &stream->lock );
789             /* Send the header */
790             if( stream->i_header > 0 )
791             {
792                 answer->i_body = stream->i_header;
793                 answer->p_body = malloc( stream->i_header );
794                 memcpy( answer->p_body, stream->p_header, stream->i_header );
795             }
796             answer->i_body_offset = stream->i_buffer_last_pos;
797             vlc_mutex_unlock( &stream->lock );
798         }
799         else
800         {
801             httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
802             answer->i_body_offset = 0;
803         }
804
805         if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
806         {
807             vlc_bool_t b_xplaystream = VLC_FALSE;
808             int i;
809
810             httpd_MsgAdd( answer, "Content-type", "%s",
811                           "application/octet-stream" );
812             httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
813             httpd_MsgAdd( answer, "Pragma", "no-cache" );
814             httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
815             httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
816
817             /* Check if there is a xPlayStrm=1 */
818             for( i = 0; i < query->i_name; i++ )
819             {
820                 if( !strcasecmp( query->name[i],  "Pragma" ) &&
821                     strstr( query->value[i], "xPlayStrm=1" ) )
822                 {
823                     b_xplaystream = VLC_TRUE;
824                 }
825             }
826
827             if( !b_xplaystream )
828             {
829                 answer->i_body_offset = 0;
830             }
831         }
832         else
833         {
834             httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
835         }
836         httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
837         return VLC_SUCCESS;
838     }
839 }
840
841 httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
842                                  const char *psz_url, const char *psz_mime,
843                                  const char *psz_user, const char *psz_password,
844                                  const vlc_acl_t *p_acl )
845 {
846     httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );
847
848     if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
849                                             psz_password, p_acl )
850         ) == NULL )
851     {
852         free( stream );
853         return NULL;
854     }
855     vlc_mutex_init( host, &stream->lock );
856     if( psz_mime && *psz_mime )
857     {
858         stream->psz_mime = strdup( psz_mime );
859     }
860     else
861     {
862         stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
863     }
864     stream->i_header = 0;
865     stream->p_header = NULL;
866     stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
867     stream->p_buffer = malloc( stream->i_buffer_size );
868     /* We set to 1 to make life simpler
869      * (this way i_body_offset can never be 0) */
870     stream->i_buffer_pos = 1;
871     stream->i_buffer_last_pos = 1;
872
873     httpd_UrlCatch( stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
874                     (httpd_callback_sys_t*)stream );
875     httpd_UrlCatch( stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
876                     (httpd_callback_sys_t*)stream );
877     httpd_UrlCatch( stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
878                     (httpd_callback_sys_t*)stream );
879
880     return stream;
881 }
882
883 int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
884 {
885     vlc_mutex_lock( &stream->lock );
886     if( stream->p_header )
887     {
888         free( stream->p_header );
889         stream->p_header = NULL;
890     }
891     stream->i_header = i_data;
892     if( i_data > 0 )
893     {
894         stream->p_header = malloc( i_data );
895         memcpy( stream->p_header, p_data, i_data );
896     }
897     vlc_mutex_unlock( &stream->lock );
898
899     return VLC_SUCCESS;
900 }
901
902 int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
903 {
904     int i_count;
905     int i_pos;
906
907     if( i_data < 0 || p_data == NULL )
908     {
909         return VLC_SUCCESS;
910     }
911     vlc_mutex_lock( &stream->lock );
912
913     /* save this pointer (to be used by new connection) */
914     stream->i_buffer_last_pos = stream->i_buffer_pos;
915
916     i_pos = stream->i_buffer_pos % stream->i_buffer_size;
917     i_count = i_data;
918     while( i_count > 0)
919     {
920         int i_copy;
921
922         i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );
923
924         /* Ok, we can't go past the end of our buffer */
925         memcpy( &stream->p_buffer[i_pos], p_data, i_copy );
926
927         i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
928         i_count -= i_copy;
929         p_data  += i_copy;
930     }
931
932     stream->i_buffer_pos += i_data;
933
934     vlc_mutex_unlock( &stream->lock );
935     return VLC_SUCCESS;
936 }
937
938 void httpd_StreamDelete( httpd_stream_t *stream )
939 {
940     httpd_UrlDelete( stream->url );
941     vlc_mutex_destroy( &stream->lock );
942     if( stream->psz_mime ) free( stream->psz_mime );
943     if( stream->p_header ) free( stream->p_header );
944     if( stream->p_buffer ) free( stream->p_buffer );
945     free( stream );
946 }
947
948 /*****************************************************************************
949  * Low level
950  *****************************************************************************/
951 static void httpd_HostThread( httpd_host_t * );
952
953 /* create a new host */
954 httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
955                              int i_port )
956 {
957     return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
958                            );
959 }
960
961 static const char psz_object_type[] = "http server";
962
963 httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
964                                 int i_port,
965                                 const char *psz_cert, const char *psz_key,
966                                 const char *psz_ca, const char *psz_crl )
967 {
968     httpd_t      *httpd;
969     httpd_host_t *host;
970     tls_server_t *p_tls;
971     char *psz_host;
972     vlc_value_t  lockval;
973     int i;
974
975     if( psz_hostname == NULL )
976         psz_hostname = "";
977
978     psz_host = strdup( psz_hostname );
979     if( psz_host == NULL )
980     {
981         msg_Err( p_this, "memory error" );
982         return NULL;
983     }
984
985     /* to be sure to avoid multiple creation */
986     var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
987     var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
988     vlc_mutex_lock( lockval.p_address );
989
990     if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
991     {
992         msg_Info( p_this, "creating httpd" );
993         httpd = (httpd_t *)vlc_custom_create( p_this, sizeof (*httpd),
994                                               VLC_OBJECT_HTTPD,
995                                               psz_object_type );
996         if (httpd == NULL)
997         {
998             vlc_mutex_unlock( lockval.p_address );
999             free( psz_host );
1000             return NULL;
1001         }
1002
1003         httpd->i_host = 0;
1004         httpd->host   = NULL;
1005
1006         vlc_object_yield( httpd );
1007         vlc_object_attach( httpd, p_this->p_libvlc );
1008     }
1009
1010     /* verify if it already exist */
1011     for( i = httpd->i_host - 1; i >= 0; i-- )
1012     {
1013         host = httpd->host[i];
1014
1015         /* cannot mix TLS and non-TLS hosts */
1016         if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
1017          || ( host->i_port != i_port )
1018          || strcmp( host->psz_hostname, psz_hostname ) )
1019             continue;
1020
1021         /* yep found */
1022         host->i_ref++;
1023
1024         vlc_mutex_unlock( lockval.p_address );
1025         return host;
1026     }
1027
1028     host = NULL;
1029
1030     /* determine TLS configuration */
1031     if ( psz_cert != NULL )
1032     {
1033         p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
1034         if ( p_tls == NULL )
1035         {
1036             msg_Err( p_this, "TLS initialization error" );
1037             goto error;
1038         }
1039
1040         if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
1041         {
1042             msg_Err( p_this, "TLS CA error" );
1043             goto error;
1044         }
1045
1046         if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
1047         {
1048             msg_Err( p_this, "TLS CRL error" );
1049             goto error;
1050         }
1051     }
1052     else
1053         p_tls = NULL;
1054
1055     /* create the new host */
1056     host = (httpd_host_t *)vlc_custom_create( p_this, sizeof (*host),
1057                                               VLC_OBJECT_HTTPD_HOST,
1058                                               psz_object_type );
1059     if (host == NULL)
1060         goto error;
1061
1062     host->httpd = httpd;
1063     vlc_mutex_init( httpd, &host->lock );
1064     host->i_ref = 1;
1065
1066     host->fds = net_ListenTCP( p_this, psz_host, i_port );
1067     if( host->fds == NULL )
1068     {
1069         msg_Err( p_this, "cannot create socket(s) for HTTP host" );
1070         goto error;
1071     }
1072     for (host->nfd = 0; host->fds[host->nfd] != -1; host->nfd++);
1073
1074     host->i_port = i_port;
1075     host->psz_hostname = psz_host;
1076
1077     host->i_url     = 0;
1078     host->url       = NULL;
1079     host->i_client  = 0;
1080     host->client    = NULL;
1081
1082     host->p_tls = p_tls;
1083
1084     /* create the thread */
1085     if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
1086                            VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1087     {
1088         msg_Err( p_this, "cannot spawn http host thread" );
1089         goto error;
1090     }
1091
1092     /* now add it to httpd */
1093     TAB_APPEND( httpd->i_host, httpd->host, host );
1094     vlc_mutex_unlock( lockval.p_address );
1095
1096     return host;
1097
1098 error:
1099     free( psz_host );
1100     if( httpd->i_host <= 0 )
1101     {
1102         vlc_object_release( httpd );
1103         vlc_object_detach( httpd );
1104         vlc_object_destroy( httpd );
1105     }
1106     vlc_mutex_unlock( lockval.p_address );
1107
1108     if( host != NULL )
1109     {
1110         net_ListenClose( host->fds );
1111         vlc_mutex_destroy( &host->lock );
1112         vlc_object_destroy( host );
1113     }
1114
1115     if( p_tls != NULL )
1116         tls_ServerDelete( p_tls );
1117
1118     return NULL;
1119 }
1120
1121 /* delete a host */
1122 void httpd_HostDelete( httpd_host_t *host )
1123 {
1124     httpd_t *httpd = host->httpd;
1125     vlc_value_t lockval;
1126     int i;
1127
1128     var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
1129     vlc_mutex_lock( lockval.p_address );
1130
1131     host->i_ref--;
1132     if( host->i_ref > 0 )
1133     {
1134         /* still used */
1135         vlc_mutex_unlock( lockval.p_address );
1136         msg_Dbg( host, "httpd_HostDelete: host still used" );
1137         return;
1138     }
1139     TAB_REMOVE( httpd->i_host, httpd->host, host );
1140
1141     vlc_object_kill( host );
1142     vlc_thread_join( host );
1143
1144     msg_Dbg( host, "HTTP host removed" );
1145
1146     for( i = 0; i < host->i_url; i++ )
1147     {
1148         msg_Err( host, "url still registered: %s", host->url[i]->psz_url );
1149     }
1150     for( i = 0; i < host->i_client; i++ )
1151     {
1152         httpd_client_t *cl = host->client[i];
1153         msg_Warn( host, "client still connected" );
1154         httpd_ClientClean( cl );
1155         TAB_REMOVE( host->i_client, host->client, cl );
1156         free( cl );
1157         i--;
1158         /* TODO */
1159     }
1160
1161     if( host->p_tls != NULL)
1162         tls_ServerDelete( host->p_tls );
1163
1164     net_ListenClose( host->fds );
1165     free( host->psz_hostname );
1166
1167     vlc_mutex_destroy( &host->lock );
1168     vlc_object_destroy( host );
1169
1170     vlc_object_release( httpd );
1171     if( httpd->i_host <= 0 )
1172     {
1173         msg_Dbg( httpd, "no host left, stopping httpd" );
1174         vlc_object_detach( httpd );
1175         vlc_object_destroy( httpd );
1176     }
1177     vlc_mutex_unlock( lockval.p_address );
1178 }
1179
1180 /* register a new url */
1181 static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
1182                                          const char *psz_user, const char *psz_password,
1183                                          const vlc_acl_t *p_acl, vlc_bool_t b_check )
1184 {
1185     httpd_url_t *url;
1186     int         i;
1187
1188     vlc_mutex_lock( &host->lock );
1189     if( b_check )
1190     {
1191         for( i = 0; i < host->i_url; i++ )
1192         {
1193             if( !strcmp( psz_url, host->url[i]->psz_url ) )
1194             {
1195                 msg_Warn( host->httpd,
1196                           "cannot add '%s' (url already defined)", psz_url );
1197                 vlc_mutex_unlock( &host->lock );
1198                 return NULL;
1199             }
1200         }
1201     }
1202
1203     url = malloc( sizeof( httpd_url_t ) );
1204     url->host = host;
1205
1206     vlc_mutex_init( host->httpd, &url->lock );
1207     url->psz_url = strdup( psz_url );
1208     url->psz_user = strdup( psz_user ? psz_user : "" );
1209     url->psz_password = strdup( psz_password ? psz_password : "" );
1210     url->p_acl = ACL_Duplicate( host, p_acl );
1211     for( i = 0; i < HTTPD_MSG_MAX; i++ )
1212     {
1213         url->catch[i].cb = NULL;
1214         url->catch[i].p_sys = NULL;
1215     }
1216
1217     TAB_APPEND( host->i_url, host->url, url );
1218     vlc_mutex_unlock( &host->lock );
1219
1220     return url;
1221 }
1222
1223 httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
1224                            const char *psz_user, const char *psz_password,
1225                            const vlc_acl_t *p_acl )
1226 {
1227     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1228                                 psz_password, p_acl, VLC_FALSE );
1229 }
1230
1231 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
1232                                  const char *psz_user, const char *psz_password,
1233                                  const vlc_acl_t *p_acl )
1234 {
1235     return httpd_UrlNewPrivate( host, psz_url, psz_user,
1236                                 psz_password, p_acl, VLC_TRUE );
1237 }
1238
1239 /* register callback on a url */
1240 int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
1241                     httpd_callback_sys_t *p_sys )
1242 {
1243     vlc_mutex_lock( &url->lock );
1244     url->catch[i_msg].cb   = cb;
1245     url->catch[i_msg].p_sys= p_sys;
1246     vlc_mutex_unlock( &url->lock );
1247
1248     return VLC_SUCCESS;
1249 }
1250
1251 /* delete an url */
1252 void httpd_UrlDelete( httpd_url_t *url )
1253 {
1254     httpd_host_t *host = url->host;
1255     int          i;
1256
1257     vlc_mutex_lock( &host->lock );
1258     TAB_REMOVE( host->i_url, host->url, url );
1259
1260     vlc_mutex_destroy( &url->lock );
1261     free( url->psz_url );
1262     free( url->psz_user );
1263     free( url->psz_password );
1264     ACL_Destroy( url->p_acl );
1265
1266     for( i = 0; i < host->i_client; i++ )
1267     {
1268         httpd_client_t *client = host->client[i];
1269
1270         if( client->url == url )
1271         {
1272             /* TODO complete it */
1273             msg_Warn( host, "force closing connections" );
1274             httpd_ClientClean( client );
1275             TAB_REMOVE( host->i_client, host->client, client );
1276             free( client );
1277             i--;
1278         }
1279     }
1280     free( url );
1281     vlc_mutex_unlock( &host->lock );
1282 }
1283
1284 void httpd_MsgInit( httpd_message_t *msg )
1285 {
1286     msg->cl         = NULL;
1287     msg->i_type     = HTTPD_MSG_NONE;
1288     msg->i_proto    = HTTPD_PROTO_NONE;
1289     msg->i_version  = -1; /* FIXME */
1290
1291     msg->i_status   = 0;
1292
1293     msg->psz_url    = NULL;
1294     msg->psz_args   = NULL;
1295
1296     msg->i_channel  = -1;
1297
1298     msg->i_name     = 0;
1299     msg->name       = NULL;
1300     msg->i_value    = 0;
1301     msg->value      = NULL;
1302
1303     msg->i_body_offset = 0;
1304     msg->i_body        = 0;
1305     msg->p_body        = NULL;
1306 }
1307
1308 void httpd_MsgClean( httpd_message_t *msg )
1309 {
1310     int i;
1311
1312     if( msg->psz_url )
1313     {
1314         free( msg->psz_url );
1315     }
1316     if( msg->psz_args )
1317     {
1318         free( msg->psz_args );
1319     }
1320     for( i = 0; i < msg->i_name; i++ )
1321     {
1322         free( msg->name[i] );
1323         free( msg->value[i] );
1324     }
1325     if( msg->name )
1326     {
1327         free( msg->name );
1328     }
1329     if( msg->value )
1330     {
1331         free( msg->value );
1332     }
1333     if( msg->p_body )
1334     {
1335         free( msg->p_body );
1336     }
1337     httpd_MsgInit( msg );
1338 }
1339
1340 const char *httpd_MsgGet( const httpd_message_t *msg, const char *name )
1341 {
1342     int i;
1343
1344     for( i = 0; i < msg->i_name; i++ )
1345     {
1346         if( !strcasecmp( msg->name[i], name ))
1347         {
1348             return msg->value[i];
1349         }
1350     }
1351     return NULL;
1352 }
1353
1354 void httpd_MsgAdd( httpd_message_t *msg, const char *name, const char *psz_value, ... )
1355 {
1356     va_list args;
1357     char *value = NULL;
1358
1359     va_start( args, psz_value );
1360     if( vasprintf( &value, psz_value, args ) == -1 )
1361         value = NULL;
1362     va_end( args );
1363
1364     if( value == NULL )
1365         return;
1366
1367     name = strdup( name );
1368     if( name == NULL )
1369     {
1370         free( value );
1371         return;
1372     }
1373
1374     TAB_APPEND( msg->i_name,  msg->name,  (char*)name );
1375     TAB_APPEND( msg->i_value, msg->value, value );
1376 }
1377
1378 static void httpd_ClientInit( httpd_client_t *cl, mtime_t now )
1379 {
1380     cl->i_state = HTTPD_CLIENT_RECEIVING;
1381     cl->i_activity_date = now;
1382     cl->i_activity_timeout = I64C(10000000);
1383     cl->i_buffer_size = HTTPD_CL_BUFSIZE;
1384     cl->i_buffer = 0;
1385     cl->p_buffer = malloc( cl->i_buffer_size );
1386     cl->i_mode   = HTTPD_CLIENT_FILE;
1387     cl->b_read_waiting = VLC_FALSE;
1388
1389     httpd_MsgInit( &cl->query );
1390     httpd_MsgInit( &cl->answer );
1391 }
1392
1393 void httpd_ClientModeStream( httpd_client_t *cl )
1394 {
1395     cl->i_mode   = HTTPD_CLIENT_STREAM;
1396 }
1397
1398 void httpd_ClientModeBidir( httpd_client_t *cl )
1399 {
1400     cl->i_mode   = HTTPD_CLIENT_BIDIR;
1401 }
1402
1403 char* httpd_ClientIP( const httpd_client_t *cl, char *psz_ip )
1404 {
1405     return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1406 }
1407
1408 char* httpd_ServerIP( const httpd_client_t *cl, char *psz_ip )
1409 {
1410     return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1411 }
1412
1413 static void httpd_ClientClean( httpd_client_t *cl )
1414 {
1415     if( cl->fd >= 0 )
1416     {
1417         if( cl->p_tls != NULL )
1418             tls_ServerSessionClose( cl->p_tls );
1419         net_Close( cl->fd );
1420         cl->fd = -1;
1421     }
1422
1423     httpd_MsgClean( &cl->answer );
1424     httpd_MsgClean( &cl->query );
1425
1426     if( cl->p_buffer )
1427     {
1428         free( cl->p_buffer );
1429         cl->p_buffer = NULL;
1430     }
1431 }
1432
1433 static httpd_client_t *httpd_ClientNew( int fd, tls_session_t *p_tls, mtime_t now )
1434 {
1435     httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
1436
1437     if( !cl ) return NULL;
1438
1439     cl->i_ref   = 0;
1440     cl->fd      = fd;
1441     cl->url     = NULL;
1442     cl->p_tls = p_tls;
1443
1444     httpd_ClientInit( cl, now );
1445
1446     return cl;
1447 }
1448
1449 static int httpd_NetRecv( httpd_client_t *cl, uint8_t *p, int i_len )
1450 {
1451     tls_session_t *p_tls;
1452
1453     p_tls = cl->p_tls;
1454     if( p_tls != NULL)
1455         return tls_Recv( p_tls, p, i_len );
1456
1457     return recv( cl->fd, p, i_len, 0 );
1458 }
1459
1460 static int httpd_NetSend( httpd_client_t *cl, const uint8_t *p, int i_len )
1461 {
1462     tls_session_t *p_tls;
1463
1464     p_tls = cl->p_tls;
1465     if( p_tls != NULL)
1466         return tls_Send( p_tls, p, i_len );
1467
1468     return send( cl->fd, p, i_len, 0 );
1469 }
1470
1471 static void httpd_ClientRecv( httpd_client_t *cl )
1472 {
1473     int i_len;
1474
1475     if( cl->query.i_proto == HTTPD_PROTO_NONE )
1476     {
1477         /* enough to see if it's rtp over rtsp or RTSP/HTTP */
1478         i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
1479                                4 - cl->i_buffer );
1480         if( i_len > 0 )
1481         {
1482             cl->i_buffer += i_len;
1483         }
1484
1485         if( cl->i_buffer >= 4 )
1486         {
1487             /*fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );*/
1488             /* detect type */
1489             if( cl->p_buffer[0] == '$' )
1490             {
1491                 /* RTSP (rtp over rtsp) */
1492                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1493                 cl->query.i_type  = HTTPD_MSG_CHANNEL;
1494                 cl->query.i_channel = cl->p_buffer[1];
1495                 cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
1496                 cl->query.p_body  = malloc( cl->query.i_body );
1497
1498                 cl->i_buffer      = 0;
1499             }
1500             else if( !memcmp( cl->p_buffer, "HTTP", 4 ) )
1501             {
1502                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1503                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1504             }
1505             else if( !memcmp( cl->p_buffer, "RTSP", 4 ) )
1506             {
1507                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1508                 cl->query.i_type  = HTTPD_MSG_ANSWER;
1509             }
1510             else if( !memcmp( cl->p_buffer, "GET ", 4 ) ||
1511                      !memcmp( cl->p_buffer, "HEAD", 4 ) ||
1512                      !memcmp( cl->p_buffer, "POST", 4 ) )
1513             {
1514                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1515                 cl->query.i_type  = HTTPD_MSG_NONE;
1516             }
1517             else
1518             {
1519                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1520                 cl->query.i_type  = HTTPD_MSG_NONE;
1521             }
1522         }
1523     }
1524     else if( cl->query.i_body > 0 )
1525     {
1526         /* we are reading the body of a request or a channel */
1527         i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
1528                                cl->query.i_body - cl->i_buffer );
1529         if( i_len > 0 )
1530         {
1531             cl->i_buffer += i_len;
1532         }
1533         if( cl->i_buffer >= cl->query.i_body )
1534         {
1535             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1536         }
1537     }
1538     else
1539     {
1540         /* we are reading a header -> char by char */
1541         for( ;; )
1542         {
1543             i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1544             if( i_len <= 0 )
1545             {
1546                 break;
1547             }
1548             cl->i_buffer++;
1549
1550             if( cl->i_buffer + 1 >= cl->i_buffer_size )
1551             {
1552                 cl->i_buffer_size += 1024;
1553                 cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
1554             }
1555             if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
1556                 ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1557             {
1558                 char *p;
1559
1560                 /* we have finished the header so parse it and set i_body */
1561                 cl->p_buffer[cl->i_buffer] = '\0';
1562
1563                 if( cl->query.i_type == HTTPD_MSG_ANSWER )
1564                 {
1565                     /* FIXME:
1566                      * assume strlen( "HTTP/1.x" ) = 8
1567                      */
1568                     cl->query.i_status =
1569                         strtol( (char *)&cl->p_buffer[8],
1570                                 &p, 0 );
1571                     while( *p == ' ' )
1572                         p++;
1573                 }
1574                 else
1575                 {
1576                     static const struct
1577                     {
1578                         const char name[16];
1579                         int  i_type;
1580                         int  i_proto;
1581                     }
1582                     msg_type[] =
1583                     {
1584                         { "OPTIONS",        HTTPD_MSG_OPTIONS,      HTTPD_PROTO_RTSP },
1585                         { "DESCRIBE",       HTTPD_MSG_DESCRIBE,     HTTPD_PROTO_RTSP },
1586                         { "SETUP",          HTTPD_MSG_SETUP,        HTTPD_PROTO_RTSP },
1587                         { "PLAY",           HTTPD_MSG_PLAY,         HTTPD_PROTO_RTSP },
1588                         { "PAUSE",          HTTPD_MSG_PAUSE,        HTTPD_PROTO_RTSP },
1589                         { "GET_PARAMETER",  HTTPD_MSG_GETPARAMETER, HTTPD_PROTO_RTSP },
1590                         { "TEARDOWN",       HTTPD_MSG_TEARDOWN,     HTTPD_PROTO_RTSP },
1591
1592                         { "GET",            HTTPD_MSG_GET,          HTTPD_PROTO_HTTP },
1593                         { "HEAD",           HTTPD_MSG_HEAD,         HTTPD_PROTO_HTTP },
1594                         { "POST",           HTTPD_MSG_POST,         HTTPD_PROTO_HTTP },
1595
1596                         { "",               HTTPD_MSG_NONE,         HTTPD_PROTO_NONE }
1597                     };
1598                     unsigned i;
1599
1600                     p = NULL;
1601                     cl->query.i_type = HTTPD_MSG_NONE;
1602
1603                     /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1604
1605                     for( i = 0; msg_type[i].name[0]; i++ )
1606                     {
1607                         if( !strncmp( (char *)cl->p_buffer, msg_type[i].name,
1608                                       strlen( msg_type[i].name ) ) )
1609                         {
1610                             p = (char *)&cl->p_buffer[strlen((char *)msg_type[i].name) + 1 ];
1611                             cl->query.i_type = msg_type[i].i_type;
1612                             if( cl->query.i_proto != msg_type[i].i_proto )
1613                             {
1614                                 p = NULL;
1615                                 cl->query.i_proto = HTTPD_PROTO_NONE;
1616                                 cl->query.i_type = HTTPD_MSG_NONE;
1617                             }
1618                             break;
1619                         }
1620                     }
1621                     if( p == NULL )
1622                     {
1623                         if( strstr( (char *)cl->p_buffer, "HTTP/1." ) )
1624                         {
1625                             cl->query.i_proto = HTTPD_PROTO_HTTP;
1626                         }
1627                         else if( strstr( (char *)cl->p_buffer, "RTSP/1." ) )
1628                         {
1629                             cl->query.i_proto = HTTPD_PROTO_RTSP;
1630                         }
1631                     }
1632                     else
1633                     {
1634                         char *p2;
1635                         char *p3;
1636
1637                         while( *p == ' ' )
1638                         {
1639                             p++;
1640                         }
1641                         p2 = strchr( p, ' ' );
1642                         if( p2 )
1643                         {
1644                             *p2++ = '\0';
1645                         }
1646                         if( !strncasecmp( p, "rtsp:", 5 ) )
1647                         {
1648                             /* for rtsp url, you have rtsp://localhost:port/path */
1649                             p += 5;
1650                             while( *p == '/' ) p++;
1651                             while( *p && *p != '/' ) p++;
1652                         }
1653                         cl->query.psz_url = strdup( p );
1654                         if( ( p3 = strchr( cl->query.psz_url, '?' ) )  )
1655                         {
1656                             *p3++ = '\0';
1657                             cl->query.psz_args = (uint8_t *)strdup( p3 );
1658                         }
1659                         if( p2 )
1660                         {
1661                             while( *p2 == ' ' )
1662                             {
1663                                 p2++;
1664                             }
1665                             if( !strncasecmp( p2, "HTTP/1.", 7 ) )
1666                             {
1667                                 cl->query.i_proto = HTTPD_PROTO_HTTP;
1668                                 cl->query.i_version = atoi( p2+7 );
1669                             }
1670                             else if( !strncasecmp( p2, "RTSP/1.", 7 ) )
1671                             {
1672                                 cl->query.i_proto = HTTPD_PROTO_RTSP;
1673                                 cl->query.i_version = atoi( p2+7 );
1674                             }
1675                         }
1676                         p = p2;
1677                     }
1678                 }
1679                 if( p )
1680                 {
1681                     p = strchr( p, '\n' );
1682                 }
1683                 if( p )
1684                 {
1685                     while( *p == '\n' || *p == '\r' )
1686                     {
1687                         p++;
1688                     }
1689                     while( p && *p != '\0' )
1690                     {
1691                         char *line = p;
1692                         char *eol = p = strchr( p, '\n' );
1693                         char *colon;
1694
1695                         while( eol && eol >= line && ( *eol == '\n' || *eol == '\r' ) )
1696                         {
1697                             *eol-- = '\0';
1698                         }
1699
1700                         if( ( colon = strchr( line, ':' ) ) )
1701                         {
1702                             char *name;
1703                             char *value;
1704
1705                             *colon++ = '\0';
1706                             while( *colon == ' ' )
1707                             {
1708                                 colon++;
1709                             }
1710                             name = strdup( line );
1711                             value = strdup( colon );
1712
1713                             TAB_APPEND( cl->query.i_name, cl->query.name, name );
1714                             TAB_APPEND( cl->query.i_value,cl->query.value,value);
1715
1716                             if( !strcasecmp( name, "Content-Length" ) )
1717                             {
1718                                 cl->query.i_body = atol( value );
1719                             }
1720                         }
1721
1722                         if( p )
1723                         {
1724                             p++;
1725                             while( *p == '\n' || *p == '\r' )
1726                             {
1727                                 p++;
1728                             }
1729                         }
1730                     }
1731                 }
1732                 if( cl->query.i_body > 0 )
1733                 {
1734                     /* TODO Mhh, handle the case client will only send a request and close the connection
1735                      * to mark and of body (probably only RTSP) */
1736                     cl->query.p_body = malloc( cl->query.i_body );
1737                     cl->i_buffer = 0;
1738                 }
1739                 else
1740                 {
1741                     cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1742                 }
1743             }
1744         }
1745     }
1746
1747     /* check if the client is to be set to dead */
1748 #if defined( WIN32 ) || defined( UNDER_CE )
1749     if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1750 #else
1751     if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1752 #endif
1753     {
1754         if( cl->query.i_proto != HTTPD_PROTO_NONE && cl->query.i_type != HTTPD_MSG_NONE )
1755         {
1756             /* connection closed -> end of data */
1757             if( cl->query.i_body > 0 )
1758             {
1759                 cl->query.i_body = cl->i_buffer;
1760             }
1761             cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
1762         }
1763         else
1764         {
1765             cl->i_state = HTTPD_CLIENT_DEAD;
1766         }
1767     }
1768
1769     /* XXX: for QT I have to disable timeout. Try to find why */
1770     if( cl->query.i_proto == HTTPD_PROTO_RTSP )
1771         cl->i_activity_timeout = 0;
1772
1773 #if 0 /* Debugging only */
1774     if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
1775     {
1776         int i;
1777
1778         fprintf( stderr, "received new request\n" );
1779         fprintf( stderr, "  - proto=%s\n",
1780                  cl->query.i_proto == HTTPD_PROTO_HTTP ? "HTTP" : "RTSP" );
1781         fprintf( stderr, "  - version=%d\n", cl->query.i_version );
1782         fprintf( stderr, "  - msg=%d\n", cl->query.i_type );
1783         if( cl->query.i_type == HTTPD_MSG_ANSWER )
1784         {
1785             fprintf( stderr, "  - answer=%d '%s'\n", cl->query.i_status,
1786                      cl->query.psz_status );
1787         }
1788         else if( cl->query.i_type != HTTPD_MSG_NONE )
1789         {
1790             fprintf( stderr, "  - url=%s\n", cl->query.psz_url );
1791         }
1792         for( i = 0; i < cl->query.i_name; i++ )
1793         {
1794             fprintf( stderr, "  - option name='%s' value='%s'\n",
1795                      cl->query.name[i], cl->query.value[i] );
1796         }
1797     }
1798 #endif
1799 }
1800
1801 static void httpd_ClientSend( httpd_client_t *cl )
1802 {
1803     int i;
1804     int i_len;
1805
1806     if( cl->i_buffer < 0 )
1807     {
1808         /* We need to create the header */
1809         int i_size = 0;
1810         char *p;
1811         const char *psz_status = httpd_ReasonFromCode( cl->answer.i_status );
1812
1813         i_size = strlen( "HTTP/1.") + 10 + 10 + strlen( psz_status ) + 5;
1814         for( i = 0; i < cl->answer.i_name; i++ )
1815         {
1816             i_size += strlen( cl->answer.name[i] ) + 2 +
1817                       strlen( cl->answer.value[i] ) + 2;
1818         }
1819
1820         if( cl->i_buffer_size < i_size )
1821         {
1822             cl->i_buffer_size = i_size;
1823             free( cl->p_buffer );
1824             cl->p_buffer = malloc( i_size );
1825         }
1826         p = (char *)cl->p_buffer;
1827
1828         p += sprintf( p, "%s.%u %d %s\r\n",
1829                       cl->answer.i_proto ==  HTTPD_PROTO_HTTP ? "HTTP/1" : "RTSP/1",
1830                       cl->answer.i_version,
1831                       cl->answer.i_status, psz_status );
1832         for( i = 0; i < cl->answer.i_name; i++ )
1833         {
1834             p += sprintf( p, "%s: %s\r\n", cl->answer.name[i],
1835                           cl->answer.value[i] );
1836         }
1837         p += sprintf( p, "\r\n" );
1838
1839         cl->i_buffer = 0;
1840         cl->i_buffer_size = (uint8_t*)p - cl->p_buffer;
1841
1842         /*fprintf( stderr, "sending answer\n" );
1843         fprintf( stderr, "%s",  cl->p_buffer );*/
1844     }
1845
1846     i_len = httpd_NetSend( cl, &cl->p_buffer[cl->i_buffer],
1847                            cl->i_buffer_size - cl->i_buffer );
1848     if( i_len >= 0 )
1849     {
1850         cl->i_buffer += i_len;
1851
1852         if( cl->i_buffer >= cl->i_buffer_size )
1853         {
1854             if( cl->answer.i_body == 0  && cl->answer.i_body_offset > 0 &&
1855                 !cl->b_read_waiting )
1856             {
1857                 /* catch more body data */
1858                 int     i_msg = cl->query.i_type;
1859                 int64_t i_offset = cl->answer.i_body_offset;
1860
1861                 httpd_MsgClean( &cl->answer );
1862                 cl->answer.i_body_offset = i_offset;
1863
1864                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
1865                                           &cl->answer, &cl->query );
1866             }
1867
1868             if( cl->answer.i_body > 0 )
1869             {
1870                 /* send the body data */
1871                 free( cl->p_buffer );
1872                 cl->p_buffer = cl->answer.p_body;
1873                 cl->i_buffer_size = cl->answer.i_body;
1874                 cl->i_buffer = 0;
1875
1876                 cl->answer.i_body = 0;
1877                 cl->answer.p_body = NULL;
1878             }
1879             else
1880             {
1881                 /* send finished */
1882                 cl->i_state = HTTPD_CLIENT_SEND_DONE;
1883             }
1884         }
1885     }
1886     else
1887     {
1888 #if defined( WIN32 ) || defined( UNDER_CE )
1889         if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1890 #else
1891         if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1892 #endif
1893         {
1894             /* error */
1895             cl->i_state = HTTPD_CLIENT_DEAD;
1896         }
1897     }
1898 }
1899
1900 static void httpd_ClientTlsHsIn( httpd_client_t *cl )
1901 {
1902     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1903     {
1904         case 0:
1905             cl->i_state = HTTPD_CLIENT_RECEIVING;
1906             break;
1907
1908         case -1:
1909             cl->i_state = HTTPD_CLIENT_DEAD;
1910             cl->p_tls = NULL;
1911             break;
1912
1913         case 2:
1914             cl->i_state = HTTPD_CLIENT_TLS_HS_OUT;
1915     }
1916 }
1917
1918 static void httpd_ClientTlsHsOut( httpd_client_t *cl )
1919 {
1920     switch( tls_SessionContinueHandshake( cl->p_tls ) )
1921     {
1922         case 0:
1923             cl->i_state = HTTPD_CLIENT_RECEIVING;
1924             break;
1925
1926         case -1:
1927             cl->i_state = HTTPD_CLIENT_DEAD;
1928             cl->p_tls = NULL;
1929             break;
1930
1931         case 1:
1932             cl->i_state = HTTPD_CLIENT_TLS_HS_IN;
1933             break;
1934     }
1935 }
1936
1937 static void httpd_HostThread( httpd_host_t *host )
1938 {
1939     tls_session_t *p_tls = NULL;
1940     counter_t *p_total_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
1941     counter_t *p_active_counter = stats_CounterCreate( host, VLC_VAR_INTEGER, STATS_COUNTER );
1942
1943     while( !host->b_die )
1944     {
1945         if( host->i_url <= 0 )
1946         {
1947             /* 0.2s */
1948             msleep( 200000 );
1949             continue;
1950         }
1951
1952         /* prepare a new TLS session */
1953         if( ( p_tls == NULL ) && ( host->p_tls != NULL ) )
1954             p_tls = tls_ServerSessionPrepare( host->p_tls );
1955
1956         struct pollfd ufd[host->nfd + host->i_client];
1957         unsigned nfd;
1958         for( nfd = 0; nfd < host->nfd; nfd++ )
1959         {
1960             ufd[nfd].fd = host->fds[nfd];
1961             ufd[nfd].events = POLLIN;
1962             ufd[nfd].revents = 0;
1963         }
1964
1965         /* add all socket that should be read/write and close dead connection */
1966         vlc_mutex_lock( &host->lock );
1967         mtime_t now = mdate();
1968         vlc_bool_t b_low_delay = VLC_FALSE;
1969
1970         for(int i_client = 0; i_client < host->i_client; i_client++ )
1971         {
1972             httpd_client_t *cl = host->client[i_client];
1973             if( cl->i_ref < 0 || ( cl->i_ref == 0 &&
1974                 ( cl->i_state == HTTPD_CLIENT_DEAD ||
1975                   ( cl->i_activity_timeout > 0 &&
1976                     cl->i_activity_date+cl->i_activity_timeout < now) ) ) )
1977             {
1978                 httpd_ClientClean( cl );
1979                 stats_UpdateInteger( host, p_active_counter, -1, NULL );
1980                 TAB_REMOVE( host->i_client, host->client, cl );
1981                 free( cl );
1982                 i_client--;
1983                 continue;
1984             }
1985
1986             struct pollfd *pufd = ufd + nfd;
1987             assert (pufd < ufd + (sizeof (ufd) / sizeof (ufd[0])));
1988
1989             pufd->fd = cl->fd;
1990             pufd->events = pufd->revents = 0;
1991
1992             if( ( cl->i_state == HTTPD_CLIENT_RECEIVING )
1993                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_IN ) )
1994             {
1995                 pufd->events = POLLIN;
1996             }
1997             else if( ( cl->i_state == HTTPD_CLIENT_SENDING )
1998                   || ( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT ) )
1999             {
2000                 pufd->events = POLLOUT;
2001             }
2002             else if( cl->i_state == HTTPD_CLIENT_RECEIVE_DONE )
2003             {
2004                 httpd_message_t *answer = &cl->answer;
2005                 httpd_message_t *query  = &cl->query;
2006                 int i_msg = query->i_type;
2007
2008                 httpd_MsgInit( answer );
2009
2010                 /* Handle what we received */
2011                 if( (cl->i_mode != HTTPD_CLIENT_BIDIR) &&
2012                     (i_msg == HTTPD_MSG_ANSWER || i_msg == HTTPD_MSG_CHANNEL) )
2013                 {
2014                     /* we can only receive request from client when not
2015                      * in BIDIR mode */
2016                     cl->url     = NULL;
2017                     cl->i_state = HTTPD_CLIENT_DEAD;
2018                 }
2019                 else if( i_msg == HTTPD_MSG_ANSWER )
2020                 {
2021                     /* We are in BIDIR mode, trigger the callback and then
2022                      * check for new data */
2023                     if( cl->url && cl->url->catch[i_msg].cb )
2024                     {
2025                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2026                                                   cl, NULL, query );
2027                     }
2028                     cl->i_state = HTTPD_CLIENT_WAITING;
2029                 }
2030                 else if( i_msg == HTTPD_MSG_CHANNEL )
2031                 {
2032                     /* We are in BIDIR mode, trigger the callback and then
2033                      * check for new data */
2034                     if( cl->url && cl->url->catch[i_msg].cb )
2035                     {
2036                         cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys,
2037                                                   cl, NULL, query );
2038                     }
2039                     cl->i_state = HTTPD_CLIENT_WAITING;
2040                 }
2041                 else if( i_msg == HTTPD_MSG_OPTIONS )
2042                 {
2043                     const char *psz;
2044
2045                     /* unimplemented */
2046                     answer->i_proto  = query->i_proto;
2047                     answer->i_type   = HTTPD_MSG_ANSWER;
2048                     answer->i_version= 0;
2049
2050                     answer->i_status = 200;
2051
2052                     answer->i_body = 0;
2053                     answer->p_body = NULL;
2054
2055                     psz = httpd_MsgGet( query, "Require" );
2056                     if( psz != NULL )
2057                     {
2058                         answer->i_status = 551;
2059                         httpd_MsgAdd( query, "Unsupported", "%s", psz );
2060                     }
2061
2062                     psz = httpd_MsgGet( query, "Cseq" );
2063                     if( psz != NULL )
2064                         httpd_MsgAdd( answer, "Cseq", "%s", psz );
2065                     psz = httpd_MsgGet( query, "Timestamp" );
2066                     if( psz != NULL )
2067                         httpd_MsgAdd( answer, "Timestamp", "%s", psz );
2068
2069                     httpd_MsgAdd( answer, "Server", "%s", PACKAGE_STRING );
2070                     httpd_MsgAdd( answer, "Public", "DESCRIBE, SETUP, "
2071                                  "TEARDOWN, PLAY, PAUSE, GET_PARAMETER" );
2072                     httpd_MsgAdd( answer, "Content-Length", "0" );
2073
2074                     cl->i_buffer = -1;  /* Force the creation of the answer in
2075                                          * httpd_ClientSend */
2076                     cl->i_state = HTTPD_CLIENT_SENDING;
2077                 }
2078                 else if( i_msg == HTTPD_MSG_NONE )
2079                 {
2080                     if( query->i_proto == HTTPD_PROTO_NONE )
2081                     {
2082                         cl->url = NULL;
2083                         cl->i_state = HTTPD_CLIENT_DEAD;
2084                     }
2085                     else
2086                     {
2087                         char *p;
2088
2089                         /* unimplemented */
2090                         answer->i_proto  = query->i_proto ;
2091                         answer->i_type   = HTTPD_MSG_ANSWER;
2092                         answer->i_version= 0;
2093                         answer->i_status = 501;
2094
2095                         answer->i_body = httpd_HtmlError (&p, 501, NULL);
2096                         answer->p_body = (uint8_t *)p;
2097                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2098
2099                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2100                         cl->i_state = HTTPD_CLIENT_SENDING;
2101                     }
2102                 }
2103                 else
2104                 {
2105                     vlc_bool_t b_auth_failed = VLC_FALSE;
2106                     vlc_bool_t b_hosts_failed = VLC_FALSE;
2107
2108                     /* Search the url and trigger callbacks */
2109                     for(int i = 0; i < host->i_url; i++ )
2110                     {
2111                         httpd_url_t *url = host->url[i];
2112
2113                         if( !strcmp( url->psz_url, query->psz_url ) )
2114                         {
2115                             if( url->catch[i_msg].cb )
2116                             {
2117                                 if( answer && ( url->p_acl != NULL ) )
2118                                 {
2119                                     char ip[NI_MAXNUMERICHOST];
2120
2121                                     if( ( httpd_ClientIP( cl, ip ) == NULL )
2122                                      || ACL_Check( url->p_acl, ip ) )
2123                                     {
2124                                         b_hosts_failed = VLC_TRUE;
2125                                         break;
2126                                     }
2127                                 }
2128
2129                                 if( answer && ( *url->psz_user || *url->psz_password ) )
2130                                 {
2131                                     /* create the headers */
2132                                     const char *b64 = httpd_MsgGet( query, "Authorization" ); /* BASIC id */
2133                                     char *user = NULL, *pass = NULL;
2134
2135                                     if( b64 != NULL
2136                                      && !strncasecmp( b64, "BASIC", 5 ) )
2137                                     {
2138                                         b64 += 5;
2139                                         while( *b64 == ' ' )
2140                                             b64++;
2141
2142                                         user = vlc_b64_decode( b64 );
2143                                         if (user != NULL)
2144                                         {
2145                                             pass = strchr (user, ':');
2146                                             if (pass != NULL)
2147                                                 *pass++ = '\0';
2148                                         }
2149                                     }
2150
2151                                     if ((user == NULL) || (pass == NULL)
2152                                      || strcmp (user, url->psz_user)
2153                                      || strcmp (pass, url->psz_password))
2154                                     {
2155                                         httpd_MsgAdd( answer,
2156                                                       "WWW-Authenticate",
2157                                                       "Basic realm=\"%s\"",
2158                                                       url->psz_user );
2159                                         /* We fail for all url */
2160                                         b_auth_failed = VLC_TRUE;
2161                                         free( user );
2162                                         break;
2163                                     }
2164
2165                                     free( user );
2166                                 }
2167
2168                                 if( !url->catch[i_msg].cb( url->catch[i_msg].p_sys, cl, answer, query ) )
2169                                 {
2170                                     if( answer->i_proto == HTTPD_PROTO_NONE )
2171                                     {
2172                                         /* Raw answer from a CGI */
2173                                         cl->i_buffer = cl->i_buffer_size;
2174                                     }
2175                                     else
2176                                         cl->i_buffer = -1;
2177
2178                                     /* only one url can answer */
2179                                     answer = NULL;
2180                                     if( cl->url == NULL )
2181                                     {
2182                                         cl->url = url;
2183                                     }
2184                                 }
2185                             }
2186                         }
2187                     }
2188
2189                     if( answer )
2190                     {
2191                         char *p;
2192
2193                         answer->i_proto  = query->i_proto;
2194                         answer->i_type   = HTTPD_MSG_ANSWER;
2195                         answer->i_version= 0;
2196
2197                         if( b_hosts_failed )
2198                         {
2199                             answer->i_status = 403;
2200                         }
2201                         else if( b_auth_failed )
2202                         {
2203                             answer->i_status = 401;
2204                         }
2205                         else
2206                         {
2207                             /* no url registered */
2208                             answer->i_status = 404;
2209                         }
2210
2211                         answer->i_body = httpd_HtmlError (&p,
2212                                                           answer->i_status,
2213                                                           query->psz_url);
2214                         answer->p_body = (uint8_t *)p;
2215
2216                         cl->i_buffer = -1;  /* Force the creation of the answer in httpd_ClientSend */
2217                         httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
2218                         httpd_MsgAdd( answer, "Content-Type", "%s", "text/html" );
2219                     }
2220
2221                     cl->i_state = HTTPD_CLIENT_SENDING;
2222                 }
2223             }
2224             else if( cl->i_state == HTTPD_CLIENT_SEND_DONE )
2225             {
2226                 if( cl->i_mode == HTTPD_CLIENT_FILE || cl->answer.i_body_offset == 0 )
2227                 {
2228                     const char *psz_connection = httpd_MsgGet( &cl->answer, "Connection" );
2229                     const char *psz_query = httpd_MsgGet( &cl->query, "Connection" );
2230                     vlc_bool_t b_connection = VLC_FALSE;
2231                     vlc_bool_t b_keepalive = VLC_FALSE;
2232                     vlc_bool_t b_query = VLC_FALSE;
2233
2234                     cl->url = NULL;
2235                     if( psz_connection )
2236                     {
2237                         b_connection = ( strcasecmp( psz_connection, "Close" ) == 0 );
2238                         b_keepalive = ( strcasecmp( psz_connection, "Keep-Alive" ) == 0 );
2239                     }
2240
2241                     if( psz_query )
2242                     {
2243                         b_query = ( strcasecmp( psz_query, "Close" ) == 0 );
2244                     }
2245
2246                     if( ( ( cl->query.i_proto == HTTPD_PROTO_HTTP ) &&
2247                           ( ( cl->answer.i_version == 0 && b_keepalive ) ||
2248                             ( cl->answer.i_version == 1 && !b_connection ) ) ) ||
2249                         ( ( cl->query.i_proto == HTTPD_PROTO_RTSP ) &&
2250                           !b_query && !b_connection ) )
2251                     {
2252                         httpd_MsgClean( &cl->query );
2253                         httpd_MsgInit( &cl->query );
2254
2255                         cl->i_buffer = 0;
2256                         cl->i_buffer_size = 1000;
2257                         free( cl->p_buffer );
2258                         cl->p_buffer = malloc( cl->i_buffer_size );
2259                         cl->i_state = HTTPD_CLIENT_RECEIVING;
2260                     }
2261                     else
2262                     {
2263                         cl->i_state = HTTPD_CLIENT_DEAD;
2264                     }
2265                     httpd_MsgClean( &cl->answer );
2266                 }
2267                 else if( cl->b_read_waiting )
2268                 {
2269                     /* we have a message waiting for us to read it */
2270                     httpd_MsgClean( &cl->answer );
2271                     httpd_MsgClean( &cl->query );
2272
2273                     cl->i_buffer = 0;
2274                     cl->i_buffer_size = 1000;
2275                     free( cl->p_buffer );
2276                     cl->p_buffer = malloc( cl->i_buffer_size );
2277                     cl->i_state = HTTPD_CLIENT_RECEIVING;
2278                     cl->b_read_waiting = VLC_FALSE;
2279                 }
2280                 else
2281                 {
2282                     int64_t i_offset = cl->answer.i_body_offset;
2283                     httpd_MsgClean( &cl->answer );
2284
2285                     cl->answer.i_body_offset = i_offset;
2286                     free( cl->p_buffer );
2287                     cl->p_buffer = NULL;
2288                     cl->i_buffer = 0;
2289                     cl->i_buffer_size = 0;
2290
2291                     cl->i_state = HTTPD_CLIENT_WAITING;
2292                 }
2293             }
2294             else if( cl->i_state == HTTPD_CLIENT_WAITING )
2295             {
2296                 int64_t i_offset = cl->answer.i_body_offset;
2297                 int     i_msg = cl->query.i_type;
2298
2299                 httpd_MsgInit( &cl->answer );
2300                 cl->answer.i_body_offset = i_offset;
2301
2302                 cl->url->catch[i_msg].cb( cl->url->catch[i_msg].p_sys, cl,
2303                                           &cl->answer, &cl->query );
2304                 if( cl->answer.i_type != HTTPD_MSG_NONE )
2305                 {
2306                     /* we have new data, so re-enter send mode */
2307                     cl->i_buffer      = 0;
2308                     cl->p_buffer      = cl->answer.p_body;
2309                     cl->i_buffer_size = cl->answer.i_body;
2310                     cl->answer.p_body = NULL;
2311                     cl->answer.i_body = 0;
2312                     cl->i_state = HTTPD_CLIENT_SENDING;
2313                 }
2314                 else
2315                 {
2316                     /* we shouldn't wait too long */
2317                     b_low_delay = VLC_TRUE;
2318                 }
2319             }
2320
2321             /* Special for BIDIR mode we also check reading */
2322             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2323                 cl->i_state == HTTPD_CLIENT_SENDING )
2324             {
2325                 pufd->events |= POLLIN;
2326             }
2327
2328             if (pufd->events != 0)
2329                 nfd++;
2330         }
2331         vlc_mutex_unlock( &host->lock );
2332
2333         /* we will wait 100ms or 20ms (not too big 'cause HTTPD_CLIENT_WAITING) */
2334         switch( poll( ufd, nfd, b_low_delay ? 20 : 100) )
2335         {
2336             case -1:
2337                 if (errno != EINTR)
2338                 {
2339                     /* This is most likely a bug */
2340                     msg_Err( host, "polling error: %s", strerror (errno));
2341                     msleep( 1000 );
2342                 }
2343             case 0:
2344                 continue;
2345         }
2346
2347         /* Handle client sockets */
2348         vlc_mutex_lock( &host->lock );
2349         now = mdate();
2350         for( int i_client = 0; i_client < host->i_client; i_client++ )
2351         {
2352             httpd_client_t *cl = host->client[i_client];
2353             const struct pollfd *pufd = &ufd[host->nfd + i_client];
2354
2355             assert( pufd < &ufd[sizeof(ufd) / sizeof(ufd[0])] );
2356
2357             if( cl->fd != pufd->fd )
2358                 continue; // we were not waiting for this client
2359             if( pufd->revents == 0 )
2360                 continue; // no event received
2361
2362             cl->i_activity_date = now;
2363
2364             if( cl->i_state == HTTPD_CLIENT_RECEIVING )
2365             {
2366                 httpd_ClientRecv( cl );
2367             }
2368             else if( cl->i_state == HTTPD_CLIENT_SENDING )
2369             {
2370                 httpd_ClientSend( cl );
2371             }
2372             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_IN )
2373             {
2374                 httpd_ClientTlsHsIn( cl );
2375             }
2376             else if( cl->i_state == HTTPD_CLIENT_TLS_HS_OUT )
2377             {
2378                 httpd_ClientTlsHsOut( cl );
2379             }
2380
2381             if( cl->i_mode == HTTPD_CLIENT_BIDIR &&
2382                 cl->i_state == HTTPD_CLIENT_SENDING &&
2383                 (pufd->revents & POLLIN) )
2384             {
2385                 cl->b_read_waiting = VLC_TRUE;
2386             }
2387         }
2388         vlc_mutex_unlock( &host->lock );
2389
2390         /* Handle server sockets (accept new connections) */
2391         for( nfd = 0; nfd < host->nfd; nfd++ )
2392         {
2393             httpd_client_t *cl;
2394             int i_state = -1;
2395
2396             assert (ufd[nfd].fd == host->fds[nfd]);
2397
2398             if( ufd[nfd].revents == 0 )
2399                 continue;
2400
2401             /* */
2402             int kludge[] = { ufd[nfd].fd, -1 };
2403             int fd = net_Accept( host, kludge, 0 );
2404             if( fd < 0 )
2405                 continue;
2406
2407             if( p_tls != NULL )
2408             {
2409                 switch( tls_ServerSessionHandshake( p_tls, fd ) )
2410                 {
2411                     case -1:
2412                         msg_Err( host, "Rejecting TLS connection" );
2413                         net_Close( fd );
2414                         fd = -1;
2415                         p_tls = NULL;
2416                         break;
2417
2418                     case 1: /* missing input - most likely */
2419                         i_state = HTTPD_CLIENT_TLS_HS_IN;
2420                         break;
2421
2422                     case 2: /* missing output */
2423                         i_state = HTTPD_CLIENT_TLS_HS_OUT;
2424                         break;
2425                 }
2426
2427                 if( (p_tls == NULL) != (host->p_tls == NULL) )
2428                     break; // wasted TLS session, cannot accept() anymore
2429             }
2430
2431             stats_UpdateInteger( host, p_total_counter, 1, NULL );
2432             stats_UpdateInteger( host, p_active_counter, 1, NULL );
2433             cl = httpd_ClientNew( fd, p_tls, now );
2434             p_tls = NULL;
2435             vlc_mutex_lock( &host->lock );
2436             TAB_APPEND( host->i_client, host->client, cl );
2437             vlc_mutex_unlock( &host->lock );
2438             if( i_state != -1 )
2439                 cl->i_state = i_state; // override state for TLS
2440
2441             if (host->p_tls != NULL)
2442                 break; // cannot accept further without new TLS session
2443         }
2444
2445     }
2446
2447     if( p_tls != NULL )
2448         tls_ServerSessionClose( p_tls );
2449     if( p_total_counter )
2450         stats_CounterClean( p_total_counter );
2451     if( p_active_counter )
2452         stats_CounterClean( p_active_counter );
2453 }
2454
2455 #else /* ENABLE_HTTPD */
2456
2457 /* We just define an empty wrapper */
2458 httpd_host_t *httpd_TLSHostNew( vlc_object_t *a, char *b, int c,
2459                                 tls_server_t *d )
2460 {
2461     msg_Err( a, "HTTP daemon support is disabled" );
2462     return NULL;
2463 }
2464
2465 httpd_host_t *httpd_HostNew( vlc_object_t *a, char *b, int c )
2466 {
2467     msg_Err( a, "HTTP daemon support is disabled" );
2468     return NULL;
2469 }
2470
2471 void httpd_HostDelete( httpd_host_t *a )
2472 {
2473 }
2474
2475 httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
2476                            char *psz_user, char *psz_password,
2477                            const vlc_acl_t *p_acl )
2478 {
2479     return NULL;
2480 }
2481
2482 httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
2483                                  char *psz_user, char *psz_password,
2484                                  const vlc_acl_t *p_acl )
2485 {
2486     return NULL;
2487 }
2488
2489 int httpd_UrlCatch( httpd_url_t *a, int b, httpd_callback_t c,
2490                     httpd_callback_sys_t *d )
2491 {
2492     return 0;
2493 }
2494
2495 void httpd_UrlDelete( httpd_url_t *a )
2496 {
2497 }
2498
2499 char* httpd_ClientIP( httpd_client_t *cl, char *psz_ip )
2500 {
2501     return NULL;
2502 }
2503
2504 char* httpd_ServerIP( httpd_client_t *cl, char *psz_ip )
2505 {
2506     return NULL;
2507 }
2508
2509 void httpd_ClientModeStream( httpd_client_t *a )
2510 {
2511 }
2512
2513 void httpd_ClientModeBidir( httpd_client_t *a )
2514 {
2515 }
2516
2517 void httpd_FileDelete( httpd_file_t *a )
2518 {
2519 }
2520
2521 httpd_file_t *httpd_FileNew( httpd_host_t *a, char *b, char *c, char *d,
2522                              char *e, httpd_file_callback_t f,
2523                              httpd_file_sys_t *g )
2524 {
2525     return NULL;
2526 }
2527
2528 httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
2529                                    const char *psz_user,
2530                                    const char *psz_password,
2531                                    const vlc_acl_t *p_acl,
2532                                    httpd_handler_callback_t pf_fill,
2533                                    httpd_handler_sys_t *p_sys )
2534 {
2535     return NULL;
2536 }
2537
2538 void httpd_HandlerDelete( httpd_handler_t *handler )
2539 {
2540 }
2541
2542 void httpd_RedirectDelete( httpd_redirect_t *a )
2543 {
2544 }
2545
2546 httpd_redirect_t *httpd_RedirectNew( httpd_host_t *a,
2547                                      char *b, char *c )
2548 {
2549     return NULL;
2550 }
2551
2552 void httpd_StreamDelete( httpd_stream_t *a )
2553 {
2554 }
2555
2556 int httpd_StreamHeader( httpd_stream_t *a, uint8_t *b, int c )
2557 {
2558     return 0;
2559 }
2560
2561 int httpd_StreamSend ( httpd_stream_t *a, uint8_t *b, int c )
2562 {
2563     return 0;
2564 }
2565
2566 httpd_stream_t *httpd_StreamNew( httpd_host_t *a, char *b, char *c,
2567                                  char *d, char *e )
2568 {
2569     return NULL;
2570 }
2571
2572 void httpd_MsgInit ( httpd_message_t *a )
2573 {
2574 }
2575
2576 void httpd_MsgAdd  ( httpd_message_t *a, const char *b, const char *c, ... )
2577 {
2578 }
2579
2580 const char *httpd_MsgGet ( httpd_message_t *a, const char *b )
2581 {
2582     return "";
2583 }
2584
2585 void httpd_MsgClean( httpd_message_t *a )
2586 {
2587 }
2588
2589 #endif /* ENABLE_HTTPD */