Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

402 lignes
15 KiB

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