Пример #1
0
def handle_json(event):
    """ dispatch web request .. return json """
    input = unquote_plus(event.path)
    bot = fleet.getfirstbot()
    ievent = Ircevent()
    try:
        what = input.split('?', 1)[1]
    except IndexError:
        return ["dispatch what ?", ]
    if what.startswith("command="):
        what = what[8:]
    ievent.txt = what
    ievent.nick = 'web'
    ievent.userhost = 'web@web'
    ievent.channel = 'web'
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 3
    ievent.bot = bot
    result = []
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))
    else:
        return ["can't dispatch %s" % ievent.txt, ]
    result = waitforqueue(q, 3)
    rlog(10, 'json', str(result))
    try:
        res = dumps(result)
    except Exception, ex:
        handle_exception()
        res = []
Пример #2
0
def fleet_enable(bot, ievent):
    """ enable a fleet bot. """

    if not ievent.rest:
        ievent.missing("list of fleet bots")
        return

    bots = ievent.rest.split()

    for name in bots:
        bot = fleet.byname(name)

        if bot:
            bot.cfg['enable'] = 1
            bot.cfg.save()
            ievent.reply('enabled %s' % name)
            start_new_thread(fleet.connect, (name, ))
        elif name in fleet.avail():
            bots = fleet.start([
                name,
            ], enable=True)
            for bot in bots:
                ievent.reply('enabled and started %s bot' % name)
                start_new_thread(fleet.connect, (name, ))
        else:
            ievent.reply('no %s bot in fleet' % name)
Пример #3
0
    def _dccresume(self, sock, nick, userhost, channel=None):

        """ resume dcc loop. """

        if not nick or not userhost:
            return
        start_new_thread(self._dccloop, (sock, nick, userhost, channel))
Пример #4
0
def fleet_enable(bot, ievent):

    """ enable a fleet bot. """

    if not ievent.rest:
        ievent.missing("list of fleet bots")
        return

    bots = ievent.rest.split()

    for name in bots:
        bot = fleet.byname(name)

        if bot:
            bot.cfg['enable'] = 1
            bot.cfg.save()
            ievent.reply('enabled %s' % name)
            start_new_thread(fleet.connect, (name, ))
        elif name in fleet.avail():
            bots = fleet.start([name, ], enable=True)
            for bot in bots:
                ievent.reply('enabled and started %s bot' % name)
                start_new_thread(fleet.connect, (name, ))
        else:
            ievent.reply('no %s bot in fleet' % name)
Пример #5
0
def handle_dispatch(event):
    """ dispatch web request """
    input = unquote_plus(event.path)
    bot = fleet.getfirstbot()
    ievent = Ircevent()
    try:
        what = input.split('?', 1)[1]
    except IndexError:
        return ["dispatch what ?", ]
    if what.startswith("command="):
        what = what[8:]
    ievent.txt = what
    ievent.nick = 'web'
    ievent.userhost = 'web@web'
    ievent.channel = 'web'
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 3
    ievent.bot = bot
    result = []
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))
    else:
        return ["can't dispatch %s" % what, ]
    result = waitforqueue(q, 60)
    if not result:
        return ["can't dispatch %s" % what, ]
    return result
Пример #6
0
def handle_dispatch(event):
    """ dispatch web request """
    input = unquote_plus(event.path)
    bot = fleet.getfirstbot()
    ievent = Ircevent()
    try:
        what = input.split('?', 1)[1]
    except IndexError:
        return [
            "dispatch what ?",
        ]
    if what.startswith("command="):
        what = what[8:]
    ievent.txt = what
    ievent.nick = 'web'
    ievent.userhost = 'web@web'
    ievent.channel = 'web'
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 3
    ievent.bot = bot
    result = []
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))
    else:
        return [
            "can't dispatch %s" % what,
        ]
    result = waitforqueue(q, 60)
    if not result:
        return [
            "can't dispatch %s" % what,
        ]
    return result
Пример #7
0
def handle_scstartwatch(bot, ievent):
    if cfg.get('scwatch'):
        ievent.reply('shoutcast watcher is already running')
        return
    scwatcher.stop = False
    cfg.set('scwatch', 1)
    start_new_thread(scwatcher.run, ())
    ievent.reply('watcher started')
Пример #8
0
def handle_cloudstartserver(bot, ievent):
    """ cloud-startserver .. start the cloud server """
    if not cfg.get('enable'):
        ievent.reply('cloud is not enabled')
        return
    cfg.set('servermode', 1)
    cfg.save()
    start_new_thread(startserver, ())
    ievent.reply('server thread started')
Пример #9
0
def markovtrain(l):
    """ train items in list """
    time.sleep(1)
    for i in l:
        if i.startswith('http://'):
            start_new_thread(markovlearnurl, (i,))
        else:
            start_new_thread(markovlearnlog, (i,))
    return 1
Пример #10
0
def markovtrain(l):
    """ train items in list """
    time.sleep(1)
    for i in l:
        if i.startswith('http://'):
            start_new_thread(markovlearnurl, (i, ))
        else:
            start_new_thread(markovlearnlog, (i, ))
    return 1
Пример #11
0
def handle_cloudstartserver(bot, ievent):
    """ cloud-startserver .. start the cloud server """
    if not cfg.get('enable'):
        ievent.reply('cloud is not enabled')
        return
    cfg.set('servermode', 1)
    cfg.save()
    start_new_thread(startserver, ())
    ievent.reply('server thread started')
Пример #12
0
    def joinchannels(self):
        """ join channels. """

        for i in self.state['joinedchannels']:
            try:
                key = self.channels.getkey(i)
                rlog(10, self.name, 'join %s' % i.split()[0])
                start_new_thread(self.join, (i, key))
                time.sleep(1)
            except Exception, ex:
                rlog(10, self.name, 'failed to join %s: %s' % (i, str(ex)))
Пример #13
0
def handle_chat(bot, ievent):

    """ chat .. start a bot initiated dcc chat session. """

    if not bot.type == 'irc':
        ievent.reply("chat only works on irc bots")
        return

    i = ievent
    thr.start_new_thread(bot._dcclisten, (i.nick, i.userhost, i.channel))
    ievent.reply('dcc chat request sent')
Пример #14
0
    def joinchannels(self):

        """ join channels. """

        for i in self.state['joinedchannels']:
            try:
                key = self.channels.getkey(i)
                rlog(10, self.name, 'join %s' % i.split()[0])
                start_new_thread(self.join, (i, key))
                time.sleep(1)
            except Exception, ex:
                rlog(10, self.name, 'failed to join %s: %s' % (i, str(ex)))
Пример #15
0
def init():
    """ init plugin """
    # check if enabled
    if not cfg.get('enable'):
        return 1
    # if so register callbacks
    callbacks.add("PRIVMSG", cb_markovtalk, cb_markovtalk_test, threaded=True)
    callbacks.add('JOIN', cb_markovjoin, threaded=True)
    jcallbacks.add('Message', cb_markovtalk, cb_jmarkovtalk_test, \
threaded=True)
    # learn log or url on startup
    start_new_thread(markovtrain, (markovlearn.data,))
    return 1
Пример #16
0
def init():
    """ init plugin """
    # check if enabled
    if not cfg.get('enable'):
        return 1
    # if so register callbacks
    callbacks.add("PRIVMSG", cb_markovtalk, cb_markovtalk_test, threaded=True)
    callbacks.add('JOIN', cb_markovjoin, threaded=True)
    jcallbacks.add('Message', cb_markovtalk, cb_jmarkovtalk_test, \
threaded=True)
    # learn log or url on startup
    start_new_thread(markovtrain, (markovlearn.data, ))
    return 1
Пример #17
0
def handle_whois(bot, ievent):
    lookup, server, port = None, None, 43
    try:
        if ':' in ievent.args[0]:
            server, port = ievent.args[0].split(':')
            port = int(port)
        else:
            server = ievent.args[0]
        lookup = ievent.args[1]
    except (IndexError, ValueError):
        ievent.missing('<server[:port]> <object>')

    #ievent.reply('doing lookup for "%s" on %s:%d' % (lookup, server, port))
    thr.start_new_thread(do_whois, (ievent, server, port, lookup))
Пример #18
0
 def start(self):
     self.name = calledfrom(sys._getframe(0))
     self.stop = False
     self.running = False
     self.handlers = {}
     self.webmods = {}
     self.state = ObjectState()
     self.state.define('whitelistenable', 0)
     self.state.define('whitelist', [])
     self.state.define('blacklist', [])
     self.state.define('disable', [])
     self.poll = select.poll()
     self.poll.register(self)
     start_new_thread(self.serve, ())
     time.sleep(1)
Пример #19
0
 def run(self):
     self.starttime = int(time.time())
     res = ""
     while cfg.get('scwatch') and not self.stop:
         time.sleep(1)
         if self.stop:
             break
         godo = []    
         for botname, channel, name, node, polltime in cfg.get('nodes'):
             if not (int(time.time()) - self.starttime) % int(polltime):
                 godo.append((botname, channel, name, node))
                 continue            
         if godo:
             rlog(0, 'shoutcast', 'running scan: %s' % str(godo))
             start_new_thread(self.doscan, (godo, ))        
Пример #20
0
 def start(self):
     self.name = calledfrom(sys._getframe(0))
     self.stop = False
     self.running = False
     self.handlers = {}
     self.webmods = {}
     self.state = ObjectState()
     self.state.define('whitelistenable', 0)
     self.state.define('whitelist', [])
     self.state.define('blacklist', [])
     self.state.define('disable', [])
     self.poll = select.poll()
     self.poll.register(self)
     start_new_thread(self.serve, ())
     time.sleep(1)
Пример #21
0
def dispatch_POST(server, request):
    """ dispatch request into the cloud """
    try:
        (host, port) = request.client_address
    except:
        return [
            "can't determine host/port",
        ]
    try:
        input = getpostdata(request)
        cmnd = input['cmnd']
    except KeyError:
        return dumps([
            'need cmnd value',
        ])
    try:
        channel = input['channel']
    except KeyError:
        channel = "#cloud"
    if not channel:
        channel = '#cloud'
    bot = fleet.getfirstbot()
    ievent = Ircevent()
    ievent.txt = cmnd
    ievent.nick = 'cloud'
    ievent.userhost = "cloud@%s" % host
    ievent.channel = channel
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 3
    ievent.bot = bot
    result = []
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))
    else:
        return dumps([
            "can't dispatch %s" % cmnd,
        ])
    result = waitforqueue(q, 10)
    if not result:
        return dumps([
            "no result",
        ])
    res = []
    for item in result:
        res.append(str(item))
    return dumps(res)
Пример #22
0
def handle_scadd(bot, ievent):
    try:
        name, node, polltime = ievent.args
    except ValueError:
        ievent.missing('<name> <host:port> <polltime>')
        return
    try:
        polltime = int(polltime)
    except ValueError:
        ievent.reply('polltime needs to be an integer')
        return
    if polltime < 60:
        ievent.reply('polltime in min. 60 seconds')
        return
    if not cfg.get('scwatch'):
        cfg.set('scwatch', 1)
        scwatcher.stop = False    
        start_new_thread(scwatcher.run, ())
    cfg.append('nodes', [bot.name, ievent.channel, name, node, polltime])
    cfg.save()
    ievent.reply('%s added' % node)
Пример #23
0
def init():
    """ init the plugin """
    if cfg['tcp']:
        start_new_thread(tcplistener._listen, ())
        start_new_thread(tcplistener._handleloop, ())
        start_new_thread(tcplistener._outloop, ())
    return 1
Пример #24
0
def dispatch_POST(server, request):
    """ dispatch request into the cloud """
    try:
        (host, port) = request.client_address
    except:
        return ["can't determine host/port", ]
    try:
        input = getpostdata(request)
        cmnd = input['cmnd']
    except KeyError:
        return dumps(['need cmnd value', ])
    try:
        channel = input['channel']
    except KeyError:
        channel = "#cloud"
    if not channel:
        channel = '#cloud'
    bot = fleet.getfirstbot()
    ievent = Ircevent()
    ievent.txt = cmnd  
    ievent.nick = 'cloud'
    ievent.userhost = "cloud@%s" % host
    ievent.channel = channel
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 3
    ievent.bot = bot
    result = []
    if plugins.woulddispatch(bot, ievent):
        start_new_thread(plugins.trydispatch, (bot, ievent))
    else:
        return dumps(["can't dispatch %s" % cmnd, ])
    result = waitforqueue(q, 10)
    if not result:
        return dumps(["no result", ])
    res = []
    for item in result:
        res.append(str(item))
    return dumps(res)
Пример #25
0
    def _listen(self):
        """ listen for tcp messages .. /msg via bot"""
        if not cfg['tcp']:
            return
        try:
            fleet.startok.wait()
            bot = fleet.byname(cfg['tcpbot'] or 'default')
            if not bot:
                rlog(10, 'tcp', "can't find main bot .. not starting")
                return
            # get listen socket on host were running on
            self.sock.bind((cfg['tcphost'], cfg['tcpport']))
            self.sock.listen(1)
            rlog(10, 'tcp', 'tcp listening on %s %s' % (cfg['tcphost'], \
cfg['tcpport']))
            self.stop = 0
        except IOError:
            handle_exception()
            self.sock = None
            self.stop = 1
            return
        # loop on listening tcp socket
        bot.connectok.wait()
        while not self.stop:
            try:
                (sock, addr) = self.sock.accept()
                rlog(10, 'tcp', 'connection from %s' % str(addr))
            except socket.timeout:
                continue
            except Exception, ex:
                if 'Invalid argument' in str(ex):
                    continue
                handle_exception()
                break
            if cfg['tcp'] and (addr[0] in cfg['tcpallow'] or \
_inmask(addr[0])):
                start_new_thread(self.handlesocket, (sock, addr))
Пример #26
0
def handle_search(bot, ievent):
    """ search all plugins that provide a search() function """
    result = {}
    queue = Queue.Queue()
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<what>')
        return
    threads = []
    for name, plug in plugins.plugs.iteritems():
        try:
            searchfunc = getattr(plug, 'search')
            if searchfunc:
                threadid = start_new_thread(searchfunc, (what, queue))
                threads.append(threadid)
        except AttributeError:
            pass
        except Exception, ex:
            handle_exception()
Пример #27
0
def handle_search(bot, ievent):
    """ search all plugins that provide a search() function """
    result = {}
    queue = Queue.Queue()
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<what>')
        return
    threads = []
    for name, plug in plugins.plugs.iteritems():
        try:
            searchfunc = getattr(plug, 'search')
            if searchfunc:
                threadid = start_new_thread(searchfunc, (what, queue))
                threads.append(threadid)
        except AttributeError:
            pass
        except Exception, ex:
            handle_exception()
Пример #28
0
 def start(self):
     self.running = True
     start_new_thread(self.watch, ())
Пример #29
0
    global httpd
    try:
        if doit:
            httpd = BotHTTPServer((webhostname, webport), BotHTTPRequestHandler)
    except Exception, ex:
        rlog(10, 'webserver', "can't start server: %s" % str(ex))
        return 0
    if httpd:
        webplugs = gozer_import('gozerplugs.webserver.webplugs')
        for i in webplugs.__all__:
            if i not in cfg.get('denyplugs'):
                try:
                    httpd.reloadhandler(i)
                except:
                    handle_exception()
        start_new_thread(httpd.run, ())
    return 1
    
def shutdown():
    """ shutdown webserver plugin """
    global httpd
    if not httpd:
        return 1
    try:
        httpd.stop = True
        httpd.server_close()
    except:
        handle_exception()
        pass
    time.sleep(3)
    return 1
Пример #30
0
    def handle_privmsg(self, ievent):

        """ check if PRIVMSG is command, if so dispatch. """

        if ievent.nick in self.nicks401:
            rlog(10, self.name, "%s is available again" % ievent.nick)
            self.nicks401.remove(ievent.nick)

        if not ievent.txt:
            return

        # check if it is a dcc chat request
        chat = re.search(dccchatre, ievent.txt)
        if chat:
            # check if the user is known
            if users.allowed(ievent.userhost, 'USER'):
                # start connection
                start_new_thread(self._dccconnect, (ievent.nick, ievent.userhost, chat.group(1), chat.group(2))) 
                return

        # see if base class method would handle it
        if '\001' in ievent.txt:
            Irc.handle_privmsg(self, ievent)
            return

        # set bot and socket in ircevent
        ievent.bot = self
        ievent.sock = self.sock
        chan = ievent.channel.lower()

        # check for /msg
        if chan == self.nick.lower():
            ievent.msg = 1
            ievent.speed =  7
            ievent.printto = ievent.nick
            ccs = ['!', '@', self.cfg['defaultcc']]
            # check for PRIVMSG waiting callback
            self.privwait.check(ievent)
            if ievent.isresponse:
                return
            if not self.cfg['noccinmsg']:
                plugins.trydispatch(self, ievent)
            elif ievent.txt[0] in ccs: 
                ievent.txt = ievent.txt[1:]
                plugins.trydispatch(self, ievent)
            return

        ievent.printto = chan

        # see if we can get channel control character
        try:
            cchar = self.channels[chan]['cc']
        except LookupError:
            cchar = self.cfg['defaultcc'] or '!'
        except TypeError:
            cchar = self.cfg['defaultcc'] or '!'

        # see if cchar matches, if so dispatch
        ievent.speed = 5
        if ievent.txt[0] in cchar:
            ievent.cc = ievent.txt[0]
            ievent.txt = ievent.txt[1:]
            plugins.trydispatch(self, ievent)
            return

        # see if were adressed, if so dispatch
        txtlist = ievent.txt.split(':', 1)
        if txtlist[0].lower() == self.nick.lower():
            if len(txtlist) < 2:
                return
            ievent.txt = txtlist[1].strip()
            plugins.trydispatch(self, ievent)
            return

        # habbie addressing mode
        txtlist = ievent.txt.split(',', 1)
        if txtlist[0].lower() == self.nick.lower():
            if len(txtlist) < 2:
                return
            ievent.txt = txtlist[1].strip()
            plugins.trydispatch(self, ievent)
            return

        # check for PRIVMSG waiting callback
        self.privwait.check(ievent)
Пример #31
0
    def _connect(self):
        """ connect to server/port using nick. """

        if self.connecting:
            rlog(10, self.name, 'already connecting')
            raise AlreadyConnecting()

        if self.connected:
            rlog(10, self.name, 'already connected')
            raise AlreadyConnected()

        self.stopped = 0
        self.connecting = True
        self.connectok.clear()
        self.connectlock.acquire()

        # create socket
        if self.ipv6:
            rlog(10, self.name, 'creating ipv6 socket')
            self.oldsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            self.ipv6 = 1
        else:
            rlog(10, self.name, 'creating ipv4 socket')
            self.oldsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        assert (self.oldsock)

        # optional bind
        server = self.server
        elite = self.cfg['bindhost'] or config['bindhost']
        if elite:
            try:
                self.oldsock.bind((elite, 0))
            except socket.gaierror:
                rlog(10, self.name, "can't bind to %s" % elite)
                # resolve the IRC server and pick a random server
                if not server:
                    # valid IPv6 ip?
                    try:
                        socket.inet_pton(socket.AF_INET6, self.server)
                    except socket.error:
                        pass
                    else:
                        server = self.server
                if not server:
                    # valid IPv4 ip?
                    try:
                        socket.inet_pton(socket.AF_INET, self.server)
                    except socket.error:
                        pass
                    else:
                        server = self.server
                if not server:
                    # valid hostname?
                    ips = []
                    try:
                        for item in socket.getaddrinfo(self.server, None):
                            if item[0] in [socket.AF_INET, socket.AF_INET6
                                           ] and item[1] == socket.SOCK_STREAM:
                                ip = item[4][0]
                                if ip not in ips: ips.append(ip)
                    except socket.error:
                        pass
                    else:
                        server = random.choice(ips)

        # do the connect .. set timeout to 30 sec upon connecting
        rlog(10, self.name, 'connecting to %s (%s)' % (server, self.server))
        self.oldsock.settimeout(5)
        self.oldsock.connect((server, int(self.port)))

        # we are connected
        rlog(10, self.name, 'connection ok')
        time.sleep(1)
        self.connected = True

        # make file socket
        self.fsock = self.oldsock.makefile("r")

        # set blocking
        self.oldsock.setblocking(self.blocking)
        self.fsock._sock.setblocking(self.blocking)

        # set socket time out
        if self.blocking:
            socktimeout = self.cfg['socktimeout']
            if not socktimeout:
                socktimeout = 301.0
            else:
                socktimeout = float(socktimeout)
            self.oldsock.settimeout(socktimeout)
            self.fsock._sock.settimeout(socktimeout)
        # enable ssl if set
        if self.ssl:
            rlog(10, self.name, 'ssl enabled')
            self.sock = socket.ssl(self.oldsock)
        else:
            self.sock = self.oldsock

        # try to release the outputlock
        try:
            self.outputlock.release()
        except thread.error:
            pass

        # start input and output loops
        start_new_thread(self._readloop, ())
        start_new_thread(self._outloop, ())

        # logon and start monitor
        self._logon()
        self.nickchanged = 0
        self.reconnectcount = 0
        saymonitor.start()
        return 1
Пример #32
0
def init():
    if cfg.get('run'):
        thr.start_new_thread(httpwatch.start, ())
    return 1
Пример #33
0
    def handle_privmsg(self, ievent):
        """ check if PRIVMSG is command, if so dispatch. """

        if ievent.nick in self.nicks401:
            rlog(10, self.name, "%s is available again" % ievent.nick)
            self.nicks401.remove(ievent.nick)

        if not ievent.txt:
            return

        # check if it is a dcc chat request
        chat = re.search(dccchatre, ievent.txt)
        if chat:
            # check if the user is known
            if users.allowed(ievent.userhost, 'USER'):
                # start connection
                start_new_thread(self._dccconnect,
                                 (ievent.nick, ievent.userhost, chat.group(1),
                                  chat.group(2)))
                return

        # see if base class method would handle it
        if '\001' in ievent.txt:
            Irc.handle_privmsg(self, ievent)
            return

        # set bot and socket in ircevent
        ievent.bot = self
        ievent.sock = self.sock
        chan = ievent.channel.lower()

        # check for /msg
        if chan == self.nick.lower():
            ievent.msg = 1
            ievent.speed = 7
            ievent.printto = ievent.nick
            ccs = ['!', '@', self.cfg['defaultcc']]
            # check for PRIVMSG waiting callback
            self.privwait.check(ievent)
            if ievent.isresponse:
                return
            if not self.cfg['noccinmsg']:
                plugins.trydispatch(self, ievent)
            elif ievent.txt[0] in ccs:
                ievent.txt = ievent.txt[1:]
                plugins.trydispatch(self, ievent)
            return

        ievent.printto = chan

        # see if we can get channel control character
        try:
            cchar = self.channels[chan]['cc']
        except LookupError:
            cchar = self.cfg['defaultcc'] or '!'
        except TypeError:
            cchar = self.cfg['defaultcc'] or '!'

        # see if cchar matches, if so dispatch
        ievent.speed = 5
        if ievent.txt[0] in cchar:
            ievent.cc = ievent.txt[0]
            ievent.txt = ievent.txt[1:]
            plugins.trydispatch(self, ievent)
            return

        # see if were adressed, if so dispatch
        txtlist = ievent.txt.split(':', 1)
        if txtlist[0].lower() == self.nick.lower():
            if len(txtlist) < 2:
                return
            ievent.txt = txtlist[1].strip()
            plugins.trydispatch(self, ievent)
            return

        # habbie addressing mode
        txtlist = ievent.txt.split(',', 1)
        if txtlist[0].lower() == self.nick.lower():
            if len(txtlist) < 2:
                return
            ievent.txt = txtlist[1].strip()
            plugins.trydispatch(self, ievent)
            return

        # check for PRIVMSG waiting callback
        self.privwait.check(ievent)
Пример #34
0
 def startwatchers(self):
     """ start watcher threads """
     for j, i in self.data.iteritems():
         if i.running:
             thr.start_new_thread(self.watch, (i.name, ))
Пример #35
0
 def startwatchers(self):
     """ start watcher threads """
     for j, i in self.data.iteritems():
         if i.running:
             thr.start_new_thread(self.watch, (i.name,))
Пример #36
0
def init():
    if cfg.get('run'):
        thr.start_new_thread(httpwatch.start, ())
    return 1
Пример #37
0
    try:
        if doit:
            httpd = BotHTTPServer((webhostname, webport),
                                  BotHTTPRequestHandler)
    except Exception, ex:
        rlog(10, 'webserver', "can't start server: %s" % str(ex))
        return 0
    if httpd:
        webplugs = gozer_import('gozerplugs.webserver.webplugs')
        for i in webplugs.__all__:
            if i not in cfg.get('denyplugs'):
                try:
                    httpd.reloadhandler(i)
                except:
                    handle_exception()
        start_new_thread(httpd.run, ())
    return 1


def shutdown():
    """ shutdown webserver plugin """
    global httpd
    if not httpd:
        return 1
    try:
        httpd.stop = True
        httpd.server_close()
    except:
        handle_exception()
        pass
    time.sleep(3)
Пример #38
0
def init():
    """ called after plugin import """
    thr.start_new_thread(watcher.startwatchers, ())
    return 1
Пример #39
0
    def _resume(self, data, reto=None):

        """ resume to server/port using nick. """

        try:
            if data['ssl']:
                self.connectwithjoin()
                return 1
        except KeyError:
            pass
        self.connecting = False # we're already connected
        self.nick = data['nick']
        self.orignick = self.nick
        self.server = str(data['server'])
        self.port = int(data['port'])
        self.password = data['password']
        self.ipv6 = data['ipv6']
        self.ssl = data['ssl']

        # create socket
        if self.ipv6:
            rlog(1, self.name, 'resuming ipv6 socket')
            self.sock = socket.fromfd(data['fd'], socket.AF_INET6, socket.SOCK_STREAM)
            self.ipv6 = 1
        else:
            rlog(1, self.name, 'resuming ipv4 socket')
            self.sock = socket.fromfd(data['fd'], socket.AF_INET, socket.SOCK_STREAM)

        # do the connect .. set timeout to 30 sec upon connecting
        rlog(10, self.name, 'resuming to ' + self.server)
        self.sock.settimeout(30)

        # we are connected
        rlog(10, self.name, 'connection ok')
        self.stopped = 0
        # make file socket
        self.fsock = self.sock.makefile("r")
        # set blocking
        self.sock.setblocking(self.blocking)

        # set socket time out
        if self.blocking:
            socktimeout = self.cfg['socktimeout']
            if not socktimeout:
                socktimeout = 301.0
            else:
                socktimeout = float(socktimeout)
            self.sock.settimeout(socktimeout)

        # start readloop
        rlog(0, self.name, 'resuming readloop')
        start_new_thread(self._readloop, ())
        start_new_thread(self._outloop, ())

        # init 
        self.reconnectcount = 0
        self.nickchanged = 0
        self.connecting = False

        # still there server?
        self._raw('PING :RESUME %s' % str(time.time()))
        self.connectok.set()
        self.connected = True
        self.reconnectcount = 0
        if reto:
            self.say(reto, 'rebooting done')
        saymonitor.start()
        return 1
Пример #40
0
    def _connect(self):

        """ connect to server/port using nick. """

        if self.connecting:
            rlog(10, self.name, 'already connecting')
            raise AlreadyConnecting()

        if self.connected:
            rlog(10, self.name, 'already connected')
            raise AlreadyConnected()

        self.stopped = 0
        self.connecting = True
        self.connectok.clear()
        self.connectlock.acquire()

        # create socket
        if self.ipv6:
            rlog(10, self.name, 'creating ipv6 socket')
            self.oldsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            self.ipv6 = 1
        else:
            rlog(10, self.name, 'creating ipv4 socket')
            self.oldsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        assert(self.oldsock)

        # optional bind
        server = self.server
        elite = self.cfg['bindhost'] or config['bindhost']
        if elite:
            try:
                self.oldsock.bind((elite, 0))
            except socket.gaierror:
                rlog(10, self.name, "can't bind to %s" % elite)
               # resolve the IRC server and pick a random server
                if not server:
                    # valid IPv6 ip?
                    try: socket.inet_pton(socket.AF_INET6, self.server)
                    except socket.error: pass
                    else: server = self.server
                if not server:  
                    # valid IPv4 ip?
                    try: socket.inet_pton(socket.AF_INET, self.server)
                    except socket.error: pass
                    else: server = self.server
                if not server:
                    # valid hostname?
                    ips = []
                    try:
                        for item in socket.getaddrinfo(self.server, None):
                            if item[0] in [socket.AF_INET, socket.AF_INET6] and item[1] == socket.SOCK_STREAM:
                                ip = item[4][0]
                                if ip not in ips: ips.append(ip)
                    except socket.error: pass
                    else: server = random.choice(ips)

        # do the connect .. set timeout to 30 sec upon connecting
        rlog(10, self.name, 'connecting to %s (%s)' % (server, self.server))
        self.oldsock.settimeout(5)
        self.oldsock.connect((server, int(self.port)))

        # we are connected
        rlog(10, self.name, 'connection ok')
        time.sleep(1)
        self.connected = True

        # make file socket
        self.fsock = self.oldsock.makefile("r")

        # set blocking
        self.oldsock.setblocking(self.blocking)
        self.fsock._sock.setblocking(self.blocking)

        # set socket time out
        if self.blocking:
            socktimeout = self.cfg['socktimeout']
            if not socktimeout:
                socktimeout = 301.0
            else:
                socktimeout = float(socktimeout)
            self.oldsock.settimeout(socktimeout)
            self.fsock._sock.settimeout(socktimeout)
        # enable ssl if set
        if self.ssl:
            rlog(10, self.name, 'ssl enabled')
            self.sock = socket.ssl(self.oldsock) 
        else:
            self.sock = self.oldsock

        # try to release the outputlock
        try:
            self.outputlock.release()
        except thread.error:
            pass

        # start input and output loops
        start_new_thread(self._readloop, ())
        start_new_thread(self._outloop, ())

        # logon and start monitor
        self._logon()
        self.nickchanged = 0
        self.reconnectcount = 0
        saymonitor.start()
        return 1
Пример #41
0
def init():
    if cfg.get('scwatch'):
         start_new_thread(scwatcher.run, ())
    return 1
Пример #42
0
            return

        try:
            # send welcome message .. show list of commands for USER perms
            cmndslist = cmnds.list('USER')
            cmndslist.sort()
            sock.send('Welcome to the GOZERBOT partyline ' + nick + " ;]\n")
            partylist = partyline.list_nicks()
            if partylist:
                sock.send("people on the partyline: %s\n" %
                          ' .. '.join(partylist))
            sock.send("control character is ! .. bot broadcast is @\n")
        except Exception, ex:
            rlog(10, self.name, 'dcc error: %s' % str(ex))
            return
        start_new_thread(self._dccloop, (sock, nick, userhost, channel))

    def _dccloop(self, sock, nick, userhost, channel=None):
        """ loop for dcc commands. """

        sockfile = sock.makefile('r')
        res = ""
        # add joined user to the partyline
        partyline.add_party(self, sock, nick, userhost, channel)

        while 1:
            time.sleep(0.001)
            try:
                # read from socket
                res = sockfile.readline()
                # if res == "" than the otherside had disconnected
Пример #43
0
def init():
    if cfg.get('startup'):
        start_new_thread(main, (cfg.get('startup'), ))
        time.sleep(1)
Пример #44
0
    def _connect(self, reconnect=True):

        """ connect to server .. start read loop. """

        try:
            self.username = self.user.split('@')[0]
        except ValueError:
            raise Exception("i need config user with a @ in it")

        self.me = self.user
        self.jid = xmpp.JID(self.user)
        self.server = self.jid.getDomain()
        self.nick = self.username
        rlog(10, self.name, 'connecting to %s' % self.server)

        if config['debug']:
            self.connection = xmpp.Client(self.server, debug=['always', 'nodebuilder'])
        else:
            self.connection = xmpp.Client(self.server, debug=[])

        time.sleep(2)

        try:
            try:
                import DNS
                self.connection.connect()
            except (ImportError, ValueError):
                if config['debug']:
                    self.connection = xmpp.Client(self.server, debug=['always', 'nodebuilder'])
                else:
                    self.connection = xmpp.Client(self.server, debug=[])
                self.connection.connect((self.host, self.port))
        except AttributeError:
            handle_exception()
            rlog(10, self.name, "can't connect to %s" % self.host)
            return

        if not self.connection:
            rlog(10, self.name, "can't connect to %s" % self.host)
            return

        try:
            rlog(10, self.name, 'doing auth')
            auth = self.connection.auth(self.username, self.password, \
'gozerbot')
        except AttributeError:
            #handle_exception()
            rlog(10, self.name, "can't auth to %s" % self.host)
            return

        if not auth:
            rlog(10, self.name, 'auth for %s failed .. trying register' \
% self.username)
            info = {'username': self.username, 'password': self.password}
            xmpp.features.getRegInfo(self.connection, self.host, info)
            if not xmpp.features.register(self.connection, self.host, info):
                rlog(100, self.name, "can't register")
                return
            else:
                self.connection = xmpp.Client(self.server, debug=[])
                self.connection.connect((self.host, self.port))
                auth = self.connection.auth(self.username, self.password, 'gozerbot')
                rlog(100, self.name, "register succeded")
        self.connecttime = time.time()
        rlog(100, self.name, 'connected! type: %s' % \
self.connection.connected)
        self.connection.RegisterHandler('message', self.messageHandler)
        self.connection.RegisterHandler('presence', self.presenceHandler)
        self.connection.RegisterHandler('iq', self.iqHandler)
        self.connection.UnregisterDisconnectHandler(\
self.connection.DisconnectHandler)
        self.connection.RegisterDisconnectHandler(self.disconnectHandler)
        self.connection.UnregisterHandlerOnce = self.UnregisterHandlerOnce
        self.stopped = 0
        jabbermonitor.start()
        start_new_thread(self._doprocess, ())
        start_new_thread(self._keepalive, ())
        start_new_thread(self._outputloop, ())
        start_new_thread(self._keepchannelsalive, ())
        self.connection.sendInitPresence()
        #self.connection.getRoster()
        self.connectok.set()
        return 1
Пример #45
0
 def start(self):
     self.running = True
     start_new_thread(self.watch, ())
Пример #46
0
    def _dccresume(self, sock, nick, userhost, channel=None):
        """ resume dcc loop. """

        if not nick or not userhost:
            return
        start_new_thread(self._dccloop, (sock, nick, userhost, channel))
Пример #47
0
    def _connect(self, reconnect=True):
        """ connect to server .. start read loop. """

        try:
            self.username = self.user.split('@')[0]
        except ValueError:
            raise Exception("i need config user with a @ in it")

        self.me = self.user
        self.jid = xmpp.JID(self.user)
        self.server = self.jid.getDomain()
        self.nick = self.username
        rlog(10, self.name, 'connecting to %s' % self.server)

        if config['debug']:
            self.connection = xmpp.Client(self.server,
                                          debug=['always', 'nodebuilder'])
        else:
            self.connection = xmpp.Client(self.server, debug=[])

        time.sleep(2)

        try:
            try:
                import DNS
                self.connection.connect()
            except (ImportError, ValueError):
                if config['debug']:
                    self.connection = xmpp.Client(
                        self.server, debug=['always', 'nodebuilder'])
                else:
                    self.connection = xmpp.Client(self.server, debug=[])
                self.connection.connect((self.host, self.port))
        except AttributeError:
            handle_exception()
            rlog(10, self.name, "can't connect to %s" % self.host)
            return

        if not self.connection:
            rlog(10, self.name, "can't connect to %s" % self.host)
            return

        try:
            rlog(10, self.name, 'doing auth')
            auth = self.connection.auth(self.username, self.password, \
'gozerbot')
        except AttributeError:
            #handle_exception()
            rlog(10, self.name, "can't auth to %s" % self.host)
            return

        if not auth:
            rlog(10, self.name, 'auth for %s failed .. trying register' \
% self.username)
            info = {'username': self.username, 'password': self.password}
            xmpp.features.getRegInfo(self.connection, self.host, info)
            if not xmpp.features.register(self.connection, self.host, info):
                rlog(100, self.name, "can't register")
                return
            else:
                self.connection = xmpp.Client(self.server, debug=[])
                self.connection.connect((self.host, self.port))
                auth = self.connection.auth(self.username, self.password,
                                            'gozerbot')
                rlog(100, self.name, "register succeded")
        self.connecttime = time.time()
        rlog(100, self.name, 'connected! type: %s' % \
self.connection.connected)
        self.connection.RegisterHandler('message', self.messageHandler)
        self.connection.RegisterHandler('presence', self.presenceHandler)
        self.connection.RegisterHandler('iq', self.iqHandler)
        self.connection.UnregisterDisconnectHandler(\
self.connection.DisconnectHandler)
        self.connection.RegisterDisconnectHandler(self.disconnectHandler)
        self.connection.UnregisterHandlerOnce = self.UnregisterHandlerOnce
        self.stopped = 0
        jabbermonitor.start()
        start_new_thread(self._doprocess, ())
        start_new_thread(self._keepalive, ())
        start_new_thread(self._outputloop, ())
        start_new_thread(self._keepchannelsalive, ())
        self.connection.sendInitPresence()
        #self.connection.getRoster()
        self.connectok.set()
        return 1
Пример #48
0
def init():
    """ called after plugin import """
    thr.start_new_thread(watcher.startwatchers, ())
    return 1
Пример #49
0
        if not nick or not userhost:
            return

        try:
            # send welcome message .. show list of commands for USER perms
            cmndslist = cmnds.list('USER')
            cmndslist.sort()
            sock.send('Welcome to the GOZERBOT partyline ' + nick + " ;]\n")
            partylist = partyline.list_nicks()
            if partylist:
                sock.send("people on the partyline: %s\n" % ' .. '.join(partylist))
            sock.send("control character is ! .. bot broadcast is @\n")
        except Exception, ex:
            rlog(10 , self.name, 'dcc error: %s' % str(ex))
            return
        start_new_thread(self._dccloop, (sock, nick, userhost, channel))

    def _dccloop(self, sock, nick, userhost, channel=None):

        """ loop for dcc commands. """

        sockfile = sock.makefile('r')
        res = ""
        # add joined user to the partyline
        partyline.add_party(self, sock, nick, userhost, channel)

        while 1:
            time.sleep(0.001)
            try:
                # read from socket
                res = sockfile.readline()
Пример #50
0
    def _resume(self, data, reto=None):
        """ resume to server/port using nick. """

        try:
            if data['ssl']:
                self.connectwithjoin()
                return 1
        except KeyError:
            pass
        self.connecting = False  # we're already connected
        self.nick = data['nick']
        self.orignick = self.nick
        self.server = str(data['server'])
        self.port = int(data['port'])
        self.password = data['password']
        self.ipv6 = data['ipv6']
        self.ssl = data['ssl']

        # create socket
        if self.ipv6:
            rlog(1, self.name, 'resuming ipv6 socket')
            self.sock = socket.fromfd(data['fd'], socket.AF_INET6,
                                      socket.SOCK_STREAM)
            self.ipv6 = 1
        else:
            rlog(1, self.name, 'resuming ipv4 socket')
            self.sock = socket.fromfd(data['fd'], socket.AF_INET,
                                      socket.SOCK_STREAM)

        # do the connect .. set timeout to 30 sec upon connecting
        rlog(10, self.name, 'resuming to ' + self.server)
        self.sock.settimeout(30)

        # we are connected
        rlog(10, self.name, 'connection ok')
        self.stopped = 0
        # make file socket
        self.fsock = self.sock.makefile("r")
        # set blocking
        self.sock.setblocking(self.blocking)

        # set socket time out
        if self.blocking:
            socktimeout = self.cfg['socktimeout']
            if not socktimeout:
                socktimeout = 301.0
            else:
                socktimeout = float(socktimeout)
            self.sock.settimeout(socktimeout)

        # start readloop
        rlog(0, self.name, 'resuming readloop')
        start_new_thread(self._readloop, ())
        start_new_thread(self._outloop, ())

        # init
        self.reconnectcount = 0
        self.nickchanged = 0
        self.connecting = False

        # still there server?
        self._raw('PING :RESUME %s' % str(time.time()))
        self.connectok.set()
        self.connected = True
        self.reconnectcount = 0
        if reto:
            self.say(reto, 'rebooting done')
        saymonitor.start()
        return 1
Пример #51
0
def init():
    if cfg.get('startup'):
        start_new_thread(main, (cfg.get('startup'), ))
        time.sleep(1)