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