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.

1123 lines
50 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. user = {
  403. 'nick': self.server.nickname,
  404. 'hostmask': f'{self.server.nickname}!{self.server.username}@{self.server.hostname}',
  405. 'account': self.server.account,
  406. 'modes': self.get_mode_chars(self.server.channels[self.server.casefold(channel)].users.get(self.server.casefold(self.server.nickname))),
  407. }
  408. self.irc2httpBroadcaster.send(channel, {'time': time_, 'command': command, 'channel': channel, 'user': user, 'message': message})
  409. return time_
  410. async def send_queue(self):
  411. while True:
  412. self.logger.debug('Trying to get data from send queue')
  413. t = asyncio.create_task(self.sendQueue.get())
  414. done, pending = await wait_cancel_pending({t, asyncio.create_task(self.connectionClosedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  415. if self.connectionClosedEvent.is_set():
  416. break
  417. assert t in done, f'{t!r} is not in {done!r}'
  418. data = t.result()
  419. self.logger.debug(f'Got {data!r} from send queue')
  420. now = time.time()
  421. if self.lastSentTime is not None and now - self.lastSentTime < 1:
  422. self.logger.debug(f'Rate limited')
  423. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = self.lastSentTime + 1 - now)
  424. if self.connectionClosedEvent.is_set():
  425. break
  426. time_ = self._direct_send(data)
  427. if self.lastSentTime is not None:
  428. self.lastSentTime = time_
  429. async def _get_message(self):
  430. self.logger.debug(f'Message queue {id(self.http2ircMessageQueue)} length: {self.http2ircMessageQueue.qsize()}')
  431. messageFuture = asyncio.create_task(self.http2ircMessageQueue.get())
  432. done, pending = await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, paws = {messageFuture}, return_when = asyncio.FIRST_COMPLETED)
  433. if self.connectionClosedEvent.is_set():
  434. if messageFuture in pending:
  435. self.logger.debug('Cancelling messageFuture')
  436. messageFuture.cancel()
  437. try:
  438. await messageFuture
  439. except asyncio.CancelledError:
  440. self.logger.debug('Cancelled messageFuture')
  441. pass
  442. else:
  443. # messageFuture is already done but we're stopping, so put the result back onto the queue
  444. self.http2ircMessageQueue.putleft_nowait(messageFuture.result())
  445. return None, None, None
  446. assert messageFuture in done, 'Invalid state: messageFuture not in done futures'
  447. return messageFuture.result()
  448. def _self_usermask_length(self):
  449. if not self.server.nickname or not self.server.username or not self.server.hostname:
  450. return 100
  451. return len(self.server.nickname) + len(self.server.username) + len(self.server.hostname)
  452. async def send_messages(self):
  453. while self.connected:
  454. self.logger.debug(f'Trying to get a message')
  455. channel, message, overlongmode = await self._get_message()
  456. self.logger.debug(f'Got message: {message!r}')
  457. if message is None:
  458. break
  459. channelB = channel.encode('utf-8')
  460. messageB = message.encode('utf-8')
  461. usermaskPrefixLength = 1 + self._self_usermask_length() + 1
  462. if usermaskPrefixLength + len(b'PRIVMSG ' + channelB + b' :' + messageB) > 510:
  463. # 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.
  464. self.logger.debug(f'Message too long, overlongmode = {overlongmode}')
  465. prefix = b'PRIVMSG ' + channelB + b' :'
  466. prefixLength = usermaskPrefixLength + len(prefix) # Need to account for the origin prefix included by the ircd when sending to others
  467. maxMessageLength = 510 - prefixLength # maximum length of the message part within each line
  468. if overlongmode == 'truncate':
  469. maxMessageLength -= 3 # Make room for an ellipsis at the end
  470. messages = []
  471. while message:
  472. if overlongmode == 'truncate' and messages:
  473. break # Only need the first message on truncation
  474. if len(messageB) <= maxMessageLength:
  475. messages.append(message)
  476. break
  477. spacePos = messageB.rfind(b' ', 0, maxMessageLength + 1)
  478. if spacePos != -1:
  479. messages.append(messageB[:spacePos].decode('utf-8'))
  480. messageB = messageB[spacePos + 1:]
  481. message = messageB.decode('utf-8')
  482. continue
  483. # No space found, need to search for a suitable codepoint location.
  484. pMessage = message[:maxMessageLength] # at most 510 codepoints which expand to at least 510 bytes
  485. pLengths = [len(x.encode('utf-8')) for x in pMessage] # byte size of each codepoint
  486. pRunningLengths = list(itertools.accumulate(pLengths)) # byte size up to each codepoint
  487. if pRunningLengths[-1] <= maxMessageLength: # Special case: entire pMessage is short enough
  488. messages.append(pMessage)
  489. message = message[maxMessageLength:]
  490. messageB = message.encode('utf-8')
  491. continue
  492. cutoffIndex = next(x[0] for x in enumerate(pRunningLengths) if x[1] > maxMessageLength)
  493. messages.append(message[:cutoffIndex])
  494. message = message[cutoffIndex:]
  495. messageB = message.encode('utf-8')
  496. if overlongmode == 'split':
  497. for msg in reversed(messages):
  498. self.http2ircMessageQueue.putleft_nowait((channel, msg, overlongmode))
  499. elif overlongmode == 'truncate':
  500. self.http2ircMessageQueue.putleft_nowait((channel, messages[0] + '…', overlongmode))
  501. else:
  502. self.logger.info(f'Sending {message!r} to {channel!r}')
  503. self.unconfirmedMessages.append((channel, message, overlongmode))
  504. self.send(b'PRIVMSG ' + channelB + b' :' + messageB)
  505. async def confirm_messages(self):
  506. while self.connected:
  507. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED, timeout = 60) # Confirm once per minute
  508. if not self.connected: # Disconnected while sleeping, can't confirm unconfirmed messages, requeue them directly
  509. self.http2ircMessageQueue.putleft_nowait(*self.unconfirmedMessages)
  510. self.unconfirmedMessages = []
  511. break
  512. if not self.unconfirmedMessages:
  513. self.logger.debug('No messages to confirm')
  514. continue
  515. self.logger.debug('Trying to confirm message delivery')
  516. self.pongReceivedEvent.clear()
  517. self.send(b'PING :42')
  518. await wait_cancel_pending({asyncio.create_task(self.pongReceivedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED, timeout = 5)
  519. self.logger.debug(f'Message delivery successful: {self.pongReceivedEvent.is_set()}')
  520. if not self.pongReceivedEvent.is_set():
  521. # No PONG received in five seconds, assume connection's dead
  522. self.logger.warning(f'Message delivery confirmation failed, putting {len(self.unconfirmedMessages)} messages back into the queue')
  523. self.http2ircMessageQueue.putleft_nowait(*self.unconfirmedMessages)
  524. self.transport.close()
  525. self.unconfirmedMessages = []
  526. def data_received(self, data):
  527. time_ = time.time()
  528. self.logger.debug(f'Data received: {data!r}')
  529. self.lastRecvTime = time_
  530. # If there's any data left in the buffer, prepend it to the data. Split on CRLF.
  531. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  532. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  533. if self.buffer:
  534. data = self.buffer + data
  535. messages = data.split(b'\r\n')
  536. for message in messages[:-1]:
  537. lines = self.server.recv(message + b'\r\n')
  538. assert len(lines) == 1, f'recv did not return exactly one line: {message!r} -> {lines!r}'
  539. self.message_received(time_, message, lines[0])
  540. self.server.parse_tokens(lines[0])
  541. self.buffer = messages[-1]
  542. def message_received(self, time_, message, line):
  543. self.logger.debug(f'Message received at {time_}: {message!r}')
  544. # Send to HTTP broadcaster
  545. # Note: WHOX is handled further down
  546. for d in self.line_to_dicts(time_, line):
  547. self.irc2httpBroadcaster.send(d['channel'], d)
  548. maybeTriggerWhox = False
  549. # PING/PONG
  550. if line.command == 'PING':
  551. self._direct_send(irctokens.build('PONG', line.params).format().encode('utf-8'))
  552. elif line.command == 'PONG':
  553. self.pongReceivedEvent.set()
  554. # IRCv3 and SASL
  555. elif line.command == 'CAP':
  556. if line.params[1] == 'ACK':
  557. for cap in line.params[2].split(' '):
  558. self.logger.debug(f'CAP ACK: {cap}')
  559. self.caps.add(cap)
  560. if cap == 'sasl' and self.sasl:
  561. self.send(b'AUTHENTICATE EXTERNAL')
  562. else:
  563. self.capReqsPending.remove(cap)
  564. elif line.params[1] == 'NAK':
  565. self.logger.warning(f'Failed to activate CAP(s): {line.params[2]}')
  566. for cap in line.params[2].split(' '):
  567. self.capReqsPending.remove(cap)
  568. if len(self.capReqsPending) == 0:
  569. self.send(b'CAP END')
  570. elif line.command == 'AUTHENTICATE' and line.params == ['+']:
  571. self.send(b'AUTHENTICATE +')
  572. elif line.command == ircstates.numerics.RPL_SASLSUCCESS:
  573. self.authenticated = True
  574. self.capReqsPending.remove('sasl')
  575. if len(self.capReqsPending) == 0:
  576. self.send(b'CAP END')
  577. elif line.command in ('902', ircstates.numerics.ERR_SASLFAIL, ircstates.numerics.ERR_SASLTOOLONG, ircstates.numerics.ERR_SASLABORTED, ircstates.numerics.RPL_SASLMECHS):
  578. self.logger.error('SASL error, terminating connection')
  579. self.transport.close()
  580. # NICK errors
  581. elif line.command in ('431', ircstates.numerics.ERR_ERRONEUSNICKNAME, ircstates.numerics.ERR_NICKNAMEINUSE, '436'):
  582. self.logger.error(f'Failed to set nickname: {message!r}, terminating connection')
  583. self.transport.close()
  584. # USER errors
  585. elif line.command in ('461', '462'):
  586. self.logger.error(f'Failed to register: {message!r}, terminating connection')
  587. self.transport.close()
  588. # JOIN errors
  589. elif line.command in (
  590. ircstates.numerics.ERR_TOOMANYCHANNELS,
  591. ircstates.numerics.ERR_CHANNELISFULL,
  592. ircstates.numerics.ERR_INVITEONLYCHAN,
  593. ircstates.numerics.ERR_BANNEDFROMCHAN,
  594. ircstates.numerics.ERR_BADCHANNELKEY,
  595. ):
  596. self.logger.error(f'Failed to join channel: {message!r}, terminating connection')
  597. self.transport.close()
  598. # PART errors
  599. elif line.command == '442':
  600. self.logger.error(f'Failed to part channel: {message!r}')
  601. # JOIN/PART errors
  602. elif line.command == ircstates.numerics.ERR_NOSUCHCHANNEL:
  603. self.logger.error(f'Failed to join or part channel: {message!r}')
  604. # PRIVMSG errors
  605. elif line.command in (ircstates.numerics.ERR_NOSUCHNICK, '404', '407', '411', '412', '413', '414'):
  606. self.logger.error(f'Failed to send message: {message!r}')
  607. # Connection registration reply
  608. elif line.command == ircstates.numerics.RPL_WELCOME:
  609. self.logger.info('IRC connection registered')
  610. if self.sasl and not self.authenticated:
  611. self.logger.error('IRC connection registered but not authenticated, terminating connection')
  612. self.transport.close()
  613. return
  614. self.lastSentTime = time.time()
  615. self._send_join_part(b'JOIN', self.channels)
  616. asyncio.create_task(self.send_messages())
  617. asyncio.create_task(self.confirm_messages())
  618. # Bot getting KICKed
  619. elif line.command == 'KICK' and line.source and self.server.casefold(line.params[1]) == self.server.casefold(self.server.nickname):
  620. self.logger.warning(f'Got kicked from {line.params[0]}')
  621. kickedChannel = self.server.casefold(line.params[0])
  622. for channel in self.channels:
  623. if self.server.casefold(channel) == kickedChannel:
  624. self.channels.remove(channel)
  625. break
  626. # WHOX on successful JOIN if supported to fetch account information
  627. 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):
  628. self.whoxQueue.extend(line.params[0].split(','))
  629. maybeTriggerWhox = True
  630. # WHOX response
  631. elif line.command == ircstates.numerics.RPL_WHOSPCRPL and line.params[1] == '042':
  632. 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})
  633. # End of WHOX response
  634. elif line.command == ircstates.numerics.RPL_ENDOFWHO:
  635. # Patch ircstates account info; ircstates does not parse the WHOX reply itself.
  636. for entry in self.whoxReply:
  637. if entry['account']:
  638. self.server.users[self.server.casefold(entry['nick'])].account = entry['account']
  639. self.irc2httpBroadcaster.send(self.whoxChannel, {'time': time_, 'command': 'RPL_ENDOFWHO', 'channel': self.whoxChannel, 'users': self.whoxReply, 'whoxstarttime': self.whoxStartTime})
  640. self.whoxChannel = None
  641. self.whoxReply = []
  642. self.whoxStartTime = None
  643. maybeTriggerWhox = True
  644. # General fatal ERROR
  645. elif line.command == 'ERROR':
  646. self.logger.error(f'Server sent ERROR: {message!r}')
  647. self.transport.close()
  648. # Send next WHOX if appropriate
  649. if maybeTriggerWhox and self.whoxChannel is None and self.whoxQueue:
  650. self.whoxChannel = self.whoxQueue.popleft()
  651. self.whoxReply = []
  652. self.whoxStartTime = time.time() # Note, may not be the actual start time due to rate limiting
  653. self.send(b'WHO ' + self.whoxChannel.encode('utf-8') + b' c%tuhna,042')
  654. def get_mode_chars(self, channelUser):
  655. if channelUser is None:
  656. return ''
  657. prefix = self.server.isupport.prefix
  658. return ''.join(prefix.prefixes[i] for i in sorted((prefix.modes.index(c) for c in channelUser.modes if c in prefix.modes)))
  659. def line_to_dicts(self, time_, line):
  660. if line.source:
  661. sourceUser = self.server.users.get(self.server.casefold(line.hostmask.nickname)) if line.source else None
  662. 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)))
  663. get_user = lambda channel, withModes = True: {
  664. 'nick': line.hostmask.nickname,
  665. 'hostmask': str(line.hostmask),
  666. 'account': getattr(self.server.users.get(self.server.casefold(line.hostmask.nickname)), 'account', None),
  667. **({'modes': get_modes(channel)} if withModes else {}),
  668. }
  669. if line.command == 'JOIN':
  670. # 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...
  671. account = {'account': line.params[-2] if line.params[-2] != '*' else None} if 'extended-join' in self.caps else {}
  672. for channel in line.params[0].split(','):
  673. # There can't be a mode set yet on the JOIN, so no need to use get_modes (which would complicate the self-join).
  674. yield {'time': time_, 'command': 'JOIN', 'channel': channel, 'user': {**get_user(channel, False), **account}}
  675. elif line.command in ('PRIVMSG', 'NOTICE'):
  676. channel = line.params[0]
  677. if channel not in self.server.channels:
  678. return
  679. if line.command == 'PRIVMSG' and line.params[1].startswith('\x01ACTION ') and line.params[1].endswith('\x01'):
  680. # CTCP ACTION (aka /me)
  681. yield {'time': time_, 'command': 'ACTION', 'channel': channel, 'user': get_user(channel), 'message': line.params[1][8:-1]}
  682. return
  683. yield {'time': time_, 'command': line.command, 'channel': channel, 'user': get_user(channel), 'message': line.params[1]}
  684. elif line.command == 'PART':
  685. for channel in line.params[0].split(','):
  686. yield {'time': time_, 'command': 'PART', 'channel': channel, 'user': get_user(channel), 'reason': line.params[1] if len(line.params) == 2 else None}
  687. elif line.command in ('QUIT', 'NICK', 'ACCOUNT'):
  688. if line.hostmask.nickname == self.server.nickname:
  689. channels = self.channels
  690. elif sourceUser is not None:
  691. channels = sourceUser.channels
  692. else:
  693. return
  694. for channel in channels:
  695. if line.command == 'QUIT':
  696. extra = {'reason': line.params[0] if len(line.params) == 1 else None}
  697. elif line.command == 'NICK':
  698. extra = {'newnick': line.params[0]}
  699. elif line.command == 'ACCOUNT':
  700. extra = {'account': line.params[0]}
  701. yield {'time': time_, 'command': line.command, 'channel': channel, 'user': get_user(channel), **extra}
  702. elif line.command == 'MODE' and line.params[0][0] in ('#', '&'):
  703. channel = line.params[0]
  704. yield {'time': time_, 'command': 'MODE', 'channel': channel, 'user': get_user(channel), 'args': line.params[1:]}
  705. elif line.command == 'KICK':
  706. channel = line.params[0]
  707. targetUser = self.server.users[self.server.casefold(line.params[1])]
  708. yield {
  709. 'time': time_,
  710. 'command': 'KICK',
  711. 'channel': channel,
  712. 'user': get_user(channel),
  713. 'targetuser': {'nick': targetUser.nickname, 'hostmask': targetUser.hostmask(), 'modes': get_modes(channel, targetUser.nickname), 'account': targetUser.account},
  714. 'reason': line.params[2] if len(line.params) == 3 else None
  715. }
  716. elif line.command == 'TOPIC':
  717. channel = line.params[0]
  718. channelObj = self.server.channels[self.server.casefold(channel)]
  719. oldTopic = {'topic': channelObj.topic, 'setter': channelObj.topic_setter, 'time': channelObj.topic_time.timestamp() if channelObj.topic_time else None} if channelObj.topic else None
  720. if line.params[1] == '':
  721. yield {'time': time_, 'command': 'TOPIC', 'channel': channel, 'user': get_user(channel), 'oldtopic': oldTopic, 'newtopic': None}
  722. else:
  723. yield {'time': time_, 'command': 'TOPIC', 'channel': channel, 'user': get_user(channel), 'oldtopic': oldTopic, 'newtopic': line.params[1]}
  724. elif line.command == ircstates.numerics.RPL_TOPIC:
  725. channel = line.params[1]
  726. yield {'time': time_, 'command': 'RPL_TOPIC', 'channel': channel, 'topic': line.params[2]}
  727. elif line.command == ircstates.numerics.RPL_TOPICWHOTIME:
  728. 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])}
  729. elif line.command == ircstates.numerics.RPL_ENDOFNAMES:
  730. channel = line.params[1]
  731. users = self.server.channels[self.server.casefold(channel)].users
  732. yield {'time': time_, 'command': 'NAMES', 'channel': channel, 'users': [{'nick': u.nickname, 'modes': self.get_mode_chars(u)} for u in users.values()]}
  733. async def quit(self):
  734. # 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.
  735. self.logger.info('Quitting')
  736. self.lastSentTime = 1.67e34 * math.pi * 1e7 # Disable sending any further messages in send_queue
  737. self._direct_send(b'QUIT :Bye')
  738. await wait_cancel_pending({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = 10)
  739. if not self.connectionClosedEvent.is_set():
  740. self.logger.error('Quitting cleanly did not work, closing connection forcefully')
  741. # Event will be set implicitly in connection_lost.
  742. self.transport.close()
  743. def connection_lost(self, exc):
  744. time_ = time.time()
  745. self.logger.info('IRC connection lost')
  746. self.connected = False
  747. self.connectionClosedEvent.set()
  748. self.irc2httpBroadcaster.send(Broadcaster.ALL_CHANNELS, {'time': time_, 'command': 'CONNLOST'})
  749. class IRCClient:
  750. logger = logging.getLogger('http2irc.IRCClient')
  751. def __init__(self, http2ircMessageQueue, irc2httpBroadcaster, config):
  752. self.http2ircMessageQueue = http2ircMessageQueue
  753. self.irc2httpBroadcaster = irc2httpBroadcaster
  754. self.config = config
  755. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  756. self._transport = None
  757. self._protocol = None
  758. def update_config(self, config):
  759. needReconnect = self.config['irc'] != config['irc']
  760. self.config = config
  761. if self._transport: # if currently connected:
  762. if needReconnect:
  763. self._transport.close()
  764. else:
  765. self.channels = {map_['ircchannel'] for map_ in config['maps'].values()}
  766. self._protocol.update_channels(self.channels)
  767. def _get_ssl_context(self):
  768. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  769. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  770. if ctx is True:
  771. ctx = ssl.create_default_context()
  772. if isinstance(ctx, ssl.SSLContext):
  773. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  774. return ctx
  775. async def run(self, loop, sigintEvent):
  776. connectionClosedEvent = asyncio.Event()
  777. while True:
  778. connectionClosedEvent.clear()
  779. try:
  780. self.logger.debug('Creating IRC connection')
  781. t = asyncio.create_task(loop.create_connection(
  782. protocol_factory = lambda: IRCClientProtocol(self.http2ircMessageQueue, self.irc2httpBroadcaster, connectionClosedEvent, loop, self.config, self.channels),
  783. host = self.config['irc']['host'],
  784. port = self.config['irc']['port'],
  785. ssl = self._get_ssl_context(),
  786. family = self.config['irc']['family'],
  787. ))
  788. # No automatic cancellation of t because it's handled manually below.
  789. done, _ = await wait_cancel_pending({asyncio.create_task(sigintEvent.wait())}, paws = {t}, return_when = asyncio.FIRST_COMPLETED, timeout = 30)
  790. if t not in done:
  791. t.cancel()
  792. await t # Raises the CancelledError
  793. self._transport, self._protocol = t.result()
  794. self.logger.debug('Starting send queue processing')
  795. sendTask = asyncio.create_task(self._protocol.send_queue()) # Quits automatically on connectionClosedEvent
  796. self.logger.debug('Waiting for connection closure or SIGINT')
  797. try:
  798. await wait_cancel_pending({asyncio.create_task(connectionClosedEvent.wait()), asyncio.create_task(sigintEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  799. finally:
  800. self.logger.debug(f'Got connection closed {connectionClosedEvent.is_set()} / SIGINT {sigintEvent.is_set()}')
  801. if not connectionClosedEvent.is_set():
  802. self.logger.debug('Quitting connection')
  803. await self._protocol.quit()
  804. if not sendTask.done():
  805. sendTask.cancel()
  806. try:
  807. await sendTask
  808. except asyncio.CancelledError:
  809. pass
  810. self._transport = None
  811. self._protocol = None
  812. except (ConnectionError, ssl.SSLError, asyncio.TimeoutError, asyncio.CancelledError) as e:
  813. self.logger.error(f'{type(e).__module__}.{type(e).__name__}: {e!s}')
  814. await wait_cancel_pending({asyncio.create_task(sigintEvent.wait())}, timeout = 5)
  815. if sigintEvent.is_set():
  816. self.logger.debug('Got SIGINT, breaking IRC loop')
  817. break
  818. @property
  819. def lastRecvTime(self):
  820. return self._protocol.lastRecvTime if self._protocol else None
  821. class Broadcaster:
  822. ALL_CHANNELS = object() # Singleton for send's channel argument, e.g. for connection loss
  823. def __init__(self):
  824. self._queues = {}
  825. def subscribe(self, channel):
  826. queue = asyncio.Queue()
  827. if channel not in self._queues:
  828. self._queues[channel] = set()
  829. self._queues[channel].add(queue)
  830. return queue
  831. def _send(self, channel, j):
  832. for queue in self._queues[channel]:
  833. queue.put_nowait(j)
  834. def send(self, channel, d):
  835. if channel is self.ALL_CHANNELS and self._queues:
  836. channels = self._queues
  837. elif channel in self._queues:
  838. channels = [channel]
  839. else:
  840. return
  841. j = json.dumps(d, separators = (',', ':')).encode('utf-8')
  842. for channel in channels:
  843. self._send(channel, j)
  844. def unsubscribe(self, channel, queue):
  845. self._queues[channel].remove(queue)
  846. if not self._queues[channel]:
  847. del self._queues[channel]
  848. class WebServer:
  849. logger = logging.getLogger('http2irc.WebServer')
  850. def __init__(self, http2ircMessageQueue, irc2httpBroadcaster, ircClient, config):
  851. self.http2ircMessageQueue = http2ircMessageQueue
  852. self.irc2httpBroadcaster = irc2httpBroadcaster
  853. self.ircClient = ircClient
  854. self.config = config
  855. self._paths = {}
  856. # '/path' => ('#channel', postauth, getauth, module, moduleargs, overlongmode)
  857. # {post,get}auth are either False (access denied) or the HTTP header value for basic auth
  858. self._app = aiohttp.web.Application()
  859. self._app.add_routes([
  860. aiohttp.web.get('/status', self.get_status),
  861. aiohttp.web.post('/{path:.+}', functools.partial(self._path_request, func = self.post)),
  862. aiohttp.web.get('/{path:.+}', functools.partial(self._path_request, func = self.get)),
  863. ])
  864. self.update_config(config)
  865. self._configChanged = asyncio.Event()
  866. self.stopEvent = None
  867. def update_config(self, config):
  868. self._paths = {map_['webpath']: (
  869. map_['ircchannel'],
  870. f'Basic {base64.b64encode(map_["postauth"].encode("utf-8")).decode("utf-8")}' if map_['postauth'] else False,
  871. f'Basic {base64.b64encode(map_["getauth"].encode("utf-8")).decode("utf-8")}' if map_['getauth'] else False,
  872. map_['module'],
  873. map_['moduleargs'],
  874. map_['overlongmode']
  875. ) for map_ in config['maps'].values()}
  876. needRebind = self.config['web'] != config['web']
  877. self.config = config
  878. if needRebind:
  879. self._configChanged.set()
  880. async def run(self, stopEvent):
  881. self.stopEvent = stopEvent
  882. while True:
  883. runner = aiohttp.web.AppRunner(self._app)
  884. await runner.setup()
  885. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  886. await site.start()
  887. await wait_cancel_pending({asyncio.create_task(stopEvent.wait()), asyncio.create_task(self._configChanged.wait())}, return_when = asyncio.FIRST_COMPLETED)
  888. await runner.cleanup()
  889. if stopEvent.is_set():
  890. break
  891. self._configChanged.clear()
  892. async def get_status(self, request):
  893. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  894. return (aiohttp.web.Response if (self.ircClient.lastRecvTime or 0) > time.time() - 600 else aiohttp.web.HTTPInternalServerError)()
  895. async def _path_request(self, request, func):
  896. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.method} {request.path!r} with body {(await request.read())!r}')
  897. try:
  898. pathConfig = self._paths[request.path]
  899. except KeyError:
  900. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  901. raise aiohttp.web.HTTPNotFound()
  902. auth = pathConfig[1] if request.method == 'POST' else pathConfig[2]
  903. authHeader = request.headers.get('Authorization')
  904. if not authHeader or not auth or authHeader != auth:
  905. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  906. raise aiohttp.web.HTTPForbidden()
  907. return (await func(request, *pathConfig))
  908. async def post(self, request, channel, postauth, getauth, module, moduleargs, overlongmode):
  909. if module is not None:
  910. self.logger.debug(f'Processing request {id(request)} using {module!r}')
  911. try:
  912. message = await module.process(request, *moduleargs)
  913. except aiohttp.web.HTTPException as e:
  914. raise e
  915. except Exception as e:
  916. self.logger.error(f'Bad request {id(request)}: exception in module process function: {type(e).__module__}.{type(e).__name__}: {e!s}')
  917. raise aiohttp.web.HTTPBadRequest()
  918. if '\r' in message or '\n' in message:
  919. self.logger.error(f'Bad request {id(request)}: module process function returned message with linebreaks: {message!r}')
  920. raise aiohttp.web.HTTPBadRequest()
  921. else:
  922. self.logger.debug(f'Processing request {id(request)} using default processor')
  923. message = await self._default_process(request)
  924. self.logger.info(f'Accepted request {id(request)}, putting message {message!r} for {channel} into message queue')
  925. self.http2ircMessageQueue.put_nowait((channel, message, overlongmode))
  926. raise aiohttp.web.HTTPOk()
  927. async def _default_process(self, request):
  928. try:
  929. message = await request.text()
  930. except Exception as e:
  931. self.logger.info(f'Bad request {id(request)}: exception while reading request data: {e!s}')
  932. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  933. self.logger.debug(f'Request {id(request)} payload: {message!r}')
  934. # Strip optional [CR] LF at the end of the payload
  935. if message.endswith('\r\n'):
  936. message = message[:-2]
  937. elif message.endswith('\n'):
  938. message = message[:-1]
  939. if '\r' in message or '\n' in message:
  940. self.logger.info(f'Bad request {id(request)}: linebreaks in message')
  941. raise aiohttp.web.HTTPBadRequest()
  942. return message
  943. async def get(self, request, channel, postauth, getauth, module, moduleargs, overlongmode):
  944. self.logger.info(f'Subscribing listener from request {id(request)} for {channel}')
  945. queue = self.irc2httpBroadcaster.subscribe(channel)
  946. response = aiohttp.web.StreamResponse()
  947. response.enable_chunked_encoding()
  948. await response.prepare(request)
  949. try:
  950. while True:
  951. t = asyncio.create_task(queue.get())
  952. done, pending = await wait_cancel_pending({t, asyncio.create_task(self.stopEvent.wait()), asyncio.create_task(self._configChanged.wait())}, return_when = asyncio.FIRST_COMPLETED)
  953. if t not in done: # stopEvent or config change
  954. #TODO Don't break if the config change doesn't affect this connection
  955. break
  956. j = t.result()
  957. await response.write(j + b'\n')
  958. finally:
  959. self.irc2httpBroadcaster.unsubscribe(channel, queue)
  960. self.logger.info(f'Unsubscribed listener from request {id(request)} for {channel}')
  961. return response
  962. def configure_logging(config):
  963. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  964. root = logging.getLogger()
  965. root.setLevel(getattr(logging, config['logging']['level']))
  966. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  967. formatter = logging.Formatter(config['logging']['format'], style = '{')
  968. stderrHandler = logging.StreamHandler()
  969. stderrHandler.setFormatter(formatter)
  970. root.addHandler(stderrHandler)
  971. async def main():
  972. if len(sys.argv) != 2:
  973. print('Usage: http2irc.py CONFIGFILE', file = sys.stderr)
  974. sys.exit(1)
  975. configFile = sys.argv[1]
  976. config = Config(configFile)
  977. configure_logging(config)
  978. loop = asyncio.get_running_loop()
  979. http2ircMessageQueue = MessageQueue()
  980. irc2httpBroadcaster = Broadcaster()
  981. irc = IRCClient(http2ircMessageQueue, irc2httpBroadcaster, config)
  982. webserver = WebServer(http2ircMessageQueue, irc2httpBroadcaster, irc, config)
  983. sigintEvent = asyncio.Event()
  984. def sigint_callback():
  985. global logger
  986. nonlocal sigintEvent
  987. logger.info('Got SIGINT, stopping')
  988. sigintEvent.set()
  989. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  990. def sigusr1_callback():
  991. global logger
  992. nonlocal config, irc, webserver
  993. logger.info('Got SIGUSR1, reloading config')
  994. try:
  995. newConfig = config.reread()
  996. except InvalidConfig as e:
  997. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  998. return
  999. config = newConfig
  1000. configure_logging(config)
  1001. irc.update_config(config)
  1002. webserver.update_config(config)
  1003. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  1004. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent))
  1005. if __name__ == '__main__':
  1006. asyncio.run(main())