Esempio n. 1
0
 def buildConfig(self):
     cfg = ElementTree.Element("hackabot")
     net = ElementTree.SubElement(cfg, "network")
     net.attrib['nick'] = self.nickname
     net.attrib['name'] = self.username
     svr = ElementTree.SubElement(net, "server")
     svr.attrib['hostname'] = "127.0.0.1"
     svr.attrib['port'] = str(self.tester.port)
     join = ElementTree.SubElement(net, "autojoin")
     join.attrib['chan'] = self.channel
     return cfg
Esempio n. 2
0
    def __init__(self, config, net=None):
        self._conf = None

        if net is not None and net.find("acl"):
            conffile = net.find("acl").get("file", None)
        elif config.find("acl") is not None:
            conffile = config.find("acl").get("file", None)
        else:
            log.debug("No ACL file to load")
            return

        if conffile is None:
            raise ConfigError("<acl> tag is missing the file attribute!");

        if not os.path.isabs(conffile):
            confdir = config.get('config', None)
            if not confdir:
                log.error("Unable to resolve relative path to ACL")
                return
            confdir = os.path.dirname(confdir)
            conffile = os.path.join(confdir, conffile)

        if not os.access(conffile, os.R_OK):
            raise ConfigError("Cannot read ACL file %s" % conffile);

        log.debug("Loading ACL file %s" % conffile)
        self._conf = ElementTree.parse(conffile)
Esempio n. 3
0
    def __init__(self, config, net=None):
        self._conf = None

        if net is not None and net.find("acl"):
            conffile = net.find("acl").get("file", None)
        elif config.find("acl") is not None:
            conffile = config.find("acl").get("file", None)
        else:
            log.debug("No ACL file to load")
            return

        if conffile is None:
            raise ConfigError("<acl> tag is missing the file attribute!")

        if not os.path.isabs(conffile):
            confdir = config.get('config', None)
            if not confdir:
                log.error("Unable to resolve relative path to ACL")
                return
            confdir = os.path.dirname(confdir)
            conffile = os.path.join(confdir, conffile)

        if not os.access(conffile, os.R_OK):
            raise ConfigError("Cannot read ACL file %s" % conffile)

        log.debug("Loading ACL file %s" % conffile)
        self._conf = ElementTree.parse(conffile)
Esempio n. 4
0
    def _handle_event(self, conn, event):
        if 'internal' in event and event['internal']:
            return

        conf = conn.manager.config
        if event['type'] == "command":
            commands = glob("%s/commands/%s" %
                    (conf.get('root'), event['command']))
        else:
            commands = glob("%s/hooks/%s/*" %
                (conf.get('root'), event['type']))

        if not commands:
            return

        vars = os.environ.copy()
        for key, val in conf.items():
            vars["HB_%s" % key.upper()] = str(val)

        if conn.network.id:
            vars['HB_NETWORK'] = conn.network.id

        vars['HB_NICK'] = conn.nickname
        vars['HB_XML'] = ElementTree.tostring(conn.manager.config)
        text = ""
        for key, val in event.iteritems():
            if key == 'text':
                text = val
            else:
                vars['HBEV_%s' % key.upper()] = str(val)

        if 'PERL5LIB' in vars:
            vars['PERL5LIB'] = "%s:%s" % (conf.get('perl'), vars['PERL5LIB'])
        else:
            vars['PERL5LIB'] = conf.get('perl')

        if 'PYTHONPATH' in vars:
            vars['PYTHONPATH'] = ("%s:%s" %
                    (conf.get('python'), vars['PYTHONPATH']))
        else:
            vars['PYTHONPATH'] = conf.get('python')

        deferreds = []
        for cmd in commands:
            if os.access(cmd, os.X_OK):
                log.debug("Running %s" % cmd)
                deferred = defer.Deferred()
                deferreds.append(deferred)
                proto = HBProcessProtocol(conn, event, deferred)
                reactor.spawnProcess(proto, cmd, [cmd], vars)

        if len(deferreds) == 1:
            return deferreds[0]
        elif len(deferreds) > 1:
            return defer.DeferredList(deferreds, consumeErrors=True)
Esempio n. 5
0
    def _handle_event(self, conn, event):
        if 'internal' in event and event['internal']:
            return

        conf = conn.manager.config
        if event['type'] == "command":
            commands = glob("%s/commands/%s" %
                            (conf.get('root'), event['command']))
        else:
            commands = glob("%s/hooks/%s/*" %
                            (conf.get('root'), event['type']))

        if not commands:
            return

        vars = os.environ.copy()
        for key, val in conf.items():
            vars["HB_%s" % key.upper()] = str(val)

        if conn.network.id:
            vars['HB_NETWORK'] = conn.network.id

        vars['HB_NICK'] = conn.nickname
        vars['HB_XML'] = ElementTree.tostring(conn.manager.config)
        text = ""
        for key, val in event.iteritems():
            if key == 'text':
                text = val
            else:
                vars['HBEV_%s' % key.upper()] = str(val)

        if 'PERL5LIB' in vars:
            vars['PERL5LIB'] = "%s:%s" % (conf.get('perl'), vars['PERL5LIB'])
        else:
            vars['PERL5LIB'] = conf.get('perl')

        if 'PYTHONPATH' in vars:
            vars['PYTHONPATH'] = ("%s:%s" %
                                  (conf.get('python'), vars['PYTHONPATH']))
        else:
            vars['PYTHONPATH'] = conf.get('python')

        deferreds = []
        for cmd in commands:
            if os.access(cmd, os.X_OK):
                log.debug("Running %s" % cmd)
                deferred = defer.Deferred()
                deferreds.append(deferred)
                proto = HBProcessProtocol(conn, event, deferred)
                reactor.spawnProcess(proto, cmd, [cmd], vars)

        if len(deferreds) == 1:
            return deferreds[0]
        elif len(deferreds) > 1:
            return defer.DeferredList(deferreds, consumeErrors=True)
Esempio n. 6
0
    def signedOn(self):
        log.info("Signed On!")
        self.factory.clientConnected(self)

        for automsg in self.factory.config.findall('automsg'):
            to = automsg.get('to', None)
            msg = automsg.get('msg', None)

            if to and msg:
                self.msg(to, msg)
            else:
                log.error("Invalid automsg: %s" % ElementTree.tostring(automsg))

        for autojoin in self.factory.config.findall('autojoin'):
            chan = autojoin.get('chan', None)
            password = autojoin.get('password', None)

            if chan:
                self.join(chan, password)
            else:
                log.error("Invalid autojoin: %s" % ElementTree.tostring(autojoin))
Esempio n. 7
0
    def signedOn(self):
        log.info("Signed On!")
        self.factory.clientConnected(self)

        for automsg in self.factory.config.findall('automsg'):
            to = automsg.get('to', None)
            msg = automsg.get('msg', None)

            if to and msg:
                self.msg(to, msg)
            else:
                log.error("Invalid automsg: %s" %
                          ElementTree.tostring(automsg))

        for autojoin in self.factory.config.findall('autojoin'):
            chan = autojoin.get('chan', None)
            password = autojoin.get('password', None)

            if chan:
                self.join(chan, password)
            else:
                log.error("Invalid autojoin: %s" %
                          ElementTree.tostring(autojoin))
Esempio n. 8
0
def parse_config(path=None, xml=None):
    """Load configuration XML, return the root element"""
    assert not (path and xml)

    from hackabot.etree import ElementTree

    # Assuming the normal svn layout, find the source root
    root = os.path.abspath(__file__).rsplit("/",4)[0]

    defaults = {
        'root': root,
        'perl': "%s/lib/perl" % root,
        'mysql': "%s/lib/mysql" % root,
        'python': "%s/lib/python" % root,
    }

    if path:
        path = os.path.abspath(path)
        try:
            config = ElementTree.parse(path).getroot()
        except IOError, (exno, exstr):
            raise ConfigError("Failed to read %s: %s" % (path, exstr))
Esempio n. 9
0
    def check(self, event):
        """Check if a command can be run by a user.
        
        Returns a tuple: (True/False, message)
        """

        if self._conf is None:
            acl = None
        elif event['private']:
            acl = self.check_private(event['command'], event['sent_by'])
        else:
            acl = self.check_public(event['command'], event['sent_by'],
                    event['sent_to'])

        if acl is None:
            log.debug("No acl")
            return (True, "")
        else:
            log.debug("Using acl: %s" % ElementTree.tostring(acl).strip())
            action = acl.get("action", "")
            if action == "" or action not in ("allow", "deny"):
                log.error('Invalid acl action="%s", allowing.' % action)
            return (action != "deny", acl.get("msg", ""))
Esempio n. 10
0
    def check(self, event):
        """Check if a command can be run by a user.
        
        Returns a tuple: (True/False, message)
        """

        if self._conf is None:
            acl = None
        elif event['private']:
            acl = self.check_private(event['command'], event['sent_by'])
        else:
            acl = self.check_public(event['command'], event['sent_by'],
                                    event['sent_to'])

        if acl is None:
            log.debug("No acl")
            return (True, "")
        else:
            log.debug("Using acl: %s" % ElementTree.tostring(acl).strip())
            action = acl.get("action", "")
            if action == "" or action not in ("allow", "deny"):
                log.error('Invalid acl action="%s", allowing.' % action)
            return (action != "deny", acl.get("msg", ""))
Esempio n. 11
0
 def start(_):
     config = ElementTree.tostring(self.buildConfig())
     self.manager = core.HBotManager(xml=config)
     return self.tester.notify('join', self.nickname)
Esempio n. 12
0
    defaults = {
        'root': root,
        'perl': "%s/lib/perl" % root,
        'mysql': "%s/lib/mysql" % root,
        'python': "%s/lib/python" % root,
    }

    if path:
        path = os.path.abspath(path)
        try:
            config = ElementTree.parse(path).getroot()
        except IOError, (exno, exstr):
            raise ConfigError("Failed to read %s: %s" % (path, exstr))
    elif xml:
        config = ElementTree.fromstring(xml)
    else:
        config = ElementTree.Element("hackabot")

    for key, value in defaults.iteritems():
        config.attrib.setdefault(key, value)

    if path:
        config.attrib['config'] = path

    return config

def run(argv=sys.argv):
    """Start up Hackabot"""

    options, conf = parse_options(argv)