Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

939 Zeilen
41 KiB

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