2015-03-19 20:55:18 +01:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
import imp
|
|
|
|
import os
|
2015-04-03 09:17:03 +02:00
|
|
|
import socket
|
2015-04-03 21:35:55 +02:00
|
|
|
import time
|
2015-04-25 07:37:07 +02:00
|
|
|
import sys
|
2015-06-24 04:29:53 +02:00
|
|
|
from collections import defaultdict
|
2015-07-10 03:29:00 +02:00
|
|
|
import threading
|
2015-07-18 01:09:50 +02:00
|
|
|
import traceback
|
2015-04-25 07:37:07 +02:00
|
|
|
|
2015-07-05 22:22:17 +02:00
|
|
|
from log import log
|
2015-07-06 04:19:49 +02:00
|
|
|
import conf
|
2015-06-24 04:29:53 +02:00
|
|
|
import classes
|
2015-07-10 03:29:00 +02:00
|
|
|
import utils
|
2015-07-17 06:30:25 +02:00
|
|
|
import coreplugin
|
2015-03-19 20:55:18 +01:00
|
|
|
|
2015-04-18 04:55:48 +02:00
|
|
|
class Irc():
|
2015-07-18 01:55:44 +02:00
|
|
|
|
|
|
|
def initVars(self):
|
2015-07-05 08:12:00 +02:00
|
|
|
# Server, channel, and user indexes to be populated by our protocol module
|
2015-05-31 07:15:19 +02:00
|
|
|
self.servers = {}
|
2015-07-05 08:12:00 +02:00
|
|
|
self.users = {}
|
|
|
|
self.channels = defaultdict(classes.IrcChannel)
|
|
|
|
# Sets flags such as whether to use halfops, etc. The default RFC1459
|
|
|
|
# modes are implied.
|
|
|
|
self.cmodes = {'op': 'o', 'secret': 's', 'private': 'p',
|
|
|
|
'noextmsg': 'n', 'moderated': 'm', 'inviteonly': 'i',
|
|
|
|
'topiclock': 't', 'limit': 'l', 'ban': 'b',
|
2015-07-06 04:19:49 +02:00
|
|
|
'voice': 'v', 'key': 'k',
|
|
|
|
# Type A, B, and C modes
|
|
|
|
'*A': 'b',
|
|
|
|
'*B': 'k',
|
|
|
|
'*C': 'l',
|
|
|
|
'*D': 'imnpstr'}
|
2015-07-05 08:12:00 +02:00
|
|
|
self.umodes = {'invisible': 'i', 'snomask': 's', 'wallops': 'w',
|
2015-07-06 04:19:49 +02:00
|
|
|
'oper': 'o',
|
|
|
|
'*A': '', '*B': '', '*C': 's', '*D': 'iow'}
|
2015-07-15 23:00:40 +02:00
|
|
|
# This nicklen value is only a default, and SHOULD be set by the
|
|
|
|
# protocol module as soon as the relevant capability information is
|
|
|
|
# received from the uplink. Plugins that depend on maxnicklen being
|
|
|
|
# set MUST call "irc.connected.wait()", which blocks until the
|
|
|
|
# capability information is received. This handling of irc.connected
|
|
|
|
# is also dependent on the protocol module.
|
2015-07-05 08:12:00 +02:00
|
|
|
self.maxnicklen = 30
|
2015-07-06 04:19:49 +02:00
|
|
|
self.prefixmodes = 'ov'
|
2015-07-17 22:39:57 +02:00
|
|
|
# Uplink SID (filled in by protocol module)
|
|
|
|
self.uplink = None
|
2015-04-03 09:17:03 +02:00
|
|
|
|
2015-07-18 01:55:44 +02:00
|
|
|
def __init__(self, netname, proto, conf):
|
|
|
|
# Initialize some variables
|
|
|
|
self.connected = threading.Event()
|
|
|
|
self.name = netname.lower()
|
|
|
|
self.conf = conf
|
|
|
|
|
|
|
|
self.initVars()
|
|
|
|
|
2015-07-10 03:29:00 +02:00
|
|
|
self.serverdata = conf['servers'][netname]
|
2015-07-06 04:19:49 +02:00
|
|
|
self.sid = self.serverdata["sid"]
|
2015-07-08 22:54:45 +02:00
|
|
|
self.botdata = conf['bot']
|
2015-07-06 04:19:49 +02:00
|
|
|
self.proto = proto
|
2015-07-17 22:39:57 +02:00
|
|
|
self.pingfreq = self.serverdata.get('pingfreq') or 10
|
|
|
|
self.pingtimeout = self.pingfreq * 2
|
|
|
|
|
2015-07-17 04:34:05 +02:00
|
|
|
self.connection_thread = threading.Thread(target = self.connect)
|
|
|
|
self.connection_thread.start()
|
2015-07-17 22:39:57 +02:00
|
|
|
self.pingTimer = None
|
|
|
|
self.lastping = time.time()
|
2015-07-06 04:19:49 +02:00
|
|
|
|
|
|
|
def connect(self):
|
2015-04-03 09:17:03 +02:00
|
|
|
ip = self.serverdata["ip"]
|
|
|
|
port = self.serverdata["port"]
|
2015-07-17 23:37:07 +02:00
|
|
|
while True:
|
|
|
|
log.info("Connecting to network %r on %s:%s", self.name, ip, port)
|
|
|
|
try:
|
|
|
|
# Initial connection timeout is a lot smaller than the timeout after
|
|
|
|
# we've connected; this is intentional.
|
|
|
|
self.socket = socket.create_connection((ip, port), timeout=1)
|
|
|
|
self.socket.setblocking(0)
|
|
|
|
self.socket.settimeout(self.pingtimeout)
|
|
|
|
self.proto.connect(self)
|
|
|
|
self.spawnMain()
|
|
|
|
self.schedulePing()
|
|
|
|
self.run()
|
|
|
|
except (socket.error, classes.ProtocolError, ConnectionError) as e:
|
2015-07-18 00:08:24 +02:00
|
|
|
log.warning('(%s) Disconnected from IRC: %s: %s',
|
2015-07-17 23:37:07 +02:00
|
|
|
self.name, type(e).__name__, str(e))
|
2015-07-18 01:55:44 +02:00
|
|
|
self.disconnect()
|
2015-07-18 01:01:51 +02:00
|
|
|
autoconnect = self.serverdata.get('autoconnect')
|
|
|
|
log.debug('(%s) Autoconnect delay set to %s seconds.', self.name, autoconnect)
|
|
|
|
if autoconnect is not None and autoconnect >= 0:
|
|
|
|
log.info('(%s) Going to auto-reconnect in %s seconds.', self.name, autoconnect)
|
|
|
|
time.sleep(autoconnect)
|
|
|
|
else:
|
|
|
|
return
|
2015-07-17 23:37:07 +02:00
|
|
|
|
2015-07-10 03:29:00 +02:00
|
|
|
|
|
|
|
def disconnect(self):
|
2015-07-17 22:39:57 +02:00
|
|
|
log.debug('(%s) Canceling pingTimer at %s due to disconnect() call', self.name, time.time())
|
2015-07-15 22:49:12 +02:00
|
|
|
self.connected.clear()
|
2015-07-17 04:34:05 +02:00
|
|
|
try:
|
|
|
|
self.socket.close()
|
2015-07-17 22:39:57 +02:00
|
|
|
self.pingTimer.cancel()
|
2015-07-17 04:34:05 +02:00
|
|
|
except: # Socket timed out during creation; ignore
|
|
|
|
pass
|
2015-07-18 01:55:44 +02:00
|
|
|
self.callHooks([None, 'PYLINK_DISCONNECT', {}])
|
|
|
|
# Reset all our variables - this is important!
|
|
|
|
self.initVars()
|
2015-04-03 09:17:03 +02:00
|
|
|
|
2015-04-03 21:35:55 +02:00
|
|
|
def run(self):
|
2015-04-18 07:11:49 +02:00
|
|
|
buf = ""
|
|
|
|
data = ""
|
2015-07-17 22:39:57 +02:00
|
|
|
while (time.time() - self.lastping) < self.pingtimeout:
|
|
|
|
log.debug('(%s) time_since_last_ping: %s', self.name, (time.time() - self.lastping))
|
|
|
|
log.debug('(%s) self.pingtimeout: %s', self.name, self.pingtimeout)
|
2015-07-18 00:08:24 +02:00
|
|
|
data = self.socket.recv(2048).decode("utf-8")
|
|
|
|
buf += data
|
2015-07-18 01:20:41 +02:00
|
|
|
if self.connected and not data:
|
2015-07-18 01:55:44 +02:00
|
|
|
log.warn('(%s) No data received and self.connected is not set; disconnecting!', self.name)
|
2015-07-15 22:49:12 +02:00
|
|
|
break
|
2015-07-18 00:08:24 +02:00
|
|
|
while '\n' in buf:
|
|
|
|
line, buf = buf.split('\n', 1)
|
|
|
|
log.debug("(%s) <- %s", self.name, line)
|
2015-07-18 01:09:50 +02:00
|
|
|
hook_args = self.proto.handle_events(self, line)
|
|
|
|
# Only call our hooks if there's data to process. Handlers that support
|
|
|
|
# hooks will return a dict of parsed arguments, which can be passed on
|
|
|
|
# to plugins and the like. For example, the JOIN handler will return
|
|
|
|
# something like: {'channel': '#whatever', 'users': ['UID1', 'UID2',
|
|
|
|
# 'UID3']}, etc.
|
|
|
|
if hook_args is not None:
|
|
|
|
self.callHooks(hook_args)
|
|
|
|
|
|
|
|
def callHooks(self, hook_args):
|
|
|
|
numeric, command, parsed_args = hook_args
|
|
|
|
# Always make sure TS is sent.
|
|
|
|
if 'ts' not in parsed_args:
|
|
|
|
parsed_args['ts'] = int(time.time())
|
|
|
|
hook_cmd = command
|
|
|
|
hook_map = self.proto.hook_map
|
|
|
|
if command in hook_map:
|
|
|
|
hook_cmd = hook_map[command]
|
|
|
|
log.debug('Parsed args %r received from %s handler (calling hook %s)', parsed_args, command, hook_cmd)
|
|
|
|
# Iterate over hooked functions, catching errors accordingly
|
|
|
|
for hook_func in utils.command_hooks[hook_cmd]:
|
|
|
|
try:
|
|
|
|
log.debug('Calling function %s', hook_func)
|
|
|
|
hook_func(self, numeric, command, parsed_args)
|
|
|
|
except Exception:
|
|
|
|
# We don't want plugins to crash our servers...
|
|
|
|
traceback.print_exc()
|
|
|
|
continue
|
2015-04-03 09:17:03 +02:00
|
|
|
|
|
|
|
def send(self, data):
|
2015-07-10 02:25:10 +02:00
|
|
|
# Safeguard against newlines in input!! Otherwise, each line gets
|
|
|
|
# treated as a separate command, which is particularly nasty.
|
|
|
|
data = data.replace('\n', ' ')
|
2015-04-03 09:17:03 +02:00
|
|
|
data = data.encode("utf-8") + b"\n"
|
2015-07-10 03:29:00 +02:00
|
|
|
log.debug("(%s) -> %s", self.name, data.decode("utf-8").strip("\n"))
|
2015-07-17 23:37:07 +02:00
|
|
|
self.socket.send(data)
|
2015-07-17 22:39:57 +02:00
|
|
|
|
|
|
|
def schedulePing(self):
|
|
|
|
self.proto.pingServer(self)
|
|
|
|
self.pingTimer = threading.Timer(self.pingfreq, self.schedulePing)
|
|
|
|
self.pingTimer.daemon = True
|
|
|
|
self.pingTimer.start()
|
|
|
|
log.debug('(%s) Ping scheduled at %s', self.name, time.time())
|
2015-03-19 20:55:18 +01:00
|
|
|
|
2015-07-17 06:30:25 +02:00
|
|
|
def spawnMain(self):
|
|
|
|
nick = self.botdata.get('nick') or 'PyLink'
|
|
|
|
ident = self.botdata.get('ident') or 'pylink'
|
|
|
|
host = self.serverdata["hostname"]
|
|
|
|
self.pseudoclient = self.proto.spawnClient(self, nick, ident, host, modes={("o", None)})
|
|
|
|
for chan in self.serverdata['channels']:
|
|
|
|
self.proto.joinClient(self, self.pseudoclient.uid, chan)
|
|
|
|
|
2015-05-31 21:20:09 +02:00
|
|
|
if __name__ == '__main__':
|
2015-07-05 22:44:48 +02:00
|
|
|
log.info('PyLink starting...')
|
2015-07-06 04:19:49 +02:00
|
|
|
if conf.conf['login']['password'] == 'changeme':
|
2015-07-05 22:44:48 +02:00
|
|
|
log.critical("You have not set the login details correctly! Exiting...")
|
2015-06-17 05:05:41 +02:00
|
|
|
sys.exit(2)
|
|
|
|
protocols_folder = [os.path.join(os.getcwd(), 'protocols')]
|
2015-07-13 08:28:34 +02:00
|
|
|
|
|
|
|
# Import plugins first globally, because they can listen for events
|
|
|
|
# that happen before the connection phase.
|
2015-07-17 06:30:25 +02:00
|
|
|
utils.plugins.append(coreplugin)
|
2015-07-13 08:28:34 +02:00
|
|
|
to_load = conf.conf['plugins']
|
|
|
|
plugins_folder = [os.path.join(os.getcwd(), 'plugins')]
|
|
|
|
# Here, we override the module lookup and import the plugins
|
|
|
|
# dynamically depending on which were configured.
|
|
|
|
for plugin in to_load:
|
|
|
|
try:
|
|
|
|
moduleinfo = imp.find_module(plugin, plugins_folder)
|
|
|
|
pl = imp.load_source(plugin, moduleinfo[1])
|
|
|
|
utils.plugins.append(pl)
|
|
|
|
except ImportError as e:
|
|
|
|
if str(e).startswith('No module named'):
|
|
|
|
log.error('Failed to load plugin %r: the plugin could not be found.', plugin)
|
|
|
|
else:
|
|
|
|
log.error('Failed to load plugin %r: import error %s', plugin, str(e))
|
|
|
|
else:
|
|
|
|
if hasattr(pl, 'main'):
|
|
|
|
log.debug('Calling main() function of plugin %r', pl)
|
|
|
|
pl.main()
|
|
|
|
|
2015-07-10 03:29:00 +02:00
|
|
|
for network in conf.conf['servers']:
|
|
|
|
protoname = conf.conf['servers'][network]['protocol']
|
|
|
|
try:
|
|
|
|
moduleinfo = imp.find_module(protoname, protocols_folder)
|
|
|
|
proto = imp.load_source(protoname, moduleinfo[1])
|
|
|
|
except ImportError as e:
|
|
|
|
if str(e).startswith('No module named'):
|
|
|
|
log.critical('Failed to load protocol module %r: the file could not be found.', protoname)
|
|
|
|
else:
|
|
|
|
log.critical('Failed to load protocol module: import error %s', protoname, str(e))
|
|
|
|
sys.exit(2)
|
2015-06-17 05:05:41 +02:00
|
|
|
else:
|
2015-07-12 05:11:48 +02:00
|
|
|
utils.networkobjects[network] = Irc(network, proto, conf.conf)
|
2015-07-14 01:07:55 +02:00
|
|
|
utils.started.set()
|
2015-07-13 08:28:34 +02:00
|
|
|
log.info("loaded plugins: %s", utils.plugins)
|
|
|
|
|