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