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