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