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