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