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