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