monolith/modules/network.py

95 lines
3.3 KiB
Python
Raw Normal View History

from twisted.internet.ssl import DefaultOpenSSLContextFactory
import json
from modules import alias
2019-10-08 20:10:42 +00:00
from modules.chankeep import nukeNetwork
from modules.regproc import needToRegister
from twisted.internet import reactor
from core.bot import IRCBot, IRCBotFactory
import main
from utils.logging.log import *
from utils.get import getRelay
2022-07-21 12:39:41 +00:00
class Network:
def __init__(self, net, host, port, security, auth):
self.net = net
self.host = host
self.port = port
self.security = security
self.auth = auth
self.last = 1
self.relays = {}
self.aliases = {}
def add_relay(self, num=None):
if not num:
num = self.last
self.last += 1
elif num == self.last:
self.last += 1
registered = False
if not needToRegister(self.net):
registered = True
# Don't need to register if it's been disabled in definitions,
# so we'll pretend we already did
self.relays[num] = {
"enabled": main.config["ConnectOnCreate"],
"net": self.net,
"id": num,
2022-07-21 12:39:41 +00:00
"registered": registered,
}
password = alias.generate_password()
if not num in main.alias.keys():
main.alias[num] = alias.generate_alias()
main.saveConf("alias")
self.aliases[num] = {"password": password}
2022-07-21 12:39:41 +00:00
# if main.config["ConnectOnCreate"]: -- Done in provision
# self.start_bot(num)
return num, main.alias[num]["nick"]
def killAliases(self, aliasList):
for i in aliasList:
2022-07-21 12:39:41 +00:00
name = self.net + str(i)
if name in main.ReactorPool.keys():
if name in main.FactoryPool.keys():
main.FactoryPool[name].stopTrying()
main.ReactorPool[name].disconnect()
if name in main.IRCPool.keys():
del main.IRCPool[name]
del main.ReactorPool[name]
del main.FactoryPool[name]
def delete_relay(self, id):
del self.relays[id]
del self.aliases[id]
2022-07-21 12:39:41 +00:00
# del main.alias[id] - Aliases are global per num, so don't delete them!
self.killAliases([id])
def seppuku(self):
# Removes all bots in preperation for deletion
self.killAliases(self.relays.keys())
2019-10-08 20:10:42 +00:00
nukeNetwork(self.net)
def start_bot(self, num):
# a single name is given to relays in the backend
# e.g. freenode1 for the first relay on freenode network
2022-07-21 12:39:41 +00:00
keyFN = main.certPath + main.config["Key"]
certFN = main.certPath + main.config["Certificate"]
contextFactory = DefaultOpenSSLContextFactory(keyFN.encode("utf-8", "replace"), certFN.encode("utf-8", "replace"))
bot = IRCBotFactory(self.net, num)
2022-07-21 12:39:41 +00:00
# host, port = self.relays[num]["host"], self.relays[num]["port"]
host, port = getRelay(num)
rct = reactor.connectSSL(host, port, bot, contextFactory)
name = self.net + str(num)
main.ReactorPool[name] = rct
main.FactoryPool[name] = bot
log("Started bot on relay %s on %s" % (num, self.host))
def start_bots(self):
for num in self.relays.keys():
if self.relays[num]["enabled"]:
self.start_bot(num)