2005-01-19 14:14:38 +01:00
|
|
|
###
|
2009-04-02 18:45:00 +02:00
|
|
|
# Copyright (c) 2002-2009, Jeremiah Fincher
|
2011-01-27 19:32:43 +01:00
|
|
|
# Copyright (c) 2011, Valentin Lorentz
|
2013-09-22 17:13:52 +02:00
|
|
|
# Copyright (c) 2009,2013, James McCoy
|
2005-01-19 14:14:38 +01:00
|
|
|
# All rights reserved.
|
|
|
|
#
|
|
|
|
# Redistribution and use in source and binary forms, with or without
|
|
|
|
# modification, are permitted provided that the following conditions are met:
|
|
|
|
#
|
|
|
|
# * Redistributions of source code must retain the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer.
|
|
|
|
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer in the
|
|
|
|
# documentation and/or other materials provided with the distribution.
|
|
|
|
# * Neither the name of the author of this software nor the name of
|
|
|
|
# contributors to this software may be used to endorse or promote products
|
|
|
|
# derived from this software without specific prior written consent.
|
|
|
|
#
|
|
|
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
|
|
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
|
|
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
|
|
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
|
|
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
|
|
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
|
|
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
|
|
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
|
|
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
|
|
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
|
|
# POSSIBILITY OF SUCH DAMAGE.
|
|
|
|
###
|
|
|
|
|
|
|
|
import os
|
|
|
|
import time
|
|
|
|
import operator
|
|
|
|
|
2015-08-11 16:50:23 +02:00
|
|
|
from . import conf, ircutils, log, registry, unpreserve, utils, world
|
|
|
|
from .utils import minisix
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def isCapability(capability):
|
|
|
|
return len(capability.split(None, 1)) == 1
|
|
|
|
|
|
|
|
def fromChannelCapability(capability):
|
|
|
|
"""Returns a (channel, capability) tuple from a channel capability."""
|
|
|
|
assert isChannelCapability(capability), 'got %s' % capability
|
|
|
|
return capability.split(',', 1)
|
|
|
|
|
|
|
|
def isChannelCapability(capability):
|
|
|
|
"""Returns True if capability is a channel capability; False otherwise."""
|
|
|
|
if ',' in capability:
|
|
|
|
(channel, capability) = capability.split(',', 1)
|
|
|
|
return ircutils.isChannel(channel) and isCapability(capability)
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def makeChannelCapability(channel, capability):
|
|
|
|
"""Makes a channel capability given a channel and a capability."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
assert ircutils.isChannel(channel), 'got %s' % channel
|
|
|
|
return '%s,%s' % (channel, capability)
|
|
|
|
|
|
|
|
def isAntiCapability(capability):
|
|
|
|
"""Returns True if capability is an anticapability; False otherwise."""
|
|
|
|
if isChannelCapability(capability):
|
|
|
|
(_, capability) = fromChannelCapability(capability)
|
|
|
|
return isCapability(capability) and capability[0] == '-'
|
|
|
|
|
|
|
|
def makeAntiCapability(capability):
|
|
|
|
"""Returns the anticapability of a given capability."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
assert not isAntiCapability(capability), \
|
|
|
|
'makeAntiCapability does not work on anticapabilities. ' \
|
|
|
|
'You probably want invertCapability; got %s.' % capability
|
|
|
|
if isChannelCapability(capability):
|
|
|
|
(channel, capability) = fromChannelCapability(capability)
|
|
|
|
return makeChannelCapability(channel, '-' + capability)
|
|
|
|
else:
|
|
|
|
return '-' + capability
|
|
|
|
|
|
|
|
def unAntiCapability(capability):
|
|
|
|
"""Takes an anticapability and returns the non-anti form."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
if not isAntiCapability(capability):
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('%s is not an anti capability' % capability)
|
2005-01-19 14:14:38 +01:00
|
|
|
if isChannelCapability(capability):
|
|
|
|
(channel, capability) = fromChannelCapability(capability)
|
|
|
|
return ','.join((channel, capability[1:]))
|
|
|
|
else:
|
|
|
|
return capability[1:]
|
|
|
|
|
|
|
|
def invertCapability(capability):
|
|
|
|
"""Make a capability into an anticapability and vice versa."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
if isAntiCapability(capability):
|
|
|
|
return unAntiCapability(capability)
|
|
|
|
else:
|
|
|
|
return makeAntiCapability(capability)
|
|
|
|
|
|
|
|
def canonicalCapability(capability):
|
|
|
|
if callable(capability):
|
|
|
|
capability = capability()
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
return capability.lower()
|
|
|
|
|
2012-08-05 09:54:34 +02:00
|
|
|
_unwildcard_remover = utils.str.MultipleRemover('!@*?')
|
2005-01-19 14:14:38 +01:00
|
|
|
def unWildcardHostmask(hostmask):
|
2012-08-05 09:54:34 +02:00
|
|
|
return _unwildcard_remover(hostmask)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
_invert = invertCapability
|
2005-02-04 04:11:02 +01:00
|
|
|
class CapabilitySet(set):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""A subclass of set handling basic capability stuff."""
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('__parent',)
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self, capabilities=()):
|
|
|
|
self.__parent = super(CapabilitySet, self)
|
|
|
|
self.__parent.__init__()
|
|
|
|
for capability in capabilities:
|
|
|
|
self.add(capability)
|
|
|
|
|
|
|
|
def add(self, capability):
|
|
|
|
"""Adds a capability to the set."""
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
inverted = _invert(capability)
|
|
|
|
if self.__parent.__contains__(inverted):
|
|
|
|
self.__parent.remove(inverted)
|
|
|
|
self.__parent.add(capability)
|
|
|
|
|
|
|
|
def remove(self, capability):
|
|
|
|
"""Removes a capability from the set."""
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
self.__parent.remove(capability)
|
|
|
|
|
|
|
|
def __contains__(self, capability):
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
if self.__parent.__contains__(capability):
|
|
|
|
return True
|
|
|
|
if self.__parent.__contains__(_invert(capability)):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2013-12-27 16:04:32 +01:00
|
|
|
def check(self, capability, ignoreOwner=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Returns the appropriate boolean for whether a given capability is
|
|
|
|
'allowed' given its (or its anticapability's) presence in the set.
|
|
|
|
"""
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
if self.__parent.__contains__(capability):
|
|
|
|
return True
|
|
|
|
elif self.__parent.__contains__(_invert(capability)):
|
|
|
|
return False
|
|
|
|
else:
|
2012-08-04 15:57:51 +02:00
|
|
|
raise KeyError
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '%s([%s])' % (self.__class__.__name__,
|
2014-01-21 10:50:55 +01:00
|
|
|
', '.join(map(repr, self)))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
antiOwner = makeAntiCapability('owner')
|
|
|
|
class UserCapabilitySet(CapabilitySet):
|
|
|
|
"""A subclass of CapabilitySet to handle the owner capability correctly."""
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('__parent',)
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.__parent = super(UserCapabilitySet, self)
|
|
|
|
self.__parent.__init__(*args, **kwargs)
|
|
|
|
|
2011-01-27 19:32:43 +01:00
|
|
|
def __contains__(self, capability, ignoreOwner=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
capability = ircutils.toLower(capability)
|
2011-01-27 19:32:43 +01:00
|
|
|
if not ignoreOwner and capability == 'owner' or capability == antiOwner:
|
2005-01-19 14:14:38 +01:00
|
|
|
return True
|
2011-01-27 19:32:43 +01:00
|
|
|
elif not ignoreOwner and self.__parent.__contains__('owner'):
|
2005-01-19 14:14:38 +01:00
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return self.__parent.__contains__(capability)
|
|
|
|
|
2011-01-27 19:32:43 +01:00
|
|
|
def check(self, capability, ignoreOwner=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Returns the appropriate boolean for whether a given capability is
|
|
|
|
'allowed' given its (or its anticapability's) presence in the set.
|
|
|
|
Differs from CapabilitySet in that it handles the 'owner' capability
|
|
|
|
appropriately.
|
|
|
|
"""
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
if capability == 'owner' or capability == antiOwner:
|
|
|
|
if self.__parent.__contains__('owner'):
|
|
|
|
return not isAntiCapability(capability)
|
|
|
|
else:
|
|
|
|
return isAntiCapability(capability)
|
2011-01-27 19:32:43 +01:00
|
|
|
elif not ignoreOwner and self.__parent.__contains__('owner'):
|
2005-01-19 14:14:38 +01:00
|
|
|
if isAntiCapability(capability):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return self.__parent.check(capability)
|
|
|
|
|
|
|
|
def add(self, capability):
|
|
|
|
"""Adds a capability to the set. Just make sure it's not -owner."""
|
|
|
|
capability = ircutils.toLower(capability)
|
|
|
|
assert capability != '-owner', '"-owner" disallowed.'
|
|
|
|
self.__parent.add(capability)
|
|
|
|
|
|
|
|
class IrcUser(object):
|
|
|
|
"""This class holds the capabilities and authentications for a user."""
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('id', 'auth', 'name', 'ignore', 'secure', 'hashed',
|
|
|
|
'password', 'capabilities', 'hostmasks', 'nicks', 'gpgkeys')
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self, ignore=False, password='', name='',
|
2012-11-04 01:28:24 +01:00
|
|
|
capabilities=(), hostmasks=None, nicks=None,
|
|
|
|
secure=False, hashed=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
self.id = None
|
|
|
|
self.auth = [] # The (time, hostmask) list of auth crap.
|
|
|
|
self.name = name # The name of the user.
|
|
|
|
self.ignore = ignore # A boolean deciding if the person is ignored.
|
|
|
|
self.secure = secure # A boolean describing if hostmasks *must* match.
|
|
|
|
self.hashed = hashed # True if the password is hashed on disk.
|
|
|
|
self.password = password # password (plaintext? hashed?)
|
|
|
|
self.capabilities = UserCapabilitySet()
|
|
|
|
for capability in capabilities:
|
|
|
|
self.capabilities.add(capability)
|
|
|
|
if hostmasks is None:
|
|
|
|
self.hostmasks = ircutils.IrcSet() # hostmasks used for recognition
|
|
|
|
else:
|
|
|
|
self.hostmasks = hostmasks
|
2012-11-04 01:28:24 +01:00
|
|
|
if nicks is None:
|
|
|
|
self.nicks = {} # {'network1': ['foo', 'bar'], 'network': ['baz']}
|
|
|
|
else:
|
|
|
|
self.nicks = nicks
|
2012-08-02 09:21:58 +02:00
|
|
|
self.gpgkeys = [] # GPG key ids
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def __repr__(self):
|
2005-01-31 15:52:27 +01:00
|
|
|
return format('%s(id=%s, ignore=%s, password="", name=%q, hashed=%r, '
|
|
|
|
'capabilities=%r, hostmasks=[], secure=%r)\n',
|
|
|
|
self.__class__.__name__, self.id, self.ignore,
|
|
|
|
self.name, self.hashed, self.capabilities, self.secure)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.id)
|
|
|
|
|
|
|
|
def addCapability(self, capability):
|
|
|
|
"""Gives the user the given capability."""
|
|
|
|
self.capabilities.add(capability)
|
|
|
|
|
|
|
|
def removeCapability(self, capability):
|
|
|
|
"""Takes from the user the given capability."""
|
|
|
|
self.capabilities.remove(capability)
|
|
|
|
|
2011-01-27 19:32:43 +01:00
|
|
|
def _checkCapability(self, capability, ignoreOwner=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Checks the user for a given capability."""
|
|
|
|
if self.ignore:
|
|
|
|
if isAntiCapability(capability):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
else:
|
2013-12-27 16:04:32 +01:00
|
|
|
return self.capabilities.check(capability, ignoreOwner=ignoreOwner)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def setPassword(self, password, hashed=False):
|
|
|
|
"""Sets the user's password."""
|
|
|
|
if hashed or self.hashed:
|
|
|
|
self.hashed = True
|
2005-02-15 14:57:57 +01:00
|
|
|
self.password = utils.saltHash(password)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
self.password = password
|
|
|
|
|
|
|
|
def checkPassword(self, password):
|
|
|
|
"""Checks the user's password."""
|
2005-10-14 14:58:41 +02:00
|
|
|
if password is None:
|
|
|
|
return False
|
2005-01-19 14:14:38 +01:00
|
|
|
if self.hashed:
|
|
|
|
(salt, _) = self.password.split('|')
|
2005-02-15 14:57:57 +01:00
|
|
|
return (self.password == utils.saltHash(password, salt=salt))
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
return (self.password == password)
|
|
|
|
|
|
|
|
def checkHostmask(self, hostmask, useAuth=True):
|
|
|
|
"""Checks a given hostmask against the user's hostmasks or current
|
|
|
|
authentication. If useAuth is False, only checks against the user's
|
|
|
|
hostmasks.
|
|
|
|
"""
|
|
|
|
if useAuth:
|
|
|
|
timeout = conf.supybot.databases.users.timeoutIdentification()
|
|
|
|
removals = []
|
|
|
|
try:
|
|
|
|
for (when, authmask) in self.auth:
|
|
|
|
if timeout and when+timeout < time.time():
|
|
|
|
removals.append((when, authmask))
|
|
|
|
elif hostmask == authmask:
|
|
|
|
return True
|
|
|
|
finally:
|
|
|
|
while removals:
|
|
|
|
self.auth.remove(removals.pop())
|
|
|
|
for pat in self.hostmasks:
|
|
|
|
if ircutils.hostmaskPatternEqual(pat, hostmask):
|
|
|
|
return pat
|
|
|
|
return False
|
|
|
|
|
|
|
|
def addHostmask(self, hostmask):
|
|
|
|
"""Adds a hostmask to the user's hostmasks."""
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
2012-04-04 15:08:49 +02:00
|
|
|
if len(unWildcardHostmask(hostmask)) < 3:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Hostmask must contain at least 3 non-wildcard characters.')
|
2005-01-19 14:14:38 +01:00
|
|
|
self.hostmasks.add(hostmask)
|
|
|
|
|
|
|
|
def removeHostmask(self, hostmask):
|
|
|
|
"""Removes a hostmask from the user's hostmasks."""
|
|
|
|
self.hostmasks.remove(hostmask)
|
|
|
|
|
2012-11-04 01:28:24 +01:00
|
|
|
def checkNick(self, network, nick):
|
|
|
|
"""Checks a given nick against the user's nicks."""
|
|
|
|
return nick in self.nicks[network]
|
|
|
|
|
|
|
|
def addNick(self, network, nick):
|
|
|
|
"""Adds a nick to the user's registered nicks on the network."""
|
|
|
|
global users
|
2015-08-10 20:24:11 +02:00
|
|
|
assert isinstance(network, minisix.string_types)
|
2012-11-04 01:28:24 +01:00
|
|
|
assert ircutils.isNick(nick), 'got %s' % nick
|
|
|
|
if users.getUserFromNick(network, nick) is not None:
|
|
|
|
raise KeyError
|
|
|
|
if network not in self.nicks:
|
|
|
|
self.nicks[network] = []
|
|
|
|
if nick not in self.nicks[network]:
|
|
|
|
self.nicks[network].append(nick)
|
|
|
|
|
|
|
|
def removeNick(self, network, nick):
|
|
|
|
"""Removes a nick from the user's registered nicks on the network."""
|
2015-08-10 20:24:11 +02:00
|
|
|
assert isinstance(network, minisix.string_types)
|
2012-11-04 01:28:24 +01:00
|
|
|
if nick not in self.nicks[network]:
|
|
|
|
raise KeyError
|
|
|
|
self.nicks[network].remove(nick)
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def addAuth(self, hostmask):
|
2013-09-22 17:13:52 +02:00
|
|
|
"""Sets a user's authenticated hostmask. This times out according to
|
|
|
|
conf.supybot.timeoutIdentification. If hostmask exactly matches an
|
|
|
|
existing, known hostmask, the previous entry is removed."""
|
2005-01-19 14:14:38 +01:00
|
|
|
if self.checkHostmask(hostmask, useAuth=False) or not self.secure:
|
|
|
|
self.auth.append((time.time(), hostmask))
|
2013-09-22 17:13:52 +02:00
|
|
|
knownHostmasks = set()
|
|
|
|
def uniqueHostmask(auth):
|
|
|
|
(_, mask) = auth
|
|
|
|
if mask not in knownHostmasks:
|
|
|
|
knownHostmasks.add(mask)
|
|
|
|
return True
|
|
|
|
return False
|
Start accelerating the 2to3 step (remove fix_apply, fix_buffer, fix_callable, fix_exec, fix_execfile, fix_exitfunc, fix_filter, fix_funcattrs, fix_future, fix_getcwdu, and fix_has_key).
2014-01-20 14:49:47 +01:00
|
|
|
uniqued = list(filter(uniqueHostmask, reversed(self.auth)))
|
2013-09-22 17:13:52 +02:00
|
|
|
self.auth = list(reversed(uniqued))
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('secure flag set, unmatched hostmask')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def clearAuth(self):
|
|
|
|
"""Unsets a user's authenticated hostmask."""
|
|
|
|
for (when, hostmask) in self.auth:
|
|
|
|
users.invalidateCache(hostmask=hostmask)
|
|
|
|
self.auth = []
|
|
|
|
|
|
|
|
def preserve(self, fd, indent=''):
|
|
|
|
def write(s):
|
|
|
|
fd.write(indent)
|
|
|
|
fd.write(s)
|
|
|
|
fd.write(os.linesep)
|
|
|
|
write('name %s' % self.name)
|
|
|
|
write('ignore %s' % self.ignore)
|
|
|
|
write('secure %s' % self.secure)
|
2016-02-07 10:49:17 +01:00
|
|
|
if self.password:
|
|
|
|
write('hashed %s' % self.hashed)
|
|
|
|
write('password %s' % self.password)
|
2005-01-19 14:14:38 +01:00
|
|
|
for capability in self.capabilities:
|
|
|
|
write('capability %s' % capability)
|
|
|
|
for hostmask in self.hostmasks:
|
|
|
|
write('hostmask %s' % hostmask)
|
2012-11-04 01:28:24 +01:00
|
|
|
for network, nicks in self.nicks.items():
|
|
|
|
write('nicks %s %s' % (network, ' '.join(nicks)))
|
2012-08-02 09:21:58 +02:00
|
|
|
for key in self.gpgkeys:
|
|
|
|
write('gpgkey %s' % key)
|
2005-01-19 14:14:38 +01:00
|
|
|
fd.write(os.linesep)
|
|
|
|
|
|
|
|
|
|
|
|
class IrcChannel(object):
|
|
|
|
"""This class holds the capabilities, bans, and ignores of a channel."""
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('defaultAllow', 'expiredBans', 'bans', 'ignores', 'silences',
|
|
|
|
'exceptions', 'capabilities', 'lobotomized')
|
2005-01-19 14:14:38 +01:00
|
|
|
defaultOff = ('op', 'halfop', 'voice', 'protected')
|
|
|
|
def __init__(self, bans=None, silences=None, exceptions=None, ignores=None,
|
|
|
|
capabilities=None, lobotomized=False, defaultAllow=True):
|
|
|
|
self.defaultAllow = defaultAllow
|
|
|
|
self.expiredBans = []
|
|
|
|
self.bans = bans or {}
|
|
|
|
self.ignores = ignores or {}
|
|
|
|
self.silences = silences or []
|
|
|
|
self.exceptions = exceptions or []
|
|
|
|
self.capabilities = capabilities or CapabilitySet()
|
|
|
|
for capability in self.defaultOff:
|
|
|
|
if capability not in self.capabilities:
|
|
|
|
self.capabilities.add(makeAntiCapability(capability))
|
|
|
|
self.lobotomized = lobotomized
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '%s(bans=%r, ignores=%r, capabilities=%r, ' \
|
|
|
|
'lobotomized=%r, defaultAllow=%s, ' \
|
|
|
|
'silences=%r, exceptions=%r)\n' % \
|
|
|
|
(self.__class__.__name__, self.bans, self.ignores,
|
|
|
|
self.capabilities, self.lobotomized,
|
|
|
|
self.defaultAllow, self.silences, self.exceptions)
|
|
|
|
|
2015-05-24 01:08:54 +02:00
|
|
|
def addBan(self, hostmask, expiration=0):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Adds a ban to the channel banlist."""
|
2012-12-02 19:04:48 +01:00
|
|
|
assert not conf.supybot.protocols.irc.strictRfc() or \
|
|
|
|
ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
2015-05-24 01:08:54 +02:00
|
|
|
self.bans[hostmask] = int(expiration)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def removeBan(self, hostmask):
|
|
|
|
"""Removes a ban from the channel banlist."""
|
2012-12-02 19:04:48 +01:00
|
|
|
assert not conf.supybot.protocols.irc.strictRfc() or \
|
|
|
|
ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
2005-01-19 14:14:38 +01:00
|
|
|
return self.bans.pop(hostmask)
|
|
|
|
|
|
|
|
def checkBan(self, hostmask):
|
|
|
|
"""Checks whether a given hostmask is banned by the channel banlist."""
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
|
|
|
now = time.time()
|
2015-09-02 17:00:20 +02:00
|
|
|
for (pattern, expiration) in list(self.bans.items()):
|
2005-01-19 14:14:38 +01:00
|
|
|
if now < expiration or not expiration:
|
|
|
|
if ircutils.hostmaskPatternEqual(pattern, hostmask):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
self.expiredBans.append((pattern, expiration))
|
|
|
|
del self.bans[pattern]
|
|
|
|
return False
|
|
|
|
|
|
|
|
def addIgnore(self, hostmask, expiration=0):
|
|
|
|
"""Adds an ignore to the channel ignore list."""
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
|
|
|
self.ignores[hostmask] = int(expiration)
|
|
|
|
|
|
|
|
def removeIgnore(self, hostmask):
|
|
|
|
"""Removes an ignore from the channel ignore list."""
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
|
|
|
return self.ignores.pop(hostmask)
|
|
|
|
|
|
|
|
def addCapability(self, capability):
|
|
|
|
"""Adds a capability to the channel's default capabilities."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
self.capabilities.add(capability)
|
|
|
|
|
|
|
|
def removeCapability(self, capability):
|
|
|
|
"""Removes a capability from the channel's default capabilities."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
self.capabilities.remove(capability)
|
|
|
|
|
|
|
|
def setDefaultCapability(self, b):
|
|
|
|
"""Sets the default capability in the channel."""
|
|
|
|
self.defaultAllow = b
|
|
|
|
|
2013-12-27 16:04:32 +01:00
|
|
|
def _checkCapability(self, capability, ignoreOwner=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Checks whether a certain capability is allowed by the channel."""
|
|
|
|
assert isCapability(capability), 'got %s' % capability
|
|
|
|
if capability in self.capabilities:
|
2013-12-27 16:04:32 +01:00
|
|
|
return self.capabilities.check(capability, ignoreOwner=ignoreOwner)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
if isAntiCapability(capability):
|
|
|
|
return not self.defaultAllow
|
|
|
|
else:
|
|
|
|
return self.defaultAllow
|
|
|
|
|
|
|
|
def checkIgnored(self, hostmask):
|
|
|
|
"""Checks whether a given hostmask is to be ignored by the channel."""
|
|
|
|
if self.lobotomized:
|
|
|
|
return True
|
|
|
|
if world.testing:
|
|
|
|
return False
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
|
|
|
if self.checkBan(hostmask):
|
|
|
|
return True
|
|
|
|
now = time.time()
|
2015-09-02 17:00:20 +02:00
|
|
|
for (pattern, expiration) in list(self.ignores.items()):
|
2005-01-19 14:14:38 +01:00
|
|
|
if now < expiration or not expiration:
|
|
|
|
if ircutils.hostmaskPatternEqual(pattern, hostmask):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
del self.ignores[pattern]
|
|
|
|
# Later we may wish to keep expiredIgnores, but not now.
|
|
|
|
return False
|
|
|
|
|
|
|
|
def preserve(self, fd, indent=''):
|
|
|
|
def write(s):
|
|
|
|
fd.write(indent)
|
|
|
|
fd.write(s)
|
|
|
|
fd.write(os.linesep)
|
|
|
|
write('lobotomized %s' % self.lobotomized)
|
|
|
|
write('defaultAllow %s' % self.defaultAllow)
|
|
|
|
for capability in self.capabilities:
|
|
|
|
write('capability ' + capability)
|
2015-08-08 22:20:14 +02:00
|
|
|
bans = list(self.bans.items())
|
2015-05-24 01:08:54 +02:00
|
|
|
utils.sortBy(operator.itemgetter(1), bans)
|
|
|
|
for (ban, expiration) in bans:
|
|
|
|
write('ban %s %d' % (ban, expiration))
|
2015-08-08 22:20:14 +02:00
|
|
|
ignores = list(self.ignores.items())
|
2005-02-15 14:57:57 +01:00
|
|
|
utils.sortBy(operator.itemgetter(1), ignores)
|
2005-01-19 14:14:38 +01:00
|
|
|
for (ignore, expiration) in ignores:
|
|
|
|
write('ignore %s %d' % (ignore, expiration))
|
|
|
|
fd.write(os.linesep)
|
|
|
|
|
|
|
|
|
|
|
|
class Creator(object):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ()
|
2005-01-19 14:14:38 +01:00
|
|
|
def badCommand(self, command, rest, lineno):
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Invalid command on line %s: %s' % (lineno, command))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
class IrcUserCreator(Creator):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('users')
|
2005-01-19 14:14:38 +01:00
|
|
|
u = None
|
|
|
|
def __init__(self, users):
|
|
|
|
if self.u is None:
|
|
|
|
IrcUserCreator.u = IrcUser()
|
|
|
|
self.users = users
|
|
|
|
|
|
|
|
def user(self, rest, lineno):
|
|
|
|
if self.u.id is not None:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Unexpected user command on line %s.' % lineno)
|
2005-01-19 14:14:38 +01:00
|
|
|
self.u.id = int(rest)
|
|
|
|
|
|
|
|
def _checkId(self):
|
|
|
|
if self.u.id is None:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Unexpected user description without user.')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def name(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.u.name = rest
|
|
|
|
|
|
|
|
def ignore(self, rest, lineno):
|
|
|
|
self._checkId()
|
2017-02-25 13:10:33 +01:00
|
|
|
self.u.ignore = bool(utils.gen.safeEval(rest))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def secure(self, rest, lineno):
|
|
|
|
self._checkId()
|
2017-02-25 13:10:33 +01:00
|
|
|
self.u.secure = bool(utils.gen.safeEval(rest))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def hashed(self, rest, lineno):
|
|
|
|
self._checkId()
|
2017-02-25 13:10:33 +01:00
|
|
|
self.u.hashed = bool(utils.gen.safeEval(rest))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def password(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.u.password = rest
|
|
|
|
|
|
|
|
def hostmask(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.u.hostmasks.add(rest)
|
|
|
|
|
2012-11-04 01:28:24 +01:00
|
|
|
def nicks(self, rest, lineno):
|
|
|
|
self._checkId()
|
2012-11-07 19:00:41 +01:00
|
|
|
network, nicks = rest.split(' ', 1)
|
2012-11-04 01:28:24 +01:00
|
|
|
self.u.nicks[network] = nicks.split(' ')
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def capability(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.u.capabilities.add(rest)
|
|
|
|
|
2012-08-02 09:21:58 +02:00
|
|
|
def gpgkey(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.u.gpgkeys.append(rest)
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def finish(self):
|
|
|
|
if self.u.name:
|
|
|
|
try:
|
|
|
|
self.users.setUser(self.u)
|
|
|
|
except DuplicateHostmask:
|
|
|
|
log.error('Hostmasks for %s collided with another user\'s. '
|
2013-09-17 15:32:52 +02:00
|
|
|
'Resetting hostmasks for %s.',
|
|
|
|
self.u.name, self.u.name)
|
2005-01-19 14:14:38 +01:00
|
|
|
# Some might argue that this is arbitrary, and perhaps it is.
|
|
|
|
# But we've got to do *something*, so we'll show some deference
|
|
|
|
# to our lower-numbered users.
|
|
|
|
self.u.hostmasks.clear()
|
|
|
|
self.users.setUser(self.u)
|
|
|
|
IrcUserCreator.u = None
|
|
|
|
|
|
|
|
class IrcChannelCreator(Creator):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('c', 'channels', 'hadChannel')
|
2005-01-19 14:14:38 +01:00
|
|
|
name = None
|
|
|
|
def __init__(self, channels):
|
|
|
|
self.c = IrcChannel()
|
|
|
|
self.channels = channels
|
|
|
|
self.hadChannel = bool(self.name)
|
|
|
|
|
|
|
|
def channel(self, rest, lineno):
|
|
|
|
if self.name is not None:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Unexpected channel command on line %s' % lineno)
|
2005-01-19 14:14:38 +01:00
|
|
|
IrcChannelCreator.name = rest
|
|
|
|
|
|
|
|
def _checkId(self):
|
|
|
|
if self.name is None:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ValueError('Unexpected channel description without channel.')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def lobotomized(self, rest, lineno):
|
|
|
|
self._checkId()
|
2017-02-25 13:10:33 +01:00
|
|
|
self.c.lobotomized = bool(utils.gen.safeEval(rest))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def defaultallow(self, rest, lineno):
|
|
|
|
self._checkId()
|
2017-02-25 13:10:33 +01:00
|
|
|
self.c.defaultAllow = bool(utils.gen.safeEval(rest))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def capability(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
self.c.capabilities.add(rest)
|
|
|
|
|
|
|
|
def ban(self, rest, lineno):
|
|
|
|
self._checkId()
|
2015-05-24 01:08:54 +02:00
|
|
|
(pattern, expiration) = rest.split()
|
2005-01-19 14:14:38 +01:00
|
|
|
self.c.bans[pattern] = int(float(expiration))
|
|
|
|
|
|
|
|
def ignore(self, rest, lineno):
|
|
|
|
self._checkId()
|
|
|
|
(pattern, expiration) = rest.split()
|
|
|
|
self.c.ignores[pattern] = int(float(expiration))
|
|
|
|
|
|
|
|
def finish(self):
|
|
|
|
if self.hadChannel:
|
|
|
|
self.channels.setChannel(self.name, self.c)
|
|
|
|
IrcChannelCreator.name = None
|
|
|
|
|
|
|
|
|
|
|
|
class DuplicateHostmask(ValueError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class UsersDictionary(utils.IterableMap):
|
|
|
|
"""A simple serialized-to-file User Database."""
|
2019-09-28 10:33:10 +02:00
|
|
|
__slots__ = ('noFlush', 'filename', 'users', '_nameCache',
|
|
|
|
'_hostmaskCache')
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self):
|
2019-09-28 10:33:10 +02:00
|
|
|
self.noFlush = False
|
2005-01-19 14:14:38 +01:00
|
|
|
self.filename = None
|
|
|
|
self.users = {}
|
|
|
|
self.nextId = 0
|
2009-04-02 18:45:00 +02:00
|
|
|
self._nameCache = utils.structures.CacheDict(1000)
|
|
|
|
self._hostmaskCache = utils.structures.CacheDict(1000)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2019-09-28 10:33:10 +02:00
|
|
|
# This is separate because the Creator has to access our instance.
|
2005-01-19 14:14:38 +01:00
|
|
|
def open(self, filename):
|
|
|
|
self.filename = filename
|
2019-09-28 10:33:10 +02:00
|
|
|
reader = unpreserve.Reader(IrcUserCreator, self)
|
|
|
|
try:
|
|
|
|
self.noFlush = True
|
|
|
|
try:
|
|
|
|
reader.readFile(filename)
|
|
|
|
self.noFlush = False
|
|
|
|
self.flush()
|
|
|
|
except EnvironmentError as e:
|
|
|
|
log.error('Invalid user dictionary file, resetting to empty.')
|
|
|
|
log.error('Exact error: %s', utils.exnToString(e))
|
|
|
|
except Exception as e:
|
|
|
|
log.exception('Exact error:')
|
|
|
|
finally:
|
|
|
|
self.noFlush = False
|
|
|
|
|
|
|
|
def reload(self):
|
|
|
|
"""Reloads the database from its file."""
|
|
|
|
if self.filename is not None:
|
2019-09-28 10:33:54 +02:00
|
|
|
self.nextId = 0
|
|
|
|
self.users.clear()
|
|
|
|
self._nameCache.clear()
|
|
|
|
self._hostmaskCache.clear()
|
2019-09-28 10:33:10 +02:00
|
|
|
try:
|
|
|
|
self.open(self.filename)
|
|
|
|
except EnvironmentError as e:
|
|
|
|
log.warning('UsersDictionary.reload failed: %s', e)
|
|
|
|
else:
|
|
|
|
log.error('UsersDictionary.reload called with no filename.')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
"""Flushes the database to its file."""
|
2019-09-28 10:33:10 +02:00
|
|
|
if not self.noFlush:
|
|
|
|
if self.filename is not None:
|
|
|
|
L = list(self.users.items())
|
|
|
|
L.sort()
|
|
|
|
fd = utils.file.AtomicFile(self.filename)
|
|
|
|
for (id, u) in L:
|
|
|
|
fd.write('user %s' % id)
|
|
|
|
fd.write(os.linesep)
|
|
|
|
u.preserve(fd, indent=' ')
|
|
|
|
fd.close()
|
|
|
|
else:
|
|
|
|
log.error('UsersDictionary.flush called with no filename.')
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2019-09-28 10:33:10 +02:00
|
|
|
log.debug('Not flushing UsersDictionary because of noFlush.')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self.flush()
|
|
|
|
if self.flush in world.flushers:
|
|
|
|
world.flushers.remove(self.flush)
|
|
|
|
self.users.clear()
|
|
|
|
|
2015-08-08 22:20:14 +02:00
|
|
|
def items(self):
|
|
|
|
return self.users.items()
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getUserId(self, s):
|
|
|
|
"""Returns the user ID of a given name or hostmask."""
|
|
|
|
if ircutils.isUserHostmask(s):
|
|
|
|
try:
|
|
|
|
return self._hostmaskCache[s]
|
|
|
|
except KeyError:
|
|
|
|
ids = {}
|
2015-08-08 22:20:14 +02:00
|
|
|
for (id, user) in self.users.items():
|
2005-01-19 14:14:38 +01:00
|
|
|
x = user.checkHostmask(s)
|
|
|
|
if x:
|
|
|
|
ids[id] = x
|
|
|
|
if len(ids) == 1:
|
2015-08-08 22:20:14 +02:00
|
|
|
id = list(ids.keys())[0]
|
2005-01-19 14:14:38 +01:00
|
|
|
self._hostmaskCache[s] = id
|
|
|
|
try:
|
|
|
|
self._hostmaskCache[id].add(s)
|
|
|
|
except KeyError:
|
2014-01-26 21:14:21 +01:00
|
|
|
self._hostmaskCache[id] = set([s])
|
2005-01-19 14:14:38 +01:00
|
|
|
return id
|
|
|
|
elif len(ids) == 0:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise KeyError(s)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
log.error('Multiple matches found in user database. '
|
|
|
|
'Removing the offending hostmasks.')
|
2015-08-08 22:20:14 +02:00
|
|
|
for (id, hostmask) in ids.items():
|
2005-02-01 14:43:57 +01:00
|
|
|
log.error('Removing %q from user %s.', hostmask, id)
|
2005-01-19 14:14:38 +01:00
|
|
|
self.users[id].removeHostmask(hostmask)
|
2014-01-20 15:43:55 +01:00
|
|
|
raise DuplicateHostmask('Ids %r matched.' % ids)
|
2005-01-19 14:14:38 +01:00
|
|
|
else: # Not a hostmask, must be a name.
|
|
|
|
s = s.lower()
|
|
|
|
try:
|
|
|
|
return self._nameCache[s]
|
|
|
|
except KeyError:
|
|
|
|
for (id, user) in self.users.items():
|
|
|
|
if s == user.name.lower():
|
|
|
|
self._nameCache[s] = id
|
|
|
|
self._nameCache[id] = s
|
|
|
|
return id
|
|
|
|
else:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise KeyError(s)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getUser(self, id):
|
|
|
|
"""Returns a user given its id, name, or hostmask."""
|
|
|
|
if not isinstance(id, int):
|
|
|
|
# Must be a string. Get the UserId first.
|
|
|
|
id = self.getUserId(id)
|
|
|
|
u = self.users[id]
|
|
|
|
while isinstance(u, int):
|
|
|
|
id = u
|
|
|
|
u = self.users[id]
|
|
|
|
u.id = id
|
|
|
|
return u
|
|
|
|
|
2012-11-04 01:28:24 +01:00
|
|
|
def getUserFromNick(self, network, nick):
|
|
|
|
"""Return a user given its nick."""
|
|
|
|
for user in self.users.values():
|
|
|
|
try:
|
|
|
|
if nick in user.nicks[network]:
|
|
|
|
return user
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
return None
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def hasUser(self, id):
|
|
|
|
"""Returns the database has a user given its id, name, or hostmask."""
|
|
|
|
try:
|
|
|
|
self.getUser(id)
|
|
|
|
return True
|
|
|
|
except KeyError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
def numUsers(self):
|
|
|
|
return len(self.users)
|
|
|
|
|
|
|
|
def invalidateCache(self, id=None, hostmask=None, name=None):
|
|
|
|
if hostmask is not None:
|
|
|
|
if hostmask in self._hostmaskCache:
|
|
|
|
id = self._hostmaskCache.pop(hostmask)
|
|
|
|
self._hostmaskCache[id].remove(hostmask)
|
|
|
|
if not self._hostmaskCache[id]:
|
|
|
|
del self._hostmaskCache[id]
|
|
|
|
if name is not None:
|
|
|
|
del self._nameCache[self._nameCache[id]]
|
|
|
|
del self._nameCache[id]
|
|
|
|
if id is not None:
|
|
|
|
if id in self._nameCache:
|
|
|
|
del self._nameCache[self._nameCache[id]]
|
|
|
|
del self._nameCache[id]
|
|
|
|
if id in self._hostmaskCache:
|
|
|
|
for hostmask in self._hostmaskCache[id]:
|
|
|
|
del self._hostmaskCache[hostmask]
|
|
|
|
del self._hostmaskCache[id]
|
|
|
|
|
2005-03-27 11:59:44 +02:00
|
|
|
def setUser(self, user, flush=True):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Sets a user (given its id) to the IrcUser given it."""
|
|
|
|
self.nextId = max(self.nextId, user.id)
|
|
|
|
try:
|
|
|
|
if self.getUserId(user.name) != user.id:
|
2017-12-30 18:47:09 +01:00
|
|
|
raise DuplicateHostmask(user.name, user.name)
|
2005-01-19 14:14:38 +01:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
for hostmask in user.hostmasks:
|
2015-08-08 22:20:14 +02:00
|
|
|
for (i, u) in self.items():
|
2005-01-19 14:14:38 +01:00
|
|
|
if i == user.id:
|
|
|
|
continue
|
|
|
|
elif u.checkHostmask(hostmask):
|
|
|
|
# We used to remove the hostmask here, but it's not
|
|
|
|
# appropriate for us both to remove the hostmask and to
|
|
|
|
# raise an exception. So instead, we'll raise an
|
|
|
|
# exception, but be nice and give the offending hostmask
|
|
|
|
# back at the same time.
|
2017-12-30 18:47:09 +01:00
|
|
|
raise DuplicateHostmask(u.name, hostmask)
|
2005-01-19 14:14:38 +01:00
|
|
|
for otherHostmask in u.hostmasks:
|
|
|
|
if ircutils.hostmaskPatternEqual(hostmask, otherHostmask):
|
2017-12-30 18:47:09 +01:00
|
|
|
raise DuplicateHostmask(u.name, hostmask)
|
2005-01-19 14:14:38 +01:00
|
|
|
self.invalidateCache(user.id)
|
|
|
|
self.users[user.id] = user
|
2005-03-27 11:59:44 +02:00
|
|
|
if flush:
|
|
|
|
self.flush()
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def delUser(self, id):
|
|
|
|
"""Removes a user from the database."""
|
|
|
|
del self.users[id]
|
|
|
|
if id in self._nameCache:
|
|
|
|
del self._nameCache[self._nameCache[id]]
|
|
|
|
del self._nameCache[id]
|
|
|
|
if id in self._hostmaskCache:
|
2015-09-02 17:00:20 +02:00
|
|
|
for hostmask in list(self._hostmaskCache[id]):
|
2005-01-19 14:14:38 +01:00
|
|
|
del self._hostmaskCache[hostmask]
|
|
|
|
del self._hostmaskCache[id]
|
|
|
|
self.flush()
|
|
|
|
|
|
|
|
def newUser(self):
|
|
|
|
"""Allocates a new user in the database and returns it and its id."""
|
|
|
|
user = IrcUser(hashed=True)
|
|
|
|
self.nextId += 1
|
|
|
|
id = self.nextId
|
|
|
|
self.users[id] = user
|
|
|
|
self.flush()
|
|
|
|
user.id = id
|
|
|
|
return user
|
|
|
|
|
|
|
|
|
|
|
|
class ChannelsDictionary(utils.IterableMap):
|
2019-09-28 10:33:10 +02:00
|
|
|
__slots__ = ('noFlush', 'filename', 'channels')
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self):
|
2019-09-28 10:33:10 +02:00
|
|
|
self.noFlush = False
|
2005-01-19 14:14:38 +01:00
|
|
|
self.filename = None
|
|
|
|
self.channels = ircutils.IrcDict()
|
|
|
|
|
|
|
|
def open(self, filename):
|
2019-09-28 10:33:10 +02:00
|
|
|
self.noFlush = True
|
|
|
|
try:
|
|
|
|
self.filename = filename
|
|
|
|
reader = unpreserve.Reader(IrcChannelCreator, self)
|
|
|
|
try:
|
|
|
|
reader.readFile(filename)
|
|
|
|
self.noFlush = False
|
|
|
|
self.flush()
|
|
|
|
except EnvironmentError as e:
|
|
|
|
log.error('Invalid channel database, resetting to empty.')
|
|
|
|
log.error('Exact error: %s', utils.exnToString(e))
|
|
|
|
except Exception as e:
|
|
|
|
log.error('Invalid channel database, resetting to empty.')
|
|
|
|
log.exception('Exact error:')
|
|
|
|
finally:
|
|
|
|
self.noFlush = False
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
"""Flushes the channel database to its file."""
|
2019-09-28 10:33:10 +02:00
|
|
|
if not self.noFlush:
|
|
|
|
if self.filename is not None:
|
|
|
|
fd = utils.file.AtomicFile(self.filename)
|
|
|
|
for (channel, c) in self.channels.items():
|
|
|
|
fd.write('channel %s' % channel)
|
|
|
|
fd.write(os.linesep)
|
|
|
|
c.preserve(fd, indent=' ')
|
|
|
|
fd.close()
|
|
|
|
else:
|
|
|
|
log.warning('ChannelsDictionary.flush without self.filename.')
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2019-09-28 10:33:10 +02:00
|
|
|
log.debug('Not flushing ChannelsDictionary because of noFlush.')
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self.flush()
|
|
|
|
if self.flush in world.flushers:
|
|
|
|
world.flushers.remove(self.flush)
|
|
|
|
self.channels.clear()
|
|
|
|
|
|
|
|
def reload(self):
|
|
|
|
"""Reloads the channel database from its file."""
|
|
|
|
if self.filename is not None:
|
|
|
|
self.channels.clear()
|
2019-09-28 10:33:10 +02:00
|
|
|
try:
|
|
|
|
self.open(self.filename)
|
|
|
|
except EnvironmentError as e:
|
|
|
|
log.warning('ChannelsDictionary.reload failed: %s', e)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
log.warning('ChannelsDictionary.reload without self.filename.')
|
|
|
|
|
|
|
|
def getChannel(self, channel):
|
|
|
|
"""Returns an IrcChannel object for the given channel."""
|
|
|
|
channel = channel.lower()
|
|
|
|
if channel in self.channels:
|
|
|
|
return self.channels[channel]
|
|
|
|
else:
|
|
|
|
c = IrcChannel()
|
|
|
|
self.channels[channel] = c
|
|
|
|
return c
|
|
|
|
|
|
|
|
def setChannel(self, channel, ircChannel):
|
|
|
|
"""Sets a given channel to the IrcChannel object given."""
|
|
|
|
channel = channel.lower()
|
|
|
|
self.channels[channel] = ircChannel
|
|
|
|
self.flush()
|
|
|
|
|
2015-08-08 22:20:14 +02:00
|
|
|
def items(self):
|
|
|
|
return self.channels.items()
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
class IgnoresDB(object):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ('filename', 'hostmasks')
|
2005-01-19 14:14:38 +01:00
|
|
|
def __init__(self):
|
|
|
|
self.filename = None
|
|
|
|
self.hostmasks = {}
|
|
|
|
|
|
|
|
def open(self, filename):
|
|
|
|
self.filename = filename
|
2012-08-04 13:13:16 +02:00
|
|
|
fd = open(self.filename)
|
2005-01-27 07:59:08 +01:00
|
|
|
for line in utils.file.nonCommentNonEmptyLines(fd):
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
|
|
|
line = line.rstrip('\r\n')
|
|
|
|
L = line.split()
|
|
|
|
hostmask = L.pop(0)
|
|
|
|
if L:
|
|
|
|
expiration = int(float(L.pop(0)))
|
|
|
|
else:
|
|
|
|
expiration = 0
|
|
|
|
self.add(hostmask, expiration)
|
2015-08-31 15:38:35 +02:00
|
|
|
except Exception:
|
2005-02-01 14:43:57 +01:00
|
|
|
log.error('Invalid line in ignores database: %q', line)
|
2005-01-19 14:14:38 +01:00
|
|
|
fd.close()
|
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
if self.filename is not None:
|
2005-01-27 07:59:08 +01:00
|
|
|
fd = utils.file.AtomicFile(self.filename)
|
2005-01-19 14:14:38 +01:00
|
|
|
now = time.time()
|
|
|
|
for (hostmask, expiration) in self.hostmasks.items():
|
|
|
|
if now < expiration or not expiration:
|
|
|
|
fd.write('%s %s' % (hostmask, expiration))
|
|
|
|
fd.write(os.linesep)
|
|
|
|
fd.close()
|
|
|
|
else:
|
|
|
|
log.warning('IgnoresDB.flush called without self.filename.')
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
if self.flush in world.flushers:
|
|
|
|
world.flushers.remove(self.flush)
|
|
|
|
self.flush()
|
|
|
|
self.hostmasks.clear()
|
|
|
|
|
|
|
|
def reload(self):
|
|
|
|
if self.filename is not None:
|
|
|
|
oldhostmasks = self.hostmasks.copy()
|
|
|
|
self.hostmasks.clear()
|
|
|
|
try:
|
|
|
|
self.open(self.filename)
|
2014-01-20 15:49:15 +01:00
|
|
|
except EnvironmentError as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
log.warning('IgnoresDB.reload failed: %s', e)
|
|
|
|
# Let's be somewhat transactional.
|
|
|
|
self.hostmasks.update(oldhostmasks)
|
|
|
|
else:
|
|
|
|
log.warning('IgnoresDB.reload called without self.filename.')
|
|
|
|
|
|
|
|
def checkIgnored(self, prefix):
|
|
|
|
now = time.time()
|
2015-09-02 17:00:20 +02:00
|
|
|
for (hostmask, expiration) in list(self.hostmasks.items()):
|
2005-01-19 14:14:38 +01:00
|
|
|
if expiration and now > expiration:
|
|
|
|
del self.hostmasks[hostmask]
|
|
|
|
else:
|
|
|
|
if ircutils.hostmaskPatternEqual(hostmask, prefix):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def add(self, hostmask, expiration=0):
|
|
|
|
assert ircutils.isUserHostmask(hostmask), 'got %s' % hostmask
|
|
|
|
self.hostmasks[hostmask] = expiration
|
|
|
|
|
|
|
|
def remove(self, hostmask):
|
|
|
|
del self.hostmasks[hostmask]
|
|
|
|
|
|
|
|
|
|
|
|
confDir = conf.supybot.directories.conf()
|
|
|
|
try:
|
|
|
|
userFile = os.path.join(confDir, conf.supybot.databases.users.filename())
|
|
|
|
users = UsersDictionary()
|
|
|
|
users.open(userFile)
|
2014-01-20 15:49:15 +01:00
|
|
|
except EnvironmentError as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
log.warning('Couldn\'t open user database: %s', e)
|
|
|
|
|
|
|
|
try:
|
|
|
|
channelFile = os.path.join(confDir,
|
|
|
|
conf.supybot.databases.channels.filename())
|
|
|
|
channels = ChannelsDictionary()
|
|
|
|
channels.open(channelFile)
|
2014-01-20 15:49:15 +01:00
|
|
|
except EnvironmentError as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
log.warning('Couldn\'t open channel database: %s', e)
|
|
|
|
|
|
|
|
try:
|
|
|
|
ignoreFile = os.path.join(confDir,
|
|
|
|
conf.supybot.databases.ignores.filename())
|
|
|
|
ignores = IgnoresDB()
|
|
|
|
ignores.open(ignoreFile)
|
2014-01-20 15:49:15 +01:00
|
|
|
except EnvironmentError as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
log.warning('Couldn\'t open ignore database: %s', e)
|
|
|
|
|
|
|
|
|
|
|
|
world.flushers.append(users.flush)
|
|
|
|
world.flushers.append(ignores.flush)
|
|
|
|
world.flushers.append(channels.flush)
|
|
|
|
|
|
|
|
|
|
|
|
###
|
|
|
|
# Useful functions for checking credentials.
|
|
|
|
###
|
|
|
|
def checkIgnored(hostmask, recipient='', users=users, channels=channels):
|
|
|
|
"""checkIgnored(hostmask, recipient='') -> True/False
|
|
|
|
|
|
|
|
Checks if the user is ignored by the recipient of the message.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
id = users.getUserId(hostmask)
|
|
|
|
user = users.getUser(id)
|
2011-11-21 21:09:38 +01:00
|
|
|
if user._checkCapability('owner'):
|
|
|
|
# Owners shouldn't ever be ignored.
|
|
|
|
return False
|
|
|
|
elif user.ignore:
|
2013-03-08 20:34:31 +01:00
|
|
|
log.debug('Ignoring %s due to their IrcUser ignore flag.', hostmask)
|
2011-11-21 21:09:38 +01:00
|
|
|
return True
|
2005-01-19 14:14:38 +01:00
|
|
|
except KeyError:
|
|
|
|
# If there's no user...
|
2011-11-21 21:09:38 +01:00
|
|
|
if conf.supybot.defaultIgnore():
|
|
|
|
log.debug('Ignoring %s due to conf.supybot.defaultIgnore',
|
|
|
|
hostmask)
|
|
|
|
return True
|
|
|
|
if ignores.checkIgnored(hostmask):
|
|
|
|
log.debug('Ignoring %s due to ignore database.', hostmask)
|
2005-01-19 14:14:38 +01:00
|
|
|
return True
|
2011-11-21 21:09:38 +01:00
|
|
|
if ircutils.isChannel(recipient):
|
|
|
|
channel = channels.getChannel(recipient)
|
|
|
|
if channel.checkIgnored(hostmask):
|
|
|
|
log.debug('Ignoring %s due to the channel ignores.', hostmask)
|
|
|
|
return True
|
|
|
|
return False
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def _x(capability, ret):
|
|
|
|
if isAntiCapability(capability):
|
|
|
|
return not ret
|
|
|
|
else:
|
|
|
|
return ret
|
|
|
|
|
2014-02-27 20:04:54 +01:00
|
|
|
def _checkCapabilityForUnknownUser(capability, users=users, channels=channels,
|
|
|
|
ignoreDefaultAllow=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
if isChannelCapability(capability):
|
|
|
|
(channel, capability) = fromChannelCapability(capability)
|
|
|
|
try:
|
|
|
|
c = channels.getChannel(channel)
|
|
|
|
if capability in c.capabilities:
|
|
|
|
return c._checkCapability(capability)
|
|
|
|
else:
|
2014-02-27 20:04:54 +01:00
|
|
|
return _x(capability, (not ignoreDefaultAllow) and c.defaultAllow)
|
2005-01-19 14:14:38 +01:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
defaultCapabilities = conf.supybot.capabilities()
|
|
|
|
if capability in defaultCapabilities:
|
|
|
|
return defaultCapabilities.check(capability)
|
2014-02-27 20:04:54 +01:00
|
|
|
elif ignoreDefaultAllow:
|
|
|
|
return _x(capability, False)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
return _x(capability, conf.supybot.capabilities.default())
|
|
|
|
|
2011-01-27 19:32:43 +01:00
|
|
|
def checkCapability(hostmask, capability, users=users, channels=channels,
|
2013-12-27 16:04:32 +01:00
|
|
|
ignoreOwner=False, ignoreChannelOp=False,
|
|
|
|
ignoreDefaultAllow=False):
|
2005-01-19 14:14:38 +01:00
|
|
|
"""Checks that the user specified by name/hostmask has the capability given.
|
2014-01-20 11:35:28 +01:00
|
|
|
|
|
|
|
``users`` and ``channels`` default to ``ircdb.users`` and
|
|
|
|
``ircdb.channels``.
|
|
|
|
|
|
|
|
``ignoreOwner``, ``ignoreChannelOp``, and ``ignoreDefaultAllow`` are
|
|
|
|
used to override default behavior of the capability system in special
|
|
|
|
cases (actually, in the AutoMode plugin):
|
|
|
|
|
|
|
|
* ``ignoreOwner`` disables the behavior "owners have all capabilites"
|
|
|
|
* ``ignoreChannelOp`` disables the behavior "channel ops have all
|
|
|
|
channel capabilities"
|
|
|
|
* ``ignoreDefaultAllow`` disables the behavior "if a user does not have
|
|
|
|
a capability or the associated anticapability, then they have the
|
|
|
|
capability"
|
2005-01-19 14:14:38 +01:00
|
|
|
"""
|
2013-01-05 19:06:49 +01:00
|
|
|
if world.testing and (not isinstance(hostmask, str) or
|
|
|
|
'@' not in hostmask or
|
2013-01-05 17:27:20 +01:00
|
|
|
'__no_testcap__' not in hostmask.split('@')[1]):
|
2005-01-19 14:14:38 +01:00
|
|
|
return _x(capability, True)
|
|
|
|
try:
|
|
|
|
u = users.getUser(hostmask)
|
|
|
|
if u.secure and not u.checkHostmask(hostmask, useAuth=False):
|
|
|
|
raise KeyError
|
|
|
|
except KeyError:
|
|
|
|
# Raised when no hostmasks match.
|
|
|
|
return _checkCapabilityForUnknownUser(capability, users=users,
|
2014-02-27 20:04:54 +01:00
|
|
|
channels=channels, ignoreDefaultAllow=ignoreDefaultAllow)
|
2014-01-20 15:49:15 +01:00
|
|
|
except ValueError as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
# Raised when multiple hostmasks match.
|
|
|
|
log.warning('%s: %s', hostmask, e)
|
|
|
|
return _checkCapabilityForUnknownUser(capability, users=users,
|
2014-02-27 20:04:54 +01:00
|
|
|
channels=channels, ignoreDefaultAllow=ignoreDefaultAllow)
|
2005-01-19 14:14:38 +01:00
|
|
|
if capability in u.capabilities:
|
2013-12-27 16:04:32 +01:00
|
|
|
try:
|
|
|
|
return u._checkCapability(capability, ignoreOwner)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
if isChannelCapability(capability):
|
|
|
|
(channel, capability) = fromChannelCapability(capability)
|
|
|
|
if not ignoreChannelOp:
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
|
|
|
chanop = makeChannelCapability(channel, 'op')
|
|
|
|
if u._checkCapability(chanop):
|
|
|
|
return _x(capability, True)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2013-12-27 16:04:32 +01:00
|
|
|
c = channels.getChannel(channel)
|
|
|
|
if capability in c.capabilities:
|
|
|
|
return c._checkCapability(capability)
|
|
|
|
elif not ignoreDefaultAllow:
|
|
|
|
return _x(capability, c.defaultAllow)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2013-12-27 16:04:32 +01:00
|
|
|
return False
|
|
|
|
defaultCapabilities = conf.supybot.capabilities()
|
2018-01-05 19:24:54 +01:00
|
|
|
defaultCapabilitiesRegistered = conf.supybot.capabilities.registeredUsers()
|
2013-12-27 16:04:32 +01:00
|
|
|
if capability in defaultCapabilities:
|
|
|
|
return defaultCapabilities.check(capability)
|
2018-01-05 19:24:54 +01:00
|
|
|
elif capability in defaultCapabilitiesRegistered:
|
|
|
|
return defaultCapabilitiesRegistered.check(capability)
|
2014-02-27 20:04:54 +01:00
|
|
|
elif ignoreDefaultAllow:
|
|
|
|
return _x(capability, False)
|
2013-12-27 16:04:32 +01:00
|
|
|
else:
|
|
|
|
return _x(capability, conf.supybot.capabilities.default())
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
def checkCapabilities(hostmask, capabilities, requireAll=False):
|
|
|
|
"""Checks that a user has capabilities in a list.
|
|
|
|
|
2005-02-10 04:16:54 +01:00
|
|
|
requireAll is True if *all* capabilities in the list must be had, False if
|
|
|
|
*any* of the capabilities in the list must be had.
|
2005-01-19 14:14:38 +01:00
|
|
|
"""
|
|
|
|
for capability in capabilities:
|
|
|
|
if requireAll:
|
|
|
|
if not checkCapability(hostmask, capability):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
if checkCapability(hostmask, capability):
|
|
|
|
return True
|
2009-02-05 22:37:30 +01:00
|
|
|
return requireAll
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
###
|
|
|
|
# supybot.capabilities
|
|
|
|
###
|
|
|
|
|
2018-01-05 19:24:54 +01:00
|
|
|
class SpaceSeparatedListOfCapabilities(registry.SpaceSeparatedListOfStrings):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ()
|
2005-01-19 14:14:38 +01:00
|
|
|
List = CapabilitySet
|
2018-01-05 19:24:54 +01:00
|
|
|
|
|
|
|
class DefaultCapabilities(SpaceSeparatedListOfCapabilities):
|
2018-09-25 18:59:46 +02:00
|
|
|
__slots__ = ()
|
2005-01-19 14:14:38 +01:00
|
|
|
# We use a keyword argument trick here to prevent eval'ing of code that
|
|
|
|
# changes allowDefaultOwner from affecting this. It's not perfect, but
|
|
|
|
# it's still an improvement, raising the bar for potential crackers.
|
|
|
|
def setValue(self, v, allowDefaultOwner=conf.allowDefaultOwner):
|
|
|
|
registry.SpaceSeparatedListOfStrings.setValue(self, v)
|
|
|
|
if '-owner' not in self.value and not allowDefaultOwner:
|
2014-01-20 15:31:09 +01:00
|
|
|
print('*** You must run supybot with the --allow-default-owner')
|
|
|
|
print('*** option in order to allow a default capability of owner.')
|
|
|
|
print('*** Don\'t do that, it\'s dumb.')
|
2005-01-19 14:14:38 +01:00
|
|
|
self.value.add('-owner')
|
|
|
|
|
|
|
|
conf.registerGlobalValue(conf.supybot, 'capabilities',
|
2019-07-31 23:00:55 +02:00
|
|
|
DefaultCapabilities([
|
|
|
|
'-owner', '-admin', '-trusted',
|
|
|
|
'-aka.add', '-aka.set', '-aka.remove',
|
|
|
|
'-alias.add', '-alias.remove',
|
|
|
|
'-scheduler.add', '-scheduler.remove',
|
|
|
|
],
|
|
|
|
"""These are the
|
2005-01-19 14:14:38 +01:00
|
|
|
capabilities that are given to everyone by default. If they are normal
|
|
|
|
capabilities, then the user will have to have the appropriate
|
|
|
|
anti-capability if you want to override these capabilities; if they are
|
|
|
|
anti-capabilities, then the user will have to have the actual capability
|
|
|
|
to override these capabilities. See docs/CAPABILITIES if you don't
|
|
|
|
understand why these default to what they do."""))
|
|
|
|
|
2018-01-05 19:24:54 +01:00
|
|
|
conf.registerGlobalValue(conf.supybot.capabilities, 'registeredUsers',
|
|
|
|
SpaceSeparatedListOfCapabilities([], """These are the
|
2018-01-06 19:39:05 +01:00
|
|
|
capabilities that are given to every authenticated user by default.
|
2018-01-05 19:24:54 +01:00
|
|
|
You probably want to use supybot.capabilities instead, to give these
|
|
|
|
capabilities both to registered and non-registered users."""))
|
2005-01-19 14:14:38 +01:00
|
|
|
conf.registerGlobalValue(conf.supybot.capabilities, 'default',
|
|
|
|
registry.Boolean(True, """Determines whether the bot by default will allow
|
|
|
|
users to have a capability. If this is disabled, a user must explicitly
|
2013-03-08 20:34:31 +01:00
|
|
|
have the capability for whatever command they wish to run."""))
|
2012-10-29 20:15:14 +01:00
|
|
|
conf.registerGlobalValue(conf.supybot.capabilities, 'private',
|
|
|
|
registry.SpaceSeparatedListOfStrings([], """Determines what capabilities
|
|
|
|
the bot will never tell to a non-admin whether or not a user has them."""))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
|
2006-02-11 16:52:51 +01:00
|
|
|
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|