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