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