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.

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