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