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