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