def doPrivmsg(self, irc, msg):
     channel, text = msg.args
     text = text.lower()
     if '#' in channel:
         #print self.regex
         #irc.reply('testing %s against %s' % (text, self._regexString))
         if self.regex.match(text):
             try:
                 hostmask = irc.state.nickToHostmask(msg.nick)
             except KeyError:
                 return
             (nick, user, host) = ircutils.splitHostmask(hostmask)
             user = self._fnUser.sub('*', user)
             banmask = ircutils.joinHostmask('*', user, msg.host)
             if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
                 return
             irc.queueMsg(ban(channel, banmask, 'For swearing. 5 minute timeout'))
             irc.queueMsg(kick(channel, msg.nick, 'For swearing'))
             def unBan():
                 if channel in irc.state.channels and \
                    banmask in irc.state.channels[channel].bans:
                     irc.queueMsg(unban(channel, banmask))
             schedule.addEvent(unBan, time.time()+300)
         elif 'f*g' in text.split():
             try:
                 hostmask = irc.state.nickToHostmask(msg.nick)
             except KeyError:
                 return
             (nick, user, host) = ircutils.splitHostmask(hostmask)
             irc.reply('No thanks %s I don\'t smoke' % user)
     return msg
Esempio n. 2
0
    def makeBanmask(self, hostmask, options=None):
        """Create a banmask from the given hostmask.  If a style of banmask
        isn't specified via options, the value of
        conf.supybot.protocols.irc.banmask is used.

        A variable named 'channel' (defining the channel the ban is taking
        place in) is expected to be in the environment of the caller of this
        function.

        options - A list specifying which parts of the hostmask should
        explicitly be matched: nick, user, host.  If 'exact' is given, then
        only the exact hostmask will be used."""
        assert ircutils.isChannel(dynamic.channel)
        (nick, user, host) = ircutils.splitHostmask(hostmask)
        bnick = '*'
        buser = '******'
        bhost = '*'
        if not options:
            options = get(supybot.protocols.irc.banmask, dynamic.channel)
        for option in options:
            if option == 'nick':
                bnick = nick
            elif option == 'user':
                buser = user
            elif option == 'host':
                bhost = host
            elif option == 'exact':
                return hostmask
        return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 3
0
    def makeBanmask(self, hostmask, options=None):
        """Create a banmask from the given hostmask.  If a style of banmask
        isn't specified via options, the value of
        conf.supybot.protocols.irc.banmask is used.

        options - A list specifying which parts of the hostmask should
        explicitly be matched: nick, user, host.  If 'exact' is given, then
        only the exact hostmask will be used."""
        channel = dynamic.channel
        assert channel is None or ircutils.isChannel(channel)
        (nick, user, host) = ircutils.splitHostmask(hostmask)
        bnick = '*'
        buser = '******'
        bhost = '*'
        if not options:
            options = get(supybot.protocols.irc.banmask, channel)
        for option in options:
            if option == 'nick':
                bnick = nick
            elif option == 'user':
                buser = user
            elif option == 'host':
                bhost = host
            elif option == 'exact':
                return hostmask
        return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 4
0
    def makeBanmask(self, hostmask, options=None):
        """Create a banmask from the given hostmask.  If a style of banmask
        isn't specified via options, the value of
        conf.supybot.protocols.irc.banmask is used.

        A variable named 'channel' (defining the channel the ban is taking
        place in) is expected to be in the environment of the caller of this
        function.

        options - A list specifying which parts of the hostmask should
        explicitly be matched: nick, user, host.  If 'exact' is given, then
        only the exact hostmask will be used."""
        assert ircutils.isChannel(dynamic.channel)
        (nick, user, host) = ircutils.splitHostmask(hostmask)
        bnick = '*'
        buser = '******'
        bhost = '*'
        if not options:
            options = get(supybot.protocols.irc.banmask, dynamic.channel)
        for option in options:
            if option == 'nick':
                bnick = nick
            elif option == 'user':
                buser = user
            elif option == 'host':
                bhost = host
            elif option == 'exact':
                return hostmask
        return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 5
0
    def makeBanmask(self, hostmask, options=None):
        """Create a banmask from the given hostmask.  If a style of banmask
        isn't specified via options, the value of
        conf.supybot.protocols.irc.banmask is used.

        options - A list specifying which parts of the hostmask should
        explicitly be matched: nick, user, host.  If 'exact' is given, then
        only the exact hostmask will be used."""
        channel = dynamic.channel
        assert channel is None or ircutils.isChannel(channel)
        (nick, user, host) = ircutils.splitHostmask(hostmask)
        bnick = '*'
        buser = '******'
        bhost = '*'
        if not options:
            options = get(supybot.protocols.irc.banmask, channel)
        for option in options:
            if option == 'nick':
                bnick = nick
            elif option == 'user':
                buser = user
            elif option == 'host':
                bhost = host
            elif option == 'exact':
                return hostmask
        return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 6
0
    def testSplitHostmask(self):
        # This is the only valid case:
        self.assertEqual(ircutils.splitHostmask('foo!bar@baz'),
                         ('foo', 'bar', 'baz'))

        # This ones are technically allowed by RFC1459, but never happens in
        # practice:
        self.assertEqual(ircutils.splitHostmask('foo!bar!qux@quux'),
                         ('foo', 'bar!qux', 'quux'))
        self.assertEqual(ircutils.splitHostmask('foo!bar@baz@quux'),
                         ('foo', 'bar@baz', 'quux'))
        self.assertEqual(ircutils.splitHostmask('foo!bar@baz!qux@quux'),
                         ('foo', 'bar@baz!qux', 'quux'))

        # And this one in garbage, let's just make sure we don't crash:
        self.assertEqual(ircutils.splitHostmask('foo!bar@baz!qux'),
                         ('foo', 'bar', 'baz!qux'))
Esempio n. 7
0
 def _logBomb(self, irc, channel, sender, victim):
     bombHistory = self.registryValue("bombHistory", channel)
     senderHostmask = irc.state.nickToHostmask(sender)
     (nick, user, host) = ircutils.splitHostmask(senderHostmask)
     senderMask = ("{}@{}".format(user, host)).lower()
     victim = victim.lower()
     bombHistory.append("{}#{}#{}".format(int(time.time()), senderMask, victim))
     self.setRegistryValue("bombHistory", bombHistory, channel)
Esempio n. 8
0
 def _logBomb(self, irc, channel, sender, victim):
     bombHistory = self.registryValue('bombHistory', channel)
     senderHostmask = irc.state.nickToHostmask(sender)
     (nick, user, host) = ircutils.splitHostmask(senderHostmask)
     senderMask = ('{}@{}'.format(user, host)).lower()
     victim = victim.lower()
     bombHistory.append('{}#{}#{}'.format(int(time.time()), senderMask, victim))
     self.setRegistryValue('bombHistory', bombHistory, channel)
Esempio n. 9
0
	def doJoin(self,irc,msg):
		(n,i,h) = ircutils.splitHostmask(msg.prefix)
		channels = msg.args[0].split(',')
		for channel in channels:
			logChannel = self.registryValue('logChannel',channel=channel)
			if logChannel in irc.state.channels:
				check = self.check(h,channel)
				if check and len(check):
					irc.queueMsg(ircmsgs.privmsg(logChannel,'[%s] %s (%s)' % (channel,msg.prefix,', '.join(check))))
Esempio n. 10
0
	def act (self, irc, msg, channel, command, owner):
		tokens = callbacks.tokenize(command)
		#if ircdb.checkCapability(owner, 'owner') or ircdb.checkCapability(owner, '%s,op' % channel):
		#	owner = irc.prefix
		#elif ircdb.checkCapability(irc.prefix, 'owner') or ircdb.checkCapability(irc.prefix, '%s,op' % channel):
		#	owner = irc.prefix
		msg.command = 'PRIVMSG'
		(n,i,h) = ircutils.splitHostmask(owner)
		msg.prefix = ircutils.joinHostmask(irc.nick,i,h)
		self.Proxy(irc.irc, msg, tokens)
Esempio n. 11
0
 def makeBanmask(bannedHostmask, options):
     (nick, user, host) = ircutils.splitHostmask(bannedHostmask)
     self.log.debug('*** nick: %s', nick)
     self.log.debug('*** user: %s', user)
     self.log.debug('*** host: %s', host)
     bnick = '*'
     buser = '******'
     bhost = '*'
     for option in options:
         if option == 'nick':
             bnick = nick
         elif option == 'user':
             buser = user
         elif option == 'host':
             bhost = host
         elif option == 'exact':
             (bnick, buser, bhost) = \
                            ircutils.splitHostmask(bannedHostmask)
     return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 12
0
 def makeBanmask(bannedHostmask, options):
     (nick, user, host) = ircutils.splitHostmask(bannedHostmask)
     self.log.debug('*** nick: %s', nick)
     self.log.debug('*** user: %s', user)
     self.log.debug('*** host: %s', host)
     bnick = '*'
     buser = '******'
     bhost = '*'
     for option in options:
         if option == 'nick':
             bnick = nick
         elif option == 'user':
             buser = user
         elif option == 'host':
             bhost = host
         elif option == 'exact':
             (bnick, buser, bhost) = \
                            ircutils.splitHostmask(bannedHostmask)
     return ircutils.joinHostmask(bnick, buser, bhost)
Esempio n. 13
0
    def fakehostmask(self, irc, msg, args, hostmask, command):
        """<hostmask> <command>

        Runs <command> as if you were wearing the <hostmask>. Of course, usage
        of the command is restricted to the owner."""
        log.info('fakehostmask used to run "%s" as %s' % (command, hostmask))
        msg.prefix = hostmask
        (msg.nick, msg.user, msg.host)=ircutils.splitHostmask(hostmask)
        tokens = callbacks.tokenize(command)
        self.Proxy(irc.irc, msg, tokens)
Esempio n. 14
0
    def _canBomb(self, irc, channel, sender, victim, replyError):
        if sender.lower() in self.registryValue('exclusions', channel):
            if replyError:
                irc.reply('You can\'t timebomb anyone, since you\'re excluded from being timebombed')
            return False

        if sender not in irc.state.channels[channel].users:
            if replyError:
                irc.error(format('You must be in {} to timebomb in there.'.format(channel), Raise=True))
            return False
        bombHistoryOrig = self.registryValue('bombHistory', channel)
        bombHistory = []
        senderHostmask = irc.state.nickToHostmask(sender)
        (nick, user, host) = ircutils.splitHostmask(senderHostmask)
        senderMask = ('{}@{}'.format(user, host)).lower()
        victim = victim.lower()
        now = int(time.time())
        storeTime = self.registryValue('rateLimitTime', channel)
        victimCount = 0
        senderCount = 0
        totalCount = 0

        for bstr in bombHistoryOrig:
            b = bstr.split('#')
            if len(b) < 3 or int(b[0]) + storeTime < now:
                continue
            totalCount += 1

            if b[1] == senderMask:
                senderCount += 1

            if b[2] == victim:
                victimCount += 1
            bombHistory.append(bstr)
        self.setRegistryValue('bombHistory', bombHistory, channel)

        if (totalCount > storeTime *
                self.registryValue('rateLimitTotal', channel) / 3600):
            if replyError:
                irc.reply('Sorry, I\'ve stuffed so many timebombs down so many pairs of pants that I\'ve temporarily run out of explosives. You\'ll have to wait.')
            return False

        if (senderCount > storeTime *
            self.registryValue('rateLimitSender', channel) / 3600):

            if replyError:
                irc.reply('You\'ve timebombed a lot of people recently, let someone else have a go.')
            return False

        if (victimCount > storeTime *
            self.registryValue('rateLimitVictim', channel) / 3600):
            if replyError:
                irc.reply('That user has been timebombed a lot recently, try picking someone else.')
            return False
        return True
Esempio n. 15
0
def getmask(hostmask):
    if hostmask in _hostmaskToBanMask:
        return _hostmaskToBanMask[hostmask]
    (n, u, h) = ircutils.splitHostmask(hostmask)
    if h.find("$") != -1:
        h = h.split("$")[0]
    if h.count(":") > 3:
        a = h.split(":")
        m = a[0] + ":" + a[1] + ":" + a[2] + ":*"
        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", m)
        return _hostmaskToBanMask[hostmask]
    elif h.startswith("gateway/tor-sasl"):
        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", h)
        return _hostmaskToBanMask[hostmask]
    elif h.startswith("gateway/"):
        a = u.split("~")
        if len(a) > 1:
            u = "*" + a[1]
        else:
            u = a[0]
        ha = h.split("/")
        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", u, "%s/%s/%s/*" % (ha[0], ha[1], ha[2]))
        return _hostmaskToBanMask[hostmask]
    elif h.startswith("nat/"):
        a = h.split("/")
        b = u.split("~")
        if len(b) > 1:
            b = "*" + b[1]
        else:
            b = b[0]
        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", b, a[0] + "/" + a[1] + "/*")
        return _hostmaskToBanMask[hostmask]
    else:
        if h.find("/") == -1:
            if not isip(h):
                try:
                    r = socket.getaddrinfo(h, None)
                    if r[0][4][0].count("::") > 3:
                        a = r[0][4][0].split(":")
                        m = a[0] + ":" + a[1] + ":" + a[2] + ":*"
                        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", m)
                        return _hostmaskToBanMask[hostmask]
                    else:
                        _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", "*%s" % r[0][4][0])
                        return _hostmaskToBanMask[hostmask]
                except:
                    _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", "*%s" % h)
                    return _hostmaskToBanMask[hostmask]
            else:
                _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", "*%s" % h)
                return _hostmaskToBanMask[hostmask]
        else:
            _hostmaskToBanMask[hostmask] = ircutils.joinHostmask("*", "*", "*%s" % h)
            return _hostmaskToBanMask[hostmask]
    return None
Esempio n. 16
0
 def act (self, irc, msg, channel, command, owner):
     tokens = callbacks.tokenize(command)
     msg.command = 'PRIVMSG'
     (n,i,h) = ircutils.splitHostmask(owner)
     msg.prefix = ircutils.joinHostmask(irc.nick,i,h)
     
     def d():
         self.Proxy(irc.irc, msg, tokens)
     
     # Wait 30 seconds before sending PM
     schedule.addEvent(d,time.time()+30)
Esempio n. 17
0
    def _canBomb(self, irc, channel, sender, victim, replyError):
        if sender.lower() in self.registryValue("exclusions", channel):
            if replyError:
                irc.reply("You can't timebomb anyone, since you're excluded from being timebombed")
            return False

        if sender not in irc.state.channels[channel].users:
            if replyError:
                irc.error(format("You must be in {} to timebomb in there.".format(channel), Raise=True))
            return False
        bombHistoryOrig = self.registryValue("bombHistory", channel)
        bombHistory = []
        senderHostmask = irc.state.nickToHostmask(sender)
        (nick, user, host) = ircutils.splitHostmask(senderHostmask)
        senderMask = ("{}@{}".format(user, host)).lower()
        victim = victim.lower()
        now = int(time.time())
        storeTime = self.registryValue("rateLimitTime", channel)
        victimCount = 0
        senderCount = 0
        totalCount = 0

        for bstr in bombHistoryOrig:
            b = bstr.split("#")
            if len(b) < 3 or int(b[0]) + storeTime < now:
                continue
            totalCount += 1

            if b[1] == senderMask:
                senderCount += 1

            if b[2] == victim:
                victimCount += 1
            bombHistory.append(bstr)
        self.setRegistryValue("bombHistory", bombHistory, channel)

        if totalCount > storeTime * self.registryValue("rateLimitTotal", channel) / 3600:
            if replyError:
                irc.reply(
                    "Sorry, I've stuffed so many timebombs down so many pairs of pants that I've temporarily run out of explosives. You'll have to wait."
                )
            return False

        if senderCount > storeTime * self.registryValue("rateLimitSender", channel) / 3600:

            if replyError:
                irc.reply("You've timebombed a lot of people recently, let someone else have a go.")
            return False

        if victimCount > storeTime * self.registryValue("rateLimitVictim", channel) / 3600:
            if replyError:
                irc.reply("That user has been timebombed a lot recently, try picking someone else.")
            return False
        return True
Esempio n. 18
0
 def __init__(self, s="", command="", args=(), prefix="", msg=None):
     assert not (msg and s), "IrcMsg.__init__ cannot accept both s and msg"
     if not s and not command and not msg:
         raise MalformedIrcMsg, "IRC messages require a command."
     self._str = None
     self._repr = None
     self._hash = None
     self._len = None
     self.tags = {}
     self.identified = False
     if s:
         originalString = s
         try:
             if not s.endswith("\n"):
                 s += "\n"
             self._str = s
             if s[0] == ":":
                 self.prefix, s = s[1:].split(None, 1)
             else:
                 self.prefix = ""
             if " :" in s:  # Note the space: IPV6 addresses are bad w/o it.
                 s, last = s.split(" :", 1)
                 self.args = s.split()
                 self.args.append(last.rstrip("\r\n"))
             else:
                 self.args = s.split()
             self.command = self.args.pop(0)
         except (IndexError, ValueError):
             raise MalformedIrcMsg, repr(originalString)
     else:
         if msg is not None:
             if prefix:
                 self.prefix = prefix
             else:
                 self.prefix = msg.prefix
             if command:
                 self.command = command
             else:
                 self.command = msg.command
             if args:
                 self.args = args
             else:
                 self.args = msg.args
             self.tags = msg.tags.copy()
         else:
             self.prefix = prefix
             self.command = command
             assert all(ircutils.isValidArgument, args)
             self.args = args
     self.args = tuple(self.args)
     if isUserHostmask(self.prefix):
         (self.nick, self.user, self.host) = ircutils.splitHostmask(self.prefix)
     else:
         (self.nick, self.user, self.host) = (self.prefix,) * 3
Esempio n. 19
0
 def __init__(self, s='', command='', args=(), prefix='', msg=None):
     assert not (msg and s), 'IrcMsg.__init__ cannot accept both s and msg'
     if not s and not command and not msg:
         raise MalformedIrcMsg, 'IRC messages require a command.'
     self._str = None
     self._repr = None
     self._hash = None
     self._len = None
     self.tags = {}
     if s:
         originalString = s
         try:
             if not s.endswith('\n'):
                 s += '\n'
             self._str = s
             if s[0] == ':':
                 self.prefix, s = s[1:].split(None, 1)
             else:
                 self.prefix = ''
             if ' :' in s:  # Note the space: IPV6 addresses are bad w/o it.
                 s, last = s.split(' :', 1)
                 self.args = s.split()
                 self.args.append(last.rstrip('\r\n'))
             else:
                 self.args = s.split()
             self.command = self.args.pop(0)
         except (IndexError, ValueError):
             raise MalformedIrcMsg, repr(originalString)
     else:
         if msg is not None:
             if prefix:
                 self.prefix = prefix
             else:
                 self.prefix = msg.prefix
             if command:
                 self.command = command
             else:
                 self.command = msg.command
             if args:
                 self.args = args
             else:
                 self.args = msg.args
             self.tags = msg.tags.copy()
         else:
             self.prefix = prefix
             self.command = command
             assert all(ircutils.isValidArgument, args)
             self.args = args
     self.args = tuple(self.args)
     if isUserHostmask(self.prefix):
         (self.nick, self.user,
          self.host) = ircutils.splitHostmask(self.prefix)
     else:
         (self.nick, self.user, self.host) = (self.prefix, ) * 3
Esempio n. 20
0
 def doJoin(self, irc, msg):
     (n, i, h) = ircutils.splitHostmask(msg.prefix)
     channels = msg.args[0].split(',')
     for channel in channels:
         logChannel = self.registryValue('logChannel', channel=channel)
         if logChannel in irc.state.channels:
             check = self.check(h, channel)
             if check:
                 irc.queueMsg(
                     ircmsgs.privmsg(
                         logChannel, '[%s] %s (%s)' %
                         (channel, msg.prefix, ', '.join(check))))
Esempio n. 21
0
    def doPrivmsg(self, irc, msg):
        """This is called everytime an IRC message is recieved."""
        (recipients, text) = msg.args
        for channel in recipients.split(','):
            if irc.isChannel(channel):
                enable = self.registryValue('enable', channel=channel)
                if not enable:
                    return
                maxKick = self.registryValue('maxKick', channel=channel)
                self.queueKick.enqueue(msg)
                if self.queueKick.len(msg) > 4:
                    #self.queueKick.reset(msg)
                    self.queueBan.enqueue(msg)
                    maxKickBeforeBan = self.registryValue('maxKickToBan',
                                                          channel=channel)
                    reason = self.registryValue('reasonKick', channel=channel)
                    if self.queueBan.len(msg) > maxKickBeforeBan:
                        #self.queueBan.reset(msg)
                        self.queueLongBan.enqueue(msg)
                        maxBanToLongBan = self.registryValue('maxBanToLongBan',
                                                             channel=channel)
                        duration = int(0)
                        if self.queueLongBan.len(msg) > maxBanToLongBan:
                            #self.queueLongBan.reset(msg)
                            duration = int(
                                self.registryValue('durationLongBan',
                                                   channel=channel))
                        else:
                            duration = int(
                                self.registryValue('durationBan',
                                                   channel=channel))
                        hostmask = irc.state.nickToHostmask(msg.nick)
                        (nick, user, host) = ircutils.splitHostmask(hostmask)
                        banmask = ircutils.joinHostmask('*', '*', host)
                        irc.sendMsg(ircmsgs.ban(channel, banmask))
                        if duration > 0:

                            def ub():
                                if channel in irc.state.channels and banmask in irc.state.channels[
                                        channel].bans:
                                    irc.queueMsg(
                                        ircmsgs.unban(channel, banmask))

                            schedule.addEvent(ub, time.time() + duration)
                        reason = self.registryValue('reasonBan',
                                                    channel=channel)
                        #                        reason = reason % utils.timeElapsed(duration)
                        #                        irc.sendMsg(ircmsgs.IrcMsg('remove %s %s : %s' % (channel, msg.nick, reason)))
                        irc.reply('remove %s %s : %s' %
                                  (channel, msg.nick, reason))
                    self.log.info('remove %s %s : %s' %
                                  (channel, msg.nick, reason))
                    irc.sendMsg(ircmsgs.kick(channel, msg.nick, reason))
Esempio n. 22
0
	def proxyuser (self,irc,msg,args,nick):
		"""<nick|ip> 
		check<nick|ip>  against configured DNSBLS"""
		if ircutils.isUserHostmask(nick)
			h = irc.state.nickToHostmask(nick)
			(n,i,h) = ircutils.splitHostmask(h)
		else:
			h = nick
		check = self.check(h,'')
		if check and len(check):
			irc.reply(', '.join(check))
		else:
			irc.reply('%s is clean' % nick)
Esempio n. 23
0
    def proxyuser(self, irc, msg, args, nick):
        """<nick|ip>

		Checks <nick|ip> against configured DNSBLS"""
        if ircutils.isUserHostmask(nick):
            h = irc.state.nickToHostmask(nick)
            (n, i, h) = ircutils.splitHostmask(h)
        else:
            h = nick
        check = self.check(h, '')
        if check:
            irc.replies(check)
        else:
            irc.reply(_('%s is clean') % nick)
Esempio n. 24
0
	def doNick (self,irc,msg):
		oldNick = msg.prefix.split('!')[0]
		newNick = msg.args[0]
		for channel in irc.state.channels:
			if ircutils.isChannel(channel):
				chan = self.getChan(irc,channel)
				if oldNick in chan.nicks:
					item = chan.nicks[oldNick]
					(n,i,h) = ircutils.splitHostmask(item[0])
					item[0] = ircutils.joinHostmask(newNick,i,h)
					if 'nick' in chan.kinds:
						text = item[0]
						self.checkAndAct(irc,msg.prefix,chan,'nick',chan.kinds['nick'],'%s %s' % (oldNick,newNick),msg)
					del chan.nicks[oldNick]
					chan.nicks[newNick] = item
Esempio n. 25
0
 def doNick (self,irc,msg):
     oldNick = msg.prefix.split('!')[0]
     newNick = msg.args[0]
     for channel in irc.state.channels:
         if ircutils.isChannel(channel):
             chan = self.getChan(irc,channel)
             if oldNick in chan.nicks:
                 item = chan.nicks[oldNick]
                 (n,i,h) = ircutils.splitHostmask(item[0])
                 item[0] = ircutils.joinHostmask(newNick,i,h)
                 if 'nick' in chan.kinds:
                     text = item[0]
                     self.checkAndAct(irc,msg.prefix,chan,'nick',chan.kinds['nick'],'%s %s' % (oldNick,newNick),msg)
                 del chan.nicks[oldNick]
                 chan.nicks[newNick] = item
Esempio n. 26
0
 def doKick(self, irc, msg):
     self.addIRC(irc)
     args = {'kicked': msg.args[1], 'channel': msg.args[0],
             'kicker': msg.nick, 'message': msg.args[2], 'userhost': ''}
     if self.registryValue('color', msg.args[0]):
         args['kicked'] = '\x03%s%s\x03' % (self.simpleHash(msg.args[1]), args['kicked'])
     if self.registryValue('hostmasks', msg.args[0]):
         # The IRC protocol only sends the hostmask of the kicker, so we'll need
         # to use an alternate method to fetch the host of the person being
         # kicked. (in this case, using ircutils)
         h = ircutils.splitHostmask(irc.state.nickToHostmask(msg.args[1]))
         args['userhost'] = ' (%s@%s)' % (h[1], h[2])
     s = ('%(network)s%(kicked)s%(userhost)s has been kicked from '
          '%(channel)s by %(kicker)s (%(message)s)')
     self.sendToOthers(irc, msg.args[0], s, args)
Esempio n. 27
0
	def proxychannel (self,irc,msg,args,channel):
		""" [<channel>] checks all users against DNSBLs
		
		returns those who has an entry"""
		hs = []
		r = []
		for n in list(irc.state.channels[channel].users):
			hs.append(irc.state.nickToHostmask(n))
		irc.reply('please wait, %s users to check' % len(hs))
		for hostmask in hs:
			(n,i,h) = ircutils.splitHostmask(hostmask)
			check = self.check(h,channel)
			if check and len(check):
				r.append('%s (%s)' % (n,', '.join(check)))
		irc.reply(', '.join(r))
Esempio n. 28
0
    def proxychannel(self, irc, msg, args, channel):
        """[<channel>]
		
		Checks all users against DNSBLs and returns those who
		have an entry"""
        hs = []
        r = []
        for n in list(irc.state.channels[channel].users):
            hs.append(irc.state.nickToHostmask(n))
        irc.reply(_('please wait, %s users to check') % len(hs))
        for hostmask in hs:
            (n, i, h) = ircutils.splitHostmask(hostmask)
            check = self.check(h, channel)
            if check:
                r.append(format(_('%s (%L)'), n, check))
        irc.replies(r)
Esempio n. 29
0
    def doJoin(self, irc, msg):
        channel = msg.args[0]
        if not self.registryValue('enable', channel):
            return
        nick, ident, host = ircutils.splitHostmask(msg.prefix)

        fd = utils.web.getUrlFd('http://rbls.org/%s' % host)
        line = ' '
        while line and not line.startswith('<title>'):
            line = fd.readline()
        if not line:
            return
        if 'is listed in' in line:
            irc.queueMsg(ircmsgs.ban(channel, '*!*@%s' % host))
            irc.queueMsg(ircmsgs.kick(channel, nick))
        else:
            assert 'is not listed' in line
Esempio n. 30
0
    def doJoin(self, irc, msg):
        channel = msg.args[0]
        if not self.registryValue('enable', channel):
            return
        nick, ident, host = ircutils.splitHostmask(msg.prefix)

        fd = utils.web.getUrlFd('http://rbls.org/%s' % host)
        line = ' '
        while line and not line.startswith('<title>'):
            line = fd.readline()
        if not line:
            return
        if 'is listed in' in line:
            irc.queueMsg(ircmsgs.ban(channel, '*!*@%s' % host))
            irc.queueMsg(ircmsgs.kick(channel, nick))
        else:
            assert 'is not listed' in line
Esempio n. 31
0
    def testBotJoin(self):
        channel = '#test'
        self.irc.feedMsg(ircmsgs.join(channel, prefix=self.prefix))
        self.assertEqual(self.irc.takeMsg().command, 'MODE')
        self.assertEqual(self.irc.takeMsg().command, 'MODE')
        self.assertEqual(self.irc.takeMsg().command, 'WHO')
        self.assertEqual(self.irc.takeMsg(), None)

        self._register()
        self.assertRegexp('whoami', "I don't recognize you", frm=self.prefix1)
        (nick, ident, host) = ircutils.splitHostmask(self.prefix1)
        self.irc.feedMsg(
            ircmsgs.IrcMsg(
                ':card.freenode.net 354 pgjrgrg 1 %(ident)s 255.255.255.255 '
                '%(host)s %(nick)s H baz :gecos' %
                dict(nick=nick, ident=ident, host=host)))
        self.assertResponse('ping', 'pong')
        self.assertResponse('whoami', 'foobar', frm=self.prefix1)
Esempio n. 32
0
 def getHostFromBan(self, irc, msg, mask):
     if irc not in self.lastStates:
         self.lastStates[irc] = irc.state.copy()
     if mask[0] == '%':
         mask = mask[1:]
     try:
         (nick, ident, host) = ircutils.splitHostmask(mask)
     except AssertionError:
         # not a hostmask
         return None
     channel = None
     chan = None
     if mask[0] not in ('*', '?'): # Nick ban
         if nick in self.nicks:
             return self.nicks[nick]
     else: # Host/ident ban
         for (inick, ihost) in self.nicks.iteritems():
             if ircutils.hostmaskPatternEqual(mask, ihost):
                 return ihost
     return None
Esempio n. 33
0
 def _ban(self, irc, nick, channel):
     try:
         hostmask = irc.state.nickToHostmask(nick)
     except KeyError:
         return
     (nick, user, host) = ircutils.splitHostmask(hostmask)
     user = self._fnUser.sub('*', user)
     banmask = ircutils.joinHostmask('*', user, host)
     if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
         return
     irc.queueMsg(ircmsgs.ban(channel, banmask))
     irc.queueMsg(ircmsgs.kick(channel, nick))
     expiry = self.registryValue('autokban.timeout', channel)
     if expiry > 0:
         expiry += time.time()
         def f():
             if channel in irc.state.channels and \
                banmask in irc.state.channels[channel].bans:
                 irc.queueMsg(ircmsgs.unban(channel, banmask))
         schedule.addEvent(f, expiry)
Esempio n. 34
0
    def doPrivmsg(self, irc, msg):
        """This is called everytime an IRC message is recieved."""
        (recipients,text) = msg.args
        for channel in recipients.split(','):
            if irc.isChannel(channel):
                enable = self.registryValue('enable',channel=channel)
                if not enable:
                        return
                maxKick = self.registryValue('maxKick',channel=channel)
                self.queueKick.enqueue(msg)
                if self.queueKick.len(msg) > 4:
                    #self.queueKick.reset(msg)
                    self.queueBan.enqueue(msg)
                    maxKickBeforeBan = self.registryValue('maxKickToBan',channel=channel)
                    reason = self.registryValue('reasonKick',channel=channel)
                    if self.queueBan.len(msg) > maxKickBeforeBan:
                        #self.queueBan.reset(msg)
                        self.queueLongBan.enqueue(msg)
                        maxBanToLongBan = self.registryValue('maxBanToLongBan',channel=channel)
                        duration = int(0)
                        if self.queueLongBan.len(msg) > maxBanToLongBan:
                            #self.queueLongBan.reset(msg)
                            duration = int(self.registryValue('durationLongBan',channel=channel))
                        else:
                            duration = int(self.registryValue('durationBan',channel=channel))
                        hostmask = irc.state.nickToHostmask(msg.nick)
                        (nick, user, host) = ircutils.splitHostmask(hostmask)
                        banmask = ircutils.joinHostmask('*', '*', host)
                        irc.sendMsg(ircmsgs.ban(channel,banmask))
                        if duration > 0:
                            def ub():
                                if channel in irc.state.channels and banmask in irc.state.channels[channel].bans:
                                    irc.queueMsg(ircmsgs.unban(channel, banmask))
                            schedule.addEvent(ub,time.time()+duration)
                        reason = self.registryValue('reasonBan',channel=channel)
#                        reason = reason % utils.timeElapsed(duration)
#                        irc.sendMsg(ircmsgs.IrcMsg('remove %s %s : %s' % (channel, msg.nick, reason)))
                        irc.reply('remove %s %s : %s' % (channel, msg.nick, reason))
                    self.log.info('remove %s %s : %s' % (channel, msg.nick, reason))
                    irc.sendMsg(ircmsgs.kick(channel, msg.nick, reason))
Esempio n. 35
0
    def _ban(self, irc, nick, channel):
        try:
            hostmask = irc.state.nickToHostmask(nick)
        except KeyError:
            return
        (nick, user, host) = ircutils.splitHostmask(hostmask)
        user = self._fnUser.sub('*', user)
        banmask = ircutils.joinHostmask('*', user, host)
        if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
            return
        irc.queueMsg(ircmsgs.ban(channel, banmask))
        irc.queueMsg(ircmsgs.kick(channel, nick))
        expiry = self.registryValue('autokban.timeout', channel)
        if expiry > 0:
            expiry += time.time()

            def f():
                if channel in irc.state.channels and \
                   banmask in irc.state.channels[channel].bans:
                    irc.queueMsg(ircmsgs.unban(channel, banmask))

            schedule.addEvent(f, expiry)
Esempio n. 36
0
    def _canBomb(self, irc, channel, sender, victim, replyError):
        if sender.lower() in self.registryValue("exclusions", channel):
            if replyError:
                irc.reply(
                    "You can't bomb anyone because you're excluded from being bombed."
                )
            return False

        if sender not in irc.state.channels[channel].users:
            if replyError:
                irc.error(
                    format(
                        "You must be in {} to timebomb in there.".format(
                            channel),
                        Raise=True,
                    ))
            return False
        bombHistoryOrig = self.registryValue("bombHistory", channel)
        bombHistory = []
        senderHostmask = irc.state.nickToHostmask(sender)
        (nick, user, host) = ircutils.splitHostmask(senderHostmask)
        senderMask = ("{}@{}".format(user, host)).lower()
        victim = victim.lower()
        now = int(time.time())
        storeTime = self.registryValue("rateLimitTime", channel)
        victimCount = 0
        senderCount = 0
        totalCount = 0

        for bstr in bombHistoryOrig:
            b = bstr.split("#")
            if len(b) < 3 or int(b[0]) + storeTime < now:
                continue
            totalCount += 1

            if b[1] == senderMask:
                senderCount += 1

            if b[2] == victim:
                victimCount += 1
            bombHistory.append(bstr)
        self.setRegistryValue("bombHistory", bombHistory, channel)

        if (totalCount > storeTime *
                self.registryValue("rateLimitTotal", channel) / 3600):
            if replyError:
                irc.reply(
                    "Sorry, I've stuffed so many timebombs down so many pants that I've"
                    " temporarily run out of explosives. You'll have to wait.")
            return False

        if (senderCount > storeTime *
                self.registryValue("rateLimitSender", channel) / 3600):

            if replyError:
                irc.reply(
                    "You've timebombed a lot of people recently, let someone else have"
                    " a go.")
            return False

        if (victimCount > storeTime *
                self.registryValue("rateLimitVictim", channel) / 3600):
            if replyError:
                irc.reply(
                    "That user has been timebombed a lot recently, try picking someone"
                    " else.")
            return False
        return True