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