auth_nb.py 25.5 KB
Newer Older
1
##   auth_nb.py
2
##       based on auth.py, changes backported up to revision 1.41
3 4 5 6 7 8 9 10 11 12 13 14 15
##
##   Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##       modified by Dimitur Kirov <dkirov@gmail.com>
##
##   This program is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as published by
##   the Free Software Foundation; either version 2, or (at your option)
##   any later version.
##
##   This program is distributed in the hope that it will be useful,
##   but WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.
16 17

"""
18
Provides plugs for SASL and NON-SASL authentication mechanisms.
19
Can be used both for client and transport authentication
20 21

See client_nb.py
22 23
"""

Yann Leboulanger's avatar
Yann Leboulanger committed
24 25
from protocol import NS_SASL, NS_SESSION, NS_STREAMS, NS_BIND, NS_AUTH
from protocol import NS_STREAM_MGMT
26
from protocol import Node, NodeProcessed, isResultNode, Iq, Protocol, JID
27
from plugin import PlugIn
Yann Leboulanger's avatar
Yann Leboulanger committed
28
from smacks import Smacks
29 30 31 32
import base64
import random
import itertools
import dispatcher_nb
33
import hashlib
34 35
import hmac
import hashlib
Yann Leboulanger's avatar
Yann Leboulanger committed
36

37 38 39
import logging
log = logging.getLogger('gajim.c.x.auth_nb')

40 41
def HH(some): return hashlib.md5(some).hexdigest()
def H(some): return hashlib.md5(some).digest()
42
def C(some): return ':'.join(some)
43

44
try:
45 46
    import kerberos
    have_kerberos = True
47
except ImportError:
48
    have_kerberos = False
49 50 51

GSS_STATE_STEP = 0
GSS_STATE_WRAP = 1
52 53 54 55
SASL_FAILURE = 'failure'
SASL_SUCCESS = 'success'
SASL_UNSUPPORTED = 'not-supported'
SASL_IN_PROCESS = 'in-process'
56

57
def challenge_splitter(data):
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    """
    Helper function that creates a dict from challenge string

    Sample challenge string:
            username="example.org",realm="somerealm",\
            nonce="OA6MG9tEQGm2hh",cnonce="OA6MHXh6VqTrRk",\
            nc=00000001,qop="auth,auth-int,auth-conf",charset=utf-8

    Expected result for challan:
            dict['qop'] = ('auth','auth-int','auth-conf')
            dict['realm'] = 'somerealm'
    """
    X_KEYWORD, X_VALUE, X_END = 0, 1, 2
    quotes_open = False
    keyword, value = '', ''
    dict_ = {}
    arr = None

    expecting = X_KEYWORD
    for iter_ in range(len(data) + 1):
        end = False
        if iter_ == len(data):
            expecting = X_END
            end = True
        else:
            char = data[iter_]
        if expecting == X_KEYWORD:
            if char == '=':
                expecting  = X_VALUE
            elif char in (',', ' ', '\t'):
                pass
            else:
                keyword = '%s%c' % (keyword, char)
        elif expecting == X_VALUE:
            if char == '"':
                if quotes_open:
                    end = True
                else:
                    quotes_open = True
            elif char in (',', ' ', '\t'):
                if quotes_open:
                    if not arr:
                        arr = [value]
                    else:
                        arr.append(value)
                    value = ""
                else:
                    end = True
            else:
                value = '%s%c' % (value, char)
        if end:
            if arr:
                arr.append(value)
                dict_[keyword] = arr
                arr = None
            else:
                dict_[keyword] = value
            value, keyword = '', ''
            expecting = X_KEYWORD
            quotes_open = False
    return dict_
119

120
def scram_parse(chatter):
121
    return dict(s.split('=', 1) for s in chatter.split(','))
122

123
class SASL(PlugIn):
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    """
    Implements SASL authentication. Can be plugged into NonBlockingClient
    to start authentication
    """

    def __init__(self, username, password, on_sasl):
        """
        :param user: XMPP username
        :param password: XMPP password
        :param on_sasl: Callback, will be called after each SASL auth-step.
        """
        PlugIn.__init__(self)
        self.username = username
        self.password = password
        self.on_sasl = on_sasl
        self.realm = None

    def plugin(self, owner):
        if 'version' not in self._owner.Dispatcher.Stream._document_attrs:
            self.startsasl = SASL_UNSUPPORTED
        elif self._owner.Dispatcher.Stream.features:
            try:
                self.FeaturesHandler(self._owner.Dispatcher,
Yann Leboulanger's avatar
Yann Leboulanger committed
147
                    self._owner.Dispatcher.Stream.features)
148 149 150 151 152 153 154 155 156 157 158
            except NodeProcessed:
                pass
        else:
            self.startsasl = None

    def plugout(self):
        """
        Remove SASL handlers from owner's dispatcher. Used internally
        """
        if 'features' in  self._owner.__dict__:
            self._owner.UnregisterHandler('features', self.FeaturesHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
159
                xmlns=NS_STREAMS)
160 161
        if 'challenge' in  self._owner.__dict__:
            self._owner.UnregisterHandler('challenge', self.SASLHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
162
                xmlns=NS_SASL)
163 164
        if 'failure' in  self._owner.__dict__:
            self._owner.UnregisterHandler('failure', self.SASLHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
165
                xmlns=NS_SASL)
166 167
        if 'success' in  self._owner.__dict__:
            self._owner.UnregisterHandler('success', self.SASLHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
168
                xmlns=NS_SASL)
169 170 171 172 173 174 175 176 177 178 179 180 181 182

    def auth(self):
        """
        Start authentication. Result can be obtained via "SASL.startsasl"
        attribute and will be either SASL_SUCCESS or SASL_FAILURE

        Note that successfull auth will take at least two Dispatcher.Process()
        calls.
        """
        if self.startsasl:
            pass
        elif self._owner.Dispatcher.Stream.features:
            try:
                self.FeaturesHandler(self._owner.Dispatcher,
Yann Leboulanger's avatar
Yann Leboulanger committed
183
                    self._owner.Dispatcher.Stream.features)
184 185 186 187
            except NodeProcessed:
                pass
        else:
            self._owner.RegisterHandler('features',
Yann Leboulanger's avatar
Yann Leboulanger committed
188
                self.FeaturesHandler, xmlns=NS_STREAMS)
189 190 191 192 193 194 195

    def FeaturesHandler(self, conn, feats):
        """
        Used to determine if server supports SASL auth. Used internally
        """
        if not feats.getTag('mechanisms', namespace=NS_SASL):
            self.startsasl='not-supported'
196
            log.info('SASL not supported by server')
197 198 199 200 201 202
            return
        self.mecs = []
        for mec in feats.getTag('mechanisms', namespace=NS_SASL).getTags(
        'mechanism'):
            self.mecs.append(mec.getData())

Yann Leboulanger's avatar
Yann Leboulanger committed
203 204
        self._owner.RegisterHandler('challenge', self.SASLHandler,
            xmlns=NS_SASL)
205 206 207 208 209 210 211
        self._owner.RegisterHandler('failure', self.SASLHandler, xmlns=NS_SASL)
        self._owner.RegisterHandler('success', self.SASLHandler, xmlns=NS_SASL)
        self.MechanismHandler()

    def MechanismHandler(self):
        if 'ANONYMOUS' in self.mecs and self.username is None:
            self.mecs.remove('ANONYMOUS')
Yann Leboulanger's avatar
Yann Leboulanger committed
212 213
            node = Node('auth', attrs={'xmlns': NS_SASL,
                'mechanism': 'ANONYMOUS'})
214 215 216 217 218 219
            self.mechanism = 'ANONYMOUS'
            self.startsasl = SASL_IN_PROCESS
            self._owner.send(str(node))
            raise NodeProcessed
        if "EXTERNAL" in self.mecs:
            self.mecs.remove('EXTERNAL')
Yann Leboulanger's avatar
Yann Leboulanger committed
220 221 222 223 224 225
            sasl_data = u'%s@%s' % (self.username, self._owner.Server)
            sasl_data = sasl_data.encode('utf-8').encode('base64').replace(
                '\n', '')
            node = Node('auth', attrs={'xmlns': NS_SASL,
                'mechanism': 'EXTERNAL'}, payload=[sasl_data])
            self.mechanism = 'EXTERNAL'
226 227 228 229 230 231 232
            self.startsasl = SASL_IN_PROCESS
            self._owner.send(str(node))
            raise NodeProcessed
        if 'GSSAPI' in self.mecs and have_kerberos:
            self.mecs.remove('GSSAPI')
            try:
                self.gss_vc = kerberos.authGSSClientInit('xmpp@' + \
Yann Leboulanger's avatar
Yann Leboulanger committed
233
                    self._owner.xmpp_hostname)[1]
234 235
                kerberos.authGSSClientStep(self.gss_vc, '')
                response = kerberos.authGSSClientResponse(self.gss_vc)
Yann Leboulanger's avatar
Yann Leboulanger committed
236 237
                node=Node('auth', attrs={'xmlns': NS_SASL,
                    'mechanism': 'GSSAPI'}, payload=(response or ''))
238 239 240 241 242 243 244
                self.mechanism = 'GSSAPI'
                self.gss_step = GSS_STATE_STEP
                self.startsasl = SASL_IN_PROCESS
                self._owner.send(str(node))
                raise NodeProcessed
            except kerberos.GSSError, e:
                log.info('GSSAPI authentication failed: %s' % str(e))
245 246 247
        if 'SCRAM-SHA-1' in self.mecs:
            self.mecs.remove('SCRAM-SHA-1')
            self.mechanism = 'SCRAM-SHA-1'
248
            self._owner._caller.get_password(self.set_password, self.mechanism)
249 250 251
            self.scram_step = 0
            self.startsasl = SASL_IN_PROCESS
            raise NodeProcessed
252 253
        if 'DIGEST-MD5' in self.mecs:
            self.mecs.remove('DIGEST-MD5')
Yann Leboulanger's avatar
Yann Leboulanger committed
254 255
            node = Node('auth', attrs={'xmlns': NS_SASL,
                'mechanism': 'DIGEST-MD5'})
256 257 258 259 260 261 262
            self.mechanism = 'DIGEST-MD5'
            self.startsasl = SASL_IN_PROCESS
            self._owner.send(str(node))
            raise NodeProcessed
        if 'PLAIN' in self.mecs:
            self.mecs.remove('PLAIN')
            self.mechanism = 'PLAIN'
263
            self._owner._caller.get_password(self.set_password, self.mechanism)
264 265 266
            self.startsasl = SASL_IN_PROCESS
            raise NodeProcessed
        self.startsasl = SASL_FAILURE
267 268
        log.info('I can only use EXTERNAL, SCRAM-SHA-1, DIGEST-MD5, GSSAPI and '
            'PLAIN mecanisms.')
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        if self.on_sasl:
            self.on_sasl()
        return

    def SASLHandler(self, conn, challenge):
        """
        Perform next SASL auth step. Used internally
        """
        if challenge.getNamespace() != NS_SASL:
            return
        ### Handle Auth result
        if challenge.getName() == 'failure':
            self.startsasl = SASL_FAILURE
            try:
                reason = challenge.getChildren()[0]
            except Exception:
                reason = challenge
286
            log.info('Failed SASL authentification: %s' % reason)
287 288 289 290 291 292 293 294
            if len(self.mecs) > 0:
                # There are other mechanisms to test
                self.MechanismHandler()
                raise NodeProcessed
            if self.on_sasl:
                self.on_sasl()
            raise NodeProcessed
        elif challenge.getName() == 'success':
295 296
            # TODO: Need to validate any data-with-success.
            # TODO: Important for DIGEST-MD5 and SCRAM.
297 298 299 300 301
            self.startsasl = SASL_SUCCESS
            log.info('Successfully authenticated with remote server.')
            handlers = self._owner.Dispatcher.dumpHandlers()

            # Bosh specific dispatcher replugging
Yann Leboulanger's avatar
Yann Leboulanger committed
302 303 304
            # save old features. They will be used in case we won't get response
            # on stream restart after SASL auth (happens with XMPP over BOSH
            # with Openfire)
305 306 307
            old_features = self._owner.Dispatcher.Stream.features
            self._owner.Dispatcher.PlugOut()
            dispatcher_nb.Dispatcher.get_instance().PlugIn(self._owner,
Yann Leboulanger's avatar
Yann Leboulanger committed
308
                after_SASL=True, old_features=old_features)
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            self._owner.Dispatcher.restoreHandlers(handlers)
            self._owner.User = self.username

            if self.on_sasl:
                self.on_sasl()
            raise NodeProcessed

        ### Perform auth step
        incoming_data = challenge.getData()
        data=base64.decodestring(incoming_data)
        log.info('Got challenge:' + data)

        if self.mechanism == 'GSSAPI':
            if self.gss_step == GSS_STATE_STEP:
                rc = kerberos.authGSSClientStep(self.gss_vc, incoming_data)
                if rc != kerberos.AUTH_GSS_CONTINUE:
                    self.gss_step = GSS_STATE_WRAP
            elif self.gss_step == GSS_STATE_WRAP:
                rc = kerberos.authGSSClientUnwrap(self.gss_vc, incoming_data)
                response = kerberos.authGSSClientResponse(self.gss_vc)
                rc = kerberos.authGSSClientWrap(self.gss_vc, response,
Yann Leboulanger's avatar
Yann Leboulanger committed
330
                    kerberos.authGSSClientUserName(self.gss_vc))
331 332 333
            response = kerberos.authGSSClientResponse(self.gss_vc)
            if not response:
                response = ''
334
            self._owner.send(Node('response', attrs={'xmlns': NS_SASL},
Yann Leboulanger's avatar
Yann Leboulanger committed
335
                payload=response).__str__())
336
            raise NodeProcessed
337 338
        if self.mechanism == 'SCRAM-SHA-1':
            hashfn = hashlib.sha1
339

340 341
            def HMAC(k, s):
                return hmac.HMAC(key=k, msg=s, digestmod=hashfn).digest()
342

343
            def XOR(x, y):
344
                r = (chr(ord(px) ^ ord(py)) for px, py in zip(x, y))
345
                return ''.join(r)
346

347 348 349
            def Hi(s, salt, iters):
                ii = 1
                try:
350
                    s = s.encode('utf-8')
351 352
                except:
                    pass
353
                ui_1 = HMAC(s, salt + '\0\0\0\01')
354 355 356
                ui = ui_1
                for i in range(iters - 1):
                    ii += 1
357
                    ui_1 = HMAC(s, ui_1)
358 359
                    ui = XOR(ui, ui_1)
                return ui
360

361 362
            def H(s):
                return hashfn(s).digest()
363

364 365
            def scram_base64(s):
                return ''.join(s.encode('base64').split('\n'))
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
            if self.scram_step == 0:
                self.scram_step = 1
                self.scram_soup += ',' + data + ','
                data = scram_parse(data)
                # TODO: Should check cnonce here.
                # TODO: Channel binding data goes in here too.
                r = 'c=' + scram_base64(self.scram_gs2)
                r += ',r=' + data['r']
                self.scram_soup += r
                salt = data['s'].decode('base64')
                iter = int(data['i'])
                SaltedPassword = Hi(self.password, salt, iter)
                # TODO: Could cache this, along with salt+iter.
                ClientKey = HMAC(SaltedPassword, 'Client Key')
                StoredKey = H(ClientKey)
                ClientSignature = HMAC(StoredKey, self.scram_soup)
                ClientProof = XOR(ClientKey, ClientSignature)
                r += ',p=' + scram_base64(ClientProof)
                ServerKey = HMAC(SaltedPassword, 'Server Key')
                self.scram_ServerSignature = HMAC(ServerKey, self.scram_soup)
                sasl_data = scram_base64(r)
                node = Node('response', attrs={'xmlns': NS_SASL},
                    payload=[sasl_data])
                self._owner.send(str(node))
                raise NodeProcessed
392

393 394 395 396
            if self.scram_step == 1:
                data = scram_parse(data)
                if data['v'].decode('base64') != self.scram_ServerSignature:
                    # TODO: Not clear what to do here - need to abort.
397
                    raise Exception
398 399 400
                node = Node('response', attrs={'xmlns': NS_SASL});
                self._owner.send(str(node))
                raise NodeProcessed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

        # magic foo...
        chal = challenge_splitter(data)
        if not self.realm and 'realm' in chal:
            self.realm = chal['realm']
        if 'qop' in chal and ((isinstance(chal['qop'], str) and \
        chal['qop'] =='auth') or (isinstance(chal['qop'], list) and 'auth' in \
        chal['qop'])):
            self.resp = {}
            self.resp['username'] = self.username
            if self.realm:
                self.resp['realm'] = self.realm
            else:
                self.resp['realm'] = self._owner.Server
            self.resp['nonce'] = chal['nonce']
Yann Leboulanger's avatar
Yann Leboulanger committed
416 417
            self.resp['cnonce'] = ''.join("%x" % randint(0, 2**28) for randint \
                in itertools.repeat(random.randint, 7))
418 419 420 421 422
            self.resp['nc'] = ('00000001')
            self.resp['qop'] = 'auth'
            self.resp['digest-uri'] = 'xmpp/' + self._owner.Server
            self.resp['charset'] = 'utf-8'
            # Password is now required
423
            self._owner._caller.get_password(self.set_password, self.mechanism)
424 425 426 427
        elif 'rspauth' in chal:
            self._owner.send(str(Node('response', attrs={'xmlns':NS_SASL})))
        else:
            self.startsasl = SASL_FAILURE
428
            log.info('Failed SASL authentification: unknown challenge')
429 430 431 432
        if self.on_sasl:
            self.on_sasl()
        raise NodeProcessed

Alexander Cherniuk's avatar
Alexander Cherniuk committed
433 434 435 436 437 438 439 440
    @staticmethod
    def _convert_to_iso88591(string):
        try:
            string = string.decode('utf-8').encode('iso-8859-1')
        except UnicodeEncodeError:
            pass
        return string

441
    def set_password(self, password):
Alexander Cherniuk's avatar
Alexander Cherniuk committed
442
        self.password = '' if password is None else password
443
        if self.mechanism == 'SCRAM-SHA-1':
Alexander Cherniuk's avatar
Alexander Cherniuk committed
444
            nonce = ''.join('%x' % randint(0, 2 ** 28) for randint in \
445 446 447 448
                itertools.repeat(random.randint, 7))
            self.scram_soup = 'n=' + self.username + ',r=' + nonce
            self.scram_gs2 = 'n,,' # No CB yet.
            sasl_data = (self.scram_gs2 + self.scram_soup).encode('base64').\
Éric Araujo's avatar
Éric Araujo committed
449
                replace('\n', '')
450 451 452
            node = Node('auth', attrs={'xmlns': NS_SASL,
                'mechanism': self.mechanism}, payload=[sasl_data])
        elif self.mechanism == 'DIGEST-MD5':
Alexander Cherniuk's avatar
Alexander Cherniuk committed
453 454 455
            hash_username = self._convert_to_iso88591(self.resp['username'])
            hash_realm = self._convert_to_iso88591(self.resp['realm'])
            hash_password = self._convert_to_iso88591(self.password)
456
            A1 = C([H(C([hash_username, hash_realm, hash_password])),
Yann Leboulanger's avatar
Yann Leboulanger committed
457
                self.resp['nonce'], self.resp['cnonce']])
458 459
            A2 = C(['AUTHENTICATE', self.resp['digest-uri']])
            response= HH(C([HH(A1), self.resp['nonce'], self.resp['nc'],
Yann Leboulanger's avatar
Yann Leboulanger committed
460
                self.resp['cnonce'], self.resp['qop'], HH(A2)]))
461 462 463 464
            self.resp['response'] = response
            sasl_data = u''
            for key in ('charset', 'username', 'realm', 'nonce', 'nc', 'cnonce',
            'digest-uri', 'response', 'qop'):
465
                if key in ('nc', 'qop', 'response', 'charset'):
466 467 468 469
                    sasl_data += u"%s=%s," % (key, self.resp[key])
                else:
                    sasl_data += u'%s="%s",' % (key, self.resp[key])
            sasl_data = sasl_data[:-1].encode('utf-8').encode('base64').replace(
Yann Leboulanger's avatar
Yann Leboulanger committed
470 471 472
                '\r', '').replace('\n', '')
            node = Node('response', attrs={'xmlns': NS_SASL},
                payload=[sasl_data])
473
        elif self.mechanism == 'PLAIN':
474
            sasl_data = u'\x00%s\x00%s' % (self.username, self.password)
475
            sasl_data = sasl_data.encode('utf-8').encode('base64').replace(
Yann Leboulanger's avatar
Yann Leboulanger committed
476
                '\n', '')
477
            node = Node('auth', attrs={'xmlns': NS_SASL, 'mechanism': 'PLAIN'},
Yann Leboulanger's avatar
Yann Leboulanger committed
478
                payload=[sasl_data])
479
        self._owner.send(str(node))
480

481

482
class NonBlockingNonSASL(PlugIn):
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    """
    Implements old Non-SASL (JEP-0078) authentication used in jabberd1.4 and
    transport authentication
    """

    def __init__(self, user, password, resource, on_auth):
        """
        Caches username, password and resource for auth
        """
        PlugIn.__init__(self)
        self.user = user
        if password is None:
            self.password = ''
        else:
            self.password = password
        self.resource = resource
        self.on_auth = on_auth
Yann Leboulanger's avatar
Yann Leboulanger committed
500 501


502 503 504 505 506 507 508 509 510
    def plugin(self, owner):
        """
        Determine the best auth method (digest/0k/plain) and use it for auth.
        Returns used method name on success. Used internally
        """
        log.info('Querying server about possible auth methods')
        self.owner = owner

        owner.Dispatcher.SendAndWaitForResponse(
Yann Leboulanger's avatar
Yann Leboulanger committed
511 512
            Iq('get', NS_AUTH, payload=[Node('username', payload=[self.user])]),
            func=self._on_username)
513 514 515

    def _on_username(self, resp):
        if not isResultNode(resp):
516
            log.info('No result node arrived! Aborting...')
517 518
            return self.on_auth(None)

519
        iq=Iq(typ='set', node=resp)
520
        query = iq.getTag('query')
521 522
        query.setTagData('username', self.user)
        query.setTagData('resource', self.resource)
523 524 525 526

        if query.getTag('digest'):
            log.info("Performing digest authentication")
            query.setTagData('digest',
Yann Leboulanger's avatar
Yann Leboulanger committed
527 528
                hashlib.sha1(self.owner.Dispatcher.Stream._document_attrs['id']
                + self.password).hexdigest())
529 530 531 532 533 534 535 536 537 538 539 540 541 542
            if query.getTag('password'):
                query.delChild('password')
            self._method = 'digest'
        elif query.getTag('token'):
            token = query.getTagData('token')
            seq = query.getTagData('sequence')
            log.info("Performing zero-k authentication")

            def hasher(s):
                return hashlib.sha1(s).hexdigest()

            def hash_n_times(s, count):
                return count and hasher(hash_n_times(s, count-1)) or s

Yann Leboulanger's avatar
Yann Leboulanger committed
543 544
            hash_ = hash_n_times(hasher(hasher(self.password) + token),
                int(seq))
545 546 547
            query.setTagData('hash', hash_)
            self._method='0k'
        else:
548
            log.warn("Secure methods unsupported, performing plain text \
Yann Leboulanger's avatar
Yann Leboulanger committed
549
                authentication")
550 551
            query.setTagData('password', self.password)
            self._method = 'plain'
Yann Leboulanger's avatar
Yann Leboulanger committed
552 553
        resp = self.owner.Dispatcher.SendAndWaitForResponse(iq,
            func=self._on_auth)
554 555 556 557 558 559

    def _on_auth(self, resp):
        if isResultNode(resp):
            log.info('Sucessfully authenticated with remote host.')
            self.owner.User = self.user
            self.owner.Resource = self.resource
Yann Leboulanger's avatar
Yann Leboulanger committed
560 561
            self.owner._registered_name = self.owner.User + '@' + \
                self.owner.Server+ '/' + self.owner.Resource
562
            return self.on_auth(self._method)
563
        log.info('Authentication failed!')
564
        return self.on_auth(None)
565

566

567
class NonBlockingBind(PlugIn):
568 569 570 571 572 573 574 575
    """
    Bind some JID to the current connection to allow router know of our
    location. Must be plugged after successful SASL auth
    """

    def __init__(self):
        PlugIn.__init__(self)
        self.bound = None
576
        self.supports_sm = False
577 578 579 580 581 582

    def plugin(self, owner):
        ''' Start resource binding, if allowed at this time. Used internally. '''
        if self._owner.Dispatcher.Stream.features:
            try:
                self.FeaturesHandler(self._owner.Dispatcher,
Yann Leboulanger's avatar
Yann Leboulanger committed
583
                    self._owner.Dispatcher.Stream.features)
584 585 586 587
            except NodeProcessed:
                pass
        else:
            self._owner.RegisterHandler('features', self.FeaturesHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
588
                xmlns=NS_STREAMS)
589 590 591 592

    def FeaturesHandler(self, conn, feats):
        """
        Determine if server supports resource binding and set some internal
593
        attributes accordingly.
Yann Leboulanger's avatar
Yann Leboulanger committed
594

595
        It also checks if server supports stream management
596
        """
Yann Leboulanger's avatar
Yann Leboulanger committed
597

598 599
        if feats.getTag('sm', namespace=NS_STREAM_MGMT):
            self.supports_sm = True # server supports stream management
Yann Leboulanger's avatar
Yann Leboulanger committed
600

601
        if not feats.getTag('bind', namespace=NS_BIND):
602
            log.info('Server does not requested binding.')
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
            # we try to bind resource anyway
            #self.bound='failure'
            self.bound = []
            return
        if feats.getTag('session', namespace=NS_SESSION):
            self.session = 1
        else:
            self.session = -1
        self.bound = []

    def plugout(self):
        """
        Remove Bind handler from owner's dispatcher. Used internally
        """
        self._owner.UnregisterHandler('features', self.FeaturesHandler,
Yann Leboulanger's avatar
Yann Leboulanger committed
618
            xmlns=NS_STREAMS)
619 620 621 622 623 624 625 626 627 628 629 630 631 632

    def NonBlockingBind(self, resource=None, on_bound=None):
        """
        Perform binding. Use provided resource name or random (if not provided).
        """
        self.on_bound = on_bound
        self._resource = resource
        if self._resource:
            self._resource = [Node('resource', payload=[self._resource])]
        else:
            self._resource = []

        self._owner.onreceive(None)
        self._owner.Dispatcher.SendAndWaitForResponse(
Yann Leboulanger's avatar
Yann Leboulanger committed
633 634 635
            Protocol('iq', typ='set', payload=[Node('bind',
            attrs={'xmlns': NS_BIND}, payload=self._resource)]),
            func=self._on_bound)
636 637 638 639 640 641 642 643 644

    def _on_bound(self, resp):
        if isResultNode(resp):
            if resp.getTag('bind') and resp.getTag('bind').getTagData('jid'):
                self.bound.append(resp.getTag('bind').getTagData('jid'))
                log.info('Successfully bound %s.' % self.bound[-1])
                jid = JID(resp.getTag('bind').getTagData('jid'))
                self._owner.User = jid.getNode()
                self._owner.Resource = jid.getResource()
645
                # Only negociate stream management after bounded
Yann Leboulanger's avatar
Yann Leboulanger committed
646
                if self.supports_sm:
647 648 649 650 651 652
                    # starts negociation
                    sm = Smacks(self._owner)
                    self._owner.Dispatcher.supports_sm = True
                    self._owner.Dispatcher.sm = sm
                    sm.negociate()

653 654 655 656 657 658
                if hasattr(self, 'session') and self.session == -1:
                    # Server don't want us to initialize a session
                    log.info('No session required.')
                    self.on_bound('ok')
                else:
                    self._owner.SendAndWaitForResponse(Protocol('iq', typ='set',
Yann Leboulanger's avatar
Yann Leboulanger committed
659 660
                        payload=[Node('session', attrs={'xmlns':NS_SESSION})]),
                        func=self._on_session)
661 662
                return
        if resp:
663
            log.info('Binding failed: %s.' % resp.getTag('error'))
664 665
            self.on_bound(None)
        else:
666
            log.info('Binding failed: timeout expired.')
667 668 669 670 671 672 673 674 675 676 677 678
            self.on_bound(None)

    def _on_session(self, resp):
        self._owner.onreceive(None)
        if isResultNode(resp):
            log.info('Successfully opened session.')
            self.session = 1
            self.on_bound('ok')
        else:
            log.error('Session open failed.')
            self.session = 0
            self.on_bound(None)