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