Index: lib/Makefile
===================================================================
--- lib/Makefile	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/Makefile	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -13,5 +13,5 @@
 
 # [SH] Program variables
-objects = arc.o base64.o $(DES) $(EVENT_HANDLER) ftutil.o http_client.o ini.o md5.o misc.o oauth.o proxy.o sha1.o $(SSL_CLIENT) url.o xmltree.o
+objects = arc.o base64.o $(DES) $(EVENT_HANDLER) ftutil.o http_client.o ini.o md5.o misc.o oauth.o oauth2.o proxy.o sha1.o $(SSL_CLIENT) url.o xmltree.o
 
 LFLAGS += -r
Index: lib/md5.c
===================================================================
--- lib/md5.c	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/md5.c	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -24,4 +24,5 @@
 #include <sys/types.h>
 #include <string.h>		/* for memcpy() */
+#include <stdio.h>
 #include "md5.h"
 
@@ -160,4 +161,14 @@
 	memcpy(digest, ctx->buf, 16);
 	memset(ctx, 0, sizeof(ctx));	/* In case it's sensitive */
+}
+
+void md5_finish_ascii(struct MD5Context *context, char *ascii)
+{
+	md5_byte_t bin[16];
+	int i;
+	
+	md5_finish(context, bin);
+	for (i = 0; i < 16; i ++)
+		sprintf(ascii + i * 2, "%02x", bin[i]);
 }
 
Index: lib/md5.h
===================================================================
--- lib/md5.h	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/md5.h	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -43,4 +43,5 @@
 G_MODULE_EXPORT void md5_append(struct MD5Context *context, const md5_byte_t *buf, unsigned int len);
 G_MODULE_EXPORT void md5_finish(struct MD5Context *context, md5_byte_t digest[16]);
+G_MODULE_EXPORT void md5_finish_ascii(struct MD5Context *context, char *ascii);
 
 #endif
Index: lib/misc.c
===================================================================
--- lib/misc.c	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/misc.c	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -729,2 +729,57 @@
 	return cmd;
 }
+
+char *get_rfc822_header( char *text, char *header, int len )
+{
+	int hlen = strlen( header ), i;
+	char *ret;
+	
+	if( text == NULL )
+		return NULL;
+	
+	if( len == 0 )
+		len = strlen( text );
+	
+	i = 0;
+	while( ( i + hlen ) < len )
+	{
+		/* Maybe this is a bit over-commented, but I just hate this part... */
+		if( g_strncasecmp( text + i, header, hlen ) == 0 )
+		{
+			/* Skip to the (probable) end of the header */
+			i += hlen;
+			
+			/* Find the first non-[: \t] character */
+			while( i < len && ( text[i] == ':' || text[i] == ' ' || text[i] == '\t' ) ) i ++;
+			
+			/* Make sure we're still inside the string */
+			if( i >= len ) return( NULL );
+			
+			/* Save the position */
+			ret = text + i;
+			
+			/* Search for the end of this line */
+			while( i < len && text[i] != '\r' && text[i] != '\n' ) i ++;
+			
+			/* Make sure we're still inside the string */
+			if( i >= len ) return( NULL );
+			
+			/* Copy the found data */
+			return( g_strndup( ret, text + i - ret ) );
+		}
+		
+		/* This wasn't the header we were looking for, skip to the next line. */
+		while( i < len && ( text[i] != '\r' && text[i] != '\n' ) ) i ++;
+		while( i < len && ( text[i] == '\r' || text[i] == '\n' ) ) i ++;
+		
+		/* End of headers? */
+		if( ( i >= 4 && strncmp( text + i - 4, "\r\n\r\n", 4 ) == 0 ) ||
+		    ( i >= 2 && ( strncmp( text + i - 2, "\n\n", 2 ) == 0 ||   
+		                  strncmp( text + i - 2, "\r\r", 2 ) == 0 ) ) )
+		{
+			break;
+		}
+	}
+	
+	return NULL;
+}
Index: lib/misc.h
===================================================================
--- lib/misc.h	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/misc.h	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -65,10 +65,8 @@
 
 G_MODULE_EXPORT char *word_wrap( const char *msg, int line_len );
-
 G_MODULE_EXPORT gboolean ssl_sockerr_again( void *ssl );
-
 G_MODULE_EXPORT int md5_verify_password( char *password, char *hash );
-
 G_MODULE_EXPORT char **split_command_parts( char *command );
+G_MODULE_EXPORT char *get_rfc822_header( char *text, char *header, int len );
 
 #endif
Index: lib/oauth.c
===================================================================
--- lib/oauth.c	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/oauth.c	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -38,45 +38,17 @@
                          const char *params, struct oauth_info *oi )
 {
-	sha1_state_t sha1;
 	uint8_t hash[sha1_hash_size];
-	uint8_t key[HMAC_BLOCK_SIZE+1];
+	GString *payload = g_string_new( "" );
+	char *key;
 	char *s;
-	int i;
-	
-	/* Create K. If our current key is >64 chars we have to hash it,
-	   otherwise just pad. */
-	memset( key, 0, HMAC_BLOCK_SIZE );
-	i = strlen( oi->sp->consumer_secret ) + 1 + ( oi->token_secret ? strlen( oi->token_secret ) : 0 );
-	if( i > HMAC_BLOCK_SIZE )
-	{
-		sha1_init( &sha1 );
-		sha1_append( &sha1, (uint8_t*) oi->sp->consumer_secret, strlen( oi->sp->consumer_secret ) );
-		sha1_append( &sha1, (uint8_t*) "&", 1 );
-		if( oi->token_secret )
-			sha1_append( &sha1, (uint8_t*) oi->token_secret, strlen( oi->token_secret ) );
-		sha1_finish( &sha1, key );
-	}
-	else
-	{
-		g_snprintf( (gchar*) key, HMAC_BLOCK_SIZE + 1, "%s&%s",
-		            oi->sp->consumer_secret, oi->token_secret ? oi->token_secret : "" );
-	}
-	
-	/* Inner part: H(K XOR 0x36, text) */
-	sha1_init( &sha1 );
-	
-	for( i = 0; i < HMAC_BLOCK_SIZE; i ++ )
-		key[i] ^= 0x36;
-	sha1_append( &sha1, key, HMAC_BLOCK_SIZE );
-	
-	/* OAuth: text = method&url&params, all http_encoded. */
-	sha1_append( &sha1, (const uint8_t*) method, strlen( method ) );
-	sha1_append( &sha1, (const uint8_t*) "&", 1 );
+	
+	key = g_strdup_printf( "%s&%s", oi->sp->consumer_secret, oi->token_secret ? oi->token_secret : "" );
+	
+	g_string_append_printf( payload, "%s&", method );
 	
 	s = g_new0( char, strlen( url ) * 3 + 1 );
 	strcpy( s, url );
 	http_encode( s );
-	sha1_append( &sha1, (const uint8_t*) s, strlen( s ) );
-	sha1_append( &sha1, (const uint8_t*) "&", 1 );
+	g_string_append_printf( payload, "%s&", s );
 	g_free( s );
 	
@@ -84,16 +56,11 @@
 	strcpy( s, params );
 	http_encode( s );
-	sha1_append( &sha1, (const uint8_t*) s, strlen( s ) );
-	g_free( s );
-	
-	sha1_finish( &sha1, hash );
-	
-	/* Final result: H(K XOR 0x5C, inner stuff) */
-	sha1_init( &sha1 );
-	for( i = 0; i < HMAC_BLOCK_SIZE; i ++ )
-		key[i] ^= 0x36 ^ 0x5c;
-	sha1_append( &sha1, key, HMAC_BLOCK_SIZE );
-	sha1_append( &sha1, hash, sha1_hash_size );
-	sha1_finish( &sha1, hash );
+	g_string_append( payload, s );
+	g_free( s );
+	
+	sha1_hmac( key, 0, payload->str, 0, hash );
+	
+	g_free( key );
+	g_string_free( payload, TRUE );
 	
 	/* base64_encode + HTTP escape it (both consumers 
@@ -122,4 +89,7 @@
 	char *item;
 	
+	if( !key || !value )
+		return;
+	
 	item = g_strdup_printf( "%s=%s", key, value );
 	*params = g_slist_insert_sorted( *params, item, (GCompareFunc) strcmp );
@@ -130,4 +100,7 @@
 	int key_len = strlen( key );
 	GSList *l, *n;
+	
+	if( params == NULL )
+		return;
 	
 	for( l = *params; l; l = n )
@@ -155,4 +128,7 @@
 	GSList *l;
 	
+	if( params == NULL )
+		return NULL;
+	
 	for( l = *params; l; l = l->next )
 	{
@@ -165,5 +141,5 @@
 }
 
-static void oauth_params_parse( GSList **params, char *in )
+void oauth_params_parse( GSList **params, char *in )
 {
 	char *amp, *eq, *s;
@@ -333,4 +309,5 @@
 		oauth_params_parse( &params, req->reply_body );
 		st->request_token = g_strdup( oauth_params_get( &params, "oauth_token" ) );
+		st->token_secret = g_strdup( oauth_params_get( &params, "oauth_token_secret" ) );
 		oauth_params_free( &params );
 	}
@@ -362,4 +339,5 @@
 		oauth_params_parse( &st->params, req->reply_body );
 		st->token = g_strdup( oauth_params_get( &st->params, "oauth_token" ) );
+		g_free( st->token_secret );
 		st->token_secret = g_strdup( oauth_params_get( &st->params, "oauth_token_secret" ) );
 	}
Index: lib/oauth.h
===================================================================
--- lib/oauth.h	(revision 5513f3e56a45d4a227bfc7d01210fdded516458c)
+++ lib/oauth.h	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -92,3 +92,8 @@
 
 /* For reading misc. data. */
+void oauth_params_add( GSList **params, const char *key, const char *value );
+void oauth_params_parse( GSList **params, char *in );
+void oauth_params_free( GSList **params );
+char *oauth_params_string( GSList *params );
+void oauth_params_set( GSList **params, const char *key, const char *value );
 const char *oauth_params_get( GSList **params, const char *key );
Index: lib/oauth2.c
===================================================================
--- lib/oauth2.c	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
+++ lib/oauth2.c	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -0,0 +1,195 @@
+/***************************************************************************\
+*                                                                           *
+*  BitlBee - An IRC to IM gateway                                           *
+*  Simple OAuth client (consumer) implementation.                           *
+*                                                                           *
+*  Copyright 2010-2011 Wilmer van der Gaast <wilmer@gaast.net>              *
+*                                                                           *
+*  This program is free software; you can redistribute it and/or modify     *
+*  it under the terms of the GNU General Public License as published by     *
+*  the Free Software Foundation; either version 2 of the License, or        *
+*  (at your option) any later version.                                      *
+*                                                                           *
+*  This program is distributed in the hope that it will be useful,          *
+*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
+*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
+*  GNU General Public License for more details.                             *
+*                                                                           *
+*  You should have received a copy of the GNU General Public License along  *
+*  with this program; if not, write to the Free Software Foundation, Inc.,  *
+*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
+*                                                                           *
+\***************************************************************************/
+
+#include <glib.h>
+#include "http_client.h"
+#include "oauth2.h"
+#include "oauth.h"
+#include "url.h"
+
+char *oauth2_url( const struct oauth2_service *sp )
+{
+	return g_strconcat( sp->auth_url,
+	                    "?scope=", sp->scope,
+	                    "&response_type=code"
+	                    "&redirect_uri=", sp->redirect_url, 
+	                    "&client_id=", sp->consumer_key,
+	                    NULL );
+}
+
+struct oauth2_access_token_data
+{
+	oauth2_token_callback func;
+	gpointer data;
+};
+
+static char *oauth2_json_dumb_get( const char *json, const char *key );
+static void oauth2_access_token_done( struct http_request *req );
+
+int oauth2_access_token( const struct oauth2_service *sp,
+                         const char *auth_type, const char *auth,
+                         oauth2_token_callback func, gpointer data )
+{
+	GSList *args = NULL;
+	char *args_s, *s;
+	url_t url_p;
+	struct http_request *req;
+	struct oauth2_access_token_data *cb_data;
+	
+	if( !url_set( &url_p, sp->token_url ) )
+		return 0;
+	
+	oauth_params_add( &args, "client_id", sp->consumer_key );
+	oauth_params_add( &args, "client_secret", sp->consumer_secret );
+	oauth_params_add( &args, "grant_type", auth_type );
+	if( strcmp( auth_type, OAUTH2_AUTH_CODE ) == 0 )
+	{
+		oauth_params_add( &args, "redirect_uri", sp->redirect_url );
+		oauth_params_add( &args, "code", auth );
+	}
+	else
+	{
+		oauth_params_add( &args, "refresh_token", auth );
+	}
+	args_s = oauth_params_string( args );
+	oauth_params_free( &args );
+	
+	s = g_strdup_printf( "POST %s HTTP/1.0\r\n"
+	                     "Host: %s\r\n"
+	                     "Content-Type: application/x-www-form-urlencoded\r\n"
+	                     "Content-Length: %zd\r\n"
+	                     "Connection: close\r\n"
+	                     "\r\n"
+	                     "%s", url_p.file, url_p.host, strlen( args_s ), args_s );
+	g_free( args_s );
+	
+	cb_data = g_new0( struct oauth2_access_token_data, 1 );
+	cb_data->func = func;
+	cb_data->data = data;
+	
+	req = http_dorequest( url_p.host, url_p.port, url_p.proto == PROTO_HTTPS,
+	                      s, oauth2_access_token_done, cb_data );
+	
+	g_free( s );
+	
+	if( req == NULL )
+		g_free( cb_data );
+	
+	return req != NULL;
+}
+
+static void oauth2_access_token_done( struct http_request *req )
+{
+	struct oauth2_access_token_data *cb_data = req->data;
+	char *atoken = NULL, *rtoken = NULL;
+	const char *content_type;
+	
+	if( getenv( "BITLBEE_DEBUG" ) && req->reply_body )
+		printf( "%s\n", req->reply_body );
+	
+	content_type = get_rfc822_header( req->reply_headers, "Content-Type", 0 );
+	
+	if( req->status_code != 200 )
+	{
+	}
+	else if( content_type && strstr( content_type, "application/json" ) )
+	{
+		atoken = oauth2_json_dumb_get( req->reply_body, "access_token" );
+		rtoken = oauth2_json_dumb_get( req->reply_body, "refresh_token" );
+		if( getenv( "BITLBEE_DEBUG" ) )
+			printf( "Extracted atoken=%s rtoken=%s\n", atoken, rtoken );
+	}
+	else
+	{
+		/* Facebook use their own odd format here, seems to be URL-encoded. */
+		GSList *p_in = NULL;
+		
+		oauth_params_parse( &p_in, req->reply_body );
+		atoken = g_strdup( oauth_params_get( &p_in, "access_token" ) );
+		rtoken = g_strdup( oauth_params_get( &p_in, "refresh_token" ) );
+		oauth_params_free( &p_in );
+	}
+	cb_data->func( cb_data->data, atoken, rtoken );
+	g_free( atoken );
+	g_free( rtoken );
+	g_free( cb_data );
+}
+
+/* Super dumb. I absolutely refuse to use/add a complete json parser library
+   (adding a new dependency to BitlBee for the first time in.. 6 years?) just
+   to parse 100 bytes of data. So I have to do my own parsing because OAuth2
+   dropped support for XML. (GRRR!) This is very dumb and for example won't
+   work for integer values, nor will it strip/handle backslashes. */
+static char *oauth2_json_dumb_get( const char *json, const char *key )
+{
+	int is_key; /* 1 == reading key, 0 == reading value */
+	int found_key = 0;
+		
+	while( json && *json )
+	{
+		/* Grab strings and see if they're what we're looking for. */
+		if( *json == '"' || *json == '\'' )
+		{
+			char q = *json;
+			const char *str_start;
+			json ++;
+			str_start = json;
+			
+			while( *json )
+			{
+				/* \' and \" are not string terminators. */
+				if( *json == '\\' && json[1] == q )
+					json ++;
+				/* But without a \ it is. */
+				else if( *json == q )
+					break;
+				json ++;
+			}
+			if( *json == '\0' )
+				return NULL;
+			
+			if( is_key && strncmp( str_start, key, strlen( key ) ) == 0 )
+			{
+				found_key = 1;
+			}
+			else if( !is_key && found_key )
+			{
+				char *ret = g_memdup( str_start, json - str_start + 1 );
+				ret[json-str_start] = '\0';
+				return ret;
+			}
+			
+		}
+		else if( *json == '{' || *json == ',' )
+		{
+			found_key = 0;
+			is_key = 1;
+		}
+		else if( *json == ':' )
+			is_key = 0;
+		
+		json ++;
+	}
+	
+	return NULL;
+}
Index: lib/oauth2.h
===================================================================
--- lib/oauth2.h	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
+++ lib/oauth2.h	(revision 34ded90e19635c7ebf2afd184f36b03abc879bec)
@@ -0,0 +1,50 @@
+/***************************************************************************\
+*                                                                           *
+*  BitlBee - An IRC to IM gateway                                           *
+*  Simple OAuth2 client (consumer) implementation.                          *
+*                                                                           *
+*  Copyright 2010-2011 Wilmer van der Gaast <wilmer@gaast.net>              *
+*                                                                           *
+*  This program is free software; you can redistribute it and/or modify     *
+*  it under the terms of the GNU General Public License as published by     *
+*  the Free Software Foundation; either version 2 of the License, or        *
+*  (at your option) any later version.                                      *
+*                                                                           *
+*  This program is distributed in the hope that it will be useful,          *
+*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
+*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
+*  GNU General Public License for more details.                             *
+*                                                                           *
+*  You should have received a copy of the GNU General Public License along  *
+*  with this program; if not, write to the Free Software Foundation, Inc.,  *
+*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
+*                                                                           *
+\***************************************************************************/
+
+/* Implementation mostly based on my experience with writing the previous OAuth
+   module, and from http://code.google.com/apis/accounts/docs/OAuth2.html . */
+
+typedef void (*oauth2_token_callback)( gpointer data, const char *atoken, const char *rtoken );
+
+struct oauth2_service
+{
+	char *auth_url;
+	char *token_url;
+	char *redirect_url;
+	char *scope;
+	char *consumer_key;
+	char *consumer_secret;
+};
+
+#define OAUTH2_AUTH_CODE "authorization_code"
+#define OAUTH2_AUTH_REFRESH "refresh_token"
+
+/* Generate a URL the user should open in his/her browser to get an
+   authorization code. */
+char *oauth2_url( const struct oauth2_service *sp );
+
+/* Exchanges an auth code or refresh token for an access token.
+   auth_type is one of the two OAUTH2_AUTH_.. constants above. */
+int oauth2_access_token( const struct oauth2_service *sp,
+                         const char *auth_type, const char *auth,
+                         oauth2_token_callback func, gpointer data );
