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