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.
 
 

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