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