You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

465 lines
18 KiB

  1. import aiohttp
  2. import aiohttp.web
  3. import asyncio
  4. import base64
  5. import collections
  6. import concurrent.futures
  7. import logging
  8. import os.path
  9. import signal
  10. import ssl
  11. import sys
  12. import toml
  13. import types
  14. logging.basicConfig(level = logging.DEBUG, format = '{asctime} {levelname} {message}', style = '{')
  15. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  16. class InvalidConfig(Exception):
  17. '''Error in configuration file'''
  18. def _mapping_to_namespace(d):
  19. '''Converts a mapping (e.g. dict) to a types.SimpleNamespace, recursively'''
  20. return types.SimpleNamespace(**{key: _mapping_to_namespace(value) if isinstance(value, collections.abc.Mapping) else value for key, value in d.items()})
  21. def is_valid_pem(path, withCert):
  22. '''Very basic check whether something looks like a valid PEM certificate'''
  23. try:
  24. with open(path, 'rb') as fp:
  25. contents = fp.read()
  26. # All of these raise exceptions if something's wrong...
  27. if withCert:
  28. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  29. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  30. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  31. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  32. else:
  33. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  34. endCertPos = -26 # Please shoot me.
  35. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  36. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  37. assert contents[endKeyPos + 26:] == b''
  38. return True
  39. except: # Yes, really
  40. return False
  41. class Config:
  42. def __init__(self, filename):
  43. self._filename = filename
  44. # Set below:
  45. self.irc = None
  46. self.web = None
  47. self.maps = None
  48. with open(self._filename, 'r') as fp:
  49. obj = toml.load(fp)
  50. logging.info(repr(obj))
  51. # Sanity checks
  52. if any(x not in ('irc', 'web', 'maps') for x in obj.keys()):
  53. raise InvalidConfig('Unknown sections found in base object')
  54. if any(not isinstance(x, collections.abc.Mapping) for x in obj.values()):
  55. raise InvalidConfig('Invalid section type(s), expected objects/dicts')
  56. if 'irc' in obj:
  57. if any(x not in ('host', 'port', 'ssl', 'nick', 'real', 'certfile', 'certkeyfile') for x in obj['irc']):
  58. raise InvalidConfig('Unknown key found in irc section')
  59. if 'host' in obj['irc'] and not isinstance(obj['irc']['host'], str): #TODO: Check whether it's a valid hostname
  60. raise InvalidConfig('Invalid IRC host')
  61. if 'port' in obj['irc'] and (not isinstance(obj['irc']['port'], int) or not 1 <= obj['irc']['port'] <= 65535):
  62. raise InvalidConfig('Invalid IRC port')
  63. if 'ssl' in obj['irc'] and obj['irc']['ssl'] not in ('yes', 'no', 'insecure'):
  64. raise InvalidConfig(f'Invalid IRC SSL setting: {obj["irc"]["ssl"]!r}')
  65. if 'nick' in obj['irc'] and not isinstance(obj['irc']['nick'], str): #TODO: Check whether it's a valid nickname
  66. raise InvalidConfig('Invalid IRC nick')
  67. if 'real' in obj['irc'] and not isinstance(obj['irc']['real'], str):
  68. raise InvalidConfig('Invalid IRC realname')
  69. if ('certfile' in obj['irc']) != ('certkeyfile' in obj['irc']):
  70. raise InvalidConfig('Invalid IRC cert config: needs both certfile and certkeyfile')
  71. if 'certfile' in obj['irc']:
  72. if not isinstance(obj['irc']['certfile'], str):
  73. raise InvalidConfig('Invalid certificate file: not a string')
  74. if not os.path.isfile(obj['irc']['certfile']):
  75. raise InvalidConfig('Invalid certificate file: not a regular file')
  76. if not is_valid_pem(obj['irc']['certfile'], True):
  77. raise InvalidConfig('Invalid certificate file: not a valid PEM cert')
  78. if 'certkeyfile' in obj['irc']:
  79. if not isinstance(obj['irc']['certkeyfile'], str):
  80. raise InvalidConfig('Invalid certificate key file: not a string')
  81. if not os.path.isfile(obj['irc']['certkeyfile']):
  82. raise InvalidConfig('Invalid certificate key file: not a regular file')
  83. if not is_valid_pem(obj['irc']['certkeyfile'], False):
  84. raise InvalidConfig('Invalid certificate key file: not a valid PEM key')
  85. if 'web' in obj:
  86. if any(x not in ('host', 'port') for x in obj['web']):
  87. raise InvalidConfig('Unknown key found in web section')
  88. if 'host' in obj['web'] and not isinstance(obj['web']['host'], str): #TODO: Check whether it's a valid hostname (must resolve I guess?)
  89. raise InvalidConfig('Invalid web hostname')
  90. if 'port' in obj['web'] and (not isinstance(obj['web']['port'], int) or not 1 <= obj['web']['port'] <= 65535):
  91. raise InvalidConfig('Invalid web port')
  92. if 'maps' in obj:
  93. for key, map_ in obj['maps'].items():
  94. # Ensure that the key is a valid Python identifier since it will be set as an attribute in the namespace.
  95. #TODO: Support for fancier identifiers (PEP 3131)?
  96. if not isinstance(key, str) or not key or key.strip('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') != '' or key[0].strip('0123456789') == '':
  97. raise InvalidConfig(f'Invalid map key {key!r}')
  98. if not isinstance(map_, collections.abc.Mapping):
  99. raise InvalidConfig(f'Invalid map for {key!r}')
  100. if any(x not in ('webpath', 'ircchannel', 'auth') for x in map_):
  101. raise InvalidConfig(f'Unknown key(s) found in map {key!r}')
  102. #TODO: Check values
  103. # Default values
  104. self._obj = {'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': {}}
  105. # Fill in default values for the maps
  106. for key, map_ in obj['maps'].items():
  107. if 'webpath' not in map_:
  108. map_['webpath'] = f'/{key}'
  109. if 'ircchannel' not in map_:
  110. map_['ircchannel'] = f'#{key}'
  111. if 'auth' not in map_:
  112. map_['auth'] = False
  113. # Merge in what was read from the config file and convert to SimpleNamespace
  114. for key in ('irc', 'web', 'maps'):
  115. if key in obj:
  116. self._obj[key].update(obj[key])
  117. setattr(self, key, _mapping_to_namespace(self._obj[key]))
  118. def __repr__(self):
  119. return f'Config(irc={self.irc!r}, web={self.web!r}, maps={self.maps!r})'
  120. def reread(self):
  121. return Config(self._filename)
  122. class MessageQueue:
  123. # An object holding onto the messages received from nodeping
  124. # This is effectively a reimplementation of parts of asyncio.Queue with some specific additional code.
  125. # Unfortunately, asyncio.Queue's extensibility (_init, _put, and _get methods) is undocumented, so I don't want to rely on that.
  126. # Differences to asyncio.Queue include:
  127. # - No maxsize
  128. # - No put coroutine (not necessary since the queue can never be full)
  129. # - Only one concurrent getter
  130. # - putleft_nowait to put to the front of the queue (so that the IRC client can put a message back when delivery fails)
  131. def __init__(self):
  132. self._getter = None # None | asyncio.Future
  133. self._queue = collections.deque()
  134. async def get(self):
  135. if self._getter is not None:
  136. raise RuntimeError('Cannot get concurrently')
  137. if len(self._queue) == 0:
  138. self._getter = asyncio.get_running_loop().create_future()
  139. logging.debug('Awaiting getter')
  140. try:
  141. await self._getter
  142. except asyncio.CancelledError:
  143. logging.debug('Cancelled getter')
  144. self._getter = None
  145. raise
  146. logging.debug('Awaited getter')
  147. self._getter = None
  148. # For testing the cancellation/putting back onto the queue
  149. #logging.debug('Delaying message queue get')
  150. #await asyncio.sleep(3)
  151. #logging.debug('Done delaying')
  152. return self.get_nowait()
  153. def get_nowait(self):
  154. if len(self._queue) == 0:
  155. raise asyncio.QueueEmpty
  156. return self._queue.popleft()
  157. def put_nowait(self, item):
  158. self._queue.append(item)
  159. if self._getter is not None:
  160. self._getter.set_result(None)
  161. def putleft_nowait(self, *item):
  162. self._queue.extendleft(reversed(item))
  163. if self._getter is not None:
  164. self._getter.set_result(None)
  165. def qsize(self):
  166. return len(self._queue)
  167. class IRCClientProtocol(asyncio.Protocol):
  168. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  169. logging.debug(f'Protocol init {id(self)}: {messageQueue} {id(messageQueue)}, {connectionClosedEvent}, {loop}')
  170. self.messageQueue = messageQueue
  171. self.connectionClosedEvent = connectionClosedEvent
  172. self.loop = loop
  173. self.config = config
  174. self.buffer = b''
  175. self.connected = False
  176. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  177. self.unconfirmedMessages = []
  178. self.pongReceivedEvent = asyncio.Event()
  179. def connection_made(self, transport):
  180. logging.info('Connected')
  181. self.transport = transport
  182. self.connected = True
  183. nickb = self.config.irc.nick.encode('utf-8')
  184. self.send(b'NICK ' + nickb)
  185. self.send(b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + self.config.irc.real.encode('utf-8'))
  186. def update_channels(self, channels: set):
  187. channelsToPart = self.channels - channels
  188. channelsToJoin = channels - self.channels
  189. self.channels = channels
  190. if self.connected:
  191. if channelsToPart:
  192. #TODO: Split if too long
  193. self.send(b'PART ' + ','.join(channelsToPart).encode('utf-8'))
  194. if channelsToJoin:
  195. self.send(b'JOIN ' + ','.join(channelsToJoin).encode('utf-8'))
  196. def send(self, data):
  197. logging.info(f'Send: {data!r}')
  198. self.transport.write(data + b'\r\n')
  199. async def _get_message(self):
  200. logging.debug(f'Message queue {id(self.messageQueue)} length: {self.messageQueue.qsize()}')
  201. messageFuture = asyncio.create_task(self.messageQueue.get())
  202. done, pending = await asyncio.wait((messageFuture, self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  203. if self.connectionClosedEvent.is_set():
  204. if messageFuture in pending:
  205. logging.debug('Cancelling messageFuture')
  206. messageFuture.cancel()
  207. try:
  208. await messageFuture
  209. except asyncio.CancelledError:
  210. logging.debug('Cancelled messageFuture')
  211. pass
  212. else:
  213. # messageFuture is already done but we're stopping, so put the result back onto the queue
  214. self.messageQueue.putleft_nowait(messageFuture.result())
  215. return None, None
  216. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  217. return messageFuture.result()
  218. async def send_messages(self):
  219. while self.connected:
  220. logging.debug(f'{id(self)}: trying to get a message')
  221. channel, message = await self._get_message()
  222. logging.debug(f'{id(self)}: got message: {message!r}')
  223. if message is None:
  224. break
  225. #TODO Split if the message is too long.
  226. self.unconfirmedMessages.append((channel, message))
  227. self.send(b'PRIVMSG ' + channel.encode('utf-8') + b' :' + message.encode('utf-8'))
  228. await asyncio.sleep(1) # Rate limit
  229. async def confirm_messages(self):
  230. while self.connected:
  231. await asyncio.wait((asyncio.sleep(60), self.connectionClosedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED) # Confirm once per minute
  232. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  233. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  234. self.unconfirmedMessages = []
  235. break
  236. if not self.unconfirmedMessages:
  237. logging.debug(f'{id(self)}: no messages to confirm')
  238. continue
  239. logging.debug(f'{id(self)}: trying to confirm message delivery')
  240. self.pongReceivedEvent.clear()
  241. self.send(b'PING :42')
  242. await asyncio.wait((asyncio.sleep(5), self.pongReceivedEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  243. logging.debug(f'{id(self)}: message delivery success: {self.pongReceivedEvent.is_set()}')
  244. if not self.pongReceivedEvent.is_set():
  245. # No PONG received in five seconds, assume connection's dead
  246. self.messageQueue.putleft_nowait(*self.unconfirmedMessages)
  247. self.transport.close()
  248. self.unconfirmedMessages = []
  249. def data_received(self, data):
  250. logging.debug(f'Data received: {data!r}')
  251. # Split received data on CRLF. If there's any data left in the buffer, prepend it to the first message and process that.
  252. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  253. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  254. messages = data.split(b'\r\n')
  255. if self.buffer:
  256. self.message_received(self.buffer + messages[0])
  257. messages = messages[1:]
  258. for message in messages[:-1]:
  259. self.message_received(message)
  260. self.buffer = messages[-1]
  261. def message_received(self, message):
  262. logging.info(f'Message received: {message!r}')
  263. if message.startswith(b':'):
  264. # Prefixed message, extract command + parameters (the prefix cannot contain a space)
  265. message = message.split(b' ', 1)[1]
  266. if message.startswith(b'PING '):
  267. self.send(b'PONG ' + message[5:])
  268. elif message.startswith(b'PONG '):
  269. self.pongReceivedEvent.set()
  270. elif message.startswith(b'001 '):
  271. # Connection registered
  272. self.send(b'JOIN ' + ','.join(self.channels).encode('utf-8')) #TODO: Split if too long
  273. asyncio.create_task(self.send_messages())
  274. asyncio.create_task(self.confirm_messages())
  275. def connection_lost(self, exc):
  276. logging.info('The server closed the connection')
  277. self.connected = False
  278. self.connectionClosedEvent.set()
  279. class IRCClient:
  280. def __init__(self, messageQueue, config):
  281. self.messageQueue = messageQueue
  282. self.config = config
  283. self.channels = {map_.ircchannel for map_ in config.maps.__dict__.values()}
  284. self._transport = None
  285. self._protocol = None
  286. def update_config(self, config):
  287. needReconnect = (self.config.irc.host, self.config.irc.port, self.config.irc.ssl) != (config.irc.host, config.irc.port, config.irc.ssl)
  288. self.config = config
  289. if self._transport: # if currently connected:
  290. if needReconnect:
  291. self._transport.close()
  292. else:
  293. self.channels = {map_.ircchannel for map_ in config.maps.__dict__.values()}
  294. self._protocol.update_channels(self.channels)
  295. def _get_ssl_context(self):
  296. ctx = SSL_CONTEXTS[self.config.irc.ssl]
  297. if self.config.irc.certfile and self.config.irc.certkeyfile:
  298. if ctx is True:
  299. ctx = ssl.create_default_context()
  300. if isinstance(ctx, ssl.SSLContext):
  301. ctx.load_cert_chain(self.config.irc.certfile, keyfile = self.config.irc.certkeyfile)
  302. return ctx
  303. async def run(self, loop, sigintEvent):
  304. connectionClosedEvent = asyncio.Event()
  305. while True:
  306. connectionClosedEvent.clear()
  307. try:
  308. 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())
  309. try:
  310. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  311. finally:
  312. 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?
  313. except (ConnectionRefusedError, asyncio.TimeoutError) as e:
  314. logging.error(str(e))
  315. await asyncio.wait((asyncio.sleep(5), sigintEvent.wait()), return_when = concurrent.futures.FIRST_COMPLETED)
  316. if sigintEvent.is_set():
  317. break
  318. class WebServer:
  319. def __init__(self, messageQueue, config):
  320. self.messageQueue = messageQueue
  321. self.config = config
  322. self._paths = {} # '/path' => ('#channel', auth) where auth is either False (no authentication) or the HTTP header value for basic auth
  323. self._app = aiohttp.web.Application()
  324. self._app.add_routes([aiohttp.web.post('/{path:.+}', self.post)])
  325. self.update_config(config)
  326. def update_config(self, config):
  327. self._paths = {map_.webpath: (map_.ircchannel, f'Basic {base64.b64encode(map_.auth.encode("utf-8")).decode("utf-8")}' if map_.auth else False) for map_ in config.maps.__dict__.values()}
  328. needRebind = (self.config.web.host, self.config.web.port) != (config.web.host, config.web.port)
  329. self.config = config
  330. if needRebind:
  331. #TODO
  332. logging.error('Webserver host or port changes while running are currently not supported')
  333. async def run(self, stopEvent):
  334. runner = aiohttp.web.AppRunner(self._app)
  335. await runner.setup()
  336. site = aiohttp.web.TCPSite(runner, self.config.web.host, self.config.web.port)
  337. await site.start()
  338. await stopEvent.wait()
  339. await runner.cleanup()
  340. async def post(self, request):
  341. logging.info(f'Received request for {request.path!r}')
  342. try:
  343. channel, auth = self._paths[request.path]
  344. except KeyError:
  345. logging.info(f'Bad request: no path {request.path!r}')
  346. raise aiohttp.web.HTTPNotFound()
  347. if auth:
  348. authHeader = request.headers.get('Authorization')
  349. if not authHeader or authHeader != auth:
  350. logging.info(f'Bad request: authentication failed: {authHeader!r} != {auth}')
  351. raise aiohttp.web.HTTPForbidden()
  352. try:
  353. message = await request.text()
  354. except Exception as e:
  355. logging.info(f'Bad request: exception while reading request data: {e!s}')
  356. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  357. logging.debug(f'Request payload: {message!r}')
  358. # Strip optional [CR] LF at the end of the payload
  359. if message.endswith('\r\n'):
  360. message = message[:-2]
  361. elif message.endswith('\n'):
  362. message = message[:-1]
  363. if '\r' in message or '\n' in message:
  364. logging.info('Bad request: linebreaks in message')
  365. raise aiohttp.web.HTTPBadRequest()
  366. logging.debug(f'Putting message {message!r} for {channel} into message queue')
  367. self.messageQueue.put_nowait((channel, message))
  368. raise aiohttp.web.HTTPOk()
  369. async def main():
  370. if len(sys.argv) != 2:
  371. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  372. sys.exit(1)
  373. configFile = sys.argv[1]
  374. config = Config(configFile)
  375. loop = asyncio.get_running_loop()
  376. messageQueue = MessageQueue()
  377. irc = IRCClient(messageQueue, config)
  378. webserver = WebServer(messageQueue, config)
  379. sigintEvent = asyncio.Event()
  380. def sigint_callback():
  381. logging.info('Got SIGINT')
  382. nonlocal sigintEvent
  383. sigintEvent.set()
  384. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  385. def sigusr1_callback():
  386. logging.info('Got SIGUSR1, reloading config')
  387. nonlocal config, irc, webserver
  388. try:
  389. newConfig = config.reread()
  390. except InvalidConfig as e:
  391. logging.error(f'Config reload failed: {e!s}')
  392. return
  393. config = newConfig
  394. irc.update_config(config)
  395. webserver.update_config(config)
  396. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  397. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  398. if __name__ == '__main__':
  399. asyncio.run(main())