source: protocols/jabber/io.c @ 0da65d5

Last change on this file since 0da65d5 was 0da65d5, checked in by Wilmer van der Gaast <wilmer@…>, at 2007-03-31T05:40:45Z

s/gaim_connection/im_connection/ and some other minor API changes. The rest
will come tomorrow. It compiles, I'll leave the real testing up to someone
else. ;-)

  • Property mode set to 100644
File size: 15.8 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Jabber module - I/O stuff (plain, SSL), queues, etc                      *
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 "jabber.h"
25#include "ssl_client.h"
26
27static gboolean jabber_write_callback( gpointer data, gint fd, b_input_condition cond );
28static gboolean jabber_write_queue( struct im_connection *ic );
29
30int jabber_write_packet( struct im_connection *ic, struct xt_node *node )
31{
32        char *buf;
33        int st;
34       
35        buf = xt_to_string( node );
36        st = jabber_write( ic, buf, strlen( buf ) );
37        g_free( buf );
38       
39        return st;
40}
41
42int jabber_write( struct im_connection *ic, char *buf, int len )
43{
44        struct jabber_data *jd = ic->proto_data;
45        gboolean ret;
46       
47        if( jd->tx_len == 0 )
48        {
49                /* If the queue is empty, allocate a new buffer. */
50                jd->tx_len = len;
51                jd->txq = g_memdup( buf, len );
52               
53                /* Try if we can write it immediately so we don't have to do
54                   it via the event handler. If not, add the handler. (In
55                   most cases it probably won't be necessary.) */
56                if( ( ret = jabber_write_queue( ic ) ) && jd->tx_len > 0 )
57                        jd->w_inpa = b_input_add( jd->fd, GAIM_INPUT_WRITE, jabber_write_callback, ic );
58        }
59        else
60        {
61                /* Just add it to the buffer if it's already filled. The
62                   event handler is already set. */
63                jd->txq = g_renew( char, jd->txq, jd->tx_len + len );
64                memcpy( jd->txq + jd->tx_len, buf, len );
65                jd->tx_len += len;
66               
67                /* The return value for write() doesn't necessarily mean
68                   that everything got sent, it mainly means that the
69                   connection (officially) still exists and can still
70                   be accessed without hitting SIGSEGV. IOW: */
71                ret = TRUE;
72        }
73       
74        return ret;
75}
76
77/* Splitting up in two separate functions: One to use as a callback and one
78   to use in the function above to escape from having to wait for the event
79   handler to call us, if possible.
80   
81   Two different functions are necessary because of the return values: The
82   callback should only return TRUE if the write was successful AND if the
83   buffer is not empty yet (ie. if the handler has to be called again when
84   the socket is ready for more data). */
85static gboolean jabber_write_callback( gpointer data, gint fd, b_input_condition cond )
86{
87        struct jabber_data *jd = ((struct im_connection *)data)->proto_data;
88       
89        return jd->fd != -1 &&
90               jabber_write_queue( data ) &&
91               jd->tx_len > 0;
92}
93
94static gboolean jabber_write_queue( struct im_connection *ic )
95{
96        struct jabber_data *jd = ic->proto_data;
97        int st;
98       
99        if( jd->ssl )
100                st = ssl_write( jd->ssl, jd->txq, jd->tx_len );
101        else
102                st = write( jd->fd, jd->txq, jd->tx_len );
103       
104        if( st == jd->tx_len )
105        {
106                /* We wrote everything, clear the buffer. */
107                g_free( jd->txq );
108                jd->txq = NULL;
109                jd->tx_len = 0;
110               
111                return TRUE;
112        }
113        else if( st == 0 || ( st < 0 && !sockerr_again() ) )
114        {
115                /* Set fd to -1 to make sure we won't write to it anymore. */
116                closesocket( jd->fd );  /* Shouldn't be necessary after errors? */
117                jd->fd = -1;
118               
119                hide_login_progress_error( ic, "Short write() to server" );
120                signoff( ic );
121                return FALSE;
122        }
123        else if( st > 0 )
124        {
125                char *s;
126               
127                s = g_memdup( jd->txq + st, jd->tx_len - st );
128                jd->tx_len -= st;
129                g_free( jd->txq );
130                jd->txq = s;
131               
132                return TRUE;
133        }
134        else
135        {
136                /* Just in case we had EINPROGRESS/EAGAIN: */
137               
138                return TRUE;
139        }
140}
141
142static gboolean jabber_read_callback( gpointer data, gint fd, b_input_condition cond )
143{
144        struct im_connection *ic = data;
145        struct jabber_data *jd = ic->proto_data;
146        char buf[512];
147        int st;
148       
149        if( jd->fd == -1 )
150                return FALSE;
151       
152        if( jd->ssl )
153                st = ssl_read( jd->ssl, buf, sizeof( buf ) );
154        else
155                st = read( jd->fd, buf, sizeof( buf ) );
156       
157        if( st > 0 )
158        {
159                /* Parse. */
160                if( xt_feed( jd->xt, buf, st ) < 0 )
161                {
162                        hide_login_progress_error( ic, "XML stream error" );
163                        signoff( ic );
164                        return FALSE;
165                }
166               
167                /* Execute all handlers. */
168                if( !xt_handle( jd->xt, NULL, 1 ) )
169                {
170                        /* Don't do anything, the handlers should have
171                           aborted the connection already. */
172                        return FALSE;
173                }
174               
175                if( jd->flags & JFLAG_STREAM_RESTART )
176                {
177                        jd->flags &= ~JFLAG_STREAM_RESTART;
178                        jabber_start_stream( ic );
179                }
180               
181                /* Garbage collection. */
182                xt_cleanup( jd->xt, NULL, 1 );
183               
184                /* This is a bit hackish, unfortunately. Although xmltree
185                   has nifty event handler stuff, it only calls handlers
186                   when nodes are complete. Since the server should only
187                   send an opening <stream:stream> tag, we have to check
188                   this by hand. :-( */
189                if( !( jd->flags & JFLAG_STREAM_STARTED ) && jd->xt && jd->xt->root )
190                {
191                        if( g_strcasecmp( jd->xt->root->name, "stream:stream" ) == 0 )
192                        {
193                                jd->flags |= JFLAG_STREAM_STARTED;
194                               
195                                /* If there's no version attribute, assume
196                                   this is an old server that can't do SASL
197                                   authentication. */
198                                if( !sasl_supported( ic ) )
199                                {
200                                        /* If there's no version= tag, we suppose
201                                           this server does NOT implement: XMPP 1.0,
202                                           SASL and TLS. */
203                                        if( set_getbool( &ic->acc->set, "tls" ) )
204                                        {
205                                                hide_login_progress( ic, "TLS is turned on for this "
206                                                          "account, but is not supported by this server" );
207                                                signoff( ic );
208                                                return FALSE;
209                                        }
210                                        else
211                                        {
212                                                return jabber_init_iq_auth( ic );
213                                        }
214                                }
215                        }
216                        else
217                        {
218                                hide_login_progress( ic, "XML stream error" );
219                                signoff( ic );
220                                return FALSE;
221                        }
222                }
223        }
224        else if( st == 0 || ( st < 0 && !sockerr_again() ) )
225        {
226                closesocket( jd->fd );
227                jd->fd = -1;
228               
229                hide_login_progress_error( ic, "Error while reading from server" );
230                signoff( ic );
231                return FALSE;
232        }
233       
234        /* EAGAIN/etc or a successful read. */
235        return TRUE;
236}
237
238gboolean jabber_connected_plain( gpointer data, gint source, b_input_condition cond )
239{
240        struct im_connection *ic = data;
241       
242        if( source == -1 )
243        {
244                hide_login_progress( ic, "Could not connect to server" );
245                signoff( ic );
246                return FALSE;
247        }
248       
249        set_login_progress( ic, 1, "Connected to server, logging in" );
250       
251        return jabber_start_stream( ic );
252}
253
254gboolean jabber_connected_ssl( gpointer data, void *source, b_input_condition cond )
255{
256        struct im_connection *ic = data;
257        struct jabber_data *jd = ic->proto_data;
258       
259        if( source == NULL )
260        {
261                /* The SSL connection will be cleaned up by the SSL lib
262                   already, set it to NULL here to prevent a double cleanup: */
263                jd->ssl = NULL;
264               
265                hide_login_progress( ic, "Could not connect to server" );
266                signoff( ic );
267                return FALSE;
268        }
269       
270        set_login_progress( ic, 1, "Connected to server, logging in" );
271       
272        return jabber_start_stream( ic );
273}
274
275static xt_status jabber_end_of_stream( struct xt_node *node, gpointer data )
276{
277        signoff( data );
278        return XT_ABORT;
279}
280
281static xt_status jabber_pkt_features( struct xt_node *node, gpointer data )
282{
283        struct im_connection *ic = data;
284        struct jabber_data *jd = ic->proto_data;
285        struct xt_node *c, *reply;
286        int trytls;
287       
288        trytls = g_strcasecmp( set_getstr( &ic->acc->set, "tls" ), "try" ) == 0;
289        c = xt_find_node( node->children, "starttls" );
290        if( c && !jd->ssl )
291        {
292                /* If the server advertises the STARTTLS feature and if we're
293                   not in a secure connection already: */
294               
295                c = xt_find_node( c->children, "required" );
296               
297                if( c && ( !trytls && !set_getbool( &ic->acc->set, "tls" ) ) )
298                {
299                        hide_login_progress( ic, "Server requires TLS connections, but TLS is turned off for this account" );
300                        signoff( ic );
301                       
302                        return XT_ABORT;
303                }
304               
305                /* Only run this if the tls setting is set to true or try: */
306                if( ( trytls || set_getbool( &ic->acc->set, "tls" ) ) )
307                {
308                        reply = xt_new_node( "starttls", NULL, NULL );
309                        xt_add_attr( reply, "xmlns", XMLNS_TLS );
310                        if( !jabber_write_packet( ic, reply ) )
311                        {
312                                xt_free_node( reply );
313                                return XT_ABORT;
314                        }
315                        xt_free_node( reply );
316                       
317                        return XT_HANDLED;
318                }
319        }
320        else if( !c && !jd->ssl )
321        {
322                /* If the server does not advertise the STARTTLS feature and
323                   we're not in a secure connection already: (Servers have a
324                   habit of not advertising <starttls/> anymore when already
325                   using SSL/TLS. */
326               
327                if( !trytls && set_getbool( &ic->acc->set, "tls" ) )
328                {
329                        hide_login_progress( ic, "TLS is turned on for this account, but is not supported by this server" );
330                        signoff( ic );
331                       
332                        return XT_ABORT;
333                }
334        }
335       
336        /* This one used to be in jabber_handlers[], but it has to be done
337           from here to make sure the TLS session will be initialized
338           properly before we attempt SASL authentication. */
339        if( ( c = xt_find_node( node->children, "mechanisms" ) ) )
340        {
341                if( sasl_pkt_mechanisms( c, data ) == XT_ABORT )
342                        return XT_ABORT;
343        }
344        /* If the server *SEEMS* to support SASL authentication but doesn't
345           support it after all, we should try to do authentication the
346           other way. jabber.com doesn't seem to do SASL while it pretends
347           to be XMPP 1.0 compliant! */
348        else if( !( jd->flags & JFLAG_AUTHENTICATED ) && sasl_supported( ic ) )
349        {
350                if( !jabber_init_iq_auth( ic ) )
351                        return XT_ABORT;
352        }
353       
354        if( ( c = xt_find_node( node->children, "bind" ) ) )
355        {
356                reply = xt_new_node( "bind", NULL, xt_new_node( "resource", set_getstr( &ic->acc->set, "resource" ), NULL ) );
357                xt_add_attr( reply, "xmlns", XMLNS_BIND );
358                reply = jabber_make_packet( "iq", "set", NULL, reply );
359                jabber_cache_add( ic, reply, jabber_pkt_bind_sess );
360               
361                if( !jabber_write_packet( ic, reply ) )
362                        return XT_ABORT;
363               
364                jd->flags |= JFLAG_WAIT_BIND;
365        }
366       
367        if( ( c = xt_find_node( node->children, "session" ) ) )
368        {
369                reply = xt_new_node( "session", NULL, NULL );
370                xt_add_attr( reply, "xmlns", XMLNS_SESSION );
371                reply = jabber_make_packet( "iq", "set", NULL, reply );
372                jabber_cache_add( ic, reply, jabber_pkt_bind_sess );
373               
374                if( !jabber_write_packet( ic, reply ) )
375                        return XT_ABORT;
376               
377                jd->flags |= JFLAG_WAIT_SESSION;
378        }
379       
380        /* This flag is already set if we authenticated via SASL, so now
381           we can resume the session in the new stream, if we don't have
382           to bind/initialize the session. */
383        if( jd->flags & JFLAG_AUTHENTICATED && ( jd->flags & ( JFLAG_WAIT_BIND | JFLAG_WAIT_SESSION ) ) == 0 )
384        {
385                if( !jabber_get_roster( ic ) )
386                        return XT_ABORT;
387        }
388       
389        return XT_HANDLED;
390}
391
392static xt_status jabber_pkt_proceed_tls( struct xt_node *node, gpointer data )
393{
394        struct im_connection *ic = data;
395        struct jabber_data *jd = ic->proto_data;
396        char *xmlns;
397       
398        xmlns = xt_find_attr( node, "xmlns" );
399       
400        /* Just ignore it when it doesn't seem to be TLS-related (is that at
401           all possible??). */
402        if( !xmlns || strcmp( xmlns, XMLNS_TLS ) != 0 )
403                return XT_HANDLED;
404       
405        /* We don't want event handlers to touch our TLS session while it's
406           still initializing! */
407        b_event_remove( jd->r_inpa );
408        if( jd->tx_len > 0 )
409        {
410                /* Actually the write queue should be empty here, but just
411                   to be sure... */
412                b_event_remove( jd->w_inpa );
413                g_free( jd->txq );
414                jd->txq = NULL;
415                jd->tx_len = 0;
416        }
417        jd->w_inpa = jd->r_inpa = 0;
418       
419        set_login_progress( ic, 1, "Converting stream to TLS" );
420       
421        jd->ssl = ssl_starttls( jd->fd, jabber_connected_ssl, ic );
422       
423        return XT_HANDLED;
424}
425
426static xt_status jabber_pkt_stream_error( struct xt_node *node, gpointer data )
427{
428        struct im_connection *ic = data;
429        struct xt_node *c;
430        char *s, *type = NULL, *text = NULL;
431       
432        for( c = node->children; c; c = c->next )
433        {
434                if( !( s = xt_find_attr( c, "xmlns" ) ) ||
435                    strcmp( s, XMLNS_STREAM_ERROR ) != 0 )
436                        continue;
437               
438                if( strcmp( c->name, "text" ) != 0 )
439                {
440                        type = c->name;
441                }
442                /* Only use the text if it doesn't have an xml:lang attribute,
443                   if it's empty or if it's set to something English. */
444                else if( !( s = xt_find_attr( c, "xml:lang" ) ) ||
445                         !*s || strncmp( s, "en", 2 ) == 0 )
446                {
447                        text = c->text;
448                }
449        }
450       
451        /* Tssk... */
452        if( type == NULL )
453        {
454                hide_login_progress_error( ic, "Unknown stream error reported by server" );
455                signoff( ic );
456                return XT_ABORT;
457        }
458       
459        /* We know that this is a fatal error. If it's a "conflict" error, we
460           should turn off auto-reconnect to make sure we won't get some nasty
461           infinite loop! */
462        if( strcmp( type, "conflict" ) == 0 )
463        {
464                hide_login_progress( ic, "Account and resource used from a different location" );
465                ic->wants_to_die = TRUE;
466        }
467        else
468        {
469                s = g_strdup_printf( "Stream error: %s%s%s", type, text ? ": " : "", text ? text : "" );
470                hide_login_progress_error( ic, s );
471                g_free( s );
472        }
473       
474        signoff( ic );
475       
476        return XT_ABORT;
477}
478
479static xt_status jabber_pkt_misc( struct xt_node *node, gpointer data )
480{
481        printf( "Received unknown packet:\n" );
482        xt_print( node );
483       
484        return XT_HANDLED;
485}
486
487static const struct xt_handler_entry jabber_handlers[] = {
488        { "stream:stream",      "<root>",               jabber_end_of_stream },
489        { "message",            "stream:stream",        jabber_pkt_message },
490        { "presence",           "stream:stream",        jabber_pkt_presence },
491        { "iq",                 "stream:stream",        jabber_pkt_iq },
492        { "stream:features",    "stream:stream",        jabber_pkt_features },
493        { "stream:error",       "stream:stream",        jabber_pkt_stream_error },
494        { "proceed",            "stream:stream",        jabber_pkt_proceed_tls },
495        { "challenge",          "stream:stream",        sasl_pkt_challenge },
496        { "success",            "stream:stream",        sasl_pkt_result },
497        { "failure",            "stream:stream",        sasl_pkt_result },
498        { NULL,                 "stream:stream",        jabber_pkt_misc },
499        { NULL,                 NULL,                   NULL }
500};
501
502gboolean jabber_start_stream( struct im_connection *ic )
503{
504        struct jabber_data *jd = ic->proto_data;
505        int st;
506        char *greet;
507       
508        /* We'll start our stream now, so prepare everything to receive one
509           from the server too. */
510        xt_free( jd->xt );      /* In case we're RE-starting. */
511        jd->xt = xt_new( ic );
512        jd->xt->handlers = (struct xt_handler_entry*) jabber_handlers;
513       
514        if( jd->r_inpa <= 0 )
515                jd->r_inpa = b_input_add( jd->fd, GAIM_INPUT_READ, jabber_read_callback, ic );
516       
517        greet = g_strdup_printf( "<?xml version='1.0' ?>"
518                                 "<stream:stream to=\"%s\" xmlns=\"jabber:client\" "
519                                  "xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">", jd->server );
520       
521        st = jabber_write( ic, greet, strlen( greet ) );
522       
523        g_free( greet );
524       
525        return st;
526}
527
528void jabber_end_stream( struct im_connection *ic )
529{
530        struct jabber_data *jd = ic->proto_data;
531       
532        /* Let's only do this if the queue is currently empty, otherwise it'd
533           take too long anyway. */
534        if( jd->tx_len == 0 )
535        {
536                char eos[] = "</stream:stream>";
537                struct xt_node *node;
538                int st = 1;
539               
540                if( ic->flags & OPT_LOGGED_IN )
541                {
542                        node = jabber_make_packet( "presence", "unavailable", NULL, NULL );
543                        st = jabber_write_packet( ic, node );
544                        xt_free_node( node );
545                }
546               
547                if( st )
548                        jabber_write( ic, eos, strlen( eos ) );
549        }
550}
Note: See TracBrowser for help on using the repository browser.