Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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