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