25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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