選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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