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