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.
 
 

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