25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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