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.

812 Zeilen
35 KiB

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