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