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.

1105 lines
49 KiB

  1. import aiohttp
  2. import aiohttp.web
  3. import asyncio
  4. import base64
  5. import collections
  6. import functools
  7. import importlib.util
  8. import inspect
  9. import ircstates
  10. import irctokens
  11. import itertools
  12. import json
  13. import logging
  14. import os.path
  15. import signal
  16. import socket
  17. import ssl
  18. import string
  19. import sys
  20. import time
  21. import toml
  22. logger = logging.getLogger('http2irc')
  23. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  24. class InvalidConfig(Exception):
  25. '''Error in configuration file'''
  26. def is_valid_pem(path, withCert):
  27. '''Very basic check whether something looks like a valid PEM certificate'''
  28. try:
  29. with open(path, 'rb') as fp:
  30. contents = fp.read()
  31. # All of these raise exceptions if something's wrong...
  32. if withCert:
  33. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  34. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  35. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  36. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  37. else:
  38. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  39. endCertPos = -26 # Please shoot me.
  40. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  41. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  42. assert contents[endKeyPos + 26:] == b''
  43. return True
  44. except: # Yes, really
  45. return False
  46. async def wait_cancel_pending(aws, paws = None, **kwargs):
  47. '''asyncio.wait but with automatic cancellation of non-completed tasks. Tasks in paws (persistent awaitables) are not automatically cancelled.'''
  48. if paws is None:
  49. paws = set()
  50. tasks = aws | paws
  51. logger.debug(f'waiting for {tasks!r}')
  52. done, pending = await asyncio.wait(tasks, **kwargs)
  53. logger.debug(f'done waiting for {tasks!r}; cancelling pending non-persistent tasks: {pending!r}')
  54. for task in pending:
  55. if task not in paws:
  56. logger.debug(f'cancelling {task!r}')
  57. task.cancel()
  58. logger.debug(f'awaiting cancellation of {task!r}')
  59. try:
  60. await task
  61. except asyncio.CancelledError:
  62. pass
  63. logger.debug(f'done cancelling {task!r}')
  64. logger.debug(f'done wait_cancel_pending {tasks!r}')
  65. return done, pending
  66. class Config(dict):
  67. def __init__(self, filename):
  68. super().__init__()
  69. self._filename = filename
  70. with open(self._filename, 'r') as fp:
  71. obj = toml.load(fp)
  72. # Sanity checks
  73. if any(x not in ('logging', 'irc', 'web', 'maps') for x in obj.keys()):
  74. raise InvalidConfig('Unknown sections found in base object')
  75. if any(not isinstance(x, collections.abc.Mapping) for x in obj.values()):
  76. raise InvalidConfig('Invalid section type(s), expected objects/dicts')
  77. if 'logging' in obj:
  78. if any(x not in ('level', 'format') for x in obj['logging']):
  79. raise InvalidConfig('Unknown key found in log section')
  80. if 'level' in obj['logging'] and obj['logging']['level'] not in ('DEBUG', 'INFO', 'WARNING', 'ERROR'):
  81. raise InvalidConfig('Invalid log level')
  82. if 'format' in obj['logging']:
  83. if not isinstance(obj['logging']['format'], str):
  84. raise InvalidConfig('Invalid log format')
  85. try:
  86. #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)
  87. # 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).
  88. assert sum(1 for x in string.Formatter().parse(obj['logging']['format']) if x[1] is not None) > 0
  89. except (ValueError, AssertionError) as e:
  90. raise InvalidConfig('Invalid log format: parsing failed') from e
  91. if 'irc' in obj:
  92. if any(x not in ('host', 'port', 'ssl', 'family', 'nick', 'real', 'certfile', 'certkeyfile') for x in obj['irc']):
  93. raise InvalidConfig('Unknown key found in irc section')
  94. if 'host' in obj['irc'] and not isinstance(obj['irc']['host'], str): #TODO: Check whether it's a valid hostname
  95. raise InvalidConfig('Invalid IRC host')
  96. if 'port' in obj['irc'] and (not isinstance(obj['irc']['port'], int) or not 1 <= obj['irc']['port'] <= 65535):
  97. raise InvalidConfig('Invalid IRC port')
  98. if 'ssl' in obj['irc'] and obj['irc']['ssl'] not in ('yes', 'no', 'insecure'):
  99. raise InvalidConfig(f'Invalid IRC SSL setting: {obj["irc"]["ssl"]!r}')
  100. if 'family' in obj['irc']:
  101. if obj['irc']['family'] not in ('inet', 'INET', 'inet6', 'INET6'):
  102. raise InvalidConfig('Invalid IRC family')
  103. obj['irc']['family'] = getattr(socket, f'AF_{obj["irc"]["family"].upper()}')
  104. if 'nick' in obj['irc'] and not isinstance(obj['irc']['nick'], str): #TODO: Check whether it's a valid nickname
  105. raise InvalidConfig('Invalid IRC nick')
  106. if len(IRCClientProtocol.nick_command(obj['irc']['nick'])) > 510:
  107. raise InvalidConfig('Invalid IRC nick: NICK command too long')
  108. if 'real' in obj['irc'] and not isinstance(obj['irc']['real'], str):
  109. raise InvalidConfig('Invalid IRC realname')
  110. if len(IRCClientProtocol.user_command(obj['irc']['nick'], obj['irc']['real'])) > 510:
  111. raise InvalidConfig('Invalid IRC nick/realname combination: USER command too long')
  112. if ('certfile' in obj['irc']) != ('certkeyfile' in obj['irc']):
  113. raise InvalidConfig('Invalid IRC cert config: needs both certfile and certkeyfile')
  114. if 'certfile' in obj['irc']:
  115. if not isinstance(obj['irc']['certfile'], str):
  116. raise InvalidConfig('Invalid certificate file: not a string')
  117. obj['irc']['certfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certfile']))
  118. if not os.path.isfile(obj['irc']['certfile']):
  119. raise InvalidConfig('Invalid certificate file: not a regular file')
  120. if not is_valid_pem(obj['irc']['certfile'], True):
  121. raise InvalidConfig('Invalid certificate file: not a valid PEM cert')
  122. if 'certkeyfile' in obj['irc']:
  123. if not isinstance(obj['irc']['certkeyfile'], str):
  124. raise InvalidConfig('Invalid certificate key file: not a string')
  125. obj['irc']['certkeyfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certkeyfile']))
  126. if not os.path.isfile(obj['irc']['certkeyfile']):
  127. raise InvalidConfig('Invalid certificate key file: not a regular file')
  128. if not is_valid_pem(obj['irc']['certkeyfile'], False):
  129. raise InvalidConfig('Invalid certificate key file: not a valid PEM key')
  130. if 'web' in obj:
  131. if any(x not in ('host', 'port') for x in obj['web']):
  132. raise InvalidConfig('Unknown key found in web section')
  133. if 'host' in obj['web'] and not isinstance(obj['web']['host'], str): #TODO: Check whether it's a valid hostname (must resolve I guess?)
  134. raise InvalidConfig('Invalid web hostname')
  135. if 'port' in obj['web'] and (not isinstance(obj['web']['port'], int) or not 1 <= obj['web']['port'] <= 65535):
  136. raise InvalidConfig('Invalid web port')
  137. if 'maps' in obj:
  138. seenWebPaths = {}
  139. for key, map_ in obj['maps'].items():
  140. if not isinstance(key, str) or not key:
  141. raise InvalidConfig(f'Invalid map key {key!r}')
  142. if not isinstance(map_, collections.abc.Mapping):
  143. raise InvalidConfig(f'Invalid map for {key!r}')
  144. if any(x not in ('webpath', 'ircchannel', 'auth', 'module', 'moduleargs', 'overlongmode') for x in map_):
  145. raise InvalidConfig(f'Unknown key(s) found in map {key!r}')
  146. if 'webpath' not in map_:
  147. map_['webpath'] = f'/{key}'
  148. if not isinstance(map_['webpath'], str):
  149. raise InvalidConfig(f'Invalid map {key!r} web path: not a string')
  150. if not map_['webpath'].startswith('/'):
  151. raise InvalidConfig(f'Invalid map {key!r} web path: does not start at the root')
  152. if map_['webpath'] == '/status':
  153. raise InvalidConfig(f'Invalid map {key!r} web path: cannot be "/status"')
  154. if map_['webpath'] in seenWebPaths:
  155. raise InvalidConfig(f'Invalid map {key!r} web path: collides with map {seenWebPaths[map_["webpath"]]!r}')
  156. seenWebPaths[map_['webpath']] = key
  157. if 'ircchannel' not in map_:
  158. map_['ircchannel'] = f'#{key}'
  159. if not isinstance(map_['ircchannel'], str):
  160. raise InvalidConfig(f'Invalid map {key!r} IRC channel: not a string')
  161. if not map_['ircchannel'].startswith('#') and not map_['ircchannel'].startswith('&'):
  162. raise InvalidConfig(f'Invalid map {key!r} IRC channel: does not start with # or &')
  163. if any(x in map_['ircchannel'][1:] for x in (' ', '\x00', '\x07', '\r', '\n', ',')):
  164. raise InvalidConfig(f'Invalid map {key!r} IRC channel: contains forbidden characters')
  165. if len(map_['ircchannel']) > 200:
  166. raise InvalidConfig(f'Invalid map {key!r} IRC channel: too long')
  167. if 'auth' in map_:
  168. if map_['auth'] is not False and not isinstance(map_['auth'], str):
  169. raise InvalidConfig(f'Invalid map {key!r} auth: must be false or a string')
  170. if isinstance(map_['auth'], str) and ':' not in map_['auth']:
  171. raise InvalidConfig(f'Invalid map {key!r} auth: must contain a colon')
  172. if 'module' in map_:
  173. # If the path is relative, try to evaluate it relative to either the config file or this file; some modules are in the repo, but this also allows overriding them.
  174. for basePath in (os.path.dirname(self._filename), os.path.dirname(__file__)):
  175. if os.path.isfile(os.path.join(basePath, map_['module'])):
  176. map_['module'] = os.path.abspath(os.path.join(basePath, map_['module']))
  177. break
  178. else:
  179. raise InvalidConfig(f'Module {map_["module"]!r} in map {key!r} is not a file')
  180. if 'moduleargs' in map_:
  181. if not isinstance(map_['moduleargs'], list):
  182. raise InvalidConfig(f'Invalid module args for {key!r}: not an array')
  183. if 'module' not in map_:
  184. raise InvalidConfig(f'Module args cannot be specified without a module for {key!r}')
  185. if 'overlongmode' in map_:
  186. if not isinstance(map_['overlongmode'], str):
  187. raise InvalidConfig(f'Invalid map {key!r} overlongmode: not a string')
  188. if map_['overlongmode'] not in ('split', 'truncate'):
  189. raise InvalidConfig(f'Invalid map {key!r} overlongmode: unsupported value')
  190. # Default values
  191. finalObj = {
  192. 'logging': {'level': 'INFO', 'format': '{asctime} {levelname} {name} {message}'},
  193. 'irc': {'host': 'irc.hackint.org', 'port': 6697, 'ssl': 'yes', 'family': 0, 'nick': 'h2ibot', 'real': 'I am an http2irc bot.', 'certfile': None, 'certkeyfile': None},
  194. 'web': {'host': '127.0.0.1', 'port': 8080},
  195. 'maps': {}
  196. }
  197. # Fill in default values for the maps
  198. for key, map_ in obj['maps'].items():
  199. # webpath is already set above for duplicate checking
  200. # ircchannel is set above for validation
  201. if 'auth' not in map_:
  202. map_['auth'] = False
  203. if 'module' not in map_:
  204. map_['module'] = None
  205. if 'moduleargs' not in map_:
  206. map_['moduleargs'] = []
  207. if 'overlongmode' not in map_:
  208. map_['overlongmode'] = 'split'
  209. # Load modules
  210. modulePaths = {} # path: str -> (extraargs: int, key: str)
  211. for key, map_ in obj['maps'].items():
  212. if map_['module'] is not None:
  213. if map_['module'] not in modulePaths:
  214. modulePaths[map_['module']] = (len(map_['moduleargs']), key)
  215. elif modulePaths[map_['module']][0] != len(map_['moduleargs']):
  216. raise InvalidConfig(f'Module {map_["module"]!r} process function extra argument inconsistency between {key!r} and {modulePaths[map_["module"]][1]!r}')
  217. modules = {} # path: str -> module: module
  218. for i, (path, (extraargs, _)) in enumerate(modulePaths.items()):
  219. try:
  220. # Build a name that is virtually guaranteed to be unique across a process.
  221. # Although importlib does not seem to perform any caching as of CPython 3.8, this is not guaranteed by spec.
  222. spec = importlib.util.spec_from_file_location(f'http2irc-module-{id(self)}-{i}', path)
  223. module = importlib.util.module_from_spec(spec)
  224. spec.loader.exec_module(module)
  225. except Exception as e: # This is ugly, but exec_module can raise virtually any exception
  226. raise InvalidConfig(f'Loading module {path!r} failed: {e!s}')
  227. if not hasattr(module, 'process'):
  228. raise InvalidConfig(f'Module {path!r} does not have a process function')
  229. if not inspect.iscoroutinefunction(module.process):
  230. raise InvalidConfig(f'Module {path!r} process attribute is not a coroutine function')
  231. nargs = len(inspect.signature(module.process).parameters)
  232. if nargs != 1 + extraargs:
  233. raise InvalidConfig(f'Module {path!r} process function takes {nargs} parameter{"s" if nargs > 1 else ""}, not {1 + extraargs}')
  234. modules[path] = module
  235. # Replace module value in maps
  236. for map_ in obj['maps'].values():
  237. if 'module' in map_ and map_['module'] is not None:
  238. map_['module'] = modules[map_['module']]
  239. # Merge in what was read from the config file and set keys on self
  240. for key in ('logging', 'irc', 'web', 'maps'):
  241. if key in obj:
  242. finalObj[key].update(obj[key])
  243. self[key] = finalObj[key]
  244. def __repr__(self):
  245. return f'<Config(logging={self["logging"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, maps={self["maps"]!r})>'
  246. def reread(self):
  247. return Config(self._filename)
  248. class MessageQueue:
  249. # An object holding onto the messages received over HTTP for sending to IRC
  250. # This is effectively a reimplementation of parts of asyncio.Queue with some specific additional code.
  251. # Unfortunately, asyncio.Queue's extensibility (_init, _put, and _get methods) is undocumented, so I don't want to rely on that.
  252. # Differences to asyncio.Queue include:
  253. # - No maxsize
  254. # - No put coroutine (not necessary since the queue can never be full)
  255. # - Only one concurrent getter
  256. # - putleft_nowait to put to the front of the queue (so that the IRC client can put a message back when delivery fails)
  257. logger = logging.getLogger('http2irc.MessageQueue')
  258. def __init__(self):
  259. self._getter = None # None | asyncio.Future
  260. self._queue = collections.deque()
  261. async def get(self):
  262. if self._getter is not None:
  263. raise RuntimeError('Cannot get concurrently')
  264. if len(self._queue) == 0:
  265. self._getter = asyncio.get_running_loop().create_future()
  266. self.logger.debug('Awaiting getter')
  267. try:
  268. await self._getter
  269. except asyncio.CancelledError:
  270. self.logger.debug('Cancelled getter')
  271. self._getter = None
  272. raise
  273. self.logger.debug('Awaited getter')
  274. self._getter = None
  275. # For testing the cancellation/putting back onto the queue
  276. #self.logger.debug('Delaying message queue get')
  277. #await asyncio.sleep(3)
  278. #self.logger.debug('Done delaying')
  279. return self.get_nowait()
  280. def get_nowait(self):
  281. if len(self._queue) == 0:
  282. raise asyncio.QueueEmpty
  283. return self._queue.popleft()
  284. def put_nowait(self, item):
  285. self._queue.append(item)
  286. if self._getter is not None and not self._getter.cancelled():
  287. self._getter.set_result(None)
  288. def putleft_nowait(self, *item):
  289. self._queue.extendleft(reversed(item))
  290. if self._getter is not None and not self._getter.cancelled():
  291. self._getter.set_result(None)
  292. def qsize(self):
  293. return len(self._queue)
  294. class IRCClientProtocol(asyncio.Protocol):
  295. logger = logging.getLogger('http2irc.IRCClientProtocol')
  296. def __init__(self, http2ircMessageQueue, irc2httpBroadcaster, connectionClosedEvent, loop, config, channels):
  297. self.http2ircMessageQueue = http2ircMessageQueue
  298. self.irc2httpBroadcaster = irc2httpBroadcaster
  299. self.connectionClosedEvent = connectionClosedEvent
  300. self.loop = loop
  301. self.config = config
  302. self.lastRecvTime = None
  303. self.lastSentTime = None # float timestamp or None; the latter disables the send rate limit
  304. self.sendQueue = asyncio.Queue()
  305. self.buffer = b''
  306. self.connected = False
  307. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  308. self.unconfirmedMessages = []
  309. self.pongReceivedEvent = asyncio.Event()
  310. self.sasl = bool(self.config['irc']['certfile'] and self.config['irc']['certkeyfile'])
  311. self.authenticated = False
  312. self.server = ircstates.Server(self.config['irc']['host'])
  313. self.capReqsPending = set() # Capabilities requested from the server but not yet ACKd or NAKd
  314. self.caps = set() # Capabilities acknowledged by the server
  315. self.whoxQueue = collections.deque() # Names of channels that were joined successfully but for which no WHO (WHOX) query was sent yet
  316. self.whoxChannel = None # Name of channel for which a WHO query is currently running
  317. self.whoxReply = [] # List of (nickname, account) tuples from the currently running WHO query
  318. self.whoxStartTime = None
  319. self.userChannels = collections.defaultdict(set) # List of which channels a user is known to be in; nickname:str -> {channel:str, ...}
  320. @staticmethod
  321. def nick_command(nick: str):
  322. return b'NICK ' + nick.encode('utf-8')
  323. @staticmethod
  324. def user_command(nick: str, real: str):
  325. nickb = nick.encode('utf-8')
  326. return b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + real.encode('utf-8')
  327. def connection_made(self, transport):
  328. self.logger.info('IRC connected')
  329. self.transport = transport
  330. self.connected = True
  331. caps = [b'multi-prefix', b'userhost-in-names', b'away-notify', b'account-notify', b'extended-join']
  332. if self.sasl:
  333. caps.append(b'sasl')
  334. for cap in caps:
  335. self.capReqsPending.add(cap.decode('ascii'))
  336. self.send(b'CAP REQ :' + cap)
  337. self.send(self.nick_command(self.config['irc']['nick']))
  338. self.send(self.user_command(self.config['irc']['nick'], self.config['irc']['real']))
  339. def _send_join_part(self, command, channels):
  340. '''Split a JOIN or PART into multiple messages as necessary'''
  341. # command: b'JOIN' or b'PART'; channels: set[str]
  342. channels = [x.encode('utf-8') for x in channels]
  343. if len(command) + sum(1 + len(x) for x in channels) <= 510: # Total length = command + (separator + channel name for each channel, where the separator is a space for the first and then a comma)
  344. # Everything fits into one command.
  345. self.send(command + b' ' + b','.join(channels))
  346. return
  347. # List too long, need to split.
  348. limit = 510 - len(command)
  349. lengths = [1 + len(x) for x in channels] # separator + channel name
  350. chanLengthAcceptable = [l <= limit for l in lengths]
  351. if not all(chanLengthAcceptable):
  352. # There are channel names that are too long to even fit into one message on their own; filter them out and warn about them.
  353. # This should never happen since the config reader would already filter it out.
  354. tooLongChannels = [x for x, a in zip(channels, chanLengthAcceptable) if not a]
  355. channels = [x for x, a in zip(channels, chanLengthAcceptable) if a]
  356. lengths = [l for l, a in zip(lengths, chanLengthAcceptable) if a]
  357. for channel in tooLongChannels:
  358. self.logger.warning(f'Cannot {command} {channel}: name too long')
  359. runningLengths = list(itertools.accumulate(lengths)) # entry N = length of all entries up to and including channel N, including separators
  360. offset = 0
  361. while channels:
  362. i = next((x[0] for x in enumerate(runningLengths) if x[1] - offset > limit), -1)
  363. if i == -1: # Last batch
  364. i = len(channels)
  365. self.send(command + b' ' + b','.join(channels[:i]))
  366. offset = runningLengths[i-1]
  367. channels = channels[i:]
  368. runningLengths = runningLengths[i:]
  369. def update_channels(self, channels: set):
  370. channelsToPart = self.channels - channels
  371. channelsToJoin = channels - self.channels
  372. self.channels = channels
  373. if self.connected:
  374. if channelsToPart:
  375. self._send_join_part(b'PART', channelsToPart)
  376. if channelsToJoin:
  377. self._send_join_part(b'JOIN', channelsToJoin)
  378. def send(self, data):
  379. self.logger.debug(f'Queueing for send: {data!r}')
  380. if len(data) > 510:
  381. raise RuntimeError(f'IRC message too long ({len(data)} > 510): {data!r}')
  382. self.sendQueue.put_nowait(data)
  383. def _direct_send(self, data):
  384. self.logger.debug(f'Send: {data!r}')
  385. time_ = time.time()
  386. self.transport.write(data + b'\r\n')
  387. if data.startswith(b'PRIVMSG '):
  388. # Send own messages to broadcaster as well
  389. command, channels, message = data.decode('utf-8').split(' ', 2)
  390. for channel in channels.split(','):
  391. assert channel.startswith('#') or channel.startswith('&'), f'invalid channel: {channel!r}'
  392. user = {
  393. 'nick': self.server.nickname,
  394. 'hostmask': f'{self.server.nickname}!{self.server.username}@{self.server.hostname}',
  395. 'account': self.server.account,
  396. 'modes': self.get_mode_chars(self.server.channels[self.server.casefold(channel)].users.get(self.server.casefold(self.server.nickname))),
  397. }
  398. self.irc2httpBroadcaster.send(channel, {'time': time_, 'command': command, 'channel': channel, 'user': user, 'message': message})
  399. return time_
  400. async def send_queue(self):
  401. while True:
  402. self.logger.debug('Trying to get data from send queue')
  403. t = asyncio.create_task(self.sendQueue.get())
  404. done, pending = await wait_cancel_pending({t, asyncio.create_task(self.connectionClosedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  405. if self.connectionClosedEvent.is_set():
  406. break
  407. assert t in done, f'{t!r} is not in {done!r}'
  408. data = t.result()
  409. self.logger.debug(f'Got {data!r} from send queue')
  410. now = time.time()
  411. if self.lastSentTime is not None and now - self.lastSentTime < 1:
  412. self.logger.debug(f'Rate limited')
  413. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = self.lastSentTime + 1 - now)
  414. if self.connectionClosedEvent.is_set():
  415. break
  416. time_ = self._direct_send(data)
  417. if self.lastSentTime is not None:
  418. self.lastSentTime = time_
  419. async def _get_message(self):
  420. self.logger.debug(f'Message queue {id(self.http2ircMessageQueue)} length: {self.http2ircMessageQueue.qsize()}')
  421. messageFuture = asyncio.create_task(self.http2ircMessageQueue.get())
  422. done, pending = await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, paws = {messageFuture}, return_when = asyncio.FIRST_COMPLETED)
  423. if self.connectionClosedEvent.is_set():
  424. if messageFuture in pending:
  425. self.logger.debug('Cancelling messageFuture')
  426. messageFuture.cancel()
  427. try:
  428. await messageFuture
  429. except asyncio.CancelledError:
  430. self.logger.debug('Cancelled messageFuture')
  431. pass
  432. else:
  433. # messageFuture is already done but we're stopping, so put the result back onto the queue
  434. self.http2ircMessageQueue.putleft_nowait(messageFuture.result())
  435. return None, None, None
  436. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  437. return messageFuture.result()
  438. def _self_usermask_length(self):
  439. if not self.server.nickname or not self.server.username or not self.server.hostname:
  440. return 100
  441. return len(self.server.nickname) + len(self.server.username) + len(self.server.hostname)
  442. async def send_messages(self):
  443. while self.connected:
  444. self.logger.debug(f'Trying to get a message')
  445. channel, message, overlongmode = await self._get_message()
  446. self.logger.debug(f'Got message: {message!r}')
  447. if message is None:
  448. break
  449. channelB = channel.encode('utf-8')
  450. messageB = message.encode('utf-8')
  451. usermaskPrefixLength = 1 + self._self_usermask_length() + 1
  452. if usermaskPrefixLength + len(b'PRIVMSG ' + channelB + b' :' + messageB) > 510:
  453. # Message too long, need to split or truncate. First try to split on spaces, then on codepoints. Ideally, would use graphemes between, but that's too complicated.
  454. self.logger.debug(f'Message too long, overlongmode = {overlongmode}')
  455. prefix = b'PRIVMSG ' + channelB + b' :'
  456. prefixLength = usermaskPrefixLength + len(prefix) # Need to account for the origin prefix included by the ircd when sending to others
  457. maxMessageLength = 510 - prefixLength # maximum length of the message part within each line
  458. if overlongmode == 'truncate':
  459. maxMessageLength -= 3 # Make room for an ellipsis at the end
  460. messages = []
  461. while message:
  462. if overlongmode == 'truncate' and messages:
  463. break # Only need the first message on truncation
  464. if len(messageB) <= maxMessageLength:
  465. messages.append(message)
  466. break
  467. spacePos = messageB.rfind(b' ', 0, maxMessageLength + 1)
  468. if spacePos != -1:
  469. messages.append(messageB[:spacePos].decode('utf-8'))
  470. messageB = messageB[spacePos + 1:]
  471. message = messageB.decode('utf-8')
  472. continue
  473. # No space found, need to search for a suitable codepoint location.
  474. pMessage = message[:maxMessageLength] # at most 510 codepoints which expand to at least 510 bytes
  475. pLengths = [len(x.encode('utf-8')) for x in pMessage] # byte size of each codepoint
  476. pRunningLengths = list(itertools.accumulate(pLengths)) # byte size up to each codepoint
  477. if pRunningLengths[-1] <= maxMessageLength: # Special case: entire pMessage is short enough
  478. messages.append(pMessage)
  479. message = message[maxMessageLength:]
  480. messageB = message.encode('utf-8')
  481. continue
  482. cutoffIndex = next(x[0] for x in enumerate(pRunningLengths) if x[1] > maxMessageLength)
  483. messages.append(message[:cutoffIndex])
  484. message = message[cutoffIndex:]
  485. messageB = message.encode('utf-8')
  486. if overlongmode == 'split':
  487. for msg in reversed(messages):
  488. self.http2ircMessageQueue.putleft_nowait((channel, msg, overlongmode))
  489. elif overlongmode == 'truncate':
  490. self.http2ircMessageQueue.putleft_nowait((channel, messages[0] + '…', overlongmode))
  491. else:
  492. self.logger.info(f'Sending {message!r} to {channel!r}')
  493. self.unconfirmedMessages.append((channel, message, overlongmode))
  494. self.send(b'PRIVMSG ' + channelB + b' :' + messageB)
  495. async def confirm_messages(self):
  496. while self.connected:
  497. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED, timeout = 60) # Confirm once per minute
  498. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  499. self.http2ircMessageQueue.putleft_nowait(*self.unconfirmedMessages)
  500. self.unconfirmedMessages = []
  501. break
  502. if not self.unconfirmedMessages:
  503. self.logger.debug('No messages to confirm')
  504. continue
  505. self.logger.debug('Trying to confirm message delivery')
  506. self.pongReceivedEvent.clear()
  507. self.send(b'PING :42')
  508. await wait_cancel_pending({asyncio.create_task(self.pongReceivedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED, timeout = 5)
  509. self.logger.debug(f'Message delivery successful: {self.pongReceivedEvent.is_set()}')
  510. if not self.pongReceivedEvent.is_set():
  511. # No PONG received in five seconds, assume connection's dead
  512. self.logger.warning(f'Message delivery confirmation failed, putting {len(self.unconfirmedMessages)} messages back into the queue')
  513. self.http2ircMessageQueue.putleft_nowait(*self.unconfirmedMessages)
  514. self.transport.close()
  515. self.unconfirmedMessages = []
  516. def data_received(self, data):
  517. time_ = time.time()
  518. self.logger.debug(f'Data received: {data!r}')
  519. self.lastRecvTime = time_
  520. # If there's any data left in the buffer, prepend it to the data. Split on CRLF.
  521. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  522. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  523. if self.buffer:
  524. data = self.buffer + data
  525. messages = data.split(b'\r\n')
  526. for message in messages[:-1]:
  527. lines = self.server.recv(message + b'\r\n')
  528. assert len(lines) == 1, f'recv did not return exactly one line: {message!r} -> {lines!r}'
  529. self.message_received(time_, message, lines[0])
  530. self.server.parse_tokens(lines[0])
  531. self.buffer = messages[-1]
  532. def message_received(self, time_, message, line):
  533. self.logger.debug(f'Message received at {time_}: {message!r}')
  534. # Send to HTTP broadcaster
  535. # Note: WHOX is handled further down
  536. for d in self.line_to_dicts(time_, line):
  537. self.irc2httpBroadcaster.send(d['channel'], d)
  538. maybeTriggerWhox = False
  539. # PING/PONG
  540. if line.command == 'PING':
  541. self._direct_send(irctokens.build('PONG', line.params).format().encode('utf-8'))
  542. elif line.command == 'PONG':
  543. self.pongReceivedEvent.set()
  544. # IRCv3 and SASL
  545. elif line.command == 'CAP':
  546. if line.params[1] == 'ACK':
  547. for cap in line.params[2].split(' '):
  548. self.logger.debug(f'CAP ACK: {cap}')
  549. self.caps.add(cap)
  550. if cap == 'sasl' and self.sasl:
  551. self.send(b'AUTHENTICATE EXTERNAL')
  552. else:
  553. self.capReqsPending.remove(cap)
  554. elif line.params[1] == 'NAK':
  555. self.logger.warning(f'Failed to activate CAP(s): {line.params[2]}')
  556. for cap in line.params[2].split(' '):
  557. self.capReqsPending.remove(cap)
  558. if len(self.capReqsPending) == 0:
  559. self.send(b'CAP END')
  560. elif line.command == 'AUTHENTICATE' and line.params == ['+']:
  561. self.send(b'AUTHENTICATE +')
  562. elif line.command == ircstates.numerics.RPL_SASLSUCCESS:
  563. self.authenticated = True
  564. self.capReqsPending.remove('sasl')
  565. if len(self.capReqsPending) == 0:
  566. self.send(b'CAP END')
  567. elif line.command in ('902', ircstates.numerics.ERR_SASLFAIL, ircstates.numerics.ERR_SASLTOOLONG, ircstates.numerics.ERR_SASLABORTED, ircstates.numerics.RPL_SASLMECHS):
  568. self.logger.error('SASL error, terminating connection')
  569. self.transport.close()
  570. # NICK errors
  571. elif line.command in ('431', ircstates.numerics.ERR_ERRONEUSNICKNAME, ircstates.numerics.ERR_NICKNAMEINUSE, '436'):
  572. self.logger.error(f'Failed to set nickname: {message!r}, terminating connection')
  573. self.transport.close()
  574. # USER errors
  575. elif line.command in ('461', '462'):
  576. self.logger.error(f'Failed to register: {message!r}, terminating connection')
  577. self.transport.close()
  578. # JOIN errors
  579. elif line.command in (
  580. ircstates.numerics.ERR_TOOMANYCHANNELS,
  581. ircstates.numerics.ERR_CHANNELISFULL,
  582. ircstates.numerics.ERR_INVITEONLYCHAN,
  583. ircstates.numerics.ERR_BANNEDFROMCHAN,
  584. ircstates.numerics.ERR_BADCHANNELKEY,
  585. ):
  586. self.logger.error(f'Failed to join channel: {message!r}, terminating connection')
  587. self.transport.close()
  588. # PART errors
  589. elif line.command == '442':
  590. self.logger.error(f'Failed to part channel: {message!r}')
  591. # JOIN/PART errors
  592. elif line.command == ircstates.numerics.ERR_NOSUCHCHANNEL:
  593. self.logger.error(f'Failed to join or part channel: {message!r}')
  594. # PRIVMSG errors
  595. elif line.command in (ircstates.numerics.ERR_NOSUCHNICK, '404', '407', '411', '412', '413', '414'):
  596. self.logger.error(f'Failed to send message: {message!r}')
  597. # Connection registration reply
  598. elif line.command == ircstates.numerics.RPL_WELCOME:
  599. self.logger.info('IRC connection registered')
  600. if self.sasl and not self.authenticated:
  601. self.logger.error('IRC connection registered but not authenticated, terminating connection')
  602. self.transport.close()
  603. return
  604. self.lastSentTime = time.time()
  605. self._send_join_part(b'JOIN', self.channels)
  606. asyncio.create_task(self.send_messages())
  607. asyncio.create_task(self.confirm_messages())
  608. # Bot getting KICKed
  609. elif line.command == 'KICK' and line.source and self.server.casefold(line.params[1]) == self.server.casefold(self.server.nickname):
  610. self.logger.warning(f'Got kicked from {line.params[0]}')
  611. kickedChannel = self.server.casefold(line.params[0])
  612. for channel in self.channels:
  613. if self.server.casefold(channel) == kickedChannel:
  614. self.channels.remove(channel)
  615. break
  616. # WHOX on successful JOIN if supported to fetch account information
  617. elif line.command == 'JOIN' and self.server.isupport.whox and line.source and self.server.casefold(line.hostmask.nickname) == self.server.casefold(self.server.nickname):
  618. self.whoxQueue.extend(line.params[0].split(','))
  619. maybeTriggerWhox = True
  620. # WHOX response
  621. elif line.command == ircstates.numerics.RPL_WHOSPCRPL and line.params[1] == '042':
  622. self.whoxReply.append({'nick': line.params[4], 'hostmask': f'{line.params[4]}!{line.params[2]}@{line.params[3]}', 'account': line.params[5] if line.params[5] != '0' else None})
  623. # End of WHOX response
  624. elif line.command == ircstates.numerics.RPL_ENDOFWHO:
  625. # Patch ircstates account info; ircstates does not parse the WHOX reply itself.
  626. for entry in self.whoxReply:
  627. if entry['account']:
  628. self.server.users[self.server.casefold(entry['nick'])].account = entry['account']
  629. self.irc2httpBroadcaster.send(self.whoxChannel, {'time': time_, 'command': 'RPL_ENDOFWHO', 'channel': self.whoxChannel, 'users': self.whoxReply, 'whoxstarttime': self.whoxStartTime})
  630. self.whoxChannel = None
  631. self.whoxReply = []
  632. self.whoxStartTime = None
  633. maybeTriggerWhox = True
  634. # General fatal ERROR
  635. elif line.command == 'ERROR':
  636. self.logger.error(f'Server sent ERROR: {message!r}')
  637. self.transport.close()
  638. # Send next WHOX if appropriate
  639. if maybeTriggerWhox and self.whoxChannel is None and self.whoxQueue:
  640. self.whoxChannel = self.whoxQueue.popleft()
  641. self.whoxReply = []
  642. self.whoxStartTime = time.time() # Note, may not be the actual start time due to rate limiting
  643. self.send(b'WHO ' + self.whoxChannel.encode('utf-8') + b' c%tuhna,042')
  644. def get_mode_chars(self, channelUser):
  645. if channelUser is None:
  646. return ''
  647. prefix = self.server.isupport.prefix
  648. return ''.join(prefix.prefixes[i] for i in sorted((prefix.modes.index(c) for c in channelUser.modes if c in prefix.modes)))
  649. def line_to_dicts(self, time_, line):
  650. if line.source:
  651. sourceUser = self.server.users.get(self.server.casefold(line.hostmask.nickname)) if line.source else None
  652. get_modes = lambda channel, nick = line.hostmask.nickname: self.get_mode_chars(self.server.channels[self.server.casefold(channel)].users.get(self.server.casefold(nick)))
  653. get_user = lambda channel, withModes = True: {
  654. 'nick': line.hostmask.nickname,
  655. 'hostmask': str(line.hostmask),
  656. 'account': getattr(self.server.users.get(self.server.casefold(line.hostmask.nickname)), 'account', None),
  657. **({'modes': get_modes(channel)} if withModes else {}),
  658. }
  659. if line.command == 'JOIN':
  660. # Although servers SHOULD NOT send multiple channels in one message per the modern IRC docs <https://modern.ircdocs.horse/#join-message>, let's do the safe thing...
  661. account = {'account': line.params[-2] if line.params[-2] != '*' else None} if 'extended-join' in self.caps else {}
  662. for channel in line.params[0].split(','):
  663. # There can't be a mode set yet on the JOIN, so no need to use get_modes (which would complicate the self-join).
  664. yield {'time': time_, 'command': 'JOIN', 'channel': channel, 'user': {**get_user(channel, False), **account}}
  665. elif line.command in ('PRIVMSG', 'NOTICE'):
  666. channel = line.params[0]
  667. if channel not in self.server.channels:
  668. return
  669. if line.command == 'PRIVMSG' and line.params[1].startswith('\x01ACTION ') and line.params[1].endswith('\x01'):
  670. # CTCP ACTION (aka /me)
  671. yield {'time': time_, 'command': 'ACTION', 'channel': channel, 'user': get_user(channel), 'message': line.params[1][8:-1]}
  672. return
  673. yield {'time': time_, 'command': line.command, 'channel': channel, 'user': get_user(channel), 'message': line.params[1]}
  674. elif line.command == 'PART':
  675. for channel in line.params[0].split(','):
  676. yield {'time': time_, 'command': 'PART', 'channel': channel, 'user': get_user(channel), 'reason': line.params[1] if len(line.params) == 2 else None}
  677. elif line.command in ('QUIT', 'NICK', 'ACCOUNT'):
  678. if line.hostmask.nickname == self.server.nickname:
  679. channels = self.channels
  680. elif sourceUser is not None:
  681. channels = sourceUser.channels
  682. else:
  683. return
  684. for channel in channels:
  685. if line.command == 'QUIT':
  686. extra = {'reason': line.params[0] if len(line.params) == 1 else None}
  687. elif line.command == 'NICK':
  688. extra = {'newnick': line.params[0]}
  689. elif line.command == 'ACCOUNT':
  690. extra = {'account': line.params[0]}
  691. yield {'time': time_, 'command': line.command, 'channel': channel, 'user': get_user(channel), **extra}
  692. elif line.command == 'MODE' and line.params[0][0] in ('#', '&'):
  693. channel = line.params[0]
  694. yield {'time': time_, 'command': 'MODE', 'channel': channel, 'user': get_user(channel), 'args': line.params[1:]}
  695. elif line.command == 'KICK':
  696. channel = line.params[0]
  697. targetUser = self.server.users[self.server.casefold(line.params[1])]
  698. yield {
  699. 'time': time_,
  700. 'command': 'KICK',
  701. 'channel': channel,
  702. 'user': get_user(channel),
  703. 'targetuser': {'nick': targetUser.nickname, 'hostmask': targetUser.hostmask(), 'modes': get_modes(channel, targetUser.nickname), 'account': targetUser.account},
  704. 'reason': line.params[2] if len(line.params) == 3 else None
  705. }
  706. elif line.command == 'TOPIC':
  707. channel = line.params[0]
  708. channelObj = self.server.channels[self.server.casefold(channel)]
  709. oldTopic = {'topic': channelObj.topic, 'setter': channelObj.topic_setter, 'time': channelObj.topic_time.timestamp() if channelObj.topic_time else None} if channelObj.topic else None
  710. if line.params[1] == '':
  711. yield {'time': time_, 'command': 'TOPIC', 'channel': channel, 'user': get_user(channel), 'oldtopic': oldTopic, 'newtopic': None}
  712. else:
  713. yield {'time': time_, 'command': 'TOPIC', 'channel': channel, 'user': get_user(channel), 'oldtopic': oldTopic, 'newtopic': line.params[1]}
  714. elif line.command == ircstates.numerics.RPL_TOPIC:
  715. channel = line.params[1]
  716. yield {'time': time_, 'command': 'RPL_TOPIC', 'channel': channel, 'topic': line.params[2]}
  717. elif line.command == ircstates.numerics.RPL_TOPICWHOTIME:
  718. yield {'time': time_, 'command': 'RPL_TOPICWHOTIME', 'channel': line.params[1], 'setter': {'nick': irctokens.hostmask(line.params[2]).nickname, 'hostmask': line.params[2]}, 'topictime': int(line.params[3])}
  719. elif line.command == ircstates.numerics.RPL_ENDOFNAMES:
  720. channel = line.params[1]
  721. users = self.server.channels[self.server.casefold(channel)].users
  722. yield {'time': time_, 'command': 'NAMES', 'channel': channel, 'users': [{'nick': u.nickname, 'modes': self.get_mode_chars(u)} for u in users.values()]}
  723. async def quit(self):
  724. # The server acknowledges a QUIT by sending an ERROR and closing the connection. The latter triggers connection_lost, so just wait for the closure event.
  725. self.logger.info('Quitting')
  726. self.lastSentTime = 1.67e34 * math.pi * 1e7 # Disable sending any further messages in send_queue
  727. self._direct_send(b'QUIT :Bye')
  728. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = 10)
  729. if not self.connectionClosedEvent.is_set():
  730. self.logger.error('Quitting cleanly did not work, closing connection forcefully')
  731. # Event will be set implicitly in connection_lost.
  732. self.transport.close()
  733. def connection_lost(self, exc):
  734. time_ = time.time()
  735. self.logger.info('IRC connection lost')
  736. self.connected = False
  737. self.connectionClosedEvent.set()
  738. self.irc2httpBroadcaster.send(Broadcaster.ALL_CHANNELS, {'time': time_, 'command': 'CONNLOST'})
  739. class IRCClient:
  740. logger = logging.getLogger('http2irc.IRCClient')
  741. def __init__(self, http2ircMessageQueue, irc2httpBroadcaster, config):
  742. self.http2ircMessageQueue = http2ircMessageQueue
  743. self.irc2httpBroadcaster = irc2httpBroadcaster
  744. self.config = config
  745. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  746. self._transport = None
  747. self._protocol = None
  748. def update_config(self, config):
  749. needReconnect = self.config['irc'] != config['irc']
  750. self.config = config
  751. if self._transport: # if currently connected:
  752. if needReconnect:
  753. self._transport.close()
  754. else:
  755. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  756. self._protocol.update_channels(self.channels)
  757. def _get_ssl_context(self):
  758. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  759. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  760. if ctx is True:
  761. ctx = ssl.create_default_context()
  762. if isinstance(ctx, ssl.SSLContext):
  763. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  764. return ctx
  765. async def run(self, loop, sigintEvent):
  766. connectionClosedEvent = asyncio.Event()
  767. while True:
  768. connectionClosedEvent.clear()
  769. try:
  770. self.logger.debug('Creating IRC connection')
  771. t = asyncio.create_task(loop.create_connection(
  772. protocol_factory = lambda: IRCClientProtocol(self.http2ircMessageQueue, self.irc2httpBroadcaster, connectionClosedEvent, loop, self.config, self.channels),
  773. host = self.config['irc']['host'],
  774. port = self.config['irc']['port'],
  775. ssl = self._get_ssl_context(),
  776. family = self.config['irc']['family'],
  777. ))
  778. # No automatic cancellation of t because it's handled manually below.
  779. done, _ = await wait_cancel_pending({asyncio.create_task(sigintEvent.wait())}, paws = {t}, return_when = asyncio.FIRST_COMPLETED, timeout = 30)
  780. if t not in done:
  781. t.cancel()
  782. await t # Raises the CancelledError
  783. self._transport, self._protocol = t.result()
  784. self.logger.debug('Starting send queue processing')
  785. sendTask = asyncio.create_task(self._protocol.send_queue()) # Quits automatically on connectionClosedEvent
  786. self.logger.debug('Waiting for connection closure or SIGINT')
  787. try:
  788. await wait_cancel_pending({asyncio.create_task(connectionClosedEvent.wait()), asyncio.create_task(sigintEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  789. finally:
  790. self.logger.debug(f'Got connection closed {connectionClosedEvent.is_set()} / SIGINT {sigintEvent.is_set()}')
  791. if not connectionClosedEvent.is_set():
  792. self.logger.debug('Quitting connection')
  793. await self._protocol.quit()
  794. if not sendTask.done():
  795. sendTask.cancel()
  796. try:
  797. await sendTask
  798. except asyncio.CancelledError:
  799. pass
  800. self._transport = None
  801. self._protocol = None
  802. except (ConnectionError, ssl.SSLError, asyncio.TimeoutError, asyncio.CancelledError) as e:
  803. self.logger.error(f'{type(e).__module__}.{type(e).__name__}: {e!s}')
  804. await wait_cancel_pending({asyncio.create_task(sigintEvent.wait())}, timeout = 5)
  805. if sigintEvent.is_set():
  806. self.logger.debug('Got SIGINT, breaking IRC loop')
  807. break
  808. @property
  809. def lastRecvTime(self):
  810. return self._protocol.lastRecvTime if self._protocol else None
  811. class Broadcaster:
  812. ALL_CHANNELS = object() # Singleton for send's channel argument, e.g. for connection loss
  813. def __init__(self):
  814. self._queues = {}
  815. def subscribe(self, channel):
  816. queue = asyncio.Queue()
  817. if channel not in self._queues:
  818. self._queues[channel] = set()
  819. self._queues[channel].add(queue)
  820. return queue
  821. def _send(self, channel, j):
  822. for queue in self._queues[channel]:
  823. queue.put_nowait(j)
  824. def send(self, channel, d):
  825. if channel is self.ALL_CHANNELS and self._queues:
  826. channels = self._queues
  827. elif channel in self._queues:
  828. channels = [channel]
  829. else:
  830. return
  831. j = json.dumps(d, separators = (',', ':')).encode('utf-8')
  832. for channel in channels:
  833. self._send(channel, j)
  834. def unsubscribe(self, channel, queue):
  835. self._queues[channel].remove(queue)
  836. if not self._queues[channel]:
  837. del self._queues[channel]
  838. class WebServer:
  839. logger = logging.getLogger('http2irc.WebServer')
  840. def __init__(self, http2ircMessageQueue, irc2httpBroadcaster, ircClient, config):
  841. self.http2ircMessageQueue = http2ircMessageQueue
  842. self.irc2httpBroadcaster = irc2httpBroadcaster
  843. self.ircClient = ircClient
  844. self.config = config
  845. self._paths = {} # '/path' => ('#channel', auth, module, moduleargs) where auth is either False (no authentication) or the HTTP header value for basic auth
  846. self._app = aiohttp.web.Application()
  847. self._app.add_routes([
  848. aiohttp.web.get('/status', self.get_status),
  849. aiohttp.web.post('/{path:.+}', functools.partial(self._path_request, func = self.post)),
  850. aiohttp.web.get('/{path:.+}', functools.partial(self._path_request, func = self.get)),
  851. ])
  852. self.update_config(config)
  853. self._configChanged = asyncio.Event()
  854. self.stopEvent = None
  855. def update_config(self, config):
  856. 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'], map_['overlongmode']) for map_ in config['maps'].values()}
  857. needRebind = self.config['web'] != config['web']
  858. self.config = config
  859. if needRebind:
  860. self._configChanged.set()
  861. async def run(self, stopEvent):
  862. self.stopEvent = stopEvent
  863. while True:
  864. runner = aiohttp.web.AppRunner(self._app)
  865. await runner.setup()
  866. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  867. await site.start()
  868. await wait_cancel_pending({asyncio.create_task(stopEvent.wait()), asyncio.create_task(self._configChanged.wait())}, return_when = asyncio.FIRST_COMPLETED)
  869. await runner.cleanup()
  870. if stopEvent.is_set():
  871. break
  872. self._configChanged.clear()
  873. async def get_status(self, request):
  874. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  875. return (aiohttp.web.Response if (self.ircClient.lastRecvTime or 0) > time.time() - 600 else aiohttp.web.HTTPInternalServerError)()
  876. async def _path_request(self, request, func):
  877. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.method} {request.path!r} with body {(await request.read())!r}')
  878. try:
  879. pathConfig = self._paths[request.path]
  880. except KeyError:
  881. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  882. raise aiohttp.web.HTTPNotFound()
  883. auth = pathConfig[1]
  884. if auth:
  885. authHeader = request.headers.get('Authorization')
  886. if not authHeader or authHeader != auth:
  887. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  888. raise aiohttp.web.HTTPForbidden()
  889. return (await func(request, *pathConfig))
  890. async def post(self, request, channel, auth, module, moduleargs, overlongmode):
  891. if module is not None:
  892. self.logger.debug(f'Processing request {id(request)} using {module!r}')
  893. try:
  894. message = await module.process(request, *moduleargs)
  895. except aiohttp.web.HTTPException as e:
  896. raise e
  897. except Exception as e:
  898. self.logger.error(f'Bad request {id(request)}: exception in module process function: {type(e).__module__}.{type(e).__name__}: {e!s}')
  899. raise aiohttp.web.HTTPBadRequest()
  900. if '\r' in message or '\n' in message:
  901. self.logger.error(f'Bad request {id(request)}: module process function returned message with linebreaks: {message!r}')
  902. raise aiohttp.web.HTTPBadRequest()
  903. else:
  904. self.logger.debug(f'Processing request {id(request)} using default processor')
  905. message = await self._default_process(request)
  906. self.logger.info(f'Accepted request {id(request)}, putting message {message!r} for {channel} into message queue')
  907. self.http2ircMessageQueue.put_nowait((channel, message, overlongmode))
  908. raise aiohttp.web.HTTPOk()
  909. async def _default_process(self, request):
  910. try:
  911. message = await request.text()
  912. except Exception as e:
  913. self.logger.info(f'Bad request {id(request)}: exception while reading request data: {e!s}')
  914. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  915. self.logger.debug(f'Request {id(request)} payload: {message!r}')
  916. # Strip optional [CR] LF at the end of the payload
  917. if message.endswith('\r\n'):
  918. message = message[:-2]
  919. elif message.endswith('\n'):
  920. message = message[:-1]
  921. if '\r' in message or '\n' in message:
  922. self.logger.info(f'Bad request {id(request)}: linebreaks in message')
  923. raise aiohttp.web.HTTPBadRequest()
  924. return message
  925. async def get(self, request, channel, auth, module, moduleargs, overlongmode):
  926. self.logger.info(f'Subscribing listener from request {id(request)} for {channel}')
  927. queue = self.irc2httpBroadcaster.subscribe(channel)
  928. response = aiohttp.web.StreamResponse()
  929. response.enable_chunked_encoding()
  930. await response.prepare(request)
  931. try:
  932. while True:
  933. t = asyncio.create_task(queue.get())
  934. done, pending = await wait_cancel_pending({t, asyncio.create_task(self.stopEvent.wait()), asyncio.create_task(self._configChanged.wait())}, return_when = asyncio.FIRST_COMPLETED)
  935. if t not in done: # stopEvent or config change
  936. #TODO Don't break if the config change doesn't affect this connection
  937. break
  938. j = t.result()
  939. await response.write(j + b'\n')
  940. finally:
  941. self.irc2httpBroadcaster.unsubscribe(channel, queue)
  942. self.logger.info(f'Unsubscribed listener from request {id(request)} for {channel}')
  943. return response
  944. def configure_logging(config):
  945. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  946. root = logging.getLogger()
  947. root.setLevel(getattr(logging, config['logging']['level']))
  948. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  949. formatter = logging.Formatter(config['logging']['format'], style = '{')
  950. stderrHandler = logging.StreamHandler()
  951. stderrHandler.setFormatter(formatter)
  952. root.addHandler(stderrHandler)
  953. async def main():
  954. if len(sys.argv) != 2:
  955. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  956. sys.exit(1)
  957. configFile = sys.argv[1]
  958. config = Config(configFile)
  959. configure_logging(config)
  960. loop = asyncio.get_running_loop()
  961. http2ircMessageQueue = MessageQueue()
  962. irc2httpBroadcaster = Broadcaster()
  963. irc = IRCClient(http2ircMessageQueue, irc2httpBroadcaster, config)
  964. webserver = WebServer(http2ircMessageQueue, irc2httpBroadcaster, irc, config)
  965. sigintEvent = asyncio.Event()
  966. def sigint_callback():
  967. global logger
  968. nonlocal sigintEvent
  969. logger.info('Got SIGINT, stopping')
  970. sigintEvent.set()
  971. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  972. def sigusr1_callback():
  973. global logger
  974. nonlocal config, irc, webserver
  975. logger.info('Got SIGUSR1, reloading config')
  976. try:
  977. newConfig = config.reread()
  978. except InvalidConfig as e:
  979. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  980. return
  981. config = newConfig
  982. configure_logging(config)
  983. irc.update_config(config)
  984. webserver.update_config(config)
  985. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  986. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  987. if __name__ == '__main__':
  988. asyncio.run(main())