source: protocols/jabber/io.c @ 84b045d

Last change on this file since 84b045d was 84b045d, checked in by Wilmer van der Gaast <wilmer@…>, at 2007-04-16T01:03:08Z

s/imc/imcb/ for callback functions. Moved things aroundin nogaim.h a
little bit, grouping things by category instead of original Gaim 0.58
filename.

  • 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                imcb_error( ic, "Short write() to server" );
120                imc_logout( ic, TRUE );
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                        imcb_error( ic, "XML stream error" );
163                        imc_logout( ic, TRUE );
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                                                imcb_error( ic, "TLS is turned on for this "
206                                                          "account, but is not supported by this server" );
207                                                imc_logout( ic, FALSE );
208                                                return FALSE;
209                                        }
210                                        else
211                                        {
212                                                return jabber_init_iq_auth( ic );
213                                        }
214                                }
215                        }
216                        else
217                        {
218                                imcb_error( ic, "XML stream error" );
219                                imc_logout( ic, TRUE );
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                imcb_error( ic, "Error while reading from server" );
230                imc_logout( ic, TRUE );
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                imcb_error( ic, "Could not connect to server" );
245                imc_logout( ic, TRUE );
246                return FALSE;
247        }
248       
249        imcb_log( ic, "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                imcb_error( ic, "Could not connect to server" );
266                imc_logout( ic, TRUE );
267                return FALSE;
268        }
269       
270        imcb_log( ic, "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        imc_logout( data, TRUE );
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                        imcb_error( ic, "Server requires TLS connections, but TLS is turned off for this account" );
300                        imc_logout( ic, FALSE );
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                        imcb_error( ic, "TLS is turned on for this account, but is not supported by this server" );
330                        imc_logout( ic, FALSE );
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        imcb_log( ic, "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        int allow_reconnect = TRUE;
432       
433        for( c = node->children; c; c = c->next )
434        {
435                if( !( s = xt_find_attr( c, "xmlns" ) ) ||
436                    strcmp( s, XMLNS_STREAM_ERROR ) != 0 )
437                        continue;
438               
439                if( strcmp( c->name, "text" ) != 0 )
440                {
441                        type = c->name;
442                }
443                /* Only use the text if it doesn't have an xml:lang attribute,
444                   if it's empty or if it's set to something English. */
445                else if( !( s = xt_find_attr( c, "xml:lang" ) ) ||
446                         !*s || strncmp( s, "en", 2 ) == 0 )
447                {
448                        text = c->text;
449                }
450        }
451       
452        /* Tssk... */
453        if( type == NULL )
454        {
455                imcb_error( ic, "Unknown stream error reported by server" );
456                imc_logout( ic, allow_reconnect );
457                return XT_ABORT;
458        }
459       
460        /* We know that this is a fatal error. If it's a "conflict" error, we
461           should turn off auto-reconnect to make sure we won't get some nasty
462           infinite loop! */
463        if( strcmp( type, "conflict" ) == 0 )
464        {
465                imcb_error( ic, "Account and resource used from a different location" );
466                allow_reconnect = FALSE;
467        }
468        else
469        {
470                imcb_error( ic, "Stream error: %s%s%s", type, text ? ": " : "", text ? text : "" );
471        }
472       
473        imc_logout( ic, allow_reconnect );
474       
475        return XT_ABORT;
476}
477
478static xt_status jabber_pkt_misc( struct xt_node *node, gpointer data )
479{
480        printf( "Received unknown packet:\n" );
481        xt_print( node );
482       
483        return XT_HANDLED;
484}
485
486static const struct xt_handler_entry jabber_handlers[] = {
487        { "stream:stream",      "<root>",               jabber_end_of_stream },
488        { "message",            "stream:stream",        jabber_pkt_message },
489        { "presence",           "stream:stream",        jabber_pkt_presence },
490        { "iq",                 "stream:stream",        jabber_pkt_iq },
491        { "stream:features",    "stream:stream",        jabber_pkt_features },
492        { "stream:error",       "stream:stream",        jabber_pkt_stream_error },
493        { "proceed",            "stream:stream",        jabber_pkt_proceed_tls },
494        { "challenge",          "stream:stream",        sasl_pkt_challenge },
495        { "success",            "stream:stream",        sasl_pkt_result },
496        { "failure",            "stream:stream",        sasl_pkt_result },
497        { NULL,                 "stream:stream",        jabber_pkt_misc },
498        { NULL,                 NULL,                   NULL }
499};
500
501gboolean jabber_start_stream( struct im_connection *ic )
502{
503        struct jabber_data *jd = ic->proto_data;
504        int st;
505        char *greet;
506       
507        /* We'll start our stream now, so prepare everything to receive one
508           from the server too. */
509        xt_free( jd->xt );      /* In case we're RE-starting. */
510        jd->xt = xt_new( ic );
511        jd->xt->handlers = (struct xt_handler_entry*) jabber_handlers;
512       
513        if( jd->r_inpa <= 0 )
514                jd->r_inpa = b_input_add( jd->fd, GAIM_INPUT_READ, jabber_read_callback, ic );
515       
516        greet = g_strdup_printf( "<?xml version='1.0' ?>"
517                                 "<stream:stream to=\"%s\" xmlns=\"jabber:client\" "
518                                  "xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">", jd->server );
519       
520        st = jabber_write( ic, greet, strlen( greet ) );
521       
522        g_free( greet );
523       
524        return st;
525}
526
527void jabber_end_stream( struct im_connection *ic )
528{
529        struct jabber_data *jd = ic->proto_data;
530       
531        /* Let's only do this if the queue is currently empty, otherwise it'd
532           take too long anyway. */
533        if( jd->tx_len == 0 )
534        {
535                char eos[] = "</stream:stream>";
536                struct xt_node *node;
537                int st = 1;
538               
539                if( ic->flags & OPT_LOGGED_IN )
540                {
541                        node = jabber_make_packet( "presence", "unavailable", NULL, NULL );
542                        st = jabber_write_packet( ic, node );
543                        xt_free_node( node );
544                }
545               
546                if( st )
547                        jabber_write( ic, eos, strlen( eos ) );
548        }
549}
Note: See TracBrowser for help on using the repository browser.