]> jfr.im git - erebus.git/blobdiff - bot.py
admin_config - add !getconfig, remove some unused functions
[erebus.git] / bot.py
diff --git a/bot.py b/bot.py
index 3ce39474d39452f673493faacfe35a72450bb3be..fd9292295aa3d2051d729d8e8e6a6e1b5b73b8a2 100644 (file)
--- a/bot.py
+++ b/bot.py
@@ -4,7 +4,7 @@
 # Erebus IRC bot - Author: John Runyon
 # "Bot" and "BotConnection" classes (handling a specific "arm")
 
-import os, random, socket, struct, sys, threading, time, traceback
+import os, random, socket, struct, sys, threading, time, traceback, fcntl
 from collections import deque
 
 if sys.version_info.major < 3:
@@ -27,6 +27,8 @@ else:
 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
 class Bot(object):
        def __init__(self, parent, nick, user, bind, authname, authpass, server, port, realname):
+               self.maxlen = 510
+
                self.parent = parent
                self.nick = nick
                self.permnick = nick
@@ -69,6 +71,7 @@ class Bot(object):
        def watchdog(self):
                if time.time() > int(self.parent.cfg.get('watchdog', 'maxtime', default=300))+self.lastreceived:
                        self.parse("ERROR :Fake-error from watchdog timer.")
+                       return
                if self.conn.registered():
                        self.conn.send("PING :%s" % (time.time()))
                        self._checknick()
@@ -97,8 +100,6 @@ class Bot(object):
                        self.conn.send("NICK %s" % (self.permnick))
 
        def parse(self, line):
-               if self.parent.cfg.getboolean('debug', 'io'):
-                       self.log('I', line)
                pieces = line.split()
 
                if pieces[0][0] == ":":
@@ -118,6 +119,7 @@ class Bot(object):
                        '354': self._got354, #WHO
                        '396': self._gotHiddenHost, # hidden host has been set
                        '433': self._got433, #nick in use
+                       '437': self._got433, #nick protected
                        'JOIN': self._gotjoin,
                        'PART': self._gotpart,
                        'KICK': self._gotkick,
@@ -237,15 +239,24 @@ class Bot(object):
                if nick == self.nick:
                        self.conn.send("WHO %s c%%cant,3" % (chan))
                else:
-                       user = self.parent.user(nick, justjoined=True)
+                       user = self.parent.user(nick, send_who=True)
                        chan.userjoin(user)
                        user.join(chan)
        def _clientLeft(self, nick, chan):
-               if nick != self.nick:
-                       gone = self.parent.user(nick).part(chan)
-                       chan.userpart(self.parent.user(nick))
+               if nick == self.nick:
+                       for u in chan.users:
+                               if u.nick != self.nick:
+                                       self._clientLeft(u.nick, chan)
+                       if chan.deleting:
+                               chan.bot.chans.remove(chan)
+                               del self.parent.chans[chan.name.lower()]
+                               del chan
+               else:
+                       user = self.parent.user(nick)
+                       gone = user.part(chan)
+                       chan.userpart(user)
                        if gone:
-                               self.parent.user(nick).quit()
+                               user.quit()
                                del self.parent.users[nick.lower()]
        def _gotpart(self, pieces):
                nick = pieces[0].split('!')[0][1:]
@@ -321,12 +332,20 @@ class Bot(object):
                if len(msg) == 0:
                        return
 
-               if target == self.nick:
-                       if msg.startswith("\001"): #ctcp
-                               msg = msg.strip("\001")
-                               if msg == "VERSION":
-                                       self.msg(user, "\001VERSION Erebus v%d.%d - http://jfr.im/git/erebus.git" % (self.parent.APIVERSION, self.parent.RELEASE))
-                               return
+               if target == self.nick and msg.startswith("\001"): #ctcp
+                       msg = msg.strip("\001")
+                       if msg:
+                               pieces = msg.split()
+                               if pieces[0] == "CLIENTINFO":
+                                       self.msg(user, "\001CLIENTINFO VERSION PING\001")
+                               elif pieces[0] == "VERSION":
+                                       self.msg(user, "\001VERSION Erebus v%d.%d - http://jfr.im/git/erebus.git\001" % (self.parent.APIVERSION, self.parent.RELEASE))
+                               elif pieces[0] == "PING":
+                                       if len(pieces) > 1:
+                                               self.msg(user, "\001PING %s\001" % (' '.join(pieces[1:])))
+                                       else:
+                                               self.msg(user, "\001PING\001")
+                       return
 
                triggerused = msg.startswith(self.parent.trigger)
                if triggerused: msg = msg[len(self.parent.trigger):]
@@ -420,15 +439,9 @@ class Bot(object):
                if self.parent.cfg.getboolean('erebus', 'nofakelag'): append_callback = self.conn.send
 
                cmd = self._formatmsg(target, msg, msgtype)
-               # The max length is much shorter than recvq (510) because of the length the server adds on about the source (us).
+               # The max length is much shorter than conn.maxlen (510) because of the length the server adds on about the source (us).
                # If you know your hostmask, you can of course figure the exact length, but it's very difficult to reliably know your hostmask.
-               maxlen = (
-                       self.conn.recvq
-                       - 63 # max hostname len
-                       - 11 # max ident len
-                       - 3  # the symbols in :nick!user@host
-                       - len(self.nick)
-               )
+               maxlen = self.maxmsglen()
                if len(cmd) > maxlen:
                        if not truncate:
                                return False
@@ -504,6 +517,15 @@ class Bot(object):
        def quit(self, reason="Shutdown"):
                self.conn.send("QUIT :%s" % (reason))
 
+       def maxmsglen(self):
+               return (
+                       self.maxlen
+                       - 63 # max hostname len
+                       - 11 # max ident len
+                       - 3  # the symbols in :nick!user@host
+                       - len(self.nick)
+               )
+
        def __str__(self): return self.nick
        def __repr__(self): return "<Bot %r>" % (self.nick)
 
@@ -520,7 +542,7 @@ class BotConnection(object):
                self.state = 0 # 0=disconnected, 1=registering, 2=connected
 
                self.bytessent = 0
-               self.recvq = 510
+               self.recvq = 510 # How much we can send per period
                self.exceeded = False
                self._nowrite = False
 
@@ -536,17 +558,23 @@ class BotConnection(object):
                self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 0, 0))
                self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                self.socket.bind((self.bind, 0))
+               self._write_oidentd()
                self.socket.connect((self.server, self.port))
                return True
        def register(self):
                if self.state == 0:
+                       pss = self.parent.parent.cfg.get('erebus', 'pass')
+                       if pss:
+                               self.send("PASS %s" % (pss))
                        self.send("NICK %s" % (self.parent.nick))
                        self.send("USER %s 0 * :%s" % (self.parent.user, self.parent.realname))
                        self.state = 1
                return True
 
        def registered(self, done=False):
-               if done: self.state = 2
+               if done:
+                       self.state = 2
+                       self._unwrite_oidentd()
                return self.state == 2
 
        def send(self, line):
@@ -564,7 +592,7 @@ class BotConnection(object):
                                self.parent.log('X', line)
 
        def _write(self, line):
-               self.socket.sendall(line.encode('utf-8', 'backslashreplace')+b"\r\n")
+               self.socket.sendall(line.encode('utf-8', 'surrogateescape')+b"\r\n")
 
        def _getsockerr(self):
                try: # SO_ERROR might not exist on all platforms
@@ -586,5 +614,33 @@ class BotConnection(object):
 
                return lines
 
+       def _format_oidentd(self):
+               ident = self.parent.user
+               fport = self.parent.port
+               from_ = self.bind
+               lport = self.socket.getsockname()[1]
+               if from_:
+                       return 'fport %s from %s lport %s { reply "%s" }\n' % (fport, from_, lport, ident)
+               else:
+                       return 'fport %s lport %s { reply "%s" }\n' % (fport, lport, ident)
+       def _write_oidentd(self):
+               path = self.parent.parent.cfg.get('erebus', 'oidentd_path')
+               if path is not None:
+                       with open(path, 'a') as fh:
+                               fcntl.lockf(fh, fcntl.LOCK_EX)
+                               fh.write(self._format_oidentd())
+                               fcntl.lockf(fh, fcntl.LOCK_UN)
+       def _unwrite_oidentd(self):
+               path = self.parent.parent.cfg.get('erebus', 'oidentd_path')
+               if path is not None:
+                       with open(path, 'r+') as fh:
+                               fcntl.lockf(fh, fcntl.LOCK_EX)
+                               data = fh.read()
+                               newdata = data.replace(self._format_oidentd(), '')
+                               fh.seek(0)
+                               fh.write(newdata)
+                               fh.truncate()
+                               fcntl.lockf(fh, fcntl.LOCK_UN)
+
        def __str__(self): return self.parent.nick
        def __repr__(self): return "<BotConnection %r (%r)>" % (self.socket.fileno(), self.parent.nick)