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