示例#1
0
def servertick(gm,sm):
    global bot_running
    if bot_running:
        emsg = acircbot.conn.event_slice()
        if emsg:
            acserver.log(emsg,ACLOG_ERROR)
            bot_running = False
示例#2
0
def main(plugin):
    global preferred_host, download_thread
    preferred_host = findbesthost()
    
    download_thread = threading.Thread(None, target=downloadThreadFunc)
    download_thread.start()
    acserver.log("AkimboDownloader: Setting preferred host to: %s"%preferred_host)
示例#3
0
 def __init__(self, path, config_path, forcedisabled):
     self.path = path
     self.config_path = config_path
     
     conf = self.getConf()
     
     
     self.isenabled = True
     try:
         self.isenabled = (conf.get('Plugin', 'enable') == 'yes')
         self.name = conf.get('Plugin', 'name')
         self.version = conf.get('Plugin', 'version')
         self.author = conf.get('Plugin', 'author')
         deps = conf.get('Plugin', 'depends')
         if deps != "":
             self.depends = set(deps.split(','))
         else:
             self.depends = set()
     except NoOptionError:
         acserver.log(":     Invalid config for %s"%self.path,ACLOG_WARNING)
         self.isenabled = False
     del conf
     
     self.__dependname = os.path.basename(self.path)
     if forcedisabled:
         self.isenabled = False
示例#4
0
def main(plugin):
    global engine
    
    conf = plugin.getConf({'db_url':'users.db','db_user':'','db_pwd':'','db_type':'sqlite3','db_database':''})
    
    DBURL = conf.get('Settings', 'db_url')    
    DBType = conf.get('Settings', 'db_type')
    DBUser = conf.get('Settings', 'db_user')
    DBPWD = conf.get('Settings', 'db_pwd')
    DBDataBase = conf.get('Settings', 'db_database')
    
    engine = db.setup(DBType,DBURL,DBUser,DBPWD,DBDataBase)
    
    session = _getSession()
    if session.query(db.User).count() == 0:
        acserver.log("Authentication: No users exist, initalizing database.")
        
        acserver.log("Authentication: Creating root user.")
        session.add(db.makeUser("root","pyacserver",""))
        
    for perm in module_permissions:
        addPermissionIfMissing(*perm)
        
    session.commit()
        
    session.close()
示例#5
0
 def enter_event_loop(self):
     """\
     Main loop of the IRCConnection - reads from the socket and dispatches
     based on regex matching
     """
     while True:
         emsg = self.event_slice()
         if emsg:
             acserver.log(emsg, ACLOG_ERROR)
             break
示例#6
0
 def new_nick(self):
     """\
     Generates a new nickname based on original nickname followed by a
     random number
     """
     old = self.nick
     self.nick = "%s_%s" % (self.base_nick, random.randint(1, 1000))
     acserver.log("IRCBOT: Nick %s already taken, trying %s" % (old, self.nick))
     self.register_nick()
     self.handle_nick_change(old, self.nick)
示例#7
0
 def handle_registered(self, server):
     """\
     When the connection to the server is registered, send all pending
     data.
     """
     if not self._registered:
         acserver.log("IRCBOT: Registered")
         self._registered = True
         for data in self._out_buffer:
             self.send(data)
         self._out_buffer = []
示例#8
0
def servertick(gm,sm):
    try:
        msg = message_queue.get(False)
    except Queue.Empty:
        return
    
    if msg['type'] == 'log':
        acserver.log(msg['text'])
    elif msg['type'] == 'msg':
        acserver.msg(msg['text'], msg['cn'])
        
示例#9
0
 def trigger(self, eventname, args=()):
     try:
         for event in self.events[eventname]:
             try:
                 event(*args)
             except:
                 exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                 acserver.log('Uncaught exception occured in event handler.',ACLOG_ERROR)
                 for line in traceback.format_exc().split('\n'):
                     acserver.log(line,ACLOG_ERROR)
     except KeyError:
         pass
示例#10
0
def addPermissionIfMissing(session,perm,desc):
    """
        Adds a permission if it is nonexistant.
        Returns True if it got added, False if it didn't.
    """
    try:
        db.getPerm(session,perm)
        return False
    except NoResultFound:
        session.add(db.makePermission(perm,desc))
        acserver.log("Authentication: Adding permission %s"%perm)
        session.commit()
        return True
示例#11
0
    def connect(self):
        """\
        Connect to the IRC server using the nickname
        """
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self._sock.connect((self.server, self.port))
        except socket.error:
            acserver.log("IRCBOT: Unable to connect to %s on port %d" % (self.server, self.port), ACLOG_ERROR)
            return False

        self._sock.setblocking(0)
        self.register_nick()
        self.register()
        return True
示例#12
0
def serverext(cn,ext,ext_text):
    global enabled, clientHealth, nextDamage
    if ext == "enableVampire":
        if auth.hasPermission(cn, "serverOp"):
            enabled = True
            acserver.msg("\f9Vampire is enabled!")
            nextDamage = acserver.getServMillis() + damageInterval
            acserver.log("Vampire: %s enabled vampire"%auth.AuthenticatedClients[cn].name)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    if ext == "disableVampire":
        if auth.hasPermission(cn, "serverOp"):
            enabled = False
            acserver.msg("\f9Vampire is disabled!")
            acserver.log("Vampire: %s disabled vampire"%auth.AuthenticatedClients[cn].name)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
示例#13
0
def serverext(cn,ext,ext_text):
    global enabled
    if ext == "enableLava":
        if auth.hasPermission(cn, "serverOp"):
            enabled = True
            acserver.msg("\f9Lava is enabled!")
            acserver.log("LavaGame: %s enabled lava"%auth.AuthenticatedClients[cn].name)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    
    if ext == "disableLava":
        if auth.hasPermission(cn, "serverOp"):
            enabled = False
            acserver.msg("\f4Lava is disabled!",cn)
            acserver.log("LavaGame: %s disabled lava"%auth.AuthenticatedClients[cn].name)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
示例#14
0
def startIRCBot():
    global acircbot, bot_running
    
    if bot_running:
        return
        
    conn = IRCConnection(settings['host'], settings['port'], settings['nick'])
    
    acircbot = ACIRCBot(conn)
    
    bot_running = conn.connect()
    
    if bot_running:
        channels = settings.get('channels',[])
        for channel in channels:
            conn.join(channel)
    else:
        acserver.log("IRCBOT: Failed to start, disabled")
示例#15
0
def findbesthost():
    ping_re = r'round-trip min/avg/max/stddev = (?P<min>[-+]?[0-9]*\.?[0-9]+)/(?P<avg>[-+]?[0-9]*\.?[0-9]+)/(?P<max>[-+]?[0-9]*\.?[0-9]+)/(?P<stddev>[-+]?[0-9]*\.?[0-9]+) ms'
    ping_re = re.compile(ping_re)

    responses = {}
    
    acserver.log("AkimboDownloader: Checking for the best host...")
    for host in sources:
        if sys.platform == 'win32': #There is a bit different of a format for windows, and I can't get my hands on a machine to figure out everything about it and test.
            #do ping command here
            return sources[0]
        else:
            ping = subprocess.Popen(["ping", "-c1", "-s2048", host], stdout=subprocess.PIPE).stdout.read()
            m = ping_re.search(ping)
            if m != None:
                avg = m.groupdict()['avg']
                responses[host] = float(avg)

    return min(responses)
示例#16
0
def serverext(cn,ext,ext_text):
    global download_thread
    if ext == "getmap":
        if auth.hasPermission(cn, "getMap"):
            maps = ext_text.split()
            acserver.log("AkimboDownloader: Download request from user %s cn(%d), maps: %s"%(auth.AuthenticatedClients[cn].name,cn,",".join(maps)))
            acserver.msg("\f2Attempting to download: %s"%(",".join(maps)),cn)
            
            for m in maps:
                download_queue.put((m,cn))
                
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    
    if ext == "removemap":
        if auth.hasPermission(cn, "rmMap"):
            maps = ext_text.split()
            acserver.log("AkimboDownloader: Delete request from user %s cn(%d), maps: %s"%(auth.AuthenticatedClients[cn].name,cn,",".join(maps)))
            for mapname in maps:
                try:
                    os.remove(os.path.join(local_maps_path,os.path.basename(mapname)+'.cgz'))
                except OSError:
                    acserver.msg("\f3Error deleting %s."%(mapname),cn)
                    acserver.log("AkimboDownloader: Map delete failed %s, full path: %s"%(mapname,os.path.join(local_maps_path,os.path.basename(mapname))))
                    continue
                
                try:
                    os.remove(os.path.join(local_maps_path,os.path.basename(mapname)+'.cfg'))
                except OSError:
                    pass #Its totally normal not to have a cfg
                
                
                acserver.msg("\f2Map %s deleted"%(mapname),cn)
                acserver.log("AkimboDownloader: Deleted map %s"%(mapname))
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
示例#17
0
 def loadModule(self):
     if self.isenabled:
         try:
             self.module = __import__(os.path.basename(self.path))
         except:
             exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
             acserver.log('Uncaught exception occured when loading %s. Disabling plugin.'%self.name,ACLOG_ERROR)
             for line in traceback.format_exc().split('\n'):
                 acserver.log(line,ACLOG_ERROR)
             return False
             
         try:
             #Reference it first to catch it not existing. Not some sort of internal error.
             main = self.module.main 
         except AttributeError:
             acserver.log("No main function in %s"%self.path,ACLOG_WARNING)
             return False
         
         main(self) #Call the main, passing the reference to the module.
         
         return True
     else:
         return False
示例#18
0
def serverext(cn,ext,ext_text):
    if ext == 'sendirc':
        if not (auth.hasPermission(cn,'IRCOp') or auth.hasPermission(cn,'IRCController')):
            acserver.msg("\f3You don't have access to that command!",cn)
            return
            
        if len(ext_text.split()) < 2:
            acserver.msg("\f9Invalid arguments to sendirc", cn)
            return
        
        chan,msg = ext_text.split(' ',1)
        acircbot.msg(msg,channel=chan)
        acserver.log("IRCBOT: User %s cn(%d) sent messsage to %s: %s."%(auth.AuthenticatedClients[cn].name,cn, chan, msg),cn)
        
    if ext == 'startirc':
        if not auth.hasPermission(cn,'IRCController'):
            acserver.msg("\f3You don't have access to that command!",cn)
            return
            
        if bot_running:
            acserver.msg("\f3The IRC Bot is already running!",cn)
        else:
            startIRCBot()
            acserver.msg("\f1Attempted startup of IRCBot.",cn)
            acserver.log("IRCBOT: Start command issued by user %s cn(%d)."%(auth.AuthenticatedClients[cn].name,cn),cn)
    
    if ext == 'stopirc':
        if not auth.hasPermission(cn,'IRCController'):
            acserver.msg("\f3You don't have access to that command!",cn)
            return
            
        if not bot_running:
            acserver.msg("\f3The IRC Bot isn't running!",cn)
        else:
            stopIRCBot()
            acserver.msg("\f1IRC bot stopped.",cn)
            acserver.log("IRCBOT: Stop command issued by user %s cn(%d)."%(auth.AuthenticatedClients[cn].name,cn),cn)
示例#19
0
def serverext(session,cn,ext,ext_text):
    if ext == "auth":
        args = ext_text.split()
        if len(args) != 2:
            acserver.msg("\f9Invalid arguments to auth/", cn)
            return
            
        name, pwd = args

        try:
            usr = session.query(db.User).filter(db.User.name==name).one()
        except NoResultFound:
            acserver.msg("\f9Invalid login!",cn)
            return
            
        if usr.checkPassword(pwd):
            AuthenticatedClients[cn] = usr
            acserver.msg("\fJLogin Succeeded!",cn)
            acserver.log("Authenticated client (%d) %s as %s"%(cn,acserver.getClient(cn)['name'],name))
        else:
            acserver.msg("\f9Invalid login!",cn)
        
    if ext == "adduser":
        if hasPermission(cn,'addUser'):
            args = ext_text.split()
            if len(args) != 3:
                acserver.msg("\f9Invalid arguments to register", cn)
                return
        
            name, email, pwd = args
        
            usrcount = session.query(db.User).filter(db.User.name==name).count()
        
            if usrcount:
                acserver.msg("\f9User already exists!",cn)
                session.close()
                return
        
            session.add(db.makeUser(name,pwd,email))
            session.commit()
            acserver.msg("\fJCreated user! Please login now with the credentials you provided.",cn)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    
    if ext == "claimadmin":
        if hasPermission(cn,'serverOp'):
            acserver.setAdmin(cn,1)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    
    if ext == "listusers":
        if hasPermission(cn,'listUsers'):
            acserver.msg("\fHUser List:",cn)
            for usr in session.query(db.User).all():
                if usr.id == AuthenticatedClients[cn].id:
                    acserver.msg("%d) \fQ%s \f5- \fI%s \f5: {\fN%s\f5}"%(usr.id, usr.name,usr.email,"\f5, \fN".join(map(lambda p: p.name, usr.permissions))),cn)
                else:
                    acserver.msg("%d) \fR%s \f5- \fI%s \f5: {\fN%s\f5}"%(usr.id, usr.name,usr.email,"\f5, \fN".join(map(lambda p: p.name, usr.permissions))),cn)
        
            acserver.msg("\fHEnd User List.",cn)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
    
    if ext == "grantperm":
        if hasPermission(cn,'grantPermission'):
            args = ext_text.split()
            if len(args) != 2:
                acserver.msg("\f9Invalid arguments to grantperm", cn)
                return
            
            username,permname = args
        
            try:
                user = db.getUser(session,username)
            except NoResultFound:
                acserver.msg("\f3User not found!",cn)
                return
        
            try:
                perm = db.getPerm(session,permname)
            except NoResultFound:
                acserver.msg("\f3Permission does not exist!",cn)
                return
        
            if perm in user.permissions:
                acserver.msg("\f3User already has that permission!",cn)
                return
            else:
                user.permissions.append(perm)
                session.commit()
                acserver.msg("\fJPermission granted successfully!",cn)
        else:
            acserver.msg("\f3You don't have access to that command!",cn)
示例#20
0
def loadPlugins():
    plugins.clear()
    
    ignoredplugins = Config['acserver']['ignoredplugins'].split()
    for path in paths:
        files = os.listdir(path)
        for file in files:
            dirpath = os.path.join(path,file)
            config_path = os.path.join(dirpath,"plugin.conf")
            if os.path.isdir(dirpath) and os.path.exists(config_path):
                if os.path.basename(dirpath) in ignoredplugins:
                    forcedisabled = True
                else:
                    forcedisabled = False
                    
                p = Plugin(dirpath, config_path, forcedisabled)
                
                if p.isenabled:
                    plugins[p.name] = p
                else:
                    acserver.log(":   - Skipping plugin %s"%p.path)
    
    
    name_to_deps = dict( (p,set(plugins[p].depends)) for p in plugins )
    
    if DEBUG:
        for name,deps in name_to_deps.iteritems():
            for parent in deps:
                print("%s -> %s;" %(name,parent))
    
    batches = []
    
    while name_to_deps:
        ready = {name for name, deps in name_to_deps.iteritems() if not deps}
        
        if not ready:
            acserver.log("Circular dependencies or missing plugin found!",ACLOG_ERROR)
            acserver.log("No plugins loaded!",ACLOG_ERROR)
            return
            
            
        for name in ready:
            del name_to_deps[name]
        for deps in name_to_deps.itervalues():
            deps.difference_update(ready)

        batches.append( {plugins[name] for name in ready} )
    
    
    deadplugins = []
    for batch in batches:
        for plugin in batch:
            acserver.log(":   + Loading plugin %s"%plugin.name)
            broken = False
            for dep in plugin.depends:
                if dep in deadplugins:
                    deadplugins.append(plugin.name)
                    acserver.log(" Failed loading plugin (dependancy errors): %s"%plugin.name,ACLOG_WARNING)
                    broken = True
                    
            if not broken and not plugin.loadModule():
                acserver.log(" Failed loading plugin (plugin errors): %s"%plugin.name,ACLOG_WARNING)
                deadplugins.append(plugin.name)
    
    for plugin.name in deadplugins:
        del plugins[plugin.name]
    
    acserver.log("Loaded plugins: %s"%", ".join(plugins.keys()))
示例#21
0
 def register_nick(self):
     acserver.log("IRCBOT: Registering nick %s" % self.nick)
     self.send("NICK %s" % self.nick, True)
示例#22
0
def reloadPlugins():
    acserver.log("Reloading Plugins:")
    for p in plugins.values():
        p.unloadModule()
    for p in plugins.values():
        p.loadModule()
示例#23
0
 def register(self):
     acserver.log("IRCBOT: Authing as %s" % self.nick)
     self.send("USER %s %s bla :%s" % (self.nick, self.server, self.nick), True)
示例#24
0
 def join(self, channel):
     if not channel.startswith("#"):
         channel = "#%s" % channel
     self.send("JOIN %s" % channel)
     acserver.log("IRCBOT: Joining %s" % channel)
示例#25
0
 def part(self, channel):
     if not channel.startswith("#"):
         channel = "#%s" % channel
     self.send("PART %s" % channel)
     acserver.log("IRCBOT: Leaving %s" % channel)
示例#26
0
 def handle_ping(self, payload):
     """\
     Respond to periodic PING messages from server
     """
     acserver.log("IRCBOT: server ping: %s" % payload)
     self.send("PONG %s" % payload, True)
示例#27
0
import acserver
from core.consts import *

cmdOpts = acserver.getCmdLineOptions()
configLocation = cmdOpts['py_global_config']

#Public interface, values defined here are defaults
Config = {
    'acserver': {
        'ignoredplugins':'',
        }
    }

conf = ConfigParser()
if os.path.exists(configLocation):
    acserver.log(":   + Loading python global config file: %s"%configLocation)
    conf.read(configLocation)
    if not conf.has_section('acserver'):
        acserver.log("Invalid config file: Make sure you include a section 'acserver'",ACLOG_ERROR)
    else:
        for sec in conf.sections():
            for i in conf.items(sec):
                key,value = i
                Config[sec][key] = value
        
else:
    acserver.log("Could not find global config file, writing default to %s"%configLocation,ACLOG_WARNING)
    
    for sec in Config:
        conf.add_section(sec)
    
示例#28
0
def masterRegister(host,port):
    acserver.log('Blocked master registration.',ACLOG_VERBOSE)
    return True