]> git.sesse.net Git - vlc/blobdiff - modules/access/http.c
Preliminary HTTP Digest Access Authentication client side support. auth-int support...
[vlc] / modules / access / http.c
index cce9f70c55964b4c58a71e169bd0b9d81773f6d3..67cd20956ec25afaba5d362f3a2d008a7f901b25 100644 (file)
 /*****************************************************************************
  * Preamble
  *****************************************************************************/
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
 #include <vlc/vlc.h>
 
 
 #include <vlc_access.h>
 
 #include <vlc_interface.h>
-#include <vlc_playlist.h>
 #include <vlc_meta.h>
 #include <vlc_network.h>
 #include <vlc_url.h>
 #include <vlc_tls.h>
 #include <vlc_strings.h>
+#include <vlc_input.h>
+#include <vlc_md5.h>
+
+#ifdef HAVE_ZLIB_H
+#   include <zlib.h>
+#endif
 
 /*****************************************************************************
  * Module descriptor
@@ -71,6 +80,9 @@ static void Close( vlc_object_t * );
     "You should not globally enable this option as it will break all other " \
     "types of HTTP streams." )
 
+#define FORWARD_COOKIES_TEXT N_("Forward Cookies")
+#define FORWARD_COOKIES_LONGTEXT N_("Forward Cookies Across http redirections ")
+
 vlc_module_begin();
     set_description( _("HTTP input") );
     set_capability( "access2", 0 );
@@ -88,6 +100,8 @@ vlc_module_begin();
               RECONNECT_LONGTEXT, VLC_TRUE );
     add_bool( "http-continuous", 0, NULL, CONTINUOUS_TEXT,
               CONTINUOUS_LONGTEXT, VLC_TRUE );
+    add_bool( "http-forward-cookies", 0, NULL, FORWARD_COOKIES_TEXT,
+              FORWARD_COOKIES_LONGTEXT, VLC_TRUE );
     add_obsolete_string("http-user");
     add_obsolete_string("http-pwd");
     add_shortcut( "http" );
@@ -100,6 +114,22 @@ vlc_module_end();
 /*****************************************************************************
  * Local prototypes
  *****************************************************************************/
+
+/* RFC 2617: Basic and Digest Access Authentification */
+typedef struct http_auth_t
+{
+    char *psz_realm;
+    char *psz_domain;
+    char *psz_nonce;
+    char *psz_opaque;
+    char *psz_stale;
+    char *psz_algorithm;
+    char *psz_qop;
+    int i_nonce;
+    char *psz_cnonce;
+    char *psz_A1; /* stored A1 value if algorithm = "MD5-sess" */
+} http_auth_t;
+
 struct access_sys_t
 {
     int fd;
@@ -109,10 +139,12 @@ struct access_sys_t
     /* From uri */
     vlc_url_t url;
     char    *psz_user_agent;
+    http_auth_t auth;
 
     /* Proxy */
     vlc_bool_t b_proxy;
     vlc_url_t  proxy;
+    http_auth_t proxy_auth;
 
     /* */
     int        i_code;
@@ -125,6 +157,14 @@ struct access_sys_t
     vlc_bool_t b_mms;
     vlc_bool_t b_icecast;
     vlc_bool_t b_ssl;
+#ifdef HAVE_ZLIB_H
+    vlc_bool_t b_compressed;
+    struct
+    {
+        z_stream   stream;
+        uint8_t   *p_buffer;
+    } inflate;
+#endif
 
     vlc_bool_t b_chunked;
     int64_t    i_chunk;
@@ -140,10 +180,16 @@ struct access_sys_t
     vlc_bool_t b_reconnect;
     vlc_bool_t b_continuous;
     vlc_bool_t b_pace_control;
+
+    vlc_array_t * cookies;
 };
 
+/* */
+static int OpenWithCookies( vlc_object_t *p_this, vlc_array_t *cookies );
+
 /* */
 static ssize_t Read( access_t *, uint8_t *, size_t );
+static ssize_t ReadCompressed( access_t *, uint8_t *, size_t );
 static int Seek( access_t *, int64_t );
 static int Control( access_t *, int, va_list );
 
@@ -152,17 +198,41 @@ static int Connect( access_t *, int64_t );
 static int Request( access_t *p_access, int64_t i_tell );
 static void Disconnect( access_t * );
 
+/* Small Cookie utilities. Cookies support is partial. */
+static char * cookie_get_content( const char * cookie );
+static char * cookie_get_domain( const char * cookie );
+static char * cookie_get_name( const char * cookie );
+static void cookie_append( vlc_array_t * cookies, char * cookie );
+
+
+static void AuthParseHeader( access_t *p_access, const char *psz_header,
+                             http_auth_t *p_auth );
+static void AuthReply( access_t *p_acces, const char *psz_prefix,
+                       vlc_url_t *p_url, http_auth_t *p_auth );
+static void AuthReset( http_auth_t *p_auth );
+
 /*****************************************************************************
  * Open:
  *****************************************************************************/
 static int Open( vlc_object_t *p_this )
+{
+    return OpenWithCookies( p_this, NULL );
+}
+
+static int OpenWithCookies( vlc_object_t *p_this, vlc_array_t *cookies )
 {
     access_t     *p_access = (access_t*)p_this;
     access_sys_t *p_sys;
     char         *psz, *p;
+    /* Only forward an store cookies if the corresponding option is activated */
+    vlc_bool_t   b_forward_cookies = var_CreateGetBool( p_access, "http-forward-cookies" );
+    vlc_array_t * saved_cookies = b_forward_cookies ? (cookies ?: vlc_array_new()) : NULL;
 
     /* Set up p_access */
     STANDARD_READ_ACCESS_INIT;
+#ifdef HAVE_ZLIB_H
+    p_access->pf_read = ReadCompressed;
+#endif
     p_sys->fd = -1;
     p_sys->b_proxy = VLC_FALSE;
     p_sys->i_version = 1;
@@ -175,6 +245,16 @@ static int Open( vlc_object_t *p_this )
     p_sys->psz_user_agent = NULL;
     p_sys->b_pace_control = VLC_TRUE;
     p_sys->b_ssl = VLC_FALSE;
+#ifdef HAVE_ZLIB_H
+    p_sys->b_compressed = VLC_FALSE;
+    /* 15 is the max windowBits, +32 to enable optional gzip decoding */
+    if( inflateInit2( &p_sys->inflate.stream, 32+15 ) != Z_OK )
+        msg_Warn( p_access, "Error during zlib initialisation: %s",
+                  p_sys->inflate.stream.msg );
+    if( zlibCompileFlags() & (1<<17) )
+        msg_Warn( p_access, "Your zlib was compiled without gzip support." );
+    p_sys->inflate.p_buffer = NULL;
+#endif
     p_sys->p_tls = NULL;
     p_sys->p_vs = NULL;
     p_sys->i_icy_meta = 0;
@@ -183,6 +263,7 @@ static int Open( vlc_object_t *p_this )
     p_sys->psz_icy_title = NULL;
     p_sys->i_remaining = 0;
 
+    p_sys->cookies = saved_cookies;
 
     /* Parse URI - remove spaces */
     p = psz = strdup( p_access->psz_path );
@@ -277,7 +358,7 @@ connect:
             if( p_access->b_die || Connect( p_access, 0 ) )
                 goto error;
 
-#ifdef DEBUG
+#ifndef NDEBUG
         case 0:
             break;
 
@@ -290,25 +371,35 @@ connect:
     if( p_sys->i_code == 401 )
     {
         char *psz_login = NULL; char *psz_password = NULL;
+        char psz_msg[250];
         int i_ret;
-        msg_Dbg( p_access, "authentication failed" );
+        /* FIXME ? */
+        if( p_sys->url.psz_username && p_sys->url.psz_password &&
+            p_sys->auth.psz_nonce && p_sys->auth.i_nonce == 0 )
+        {
+            goto connect;
+        }
+        snprintf( psz_msg, 250,
+            _("Please enter a valid login name and a password for realm %s."),
+            p_sys->auth.psz_realm );
+        msg_Dbg( p_access, "authentication failed for realm %s",
+            p_sys->auth.psz_realm );
         i_ret = intf_UserLoginPassword( p_access, _("HTTP authentication"),
-                        _("Please enter a valid login name and a password."),
-                                                &psz_login, &psz_password );
+                                        psz_msg, &psz_login, &psz_password );
         if( i_ret == DIALOG_OK_YES )
         {
             msg_Dbg( p_access, "retrying with user=%s, pwd=%s",
                         psz_login, psz_password );
             if( psz_login ) p_sys->url.psz_username = strdup( psz_login );
             if( psz_password ) p_sys->url.psz_password = strdup( psz_password );
-            if( psz_login ) free( psz_login );
-            if( psz_password ) free( psz_password );
+            free( psz_login );
+            free( psz_password );
             goto connect;
         }
         else
         {
-            if( psz_login ) free( psz_login );
-            if( psz_password ) free( psz_password );
+            free( psz_login );
+            free( psz_password );
             goto error;
         }
     }
@@ -317,9 +408,6 @@ connect:
           p_sys->i_code == 303 || p_sys->i_code == 307 ) &&
         p_sys->psz_location && *p_sys->psz_location )
     {
-        playlist_t * p_playlist;
-        input_item_t *p_input_item;
-
         msg_Dbg( p_access, "redirection to %s", p_sys->psz_location );
 
         /* Do not accept redirection outside of HTTP works */
@@ -330,32 +418,24 @@ connect:
             msg_Err( p_access, "insecure redirection ignored" );
             goto error;
         }
-
-        /* Change the URI */
-        p_playlist = pl_Yield( p_access );
-        PL_LOCK;
-
-        p_input_item = p_playlist->status.p_item->p_input;
-        input_item_SetURI( p_input_item, p_sys->psz_location );
         free( p_access->psz_path );
         p_access->psz_path = strdup( p_sys->psz_location );
-
-        PL_UNLOCK;
-        pl_Release( p_access );
-
         /* Clean up current Open() run */
         vlc_UrlClean( &p_sys->url );
+        AuthReset( &p_sys->auth );
         vlc_UrlClean( &p_sys->proxy );
+        AuthReset( &p_sys->proxy_auth );
         free( p_sys->psz_mime );
         free( p_sys->psz_pragma );
         free( p_sys->psz_location );
         free( p_sys->psz_user_agent );
 
         Disconnect( p_access );
+        cookies = p_sys->cookies;
         free( p_sys );
 
         /* Do new Open() run with new data */
-        return Open( p_this );
+        return OpenWithCookies( p_this, cookies );
     }
 
     if( p_sys->b_mms )
@@ -438,7 +518,9 @@ static void Close( vlc_object_t *p_this )
     access_sys_t *p_sys = p_access->p_sys;
 
     vlc_UrlClean( &p_sys->url );
+    AuthReset( &p_sys->auth );
     vlc_UrlClean( &p_sys->proxy );
+    AuthReset( &p_sys->proxy_auth );
 
     free( p_sys->psz_mime );
     free( p_sys->psz_pragma );
@@ -451,6 +533,20 @@ static void Close( vlc_object_t *p_this )
     free( p_sys->psz_user_agent );
 
     Disconnect( p_access );
+
+    if( p_sys->cookies )
+    {
+        int i;
+        for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
+            free(vlc_array_item_at_index( p_sys->cookies, i ));
+        vlc_array_destroy( p_sys->cookies );
+    }
+
+#ifdef HAVE_ZLIB_H
+    inflateEnd( &p_sys->inflate.stream );
+    free( p_sys->inflate.p_buffer );
+#endif
+
     free( p_sys );
 }
 
@@ -515,7 +611,7 @@ static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
         }
     }
 
-    if( p_sys->b_continuous && i_len > p_sys->i_remaining )
+    if( p_sys->b_continuous && (ssize_t)i_len > p_sys->i_remaining )
     {
         /* Only ask for the remaining length */
         int i_new_len = p_sys->i_remaining;
@@ -558,7 +654,7 @@ static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
             {
                 /* read the empty line */
                 char *psz = net_Gets( VLC_OBJECT(p_access), p_sys->fd, p_sys->p_vs );
-                if( psz ) free( psz );
+                free( psz );
             }
         }
     }
@@ -656,8 +752,7 @@ static int ReadICYMeta( access_t *p_access )
         if( !p_sys->psz_icy_title ||
             strcmp( p_sys->psz_icy_title, &p[1] ) )
         {
-            if( p_sys->psz_icy_title )
-                free( p_sys->psz_icy_title );
+            free( p_sys->psz_icy_title );
             p_sys->psz_icy_title = strdup( &p[1] );
             p_access->info.i_update |= INPUT_UPDATE_META;
 
@@ -669,6 +764,42 @@ static int ReadICYMeta( access_t *p_access )
     return VLC_SUCCESS;
 }
 
+#ifdef HAVE_ZLIB_H
+static ssize_t ReadCompressed( access_t *p_access, uint8_t *p_buffer,
+                               size_t i_len )
+{
+    access_sys_t *p_sys = p_access->p_sys;
+
+    if( p_sys->b_compressed )
+    {
+        int i_ret;
+
+        if( !p_sys->inflate.p_buffer )
+            p_sys->inflate.p_buffer = malloc( 256 * 1024 );
+
+        if( p_sys->inflate.stream.avail_in == 0 )
+        {
+            ssize_t i_read = Read( p_access, p_sys->inflate.p_buffer + p_sys->inflate.stream.avail_in, 256 * 1024 );
+            if( i_read <= 0 ) return i_read;
+            p_sys->inflate.stream.next_in = p_sys->inflate.p_buffer;
+            p_sys->inflate.stream.avail_in = i_read;
+        }
+
+        p_sys->inflate.stream.avail_out = i_len;
+        p_sys->inflate.stream.next_out = p_buffer;
+
+        i_ret = inflate( &p_sys->inflate.stream, Z_SYNC_FLUSH );
+        msg_Warn( p_access, "inflate return value: %d, %s", i_ret, p_sys->inflate.stream.msg );
+
+        return i_len - p_sys->inflate.stream.avail_out;
+    }
+    else
+    {
+        return Read( p_access, p_buffer, i_len );
+    }
+}
+#endif
+
 /*****************************************************************************
  * Seek: close and re-open a connection at the right place
  *****************************************************************************/
@@ -861,6 +992,12 @@ static int Connect( access_t *p_access, int64_t i_tell )
                     i_status = 0;
 
                 free( psz );
+
+                if( p_access->b_die || p_access->b_error )
+                {
+                    Disconnect( p_access );
+                    return -1;
+                }
             }
             while( i_status );
         }
@@ -911,7 +1048,7 @@ static int Request( access_t *p_access, int64_t i_tell )
         {
             psz_path = "/";
         }
-        if( p_sys->url.i_port != 80)
+        if( p_sys->url.i_port != (pvs ? 443 : 80) )
         {
             net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs,
                         "GET %s HTTP/1.%d\r\nHost: %s:%d\r\n",
@@ -935,43 +1072,39 @@ static int Request( access_t *p_access, int64_t i_tell )
                     "Range: bytes="I64Fd"-\r\n", i_tell );
     }
 
-    /* Authentication */
-    if( p_sys->url.psz_username || p_sys->url.psz_password )
+    /* Cookies */
+    if( p_sys->cookies )
     {
-        char buf[strlen( p_sys->url.psz_username ?: "" )
-                  + strlen( p_sys->url.psz_password ?: "" ) + 2];
-        char *b64;
+        int i;
+        for( i = 0; i < vlc_array_count( p_sys->cookies ); i++ )
+        {
+            const char * cookie = vlc_array_item_at_index( p_sys->cookies, i );
+            char * psz_cookie_content = cookie_get_content( cookie );
+            char * psz_cookie_domain = cookie_get_domain( cookie );
 
-        snprintf( buf, sizeof( buf ), "%s:%s", p_sys->url.psz_username ?: "",
-                  p_sys->url.psz_password ?: "" );
-        b64 = vlc_b64_encode( buf );
+            assert( psz_cookie_content );
 
-        if( b64 != NULL )
-        {
-             net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs,
-                         "Authorization: Basic %s\r\n", b64 );
-             free( b64 );
+            /* FIXME: This is clearly not conforming to the rfc */
+            vlc_bool_t is_in_right_domain = (!psz_cookie_domain || strstr( p_sys->url.psz_host, psz_cookie_domain ));
+
+            if( is_in_right_domain )
+            {
+                msg_Dbg( p_access, "Sending Cookie %s", psz_cookie_content );
+                if( net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs, "Cookie: %s\r\n", psz_cookie_content ) < 0 )
+                    msg_Err( p_access, "failed to send Cookie" );
+            }
+            free( psz_cookie_content );
+            free( psz_cookie_domain );
         }
     }
 
+    /* Authentication */
+    if( p_sys->url.psz_username || p_sys->url.psz_password )
+        AuthReply( p_access, "", &p_sys->url, &p_sys->auth );
+
     /* Proxy Authentication */
     if( p_sys->proxy.psz_username || p_sys->proxy.psz_password )
-    {
-        char buf[strlen( p_sys->proxy.psz_username ?: "" )
-                  + strlen( p_sys->proxy.psz_password ?: "" )];
-        char *b64;
-
-        snprintf( buf, sizeof( buf ), "%s:%s", p_sys->proxy.psz_username ?: "",
-                  p_sys->proxy.psz_password ?: "" );
-        b64 = vlc_b64_encode( buf );
-
-        if( b64 != NULL)
-        {
-            net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs,
-                        "Proxy-Authorization: Basic %s\r\n", b64 );
-            free( b64 );
-        }
-    }
+        AuthReply( p_access, "Proxy-", &p_sys->proxy, &p_sys->proxy_auth );
 
     /* ICY meta data request */
     net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs, "Icy-MetaData: 1\r\n" );
@@ -1053,6 +1186,12 @@ static int Request( access_t *p_access, int64_t i_tell )
             goto error;
         }
 
+        if( p_access->b_die || p_access->b_error )
+        {
+            free( psz );
+            goto error;
+        }
+
         /* msg_Dbg( p_input, "Line=%s", psz ); */
         if( *psz == '\0' )
         {
@@ -1060,7 +1199,6 @@ static int Request( access_t *p_access, int64_t i_tell )
             break;
         }
 
-
         if( ( p = strchr( psz, ':' ) ) == NULL )
         {
             msg_Err( p_access, "malformed header line: %s", psz );
@@ -1096,13 +1234,15 @@ static int Request( access_t *p_access, int64_t i_tell )
 
                 if( p_sys->url.i_port == ( p_sys->b_ssl ? 443 : 80 ) )
                 {
-                    asprintf(&psz_new_loc, "http%s://%s%s", psz_http_ext,
-                             p_sys->url.psz_host, p);
+                    if( asprintf(&psz_new_loc, "http%s://%s%s", psz_http_ext,
+                                 p_sys->url.psz_host, p) < 0 )
+                        goto error;
                 }
                 else
                 {
-                    asprintf(&psz_new_loc, "http%s://%s:%d%s", psz_http_ext,
-                             p_sys->url.psz_host, p_sys->url.i_port, p);
+                    if( asprintf(&psz_new_loc, "http%s://%s:%d%s", psz_http_ext,
+                                 p_sys->url.psz_host, p_sys->url.i_port, p) < 0 )
+                        goto error;
                 }
             }
             else
@@ -1110,20 +1250,30 @@ static int Request( access_t *p_access, int64_t i_tell )
                 psz_new_loc = strdup( p );
             }
 
-            if( p_sys->psz_location ) free( p_sys->psz_location );
+            free( p_sys->psz_location );
             p_sys->psz_location = psz_new_loc;
         }
         else if( !strcasecmp( psz, "Content-Type" ) )
         {
-            if( p_sys->psz_mime ) free( p_sys->psz_mime );
+            free( p_sys->psz_mime );
             p_sys->psz_mime = strdup( p );
             msg_Dbg( p_access, "Content-Type: %s", p_sys->psz_mime );
         }
+        else if( !strcasecmp( psz, "Content-Encoding" ) )
+        {
+            msg_Dbg( p_access, "Content-Encoding: %s", p );
+            if( strcasecmp( p, "identity" ) )
+#ifdef HAVE_ZLIB_H
+                p_sys->b_compressed = VLC_TRUE;
+#else
+                msg_Warn( p_access, "Compressed content not supported. Rebuild with zlib support." );
+#endif
+        }
         else if( !strcasecmp( psz, "Pragma" ) )
         {
             if( !strcasecmp( psz, "Pragma: features" ) )
                 p_sys->b_mms = VLC_TRUE;
-            if( p_sys->psz_pragma ) free( p_sys->psz_pragma );
+            free( p_sys->psz_pragma );
             p_sys->psz_pragma = strdup( p );
             msg_Dbg( p_access, "Pragma: %s", p_sys->psz_pragma );
         }
@@ -1164,7 +1314,7 @@ static int Request( access_t *p_access, int64_t i_tell )
         }
         else if( !strcasecmp( psz, "Icy-Name" ) )
         {
-            if( p_sys->psz_icy_name ) free( p_sys->psz_icy_name );
+            free( p_sys->psz_icy_name );
             p_sys->psz_icy_name = strdup( p );
             msg_Dbg( p_access, "Icy-Name: %s", p_sys->psz_icy_name );
 
@@ -1174,7 +1324,7 @@ static int Request( access_t *p_access, int64_t i_tell )
         }
         else if( !strcasecmp( psz, "Icy-Genre" ) )
         {
-            if( p_sys->psz_icy_genre ) free( p_sys->psz_icy_genre );
+            free( p_sys->psz_icy_genre );
             p_sys->psz_icy_genre = strdup( p );
             msg_Dbg( p_access, "Icy-Genre: %s", p_sys->psz_icy_genre );
         }
@@ -1188,6 +1338,31 @@ static int Request( access_t *p_access, int64_t i_tell )
         {
             msg_Dbg( p_access, "Meta-Info: %s: %s", psz, p );
         }
+        else if( !strcasecmp( psz, "Set-Cookie" ) )
+        {
+            if( p_sys->cookies )
+            {
+                msg_Dbg( p_access, "Accepting Cookie: %s", p );
+                cookie_append( p_sys->cookies, strdup(p) );
+            }
+            else
+                msg_Dbg( p_access, "We have a Cookie we won't remember: %s", p );
+        }
+        else if( !strcasecmp( psz, "www-authenticate" ) )
+        {
+            msg_Dbg( p_access, "Authentication header: %s", p );
+            AuthParseHeader( p_access, p, &p_sys->auth );
+        }
+        else if( !strcasecmp( psz, "proxy-authenticate" ) )
+        {
+            msg_Dbg( p_access, "Proxy authentication header: %s", p );
+            AuthParseHeader( p_access, p, &p_sys->proxy_auth );
+        }
+        else if( !strcasecmp( psz, "authentication-info" ) )
+        {
+            msg_Dbg( p_access, "Authentication info: %s", p );
+            /* FIXME: use */
+        }
 
         free( psz );
     }
@@ -1218,3 +1393,433 @@ static void Disconnect( access_t *p_access )
     }
 
 }
+
+/*****************************************************************************
+ * Cookies (FIXME: we may want to rewrite that using a nice structure to hold
+ * them) (FIXME: only support the "domain=" param)
+ *****************************************************************************/
+
+/* Get the NAME=VALUE part of the Cookie */
+static char * cookie_get_content( const char * cookie )
+{
+    char * ret = strdup( cookie );
+    if( !ret ) return NULL;
+    char * str = ret;
+    /* Look for a ';' */
+    while( *str && *str != ';' ) str++;
+    /* Replace it by a end-char */
+    if( *str == ';' ) *str = 0;
+    return ret;
+}
+
+/* Get the domain where the cookie is stored */
+static char * cookie_get_domain( const char * cookie )
+{
+    const char * str = cookie;
+    static const char domain[] = "domain=";
+    if( !str )
+        return NULL;
+    /* Look for a ';' */
+    while( *str )
+    {
+        if( !strncmp( str, domain, sizeof(domain) - 1 /* minus \0 */ ) )
+        {
+            str += sizeof(domain) - 1 /* minus \0 */;
+            char * ret = strdup( str );
+            /* Now remove the next ';' if present */
+            char * ret_iter = ret;
+            while( *ret_iter && *ret_iter != ';' ) ret_iter++;
+            if( *ret_iter == ';' )
+                *ret_iter = 0;
+            return ret;
+        }
+        /* Go to next ';' field */
+        while( *str && *str != ';' ) str++;
+        if( *str == ';' ) str++;
+        /* skip blank */
+        while( *str && *str == ' ' ) str++;
+    }
+    return NULL;
+}
+
+/* Get NAME in the NAME=VALUE field */
+static char * cookie_get_name( const char * cookie )
+{
+    char * ret = cookie_get_content( cookie ); /* NAME=VALUE */
+    if( !ret ) return NULL;
+    char * str = ret;
+    while( *str && *str != '=' ) str++;
+    *str = 0;
+    return ret;
+}
+
+/* Add a cookie in cookies, checking to see how it should be added */
+static void cookie_append( vlc_array_t * cookies, char * cookie )
+{
+    int i;
+
+    if( !cookie )
+        return;
+
+    char * cookie_name = cookie_get_name( cookie );
+
+    /* Don't send invalid cookies */
+    if( !cookie_name )
+        return;
+
+    char * cookie_domain = cookie_get_domain( cookie );
+    for( i = 0; i < vlc_array_count( cookies ); i++ )
+    {
+        char * current_cookie = vlc_array_item_at_index( cookies, i );
+        char * current_cookie_name = cookie_get_name( current_cookie );
+        char * current_cookie_domain = cookie_get_domain( current_cookie );
+
+        assert( current_cookie_name );
+
+        vlc_bool_t is_domain_matching = ( cookie_domain && current_cookie_domain &&
+                                         !strcmp( cookie_domain, current_cookie_domain ) );
+
+        if( is_domain_matching && !strcmp( cookie_name, current_cookie_name )  )
+        {
+            /* Remove previous value for this cookie */
+            free( current_cookie );
+            vlc_array_remove( cookies, i );
+
+            /* Clean */
+            free( current_cookie_name );
+            free( current_cookie_domain );
+            break;
+        }
+        free( current_cookie_name );
+        free( current_cookie_domain );
+    }
+    free( cookie_name );
+    free( cookie_domain );
+    vlc_array_append( cookies, cookie );
+}
+
+/*****************************************************************************
+ * "RFC 2617: Basic and Digest Access Authentification" header parsing
+ *****************************************************************************/
+static char *AuthGetParam( const char *psz_header, const char *psz_param )
+{
+    char psz_what[strlen(psz_param)+3];
+    sprintf( psz_what, "%s=\"", psz_param );
+    psz_header = strstr( psz_header, psz_what );
+    if( psz_header )
+    {
+        const char *psz_end;
+        psz_header += strlen( psz_what );
+        psz_end = strchr( psz_header, '"' );
+        if( !psz_end )
+        {
+            psz_end = psz_header;
+            while( *psz_end ) psz_end++;
+        }
+        return strndup( psz_header, psz_end - psz_header );
+    }
+    else
+    {
+        return NULL;
+    }
+}
+
+static char *AuthGetParamNoQuotes( const char *psz_header, const char *psz_param )
+{
+    char psz_what[strlen(psz_param)+3];
+    sprintf( psz_what, "%s=", psz_param );
+    psz_header = strstr( psz_header, psz_what );
+    if( psz_header )
+    {
+        const char *psz_end;
+        psz_header += strlen( psz_what );
+        psz_end = strchr( psz_header, ',' );
+        if( !psz_end )
+        {
+            psz_end = psz_header;
+            while( *psz_end ) psz_end++;
+        }
+        return strndup( psz_header, psz_end - psz_header );
+    }
+    else
+    {
+        return NULL;
+    }
+}
+
+static void AuthParseHeader( access_t *p_access, const char *psz_header,
+                             http_auth_t *p_auth )
+{
+    /* FIXME: multiple auth methods can be listed (comma seperated) */
+
+    /* 2 Basic Authentication Scheme */
+    if( !strncasecmp( psz_header, "Basic ", strlen( "Basic " ) ) )
+    {
+        msg_Dbg( p_access, "Using Basic Authentication" );
+        psz_header += strlen( "Basic " );
+        p_auth->psz_realm = AuthGetParam( psz_header, "realm" );
+        if( !p_auth->psz_realm )
+            msg_Warn( p_access, "Basic Authentication: "
+                      "Mandatory 'realm' parameter is missing" );
+    }
+    /* 3 Digest Access Authentication Scheme */
+    else if( !strncasecmp( psz_header, "Digest ", strlen( "Digest " ) ) )
+    {
+        msg_Dbg( p_access, "Using Digest Access Authentication" );
+        if( p_auth->psz_nonce ) return; /* FIXME */
+        psz_header += strlen( "Digest " );
+        p_auth->psz_realm = AuthGetParam( psz_header, "realm" );
+        p_auth->psz_domain = AuthGetParam( psz_header, "domain" );
+        p_auth->psz_nonce = AuthGetParam( psz_header, "nonce" );
+        p_auth->psz_opaque = AuthGetParam( psz_header, "opaque" );
+        p_auth->psz_stale = AuthGetParamNoQuotes( psz_header, "stale" );
+        p_auth->psz_algorithm = AuthGetParamNoQuotes( psz_header, "algorithm" );
+        p_auth->psz_qop = AuthGetParam( psz_header, "qop" );
+        p_auth->i_nonce = 0;
+        /* printf("realm: %s\ndomain: %s\nnonce: %s\nopaque: %s\nstale: %s\nalgorithm: %s\nqop: %s\n",p_auth->psz_realm,p_auth->psz_domain,p_auth->psz_nonce,p_auth->psz_opaque,p_auth->psz_stale,p_auth->psz_algorithm,p_auth->psz_qop); */
+        if( !p_auth->psz_realm )
+            msg_Warn( p_access, "Digest Access Authentication: "
+                      "Mandatory 'realm' parameter is missing" );
+        if( !p_auth->psz_nonce )
+            msg_Warn( p_access, "Digest Access Authentication: "
+                      "Mandatory 'nonce' parameter is missing" );
+        if( p_auth->psz_qop ) /* FIXME */
+        {
+            char *psz_tmp = strchr( p_auth->psz_qop, ',' );
+            if( psz_tmp ) *psz_tmp = '\0';
+        }
+    }
+    else
+    {
+        const char *psz_end = strchr( psz_header, ' ' );
+        if( !psz_end )
+        {
+            psz_end = psz_header;
+            while( *psz_end ) psz_end++;
+        }
+        msg_Warn( p_access, "Unknown authentication scheme: '%*s'",
+                  psz_end - psz_header, psz_header );
+    }
+}
+
+static char *AuthAlgoMD5( const char *psz_data )
+{
+    struct md5_s md5;
+    char *psz_md5;
+    InitMD5( &md5 );
+    AddMD5( &md5, psz_data, strlen( psz_data ) );
+    EndMD5( &md5 );
+    psz_md5 = psz_md5_hash( &md5 );
+    return psz_md5;
+}
+
+static void AuthReply( access_t *p_access, const char *psz_prefix,
+                       vlc_url_t *p_url, http_auth_t *p_auth )
+{
+    access_sys_t *p_sys = p_access->p_sys;
+    v_socket_t     *pvs = p_sys->p_vs;
+
+    const char *psz_username = p_url->psz_username ?: "";
+    const char *psz_password = p_url->psz_password ?: "";
+
+    if( p_auth->psz_nonce )
+    {
+        /* Digest Access Authentication */
+        char *psz_response = NULL;
+        char *psz_A1 = NULL;
+        char *psz_A2 = NULL;
+        char *psz_secret = NULL;
+        char *psz_data = NULL;
+        char * (*pf_algo)( const char * );
+
+        if(    p_auth->psz_algorithm == NULL
+            || !strcmp( p_auth->psz_algorithm, "MD5" )
+            || !strcmp( p_auth->psz_algorithm, "MD5-sess" ) )
+        {
+            pf_algo = AuthAlgoMD5;
+        }
+        else
+        {
+            msg_Err( p_access, "Digest Access Authentication: "
+                     "Unknown algorithm '%s'", p_auth->psz_algorithm );
+        }
+        if( !pf_algo ) return;
+
+        if( p_auth->psz_qop )
+        {
+            /* FIXME: needs to be really random to prevent man in the middle
+             * attacks */
+            free( p_auth->psz_cnonce );
+            p_auth->psz_cnonce = strdup( "Some random string FIXME" );
+        }
+        p_auth->i_nonce ++;
+
+        if( p_auth->psz_algorithm && !strcmp( p_auth->psz_algorithm, "MD5-sess" ) )
+        {
+            if( !p_auth->psz_A1 )
+            {
+                char *psz_tmp = NULL;
+                if( asprintf( &psz_A1, "%s:%s:%s", psz_username,
+                              p_auth->psz_realm, psz_password ) < 0 )
+                    goto error;
+                psz_tmp = pf_algo( psz_A1 );
+                free( psz_A1 ); psz_A1 = NULL;
+                if( !psz_tmp ) goto error;
+                if( asprintf( &psz_A1, "%s:%s:%s", psz_tmp, p_auth->psz_nonce,
+                    p_auth->psz_cnonce ) < 0 )
+                {
+                    free( psz_tmp );
+                    goto error;
+                }
+                p_auth->psz_A1 = strdup( psz_A1 );
+            }
+            else
+            {
+                psz_A1 = strdup( p_auth->psz_A1 );
+            }
+        }
+        else
+        {
+            if( asprintf( &psz_A1, "%s:%s:%s", psz_username, p_auth->psz_realm,
+                          psz_password ) < 0 ) goto error;
+        }
+
+        if( !p_auth->psz_qop || !strcmp( p_auth->psz_qop, "auth" ) )
+        {
+            if( asprintf( &psz_A2, "%s:%s", "GET", p_url->psz_path ?: "/" )
+                < 0 ) goto error;
+        }
+        else
+        {
+            char *psz_tmp = pf_algo( "FIXME entity-body" ); /* FIXME */
+            if( asprintf( &psz_A2, "%s:%s:%s", "GET", p_url->psz_path ?: "/",
+                psz_tmp ) < 0 )
+            {
+                free( psz_tmp );
+                goto error;
+            }
+            free( psz_tmp );
+        }
+
+        psz_secret = pf_algo( psz_A1 );
+
+        if( p_auth->psz_qop
+            && ( !strcmp( p_auth->psz_qop, "auth" )
+                 || !strcmp( p_auth->psz_qop, "auth-int" ) ) )
+        {
+            char *psz_tmp = pf_algo( psz_A2 );
+            if( !psz_tmp ) goto error;
+            if( asprintf( &psz_data, "%s:%08x:%s:%s:%s",
+                          p_auth->psz_nonce, p_auth->i_nonce,
+                          p_auth->psz_cnonce, p_auth->psz_qop, psz_tmp ) < 0 )
+            {
+                free( psz_tmp );
+                goto error;
+            }
+            free( psz_tmp );
+        }
+        else
+        {
+            char *psz_tmp = pf_algo( psz_A2 );
+            if( !psz_tmp ) goto error;
+            if( asprintf( &psz_data, "%s:%s", p_auth->psz_nonce, psz_tmp ) < 0 )
+            {
+                free( psz_tmp );
+                goto error;
+            }
+            free( psz_tmp );
+        }
+
+        if( psz_secret && psz_data )
+        {
+            char *psz_tmp = NULL;
+            if( asprintf( &psz_tmp, "%s:%s", psz_secret, psz_data ) < 0 )
+                goto error;
+            psz_response = pf_algo( psz_tmp );
+            free( psz_tmp );
+            if( !psz_response )
+                goto error;
+        }
+        else
+        {
+            goto error;
+        }
+
+        net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs,
+                    "%sAuthorization: Digest "
+                    /* Mandatory parameters */
+                    "username=\"%s\", "
+                    "realm=\"%s\", "
+                    "nonce=\"%s\", "
+                    "uri=\"%s\", "
+                    "response=\"%s\", "
+                    /* Optional parameters */
+                    "%s%s%s" /* algorithm */
+                    "%s%s%s" /* cnonce */
+                    "%s%s%s" /* opaque */
+                    "%s%s%s" /* message qop */
+                    "%s%08x%s" /* nonce count */
+                    "\r\n",
+                    /* Mandatory parameters */
+                    psz_prefix,
+                    psz_username,
+                    p_auth->psz_realm,
+                    p_auth->psz_nonce,
+                    p_url->psz_path ?: "/",
+                    psz_response,
+                    /* Optional parameters */
+                    p_auth->psz_algorithm ? "algorithm=\"" : "",
+                    p_auth->psz_algorithm ?: "",
+                    p_auth->psz_algorithm ? "\", " : "",
+                    p_auth->psz_cnonce ? "cnonce=\"" : "",
+                    p_auth->psz_cnonce ?: "",
+                    p_auth->psz_cnonce ? "\", " : "",
+                    p_auth->psz_opaque ? "opaque=\"" : "",
+                    p_auth->psz_opaque ?: "",
+                    p_auth->psz_opaque ? "\", " : "",
+                    p_auth->psz_qop ? "qop=\"" : "",
+                    p_auth->psz_qop ?: "",
+                    p_auth->psz_qop ? "\", " : "",
+                    p_auth->i_nonce ? "nc=\"" : "uglyhack=\"", /* Will be parsed as an unhandled extension */
+                    p_auth->i_nonce,
+                    p_auth->i_nonce ? "\"" : "\""
+                  );
+
+    error:
+        free( psz_response );
+        free( psz_A1 );
+        free( psz_A2 );
+        free( psz_secret );
+        free( psz_data );
+    }
+    else
+    {
+        /* Basic Access Authentication */
+        char buf[strlen( psz_username ) + strlen( psz_password ) + 2];
+        char *b64;
+
+        snprintf( buf, sizeof( buf ), "%s:%s", psz_username, psz_password );
+        b64 = vlc_b64_encode( buf );
+
+        if( b64 != NULL )
+        {
+             net_Printf( VLC_OBJECT(p_access), p_sys->fd, pvs,
+                         "%sAuthorization: Basic %s\r\n", psz_prefix, b64 );
+             free( b64 );
+        }
+    }
+}
+
+static void AuthReset( http_auth_t *p_auth )
+{
+    FREENULL( p_auth->psz_realm );
+    FREENULL( p_auth->psz_domain );
+    FREENULL( p_auth->psz_nonce );
+    FREENULL( p_auth->psz_opaque );
+    FREENULL( p_auth->psz_stale );
+    FREENULL( p_auth->psz_algorithm );
+    FREENULL( p_auth->psz_qop );
+    p_auth->i_nonce = 0;
+    FREENULL( p_auth->psz_cnonce );
+    FREENULL( p_auth->psz_A1 );
+}