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