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