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