]> git.sesse.net Git - vlc/blob - modules/access/http.c
DShow: change text
[vlc] / modules / access / http.c
1 /*****************************************************************************
2  * http.c: HTTP input module
3  *****************************************************************************
4  * Copyright (C) 2001-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          RĂ©mi Denis-Courmont <rem # videolan.org>
10  *          Antoine Cellerier <dionoea at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36
37
38 #include <vlc_access.h>
39
40 #include <vlc_dialog.h>
41 #include <vlc_meta.h>
42 #include <vlc_network.h>
43 #include <vlc_url.h>
44 #include <vlc_tls.h>
45 #include <vlc_strings.h>
46 #include <vlc_charset.h>
47 #include <vlc_input.h>
48 #include <vlc_md5.h>
49 #include <vlc_http.h>
50
51 #ifdef HAVE_ZLIB_H
52 #   include <zlib.h>
53 #endif
54
55 #include <assert.h>
56 #include <limits.h>
57
58 #ifdef HAVE_LIBPROXY
59 #    include <proxy.h>
60 #endif
61
62 #ifdef WIN32
63 #   include <windows.h>
64 #endif
65
66 /*****************************************************************************
67  * Module descriptor
68  *****************************************************************************/
69 static int  Open ( vlc_object_t * );
70 static void Close( vlc_object_t * );
71
72 #define PROXY_TEXT N_("HTTP proxy")
73 #define PROXY_LONGTEXT N_( \
74     "HTTP proxy to be used It must be of the form " \
75     "http://[user@]myproxy.mydomain:myport/ ; " \
76     "if empty, the http_proxy environment variable will be tried." )
77
78 #define PROXY_PASS_TEXT N_("HTTP proxy password")
79 #define PROXY_PASS_LONGTEXT N_( \
80     "If your HTTP proxy requires a password, set it here." )
81
82 #define RECONNECT_TEXT N_("Auto re-connect")
83 #define RECONNECT_LONGTEXT N_( \
84     "Automatically try to reconnect to the stream in case of a sudden " \
85     "disconnect." )
86
87 #define CONTINUOUS_TEXT N_("Continuous stream")
88 #define CONTINUOUS_LONGTEXT N_("Read a file that is " \
89     "being constantly updated (for example, a JPG file on a server). " \
90     "You should not globally enable this option as it will break all other " \
91     "types of HTTP streams." )
92
93 #define FORWARD_COOKIES_TEXT N_("Forward Cookies")
94 #define FORWARD_COOKIES_LONGTEXT N_("Forward Cookies across http redirections.")
95
96 #define REFERER_TEXT N_("HTTP referer value")
97 #define REFERER_LONGTEXT N_("Customize the HTTP referer, simulating a previous document")
98
99 #define UA_TEXT N_("User Agent")
100 #define UA_LONGTEXT N_("The name and version of the program will be " \
101     "provided to the HTTP server. They must be separated by a forward " \
102     "slash, e.g. FooBar/1.2.3. This option can only be specified per input " \
103     "item, not globally.")
104
105 vlc_module_begin ()
106     set_description( N_("HTTP input") )
107     set_capability( "access", 0 )
108     set_shortname( N_( "HTTP(S)" ) )
109     set_category( CAT_INPUT )
110     set_subcategory( SUBCAT_INPUT_ACCESS )
111
112     add_string( "http-proxy", NULL, PROXY_TEXT, PROXY_LONGTEXT,
113                 false )
114     add_password( "http-proxy-pwd", NULL,
115                   PROXY_PASS_TEXT, PROXY_PASS_LONGTEXT, false )
116     add_obsolete_bool( "http-use-IE-proxy" )
117     add_string( "http-referrer", NULL, REFERER_TEXT, REFERER_LONGTEXT, false )
118         change_safe()
119     add_string( "http-user-agent", NULL, UA_TEXT, UA_LONGTEXT, false )
120         change_safe()
121         change_private()
122     add_bool( "http-reconnect", false, RECONNECT_TEXT,
123               RECONNECT_LONGTEXT, true )
124     add_bool( "http-continuous", false, CONTINUOUS_TEXT,
125               CONTINUOUS_LONGTEXT, true )
126         change_safe()
127     add_bool( "http-forward-cookies", true, FORWARD_COOKIES_TEXT,
128               FORWARD_COOKIES_LONGTEXT, true )
129     /* 'itpc' = iTunes Podcast */
130     add_shortcut( "http", "https", "unsv", "itpc", "icyx" )
131     set_callbacks( Open, Close )
132 vlc_module_end ()
133
134 /*****************************************************************************
135  * Local prototypes
136  *****************************************************************************/
137
138 struct access_sys_t
139 {
140     int fd;
141     bool b_error;
142     vlc_tls_creds_t *p_creds;
143     vlc_tls_t *p_tls;
144     v_socket_t *p_vs;
145
146     /* From uri */
147     vlc_url_t url;
148     char    *psz_user_agent;
149     char    *psz_referrer;
150     http_auth_t auth;
151
152     /* Proxy */
153     bool b_proxy;
154     vlc_url_t  proxy;
155     http_auth_t proxy_auth;
156     char       *psz_proxy_passbuf;
157
158     /* */
159     int        i_code;
160     const char *psz_protocol;
161     int        i_version;
162
163     char       *psz_mime;
164     char       *psz_pragma;
165     char       *psz_location;
166     bool b_mms;
167     bool b_icecast;
168 #ifdef HAVE_ZLIB_H
169     bool b_compressed;
170     struct
171     {
172         z_stream   stream;
173         uint8_t   *p_buffer;
174     } inflate;
175 #endif
176
177     bool b_chunked;
178     int64_t    i_chunk;
179
180     int        i_icy_meta;
181     uint64_t   i_icy_offset;
182     char       *psz_icy_name;
183     char       *psz_icy_genre;
184     char       *psz_icy_title;
185
186     uint64_t i_remaining;
187
188     bool b_seekable;
189     bool b_reconnect;
190     bool b_continuous;
191     bool b_pace_control;
192     bool b_persist;
193     bool b_has_size;
194
195     vlc_array_t * cookies;
196 };
197
198 /* */
199 static int OpenWithCookies( vlc_object_t *p_this, const char *psz_access,
200                             unsigned i_redirect, vlc_array_t *cookies );
201
202 /* */
203 static ssize_t Read( access_t *, uint8_t *, size_t );
204 static ssize_t ReadCompressed( access_t *, uint8_t *, size_t );
205 static int Seek( access_t *, uint64_t );
206 static int Control( access_t *, int, va_list );
207
208 /* */
209 static int Connect( access_t *, uint64_t );
210 static int Request( access_t *p_access, uint64_t i_tell );
211 static void Disconnect( access_t * );
212
213 /* Small Cookie utilities. Cookies support is partial. */
214 static char * cookie_get_content( const char * cookie );
215 static char * cookie_get_domain( const char * cookie );
216 static char * cookie_get_name( const char * cookie );
217 static void cookie_append( vlc_array_t * cookies, char * cookie );
218
219
220 static void AuthReply( access_t *p_acces, const char *psz_prefix,
221                        vlc_url_t *p_url, http_auth_t *p_auth );
222 static int AuthCheckReply( access_t *p_access, const char *psz_header,
223                            vlc_url_t *p_url, http_auth_t *p_auth );
224
225 /*****************************************************************************
226  * Open:
227  *****************************************************************************/
228 static int Open( vlc_object_t *p_this )
229 {
230     access_t *p_access = (access_t*)p_this;
231     return OpenWithCookies( p_this, p_access->psz_access, 5, NULL );
232 }
233
234 /**
235  * Open the given url using the given cookies
236  * @param p_this: the vlc object
237  * @psz_access: the acces to use (http, https, ...) (this value must be used
238  *              instead of p_access->psz_access)
239  * @i_redirect: number of redirections remaining
240  * @cookies: the available cookies
241  * @return vlc error codes
242  */
243 static int OpenWithCookies( vlc_object_t *p_this, const char *psz_access,
244                             unsigned i_redirect, vlc_array_t *cookies )
245 {
246     access_t     *p_access = (access_t*)p_this;
247     access_sys_t *p_sys;
248     char         *psz, *p;
249
250     /* Only forward an store cookies if the corresponding option is activated */
251     bool   b_forward_cookies = var_InheritBool( p_access, "http-forward-cookies" );
252     vlc_array_t * saved_cookies = b_forward_cookies ? (cookies ? cookies : vlc_array_new()) : NULL;
253
254     /* Set up p_access */
255     STANDARD_READ_ACCESS_INIT;
256 #ifdef HAVE_ZLIB_H
257     p_access->pf_read = ReadCompressed;
258 #endif
259     p_sys->fd = -1;
260     p_sys->b_proxy = false;
261     p_sys->psz_proxy_passbuf = NULL;
262     p_sys->i_version = 1;
263     p_sys->b_seekable = true;
264     p_sys->psz_mime = NULL;
265     p_sys->psz_pragma = NULL;
266     p_sys->b_mms = false;
267     p_sys->b_icecast = false;
268     p_sys->psz_location = NULL;
269     p_sys->psz_user_agent = NULL;
270     p_sys->psz_referrer = NULL;
271     p_sys->b_pace_control = true;
272 #ifdef HAVE_ZLIB_H
273     p_sys->b_compressed = false;
274     /* 15 is the max windowBits, +32 to enable optional gzip decoding */
275     if( inflateInit2( &p_sys->inflate.stream, 32+15 ) != Z_OK )
276         msg_Warn( p_access, "Error during zlib initialisation: %s",
277                   p_sys->inflate.stream.msg );
278     if( zlibCompileFlags() & (1<<17) )
279         msg_Warn( p_access, "Your zlib was compiled without gzip support." );
280     p_sys->inflate.p_buffer = NULL;
281 #endif
282     p_sys->p_tls = NULL;
283     p_sys->p_vs = NULL;
284     p_sys->i_icy_meta = 0;
285     p_sys->i_icy_offset = 0;
286     p_sys->psz_icy_name = NULL;
287     p_sys->psz_icy_genre = NULL;
288     p_sys->psz_icy_title = NULL;
289     p_sys->i_remaining = 0;
290     p_sys->b_persist = false;
291     p_sys->b_has_size = false;
292     p_access->info.i_size = 0;
293     p_access->info.i_pos  = 0;
294     p_access->info.b_eof  = false;
295
296     p_sys->cookies = saved_cookies;
297
298     http_auth_Init( &p_sys->auth );
299     http_auth_Init( &p_sys->proxy_auth );
300
301     /* Parse URI - remove spaces */
302     p = psz = strdup( p_access->psz_location );
303     while( (p = strchr( p, ' ' )) != NULL )
304         *p = '+';
305     vlc_UrlParse( &p_sys->url, psz, 0 );
306     free( psz );
307
308     if( p_sys->url.psz_host == NULL || *p_sys->url.psz_host == '\0' )
309     {
310         msg_Warn( p_access, "invalid host" );
311         goto error;
312     }
313     if( !strncmp( psz_access, "https", 5 ) )
314     {
315         /* HTTP over SSL */
316         p_sys->p_creds = vlc_tls_ClientCreate( p_this );
317         if( p_sys->p_creds == NULL )
318             goto error;
319         if( p_sys->url.i_port <= 0 )
320             p_sys->url.i_port = 443;
321     }
322     else
323     {
324         if( p_sys->url.i_port <= 0 )
325             p_sys->url.i_port = 80;
326     }
327
328     /* Determine the HTTP user agent */
329     /* See RFC2616 Â§2.2 token and comment definition, and Â§3.8 and
330      * Â§14.43 user-agent header */
331     p_sys->psz_user_agent = var_InheritString( p_access, "http-user-agent" );
332     if (p_sys->psz_user_agent)
333     {
334         unsigned comment_level = 0;
335         for( char *p = p_sys->psz_user_agent; *p; p++ )
336         {
337             uint8_t c = *p;
338             if (comment_level == 0)
339             {
340                 if( c < 32 || strchr( ")<>@,;:\\\"[]?={}", c ) )
341                     *p = '_'; /* remove potentially harmful characters */
342             }
343             else
344             {
345                 if (c == ')')
346                     comment_level--;
347                 else if( c < 32 && strchr( "\t\r\n", c ) == NULL)
348                     *p = '_'; /* remove potentially harmful characters */
349             }
350             if (c == '(')
351             {
352                 if (comment_level == UINT_MAX)
353                     break;
354                 comment_level++;
355             }
356         }
357         /* truncate evil unclosed comments */
358         if (comment_level > 0)
359         {
360             char *p = strchr(p_sys->psz_user_agent, '(');
361             *p = '\0';
362         }
363     }
364
365     /* HTTP referrer */
366     p_sys->psz_referrer = var_InheritString( p_access, "http-referrer" );
367
368     /* Check proxy */
369     psz = var_InheritString( p_access, "http-proxy" );
370     if( psz )
371     {
372         p_sys->b_proxy = true;
373         vlc_UrlParse( &p_sys->proxy, psz, 0 );
374         free( psz );
375     }
376 #ifdef HAVE_LIBPROXY
377     else
378     {
379         pxProxyFactory *pf = px_proxy_factory_new();
380         if (pf)
381         {
382             char *buf;
383             int i;
384             i=asprintf(&buf, "%s://%s", psz_access, p_access->psz_location);
385             if (i >= 0)
386             {
387                 msg_Dbg(p_access, "asking libproxy about url '%s'", buf);
388                 char **proxies = px_proxy_factory_get_proxies(pf, buf);
389                 if (proxies[0])
390                 {
391                     msg_Dbg(p_access, "libproxy suggest to use '%s'", proxies[0]);
392                     if(strcmp(proxies[0],"direct://") != 0)
393                     {
394                         p_sys->b_proxy = true;
395                         vlc_UrlParse( &p_sys->proxy, proxies[0], 0);
396                     }
397                 }
398                 for(i=0;proxies[i];i++) free(proxies[i]);
399                 free(proxies);
400                 free(buf);
401             }
402             px_proxy_factory_free(pf);
403         }
404         else
405         {
406             msg_Err(p_access, "Allocating memory for libproxy failed");
407         }
408     }
409 #elif (0) // defined( WIN32 ) The parsing is not complete enough
410     else
411     {
412         /* Try to get the proxy server address from Windows internet settings using registry. */
413         HKEY h_key;
414         /* Open the key */
415         if( RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft"
416                           "\\Windows\\CurrentVersion\\Internet Settings",
417                           0, KEY_READ, &h_key ) == ERROR_SUCCESS )
418         {
419             DWORD len = sizeof( DWORD );
420             BYTE proxyEnable;
421
422             /* Get the proxy enable value */
423             if( RegQueryValueEx( h_key, "ProxyEnable", NULL, NULL,
424                                  &proxyEnable, &len ) == ERROR_SUCCESS
425              && proxyEnable )
426             {
427                 /* Proxy is enabled */
428                 /* Get the proxy URL :
429                    Proxy server value in the registry can be something like "address:port"
430                    or "ftp=address1:port1;http=address2:port2 ..." depending of the
431                    confirguration. */
432                 unsigned char key[256];
433
434                 len = sizeof( key );
435                 if( RegQueryValueEx( h_key, "ProxyServer", NULL, NULL,
436                                      key, &len ) == ERROR_SUCCESS )
437                 {
438                     /* FIXME: This is lame. The string should be tokenized. */
439 #warning FIXME.
440                     char *psz_proxy = strstr( (char *)key, "http=" );
441                     if( psz_proxy != NULL )
442                     {
443                         psz_proxy += 5;
444                         char *end = strchr( psz_proxy, ';' );
445                         if( end != NULL )
446                             *end = '\0';
447                     }
448                     else
449                         psz_proxy = (char *)key;
450                     /* Set proxy enable for this connection. */
451                     p_sys->b_proxy = true;
452                     vlc_UrlParse( &p_sys->proxy, psz_proxy, 0 );
453                 }
454             }
455             else
456                 msg_Dbg( p_access, "HTTP proxy disabled (MSIE)" );
457             RegCloseKey( h_key );
458         }
459     }
460 #else
461     else
462     {
463         psz = getenv( "http_proxy" );
464         if( psz )
465         {
466             p_sys->b_proxy = true;
467             vlc_UrlParse( &p_sys->proxy, psz, 0 );
468         }
469     }
470 #endif
471
472     if( psz ) /* No, this is NOT a use-after-free error */
473     {
474         psz = var_InheritString( p_access, "http-proxy-pwd" );
475         if( psz )
476             p_sys->proxy.psz_password = p_sys->psz_proxy_passbuf = psz;
477     }
478
479     if( p_sys->b_proxy )
480     {
481         if( p_sys->proxy.psz_host == NULL || *p_sys->proxy.psz_host == '\0' )
482         {
483             msg_Warn( p_access, "invalid proxy host" );
484             goto error;
485         }
486         if( p_sys->proxy.i_port <= 0 )
487         {
488             p_sys->proxy.i_port = 80;
489         }
490     }
491
492     msg_Dbg( p_access, "http: server='%s' port=%d file='%s'",
493              p_sys->url.psz_host, p_sys->url.i_port,
494              p_sys->url.psz_path != NULL ? p_sys->url.psz_path : "" );
495     if( p_sys->b_proxy )
496     {
497         msg_Dbg( p_access, "      proxy %s:%d", p_sys->proxy.psz_host,
498                  p_sys->proxy.i_port );
499     }
500     if( p_sys->url.psz_username && *p_sys->url.psz_username )
501     {
502         msg_Dbg( p_access, "      user='%s'", p_sys->url.psz_username );
503     }
504
505     p_sys->b_reconnect = var_InheritBool( p_access, "http-reconnect" );
506     p_sys->b_continuous = var_InheritBool( p_access, "http-continuous" );
507
508 connect:
509     /* Connect */
510     switch( Connect( p_access, 0 ) )
511     {
512         case -1:
513             goto error;
514
515         case -2:
516             /* Retry with http 1.0 */
517             msg_Dbg( p_access, "switching to HTTP version 1.0" );
518             p_sys->i_version = 0;
519             p_sys->b_seekable = false;
520
521             if( !vlc_object_alive (p_access) || Connect( p_access, 0 ) )
522                 goto error;
523
524         case 0:
525             break;
526
527         default:
528             assert(0);
529     }
530
531     if( p_sys->i_code == 401 )
532     {
533         char *psz_login, *psz_password;
534         /* FIXME ? */
535         if( p_sys->url.psz_username && p_sys->url.psz_password &&
536             p_sys->auth.psz_nonce && p_sys->auth.i_nonce == 0 )
537         {
538             Disconnect( p_access );
539             goto connect;
540         }
541         msg_Dbg( p_access, "authentication failed for realm %s",
542                  p_sys->auth.psz_realm );
543         dialog_Login( p_access, &psz_login, &psz_password,
544                       _("HTTP authentication"),
545              _("Please enter a valid login name and a password for realm %s."),
546                       p_sys->auth.psz_realm );
547         if( psz_login != NULL && psz_password != NULL )
548         {
549             msg_Dbg( p_access, "retrying with user=%s", psz_login );
550             p_sys->url.psz_username = psz_login;
551             p_sys->url.psz_password = psz_password;
552             Disconnect( p_access );
553             goto connect;
554         }
555         else
556         {
557             free( psz_login );
558             free( psz_password );
559             goto error;
560         }
561     }
562
563     if( ( p_sys->i_code == 301 || p_sys->i_code == 302 ||
564           p_sys->i_code == 303 || p_sys->i_code == 307 ) &&
565         p_sys->psz_location && *p_sys->psz_location )
566     {
567         msg_Dbg( p_access, "redirection to %s", p_sys->psz_location );
568
569         /* Check the number of redirection already done */
570         if( i_redirect == 0 )
571         {
572             msg_Err( p_access, "Too many redirection: break potential infinite"
573                      "loop" );
574             goto error;
575         }
576
577         const char *psz_protocol;
578         if( !strncmp( p_sys->psz_location, "http://", 7 ) )
579             psz_protocol = "http";
580         else if( !strncmp( p_sys->psz_location, "https://", 8 ) )
581             psz_protocol = "https";
582         else
583         {   /* Do not accept redirection outside of HTTP */
584             msg_Err( p_access, "unsupported redirection ignored" );
585             goto error;
586         }
587         free( p_access->psz_location );
588         p_access->psz_location = strdup( p_sys->psz_location
589                                        + strlen( psz_protocol ) + 3 );
590         /* Clean up current Open() run */
591         vlc_UrlClean( &p_sys->url );
592         http_auth_Reset( &p_sys->auth );
593         vlc_UrlClean( &p_sys->proxy );
594         free( p_sys->psz_proxy_passbuf );
595         http_auth_Reset( &p_sys->proxy_auth );
596         free( p_sys->psz_mime );
597         free( p_sys->psz_pragma );
598         free( p_sys->psz_location );
599         free( p_sys->psz_user_agent );
600         free( p_sys->psz_referrer );
601
602         Disconnect( p_access );
603         vlc_tls_Delete( p_sys->p_creds );
604         cookies = p_sys->cookies;
605 #ifdef HAVE_ZLIB_H
606         inflateEnd( &p_sys->inflate.stream );
607 #endif
608         free( p_sys );
609
610         /* Do new Open() run with new data */
611         return OpenWithCookies( p_this, psz_protocol, i_redirect - 1,
612                                 cookies );
613     }
614
615     if( p_sys->b_mms )
616     {
617         msg_Dbg( p_access, "this is actually a live mms server, BAIL" );
618         goto error;
619     }
620
621     if( !strcmp( p_sys->psz_protocol, "ICY" ) || p_sys->b_icecast )
622     {
623         if( p_sys->psz_mime && strcasecmp( p_sys->psz_mime, "application/ogg" ) )
624         {
625             if( !strcasecmp( p_sys->psz_mime, "video/nsv" ) ||
626                 !strcasecmp( p_sys->psz_mime, "video/nsa" ) )
627             {
628                 free( p_access->psz_demux );
629                 p_access->psz_demux = strdup( "nsv" );
630             }
631             else if( !strcasecmp( p_sys->psz_mime, "audio/aac" ) ||
632                      !strcasecmp( p_sys->psz_mime, "audio/aacp" ) )
633             {
634                 free( p_access->psz_demux );
635                 p_access->psz_demux = strdup( "m4a" );
636             }
637             else if( !strcasecmp( p_sys->psz_mime, "audio/mpeg" ) )
638             {
639                 free( p_access->psz_demux );
640                 p_access->psz_demux = strdup( "mp3" );
641             }
642
643             msg_Info( p_access, "Raw-audio server found, %s demuxer selected",
644                       p_access->psz_demux );
645
646 #if 0       /* Doesn't work really well because of the pre-buffering in
647              * shoutcast servers (the buffer content will be sent as fast as
648              * possible). */
649             p_sys->b_pace_control = false;
650 #endif
651         }
652         else if( !p_sys->psz_mime )
653         {
654             free( p_access->psz_demux );
655             /* Shoutcast */
656             p_access->psz_demux = strdup( "mp3" );
657         }
658         /* else probably Ogg Vorbis */
659     }
660     else if( !strcasecmp( psz_access, "unsv" ) &&
661              p_sys->psz_mime &&
662              !strcasecmp( p_sys->psz_mime, "misc/ultravox" ) )
663     {
664         free( p_access->psz_demux );
665         /* Grrrr! detect ultravox server and force NSV demuxer */
666         p_access->psz_demux = strdup( "nsv" );
667     }
668     else if( !strcmp( psz_access, "itpc" ) )
669     {
670         free( p_access->psz_demux );
671         p_access->psz_demux = strdup( "podcast" );
672     }
673     else if( p_sys->psz_mime &&
674              !strncasecmp( p_sys->psz_mime, "application/xspf+xml", 20 ) &&
675              ( memchr( " ;\t", p_sys->psz_mime[20], 4 ) != NULL ) )
676     {
677         free( p_access->psz_demux );
678         p_access->psz_demux = strdup( "xspf-open" );
679     }
680
681     if( p_sys->b_reconnect ) msg_Dbg( p_access, "auto re-connect enabled" );
682
683     return VLC_SUCCESS;
684
685 error:
686     vlc_UrlClean( &p_sys->url );
687     vlc_UrlClean( &p_sys->proxy );
688     free( p_sys->psz_proxy_passbuf );
689     free( p_sys->psz_mime );
690     free( p_sys->psz_pragma );
691     free( p_sys->psz_location );
692     free( p_sys->psz_user_agent );
693     free( p_sys->psz_referrer );
694
695     Disconnect( p_access );
696     vlc_tls_Delete( p_sys->p_creds );
697
698     if( p_sys->cookies )
699     {
700         int i;
701         for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
702             free(vlc_array_item_at_index( p_sys->cookies, i ));
703         vlc_array_destroy( p_sys->cookies );
704     }
705
706 #ifdef HAVE_ZLIB_H
707     inflateEnd( &p_sys->inflate.stream );
708 #endif
709     free( p_sys );
710     return VLC_EGENERIC;
711 }
712
713 /*****************************************************************************
714  * Close:
715  *****************************************************************************/
716 static void Close( vlc_object_t *p_this )
717 {
718     access_t     *p_access = (access_t*)p_this;
719     access_sys_t *p_sys = p_access->p_sys;
720
721     vlc_UrlClean( &p_sys->url );
722     http_auth_Reset( &p_sys->auth );
723     vlc_UrlClean( &p_sys->proxy );
724     http_auth_Reset( &p_sys->proxy_auth );
725
726     free( p_sys->psz_mime );
727     free( p_sys->psz_pragma );
728     free( p_sys->psz_location );
729
730     free( p_sys->psz_icy_name );
731     free( p_sys->psz_icy_genre );
732     free( p_sys->psz_icy_title );
733
734     free( p_sys->psz_user_agent );
735     free( p_sys->psz_referrer );
736
737     Disconnect( p_access );
738     vlc_tls_Delete( p_sys->p_creds );
739
740     if( p_sys->cookies )
741     {
742         int i;
743         for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
744             free(vlc_array_item_at_index( p_sys->cookies, i ));
745         vlc_array_destroy( p_sys->cookies );
746     }
747
748 #ifdef HAVE_ZLIB_H
749     inflateEnd( &p_sys->inflate.stream );
750     free( p_sys->inflate.p_buffer );
751 #endif
752
753     free( p_sys );
754 }
755
756 /* Read data from the socket taking care of chunked transfer if needed */
757 static int ReadData( access_t *p_access, int *pi_read,
758                      uint8_t *p_buffer, size_t i_len )
759 {
760     access_sys_t *p_sys = p_access->p_sys;
761     if( p_sys->b_chunked )
762     {
763         if( p_sys->i_chunk < 0 )
764             return VLC_EGENERIC;
765
766         if( p_sys->i_chunk <= 0 )
767         {
768             char *psz = net_Gets( p_access, p_sys->fd, p_sys->p_vs );
769             /* read the chunk header */
770             if( psz == NULL )
771             {
772                 /* fatal error - end of file */
773                 msg_Dbg( p_access, "failed reading chunk-header line" );
774                 return VLC_EGENERIC;
775             }
776             p_sys->i_chunk = strtoll( psz, NULL, 16 );
777             free( psz );
778
779             if( p_sys->i_chunk <= 0 )   /* eof */
780             {
781                 p_sys->i_chunk = -1;
782                 return VLC_EGENERIC;
783             }
784         }
785
786         if( i_len > p_sys->i_chunk )
787             i_len = p_sys->i_chunk;
788     }
789     *pi_read = net_Read( p_access, p_sys->fd, p_sys->p_vs, p_buffer, i_len, false );
790     if( *pi_read <= 0 )
791         return VLC_SUCCESS;
792
793     if( p_sys->b_chunked )
794     {
795         p_sys->i_chunk -= *pi_read;
796         if( p_sys->i_chunk <= 0 )
797         {
798             /* read the empty line */
799             char *psz = net_Gets( p_access, p_sys->fd, p_sys->p_vs );
800             free( psz );
801         }
802     }
803     return VLC_SUCCESS;
804 }
805
806 /*****************************************************************************
807  * Read: Read up to i_len bytes from the http connection and place in
808  * p_buffer. Return the actual number of bytes read
809  *****************************************************************************/
810 static int ReadICYMeta( access_t *p_access );
811 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
812 {
813     access_sys_t *p_sys = p_access->p_sys;
814     int i_read;
815
816     if( p_sys->fd == -1 )
817         goto fatal;
818
819     if( p_sys->b_has_size )
820     {
821         /* Remaining bytes in the file */
822         uint64_t remainder = p_access->info.i_size - p_access->info.i_pos;
823         if( remainder < i_len )
824             i_len = remainder;
825
826         /* Remaining bytes in the response */
827         if( p_sys->i_remaining < i_len )
828             i_len = p_sys->i_remaining;
829     }
830     if( i_len == 0 )
831         goto fatal;
832
833     if( p_sys->i_icy_meta > 0 && p_access->info.i_pos - p_sys->i_icy_offset > 0 )
834     {
835         int64_t i_next = p_sys->i_icy_meta -
836                                     (p_access->info.i_pos - p_sys->i_icy_offset ) % p_sys->i_icy_meta;
837
838         if( i_next == p_sys->i_icy_meta )
839         {
840             if( ReadICYMeta( p_access ) )
841                 goto fatal;
842         }
843         if( i_len > i_next )
844             i_len = i_next;
845     }
846
847     if( ReadData( p_access, &i_read, p_buffer, i_len ) )
848         goto fatal;
849
850     if( i_read <= 0 )
851     {
852         /*
853          * I very much doubt that this will work.
854          * If i_read == 0, the connection *IS* dead, so the only
855          * sensible thing to do is Disconnect() and then retry.
856          * Otherwise, I got recv() completely wrong. -- Courmisch
857          */
858         if( p_sys->b_continuous )
859         {
860             Request( p_access, 0 );
861             p_sys->b_continuous = false;
862             i_read = Read( p_access, p_buffer, i_len );
863             p_sys->b_continuous = true;
864         }
865         Disconnect( p_access );
866         if( p_sys->b_reconnect && vlc_object_alive( p_access ) )
867         {
868             msg_Dbg( p_access, "got disconnected, trying to reconnect" );
869             if( Connect( p_access, p_access->info.i_pos ) )
870             {
871                 msg_Dbg( p_access, "reconnection failed" );
872             }
873             else
874             {
875                 p_sys->b_reconnect = false;
876                 i_read = Read( p_access, p_buffer, i_len );
877                 p_sys->b_reconnect = true;
878
879                 return i_read;
880             }
881         }
882
883         if( i_read <= 0 )
884         {
885             if( i_read < 0 )
886                 p_sys->b_error = true;
887             goto fatal;
888         }
889     }
890
891     assert( i_read >= 0 );
892     p_access->info.i_pos += i_read;
893     if( p_sys->b_has_size )
894     {
895         assert( p_access->info.i_pos <= p_access->info.i_size );
896         assert( (unsigned)i_read <= p_sys->i_remaining );
897         p_sys->i_remaining -= i_read;
898     }
899
900     return i_read;
901
902 fatal:
903     p_access->info.b_eof = true;
904     return 0;
905 }
906
907 static int ReadICYMeta( access_t *p_access )
908 {
909     access_sys_t *p_sys = p_access->p_sys;
910
911     uint8_t buffer;
912     char *p, *psz_meta;
913     int i_read;
914
915     /* Read meta data length */
916     if( ReadData( p_access, &i_read, &buffer, 1 ) )
917         return VLC_EGENERIC;
918     if( i_read != 1 )
919         return VLC_EGENERIC;
920     const int i_size = buffer << 4;
921     /* msg_Dbg( p_access, "ICY meta size=%u", i_size); */
922
923     psz_meta = malloc( i_size + 1 );
924     for( i_read = 0; i_read < i_size; )
925     {
926         int i_tmp;
927         if( ReadData( p_access, &i_tmp, (uint8_t *)&psz_meta[i_read], i_size - i_read ) || i_tmp <= 0 )
928         {
929             free( psz_meta );
930             return VLC_EGENERIC;
931         }
932         i_read += i_tmp;
933     }
934     psz_meta[i_read] = '\0'; /* Just in case */
935
936     /* msg_Dbg( p_access, "icy-meta=%s", psz_meta ); */
937
938     /* Now parse the meta */
939     /* Look for StreamTitle= */
940     p = strcasestr( (char *)psz_meta, "StreamTitle=" );
941     if( p )
942     {
943         p += strlen( "StreamTitle=" );
944         if( *p == '\'' || *p == '"' )
945         {
946             char closing[] = { p[0], ';', '\0' };
947             char *psz = strstr( &p[1], closing );
948             if( !psz )
949                 psz = strchr( &p[1], ';' );
950
951             if( psz ) *psz = '\0';
952         }
953         else
954         {
955             char *psz = strchr( &p[1], ';' );
956             if( psz ) *psz = '\0';
957         }
958
959         if( !p_sys->psz_icy_title ||
960             strcmp( p_sys->psz_icy_title, &p[1] ) )
961         {
962             free( p_sys->psz_icy_title );
963             char *psz_tmp = strdup( &p[1] );
964             p_sys->psz_icy_title = EnsureUTF8( psz_tmp );
965             if( !p_sys->psz_icy_title )
966                 free( psz_tmp );
967             p_access->info.i_update |= INPUT_UPDATE_META;
968
969             msg_Dbg( p_access, "New Title=%s", p_sys->psz_icy_title );
970         }
971     }
972     free( psz_meta );
973
974     return VLC_SUCCESS;
975 }
976
977 #ifdef HAVE_ZLIB_H
978 static ssize_t ReadCompressed( access_t *p_access, uint8_t *p_buffer,
979                                size_t i_len )
980 {
981     access_sys_t *p_sys = p_access->p_sys;
982
983     if( p_sys->b_compressed )
984     {
985         int i_ret;
986
987         if( !p_sys->inflate.p_buffer )
988             p_sys->inflate.p_buffer = malloc( 256 * 1024 );
989
990         if( p_sys->inflate.stream.avail_in == 0 )
991         {
992             ssize_t i_read = Read( p_access, p_sys->inflate.p_buffer, 256 * 1024 );
993             if( i_read <= 0 ) return i_read;
994             p_sys->inflate.stream.next_in = p_sys->inflate.p_buffer;
995             p_sys->inflate.stream.avail_in = i_read;
996         }
997
998         p_sys->inflate.stream.avail_out = i_len;
999         p_sys->inflate.stream.next_out = p_buffer;
1000
1001         i_ret = inflate( &p_sys->inflate.stream, Z_SYNC_FLUSH );
1002         msg_Warn( p_access, "inflate return value: %d, %s", i_ret, p_sys->inflate.stream.msg );
1003
1004         return i_len - p_sys->inflate.stream.avail_out;
1005     }
1006     else
1007     {
1008         return Read( p_access, p_buffer, i_len );
1009     }
1010 }
1011 #endif
1012
1013 /*****************************************************************************
1014  * Seek: close and re-open a connection at the right place
1015  *****************************************************************************/
1016 static int Seek( access_t *p_access, uint64_t i_pos )
1017 {
1018     msg_Dbg( p_access, "trying to seek to %"PRId64, i_pos );
1019
1020     Disconnect( p_access );
1021
1022     if( p_access->info.i_size
1023      && i_pos >= p_access->info.i_size ) {
1024         msg_Err( p_access, "seek to far" );
1025         int retval = Seek( p_access, p_access->info.i_size - 1 );
1026         if( retval == VLC_SUCCESS ) {
1027             uint8_t p_buffer[2];
1028             Read( p_access, p_buffer, 1);
1029             p_access->info.b_eof  = false;
1030         }
1031         return retval;
1032     }
1033     if( Connect( p_access, i_pos ) )
1034     {
1035         msg_Err( p_access, "seek failed" );
1036         p_access->info.b_eof = true;
1037         return VLC_EGENERIC;
1038     }
1039     return VLC_SUCCESS;
1040 }
1041
1042 /*****************************************************************************
1043  * Control:
1044  *****************************************************************************/
1045 static int Control( access_t *p_access, int i_query, va_list args )
1046 {
1047     access_sys_t *p_sys = p_access->p_sys;
1048     bool       *pb_bool;
1049     int64_t    *pi_64;
1050     vlc_meta_t *p_meta;
1051
1052     switch( i_query )
1053     {
1054         /* */
1055         case ACCESS_CAN_SEEK:
1056             pb_bool = (bool*)va_arg( args, bool* );
1057             *pb_bool = p_sys->b_seekable;
1058             break;
1059         case ACCESS_CAN_FASTSEEK:
1060             pb_bool = (bool*)va_arg( args, bool* );
1061             *pb_bool = false;
1062             break;
1063         case ACCESS_CAN_PAUSE:
1064         case ACCESS_CAN_CONTROL_PACE:
1065             pb_bool = (bool*)va_arg( args, bool* );
1066
1067 #if 0       /* Disable for now until we have a clock synchro algo
1068              * which works with something else than MPEG over UDP */
1069             *pb_bool = p_sys->b_pace_control;
1070 #endif
1071             *pb_bool = true;
1072             break;
1073
1074         /* */
1075         case ACCESS_GET_PTS_DELAY:
1076             pi_64 = (int64_t*)va_arg( args, int64_t * );
1077             *pi_64 = INT64_C(1000)
1078                 * var_InheritInteger( p_access, "network-caching" );
1079             break;
1080
1081         /* */
1082         case ACCESS_SET_PAUSE_STATE:
1083             break;
1084
1085         case ACCESS_GET_META:
1086             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1087
1088             if( p_sys->psz_icy_name )
1089                 vlc_meta_Set( p_meta, vlc_meta_Title, p_sys->psz_icy_name );
1090             if( p_sys->psz_icy_genre )
1091                 vlc_meta_Set( p_meta, vlc_meta_Genre, p_sys->psz_icy_genre );
1092             if( p_sys->psz_icy_title )
1093                 vlc_meta_Set( p_meta, vlc_meta_NowPlaying, p_sys->psz_icy_title );
1094             break;
1095
1096         case ACCESS_GET_CONTENT_TYPE:
1097             *va_arg( args, char ** ) =
1098                 p_sys->psz_mime ? strdup( p_sys->psz_mime ) : NULL;
1099             break;
1100
1101         case ACCESS_GET_TITLE_INFO:
1102         case ACCESS_SET_TITLE:
1103         case ACCESS_SET_SEEKPOINT:
1104         case ACCESS_SET_PRIVATE_ID_STATE:
1105             return VLC_EGENERIC;
1106
1107         default:
1108             msg_Warn( p_access, "unimplemented query in control" );
1109             return VLC_EGENERIC;
1110
1111     }
1112     return VLC_SUCCESS;
1113 }
1114
1115 /*****************************************************************************
1116  * Connect:
1117  *****************************************************************************/
1118 static int Connect( access_t *p_access, uint64_t i_tell )
1119 {
1120     access_sys_t   *p_sys = p_access->p_sys;
1121     vlc_url_t      srv = p_sys->b_proxy ? p_sys->proxy : p_sys->url;
1122
1123     /* Clean info */
1124     free( p_sys->psz_location );
1125     free( p_sys->psz_mime );
1126     free( p_sys->psz_pragma );
1127
1128     free( p_sys->psz_icy_genre );
1129     free( p_sys->psz_icy_name );
1130     free( p_sys->psz_icy_title );
1131
1132
1133     p_sys->psz_location = NULL;
1134     p_sys->psz_mime = NULL;
1135     p_sys->psz_pragma = NULL;
1136     p_sys->b_mms = false;
1137     p_sys->b_chunked = false;
1138     p_sys->i_chunk = 0;
1139     p_sys->i_icy_meta = 0;
1140     p_sys->i_icy_offset = i_tell;
1141     p_sys->psz_icy_name = NULL;
1142     p_sys->psz_icy_genre = NULL;
1143     p_sys->psz_icy_title = NULL;
1144     p_sys->i_remaining = 0;
1145     p_sys->b_persist = false;
1146     p_sys->b_has_size = false;
1147     p_access->info.i_size = 0;
1148     p_access->info.i_pos  = i_tell;
1149     p_access->info.b_eof  = false;
1150
1151     /* Open connection */
1152     assert( p_sys->fd == -1 ); /* No open sockets (leaking fds is BAD) */
1153     p_sys->fd = net_ConnectTCP( p_access, srv.psz_host, srv.i_port );
1154     if( p_sys->fd == -1 )
1155     {
1156         msg_Err( p_access, "cannot connect to %s:%d", srv.psz_host, srv.i_port );
1157         return -1;
1158     }
1159     setsockopt (p_sys->fd, SOL_SOCKET, SO_KEEPALIVE, &(int){ 1 }, sizeof (int));
1160
1161     /* Initialize TLS/SSL session */
1162     if( p_sys->p_creds != NULL )
1163     {
1164         /* CONNECT to establish TLS tunnel through HTTP proxy */
1165         if( p_sys->b_proxy )
1166         {
1167             char *psz;
1168             unsigned i_status = 0;
1169
1170             if( p_sys->i_version == 0 )
1171             {
1172                 /* CONNECT is not in HTTP/1.0 */
1173                 Disconnect( p_access );
1174                 return -1;
1175             }
1176
1177             net_Printf( p_access, p_sys->fd, NULL,
1178                         "CONNECT %s:%d HTTP/1.%d\r\nHost: %s:%d\r\n\r\n",
1179                         p_sys->url.psz_host, p_sys->url.i_port,
1180                         p_sys->i_version,
1181                         p_sys->url.psz_host, p_sys->url.i_port);
1182
1183             psz = net_Gets( p_access, p_sys->fd, NULL );
1184             if( psz == NULL )
1185             {
1186                 msg_Err( p_access, "cannot establish HTTP/TLS tunnel" );
1187                 Disconnect( p_access );
1188                 return -1;
1189             }
1190
1191             sscanf( psz, "HTTP/%*u.%*u %3u", &i_status );
1192             free( psz );
1193
1194             if( ( i_status / 100 ) != 2 )
1195             {
1196                 msg_Err( p_access, "HTTP/TLS tunnel through proxy denied" );
1197                 Disconnect( p_access );
1198                 return -1;
1199             }
1200
1201             do
1202             {
1203                 psz = net_Gets( p_access, p_sys->fd, NULL );
1204                 if( psz == NULL )
1205                 {
1206                     msg_Err( p_access, "HTTP proxy connection failed" );
1207                     Disconnect( p_access );
1208                     return -1;
1209                 }
1210
1211                 if( *psz == '\0' )
1212                     i_status = 0;
1213
1214                 free( psz );
1215
1216                 if( !vlc_object_alive (p_access) || p_sys->b_error )
1217                 {
1218                     Disconnect( p_access );
1219                     return -1;
1220                 }
1221             }
1222             while( i_status );
1223         }
1224
1225         /* TLS/SSL handshake */
1226         p_sys->p_tls = vlc_tls_ClientSessionCreate( p_sys->p_creds, p_sys->fd,
1227                                                 p_sys->url.psz_host, "https" );
1228         if( p_sys->p_tls == NULL )
1229         {
1230             msg_Err( p_access, "cannot establish HTTP/TLS session" );
1231             Disconnect( p_access );
1232             return -1;
1233         }
1234         p_sys->p_vs = &p_sys->p_tls->sock;
1235     }
1236
1237     return Request( p_access, i_tell ) ? -2 : 0;
1238 }
1239
1240
1241 static int Request( access_t *p_access, uint64_t i_tell )
1242 {
1243     access_sys_t   *p_sys = p_access->p_sys;
1244     char           *psz ;
1245     v_socket_t     *pvs = p_sys->p_vs;
1246     p_sys->b_persist = false;
1247
1248     p_sys->i_remaining = 0;
1249
1250     const char *psz_path = p_sys->url.psz_path;
1251     if( !psz_path || !*psz_path )
1252         psz_path = "/";
1253     if( p_sys->b_proxy && pvs == NULL )
1254         net_Printf( p_access, p_sys->fd, NULL,
1255                     "GET http://%s:%d%s HTTP/1.%d\r\n",
1256                     p_sys->url.psz_host, p_sys->url.i_port,
1257                     psz_path, p_sys->i_version );
1258     else
1259         net_Printf( p_access, p_sys->fd, pvs, "GET %s HTTP/1.%d\r\n",
1260                     psz_path, p_sys->i_version );
1261     if( p_sys->url.i_port != (pvs ? 443 : 80) )
1262         net_Printf( p_access, p_sys->fd, pvs, "Host: %s:%d\r\n",
1263                     p_sys->url.psz_host, p_sys->url.i_port );
1264     else
1265         net_Printf( p_access, p_sys->fd, pvs, "Host: %s\r\n",
1266                     p_sys->url.psz_host );
1267     /* User Agent */
1268     net_Printf( p_access, p_sys->fd, pvs, "User-Agent: %s\r\n",
1269                 p_sys->psz_user_agent );
1270     /* Referrer */
1271     if (p_sys->psz_referrer)
1272     {
1273         net_Printf( p_access, p_sys->fd, pvs, "Referer: %s\r\n",
1274                     p_sys->psz_referrer);
1275     }
1276 #ifdef HAVE_ZLIB_H
1277     net_Printf( p_access, p_sys->fd, pvs, "Accept-Encoding: gzip, deflate\r\n" );
1278 #endif
1279     /* Offset */
1280     if( p_sys->i_version == 1 && ! p_sys->b_continuous )
1281     {
1282         p_sys->b_persist = true;
1283         net_Printf( p_access, p_sys->fd, pvs,
1284                     "Range: bytes=%"PRIu64"-\r\n", i_tell );
1285         net_Printf( p_access, p_sys->fd, pvs, "Connection: close\r\n" );
1286     }
1287
1288     /* Cookies */
1289     if( p_sys->cookies )
1290     {
1291         int i;
1292         for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
1293         {
1294             const char * cookie = vlc_array_item_at_index( p_sys->cookies, i );
1295             char * psz_cookie_content = cookie_get_content( cookie );
1296             char * psz_cookie_domain = cookie_get_domain( cookie );
1297
1298             assert( psz_cookie_content );
1299
1300             /* FIXME: This is clearly not conforming to the rfc */
1301             bool is_in_right_domain = (!psz_cookie_domain || strstr( p_sys->url.psz_host, psz_cookie_domain ));
1302
1303             if( is_in_right_domain )
1304             {
1305                 msg_Dbg( p_access, "Sending Cookie %s", psz_cookie_content );
1306                 if( net_Printf( p_access, p_sys->fd, pvs, "Cookie: %s\r\n", psz_cookie_content ) < 0 )
1307                     msg_Err( p_access, "failed to send Cookie" );
1308             }
1309             free( psz_cookie_content );
1310             free( psz_cookie_domain );
1311         }
1312     }
1313
1314     /* Authentication */
1315     if( p_sys->url.psz_username || p_sys->url.psz_password )
1316         AuthReply( p_access, "", &p_sys->url, &p_sys->auth );
1317
1318     /* Proxy Authentication */
1319     if( p_sys->proxy.psz_username || p_sys->proxy.psz_password )
1320         AuthReply( p_access, "Proxy-", &p_sys->proxy, &p_sys->proxy_auth );
1321
1322     /* ICY meta data request */
1323     net_Printf( p_access, p_sys->fd, pvs, "Icy-MetaData: 1\r\n" );
1324
1325
1326     if( net_Printf( p_access, p_sys->fd, pvs, "\r\n" ) < 0 )
1327     {
1328         msg_Err( p_access, "failed to send request" );
1329         Disconnect( p_access );
1330         return VLC_EGENERIC;
1331     }
1332
1333     /* Read Answer */
1334     if( ( psz = net_Gets( p_access, p_sys->fd, pvs ) ) == NULL )
1335     {
1336         msg_Err( p_access, "failed to read answer" );
1337         goto error;
1338     }
1339     if( !strncmp( psz, "HTTP/1.", 7 ) )
1340     {
1341         p_sys->psz_protocol = "HTTP";
1342         p_sys->i_code = atoi( &psz[9] );
1343     }
1344     else if( !strncmp( psz, "ICY", 3 ) )
1345     {
1346         p_sys->psz_protocol = "ICY";
1347         p_sys->i_code = atoi( &psz[4] );
1348         p_sys->b_reconnect = true;
1349     }
1350     else
1351     {
1352         msg_Err( p_access, "invalid HTTP reply '%s'", psz );
1353         free( psz );
1354         goto error;
1355     }
1356     msg_Dbg( p_access, "protocol '%s' answer code %d",
1357              p_sys->psz_protocol, p_sys->i_code );
1358     if( !strcmp( p_sys->psz_protocol, "ICY" ) )
1359     {
1360         p_sys->b_seekable = false;
1361     }
1362     if( p_sys->i_code != 206 && p_sys->i_code != 401 )
1363     {
1364         p_sys->b_seekable = false;
1365     }
1366     /* Authentication error - We'll have to display the dialog */
1367     if( p_sys->i_code == 401 )
1368     {
1369
1370     }
1371     /* Other fatal error */
1372     else if( p_sys->i_code >= 400 )
1373     {
1374         msg_Err( p_access, "error: %s", psz );
1375         free( psz );
1376         goto error;
1377     }
1378     free( psz );
1379
1380     for( ;; )
1381     {
1382         char *psz = net_Gets( p_access, p_sys->fd, pvs );
1383         char *p;
1384
1385         if( psz == NULL )
1386         {
1387             msg_Err( p_access, "failed to read answer" );
1388             goto error;
1389         }
1390
1391         if( !vlc_object_alive (p_access) || p_sys->b_error )
1392         {
1393             free( psz );
1394             goto error;
1395         }
1396
1397         /* msg_Dbg( p_input, "Line=%s", psz ); */
1398         if( *psz == '\0' )
1399         {
1400             free( psz );
1401             break;
1402         }
1403
1404         if( ( p = strchr( psz, ':' ) ) == NULL )
1405         {
1406             msg_Err( p_access, "malformed header line: %s", psz );
1407             free( psz );
1408             goto error;
1409         }
1410         *p++ = '\0';
1411         while( *p == ' ' ) p++;
1412
1413         if( !strcasecmp( psz, "Content-Length" ) )
1414         {
1415             uint64_t i_size = i_tell + (p_sys->i_remaining = (uint64_t)atoll( p ));
1416             if(i_size > p_access->info.i_size) {
1417                 p_sys->b_has_size = true;
1418                 p_access->info.i_size = i_size;
1419             }
1420             msg_Dbg( p_access, "this frame size=%"PRIu64, p_sys->i_remaining );
1421         }
1422         else if( !strcasecmp( psz, "Content-Range" ) ) {
1423             uint64_t i_ntell = i_tell;
1424             uint64_t i_nend = (p_access->info.i_size > 0)?(p_access->info.i_size - 1):i_tell;
1425             uint64_t i_nsize = p_access->info.i_size;
1426             sscanf(p,"bytes %"SCNu64"-%"SCNu64"/%"SCNu64,&i_ntell,&i_nend,&i_nsize);
1427             if(i_nend > i_ntell ) {
1428                 p_access->info.i_pos = i_ntell;
1429                 p_sys->i_icy_offset  = i_ntell;
1430                 p_sys->i_remaining = i_nend+1-i_ntell;
1431                 uint64_t i_size = (i_nsize > i_nend) ? i_nsize : (i_nend + 1);
1432                 if(i_size > p_access->info.i_size) {
1433                     p_sys->b_has_size = true;
1434                     p_access->info.i_size = i_size;
1435                 }
1436                 msg_Dbg( p_access, "stream size=%"PRIu64",pos=%"PRIu64",remaining=%"PRIu64,
1437                          i_nsize, i_ntell, p_sys->i_remaining);
1438             }
1439         }
1440         else if( !strcasecmp( psz, "Connection" ) ) {
1441             msg_Dbg( p_access, "Connection: %s",p );
1442             int i = -1;
1443             sscanf(p, "close%n",&i);
1444             if( i >= 0 ) {
1445                 p_sys->b_persist = false;
1446             }
1447         }
1448         else if( !strcasecmp( psz, "Location" ) )
1449         {
1450             char * psz_new_loc;
1451
1452             /* This does not follow RFC 2068, but yet if the url is not absolute,
1453              * handle it as everyone does. */
1454             if( p[0] == '/' )
1455             {
1456                 const char *psz_http_ext = p_sys->p_tls ? "s" : "" ;
1457
1458                 if( p_sys->url.i_port == ( p_sys->p_tls ? 443 : 80 ) )
1459                 {
1460                     if( asprintf(&psz_new_loc, "http%s://%s%s", psz_http_ext,
1461                                  p_sys->url.psz_host, p) < 0 )
1462                         goto error;
1463                 }
1464                 else
1465                 {
1466                     if( asprintf(&psz_new_loc, "http%s://%s:%d%s", psz_http_ext,
1467                                  p_sys->url.psz_host, p_sys->url.i_port, p) < 0 )
1468                         goto error;
1469                 }
1470             }
1471             else
1472             {
1473                 psz_new_loc = strdup( p );
1474             }
1475
1476             free( p_sys->psz_location );
1477             p_sys->psz_location = psz_new_loc;
1478         }
1479         else if( !strcasecmp( psz, "Content-Type" ) )
1480         {
1481             free( p_sys->psz_mime );
1482             p_sys->psz_mime = strdup( p );
1483             msg_Dbg( p_access, "Content-Type: %s", p_sys->psz_mime );
1484         }
1485         else if( !strcasecmp( psz, "Content-Encoding" ) )
1486         {
1487             msg_Dbg( p_access, "Content-Encoding: %s", p );
1488             if( !strcasecmp( p, "identity" ) )
1489                 ;
1490 #ifdef HAVE_ZLIB_H
1491             else if( !strcasecmp( p, "gzip" ) || !strcasecmp( p, "deflate" ) )
1492                 p_sys->b_compressed = true;
1493 #endif
1494             else
1495                 msg_Warn( p_access, "Unknown content coding: %s", p );
1496         }
1497         else if( !strcasecmp( psz, "Pragma" ) )
1498         {
1499             if( !strcasecmp( psz, "Pragma: features" ) )
1500                 p_sys->b_mms = true;
1501             free( p_sys->psz_pragma );
1502             p_sys->psz_pragma = strdup( p );
1503             msg_Dbg( p_access, "Pragma: %s", p_sys->psz_pragma );
1504         }
1505         else if( !strcasecmp( psz, "Server" ) )
1506         {
1507             msg_Dbg( p_access, "Server: %s", p );
1508             if( !strncasecmp( p, "Icecast", 7 ) ||
1509                 !strncasecmp( p, "Nanocaster", 10 ) )
1510             {
1511                 /* Remember if this is Icecast
1512                  * we need to force demux in this case without breaking
1513                  *  autodetection */
1514
1515                 /* Let live 365 streams (nanocaster) piggyback on the icecast
1516                  * routine. They look very similar */
1517
1518                 p_sys->b_reconnect = true;
1519                 p_sys->b_pace_control = false;
1520                 p_sys->b_icecast = true;
1521             }
1522         }
1523         else if( !strcasecmp( psz, "Transfer-Encoding" ) )
1524         {
1525             msg_Dbg( p_access, "Transfer-Encoding: %s", p );
1526             if( !strncasecmp( p, "chunked", 7 ) )
1527             {
1528                 p_sys->b_chunked = true;
1529             }
1530         }
1531         else if( !strcasecmp( psz, "Icy-MetaInt" ) )
1532         {
1533             msg_Dbg( p_access, "Icy-MetaInt: %s", p );
1534             p_sys->i_icy_meta = atoi( p );
1535             if( p_sys->i_icy_meta < 0 )
1536                 p_sys->i_icy_meta = 0;
1537             if( p_sys->i_icy_meta > 0 )
1538                 p_sys->b_icecast = true;
1539
1540             msg_Warn( p_access, "ICY metaint=%d", p_sys->i_icy_meta );
1541         }
1542         else if( !strcasecmp( psz, "Icy-Name" ) )
1543         {
1544             free( p_sys->psz_icy_name );
1545             char *psz_tmp = strdup( p );
1546             p_sys->psz_icy_name = EnsureUTF8( psz_tmp );
1547             if( !p_sys->psz_icy_name )
1548                 free( psz_tmp );
1549             msg_Dbg( p_access, "Icy-Name: %s", p_sys->psz_icy_name );
1550
1551             p_sys->b_icecast = true; /* be on the safeside. set it here as well. */
1552             p_sys->b_reconnect = true;
1553             p_sys->b_pace_control = false;
1554         }
1555         else if( !strcasecmp( psz, "Icy-Genre" ) )
1556         {
1557             free( p_sys->psz_icy_genre );
1558             char *psz_tmp = strdup( p );
1559             p_sys->psz_icy_genre = EnsureUTF8( psz_tmp );
1560             if( !p_sys->psz_icy_genre )
1561                 free( psz_tmp );
1562             msg_Dbg( p_access, "Icy-Genre: %s", p_sys->psz_icy_genre );
1563         }
1564         else if( !strncasecmp( psz, "Icy-Notice", 10 ) )
1565         {
1566             msg_Dbg( p_access, "Icy-Notice: %s", p );
1567         }
1568         else if( !strncasecmp( psz, "icy-", 4 ) ||
1569                  !strncasecmp( psz, "ice-", 4 ) ||
1570                  !strncasecmp( psz, "x-audiocast", 11 ) )
1571         {
1572             msg_Dbg( p_access, "Meta-Info: %s: %s", psz, p );
1573         }
1574         else if( !strcasecmp( psz, "Set-Cookie" ) )
1575         {
1576             if( p_sys->cookies )
1577             {
1578                 msg_Dbg( p_access, "Accepting Cookie: %s", p );
1579                 cookie_append( p_sys->cookies, strdup(p) );
1580             }
1581             else
1582                 msg_Dbg( p_access, "We have a Cookie we won't remember: %s", p );
1583         }
1584         else if( !strcasecmp( psz, "www-authenticate" ) )
1585         {
1586             msg_Dbg( p_access, "Authentication header: %s", p );
1587             http_auth_ParseWwwAuthenticateHeader( VLC_OBJECT(p_access),
1588                                                   &p_sys->auth, p );
1589         }
1590         else if( !strcasecmp( psz, "proxy-authenticate" ) )
1591         {
1592             msg_Dbg( p_access, "Proxy authentication header: %s", p );
1593             http_auth_ParseWwwAuthenticateHeader( VLC_OBJECT(p_access),
1594                                                   &p_sys->proxy_auth, p );
1595         }
1596         else if( !strcasecmp( psz, "authentication-info" ) )
1597         {
1598             msg_Dbg( p_access, "Authentication Info header: %s", p );
1599             if( AuthCheckReply( p_access, p, &p_sys->url, &p_sys->auth ) )
1600                 goto error;
1601         }
1602         else if( !strcasecmp( psz, "proxy-authentication-info" ) )
1603         {
1604             msg_Dbg( p_access, "Proxy Authentication Info header: %s", p );
1605             if( AuthCheckReply( p_access, p, &p_sys->proxy, &p_sys->proxy_auth ) )
1606                 goto error;
1607         }
1608         else if( !strcasecmp( psz, "Accept-Ranges" ) )
1609         {
1610             if( !strcasecmp( p, "bytes" ) )
1611                 p_sys->b_seekable = true;
1612         }
1613
1614         free( psz );
1615     }
1616     /* We close the stream for zero length data, unless of course the
1617      * server has already promised to do this for us.
1618      */
1619     if( p_sys->b_has_size && p_sys->i_remaining == 0 && p_sys->b_persist ) {
1620         Disconnect( p_access );
1621     }
1622     return VLC_SUCCESS;
1623
1624 error:
1625     Disconnect( p_access );
1626     return VLC_EGENERIC;
1627 }
1628
1629 /*****************************************************************************
1630  * Disconnect:
1631  *****************************************************************************/
1632 static void Disconnect( access_t *p_access )
1633 {
1634     access_sys_t *p_sys = p_access->p_sys;
1635
1636     if( p_sys->p_tls != NULL)
1637     {
1638         vlc_tls_SessionDelete( p_sys->p_tls );
1639         p_sys->p_tls = NULL;
1640         p_sys->p_vs = NULL;
1641     }
1642     if( p_sys->fd != -1)
1643     {
1644         net_Close(p_sys->fd);
1645         p_sys->fd = -1;
1646     }
1647
1648 }
1649
1650 /*****************************************************************************
1651  * Cookies (FIXME: we may want to rewrite that using a nice structure to hold
1652  * them) (FIXME: only support the "domain=" param)
1653  *****************************************************************************/
1654
1655 /* Get the NAME=VALUE part of the Cookie */
1656 static char * cookie_get_content( const char * cookie )
1657 {
1658     char * ret = strdup( cookie );
1659     if( !ret ) return NULL;
1660     char * str = ret;
1661     /* Look for a ';' */
1662     while( *str && *str != ';' ) str++;
1663     /* Replace it by a end-char */
1664     if( *str == ';' ) *str = 0;
1665     return ret;
1666 }
1667
1668 /* Get the domain where the cookie is stored */
1669 static char * cookie_get_domain( const char * cookie )
1670 {
1671     const char * str = cookie;
1672     static const char domain[] = "domain=";
1673     if( !str )
1674         return NULL;
1675     /* Look for a ';' */
1676     while( *str )
1677     {
1678         if( !strncmp( str, domain, sizeof(domain) - 1 /* minus \0 */ ) )
1679         {
1680             str += sizeof(domain) - 1 /* minus \0 */;
1681             char * ret = strdup( str );
1682             /* Now remove the next ';' if present */
1683             char * ret_iter = ret;
1684             while( *ret_iter && *ret_iter != ';' ) ret_iter++;
1685             if( *ret_iter == ';' )
1686                 *ret_iter = 0;
1687             return ret;
1688         }
1689         /* Go to next ';' field */
1690         while( *str && *str != ';' ) str++;
1691         if( *str == ';' ) str++;
1692         /* skip blank */
1693         while( *str && *str == ' ' ) str++;
1694     }
1695     return NULL;
1696 }
1697
1698 /* Get NAME in the NAME=VALUE field */
1699 static char * cookie_get_name( const char * cookie )
1700 {
1701     char * ret = cookie_get_content( cookie ); /* NAME=VALUE */
1702     if( !ret ) return NULL;
1703     char * str = ret;
1704     while( *str && *str != '=' ) str++;
1705     *str = 0;
1706     return ret;
1707 }
1708
1709 /* Add a cookie in cookies, checking to see how it should be added */
1710 static void cookie_append( vlc_array_t * cookies, char * cookie )
1711 {
1712     int i;
1713
1714     if( !cookie )
1715         return;
1716
1717     char * cookie_name = cookie_get_name( cookie );
1718
1719     /* Don't send invalid cookies */
1720     if( !cookie_name )
1721         return;
1722
1723     char * cookie_domain = cookie_get_domain( cookie );
1724     for( i = 0; i < vlc_array_count( cookies ); i++ )
1725     {
1726         char * current_cookie = vlc_array_item_at_index( cookies, i );
1727         char * current_cookie_name = cookie_get_name( current_cookie );
1728         char * current_cookie_domain = cookie_get_domain( current_cookie );
1729
1730         assert( current_cookie_name );
1731
1732         bool is_domain_matching = (
1733                       ( !cookie_domain && !current_cookie_domain ) ||
1734                       ( cookie_domain && current_cookie_domain &&
1735                         !strcmp( cookie_domain, current_cookie_domain ) ) );
1736
1737         if( is_domain_matching && !strcmp( cookie_name, current_cookie_name )  )
1738         {
1739             /* Remove previous value for this cookie */
1740             free( current_cookie );
1741             vlc_array_remove( cookies, i );
1742
1743             /* Clean */
1744             free( current_cookie_name );
1745             free( current_cookie_domain );
1746             break;
1747         }
1748         free( current_cookie_name );
1749         free( current_cookie_domain );
1750     }
1751     free( cookie_name );
1752     free( cookie_domain );
1753     vlc_array_append( cookies, cookie );
1754 }
1755
1756
1757 /*****************************************************************************
1758  * HTTP authentication
1759  *****************************************************************************/
1760
1761 static void AuthReply( access_t *p_access, const char *psz_prefix,
1762                        vlc_url_t *p_url, http_auth_t *p_auth )
1763 {
1764     access_sys_t *p_sys = p_access->p_sys;
1765     char *psz_value;
1766
1767     psz_value =
1768         http_auth_FormatAuthorizationHeader( VLC_OBJECT(p_access), p_auth,
1769                                              "GET", p_url->psz_path,
1770                                              p_url->psz_username,
1771                                              p_url->psz_password );
1772     if ( psz_value == NULL )
1773         return;
1774
1775     net_Printf( p_access, p_sys->fd, p_sys->p_vs,
1776                 "%sAuthorization: %s\r\n", psz_prefix, psz_value );
1777     free( psz_value );
1778 }
1779
1780 static int AuthCheckReply( access_t *p_access, const char *psz_header,
1781                            vlc_url_t *p_url, http_auth_t *p_auth )
1782 {
1783     return
1784         http_auth_ParseAuthenticationInfoHeader( VLC_OBJECT(p_access), p_auth,
1785                                                  psz_header, "",
1786                                                  p_url->psz_path,
1787                                                  p_url->psz_username,
1788                                                  p_url->psz_password );
1789 }