starttls.py 2.04 KB
Newer Older
1

2 3 4 5
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2011  Nathanael C. Fritz
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
6 7
import logging

louiz’'s avatar
louiz’ committed
8
from slixmpp.stanza import StreamFeatures
9
from slixmpp.xmlstream import register_stanza_plugin
louiz’'s avatar
louiz’ committed
10 11
from slixmpp.plugins import BasePlugin
from slixmpp.xmlstream.matcher import MatchXPath
mathieui's avatar
mathieui committed
12
from slixmpp.xmlstream.handler import CoroutineCallback
louiz’'s avatar
louiz’ committed
13
from slixmpp.features.feature_starttls import stanza
14

mathieui's avatar
mathieui committed
15 16
from typing import ClassVar, Set

17 18 19 20

log = logging.getLogger(__name__)


21
class FeatureSTARTTLS(BasePlugin):
22

23 24
    name = 'feature_starttls'
    description = 'RFC 6120: Stream Feature: STARTTLS'
mathieui's avatar
mathieui committed
25
    dependencies: ClassVar[Set[str]] = set()
26
    stanza = stanza
27

28
    def plugin_init(self):
29
        self.xmpp.register_handler(
mathieui's avatar
mathieui committed
30
                CoroutineCallback('STARTTLS Proceed',
31 32 33
                        MatchXPath(stanza.Proceed.tag_name()),
                        self._handle_starttls_proceed,
                        instream=True))
34 35 36 37 38
        self.xmpp.register_feature('starttls',
                self._handle_starttls,
                restart=True,
                order=self.config.get('order', 0))

39 40 41 42
        self.xmpp.register_stanza(stanza.Proceed)
        self.xmpp.register_stanza(stanza.Failure)
        register_stanza_plugin(StreamFeatures, stanza.STARTTLS)

43 44 45 46 47 48 49
    def _handle_starttls(self, features):
        """
        Handle notification that the server supports TLS.

        Arguments:
            features -- The stream:features element.
        """
50 51 52 53
        if 'starttls' in self.xmpp.features:
            # We have already negotiated TLS, but the server is
            # offering it again, against spec.
            return False
louiz’'s avatar
louiz’ committed
54
        elif self.xmpp.disable_starttls:
55
            return False
56
        else:
57
            self.xmpp.send(stanza.STARTTLS())
58 59
            return True

mathieui's avatar
mathieui committed
60
    async def _handle_starttls_proceed(self, proceed):
61 62
        """Restart the XML stream when TLS is accepted."""
        log.debug("Starting TLS")
mathieui's avatar
mathieui committed
63
        if await self.xmpp.start_tls():
64
            self.xmpp.features.add('starttls')