Index: lib/oauth.h
===================================================================
--- lib/oauth.h	(revision 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ lib/oauth.h	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -92,3 +92,6 @@
 
 /* For reading misc. data. */
+void oauth_params_add( GSList **params, const char *key, const char *value );
+void oauth_params_free( GSList **params );
+char *oauth_params_string( GSList *params );
 const char *oauth_params_get( GSList **params, const char *key );
Index: lib/oauth2.c
===================================================================
--- lib/oauth2.c	(revision 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ lib/oauth2.c	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -23,5 +23,8 @@
 
 #include <glib.h>
+#include "http_client.h"
 #include "oauth2.h"
+#include "oauth.h"
+#include "url.h"
 
 struct oauth2_service oauth2_service_google =
@@ -41,2 +44,138 @@
 	                    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->base_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", "urn:ietf:wg:oauth:2.0:oob" );
+		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%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, "token", 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;
+	
+	if( req->status_code == 200 )
+	{
+		atoken = oauth2_json_dumb_get( req->reply_body, "access_token" );
+		rtoken = oauth2_json_dumb_get( req->reply_body, "refresh_token" );
+	}
+	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 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ lib/oauth2.h	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -2,5 +2,5 @@
 *                                                                           *
 *  BitlBee - An IRC to IM gateway                                           *
-*  Simple OAuth client (consumer) implementation.                           *
+*  Simple OAuth2 client (consumer) implementation.                          *
 *                                                                           *
 *  Copyright 2010-2011 Wilmer van der Gaast <wilmer@gaast.net>              *
@@ -22,26 +22,8 @@
 \***************************************************************************/
 
-struct oauth2_info;
+/* Implementation mostly based on my experience with writing the previous OAuth
+   module, and from http://code.google.com/apis/accounts/docs/OAuth2.html . */
 
-/* Callback function called twice during the access token request process.
-   Return FALSE if something broke and the process must be aborted. */
-typedef gboolean (*oauth_cb)( struct oauth2_info * );
-
-struct oauth2_info
-{
-	const struct oauth_service *sp;
-	
-	oauth_cb func;
-	void *data;
-	
-	struct http_request *http;
-	
-//	char *auth_url;
-//	char *request_token;
-	
-//	char *token;
-//	char *token_secret;
-//	GSList *params;
-};
+typedef void (*oauth2_token_callback)( gpointer data, const char *atoken, const char *rtoken );
 
 struct oauth2_service
@@ -52,18 +34,18 @@
 };
 
+/* Currently suitable for authenticating to Google Talk only, and only for
+   accounts that have 2-factor authorization enabled. */
 extern struct oauth2_service oauth2_service_google;
 
-/* http://oauth.net/core/1.0a/#auth_step1 (section 6.1) 
-   Request an initial anonymous token which can be used to construct an
-   authorization URL for the user. This is passed to the callback function
-   in a struct oauth2_info. */
+#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, const char *scope );
 
-/* http://oauth.net/core/1.0a/#auth_step3 (section 6.3)
-   The user gets a PIN or so which we now exchange for the final access
-   token. This is passed to the callback function in the same
-   struct oauth2_info. */
-gboolean oauth2_access_token( const char *pin, struct oauth2_info *st );
-
-/* Shouldn't normally be required unless the process is aborted by the user. */
-void oauth2_info_free( struct oauth2_info *info );
+/* 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 );
Index: protocols/jabber/jabber.c
===================================================================
--- protocols/jabber/jabber.c	(revision 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ protocols/jabber/jabber.c	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -98,7 +98,5 @@
 	struct im_connection *ic = imcb_new( acc );
 	struct jabber_data *jd = g_new0( struct jabber_data, 1 );
-	struct ns_srv_reply **srvl = NULL, *srv = NULL;
-	char *connect_to, *s;
-	int i;
+	char *s;
 	
 	/* For now this is needed in the _connected() handlers if using
@@ -139,4 +137,28 @@
 	jd->node_cache = g_hash_table_new_full( g_str_hash, g_str_equal, NULL, jabber_cache_entry_free );
 	jd->buddies = g_hash_table_new( g_str_hash, g_str_equal );
+	
+	if( set_getbool( &acc->set, "oauth" ) )
+	{
+		/* For the first login with OAuth, we have to authenticate via the browser.
+		   For subsequent logins, exchange the refresh token for a valid access
+		   token (even though the last one maybe didn't expire yet). */
+		if( strncmp( acc->pass, "refresh_token=", 14 ) != 0 )
+			sasl_oauth2_init( ic );
+		else
+			sasl_oauth2_refresh( ic, acc->pass + 14 );
+	}
+	else
+		jabber_connect( ic );
+}
+
+/* Separate this from jabber_login() so we can do OAuth first if necessary.
+   Putting this in io.c would probably be more correct. */
+void jabber_connect( struct im_connection *ic )
+{
+	account_t *acc = ic->acc;
+	struct jabber_data *jd = ic->proto_data;
+	int i;
+	char *connect_to;
+	struct ns_srv_reply **srvl = NULL, *srv = NULL;
 	
 	/* Figure out the hostname to connect to. */
@@ -280,4 +302,17 @@
 	if( g_strcasecmp( who, JABBER_XMLCONSOLE_HANDLE ) == 0 )
 		return jabber_write( ic, message, strlen( message ) );
+	
+	if( g_strcasecmp( who, "jabber_oauth" ) == 0 )
+	{
+		if( sasl_oauth2_get_refresh_token( ic, message ) )
+		{
+			return 1;
+		}
+		else
+		{
+			imcb_error( ic, "OAuth failure" );
+			imc_logout( ic, TRUE );
+		}
+	}
 	
 	if( ( s = strchr( who, '=' ) ) && jabber_chat_by_jid( ic, s + 1 ) )
Index: protocols/jabber/jabber.h
===================================================================
--- protocols/jabber/jabber.h	(revision 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ protocols/jabber/jabber.h	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -92,4 +92,6 @@
 	char *username;		/* USERNAME@server */
 	char *server;		/* username@SERVER -=> server/domain, not hostname */
+	
+	char *oauth2_access_token;
 	
 	/* After changing one of these two (or the priority setting), call
@@ -232,4 +234,7 @@
 #define XMLNS_IBB          "http://jabber.org/protocol/ibb"                      /* XEP-0047 */
 
+/* jabber.c */
+void jabber_connect( struct im_connection *ic );
+
 /* iq.c */
 xt_status jabber_pkt_iq( struct xt_node *node, gpointer data );
@@ -316,4 +321,7 @@
 xt_status sasl_pkt_result( struct xt_node *node, gpointer data );
 gboolean sasl_supported( struct im_connection *ic );
+void sasl_oauth2_init( struct im_connection *ic );
+int sasl_oauth2_get_refresh_token( struct im_connection *ic, const char *msg );
+int sasl_oauth2_refresh( struct im_connection *ic, const char *refresh_token );
 
 /* conference.c */
Index: protocols/jabber/sasl.c
===================================================================
--- protocols/jabber/sasl.c	(revision 59c9adb4e3e27ded95ec9ccee4f57cf79490bd12)
+++ protocols/jabber/sasl.c	(revision 4a5d88504235e1df5d01a3a5701b83dd82d6695d)
@@ -76,11 +76,29 @@
 	xt_add_attr( reply, "xmlns", XMLNS_SASL );
 	
-	if( sup_oauth2 && set_getbool( &ic->acc->set, "oauth" ) )
-	{
-		imcb_log( ic, "Open this URL in your browser to authenticate: %s",
-		          oauth2_url( &oauth2_service_google,
-		                      "https://www.googleapis.com/auth/googletalk" ) );
-		xt_free_node( reply );
-		reply = NULL;
+	if( set_getbool( &ic->acc->set, "oauth" ) )
+	{
+		int len;
+		
+		if( !sup_oauth2 )
+		{
+			imcb_error( ic, "OAuth requested, but not supported by server" );
+			imc_logout( ic, FALSE );
+			xt_free_node( reply );
+			return XT_ABORT;
+		}
+		
+		/* X-OAUTH2 is, not *the* standard OAuth2 SASL/XMPP implementation.
+		   It's currently used by GTalk and vaguely documented on
+		   http://code.google.com/apis/cloudprint/docs/rawxmpp.html . */
+		xt_add_attr( reply, "mechanism", "X-OAUTH2" );
+		
+		len = strlen( jd->username ) + strlen( jd->oauth2_access_token ) + 2;
+		s = g_malloc( len + 1 );
+		s[0] = 0;
+		strcpy( s + 1, jd->username );
+		strcpy( s + 2 + strlen( jd->username ), jd->oauth2_access_token );
+		reply->text = base64_encode( (unsigned char *)s, len );
+		reply->text_len = strlen( reply->text );
+		g_free( s );
 	}
 	else if( sup_digest )
@@ -358,2 +376,83 @@
 	return ( jd->xt && jd->xt->root && xt_find_attr( jd->xt->root, "version" ) ) != 0;
 }
+
+void sasl_oauth2_init( struct im_connection *ic )
+{
+	char *msg, *url;
+	
+	imcb_log( ic, "Starting OAuth authentication" );
+	
+	/* Temporary contact, just used to receive the OAuth response. */
+	imcb_add_buddy( ic, "jabber_oauth", NULL );
+	url = oauth2_url( &oauth2_service_google,
+	                  "https://www.googleapis.com/auth/googletalk" );
+	msg = g_strdup_printf( "Open this URL in your browser to authenticate: %s", url );
+	imcb_buddy_msg( ic, "jabber_oauth", msg, 0, 0 );
+	imcb_buddy_msg( ic, "jabber_oauth", "Respond to this message with the returned "
+	                                    "authorization token.", 0, 0 );
+	
+	g_free( msg );
+	g_free( url );
+}
+
+static gboolean sasl_oauth2_remove_contact( gpointer data, gint fd, b_input_condition cond )
+{
+	struct im_connection *ic = data;
+	imcb_remove_buddy( ic, "jabber_oauth", NULL );
+	return FALSE;
+}
+
+static void sasl_oauth2_got_token( gpointer data, const char *access_token, const char *refresh_token );
+
+int sasl_oauth2_get_refresh_token( struct im_connection *ic, const char *msg )
+{
+	char *code;
+	int ret;
+	
+	imcb_log( ic, "Requesting OAuth access token" );
+	
+	/* Don't do it here because the caller may get confused if the contact
+	   we're currently sending a message to is deleted. */
+	b_timeout_add( 1, sasl_oauth2_remove_contact, ic );
+	
+	code = g_strdup( msg );
+	g_strstrip( code );
+	ret = oauth2_access_token( &oauth2_service_google, OAUTH2_AUTH_CODE,
+	                           code, sasl_oauth2_got_token, ic );
+	
+	g_free( code );
+	return ret;
+}
+
+int sasl_oauth2_refresh( struct im_connection *ic, const char *refresh_token )
+{
+	return oauth2_access_token( &oauth2_service_google, OAUTH2_AUTH_REFRESH,
+	                            refresh_token, sasl_oauth2_got_token, ic );
+}
+
+static void sasl_oauth2_got_token( gpointer data, const char *access_token, const char *refresh_token )
+{
+	struct im_connection *ic = data;
+	struct jabber_data *jd;
+	
+	if( g_slist_find( jabber_connections, ic ) == NULL )
+		return;
+	
+	jd = ic->proto_data;
+	
+	if( access_token == NULL )
+	{
+		imcb_error( ic, "OAuth failure (missing access token)" );
+		imc_logout( ic, TRUE );
+	}
+	if( refresh_token != NULL )
+	{
+		g_free( ic->acc->pass );
+		ic->acc->pass = g_strdup_printf( "refresh_token=%s", refresh_token );
+	}
+	
+	g_free( jd->oauth2_access_token );
+	jd->oauth2_access_token = g_strdup( access_token );
+	
+	jabber_connect( ic );
+}
