Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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