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