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