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