bitbot-3.11-fork/modules/sts.py

70 lines
2.8 KiB
Python
Raw Normal View History

2018-11-05 12:39:02 +00:00
import time
from src import ModuleManager, utils
class Module(ModuleManager.BaseModule):
def _get_policy(self, server):
return server.get_setting("sts-policy", None)
def _set_policy(self, server, policy):
2018-11-05 14:57:34 +00:00
self.log.trace("Setting STS policy for '%s': %s", [str(server), policy])
server.set_setting("sts-policy", policy)
def _remove_policy(self, server):
server.del_setting("sts-policy")
def set_policy(self, server, port, duration):
2018-11-05 12:39:02 +00:00
expiration = None
self._set_policy(server, {
2018-11-05 12:39:02 +00:00
"port": port,
2018-11-05 14:12:59 +00:00
"from": time.time(),
"duration": duration})
def change_duration(self, server, info):
duration = int(info["duration"])
if duration == 0:
self._remove_policy(server)
else:
port = server.connection_params.port
if "port" in info:
port = int(info["port"])
self.set_policy(server, port, duration)
2018-11-05 12:39:02 +00:00
2018-11-05 14:52:25 +00:00
def _get_sts(self, capabilities):
return capabilities.get("sts", capabilities.get("draft/sts", None))
2018-11-05 12:39:02 +00:00
@utils.hook("received.cap.ls")
def on_cap_ls(self, event):
2018-11-05 14:52:25 +00:00
sts = self._get_sts(event["capabilities"])
if sts:
info = utils.parse.keyvalue(sts, delimiter=",")
if not event["server"].connection_params.tls:
self.set_policy(event["server"], int(info["port"]), None)
event["server"].disconnect()
self.bot.reconnect(event["server"].id,
event["server"].connection_params)
2018-11-05 12:39:02 +00:00
else:
self.change_duration(event["server"], info)
2018-11-05 12:39:02 +00:00
@utils.hook("received.cap.new")
def on_cap_new(self, event):
2018-11-05 14:52:25 +00:00
sts = self._get_sts(event["capabilities"])
if sts and event["server"].connection_params.tls:
2018-11-05 14:52:25 +00:00
info = utils.parse.keyvalue(sts, delimiter=",")
self.change_duration(event["server"], info)
2018-11-05 12:39:02 +00:00
@utils.hook("new.server")
def new_server(self, event):
sts_policy = self._get_policy(event["server"])
if sts_policy:
if not event["server"].connection_params.tls:
if not sts_policy["duration"] or time.time() <= (
sts_policy["from"]+sts_policy["duration"]):
self.log.trace("Applying STS policy for '%s'",
[str(event["server"])])
event["server"].connection_params.tls = True
event["server"].connection_params.port = sts_policy["port"]
@utils.hook("server.disconnect")
def on_disconnect(self, event):
sts_policy = self._get_policy(event["server"])
if sts_policy and sts_policy["duration"]:
sts_policy["from"] = time.time()
2018-11-05 14:13:27 +00:00
self._set_policy(event["server"], sts_policy)