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