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