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.
 
 

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