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