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