Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

530 wiersze
21 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') 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. # Default values
  113. 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': {}}
  114. # Fill in default values for the maps
  115. for key, map_ in obj['maps'].items():
  116. if 'webpath' not in map_:
  117. map_['webpath'] = f'/{key}'
  118. if 'ircchannel' not in map_:
  119. map_['ircchannel'] = f'#{key}'
  120. if 'auth' not in map_:
  121. map_['auth'] = False
  122. if 'module' not in map_:
  123. map_['module'] = None
  124. # Load modules
  125. modulePaths = {map_['module'] for map_ in obj['maps'].values() if 'module' in map_ and map_['module'] is not None}
  126. modules = {} # path: str -> module: module
  127. for i, path in enumerate(modulePaths):
  128. try:
  129. # Build a name that is virtually guaranteed to be unique across a process.
  130. # Although importlib does not seem to perform any caching as of CPython 3.8, this is not guaranteed by spec.
  131. spec = importlib.util.spec_from_file_location(f'http2irc-module-{id(self)}-{i}', path)
  132. module = importlib.util.module_from_spec(spec)
  133. spec.loader.exec_module(module)
  134. except Exception as e: # This is ugly, but exec_module can raise virtually any exception
  135. raise InvalidConfig(f'Loading module {path!r} failed: {e!s}')
  136. if not hasattr(module, 'process'):
  137. raise InvalidConfig(f'Module {path!r} does not have a process function')
  138. if not inspect.iscoroutinefunction(module.process):
  139. raise InvalidConfig(f'Module {path!r} process attribute is not a coroutine function')
  140. if len(inspect.signature(module.process).parameters) != 1:
  141. raise InvalidConfig(f'Module {path!r} process function does not take exactly 1 parameter')
  142. modules[path] = module
  143. # Replace module value in maps
  144. for map_ in obj['maps'].values():
  145. if 'module' in map_ and map_['module'] is not None:
  146. map_['module'] = modules[map_['module']]
  147. # Merge in what was read from the config file and set keys on self
  148. for key in ('logging', 'irc', 'web', 'maps'):
  149. if key in obj:
  150. finalObj[key].update(obj[key])
  151. self[key] = finalObj[key]
  152. def __repr__(self):
  153. return f'<Config(logging={self["logging"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, maps={self["maps"]!r})>'
  154. def reread(self):
  155. return Config(self._filename)
  156. class MessageQueue:
  157. # An object holding onto the messages received from nodeping
  158. # This is effectively a reimplementation of parts of asyncio.Queue with some specific additional code.
  159. # Unfortunately, asyncio.Queue's extensibility (_init, _put, and _get methods) is undocumented, so I don't want to rely on that.
  160. # Differences to asyncio.Queue include:
  161. # - No maxsize
  162. # - No put coroutine (not necessary since the queue can never be full)
  163. # - Only one concurrent getter
  164. # - putleft_nowait to put to the front of the queue (so that the IRC client can put a message back when delivery fails)
  165. def __init__(self):
  166. self._getter = None # None | asyncio.Future
  167. self._queue = collections.deque()
  168. async def get(self):
  169. if self._getter is not None:
  170. raise RuntimeError('Cannot get concurrently')
  171. if len(self._queue) == 0:
  172. self._getter = asyncio.get_running_loop().create_future()
  173. logging.debug('Awaiting getter')
  174. try:
  175. await self._getter
  176. except asyncio.CancelledError:
  177. logging.debug('Cancelled getter')
  178. self._getter = None
  179. raise
  180. logging.debug('Awaited getter')
  181. self._getter = None
  182. # For testing the cancellation/putting back onto the queue
  183. #logging.debug('Delaying message queue get')
  184. #await asyncio.sleep(3)
  185. #logging.debug('Done delaying')
  186. return self.get_nowait()
  187. def get_nowait(self):
  188. if len(self._queue) == 0:
  189. raise asyncio.QueueEmpty
  190. return self._queue.popleft()
  191. def put_nowait(self, item):
  192. self._queue.append(item)
  193. if self._getter is not None and not self._getter.cancelled():
  194. self._getter.set_result(None)
  195. def putleft_nowait(self, *item):
  196. self._queue.extendleft(reversed(item))
  197. if self._getter is not None and not self._getter.cancelled():
  198. self._getter.set_result(None)
  199. def qsize(self):
  200. return len(self._queue)
  201. class IRCClientProtocol(asyncio.Protocol):
  202. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  203. logging.debug(f'Protocol init {id(self)}: {messageQueue} {id(messageQueue)}, {connectionClosedEvent}, {loop}')
  204. self.messageQueue = messageQueue
  205. self.connectionClosedEvent = connectionClosedEvent
  206. self.loop = loop
  207. self.config = config
  208. self.buffer = b''
  209. self.connected = False
  210. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  211. self.unconfirmedMessages = []
  212. self.pongReceivedEvent = asyncio.Event()
  213. def connection_made(self, transport):
  214. logging.info('Connected')
  215. self.transport = transport
  216. self.connected = True
  217. nickb = self.config['irc']['nick'].encode('utf-8')
  218. self.send(b'NICK ' + nickb)
  219. self.send(b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + self.config['irc']['real'].encode('utf-8'))
  220. def update_channels(self, channels: set):
  221. channelsToPart = self.channels - channels
  222. channelsToJoin = channels - self.channels
  223. self.channels = channels
  224. if self.connected:
  225. if channelsToPart:
  226. #TODO: Split if too long
  227. self.send(b'PART ' + ','.join(channelsToPart).encode('utf-8'))
  228. if channelsToJoin:
  229. self.send(b'JOIN ' + ','.join(channelsToJoin).encode('utf-8'))
  230. def send(self, data):
  231. logging.info(f'Send: {data!r}')
  232. self.transport.write(data + b'\r\n')
  233. async def _get_message(self):
  234. logging.debug(f'Message queue {id(self.messageQueue)} length: {self.messageQueue.qsize()}')
  235. messageFuture = asyncio.create_task(self.messageQueue.get())
  236. done, pending = await asyncio.wait((messageFuture, self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  237. if self.connectionClosedEvent.is_set():
  238. if messageFuture in pending:
  239. logging.debug('Cancelling messageFuture')
  240. messageFuture.cancel()
  241. try:
  242. await messageFuture
  243. except asyncio.CancelledError:
  244. logging.debug('Cancelled messageFuture')
  245. pass
  246. else:
  247. # messageFuture is already done but we're stopping, so put the result back onto the queue
  248. self.messageQueue.putleft_nowait(messageFuture.result())
  249. return None, None
  250. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  251. return messageFuture.result()
  252. async def send_messages(self):
  253. while self.connected:
  254. logging.debug(f'{id(self)}: trying to get a message')
  255. channel, message = await self._get_message()
  256. logging.debug(f'{id(self)}: got message: {message!r}')
  257. if message is None:
  258. break
  259. #TODO Split if the message is too long.
  260. self.unconfirmedMessages.append((channel, message))
  261. self.send(b'PRIVMSG ' + channel.encode('utf-8') + b' :' + message.encode('utf-8'))
  262. await asyncio.sleep(1) # Rate limit
  263. async def confirm_messages(self):
  264. while self.connected:
  265. await asyncio.wait((asyncio.sleep(60), self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED) # Confirm once per minute
  266. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  267. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  268. self.unconfirmedMessages = []
  269. break
  270. if not self.unconfirmedMessages:
  271. logging.debug(f'{id(self)}: no messages to confirm')
  272. continue
  273. logging.debug(f'{id(self)}: trying to confirm message delivery')
  274. self.pongReceivedEvent.clear()
  275. self.send(b'PING :42')
  276. await asyncio.wait((asyncio.sleep(5), self.pongReceivedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  277. logging.debug(f'{id(self)}: message delivery success: {self.pongReceivedEvent.is_set()}')
  278. if not self.pongReceivedEvent.is_set():
  279. # No PONG received in five seconds, assume connection's dead
  280. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  281. self.transport.close()
  282. self.unconfirmedMessages = []
  283. def data_received(self, data):
  284. logging.debug(f'Data received: {data!r}')
  285. # Split received data on CRLF. If there's any data left in the buffer, prepend it to the first message and process that.
  286. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  287. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  288. messages = data.split(b'\r\n')
  289. if self.buffer:
  290. self.message_received(self.buffer + messages[0])
  291. messages = messages[1:]
  292. for message in messages[:-1]:
  293. self.message_received(message)
  294. self.buffer = messages[-1]
  295. def message_received(self, message):
  296. logging.info(f'Message received: {message!r}')
  297. if message.startswith(b':'):
  298. # Prefixed message, extract command + parameters (the prefix cannot contain a space)
  299. message = message.split(b' ', 1)[1]
  300. if message.startswith(b'PING '):
  301. self.send(b'PONG ' + message[5:])
  302. elif message.startswith(b'PONG '):
  303. self.pongReceivedEvent.set()
  304. elif message.startswith(b'001 '):
  305. # Connection registered
  306. self.send(b'JOIN ' + ','.join(self.channels).encode('utf-8')) #TODO: Split if too long
  307. asyncio.create_task(self.send_messages())
  308. asyncio.create_task(self.confirm_messages())
  309. def connection_lost(self, exc):
  310. logging.info('The server closed the connection')
  311. self.connected = False
  312. self.connectionClosedEvent.set()
  313. class IRCClient:
  314. def __init__(self, messageQueue, config):
  315. self.messageQueue = messageQueue
  316. self.config = config
  317. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  318. self._transport = None
  319. self._protocol = None
  320. def update_config(self, config):
  321. needReconnect = self.config['irc'] != config['irc']
  322. self.config = config
  323. if self._transport: # if currently connected:
  324. if needReconnect:
  325. self._transport.close()
  326. else:
  327. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  328. self._protocol.update_channels(self.channels)
  329. def _get_ssl_context(self):
  330. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  331. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  332. if ctx is True:
  333. ctx = ssl.create_default_context()
  334. if isinstance(ctx, ssl.SSLContext):
  335. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  336. return ctx
  337. async def run(self, loop, sigintEvent):
  338. connectionClosedEvent = asyncio.Event()
  339. while True:
  340. connectionClosedEvent.clear()
  341. try:
  342. 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())
  343. try:
  344. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  345. finally:
  346. 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?
  347. except (ConnectionRefusedError, asyncio.TimeoutError) as e:
  348. logging.error(str(e))
  349. await asyncio.wait((asyncio.sleep(5), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  350. if sigintEvent.is_set():
  351. break
  352. class WebServer:
  353. def __init__(self, messageQueue, config):
  354. self.messageQueue = messageQueue
  355. self.config = config
  356. self._paths = {} # '/path' => ('#channel', auth, module) where auth is either False (no authentication) or the HTTP header value for basic auth
  357. self._app = aiohttp.web.Application()
  358. self._app.add_routes([aiohttp.web.post('/{path:.+}', self.post)])
  359. self.update_config(config)
  360. self._configChanged = asyncio.Event()
  361. def update_config(self, config):
  362. 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']) for map_ in config['maps'].values()}
  363. needRebind = self.config['web'] != config['web']
  364. self.config = config
  365. if needRebind:
  366. self._configChanged.set()
  367. async def run(self, stopEvent):
  368. while True:
  369. runner = aiohttp.web.AppRunner(self._app)
  370. await runner.setup()
  371. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  372. await site.start()
  373. await asyncio.wait((stopEvent.wait(), self._configChanged.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  374. await runner.cleanup()
  375. if stopEvent.is_set():
  376. break
  377. self._configChanged.clear()
  378. async def post(self, request):
  379. logging.info(f'Received request for {request.path!r}')
  380. try:
  381. channel, auth, module = self._paths[request.path]
  382. except KeyError:
  383. logging.info(f'Bad request: no path {request.path!r}')
  384. raise aiohttp.web.HTTPNotFound()
  385. if auth:
  386. authHeader = request.headers.get('Authorization')
  387. if not authHeader or authHeader != auth:
  388. logging.info(f'Bad request: authentication failed: {authHeader!r} != {auth}')
  389. raise aiohttp.web.HTTPForbidden()
  390. if module is not None:
  391. try:
  392. message = await module.process(request)
  393. except aiohttp.web.HTTPException as e:
  394. raise e
  395. except Exception as e:
  396. logging.error(f'Bad request: exception in module process function: {e!s}')
  397. raise aiohttp.web.HTTPBadRequest()
  398. if '\r' in message or '\n' in message:
  399. logging.error(f'Bad request: module process function returned message with linebreaks: {message!r}')
  400. raise aiohttp.web.HTTPBadRequest()
  401. else:
  402. message = await self._default_process(request)
  403. logging.debug(f'Putting message {message!r} for {channel} into message queue')
  404. self.messageQueue.put_nowait((channel, message))
  405. raise aiohttp.web.HTTPOk()
  406. async def _default_process(self, request):
  407. try:
  408. message = await request.text()
  409. except Exception as e:
  410. logging.info(f'Bad request: exception while reading request data: {e!s}')
  411. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  412. logging.debug(f'Request payload: {message!r}')
  413. # Strip optional [CR] LF at the end of the payload
  414. if message.endswith('\r\n'):
  415. message = message[:-2]
  416. elif message.endswith('\n'):
  417. message = message[:-1]
  418. if '\r' in message or '\n' in message:
  419. logging.info('Bad request: linebreaks in message')
  420. raise aiohttp.web.HTTPBadRequest()
  421. return message
  422. def configure_logging(config):
  423. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  424. root = logging.getLogger()
  425. root.setLevel(getattr(logging, config['logging']['level']))
  426. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  427. formatter = logging.Formatter(config['logging']['format'], style = '{')
  428. stderrHandler = logging.StreamHandler()
  429. stderrHandler.setFormatter(formatter)
  430. root.addHandler(stderrHandler)
  431. async def main():
  432. if len(sys.argv) != 2:
  433. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  434. sys.exit(1)
  435. configFile = sys.argv[1]
  436. config = Config(configFile)
  437. configure_logging(config)
  438. loop = asyncio.get_running_loop()
  439. messageQueue = MessageQueue()
  440. irc = IRCClient(messageQueue, config)
  441. webserver = WebServer(messageQueue, config)
  442. sigintEvent = asyncio.Event()
  443. def sigint_callback():
  444. logging.info('Got SIGINT')
  445. nonlocal sigintEvent
  446. sigintEvent.set()
  447. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  448. def sigusr1_callback():
  449. logging.info('Got SIGUSR1, reloading config')
  450. nonlocal config, irc, webserver
  451. try:
  452. newConfig = config.reread()
  453. except InvalidConfig as e:
  454. logging.error(f'Config reload failed: {e!s}')
  455. return
  456. config = newConfig
  457. configure_logging(config)
  458. irc.update_config(config)
  459. webserver.update_config(config)
  460. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  461. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  462. if __name__ == '__main__':
  463. asyncio.run(main())