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

1249 lines
57 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 math
  17. import os.path
  18. import signal
  19. import ssl
  20. import string
  21. import sys
  22. import tempfile
  23. import time
  24. import toml
  25. logger = logging.getLogger('irclog')
  26. SSL_CONTEXTS = {'yes': True, 'no': False, 'insecure': ssl.SSLContext()}
  27. messageConnectionClosed = object() # Signals that the connection was closed by either the bot or the server
  28. messageEOF = object() # Special object to signal the end of messages to Storage
  29. LOG_COMMANDS = [
  30. # IRC protocol(-ish)
  31. 'JOIN', 'QUIT', 'PART', 'KICK', 'NICK', 'ACCOUNT', 'MODE', 'TOPIC', 'TOPICWHO', 'NAMES', 'WHOX', 'NOTICE', 'PRIVMSG',
  32. # Connection lost
  33. 'CONNCLOSED',
  34. ]
  35. def get_month_str(ts = None):
  36. dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo = datetime.timezone.utc) if ts is not None else datetime.datetime.utcnow()
  37. return dt.strftime('%Y-%m')
  38. class InvalidConfig(Exception):
  39. '''Error in configuration file'''
  40. def is_valid_pem(path, withCert):
  41. '''Very basic check whether something looks like a valid PEM certificate'''
  42. try:
  43. with open(path, 'rb') as fp:
  44. contents = fp.read()
  45. # All of these raise exceptions if something's wrong...
  46. if withCert:
  47. assert contents.startswith(b'-----BEGIN CERTIFICATE-----\n')
  48. endCertPos = contents.index(b'-----END CERTIFICATE-----\n')
  49. base64.b64decode(contents[28:endCertPos].replace(b'\n', b''), validate = True)
  50. assert contents[endCertPos + 26:].startswith(b'-----BEGIN PRIVATE KEY-----\n')
  51. else:
  52. assert contents.startswith(b'-----BEGIN PRIVATE KEY-----\n')
  53. endCertPos = -26 # Please shoot me.
  54. endKeyPos = contents.index(b'-----END PRIVATE KEY-----\n')
  55. base64.b64decode(contents[endCertPos + 26 + 28: endKeyPos].replace(b'\n', b''), validate = True)
  56. assert contents[endKeyPos + 26:] == b''
  57. return True
  58. except: # Yes, really
  59. return False
  60. class Config(dict):
  61. def __init__(self, filename):
  62. super().__init__()
  63. self._filename = filename
  64. with open(self._filename, 'r') as fp:
  65. obj = toml.load(fp)
  66. # Sanity checks
  67. if any(x not in ('logging', 'storage', 'irc', 'web', 'channels') for x in obj.keys()):
  68. raise InvalidConfig('Unknown sections found in base object')
  69. if any(not isinstance(x, collections.abc.Mapping) for x in obj.values()):
  70. raise InvalidConfig('Invalid section type(s), expected objects/dicts')
  71. if 'logging' in obj:
  72. if any(x not in ('level', 'format') for x in obj['logging']):
  73. raise InvalidConfig('Unknown key found in log section')
  74. if 'level' in obj['logging'] and obj['logging']['level'] not in ('DEBUG', 'INFO', 'WARNING', 'ERROR'):
  75. raise InvalidConfig('Invalid log level')
  76. if 'format' in obj['logging']:
  77. if not isinstance(obj['logging']['format'], str):
  78. raise InvalidConfig('Invalid log format')
  79. try:
  80. #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)
  81. # 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).
  82. assert sum(1 for x in string.Formatter().parse(obj['logging']['format']) if x[1] is not None) > 0
  83. except (ValueError, AssertionError) as e:
  84. raise InvalidConfig('Invalid log format: parsing failed') from e
  85. if 'storage' in obj:
  86. if any(x not in ('path', 'flushTime') for x in obj['storage']):
  87. raise InvalidConfig('Unknown key found in storage section')
  88. if 'path' in obj['storage']:
  89. obj['storage']['path'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['storage']['path']))
  90. try:
  91. #TODO This doesn't seem to work correctly; doesn't fail when the dir is -w
  92. f = tempfile.TemporaryFile(dir = obj['storage']['path'])
  93. f.close()
  94. except (OSError, IOError) as e:
  95. raise InvalidConfig('Invalid storage path: not writable') from e
  96. if 'flushTime' in obj['storage']:
  97. if not isinstance(obj['storage']['flushTime'], (int, float)) or obj['storage']['flushTime'] <= 0:
  98. raise InvalidConfig('Invalid storage flushTime: must be a positive int or float')
  99. if 'irc' in obj:
  100. if any(x not in ('host', 'port', 'ssl', 'nick', 'real', 'certfile', 'certkeyfile') for x in obj['irc']):
  101. raise InvalidConfig('Unknown key found in irc section')
  102. if 'host' in obj['irc'] and not isinstance(obj['irc']['host'], str): #TODO: Check whether it's a valid hostname
  103. raise InvalidConfig('Invalid IRC host')
  104. if 'port' in obj['irc'] and (not isinstance(obj['irc']['port'], int) or not 1 <= obj['irc']['port'] <= 65535):
  105. raise InvalidConfig('Invalid IRC port')
  106. if 'ssl' in obj['irc'] and obj['irc']['ssl'] not in ('yes', 'no', 'insecure'):
  107. raise InvalidConfig(f'Invalid IRC SSL setting: {obj["irc"]["ssl"]!r}')
  108. if 'nick' in obj['irc'] and not isinstance(obj['irc']['nick'], str): #TODO: Check whether it's a valid nickname, username, etc.
  109. raise InvalidConfig('Invalid IRC nick')
  110. if len(IRCClientProtocol.nick_command(obj['irc']['nick'])) > 510:
  111. raise InvalidConfig('Invalid IRC nick: NICK command too long')
  112. if 'real' in obj['irc'] and not isinstance(obj['irc']['real'], str):
  113. raise InvalidConfig('Invalid IRC realname')
  114. if len(IRCClientProtocol.user_command(obj['irc']['nick'], obj['irc']['real'])) > 510:
  115. raise InvalidConfig('Invalid IRC nick/realname combination: USER command too long')
  116. if ('certfile' in obj['irc']) != ('certkeyfile' in obj['irc']):
  117. raise InvalidConfig('Invalid IRC cert config: needs both certfile and certkeyfile')
  118. if 'certfile' in obj['irc']:
  119. if not isinstance(obj['irc']['certfile'], str):
  120. raise InvalidConfig('Invalid certificate file: not a string')
  121. obj['irc']['certfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certfile']))
  122. if not os.path.isfile(obj['irc']['certfile']):
  123. raise InvalidConfig('Invalid certificate file: not a regular file')
  124. if not is_valid_pem(obj['irc']['certfile'], True):
  125. raise InvalidConfig('Invalid certificate file: not a valid PEM cert')
  126. if 'certkeyfile' in obj['irc']:
  127. if not isinstance(obj['irc']['certkeyfile'], str):
  128. raise InvalidConfig('Invalid certificate key file: not a string')
  129. obj['irc']['certkeyfile'] = os.path.abspath(os.path.join(os.path.dirname(self._filename), obj['irc']['certkeyfile']))
  130. if not os.path.isfile(obj['irc']['certkeyfile']):
  131. raise InvalidConfig('Invalid certificate key file: not a regular file')
  132. if not is_valid_pem(obj['irc']['certkeyfile'], False):
  133. raise InvalidConfig('Invalid certificate key file: not a valid PEM key')
  134. if 'web' in obj:
  135. if any(x not in ('host', 'port', 'search') for x in obj['web']):
  136. raise InvalidConfig('Unknown key found in web section')
  137. if 'host' in obj['web'] and not isinstance(obj['web']['host'], str): #TODO: Check whether it's a valid hostname (must resolve I guess?)
  138. raise InvalidConfig('Invalid web hostname')
  139. if 'port' in obj['web'] and (not isinstance(obj['web']['port'], int) or not 1 <= obj['web']['port'] <= 65535):
  140. raise InvalidConfig('Invalid web port')
  141. if 'search' in obj['web']:
  142. if not isinstance(obj['web']['search'], collections.abc.Mapping):
  143. raise InvalidConfig('Invalid web search: must be a mapping')
  144. if any(x not in ('maxTime', 'maxSize', 'nice', 'maxMemory') for x in obj['web']['search']):
  145. raise InvalidConfig('Unknown key found in web search section')
  146. for key in ('maxTime', 'maxSize', 'nice', 'maxMemory'):
  147. if key not in obj['web']['search']:
  148. continue
  149. if not isinstance(obj['web']['search'][key], int):
  150. raise InvalidConfig('Invalid web search {key}: not an integer')
  151. if key != 'nice' and obj['web']['search'][key] < 0:
  152. raise InvalidConfig('Invalid web search {key}: cannot be negative')
  153. if 'channels' in obj:
  154. seenChannels = {}
  155. seenPaths = {}
  156. for key, channel in obj['channels'].items():
  157. if not isinstance(key, str) or not key:
  158. raise InvalidConfig(f'Invalid channel key {key!r}')
  159. if not isinstance(channel, collections.abc.Mapping):
  160. raise InvalidConfig(f'Invalid channel for {key!r}')
  161. if any(x not in ('ircchannel', 'path', 'auth', 'active', 'hidden', 'extrasearchchannels', 'description') for x in channel):
  162. raise InvalidConfig(f'Unknown key(s) found in channel {key!r}')
  163. if 'ircchannel' not in channel:
  164. channel['ircchannel'] = f'#{key}'
  165. if not isinstance(channel['ircchannel'], str):
  166. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: not a string')
  167. if not channel['ircchannel'].startswith('#') and not channel['ircchannel'].startswith('&'):
  168. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: does not start with # or &')
  169. if any(x in channel['ircchannel'][1:] for x in (' ', '\x00', '\x07', '\r', '\n', ',')):
  170. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: contains forbidden characters')
  171. if len(channel['ircchannel']) > 200:
  172. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: too long')
  173. if channel['ircchannel'] in seenChannels:
  174. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: collides with channel {seenChannels[channel["ircchannel"]]!r}')
  175. seenChannels[channel['ircchannel']] = key
  176. if 'path' not in channel:
  177. channel['path'] = key
  178. if not isinstance(channel['path'], str):
  179. raise InvalidConfig(f'Invalid channel {key!r} path: not a string')
  180. if any(x in channel['path'] for x in itertools.chain(map(chr, range(32)), ('/', '\\', '"', '\x7F'))):
  181. raise InvalidConfig(f'Invalid channel {key!r} path: contains invalid characters')
  182. if channel['path'] in ('general', 'status'):
  183. raise InvalidConfig(f'Invalid channel {key!r} path: cannot be "general" or "status"')
  184. if channel['path'] in seenPaths:
  185. raise InvalidConfig(f'Invalid channel {key!r} path: collides with channel {seenPaths[channel["path"]]!r}')
  186. seenPaths[channel['path']] = key
  187. if 'auth' not in channel:
  188. channel['auth'] = False
  189. if channel['auth'] is not False and not isinstance(channel['auth'], str):
  190. raise InvalidConfig(f'Invalid channel {key!r} auth: must be false or a string')
  191. if isinstance(channel['auth'], str) and ':' not in channel['auth']:
  192. raise InvalidConfig(f'Invalid channel {key!r} auth: must contain a colon')
  193. if 'active' not in channel:
  194. channel['active'] = True
  195. if channel['active'] is not True and channel['active'] is not False:
  196. raise InvalidConfig(f'Invalid channel {key!r} active: must be true or false')
  197. if 'hidden' not in channel:
  198. channel['hidden'] = False
  199. if channel['hidden'] is not False and channel['hidden'] is not True:
  200. raise InvalidConfig(f'Invalid channel {key!r} hidden: must be true or false')
  201. if 'extrasearchchannels' not in channel:
  202. channel['extrasearchchannels'] = []
  203. if not isinstance(channel['extrasearchchannels'], collections.abc.Sequence):
  204. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: must be a sequence (e.g. list)')
  205. if any(not isinstance(x, str) for x in channel['extrasearchchannels']):
  206. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: must only contain strings')
  207. if any(x == key for x in channel['extrasearchchannels']):
  208. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: cannot refer to self')
  209. # Validation of the values is performed after reading everything
  210. if 'description' not in channel:
  211. channel['description'] = None
  212. if not isinstance(channel['description'], str) and channel['description'] is not None:
  213. raise InvalidConfig(f'Invalid channel {key!r} description: must be a str or None')
  214. # extrasearchchannels validation after reading all channels
  215. for key, channel in obj['channels'].items():
  216. if any(x not in obj['channels'] for x in channel['extrasearchchannels']):
  217. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: refers to undefined channel')
  218. if any(obj['channels'][x]['auth'] is not False and obj['channels'][x]['auth'] != channel['auth'] for x in channel['extrasearchchannels']):
  219. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: refers to auth-required channel whose auth differs from this channel\'s')
  220. # Default values
  221. defaults = {
  222. 'logging': {'level': 'INFO', 'format': '{asctime} {levelname} {name} {message}'},
  223. 'storage': {'path': os.path.abspath(os.path.dirname(self._filename)), 'flushTime': 60},
  224. 'irc': {'host': 'irc.hackint.org', 'port': 6697, 'ssl': 'yes', 'nick': 'irclogbot', 'real': 'I am an irclog bot.', 'certfile': None, 'certkeyfile': None},
  225. 'web': {'host': '127.0.0.1', 'port': 8080, 'search': {'maxTime': 10, 'maxSize': 1048576, 'nice': 10, 'maxMemory': 52428800}},
  226. 'channels': obj['channels'], # _merge_dicts expects the same structure, and this is the easiest way to achieve that
  227. }
  228. # Default values for channels are already set above.
  229. # Merge in what was read from the config file and set keys on self
  230. finalObj = self._merge_dicts(defaults, obj)
  231. for key in defaults.keys():
  232. self[key] = finalObj[key]
  233. def _merge_dicts(self, defaults, overrides):
  234. # Takes two dicts; the keys in overrides must be a subset of the ones in defaults. Returns a merged dict with values from overrides replacing those in defaults, recursively.
  235. assert set(overrides.keys()).issubset(defaults.keys()), f'{overrides!r} is not a subset of {defaults!r}'
  236. out = {}
  237. for key in defaults.keys():
  238. if isinstance(defaults[key], dict):
  239. out[key] = self._merge_dicts(defaults[key], overrides[key] if key in overrides else {})
  240. else:
  241. out[key] = overrides[key] if key in overrides else defaults[key]
  242. return out
  243. def __repr__(self):
  244. return f'<Config(logging={self["logging"]!r}, storage={self["storage"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, channels={self["channels"]!r})>'
  245. def reread(self):
  246. return Config(self._filename)
  247. class IRCClientProtocol(asyncio.Protocol):
  248. logger = logging.getLogger('irclog.IRCClientProtocol')
  249. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  250. self.messageQueue = messageQueue
  251. self.connectionClosedEvent = connectionClosedEvent
  252. self.loop = loop
  253. self.config = config
  254. self.lastRecvTime = None
  255. self.lastSentTime = None # float timestamp or None; the latter disables the send rate limit
  256. self.sendQueue = asyncio.Queue()
  257. self.buffer = b''
  258. self.connected = False
  259. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  260. self.userChannels = collections.defaultdict(set) # List of which channels a user is known to be in; nickname:str -> {channel:str, ...}
  261. self.sasl = bool(self.config['irc']['certfile'] and self.config['irc']['certkeyfile'])
  262. self.authenticated = False
  263. self.server = ircstates.Server(self.config['irc']['host'])
  264. self.capReqsPending = set() # Capabilities requested from the server but not yet ACKd or NAKd
  265. self.caps = set() # Capabilities acknowledged by the server
  266. self.whoxQueue = collections.deque() # Names of channels that were joined successfully but for which no WHO (WHOX) query was sent yet
  267. self.whoxChannel = None # Name of channel for which a WHO query is currently running
  268. self.whoxReply = [] # List of (nickname, account) tuples from the currently running WHO query
  269. @staticmethod
  270. def nick_command(nick: str):
  271. return b'NICK ' + nick.encode('utf-8')
  272. @staticmethod
  273. def user_command(nick: str, real: str):
  274. nickb = nick.encode('utf-8')
  275. return b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + real.encode('utf-8')
  276. @staticmethod
  277. def valid_channel(channel: str):
  278. return channel[0] in ('#', '&') and not any(x in channel for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  279. @staticmethod
  280. def valid_nick(nick: str):
  281. # 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.
  282. # So instead, just do a sanity check similar to the channel one to disallow obvious bullshit.
  283. return not any(x in nick for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  284. @staticmethod
  285. def prefix_to_nick(prefix: str):
  286. nick = prefix[1:]
  287. if '!' in nick:
  288. nick = nick.split('!', 1)[0]
  289. if '@' in nick: # nick@host is also legal
  290. nick = nick.split('@', 1)[0]
  291. return nick
  292. def connection_made(self, transport):
  293. self.logger.info('IRC connected')
  294. self.transport = transport
  295. self.connected = True
  296. caps = [b'multi-prefix', b'userhost-in-names', b'away-notify', b'account-notify', b'extended-join']
  297. if self.sasl:
  298. caps.append(b'sasl')
  299. for cap in caps:
  300. self.capReqsPending.add(cap.decode('ascii'))
  301. self.send(b'CAP REQ :' + cap)
  302. self.send(self.nick_command(self.config['irc']['nick']))
  303. self.send(self.user_command(self.config['irc']['nick'], self.config['irc']['real']))
  304. def _send_join_part(self, command, channels):
  305. '''Split a JOIN or PART into multiple messages as necessary'''
  306. # command: b'JOIN' or b'PART'; channels: set[str]
  307. channels = [x.encode('utf-8') for x in channels]
  308. 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)
  309. # Everything fits into one command.
  310. self.send(command + b' ' + b','.join(channels))
  311. return
  312. # List too long, need to split.
  313. limit = 510 - len(command)
  314. lengths = [1 + len(x) for x in channels] # separator + channel name
  315. chanLengthAcceptable = [l <= limit for l in lengths]
  316. if not all(chanLengthAcceptable):
  317. # There are channel names that are too long to even fit into one message on their own; filter them out and warn about them.
  318. # This should never happen since the config reader would already filter it out.
  319. tooLongChannels = [x for x, a in zip(channels, chanLengthAcceptable) if not a]
  320. channels = [x for x, a in zip(channels, chanLengthAcceptable) if a]
  321. lengths = [l for l, a in zip(lengths, chanLengthAcceptable) if a]
  322. for channel in tooLongChannels:
  323. self.logger.warning(f'Cannot {command} {channel}: name too long')
  324. runningLengths = list(itertools.accumulate(lengths)) # entry N = length of all entries up to and including channel N, including separators
  325. offset = 0
  326. while channels:
  327. i = next((x[0] for x in enumerate(runningLengths) if x[1] - offset > limit), -1)
  328. if i == -1: # Last batch
  329. i = len(channels)
  330. self.send(command + b' ' + b','.join(channels[:i]))
  331. offset = runningLengths[i-1]
  332. channels = channels[i:]
  333. runningLengths = runningLengths[i:]
  334. def update_channels(self, channels: set):
  335. channelsToPart = self.channels - channels
  336. channelsToJoin = channels - self.channels
  337. self.channels = channels
  338. if self.connected:
  339. if channelsToPart:
  340. self._send_join_part(b'PART', channelsToPart)
  341. if channelsToJoin:
  342. self._send_join_part(b'JOIN', channelsToJoin)
  343. def send(self, data):
  344. self.logger.debug(f'Queueing for send: {data!r}')
  345. if len(data) > 510:
  346. raise RuntimeError(f'IRC message too long ({len(data)} > 510): {data!r}')
  347. self.sendQueue.put_nowait(data)
  348. def _direct_send(self, data):
  349. self.logger.debug(f'Send: {data!r}')
  350. time_ = time.time()
  351. self.transport.write(data + b'\r\n')
  352. self.messageQueue.put_nowait((time_, b'> ' + data, None, None))
  353. return time_
  354. async def send_queue(self):
  355. while True:
  356. self.logger.debug(f'Trying to get data from send queue')
  357. t = asyncio.create_task(self.sendQueue.get())
  358. done, pending = await asyncio.wait({t, asyncio.create_task(self.connectionClosedEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  359. if self.connectionClosedEvent.is_set():
  360. break
  361. assert t in done, f'{t!r} is not in {done!r}'
  362. data = t.result()
  363. self.logger.debug(f'Got {data!r} from send queue')
  364. now = time.time()
  365. if self.lastSentTime is not None and now - self.lastSentTime < 1:
  366. self.logger.debug(f'Rate limited')
  367. await asyncio.wait({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = self.lastSentTime + 1 - now)
  368. if self.connectionClosedEvent.is_set():
  369. break
  370. time_ = self._direct_send(data)
  371. if self.lastSentTime is not None:
  372. self.lastSentTime = time_
  373. def data_received(self, data):
  374. time_ = time.time()
  375. self.logger.debug(f'Data received: {data!r}')
  376. self.lastRecvTime = time_
  377. # If there's any data left in the buffer, prepend it to the data. Split on CRLF.
  378. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  379. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  380. if self.buffer:
  381. data = self.buffer + data
  382. messages = data.split(b'\r\n')
  383. for message in messages[:-1]:
  384. lines = self.server.recv(message + b'\r\n')
  385. assert len(lines) == 1, f'recv did not return exactly one line: {message!r} -> {lines!r}'
  386. self.message_received(time_, message, lines[0])
  387. self.server.parse_tokens(lines[0])
  388. self.buffer = messages[-1]
  389. def message_received(self, time_, message, line):
  390. self.logger.debug(f'Message received at {time_}: {message!r}')
  391. # Queue message for storage
  392. # Note: WHOX is queued further down
  393. self.messageQueue.put_nowait((time_, b'< ' + message, None, None))
  394. for command, channel, logMessage in self.render_message(line):
  395. self.messageQueue.put_nowait((time_, logMessage, command, channel))
  396. maybeTriggerWhox = False
  397. # PING/PONG
  398. if line.command == 'PING':
  399. self._direct_send(irctokens.build('PONG', line.params).format().encode('utf-8'))
  400. # IRCv3 and SASL
  401. elif line.command == 'CAP':
  402. if line.params[1] == 'ACK':
  403. for cap in line.params[2].split(' '):
  404. self.logger.debug('CAP ACK: {cap}')
  405. self.caps.add(cap)
  406. if cap == 'sasl' and self.sasl:
  407. self.send(b'AUTHENTICATE EXTERNAL')
  408. else:
  409. self.capReqsPending.remove(cap)
  410. elif line.params[1] == 'NAK':
  411. self.logger.warning(f'Failed to activate CAP(s): {line.params[2]}')
  412. for cap in line.params[2].split(' '):
  413. self.capReqsPending.remove(cap)
  414. if len(self.capReqsPending) == 0:
  415. self.send(b'CAP END')
  416. elif line.command == 'AUTHENTICATE' and line.params == ['+']:
  417. self.send(b'AUTHENTICATE +')
  418. elif line.command == ircstates.numerics.RPL_SASLSUCCESS:
  419. self.authenticated = True
  420. self.capReqsPending.remove('sasl')
  421. if len(self.capReqsPending) == 0:
  422. self.send(b'CAP END')
  423. elif line.command in ('902', ircstates.numerics.ERR_SASLFAIL, ircstates.numerics.ERR_SASLTOOLONG, ircstates.numerics.ERR_SASLABORTED, ircstates.numerics.RPL_SASLMECHS):
  424. self.logger.error('SASL error, terminating connection')
  425. self.transport.close()
  426. # NICK errors
  427. elif line.command in ('431', ircstates.numerics.ERR_ERRONEUSNICKNAME, ircstates.numerics.ERR_NICKNAMEINUSE, '436'):
  428. self.logger.error(f'Failed to set nickname: {message!r}, terminating connection')
  429. self.transport.close()
  430. # USER errors
  431. elif line.command in ('461', '462'):
  432. self.logger.error(f'Failed to register: {message!r}, terminating connection')
  433. self.transport.close()
  434. # JOIN errors
  435. elif line.command in (
  436. ircstates.numerics.ERR_TOOMANYCHANNELS,
  437. ircstates.numerics.ERR_CHANNELISFULL,
  438. ircstates.numerics.ERR_INVITEONLYCHAN,
  439. ircstates.numerics.ERR_BANNEDFROMCHAN,
  440. ircstates.numerics.ERR_BADCHANNELKEY,
  441. ):
  442. self.logger.error(f'Failed to join channel: {message!r}, terminating connection')
  443. self.transport.close()
  444. # PART errors
  445. elif line.command == '442':
  446. self.logger.error(f'Failed to part channel: {message!r}')
  447. # JOIN/PART errors
  448. elif line.command == ircstates.numerics.ERR_NOSUCHCHANNEL:
  449. self.logger.error(f'Failed to join or part channel: {message!r}')
  450. # Connection registration reply
  451. elif line.command == ircstates.numerics.RPL_WELCOME:
  452. self.logger.info('IRC connection registered')
  453. if self.sasl and not self.authenticated:
  454. self.logger.error('IRC connection registered but not authenticated, terminating connection')
  455. self.transport.close()
  456. return
  457. self.lastSentTime = time.time()
  458. self._send_join_part(b'JOIN', self.channels)
  459. # Bot getting KICKed
  460. elif line.command == 'KICK' and line.source and self.server.casefold(line.params[1]) == self.server.casefold(self.server.nickname):
  461. self.logger.warning(f'Got kicked from {line.params[0]}')
  462. kickedChannel = self.server.casefold(line.params[0])
  463. for channel in self.channels:
  464. if self.server.casefold(channel) == kickedChannel:
  465. self.channels.remove(channel)
  466. break
  467. # WHOX on successful JOIN if supported to fetch account information
  468. 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):
  469. self.whoxQueue.extend(line.params[0].split(','))
  470. maybeTriggerWhox = True
  471. # WHOX response
  472. elif line.command == ircstates.numerics.RPL_WHOSPCRPL and line.params[1] == '042':
  473. self.whoxReply.append((line.params[2], line.params[3] if line.params[3] != '0' else None))
  474. # End of WHOX response
  475. elif line.command == ircstates.numerics.RPL_ENDOFWHO:
  476. self.messageQueue.put_nowait((time_, self.render_whox(), 'WHOX', self.whoxChannel))
  477. self.whoxChannel = None
  478. self.whoxReply = []
  479. maybeTriggerWhox = True
  480. # General fatal ERROR
  481. elif line.command == 'ERROR':
  482. self.logger.error(f'Server sent ERROR: {message!r}')
  483. self.transport.close()
  484. # Send next WHOX if appropriate
  485. if maybeTriggerWhox and self.whoxChannel is None and self.whoxQueue:
  486. self.whoxChannel = self.whoxQueue.popleft()
  487. self.whoxReply = []
  488. self.send(b'WHO ' + self.whoxChannel.encode('utf-8') + b' c%nat,042')
  489. def get_mode_char(self, channelUser):
  490. if channelUser is None:
  491. return ''
  492. prefix = self.server.isupport.prefix
  493. if any(x in prefix.modes for x in channelUser.modes):
  494. return prefix.prefixes[min(prefix.modes.index(x) for x in channelUser.modes if x in prefix.modes)]
  495. return ''
  496. def render_nick_with_mode(self, channelUser, nickname):
  497. return f'{self.get_mode_char(channelUser)}{nickname}'
  498. def render_message(self, line):
  499. if line.source:
  500. sourceUser = self.server.users.get(self.server.casefold(line.hostmask.nickname)) if line.source else None
  501. 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)
  502. if line.command == 'JOIN':
  503. # 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...
  504. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  505. account = f' ({line.params[-2]})' if 'extended-join' in self.caps and line.params[-2] != '*' else ''
  506. for channel in channels:
  507. # 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).
  508. yield 'JOIN', channel, f'{line.hostmask.nickname}{account} joins'
  509. elif line.command in ('PRIVMSG', 'NOTICE'):
  510. channel = line.params[0]
  511. if channel not in self.server.channels:
  512. return
  513. if line.command == 'PRIVMSG' and line.params[1].startswith('\x01ACTION ') and line.params[1].endswith('\x01'):
  514. # CTCP ACTION (aka /me)
  515. yield 'ACTION', channel, f'{get_mode_nick(channel)} {line.params[1][8:-1]}'
  516. return
  517. yield line.command, channel, f'<{get_mode_nick(channel)}> {line.params[1]}'
  518. elif line.command == 'PART':
  519. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  520. reason = f' [{line.params[1]}]' if len(line.params) == 2 else ''
  521. for channel in channels:
  522. yield 'PART', channel, f'{get_mode_nick(channel)} leaves{reason}'
  523. elif line.command in ('QUIT', 'NICK', 'ACCOUNT'):
  524. if line.hostmask.nickname == self.server.nickname:
  525. channels = self.channels
  526. elif sourceUser is not None:
  527. channels = sourceUser.channels
  528. else:
  529. return
  530. for channel in channels:
  531. if line.command == 'QUIT':
  532. reason = f' [{line.params[0]}]' if len(line.params) == 1 else ''
  533. message = f'{get_mode_nick(channel)} quits{reason}'
  534. elif line.command == 'NICK':
  535. newMode = self.get_mode_char(self.server.channels[self.server.casefold(channel)].users[self.server.casefold(line.hostmask.nickname)])
  536. message = f'{get_mode_nick(channel)} is now known as {newMode}{line.params[0]}'
  537. elif line.command == 'ACCOUNT':
  538. message = f'{get_mode_nick(channel)} is now authenticated as {line.params[0]}'
  539. yield line.command, channel, message
  540. elif line.command == 'MODE' and line.params[0][0] in ('#', '&'):
  541. yield 'MODE', line.params[0], f'{get_mode_nick(line.params[0])} sets mode: {" ".join(line.params[1:])}'
  542. elif line.command == 'KICK':
  543. channel = line.params[0]
  544. reason = f' [{line.params[2]}]' if len(line.params) == 3 else ''
  545. yield 'KICK', channel, f'{get_mode_nick(channel, line.params[1])} is kicked by {get_mode_nick(channel)}{reason}'
  546. elif line.command == 'TOPIC':
  547. channel = line.params[0]
  548. if line.params[1] == '':
  549. yield 'TOPIC', channel, f'{get_mode_nick(channel)} unsets the topic'
  550. else:
  551. yield 'TOPIC', channel, f'{get_mode_nick(channel)} sets the topic to: {line.params[1]}'
  552. elif line.command == ircstates.numerics.RPL_TOPIC:
  553. channel = line.params[1]
  554. yield 'TOPIC', channel, f'Topic: {line.params[2]}'
  555. elif line.command == ircstates.numerics.RPL_TOPICWHOTIME:
  556. date = datetime.datetime.utcfromtimestamp(int(line.params[3])).replace(tzinfo = datetime.timezone.utc)
  557. yield 'TOPICWHO', line.params[1], f'Topic set by {irctokens.hostmask(line.params[2]).nickname} at {date:%Y-%m-%d %H:%M:%SZ}'
  558. elif line.command == ircstates.numerics.RPL_ENDOFNAMES:
  559. channel = line.params[1]
  560. users = self.server.channels[self.server.casefold(channel)].users
  561. yield 'NAMES', channel, f'Current users: {", ".join(self.render_nick_with_mode(u, u.nickname) for u in users.values())}'
  562. def render_whox(self):
  563. users = []
  564. for nickname, account in self.whoxReply:
  565. accountStr = f' ({account})' if account is not None else ''
  566. users.append(f'{self.render_nick_with_mode(self.server.channels[self.server.casefold(self.whoxChannel)].users.get(self.server.casefold(nickname)), nickname)}{accountStr}')
  567. return f'Current users: {", ".join(users)}'
  568. async def quit(self):
  569. # 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.
  570. self.logger.info('Quitting')
  571. self.lastSentTime = 1.67e34 * math.pi * 1e7 # Disable sending any further messages in send_queue
  572. self._direct_send(b'QUIT :Bye')
  573. await asyncio.wait({asyncio.create_task(self.connectionClosedEvent.wait())}, timeout = 10)
  574. if not self.connectionClosedEvent.is_set():
  575. self.logger.error('Quitting cleanly did not work, closing connection forcefully')
  576. # Event will be set implicitly in connection_lost.
  577. self.transport.close()
  578. def connection_lost(self, exc):
  579. time_ = time.time()
  580. self.logger.info('IRC connection lost')
  581. self.connected = False
  582. self.connectionClosedEvent.set()
  583. self.messageQueue.put_nowait((time_, b'- Connection closed.', None, None))
  584. for channel in self.channels:
  585. self.messageQueue.put_nowait((time_, 'Connection closed.', 'CONNCLOSED', channel))
  586. class IRCClient:
  587. logger = logging.getLogger('irclog.IRCClient')
  588. def __init__(self, messageQueue, config):
  589. self.messageQueue = messageQueue
  590. self.config = config
  591. self.channels = {channel['ircchannel'] for channel in config['channels'].values() if channel['active']}
  592. self._transport = None
  593. self._protocol = None
  594. def update_config(self, config):
  595. needReconnect = self.config['irc'] != config['irc']
  596. self.config = config
  597. if self._transport: # if currently connected:
  598. if needReconnect:
  599. self._transport.close()
  600. else:
  601. self.channels = {channel['ircchannel'] for channel in config['channels'].values() if channel['active']}
  602. self._protocol.update_channels(self.channels)
  603. def _get_ssl_context(self):
  604. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  605. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  606. if ctx is True:
  607. ctx = ssl.create_default_context()
  608. if isinstance(ctx, ssl.SSLContext):
  609. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  610. return ctx
  611. async def run(self, loop, sigintEvent):
  612. connectionClosedEvent = asyncio.Event()
  613. while True:
  614. connectionClosedEvent.clear()
  615. try:
  616. self.logger.debug('Creating IRC connection')
  617. t = asyncio.create_task(loop.create_connection(
  618. protocol_factory = lambda: IRCClientProtocol(self.messageQueue, connectionClosedEvent, loop, self.config, self.channels),
  619. host = self.config['irc']['host'],
  620. port = self.config['irc']['port'],
  621. ssl = self._get_ssl_context(),
  622. ))
  623. done, _ = await asyncio.wait({t, asyncio.create_task(sigintEvent.wait())}, return_when = asyncio.FIRST_COMPLETED, timeout = 30)
  624. if t not in done:
  625. t.cancel()
  626. await t # Raises the CancelledError
  627. self._transport, self._protocol = t.result()
  628. self.logger.debug('Starting send queue processing')
  629. asyncio.create_task(self._protocol.send_queue()) # Quits automatically on connectionClosedEvent
  630. self.logger.debug('Waiting for connection closure or SIGINT')
  631. try:
  632. await asyncio.wait({asyncio.create_task(connectionClosedEvent.wait()), asyncio.create_task(sigintEvent.wait())}, return_when = asyncio.FIRST_COMPLETED)
  633. finally:
  634. self.logger.debug(f'Got connection closed {connectionClosedEvent.is_set()} / SIGINT {sigintEvent.is_set()}')
  635. if not connectionClosedEvent.is_set():
  636. self.logger.debug('Quitting connection')
  637. await self._protocol.quit()
  638. self._transport = None
  639. self._protocol = None
  640. except (ConnectionRefusedError, ssl.SSLError, asyncio.TimeoutError, asyncio.CancelledError) as e:
  641. self.logger.error(f'{type(e).__module__}.{type(e).__name__}: {e!s}')
  642. await asyncio.wait({asyncio.create_task(sigintEvent.wait())}, timeout = 5)
  643. if sigintEvent.is_set():
  644. self.logger.debug('Got SIGINT, putting EOF and breaking')
  645. self.messageQueue.put_nowait(messageEOF)
  646. break
  647. @property
  648. def lastRecvTime(self):
  649. return self._protocol.lastRecvTime if self._protocol else None
  650. class Storage:
  651. logger = logging.getLogger('irclog.Storage')
  652. def __init__(self, messageQueue, config):
  653. self.messageQueue = messageQueue
  654. self.config = config
  655. self.paths = {} # channel -> path from channels config
  656. self.files = {} # channel|None -> [filename, fileobj, lastWriteTime]; None = general raw log
  657. def update_config(self, config):
  658. channelsOld = {channel['ircchannel'] for channel in self.config['channels'].values()}
  659. channelsNew = {channel['ircchannel'] for channel in config['channels'].values()}
  660. channelsRemoved = channelsOld - channelsNew
  661. self.config = config
  662. self.paths = {channel['ircchannel']: channel['path'] for channel in self.config['channels'].values()}
  663. # Since the PART messages will still arrive for the removed channels, only close those files after a little while.
  664. asyncio.create_task(self.delayed_close_files(channelsRemoved))
  665. async def delayed_close_files(self, channelsRemoved):
  666. await asyncio.sleep(10)
  667. for channel in channelsRemoved:
  668. if channel in self.files:
  669. self.logger.debug(f'Closing file for {channel!r}')
  670. self.files[channel][1].close()
  671. del self.files[channel]
  672. def ensure_file_open(self, time_, channel):
  673. fn = f'{get_month_str(time_)}.log'
  674. if channel in self.files and fn == self.files[channel][0]:
  675. return
  676. if channel in self.files:
  677. self.logger.debug(f'Closing file for {channel!r}')
  678. self.files[channel][1].close()
  679. dn = self.paths[channel] if channel is not None else 'general'
  680. mode = 'a' if channel is not None else 'ab'
  681. fpath = os.path.join(self.config['storage']['path'], dn, fn)
  682. self.logger.debug(f'Opening file {fpath!r} for {channel!r} with mode {mode!r}')
  683. os.makedirs(os.path.join(self.config['storage']['path'], dn), exist_ok = True)
  684. self.files[channel] = [fn, open(fpath, mode), 0]
  685. async def run(self, loop, sigintEvent):
  686. self.update_config(self.config) # Ensure that files are open etc.
  687. flushExitEvent = asyncio.Event()
  688. storageTask = asyncio.create_task(self.store_messages(sigintEvent))
  689. flushTask = asyncio.create_task(self.flush_files(flushExitEvent))
  690. await sigintEvent.wait()
  691. self.logger.debug('Got SIGINT, waiting for remaining messages to be stored')
  692. await storageTask # Wait until everything's stored
  693. flushExitEvent.set()
  694. self.logger.debug('Waiting for flush task')
  695. await flushTask
  696. self.close()
  697. async def store_messages(self, sigintEvent):
  698. while True:
  699. self.logger.debug('Waiting for message')
  700. res = await self.messageQueue.get()
  701. self.logger.debug(f'Got {res!r} from message queue')
  702. if res is messageEOF:
  703. self.logger.debug('Message EOF, breaking store_messages loop')
  704. break
  705. self.store_message(*res)
  706. def store_message(self, time_, message, command, channel):
  707. # Sanity check
  708. 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):
  709. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  710. return
  711. elif channel is not None and (not isinstance(message, str) or command is None):
  712. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  713. return
  714. self.logger.debug(f'Logging {message!r} ({command}) at {time_} for {channel!r}')
  715. self.ensure_file_open(time_, channel)
  716. if channel is None:
  717. self.files[None][1].write(str(time_).encode('ascii') + b' ' + message + b'\n')
  718. else:
  719. self.files[channel][1].write(f'{time_} {command} {message}\n')
  720. self.files[channel][2] = time.time()
  721. async def flush_files(self, flushExitEvent):
  722. lastFlushTime = 0
  723. while True:
  724. await asyncio.wait({asyncio.create_task(flushExitEvent.wait())}, timeout = self.config['storage']['flushTime'])
  725. self.logger.debug('Flushing files')
  726. flushedFiles = []
  727. for channel, (fn, f, fLastWriteTime) in self.files.items():
  728. if fLastWriteTime > lastFlushTime:
  729. flushedFiles.append(f'{channel} {fn}')
  730. f.flush()
  731. if flushedFiles:
  732. self.logger.debug(f'Flushed: {", ".join(flushedFiles)}')
  733. if flushExitEvent.is_set():
  734. break
  735. lastFlushTime = time.time()
  736. self.logger.debug('Exiting flush_files')
  737. def close(self):
  738. for _, f, _ in self.files.values():
  739. f.close()
  740. self.files = {}
  741. class WebServer:
  742. logger = logging.getLogger('irclog.WebServer')
  743. logStyleTag = '<style>' + " ".join([
  744. 'table { border-collapse: collapse; }',
  745. 'tr:nth-child(even) { background-color: #DDDDDD; }',
  746. 'td { padding: 2px; vertical-align: top; }',
  747. 'tr:target { background-color: yellow !important; }',
  748. 'tr.command_JOIN { color: green; }',
  749. 'tr.command_QUIT, tr.command_PART, tr.command_KICK, tr.command_CONNCLOSED { color: red; }',
  750. 'tr.command_NICK, tr.command_ACCOUNT, tr.command_MODE, tr.command_TOPIC, tr.command_TOPICWHO, tr.command_WHOX { color: grey; }',
  751. 'tr.command_NOTICE td:nth-child(3) { font-style: italic; }',
  752. 'tr.command_UNKNOWN { color: grey; }',
  753. ]) + '</style>'
  754. generalStyleTag = '<style>' + ' '.join([
  755. '.linkbar a { padding: 4px; border-right: black solid 1px; }',
  756. '.linkbar a:last-of-type { border-right: none; }',
  757. ]) + '</style>'
  758. def __init__(self, ircClient, config):
  759. self.ircClient = ircClient
  760. self.config = config
  761. self._paths = {} # '/path' => ('#channel', auth, hidden, extrasearchpaths, description) where auth is either False (no authentication) or the HTTP header value for basic auth
  762. self._app = aiohttp.web.Application()
  763. self._app.add_routes([
  764. aiohttp.web.get('/', self.get_homepage),
  765. aiohttp.web.get('/status', self.get_status),
  766. aiohttp.web.get(r'/{path:[^/]+}', functools.partial(self._channel_handler, handler = self.get_channel_info)),
  767. aiohttp.web.get(r'/{path:[^/]+}/{date:\d{4}-\d{2}-\d{2}}', functools.partial(self._channel_handler, handler = self.get_log)),
  768. aiohttp.web.get(r'/{path:[^/]+}/today', functools.partial(self._channel_handler, handler = self.log_redirect_today)),
  769. aiohttp.web.get('/{path:[^/]+}/search', functools.partial(self._channel_handler, handler = self.search)),
  770. ])
  771. self.update_config(config)
  772. self._configChanged = asyncio.Event()
  773. def update_config(self, config):
  774. self._paths = {channel['path']: (
  775. channel['ircchannel'],
  776. f'Basic {base64.b64encode(channel["auth"].encode("utf-8")).decode("utf-8")}' if channel['auth'] else False,
  777. channel['hidden'],
  778. [config['channels'][otherchannel]['path'] for otherchannel in channel['extrasearchchannels']],
  779. channel['description'],
  780. ) for channel in config['channels'].values()}
  781. 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
  782. self.config = config
  783. if needRebind:
  784. self._configChanged.set()
  785. async def run(self, stopEvent):
  786. while True:
  787. runner = aiohttp.web.AppRunner(self._app)
  788. await runner.setup()
  789. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  790. await site.start()
  791. await asyncio.wait({asyncio.create_task(stopEvent.wait()), asyncio.create_task(self._configChanged.wait())}, return_when = asyncio.FIRST_COMPLETED)
  792. await runner.cleanup()
  793. if stopEvent.is_set():
  794. break
  795. self._configChanged.clear()
  796. async def _check_valid_channel(self, request):
  797. if request.match_info['path'] not in self._paths:
  798. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  799. raise aiohttp.web.HTTPNotFound()
  800. async def _check_auth(self, request):
  801. auth = self._paths[request.match_info['path']][1]
  802. if auth:
  803. authHeader = request.headers.get('Authorization')
  804. if not authHeader or authHeader != auth:
  805. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  806. raise aiohttp.web.HTTPUnauthorized(headers = {'WWW-Authenticate': f'Basic realm="{request.match_info["path"]}"'})
  807. async def _channel_handler(self, request, handler):
  808. await self._check_valid_channel(request)
  809. await self._check_auth(request)
  810. return (await handler(request))
  811. async def get_homepage(self, request):
  812. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  813. lines = []
  814. for path, (channel, auth, hidden, extrasearchpaths, description) in self._paths.items():
  815. if hidden:
  816. continue
  817. lines.append(f'{"(PW) " if auth else ""}<a href="/{html.escape(path)}">{html.escape(channel)}</a> (<a href="/{html.escape(path)}/today">today&#x27;s log</a>, <a href="/{html.escape(path)}/search">search</a>)')
  818. 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')
  819. async def get_status(self, request):
  820. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  821. return (aiohttp.web.Response if (self.ircClient.lastRecvTime or 0) > time.time() - 600 else aiohttp.web.HTTPInternalServerError)()
  822. async def get_channel_info(self, request):
  823. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  824. description = html.escape(self._paths[request.match_info["path"]][4]) if self._paths[request.match_info["path"]][4] else '<span style="font-style: italic">(not available)</span>'
  825. return aiohttp.web.Response(
  826. text = ''.join([
  827. '<!DOCTYPE html><html lang="en">',
  828. f'<head><title>{html.escape(self._paths[request.match_info["path"]][0])}</title>{self.generalStyleTag}</head>',
  829. '<body>',
  830. '<p class="linkbar">',
  831. '<a href="/">Home</a>',
  832. f'<a href="/{html.escape(request.match_info["path"])}/today">Today&#x27;s log</a>',
  833. f'<a href="/{html.escape(request.match_info["path"])}/search">Search</a>',
  834. '</p>',
  835. '<hr />',
  836. '<p>',
  837. f'<span style="font-weight: bold">Channel:</span> {html.escape(self._paths[request.match_info["path"]][0])}<br />',
  838. f'<span style="font-weight: bold">Description:</span> {description}',
  839. '</p>',
  840. '</body>',
  841. '</html>'
  842. ]),
  843. content_type = 'text/html'
  844. )
  845. def _file_iter_with_path(self, fn, path):
  846. # Open fn, iterate over its lines yielding (path, line) tuples
  847. try:
  848. with open(fn, 'r', errors = 'surrogateescape') as fp:
  849. for line in fp:
  850. yield (path, line)
  851. except FileNotFoundError:
  852. pass
  853. def _stdout_with_path(self, stdout):
  854. # Process grep output with --with-filenames, --null, and --line-number into (path, line) tuples.
  855. # Lines are sorted by timestamp, filename, and line number to ensure a consistent and chronological order.
  856. out = []
  857. # splitlines splits on more than desired, in particular also on various things that can occur within IRC messages (which is really anything except CR LF, basically).
  858. # split has the downside of producing a final empty element (because stdout ends with LF) and an empty element when the input is empty.
  859. # So just discard empty lines.
  860. for line in stdout.decode('utf-8', errors = 'surrogateescape').split('\n'):
  861. if line == '':
  862. continue
  863. fn, line = line.split('\0', 1)
  864. assert fn.startswith(self.config['storage']['path'] + '/') and fn.count('/', len(self.config['storage']['path']) + 1) == 1
  865. _, path, _ = fn.rsplit('/', 2)
  866. assert path in self._paths
  867. ln, line = line.split(':', 1)
  868. ln = int(ln)
  869. ts = float(line.split(' ', 1)[0])
  870. out.append((ts, fn, ln, path, line))
  871. yield from (x[3:] for x in sorted(out, key = lambda y: y[0:3], reverse = True))
  872. def _raw_to_lines(self, f, filter = lambda path, dt, command, content: True):
  873. # f: iterable producing tuples (path, line) where each line has the format '<ts> " " <command> " " <content>', <ts> is a float, <command> is one of the valid commands, and <content> is any str
  874. # filter: function taking the line fields (path: str, ts: float, command: str, content: str) and returning whether to include the line
  875. for path, line in f:
  876. ts, command, content = line.removesuffix('\n').split(' ', 2)
  877. ts = float(ts)
  878. if not filter(path, ts, command, content):
  879. continue
  880. yield (path, ts, command, content)
  881. def _render_log(self, lines, withDate = False):
  882. # lines: iterable of (path: str, timestamp: float, command: str, content: str)
  883. # withDate: whether to include the date with the time of the log line
  884. ret = []
  885. for path, ts, command, content in lines:
  886. if command == 'NAMES':
  887. # Hidden as WHOX provides more information
  888. continue
  889. if command not in LOG_COMMANDS:
  890. command = 'UNKNOWN'
  891. d = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo = datetime.timezone.utc)
  892. date = f'{d:%Y-%m-%d }' if withDate else ''
  893. lineId = hashlib.md5(f'{ts} {command} {content}'.encode('utf-8', errors = 'surrogateescape')).hexdigest()[:8]
  894. if command in ('NOTICE', 'PRIVMSG'):
  895. author, content = content.split(' ', 1)
  896. else:
  897. author = ''
  898. ret.append(''.join([
  899. f'<tr id="l{lineId}" class="command_{html.escape(command)}">',
  900. f'<td><a href="/{html.escape(path)}/{d:%Y-%m-%d}#l{lineId}">{date}{d:%H:%M:%S}</a></td>',
  901. f'<td>{html.escape(author)}</td>',
  902. f'<td>{html.escape(content)}</td>',
  903. '</tr>'
  904. ]))
  905. return '<table>\n' + '\n'.join(ret) + '\n</table>' if ret else ''
  906. async def get_log(self, request):
  907. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  908. date = datetime.datetime.strptime(request.match_info['date'], '%Y-%m-%d').replace(tzinfo = datetime.timezone.utc)
  909. dateStart = date.timestamp()
  910. dateEnd = (date + datetime.timedelta(days = 1)).timestamp()
  911. channelLinks = '<p class="linkbar">' + ''.join([
  912. '<a href="/">Home</a>',
  913. f'<a href="/{html.escape(request.match_info["path"])}/search">Search</a>',
  914. f'<a href="/{html.escape(request.match_info["path"])}/{(date - datetime.timedelta(days = 1)).strftime("%Y-%m-%d")}">Previous day</a>',
  915. f'<a href="/{html.escape(request.match_info["path"])}/{(date + datetime.timedelta(days = 1)).strftime("%Y-%m-%d")}">Next day</a>',
  916. ]) + '</p>'
  917. #TODO Implement this in a better way...
  918. fn = date.strftime('%Y-%m.log')
  919. lines = list(self._raw_to_lines(self._file_iter_with_path(os.path.join(self.config['storage']['path'], request.match_info["path"], fn), request.match_info["path"]), filter = lambda path, ts, command, content: dateStart <= ts <= dateEnd))
  920. return aiohttp.web.Response(
  921. body = ''.join([
  922. '<!DOCTYPE html><html lang="en">',
  923. f'<head><title>{html.escape(self._paths[request.match_info["path"]][0])} log for {date:%Y-%m-%d}</title>{self.generalStyleTag}{self.logStyleTag}</head>',
  924. '<body>',
  925. channelLinks,
  926. '<hr />',
  927. self._render_log(lines),
  928. '<hr />',
  929. channelLinks,
  930. '</body>',
  931. '</html>',
  932. ]).encode('utf-8', errors = 'surrogateescape'),
  933. content_type = 'text/html'
  934. )
  935. async def log_redirect_today(self, request):
  936. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  937. date = datetime.datetime.now(tz = datetime.timezone.utc).replace(hour = 0, minute = 0, second = 0, microsecond = 0)
  938. return aiohttp.web.HTTPFound(f'/{request.match_info["path"]}/{date:%Y-%m-%d}')
  939. async def search(self, request):
  940. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r} with query {request.query!r}')
  941. if self._paths[request.match_info['path']][2]: # Hidden channels aren't searchable
  942. return aiohttp.web.HTTPNotFound()
  943. linkBar = ''.join([
  944. '<p class="linkbar">',
  945. '<a href="/">Home</a>',
  946. f'<a href="/{html.escape(request.match_info["path"])}/today">Today&#x27;s log</a>',
  947. '</p>',
  948. ])
  949. searchForm = ''.join([
  950. '<form>',
  951. '<input name="q" ', f'value="{html.escape(request.query["q"])}" ' if 'q' in request.query else '', '/>',
  952. '<input type="submit" value="Search!" />',
  953. '<br />',
  954. '<input type="checkbox" name="casesensitive" value="true" ', 'checked ' if 'casesensitive' in request.query else '', '/>&nbsp;Case-sensitive',
  955. '</form>',
  956. ])
  957. if 'q' not in request.query:
  958. return aiohttp.web.Response(
  959. text = ''.join([
  960. '<!DOCTYPE html><html lang="en">'
  961. f'<head><title>{html.escape(self._paths[request.match_info["path"]][0])} search</title>{self.generalStyleTag}</head>',
  962. '<body>',
  963. linkBar,
  964. searchForm,
  965. '</body>',
  966. '</html>'
  967. ]),
  968. content_type = 'text/html'
  969. )
  970. # Run the search with grep, limiting memory use, output size, and runtime and setting the niceness.
  971. # While Python's subprocess.Process has preexec_fn, this isn't safe in conjunction with threads, and asyncio uses threads under the hood.
  972. # So instead, use a wrapper script in Bash which sets the niceness and memory limit.
  973. cmd = [
  974. os.path.join('.', os.path.dirname(__file__), 'nicegrep'), str(self.config['web']['search']['nice']), str(self.config['web']['search']['maxMemory']),
  975. '--fixed-strings', '--recursive', '--with-filename', '--null', '--line-number',
  976. ]
  977. if 'casesensitive' not in request.query:
  978. cmd.append('--ignore-case')
  979. cmd.append('--')
  980. cmd.append(request.query['q'])
  981. for path in itertools.chain((request.match_info['path'],), self._paths[request.match_info['path']][3]):
  982. cmd.append(os.path.join(self.config['storage']['path'], path, ''))
  983. proc = await asyncio.create_subprocess_exec(*cmd, stdout = asyncio.subprocess.PIPE, stderr = asyncio.subprocess.PIPE)
  984. async def process_stdout():
  985. out = []
  986. size = 0
  987. incomplete = False
  988. while (buf := await proc.stdout.read(1024)):
  989. self.logger.debug(f'Request {id(request)} grep stdout: {buf!r}')
  990. if self.config['web']['search']['maxSize'] != 0 and size + len(buf) > self.config['web']['search']['maxSize']:
  991. self.logger.warning(f'Request {id(request)} grep output exceeds max size')
  992. if (bufLFPos := buf.rfind(b'\n', 0, self.config['web']['search']['maxSize'] - size)) > -1:
  993. # There's a LF in this buffer at the right position, keep everything up to it such that the total size is <= maxSize.
  994. out.append(buf[:bufLFPos + 1])
  995. else:
  996. # Try to find the last LF in the previous buffers
  997. for i, prevBuf in enumerate(reversed(out)):
  998. if (lfPos := prevBuf.rfind(b'\n')) > -1:
  999. j = len(out) - 1 - i
  1000. out[j] = out[j][:lfPos + 1]
  1001. out = out[:j + 1]
  1002. break
  1003. else:
  1004. # No newline to be found anywhere at all; no output.
  1005. out = []
  1006. incomplete = True
  1007. proc.kill()
  1008. break
  1009. out.append(buf)
  1010. size += len(buf)
  1011. return (b''.join(out), incomplete)
  1012. async def process_stderr():
  1013. buf = b''
  1014. while (buf := buf + (await proc.stderr.read(64))):
  1015. lines = buf.split(b'\n')
  1016. buf = lines[-1]
  1017. for line in lines[:-1]:
  1018. try:
  1019. line = line.decode('utf-8')
  1020. except UnicodeDecodeError:
  1021. pass
  1022. self.logger.warning(f'Request {id(request)} grep stderr output: {line!r}')
  1023. stdoutTask = asyncio.create_task(process_stdout())
  1024. stderrTask = asyncio.create_task(process_stderr())
  1025. await asyncio.wait({stdoutTask, stderrTask}, timeout = self.config['web']['search']['maxTime'] if self.config['web']['search']['maxTime'] != 0 else None)
  1026. # The stream readers may quit before the process is done even on a successful grep. Wait a tiny bit longer for the process to exit.
  1027. await asyncio.wait({asyncio.create_task(proc.wait())}, timeout = 0.1)
  1028. if proc.returncode is None:
  1029. # Process hasn't finished yet after maxTime. Murder it and wait for it to die.
  1030. self.logger.warning(f'Request {id(request)} grep took more than the time limit')
  1031. proc.kill()
  1032. await asyncio.wait({stdoutTask, stderrTask, asyncio.create_task(proc.wait())}, timeout = 1) # This really shouldn't take longer.
  1033. if proc.returncode is None:
  1034. # Still not done?! Cancel tasks and bail.
  1035. self.logger.error(f'Request {id(request)} grep did not exit after getting killed!')
  1036. stdoutTask.cancel()
  1037. stderrTask.cancel()
  1038. return aiohttp.web.HTTPInternalServerError()
  1039. stdout, incomplete = stdoutTask.result()
  1040. self.logger.info(f'Request {id(request)} grep exited with {proc.returncode} and produced {len(stdout)} bytes (incomplete: {incomplete})')
  1041. if proc.returncode not in (0, 1):
  1042. incomplete = True
  1043. lines = self._raw_to_lines(self._stdout_with_path(stdout))
  1044. return aiohttp.web.Response(
  1045. body = ''.join([
  1046. '<!DOCTYPE html><html lang="en">',
  1047. '<head>',
  1048. f'<title>{html.escape(self._paths[request.match_info["path"]][0])} search results for "{html.escape(request.query["q"])}"</title>',
  1049. self.generalStyleTag,
  1050. self.logStyleTag,
  1051. '<style>#incomplete { background-color: #FF6666; padding: 10px; }</style>',
  1052. '</head>',
  1053. '<body>',
  1054. linkBar,
  1055. searchForm,
  1056. '<p id="incomplete">Warning: output incomplete due to exceeding time or size limits</p>' if incomplete else '',
  1057. self._render_log(lines, withDate = True) or 'No results.',
  1058. linkBar,
  1059. '</body>',
  1060. '</html>'
  1061. ]).encode('utf-8', errors = 'surrogateescape'),
  1062. content_type = 'text/html'
  1063. )
  1064. def configure_logging(config):
  1065. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  1066. root = logging.getLogger()
  1067. root.setLevel(getattr(logging, config['logging']['level']))
  1068. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  1069. formatter = logging.Formatter(config['logging']['format'], style = '{')
  1070. stderrHandler = logging.StreamHandler()
  1071. stderrHandler.setFormatter(formatter)
  1072. root.addHandler(stderrHandler)
  1073. async def main():
  1074. if len(sys.argv) != 2:
  1075. print('Usage: irclog.py CONFIGFILE', file = sys.stderr)
  1076. sys.exit(1)
  1077. configFile = sys.argv[1]
  1078. config = Config(configFile)
  1079. configure_logging(config)
  1080. loop = asyncio.get_running_loop()
  1081. messageQueue = asyncio.Queue()
  1082. # tuple(time: float, message: bytes or str, command: str or None, channel: str or None)
  1083. # command is an identifier of the type of message.
  1084. # 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.
  1085. # The queue can also contain messageEOF, which signals to the storage layer to stop logging.
  1086. irc = IRCClient(messageQueue, config)
  1087. webserver = WebServer(irc, config)
  1088. storage = Storage(messageQueue, config)
  1089. sigintEvent = asyncio.Event()
  1090. def sigint_callback():
  1091. global logger
  1092. nonlocal sigintEvent
  1093. logger.info('Got SIGINT, stopping')
  1094. sigintEvent.set()
  1095. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  1096. def sigusr1_callback():
  1097. global logger
  1098. nonlocal config, irc, webserver, storage
  1099. logger.info('Got SIGUSR1, reloading config')
  1100. try:
  1101. newConfig = config.reread()
  1102. except InvalidConfig as e:
  1103. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  1104. return
  1105. config = newConfig
  1106. configure_logging(config)
  1107. irc.update_config(config)
  1108. webserver.update_config(config)
  1109. storage.update_config(config)
  1110. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  1111. def sigusr2_callback():
  1112. nonlocal storage
  1113. logger.info('Got SIGUSR2, forcing log flush')
  1114. for channel in storage.files:
  1115. storage.files[channel][2] = time.time()
  1116. loop.add_signal_handler(signal.SIGUSR2, sigusr2_callback)
  1117. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent), storage.run(loop, sigintEvent))
  1118. if __name__ == '__main__':
  1119. asyncio.run(main())