* http: rework of the http interface.
[vlc.git] / modules / misc / httpd.c
1 /*****************************************************************************
2  * httpd.c
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id: httpd.c,v 1.23 2003/07/10 22:24:09 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>
28 #include <vlc/vlc.h>
29
30 #include <sys/stat.h>
31
32 #include <errno.h>
33 #include <fcntl.h>
34
35 #include "httpd.h"
36
37 #ifdef HAVE_SYS_TIME_H
38 #    include <sys/time.h>
39 #endif
40
41 #ifdef HAVE_UNISTD_H
42 #   include <unistd.h>
43 #endif
44
45 #if defined( UNDER_CE )
46 #   include <winsock.h>
47 #elif defined( WIN32 )
48 #   include <winsock2.h>
49 #   include <ws2tcpip.h>
50 #   ifndef IN_MULTICAST
51 #       define IN_MULTICAST(a) IN_CLASSD(a)
52 #   endif
53 #else
54 #   include <netdb.h>                                         /* hostent ... */
55 #   include <sys/socket.h>
56 #   include <netinet/in.h>
57 #   ifdef HAVE_ARPA_INET_H
58 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
59 #   endif
60 #endif
61
62 #include "network.h"
63
64 #ifndef INADDR_ANY
65 #   define INADDR_ANY  0x00000000
66 #endif
67 #ifndef INADDR_NONE
68 #   define INADDR_NONE 0xFFFFFFFF
69 #endif
70
71 #define LISTEN_BACKLOG          100
72 #define HTTPD_MAX_CONNECTION    512
73 #define HTTPD_CONNECTION_MAX_UNUSED 10000000
74
75
76 #define FREE( p ) if( p ) { free( p); (p) = NULL; }
77
78 #if defined( WIN32 ) || defined( UNDER_CE )
79 #define SOCKET_CLOSE(a)    closesocket(a)
80 #else
81 #define SOCKET_CLOSE(a)    close(a)
82 #endif
83
84 /*****************************************************************************
85  * Exported prototypes
86  *****************************************************************************/
87 static int              Open   ( vlc_object_t * );
88 static void             Close  ( vlc_object_t * );
89
90 /*****************************************************************************
91  * Module descriptor
92  *****************************************************************************/
93 vlc_module_begin();
94     set_description( _("HTTP 1.0 daemon") );
95     set_capability( "httpd", 42 );
96     set_callbacks( Open, Close );
97     var_Create( p_module->p_libvlc, "httpd", VLC_VAR_MUTEX );
98 vlc_module_end();
99
100 /*****************************************************************************
101  * Prototypes
102  *****************************************************************************/
103 static httpd_host_t     *RegisterHost   ( httpd_t *, char *, int );
104 static void             UnregisterHost  ( httpd_t *, httpd_host_t * );
105
106 static httpd_file_t     *RegisterFile   ( httpd_t *,
107                                           char *psz_file, char *psz_mime,
108                                           char *psz_user, char *psz_password,
109                                           httpd_file_callback pf_get,
110                                           httpd_file_callback pf_post,
111                                           httpd_file_callback_args_t *p_args );
112 static void             UnregisterFile  ( httpd_t *, httpd_file_t * );
113
114 //#define httpd_stream_t              httpd_file_t
115 static httpd_stream_t   *RegisterStream ( httpd_t *,
116                                          char *psz_file, char *psz_mime,
117                                          char *psz_user, char *psz_password );
118 static int              SendStream      ( httpd_t *, httpd_stream_t *, uint8_t *, int );
119 static int              HeaderStream    ( httpd_t *, httpd_stream_t *, uint8_t *, int );
120 static void             UnregisterStream( httpd_t *, httpd_stream_t* );
121 static int              Control         ( httpd_t *, int , void*, void* );
122 /*****************************************************************************
123  * Internal definitions
124  *****************************************************************************/
125 struct httpd_host_t
126 {
127     int    i_ref;
128
129     char   *psz_host_addr;
130     int    i_port;
131
132     struct sockaddr_in sock;
133     int    fd;
134
135 };
136
137 #define HTTPD_AUTHENTICATE_NONE     0
138 #define HTTPD_AUTHENTICATE_BASIC    1
139
140 //typedef httpd_file_t httpd_stream_t;
141
142 struct httpd_file_t
143 {
144     int         i_ref;
145
146     char        *psz_file;
147     char        *psz_mime;
148
149
150     int         i_authenticate_method;
151         char        *psz_user;          /* NULL if no auth */
152         char        *psz_password;      /* NULL if no auth */
153
154     vlc_bool_t  b_stream;               /* if false: httpd will retreive data by a callback
155                                               true:  it's up to the program to give data to httpd */
156     void                *p_sys;         /* provided for user */
157     httpd_file_callback pf_get;         /* it should allocate and fill *pp_data and *pi_data */
158     httpd_file_callback pf_post;        /* it should allocate and fill *pp_data and *pi_data */
159
160     /* private */
161
162     /* circular buffer for stream only */
163     int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
164     uint8_t     *p_buffer;          /* buffer */
165     int64_t     i_buffer_pos;       /* absolute position from begining */
166     int         i_buffer_last_pos;  /* a new connection will start with that */
167
168     /* data to be send at connection time (if any) */
169     int         i_header_size;
170     uint8_t     *p_header;
171 };
172
173
174 #define HTTPD_CONNECTION_RECEIVING_REQUEST      1
175 #define HTTPD_CONNECTION_SENDING_HEADER         2
176 #define HTTPD_CONNECTION_SENDING_FILE           3
177 #define HTTPD_CONNECTION_SENDING_STREAM         4
178 #define HTTPD_CONNECTION_TO_BE_CLOSED           5
179
180 #define HTTPD_CONNECTION_METHOD_GET             1
181 #define HTTPD_CONNECTION_METHOD_POST            2
182 typedef struct httpd_connection_s
183 {
184     struct httpd_connection_s *p_next;
185     struct httpd_connection_s *p_prev;
186
187     struct  sockaddr_in sock;
188     int     fd;
189     mtime_t i_last_activity_date;
190
191     int    i_state;
192     int    i_method;       /* get/post */
193
194     char    *psz_file;      // file to be send
195     int     i_http_error;   // error to be send with the file
196     char    *psz_user;      // if Authorization in the request header
197     char    *psz_password;
198
199     uint8_t *p_request;     // whith get: ?<*>, with post: main data
200     int      i_request_size;
201
202     httpd_file_t    *p_file;
203
204     /* used while sending header and file */
205     int     i_buffer_size;
206     uint8_t *p_buffer;
207     int     i_buffer;            /* private */
208
209     /* used for stream */
210     int64_t i_stream_pos;   /* absolute pos in stream */
211 } httpd_connection_t;
212
213 /* Linked List of banned IP */
214 typedef struct httpd_banned_ip_s
215 {
216     struct httpd_banned_ip_s *p_next;
217     struct httpd_banned_ip_s *p_prev;
218
219     char *psz_ip;
220
221 } httpd_banned_ip_t;
222 /*
223  * The httpd thread
224  */
225 struct httpd_sys_t
226 {
227     VLC_COMMON_MEMBERS
228
229     vlc_mutex_t             host_lock;
230     volatile int            i_host_count;
231     httpd_host_t            **host;
232
233     vlc_mutex_t             file_lock;
234     int                     i_file_count;
235     httpd_file_t            **file;
236
237     vlc_mutex_t             connection_lock;
238     int                     i_connection_count;
239     httpd_connection_t      *p_first_connection;
240
241     vlc_mutex_t             ban_lock;
242     int                     i_banned_ip_count;
243     httpd_banned_ip_t       *p_first_banned_ip;
244 };
245
246 static void httpd_Thread( httpd_sys_t *p_httpt );
247 static void httpd_ConnnectionNew( httpd_sys_t *, int , struct sockaddr_in * );
248 static void httpd_ConnnectionClose( httpd_sys_t *, httpd_connection_t * );
249 static int httpd_UnbanIP( httpd_sys_t *, httpd_banned_ip_t *);
250 static int httpd_BanIP( httpd_sys_t *, char *);
251 static httpd_banned_ip_t *httpd_GetbannedIP( httpd_sys_t *, char * );
252
253 /*****************************************************************************
254  * Open:
255  *****************************************************************************/
256
257 static int Open( vlc_object_t *p_this )
258 {
259     httpd_t     *p_httpd = (httpd_t*)p_this;
260     httpd_sys_t *p_httpt;
261
262     /* Launch httpt thread */
263     if( !( p_httpt = vlc_object_create( p_this, sizeof( httpd_sys_t ) ) ) )
264     {
265         msg_Err( p_this, "out of memory" );
266         return( VLC_EGENERIC );
267     }
268
269     p_httpt->b_die  = 0;
270     p_httpt->b_error= 0;
271
272     /* init httpt_t structure */
273     vlc_mutex_init( p_httpd, &p_httpt->host_lock );
274     p_httpt->i_host_count = 0;
275     p_httpt->host = NULL;
276
277     vlc_mutex_init( p_httpd, &p_httpt->file_lock );
278     p_httpt->i_file_count = 0;
279     p_httpt->file = NULL;
280
281     vlc_mutex_init( p_httpd, &p_httpt->connection_lock );
282     p_httpt->i_connection_count = 0;
283     p_httpt->p_first_connection = NULL;
284
285     vlc_mutex_init( p_httpd, &p_httpt->ban_lock );
286     p_httpt->i_banned_ip_count = 0;
287     p_httpt->p_first_banned_ip = NULL;
288
289     /* start the thread */
290     if( vlc_thread_create( p_httpt, "httpd thread",
291                            httpd_Thread, VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
292     {
293         msg_Err( p_this, "cannot spawn http thread" );
294
295         vlc_mutex_destroy( &p_httpt->host_lock );
296         vlc_mutex_destroy( &p_httpt->file_lock );
297         vlc_mutex_destroy( &p_httpt->connection_lock );
298         vlc_mutex_destroy( &p_httpt->ban_lock );
299
300         vlc_object_destroy( p_httpt );
301         return( VLC_EGENERIC );
302     }
303
304     msg_Info( p_httpd, "http thread launched" );
305
306     p_httpd->p_sys = p_httpt;
307     p_httpd->pf_register_host   = RegisterHost;
308     p_httpd->pf_unregister_host = UnregisterHost;
309     p_httpd->pf_register_file   = RegisterFile;
310     p_httpd->pf_unregister_file = UnregisterFile;
311     p_httpd->pf_register_stream = RegisterStream;
312     p_httpd->pf_header_stream   = HeaderStream;
313     p_httpd->pf_send_stream     = SendStream;
314     p_httpd->pf_unregister_stream=UnregisterStream;
315     p_httpd->pf_control         = Control;
316
317     return( VLC_SUCCESS );
318 }
319
320 /*****************************************************************************
321  * Close: close the target
322  *****************************************************************************/
323 static void Close( vlc_object_t * p_this )
324 {
325     httpd_t     *p_httpd = (httpd_t*)p_this;
326     httpd_sys_t *p_httpt = p_httpd->p_sys;
327
328     httpd_connection_t *p_con;
329     httpd_banned_ip_t *p_banned_ip;
330
331     int i;
332
333     p_httpt->b_die = 1;
334     vlc_thread_join( p_httpt );
335
336     /* first close all host */
337     vlc_mutex_destroy( &p_httpt->host_lock );
338     if( p_httpt->i_host_count )
339     {
340         msg_Err( p_httpd, "still have %d hosts registered !", p_httpt->i_host_count );
341     }
342     for( i = 0; i < p_httpt->i_host_count; i++ )
343     {
344 #define p_host p_httpt->host[i]
345         FREE( p_host->psz_host_addr );
346         SOCKET_CLOSE( p_host->fd );
347
348         FREE( p_host );
349 #undef p_host
350     }
351     FREE( p_httpt->host );
352
353     /* now all file */
354     vlc_mutex_destroy( &p_httpt->file_lock );
355     if( p_httpt->i_file_count )
356     {
357         msg_Err( p_httpd, "still have %d files registered !", p_httpt->i_file_count );
358     }
359     for( i = 0; i < p_httpt->i_file_count; i++ )
360     {
361 #define p_file p_httpt->file[i]
362         FREE( p_file->psz_file );
363         FREE( p_file->psz_mime );
364         if( p_file->i_authenticate_method != HTTPD_AUTHENTICATE_NONE )
365         {
366             FREE( p_file->psz_user );
367             FREE( p_file->psz_password );
368         }
369         FREE( p_file->p_buffer );
370
371         FREE( p_file );
372 #undef p_file
373     }
374     FREE( p_httpt->file );
375
376     /* andd close all connection */
377     vlc_mutex_destroy( &p_httpt->connection_lock );
378     if( p_httpt->i_connection_count )
379     {
380         msg_Warn( p_httpd, "%d connections still in use", p_httpt->i_connection_count );
381     }
382     while( ( p_con = p_httpt->p_first_connection ) )
383     {
384         httpd_ConnnectionClose( p_httpt, p_con );
385     }
386
387     /* Free all banned IP */
388     vlc_mutex_destroy( &p_httpt->ban_lock );
389     while( ( p_banned_ip = p_httpt->p_first_banned_ip))
390     {
391         httpd_UnbanIP(p_httpt,p_banned_ip);
392     }
393
394     msg_Info( p_httpd, "httpd instance closed" );
395     vlc_object_destroy( p_httpt );
396 }
397
398
399 /****************************************************************************
400  ****************************************************************************
401  ***
402  ***
403  ****************************************************************************
404  ****************************************************************************/
405 static int BuildAddr( struct sockaddr_in * p_socket,
406                       const char * psz_address, int i_port )
407 {
408     /* Reset struct */
409     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
410     p_socket->sin_family = AF_INET;                                /* family */
411     p_socket->sin_port = htons( (uint16_t)i_port );
412     if( !*psz_address )
413     {
414         p_socket->sin_addr.s_addr = INADDR_ANY;
415     }
416     else
417     {
418         struct hostent    * p_hostent;
419
420         /* Try to convert address directly from in_addr - this will work if
421          * psz_address is dotted decimal. */
422 #ifdef HAVE_ARPA_INET_H
423         if( !inet_aton( psz_address, &p_socket->sin_addr ) )
424 #else
425         p_socket->sin_addr.s_addr = inet_addr( psz_address );
426         if( p_socket->sin_addr.s_addr == INADDR_NONE )
427 #endif
428         {
429             /* We have a fqdn, try to find its address */
430             if ( (p_hostent = gethostbyname( psz_address )) == NULL )
431             {
432                 return( -1 );
433             }
434
435             /* Copy the first address of the host in the socket address */
436             memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
437                      p_hostent->h_length );
438         }
439     }
440     return( 0 );
441 }
442
443
444 /*
445  * listen on a host for a httpd instance
446  */
447
448 static httpd_host_t *_RegisterHost( httpd_sys_t *p_httpt, char *psz_host_addr, int i_port )
449 {
450     httpd_host_t    *p_host;
451     struct sockaddr_in  sock;
452     int i;
453     int fd = -1;
454     int i_opt;
455 #if !defined( WIN32 ) && !defined( UNDER_CE )
456     int i_flags;
457 #endif
458
459     if( BuildAddr( &sock, psz_host_addr, i_port ) )
460     {
461         msg_Err( p_httpt, "cannot build address for %s:%d", psz_host_addr, i_port );
462         return NULL;
463     }
464
465     /* is it already declared ? */
466     vlc_mutex_lock( &p_httpt->host_lock );
467     for( i = 0; i < p_httpt->i_host_count; i++ )
468     {
469         if( p_httpt->host[i]->sock.sin_port == sock.sin_port &&
470             ( p_httpt->host[i]->sock.sin_addr.s_addr == INADDR_ANY ||
471             p_httpt->host[i]->sock.sin_addr.s_addr == sock.sin_addr.s_addr ) )
472         {
473             break;
474         }
475     }
476
477     if( i < p_httpt->i_host_count )
478     {
479         /* yes, increment ref count and succed */
480         p_httpt->host[i]->i_ref++;
481         vlc_mutex_unlock( &p_httpt->host_lock );
482         return( p_httpt->host[i] );
483     }
484
485     /* need to add a new listening socket */
486
487     /* open socket */
488     fd = socket( AF_INET, SOCK_STREAM, 0 );
489     if( fd < 0 )
490     {
491         msg_Err( p_httpt, "cannot open socket" );
492         goto socket_failed;
493     }
494     /* reuse socket */
495     i_opt = 1;
496     if( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,
497                     (void *) &i_opt, sizeof( i_opt ) ) < 0 )
498     {
499         msg_Warn( p_httpt, "cannot configure socket (SO_REUSEADDR)" );
500     }
501     /* bind it */
502     if( bind( fd, (struct sockaddr *)&sock, sizeof( struct sockaddr_in ) ) < 0 )
503     {
504         msg_Err( p_httpt, "cannot bind socket" );
505         goto socket_failed;
506     }
507     /* set to non-blocking */
508 #if defined( WIN32 ) || defined( UNDER_CE )
509     {
510         unsigned long i_dummy = 1;
511         if( ioctlsocket( fd, FIONBIO, &i_dummy ) != 0 )
512         {
513             msg_Err( p_httpt, "cannot set socket to non-blocking mode" );
514             goto socket_failed;
515         }
516     }
517 #else
518     if( ( i_flags = fcntl( fd, F_GETFL, 0 ) ) < 0 )
519     {
520         msg_Err( p_httpt, "cannot F_GETFL socket" );
521         goto socket_failed;
522     }
523     if( fcntl( fd, F_SETFL, i_flags | O_NONBLOCK ) < 0 )
524     {
525         msg_Err( p_httpt, "cannot F_SETFL O_NONBLOCK" );
526         goto socket_failed;
527     }
528 #endif
529     /* listen */
530     if( listen( fd, LISTEN_BACKLOG ) < 0 )
531     {
532         msg_Err( p_httpt, "cannot listen socket" );
533         goto socket_failed;
534     }
535
536     if( p_httpt->host )
537     {
538         p_httpt->host = realloc( p_httpt->host, sizeof( httpd_host_t *)  * ( p_httpt->i_host_count + 1 ) );
539     }
540     else
541     {
542         p_httpt->host = malloc( sizeof( httpd_host_t *) );
543     }
544     p_host                = malloc( sizeof( httpd_host_t ) );
545     p_host->i_ref         = 1;
546     p_host->psz_host_addr = strdup( psz_host_addr );
547     p_host->i_port        = i_port;
548     p_host->sock          = sock;
549     p_host->fd            = fd;
550
551     p_httpt->host[p_httpt->i_host_count++] = p_host;
552     vlc_mutex_unlock( &p_httpt->host_lock );
553
554     return p_host;
555
556 socket_failed:
557     vlc_mutex_unlock( &p_httpt->host_lock );
558     if( fd >= 0 )
559     {
560         SOCKET_CLOSE( fd );
561     }
562     return NULL;
563 }
564 static httpd_host_t     *RegisterHost( httpd_t *p_httpd, char *psz_host_addr, int i_port )
565 {
566     return( _RegisterHost( p_httpd->p_sys, psz_host_addr, i_port ) );
567 }
568
569 /*
570  * remove a listening host for an httpd instance
571  */
572 static void            _UnregisterHost( httpd_sys_t *p_httpt, httpd_host_t *p_host )
573 {
574     int i;
575
576     vlc_mutex_lock( &p_httpt->host_lock );
577     for( i = 0; i < p_httpt->i_host_count; i++ )
578     {
579         if( p_httpt->host[i] == p_host )
580         {
581             break;
582         }
583     }
584     if( i >= p_httpt->i_host_count )
585     {
586         vlc_mutex_unlock( &p_httpt->host_lock );
587         msg_Err( p_httpt, "cannot unregister host" );
588         return;
589     }
590
591     p_host->i_ref--;
592
593     if( p_host->i_ref > 0 )
594     {
595         /* still in use */
596         vlc_mutex_unlock( &p_httpt->host_lock );
597         return;
598     }
599
600     /* no more used */
601     FREE( p_host->psz_host_addr );
602     SOCKET_CLOSE( p_host->fd );
603
604     FREE( p_host );
605
606     if( p_httpt->i_host_count <= 1 )
607     {
608         FREE( p_httpt->host );
609         p_httpt->i_host_count = 0;
610     }
611     else
612     {
613         int i_move;
614
615         i_move = p_httpt->i_host_count - i - 1;
616
617         if( i_move > 0 )
618         {
619             memmove( &p_httpt->host[i],
620                      &p_httpt->host[i+1],
621                      i_move * sizeof( httpd_host_t * ) );
622         }
623
624         p_httpt->i_host_count--;
625         p_httpt->host = realloc( p_httpt->host,
626                                  p_httpt->i_host_count * sizeof( httpd_host_t * ) );
627     }
628
629     vlc_mutex_unlock( &p_httpt->host_lock );
630 }
631 static void             UnregisterHost( httpd_t *p_httpd, httpd_host_t *p_host )
632 {
633     _UnregisterHost( p_httpd->p_sys, p_host );
634 }
635
636
637 static void __RegisterFile( httpd_sys_t *p_httpt, httpd_file_t *p_file )
638 {
639     /* add a new file */
640     if( p_httpt->i_file_count )
641     {
642         p_httpt->file = realloc( p_httpt->file, sizeof( httpd_file_t *)  * ( p_httpt->i_file_count + 1 ) );
643     }
644     else
645     {
646         p_httpt->file = malloc( sizeof( httpd_file_t *) );
647     }
648
649     p_httpt->file[p_httpt->i_file_count++] = p_file;
650 }
651
652 static httpd_file_t    *_RegisterFile( httpd_sys_t *p_httpt,
653                                        char *psz_file, char *psz_mime,
654                                        char *psz_user, char *psz_password,
655                                        httpd_file_callback pf_get,
656                                        httpd_file_callback pf_post,
657                                        httpd_file_callback_args_t *p_args )
658 {
659     httpd_file_t    *p_file;
660     int i;
661
662     vlc_mutex_lock( &p_httpt->file_lock );
663     for( i = 0; i < p_httpt->i_file_count; i++ )
664     {
665         if( !strcmp( psz_file, p_httpt->file[i]->psz_file ) )
666         {
667             break;
668         }
669     }
670     if( i < p_httpt->i_file_count )
671     {
672         vlc_mutex_unlock( &p_httpt->file_lock );
673         msg_Err( p_httpt, "%s already registered", psz_file );
674         return NULL;
675     }
676
677     p_file              = malloc( sizeof( httpd_file_t ) );
678     p_file->i_ref       = 0;
679     p_file->psz_file    = strdup( psz_file );
680     p_file->psz_mime    = strdup( psz_mime );
681     if( psz_user && *psz_user )
682     {
683         p_file->i_authenticate_method = HTTPD_AUTHENTICATE_BASIC;
684         p_file->psz_user              = strdup( psz_user );
685         p_file->psz_password          = strdup( psz_password );
686     }
687     else
688     {
689         p_file->i_authenticate_method = HTTPD_AUTHENTICATE_NONE;
690         p_file->psz_user              = NULL;
691         p_file->psz_password          = NULL;
692     }
693
694     p_file->b_stream          = VLC_FALSE;
695     p_file->p_sys             = p_args;
696     p_file->pf_get            = pf_get;
697     p_file->pf_post           = pf_post;
698
699     p_file->i_buffer_size     = 0;
700     p_file->i_buffer_last_pos = 0;
701     p_file->i_buffer_pos      = 0;
702     p_file->p_buffer          = NULL;
703
704     p_file->i_header_size     = 0;
705     p_file->p_header          = NULL;
706
707     __RegisterFile( p_httpt, p_file );
708
709     vlc_mutex_unlock( &p_httpt->file_lock );
710
711     return p_file;
712 }
713 static httpd_file_t     *RegisterFile( httpd_t *p_httpd,
714                                        char *psz_file, char *psz_mime,
715                                        char *psz_user, char *psz_password,
716                                        httpd_file_callback pf_get,
717                                        httpd_file_callback pf_post,
718                                        httpd_file_callback_args_t *p_args )
719 {
720     return( _RegisterFile( p_httpd->p_sys,
721                            psz_file, psz_mime, psz_user, psz_password,
722                            pf_get, pf_post, p_args ) );
723 }
724
725 static httpd_stream_t  *_RegisterStream( httpd_sys_t *p_httpt,
726                                          char *psz_file, char *psz_mime,
727                                          char *psz_user, char *psz_password )
728 {
729     httpd_stream_t    *p_stream;
730     int i;
731
732     vlc_mutex_lock( &p_httpt->file_lock );
733     for( i = 0; i < p_httpt->i_file_count; i++ )
734     {
735         if( !strcmp( psz_file, p_httpt->file[i]->psz_file ) )
736         {
737             break;
738         }
739     }
740     if( i < p_httpt->i_file_count )
741     {
742         vlc_mutex_unlock( &p_httpt->file_lock );
743         msg_Err( p_httpt, "%s already registered", psz_file );
744         return NULL;
745     }
746
747     p_stream              = malloc( sizeof( httpd_stream_t ) );
748     p_stream->i_ref       = 0;
749     p_stream->psz_file    = strdup( psz_file );
750     p_stream->psz_mime    = strdup( psz_mime );
751     if( psz_user && *psz_user )
752     {
753         p_stream->i_authenticate_method = HTTPD_AUTHENTICATE_BASIC;
754         p_stream->psz_user              = strdup( psz_user );
755         p_stream->psz_password          = strdup( psz_password );
756     }
757     else
758     {
759         p_stream->i_authenticate_method = HTTPD_AUTHENTICATE_NONE;
760         p_stream->psz_user              = NULL;
761         p_stream->psz_password          = NULL;
762     }
763
764     p_stream->b_stream        = VLC_TRUE;
765     p_stream->p_sys           = NULL;
766     p_stream->pf_get          = NULL;
767     p_stream->pf_post         = NULL;
768
769     p_stream->i_buffer_size   = 5*1024*1024;
770     p_stream->i_buffer_pos      = 0;
771     p_stream->i_buffer_last_pos = 0;
772     p_stream->p_buffer        = malloc( p_stream->i_buffer_size );
773
774     p_stream->i_header_size   = 0;
775     p_stream->p_header        = NULL;
776
777     __RegisterFile( p_httpt, p_stream );
778
779     vlc_mutex_unlock( &p_httpt->file_lock );
780
781     return p_stream;
782 }
783 static httpd_stream_t   *RegisterStream( httpd_t *p_httpd,
784                                          char *psz_file, char *psz_mime,
785                                          char *psz_user, char *psz_password )
786 {
787     return( _RegisterStream( p_httpd->p_sys,
788                              psz_file, psz_mime, psz_user, psz_password ) );
789 }
790
791 static void            _UnregisterFile( httpd_sys_t *p_httpt, httpd_file_t *p_file )
792 {
793     int i;
794
795     vlc_mutex_lock( &p_httpt->file_lock );
796     for( i = 0; i < p_httpt->i_file_count; i++ )
797     {
798         if( !strcmp( p_file->psz_file, p_httpt->file[i]->psz_file ) )
799         {
800             break;
801         }
802     }
803     if( i >= p_httpt->i_file_count )
804     {
805         vlc_mutex_unlock( &p_httpt->file_lock );
806         msg_Err( p_httpt, "cannot unregister file" );
807         return;
808     }
809
810     if( p_file->i_ref > 0 )
811     {
812         httpd_connection_t *p_con;
813         /* force closing all connection for this file */
814         msg_Err( p_httpt, "closing all client connection" );
815
816         vlc_mutex_lock( &p_httpt->connection_lock );
817         for( p_con = p_httpt->p_first_connection; p_con != NULL; )
818         {
819             httpd_connection_t *p_next;
820
821             p_next = p_con->p_next;
822             if( p_con->p_file == p_file )
823             {
824                 httpd_ConnnectionClose( p_httpt, p_con );
825             }
826             p_con = p_next;
827         }
828         vlc_mutex_unlock( &p_httpt->connection_lock );
829     }
830
831     FREE( p_file->psz_file );
832     FREE( p_file->psz_mime );
833     if( p_file->i_authenticate_method != HTTPD_AUTHENTICATE_NONE )
834     {
835         FREE( p_file->psz_user );
836         FREE( p_file->psz_password );
837     }
838     FREE( p_file->p_buffer );
839     FREE( p_file->p_header );
840
841     FREE( p_file );
842
843
844     if( p_httpt->i_file_count == 1 )
845     {
846         FREE( p_httpt->file );
847         p_httpt->i_file_count = 0;
848     }
849     else
850     {
851         int i_move;
852
853         i_move = p_httpt->i_file_count - i - 1;
854         if( i_move > 0  )
855         {
856             memmove( &p_httpt->file[i], &p_httpt->file[i + 1], sizeof( httpd_file_t *) * i_move );
857         }
858         p_httpt->i_file_count--;
859         p_httpt->file = realloc( p_httpt->file, sizeof( httpd_file_t *) * p_httpt->i_file_count );
860     }
861
862     vlc_mutex_unlock( &p_httpt->file_lock );
863 }
864 static void            UnregisterFile( httpd_t *p_httpd, httpd_file_t *p_file )
865 {
866     _UnregisterFile( p_httpd->p_sys, p_file );
867 }
868
869 static void             UnregisterStream( httpd_t *p_httpd, httpd_stream_t *p_stream )
870 {
871     _UnregisterFile( p_httpd->p_sys, p_stream );
872 }
873
874
875
876 static int             _SendStream( httpd_sys_t *p_httpt, httpd_stream_t *p_stream, uint8_t *p_data, int i_data )
877 {
878     int i_count;
879     int i_pos;
880
881     if( i_data <= 0 || p_data == NULL )
882     {
883         return( VLC_SUCCESS );
884     }
885     //fprintf( stderr, "## i_data=%d pos=%lld\n", i_data, p_stream->i_buffer_pos );
886
887     vlc_mutex_lock( &p_httpt->file_lock );
888
889     /* save this pointer (to be used by new connection) */
890     p_stream->i_buffer_last_pos = p_stream->i_buffer_pos;
891
892     i_pos = p_stream->i_buffer_pos % p_stream->i_buffer_size;
893     i_count = i_data;
894     while( i_count > 0)
895     {
896         int i_copy;
897
898         i_copy = __MIN( i_count, p_stream->i_buffer_size - i_pos );
899
900         memcpy( &p_stream->p_buffer[i_pos],
901                 p_data,
902                 i_copy );
903
904         i_pos = ( i_pos + i_copy ) % p_stream->i_buffer_size;
905         i_count -= i_copy;
906         p_data += i_copy;
907     }
908
909     p_stream->i_buffer_pos += i_data;
910     vlc_mutex_unlock( &p_httpt->file_lock );
911
912     return( VLC_SUCCESS );
913 }
914 static int             SendStream( httpd_t *p_httpd, httpd_stream_t *p_stream, uint8_t *p_data, int i_data )
915 {
916     return( _SendStream( p_httpd->p_sys, p_stream, p_data, i_data ) );
917 }
918
919 static int             HeaderStream( httpd_t *p_httpd, httpd_stream_t *p_stream, uint8_t *p_data, int i_data )
920 {
921     httpd_sys_t *p_httpt = p_httpd->p_sys;
922
923     vlc_mutex_lock( &p_httpt->file_lock );
924
925     FREE( p_stream->p_header );
926     if( p_data == NULL || i_data <= 0 )
927     {
928         p_stream->i_header_size = 0;
929     }
930     else
931     {
932         p_stream->i_header_size = i_data;
933         p_stream->p_header = malloc( i_data );
934         memcpy( p_stream->p_header,
935                 p_data,
936                 i_data );
937     }
938     vlc_mutex_unlock( &p_httpt->file_lock );
939
940     return( VLC_SUCCESS );
941 }
942
943 static void httpd_info_add_ss( httpd_info_t *p_info, char *name, char *value )
944 {
945     if( p_info->i_count == 0 )
946     {
947         p_info->info = malloc( sizeof( httpd_val_t ) );
948     }
949     else
950     {
951         p_info->info =
952             realloc( p_info->info,
953                      sizeof( httpd_val_t ) * ( p_info->i_count + 1 ) );
954     }
955     p_info->info[p_info->i_count].psz_name  = strdup( name );
956     p_info->info[p_info->i_count].psz_value = strdup( value );
957     p_info->i_count++;
958 }
959
960 static void httpd_info_add_si( httpd_info_t *p_info, char *name, int i_value )
961 {
962     char v[40];
963
964     sprintf( v, "%d", i_value );
965     httpd_info_add_ss( p_info, name, v );
966 }
967
968 static void httpd_info_add_sp( httpd_info_t *p_info, char *name, void *value )
969 {
970     char v[40];
971
972     sprintf( v, "%p", value );
973     httpd_info_add_ss( p_info, name, v );
974 }
975
976
977 static int Control( httpd_t *p_httpd,
978                     int i_query, void *arg1, void *arg2 )
979 {
980     httpd_sys_t  *p_httpt = p_httpd->p_sys;
981     httpd_info_t *p_info;
982     httpd_connection_t *p_con;
983     int i;
984     void *id;
985
986     switch( i_query )
987     {
988         case HTTPD_GET_HOSTS:
989             p_info = arg1;
990             p_info->i_count = 0;
991             vlc_mutex_lock( &p_httpt->host_lock );
992             for( i = 0; i < p_httpt->i_host_count; i++ )
993             {
994                 httpd_info_add_sp( p_info,
995                                    "id", p_httpt->host[i] );
996                 httpd_info_add_ss( p_info,
997                                    "host", p_httpt->host[i]->psz_host_addr );
998                 httpd_info_add_ss( p_info,
999                                    "ip",
1000                                    inet_ntoa(p_httpt->host[i]->sock.sin_addr));
1001                 httpd_info_add_si( p_info,
1002                                    "port", p_httpt->host[i]->i_port );
1003             }
1004             vlc_mutex_unlock( &p_httpt->host_lock );
1005             return VLC_SUCCESS;
1006         case HTTPD_GET_URLS:
1007             p_info = arg1;
1008             p_info->i_count = 0;
1009             /* we can't take file_lock */
1010             for( i = 0; i < p_httpt->i_file_count; i++ )
1011             {
1012                 httpd_info_add_sp( p_info,
1013                                    "id", p_httpt->file[i] );
1014                 httpd_info_add_si( p_info,
1015                                    "stream", p_httpt->file[i]->b_stream ? 1 : 0 );
1016                 httpd_info_add_ss( p_info,
1017                                    "url", p_httpt->file[i]->psz_file );
1018                 httpd_info_add_ss( p_info,
1019                                    "mime", p_httpt->file[i]->psz_mime );
1020                 httpd_info_add_si( p_info,
1021                                    "protected", p_httpt->file[i]->psz_user ? 1 : 0 );
1022                 httpd_info_add_si( p_info,
1023                                    "used", p_httpt->file[i]->i_ref );
1024             }
1025             return VLC_SUCCESS;
1026         case HTTPD_GET_CONNECTIONS:
1027             p_info = arg1;
1028             p_info->i_count = 0;
1029             /* we can't take lock */
1030             for( p_con = p_httpt->p_first_connection;p_con != NULL; p_con = p_con->p_next )
1031             {
1032                 httpd_info_add_sp( p_info,
1033                                    "id", p_con );
1034                 httpd_info_add_ss( p_info,
1035                                    "ip", inet_ntoa( p_con->sock.sin_addr ) );
1036                 httpd_info_add_ss( p_info,
1037                                    "url", p_con->psz_file );
1038                 httpd_info_add_si( p_info,
1039                                    "status", p_con->i_http_error );
1040             }
1041             return VLC_SUCCESS;
1042         case HTTPD_GET_ACL:
1043             p_info = arg1;
1044             p_info->i_count = 0;
1045             return VLC_EGENERIC;
1046
1047         case HTTPD_SET_CLOSE:
1048             sscanf( arg1, "%p", &id );
1049             fprintf( stderr, "Control: HTTPD_SET_CLOSE: id=%p", id );
1050
1051             for( p_con = p_httpt->p_first_connection;p_con != NULL; p_con = p_con->p_next )
1052             {
1053                 if( (void*)p_con == id )
1054                 {
1055                     /* XXX don't free p_con as it could be the one that it is sending ... */
1056                     p_con->i_state = HTTPD_CONNECTION_TO_BE_CLOSED;
1057                     return VLC_SUCCESS;
1058                 }
1059             }
1060             return VLC_EGENERIC;
1061
1062         case HTTPD_SET_ACL:
1063             sscanf( arg1, "%p", &id );
1064             fprintf( stderr, "Control: %p", id );
1065         default:
1066             return VLC_EGENERIC;
1067     }
1068 }
1069
1070 /****************************************************************************/
1071 /****************************************************************************/
1072 /****************************************************************************/
1073 /****************************************************************************/
1074 /****************************************************************************/
1075
1076 static int  httpd_page_401_get( httpd_file_callback_args_t *p_args,
1077                                 uint8_t *p_request, int i_request,
1078                                 uint8_t **pp_data, int *pi_data )
1079 {
1080     char *p;
1081
1082     p = *pp_data = malloc( 1024 );
1083
1084     p += sprintf( p, "<html>\n" );
1085     p += sprintf( p, "<head>\n" );
1086     p += sprintf( p, "<title>Error 401</title>\n" );
1087     p += sprintf( p, "</head>\n" );
1088     p += sprintf( p, "<body>\n" );
1089     p += sprintf( p, "<h1><center> 401 authentification needed</center></h1>\n" );
1090     p += sprintf( p, "<hr />\n" );
1091     p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
1092     p += sprintf( p, "</body>\n" );
1093     p += sprintf( p, "</html>\n" );
1094
1095     *pi_data = strlen( *pp_data ) + 1;
1096
1097     return VLC_SUCCESS;
1098 }
1099 static int  httpd_page_404_get( httpd_file_callback_args_t *p_args,
1100                                 uint8_t *p_request, int i_request,
1101                                 uint8_t **pp_data, int *pi_data )
1102 {
1103     char *p;
1104
1105     p = *pp_data = malloc( 1024 );
1106
1107     p += sprintf( p, "<html>\n" );
1108     p += sprintf( p, "<head>\n" );
1109     p += sprintf( p, "<title>Error 404</title>\n" );
1110     p += sprintf( p, "</head>\n" );
1111     p += sprintf( p, "<body>\n" );
1112     p += sprintf( p, "<h1><center> 404 Ressource not found</center></h1>\n" );
1113     p += sprintf( p, "<hr />\n" );
1114     p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
1115     p += sprintf( p, "</body>\n" );
1116     p += sprintf( p, "</html>\n" );
1117
1118     *pi_data = strlen( *pp_data ) + 1;
1119
1120     return VLC_SUCCESS;
1121 }
1122
1123
1124 static int httpd_BanIP( httpd_sys_t *p_httpt, char * psz_new_banned_ip)
1125 {
1126     httpd_banned_ip_t *p_new_banned_ip ;
1127
1128     p_new_banned_ip = malloc( sizeof( httpd_banned_ip_t ) );
1129     if( !p_new_banned_ip )
1130     {
1131         return -1;
1132     }
1133     p_new_banned_ip->p_next=NULL;
1134     p_new_banned_ip->psz_ip = malloc( strlen( psz_new_banned_ip ) + 1 );
1135     if( !p_new_banned_ip->psz_ip )
1136     {
1137         return -2;
1138     }
1139
1140     strcpy( p_new_banned_ip->psz_ip, psz_new_banned_ip );
1141
1142     msg_Dbg( p_httpt, "Banning IP %s", psz_new_banned_ip );
1143
1144     if( p_httpt->p_first_banned_ip )
1145     {
1146         httpd_banned_ip_t *p_last;
1147
1148         p_last = p_httpt->p_first_banned_ip;
1149         while( p_last->p_next )
1150         {
1151             p_last = p_last->p_next;
1152         }
1153
1154         p_last->p_next = p_new_banned_ip;
1155         p_new_banned_ip->p_prev = p_last;
1156     }
1157     else
1158     {
1159         p_new_banned_ip->p_prev = NULL;
1160
1161         p_httpt->p_first_banned_ip = p_new_banned_ip;
1162     }
1163
1164     p_httpt->i_banned_ip_count++;
1165     return 0;
1166 }
1167
1168 static httpd_banned_ip_t *httpd_GetbannedIP( httpd_sys_t *p_httpt, char *psz_ip )
1169 {
1170     httpd_banned_ip_t *p_ip;
1171
1172     p_ip = p_httpt->p_first_banned_ip;
1173
1174     while( p_ip)
1175     {
1176         if( strcmp( psz_ip, p_ip->psz_ip ) == 0 )
1177         {
1178             return p_ip;
1179         }
1180         p_ip = p_ip->p_next;
1181     }
1182
1183     return NULL;
1184 }
1185
1186 static int httpd_UnbanIP( httpd_sys_t *p_httpt, httpd_banned_ip_t *p_banned_ip )
1187 {
1188     if(!p_banned_ip)
1189     {
1190         return -1;
1191     }
1192
1193     msg_Dbg( p_httpt, "Unbanning IP %s",p_banned_ip->psz_ip);
1194
1195     /* first cut out from list */
1196     if( p_banned_ip->p_prev )
1197     {
1198         p_banned_ip->p_prev->p_next = p_banned_ip->p_next;
1199     }
1200     else
1201     {
1202         p_httpt->p_first_banned_ip = p_banned_ip->p_next;
1203     }
1204
1205     if( p_banned_ip->p_next )
1206     {
1207         p_banned_ip->p_next->p_prev = p_banned_ip->p_prev;
1208     }
1209
1210     FREE( p_banned_ip->psz_ip );
1211     FREE( p_banned_ip );
1212
1213     p_httpt->i_banned_ip_count--;
1214
1215     return 0;
1216 }
1217
1218 static void httpd_ConnnectionNew( httpd_sys_t *p_httpt, int fd, struct sockaddr_in *p_sock )
1219 {
1220     httpd_connection_t *p_con;
1221
1222     msg_Dbg( p_httpt, "new connection from %s", inet_ntoa( p_sock->sin_addr ) );
1223
1224     /* verify if it's a banned ip */
1225     if(httpd_GetbannedIP( p_httpt,inet_ntoa( p_sock->sin_addr ) ) )
1226     {
1227         msg_Dbg( p_httpt, "Ip %s banned : closing connection", inet_ntoa( p_sock->sin_addr ) );
1228         close(fd);
1229         return;
1230     }
1231
1232     /* create a new connection and link it */
1233     p_con = malloc( sizeof( httpd_connection_t ) );
1234     p_con->i_state  = HTTPD_CONNECTION_RECEIVING_REQUEST;
1235     p_con->fd       = fd;
1236     p_con->i_last_activity_date = mdate();
1237
1238     p_con->sock     = *p_sock;
1239     p_con->psz_file = NULL;
1240     p_con->i_http_error = 0;
1241     p_con->psz_user = NULL;
1242     p_con->psz_password = NULL;
1243     p_con->p_file   = NULL;
1244
1245     p_con->i_request_size = 0;
1246     p_con->p_request = NULL;
1247
1248     p_con->i_buffer = 0;
1249     p_con->i_buffer_size = 8096;
1250     p_con->p_buffer = malloc( p_con->i_buffer_size );
1251
1252     p_con->i_stream_pos = 0; // updated by httpd_thread */
1253     p_con->p_next = NULL;
1254
1255     if( p_httpt->p_first_connection )
1256     {
1257         httpd_connection_t *p_last;
1258
1259         p_last = p_httpt->p_first_connection;
1260         while( p_last->p_next )
1261         {
1262             p_last = p_last->p_next;
1263         }
1264
1265         p_last->p_next = p_con;
1266         p_con->p_prev = p_last;
1267     }
1268     else
1269     {
1270         p_con->p_prev = NULL;
1271
1272         p_httpt->p_first_connection = p_con;
1273     }
1274
1275     p_httpt->i_connection_count++;
1276 }
1277
1278 static void httpd_ConnnectionClose( httpd_sys_t *p_httpt, httpd_connection_t *p_con )
1279 {
1280     msg_Dbg( p_httpt, "close connection from %s", inet_ntoa( p_con->sock.sin_addr ) );
1281
1282     p_httpt->i_connection_count--;
1283     /* first cut out from list */
1284     if( p_con->p_prev )
1285     {
1286         p_con->p_prev->p_next = p_con->p_next;
1287     }
1288     else
1289     {
1290         p_httpt->p_first_connection = p_con->p_next;
1291     }
1292
1293     if( p_con->p_next )
1294     {
1295         p_con->p_next->p_prev = p_con->p_prev;
1296     }
1297
1298     if( p_con->p_file ) p_con->p_file->i_ref--;
1299     FREE( p_con->psz_file );
1300
1301     FREE( p_con->p_buffer );
1302     SOCKET_CLOSE( p_con->fd );
1303
1304     FREE( p_con->psz_user );
1305     FREE( p_con->psz_password );
1306
1307     FREE( p_con->p_request );
1308     free( p_con );
1309 }
1310
1311 static void httpd_RequestGetWord( char *word, int i_word_max, char **pp_buffer, char *p_end )
1312 {
1313     char *p = *pp_buffer;
1314     int i;
1315
1316     while( p < p_end && *p && ( *p == ' ' || *p == '\t' ) )
1317     {
1318         p++;
1319     }
1320
1321     i = 0;
1322     for( i = 0; i < i_word_max && p < p_end && *p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r'; i++,p++)
1323     {
1324         word[i] = *p;
1325     }
1326
1327     word[__MIN( i, i_word_max -1 )] = '\0';
1328
1329     *pp_buffer = p;
1330
1331 }
1332 static int httpd_RequestNextLine( char **pp_buffer, char *p_end )
1333 {
1334     char *p;
1335
1336     for( p = *pp_buffer; p < p_end; p++ )
1337     {
1338         if( p + 1 < p_end && *p == '\n' )
1339         {
1340             *pp_buffer = p + 1;
1341             return VLC_SUCCESS;
1342         }
1343         if( p + 2 < p_end && p[0] == '\r' && p[1] == '\n' )
1344         {
1345             *pp_buffer = p + 2;
1346             return VLC_SUCCESS;
1347         }
1348     }
1349     *pp_buffer = p_end;
1350     return VLC_EGENERIC;
1351 }
1352
1353 //char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1354 static void b64_decode( char *dest, char *src )
1355 {
1356     int  i_level;
1357     int  last = 0;
1358     int  b64[256] = {
1359         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
1360         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
1361         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
1362         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
1363         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
1364         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
1365         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
1366         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
1367         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
1368         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
1369         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
1370         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
1371         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
1372         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
1373         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
1374         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
1375         };
1376
1377     for( i_level = 0; *src != '\0'; src++ )
1378     {
1379         int  c;
1380
1381         c = b64[(unsigned int)*src];
1382         if( c == -1 )
1383         {
1384             src++;
1385             continue;
1386         }
1387
1388         switch( i_level )
1389         {
1390             case 0:
1391                 i_level++;
1392                 break;
1393             case 1:
1394                 *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
1395                 i_level++;
1396                 break;
1397             case 2:
1398                 *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
1399                 i_level++;
1400                 break;
1401             case 3:
1402                 *dest++ = ( ( last &0x03 ) << 6 ) | c;
1403                 i_level = 0;
1404         }
1405         last = c;
1406     }
1407
1408     *dest = '\0';
1409 }
1410
1411 static void httpd_ConnectionParseRequest( httpd_sys_t *p_httpt, httpd_connection_t *p_con )
1412 {
1413     char *psz_status;
1414     char *p, *p_end;
1415
1416     int  i;
1417     char command[32];
1418     char url[1024];
1419     char version[32];
1420     char user[512] = "";
1421     char password[512] = "";
1422
1423     //msg_Dbg( p_httpt, "new request=\n%s", p_con->p_buffer );
1424
1425
1426     p = p_con->p_buffer;
1427     p_end = p + strlen( p ) + 1;
1428
1429     httpd_RequestGetWord( command, 32, &p, p_end );
1430     httpd_RequestGetWord( url, 1024, &p, p_end );
1431     httpd_RequestGetWord( version, 32, &p, p_end );
1432     //msg_Dbg( p_httpt, "ask =%s= =%s= =%s=", command, url, version );
1433
1434     p_con->p_request      = NULL;
1435     p_con->i_request_size = 0;
1436     if( !strcmp( command, "GET" ) )
1437     {
1438         p_con->i_method = HTTPD_CONNECTION_METHOD_GET;
1439     }
1440     else if( !strcmp( command, "POST" ))
1441     {
1442         p_con->i_method = HTTPD_CONNECTION_METHOD_POST;
1443     }
1444     else
1445     {
1446         /* unimplemented */
1447         p_con->psz_file = strdup( "/501.html" );
1448         p_con->i_method = HTTPD_CONNECTION_METHOD_GET;
1449         p_con->i_http_error = 501;
1450         goto create_header;
1451     }
1452
1453     if( strcmp( version, "HTTP/1.0" ) && strcmp( version, "HTTP/1.1" ) )
1454     {
1455         p_con->psz_file = strdup( "/505.html" );
1456         p_con->i_http_error = 505;
1457
1458         goto create_header;
1459     }
1460
1461     /* parse headers */
1462     for( ;; )
1463     {
1464         char header[1024];
1465
1466         if( httpd_RequestNextLine( &p, p_end ) )
1467         {
1468             //msg_Dbg( p_httpt, "failled new line" );
1469             break;;
1470         }
1471         //msg_Dbg( p_httpt, "new line=%s", p );
1472
1473         httpd_RequestGetWord( header, 1024, &p, p_end );
1474         if( !strcmp( header, "\r\n" ) || !strcmp( header, "\n" ) )
1475         {
1476             break;
1477         }
1478
1479         if( !strcmp( header, "Authorization:" ) )
1480         {
1481             char method[32];
1482
1483             httpd_RequestGetWord( method, 32, &p, p_end );
1484             if( !strcasecmp( method, "BASIC" ) )
1485             {
1486                 char basic[1024];
1487                 char decoded[1024];
1488
1489                 httpd_RequestGetWord( basic, 1024, &p, p_end );
1490 //                msg_Dbg( p_httpt, "Authorization: basic:%s", basic );
1491                 b64_decode( decoded, basic );
1492 //                msg_Dbg( p_httpt, "Authorization: decoded:%s", decoded );
1493                 if( strchr( decoded, ':' ) )
1494                 {
1495                     char *p = strchr( decoded, ':' );
1496
1497                     p[0] = '\0'; p++;
1498                     strcpy( user, decoded );
1499                     strcpy( password, p );
1500                 }
1501             }
1502         }
1503     }
1504
1505     if( strchr( url, '?' ) )
1506     {
1507         char *p_request = strchr( url, '?' );
1508         *p_request++ = '\0';
1509         p_con->psz_file = strdup( url );
1510         p_con->p_request = strdup( p_request );
1511         p_con->i_request_size = strlen( p_con->p_request );
1512     }
1513     else
1514     {
1515         p_con->psz_file = strdup( url );
1516     }
1517
1518     /* fix p_request */
1519     if( p_con->i_method == HTTPD_CONNECTION_METHOD_POST )
1520     {
1521         char *p_request;
1522         if( strstr( p_con->p_buffer, "\r\n\r\n" ) )
1523         {
1524             p_request = strstr( p_con->p_buffer, "\r\n\r\n" ) + 4;
1525         }
1526         else if( strstr( p_con->p_buffer, "\n\n" ) )
1527         {
1528             p_request = strstr( p_con->p_buffer, "\n\n" ) + 2;
1529         }
1530         else
1531         {
1532             p_request = NULL;
1533         }
1534         if( p_request && p_request < p_end )
1535         {
1536             p_con->i_request_size = p_end - p_request;
1537             p_con->p_request = malloc( p_con->i_request_size + 1);
1538
1539             memcpy( p_con->p_request,
1540                     p_request,
1541                     p_con->i_request_size );
1542
1543             p_con->p_request[p_con->i_request_size] = '\0';
1544         }
1545     }
1546     p_con->i_http_error = 200;
1547
1548 create_header:
1549     //msg_Dbg( p_httpt, "ask %s %s %d", command, p_con->psz_file, p_con->i_http_error );
1550     FREE( p_con->p_buffer );
1551     p_con->i_buffer = 0;
1552     p_con->i_buffer_size = 0;
1553
1554     //vlc_mutex_lock( &p_httpt->file_lock );
1555 search_file:
1556     /* search file */
1557     p_con->p_file = NULL;
1558     for( i = 0; i < p_httpt->i_file_count; i++ )
1559     {
1560         if( !strcmp( p_httpt->file[i]->psz_file, p_con->psz_file ) )
1561         {
1562             if( p_httpt->file[i]->b_stream ||
1563                 ( p_con->i_method == HTTPD_CONNECTION_METHOD_GET  && p_httpt->file[i]->pf_get ) ||
1564                 ( p_con->i_method == HTTPD_CONNECTION_METHOD_POST && p_httpt->file[i]->pf_post ) )
1565             {
1566                 p_con->p_file = p_httpt->file[i];
1567                 break;
1568             }
1569         }
1570     }
1571
1572     if( !p_con->p_file )
1573     {
1574         p_con->psz_file = strdup( "/404.html" );
1575         p_con->i_http_error = 404;
1576
1577         /* XXX be sure that "/404.html" exist else ... */
1578         goto search_file;
1579     }
1580
1581     if( p_con->p_file->i_authenticate_method == HTTPD_AUTHENTICATE_BASIC )
1582     {
1583         if( strcmp( user, p_con->p_file->psz_user ) || strcmp( password, p_con->p_file->psz_password ) )
1584         {
1585             p_con->psz_file = strdup( "/401.html" );
1586             strcpy( user, p_con->p_file->psz_user );
1587             p_con->i_http_error = 401;
1588
1589             /* XXX do not put password on 404 else ... */
1590             goto search_file;
1591         }
1592     }
1593
1594     p_con->p_file->i_ref++;
1595 //    vlc_mutex_unlock( &p_httpt->file_lock );
1596
1597     switch( p_con->i_http_error )
1598     {
1599         case 200:
1600             psz_status = "OK";
1601             break;
1602
1603         case 401:
1604             psz_status = "Authorization Required";
1605             break;
1606         default:
1607             psz_status = "Unknown";
1608             break;
1609     }
1610
1611     p_con->i_state = HTTPD_CONNECTION_SENDING_HEADER;
1612
1613     p_con->i_buffer_size = 4096;
1614     p_con->i_buffer = 0;
1615
1616     /* we send stream header with this one */
1617     if( p_con->i_http_error == 200 && p_con->p_file->b_stream )
1618     {
1619         p_con->i_buffer_size += p_con->p_file->i_header_size;
1620     }
1621
1622     p = p_con->p_buffer = malloc( p_con->i_buffer_size );
1623
1624     p += sprintf( p, "HTTP/1.0 %d %s\r\n", p_con->i_http_error, psz_status );
1625     p += sprintf( p, "Content-type: %s\r\n", p_con->p_file->psz_mime );
1626     if( p_con->i_http_error == 401 )
1627     {
1628         p += sprintf( p, "WWW-Authenticate: Basic realm=\"%s\"\r\n", user );
1629     }
1630     p += sprintf( p, "Cache-Control: no-cache\r\n" );
1631     p += sprintf( p, "\r\n" );
1632
1633     p_con->i_buffer_size = strlen( p_con->p_buffer );// + 1;
1634
1635     if( p_con->i_http_error == 200 && p_con->p_file->b_stream && p_con->p_file->i_header_size > 0 )
1636     {
1637         /* add stream header */
1638         memcpy( &p_con->p_buffer[p_con->i_buffer_size],
1639                 p_con->p_file->p_header,
1640                 p_con->p_file->i_header_size );
1641         p_con->i_buffer_size += p_con->p_file->i_header_size;
1642     }
1643
1644     //msg_Dbg( p_httpt, "answer=\n%s", p_con->p_buffer );
1645 }
1646 #define HTTPD_STREAM_PACKET 10000
1647 static void httpd_Thread( httpd_sys_t *p_httpt )
1648 {
1649     httpd_file_t    *p_page_401;
1650     httpd_file_t    *p_page_404;
1651
1652     httpd_connection_t *p_con;
1653
1654     msg_Info( p_httpt, "httpd started" );
1655
1656     p_page_401 = _RegisterFile( p_httpt,
1657                                 "/401.html", "text/html",
1658                                 NULL, NULL,
1659                                 httpd_page_401_get,
1660                                 NULL,
1661                                 (httpd_file_callback_args_t*)NULL );
1662     p_page_404 = _RegisterFile( p_httpt,
1663                                 "/404.html", "text/html",
1664                                 NULL, NULL,
1665                                 httpd_page_404_get,
1666                                 NULL,
1667                                 (httpd_file_callback_args_t*)NULL );
1668
1669     while( !p_httpt->b_die )
1670     {
1671         struct timeval  timeout;
1672         fd_set          fds_read;
1673         fd_set          fds_write;
1674         int             i_handle_max = 0;
1675         int             i_ret;
1676         int i;
1677         if( p_httpt->i_host_count <= 0 )
1678         {
1679             msleep( 100 * 1000 );
1680             continue;
1681         }
1682
1683         /* we will create a socket set with host and connection */
1684         FD_ZERO( &fds_read );
1685         FD_ZERO( &fds_write );
1686
1687         vlc_mutex_lock( &p_httpt->host_lock );
1688         vlc_mutex_lock( &p_httpt->connection_lock );
1689         for( i = 0; i < p_httpt->i_host_count; i++ )
1690         {
1691             FD_SET( p_httpt->host[i]->fd, &fds_read );
1692             i_handle_max = __MAX( i_handle_max, p_httpt->host[i]->fd );
1693         }
1694         for( p_con = p_httpt->p_first_connection; p_con != NULL; )
1695         {
1696             /* no more than 10s of inactivity */
1697             if( p_con->i_last_activity_date + (mtime_t)HTTPD_CONNECTION_MAX_UNUSED < mdate() ||
1698                 p_con->i_state == HTTPD_CONNECTION_TO_BE_CLOSED)
1699             {
1700                 httpd_connection_t *p_next = p_con->p_next;
1701
1702                 msg_Dbg( p_httpt,  "close unused connection" );
1703                 httpd_ConnnectionClose( p_httpt, p_con );
1704                 p_con = p_next;
1705                 continue;
1706             }
1707
1708             if( p_con->i_state == HTTPD_CONNECTION_SENDING_STREAM && p_con->i_stream_pos + HTTPD_STREAM_PACKET >= p_con->p_file->i_buffer_pos )
1709             {
1710                 p_con = p_con->p_next;
1711                 continue;
1712             }
1713
1714             if( p_con->i_state == HTTPD_CONNECTION_RECEIVING_REQUEST )
1715             {
1716                 FD_SET( p_con->fd, &fds_read );
1717             }
1718             else
1719             {
1720                 FD_SET( p_con->fd, &fds_write );
1721             }
1722             i_handle_max = __MAX( i_handle_max, p_con->fd );
1723
1724             p_con = p_con->p_next;
1725         }
1726         vlc_mutex_unlock( &p_httpt->host_lock );
1727         vlc_mutex_unlock( &p_httpt->connection_lock );
1728
1729         /* we will wait 0.5s */
1730         timeout.tv_sec = 0;
1731         timeout.tv_usec = 500*1000;
1732
1733         i_ret = select( i_handle_max + 1,
1734                         &fds_read,
1735                         &fds_write,
1736                         NULL,
1737                         &timeout );
1738         if( i_ret == -1 && errno != EINTR )
1739         {
1740             msg_Warn( p_httpt, "cannot select sockets" );
1741             msleep( 1000 );
1742             continue;
1743         }
1744
1745         if( i_ret <= 0 )
1746         {
1747             continue;
1748         }
1749
1750         vlc_mutex_lock( &p_httpt->host_lock );
1751         /* accept/refuse new connection */
1752         for( i = 0; i < p_httpt->i_host_count; i++ )
1753         {
1754             int     i_sock_size = sizeof( struct sockaddr_in );
1755             struct  sockaddr_in sock;
1756             int     fd;
1757
1758             fd = accept( p_httpt->host[i]->fd, (struct sockaddr *)&sock,
1759                          &i_sock_size );
1760             if( fd > 0 )
1761             {
1762 #if defined( WIN32 ) || defined( UNDER_CE )
1763                 {
1764                     unsigned long i_dummy = 1;
1765                     ioctlsocket( fd, FIONBIO, &i_dummy );
1766                 }
1767 #else
1768                 fcntl( fd, F_SETFL, O_NONBLOCK );
1769 #endif
1770
1771                 if( p_httpt->i_connection_count >= HTTPD_MAX_CONNECTION )
1772                 {
1773                     msg_Warn( p_httpt, "max connection reached" );
1774                     SOCKET_CLOSE( fd );
1775                     continue;
1776                 }
1777                 /* create a new connection and link it */
1778                 httpd_ConnnectionNew( p_httpt, fd, &sock );
1779
1780             }
1781         }
1782         vlc_mutex_unlock( &p_httpt->host_lock );
1783
1784         vlc_mutex_lock( &p_httpt->file_lock );
1785         /* now do work for all connections */
1786         for( p_con = p_httpt->p_first_connection; p_con != NULL; )
1787         {
1788             if( p_con->i_state == HTTPD_CONNECTION_RECEIVING_REQUEST )
1789             {
1790                 int i_len;
1791                 /* read data */
1792                 i_len = recv( p_con->fd,
1793                               p_con->p_buffer + p_con->i_buffer,
1794                               p_con->i_buffer_size - p_con->i_buffer, 0 );
1795
1796
1797 #if defined( WIN32 ) || defined( UNDER_CE )
1798                 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1799 #else
1800                 if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1801 #endif
1802                 {
1803                     httpd_connection_t *p_next = p_con->p_next;
1804
1805                     httpd_ConnnectionClose( p_httpt, p_con );
1806                     p_con = p_next;
1807                 }
1808                 else if( i_len > 0 )
1809                 {
1810                     uint8_t *ptr;
1811                     p_con->i_last_activity_date = mdate();
1812                     p_con->i_buffer += i_len;
1813
1814                     ptr = p_con->p_buffer + p_con->i_buffer;
1815
1816                     if( ( p_con->i_buffer >= 2 && !strncmp( ptr - 2, "\n\n", 2 ) )||
1817                         ( p_con->i_buffer >= 4 && !strncmp( ptr - 4, "\r\n\r\n", 4 ) ) ||
1818                         p_con->i_buffer >= p_con->i_buffer_size )
1819                     {
1820                         p_con->p_buffer[__MIN( p_con->i_buffer, p_con->i_buffer_size - 1 )] = '\0';
1821                         httpd_ConnectionParseRequest( p_httpt, p_con );
1822                     }
1823
1824                     p_con = p_con->p_next;
1825                 }
1826                 else
1827                 {
1828                     p_con = p_con->p_next;
1829                 }
1830                 continue;   /* just for clarity */
1831             }
1832             else if( p_con->i_state == HTTPD_CONNECTION_SENDING_HEADER || p_con->i_state == HTTPD_CONNECTION_SENDING_FILE )
1833             {
1834                 int i_len;
1835
1836                 /* write data */
1837                 if( p_con->i_buffer_size - p_con->i_buffer > 0 )
1838                 {
1839                     i_len = send( p_con->fd, p_con->p_buffer + p_con->i_buffer, p_con->i_buffer_size - p_con->i_buffer, 0 );
1840                 }
1841                 else
1842                 {
1843                     i_len = 0;
1844                 }
1845 //                msg_Warn( p_httpt, "on %d send %d bytes %s", p_con->i_buffer_size, i_len, p_con->p_buffer + p_con->i_buffer );
1846
1847 #if defined( WIN32 ) || defined( UNDER_CE )
1848                 if( ( i_len < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) || ( i_len == 0 ) )
1849 #else
1850                 if( ( i_len < 0 && errno != EAGAIN && errno != EINTR ) || ( i_len == 0 ) )
1851 #endif
1852                 {
1853                     httpd_connection_t *p_next = p_con->p_next;
1854
1855                     httpd_ConnnectionClose( p_httpt, p_con );
1856                     p_con = p_next;
1857                 }
1858                 else if( i_len > 0 )
1859                 {
1860                     p_con->i_last_activity_date = mdate();
1861                     p_con->i_buffer += i_len;
1862
1863                     if( p_con->i_buffer >= p_con->i_buffer_size )
1864                     {
1865                         if( p_con->i_state == HTTPD_CONNECTION_SENDING_HEADER )
1866                         {
1867                             p_con->i_buffer_size = 0;
1868                             p_con->i_buffer = 0;
1869                             FREE( p_con->p_buffer );
1870
1871                             if( !p_con->p_file->b_stream )
1872                             {
1873                                 p_con->i_state = HTTPD_CONNECTION_SENDING_FILE; // be sure to out from HTTPD_CONNECTION_SENDING_HEADER
1874                                 if( p_con->i_method == HTTPD_CONNECTION_METHOD_GET )
1875                                 {
1876                                     p_con->p_file->pf_get( p_con->p_file->p_sys,
1877                                                            p_con->p_request, p_con->i_request_size,
1878                                                            &p_con->p_buffer, &p_con->i_buffer_size );
1879                                 }
1880                                 else if( p_con->i_method == HTTPD_CONNECTION_METHOD_POST )
1881                                 {
1882                                     p_con->p_file->pf_post( p_con->p_file->p_sys,
1883                                                             p_con->p_request, p_con->i_request_size,
1884                                                             &p_con->p_buffer, &p_con->i_buffer_size );
1885                                 }
1886                                 else
1887                                 {
1888                                     p_con->p_buffer = NULL;
1889                                     p_con->i_buffer_size = 0;
1890                                 }
1891                             }
1892                             else
1893                             {
1894                                 p_con->i_state = HTTPD_CONNECTION_SENDING_STREAM;
1895                                 p_con->i_stream_pos = p_con->p_file->i_buffer_last_pos;
1896                             }
1897                             p_con = p_con->p_next;
1898                         }
1899                         else
1900                         {
1901                             httpd_connection_t *p_next = p_con->p_next;
1902
1903                             httpd_ConnnectionClose( p_httpt, p_con );
1904                             p_con = p_next;
1905                         }
1906                     }
1907                     else
1908                     {
1909                         p_con = p_con->p_next;
1910                     }
1911                 }
1912                 else
1913                 {
1914                     p_con = p_con->p_next;
1915                 }
1916                 continue;   /* just for clarity */
1917             }
1918             else if( p_con->i_state == HTTPD_CONNECTION_SENDING_STREAM )
1919             {
1920                 httpd_stream_t *p_stream = p_con->p_file;
1921                 int i_send;
1922                 int i_write;
1923
1924                 if( p_con->i_stream_pos < p_stream->i_buffer_pos )
1925                 {
1926                     int i_pos;
1927                     /* check if this p_con aren't to late */
1928                     if( p_con->i_stream_pos + p_stream->i_buffer_size < p_stream->i_buffer_pos )
1929                     {
1930                         fprintf( stderr, "fixing i_stream_pos (old=%lld i_buffer_pos=%lld\n",
1931                                  p_con->i_stream_pos, p_stream->i_buffer_pos  );
1932                         p_con->i_stream_pos = p_stream->i_buffer_last_pos;
1933                     }
1934
1935                     i_pos = p_con->i_stream_pos % p_stream->i_buffer_size;
1936                     /* size until end of buffer */
1937                     i_write = p_stream->i_buffer_size - i_pos;
1938                     /* is it more than valid data */
1939                     if( i_write >= p_stream->i_buffer_pos - p_con->i_stream_pos )
1940                     {
1941                         i_write = p_stream->i_buffer_pos - p_con->i_stream_pos;
1942                     }
1943                     /* limit to HTTPD_STREAM_PACKET */
1944                     if( i_write > HTTPD_STREAM_PACKET )
1945                     {
1946                         i_write = HTTPD_STREAM_PACKET;
1947                     }
1948                     i_send = send( p_con->fd, &p_stream->p_buffer[i_pos], i_write, 0 );
1949
1950 #if defined( WIN32 ) || defined( UNDER_CE )
1951                     if( ( i_send < 0 && WSAGetLastError() != WSAEWOULDBLOCK )|| ( i_send == 0 ) )
1952 #else
1953                     if( ( i_send < 0 && errno != EAGAIN && errno != EINTR )|| ( i_send == 0 ) )
1954 #endif
1955                     {
1956                         httpd_connection_t *p_next = p_con->p_next;
1957
1958                         httpd_ConnnectionClose( p_httpt, p_con );
1959                         p_con = p_next;
1960                         continue;
1961                     }
1962                     else if( i_send > 0 )
1963                     {
1964                         p_con->i_last_activity_date = mdate();
1965                         p_con->i_stream_pos += i_send;
1966                     }
1967                 }
1968                 p_con = p_con->p_next;
1969                 continue;   /* just for clarity */
1970             }
1971             else if( p_con->i_state != HTTPD_CONNECTION_TO_BE_CLOSED )
1972             {
1973                 msg_Warn( p_httpt, "cannot occur (Invalid p_con->i_state)" );
1974                 p_con = p_con->p_next;
1975             }
1976         }   /* for over connection */
1977
1978         vlc_mutex_unlock( &p_httpt->file_lock );
1979     }
1980
1981     msg_Info( p_httpt, "httpd stopped" );
1982
1983     _UnregisterFile( p_httpt, p_page_401 );
1984     _UnregisterFile( p_httpt, p_page_404 );
1985 }