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