You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

812 rivejä
36 KiB

  1. import aiohttp
  2. import aiohttp.web
  3. import asyncio
  4. import base64
  5. import collections
  6. import datetime
  7. import importlib.util
  8. import inspect
  9. import ircstates
  10. import irctokens
  11. import itertools
  12. import logging
  13. import os.path
  14. import signal
  15. import ssl
  16. import string
  17. import sys
  18. import tempfile
  19. import time
  20. import toml
  21. logger = logging.getLogger('irclog')
  22. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  23. messageConnectionClosed = object() # Signals that the connection was closed by either the bot or the server
  24. messageEOF = object() # Special object to signal the end of messages to Storage
  25. def get_month_str(ts = None):
  26. dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo = datetime.timezone.utc) if ts is not None else datetime.datetime.utcnow()
  27. return dt.strftime('%Y-%m')
  28. class InvalidConfig(Exception):
  29. '''Error in configuration file'''
  30. def is_valid_pem(path, withCert):
  31. '''Very basic check whether something looks like a valid PEM certificate'''
  32. try:
  33. with open(path, 'rb') as fp:
  34. contents = fp.read()
  35. # All of these raise exceptions if something's wrong...
  36. if withCert:
  37. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  38. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  39. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  40. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  41. else:
  42. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  43. endCertPos = -26 # Please shoot me.
  44. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  45. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  46. assert contents[endKeyPos + 26:] == b''
  47. return True
  48. except: # Yes, really
  49. return False
  50. class Config(dict):
  51. def __init__(self, filename):
  52. super().__init__()
  53. self._filename = filename
  54. with open(self._filename, 'r') as fp:
  55. obj = toml.load(fp)
  56. # Sanity checks
  57. if any(x not in ('logging', 'storage', 'irc', 'web', 'channels') for x in obj.keys()):
  58. raise InvalidConfig('Unknown sections found in base object')
  59. if any(not isinstance(x, collections.abc.Mapping) for x in obj.values()):
  60. raise InvalidConfig('Invalid section type(s), expected objects/dicts')
  61. if 'logging' in obj:
  62. if any(x not in ('level', 'format') for x in obj['logging']):
  63. raise InvalidConfig('Unknown key found in log section')
  64. if 'level' in obj['logging'] and obj['logging']['level'] not in ('DEBUG', 'INFO', 'WARNING', 'ERROR'):
  65. raise InvalidConfig('Invalid log level')
  66. if 'format' in obj['logging']:
  67. if not isinstance(obj['logging']['format'], str):
  68. raise InvalidConfig('Invalid log format')
  69. try:
  70. #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)
  71. # 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).
  72. assert sum(1 for x in string.Formatter().parse(obj['logging']['format']) if x[1] is not None) > 0
  73. except (ValueError, AssertionError) as e:
  74. raise InvalidConfig('Invalid log format: parsing failed') from e
  75. if 'storage' in obj:
  76. if any(x != 'path' for x in obj['storage']):
  77. raise InvalidConfig('Unknown key found in storage section')
  78. if 'path' in obj['storage']:
  79. obj['storage']['path'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['storage']['path']))
  80. try:
  81. #TODO This doesn't seem to work correctly; doesn't fail when the dir is -w
  82. f = tempfile.TemporaryFile(dir = obj['storage']['path'])
  83. f.close()
  84. except (OSError, IOError) as e:
  85. raise InvalidConfig('Invalid storage path: not writable') from e
  86. if 'irc' in obj:
  87. if any(x not in ('host', 'port', 'ssl', 'nick', 'real', 'certfile', 'certkeyfile') for x in obj['irc']):
  88. raise InvalidConfig('Unknown key found in irc section')
  89. if 'host' in obj['irc'] and not isinstance(obj['irc']['host'], str): #TODO: Check whether it's a valid hostname
  90. raise InvalidConfig('Invalid IRC host')
  91. if 'port' in obj['irc'] and (not isinstance(obj['irc']['port'], int) or not 1 <= obj['irc']['port'] <= 65535):
  92. raise InvalidConfig('Invalid IRC port')
  93. if 'ssl' in obj['irc'] and obj['irc']['ssl'] not in ('yes', 'no', 'insecure'):
  94. raise InvalidConfig(f'Invalid IRC SSL setting: {obj["irc"]["ssl"]!r}')
  95. if 'nick' in obj['irc'] and not isinstance(obj['irc']['nick'], str): #TODO: Check whether it's a valid nickname, username, etc.
  96. raise InvalidConfig('Invalid IRC nick')
  97. if len(IRCClientProtocol.nick_command(obj['irc']['nick'])) > 510:
  98. raise InvalidConfig('Invalid IRC nick: NICK command too long')
  99. if 'real' in obj['irc'] and not isinstance(obj['irc']['real'], str):
  100. raise InvalidConfig('Invalid IRC realname')
  101. if len(IRCClientProtocol.user_command(obj['irc']['nick'], obj['irc']['real'])) > 510:
  102. raise InvalidConfig('Invalid IRC nick/realname combination: USER command too long')
  103. if ('certfile' in obj['irc']) != ('certkeyfile' in obj['irc']):
  104. raise InvalidConfig('Invalid IRC cert config: needs both certfile and certkeyfile')
  105. if 'certfile' in obj['irc']:
  106. if not isinstance(obj['irc']['certfile'], str):
  107. raise InvalidConfig('Invalid certificate file: not a string')
  108. obj['irc']['certfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certfile']))
  109. if not os.path.isfile(obj['irc']['certfile']):
  110. raise InvalidConfig('Invalid certificate file: not a regular file')
  111. if not is_valid_pem(obj['irc']['certfile'], True):
  112. raise InvalidConfig('Invalid certificate file: not a valid PEM cert')
  113. if 'certkeyfile' in obj['irc']:
  114. if not isinstance(obj['irc']['certkeyfile'], str):
  115. raise InvalidConfig('Invalid certificate key file: not a string')
  116. obj['irc']['certkeyfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certkeyfile']))
  117. if not os.path.isfile(obj['irc']['certkeyfile']):
  118. raise InvalidConfig('Invalid certificate key file: not a regular file')
  119. if not is_valid_pem(obj['irc']['certkeyfile'], False):
  120. raise InvalidConfig('Invalid certificate key file: not a valid PEM key')
  121. if 'web' in obj:
  122. if any(x not in ('host', 'port') for x in obj['web']):
  123. raise InvalidConfig('Unknown key found in web section')
  124. if 'host' in obj['web'] and not isinstance(obj['web']['host'], str): #TODO: Check whether it's a valid hostname (must resolve I guess?)
  125. raise InvalidConfig('Invalid web hostname')
  126. if 'port' in obj['web'] and (not isinstance(obj['web']['port'], int) or not 1 <= obj['web']['port'] <= 65535):
  127. raise InvalidConfig('Invalid web port')
  128. if 'channels' in obj:
  129. seenChannels = {}
  130. for key, channel in obj['channels'].items():
  131. if not isinstance(key, str) or not key:
  132. raise InvalidConfig(f'Invalid channel key {key!r}')
  133. if not isinstance(channel, collections.abc.Mapping):
  134. raise InvalidConfig(f'Invalid channel for {key!r}')
  135. if any(x not in ('ircchannel', 'auth', 'active') for x in channel):
  136. raise InvalidConfig(f'Unknown key(s) found in channel {key!r}')
  137. if 'ircchannel' not in channel:
  138. channel['ircchannel'] = f'#{key}'
  139. if not isinstance(channel['ircchannel'], str):
  140. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: not a string')
  141. if not channel['ircchannel'].startswith('#') and not channel['ircchannel'].startswith('&'):
  142. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: does not start with # or &')
  143. if any(x in channel['ircchannel'][1:] for x in (' ', '\x00', '\x07', '\r', '\n', ',')):
  144. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: contains forbidden characters')
  145. if len(channel['ircchannel']) > 200:
  146. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: too long')
  147. if channel['ircchannel'] in seenChannels:
  148. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: collides with channel {seenWebPaths[channel["ircchannel"]]!r}')
  149. seenChannels[channel['ircchannel']] = key
  150. if 'auth' in channel:
  151. if channel['auth'] is not False and not isinstance(channel['auth'], str):
  152. raise InvalidConfig(f'Invalid channel {key!r} auth: must be false or a string')
  153. if isinstance(channel['auth'], str) and ':' not in channel['auth']:
  154. raise InvalidConfig(f'Invalid channel {key!r} auth: must contain a colon')
  155. else:
  156. channel['auth'] = False
  157. if 'active' in channel:
  158. if channel['active'] is not True and channel['active'] is not False:
  159. raise InvalidConfig(f'Invalid channel {key!r} active: must be true or false')
  160. else:
  161. channel['active'] = True
  162. # Default values
  163. finalObj = {'logging': {'level': 'INFO', 'format': '{asctime} {levelname} {name} {message}'}, 'storage': {'path': os.path.abspath(os.path.dirname(self._filename))}, 'irc': {'host': 'irc.hackint.org', 'port': 6697, 'ssl': 'yes', 'nick': 'irclogbot', 'real': 'I am an irclog bot.', 'certfile': None, 'certkeyfile': None}, 'web': {'host': '127.0.0.1', 'port': 8080}, 'channels': {}}
  164. # Default values for channels are already set above.
  165. # Merge in what was read from the config file and set keys on self
  166. for key in ('logging', 'storage', 'irc', 'web', 'channels'):
  167. if key in obj:
  168. finalObj[key].update(obj[key])
  169. self[key] = finalObj[key]
  170. def __repr__(self):
  171. return f'<Config(logging={self["logging"]!r}, storage={self["storage"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, channels={self["channels"]!r})>'
  172. def reread(self):
  173. return Config(self._filename)
  174. class IRCClientProtocol(asyncio.Protocol):
  175. logger = logging.getLogger('irclog.IRCClientProtocol')
  176. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  177. self.messageQueue = messageQueue
  178. self.connectionClosedEvent = connectionClosedEvent
  179. self.loop = loop
  180. self.config = config
  181. self.buffer = b''
  182. self.connected = False
  183. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  184. self.userChannels = collections.defaultdict(set) # List of which channels a user is known to be in; nickname:str -> {channel:str, ...}
  185. self.sasl = bool(self.config['irc']['certfile'] and self.config['irc']['certkeyfile'])
  186. self.authenticated = False
  187. self.server = ircstates.Server(self.config['irc']['host'])
  188. self.capReqsPending = set() # Capabilities requested from the server but not yet ACKd or NAKd
  189. self.caps = set() # Capabilities acknowledged by the server
  190. self.whoxQueue = collections.deque() # Names of channels that were joined successfully but for which no WHO (WHOX) query was sent yet
  191. self.whoxChannel = None # Name of channel for which a WHO query is currently running
  192. self.whoxReply = [] # List of (nickname, account) tuples from the currently running WHO query
  193. @staticmethod
  194. def nick_command(nick: str):
  195. return b'NICK ' + nick.encode('utf-8')
  196. @staticmethod
  197. def user_command(nick: str, real: str):
  198. nickb = nick.encode('utf-8')
  199. return b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + real.encode('utf-8')
  200. @staticmethod
  201. def valid_channel(channel: str):
  202. return channel[0] in ('#', '&') and not any(x in channel for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  203. @staticmethod
  204. def valid_nick(nick: str):
  205. # According to RFC 1459, a nick must be '<letter> { <letter> | <number> | <special> }'. This is obviously not true in practice because <special> doesn't include underscores, for example.
  206. # So instead, just do a sanity check similar to the channel one to disallow obvious bullshit.
  207. return not any(x in nick for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  208. @staticmethod
  209. def prefix_to_nick(prefix: str):
  210. nick = prefix[1:]
  211. if '!' in nick:
  212. nick = nick.split('!', 1)[0]
  213. if '@' in nick: # nick@host is also legal
  214. nick = nick.split('@', 1)[0]
  215. return nick
  216. def connection_made(self, transport):
  217. self.logger.info('IRC connected')
  218. self.transport = transport
  219. self.connected = True
  220. caps = [b'userhost-in-names', b'away-notify', b'account-notify', b'extended-join']
  221. if self.sasl:
  222. caps.append(b'sasl')
  223. for cap in caps:
  224. self.capReqsPending.add(cap.decode('ascii'))
  225. self.send(b'CAP REQ :' + cap)
  226. self.send(self.nick_command(self.config['irc']['nick']))
  227. self.send(self.user_command(self.config['irc']['nick'], self.config['irc']['real']))
  228. def _send_join_part(self, command, channels):
  229. '''Split a JOIN or PART into multiple messages as necessary'''
  230. # command: b'JOIN' or b'PART'; channels: set[str]
  231. channels = [x.encode('utf-8') for x in channels]
  232. 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)
  233. # Everything fits into one command.
  234. self.send(command + b' ' + b','.join(channels))
  235. return
  236. # List too long, need to split.
  237. limit = 510 - len(command)
  238. lengths = [1 + len(x) for x in channels] # separator + channel name
  239. chanLengthAcceptable = [l <= limit for l in lengths]
  240. if not all(chanLengthAcceptable):
  241. # There are channel names that are too long to even fit into one message on their own; filter them out and warn about them.
  242. # This should never happen since the config reader would already filter it out.
  243. tooLongChannels = [x for x, a in zip(channels, chanLengthAcceptable) if not a]
  244. channels = [x for x, a in zip(channels, chanLengthAcceptable) if a]
  245. lengths = [l for l, a in zip(lengths, chanLengthAcceptable) if a]
  246. for channel in tooLongChannels:
  247. self.logger.warning(f'Cannot {command} {channel}: name too long')
  248. runningLengths = list(itertools.accumulate(lengths)) # entry N = length of all entries up to and including channel N, including separators
  249. offset = 0
  250. while channels:
  251. i = next((x[0] for x in enumerate(runningLengths) if x[1] - offset > limit), -1)
  252. if i == -1: # Last batch
  253. i = len(channels)
  254. self.send(command + b' ' + b','.join(channels[:i]))
  255. offset = runningLengths[i-1]
  256. channels = channels[i:]
  257. runningLengths = runningLengths[i:]
  258. def update_channels(self, channels: set):
  259. channelsToPart = self.channels - channels
  260. channelsToJoin = channels - self.channels
  261. self.channels = channels
  262. #TODO Rejoin channels the bot got kicked from?
  263. if self.connected:
  264. if channelsToPart:
  265. self._send_join_part(b'PART', channelsToPart)
  266. if channelsToJoin:
  267. self._send_join_part(b'JOIN', channelsToJoin)
  268. def send(self, data):
  269. self.logger.debug(f'Send: {data!r}')
  270. if len(data) > 510:
  271. raise RuntimeError(f'IRC message too long ({len(data)} > 510): {data!r}')
  272. time_ = time.time()
  273. self.transport.write(data + b'\r\n')
  274. self.messageQueue.put_nowait((time_, b'> ' + data, None, None))
  275. def data_received(self, data):
  276. time_ = time.time()
  277. self.logger.debug(f'Data received: {data!r}')
  278. # Split received data on CRLF. If there's any data left in the buffer, prepend it to the first message and process that.
  279. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  280. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  281. messages = data.split(b'\r\n')
  282. if self.buffer:
  283. messages[0] = self.buffer + messages[0]
  284. for message in messages[:-1]:
  285. lines = self.server.recv(message + b'\r\n')
  286. assert len(lines) == 1
  287. self.message_received(time_, message, lines[0])
  288. self.server.parse_tokens(lines[0])
  289. self.buffer = messages[-1]
  290. def message_received(self, time_, message, line):
  291. self.logger.debug(f'Message received at {time_}: {message!r}')
  292. # Queue message for storage
  293. # Note: WHOX is queued further down
  294. self.messageQueue.put_nowait((time_, b'< ' + message, None, None))
  295. for command, channel, logMessage in self.render_message(line):
  296. self.messageQueue.put_nowait((time_, logMessage, command, channel))
  297. maybeTriggerWhox = False
  298. # PING/PONG
  299. if line.command == 'PING':
  300. self.send(irctokens.build('PONG', line.params).format().encode('utf-8'))
  301. # IRCv3 and SASL
  302. elif line.command == 'CAP':
  303. if line.params[1] == 'ACK':
  304. for cap in line.params[2].split(' '):
  305. self.logger.debug('CAP ACK: {cap}')
  306. self.caps.add(cap)
  307. if cap == 'sasl' and self.sasl:
  308. self.send(b'AUTHENTICATE EXTERNAL')
  309. else:
  310. self.capReqsPending.remove(cap)
  311. elif line.params[1] == 'NAK':
  312. self.logger.warning(f'Failed to activate CAP(s): {line.params[2]}')
  313. for cap in line.params[2].split(' '):
  314. self.capReqsPending.remove(cap)
  315. if len(self.capReqsPending) == 0:
  316. self.send(b'CAP END')
  317. elif line.command == 'AUTHENTICATE' and line.params == ['+']:
  318. self.send(b'AUTHENTICATE +')
  319. elif line.command == ircstates.numerics.RPL_SASLSUCCESS:
  320. self.authenticated = True
  321. self.capReqsPending.remove('sasl')
  322. if len(self.capReqsPending) == 0:
  323. self.send(b'CAP END')
  324. elif line.command in ('902', ircstates.numerics.ERR_SASLFAIL, ircstates.numerics.ERR_SASLTOOLONG, ircstates.numerics.ERR_SASLABORTED, ircstates.numerics.RPL_SASLMECHS):
  325. self.logger.error('SASL error, terminating connection')
  326. self.transport.close()
  327. # NICK errors
  328. elif line.command in ('431', ircstates.numerics.ERR_ERRONEUSNICKNAME, ircstates.numerics.ERR_NICKNAMEINUSE, '436'):
  329. self.logger.error(f'Failed to set nickname: {message!r}, terminating connection')
  330. self.transport.close()
  331. # USER errors
  332. elif line.command in ('461', '462'):
  333. self.logger.error(f'Failed to register: {message!r}, terminating connection')
  334. self.transport.close()
  335. # JOIN errors
  336. elif line.command in (ircstates.numerics.ERR_TOOMANYCHANNELS, ircstates.numerics.ERR_CHANNELISFULL, ircstates.numerics.ERR_INVITEONLYCHAN, ircstates.numerics.ERR_BANNEDFROMCHAN, ircstates.numerics.ERR_BADCHANNELKEY):
  337. self.logger.error(f'Failed to join channel: {message!r}, terminating connection')
  338. self.transport.close()
  339. # PART errors
  340. elif line.command == '442':
  341. self.logger.error(f'Failed to part channel: {message!r}')
  342. # JOIN/PART errors
  343. elif line.command == ircstates.numerics.ERR_NOSUCHCHANNEL:
  344. self.logger.error(f'Failed to join or part channel: {message!r}')
  345. # Connection registration reply
  346. elif line.command == ircstates.numerics.RPL_WELCOME:
  347. self.logger.info('IRC connection registered')
  348. if self.sasl and not self.authenticated:
  349. self.logger.error('IRC connection registered but not authenticated, terminating connection')
  350. self.transport.close()
  351. return
  352. self._send_join_part(b'JOIN', self.channels)
  353. # Bot getting KICKed
  354. elif line.command == 'KICK' and line.source and self.server.casefold(line.params[1]) == self.server.casefold(self.server.nickname):
  355. self.logger.warning(f'Got kicked from {line.params[0]}')
  356. kickedChannel = self.server.casefold(line.params[0])
  357. for channel in self.channels:
  358. if self.server.casefold(channel) == kickedChannel:
  359. self.channels.remove(channel)
  360. break
  361. # WHOX on successful JOIN if supported to fetch account information
  362. 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):
  363. self.whoxQueue.extend(line.params[0].split(','))
  364. maybeTriggerWhox = True
  365. # WHOX response
  366. elif line.command == ircstates.numerics.RPL_WHOSPCRPL and line.params[1] == '042':
  367. self.whoxReply.append((line.params[2], line.params[3] if line.params[3] != '0' else None))
  368. # End of WHOX response
  369. elif line.command == ircstates.numerics.RPL_ENDOFWHO:
  370. self.messageQueue.put_nowait((time_, self.render_whox(), 'WHOX', self.whoxChannel))
  371. self.whoxChannel = None
  372. self.whoxReply = []
  373. maybeTriggerWhox = True
  374. # General fatal ERROR
  375. elif line.command == 'ERROR':
  376. self.logger.error(f'Server sent ERROR: {message!r}')
  377. self.transport.close()
  378. # Send next WHOX if appropriate
  379. if maybeTriggerWhox and self.whoxChannel is None and self.whoxQueue:
  380. self.whoxChannel = self.whoxQueue.popleft()
  381. self.whoxReply = []
  382. self.send(b'WHO ' + self.whoxChannel.encode('utf-8') + b' c%nat,042')
  383. def get_mode_char(self, channelUser):
  384. if channelUser is None:
  385. return ''
  386. prefix = self.server.isupport.prefix
  387. if any(x in prefix.modes for x in channelUser.modes):
  388. return prefix.prefixes[min(prefix.modes.index(x) for x in channelUser.modes if x in prefix.modes)]
  389. return ''
  390. def render_nick_with_mode(self, channelUser, nickname):
  391. return f'{self.get_mode_char(channelUser)}{nickname}'
  392. def render_message(self, line):
  393. if line.source:
  394. sourceUser = self.server.users.get(self.server.casefold(line.hostmask.nickname)) if line.source else None
  395. get_mode_nick = lambda channel, nick = line.hostmask.nickname: self.render_nick_with_mode(self.server.channels[self.server.casefold(channel)].users.get(self.server.casefold(nick)), nick)
  396. if line.command == 'JOIN':
  397. # Although servers SHOULD NOT send multiple channels in one message per the modern IRC docs <https://modern.ircdocs.horse/#join-message>, let's do the safe thing...
  398. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  399. account = f' ({line.params[-2]})' if 'extended-join' in self.caps and line.params[-2] != '*' else ''
  400. for channel in channels:
  401. # There can't be a mode set yet on the JOIN, so no need to use get_mode_nick (which would complicate the self-join).
  402. yield 'JOIN', channel, f'{line.hostmask.nickname}{account} joins {channel}'
  403. elif line.command in ('PRIVMSG', 'NOTICE'):
  404. channel = line.params[0]
  405. if channel not in self.server.channels:
  406. return
  407. yield line.command, channel, f'<{get_mode_nick(channel)}> {line.params[1]}'
  408. elif line.command == 'PART':
  409. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  410. reason = f' [{line.params[1]}]' if len(line.params) == 2 else ''
  411. for channel in channels:
  412. yield 'PART', channel, f'{get_mode_nick(channel)} leaves {channel}'
  413. elif line.command in ('QUIT', 'NICK', 'ACCOUNT'):
  414. if line.hostmask.nickname == self.server.nickname:
  415. channels = self.channels
  416. elif sourceUser is not None:
  417. channels = sourceUser.channels
  418. else:
  419. return
  420. for channel in channels:
  421. if line.command == 'QUIT':
  422. message = f'{get_mode_nick(channel)} quits [{line.params[0]}]'
  423. elif line.command == 'NICK':
  424. newMode = self.get_mode_char(self.server.channels[self.server.casefold(channel)].users[self.server.casefold(line.hostmask.nickname)])
  425. message = f'{get_mode_nick(channel)} is now known as {newMode}{line.params[0]}'
  426. elif line.command == 'ACCOUNT':
  427. message = f'{get_mode_nick(channel)} is now authenticated as {line.params[0]}'
  428. yield line.command, channel, message
  429. elif line.command == 'MODE' and line.params[0][0] in ('#', '&'):
  430. yield 'MODE', line.params[0], f'{get_mode_nick(line.params[0])} sets mode: {" ".join(line.params[1:])}'
  431. elif line.command == 'KICK':
  432. channel = line.params[0]
  433. reason = f' [{line.params[2]}]' if len(line.params) == 3 else ''
  434. yield 'KICK', channel, f'{get_mode_nick(channel, line.params[1])} is kicked from {channel} by {get_mode_nick(channel)}{reason}'
  435. elif line.command == 'TOPIC':
  436. channel = line.params[0]
  437. if line.params[1] == '':
  438. yield 'TOPIC', channel, f'{get_mode_nick(channel)} unsets the topic of {channel}'
  439. else:
  440. yield 'TOPIC', channel, f'{get_mode_nick(channel)} sets the topic of {channel} to: {line.params[1]}'
  441. elif line.command == ircstates.numerics.RPL_TOPIC:
  442. channel = line.params[1]
  443. yield 'TOPIC', channel, f'Topic of {channel}: {line.params[2]}'
  444. elif line.command == ircstates.numerics.RPL_TOPICWHOTIME:
  445. yield 'TOPICWHO', line.params[1], f'Topic set by {irctokens.hostmask(line.params[2]).nickname} at {datetime.datetime.utcfromtimestamp(int(line.params[3])).replace(tzinfo = datetime.timezone.utc):%Y-%m-%d %H:%M:%SZ}'
  446. elif line.command == ircstates.numerics.RPL_ENDOFNAMES:
  447. channel = line.params[1]
  448. users = self.server.channels[self.server.casefold(channel)].users
  449. yield 'NAMES', channel, f'Currently in {channel}: {", ".join(self.render_nick_with_mode(u, u.nickname) for u in users.values())}'
  450. def render_whox(self):
  451. users = []
  452. for nickname, account in self.whoxReply:
  453. accountStr = f' ({account})' if account is not None else ''
  454. users.append(f'{self.render_nick_with_mode(self.server.channels[self.server.casefold(self.whoxChannel)].users.get(self.server.casefold(nickname)), nickname)}{accountStr}')
  455. return f'Currently in {self.whoxChannel}: {", ".join(users)}'
  456. async def quit(self):
  457. # 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.
  458. self.logger.info('Quitting')
  459. self.send(b'QUIT :Bye')
  460. await self.connectionClosedEvent.wait()
  461. self.transport.close()
  462. def connection_lost(self, exc):
  463. time_ = time.time()
  464. self.logger.info('IRC connection lost')
  465. self.connected = False
  466. self.connectionClosedEvent.set()
  467. self.messageQueue.put_nowait((time_, b'- Connection closed.', None, None))
  468. for channel in self.channels:
  469. self.messageQueue.put_nowait((time_, 'Connection closed.', '_CONNCLOSED', channel))
  470. class IRCClient:
  471. logger = logging.getLogger('irclog.IRCClient')
  472. def __init__(self, messageQueue, config):
  473. self.messageQueue = messageQueue
  474. self.config = config
  475. self.channels = {channel['ircchannel'] for channel in config['channels'].values()}
  476. self._transport = None
  477. self._protocol = None
  478. def update_config(self, config):
  479. needReconnect = self.config['irc'] != config['irc']
  480. self.config = config
  481. if self._transport: # if currently connected:
  482. if needReconnect:
  483. self._transport.close()
  484. else:
  485. self.channels = {channel['ircchannel'] for channel in config['channels'].values()}
  486. self._protocol.update_channels(self.channels)
  487. def _get_ssl_context(self):
  488. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  489. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  490. if ctx is True:
  491. ctx = ssl.create_default_context()
  492. if isinstance(ctx, ssl.SSLContext):
  493. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  494. return ctx
  495. async def run(self, loop, sigintEvent):
  496. connectionClosedEvent = asyncio.Event()
  497. while True:
  498. connectionClosedEvent.clear()
  499. try:
  500. 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())
  501. try:
  502. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = asyncio.FIRST_COMPLETED)
  503. finally:
  504. if not connectionClosedEvent.is_set():
  505. await self._protocol.quit()
  506. except (ConnectionRefusedError, ssl.SSLError, asyncio.TimeoutError) as e:
  507. self.logger.error(str(e))
  508. await asyncio.wait((asyncio.sleep(5), sigintEvent.wait()), return_when = asyncio.FIRST_COMPLETED)
  509. if sigintEvent.is_set():
  510. self.logger.debug('Got SIGINT, putting EOF and breaking')
  511. self.messageQueue.put_nowait(messageEOF)
  512. break
  513. class Storage:
  514. logger = logging.getLogger('irclog.Storage')
  515. def __init__(self, messageQueue, config):
  516. self.messageQueue = messageQueue
  517. self.config = config
  518. self.files = {} # channel|None -> (filename, fileobj); None = general raw log
  519. def update_config(self, config):
  520. channelsOld = {channel['ircchannel'] for channel in self.config['channels'].values()}
  521. channelsNew = {channel['ircchannel'] for channel in config['channels'].values()}
  522. channelsRemoved = channelsOld - channelsNew
  523. self.config = config
  524. for channel in channelsRemoved:
  525. if channel in self.files:
  526. self.files[channel][1].close()
  527. del self.files[channel]
  528. def ensure_file_open(self, time_, channel):
  529. fn = f'{get_month_str(time_)}.log'
  530. if channel in self.files and fn == self.files[channel][0]:
  531. return
  532. if channel in self.files:
  533. self.files[channel][1].close()
  534. dn = channel if channel is not None else 'general'
  535. mode = 'a' if channel is not None else 'ab'
  536. os.makedirs(os.path.join(self.config['storage']['path'], dn), exist_ok = True)
  537. self.files[channel] = (fn, open(os.path.join(self.config['storage']['path'], dn, fn), mode))
  538. async def run(self, loop, sigintEvent):
  539. self.update_config(self.config) # Ensure that files are open etc.
  540. flushExitEvent = asyncio.Event()
  541. storageTask = asyncio.create_task(self.store_messages(sigintEvent))
  542. flushTask = asyncio.create_task(self.flush_files(flushExitEvent))
  543. await sigintEvent.wait()
  544. self.logger.debug('Got SIGINT, waiting for remaining messages to be stored')
  545. await storageTask # Wait until everything's stored
  546. flushExitEvent.set()
  547. self.logger.debug('Waiting for flush task')
  548. await flushTask
  549. self.close()
  550. async def store_messages(self, sigintEvent):
  551. while True:
  552. self.logger.debug('Waiting for message')
  553. res = await self.messageQueue.get()
  554. self.logger.debug(f'Got {res!r} from message queue')
  555. if res is messageEOF:
  556. self.logger.debug('Message EOF, breaking store_messages loop')
  557. break
  558. self.store_message(*res)
  559. def store_message(self, time_, message, command, channel):
  560. # Sanity check
  561. if channel is None and (not isinstance(message, bytes) or message[0:1] not in (b'<', b'>', b'-') or message[1:2] != b' ' or command is not None):
  562. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  563. return
  564. elif channel is not None and (not isinstance(message, str) or command is None):
  565. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  566. return
  567. self.logger.debug(f'Logging {message!r} ({command}) at {time_} for {channel!r}')
  568. self.ensure_file_open(time_, channel)
  569. if channel is None:
  570. self.files[None][1].write(str(time_).encode('ascii') + b' ' + message + b'\n')
  571. else:
  572. self.files[channel][1].write(f'{time_} {command} {message}\n')
  573. async def flush_files(self, flushExitEvent):
  574. while True:
  575. await asyncio.wait((flushExitEvent.wait(), asyncio.sleep(60)), return_when = asyncio.FIRST_COMPLETED)
  576. self.logger.debug('Flushing files')
  577. for _, f in self.files.values():
  578. f.flush()
  579. self.logger.debug('Flushing done')
  580. if flushExitEvent.is_set():
  581. break
  582. self.logger.debug('Exiting flush_files')
  583. def close(self):
  584. for _, f in self.files.values():
  585. f.close()
  586. self.files = {}
  587. class WebServer:
  588. logger = logging.getLogger('irclog.WebServer')
  589. def __init__(self, config):
  590. self.config = config
  591. self._paths = {} # '/path' => ('#channel', auth, module, moduleargs) where auth is either False (no authentication) or the HTTP header value for basic auth
  592. self._app = aiohttp.web.Application()
  593. self._app.add_routes([aiohttp.web.post('/{path:.+}', self.post)])
  594. self.update_config(config)
  595. self._configChanged = asyncio.Event()
  596. def update_config(self, config):
  597. # self._paths = {channel['webpath']: (channel['ircchannel'], f'Basic {base64.b64encode(channel["auth"].encode("utf-8")).decode("utf-8")}' if channel['auth'] else False) for channel in config['channels'].values()}
  598. needRebind = self.config['web'] != config['web'] #TODO only if there are changes to web.host or web.port; everything else can be updated without rebinding
  599. self.config = config
  600. if needRebind:
  601. self._configChanged.set()
  602. async def run(self, stopEvent):
  603. while True:
  604. runner = aiohttp.web.AppRunner(self._app)
  605. await runner.setup()
  606. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  607. await site.start()
  608. await asyncio.wait((stopEvent.wait(), self._configChanged.wait()), return_when = asyncio.FIRST_COMPLETED)
  609. await runner.cleanup()
  610. if stopEvent.is_set():
  611. break
  612. self._configChanged.clear()
  613. # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process
  614. # https://stackoverflow.com/questions/1180606/using-subprocess-popen-for-process-with-large-output
  615. # -> https://stackoverflow.com/questions/57730010/python-asyncio-subprocess-write-stdin-and-read-stdout-stderr-continuously
  616. async def post(self, request):
  617. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r} with body {(await request.read())!r}')
  618. try:
  619. channel, auth, module, moduleargs, overlongmode = self._paths[request.path]
  620. except KeyError:
  621. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  622. raise aiohttp.web.HTTPNotFound()
  623. if auth:
  624. authHeader = request.headers.get('Authorization')
  625. if not authHeader or authHeader != auth:
  626. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  627. raise aiohttp.web.HTTPForbidden()
  628. if module is not None:
  629. self.logger.debug(f'Processing request {id(request)} using {module!r}')
  630. try:
  631. message = await module.process(request, *moduleargs)
  632. except aiohttp.web.HTTPException as e:
  633. raise e
  634. except Exception as e:
  635. self.logger.error(f'Bad request {id(request)}: exception in module process function: {type(e).__module__}.{type(e).__name__}: {e!s}')
  636. raise aiohttp.web.HTTPBadRequest()
  637. if '\r' in message or '\n' in message:
  638. self.logger.error(f'Bad request {id(request)}: module process function returned message with linebreaks: {message!r}')
  639. raise aiohttp.web.HTTPBadRequest()
  640. else:
  641. self.logger.debug(f'Processing request {id(request)} using default processor')
  642. message = await self._default_process(request)
  643. self.logger.info(f'Accepted request {id(request)}, putting message {message!r} for {channel} into message queue')
  644. self.messageQueue.put_nowait((channel, message, overlongmode))
  645. raise aiohttp.web.HTTPOk()
  646. async def _default_process(self, request):
  647. try:
  648. message = await request.text()
  649. except Exception as e:
  650. self.logger.info(f'Bad request {id(request)}: exception while reading request data: {e!s}')
  651. raise aiohttp.web.HTTPBadRequest() # Yes, it's always the client's fault. :-)
  652. self.logger.debug(f'Request {id(request)} payload: {message!r}')
  653. # Strip optional [CR] LF at the end of the payload
  654. if message.endswith('\r\n'):
  655. message = message[:-2]
  656. elif message.endswith('\n'):
  657. message = message[:-1]
  658. if '\r' in message or '\n' in message:
  659. self.logger.info(f'Bad request {id(request)}: linebreaks in message')
  660. raise aiohttp.web.HTTPBadRequest()
  661. return message
  662. def configure_logging(config):
  663. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  664. root = logging.getLogger()
  665. root.setLevel(getattr(logging, config['logging']['level']))
  666. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  667. formatter = logging.Formatter(config['logging']['format'], style = '{')
  668. stderrHandler = logging.StreamHandler()
  669. stderrHandler.setFormatter(formatter)
  670. root.addHandler(stderrHandler)
  671. async def main():
  672. if len(sys.argv) != 2:
  673. print('Usage: irclog.py CONFIGFILE', file = sys.stderr)
  674. sys.exit(1)
  675. configFile = sys.argv[1]
  676. config = Config(configFile)
  677. configure_logging(config)
  678. loop = asyncio.get_running_loop()
  679. messageQueue = asyncio.Queue()
  680. # tuple(time: float, message: bytes or str, command: str or None, channel: str or None)
  681. # command is an identifier of the type of message.
  682. # For raw message logs, message is bytes and command and channel are None. For channel-specific formatted messages, message, command, and channel are all strs.
  683. # The queue can also contain messageEOF, which signals to the storage layer to stop logging.
  684. irc = IRCClient(messageQueue, config)
  685. webserver = WebServer(config)
  686. storage = Storage(messageQueue, config)
  687. sigintEvent = asyncio.Event()
  688. def sigint_callback():
  689. global logger
  690. nonlocal sigintEvent
  691. logger.info('Got SIGINT, stopping')
  692. sigintEvent.set()
  693. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  694. def sigusr1_callback():
  695. global logger
  696. nonlocal config, irc, webserver, storage
  697. logger.info('Got SIGUSR1, reloading config')
  698. try:
  699. newConfig = config.reread()
  700. except InvalidConfig as e:
  701. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  702. return
  703. config = newConfig
  704. configure_logging(config)
  705. irc.update_config(config)
  706. webserver.update_config(config)
  707. storage.update_config(config)
  708. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  709. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent), storage.run(loop, sigintEvent))
  710. if __name__ == '__main__':
  711. asyncio.run(main())