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