]> git.sesse.net Git - vlc/blob - modules/access/http.c
access_http: fix unbalanced quotes
[vlc] / modules / access / http.c
1 /*****************************************************************************
2  * http.c: HTTP input module
3  *****************************************************************************
4  * Copyright (C) 2001-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          RĂ©mi Denis-Courmont <rem # videolan.org>
10  *          Antoine Cellerier <dionoea at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36
37
38 #include <vlc_access.h>
39
40 #include <vlc_dialog.h>
41 #include <vlc_meta.h>
42 #include <vlc_network.h>
43 #include <vlc_url.h>
44 #include <vlc_tls.h>
45 #include <vlc_strings.h>
46 #include <vlc_charset.h>
47 #include <vlc_input.h>
48 #include <vlc_md5.h>
49 #include <vlc_http.h>
50
51 #ifdef HAVE_ZLIB_H
52 #   include <zlib.h>
53 #endif
54
55 #include <assert.h>
56
57 #ifdef HAVE_LIBPROXY
58 #    include <proxy.h>
59 #endif
60
61 #ifdef WIN32
62 #   include <windows.h>
63 #endif
64
65 /*****************************************************************************
66  * Module descriptor
67  *****************************************************************************/
68 static int  Open ( vlc_object_t * );
69 static void Close( vlc_object_t * );
70
71 #define PROXY_TEXT N_("HTTP proxy")
72 #define PROXY_LONGTEXT N_( \
73     "HTTP proxy to be used It must be of the form " \
74     "http://[user@]myproxy.mydomain:myport/ ; " \
75     "if empty, the http_proxy environment variable will be tried." )
76
77 #define PROXY_PASS_TEXT N_("HTTP proxy password")
78 #define PROXY_PASS_LONGTEXT N_( \
79     "If your HTTP proxy requires a password, set it here." )
80
81 #define CACHING_TEXT N_("Caching value in ms")
82 #define CACHING_LONGTEXT N_( \
83     "Caching value for HTTP streams. This " \
84     "value should be set in milliseconds." )
85
86 #define AGENT_TEXT N_("HTTP user agent")
87 #define AGENT_LONGTEXT N_("User agent that will be " \
88     "used for the connection.")
89
90 #define RECONNECT_TEXT N_("Auto re-connect")
91 #define RECONNECT_LONGTEXT N_( \
92     "Automatically try to reconnect to the stream in case of a sudden " \
93     "disconnect." )
94
95 #define CONTINUOUS_TEXT N_("Continuous stream")
96 #define CONTINUOUS_LONGTEXT N_("Read a file that is " \
97     "being constantly updated (for example, a JPG file on a server). " \
98     "You should not globally enable this option as it will break all other " \
99     "types of HTTP streams." )
100
101 #define FORWARD_COOKIES_TEXT N_("Forward Cookies")
102 #define FORWARD_COOKIES_LONGTEXT N_("Forward Cookies across http redirections.")
103
104 #define MAX_REDIRECT_TEXT N_("Max number of redirection")
105 #define MAX_REDIRECT_LONGTEXT N_("Limit the number of redirection to follow.")
106
107 #define USE_IE_PROXY_TEXT N_("Use Internet Explorer entered HTTP proxy server")
108 #define USE_IE_PROXY_LONGTEXT N_("Use Internet Explorer entered HTTP proxy " \
109     "server for all URL. Don't take into account bypasses settings and auto " \
110     "configuration scripts.")
111
112 vlc_module_begin ()
113     set_description( N_("HTTP input") )
114     set_capability( "access", 0 )
115     set_shortname( N_( "HTTP(S)" ) )
116     set_category( CAT_INPUT )
117     set_subcategory( SUBCAT_INPUT_ACCESS )
118
119     add_string( "http-proxy", NULL, NULL, PROXY_TEXT, PROXY_LONGTEXT,
120                 false )
121     add_password( "http-proxy-pwd", NULL, NULL,
122                   PROXY_PASS_TEXT, PROXY_PASS_LONGTEXT, false )
123     add_integer( "http-caching", 4 * DEFAULT_PTS_DELAY / 1000, NULL,
124                  CACHING_TEXT, CACHING_LONGTEXT, true )
125         change_safe()
126     add_string( "http-user-agent", PACKAGE_NAME" "PACKAGE_VERSION, NULL,
127                 AGENT_TEXT, AGENT_LONGTEXT, true )
128         change_safe()
129     add_bool( "http-reconnect", false, NULL, RECONNECT_TEXT,
130               RECONNECT_LONGTEXT, true )
131     add_bool( "http-continuous", false, NULL, CONTINUOUS_TEXT,
132               CONTINUOUS_LONGTEXT, true )
133         change_safe()
134     add_bool( "http-forward-cookies", true, NULL, FORWARD_COOKIES_TEXT,
135               FORWARD_COOKIES_LONGTEXT, true )
136     add_integer( "http-max-redirect", 5, NULL, MAX_REDIRECT_TEXT,
137                  MAX_REDIRECT_LONGTEXT, true )
138 #ifdef WIN32
139     add_bool( "http-use-IE-proxy", false, NULL, USE_IE_PROXY_TEXT,
140               USE_IE_PROXY_LONGTEXT, true )
141 #endif
142     add_obsolete_string("http-user")
143     add_obsolete_string("http-pwd")
144     add_shortcut( "http" )
145     add_shortcut( "https" )
146     add_shortcut( "unsv" )
147     add_shortcut( "itpc" ) /* iTunes Podcast */
148     add_shortcut( "icyx" )
149     set_callbacks( Open, Close )
150 vlc_module_end ()
151
152 /*****************************************************************************
153  * Local prototypes
154  *****************************************************************************/
155
156 struct access_sys_t
157 {
158     int fd;
159     bool b_error;
160     tls_session_t *p_tls;
161     v_socket_t    *p_vs;
162
163     /* From uri */
164     vlc_url_t url;
165     char    *psz_user_agent;
166     http_auth_t auth;
167
168     /* Proxy */
169     bool b_proxy;
170     vlc_url_t  proxy;
171     http_auth_t proxy_auth;
172     char       *psz_proxy_passbuf;
173
174     /* */
175     int        i_code;
176     const char *psz_protocol;
177     int        i_version;
178
179     char       *psz_mime;
180     char       *psz_pragma;
181     char       *psz_location;
182     bool b_mms;
183     bool b_icecast;
184     bool b_ssl;
185 #ifdef HAVE_ZLIB_H
186     bool b_compressed;
187     struct
188     {
189         z_stream   stream;
190         uint8_t   *p_buffer;
191     } inflate;
192 #endif
193
194     bool b_chunked;
195     int64_t    i_chunk;
196
197     int        i_icy_meta;
198     uint64_t   i_icy_offset;
199     char       *psz_icy_name;
200     char       *psz_icy_genre;
201     char       *psz_icy_title;
202
203     uint64_t i_remaining;
204
205     bool b_seekable;
206     bool b_reconnect;
207     bool b_continuous;
208     bool b_pace_control;
209     bool b_persist;
210     bool b_has_size;
211
212     vlc_array_t * cookies;
213 };
214
215 /* */
216 static int OpenWithCookies( vlc_object_t *p_this, const char *psz_access,
217                             int i_nb_redirect, int i_max_redirect,
218                             vlc_array_t *cookies );
219
220 /* */
221 static ssize_t Read( access_t *, uint8_t *, size_t );
222 static ssize_t ReadCompressed( access_t *, uint8_t *, size_t );
223 static int Seek( access_t *, uint64_t );
224 static int Control( access_t *, int, va_list );
225
226 /* */
227 static int Connect( access_t *, uint64_t );
228 static int Request( access_t *p_access, uint64_t i_tell );
229 static void Disconnect( access_t * );
230
231 /* Small Cookie utilities. Cookies support is partial. */
232 static char * cookie_get_content( const char * cookie );
233 static char * cookie_get_domain( const char * cookie );
234 static char * cookie_get_name( const char * cookie );
235 static void cookie_append( vlc_array_t * cookies, char * cookie );
236
237
238 static void AuthReply( access_t *p_acces, const char *psz_prefix,
239                        vlc_url_t *p_url, http_auth_t *p_auth );
240 static int AuthCheckReply( access_t *p_access, const char *psz_header,
241                            vlc_url_t *p_url, http_auth_t *p_auth );
242
243 /*****************************************************************************
244  * Open:
245  *****************************************************************************/
246 static int Open( vlc_object_t *p_this )
247 {
248     access_t *p_access = (access_t*)p_this;
249     return OpenWithCookies( p_this, p_access->psz_access, 0,
250                 var_CreateGetInteger( p_access, "http-max-redirect" ), NULL );
251 }
252
253 /**
254  * Open the given url using the given cookies
255  * @param p_this: the vlc object
256  * @psz_access: the acces to use (http, https, ...) (this value must be used
257  *              instead of p_access->psz_access)
258  * @i_nb_redirect: the number of redirection already done
259  * @i_max_redirect: limit to the number of redirection to follow
260  * @cookies: the available cookies
261  * @return vlc error codes
262  */
263 static int OpenWithCookies( vlc_object_t *p_this, const char *psz_access,
264                             int i_nb_redirect, int i_max_redirect,
265                             vlc_array_t *cookies )
266 {
267     access_t     *p_access = (access_t*)p_this;
268     access_sys_t *p_sys;
269     char         *psz, *p;
270
271     /* Only forward an store cookies if the corresponding option is activated */
272     bool   b_forward_cookies = var_CreateGetBool( p_access, "http-forward-cookies" );
273     vlc_array_t * saved_cookies = b_forward_cookies ? (cookies ? cookies : vlc_array_new()) : NULL;
274
275     /* Set up p_access */
276     STANDARD_READ_ACCESS_INIT;
277 #ifdef HAVE_ZLIB_H
278     p_access->pf_read = ReadCompressed;
279 #endif
280     p_sys->fd = -1;
281     p_sys->b_proxy = false;
282     p_sys->psz_proxy_passbuf = NULL;
283     p_sys->i_version = 1;
284     p_sys->b_seekable = true;
285     p_sys->psz_mime = NULL;
286     p_sys->psz_pragma = NULL;
287     p_sys->b_mms = false;
288     p_sys->b_icecast = false;
289     p_sys->psz_location = NULL;
290     p_sys->psz_user_agent = NULL;
291     p_sys->b_pace_control = true;
292     p_sys->b_ssl = false;
293 #ifdef HAVE_ZLIB_H
294     p_sys->b_compressed = false;
295     /* 15 is the max windowBits, +32 to enable optional gzip decoding */
296     if( inflateInit2( &p_sys->inflate.stream, 32+15 ) != Z_OK )
297         msg_Warn( p_access, "Error during zlib initialisation: %s",
298                   p_sys->inflate.stream.msg );
299     if( zlibCompileFlags() & (1<<17) )
300         msg_Warn( p_access, "Your zlib was compiled without gzip support." );
301     p_sys->inflate.p_buffer = NULL;
302 #endif
303     p_sys->p_tls = NULL;
304     p_sys->p_vs = NULL;
305     p_sys->i_icy_meta = 0;
306     p_sys->i_icy_offset = 0;
307     p_sys->psz_icy_name = NULL;
308     p_sys->psz_icy_genre = NULL;
309     p_sys->psz_icy_title = NULL;
310     p_sys->i_remaining = 0;
311     p_sys->b_persist = false;
312     p_sys->b_has_size = false;
313     p_access->info.i_size = 0;
314     p_access->info.i_pos  = 0;
315     p_access->info.b_eof  = false;
316
317     p_sys->cookies = saved_cookies;
318
319     http_auth_Init( &p_sys->auth );
320     http_auth_Init( &p_sys->proxy_auth );
321
322     /* Parse URI - remove spaces */
323     p = psz = strdup( p_access->psz_path );
324     while( (p = strchr( p, ' ' )) != NULL )
325         *p = '+';
326     vlc_UrlParse( &p_sys->url, psz, 0 );
327     free( psz );
328
329     if( p_sys->url.psz_host == NULL || *p_sys->url.psz_host == '\0' )
330     {
331         msg_Warn( p_access, "invalid host" );
332         goto error;
333     }
334     if( !strncmp( psz_access, "https", 5 ) )
335     {
336         /* HTTP over SSL */
337         p_sys->b_ssl = true;
338         if( p_sys->url.i_port <= 0 )
339             p_sys->url.i_port = 443;
340     }
341     else
342     {
343         if( p_sys->url.i_port <= 0 )
344             p_sys->url.i_port = 80;
345     }
346
347     /* Do user agent */
348     p_sys->psz_user_agent = var_CreateGetString( p_access, "http-user-agent" );
349
350     /* Check proxy */
351     psz = var_CreateGetNonEmptyString( p_access, "http-proxy" );
352     if( psz )
353     {
354         p_sys->b_proxy = true;
355         vlc_UrlParse( &p_sys->proxy, psz, 0 );
356         free( psz );
357     }
358 #ifdef HAVE_LIBPROXY
359     else
360     {
361         pxProxyFactory *pf = px_proxy_factory_new();
362         if (pf)
363         {
364             char *buf;
365             int i;
366             i=asprintf(&buf, "%s://%s", psz_access, p_access->psz_path);
367             if (i >= 0)
368             {
369                 msg_Dbg(p_access, "asking libproxy about url '%s'", buf);
370                 char **proxies = px_proxy_factory_get_proxies(pf, buf);
371                 if (proxies[0])
372                 {
373                     msg_Dbg(p_access, "libproxy suggest to use '%s'", proxies[0]);
374                     if(strcmp(proxies[0],"direct://") != 0)
375                     {
376                         p_sys->b_proxy = true;
377                         vlc_UrlParse( &p_sys->proxy, proxies[0], 0);
378                     }
379                 }
380                 for(i=0;proxies[i];i++) free(proxies[i]);
381                 free(proxies);
382                 free(buf);
383             }
384             px_proxy_factory_free(pf);
385         }
386         else
387         {
388             msg_Err(p_access, "Allocating memory for libproxy failed");
389         }
390     }
391 #elif defined( WIN32 )
392     else
393     {
394         if( var_CreateGetBool( p_access, "http-use-IE-proxy" ) )
395         {
396             /* Try to get the proxy server address from Windows internet settings using registry. */
397             HKEY h_key;
398             /* Open the key */
399             if( RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft" \
400                               "\\Windows\\CurrentVersion\\Internet Settings",
401                               0, KEY_READ, &h_key ) == ERROR_SUCCESS )
402             {
403                 DWORD i_dataReadSize = 4; /* sizeof( DWORD ); */
404                 DWORD proxyEnable = 0;
405                 /* Get the proxy enable value */
406                 if( RegQueryValueEx( h_key, "ProxyEnable", NULL, NULL,
407                                      (char *)&proxyEnable, &i_dataReadSize )
408                                      == ERROR_SUCCESS )
409                 {
410                     if( proxyEnable )
411                     {
412                         /* Proxy is enable */
413                         char psz_key[256];
414                         i_dataReadSize = 256;
415                         if( RegQueryValueEx( h_key, "ProxyServer",
416                                              NULL, NULL, psz_key,
417                                              &i_dataReadSize )
418                                              == ERROR_SUCCESS )
419                         {
420                             /* Get the proxy URL :
421                             Proxy server value in the registry can be something like "address:port"
422                             or "ftp=adress1:port1;http=adress2:port2 ..." depending of the
423                             confirguration. */
424                             char *psz_proxy;
425                             psz_proxy = strstr( psz_key, "http=" );
426                             if( psz_proxy != NULL )
427                             {
428                                 psz_proxy += strlen( "http=" );
429                                 char *psz_endUrl = strchr( psz_proxy, ';' );
430                                 if( psz_endUrl != NULL )
431                                     *psz_endUrl = '\0';
432                             }
433                             else
434                                 psz_proxy = psz_key;
435                             /* Set proxy enable for this connection. */
436                             p_sys->b_proxy = true;
437                             vlc_UrlParse( &p_sys->proxy, psz_proxy, 0 );
438                         }
439                         msg_Warn( p_access, "Couldn't read in registry " \
440                                   "the proxy server address." );
441                     }
442                 }
443                 else
444                     msg_Warn( p_access, "Couldn't read in registry if the " \
445                               "proxy is enable or not." );
446             }
447             else
448                 msg_Warn( p_access, "Couldn't open internet settings key " \
449                           "in registry." );
450         }
451     }
452 #elif HAVE_GETENV
453     else
454     {
455         psz = getenv( "http_proxy" );
456         if( psz )
457         {
458             p_sys->b_proxy = true;
459             vlc_UrlParse( &p_sys->proxy, psz, 0 );
460         }
461     }
462 #endif
463
464     if( psz ) /* No, this is NOT a use-after-free error */
465     {
466         psz = var_CreateGetNonEmptyString( p_access, "http-proxy-pwd" );
467         if( psz )
468             p_sys->proxy.psz_password = p_sys->psz_proxy_passbuf = psz;
469     }
470
471     if( p_sys->b_proxy )
472     {
473         if( p_sys->proxy.psz_host == NULL || *p_sys->proxy.psz_host == '\0' )
474         {
475             msg_Warn( p_access, "invalid proxy host" );
476             goto error;
477         }
478         if( p_sys->proxy.i_port <= 0 )
479         {
480             p_sys->proxy.i_port = 80;
481         }
482     }
483
484     msg_Dbg( p_access, "http: server='%s' port=%d file='%s'",
485              p_sys->url.psz_host, p_sys->url.i_port, p_sys->url.psz_path );
486     if( p_sys->b_proxy )
487     {
488         msg_Dbg( p_access, "      proxy %s:%d", p_sys->proxy.psz_host,
489                  p_sys->proxy.i_port );
490     }
491     if( p_sys->url.psz_username && *p_sys->url.psz_username )
492     {
493         msg_Dbg( p_access, "      user='%s'", p_sys->url.psz_username );
494     }
495
496     p_sys->b_reconnect = var_CreateGetBool( p_access, "http-reconnect" );
497     p_sys->b_continuous = var_CreateGetBool( p_access, "http-continuous" );
498
499 connect:
500     /* Connect */
501     switch( Connect( p_access, 0 ) )
502     {
503         case -1:
504             goto error;
505
506         case -2:
507             /* Retry with http 1.0 */
508             msg_Dbg( p_access, "switching to HTTP version 1.0" );
509             p_sys->i_version = 0;
510             p_sys->b_seekable = false;
511
512             if( !vlc_object_alive (p_access) || Connect( p_access, 0 ) )
513                 goto error;
514
515 #ifndef NDEBUG
516         case 0:
517             break;
518
519         default:
520             msg_Err( p_access, "You should not be here" );
521             abort();
522 #endif
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_nb_redirect >= i_max_redirect )
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_path );
584         p_access->psz_path = 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
596         Disconnect( p_access );
597         cookies = p_sys->cookies;
598 #ifdef HAVE_ZLIB_H
599         inflateEnd( &p_sys->inflate.stream );
600 #endif
601         free( p_sys );
602
603         /* Do new Open() run with new data */
604         return OpenWithCookies( p_this, psz_protocol, i_nb_redirect + 1,
605                                 i_max_redirect, cookies );
606     }
607
608     if( p_sys->b_mms )
609     {
610         msg_Dbg( p_access, "this is actually a live mms server, BAIL" );
611         goto error;
612     }
613
614     if( !strcmp( p_sys->psz_protocol, "ICY" ) || p_sys->b_icecast )
615     {
616         if( p_sys->psz_mime && strcasecmp( p_sys->psz_mime, "application/ogg" ) )
617         {
618             if( !strcasecmp( p_sys->psz_mime, "video/nsv" ) ||
619                 !strcasecmp( p_sys->psz_mime, "video/nsa" ) )
620             {
621                 free( p_access->psz_demux );
622                 p_access->psz_demux = strdup( "nsv" );
623             }
624             else if( !strcasecmp( p_sys->psz_mime, "audio/aac" ) ||
625                      !strcasecmp( p_sys->psz_mime, "audio/aacp" ) )
626             {
627                 free( p_access->psz_demux );
628                 p_access->psz_demux = strdup( "m4a" );
629             }
630             else if( !strcasecmp( p_sys->psz_mime, "audio/mpeg" ) )
631             {
632                 free( p_access->psz_demux );
633                 p_access->psz_demux = strdup( "mp3" );
634             }
635
636             msg_Info( p_access, "Raw-audio server found, %s demuxer selected",
637                       p_access->psz_demux );
638
639 #if 0       /* Doesn't work really well because of the pre-buffering in
640              * shoutcast servers (the buffer content will be sent as fast as
641              * possible). */
642             p_sys->b_pace_control = false;
643 #endif
644         }
645         else if( !p_sys->psz_mime )
646         {
647             free( p_access->psz_demux );
648             /* Shoutcast */
649             p_access->psz_demux = strdup( "mp3" );
650         }
651         /* else probably Ogg Vorbis */
652     }
653     else if( !strcasecmp( psz_access, "unsv" ) &&
654              p_sys->psz_mime &&
655              !strcasecmp( p_sys->psz_mime, "misc/ultravox" ) )
656     {
657         free( p_access->psz_demux );
658         /* Grrrr! detect ultravox server and force NSV demuxer */
659         p_access->psz_demux = strdup( "nsv" );
660     }
661     else if( !strcmp( psz_access, "itpc" ) )
662     {
663         free( p_access->psz_demux );
664         p_access->psz_demux = strdup( "podcast" );
665     }
666     else if( p_sys->psz_mime &&
667              !strncasecmp( p_sys->psz_mime, "application/xspf+xml", 20 ) &&
668              ( memchr( " ;\t", p_sys->psz_mime[20], 4 ) != NULL ) )
669     {
670         free( p_access->psz_demux );
671         p_access->psz_demux = strdup( "xspf-open" );
672     }
673
674     if( p_sys->b_reconnect ) msg_Dbg( p_access, "auto re-connect enabled" );
675
676     /* PTS delay */
677     var_Create( p_access, "http-caching", VLC_VAR_INTEGER |VLC_VAR_DOINHERIT );
678
679     return VLC_SUCCESS;
680
681 error:
682     vlc_UrlClean( &p_sys->url );
683     vlc_UrlClean( &p_sys->proxy );
684     free( p_sys->psz_proxy_passbuf );
685     free( p_sys->psz_mime );
686     free( p_sys->psz_pragma );
687     free( p_sys->psz_location );
688     free( p_sys->psz_user_agent );
689
690     Disconnect( p_access );
691
692     if( p_sys->cookies )
693     {
694         int i;
695         for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
696             free(vlc_array_item_at_index( p_sys->cookies, i ));
697         vlc_array_destroy( p_sys->cookies );
698     }
699
700 #ifdef HAVE_ZLIB_H
701     inflateEnd( &p_sys->inflate.stream );
702 #endif
703     free( p_sys );
704     return VLC_EGENERIC;
705 }
706
707 /*****************************************************************************
708  * Close:
709  *****************************************************************************/
710 static void Close( vlc_object_t *p_this )
711 {
712     access_t     *p_access = (access_t*)p_this;
713     access_sys_t *p_sys = p_access->p_sys;
714
715     vlc_UrlClean( &p_sys->url );
716     http_auth_Reset( &p_sys->auth );
717     vlc_UrlClean( &p_sys->proxy );
718     http_auth_Reset( &p_sys->proxy_auth );
719
720     free( p_sys->psz_mime );
721     free( p_sys->psz_pragma );
722     free( p_sys->psz_location );
723
724     free( p_sys->psz_icy_name );
725     free( p_sys->psz_icy_genre );
726     free( p_sys->psz_icy_title );
727
728     free( p_sys->psz_user_agent );
729
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     {
760         p_access->info.b_eof = true;
761         return 0;
762     }
763
764     if( p_sys->b_has_size )
765     {
766         /* Remaining bytes in the file */
767         uint64_t remainder = p_access->info.i_size - p_access->info.i_pos;
768         if( remainder < i_len )
769             i_len = remainder;
770
771         /* Remaining bytes in the response */
772         if( p_sys->i_remaining < i_len )
773             i_len = p_sys->i_remaining;
774     }
775
776     if( p_sys->b_chunked )
777     {
778         if( p_sys->i_chunk < 0 )
779         {
780             p_access->info.b_eof = true;
781             return 0;
782         }
783
784         if( p_sys->i_chunk <= 0 )
785         {
786             char *psz = net_Gets( p_access, p_sys->fd, p_sys->p_vs );
787             /* read the chunk header */
788             if( psz == NULL )
789             {
790                 /* fatal error - end of file */
791                 msg_Dbg( p_access, "failed reading chunk-header line" );
792                 return 0;
793             }
794             p_sys->i_chunk = strtoll( psz, NULL, 16 );
795             free( psz );
796
797             if( p_sys->i_chunk <= 0 )   /* eof */
798             {
799                 p_sys->i_chunk = -1;
800                 p_access->info.b_eof = true;
801                 return 0;
802             }
803         }
804
805         if( i_len > p_sys->i_chunk )
806             i_len = p_sys->i_chunk;
807     }
808
809     if( i_len == 0 )
810     {
811         p_access->info.b_eof = true;
812         return 0;
813     }
814
815     if( p_sys->i_icy_meta > 0 && p_access->info.i_pos-p_sys->i_icy_offset > 0 )
816     {
817         int64_t i_next = p_sys->i_icy_meta -
818                                     (p_access->info.i_pos - p_sys->i_icy_offset ) % p_sys->i_icy_meta;
819
820         if( i_next == p_sys->i_icy_meta )
821         {
822             if( ReadICYMeta( p_access ) )
823             {
824                 p_access->info.b_eof = true;
825                 return -1;
826             }
827         }
828         if( i_len > i_next )
829             i_len = i_next;
830     }
831
832     i_read = net_Read( p_access, p_sys->fd, p_sys->p_vs, p_buffer, i_len, false );
833
834     if( i_read > 0 )
835     {
836         if( p_sys->b_chunked )
837         {
838             p_sys->i_chunk -= i_read;
839             if( p_sys->i_chunk <= 0 )
840             {
841                 /* read the empty line */
842                 char *psz = net_Gets( p_access, p_sys->fd, p_sys->p_vs );
843                 free( psz );
844             }
845         }
846     }
847     else
848     {
849         /*
850          * I very much doubt that this will work.
851          * If i_read == 0, the connection *IS* dead, so the only
852          * sensible thing to do is Disconnect() and then retry.
853          * Otherwise, I got recv() completely wrong. -- Courmisch
854          */
855         if( p_sys->b_continuous )
856         {
857             Request( p_access, 0 );
858             p_sys->b_continuous = false;
859             i_read = Read( p_access, p_buffer, i_len );
860             p_sys->b_continuous = true;
861         }
862         Disconnect( p_access );
863         if( p_sys->b_reconnect && vlc_object_alive( p_access ) )
864         {
865             msg_Dbg( p_access, "got disconnected, trying to reconnect" );
866             if( Connect( p_access, p_access->info.i_pos ) )
867             {
868                 msg_Dbg( p_access, "reconnection failed" );
869             }
870             else
871             {
872                 p_sys->b_reconnect = false;
873                 i_read = Read( p_access, p_buffer, i_len );
874                 p_sys->b_reconnect = true;
875
876                 return i_read;
877             }
878         }
879
880         if( i_read <= 0 )
881         {
882             p_access->info.b_eof = true;
883             if( i_read < 0 )
884                 p_sys->b_error = true;
885             return 0;
886         }
887     }
888
889     assert( i_read >= 0 );
890     p_access->info.i_pos += i_read;
891     if( p_sys->b_has_size )
892     {
893         assert( p_access->info.i_pos <= p_access->info.i_size );
894         assert( (unsigned)i_read <= p_sys->i_remaining );
895         p_sys->i_remaining -= i_read;
896     }
897
898     return i_read;
899 }
900
901 static int ReadICYMeta( access_t *p_access )
902 {
903     access_sys_t *p_sys = p_access->p_sys;
904
905     uint8_t buffer;
906     char *p, *psz_meta;
907     int i_read;
908
909     /* Read meta data length */
910     i_read = net_Read( p_access, p_sys->fd, p_sys->p_vs, &buffer, 1,
911                        true );
912     if( i_read <= 0 )
913         return VLC_EGENERIC;
914     if( buffer == 0 )
915         return VLC_SUCCESS;
916
917     i_read = buffer << 4;
918     /* msg_Dbg( p_access, "ICY meta size=%u", i_read); */
919
920     psz_meta = malloc( i_read + 1 );
921     if( net_Read( p_access, p_sys->fd, p_sys->p_vs,
922                   (uint8_t *)psz_meta, i_read, true ) != i_read )
923     {
924         free( psz_meta );
925         return VLC_EGENERIC;
926     }
927
928     psz_meta[i_read] = '\0'; /* Just in case */
929
930     /* msg_Dbg( p_access, "icy-meta=%s", psz_meta ); */
931
932     /* Now parse the meta */
933     /* Look for StreamTitle= */
934     p = strcasestr( (char *)psz_meta, "StreamTitle=" );
935     if( p )
936     {
937         p += strlen( "StreamTitle=" );
938         if( *p == '\'' || *p == '"' )
939         {
940             char closing[] = { p[0], ';', '\0' };
941             char *psz = strstr( &p[1], closing );
942             if( !psz )
943                 psz = strchr( &p[1], ';' );
944
945             if( psz ) *psz = '\0';
946         }
947         else
948         {
949             char *psz = strchr( &p[1], ';' );
950             if( psz ) *psz = '\0';
951         }
952
953         if( !p_sys->psz_icy_title ||
954             strcmp( p_sys->psz_icy_title, &p[1] ) )
955         {
956             free( p_sys->psz_icy_title );
957             char *psz_tmp = strdup( &p[1] );
958             p_sys->psz_icy_title = EnsureUTF8( psz_tmp );
959             if( !p_sys->psz_icy_title )
960                 free( psz_tmp );
961             p_access->info.i_update |= INPUT_UPDATE_META;
962
963             msg_Dbg( p_access, "New Title=%s", p_sys->psz_icy_title );
964         }
965     }
966     free( psz_meta );
967
968     return VLC_SUCCESS;
969 }
970
971 #ifdef HAVE_ZLIB_H
972 static ssize_t ReadCompressed( access_t *p_access, uint8_t *p_buffer,
973                                size_t i_len )
974 {
975     access_sys_t *p_sys = p_access->p_sys;
976
977     if( p_sys->b_compressed )
978     {
979         int i_ret;
980
981         if( !p_sys->inflate.p_buffer )
982             p_sys->inflate.p_buffer = malloc( 256 * 1024 );
983
984         if( p_sys->inflate.stream.avail_in == 0 )
985         {
986             ssize_t i_read = Read( p_access, p_sys->inflate.p_buffer + p_sys->inflate.stream.avail_in, 256 * 1024 );
987             if( i_read <= 0 ) return i_read;
988             p_sys->inflate.stream.next_in = p_sys->inflate.p_buffer;
989             p_sys->inflate.stream.avail_in = i_read;
990         }
991
992         p_sys->inflate.stream.avail_out = i_len;
993         p_sys->inflate.stream.next_out = p_buffer;
994
995         i_ret = inflate( &p_sys->inflate.stream, Z_SYNC_FLUSH );
996         msg_Warn( p_access, "inflate return value: %d, %s", i_ret, p_sys->inflate.stream.msg );
997
998         return i_len - p_sys->inflate.stream.avail_out;
999     }
1000     else
1001     {
1002         return Read( p_access, p_buffer, i_len );
1003     }
1004 }
1005 #endif
1006
1007 /*****************************************************************************
1008  * Seek: close and re-open a connection at the right place
1009  *****************************************************************************/
1010 static int Seek( access_t *p_access, uint64_t i_pos )
1011 {
1012     msg_Dbg( p_access, "trying to seek to %"PRId64, i_pos );
1013
1014     Disconnect( p_access );
1015
1016     if( p_access->info.i_size
1017      && i_pos >= p_access->info.i_size ) {
1018         msg_Err( p_access, "seek to far" );
1019         int retval = Seek( p_access, p_access->info.i_size - 1 );
1020         if( retval == VLC_SUCCESS ) {
1021             uint8_t p_buffer[2];
1022             Read( p_access, p_buffer, 1);
1023             p_access->info.b_eof  = false;
1024         }
1025         return retval;
1026     }
1027     if( Connect( p_access, i_pos ) )
1028     {
1029         msg_Err( p_access, "seek failed" );
1030         p_access->info.b_eof = true;
1031         return VLC_EGENERIC;
1032     }
1033     return VLC_SUCCESS;
1034 }
1035
1036 /*****************************************************************************
1037  * Control:
1038  *****************************************************************************/
1039 static int Control( access_t *p_access, int i_query, va_list args )
1040 {
1041     access_sys_t *p_sys = p_access->p_sys;
1042     bool       *pb_bool;
1043     int64_t    *pi_64;
1044     vlc_meta_t *p_meta;
1045
1046     switch( i_query )
1047     {
1048         /* */
1049         case ACCESS_CAN_SEEK:
1050             pb_bool = (bool*)va_arg( args, bool* );
1051             *pb_bool = p_sys->b_seekable;
1052             break;
1053         case ACCESS_CAN_FASTSEEK:
1054             pb_bool = (bool*)va_arg( args, bool* );
1055             *pb_bool = false;
1056             break;
1057         case ACCESS_CAN_PAUSE:
1058         case ACCESS_CAN_CONTROL_PACE:
1059             pb_bool = (bool*)va_arg( args, bool* );
1060
1061 #if 0       /* Disable for now until we have a clock synchro algo
1062              * which works with something else than MPEG over UDP */
1063             *pb_bool = p_sys->b_pace_control;
1064 #endif
1065             *pb_bool = true;
1066             break;
1067
1068         /* */
1069         case ACCESS_GET_PTS_DELAY:
1070             pi_64 = (int64_t*)va_arg( args, int64_t * );
1071             *pi_64 = (int64_t)var_GetInteger( p_access, "http-caching" ) * 1000;
1072             break;
1073
1074         /* */
1075         case ACCESS_SET_PAUSE_STATE:
1076             break;
1077
1078         case ACCESS_GET_META:
1079             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1080
1081             if( p_sys->psz_icy_name )
1082                 vlc_meta_Set( p_meta, vlc_meta_Title, p_sys->psz_icy_name );
1083             if( p_sys->psz_icy_genre )
1084                 vlc_meta_Set( p_meta, vlc_meta_Genre, p_sys->psz_icy_genre );
1085             if( p_sys->psz_icy_title )
1086                 vlc_meta_Set( p_meta, vlc_meta_NowPlaying, p_sys->psz_icy_title );
1087             break;
1088
1089         case ACCESS_GET_CONTENT_TYPE:
1090             *va_arg( args, char ** ) =
1091                 p_sys->psz_mime ? strdup( p_sys->psz_mime ) : NULL;
1092             break;
1093
1094         case ACCESS_GET_TITLE_INFO:
1095         case ACCESS_SET_TITLE:
1096         case ACCESS_SET_SEEKPOINT:
1097         case ACCESS_SET_PRIVATE_ID_STATE:
1098             return VLC_EGENERIC;
1099
1100         default:
1101             msg_Warn( p_access, "unimplemented query in control" );
1102             return VLC_EGENERIC;
1103
1104     }
1105     return VLC_SUCCESS;
1106 }
1107
1108 /*****************************************************************************
1109  * Connect:
1110  *****************************************************************************/
1111 static int Connect( access_t *p_access, uint64_t i_tell )
1112 {
1113     access_sys_t   *p_sys = p_access->p_sys;
1114     vlc_url_t      srv = p_sys->b_proxy ? p_sys->proxy : p_sys->url;
1115
1116     /* Clean info */
1117     free( p_sys->psz_location );
1118     free( p_sys->psz_mime );
1119     free( p_sys->psz_pragma );
1120
1121     free( p_sys->psz_icy_genre );
1122     free( p_sys->psz_icy_name );
1123     free( p_sys->psz_icy_title );
1124
1125
1126     p_sys->psz_location = NULL;
1127     p_sys->psz_mime = NULL;
1128     p_sys->psz_pragma = NULL;
1129     p_sys->b_mms = false;
1130     p_sys->b_chunked = false;
1131     p_sys->i_chunk = 0;
1132     p_sys->i_icy_meta = 0;
1133     p_sys->i_icy_offset = i_tell;
1134     p_sys->psz_icy_name = NULL;
1135     p_sys->psz_icy_genre = NULL;
1136     p_sys->psz_icy_title = NULL;
1137     p_sys->i_remaining = 0;
1138     p_sys->b_persist = false;
1139     p_sys->b_has_size = false;
1140     p_access->info.i_size = 0;
1141     p_access->info.i_pos  = i_tell;
1142     p_access->info.b_eof  = false;
1143
1144     /* Open connection */
1145     assert( p_sys->fd == -1 ); /* No open sockets (leaking fds is BAD) */
1146     p_sys->fd = net_ConnectTCP( p_access, srv.psz_host, srv.i_port );
1147     if( p_sys->fd == -1 )
1148     {
1149         msg_Err( p_access, "cannot connect to %s:%d", srv.psz_host, srv.i_port );
1150         return -1;
1151     }
1152     setsockopt (p_sys->fd, SOL_SOCKET, SO_KEEPALIVE, &(int){ 1 }, sizeof (int));
1153
1154     /* Initialize TLS/SSL session */
1155     if( p_sys->b_ssl == true )
1156     {
1157         /* CONNECT to establish TLS tunnel through HTTP proxy */
1158         if( p_sys->b_proxy )
1159         {
1160             char *psz;
1161             unsigned i_status = 0;
1162
1163             if( p_sys->i_version == 0 )
1164             {
1165                 /* CONNECT is not in HTTP/1.0 */
1166                 Disconnect( p_access );
1167                 return -1;
1168             }
1169
1170             net_Printf( p_access, p_sys->fd, NULL,
1171                         "CONNECT %s:%d HTTP/1.%d\r\nHost: %s:%d\r\n\r\n",
1172                         p_sys->url.psz_host, p_sys->url.i_port,
1173                         p_sys->i_version,
1174                         p_sys->url.psz_host, p_sys->url.i_port);
1175
1176             psz = net_Gets( p_access, p_sys->fd, NULL );
1177             if( psz == NULL )
1178             {
1179                 msg_Err( p_access, "cannot establish HTTP/TLS tunnel" );
1180                 Disconnect( p_access );
1181                 return -1;
1182             }
1183
1184             sscanf( psz, "HTTP/%*u.%*u %3u", &i_status );
1185             free( psz );
1186
1187             if( ( i_status / 100 ) != 2 )
1188             {
1189                 msg_Err( p_access, "HTTP/TLS tunnel through proxy denied" );
1190                 Disconnect( p_access );
1191                 return -1;
1192             }
1193
1194             do
1195             {
1196                 psz = net_Gets( p_access, p_sys->fd, NULL );
1197                 if( psz == NULL )
1198                 {
1199                     msg_Err( p_access, "HTTP proxy connection failed" );
1200                     Disconnect( p_access );
1201                     return -1;
1202                 }
1203
1204                 if( *psz == '\0' )
1205                     i_status = 0;
1206
1207                 free( psz );
1208
1209                 if( !vlc_object_alive (p_access) || p_sys->b_error )
1210                 {
1211                     Disconnect( p_access );
1212                     return -1;
1213                 }
1214             }
1215             while( i_status );
1216         }
1217
1218         /* TLS/SSL handshake */
1219         p_sys->p_tls = tls_ClientCreate( VLC_OBJECT(p_access), p_sys->fd,
1220                                          p_sys->url.psz_host );
1221         if( p_sys->p_tls == NULL )
1222         {
1223             msg_Err( p_access, "cannot establish HTTP/TLS session" );
1224             Disconnect( p_access );
1225             return -1;
1226         }
1227         p_sys->p_vs = &p_sys->p_tls->sock;
1228     }
1229
1230     return Request( p_access, i_tell ) ? -2 : 0;
1231 }
1232
1233
1234 static int Request( access_t *p_access, uint64_t i_tell )
1235 {
1236     access_sys_t   *p_sys = p_access->p_sys;
1237     char           *psz ;
1238     v_socket_t     *pvs = p_sys->p_vs;
1239     p_sys->b_persist = false;
1240
1241     p_sys->i_remaining = 0;
1242     if( p_sys->b_proxy )
1243     {
1244         if( p_sys->url.psz_path )
1245         {
1246             net_Printf( p_access, p_sys->fd, NULL,
1247                         "GET http://%s:%d%s HTTP/1.%d\r\n",
1248                         p_sys->url.psz_host, p_sys->url.i_port,
1249                         p_sys->url.psz_path, p_sys->i_version );
1250         }
1251         else
1252         {
1253             net_Printf( p_access, p_sys->fd, NULL,
1254                         "GET http://%s:%d/ HTTP/1.%d\r\n",
1255                         p_sys->url.psz_host, p_sys->url.i_port,
1256                         p_sys->i_version );
1257         }
1258     }
1259     else
1260     {
1261         const char *psz_path = p_sys->url.psz_path;
1262         if( !psz_path || !*psz_path )
1263         {
1264             psz_path = "/";
1265         }
1266         if( p_sys->url.i_port != (pvs ? 443 : 80) )
1267         {
1268             net_Printf( p_access, p_sys->fd, pvs,
1269                         "GET %s HTTP/1.%d\r\nHost: %s:%d\r\n",
1270                         psz_path, p_sys->i_version, p_sys->url.psz_host,
1271                         p_sys->url.i_port );
1272         }
1273         else
1274         {
1275             net_Printf( p_access, p_sys->fd, pvs,
1276                         "GET %s HTTP/1.%d\r\nHost: %s\r\n",
1277                         psz_path, p_sys->i_version, p_sys->url.psz_host );
1278         }
1279     }
1280     /* User Agent */
1281     net_Printf( p_access, p_sys->fd, pvs, "User-Agent: %s\r\n",
1282                 p_sys->psz_user_agent );
1283     /* Offset */
1284     if( p_sys->i_version == 1 && ! p_sys->b_continuous )
1285     {
1286         p_sys->b_persist = true;
1287         net_Printf( p_access, p_sys->fd, pvs,
1288                     "Range: bytes=%"PRIu64"-\r\n", i_tell );
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                 int64_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         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 }