source: protocols/jabber/io.c @ 5513f3e

Last change on this file since 5513f3e was 792a93b, checked in by Wilmer van der Gaast <wilmer@…>, at 2011-12-23T12:44:08Z

Merging SSL certificate verification for GnuTLS, with help from AopicieR.

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