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