예제 #1
0
    def __init__(self, **kwargs):

        """
        Default factory, used for TCP servers, implements IDefaultFactory
        :param kwargs:

        """

        self.__logger = Logger()

        self.config = kwargs.get('config', None)

        if self.config is None:

            self.__logger.warning('Config for IDefaultFactory is not provided, failback to defaults...')

            tcp = TCP()

            self.config = {
                'port': 8484,
                'tcp_back_log': 50,
                'service_name': 'Default TCP Server'
            }

            self.config = tcp.to_object(self.config)

        self.protocol = kwargs.get('protocol', DefaultLineReceiver)

        self.name = kwargs.get('name', self.config.service_name)

        self.port = kwargs.get('port', self.config.port)

        self.belong_to = kwargs.get('belong_to', False)
예제 #2
0
    def __init__(self, factory):
        """

        :param factory:
        :type IDefaultFactory

        """

        self.factory = factory

        self.__logger = Logger()

        self.listener = None

        if self.factory.ws_protocol == 'wss':

            self.__ssl_context = ssl.DefaultOpenSSLContextFactory(
                self.factory.crt_keys.get('key'),
                self.factory.crt_keys.get('crt')
            )

        self.setName(self.factory.name)

        if self.factory.belong_to is False:

            self.__application = service.Application(self.factory.name, uid=1000, gid=1000)
            self.service_collection = service.IServiceCollection(self.__application)

        else:

            self.service_collection = self.factory.belong_to
예제 #3
0
    def __init__(self, factories_source, file_loader=None, out_filter=None):
        """
        The constructor will init the storage and all objects that are matched from our filters

        :param file_loader:
        :param factories_source:

        :return: void
        """

        super(RegisterFactories, self).__init__()

        self.__gsm = getGlobalSiteManager()

        self.file_loader = file_loader or FileFactoryLoader()

        if not out_filter:
            out_filter = []

        self.default_filter = list(
            set(out_filter + [IUserStorage, IUserFactory]))

        self.__objects = self.file_loader.load(factories_source,
                                               self.default_filter)

        self.__storage = createObject('storageregister')
        self.__logger = Logger()
예제 #4
0
    def __init__(self, factory):
        """

        :param factory:
        :return: void
        """

        base = BaseWebMethods()
        self.__logger = Logger()

        for meth in factory.config.http_methods:

            try:

                name = 'render_{}'.format(meth)
                web_resource = getattr(base, name)

            except AttributeError as e:

                allow_methods = [
                    render.replace('render_', '') for render in base.__class__.__dict__ if render.startswith('render')
                ]

                print('[ !!!!! Warning: ] Ivalid web methods was provided, available are: {}, error: {}'.format(
                    ', '.join(allow_methods), e
                ))

            else:
                setattr(DefaultWebResource, name, web_resource)

        Resource.__init__(self)
예제 #5
0
    def __init__(self, **kwargs):

        """

        Default factory, used for TCP servers, implements IDefaultFactory
        :param kwargs:

        """
        self.__logger = Logger()

        self.config = kwargs.get('config', None)

        if self.config is None:

            web = WEB()

            self.__logger.warning('Config for IDefaultWebFactory is not provided, failback to defaults...')

            self.config = {
                'port': 8000,
                'www_root': '',
                'service_name': 'Default WEB Server',
                'http_methods': ['GET']
            }

            self.config = web.to_object(self.config)

        self.name = kwargs.get('name', self.config.service_name)
        self.port = kwargs.get('port', self.config.port)
        self.methods = kwargs.get('http_methods', self.config.http_methods)
        self.belong_to = kwargs.get('belong_to', False)
예제 #6
0
    def __init__(self, validate_msg):
        """
        :param validate_msg: IMessage
        """

        super(JSONValidator, self).__init__(validate_msg)

        self.__logger = Logger()
예제 #7
0
    def __init__(self, factory):
        """
        Just settings
        :param factory:
        :return: void
        """

        self.__logger = Logger()
        self.factory = factory
예제 #8
0
    def __init__(self, validate_msg):
        """
        Accept message that have to be validated

        :param validate_msg: currently we supporting only a json validators
        """
        super(Validator, self).__init__(validate_msg)

        self.__msg = Message(validate_msg)
        self.__logger = Logger()
예제 #9
0
    def __init__(self, comp):
        """
        A RootAPI constructor will init an logger and will initialize a public attribute
        - self.comp which representing an input object as DynamicProtocol

        :param comp:
        :type comp: DynamicProtocol

        :return: void
        """
        self.comp = comp
        self.__logger = Logger()
예제 #10
0
    def __init__(self, **kwargs):
        """
        Default factory, used for TCP servers, implements IDefaultFactory
        :param kwargs:

        :return:
        """
        self.__logger = Logger()

        self.config = kwargs.get('config', None)

        if self.config is None:

            ws = WS()

            self.__logger.warning(
                'Config for IDefaultFactory is not provided, failback to defaults...'
            )

            self.config = {
                'url': 'ws://localhost:8585',
                'port': 8585,
                'hostname': 'localhost',
                'protocol': 'ws'
            }

            self.config = ws.to_object(self.config)

        self.ws_protocol = self.config.protocol

        self.name = kwargs.get('name', 'DefaultWSFactory')

        self.port = kwargs.get('port', self.config.port)

        self.url = kwargs.get('port', self.config.url)

        self.belong_to = kwargs.get('belong_to', False)

        self.ws_server_factory = DefaultWSFactoryRunner

        if self.ws_protocol == 'wss':

            key = self.config.keys.key
            crt = self.config.keys.crt

            if key is None or crt is None:
                raise AttributeError(
                    'WS over SSL required attribute a key and a crt')

            self.crt_keys = dict(key=key, crt=crt)

        self.ws_msg_protocol = DefaultWSProtocol
예제 #11
0
def on_connect(self):
    """
    A function that is called when we got connected to a WAMP router.
    This function is attached to our WampDefaultComponent only if protocol is WSS
    :param self:
    :return: void
    """
    cfg = Config().get_wamp()
    log = Logger()

    log.info('Connecting to router...')

    self.join(self.config.realm, [u'wampcra'], cfg.user)
예제 #12
0
    def __init__(self, comp):
        """
        A NonRootAPi constructor will init a logger and a comp property for an object
        that have to be compare with the existing registered protocols

        :param comp:
        :type comp: an input object as DynamicProtocol

        :return: void
        """

        self.comp = comp
        self.__logger = Logger()
예제 #13
0
    def __init__(self, validator):
        """
        The constructor will init a logger and will init a public attribute - self.validator
        that is a validated requests, here we have to determinate which protocol and API have
        to process this request

        :param validator:
        :type validator: IValidator

        :return: void
        """

        self.validator = validator
        self.__logger = Logger()
예제 #14
0
    def __init__(self, **kwargs):
        """
        A constructor will init our wamp session and a runner.
        A runner is a callable that have to be processed when we lose the connection

        :param kwargs: keys: 'session' and 'runner'
        :return: void
        """

        if 'session' not in kwargs or 'runner' not in kwargs:
            raise Exception('session is not provided')

        self.__session = kwargs['session']
        self.__runner = kwargs['runner']

        self.logger = Logger()
        self.config = kwargs.get('config')
예제 #15
0
    def subscriber_dispatcher(self, sub_data):
        """
        Callback function for our global subscriber
        will pass sub_data to GlobalSubscribeMessage and then will trying to
        get wamp component which implements IUserGlobalSubscriber and adapts
        IGlobalSubscribeMessage

        :param sub_data:
        """

        log = Logger()

        try:

            result = IDispatcher(Validator(sub_data)).dispatch()

        # NETODO what exception can happen here?
        except Exception as e:

            import traceback
            print traceback.format_exc()

            log.warning('subscriber_dispatcher exception: {}'.format(
                e.message))

        else:

            if IValidator.providedBy(result):
                log.warning('WAMP Message is invalid: {}'.format(
                    result.message))

            if result is not False and IJSONResource.providedBy(result):

                fac = None

                for sub in subscribers([result], IUserGlobalSubscriber):

                    sub.subscribe(self)
                    fac = True

                    break

                if not fac:
                    log.warning(
                        'There are no user definition for IUserGlobalSubscriber, message was skipped'
                    )
예제 #16
0
def on_challenge(self, challenge):
    """
    A function that is called when we got onChallenge event aka authentication to a WAMP router.
    This function is attached to our WampDefaultComponent only if protocol is WSS

    :param self:
    :param challenge:

    :return: digital signature decode in ascii
    """

    log = Logger()
    log.info('On Challenge...')

    if challenge.method == u"wampcra":

        cfg = Config().get_wamp()

        password = {u'%s' % cfg.user: u'%s' % cfg.password}

        if u'salt' in challenge.extra:

            key = auth.derive_key(password[cfg.user].encode('utf8'),
                                  challenge.extra['salt'].encode('utf8'),
                                  challenge.extra.get('iterations', None),
                                  challenge.extra.get('keylen', None))

        else:

            key = password[cfg.user].encode('utf8')

        signature = auth.compute_wcs(
            key, challenge.extra['challenge'].encode('utf8'))

        return signature.decode('ascii')

    else:

        raise Exception(
            "don't know how to compute challenge for authmethod {}".format(
                challenge.method))
예제 #17
0
    def __init__(self, **kwargs):
        """
        The constructor will init self.cfg self.__gsm and if the protocol is wss,
        will attach on_connect and on_challenge to this object as methods
        :param kwargs: we looking for key 'config'
        :return: void
        """
        config = kwargs.get('config')

        super(WampDefaultComponent, self).__init__(config)

        self.__logger = Logger()
        self.cfg = Config().get_wamp()

        self.__gsm = getGlobalSiteManager()

        if self.cfg.protocol == 'wss':

            self.__logger.info('WAMP is secure, switch to wss...')

            WampDefaultComponent.onConnect = on_connect
            WampDefaultComponent.onChallenge = on_challenge
예제 #18
0
    def __init__(self, factory):

        super(Time, self).__init__(factory)

        self.factory = factory
        self.logger = Logger()
예제 #19
0
 def __init__(self):
     """
     The constructor will init our logger
     :return: void
     """
     self.__logger = Logger()
예제 #20
0
"""
A Default implementation of WS protocol
"""

from zope.interface import implementer
from autobahn.twisted.websocket import WebSocketServerProtocol

from NetCatKS.NetCAT.api.interfaces import IWSProtocol
from NetCatKS.Dispatcher import IDispatcher, DispathcherResultHelper
from NetCatKS.Validators import Validator
from NetCatKS.Logger import Logger

__author__ = 'dimd'

logger = Logger()


@implementer(IWSProtocol)
class DefaultWSProtocol(WebSocketServerProtocol):
    """
    A class that implements a Default WS Protocol
    """
    def onConnect(self, request):
        """
        A callback that fired when connect occur
        :param request:

        :return:
        """
        logger.info("Client connecting: {0}".format(request.peer))
예제 #21
0
 def __init__(self):
     """
     A constructor will init the logger only
     :return: void
     """
     self.__logger = Logger()
예제 #22
0
    def __init__(self, **kwargs):
        """

        :param url: The WebSocket URL of the WAMP router to connect to (e.g. `ws://somehost.com:8090/somepath`)
        :type url: unicode
        :param realm: The WAMP realm to join the application session to.
        :type realm: unicode
        :param extra: Optional extra configuration to forward to the application component.
        :type extra: dict
        :param debug: Turn on low-level debugging.
        :type debug: bool
        :param debug_wamp: Turn on WAMP-level debugging.
        :type debug_wamp: bool
        :param debug_app: Turn on app-level debugging.
        :type debug_app: bool

        """

        self.logger = Logger()

        self.config = kwargs.get('config', None)

        if self.config is None:

            self.config = {}
            wamp = WAMP()

            self.logger.warning('Config is not provided failback to defaults')

            self.config.update({
                'protocol': 'wss',
                'hostname': 'localhost',
                'port': 8080,  # integer
                'realm': 'realm1',
                'path': 'ws',
                'retry_interval': 2,  # in seconds
                'url': u'ws://localhost:8080/ws',
                'service_name': 'A Default WAMP Service name"'
            })

            self.config = wamp.to_object(self.config)

        self.url = kwargs.get('url', self.config.url)

        self.realm = u'{}'.format(kwargs.get('realm', self.config.realm))

        self.extra = kwargs.get('extra', dict())

        self.debug = kwargs.get('debug', False)

        self.debug_wamp = kwargs.get('debug_wamp', False)

        self.debug_app = kwargs.get('debug_app', False)

        self.belong_to = kwargs.get('belong_to', False)

        self.make = None

        self.protocol = kwargs.get('protocol', self.config.protocol)

        self.name = kwargs.get('name', self.config.service_name)

        self.port = kwargs.get('port', self.config.port)

        self.host = kwargs.get('host', self.config.hostname)

        self.path = kwargs.get('path', self.config.path)
예제 #23
0
    def __init__(self, factory=None):

        super(Clock, self).__init__(factory)

        self.logger = Logger()
예제 #24
0
from NetCatKS.Components import BaseAPI, BaseRootAPI
from NetCatKS.Logger import Logger

log = Logger()


class Command(BaseAPI):
    def __init__(self, factory):
        super(Command, self).__init__(factory)

    def event(self):

        log.info('TIME API ADAPTER: {}'.format(self.factory.id))
        self.factory.id = 10
        return self.factory


class Convert(BaseRootAPI):
    def __init__(self, factory):
        super(Convert, self).__init__(factory)

    def process_factory(self):

        self.factory.convert.id = 4200
        return self.factory