source: protocols/jabber/jabber.c @ f138bd2

Last change on this file since f138bd2 was f138bd2, checked in by Wilmer van der Gaast <wilmer@…>, at 2011-07-31T20:27:30Z

OAuth code cleanup.

  • Property mode set to 100644
File size: 17.2 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Jabber module - Main file                                                *
5*                                                                           *
6*  Copyright 2006 Wilmer van der Gaast <wilmer@gaast.net>                   *
7*                                                                           *
8*  This program is free software; you can redistribute it and/or modify     *
9*  it under the terms of the GNU General Public License as published by     *
10*  the Free Software Foundation; either version 2 of the License, or        *
11*  (at your option) any later version.                                      *
12*                                                                           *
13*  This program is distributed in the hope that it will be useful,          *
14*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
15*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
16*  GNU General Public License for more details.                             *
17*                                                                           *
18*  You should have received a copy of the GNU General Public License along  *
19*  with this program; if not, write to the Free Software Foundation, Inc.,  *
20*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
21*                                                                           *
22\***************************************************************************/
23
24#include <glib.h>
25#include <string.h>
26#include <unistd.h>
27#include <ctype.h>
28#include <stdio.h>
29
30#include "ssl_client.h"
31#include "xmltree.h"
32#include "bitlbee.h"
33#include "jabber.h"
34#include "md5.h"
35
36GSList *jabber_connections;
37
38/* First enty is the default */
39static const int jabber_port_list[] = {
40        5222,
41        5223,
42        5220,
43        5221,
44        5224,
45        5225,
46        5226,
47        5227,
48        5228,
49        5229,
50        80,
51        443,
52        0
53};
54
55static void jabber_init( account_t *acc )
56{
57        set_t *s;
58        char str[16];
59       
60        s = set_add( &acc->set, "activity_timeout", "600", set_eval_int, acc );
61       
62        s = set_add( &acc->set, "oauth", "false", set_eval_bool, acc );
63
64        g_snprintf( str, sizeof( str ), "%d", jabber_port_list[0] );
65        s = set_add( &acc->set, "port", str, set_eval_int, acc );
66        s->flags |= ACC_SET_OFFLINE_ONLY;
67       
68        s = set_add( &acc->set, "priority", "0", set_eval_priority, acc );
69
70        s = set_add( &acc->set, "proxy", "<local>;<auto>", NULL, acc );
71       
72        s = set_add( &acc->set, "resource", "BitlBee", NULL, acc );
73        s->flags |= ACC_SET_OFFLINE_ONLY;
74       
75        s = set_add( &acc->set, "resource_select", "activity", NULL, acc );
76       
77        s = set_add( &acc->set, "server", NULL, set_eval_account, acc );
78        s->flags |= ACC_SET_NOSAVE | ACC_SET_OFFLINE_ONLY | SET_NULL_OK;
79       
80        s = set_add( &acc->set, "ssl", "false", set_eval_bool, acc );
81        s->flags |= ACC_SET_OFFLINE_ONLY;
82       
83        s = set_add( &acc->set, "tls", "try", set_eval_tls, acc );
84        s->flags |= ACC_SET_OFFLINE_ONLY;
85       
86        s = set_add( &acc->set, "user_agent", "BitlBee", NULL, acc );
87       
88        s = set_add( &acc->set, "xmlconsole", "false", set_eval_bool, acc );
89        s->flags |= ACC_SET_OFFLINE_ONLY;
90       
91        acc->flags |= ACC_FLAG_AWAY_MESSAGE | ACC_FLAG_STATUS_MESSAGE;
92}
93
94static void jabber_generate_id_hash( struct jabber_data *jd );
95
96static void jabber_login( account_t *acc )
97{
98        struct im_connection *ic = imcb_new( acc );
99        struct jabber_data *jd = g_new0( struct jabber_data, 1 );
100        char *s;
101       
102        /* For now this is needed in the _connected() handlers if using
103           GLib event handling, to make sure we're not handling events
104           on dead connections. */
105        jabber_connections = g_slist_prepend( jabber_connections, ic );
106       
107        jd->ic = ic;
108        ic->proto_data = jd;
109       
110        jd->username = g_strdup( acc->user );
111        jd->server = strchr( jd->username, '@' );
112       
113        jd->fd = jd->r_inpa = jd->w_inpa = -1;
114       
115        if( jd->server == NULL )
116        {
117                imcb_error( ic, "Incomplete account name (format it like <username@jabberserver.name>)" );
118                imc_logout( ic, FALSE );
119                return;
120        }
121       
122        /* So don't think of free()ing jd->server.. :-) */
123        *jd->server = 0;
124        jd->server ++;
125       
126        if( ( s = strchr( jd->server, '/' ) ) )
127        {
128                *s = 0;
129                set_setstr( &acc->set, "resource", s + 1 );
130               
131                /* Also remove the /resource from the original variable so we
132                   won't have to do this again every time. */
133                s = strchr( acc->user, '/' );
134                *s = 0;
135        }
136       
137        jd->node_cache = g_hash_table_new_full( g_str_hash, g_str_equal, NULL, jabber_cache_entry_free );
138        jd->buddies = g_hash_table_new( g_str_hash, g_str_equal );
139       
140        if( set_getbool( &acc->set, "oauth" ) )
141        {
142                jd->fd = jd->r_inpa = jd->w_inpa = -1;
143               
144                /* For the first login with OAuth, we have to authenticate via the browser.
145                   For subsequent logins, exchange the refresh token for a valid access
146                   token (even though the last one maybe didn't expire yet). */
147                if( strncmp( acc->pass, "refresh_token=", 14 ) != 0 )
148                        sasl_oauth2_init( ic );
149                else
150                        sasl_oauth2_refresh( ic, acc->pass + 14 );
151        }
152        else
153                jabber_connect( ic );
154}
155
156/* Separate this from jabber_login() so we can do OAuth first if necessary.
157   Putting this in io.c would probably be more correct. */
158void jabber_connect( struct im_connection *ic )
159{
160        account_t *acc = ic->acc;
161        struct jabber_data *jd = ic->proto_data;
162        int i;
163        char *connect_to;
164        struct ns_srv_reply **srvl = NULL, *srv = NULL;
165       
166        /* Figure out the hostname to connect to. */
167        if( acc->server && *acc->server )
168                connect_to = acc->server;
169        else if( ( srvl = srv_lookup( "xmpp-client", "tcp", jd->server ) ) ||
170                 ( srvl = srv_lookup( "jabber-client", "tcp", jd->server ) ) )
171        {
172                /* Find the lowest-priority one. These usually come
173                   back in random/shuffled order. Not looking at
174                   weights etc for now. */
175                srv = *srvl;
176                for( i = 1; srvl[i]; i ++ )
177                        if( srvl[i]->prio < srv->prio )
178                                srv = srvl[i];
179               
180                connect_to = srv->name;
181        }
182        else
183                connect_to = jd->server;
184       
185        imcb_log( ic, "Connecting" );
186       
187        for( i = 0; jabber_port_list[i] > 0; i ++ )
188                if( set_getint( &acc->set, "port" ) == jabber_port_list[i] )
189                        break;
190
191        if( jabber_port_list[i] == 0 )
192        {
193                imcb_log( ic, "Illegal port number" );
194                imc_logout( ic, FALSE );
195                return;
196        }
197       
198        /* For non-SSL connections we can try to use the port # from the SRV
199           reply, but let's not do that when using SSL, SSL usually runs on
200           non-standard ports... */
201        if( set_getbool( &acc->set, "ssl" ) )
202        {
203                jd->ssl = ssl_connect( connect_to, set_getint( &acc->set, "port" ), jabber_connected_ssl, ic );
204                jd->fd = jd->ssl ? ssl_getfd( jd->ssl ) : -1;
205        }
206        else
207        {
208                jd->fd = proxy_connect( connect_to, srv ? srv->port : set_getint( &acc->set, "port" ), jabber_connected_plain, ic );
209        }
210        srv_free( srvl );
211       
212        if( jd->fd == -1 )
213        {
214                imcb_error( ic, "Could not connect to server" );
215                imc_logout( ic, TRUE );
216               
217                return;
218        }
219       
220        if( set_getbool( &acc->set, "xmlconsole" ) )
221        {
222                jd->flags |= JFLAG_XMLCONSOLE;
223                /* Shouldn't really do this at this stage already, maybe. But
224                   I think this shouldn't break anything. */
225                imcb_add_buddy( ic, JABBER_XMLCONSOLE_HANDLE, NULL );
226        }
227       
228        jabber_generate_id_hash( jd );
229}
230
231/* This generates an unfinished md5_state_t variable. Every time we generate
232   an ID, we finish the state by adding a sequence number and take the hash. */
233static void jabber_generate_id_hash( struct jabber_data *jd )
234{
235        md5_byte_t binbuf[4];
236        char *s;
237       
238        md5_init( &jd->cached_id_prefix );
239        md5_append( &jd->cached_id_prefix, (unsigned char *) jd->username, strlen( jd->username ) );
240        md5_append( &jd->cached_id_prefix, (unsigned char *) jd->server, strlen( jd->server ) );
241        s = set_getstr( &jd->ic->acc->set, "resource" );
242        md5_append( &jd->cached_id_prefix, (unsigned char *) s, strlen( s ) );
243        random_bytes( binbuf, 4 );
244        md5_append( &jd->cached_id_prefix, binbuf, 4 );
245}
246
247static void jabber_logout( struct im_connection *ic )
248{
249        struct jabber_data *jd = ic->proto_data;
250       
251        while( jd->filetransfers )
252                imcb_file_canceled( ic, ( ( struct jabber_transfer *) jd->filetransfers->data )->ft, "Logging out" );
253
254        while( jd->streamhosts )
255        {
256                jabber_streamhost_t *sh = jd->streamhosts->data;
257                jd->streamhosts = g_slist_remove( jd->streamhosts, sh );
258                g_free( sh->jid );
259                g_free( sh->host );
260                g_free( sh );
261        }
262
263        if( jd->fd >= 0 )
264                jabber_end_stream( ic );
265       
266        while( ic->groupchats )
267                jabber_chat_free( ic->groupchats->data );
268       
269        if( jd->r_inpa >= 0 )
270                b_event_remove( jd->r_inpa );
271        if( jd->w_inpa >= 0 )
272                b_event_remove( jd->w_inpa );
273       
274        if( jd->ssl )
275                ssl_disconnect( jd->ssl );
276        if( jd->fd >= 0 )
277                closesocket( jd->fd );
278       
279        if( jd->tx_len )
280                g_free( jd->txq );
281       
282        if( jd->node_cache )
283                g_hash_table_destroy( jd->node_cache );
284       
285        jabber_buddy_remove_all( ic );
286       
287        xt_free( jd->xt );
288       
289        g_free( jd->oauth2_access_token );
290        g_free( jd->away_message );
291        g_free( jd->username );
292        g_free( jd );
293       
294        jabber_connections = g_slist_remove( jabber_connections, ic );
295}
296
297static int jabber_buddy_msg( struct im_connection *ic, char *who, char *message, int flags )
298{
299        struct jabber_data *jd = ic->proto_data;
300        struct jabber_buddy *bud;
301        struct xt_node *node;
302        char *s;
303        int st;
304       
305        if( g_strcasecmp( who, JABBER_XMLCONSOLE_HANDLE ) == 0 )
306                return jabber_write( ic, message, strlen( message ) );
307       
308        if( g_strcasecmp( who, "jabber_oauth" ) == 0 )
309        {
310                if( sasl_oauth2_get_refresh_token( ic, message ) )
311                {
312                        return 1;
313                }
314                else
315                {
316                        imcb_error( ic, "OAuth failure" );
317                        imc_logout( ic, TRUE );
318                }
319        }
320       
321        if( ( s = strchr( who, '=' ) ) && jabber_chat_by_jid( ic, s + 1 ) )
322                bud = jabber_buddy_by_ext_jid( ic, who, 0 );
323        else
324                bud = jabber_buddy_by_jid( ic, who, GET_BUDDY_BARE_OK );
325       
326        node = xt_new_node( "body", message, NULL );
327        node = jabber_make_packet( "message", "chat", bud ? bud->full_jid : who, node );
328       
329        if( bud && ( jd->flags & JFLAG_WANT_TYPING ) &&
330            ( ( bud->flags & JBFLAG_DOES_XEP85 ) ||
331             !( bud->flags & JBFLAG_PROBED_XEP85 ) ) )
332        {
333                struct xt_node *act;
334               
335                /* If the user likes typing notification and if we don't know
336                   (and didn't probe before) if this resource supports XEP85,
337                   include a probe in this packet now. Also, if we know this
338                   buddy does support XEP85, we have to send this <active/>
339                   tag to tell that the user stopped typing (well, that's what
340                   we guess when s/he pressed Enter...). */
341                act = xt_new_node( "active", NULL, NULL );
342                xt_add_attr( act, "xmlns", XMLNS_CHATSTATES );
343                xt_add_child( node, act );
344               
345                /* Just make sure we do this only once. */
346                bud->flags |= JBFLAG_PROBED_XEP85;
347        }
348       
349        st = jabber_write_packet( ic, node );
350        xt_free_node( node );
351       
352        return st;
353}
354
355static GList *jabber_away_states( struct im_connection *ic )
356{
357        static GList *l = NULL;
358        int i;
359       
360        if( l == NULL )
361                for( i = 0; jabber_away_state_list[i].full_name; i ++ )
362                        l = g_list_append( l, (void*) jabber_away_state_list[i].full_name );
363       
364        return l;
365}
366
367static void jabber_get_info( struct im_connection *ic, char *who )
368{
369        struct jabber_buddy *bud;
370       
371        bud = jabber_buddy_by_jid( ic, who, GET_BUDDY_FIRST );
372       
373        while( bud )
374        {
375                imcb_log( ic, "Buddy %s (%d) information:", bud->full_jid, bud->priority );
376                if( bud->away_state )
377                        imcb_log( ic, "Away state: %s", bud->away_state->full_name );
378                imcb_log( ic, "Status message: %s", bud->away_message ? bud->away_message : "(none)" );
379               
380                bud = bud->next;
381        }
382       
383        jabber_get_vcard( ic, bud ? bud->full_jid : who );
384}
385
386static void jabber_set_away( struct im_connection *ic, char *state_txt, char *message )
387{
388        struct jabber_data *jd = ic->proto_data;
389       
390        /* state_txt == NULL -> Not away.
391           Unknown state -> fall back to the first defined away state. */
392        if( state_txt == NULL )
393                jd->away_state = NULL;
394        else if( ( jd->away_state = jabber_away_state_by_name( state_txt ) ) == NULL )
395                jd->away_state = jabber_away_state_list;
396       
397        g_free( jd->away_message );
398        jd->away_message = ( message && *message ) ? g_strdup( message ) : NULL;
399       
400        presence_send_update( ic );
401}
402
403static void jabber_add_buddy( struct im_connection *ic, char *who, char *group )
404{
405        struct jabber_data *jd = ic->proto_data;
406       
407        if( g_strcasecmp( who, JABBER_XMLCONSOLE_HANDLE ) == 0 )
408        {
409                jd->flags |= JFLAG_XMLCONSOLE;
410                imcb_add_buddy( ic, JABBER_XMLCONSOLE_HANDLE, NULL );
411                return;
412        }
413       
414        if( jabber_add_to_roster( ic, who, NULL, group ) )
415                presence_send_request( ic, who, "subscribe" );
416}
417
418static void jabber_remove_buddy( struct im_connection *ic, char *who, char *group )
419{
420        struct jabber_data *jd = ic->proto_data;
421       
422        if( g_strcasecmp( who, JABBER_XMLCONSOLE_HANDLE ) == 0 )
423        {
424                jd->flags &= ~JFLAG_XMLCONSOLE;
425                /* Not necessary for now. And for now the code isn't too
426                   happy if the buddy is completely gone right after calling
427                   this function already.
428                imcb_remove_buddy( ic, JABBER_XMLCONSOLE_HANDLE, NULL );
429                */
430                return;
431        }
432       
433        /* We should always do this part. Clean up our administration a little bit. */
434        jabber_buddy_remove_bare( ic, who );
435       
436        if( jabber_remove_from_roster( ic, who ) )
437                presence_send_request( ic, who, "unsubscribe" );
438}
439
440static struct groupchat *jabber_chat_join_( struct im_connection *ic, const char *room, const char *nick, const char *password, set_t **sets )
441{
442        if( strchr( room, '@' ) == NULL )
443                imcb_error( ic, "Invalid room name: %s", room );
444        else if( jabber_chat_by_jid( ic, room ) )
445                imcb_error( ic, "Already present in chat `%s'", room );
446        else
447                return jabber_chat_join( ic, room, nick, set_getstr( sets, "password" ) );
448       
449        return NULL;
450}
451
452static void jabber_chat_msg_( struct groupchat *c, char *message, int flags )
453{
454        if( c && message )
455                jabber_chat_msg( c, message, flags );
456}
457
458static void jabber_chat_topic_( struct groupchat *c, char *topic )
459{
460        if( c && topic )
461                jabber_chat_topic( c, topic );
462}
463
464static void jabber_chat_leave_( struct groupchat *c )
465{
466        if( c )
467                jabber_chat_leave( c, NULL );
468}
469
470static void jabber_chat_invite_( struct groupchat *c, char *who, char *msg )
471{
472        struct jabber_chat *jc = c->data;
473        gchar *msg_alt = NULL;
474
475        if( msg == NULL )
476                msg_alt = g_strdup_printf( "%s invited you to %s", c->ic->acc->user, jc->name );
477       
478        if( c && who )
479                jabber_chat_invite( c, who, msg ? msg : msg_alt );
480       
481        g_free( msg_alt );
482}
483
484static void jabber_keepalive( struct im_connection *ic )
485{
486        /* Just any whitespace character is enough as a keepalive for XMPP sessions. */
487        if( !jabber_write( ic, "\n", 1 ) )
488                return;
489       
490        /* This runs the garbage collection every minute, which means every packet
491           is in the cache for about a minute (which should be enough AFAIK). */
492        jabber_cache_clean( ic );
493}
494
495static int jabber_send_typing( struct im_connection *ic, char *who, int typing )
496{
497        struct jabber_data *jd = ic->proto_data;
498        struct jabber_buddy *bud;
499       
500        /* Enable typing notification related code from now. */
501        jd->flags |= JFLAG_WANT_TYPING;
502       
503        if( ( bud = jabber_buddy_by_jid( ic, who, 0 ) ) == NULL )
504        {
505                /* Sending typing notifications to unknown buddies is
506                   unsupported for now. Shouldn't be a problem, I think. */
507                return 0;
508        }
509       
510        if( bud->flags & JBFLAG_DOES_XEP85 )
511        {
512                /* We're only allowed to send this stuff if we know the other
513                   side supports it. */
514               
515                struct xt_node *node;
516                char *type;
517                int st;
518               
519                if( typing & OPT_TYPING )
520                        type = "composing";
521                else if( typing & OPT_THINKING )
522                        type = "paused";
523                else
524                        type = "active";
525               
526                node = xt_new_node( type, NULL, NULL );
527                xt_add_attr( node, "xmlns", XMLNS_CHATSTATES );
528                node = jabber_make_packet( "message", "chat", bud->full_jid, node );
529               
530                st = jabber_write_packet( ic, node );
531                xt_free_node( node );
532               
533                return st;
534        }
535       
536        return 1;
537}
538
539void jabber_chat_add_settings( account_t *acc, set_t **head )
540{
541        /* Meh. Stupid room passwords. Not trying to obfuscate/hide
542           them from the user for now. */
543        set_add( head, "password", NULL, NULL, NULL );
544}
545
546void jabber_chat_free_settings( account_t *acc, set_t **head )
547{
548        set_del( head, "password" );
549}
550
551GList *jabber_buddy_action_list( bee_user_t *bu )
552{
553        static GList *ret = NULL;
554       
555        if( ret == NULL )
556        {
557                static const struct buddy_action ba[2] = {
558                        { "VERSION", "Get client (version) information" },
559                };
560               
561                ret = g_list_prepend( ret, (void*) ba + 0 );
562        }
563       
564        return ret;
565}
566
567void *jabber_buddy_action( struct bee_user *bu, const char *action, char * const args[], void *data )
568{
569        if( g_strcasecmp( action, "VERSION" ) == 0 )
570        {
571                struct jabber_buddy *bud;
572               
573                if( ( bud = jabber_buddy_by_ext_jid( bu->ic, bu->handle, 0 ) ) == NULL )
574                        bud = jabber_buddy_by_jid( bu->ic, bu->handle, GET_BUDDY_FIRST );
575                for( ; bud; bud = bud->next )
576                        jabber_iq_version_send( bu->ic, bud, data );
577        }
578       
579        return NULL;
580}
581
582void jabber_initmodule()
583{
584        struct prpl *ret = g_new0( struct prpl, 1 );
585       
586        ret->name = "jabber";
587        ret->mms = 0;                        /* no limit */
588        ret->login = jabber_login;
589        ret->init = jabber_init;
590        ret->logout = jabber_logout;
591        ret->buddy_msg = jabber_buddy_msg;
592        ret->away_states = jabber_away_states;
593        ret->set_away = jabber_set_away;
594//      ret->set_info = jabber_set_info;
595        ret->get_info = jabber_get_info;
596        ret->add_buddy = jabber_add_buddy;
597        ret->remove_buddy = jabber_remove_buddy;
598        ret->chat_msg = jabber_chat_msg_;
599        ret->chat_topic = jabber_chat_topic_;
600        ret->chat_invite = jabber_chat_invite_;
601        ret->chat_leave = jabber_chat_leave_;
602        ret->chat_join = jabber_chat_join_;
603        ret->chat_add_settings = jabber_chat_add_settings;
604        ret->chat_free_settings = jabber_chat_free_settings;
605        ret->keepalive = jabber_keepalive;
606        ret->send_typing = jabber_send_typing;
607        ret->handle_cmp = g_strcasecmp;
608        ret->transfer_request = jabber_si_transfer_request;
609        ret->buddy_action_list = jabber_buddy_action_list;
610        ret->buddy_action = jabber_buddy_action;
611
612        register_protocol( ret );
613}
Note: See TracBrowser for help on using the repository browser.