Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1019 lignes
46 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') 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 'channels' in obj:
  136. seenChannels = {}
  137. seenPaths = {}
  138. for key, channel in obj['channels'].items():
  139. if not isinstance(key, str) or not key:
  140. raise InvalidConfig(f'Invalid channel key {key!r}')
  141. if not isinstance(channel, collections.abc.Mapping):
  142. raise InvalidConfig(f'Invalid channel for {key!r}')
  143. if any(x not in ('ircchannel', 'path', 'auth', 'active', 'hidden', 'extrasearchchannels') for x in channel):
  144. raise InvalidConfig(f'Unknown key(s) found in channel {key!r}')
  145. if 'ircchannel' not in channel:
  146. channel['ircchannel'] = f'#{key}'
  147. if not isinstance(channel['ircchannel'], str):
  148. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: not a string')
  149. if not channel['ircchannel'].startswith('#') and not channel['ircchannel'].startswith('&'):
  150. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: does not start with # or &')
  151. if any(x in channel['ircchannel'][1:] for x in (' ', '\x00', '\x07', '\r', '\n', ',')):
  152. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: contains forbidden characters')
  153. if len(channel['ircchannel']) > 200:
  154. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: too long')
  155. if channel['ircchannel'] in seenChannels:
  156. raise InvalidConfig(f'Invalid channel {key!r} IRC channel: collides with channel {seenChannels[channel["ircchannel"]]!r}')
  157. seenChannels[channel['ircchannel']] = key
  158. if 'path' not in channel:
  159. channel['path'] = key
  160. if not isinstance(channel['path'], str):
  161. raise InvalidConfig(f'Invalid channel {key!r} path: not a string')
  162. if any(x in channel['path'] for x in itertools.chain(map(chr, range(32)), ('/', '\\', '"', '\x7F'))):
  163. raise InvalidConfig(f'Invalid channel {key!r} path: contains invalid characters')
  164. if channel['path'] == 'general':
  165. raise InvalidConfig(f'Invalid channel {key!r} path: cannot be "general"')
  166. if channel['path'] in seenPaths:
  167. raise InvalidConfig(f'Invalid channel {key!r} path: collides with channel {seenPaths[channel["path"]]!r}')
  168. seenPaths[channel['path']] = key
  169. if 'auth' in channel:
  170. if channel['auth'] is not False and not isinstance(channel['auth'], str):
  171. raise InvalidConfig(f'Invalid channel {key!r} auth: must be false or a string')
  172. if isinstance(channel['auth'], str) and ':' not in channel['auth']:
  173. raise InvalidConfig(f'Invalid channel {key!r} auth: must contain a colon')
  174. else:
  175. channel['auth'] = False
  176. if 'active' in channel:
  177. if channel['active'] is not True and channel['active'] is not False:
  178. raise InvalidConfig(f'Invalid channel {key!r} active: must be true or false')
  179. else:
  180. channel['active'] = True
  181. if 'hidden' not in channel:
  182. channel['hidden'] = False
  183. if channel['hidden'] is not False and channel['hidden'] is not True:
  184. raise InvalidConfig(f'Invalid channel {key!r} hidden: must be true or false')
  185. if 'extrasearchchannels' not in channel:
  186. channel['extrasearchchannels'] = []
  187. if not isinstance(channel['extrasearchchannels'], collections.abc.Sequence):
  188. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: must be a sequence (e.g. list)')
  189. if any(not isinstance(x, str) for x in channel['extrasearchchannels']):
  190. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: must only contain strings')
  191. if any(x == key for x in channel['extrasearchchannels']):
  192. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: cannot refer to self')
  193. # Validation of the values is performed after reading everything
  194. # extrasearchchannels validation after reading all channels
  195. for key, channel in obj['channels'].items():
  196. if any(x not in obj['channels'] for x in channel['extrasearchchannels']):
  197. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: refers to undefined channel')
  198. if any(obj['channels'][x]['auth'] is not False and obj['channels'][x]['auth'] != channel['auth'] for x in channel['extrasearchchannels']):
  199. raise InvalidConfig(f'Invalid channel {key!r} extrasearchchannels: refers to auth-required channel whose auth differs from this channel\'s')
  200. # Default values
  201. finalObj = {
  202. 'logging': {'level': 'INFO', 'format': '{asctime} {levelname} {name} {message}'},
  203. 'storage': {'path': os.path.abspath(os.path.dirname(self._filename)), 'flushTime': 60},
  204. 'irc': {'host': 'irc.hackint.org', 'port': 6697, 'ssl': 'yes', 'nick': 'irclogbot', 'real': 'I am an irclog bot.', 'certfile': None, 'certkeyfile': None},
  205. 'web': {'host': '127.0.0.1', 'port': 8080},
  206. 'channels': {}
  207. }
  208. # Default values for channels are already set above.
  209. # Merge in what was read from the config file and set keys on self
  210. for key in ('logging', 'storage', 'irc', 'web', 'channels'):
  211. if key in obj:
  212. finalObj[key].update(obj[key])
  213. self[key] = finalObj[key]
  214. def __repr__(self):
  215. return f'<Config(logging={self["logging"]!r}, storage={self["storage"]!r}, irc={self["irc"]!r}, web={self["web"]!r}, channels={self["channels"]!r})>'
  216. def reread(self):
  217. return Config(self._filename)
  218. class IRCClientProtocol(asyncio.Protocol):
  219. logger = logging.getLogger('irclog.IRCClientProtocol')
  220. def __init__(self, messageQueue, connectionClosedEvent, loop, config, channels):
  221. self.messageQueue = messageQueue
  222. self.connectionClosedEvent = connectionClosedEvent
  223. self.loop = loop
  224. self.config = config
  225. self.lastSentTime = None # float timestamp or None; the latter disables the send rate limit
  226. self.sendQueue = asyncio.Queue()
  227. self.buffer = b''
  228. self.connected = False
  229. self.channels = channels # Currently joined/supposed-to-be-joined channels; set(str)
  230. self.userChannels = collections.defaultdict(set) # List of which channels a user is known to be in; nickname:str -> {channel:str, ...}
  231. self.sasl = bool(self.config['irc']['certfile'] and self.config['irc']['certkeyfile'])
  232. self.authenticated = False
  233. self.server = ircstates.Server(self.config['irc']['host'])
  234. self.capReqsPending = set() # Capabilities requested from the server but not yet ACKd or NAKd
  235. self.caps = set() # Capabilities acknowledged by the server
  236. self.whoxQueue = collections.deque() # Names of channels that were joined successfully but for which no WHO (WHOX) query was sent yet
  237. self.whoxChannel = None # Name of channel for which a WHO query is currently running
  238. self.whoxReply = [] # List of (nickname, account) tuples from the currently running WHO query
  239. @staticmethod
  240. def nick_command(nick: str):
  241. return b'NICK ' + nick.encode('utf-8')
  242. @staticmethod
  243. def user_command(nick: str, real: str):
  244. nickb = nick.encode('utf-8')
  245. return b'USER ' + nickb + b' ' + nickb + b' ' + nickb + b' :' + real.encode('utf-8')
  246. @staticmethod
  247. def valid_channel(channel: str):
  248. return channel[0] in ('#', '&') and not any(x in channel for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  249. @staticmethod
  250. def valid_nick(nick: str):
  251. # 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.
  252. # So instead, just do a sanity check similar to the channel one to disallow obvious bullshit.
  253. return not any(x in nick for x in (' ', '\x00', '\x07', '\r', '\n', ','))
  254. @staticmethod
  255. def prefix_to_nick(prefix: str):
  256. nick = prefix[1:]
  257. if '!' in nick:
  258. nick = nick.split('!', 1)[0]
  259. if '@' in nick: # nick@host is also legal
  260. nick = nick.split('@', 1)[0]
  261. return nick
  262. def connection_made(self, transport):
  263. self.logger.info('IRC connected')
  264. self.transport = transport
  265. self.connected = True
  266. caps = [b'userhost-in-names', b'away-notify', b'account-notify', b'extended-join']
  267. if self.sasl:
  268. caps.append(b'sasl')
  269. for cap in caps:
  270. self.capReqsPending.add(cap.decode('ascii'))
  271. self.send(b'CAP REQ :' + cap)
  272. self.send(self.nick_command(self.config['irc']['nick']))
  273. self.send(self.user_command(self.config['irc']['nick'], self.config['irc']['real']))
  274. def _send_join_part(self, command, channels):
  275. '''Split a JOIN or PART into multiple messages as necessary'''
  276. # command: b'JOIN' or b'PART'; channels: set[str]
  277. channels = [x.encode('utf-8') for x in channels]
  278. 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)
  279. # Everything fits into one command.
  280. self.send(command + b' ' + b','.join(channels))
  281. return
  282. # List too long, need to split.
  283. limit = 510 - len(command)
  284. lengths = [1 + len(x) for x in channels] # separator + channel name
  285. chanLengthAcceptable = [l <= limit for l in lengths]
  286. if not all(chanLengthAcceptable):
  287. # There are channel names that are too long to even fit into one message on their own; filter them out and warn about them.
  288. # This should never happen since the config reader would already filter it out.
  289. tooLongChannels = [x for x, a in zip(channels, chanLengthAcceptable) if not a]
  290. channels = [x for x, a in zip(channels, chanLengthAcceptable) if a]
  291. lengths = [l for l, a in zip(lengths, chanLengthAcceptable) if a]
  292. for channel in tooLongChannels:
  293. self.logger.warning(f'Cannot {command} {channel}: name too long')
  294. runningLengths = list(itertools.accumulate(lengths)) # entry N = length of all entries up to and including channel N, including separators
  295. offset = 0
  296. while channels:
  297. i = next((x[0] for x in enumerate(runningLengths) if x[1] - offset > limit), -1)
  298. if i == -1: # Last batch
  299. i = len(channels)
  300. self.send(command + b' ' + b','.join(channels[:i]))
  301. offset = runningLengths[i-1]
  302. channels = channels[i:]
  303. runningLengths = runningLengths[i:]
  304. def update_channels(self, channels: set):
  305. channelsToPart = self.channels - channels
  306. channelsToJoin = channels - self.channels
  307. self.channels = channels
  308. if self.connected:
  309. if channelsToPart:
  310. self._send_join_part(b'PART', channelsToPart)
  311. if channelsToJoin:
  312. self._send_join_part(b'JOIN', channelsToJoin)
  313. def send(self, data):
  314. self.logger.debug(f'Queueing for send: {data!r}')
  315. if len(data) > 510:
  316. raise RuntimeError(f'IRC message too long ({len(data)} > 510): {data!r}')
  317. self.sendQueue.put_nowait(data)
  318. def _direct_send(self, data):
  319. self.logger.debug(f'Send: {data!r}')
  320. time_ = time.time()
  321. self.transport.write(data + b'\r\n')
  322. self.messageQueue.put_nowait((time_, b'> ' + data, None, None))
  323. return time_
  324. async def send_queue(self):
  325. while True:
  326. self.logger.debug(f'Trying to get data from send queue')
  327. t = asyncio.create_task(self.sendQueue.get())
  328. done, pending = await asyncio.wait((t, self.connectionClosedEvent.wait()), return_when = asyncio.FIRST_COMPLETED)
  329. if self.connectionClosedEvent.is_set():
  330. break
  331. assert t in done, f'{t!r} is not in {done!r}'
  332. data = t.result()
  333. self.logger.debug(f'Got {data!r} from send queue')
  334. now = time.time()
  335. if self.lastSentTime is not None and now - self.lastSentTime < 1:
  336. self.logger.debug(f'Rate limited')
  337. await asyncio.wait({self.connectionClosedEvent.wait()}, timeout = self.lastSentTime + 1 - now)
  338. if self.connectionClosedEvent.is_set():
  339. break
  340. time_ = self._direct_send(data)
  341. if self.lastSentTime is not None:
  342. self.lastSentTime = time_
  343. def data_received(self, data):
  344. time_ = time.time()
  345. self.logger.debug(f'Data received: {data!r}')
  346. # If there's any data left in the buffer, prepend it to the data. Split on CRLF.
  347. # Then, process all messages except the last one (since data might not end on a CRLF) and keep the remainder in the buffer.
  348. # If data does end with CRLF, all messages will have been processed and the buffer will be empty again.
  349. if self.buffer:
  350. data = self.buffer + data
  351. messages = data.split(b'\r\n')
  352. for message in messages[:-1]:
  353. lines = self.server.recv(message + b'\r\n')
  354. assert len(lines) == 1, f'recv did not return exactly one line: {message!r} -> {lines!r}'
  355. self.message_received(time_, message, lines[0])
  356. self.server.parse_tokens(lines[0])
  357. self.buffer = messages[-1]
  358. def message_received(self, time_, message, line):
  359. self.logger.debug(f'Message received at {time_}: {message!r}')
  360. # Queue message for storage
  361. # Note: WHOX is queued further down
  362. self.messageQueue.put_nowait((time_, b'< ' + message, None, None))
  363. for command, channel, logMessage in self.render_message(line):
  364. self.messageQueue.put_nowait((time_, logMessage, command, channel))
  365. maybeTriggerWhox = False
  366. # PING/PONG
  367. if line.command == 'PING':
  368. self._direct_send(irctokens.build('PONG', line.params).format().encode('utf-8'))
  369. # IRCv3 and SASL
  370. elif line.command == 'CAP':
  371. if line.params[1] == 'ACK':
  372. for cap in line.params[2].split(' '):
  373. self.logger.debug('CAP ACK: {cap}')
  374. self.caps.add(cap)
  375. if cap == 'sasl' and self.sasl:
  376. self.send(b'AUTHENTICATE EXTERNAL')
  377. else:
  378. self.capReqsPending.remove(cap)
  379. elif line.params[1] == 'NAK':
  380. self.logger.warning(f'Failed to activate CAP(s): {line.params[2]}')
  381. for cap in line.params[2].split(' '):
  382. self.capReqsPending.remove(cap)
  383. if len(self.capReqsPending) == 0:
  384. self.send(b'CAP END')
  385. elif line.command == 'AUTHENTICATE' and line.params == ['+']:
  386. self.send(b'AUTHENTICATE +')
  387. elif line.command == ircstates.numerics.RPL_SASLSUCCESS:
  388. self.authenticated = True
  389. self.capReqsPending.remove('sasl')
  390. if len(self.capReqsPending) == 0:
  391. self.send(b'CAP END')
  392. elif line.command in ('902', ircstates.numerics.ERR_SASLFAIL, ircstates.numerics.ERR_SASLTOOLONG, ircstates.numerics.ERR_SASLABORTED, ircstates.numerics.RPL_SASLMECHS):
  393. self.logger.error('SASL error, terminating connection')
  394. self.transport.close()
  395. # NICK errors
  396. elif line.command in ('431', ircstates.numerics.ERR_ERRONEUSNICKNAME, ircstates.numerics.ERR_NICKNAMEINUSE, '436'):
  397. self.logger.error(f'Failed to set nickname: {message!r}, terminating connection')
  398. self.transport.close()
  399. # USER errors
  400. elif line.command in ('461', '462'):
  401. self.logger.error(f'Failed to register: {message!r}, terminating connection')
  402. self.transport.close()
  403. # JOIN errors
  404. elif line.command in (
  405. ircstates.numerics.ERR_TOOMANYCHANNELS,
  406. ircstates.numerics.ERR_CHANNELISFULL,
  407. ircstates.numerics.ERR_INVITEONLYCHAN,
  408. ircstates.numerics.ERR_BANNEDFROMCHAN,
  409. ircstates.numerics.ERR_BADCHANNELKEY,
  410. ):
  411. self.logger.error(f'Failed to join channel: {message!r}, terminating connection')
  412. self.transport.close()
  413. # PART errors
  414. elif line.command == '442':
  415. self.logger.error(f'Failed to part channel: {message!r}')
  416. # JOIN/PART errors
  417. elif line.command == ircstates.numerics.ERR_NOSUCHCHANNEL:
  418. self.logger.error(f'Failed to join or part channel: {message!r}')
  419. # Connection registration reply
  420. elif line.command == ircstates.numerics.RPL_WELCOME:
  421. self.logger.info('IRC connection registered')
  422. if self.sasl and not self.authenticated:
  423. self.logger.error('IRC connection registered but not authenticated, terminating connection')
  424. self.transport.close()
  425. return
  426. self.lastSentTime = time.time()
  427. self._send_join_part(b'JOIN', self.channels)
  428. # Bot getting KICKed
  429. elif line.command == 'KICK' and line.source and self.server.casefold(line.params[1]) == self.server.casefold(self.server.nickname):
  430. self.logger.warning(f'Got kicked from {line.params[0]}')
  431. kickedChannel = self.server.casefold(line.params[0])
  432. for channel in self.channels:
  433. if self.server.casefold(channel) == kickedChannel:
  434. self.channels.remove(channel)
  435. break
  436. # WHOX on successful JOIN if supported to fetch account information
  437. 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):
  438. self.whoxQueue.extend(line.params[0].split(','))
  439. maybeTriggerWhox = True
  440. # WHOX response
  441. elif line.command == ircstates.numerics.RPL_WHOSPCRPL and line.params[1] == '042':
  442. self.whoxReply.append((line.params[2], line.params[3] if line.params[3] != '0' else None))
  443. # End of WHOX response
  444. elif line.command == ircstates.numerics.RPL_ENDOFWHO:
  445. self.messageQueue.put_nowait((time_, self.render_whox(), 'WHOX', self.whoxChannel))
  446. self.whoxChannel = None
  447. self.whoxReply = []
  448. maybeTriggerWhox = True
  449. # General fatal ERROR
  450. elif line.command == 'ERROR':
  451. self.logger.error(f'Server sent ERROR: {message!r}')
  452. self.transport.close()
  453. # Send next WHOX if appropriate
  454. if maybeTriggerWhox and self.whoxChannel is None and self.whoxQueue:
  455. self.whoxChannel = self.whoxQueue.popleft()
  456. self.whoxReply = []
  457. self.send(b'WHO ' + self.whoxChannel.encode('utf-8') + b' c%nat,042')
  458. def get_mode_char(self, channelUser):
  459. if channelUser is None:
  460. return ''
  461. prefix = self.server.isupport.prefix
  462. if any(x in prefix.modes for x in channelUser.modes):
  463. return prefix.prefixes[min(prefix.modes.index(x) for x in channelUser.modes if x in prefix.modes)]
  464. return ''
  465. def render_nick_with_mode(self, channelUser, nickname):
  466. return f'{self.get_mode_char(channelUser)}{nickname}'
  467. def render_message(self, line):
  468. if line.source:
  469. sourceUser = self.server.users.get(self.server.casefold(line.hostmask.nickname)) if line.source else None
  470. 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)
  471. if line.command == 'JOIN':
  472. # 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...
  473. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  474. account = f' ({line.params[-2]})' if 'extended-join' in self.caps and line.params[-2] != '*' else ''
  475. for channel in channels:
  476. # 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).
  477. yield 'JOIN', channel, f'{line.hostmask.nickname}{account} joins {channel}'
  478. elif line.command in ('PRIVMSG', 'NOTICE'):
  479. channel = line.params[0]
  480. if channel not in self.server.channels:
  481. return
  482. yield line.command, channel, f'<{get_mode_nick(channel)}> {line.params[1]}'
  483. elif line.command == 'PART':
  484. channels = [line.params[0]] if ',' not in line.params[0] else line.params[0].split(',')
  485. reason = f' [{line.params[1]}]' if len(line.params) == 2 else ''
  486. for channel in channels:
  487. yield 'PART', channel, f'{get_mode_nick(channel)} leaves {channel}'
  488. elif line.command in ('QUIT', 'NICK', 'ACCOUNT'):
  489. if line.hostmask.nickname == self.server.nickname:
  490. channels = self.channels
  491. elif sourceUser is not None:
  492. channels = sourceUser.channels
  493. else:
  494. return
  495. for channel in channels:
  496. if line.command == 'QUIT':
  497. message = f'{get_mode_nick(channel)} quits [{line.params[0]}]'
  498. elif line.command == 'NICK':
  499. newMode = self.get_mode_char(self.server.channels[self.server.casefold(channel)].users[self.server.casefold(line.hostmask.nickname)])
  500. message = f'{get_mode_nick(channel)} is now known as {newMode}{line.params[0]}'
  501. elif line.command == 'ACCOUNT':
  502. message = f'{get_mode_nick(channel)} is now authenticated as {line.params[0]}'
  503. yield line.command, channel, message
  504. elif line.command == 'MODE' and line.params[0][0] in ('#', '&'):
  505. yield 'MODE', line.params[0], f'{get_mode_nick(line.params[0])} sets mode: {" ".join(line.params[1:])}'
  506. elif line.command == 'KICK':
  507. channel = line.params[0]
  508. reason = f' [{line.params[2]}]' if len(line.params) == 3 else ''
  509. yield 'KICK', channel, f'{get_mode_nick(channel, line.params[1])} is kicked from {channel} by {get_mode_nick(channel)}{reason}'
  510. elif line.command == 'TOPIC':
  511. channel = line.params[0]
  512. if line.params[1] == '':
  513. yield 'TOPIC', channel, f'{get_mode_nick(channel)} unsets the topic of {channel}'
  514. else:
  515. yield 'TOPIC', channel, f'{get_mode_nick(channel)} sets the topic of {channel} to: {line.params[1]}'
  516. elif line.command == ircstates.numerics.RPL_TOPIC:
  517. channel = line.params[1]
  518. yield 'TOPIC', channel, f'Topic of {channel}: {line.params[2]}'
  519. elif line.command == ircstates.numerics.RPL_TOPICWHOTIME:
  520. date = datetime.datetime.utcfromtimestamp(int(line.params[3])).replace(tzinfo = datetime.timezone.utc)
  521. yield 'TOPICWHO', line.params[1], f'Topic set by {irctokens.hostmask(line.params[2]).nickname} at {date:%Y-%m-%d %H:%M:%SZ}'
  522. elif line.command == ircstates.numerics.RPL_ENDOFNAMES:
  523. channel = line.params[1]
  524. users = self.server.channels[self.server.casefold(channel)].users
  525. yield 'NAMES', channel, f'Currently in {channel}: {", ".join(self.render_nick_with_mode(u, u.nickname) for u in users.values())}'
  526. def render_whox(self):
  527. users = []
  528. for nickname, account in self.whoxReply:
  529. accountStr = f' ({account})' if account is not None else ''
  530. users.append(f'{self.render_nick_with_mode(self.server.channels[self.server.casefold(self.whoxChannel)].users.get(self.server.casefold(nickname)), nickname)}{accountStr}')
  531. return f'Currently in {self.whoxChannel}: {", ".join(users)}'
  532. async def quit(self):
  533. # 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.
  534. self.logger.info('Quitting')
  535. self.lastSentTime = 1.67e34 * math.pi * 1e7 # Disable sending any further messages in send_queue
  536. self._direct_send(b'QUIT :Bye')
  537. await asyncio.wait({self.connectionClosedEvent.wait()}, timeout = 10)
  538. if not self.connectionClosedEvent.is_set():
  539. self.logger.error('Quitting cleanly did not work, closing connection forcefully')
  540. # Event will be set implicitly in connection_lost.
  541. self.transport.close()
  542. def connection_lost(self, exc):
  543. time_ = time.time()
  544. self.logger.info('IRC connection lost')
  545. self.connected = False
  546. self.connectionClosedEvent.set()
  547. self.messageQueue.put_nowait((time_, b'- Connection closed.', None, None))
  548. for channel in self.channels:
  549. self.messageQueue.put_nowait((time_, 'Connection closed.', 'CONNCLOSED', channel))
  550. class IRCClient:
  551. logger = logging.getLogger('irclog.IRCClient')
  552. def __init__(self, messageQueue, config):
  553. self.messageQueue = messageQueue
  554. self.config = config
  555. self.channels = {channel['ircchannel'] for channel in config['channels'].values() if channel['active']}
  556. self._transport = None
  557. self._protocol = None
  558. def update_config(self, config):
  559. needReconnect = self.config['irc'] != config['irc']
  560. self.config = config
  561. if self._transport: # if currently connected:
  562. if needReconnect:
  563. self._transport.close()
  564. else:
  565. self.channels = {channel['ircchannel'] for channel in config['channels'].values() if channel['active']}
  566. self._protocol.update_channels(self.channels)
  567. def _get_ssl_context(self):
  568. ctx = SSL_CONTEXTS[self.config['irc']['ssl']]
  569. if self.config['irc']['certfile'] and self.config['irc']['certkeyfile']:
  570. if ctx is True:
  571. ctx = ssl.create_default_context()
  572. if isinstance(ctx, ssl.SSLContext):
  573. ctx.load_cert_chain(self.config['irc']['certfile'], keyfile = self.config['irc']['certkeyfile'])
  574. return ctx
  575. async def run(self, loop, sigintEvent):
  576. connectionClosedEvent = asyncio.Event()
  577. while True:
  578. connectionClosedEvent.clear()
  579. try:
  580. self.logger.debug('Creating IRC connection')
  581. self._transport, self._protocol = await loop.create_connection(
  582. protocol_factory = lambda: IRCClientProtocol(self.messageQueue, connectionClosedEvent, loop, self.config, self.channels),
  583. host = self.config['irc']['host'],
  584. port = self.config['irc']['port'],
  585. ssl = self._get_ssl_context(),
  586. )
  587. self.logger.debug('Starting send queue processing')
  588. asyncio.create_task(self._protocol.send_queue()) # Quits automatically on connectionClosedEvent
  589. self.logger.debug('Waiting for connection closure or SIGINT')
  590. try:
  591. await asyncio.wait((connectionClosedEvent.wait(), sigintEvent.wait()), return_when = asyncio.FIRST_COMPLETED)
  592. finally:
  593. self.logger.debug(f'Got connection closed {connectionClosedEvent.is_set()} / SIGINT {sigintEvent.is_set()}')
  594. if not connectionClosedEvent.is_set():
  595. self.logger.debug('Quitting connection')
  596. await self._protocol.quit()
  597. except (ConnectionRefusedError, ssl.SSLError, asyncio.TimeoutError) as e:
  598. self.logger.error(str(e))
  599. await asyncio.wait({sigintEvent.wait()}, timeout = 5)
  600. if sigintEvent.is_set():
  601. self.logger.debug('Got SIGINT, putting EOF and breaking')
  602. self.messageQueue.put_nowait(messageEOF)
  603. break
  604. class Storage:
  605. logger = logging.getLogger('irclog.Storage')
  606. def __init__(self, messageQueue, config):
  607. self.messageQueue = messageQueue
  608. self.config = config
  609. self.paths = {} # channel -> path from channels config
  610. self.files = {} # channel|None -> (filename, fileobj); None = general raw log
  611. def update_config(self, config):
  612. channelsOld = {channel['ircchannel'] for channel in self.config['channels'].values()}
  613. channelsNew = {channel['ircchannel'] for channel in config['channels'].values()}
  614. channelsRemoved = channelsOld - channelsNew
  615. self.config = config
  616. self.paths = {channel['ircchannel']: channel['path'] for channel in self.config['channels'].values()}
  617. # Since the PART messages will still arrive for the removed channels, only close those files after a little while.
  618. asyncio.create_task(self.delayed_close_files(channelsRemoved))
  619. async def delayed_close_files(self, channelsRemoved):
  620. await asyncio.sleep(10)
  621. for channel in channelsRemoved:
  622. if channel in self.files:
  623. self.logger.debug(f'Closing file for {channel!r}')
  624. self.files[channel][1].close()
  625. del self.files[channel]
  626. def ensure_file_open(self, time_, channel):
  627. fn = f'{get_month_str(time_)}.log'
  628. if channel in self.files and fn == self.files[channel][0]:
  629. return
  630. if channel in self.files:
  631. self.logger.debug(f'Closing file for {channel!r}')
  632. self.files[channel][1].close()
  633. dn = self.paths[channel] if channel is not None else 'general'
  634. mode = 'a' if channel is not None else 'ab'
  635. fpath = os.path.join(self.config['storage']['path'], dn, fn)
  636. self.logger.debug(f'Opening file {fpath!r} for {channel!r} with mode {mode!r}')
  637. os.makedirs(os.path.join(self.config['storage']['path'], dn), exist_ok = True)
  638. self.files[channel] = (fn, open(fpath, mode))
  639. async def run(self, loop, sigintEvent):
  640. self.update_config(self.config) # Ensure that files are open etc.
  641. flushExitEvent = asyncio.Event()
  642. storageTask = asyncio.create_task(self.store_messages(sigintEvent))
  643. flushTask = asyncio.create_task(self.flush_files(flushExitEvent))
  644. await sigintEvent.wait()
  645. self.logger.debug('Got SIGINT, waiting for remaining messages to be stored')
  646. await storageTask # Wait until everything's stored
  647. flushExitEvent.set()
  648. self.logger.debug('Waiting for flush task')
  649. await flushTask
  650. self.close()
  651. async def store_messages(self, sigintEvent):
  652. while True:
  653. self.logger.debug('Waiting for message')
  654. res = await self.messageQueue.get()
  655. self.logger.debug(f'Got {res!r} from message queue')
  656. if res is messageEOF:
  657. self.logger.debug('Message EOF, breaking store_messages loop')
  658. break
  659. self.store_message(*res)
  660. def store_message(self, time_, message, command, channel):
  661. # Sanity check
  662. 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):
  663. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  664. return
  665. elif channel is not None and (not isinstance(message, str) or command is None):
  666. self.logger.warning(f'Dropping invalid store_message arguments: {time_}, {message!r}, {command!r}, {channel!r}')
  667. return
  668. self.logger.debug(f'Logging {message!r} ({command}) at {time_} for {channel!r}')
  669. self.ensure_file_open(time_, channel)
  670. if channel is None:
  671. self.files[None][1].write(str(time_).encode('ascii') + b' ' + message + b'\n')
  672. else:
  673. self.files[channel][1].write(f'{time_} {command} {message}\n')
  674. async def flush_files(self, flushExitEvent):
  675. while True:
  676. await asyncio.wait({flushExitEvent.wait()}, timeout = self.config['storage']['flushTime'])
  677. self.logger.debug('Flushing files')
  678. for _, f in self.files.values():
  679. f.flush()
  680. self.logger.debug('Flushing done')
  681. if flushExitEvent.is_set():
  682. break
  683. self.logger.debug('Exiting flush_files')
  684. def close(self):
  685. for _, f in self.files.values():
  686. f.close()
  687. self.files = {}
  688. class WebServer:
  689. logger = logging.getLogger('irclog.WebServer')
  690. logStyleTag = '<style>' + " ".join([
  691. 'tr:target { background-color: yellow; }',
  692. 'tr.command_JOIN { color: green; }',
  693. 'tr.command_QUIT, tr.command_PART, tr.command_KICK, tr.command_CONNCLOSED { color: red; }',
  694. 'tr.command_NAMES { display: none; }',
  695. 'tr.command_NICK, tr.command_ACCOUNT, tr.command_MODE, tr.command_TOPIC, tr.command_TOPICWHO, tr.command_WHOX { color: grey; }'
  696. ]) + '</style>'
  697. def __init__(self, config):
  698. self.config = config
  699. self._paths = {} # '/path' => ('#channel', auth, hidden, extrasearchpaths) where auth is either False (no authentication) or the HTTP header value for basic auth
  700. self._app = aiohttp.web.Application()
  701. self._app.add_routes([
  702. aiohttp.web.get('/', self.get_homepage),
  703. aiohttp.web.get(r'/{path:[^/]+}/{date:\d{4}-\d{2}-\d{2}}', functools.partial(self._channel_handler, handler = self.get_log)),
  704. aiohttp.web.get(r'/{path:[^/]+}/{date:today}', functools.partial(self._channel_handler, handler = self.get_log)),
  705. aiohttp.web.get('/{path:[^/]+}/search', functools.partial(self._channel_handler, handler = self.search)),
  706. ])
  707. self.update_config(config)
  708. self._configChanged = asyncio.Event()
  709. def update_config(self, config):
  710. self._paths = {channel['path']: (
  711. channel['ircchannel'],
  712. f'Basic {base64.b64encode(channel["auth"].encode("utf-8")).decode("utf-8")}' if channel['auth'] else False,
  713. channel['hidden'],
  714. [config['channels'][otherchannel]['path'] for otherchannel in channel['extrasearchchannels']]
  715. ) for channel in config['channels'].values()}
  716. 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
  717. self.config = config
  718. if needRebind:
  719. self._configChanged.set()
  720. async def run(self, stopEvent):
  721. while True:
  722. runner = aiohttp.web.AppRunner(self._app)
  723. await runner.setup()
  724. site = aiohttp.web.TCPSite(runner, self.config['web']['host'], self.config['web']['port'])
  725. await site.start()
  726. await asyncio.wait((stopEvent.wait(), self._configChanged.wait()), return_when = asyncio.FIRST_COMPLETED)
  727. await runner.cleanup()
  728. if stopEvent.is_set():
  729. break
  730. self._configChanged.clear()
  731. async def _check_valid_channel(self, request):
  732. if request.match_info['path'] not in self._paths:
  733. self.logger.info(f'Bad request {id(request)}: no path {request.path!r}')
  734. raise aiohttp.web.HTTPNotFound()
  735. async def _check_auth(self, request):
  736. auth = self._paths[request.match_info['path']][1]
  737. if auth:
  738. authHeader = request.headers.get('Authorization')
  739. if not authHeader or authHeader != auth:
  740. self.logger.info(f'Bad request {id(request)}: authentication failed: {authHeader!r} != {auth}')
  741. raise aiohttp.web.HTTPUnauthorized(headers = {'WWW-Authenticate': f'Basic, realm="{request.match_info["path"]}"'})
  742. async def _channel_handler(self, request, handler):
  743. await self._check_valid_channel(request)
  744. await self._check_auth(request)
  745. return (await handler(request))
  746. async def get_homepage(self, request):
  747. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  748. lines = []
  749. for path, (channel, auth, hidden, extrasearchpaths) in self._paths.items():
  750. if hidden:
  751. continue
  752. 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>)')
  753. 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')
  754. def _file_iter_with_path(self, fn, path):
  755. # Open fn, iterate over its lines yielding (path, line) tuples
  756. with open(fn, 'r') as fp:
  757. for line in fp:
  758. yield (path, line)
  759. def _stdout_with_path(self, stdout):
  760. # Process grep output with --with-filenames, --null, and --line-number into (path, line) tuples; this blindly assumes the expected directory structure of '.../path/YYYY-MM.log'.
  761. # Lines are sorted by timestamp, filename, and line number to ensure a consistent and chronological order.
  762. out = []
  763. for line in stdout.decode('utf-8').splitlines():
  764. fn, line = line.split('\0', 1)
  765. _, path, _ = fn.rsplit('/', 2)
  766. ln, line = line.split(':', 1)
  767. ln = int(ln)
  768. ts = float(line.split(' ', 1)[0])
  769. out.append((ts, fn, ln, path, line))
  770. yield from (x[3:] for x in sorted(out, key = lambda y: y[0:3]))
  771. def _raw_to_lines(self, f, filter = lambda path, dt, command, content: True):
  772. # 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
  773. # filter: function taking the line fields (path: str, ts: float, command: str, content: str) and returning whether to include the line
  774. for path, line in f:
  775. ts, command, content = line.strip().split(' ', 2)
  776. ts = float(ts)
  777. if not filter(path, ts, command, content):
  778. continue
  779. yield (path, ts, command, content)
  780. def _render_log(self, lines, withDate = False):
  781. # lines: iterable of (path: str, timestamp: float, command: str, content: str)
  782. # withDate: whether to include the date with the time of the log line
  783. ret = []
  784. for path, ts, command, content in lines:
  785. d = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo = datetime.timezone.utc)
  786. date = f'{d:%Y-%m-%d }' if withDate else ''
  787. lineId = hashlib.md5(f'{ts} {command} {content}'.encode('utf-8')).hexdigest()[:8]
  788. 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>')
  789. return '<table>\n' + '\n'.join(ret) + '\n</table>'
  790. async def get_log(self, request):
  791. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  792. if request.match_info['date'] == 'today':
  793. date = datetime.datetime.now(tz = datetime.timezone.utc).replace(hour = 0, minute = 0, second = 0, microsecond = 0)
  794. else:
  795. date = datetime.datetime.strptime(request.match_info['date'], '%Y-%m-%d').replace(tzinfo = datetime.timezone.utc)
  796. dateStart = date.timestamp()
  797. dateEnd = (date + datetime.timedelta(days = 1)).timestamp()
  798. #TODO Implement this in a better way...
  799. fn = date.strftime('%Y-%m.log')
  800. 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))
  801. return aiohttp.web.Response(
  802. text = ''.join([
  803. '<!DOCTYPE html><html lang="en">',
  804. f'<head><title>{html.escape(self._paths[request.match_info["path"]][0])} log for {date:%Y-%m-%d}</title>{self.logStyleTag}</head>',
  805. '<body>',
  806. f'<a href="/{html.escape(request.match_info["path"])}/{(date - datetime.timedelta(days = 1)).strftime("%Y-%m-%d")}">Previous day</a> ',
  807. f'<a href="/{html.escape(request.match_info["path"])}/{(date + datetime.timedelta(days = 1)).strftime("%Y-%m-%d")}">Next day</a>',
  808. '<br /><br />',
  809. self._render_log(lines),
  810. '</body>',
  811. '</html>',
  812. ]),
  813. content_type = 'text/html'
  814. )
  815. async def search(self, request):
  816. self.logger.info(f'Received request {id(request)} from {request.remote!r} for {request.path!r}')
  817. if self._paths[request.match_info['path']][2]: # Hidden channels aren't searchable
  818. return aiohttp.web.HTTPNotFound()
  819. if 'q' not in request.query:
  820. return aiohttp.web.Response(
  821. text = ''.join([
  822. '<!DOCTYPE html><html lang="en">'
  823. f'<head><title>{html.escape(self._paths[request.match_info["path"]][0])} search</title></head>',
  824. '<body>',
  825. '<form>',
  826. '<input name="q" />',
  827. '<input type="submit" value="Search!" />',
  828. '</form>',
  829. '</body>',
  830. '</html>'
  831. ]),
  832. content_type = 'text/html'
  833. )
  834. cmd = ['grep', '--fixed-strings', '--recursive', '--with-filename', '--null', '--line-number', request.query['q']]
  835. for path in itertools.chain((request.match_info['path'],), self._paths[request.match_info['path']][3]):
  836. cmd.append(os.path.join(self.config['storage']['path'], path, ''))
  837. proc = await asyncio.create_subprocess_exec(*cmd, stdout = asyncio.subprocess.PIPE)
  838. #TODO Limit size and runtime
  839. stdout, _ = await proc.communicate()
  840. lines = self._raw_to_lines(self._stdout_with_path(stdout))
  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])} search results for "{html.escape(request.query["q"])}"</title>{self.logStyleTag}</head>',
  845. '<body>',
  846. self._render_log(lines, withDate = True),
  847. '</body>',
  848. '</html>'
  849. ]),
  850. content_type = 'text/html'
  851. )
  852. def configure_logging(config):
  853. #TODO: Replace with logging.basicConfig(..., force = True) (Py 3.8+)
  854. root = logging.getLogger()
  855. root.setLevel(getattr(logging, config['logging']['level']))
  856. root.handlers = [] #FIXME: Undocumented attribute of logging.Logger
  857. formatter = logging.Formatter(config['logging']['format'], style = '{')
  858. stderrHandler = logging.StreamHandler()
  859. stderrHandler.setFormatter(formatter)
  860. root.addHandler(stderrHandler)
  861. async def main():
  862. if len(sys.argv) != 2:
  863. print('Usage: irclog.py CONFIGFILE', file = sys.stderr)
  864. sys.exit(1)
  865. configFile = sys.argv[1]
  866. config = Config(configFile)
  867. configure_logging(config)
  868. loop = asyncio.get_running_loop()
  869. messageQueue = asyncio.Queue()
  870. # tuple(time: float, message: bytes or str, command: str or None, channel: str or None)
  871. # command is an identifier of the type of message.
  872. # 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.
  873. # The queue can also contain messageEOF, which signals to the storage layer to stop logging.
  874. irc = IRCClient(messageQueue, config)
  875. webserver = WebServer(config)
  876. storage = Storage(messageQueue, config)
  877. sigintEvent = asyncio.Event()
  878. def sigint_callback():
  879. global logger
  880. nonlocal sigintEvent
  881. logger.info('Got SIGINT, stopping')
  882. sigintEvent.set()
  883. loop.add_signal_handler(signal.SIGINT, sigint_callback)
  884. def sigusr1_callback():
  885. global logger
  886. nonlocal config, irc, webserver, storage
  887. logger.info('Got SIGUSR1, reloading config')
  888. try:
  889. newConfig = config.reread()
  890. except InvalidConfig as e:
  891. logger.error(f'Config reload failed: {e!s} (old config remains active)')
  892. return
  893. config = newConfig
  894. configure_logging(config)
  895. irc.update_config(config)
  896. webserver.update_config(config)
  897. storage.update_config(config)
  898. loop.add_signal_handler(signal.SIGUSR1, sigusr1_callback)
  899. await asyncio.gather(irc.run(loop, sigintEvent), webserver.run(sigintEvent), storage.run(loop, sigintEvent))
  900. if __name__ == '__main__':
  901. asyncio.run(main())