Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

544 linhas
22 KiB

  1. import aiohttp
  2. import aiohttp.web
  3. import asyncio
  4. import base64
  5. import collections
  6. import concurrent.futures
  7. import importlib.util
  8. import inspect
  9. import logging
  10. import os.path
  11. import signal
  12. import ssl
  13. import string
  14. import sys
  15. import toml
  16. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  17. class InvalidConfig(Exception):
  18. '''Error in configuration file'''
  19. def is_valid_pem(path, withCert):
  20. '''Very basic check whether something looks like a valid PEM certificate'''
  21. try:
  22. with open(path, 'rb') as fp:
  23. contents = fp.read()
  24. # All of these raise exceptions if something's wrong...
  25. if withCert:
  26. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  27. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  28. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  29. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  30. else:
  31. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  32. endCertPos = -26 # Please shoot me.
  33. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  34. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  35. assert contents[endKeyPos + 26:] == b''
  36. return True
  37. except: # Yes, really
  38. return False
  39. class Config(dict):
  40. def __init__(self, filename):
  41. super().__init__()
  42. self._filename = filename
  43. with open(self._filename, 'r') as fp:
  44. obj = toml.load(fp)
  45. logging.info(repr(obj))
  46. # Sanity checks
  47. if any(x not in ('logging', 'irc', 'web', 'maps') for x in obj.keys()):
  48. raise InvalidConfig('Unknown sections found in base object')
  49. if any(not isinstance(x, collections.abc.Mapping) for x in obj.values()):
  50. raise InvalidConfig('Invalid section type(s), expected objects/dicts')
  51. if 'logging' in obj:
  52. if any(x not in ('level', 'format') for x in obj['logging']):
  53. raise InvalidConfig('Unknown key found in log section')
  54. if 'level' in obj['logging'] and obj['logging']['level'] not in ('DEBUG', 'INFO', 'WARNING', 'ERROR'):
  55. raise InvalidConfig('Invalid log level')
  56. if 'format' in obj['logging']:
  57. if not isinstance(obj['logging']['format'], str):
  58. raise InvalidConfig('Invalid log format')
  59. try:
  60. #TODO: Replace with logging.Formatter's validate option (3.8+); this test does not cover everything that could be wrong (e.g. invalid format spec or conversion)
  61. # This counts the number of replacement fields. Formatter.parse yields tuples whose second value is the field name; if it's None, there is no field (e.g. literal text).
  62. assert sum(1 for x in string.Formatter().parse(obj['logging']['format']) if x[1] is not None) > 0
  63. except (ValueError, AssertionError) as e:
  64. raise InvalidConfig('Invalid log format: parsing failed') from e
  65. if 'irc' in obj:
  66. if any(x not in ('host', 'port', 'ssl', 'nick', 'real', 'certfile', 'certkeyfile') for x in obj['irc']):
  67. raise InvalidConfig('Unknown key found in irc section')
  68. if 'host' in obj['irc'] and not isinstance(obj['irc']['host'], str): #TODO: Check whether it's a valid hostname
  69. raise InvalidConfig('Invalid IRC host')
  70. if 'port' in obj['irc'] and (not isinstance(obj['irc']['port'], int) or not 1 <= obj['irc']['port'] <= 65535):
  71. raise InvalidConfig('Invalid IRC port')
  72. if 'ssl' in obj['irc'] and obj['irc']['ssl'] not in ('yes', 'no', 'insecure'):
  73. raise InvalidConfig(f'Invalid IRC SSL setting: {obj["irc"]["ssl"]!r}')
  74. if 'nick' in obj['irc'] and not isinstance(obj['irc']['nick'], str): #TODO: Check whether it's a valid nickname
  75. raise InvalidConfig('Invalid IRC nick')
  76. if 'real' in obj['irc'] and not isinstance(obj['irc']['real'], str):
  77. raise InvalidConfig('Invalid IRC realname')
  78. if ('certfile' in obj['irc']) != ('certkeyfile' in obj['irc']):
  79. raise InvalidConfig('Invalid IRC cert config: needs both certfile and certkeyfile')
  80. if 'certfile' in obj['irc']:
  81. if not isinstance(obj['irc']['certfile'], str):
  82. raise InvalidConfig('Invalid certificate file: not a string')
  83. if not os.path.isfile(obj['irc']['certfile']):
  84. raise InvalidConfig('Invalid certificate file: not a regular file')
  85. if not is_valid_pem(obj['irc']['certfile'], True):
  86. raise InvalidConfig('Invalid certificate file: not a valid PEM cert')
  87. if 'certkeyfile' in obj['irc']:
  88. if not isinstance(obj['irc']['certkeyfile'], str):
  89. raise InvalidConfig('Invalid certificate key file: not a string')
  90. if not os.path.isfile(obj['irc']['certkeyfile']):
  91. raise InvalidConfig('Invalid certificate key file: not a regular file')
  92. if not is_valid_pem(obj['irc']['certkeyfile'], False):
  93. raise InvalidConfig('Invalid certificate key file: not a valid PEM key')
  94. if 'web' in obj:
  95. if any(x not in ('host', 'port') for x in obj['web']):
  96. raise InvalidConfig('Unknown key found in web section')
  97. if 'host' in obj['web'] and not isinstance(obj['web']['host'], str): #TODO: Check whether it's a valid hostname (must resolve I guess?)
  98. raise InvalidConfig('Invalid web hostname')
  99. if 'port' in obj['web'] and (not isinstance(obj['web']['port'], int) or not 1 <= obj['web']['port'] <= 65535):
  100. raise InvalidConfig('Invalid web port')
  101. if 'maps' in obj:
  102. for key, map_ in obj['maps'].items():
  103. if not isinstance(key, str) or not key:
  104. raise InvalidConfig(f'Invalid map key {key!r}')
  105. if not isinstance(map_, collections.abc.Mapping):
  106. raise InvalidConfig(f'Invalid map for {key!r}')
  107. if any(x not in ('webpath', 'ircchannel', 'auth', 'module', 'moduleargs') for x in map_):
  108. raise InvalidConfig(f'Unknown key(s) found in map {key!r}')
  109. #TODO: Check values
  110. if 'module' in map_ and not os.path.isfile(map_['module']):
  111. raise InvalidConfig(f'Module {map_["module"]!r} in map {key!r} is not a file')
  112. if 'moduleargs' in map_:
  113. if not isinstance(map_['moduleargs'], list):
  114. raise InvalidConfig(f'Invalid module args for {key!r}: not an array')
  115. if 'module' not in map_:
  116. raise InvalidConfig(f'Module args cannot be specified without a module for {key!r}')
  117. # Default values
  118. finalObj = {'logging': {'level': 'INFO', 'format': '{asctime} {levelname} {message}'}, 'irc': {'host': 'irc.hackint.org', 'port': 6697, 'ssl': 'yes', 'nick': 'h2ibot', 'real': 'I am an http2irc bot.', 'certfile': None, 'certkeyfile': None}, 'web': {'host': '127.0.0.1', 'port': 8080}, 'maps': {}}
  119. # Fill in default values for the maps
  120. for key, map_ in obj['maps'].items():
  121. if 'webpath' not in map_:
  122. map_['webpath'] = f'/{key}'
  123. if 'ircchannel' not in map_:
  124. map_['ircchannel'] = f'#{key}'
  125. if 'auth' not in map_:
  126. map_['auth'] = False
  127. if 'module' not in map_:
  128. map_['module'] = None
  129. if 'moduleargs' not in map_:
  130. map_['moduleargs'] = []
  131. # Load modules
  132. modulePaths = {} # path: str -> (extraargs: int, key: str)
  133. for key, map_ in obj['maps'].items():
  134. if map_['module'] is not None:
  135. if map_['module'] not in modulePaths:
  136. modulePaths[map_['module']] = (len(map_['moduleargs']), key)
  137. elif modulePaths[map_['module']][0] != len(map_['moduleargs']):
  138. raise InvalidConfig(f'Module {map_["module"]!r} process function extra argument inconsistency between {key!r} and {modulePaths[map_["module"]][1]!r}')
  139. modules = {} # path: str -> module: module
  140. for i, (path, (extraargs, _)) in enumerate(modulePaths.items()):
  141. try:
  142. # Build a name that is virtually guaranteed to be unique across a process.
  143. # Although importlib does not seem to perform any caching as of CPython 3.8, this is not guaranteed by spec.
  144. spec = importlib.util.spec_from_file_location(f'http2irc-module-{id(self)}-{i}', path)
  145. module = importlib.util.module_from_spec(spec)
  146. spec.loader.exec_module(module)
  147. except Exception as e: # This is ugly, but exec_module can raise virtually any exception
  148. raise InvalidConfig(f'Loading module {path!r} failed: {e!s}')
  149. if not hasattr(module, 'process'):
  150. raise InvalidConfig(f'Module {path!r} does not have a process function')
  151. if not inspect.iscoroutinefunction(module.process):
  152. raise InvalidConfig(f'Module {path!r} process attribute is not a coroutine function')
  153. nargs = len(inspect.signature(module.process).parameters)
  154. if nargs != 1 + extraargs:
  155. raise InvalidConfig(f'Module {path!r} process function takes {nargs} parameter{"s" if nargs > 1 else ""}, not {1 + extraargs}')
  156. modules[path] = module
  157. # Replace module value in maps
  158. for map_ in obj['maps'].values():
  159. if 'module' in map_ and map_['module'] is not None:
  160. map_['module'] = modules[map_['module']]
  161. # Merge in what was read from the config file and set keys on self
  162. for key in ('logging', 'irc', 'web', 'maps'):
  163. if key in obj:
  164. finalObj[key].update(obj[key])
  165. self[key] = finalObj[key]
  166. def __repr__(self):
  167. return f'<Config(logging={self["logging"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, maps={self["maps"]!r})>'
  168. def reread(self):
  169. return Config(self._filename)
  170. class MessageQueue:
  171. # An object holding onto the messages received from nodeping
  172. # This is effectively a reimplementation of parts of asyncio.Queue with some specific additional code.
  173. # Unfortunately, asyncio.Queue's extensibility (_init, _put, and _get methods) is undocumented, so I don't want to rely on that.
  174. # Differences to asyncio.Queue include:
  175. # - No maxsize
  176. # - No put coroutine (not necessary since the queue can never be full)
  177. # - Only one concurrent getter
  178. # - putleft_nowait to put to the front of the queue (so that the IRC client can put a message back when delivery fails)
  179. def __init__(self):
  180. self._getter = None # None | asyncio.Future
  181. self._queue = collections.deque()
  182. async def get(self):
  183. if self._getter is not None:
  184. raise RuntimeError('Cannot get concurrently')
  185. if len(self._queue) == 0:
  186. self._getter = asyncio.get_running_loop().create_future()
  187. logging.debug('Awaiting getter')
  188. try:
  189. await self._getter
  190. except asyncio.CancelledError:
  191. logging.debug('Cancelled getter')
  192. self._getter = None
  193. raise
  194. logging.debug('Awaited getter')
  195. self._getter = None
  196. # For testing the cancellation/putting back onto the queue
  197. #logging.debug('Delaying message queue get')
  198. #await asyncio.sleep(3)
  199. #logging.debug('Done delaying')
  200. return self.get_nowait()
  201. def get_nowait(self):
  202. if len(self._queue) == 0:
  203. raise asyncio.QueueEmpty
  204. return self._queue.popleft()
  205. def put_nowait(self, item):
  206. self._queue.append(item)
  207. if self._getter is not None and not self._getter.cancelled():
  208. self._getter.set_result(None)
  209. def putleft_nowait(self, *item):
  210. self._queue.extendleft(reversed(item))
  211. if self._getter is not None and not self._getter.cancelled():
  212. self._getter.set_result(None)
  213. def qsize(self):
  214. return len(self._queue)
  215. class IRCClientProtocol(asyncio.Protocol):
  216. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  217. logging.debug(f'Protocol init {id(self)}: {messageQueue} {id(messageQueue)}, {connectionClosedEvent}, {loop}')
  218. self.messageQueue = messageQueue
  219. self.connectionClosedEvent = connectionClosedEvent
  220. self.loop = loop
  221. self.config = config
  222. self.buffer = b''
  223. self.connected = False
  224. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  225. self.unconfirmedMessages = []
  226. self.pongReceivedEvent = asyncio.Event()
  227. def connection_made(self, transport):
  228. logging.info('Connected')
  229. self.transport = transport
  230. self.connected = True
  231. nickb = self.config['irc']['nick'].encode('utf-8')
  232. self.send(b'NICK ' + nickb)
  233. self.send(b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + self.config['irc']['real'].encode('utf-8'))
  234. def update_channels(self, channels: set):
  235. channelsToPart = self.channels - channels
  236. channelsToJoin = channels - self.channels
  237. self.channels = channels
  238. if self.connected:
  239. if channelsToPart:
  240. #TODO: Split if too long
  241. self.send(b'PART ' + ','.join(channelsToPart).encode('utf-8'))
  242. if channelsToJoin:
  243. self.send(b'JOIN ' + ','.join(channelsToJoin).encode('utf-8'))
  244. def send(self, data):
  245. logging.info(f'Send: {data!r}')
  246. self.transport.write(data + b'\r\n')
  247. async def _get_message(self):
  248. logging.debug(f'Message queue {id(self.messageQueue)} length: {self.messageQueue.qsize()}')
  249. messageFuture = asyncio.create_task(self.messageQueue.get())
  250. done, pending = await asyncio.wait((messageFuture, self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  251. if self.connectionClosedEvent.is_set():
  252. if messageFuture in pending:
  253. logging.debug('Cancelling messageFuture')
  254. messageFuture.cancel()
  255. try:
  256. await messageFuture
  257. except asyncio.CancelledError:
  258. logging.debug('Cancelled messageFuture')
  259. pass
  260. else:
  261. # messageFuture is already done but we're stopping, so put the result back onto the queue
  262. self.messageQueue.putleft_nowait(messageFuture.result())
  263. return None, None
  264. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  265. return messageFuture.result()
  266. async def send_messages(self):
  267. while self.connected:
  268. logging.debug(f'{id(self)}: trying to get a message')
  269. channel, message = await self._get_message()
  270. logging.debug(f'{id(self)}: got message: {message!r}')
  271. if message is None:
  272. break
  273. #TODO Split if the message is too long.
  274. self.unconfirmedMessages.append((channel, message))
  275. self.send(b'PRIVMSG ' + channel.encode('utf-8') + b' :' + message.encode('utf-8'))
  276. await asyncio.sleep(1) # Rate limit
  277. async def confirm_messages(self):
  278. while self.connected:
  279. await asyncio.wait((asyncio.sleep(60), self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED) # Confirm once per minute
  280. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  281. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  282. self.unconfirmedMessages = []
  283. break
  284. if not self.unconfirmedMessages:
  285. logging.debug(f'{id(self)}: no messages to confirm')
  286. continue
  287. logging.debug(f'{id(self)}: trying to confirm message delivery')
  288. self.pongReceivedEvent.clear()
  289. self.send(b'PING :42')
  290. await asyncio.wait((asyncio.sleep(5), self.pongReceivedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  291. logging.debug(f'{id(self)}: message delivery success: {self.pongReceivedEvent.is_set()}')
  292. if not self.pongReceivedEvent.is_set():
  293. # No PONG received in five seconds, assume connection's dead
  294. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  295. self.transport.close()
  296. self.unconfirmedMessages = []
  297. def data_received(self, data):
  298. logging.debug(f'Data received: {data!r}')
  299. # Split received data on CRLF. If there's any data left in the buffer, prepend it to the first message and process that.
  300. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  301. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  302. messages = data.split(b'\r\n')
  303. if self.buffer:
  304. self.message_received(self.buffer + messages[0])
  305. messages = messages[1:]
  306. for message in messages[:-1]:
  307. self.message_received(message)
  308. self.buffer = messages[-1]
  309. def message_received(self, message):
  310. logging.info(f'Message received: {message!r}')
  311. if message.startswith(b':'):
  312. # Prefixed message, extract command + parameters (the prefix cannot contain a space)
  313. message = message.split(b' ', 1)[1]
  314. if message.startswith(b'PING '):
  315. self.send(b'PONG ' + message[5:])
  316. elif message.startswith(b'PONG '):
  317. self.pongReceivedEvent.set()
  318. elif message.startswith(b'001 '):
  319. # Connection registered
  320. self.send(b'JOIN ' + ','.join(self.channels).encode('utf-8')) #TODO: Split if too long
  321. asyncio.create_task(self.send_messages())
  322. asyncio.create_task(self.confirm_messages())
  323. def connection_lost(self, exc):
  324. logging.info('The server closed the connection')
  325. self.connected = False
  326. self.connectionClosedEvent.set()
  327. class IRCClient:
  328. def __init__(self, messageQueue, config):
  329. self.messageQueue = messageQueue
  330. self.config = config
  331. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  332. self._transport = None
  333. self._protocol = None
  334. def update_config(self, config):
  335. needReconnect = self.config['irc'] != config['irc']
  336. self.config = config
  337. if self._transport: # if currently connected:
  338. if needReconnect:
  339. self._transport.close()
  340. else:
  341. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  342. self._protocol.update_channels(self.channels)
  343. def _get_ssl_context(self):
  344. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  345. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  346. if ctx is True:
  347. ctx = ssl.create_default_context()
  348. if isinstance(ctx, ssl.SSLContext):
  349. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  350. return ctx
  351. async def run(self, loop, sigintEvent):
  352. connectionClosedEvent = asyncio.Event()
  353. while True:
  354. connectionClosedEvent.clear()
  355. try:
  356. self._transport, self._protocol = await loop.create_connection(lambda: IRCClientProtocol(self.messageQueue, connectionClosedEvent, loop, self.config, self.channels), self.config['irc']['host'], self.config['irc']['port'], ssl = self._get_ssl_context())
  357. try:
  358. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  359. finally:
  360. self._transport.close() #TODO BaseTransport.close is asynchronous and then triggers the protocol's connection_lost callback; need to wait for connectionClosedEvent again perhaps to correctly handle ^C?
  361. except (ConnectionRefusedError, asyncio.TimeoutError) as e:
  362. logging.error(str(e))
  363. await asyncio.wait((asyncio.sleep(5), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  364. if sigintEvent.is_set():
  365. break
  366. class WebServer:
  367. def __init__(self, messageQueue, config):
  368. self.messageQueue = messageQueue
  369. self.config = config
  370. self._paths = {} # '/path' => ('#channel', auth, module, moduleargs) where auth is either False (no authentication) or the HTTP header value for basic auth
  371. self._app = aiohttp.web.Application()
  372. self._app.add_routes([aiohttp.web.post('/{path:.+}', self.post)])
  373. self.update_config(config)
  374. self._configChanged = asyncio.Event()
  375. def update_config(self, config):
  376. self._paths = {map_['webpath']: (map_['ircchannel'], f'Basic {base64.b64encode(map_["auth"].encode("utf-8")).decode("utf-8")}' if map_['auth'] else False, map_['module'], map_['moduleargs']) for map_ in config['maps'].values()}
  377. needRebind = self.config['web'] != config['web']
  378. self.config = config
  379. if needRebind:
  380. self._configChanged.set()
  381. async def run(self, stopEvent):
  382. while True:
  383. runner = aiohttp.web.AppRunner(self._app)
  384. await runner.setup()
  385. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  386. await site.start()
  387. await asyncio.wait((stopEvent.wait(), self._configChanged.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  388. await runner.cleanup()
  389. if stopEvent.is_set():
  390. break
  391. self._configChanged.clear()
  392. async def post(self, request):
  393. logging.info(f'Received request for {request.path!r}')
  394. try:
  395. channel, auth, module, moduleargs = self._paths[request.path]
  396. except KeyError:
  397. logging.info(f'Bad request: no path {request.path!r}')
  398. raise aiohttp.web.HTTPNotFound()
  399. if auth:
  400. authHeader = request.headers.get('Authorization')
  401. if not authHeader or authHeader != auth:
  402. logging.info(f'Bad request: authentication failed: {authHeader!r} != {auth}')
  403. raise aiohttp.web.HTTPForbidden()
  404. if module is not None:
  405. try:
  406. message = await module.process(request, *moduleargs)
  407. except aiohttp.web.HTTPException as e:
  408. raise e
  409. except Exception as e:
  410. logging.error(f'Bad request: exception in module process function: {e!s}')
  411. raise aiohttp.web.HTTPBadRequest()
  412. if '\r' in message or '\n' in message:
  413. logging.error(f'Bad request: module process function returned message with linebreaks: {message!r}')
  414. raise aiohttp.web.HTTPBadRequest()
  415. else:
  416. message = await self._default_process(request)
  417. logging.debug(f'Putting message {message!r} for {channel} into message queue')
  418. self.messageQueue.put_nowait((channel, message))
  419. raise aiohttp.web.HTTPOk()
  420. async def _default_process(self, request):
  421. try:
  422. message = await request.text()
  423. except Exception as e:
  424. logging.info(f'Bad request: exception while reading request data: {e!s}')
  425. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  426. logging.debug(f'Request payload: {message!r}')
  427. # Strip optional [CR] LF at the end of the payload
  428. if message.endswith('\r\n'):
  429. message = message[:-2]
  430. elif message.endswith('\n'):
  431. message = message[:-1]
  432. if '\r' in message or '\n' in message:
  433. logging.info('Bad request: linebreaks in message')
  434. raise aiohttp.web.HTTPBadRequest()
  435. return message
  436. def configure_logging(config):
  437. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  438. root = logging.getLogger()
  439. root.setLevel(getattr(logging, config['logging']['level']))
  440. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  441. formatter = logging.Formatter(config['logging']['format'], style = '{')
  442. stderrHandler = logging.StreamHandler()
  443. stderrHandler.setFormatter(formatter)
  444. root.addHandler(stderrHandler)
  445. async def main():
  446. if len(sys.argv) != 2:
  447. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  448. sys.exit(1)
  449. configFile = sys.argv[1]
  450. config = Config(configFile)
  451. configure_logging(config)
  452. loop = asyncio.get_running_loop()
  453. messageQueue = MessageQueue()
  454. irc = IRCClient(messageQueue, config)
  455. webserver = WebServer(messageQueue, config)
  456. sigintEvent = asyncio.Event()
  457. def sigint_callback():
  458. logging.info('Got SIGINT')
  459. nonlocal sigintEvent
  460. sigintEvent.set()
  461. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  462. def sigusr1_callback():
  463. logging.info('Got SIGUSR1, reloading config')
  464. nonlocal config, irc, webserver
  465. try:
  466. newConfig = config.reread()
  467. except InvalidConfig as e:
  468. logging.error(f'Config reload failed: {e!s}')
  469. return
  470. config = newConfig
  471. configure_logging(config)
  472. irc.update_config(config)
  473. webserver.update_config(config)
  474. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  475. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  476. if __name__ == '__main__':
  477. asyncio.run(main())