25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 

830 satır
37 KiB

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