コード例 #1
0
ファイル: mumble.py プロジェクト: Auph/pyHoNBot
def setup(bot):
    global _server,_meta
    bot.config.module_config('mumble_host',[None,'Host for mumble server'])
    bot.config.module_config('mumble_port',[0,'Port for mumble server'])
    bot.config.module_config('mumble_secret',[None,'Secret for mumble server'])

    if not bot.config.mumble_host or not bot.config.mumble_port:
        return
    prxstr = "s/1 -t:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    meta_prxstr = "Meta:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    props = Ice.createProperties()
    props.setProperty("Ice.ImplicitContext", "Shared")
    idata = Ice.InitializationData()
    idata.properties = props
    ice = Ice.initialize(idata)
    prx = ice.stringToProxy(str(prxstr))
    prx_meta = ice.stringToProxy(str(meta_prxstr))
    try:
        slice = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (), IcePy._t_string, ()).invoke(prx_meta, ((), None))
        (dynslicefiledesc, dynslicefilepath)  = tempfile.mkstemp(suffix = '.ice')
        dynslicefile = os.fdopen(dynslicefiledesc, 'w')
        dynslicefile.write(slice)
        dynslicefile.flush()
        Ice.loadSlice('', ['-I' + Ice.getSliceDir(), dynslicefilepath])
        dynslicefile.close()
        os.remove(dynslicefilepath)

        import Murmur
        if bot.config.mumble_secret:
            ice.getImplicitContext().put("secret", str(bot.config.mumble_secret))
        _server = Murmur.ServerPrx.checkedCast(prx)
        _meta = Murmur.MetaPrx.checkedCast(prx_meta)
        bot.mumbleannounce = lambda msg: _server.sendMessageChannel(0,True,msg)
    except Exception, e:
        print str(e)
コード例 #2
0
def main():
    sliceDir = Ice.getSliceDir()
    # Automatically add the slice dir.
    if not sliceDir is None:
        sys.argv.append('-I' + sliceDir)
    val = IcePy.compile(sys.argv)
    sys.exit(int(val))
コード例 #3
0
ファイル: slice2py.py プロジェクト: zj771484545/ice
def main():
    sliceDir = Ice.getSliceDir()
    # Automatically add the slice dir.
    if sliceDir is not None:
        sys.argv.append('-I' + sliceDir)
    val = IcePy.compile(sys.argv)
    sys.exit(int(val))
コード例 #4
0
def setup(self):
    """Sets up ICE"""
    if self.config.mumble:
        slicefile = self.config.mumble.slice
        icesecret = self.config.mumble.secret
    else:
        slicefile = self.config.mumble_slice
        icesecret = self.config.mumble_secret

    Ice.loadSlice('', ['-I' + Ice.getSliceDir(), slicefile ] )
    prop = Ice.createProperties([])
    prop.setProperty('Ice.Default.EncodingVersion', '1.0')
    prop.setProperty("Ice.ImplicitContext", "Shared")
    prop.setProperty("Ice.MessageSizeMax",  "65535")

    idd = Ice.InitializationData()
    idd.properties = prop
    global ice
    ice = Ice.initialize(idd)
    ice.getImplicitContext().put("secret", icesecret.encode("utf-8"))
    global Murmur
    import Murmur
    ## Set up threaded checker
    print "set up and now starting timer thread"
    t = threading.Timer(20.0, mumble_auto_loop, [self])
    t.start()
コード例 #5
0
def setup(bot):
    global _server,_meta
    if not hasattr(bot.config,'mumble_host') or not hasattr(bot.config,"mumble_port"):
        return
    prxstr = "s/1 -t:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    meta_prxstr = "Meta:tcp -h %s -p %d -t 1000" % (bot.config.mumble_host,bot.config.mumble_port)
    props = Ice.createProperties()
    props.setProperty("Ice.ImplicitContext", "Shared")
    idata = Ice.InitializationData()
    idata.properties = props
    ice = Ice.initialize(idata)
    prx = ice.stringToProxy(prxstr)
    prx_meta = ice.stringToProxy(meta_prxstr)
    try:
        slice = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (), IcePy._t_string, ()).invoke(prx_meta, ((), None))
        (dynslicefiledesc, dynslicefilepath)  = tempfile.mkstemp(suffix = '.ice')
        dynslicefile = os.fdopen(dynslicefiledesc, 'w')
        dynslicefile.write(slice)
        dynslicefile.flush()
        Ice.loadSlice('', ['-I' + Ice.getSliceDir(), dynslicefilepath])
        dynslicefile.close()
        os.remove(dynslicefilepath)

        import Murmur
        if hasattr(bot.config,'mumble_secret'):
            ice.getImplicitContext().put("secret", bot.config.mumble_secret)
        _server = Murmur.ServerPrx.checkedCast(prx)
        _meta = Murmur.MetaPrx.checkedCast(prx_meta)
        bot.mumbleannounce = lambda msg: _server.sendMessageChannel(0,True,msg)
    except Exception, e:
        print str(e)
コード例 #6
0
ファイル: tasks.py プロジェクト: CokkocZateki/avrse-auth
def get_server():
    import Ice
    Ice.loadSlice( '', ['-I' + Ice.getSliceDir(), "eveauth/Murmur.ice"])
    import Murmur

    ice = Ice.initialize()
    meta = Murmur.MetaPrx.checkedCast(ice.stringToProxy('Meta:tcp -h 127.0.0.1 -p 6502'))
    server = meta.getServer(1)
    return server
コード例 #7
0
ファイル: mumbule_service.py プロジェクト: egguy/ZeroMumble
    def __init__(self, secret):
        import Ice, IcePy
        
        # Setup Ice
        icepath = Ice.getSliceDir()

        prop = Ice.createProperties([])
        prop.setProperty("Ice.ImplicitContext", "Shared")
        prop.setProperty("Ice.MessageSizeMax",  "65535")
       
        idd = Ice.InitializationData()
        idd.properties = prop

        ice = Ice.initialize(idd)
        
        # Set the secret
        ice.getImplicitContext().put( "secret", secret )
        
        # Initialization of a local connexion
        prx = ice.stringToProxy('Meta:tcp -h localhost -p 6502')
        prx.ice_ping()

        # Load the object definition
        Ice.loadSlice( '', ['-I' + icepath, "Murmur.ice" ] )

        import Murmur
        self._murmur     = Murmur.MetaPrx.checkedCast(prx)
        
        # Generic ACL ready to use
        self._password_ACL = [
            Murmur.ACL(
                applyHere = True,
                applySubs = False,
                inherited = False,
                userid = -1,
                group = "all",
                allow = 0,
                deny = 910,
            ), Murmur.ACL(
                applyHere = True,
                applySubs = False,
                inherited = False,
                userid = -1,
                # The password is defined by adding a # in front of group name
                group = "",
                allow = 910,
                deny = 0,
            )
        ]

        self._server = self._murmur.getServer(1)
コード例 #8
0
def init(force=False):
    global state, murmur
    if state != 'uninitialised' and not force:
        return 'previously failed'

    try:
        settings = TrosnothServerSettings.get()
        if not settings.iceEnabled:
            state = 'disabled'
            return

        import Ice, IcePy

        proxyString = settings.iceProxyStringOverride
        if not proxyString:
            proxyString = 'Meta:tcp -h {host} -p {port} -t 1000'.format(
                host=settings.iceHost, port=settings.icePort)

        props = Ice.createProperties()
        props.setProperty('Ice.ImplicitContext', 'Shared')
        initData = Ice.InitializationData()
        initData.properties = props
        ice = Ice.initialize(initData)

        proxy = ice.stringToProxy(proxyString)
        op = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent,
                             Ice.OperationMode.Idempotent, True, None, (), (),
                             (), ((), IcePy._t_string, False, 0), ())

        sl = op.invoke(proxy, ((), None))
        fd, path = tempfile.mkstemp(suffix='.ice')
        f = os.fdopen(fd, 'w')
        with f:
            f.write(sl)
            f.flush()

            Ice.loadSlice('', ['-I' + Ice.getSliceDir(), path])
        os.unlink(path)

        if settings.iceSecret:
            ice.getImplicitContext().put('secret',
                                         settings.iceSecret.encode('ascii'))

        import Murmur
        murmur = Murmur.MetaPrx.checkedCast(proxy)
    except Exception:
        log.exception('Error initialising murmur connection')
        state = 'failed'
    else:
        state = 'initialised'
    return state
コード例 #9
0
ファイル: meta.py プロジェクト: nikdoof/mumblepy
    def _load_slice(self, proxy):
        mumble_slice = IcePy.Operation('getSlice',
                                       Ice.OperationMode.Idempotent,
                                       Ice.OperationMode.Idempotent, True, (),
                                       (), (), IcePy._t_string,
                                       ()).invoke(proxy, ((), None))

        _, temp = tempfile.mkstemp(suffix='.ice')

        with open(temp, 'w') as slice_file:
            slice_file.write(mumble_slice)
            slice_file.flush()
            Ice.loadSlice('', ['-I' + Ice.getSliceDir(), temp])

        os.remove(temp)
コード例 #10
0
def setup(self):
    """Sets up ICE"""
    slicefile = self.config.mumble_slice
    icesecret = self.config.mumble_secret

    Ice.loadSlice('', ['-I' + Ice.getSliceDir(), slicefile ] )
    prop = Ice.createProperties([])
    prop.setProperty("Ice.ImplicitContext", "Shared")
    prop.setProperty("Ice.MessageSizeMax",  "65535")

    idd = Ice.InitializationData()
    idd.properties = prop
    global ice
    ice = Ice.initialize(idd)
    ice.getImplicitContext().put("secret", icesecret)
    global Murmur
    import Murmur
    ## Set up threaded checker
    t = threading.Timer(20.0, mumble_auto_loop, [self])
    t.start()
コード例 #11
0
ファイル: meta.py プロジェクト: vishnevskiy/mumblepy
    def load_slice(self, proxy):
        mumble_slice = IcePy.Operation(
            'getSlice',
            Ice.OperationMode.Idempotent,
            Ice.OperationMode.Idempotent,
            True,
            (),
            (),
            (),
            IcePy._t_string,
            ()
        ).invoke(proxy, ((), None))

        _, temp = tempfile.mkstemp(suffix='.ice')

        with open(temp, 'w') as slice_file:
            slice_file.write(mumble_slice)
            slice_file.flush()
            Ice.loadSlice('', ['-I' + Ice.getSliceDir(), temp])

        os.remove(temp)
コード例 #12
0
ファイル: mumble.py プロジェクト: mckang/AgentP
    def configure_slice(self):
        logging.info('Configuring Ice slice.')

        slicedir = Ice.getSliceDir()
        if not slicedir:
            slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
        else:
            slicedir = ['-I' + slicedir]

        try:
            logging.info('Trying to retrieve slice dynamically from server...')
            op = None
            if IcePy.intVersion() < 30500L:
                # Old 3.4 signature with 9 parameters
                op = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent,
                                     Ice.OperationMode.Idempotent, True, (),
                                     (), (), IcePy._t_string, ())
            else:
                # New 3.5 signature with 10 parameters.
                op = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent,
                                     Ice.OperationMode.Idempotent, True, None,
                                     (), (), (),
                                     ((), IcePy._t_string, False, 0), ())

            slice = op.invoke(self.prx, ((), None))
            (dynslicefiledesc,
             dynslicefilepath) = tempfile.mkstemp(suffix='.ice')
            dynslicefile = os.fdopen(dynslicefiledesc, 'w')
            dynslicefile.write(slice)
            dynslicefile.flush()
            Ice.loadSlice('', slicedir + [dynslicefilepath])
            dynslicefile.close()
            os.remove(dynslicefilepath)

        except Exception:
            logging.error('Can not retrieve slice from server...')
            raise SystemExit(1)
コード例 #13
0
def loadSlice(slicefile):
    """ Load the slice file with the correct include dir set, if possible. """
    if hasattr(Ice, "getSliceDir"):
        icepath = Ice.getSliceDir()
    else:
        icepath = None

    # Ice returns '' in getSliceDir() sometimes. (I kid you not.)
    if not icepath:
        try:
            from django.conf import settings
        except ImportError:
            # CTL is being used independently from MD
            icepath = None
        else:
            icepath = settings.SLICEDIR
            if not exists(join(icepath, "Ice", "SliceChecksumDict.ice")):
                icepath = None

    if not icepath:
        # last resort when getSliceDir fails AND settings are wrong/unavailable, won't work for >=1.2.3
        Ice.loadSlice(slicefile)
    else:
        Ice.loadSlice('', ['-I' + icepath, slicefile])
コード例 #14
0
ファイル: MumbleCtlIce.py プロジェクト: Natenom/murmur-cvp
def loadSlice( slicefile ):
    """ Load the slice file with the correct include dir set, if possible. """
    if hasattr( Ice, "getSliceDir" ):
        icepath = Ice.getSliceDir()
    else:
        icepath = None

    # Ice returns '' in getSliceDir() sometimes. (I kid you not.)
    if not icepath:
        try:
            from django.conf import settings
        except ImportError:
            # CTL is being used independently from MD
            icepath = None
        else:
            icepath = settings.SLICEDIR
            if not exists( join( icepath, "Ice", "SliceChecksumDict.ice" ) ):
                icepath = None

    if not icepath:
        # last resort when getSliceDir fails AND settings are wrong/unavailable, won't work for >=1.2.3
        Ice.loadSlice( slicefile )
    else:
        Ice.loadSlice( '', ['-I' + icepath, slicefile ] )
コード例 #15
0
ファイル: antirec.py プロジェクト: DunkleAura/murmur-antirec
msg_context_allow = "Aufnahmeerlaubnis erteilen"
msg_context_disallow = "Aufnahmeerlaubnis zurückziehen"

PUNISHMENT = "DEAF"  # Punishment for users that try to record :P" Can be "DEAF" or "KICK".
ADMINALLOWSELF = False  # Don't allow members of the group canallowrecording to permit themselfs to record.

JOININFO = False  # Shows a small piece of Information on Join
DEBUG = False  # More verbose output, True or False

################################################################################
# DO NOT CHANGE BELOW THIS LINE #
################################################################################
import Ice

# Ice.loadSlice("--all -I/usr/share/slice /usr/share/slice/Murmur.ice")
Ice.loadSlice("", ["-I" + Ice.getSliceDir(), "/usr/share/slice/Murmur.ice"])
import Murmur
import sys
import os
import logging
import signal

myname = os.path.basename(__file__)

FORMAT = "%(levelname)s:%(name)s - %(message)s"
if DEBUG:
    logging.basicConfig(stream=sys.stdout, format=FORMAT, level=logging.DEBUG)
else:
    logging.basicConfig(stream=sys.stdout, format=FORMAT, level=logging.INFO)

AllowedToRec = {}  # Temporary list of users allowed to record.
コード例 #16
0
import sys, traceback, Ice, IceGrid

Ice.loadSlice('-I {} Geocloud.ice'.format(Ice.getSliceDir()))
import geocloud
import sys
import time


class GroundStation(Ice.Application):
    def run(self, args):
        com = self.communicator()
        if not com:
            raise RuntimeError("Not communicator")

        else:
            print "ID:", args[0]
            query = com.stringToProxy('IceGrid/Query')
            q = IceGrid.QueryPrx.checkedCast(query)
            if not q:
                raise RuntimeError("Invalid proxy")
            try:
                broker = q.findObjectById(com.stringToIdentity('broker'))
                brokerPrx = geocloud.BrokerPrx.checkedCast(broker)
                print brokerPrx

                orch = q.findObjectById(com.stringToIdentity('orchestrator'))
                orchestratorPrx = geocloud.OrchestratorPrx.checkedCast(orch)
                print orchestratorPrx
            except Exception as e:
                print e
                sys.exit(-1)
コード例 #17
0
ファイル: plugin.py プロジェクト: rubinlinux/Limnoria-mumble
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
try:
  from supybot.i18n import PluginInternationalization, internationalizeDocstring
  _ = PluginInternationalization('Mumble')
except :
  _ = lambda x : x
  internationalizeDocstring = lambda x : x

#XXX: Have to hard-code the location to Murmur.ice for now, because I don't know 
#how to make Murmure available to metaCallbackI and serverCallbackI without
Ice.loadSlice('', ['-I' + Ice.getSliceDir(), "/usr/share/slice/Murmur.ice" ] )
import Murmur

class metaCallbackI(Murmur.MetaCallback):
    def started(self, s, current=None):
        print "DEBUG: got a callback on started"
        serverR=Murmur.ServerCallbackPrx.uncheckedCast(adapter.addWithUUID(serverCallbackI(server, current.adapter)))
        s.addCallback(serverR)

class serverCallbackI(Murmur.ServerCallback):
    def __init__(self, server, adapter, m):
        self.server = server
        self.m = m
    def userConnected(self, p, current=None):
        self.m.SayChannels(self.m.irc, "%s connected"%p.name)
    def userDisconnected(self, p, current=None):
コード例 #18
0
ファイル: Server.py プロジェクト: DavidGB18/hello.ice
#!/usr/bin/python3 -u
# -*- coding: utf-8; mode: python; -*-

import sys
import traceback
import threading
import Ice

Ice.loadSlice('Printer.ice')
Ice.loadSlice('-I{} Callback.ice'.format(Ice.getSliceDir()))
import Example


class PrinterCallbackI(Example.Callback, threading.Thread):
    def __init__(self, communicator):
        threading.Thread.__init__(self)
        self._broker = communicator
        self._destroy = False
        self._clients = []
        self._cond = threading.Condition()

    def destroy(self):
        self._cond.acquire()

        print("destroying callback sender")
        self._destroy = True

        try:
            self._cond.notify()
        finally:
            self._cond.release()
コード例 #19
0
import numpy as np

import Ice, os, sys
Ice.loadSlice("-I" + Ice.getSliceDir() + " --all " +
              os.path.dirname(__file__) + "/slice/data.ice")
sys.path.append(os.path.dirname(__file__) + "/slice")
Ice.updateModules()
import DataFlow

from ..utils.logger import logger


def _convertNPDType2NDDType(dtype):
    if dtype == np.float32: ret = DataFlow.NDType.ndtFloat32
    elif dtype == np.uint8: ret = DataFlow.NDType.ndtUint8
    elif dtype == np.int32: ret = DataFlow.NDType.ndtInt32
    elif dtype == np.int64: ret = DataFlow.NDType.ndtInt64
    else: assert 0, "unknown dtype: {}".format(dtype)
    return ret


def _convertNDDType2NPDType(dtype):
    if dtype == DataFlow.NDType.ndtFloat32: return np.float32
    if dtype == DataFlow.NDType.ndtUint8: return np.uint8
    if dtype == DataFlow.NDType.ndtInt32: return np.int32
    if dtype == DataFlow.NDType.ndtInt64: return np.int64
    assert (0), 'unknow dtype: {}'.format(dtype)


def np2NDArray(array, cls=DataFlow.NDArray):
    ret = cls()
コード例 #20
0
ファイル: mumble-json.py プロジェクト: Kasper4711/mumble-json
SERVER_ID = 1

# provide correct location of slice here
SLICE = '/usr/share/slice/Murmur.ice'

# The port of the ICE connection
ICE_PORT = 6502

##################################################################################
# DO NOT EDIT BEYOND THIS LINE !!!
##################################################################################

import Ice
import sys

Ice.loadSlice("", ["-I" + Ice.getSliceDir(), SLICE])
import Murmur

# Init ice
comm = Ice.initialize()
# Let Ice know where to go to connect to mumble
proxy = comm.stringToProxy('Meta -e 1.0:tcp -p ' + str(ICE_PORT))
# Create a dynamic object that allows us to get a programmable interface for Mumble
meta = Murmur.MetaPrx.checkedCast(proxy)

##################################################################################
# Query the Mumble server
##################################################################################

# Get the server instance from the set of servers.
server = meta.getServer(SERVER_ID)
コード例 #21
0
import os
import yaml
import Ice
from mumble.app import create_app

with open('./config.yml') as f:
    config_file = yaml.load(f.read())

Ice.loadSlice('', ['-I' + Ice.getSliceDir(), config_file['SLICE_FILE']])

app = create_app(config_object=config_file)

if __name__ == '__main__':
    app.run('0.0.0.0', port=int(os.environ.get('PORT', 5002)), debug=True)
コード例 #22
0
#
# Author: Ruben Perez <*****@*****.**>


import sys, traceback, Ice,IceGrid
import time
import threading
import pdb
from geoserver.catalog import Catalog
from geoserver.workspace import Workspace
from geoserver.store import DataStore
from geoserver.store import CoverageStore
from geoserver.catalog import Catalog, ConflictingDataError, UploadError, \
    FailedRequestError
#Ice.loadSlice('-I {} Geocloud.ice'.format(Ice.getSliceDir()))
Ice.loadSlice('-I'+Ice.getSliceDir()+' Geocloud.ice')
import geocloud


class ArchiveAndCatalogueI(geocloud.ArchiveAndCatalogue):

    def __init__(self,com):
        if not com:
            raise RuntimeError("Not communicator")
        self.com=com
        q = com.stringToProxy('IceGrid/Query')
        self.query = IceGrid.QueryPrx.checkedCast(q)
        if not self.query:
            raise RuntimeError("Invalid proxy")
        self.broker=geocloud.BrokerPrx.checkedCast(com.stringToProxy("broker"))
        self.sem = Ice.threading.RLock() #Lock for managing the data structures
コード例 #23
0
ファイル: run-backend.py プロジェクト: migel1976/dpl_test
#import ipdb
import Ice, sys, os
import prctl, signal

if not 'topdir' in os.environ:
    raise Exception("no topdir specified in env")

Ice.loadSlice("--all -I. -I{ICE_SLICE_DIR} {top}/backend/backend.ice".format(
    ICE_SLICE_DIR=Ice.getSliceDir(), top=os.environ['topdir']))
import Hello


class HelloI(Hello.HelloIfc):
    def sayHello(self, current):
        name = 'Hello world'
        return name

    def sayAloha(self, current):
        name = 'Aloha'
        return name

    #    print "Hello World!"
    #    return "Hello, World!"
    #


if __name__ == "__main__":
    # https://github.com/seveas/python-prctl -- prctl wrapper module
    # more on pdeathsignal: https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
    prctl.set_pdeathsig(
        signal.SIGTERM)  # if parent dies this child will get SIGTERM
コード例 #24
0
def do_main_program():
    #
    # --- Authenticator implementation
    #    All of this has to go in here so we can correctly daemonize the tool
    #    without losing the file descriptors opened by the Ice module
    slicedir = Ice.getSliceDir()
    if not slicedir:
        slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
    else:
        slicedir = ["-I" + slicedir]
    Ice.loadSlice("", slicedir + [cfg.ice.slice])
    import Murmur

    # If we are using entryUUID, create a entryUUID mapping file
    if cfg.ldap.number_attr == "entryUUID":
        head, tail = os.path.split(cfgfile)
        mapper_file = "entryuuid.map"
        if head:
            mapper_file = "{}/{}".format(head, mapper_file)
        info("Using entryUUID mapping file '{}'".format(mapper_file))
        try:
            with open(mapper_file, "r") as filehandle:
                for line in filehandle:
                    if not line.startswith("#"):
                        entry_uuid_mapping.append(line.strip())
        except FileNotFoundError:
            pass
        info("Imported {} user mappings".format(len(entry_uuid_mapping)))

    class LDAPAuthenticatorApp(Ice.Application):
        def run(self, args):
            self.shutdownOnInterrupt()

            if not self.initializeIceConnection():
                return 1

            if cfg.ice.watchdog > 0:
                self.failedWatch = True
                self.checkConnection()

            # Serve till we are stopped
            self.communicator().waitForShutdown()
            self.watchdog.cancel()

            if self.interrupted():
                warning("Caught interrupt, shutting down")

            return 0

        def initializeIceConnection(self):
            """
            Establishes the two-way Ice connection and adds the authenticator to the
            configured servers
            """
            ice = self.communicator()

            if cfg.ice.secret:
                debug("Using shared ice secret")
                ice.getImplicitContext().put("secret", cfg.ice.secret)
            elif not cfg.glacier.enabled:
                warning("Consider using an ice secret to improve security")

            if cfg.glacier.enabled:
                # info("Connecting to Glacier2 server (%s:%d)", glacier_host, glacier_port)
                error("Glacier support not implemented yet")
                # TODO: Implement this

            info("Connecting to Ice server (%s:%d)", cfg.ice.host,
                 cfg.ice.port)
            base = ice.stringToProxy("Meta:tcp -h %s -p %d" %
                                     (cfg.ice.host, cfg.ice.port))
            self.meta = Murmur.MetaPrx.uncheckedCast(base)

            adapter = ice.createObjectAdapterWithEndpoints(
                "Callback.Client", "tcp -h %s" % cfg.ice.host)
            adapter.activate()

            metacbprx = adapter.addWithUUID(metaCallback(self))
            self.metacb = Murmur.MetaCallbackPrx.uncheckedCast(metacbprx)

            authprx = adapter.addWithUUID(LDAPAuthenticator())
            self.auth = Murmur.ServerUpdatingAuthenticatorPrx.uncheckedCast(
                authprx)

            return self.attachCallbacks()

        def attachCallbacks(self, quiet=False):
            """
            Attaches all callbacks for meta and authenticators
            """

            # Ice.ConnectionRefusedException
            # debug("Attaching callbacks")
            try:
                if not quiet:
                    info("Attaching meta callback")

                self.meta.addCallback(self.metacb)

                for server in self.meta.getBootedServers():
                    if not cfg.murmur.servers or server.id(
                    ) in cfg.murmur.servers:
                        if not quiet:
                            info(
                                "Setting authenticator for virtual server %d",
                                server.id(),
                            )
                        server.setAuthenticator(self.auth)

            except (
                    Murmur.InvalidSecretException,
                    Ice.UnknownUserException,
                    Ice.ConnectionRefusedException,
            ) as e:
                if isinstance(e, Ice.ConnectionRefusedException):
                    error("Server refused connection")
                elif (isinstance(e, Murmur.InvalidSecretException)
                      or isinstance(e, Ice.UnknownUserException) and
                      (e.unknown == "Murmur::InvalidSecretException")):
                    error("Invalid ice secret")
                else:
                    # We do not actually want to handle this one, re-raise it
                    raise e

                self.connected = False
                return False

            self.connected = True
            return True

        def checkConnection(self):
            """
            Tries reapplies all callbacks to make sure the authenticator
            survives server restarts and disconnects.
            """
            # debug("Watchdog run")

            try:
                if not self.attachCallbacks(quiet=not self.failedWatch):
                    self.failedWatch = True
                else:
                    self.failedWatch = False
            except Ice.Exception as e:
                error(
                    "Failed connection check, will retry in next watchdog run (%ds)",
                    cfg.ice.watchdog,
                )
                debug(str(e))
                self.failedWatch = True

            # Renew the timer
            self.watchdog = Timer(cfg.ice.watchdog, self.checkConnection)
            self.watchdog.start()

    def checkSecret(func):
        """
        Decorator that checks whether the server transmitted the right secret
        if a secret is supposed to be used.
        """
        if not cfg.ice.secret:
            return func

        def newfunc(*args, **kws):
            if "current" in kws:
                current = kws["current"]
            else:
                current = args[-1]

            if (not current or "secret" not in current.ctx
                    or current.ctx["secret"] != cfg.ice.secret):
                error(
                    "Server transmitted invalid secret. Possible injection attempt."
                )
                raise Murmur.InvalidSecretException()

            return func(*args, **kws)

        return newfunc

    def fortifyIceFu(retval=None, exceptions=(Ice.Exception, )):
        """
        Decorator that catches exceptions,logs them and returns a safe retval
        value. This helps preventing the authenticator getting stuck in
        critical code paths. Only exceptions that are instances of classes
        given in the exceptions list are not caught.

        The default is to catch all non-Ice exceptions.
        """
        def newdec(func):
            def newfunc(*args, **kws):
                try:
                    return func(*args, **kws)
                except Exception as e:
                    catch = True
                    for ex in exceptions:
                        if isinstance(e, ex):
                            catch = False
                            break

                    if catch:
                        critical("Unexpected exception caught")
                        exception(e)
                        return retval
                    raise

            return newfunc

        return newdec

    class metaCallback(Murmur.MetaCallback):
        def __init__(self, app):
            Murmur.MetaCallback.__init__(self)
            self.app = app

        @fortifyIceFu()
        @checkSecret
        def started(self, server, current=None):
            """
            This function is called when a virtual server is started
            and makes sure an authenticator gets attached if needed.
            """
            if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                info("Setting authenticator for virtual server %d",
                     server.id())
                try:
                    server.setAuthenticator(app.auth)
                # Apparently this server was restarted without us noticing
                except (Murmur.InvalidSecretException,
                        Ice.UnknownUserException) as e:
                    if (hasattr(e, "unknown")
                            and e.unknown != "Murmur::InvalidSecretException"):
                        # Special handling for Murmur 1.2.2 servers with invalid slice files
                        raise e

                    error("Invalid ice secret")
                    return
            else:
                debug("Virtual server %d got started", server.id())

        @fortifyIceFu()
        @checkSecret
        def stopped(self, server, current=None):
            """
            This function is called when a virtual server is stopped
            """
            if self.app.connected:
                # Only try to output the server id if we think we are still connected to prevent
                # flooding of our thread pool
                try:
                    if not cfg.murmur.servers or server.id(
                    ) in cfg.murmur.servers:
                        info("Authenticated virtual server %d got stopped",
                             server.id())
                    else:
                        debug("Virtual server %d got stopped", server.id())
                    return
                except Ice.ConnectionRefusedException:
                    self.app.connected = False

            debug("Server shutdown stopped a virtual server")

    if cfg.user.reject_on_error:  # Python 2.4 compat
        authenticateFortifyResult = (-1, None, None)
    else:
        authenticateFortifyResult = (-2, None, None)

    class LDAPAuthenticator(Murmur.ServerUpdatingAuthenticator):
        def __init__(self):
            Murmur.ServerUpdatingAuthenticator.__init__(self)
            self.name_uid_cache = dict()

        @fortifyIceFu(authenticateFortifyResult)
        @checkSecret
        def authenticate(self,
                         name,
                         pw,
                         certlist,
                         certhash,
                         strong,
                         current=None):
            """
            This function is called to authenticate a user
            """

            # Search for the user in the database
            FALL_THROUGH = -2
            AUTH_REFUSED = -1

            # SuperUser is a special login.
            if name == "SuperUser":
                debug("Forced fall through for SuperUser")
                return (FALL_THROUGH, None, None)

            # Otherwise, let's check the LDAP server.
            uid = None

            if cfg.ldap.use_start_tls:
                # try StartTLS: global options
                debug(
                    "use_start_tls is set, setting global option TLS_REQCERT = never"
                )
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
                                ldap.OPT_X_TLS_NEVER)

            ldap_trace = 0  # Change to 1 for more verbose trace
            ldap_conn = ldap.initialize(cfg.ldap.ldap_uri, ldap_trace)

            if cfg.ldap.use_start_tls:
                # try StartTLS: connection specific options
                debug(
                    "use_start_tls is set, setting connection options X_TLS_*")
                ldap_conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
                ldap_conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
                ldap_conn.set_option(ldap.OPT_X_TLS_DEMAND, True)
                try:
                    ldap_conn.start_tls_s()
                except Exception as e:
                    warning("could not initiate StartTLS, e = " + str(e))
                    return (AUTH_REFUSED, None, None)

            if cfg.ldap.bind_dn:
                # Bind the functional account to search the directory.
                bind_dn = cfg.ldap.bind_dn
                bind_pass = cfg.ldap.bind_pass
                try:
                    debug("try to connect to ldap (bind_dn will be used)")
                    ldap_conn.bind_s(bind_dn, bind_pass)
                except ldap.INVALID_CREDENTIALS:
                    ldap_conn.unbind()
                    warning("Invalid credentials for bind_dn=" + bind_dn)
                    return (AUTH_REFUSED, None, None)
            elif cfg.ldap.discover_dn:
                # Use anonymous bind to discover the DN
                try:
                    ldap_conn.bind_s()
                except ldap.INVALID_CREDENTIALS:
                    ldap_conn.unbind()
                    warning("Failed anomymous bind for discovering DN")
                    return (AUTH_REFUSED, None, None)

            else:
                # Prevent anonymous authentication.
                if not pw:
                    warning("No password supplied for user " + name)
                    return (AUTH_REFUSED, None, None)

                # Bind the user account to search the directory.
                bind_dn = "%s=%s,%s" % (cfg.ldap.username_attr, name,
                                        cfg.ldap.users_dn)
                bind_pass = pw
                try:
                    ldap_conn.bind_s(bind_dn, bind_pass)
                except ldap.INVALID_CREDENTIALS:
                    ldap_conn.unbind()
                    warning("User " + name +
                            " failed with invalid credentials")
                    return (AUTH_REFUSED, None, None)

            # Search for the user.
            res = ldap_conn.search_s(
                cfg.ldap.users_dn,
                ldap.SCOPE_SUBTREE,
                "(%s=%s)" % (cfg.ldap.username_attr, name),
                [cfg.ldap.number_attr, cfg.ldap.display_attr],
            )
            if len(res) == 0:
                warning("User " + name + " not found")
                if cfg.user.reject_on_miss:
                    return (AUTH_REFUSED, None, None)
                else:
                    return (FALL_THROUGH, None, None)
            match = res[
                0]  # Only interested in the first result, as there should only be one match

            # Parse the user information.
            uid = self.getMumbleID(match[1][cfg.ldap.number_attr][0])
            displayName = match[1][cfg.ldap.display_attr][0].decode("UTF-8")
            user_dn = match[0]
            debug("User match found, display '" + displayName + "' with UID " +
                  repr(uid))

            # Optionally check groups.
            if cfg.ldap.group_cn != "":
                debug("Checking group membership for " + name)

                # Search for user in group
                res = ldap_conn.search_s(
                    cfg.ldap.group_cn,
                    ldap.SCOPE_SUBTREE,
                    "(%s=%s)" % (cfg.ldap.group_attr, user_dn),
                    [cfg.ldap.number_attr, cfg.ldap.display_attr],
                )

                # Check if the user is a member of the group
                if len(res) < 1:
                    debug("User " + name + " failed with no group membership")
                    return (AUTH_REFUSED, None, None)

            # Second bind to test user credentials if using bind_dn or discover_dn.
            if cfg.ldap.bind_dn or cfg.ldap.discover_dn:
                # Prevent anonymous authentication.
                if not pw:
                    warning("No password supplied for user " + name)
                    return (AUTH_REFUSED, None, None)

                bind_dn = user_dn
                bind_pass = pw
                try:
                    ldap_conn.bind_s(bind_dn, bind_pass)
                except ldap.INVALID_CREDENTIALS:
                    ldap_conn.unbind()
                    warning("User " + name + " failed with wrong password")
                    return (AUTH_REFUSED, None, None)

            # Unbind and close connection.
            ldap_conn.unbind()

            # If we get here, the login is correct.
            # Add the user/id combo to cache, then accept:
            self.name_uid_cache[displayName] = uid
            debug("Login accepted for " + name)
            return (uid + cfg.user.id_offset, displayName, [])

        @fortifyIceFu((False, None))
        @checkSecret
        def getInfo(self, id, current=None):
            """
            Gets called to fetch user specific information
            """

            if not cfg.ldap.provide_info:
                # We do not expose any additional information so always fall through
                debug("getInfo for %d -> denied", id)
                return (False, None)

            ldap_conn = ldap.initialize(cfg.ldap.ldap_uri, 0)

            # Bind if configured, else do explicit anonymous bind
            if cfg.ldap.bind_dn and cfg.ldap.bind_pass:
                ldap_conn.simple_bind_s(cfg.ldap.bind_dn, cfg.ldap.bind_pass)
            else:
                ldap_conn.simple_bind_s()

            name = self.idToName(id, current)

            res = ldap_conn.search_s(
                cfg.ldap.users_dn,
                ldap.SCOPE_SUBTREE,
                "(%s=%s)" % (cfg.ldap.display_attr, name),
                [cfg.ldap.display_attr, cfg.ldap.mail_attr],
            )

            # If user found, return info
            if len(res) == 1:
                info = {}

                if cfg.ldap.mail_attr in res[0][1]:
                    info[Murmur.UserInfo.UserEmail] = res[0][1][
                        cfg.ldap.mail_attr][0].decode("UTF-8")

                debug("getInfo %s -> %s", name, repr(info))
                return (True, info)
            else:
                debug("getInfo %s -> ?", name)
                return (False, None)

        @fortifyIceFu(-2)
        @checkSecret
        def nameToId(self, name, current=None):
            """
            Gets called to get the id for a given username
            """
            FALL_THROUGH = -2

            if name == "SuperUser":
                debug("nameToId SuperUser -> forced fall through")
                return FALL_THROUGH

            if name in self.name_uid_cache:
                uid = self.name_uid_cache[name] + cfg.user.id_offset
                debug("nameToId %s (cache) -> %d", name, uid)
                return uid

            ldap_conn = ldap.initialize(cfg.ldap.ldap_uri, 0)

            # Bind if configured, else do explicit anonymous bind
            if cfg.ldap.bind_dn and cfg.ldap.bind_pass:
                ldap_conn.simple_bind_s(cfg.ldap.bind_dn, cfg.ldap.bind_pass)
            else:
                ldap_conn.simple_bind_s()

            res = ldap_conn.search_s(
                cfg.ldap.users_dn,
                ldap.SCOPE_SUBTREE,
                "(%s=%s)" % (cfg.ldap.display_attr, name),
                [cfg.ldap.number_attr],
            )

            # If user found, return the ID
            if len(res) == 1:
                uid = (self.getMumbleID(res[0][1][cfg.ldap.number_attr][0]) +
                       cfg.user.id_offset)
                debug("nameToId %s -> %d", name, uid)
            else:
                debug("nameToId %s -> ?", name)
                return FALL_THROUGH

            return uid

        @fortifyIceFu("")
        @checkSecret
        def idToName(self, id, current=None):
            """
            Gets called to get the username for a given id
            """

            FALL_THROUGH = ""

            # Make sure the ID is in our range and transform it to the actual LDAP user id
            if id < cfg.user.id_offset:
                debug("idToName %d -> fall through", id)
                return FALL_THROUGH

            ldapid = id - cfg.user.id_offset

            for name, uid in self.name_uid_cache.items():
                if uid == ldapid:
                    if name == "SuperUser":
                        debug("idToName %d -> 'SuperUser' catched", id)
                        return FALL_THROUGH

                    debug("idToName %d -> '%s'", id, name)
                    return name

            debug("idToName %d -> ?", id)
            return FALL_THROUGH

        @fortifyIceFu("")
        @checkSecret
        def idToTexture(self, id, current=None):
            """
            Gets called to get the corresponding texture for a user
            """

            FALL_THROUGH = ""
            debug("idToTexture %d -> fall through", id)
            return FALL_THROUGH

        @fortifyIceFu(-2)
        @checkSecret
        def registerUser(self, name, current=None):
            """
            Gets called when the server is asked to register a user.
            """

            FALL_THROUGH = -2
            debug("registerUser '%s' -> fall through", name)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def unregisterUser(self, id, current=None):
            """
            Gets called when the server is asked to unregister a user.
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to internal server database, we will not modify the LDAP directory
            # but we can make murmur delete all additional information it got this way.
            debug("unregisterUser %d -> fall through", id)
            return FALL_THROUGH

        @fortifyIceFu({})
        @checkSecret
        def getRegisteredUsers(self, filter, current=None):
            """
            Returns a list of usernames in the LDAP directory which contain
            filter as a substring.
            """
            FALL_THROUGH = {}

            if not cfg.ldap.provide_users:
                # Fall through if not configured to provide user list
                debug("getRegisteredUsers -> fall through")
                return FALL_THROUGH

            ldap_conn = ldap.initialize(cfg.ldap.ldap_uri, 0)

            # Bind if configured, else do explicit anonymous bind
            if cfg.ldap.bind_dn and cfg.ldap.bind_pass:
                ldap_conn.simple_bind_s(cfg.ldap.bind_dn, cfg.ldap.bind_pass)
            else:
                ldap_conn.simple_bind_s()

            if filter:
                res = ldap_conn.search_s(
                    cfg.ldap.users_dn,
                    ldap.SCOPE_SUBTREE,
                    "(&(uid=*)(%s=*%s*))" % (cfg.ldap.display_attr, filter),
                    [cfg.ldap.number_attr, cfg.ldap.display_attr],
                )
            else:
                res = ldap_conn.search_s(
                    cfg.ldap.users_dn,
                    ldap.SCOPE_SUBTREE,
                    "(uid=*)",
                    [cfg.ldap.number_attr, cfg.ldap.display_attr],
                )

            # Build result dict
            users = {}
            for dn, attrs in res:
                if cfg.ldap.number_attr in attrs and cfg.ldap.display_attr in attrs:
                    uid = (self.getMumbleID(attrs[cfg.ldap.number_attr][0]) +
                           cfg.user.id_offset)
                    name = attrs[cfg.ldap.display_attr][0].decode("UTF-8")
                    users[uid] = name
            debug("getRegisteredUsers %s -> %s", filter, repr(users))
            return users

        @fortifyIceFu(-1)
        @checkSecret
        def setInfo(self, id, info, current=None):
            """
            Gets called when the server is supposed to save additional information
            about a user to his database
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to the internal server handler. We do not store
            # any information in LDAP
            debug("setInfo %d -> fall through", id)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def setTexture(self, id, texture, current=None):
            """
            Gets called when the server is asked to update the user texture of a user
            """
            FALL_THROUGH = -1

            # We do not store textures in LDAP
            debug("setTexture %d -> fall through", id)
            return FALL_THROUGH

        def getMumbleID(self, number_attr) -> int:
            """
            Gets the Mumble User ID for a given number_attr
            number_attr will be converted to an int
            If number_attr is an entryUUID, this will take care of mapping it
            """
            if cfg.ldap.number_attr == "entryUUID":
                entry_uuid = number_attr.decode("UTF-8")
                if entry_uuid not in entry_uuid_mapping:
                    entry_uuid_mapping.append(entry_uuid)
                    with open(mapper_file, "w") as filehandle:
                        filehandle.write(
                            "# DO NOT MODIFY THIS FILE! Changing anything here will mess up your Mumble permissions!\n"
                        )
                        for listitem in entry_uuid_mapping:
                            filehandle.write("{}\n".format(listitem))
                mumble_id = entry_uuid_mapping.index(entry_uuid) + 1
                debug("Mapping entryUUID '{}' -> '{}'".format(
                    entry_uuid, mumble_id))
                return mumble_id
            else:
                return int(number_attr)

    class CustomLogger(Ice.Logger):
        """
        Logger implementation to pipe Ice log messages into
        out own log
        """
        def __init__(self):
            Ice.Logger.__init__(self)
            self._log = getLogger("Ice")

        def _print(self, message):
            self._log.info(message)

        def trace(self, category, message):
            self._log.debug("Trace %s: %s", category, message)

        def warning(self, message):
            self._log.warning(message)

        def error(self, message):
            self._log.error(message)

    #
    # --- Start of authenticator
    #
    info("Starting LDAP mumble authenticator")
    initdata = Ice.InitializationData()
    initdata.properties = Ice.createProperties([], initdata.properties)
    for prop, val in cfg.iceraw:
        initdata.properties.setProperty(prop, val)

    initdata.properties.setProperty("Ice.ImplicitContext", "Shared")
    initdata.properties.setProperty("Ice.Default.EncodingVersion", "1.0")
    initdata.logger = CustomLogger()

    app = LDAPAuthenticatorApp()
    app.main(sys.argv[:1], initData=initdata)
    info("Shutdown complete")
コード例 #25
0
 def init_slice():
     slice_dir = '-I' + Ice.getSliceDir()
     slice_file = 'Murmur.ice'
     Ice.loadSlice('', [slice_dir] + [slice_file])
コード例 #26
0
ファイル: auth.py プロジェクト: tyler274/murmur_auth
def do_main_program():
    try:
        sql = "CREATE TABLE IF NOT EXISTS user_inf LIKE user_info"
        mumdbcon = db.connect(mdbhost,mdbuser,mdbpw,mdbname)
        curs = mumdbcon.cursor()
        curs.execute(sql)
        curs.close()
        mumdbcon.autocommit(True)
    except db.OperationalError as e:
        info("user_inf table exists, will not try to make.")

    try:
        forumdbcon = db.connect(dbhost,dbuser,dbpw,dbname)
    except db.OperationalError as e:
        error("Database error: {}".format(e))

    Ice.loadSlice('', ['-I'+Ice.getSliceDir(), slicefile])
    info("Ice Loaded")
    import Murmur

    class AuthenticatorApp(Ice.Application):
        def run(self, args):
            self.shutdownOnInterrupt()

            if not self.initializeIceConnection():
                return 1
            self.communicator().waitForShutdown()

            if self.interrupted():
                warning("Murmur-auth shutdown, removing callbacks.")
                self.meta.removeCallback(self.metacb)

            forumdbcon.close()
            mumdbcon.close()

            return 0

        def initializeIceConnection(self):
            ice = self.communicator()
            ice.getImplicitContext().put("secret",iceSecret)
            info("Connecting to server {} on port {}".format(iceHost,icePort))

            base = ice.stringToProxy('Meta:tcp -h {} -p {}'.format(iceHost,icePort))
            self.meta = Murmur.MetaPrx.uncheckedCast(base)

            adapter = ice.createObjectAdapterWithEndpoints('Callback.Client', 'tcp -h {}'.format(iceHost))
            adapter.activate()
            self.adapter = adapter

            metacbprx = adapter.addWithUUID(metaCallback(self))
            self.metacb = Murmur.MetaCallbackPrx.uncheckedCast(metacbprx)

#            authprx = adapter.addWithUUID(Authenticator())
#            self.auth = Murmur.ServerAuthenticatorPrx.uncheckedCast(authprx)

            return self.attachCallbacks(adapter)

        def checkConnection(self):
#            try:
#                if not self.attachCallbacks(self.adapter,quiet = not self.failedWatch):
#                    self.failedWatch = True
#                else:
#                    self.failedWatch = False
#            except Ice.Exception as e:
#                error("Failed connection check, will retry in next watchdog run ({})".format(watchdog))
#                debug(str(e))
#                self.watchFailed = True
#            self.watchdog = Timer(watchdog, self.checkConnection)
#            self.watchdog.start()
             return

        def attachCallbacks(self, adapter, quiet = False):
            try:
                self.meta.addCallback(self.metacb)
                for server in self.meta.getBootedServers():
                    if not servers or server.id() in servers:
                        serverprx = Murmur.ServerCallbackPrx.uncheckedCast(adapter.addWithUUID(ServerCallbackI(server, adapter)))
                        server.addCallback(serverprx)
                        server.setAuthenticator(Murmur.ServerAuthenticatorPrx.uncheckedCast(adapter.addWithUUID(Authenticator(int(server.id())))))

            except (Murmur.InvalidSecretException, Ice.UnknownUserException, Ice.ConnectionRefusedException) as e:
                if isinstance(e, Ice.ConnectionRefusedException):
                    error('Server refused connection')
                elif isinstance(e, Murmur.invalidSecretException) or isinstance(e, Ice.UnknownUserException) and (e.unknown == 'Murmur::InvalidSecretException'):
                    error('Invalid Secret')
                else:
                    raise e
                self.connected = False
                return False
            self.connected = True
            return True
    def fortifyIceFu(retval = None, exceptions = (Ice.Exception,)):
        def newdec(func):
            def newfunc(*args,**kws):
                try:
                    return func(*args,**kws)
                except Exception as e:
                    catch = True
                    for ex in exceptions:
                        if isinstance(e,ex):
                            catch = False
                            break
                    if catch:
                        critical("Unexpected exception caught")
                        critical(e)
                        return retval
                    raise
            return newfunc
        return newdec

    def checkSecret(func):
        if not iceSecret:
                return func
        def newfunc(*args,**kws):
            if 'current' in kws:
                current = kws["current"]
            else:
                current = args[-1]
            if not current or 'secret' not in current.ctx or current.ctx['secret'] != iceSecret:
                error("Server transmitted invalid secret. Possible injection attempt.")
                raise Murmur.InvalidSecretException()
            return func(*args,**kws)
        return newfunc                          

    class ServerCallbackI(Murmur.ServerCallback):
        def __init__(self, server, adapter):
            self.server = server
            self.contextR = Murmur.ServerContextCallbackPrx.uncheckedCast(adapter.addWithUUID(ServerContextCallbackI(server)))

        def userConnected(self, p, current = None):
            if p.address[10] == 255 and p.address[11] == 255:
                address = '.'.join(map(str,p.address[12:]))
            else:
                ip = []
                for i in p.address:
                    n = hex(i).split('x')[1]
                    if len(n) < 2:
                        n = "0"+n
                    ip.append(n)
                address = str(ip[0]+ip[1]+":"+ip[2]+ip[3]+":"+ip[4]+ip[5]+":"+ip[6]+ip[7]+":"+ip[8]+ip[9]+":"+ip[10]+ip[11]+":"+ip[12]+ip[13]+":"+ip[14]+ip[15])
            info("User {} connected from IP: {}".format(p.name, address))
#            sql = "SELECT mgroup_others FROM gsfForums.members WHERE member_id = %s"
#            con = db.connect(dbhost,dbuser,dbpw,dbname)
#            cur = con.cursor()
#            cur.execute(sql,(p.userid,))
#            res = cur.fetchone()
#            cur.close()
#            con.close()
#            if res:
#                groups = res[0].split(',')
#                isFc = False
#                for g in fcgroups:
#                    if g in groups:
#                        isFc = True
#                if isFc:
#                    info("User {} is an FC, adding context callback".format(p.name))
#                    self.server.addContextCallback(p.session, "Buttes", "Dongues", self.contextR, Murmur.ContextChannel)

        def userDisconnected(self, p, current = None):
            info("User {} disconnected".format(p.name))

    class ServerContextCallbackI(Murmur.ServerContextCallback):
        def __init__(self, server):
            self.server = server
        def contextAction(self, action, p, session, chanid, current = None):
            info("Action: {}, User: {}, SessionID: {}, Channel ID: {}".format(action, p.name, session, chanid))

    class metaCallback(Murmur.MetaCallback):
        def __init__(self,app):
            Murmur.MetaCallback.__init__(self)
            self.app = app
        @fortifyIceFu()
        @checkSecret
        def started(self, server, current = None):
            if not servers or server.id() in servers:
                try:
                    server.setAuthenticator(app.auth)
                except (Murmur.InvalidSecretException, Ice.UnknownUserException) as e:
                    if hasattr(e, "unknown" and e.unknown != "Murmur:InvalidSecretException"):
                        raise e

                    error("invalid secret")
                    return()
        @fortifyIceFu()
        @checkSecret
        def stopped(self, server, current = None):
            if self.app.connected:
                try:
                    if not servers or server.id() in servers:
                        debug("Mumble server was stopped")
                except Ice.ConnectionRefusedException:
                    self.app.connected = False
            os._exit(1)

    class Authenticator(Murmur.ServerAuthenticator):
        texture_cache = {}
        def __init__(self,serverid):
            Murmur.ServerAuthenticator.__init__(self)
            self.sid = serverid

        @fortifyIceFu(authenticateFortifyResult)
        @checkSecret

        def authenticate(self, name, pw, certlist, certhash, strong, current = None):
            forumdbcon.ping(True)
            mumdbcon.ping(True)

            FALL_THROUGH = -2
            AUTH_REFUSED = -1
            serverID = 1
            info("Authentication attempt for user '{}', cert hash '{}'".format(name,certhash))

            if name == 'SuperUser':
                return(FALL_THROUGH,None,None)
            
            #Check to see if a certificate hash exists for this user
            
            if name.find(' - ') > -1:
                name = name.split(' - ')[1]
            name = name.title()
            sql = "SELECT lcase(u.name),u.user_id, ui.value FROM users u JOIN user_inf ui ON ui.user_id = u.user_id WHERE SUBSTR(u.name,LOCATE(' - ',u.name)+3) = %s AND ui.value = %s"
            try:
                cur2 = mumdbcon.cursor()
                cur2.execute(sql,(name,certhash))
                res1 = cur2.fetchone()
                cur2.close()

                if res1:
                    sql = "SELECT CONCAT(t.ticker,' - ',replace(m.name,'&#39;','\\'')) AS name, m.member_id, g.g_title, m.member_banned FROM gsfForums.members m \
    JOIN gsfGSOAR.mumble esa ON esa.member_id = m.member_id JOIN gsfForums.groups g ON FIND_IN_SET(g.g_id, CONCAT(m.mgroup_others,',',m.member_group_id))\
    JOIN gsfGSOAR.groupTickers t ON t.groupID = m.member_group_id \
    WHERE (m.member_id = %s) ORDER BY g_title"
                    try:
                        cur3 = forumdbcon.cursor()
                        cur3.execute(sql,(res1[1],))
                        res2 = cur3.fetchall()
                        cur3.close()
                        groups = []
                        uname = ''
                        member_id = 0
                        for name, memid, gTitle, banned in res2:
                            if banned == 1:
                                info("Banned user '{}' attempted to connect.".format(name))
                                return(AUTH_REFUSED,None,None)
                            uname = name
                            member_id = memid
                            if gTitle == 'Administrators':
                                groups.append("admin")
                                info("User '{}' is an admin, adding to admin group".format(name))
                            else:
                                groups.append(gTitle)
                        info("User '{}' Authenticated by certificate hash. Added to groups {}".format(uname,groups))
                        return(member_id,uname,groups)
                    except (db.Error, db.OperationalError) as e:
                        error("Database error: {}".format(str(e)))
                        return(FALL_THROUGH,None,None)
                else:
                #No cert hash found, must be a new user. Check uname and pw against forum/esa dbs
                    sql = "SELECT CONCAT(t.ticker,' - ',replace(m.name,'&#39;','\\'')) AS name, m.member_id, g.g_title, m.member_banned FROM gsfForums.members m \
    JOIN gsfGSOAR.mumble esa ON esa.member_id = m.member_id JOIN gsfForums.groups g ON FIND_IN_SET(g.g_id, CONCAT(m.mgroup_others,',',m.member_group_id))\
    JOIN gsfGSOAR.groupTickers t ON t.groupID = m.member_group_id \
    WHERE (m.name = replace(%s,'\\'','&#39;') OR (m.name = replace(SUBSTR(%s, LOCATE(' - ',%s)+3),'\\'','&#39;'))) AND esa.passwd = SHA1(%s) ORDER BY g.g_title;"
                    try:
                        cur = forumdbcon.cursor()
                        cur.execute(sql,(name,name,name,pw))
                        res = cur.fetchall()
                        cur.close()
                        if res:
                            groups = []
                            uname = ''
                            member_id = 0
                            for name, memid, gTitle, banned in res:
                                if banned == 1:
                                    info("Banned user '{}' attempted to connect.".format(name))
                                    return(AUTH_REFUSED,None,None)

                                uname = name
                                member_id = memid
                                if gTitle == 'Administrators':
                                    groups.append("admin")
                                    info("User '{}' is an admin, adding to admin group.".format(name))
                                else:
                                    groups.append(gTitle)
                            sql = "INSERT INTO `user_inf` (`server_id`, `user_id`, `key`, `value`) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE value = %s;"
                            try:
                                cur2 = mumdbcon.cursor()
                                cur2.execute(sql,(serverID,member_id,3,certhash,certhash))
                                info("This is the first time {} has connected, inserting cert hash into user_inf".format(name))
                                cur2.close()
                            except (db.Error, db.OperationalError) as e:
                                error("Database error: {}".format(str(e)))
                            info("User '{}' Authenticated by password. Added to groups {}".format(uname,groups))
                            return(member_id, uname, groups)
                        else:
                            info("Authentication failed for user '{}'. Password or certificate invalid. Cert hash: {}".format(name,certhash))
                            return(AUTH_REFUSED,None,None)
                    except (db.Error, db.OperationalError) as e:
                        error("Database error: {}".format(str(e)))
                        return(FALL_THROUGH,None,None)
            except (db.Error, db.OperationalError) as e:
                error("Database error: {}".format(str(e)))
                return(FALL_THROUGH,None,None)
        @fortifyIceFu((False,None))
        @checkSecret

        def getInfo(self, id, current = None):
            return(False, None)
        @fortifyIceFu(-2)
        @checkSecret
        def nameToId(self, name, current = None):
            FALL_THROUGH = -2
            return(FALL_THROUGH)
        @fortifyIceFu("")
        @checkSecret
        def idToName(self, id, current = None):
            FALL_THROUGH = ""
            return FALL_THROUGH
        @fortifyIceFu("")
        @checkSecret
        def registerUser(self, name, current = None):
            FALL_THROUGH = -2
            return FALL_THROUGH
        @fortifyIceFu(-1)
        @checkSecret
        def unregisterUser(self, id, current = None):
            FALL_THROUGH = -1
            return FALL_THROUGH
        @fortifyIceFu({})
        @checkSecret
        def getRegisteredUsers(self, filter, current = None):
            return {}
        @fortifyIceFu(-1)
        @checkSecret
        def setInfo(self, id, info, current = None):
            FALL_THROUGH = -1
            return FALL_THROUGH
        @fortifyIceFu(-1)
        @checkSecret
        def setTexture(self, id, texture, current = None):
            FALL_THROUGH = -1
            return FALL_THROUGH

    class CustomLogger(Ice.Logger):
        def __init__(self):
            Ice.Logger.__init__(self)
            self._log = getLogger("Ice")
        def _print(self, message):
            self._log.info(message)
        def trace(self, category, message):
            self._log.debug("Trace {}: {}".format(category,message))
        def info(self, message):
            self._log.info(message)
        def warning(self, message):
            self._log.warning(message)
        def error(self, message):
            self._log.error(message)

    info("Starting Auth")
    initdata = Ice.InitializationData()
    initdata.properties = Ice.createProperties([], initdata.properties)
    initdata.properties.setProperty('Ice.ThreadPool.Server.Size','5')
    initdata.properties.setProperty('Ice.ImplicitContext','Shared')
    initdata.logger = CustomLogger()

    app = AuthenticatorApp()
    state = app.main(sys.argv[:1], initData = initdata)
コード例 #27
0
ファイル: manage.py プロジェクト: J4LP/mumble
from flask.ext.migrate import MigrateCommand
from flask.ext.script import Manager
import yaml
import Ice
from mumble.app import create_app

with open("./config.yml") as f:
    config_file = yaml.load(f.read())

Ice.loadSlice("", ["-I" + Ice.getSliceDir(), config_file["SLICE_FILE"]])
app = create_app(config_object=config_file)

manager = Manager(app)
manager.add_command("db", MigrateCommand)

if __name__ == "__main__":
    manager.run()
コード例 #28
0
ファイル: service.py プロジェクト: kiu/jabber-auth
# encoding: utf-8

from __future__ import unicode_literals

import Ice
import sys
import time
from M2Crypto import X509;

Ice.loadSlice('', ['-I' + Ice.getSliceDir(), 'Murmur.ice'])

import Murmur


log = __import__('logging').getLogger(__name__)



"""


id = server.registerUser(username=username, password=password)

server.kickPlayer(id, reason)
server.unregisterUser(id)

user = server.getRegistration(id)
user.password = password
server.updateRegistration(id, user)

for is, name in server.getRegisteredUsers(""):
コード例 #29
0
ファイル: mumble-djangoauth.py プロジェクト: cronala/mafiasi
def do_main_program():
    #
    #--- Authenticator implementation
    #    All of this has to go in here so we can correctly daemonize the tool
    #    without loosing the file descriptors opened by the Ice module
    slicedir = Ice.getSliceDir()
    if not slicedir:
        slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
    else:
        slicedir = ['-I' + slicedir]
    Ice.loadSlice('', slicedir + [cfg.ice.slice])
    import Murmur

    class DjangoAuthenticatorApp(Ice.Application):
        def run(self, args):
            self.shutdownOnInterrupt()

            if not self.initializeIceConnection():
                return 1

            if cfg.ice.watchdog > 0:
                self.failedWatch = True
                self.checkConnection()

            # Serve till we are stopped
            self.communicator().waitForShutdown()
            self.watchdog.cancel()

            if self.interrupted():
                warning('Caught interrupt, shutting down')

            threadDB.disconnect()
            return 0

        def initializeIceConnection(self):
            """
            Establishes the two-way Ice connection and adds the authenticator to the
            configured servers
            """
            ice = self.communicator()

            if cfg.ice.secret:
                debug('Using shared ice secret')
                ice.getImplicitContext().put("secret", cfg.ice.secret)
            elif not cfg.glacier.enabled:
                warning('Consider using an ice secret to improve security')

            if cfg.glacier.enabled:
                #info('Connecting to Glacier2 server (%s:%d)', glacier_host, glacier_port)
                error('Glacier support not implemented yet')
                #TODO: Implement this

            info('Connecting to Ice server (%s:%d)', cfg.ice.host,
                 cfg.ice.port)
            base = ice.stringToProxy('Meta:tcp -h %s -p %d' %
                                     (cfg.ice.host, cfg.ice.port))
            self.meta = Murmur.MetaPrx.uncheckedCast(base)

            adapter = ice.createObjectAdapterWithEndpoints(
                'Callback.Client', 'tcp -h %s' % cfg.ice.host)
            adapter.activate()

            metacbprx = adapter.addWithUUID(metaCallback(self))
            self.metacb = Murmur.MetaCallbackPrx.uncheckedCast(metacbprx)

            authprx = adapter.addWithUUID(DjangoAuthenticator())
            self.auth = Murmur.ServerUpdatingAuthenticatorPrx.uncheckedCast(
                authprx)

            return self.attachCallbacks()

        def attachCallbacks(self, quiet=False):
            """
            Attaches all callbacks for meta and authenticators
            """

            # Ice.ConnectionRefusedException
            #debug('Attaching callbacks')
            try:
                if not quiet: info('Attaching meta callback')

                self.meta.addCallback(self.metacb)

                for server in self.meta.getBootedServers():
                    if not cfg.murmur.servers or server.id(
                    ) in cfg.murmur.servers:
                        if not quiet:
                            info('Setting authenticator for virtual server %d',
                                 server.id())
                        server.setAuthenticator(self.auth)

            except (Murmur.InvalidSecretException, Ice.UnknownUserException,
                    Ice.ConnectionRefusedException) as e:
                if isinstance(e, Ice.ConnectionRefusedException):
                    error('Server refused connection')
                elif isinstance(e, Murmur.InvalidSecretException) or \
                     isinstance(e, Ice.UnknownUserException) and (e.unknown == 'Murmur::InvalidSecretException'):
                    error('Invalid ice secret')
                else:
                    # We do not actually want to handle this one, re-raise it
                    raise e

                self.connected = False
                return False

            self.connected = True
            return True

        def checkConnection(self):
            """
            Tries reapplies all callbacks to make sure the authenticator
            survives server restarts and disconnects.
            """
            #debug('Watchdog run')

            try:
                if not self.attachCallbacks(quiet=not self.failedWatch):
                    self.failedWatch = True
                else:
                    self.failedWatch = False
            except Ice.Exception as e:
                error(
                    'Failed connection check, will retry in next watchdog run (%ds)',
                    cfg.ice.watchdog)
                debug(str(e))
                self.failedWatch = True

            # Renew the timer
            self.watchdog = Timer(cfg.ice.watchdog, self.checkConnection)
            self.watchdog.start()

    def checkSecret(func):
        """
        Decorator that checks whether the server transmitted the right secret
        if a secret is supposed to be used.
        """
        if not cfg.ice.secret:
            return func

        def newfunc(*args, **kws):
            if 'current' in kws:
                current = kws["current"]
            else:
                current = args[-1]

            if not current or 'secret' not in current.ctx or current.ctx[
                    'secret'] != cfg.ice.secret:
                error(
                    'Server transmitted invalid secret. Possible injection attempt.'
                )
                raise Murmur.InvalidSecretException()

            return func(*args, **kws)

        return newfunc

    def fortifyIceFu(retval=None, exceptions=(Ice.Exception, )):
        """
        Decorator that catches exceptions,logs them and returns a safe retval
        value. This helps preventing the authenticator getting stuck in
        critical code paths. Only exceptions that are instances of classes
        given in the exceptions list are not caught.
        
        The default is to catch all non-Ice exceptions.
        """
        def newdec(func):
            def newfunc(*args, **kws):
                try:
                    return func(*args, **kws)
                except Exception as e:
                    catch = True
                    for ex in exceptions:
                        if isinstance(e, ex):
                            catch = False
                            break

                    if catch:
                        critical('Unexpected exception caught')
                        exception(e)
                        return retval
                    raise

            return newfunc

        return newdec

    class metaCallback(Murmur.MetaCallback):
        def __init__(self, app):
            Murmur.MetaCallback.__init__(self)
            self.app = app

        @fortifyIceFu()
        @checkSecret
        def started(self, server, current=None):
            """
            This function is called when a virtual server is started
            and makes sure an authenticator gets attached if needed.
            """
            if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                info('Setting authenticator for virtual server %d',
                     server.id())
                try:
                    server.setAuthenticator(app.auth)
                # Apparently this server was restarted without us noticing
                except (Murmur.InvalidSecretException,
                        Ice.UnknownUserException) as e:
                    if hasattr(
                            e, "unknown"
                    ) and e.unknown != "Murmur::InvalidSecretException":
                        # Special handling for Murmur 1.2.2 servers with invalid slice files
                        raise e

                    error('Invalid ice secret')
                    return
            else:
                debug('Virtual server %d got started', server.id())

        @fortifyIceFu()
        @checkSecret
        def stopped(self, server, current=None):
            """
            This function is called when a virtual server is stopped
            """
            if self.app.connected:
                # Only try to output the server id if we think we are still connected to prevent
                # flooding of our thread pool
                try:
                    if not cfg.murmur.servers or server.id(
                    ) in cfg.murmur.servers:
                        info('Authenticated virtual server %d got stopped',
                             server.id())
                    else:
                        debug('Virtual server %d got stopped', server.id())
                    return
                except Ice.ConnectionRefusedException:
                    self.app.connected = False

            debug('Server shutdown stopped a virtual server')

    if cfg.user.reject_on_error:  # Python 2.4 compat
        authenticateFortifyResult = (-1, None, None)
    else:
        authenticateFortifyResult = (-2, None, None)

    class DjangoAuthenticator(Murmur.ServerUpdatingAuthenticator):
        texture_cache = {}

        def __init__(self):
            Murmur.ServerUpdatingAuthenticator.__init__(self)

        @fortifyIceFu(authenticateFortifyResult)
        @checkSecret
        def authenticate(self,
                         name,
                         pw,
                         certlist,
                         certhash,
                         strong,
                         current=None):
            """
            This function is called to authenticate a user
            """

            # Search for the user in the database
            FALL_THROUGH = -2
            AUTH_REFUSED = -1

            if name == 'SuperUser':
                debug('Forced fall through for SuperUser')
                return (FALL_THROUGH, None, None)

            try:
                sql = 'SELECT id, password, username FROM %s WHERE username = %%s' % cfg.database.users_table
                cur = threadDB.execute(sql, (name, ))
            except threadDbException:
                return (FALL_THROUGH, None, None)

            res = cur.fetchone()
            cur.close()
            if not res:
                info('Fall through for unknown user "%s"', name)
                return (FALL_THROUGH, None, None)

            uid, upw, unm = res
            if django_check_hash(pw, upw):
                # Authenticated

                # Commented out: fetch group memberships
                """
                try:
                    sql = 'SELECT group_name FROM %suser_group JOIN %sgroups USING (group_id) WHERE user_id = %%s' % (cfg.database.prefix, cfg.database.prefix)
                    cur = threadDB.execute(sql, (uid, ))
                except threadDbException:
                    return (FALL_THROUGH, None, None)
                
                res = cur.fetchall()
                cur.close()
                if res:
                    res = [a[0] for a in res]
                """
                res = []

                info('User authenticated: "%s" (%d)', name,
                     uid + cfg.user.id_offset)
                debug('Group memberships: %s', str(res))
                return (uid + cfg.user.id_offset, name, res)

            info('Failed authentication attempt for user: "******" (%d)', name,
                 uid + cfg.user.id_offset)
            return (AUTH_REFUSED, None, None)

        @fortifyIceFu((False, None))
        @checkSecret
        def getInfo(self, id, current=None):
            """
            Gets called to fetch user specific information
            """

            # We do not expose any additional information so always fall through
            debug('getInfo for %d -> denied', id)
            return (False, None)

        @fortifyIceFu(-2)
        @checkSecret
        def nameToId(self, name, current=None):
            """
            Gets called to get the id for a given username
            """

            FALL_THROUGH = -2
            if name == 'SuperUser':
                debug('nameToId SuperUser -> forced fall through')
                return FALL_THROUGH

            try:
                sql = 'SELECT id FROM %s WHERE username = %%s' % cfg.database.users_table
                cur = threadDB.execute(sql, (name, ))
            except threadDbException:
                return FALL_THROUGH

            res = cur.fetchone()
            cur.close()
            if not res:
                debug('nameToId %s -> ?', name)
                return FALL_THROUGH

            debug('nameToId %s -> %d', name, (res[0] + cfg.user.id_offset))
            return res[0] + cfg.user.id_offset

        @fortifyIceFu("")
        @checkSecret
        def idToName(self, id, current=None):
            """
            Gets called to get the username for a given id
            """

            FALL_THROUGH = ""
            # Make sure the ID is in our range and transform it to the actual Django user id
            if id < cfg.user.id_offset:
                return FALL_THROUGH
            bbid = id - cfg.user.id_offset

            # Fetch the user from the database
            try:
                sql = 'SELECT username FROM %s WHER id = %%s' % cfg.database.users_table
                cur = threadDB.execute(sql, (bbid, ))
            except threadDbException:
                return FALL_THROUGH

            res = cur.fetchone()
            cur.close()
            if res:
                if res[0] == 'SuperUser':
                    debug('idToName %d -> "SuperUser" catched')
                    return FALL_THROUGH

                debug('idToName %d -> "%s"', id, res[0])
                return res[0]

            debug('idToName %d -> ?', id)
            return FALL_THROUGH

        @fortifyIceFu("")
        @checkSecret
        def idToTexture(self, id, current=None):
            """
            Gets called to get the corresponding texture for a user
            """

            FALL_THROUGH = ""

            debug('idToTexture for %d', id)
            if id < cfg.user.id_offset or not cfg.user.avatar_enable:
                debug('idToTexture %d -> fall through', id)
                return FALL_THROUGH

            # FIXME: Implement avatars once we have them in mafiasi
            if cfg.user.avatar_enable:
                raise TypeError(
                    'You can not enable avatars in this hacked version')

            # Otherwise get the users texture from phpBB3
            bbid = id - cfg.user.id_offset
            try:
                sql = 'SELECT username, user_avatar, user_avatar_type FROM %susers WHERE (user_type = 0 OR user_type = 3) AND user_id = %%s' % cfg.database.prefix
                cur = threadDB.execute(sql, (bbid, ))
            except threadDbException:
                return FALL_THROUGH

            res = cur.fetchone()
            cur.close()
            if not res:
                debug('idToTexture %d -> user unknown, fall through', id)
                return FALL_THROUGH
            username, avatar_file, avatar_type = res
            if avatar_type != 1 and avatar_type != 2:
                debug(
                    'idToTexture %d -> no texture available for this user (%d), fall through',
                    id, avatar_type)
                return FALL_THROUGH

            if avatar_file in self.texture_cache:
                return self.texture_cache[avatar_file]

            if avatar_type == 1:
                url = cfg.user.avatar_path + avatar_file
            else:
                url = avatar_file

            try:
                handle = urllib.request.urlopen(url)
                file = handle.read()
                handle.close()
            except urllib.error.URLError as e:
                warning('Image download for "%s" (%d) failed: %s', url, id,
                        str(e))
                return FALL_THROUGH

            self.texture_cache[avatar_file] = file

            return self.texture_cache[avatar_file]

        @fortifyIceFu(-2)
        @checkSecret
        def registerUser(self, name, current=None):
            """
            Gets called when the server is asked to register a user.
            """

            FALL_THROUGH = -2
            debug('registerUser "%s" -> fall through', name)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def unregisterUser(self, id, current=None):
            """
            Gets called when the server is asked to unregister a user.
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to internal server database, we will not modify the phpbb3 database
            # but we can make murmur delete all additional information it got this way.
            debug('unregisterUser %d -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu({})
        @checkSecret
        def getRegisteredUsers(self, filter, current=None):
            """
            Returns a list of usernames in the Django database which contain
            filter as a substring.
            """

            if not filter:
                filter = '%'

            try:
                sql = 'SELECT id, username FROM %s WHERE username LIKE %%s' % cfg.database.users_table
                cur = threadDB.execute(sql, (filter, ))
            except threadDbException:
                return {}

            res = cur.fetchall()
            cur.close()
            if not res:
                debug('getRegisteredUsers -> empty list for filter "%s"',
                      filter)
                return {}
            debug('getRegisteredUsers -> %d results for filter "%s"', len(res),
                  filter)
            return dict([(a + cfg.user.id_offset, b) for a, b in res])

        @fortifyIceFu(-1)
        @checkSecret
        def setInfo(self, id, info, current=None):
            """
            Gets called when the server is supposed to save additional information
            about a user to his database
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to the internal server handler. We must not modify
            # the Django database so the additional information is stored in murmurs database
            debug('setInfo %d -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def setTexture(self, id, texture, current=None):
            """
            Gets called when the server is asked to update the user texture of a user
            """

            FAILED = 0
            FALL_THROUGH = -1

            if id < cfg.user.id_offset:
                debug('setTexture %d -> fall through', id)
                return FALL_THROUGH

            if cfg.user.avatar_enable:
                # Report a fail (0) as we will not update the avatar in the Django database.
                debug('setTexture %d -> failed', id)
                return FAILED

            # If we don't use textures from phpbb we let mumble save it
            debug('setTexture %d -> fall through', id)
            return FALL_THROUGH

    class CustomLogger(Ice.Logger):
        """
        Logger implementation to pipe Ice log messages into
        out own log
        """
        def __init__(self):
            Ice.Logger.__init__(self)
            self._log = getLogger('Ice')

        def _print(self, message):
            self._log.info(message)

        def trace(self, category, message):
            self._log.debug('Trace %s: %s', category, message)

        def warning(self, message):
            self._log.warning(message)

        def error(self, message):
            self._log.error(message)

    #
    #--- Start of authenticator
    #
    info('Starting Django mumble authenticator')
    initdata = Ice.InitializationData()
    initdata.properties = Ice.createProperties([], initdata.properties)
    for prop, val in cfg.iceraw:
        initdata.properties.setProperty(prop, val)

    initdata.properties.setProperty('Ice.ImplicitContext', 'Shared')
    initdata.logger = CustomLogger()

    app = DjangoAuthenticatorApp()
    state = app.main(sys.argv[:1], initData=initdata)
    info('Shutdown complete')
コード例 #30
0
#coding: utf-8

import filelock
import numpy as np
from ..utils import logger
from .base import AgentBase
from .simulator.gym_torcs import TorcsEnv
import Ice, os, sys
Ice.loadSlice("-I" + Ice.getSliceDir() + " --all " + os.path.dirname(__file__) + "/race.ice")
sys.path.append(os.path.dirname(__file__) + "/slice")
Ice.updateModules()
import Race

class _TorcsBot(object):
    def __init__(self, name, idx, agent):
        self._name = name
        self._idx = idx
        self._agent = agent     # type: AgentTorcs2
        self._init()

    def _init(self):
        self._cur_status = None
        self._cur_driveInfo = Race.DriveInfo()
        self._cur_driveInfo.ident = self._idx
        self._isHookBot = not self._name.startswith("scr_server")
        self._prev_rpm = None
        self._reward = 0.
        self._isOver = False
        self._hist_status = []
        self._hist_actions = []
        self._cur_laps = 0
コード例 #31
0
#!/usr/bin/python
# -*- mode:python; coding:utf-8; tab-width:4 -*-

import sys

import Ice

Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
import Cannon

Ice.loadSlice('-I %s container.ice' % Ice.getSliceDir())
import Services

from matrix_utils import matrix_multiply, matrix_add


class ProcessorI(Cannon.Processor):
    row = None
    col = None
    above = None
    left = None
    order = None
    target = None
    current_step = None
    result_parcial = None
    A_blocks = []
    B_blocks = []

    def init(self, row, col, above, left, order, target, current=None):
        self.row = row
        self.col = col
コード例 #32
0
ファイル: TestHelper.py プロジェクト: zk2013/ice
 def loadSlice(self, args):
     sliceDir = Ice.getSliceDir()
     if not sliceDir:
         print(sys.argv[0] + ': Slice directory not found.')
         sys.exit(1)
     Ice.loadSlice("'-I{0}' {1}".format(sliceDir, args))
コード例 #33
0
# -*- mode:python; coding:utf-8; tab-width:4 -*-

import itertools
import math

import Ice
Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
import Cannon


def matrix_multiply(A, B):
    order = A.ncols
    C = Cannon.Matrix(order, [])

    for row in range(0, order):
        for col in range(0, order):
            result = 0
            for i in range(0, order):
                result += A.data[row*order+i] * B.data[i*order+col]
            C.data.append(result)

    return C


def matrix_add(A, B):
    order = A.ncols
    C = Cannon.Matrix(order, [])

    for pos in range(0, order**2):
            C.data.append(A.data[pos] + B.data[pos])
コード例 #34
0
#!/usr/bin/python -u
# -*- coding:utf-8; tab-width:4; mode:python -*-

import sys
import Ice
Ice.loadSlice('-I {} container.ice'.format(Ice.getSliceDir()))
import Services


class ContainerI(Services.Container):
    def __init__(self):
        self.proxies = {}

    def link(self, key, proxy, current=None):
        if key in self.proxies:
            raise Services.AlreadyExists(key)

        self.proxies[key] = proxy

        print("{} ha sido agregado".format(key))

    def unlink(self, key, current=None):
        if not key in self.proxies:
            raise Services.NoSuchKey(key)

        del self.proxies[key]

        print("{} ha sido eliminado".format(key))

    def list(self, current=None):
        return self.proxies
コード例 #35
0
ファイル: Server.py プロジェクト: arco-group/ice-hello
#!/usr/bin/python3 -u
# -*- coding: utf-8; mode: python; -*-

import sys
import Ice

Ice.loadSlice('-I{} BidirAdapter.ice'.format(Ice.getSliceDir()))
import Utils


class MessageForwarder(Ice.Blobject):
    def __init__(self, peer, adapter):
        self.peer = peer
        self.adapter = adapter

    def ice_invoke(self, in_params, current):
        try:
            print(" - forward to '{}'".format(self.peer.ice_getIdentity().name))
            return self.peer.ice_invoke(
                current.operation, current.mode, in_params, current.ctx)
        except Ice.Exception as e:
            msg = "  : ERROR: "
            msg += "> " + str(e).replace("\n", "\n" + " " * len(msg) + "> ")
            print(msg)

            self.discard()
            return True, bytes()

    def discard(self):
        oid = self.peer.ice_getIdentity()
        print("  : discarding proxy: {}...".format(oid.name))
コード例 #36
0
ファイル: processor.py プロジェクト: fernandogualo/cannon
#!/usr/bin/python
# -*- mode:python; coding:utf-8; tab-width:4 -*-

import sys
import Ice
Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
Ice.loadSlice('-I %s container.ice' % Ice.getSliceDir())
import Services
import Cannon
from matrix_utils import matrix_multiply,matrix_add


class ProcessorI(Cannon.Processor):
    def init(self, index, order, above, left, target, current=None):
        self.resultado=None
		self.step_aux=0
        self.index=index
        self.order=order
        self.above=above
        self.left=left
        self.target=target
        self.matrixA={}
        self.matrixB={}               

    def injectA(self, A, step, current=None):
        self.matrixA[step]=A       
        if self.matrixB.has_key(step):
			self.matrix_check(step)
       
    def injectB(self, B, step, current=None):
        self.matrixB[step]=B        
コード例 #37
0
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Ruben Perez <*****@*****.**>

import sys, traceback, Ice, IceGrid
import time, datetime
import threading
import pdb
#from processingChain import processingChainController
#from AyC import catalog
import MySQLdb as mdb
from collections import deque
#Ice.loadSlice('-I {} Geocloud.ice'.format(Ice.getSliceDir()))
Ice.loadSlice('-I' + Ice.getSliceDir() + ' Geocloud.ice')
import geocloud


class OrchestratorI(geocloud.Orchestrator):
    proxies_pp = []
    busy_proxies_pp = dict()
    stages_pp = dict()
    pending = []
    processing = []
    for_cataloguing = []

    def __init__(self, com):
        if not com:
            raise RuntimeError("Not communicator")
        self.com = com
コード例 #38
0
#!/usr/bin/env python

import re
import sys
import time
import ConfigParser
import json
from operator import itemgetter, attrgetter, methodcaller

import Ice
#Ice.loadSlice('-I/usr/share/Ice-3.5.1/slice/ /usr/share/slice/Murmur.ice')
Ice.loadSlice(b'', [b'-I' + (Ice.getSliceDir() or b'/usr/local/share/Ice-3.5/slice/'), b'Murmur.ice'])

import Murmur
from Murmur import Ban

# -------------------------------------------------------------------------------

cfg = 'mumble-sso-core-admin.ini'
#print('Reading config file: {0}').format(cfg)
config = ConfigParser.RawConfigParser()
config.read(cfg)

server_id = config.getint('murmur', 'server_id')
ice_host = config.get('murmur', 'ice_host')
ice_port = config.get('murmur', 'ice_port')
ice_secret = config.get('murmur', 'ice_secret')

# -------------------------------------------------------------------------------

pok = None
コード例 #39
0
ファイル: PyUpManager.py プロジェクト: Gonlo2/PyUpManager
#from modules.db.DBActionManager import DBActionManager
from modules.control.ControlProxy import ControlProxy
from modules.formatter.TerminalFormatter import TerminalFormatter
from modules.formatter.FormatInfo import FormatInfo
from modules.formatter.FormatAccounts import FormatAccounts
from modules.config.ConfigManager import ConfigManager
import sys
import logging
import argparse
import signal
import os
from modules.control.ControlServerAdapter import ServerFrontend
import getpass

import Ice
Ice.loadSlice('-I {} pyupmanager.ice'.format(Ice.getSliceDir()))

import PyUpManager

logging.basicConfig(level=logging.DEBUG)

class Client(Ice.Application):
    def run(self, argv):
        logger = logging.getLogger( __name__ )

        frontend_processor = self.communicator().stringToProxy( self._proxy_name )
        frontend = PyUpManager.FrontendPrx.checkedCast( frontend_processor )

        if not frontend:
            logger.error( "No se ha podido conectar al frontend del proxy '%s'", frontend_processor )
            raise RuntimeError('Invalid frontend proxy')
コード例 #40
0
ファイル: testcallback.py プロジェクト: arrai/mumble-record
#!/usr/bin/env python
# -*- coding: utf-8
import Ice, sys, sha
from M2Crypto import X509

Ice.loadSlice("", ["-I" + Ice.getSliceDir(), "Murmur.ice"])
import Murmur


class MetaCallbackI(Murmur.MetaCallback):
    def started(self, s, current=None):
        print "started"
        serverR = Murmur.ServerCallbackPrx.uncheckedCast(adapter.addWithUUID(ServerCallbackI(server, current.adapter)))
        s.addCallback(serverR)

    def stopped(self, s, current=None):
        print "stopped"


class ServerCallbackI(Murmur.ServerCallback):
    def __init__(self, server, adapter):
        self.server = server
        self.contextR = Murmur.ServerContextCallbackPrx.uncheckedCast(
            adapter.addWithUUID(ServerContextCallbackI(server))
        )

    def userConnected(self, p, current=None):
        print "connected"
        print p
        self.server.addContextCallback(
            p.session, "flubber", "Power up the T", self.contextR, Murmur.ContextChannel | Murmur.ContextUser
コード例 #41
0
#!/usr/bin/python -u
# -*- coding:utf-8; tab-width:4; mode:python -*-

import sys
import Ice
Ice.loadSlice('-I %s container.ice' % Ice.getSliceDir())
import Services


class ContainerI(Services.Container):
    def __init__(self):
        self.proxies = {}

    def link(self, key, proxy, current=None):
        if key in self.proxies:
            raise Services.AlreadyExists(key)

        print("link: {0} -> {1}".format(key, proxy))
        self.proxies[key] = proxy

    def unlink(self, key, current=None):
        if not key in self.proxies:
            raise Services.NoSuchKey(key)

        print("unlink: {0}".format(key))
        del self.proxies[key]

    def list(self, current=None):
        return self.proxies

コード例 #42
0
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
#
# **********************************************************************

import sys, traceback, Ice, threading

slice_dir = Ice.getSliceDir()
if not slice_dir:
    print(sys.argv[0] + ': Slice directory not found.')
    sys.exit(1)

Ice.loadSlice("'-I" + slice_dir + "' Props.ice")
import Demo

class PropsI(Demo.Props, Ice.PropertiesAdminUpdateCallback):
    def __init__(self):
        self.called = False
        self.m = threading.Condition()

    def getChanges(self, current = None):
        self.m.acquire()
        try:
            #
            # Make sure that we have received the property updates before we
            # return the results.
            #
            while not self.called:
                self.m.wait()
コード例 #43
0
ファイル: cockpit.py プロジェクト: robomakery/a20
#!/usr/bin/env python3

import sys, platform
import pygame
from pygame.locals import *

import Ice, IceStorm

Ice.loadSlice('--all -I' + Ice.getSliceDir() + ' -I../interfaces/' + ' ../interfaces/motorcontrol.ice')
Ice.loadSlice('--all -I' + Ice.getSliceDir() + ' -I../interfaces/' + ' ../interfaces/sensor.ice')
Ice.updateModules()
import Sensor

FPS = 30 # frames per second to update the screen
window_dim = (1024, 768) # default width and height of the program's window

# Known sensor names
#sensor_type = {
#    Sensor.text : 'TEXT',
#    Sensor.range : 'RANGE',
#    Sensor.bearing : 'BEARING',
#    Sensor.altitude : 'ALTITUDE',
#    Sensor.longitude : 'LONGITUDE',
#    Sensor.lattitude : 'LATTITUDE',
#    Sensor.temperature : 'TEMPERATURE',
#    Sensor.pressure : 'PRESURE',
#    Sensor.roll : 'ROLL',
#    Sensor.pitch : 'PITCH',
#    Sensor.yaw : 'YAW',
#    Sensor.speed : 'SPEED',
#    Sensor.accelx : 'ACCELX',
コード例 #44
0
# -*- mode:python; coding:utf-8; tab-width:4 -*-

from unittest import TestCase

from hamcrest import assert_that, anything
from doublex import Spy, called

import Ice
Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir()))
import Cannon

from frontend import FrontendI

from common import M1, M2, M4


class FrontendServantTests(TestCase):
    """
    These are NOT remote tests. We directly instantiate servants here.
    """
    def test_processor_init_2x2_operands_in_2x2_processors(self):
        # given
        nprocs = 4
        procs = [Spy(Cannon.Processor) for i in range(nprocs)]
        frontend = FrontendI(procs)

        # when
        frontend.init_processors()

        # then
        assert_that(procs[0].init,
コード例 #45
0
def do_main_program():
    #
    # --- Authenticator implementation
    #    All of this has to go in here so we can correctly daemonize the tool
    #    without loosing the file descriptors opened by the Ice module
    slicedir = Ice.getSliceDir()
    if not slicedir:
        slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
    else:
        slicedir = ['-I' + slicedir]
    Ice.loadSlice('', slicedir + [cfg.ice.slice])
    import Murmur

    class allianceauthauthenticatorApp(Ice.Application):
        def run(self, args):
            self.shutdownOnInterrupt()

            if not self.initializeIceConnection():
                return 1

            if cfg.ice.watchdog > 0:
                self.failedWatch = True
                self.checkConnection()

            # Serve till we are stopped
            self.communicator().waitForShutdown()
            self.watchdog.cancel()

            if self.interrupted():
                warning('Caught interrupt, shutting down')

            threadDB.disconnect()
            return 0

        def initializeIceConnection(self):
            """
            Establishes the two-way Ice connection and adds the authenticator to the
            configured servers
            """
            ice = self.communicator()

            if cfg.ice.secret:
                debug('Using shared ice secret')
                ice.getImplicitContext().put("secret", cfg.ice.secret)
            elif not cfg.glacier.enabled:
                warning('Consider using an ice secret to improve security')

            if cfg.glacier.enabled:
                # info('Connecting to Glacier2 server (%s:%d)', glacier_host, glacier_port)
                error('Glacier support not implemented yet')
                # TODO: Implement this

            info('Connecting to Ice server (%s:%d)', cfg.ice.host, cfg.ice.port)
            base = ice.stringToProxy('Meta:tcp -h %s -p %d' % (cfg.ice.host, cfg.ice.port))
            self.meta = Murmur.MetaPrx.uncheckedCast(base)

            adapter = ice.createObjectAdapterWithEndpoints('Callback.Client', 'tcp -h %s' % cfg.ice.host)
            adapter.activate()

            metacbprx = adapter.addWithUUID(metaCallback(self))
            self.metacb = Murmur.MetaCallbackPrx.uncheckedCast(metacbprx)

            authprx = adapter.addWithUUID(allianceauthauthenticator())
            self.auth = Murmur.ServerUpdatingAuthenticatorPrx.uncheckedCast(authprx)

            return self.attachCallbacks()

        def attachCallbacks(self, quiet=False):
            """
            Attaches all callbacks for meta and authenticators
            """

            # Ice.ConnectionRefusedException
            # debug('Attaching callbacks')
            try:
                if not quiet: info('Attaching meta callback')

                self.meta.addCallback(self.metacb)

                for server in self.meta.getBootedServers():
                    if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                        if not quiet: info('Setting authenticator for virtual server %d', server.id())
                        server.setAuthenticator(self.auth)

            except (Murmur.InvalidSecretException, Ice.UnknownUserException, Ice.ConnectionRefusedException) as e:
                if isinstance(e, Ice.ConnectionRefusedException):
                    error('Server refused connection')
                elif isinstance(e, Murmur.InvalidSecretException) or \
                                isinstance(e, Ice.UnknownUserException) and (
                                    e.unknown == 'Murmur::InvalidSecretException'):
                    error('Invalid ice secret')
                else:
                    # We do not actually want to handle this one, re-raise it
                    raise e

                self.connected = False
                return False

            self.connected = True
            return True

        def checkConnection(self):
            """
            Tries reapplies all callbacks to make sure the authenticator
            survives server restarts and disconnects.
            """
            # debug('Watchdog run')

            try:
                if not self.attachCallbacks(quiet=not self.failedWatch):
                    self.failedWatch = True
                else:
                    self.failedWatch = False
            except Ice.Exception as e:
                error('Failed connection check, will retry in next watchdog run (%ds)', cfg.ice.watchdog)
                debug(str(e))
                self.failedWatch = True

            # Renew the timer
            self.watchdog = Timer(cfg.ice.watchdog, self.checkConnection)
            self.watchdog.start()

    def checkSecret(func):
        """
        Decorator that checks whether the server transmitted the right secret
        if a secret is supposed to be used.
        """
        if not cfg.ice.secret:
            return func

        def newfunc(*args, **kws):
            if 'current' in kws:
                current = kws["current"]
            else:
                current = args[-1]

            if not current or 'secret' not in current.ctx or current.ctx['secret'] != cfg.ice.secret:
                error('Server transmitted invalid secret. Possible injection attempt.')
                raise Murmur.InvalidSecretException()

            return func(*args, **kws)

        return newfunc

    def fortifyIceFu(retval=None, exceptions=(Ice.Exception,)):
        """
        Decorator that catches exceptions,logs them and returns a safe retval
        value. This helps preventing the authenticator getting stuck in
        critical code paths. Only exceptions that are instances of classes
        given in the exceptions list are not caught.
        
        The default is to catch all non-Ice exceptions.
        """

        def newdec(func):
            def newfunc(*args, **kws):
                try:
                    return func(*args, **kws)
                except Exception as e:
                    catch = True
                    for ex in exceptions:
                        if isinstance(e, ex):
                            catch = False
                            break

                    if catch:
                        critical('Unexpected exception caught')
                        exception(e)
                        return retval
                    raise

            return newfunc

        return newdec

    class metaCallback(Murmur.MetaCallback):
        def __init__(self, app):
            Murmur.MetaCallback.__init__(self)
            self.app = app

        @fortifyIceFu()
        @checkSecret
        def started(self, server, current=None):
            """
            This function is called when a virtual server is started
            and makes sure an authenticator gets attached if needed.
            """
            if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                info('Setting authenticator for virtual server %d', server.id())
                try:
                    server.setAuthenticator(app.auth)
                # Apparently this server was restarted without us noticing
                except (Murmur.InvalidSecretException, Ice.UnknownUserException) as e:
                    if hasattr(e, "unknown") and e.unknown != "Murmur::InvalidSecretException":
                        # Special handling for Murmur 1.2.2 servers with invalid slice files
                        raise e

                    error('Invalid ice secret')
                    return
            else:
                debug('Virtual server %d got started', server.id())

        @fortifyIceFu()
        @checkSecret
        def stopped(self, server, current=None):
            """
            This function is called when a virtual server is stopped
            """
            if self.app.connected:
                # Only try to output the server id if we think we are still connected to prevent
                # flooding of our thread pool
                try:
                    if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                        info('Authenticated virtual server %d got stopped', server.id())
                    else:
                        debug('Virtual server %d got stopped', server.id())
                    return
                except Ice.ConnectionRefusedException:
                    self.app.connected = False

            debug('Server shutdown stopped a virtual server')

    if cfg.user.reject_on_error:  # Python 2.4 compat
        authenticateFortifyResult = (-1, None, None)
    else:
        authenticateFortifyResult = (-2, None, None)

    class allianceauthauthenticator(Murmur.ServerUpdatingAuthenticator):
        texture_cache = {}

        def __init__(self):
            Murmur.ServerUpdatingAuthenticator.__init__(self)

        @fortifyIceFu(authenticateFortifyResult)
        @checkSecret
        def authenticate(self, name, pw, certlist, certhash, strong, current=None):
            """
            This function is called to authenticate a user
            """

            # Search for the user in the database
            FALL_THROUGH = -2
            AUTH_REFUSED = -1

            if name == 'SuperUser':
                debug('Forced fall through for SuperUser')
                return (FALL_THROUGH, None, None)

            try:
                sql = 'SELECT id, pwhash, groups FROM %sservices_mumbleuser WHERE username = %%s' % cfg.database.prefix
                cur = threadDB.execute(sql, [name])
            except threadDbException:
                return (FALL_THROUGH, None, None)

            res = cur.fetchone()
            cur.close()
            if not res:
                info('Fall through for unknown user "%s"', name)
                return (FALL_THROUGH, None, None)

            uid, upwhash, ugroups = res

            if ugroups:
                groups = ugroups.split(',')
            else:
                groups = []

            if allianceauth_check_hash(pw, upwhash):
                info('User authenticated: "%s" (%d)', name, uid + cfg.user.id_offset)
                debug('Group memberships: %s', str(groups))
                return (uid + cfg.user.id_offset, entity_decode(name), groups)

            info('Failed authentication attempt for user: "******" (%d)', name, uid + cfg.user.id_offset)
            return (AUTH_REFUSED, None, None)

        @fortifyIceFu((False, None))
        @checkSecret
        def getInfo(self, id, current=None):
            """
            Gets called to fetch user specific information
            """

            # We do not expose any additional information so always fall through
            debug('getInfo for %d -> denied', id)
            return (False, None)

        @fortifyIceFu(-2)
        @checkSecret
        def nameToId(self, name, current=None):
            """
            Gets called to get the id for a given username
            """

            FALL_THROUGH = -2
            if name == 'SuperUser':
                debug('nameToId SuperUser -> forced fall through')
                return FALL_THROUGH

            try:
                sql = 'SELECT id FROM %sservices_mumbleuser WHERE username = %%s' % cfg.database.prefix
                cur = threadDB.execute(sql, [name])
            except threadDbException:
                return FALL_THROUGH

            res = cur.fetchone()
            cur.close()
            if not res:
                debug('nameToId %s -> ?', name)
                return FALL_THROUGH

            debug('nameToId %s -> %d', name, (res[0] + cfg.user.id_offset))
            return res[0] + cfg.user.id_offset

        @fortifyIceFu("")
        @checkSecret
        def idToName(self, id, current=None):
            """
            Gets called to get the username for a given id
            """

            FALL_THROUGH = ""
            # Make sure the ID is in our range and transform it to the actual smf user id
            if id < cfg.user.id_offset:
                return FALL_THROUGH
            bbid = id - cfg.user.id_offset

            # Fetch the user from the database
            try:
                sql = 'SELECT username FROM %sservices_mumbleuser WHERE id = %%s' % cfg.database.prefix
                cur = threadDB.execute(sql, [bbid])
            except threadDbException:
                return FALL_THROUGH

            res = cur.fetchone()
            cur.close()
            if res:
                if res[0] == 'SuperUser':
                    debug('idToName %d -> "SuperUser" catched')
                    return FALL_THROUGH

                debug('idToName %d -> "%s"', id, res[0])
                return res[0]

            debug('idToName %d -> ?', id)
            return FALL_THROUGH

        @fortifyIceFu("")
        @checkSecret
        def idToTexture(self, id, current=None):
            """
            Gets called to get the corresponding texture for a user
            """

            FALL_THROUGH = ""

            debug('idToTexture "%s" -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu(-2)
        @checkSecret
        def registerUser(self, name, current=None):
            """
            Gets called when the server is asked to register a user.
            """

            FALL_THROUGH = -2
            debug('registerUser "%s" -> fall through', name)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def unregisterUser(self, id, current=None):
            """
            Gets called when the server is asked to unregister a user.
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to internal server database, we will not modify the smf database
            # but we can make murmur delete all additional information it got this way.
            debug('unregisterUser %d -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu({})
        @checkSecret
        def getRegisteredUsers(self, filter, current=None):
            """
            Returns a list of usernames in the AllianceAuth database which contain
            filter as a substring.
            """

            if not filter:
                filter = '%'

            try:
                sql = 'SELECT id, username FROM %sservices_mumbleuser WHERE username LIKE %%s' % cfg.database.prefix
                cur = threadDB.execute(sql, [filter])
            except threadDbException:
                return {}

            res = cur.fetchall()
            cur.close()
            if not res:
                debug('getRegisteredUsers -> empty list for filter "%s"', filter)
                return {}
            debug('getRegisteredUsers -> %d results for filter "%s"', len(res), filter)
            return dict([(a + cfg.user.id_offset, b) for a, b in res])

        @fortifyIceFu(-1)
        @checkSecret
        def setInfo(self, id, info, current=None):
            """
            Gets called when the server is supposed to save additional information
            about a user to his database
            """

            FALL_THROUGH = -1
            # Return -1 to fall through to the internal server handler. We must not modify
            # the smf database so the additional information is stored in murmurs database
            debug('setInfo %d -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def setTexture(self, id, texture, current=None):
            """
            Gets called when the server is asked to update the user texture of a user
            """

            FALL_THROUGH = -1

            debug('setTexture %d -> fall through', id)
            return FALL_THROUGH

    class CustomLogger(Ice.Logger):
        """
        Logger implementation to pipe Ice log messages into
        our own log
        """

        def __init__(self):
            Ice.Logger.__init__(self)
            self._log = getLogger('Ice')

        def _print(self, message):
            self._log.info(message)

        def trace(self, category, message):
            self._log.debug('Trace %s: %s', category, message)

        def warning(self, message):
            self._log.warning(message)

        def error(self, message):
            self._log.error(message)

    #
    # --- Start of authenticator
    #
    info('Starting AllianceAuth mumble authenticator')
    initdata = Ice.InitializationData()
    initdata.properties = Ice.createProperties([], initdata.properties)
    for prop, val in cfg.iceraw:
        initdata.properties.setProperty(prop, val)

    initdata.properties.setProperty('Ice.ImplicitContext', 'Shared')
    initdata.properties.setProperty('Ice.Default.EncodingVersion', '1.0')
    initdata.logger = CustomLogger()

    app = allianceauthauthenticatorApp()
    state = app.main(sys.argv[:1], initData=initdata)
    info('Shutdown complete')
コード例 #46
0
ファイル: mice.py プロジェクト: alysisLeonis/juju-charms
props.setProperty("Ice.ImplicitContext", "Shared")
idata = Ice.InitializationData()
idata.properties = props

ice = Ice.initialize(idata)
prx = ice.stringToProxy(prxstr)

try:
    print "Trying to retrieve slice dynamically from server...",
    slice = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (), IcePy._t_string, ()).invoke(prx, ((), None))

    (dynslicefiledesc, dynslicefilepath)  = tempfile.mkstemp(suffix = '.ice')
    dynslicefile = os.fdopen(dynslicefiledesc, 'w')
    dynslicefile.write(slice)
    dynslicefile.flush()
    Ice.loadSlice('', ['-I' + Ice.getSliceDir(), dynslicefilepath])
    dynslicefile.close()
    os.remove(dynslicefilepath)
    print "Success"
except Exception, e:
    print "Failed"
    print str(e)
    while not os.path.exists(slicefile):
         slicefile = raw_input("Path to slicefile: ")
    print "Load slice (%s)..." % slicefile,
    Ice.loadSlice('', ['-I' + Ice.getSliceDir(), slicefile])
    print "Done"

print "Import dynamically compiled murmur class...",
import Murmur
print "Establish ice connection...",
コード例 #47
0
ファイル: imapauth.py プロジェクト: dadosch/mumble_auth_imap
def do_main_program():
    #
    #--- Authenticator implementation
    #    All of this has to go in here so we can correctly daemonize the tool
    #    without loosing the file descriptors opened by the Ice module
    slicedir = Ice.getSliceDir()
    # I had to hardcode this in a newer install. Might be different for you
    slicedir = "-I/usr/share/ice/slice /usr/share/slice/"
    Ice.loadSlice(slicedir +  cfg.ice.slice)
    import Murmur
    
    class imapauthenticatorApp(Ice.Application):
        def run(self, args):
            self.shutdownOnInterrupt()
            
            if not self.initializeIceConnection():
                return 1

            if cfg.ice.watchdog > 0:
                self.failedWatch = True
                self.checkConnection()
                
            # Serve till we are stopped
            self.communicator().waitForShutdown()
            self.watchdog.cancel()
            
            if self.interrupted():
                warning('Caught interrupt, shutting down')
                
            return 0
        
        def initializeIceConnection(self):
            """
            Establishes the two-way Ice connection and adds the authenticator to the
            configured servers
            """
            ice = self.communicator()
            
            if cfg.ice.secret:
                debug('Using shared ice secret')
                ice.getImplicitContext().put("secret", cfg.ice.secret)
                
            info('Connecting to Ice server (%s:%d)', cfg.ice.host, cfg.ice.port)
            base = ice.stringToProxy('Meta:tcp -h %s -p %d' % (cfg.ice.host, cfg.ice.port))
            self.meta = Murmur.MetaPrx.uncheckedCast(base)
        
            adapter = ice.createObjectAdapterWithEndpoints('Callback.Client', 'tcp -h %s' % cfg.ice.host)
            adapter.activate()
            
            metacbprx = adapter.addWithUUID(metaCallback(self))
            self.metacb = Murmur.MetaCallbackPrx.uncheckedCast(metacbprx)
            
            authprx = adapter.addWithUUID(imapauthenticator())
            self.auth = Murmur.ServerUpdatingAuthenticatorPrx.uncheckedCast(authprx)
            
            return self.attachCallbacks()
        
        def attachCallbacks(self, quiet = False):
            """
            Attaches all callbacks for meta and authenticators
            """
            
            # Ice.ConnectionRefusedException
            #debug('Attaching callbacks')
            try:
                if not quiet: info('Attaching meta callback')

                self.meta.addCallback(self.metacb)
                
                for server in self.meta.getBootedServers():
                    if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                        if not quiet: info('Setting authenticator for virtual server %d', server.id())
                        server.setAuthenticator(self.auth)
                        
            except (Murmur.InvalidSecretException, Ice.UnknownUserException, Ice.ConnectionRefusedException) as e:
                if isinstance(e, Ice.ConnectionRefusedException):
                    error('Server refused connection')
                elif isinstance(e, Murmur.InvalidSecretException) or \
                     isinstance(e, Ice.UnknownUserException) and (e.unknown == 'Murmur::InvalidSecretException'):
                    error('Invalid ice secret')
                else:
                    # We do not actually want to handle this one, re-raise it
                    raise e
                
                self.connected = False
                return False

            self.connected = True
            return True
        
        def checkConnection(self):
            """
            Tries reapplies all callbacks to make sure the authenticator
            survives server restarts and disconnects.
            """
            #debug('Watchdog run')

            try:
                if not self.attachCallbacks(quiet = not self.failedWatch):
                    self.failedWatch = True
                else:
                    self.failedWatch = False
            except Ice.Exception as e:
                error('Failed connection check, will retry in next watchdog run (%ds)', cfg.ice.watchdog)
                debug(str(e))
                self.failedWatch = True

            # Renew the timer
            self.watchdog = Timer(cfg.ice.watchdog, self.checkConnection)
            self.watchdog.start()
        
    def checkSecret(func):
        """
        Decorator that checks whether the server transmitted the right secret
        if a secret is supposed to be used.
        """
        if not cfg.ice.secret:
            return func
        
        def newfunc(*args, **kws):
            if 'current' in kws:
                current = kws["current"]
            else:
                current = args[-1]
            
            if not current or 'secret' not in current.ctx or current.ctx['secret'] != cfg.ice.secret:
                error('Server transmitted invalid secret. Possible injection attempt.')
                raise Murmur.InvalidSecretException()
            
            return func(*args, **kws)
        
        return newfunc

    def fortifyIceFu(retval = None, exceptions = (Ice.Exception,)):
        """
        Decorator that catches exceptions,logs them and returns a safe retval
        value. This helps preventing the authenticator getting stuck in
        critical code paths. Only exceptions that are instances of classes
        given in the exceptions list are not caught.
        
        The default is to catch all non-Ice exceptions.
        """
        def newdec(func):
            def newfunc(*args, **kws):
                try:
                    return func(*args, **kws)
                except Exception as e:
                    catch = True
                    for ex in exceptions:
                        if isinstance(e, ex):
                            catch = False
                            break

                    if catch:
                        critical('Unexpected exception caught')
                        exception(e)
                        return retval
                    raise

            return newfunc
        return newdec
                
    class metaCallback(Murmur.MetaCallback):
        def __init__(self, app):
            Murmur.MetaCallback.__init__(self)
            self.app = app

        @fortifyIceFu()
        @checkSecret
        def started(self, server, current = None):
            """
            This function is called when a virtual server is started
            and makes sure an authenticator gets attached if needed.
            """
            if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                info('Setting authenticator for virtual server %d', server.id())
                try:
                    server.setAuthenticator(app.auth)
                # Apparently this server was restarted without us noticing
                except (Murmur.InvalidSecretException, Ice.UnknownUserException) as e:
                    if hasattr(e, "unknown") and e.unknown != "Murmur::InvalidSecretException":
                        # Special handling for Murmur 1.2.2 servers with invalid slice files
                        raise e
                    
                    error('Invalid ice secret')
                    return
            else:
                debug('Virtual server %d got started', server.id())

        @fortifyIceFu()
        @checkSecret
        def stopped(self, server, current = None):
            """
            This function is called when a virtual server is stopped
            """
            if self.app.connected:
                # Only try to output the server id if we think we are still connected to prevent
                # flooding of our thread pool
                try:
                    if not cfg.murmur.servers or server.id() in cfg.murmur.servers:
                        info('Authenticated virtual server %d got stopped', server.id())
                    else:
                        debug('Virtual server %d got stopped', server.id())
                    return
                except Ice.ConnectionRefusedException:
                    self.app.connected = False
            
            debug('Server shutdown stopped a virtual server')
    
    authenticateFortifyResult = (-2, None, None)
        
    class imapauthenticator(Murmur.ServerUpdatingAuthenticator):
        texture_cache = {}
        def __init__(self):
            Murmur.ServerUpdatingAuthenticator.__init__(self)

        @fortifyIceFu(authenticateFortifyResult)
        @checkSecret
        def authenticate(self, name, pw, certlist, certhash, strong, current = None):
            """
            This function is called to authenticate a user
            """
            
            # Search for the user in the database
            FALL_THROUGH = -2
            AUTH_REFUSED = -1
            
            if name == 'SuperUser':
                debug('Forced fall through for SuperUser')
                return (FALL_THROUGH, None, None)
            

            try:
                with IMAPClient(host=cfg.imap.host, ssl_context=ssl_context) as client:
                    client.login(name, pw)
            except IMAPClient.Error as e:
                info('Fall through for unknown user "%s" or connection problem', name)
                return (AUTH_REFUSED, None, None)
            
            # As IMAP hasn't got such thing as a USERID, we use the given name to calculate a hash 
	    # TODO this might be highly insecure when two mails have coindently the same hash (note that we are cutting the integer off as otherwise we would get an error from mumble)
            uid = hashString(name)
            info('User authenticated: "%s", UID: %s', name, str(uid))
            return (uid, name, [])

            
        @fortifyIceFu((False, None))
        @checkSecret
        def getInfo(self, id, current = None):
            """
            Gets called to fetch user specific information
            """
            
            # We do not expose any additional information so always fall through
            debug('getInfo for %d -> denied', id)
            return (False, None)

        @fortifyIceFu(-2)
        @checkSecret
        def nameToId(self, name, current = None):
            """
            Gets called to get the id for a given username
            """
            
            FALL_THROUGH = -2
            if name == 'SuperUser':
                debug('nameToId SuperUser -> forced fall through')
                return FALL_THROUGH
            
            # There is no such thing in IMAP
            return hashString(name)
        
        @fortifyIceFu("")
        @checkSecret
        def idToName(self, id, current = None):
            """
            Gets called to get the username for a given id
            """
            
            FALL_THROUGH = ""
            
            # There is no such thing in IMAP
            return FALL_THROUGH
            
        @fortifyIceFu("")
        @checkSecret
        def idToTexture(self, id, current = None):
            """
            Gets called to get the corresponding texture for a user
            """

            FALL_THROUGH = ""
            return FALL_THROUGH

        @fortifyIceFu(-2)
        @checkSecret
        def registerUser(self, name, current = None):
            """
            Gets called when the server is asked to register a user.
            """
            
            FALL_THROUGH = -2
            debug('registerUser "%s" -> fall through', name)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def unregisterUser(self, id, current = None):
            """
            Gets called when the server is asked to unregister a user.
            """
            
            FALL_THROUGH = -1
            # Return -1 to fall through to internal server database, we don't want to modify IMAP backend
            # but we can make murmur delete all additional information it got this way.
            debug('unregisterUser %d -> fall through', id)
            return FALL_THROUGH

        @fortifyIceFu(-1)
        @checkSecret
        def getRegisteredUsers(self, filter, current = None):
            """
            Returns a list of usernames from IMAP which contain
            filter as a substring.
            """
            
            FALL_THROUGH = -1
            # Return -1 to fall through to internal server database, we can't access a list of users using IMAP
            # but we can make murmur delete all additional information it got this way.
        
        @fortifyIceFu(-1)
        @checkSecret
        def setInfo(self, id, info, current = None):
            """
            Gets called when the server is supposed to save additional information
            about a user to his database
            """
            
            FALL_THROUGH = -1
            # Return -1 to fall through to the internal server handler. We must not modify
            # IMAP backend so the additional information is stored in murmurs database
            debug('setInfo %d -> fall through', id)
            return FALL_THROUGH
        
        @fortifyIceFu(-1)
        @checkSecret
        def setTexture(self, id, texture, current = None):
            """
            Gets called when the server is asked to update the user texture of a user
            """
            

            # There is no such thing in IMAP
            FALL_THROUGH = -1
            return FALL_THROUGH
        
    class CustomLogger(Ice.Logger):
        """
        Logger implementation to pipe Ice log messages into
        our own log
        """
        
        def __init__(self):
            Ice.Logger.__init__(self)
            self._log = getLogger('Ice')
            
        def _print(self, message):
            self._log.info(message)
            
        def trace(self, category, message):
            self._log.debug('Trace %s: %s', category, message)
            
        def warning(self, message):
            self._log.warning(message)
            
        def error(self, message):
            self._log.error(message)

    #
    #--- Start of authenticator
    #
    info('Starting imap mumble authenticator')
    initdata = Ice.InitializationData()
    initdata.properties = Ice.createProperties([], initdata.properties)
    for prop, val in cfg.iceraw:
        initdata.properties.setProperty(prop, val)
        
    initdata.properties.setProperty('Ice.ImplicitContext', 'Shared')
    initdata.properties.setProperty('Ice.Default.EncodingVersion', '1.0')
    initdata.logger = CustomLogger()
    
    app = imapauthenticatorApp()
    state = app.main(sys.argv[:1], initData = initdata)
    info('Shutdown complete')
コード例 #48
0
ファイル: plugin.py プロジェクト: rubinlinux/Limnoria-mumble
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
try:
    from supybot.i18n import PluginInternationalization, internationalizeDocstring
    _ = PluginInternationalization('Mumble')
except:
    _ = lambda x: x
    internationalizeDocstring = lambda x: x

#XXX: Have to hard-code the location to Murmur.ice for now, because I don't know
#how to make Murmure available to metaCallbackI and serverCallbackI without
Ice.loadSlice('', ['-I' + Ice.getSliceDir(), "/usr/share/slice/Murmur.ice"])
import Murmur


class metaCallbackI(Murmur.MetaCallback):
    def started(self, s, current=None):
        print "DEBUG: got a callback on started"
        serverR = Murmur.ServerCallbackPrx.uncheckedCast(
            adapter.addWithUUID(serverCallbackI(server, current.adapter)))
        s.addCallback(serverR)


class serverCallbackI(Murmur.ServerCallback):
    def __init__(self, server, adapter, m):
        self.server = server
        self.m = m
コード例 #49
0
# Mumble source tree or at <https://www.mumble.info/LICENSE>.

# -*- coding: utf-8
import Ice, IcePy, sys, tempfile, os

ice = Ice.initialize(sys.argv)

proxy = ice.stringToProxy('Meta:tcp -h 127.0.0.1 -p 6502')

try:
  slice = IcePy.Operation('getSlice', Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent, True, (), (), (), IcePy._t_string, ()).invoke(proxy, ((), None))

  (slicefiledesc, slicefilepath)  = tempfile.mkstemp(suffix = '.ice')
  slicefile = os.fdopen(slicefiledesc, 'w')
  slicefile.write(slice)
  slicefile.flush()
  Ice.loadSlice('', ['-I' + Ice.getSliceDir(), slicefilepath])
  slicefile.close()
  os.remove(slicefilepath)
  
  print 'Using dynamic slice'
except Exception:
  Ice.loadSlice('', ['-I' + Ice.getSliceDir(), 'Murmur.ice'])
  print 'Using bundled slice'

import Murmur

meta = Murmur.MetaPrx.checkedCast(proxy)

print meta.getVersion()
コード例 #50
0
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.  


#Path to Murmur.ice
iceslice='/usr/share/slice/Murmur.ice'

#Murmur-Port (not needed to work, only for display purposes)
serverport=64738

#Port where ice listen
iceport=6502


import Ice, sys
Ice.loadSlice('', ['-I' + Ice.getSliceDir(), iceslice])
ice = Ice.initialize()
import Murmur

if (sys.argv[1:]):
  if (sys.argv[1] == "config"):
    print 'graph_title Murmur (Port %s)' % (serverport)
    print 'graph_vlabel Count'
    print 'users.label Users'
    print 'uptime.label Uptime in days'
    print 'chancount.label Channelcount/10'
    print 'bancount.label Bans on server'
    sys.exit(0)

meta = Murmur.MetaPrx.checkedCast(ice.stringToProxy("Meta:tcp -h 127.0.0.1 -p %s" % (iceport)))
server=meta.getServer(1)
コード例 #51
0
ファイル: __init__.py プロジェクト: zachlevy/murmur-rest
import settings

import Ice

# Create Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

# Initialize Digest Auth
auth = HTTPDigestAuth()

# If enabled, all endpoints will be digest auth protected
auth_enabled = settings.ENABLE_AUTH

# Load up Murmur slice file into Ice
Ice.loadSlice('', ['-I' + Ice.getSliceDir(), os.path.join(settings.MURMUR_ROOT, settings.SLICE_FILE)])
import Murmur

# Configure Ice properties
props = Ice.createProperties()
props.setProperty("Ice.ImplicitContext", "Shared")
props.setProperty('Ice.Default.EncodingVersion', '1.0')
props.setProperty('Ice.MessageSizeMax', str(settings.ICE_MESSAGESIZE))
idata = Ice.InitializationData()
idata.properties = props

# Create Ice connection
ice = Ice.initialize(idata)
proxy = ice.stringToProxy(settings.ICE_HOST)
secret = settings.ICE_SECRET
if secret != '':
コード例 #52
0
import sys, traceback, Ice,IceGrid
Ice.loadSlice('-I {} Geocloud.ice'.format(Ice.getSliceDir()))
import geocloud
import sys
import time
class GroundStation(Ice.Application):
    def run(self,args):
        com = self.communicator()
        if not com:
            raise RuntimeError("Not communicator")

        else:
            print "ID:",args[0]
            query = com.stringToProxy('IceGrid/Query')
            q = IceGrid.QueryPrx.checkedCast(query)
            if not q:
                raise RuntimeError("Invalid proxy")
            try:
                broker = q.findObjectById(com.stringToIdentity('broker'))
                brokerPrx = geocloud.BrokerPrx.checkedCast(broker)
                print brokerPrx

                orch = q.findObjectById(com.stringToIdentity('orchestrator'))
                orchestratorPrx = geocloud.OrchestratorPrx.checkedCast(orch)
                print orchestratorPrx
            except Exception as e:
                print e
                sys.exit(-1)

           # for i in range(1,3):
                #orchestratorPrx.downloadedImage("imagen"+str(i))
コード例 #53
0
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import os, sys, traceback, threading, time

haveConcurrentFuture = sys.version_info.major > 3 or (
    sys.version_info.major == 3 and sys.version_info.minor >= 5)
if haveConcurrentFuture:
    import concurrent.futures

import Ice

slice_dir = Ice.getSliceDir()
if not slice_dir:
    print(sys.argv[0] + ': Slice directory not found.')
    sys.exit(1)

Ice.loadSlice("'-I" + slice_dir + "' TestAMD.ice")
import Test


def test(b):
    if not b:
        raise RuntimeError('test assertion failed')


class FutureThread(threading.Thread):
    def __init__(self, f, r):
コード例 #54
0
import os
import sys
from getpass import getpass
from hashlib import sha1

import Glacier2
import Ice
Ice.loadSlice('-I%s %s' % (Ice.getSliceDir(), os.path.abspath(os.path.join(__file__, '..', 'MotionDatabase.ice'))))
import MotionDatabase

from django.core.management.base import BaseCommand, CommandError
from dataset.models import MotionFile


DATA_PATH = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'static', 'motions'))
ICE_CLIENT_CONFIG_PATH = os.path.abspath(os.path.join(__file__, '..', 'client.cfg'))


class Command(BaseCommand):
	help = 'Removes motions from the tool that are marked as not public'

	def add_arguments(self, parser):
		pass

	def handle(self, *args, **options):
		username = raw_input('MotionDB Username: '******'MotionDB Password: ')

		# Configure Ice and Connect to database.
		properties = Ice.createProperties(sys.argv)
		properties.load(ICE_CLIENT_CONFIG_PATH)