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