您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

556 行
23 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. logger = logging.getLogger('http2irc')
  17. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  18. class InvalidConfig(Exception):
  19. '''Error in configuration file'''
  20. def is_valid_pem(path, withCert):
  21. '''Very basic check whether something looks like a valid PEM certificate'''
  22. try:
  23. with open(path, 'rb') as fp:
  24. contents = fp.read()
  25. # All of these raise exceptions if something's wrong...
  26. if withCert:
  27. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  28. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  29. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  30. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  31. else:
  32. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  33. endCertPos = -26 # Please shoot me.
  34. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  35. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  36. assert contents[endKeyPos + 26:] == b''
  37. return True
  38. except: # Yes, really
  39. return False
  40. class Config(dict):
  41. def __init__(self, filename):
  42. super().__init__()
  43. self._filename = filename
  44. with open(self._filename, 'r') as fp:
  45. obj = toml.load(fp)
  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} {name} {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. logger = logging.getLogger('http2irc.MessageQueue')
  180. def __init__(self):
  181. self._getter = None # None | asyncio.Future
  182. self._queue = collections.deque()
  183. async def get(self):
  184. if self._getter is not None:
  185. raise RuntimeError('Cannot get concurrently')
  186. if len(self._queue) == 0:
  187. self._getter = asyncio.get_running_loop().create_future()
  188. self.logger.debug('Awaiting getter')
  189. try:
  190. await self._getter
  191. except asyncio.CancelledError:
  192. self.logger.debug('Cancelled getter')
  193. self._getter = None
  194. raise
  195. self.logger.debug('Awaited getter')
  196. self._getter = None
  197. # For testing the cancellation/putting back onto the queue
  198. #self.logger.debug('Delaying message queue get')
  199. #await asyncio.sleep(3)
  200. #self.logger.debug('Done delaying')
  201. return self.get_nowait()
  202. def get_nowait(self):
  203. if len(self._queue) == 0:
  204. raise asyncio.QueueEmpty
  205. return self._queue.popleft()
  206. def put_nowait(self, item):
  207. self._queue.append(item)
  208. if self._getter is not None and not self._getter.cancelled():
  209. self._getter.set_result(None)
  210. def putleft_nowait(self, *item):
  211. self._queue.extendleft(reversed(item))
  212. if self._getter is not None and not self._getter.cancelled():
  213. self._getter.set_result(None)
  214. def qsize(self):
  215. return len(self._queue)
  216. class IRCClientProtocol(asyncio.Protocol):
  217. logger = logging.getLogger('http2irc.IRCClientProtocol')
  218. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  219. self.messageQueue = messageQueue
  220. self.connectionClosedEvent = connectionClosedEvent
  221. self.loop = loop
  222. self.config = config
  223. self.buffer = b''
  224. self.connected = False
  225. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  226. self.unconfirmedMessages = []
  227. self.pongReceivedEvent = asyncio.Event()
  228. def connection_made(self, transport):
  229. self.logger.info('IRC connected')
  230. self.transport = transport
  231. self.connected = True
  232. nickb = self.config['irc']['nick'].encode('utf-8')
  233. self.send(b'NICK ' + nickb)
  234. self.send(b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + self.config['irc']['real'].encode('utf-8'))
  235. def update_channels(self, channels: set):
  236. channelsToPart = self.channels - channels
  237. channelsToJoin = channels - self.channels
  238. self.channels = channels
  239. if self.connected:
  240. if channelsToPart:
  241. #TODO: Split if too long
  242. self.send(b'PART ' + ','.join(channelsToPart).encode('utf-8'))
  243. if channelsToJoin:
  244. self.send(b'JOIN ' + ','.join(channelsToJoin).encode('utf-8'))
  245. def send(self, data):
  246. self.logger.debug(f'Send: {data!r}')
  247. self.transport.write(data + b'\r\n')
  248. async def _get_message(self):
  249. self.logger.debug(f'Message queue {id(self.messageQueue)} length: {self.messageQueue.qsize()}')
  250. messageFuture = asyncio.create_task(self.messageQueue.get())
  251. done, pending = await asyncio.wait((messageFuture, self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  252. if self.connectionClosedEvent.is_set():
  253. if messageFuture in pending:
  254. self.logger.debug('Cancelling messageFuture')
  255. messageFuture.cancel()
  256. try:
  257. await messageFuture
  258. except asyncio.CancelledError:
  259. self.logger.debug('Cancelled messageFuture')
  260. pass
  261. else:
  262. # messageFuture is already done but we're stopping, so put the result back onto the queue
  263. self.messageQueue.putleft_nowait(messageFuture.result())
  264. return None, None
  265. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  266. return messageFuture.result()
  267. async def send_messages(self):
  268. while self.connected:
  269. self.logger.debug(f'Trying to get a message')
  270. channel, message = await self._get_message()
  271. self.logger.debug(f'Got message: {message!r}')
  272. if message is None:
  273. break
  274. self.logger.info(f'Sending {message!r} to {channel!r}')
  275. #TODO Split if the message is too long.
  276. self.unconfirmedMessages.append((channel, message))
  277. self.send(b'PRIVMSG ' + channel.encode('utf-8') + b' :' + message.encode('utf-8'))
  278. await asyncio.sleep(1) # Rate limit
  279. async def confirm_messages(self):
  280. while self.connected:
  281. await asyncio.wait((asyncio.sleep(60), self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED) # Confirm once per minute
  282. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  283. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  284. self.unconfirmedMessages = []
  285. break
  286. if not self.unconfirmedMessages:
  287. self.logger.debug('No messages to confirm')
  288. continue
  289. self.logger.debug('Trying to confirm message delivery')
  290. self.pongReceivedEvent.clear()
  291. self.send(b'PING :42')
  292. await asyncio.wait((asyncio.sleep(5), self.pongReceivedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  293. self.logger.debug(f'Message delivery successful: {self.pongReceivedEvent.is_set()}')
  294. if not self.pongReceivedEvent.is_set():
  295. # No PONG received in five seconds, assume connection's dead
  296. self.logger.warning(f'Message delivery confirmation failed, putting {len(self.unconfirmedMessages)} messages back into the queue')
  297. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  298. self.transport.close()
  299. self.unconfirmedMessages = []
  300. def data_received(self, data):
  301. self.logger.debug(f'Data received: {data!r}')
  302. # Split received data on CRLF. If there's any data left in the buffer, prepend it to the first message and process that.
  303. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  304. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  305. messages = data.split(b'\r\n')
  306. if self.buffer:
  307. self.message_received(self.buffer + messages[0])
  308. messages = messages[1:]
  309. for message in messages[:-1]:
  310. self.message_received(message)
  311. self.buffer = messages[-1]
  312. def message_received(self, message):
  313. self.logger.debug(f'Message received: {message!r}')
  314. if message.startswith(b':'):
  315. # Prefixed message, extract command + parameters (the prefix cannot contain a space)
  316. message = message.split(b' ', 1)[1]
  317. if message.startswith(b'PING '):
  318. self.send(b'PONG ' + message[5:])
  319. elif message.startswith(b'PONG '):
  320. self.pongReceivedEvent.set()
  321. elif message.startswith(b'001 '):
  322. self.logger.info('IRC connection registered')
  323. self.send(b'JOIN ' + ','.join(self.channels).encode('utf-8')) #TODO: Split if too long
  324. asyncio.create_task(self.send_messages())
  325. asyncio.create_task(self.confirm_messages())
  326. def connection_lost(self, exc):
  327. self.logger.info('IRC connection lost')
  328. self.connected = False
  329. self.connectionClosedEvent.set()
  330. class IRCClient:
  331. logger = logging.getLogger('http2irc.IRCClient')
  332. def __init__(self, messageQueue, config):
  333. self.messageQueue = messageQueue
  334. self.config = config
  335. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  336. self._transport = None
  337. self._protocol = None
  338. def update_config(self, config):
  339. needReconnect = self.config['irc'] != config['irc']
  340. self.config = config
  341. if self._transport: # if currently connected:
  342. if needReconnect:
  343. self._transport.close()
  344. else:
  345. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  346. self._protocol.update_channels(self.channels)
  347. def _get_ssl_context(self):
  348. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  349. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  350. if ctx is True:
  351. ctx = ssl.create_default_context()
  352. if isinstance(ctx, ssl.SSLContext):
  353. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  354. return ctx
  355. async def run(self, loop, sigintEvent):
  356. connectionClosedEvent = asyncio.Event()
  357. while True:
  358. connectionClosedEvent.clear()
  359. try:
  360. 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())
  361. try:
  362. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  363. finally:
  364. 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?
  365. except (ConnectionRefusedError, asyncio.TimeoutError) as e:
  366. self.logger.error(str(e))
  367. await asyncio.wait((asyncio.sleep(5), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  368. if sigintEvent.is_set():
  369. break
  370. class WebServer:
  371. logger = logging.getLogger('http2irc.WebServer')
  372. def __init__(self, messageQueue, config):
  373. self.messageQueue = messageQueue
  374. self.config = config
  375. self._paths = {} # '/path' => ('#channel', auth, module, moduleargs) where auth is either False (no authentication) or the HTTP header value for basic auth
  376. self._app = aiohttp.web.Application()
  377. self._app.add_routes([aiohttp.web.post('/{path:.+}', self.post)])
  378. self.update_config(config)
  379. self._configChanged = asyncio.Event()
  380. def update_config(self, config):
  381. 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()}
  382. needRebind = self.config['web'] != config['web']
  383. self.config = config
  384. if needRebind:
  385. self._configChanged.set()
  386. async def run(self, stopEvent):
  387. while True:
  388. runner = aiohttp.web.AppRunner(self._app)
  389. await runner.setup()
  390. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  391. await site.start()
  392. await asyncio.wait((stopEvent.wait(), self._configChanged.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  393. await runner.cleanup()
  394. if stopEvent.is_set():
  395. break
  396. self._configChanged.clear()
  397. async def post(self, request):
  398. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  399. try:
  400. channel, auth, module, moduleargs = self._paths[request.path]
  401. except KeyError:
  402. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  403. raise aiohttp.web.HTTPNotFound()
  404. if auth:
  405. authHeader = request.headers.get('Authorization')
  406. if not authHeader or authHeader != auth:
  407. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  408. raise aiohttp.web.HTTPForbidden()
  409. if module is not None:
  410. self.logger.debug(f'Processing request {id(request)} using {module!r}')
  411. try:
  412. message = await module.process(request, *moduleargs)
  413. except aiohttp.web.HTTPException as e:
  414. raise e
  415. except Exception as e:
  416. self.logger.error(f'Bad request {id(request)}: exception in module process function: {e!s}')
  417. raise aiohttp.web.HTTPBadRequest()
  418. if '\r' in message or '\n' in message:
  419. self.logger.error(f'Bad request {id(request)}: module process function returned message with linebreaks: {message!r}')
  420. raise aiohttp.web.HTTPBadRequest()
  421. else:
  422. self.logger.debug(f'Processing request {id(request)} using default processor')
  423. message = await self._default_process(request)
  424. self.logger.info(f'Accepted request {id(request)}, putting message {message!r} for {channel} into message queue')
  425. self.messageQueue.put_nowait((channel, message))
  426. raise aiohttp.web.HTTPOk()
  427. async def _default_process(self, request):
  428. try:
  429. message = await request.text()
  430. except Exception as e:
  431. self.logger.info(f'Bad request {id(request)}: exception while reading request data: {e!s}')
  432. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  433. self.logger.debug(f'Request {id(request)} payload: {message!r}')
  434. # Strip optional [CR] LF at the end of the payload
  435. if message.endswith('\r\n'):
  436. message = message[:-2]
  437. elif message.endswith('\n'):
  438. message = message[:-1]
  439. if '\r' in message or '\n' in message:
  440. self.logger.info('Bad request {id(request)}: linebreaks in message')
  441. raise aiohttp.web.HTTPBadRequest()
  442. return message
  443. def configure_logging(config):
  444. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  445. root = logging.getLogger()
  446. root.setLevel(getattr(logging, config['logging']['level']))
  447. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  448. formatter = logging.Formatter(config['logging']['format'], style = '{')
  449. stderrHandler = logging.StreamHandler()
  450. stderrHandler.setFormatter(formatter)
  451. root.addHandler(stderrHandler)
  452. async def main():
  453. if len(sys.argv) != 2:
  454. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  455. sys.exit(1)
  456. configFile = sys.argv[1]
  457. config = Config(configFile)
  458. configure_logging(config)
  459. loop = asyncio.get_running_loop()
  460. messageQueue = MessageQueue()
  461. irc = IRCClient(messageQueue, config)
  462. webserver = WebServer(messageQueue, config)
  463. sigintEvent = asyncio.Event()
  464. def sigint_callback():
  465. global logger
  466. nonlocal sigintEvent
  467. logger.info('Got SIGINT, stopping')
  468. sigintEvent.set()
  469. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  470. def sigusr1_callback():
  471. global logger
  472. nonlocal config, irc, webserver
  473. logger.info('Got SIGUSR1, reloading config')
  474. try:
  475. newConfig = config.reread()
  476. except InvalidConfig as e:
  477. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  478. return
  479. config = newConfig
  480. configure_logging(config)
  481. irc.update_config(config)
  482. webserver.update_config(config)
  483. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  484. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  485. if __name__ == '__main__':
  486. asyncio.run(main())