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