Example #1
0
def service(
    description: str,
    factory: interfaces.IProtocolFactory,
    reactor: Optional[interfaces.IReactorCore] = None,
) -> StreamServerEndpointService:
    """
    Return the service corresponding to a description.

    @param description: The description of the listening port, in the syntax
        described by L{twisted.internet.endpoints.serverFromString}.
    @type description: C{str}

    @param factory: The protocol factory which will build protocols for
        connections to this service.
    @type factory: L{twisted.internet.interfaces.IProtocolFactory}

    @rtype: C{twisted.application.service.IService}
    @return: the service corresponding to a description of a reliable stream
        server.

    @see: L{twisted.internet.endpoints.serverFromString}
    """
    if reactor is None:
        reactor = _getReactor()

    svc = StreamServerEndpointService(
        endpoints.serverFromString(reactor, description), factory)
    svc._raiseSynchronously = True
    return svc
Example #2
0
def service(description, factory, reactor=None):
    """
    Return the service corresponding to a description.

    @param description: The description of the listening port, in the syntax
        described by L{twisted.internet.endpoints.serverFromString}.
    @type description: C{str}

    @param factory: The protocol factory which will build protocols for
        connections to this service.
    @type factory: L{twisted.internet.interfaces.IProtocolFactory}

    @rtype: C{twisted.application.service.IService}
    @return: the service corresponding to a description of a reliable stream
        server.

    @see: L{twisted.internet.endpoints.serverFromString}
    """
    if reactor is None:
        from twisted.internet import reactor

    svc = StreamServerEndpointService(
        endpoints.serverFromString(reactor, description), factory)
    svc._raiseSynchronously = True
    return svc
Example #3
0
    def setup(self):
        # initialize storage
        # doing it here because it's needed by the server factory
        storage.init(self.config['database'])
        self.presencedb = storage.MySQLPresenceStorage()

        # TODO from configuration
        stor_class = self.config['storage']['class']
        klass = getattr(storage, stor_class)
        self.storage = klass(*self.config['storage']['params'])

        self.keyring = keyring.Keyring(storage.MySQLNetworkStorage(), self.config['fingerprint'], self.network, self.servername, disable_cache=True)
        token_auth = auth.AuthKontalkChecker(self.config['fingerprint'], self.keyring)

        # upload endpoint
        portal = Portal(FileUploadRealm(self), [token_auth])
        resource = HTTPSAuthSessionWrapper(portal, auth.KontalkCertificate)
        self.putChild('upload', resource)

        # download endpoint
        portal = Portal(FileDownloadRealm(self), [token_auth])
        resource = HTTPSAuthSessionWrapper(portal, auth.KontalkCertificate)
        self.putChild('download', resource)

        # http service
        self.factory = server.Site(self)
        sslFactory = xmlstream2.MyOpenSSLCertificateOptions(self.config['ssl_key'], self.config['ssl_cert'], self._sslVerify)
        endpoint = SSL4ServerEndpoint(reactor, self.config['bind'][1], sslFactory, interface=str(self.config['bind'][0]))
        svc = StreamServerEndpointService(endpoint, self.factory)
        svc._raiseSynchronously = True
        return svc
Example #4
0
def makeBroadcasterService(endpoint, local_ivo, test_interval, whitelist):
    """Create a VOEvent receiver service.

    The receiver service accepts VOEvent messages submitted to the broker by
    authors.

    Parameters
    ----------
    endpoint : implements `twisted.internet.interfaces.IStreamServerEndpoint`
        The endpoint to which the service will listen.
    local_ivo : `str`
        IVOA identifier for the subscriber.
    test_interval: `int`
        The interval in seconds between test events to be broadcast. If ``0``,
        no test events will be sent.
    whitelist : `list` of `ipaddress.IPv4Network` or `ipaddress.IPv6Network`
        Only addresses which fall in a network included in the whitelist are
        permitted to subscribe.
    """
    factory = VOEventBroadcasterFactory(local_ivo, test_interval)
    if log.LEVEL >= log.Levels.INFO:
        factory.noisy = False

    whitelisting_factory = WhitelistingFactory(factory, whitelist,
                                               "subscription")
    if log.LEVEL >= log.Levels.INFO:
        whitelisting_factory.noisy = False

    service = StreamServerEndpointService(endpoint, whitelisting_factory)

    # Shut down, rather than simply logging an error, if we can't bind.
    service._raiseSynchronously = True

    return service
Example #5
0
    def setup(self):
        storage.init(self.config['database'])

        cert = OpenPGPCertificate(open(self.config['pgp_cert']).read())
        key = OpenPGPPrivateKey(open(self.config['pgp_key']).read())

        cred = auth.OpenPGPKontalkCredentials(cert, key,
                                              str(self.config['pgp_keyring']))
        cred.verify_peer = True

        ring = keyring.Keyring(storage.MySQLNetworkStorage(),
                               self.config['fingerprint'], self.network,
                               self.servername)
        self.service = NetService(self.config, self, ring, cred)
        self.service.logTraffic = self.logTraffic
        self.sfactory = XMPPNetServerFactory(self.service)
        self.sfactory.logTraffic = self.logTraffic

        tls_svc = StreamServerEndpointService(
            tls.TLSServerEndpoint(reactor=reactor,
                                  port=int(self.config['bind'][1]),
                                  interface=str(self.config['bind'][0]),
                                  credentials=cred), self.sfactory)
        tls_svc._raiseSynchronously = True

        return tls_svc
Example #6
0
def makeBroadcasterService(endpoint, local_ivo, test_interval, whitelist):
    """Create a VOEvent receiver service.

    The receiver service accepts VOEvent messages submitted to the broker by
    authors.

    Parameters
    ----------
    endpoint : implements `twisted.internet.interfaces.IStreamServerEndpoint`
        The endpoint to which the service will listen.
    local_ivo : `str`
        IVOA identifier for the subscriber.
    test_interval: `int`
        The interval in seconds between test events to be broadcast. If ``0``,
        no test events will be sent.
    whitelist : `list` of `ipaddress.IPv4Network` or `ipaddress.IPv6Network`
        Only addresses which fall in a network included in the whitelist are
        permitted to subscribe.
    """
    factory = VOEventBroadcasterFactory(local_ivo, test_interval)
    if log.LEVEL >= log.Levels.INFO:
        factory.noisy = False

    whitelisting_factory = WhitelistingFactory(factory, whitelist,
                                               "subscription")
    if log.LEVEL >= log.Levels.INFO:
        whitelisting_factory.noisy = False

    service = StreamServerEndpointService(endpoint, whitelisting_factory)

    # Shut down, rather than simply logging an error, if we can't bind.
    service._raiseSynchronously = True

    return service
Example #7
0
    def setup(self):
        # initialize storage
        # doing it here because it's needed by the server factory
        storage.init(self.config['database'])

        # TODO from configuration
        stor_class = self.config['storage']['class']
        klass = getattr(storage, stor_class)
        self.storage = klass(*self.config['storage']['params'])

        self.keyring = keyring.Keyring(storage.MySQLNetworkStorage(), self.config['fingerprint'], self.network, self.servername, disable_cache=True)
        token_auth = auth.AuthKontalkChecker(self.config['fingerprint'], self.keyring)

        # upload endpoint
        portal = Portal(FileUploadRealm(self), [token_auth])
        resource = HTTPSAuthSessionWrapper(portal, auth.KontalkCertificate)
        self.putChild('upload', resource)

        # download endpoint
        portal = Portal(FileDownloadRealm(self), [token_auth])
        resource = HTTPSAuthSessionWrapper(portal, auth.KontalkCertificate)
        self.putChild('download', resource)

        # http service
        self.factory = server.Site(self)
        sslFactory = MyOpenSSLCertificateOptions(self.config['ssl_key'], self.config['ssl_cert'], self._sslVerify)
        endpoint = SSL4ServerEndpoint(reactor, self.config['bind'][1], sslFactory, interface=str(self.config['bind'][0]))
        svc = StreamServerEndpointService(endpoint, self.factory)
        svc._raiseSynchronously = True
        return svc
Example #8
0
    def setup(self):
        # initialize storage
        # doing it here because it's needed by the c2s server factory
        storage.init(self.config['database'])
        self.presencedb = storage.MySQLPresenceStorage()

        try:
            stanza_expire = self.config['stanza_expire']
        except KeyError:
            stanza_expire = 0
        self.stanzadb = storage.MySQLStanzaStorage(stanza_expire)

        try:
            validation_expire = self.config['registration']['expire']
        except KeyError:
            validation_expire = 0
        self.validationdb = storage.MySQLUserValidationStorage(validation_expire)

        self.keyring = keyring.Keyring(storage.MySQLNetworkStorage(), self.config['fingerprint'], self.network, self.servername)
        authrealm = auth.SASLRealm("Kontalk")
        authportal = portal.Portal(authrealm, [auth.AuthKontalkChecker(self.config['fingerprint'], self.keyring, self._verify_fingerprint)])

        self.sfactory = XMPPServerFactory(authportal, self, self.network, self.servername)
        self.sfactory.logTraffic = self.config['debug']
        if 'ssl_key' in self.config and 'ssl_cert' in self.config:
            self.sfactory.loadPEM(self.config['ssl_cert'], self.config['ssl_key'])

        services = []

        if 'plain' in self.config['bind']:
            plain_svc = strports.service('tcp:' + str(self.config['bind']['plain'][1]) +
                ':interface=' + str(self.config['bind']['plain'][0]), self.sfactory)
            services.append(plain_svc)

        if 'ssl' in self.config['bind']:
            ssl_svc = internet.SSLServer(port=int(self.config['bind']['ssl'][1]),
                interface=str(self.config['bind']['ssl'][0]),
                factory=self.sfactory,
                contextFactory=self.sfactory.getSSLContext())

            services.append(ssl_svc)

        if 'tls' in self.config['bind']:
            cert = OpenPGPCertificate(open(self.config['pgp_cert']).read())
            key = OpenPGPPrivateKey(open(self.config['pgp_key']).read())

            cred = auth.OpenPGPKontalkCredentials(cert, key, str(self.config['pgp_keyring']))
            cred.verify_peer = True
            tls_svc = StreamServerEndpointService(
                tls.TLSServerEndpoint(reactor=reactor,
                    port=int(self.config['bind']['tls'][1]),
                    interface=str(self.config['bind']['tls'][0]),
                    credentials=cred),
                self.sfactory)
            tls_svc._raiseSynchronously = True

            services.append(tls_svc)

        return services
Example #9
0
def makeReceiverService(endpoint, local_ivo, validators, handlers, whitelist):
    """Create a VOEvent receiver service.

    The receiver service accepts VOEvent messages submitted to the broker by
    authors.

    Parameters
    ----------
    endpoint : implements `twisted.internet.interfaces.IStreamServerEndpoint`
        The endpoint to which the service will listen.
    local_ivo : `str`
        IVOA identifier for the subscriber.
    validators : `list` of implementers of `~comet.icomet.IValidator`.
        Validators which will be applied to incoming events. Events which fail
        validation will be rejected.
    handlers : `list` of implementers of `~comet.icomet.IHandler`.
        Handlers to which events which pass validation will be passed.
    whitelist : `list` of `ipaddress.IPv4Network` or `ipaddress.IPv6Network`
        Submissions are only accepted from addresses which fall in a network
        included in the whitelist.

    Warnings
    --------
    Although a non-TCP endpoint can be specified (a Unix domain socket, for
    example), the whitelist won't be applied to it correctly (indeed, it will
    probably break horribly).
    """
    factory = VOEventReceiverFactory(local_ivo=local_ivo,
                                     validators=validators,
                                     handlers=handlers)
    if log.LEVEL >= log.Levels.INFO:
        factory.noisy = False

    whitelisting_factory = WhitelistingFactory(factory, whitelist,
                                               "submission")
    if log.LEVEL >= log.Levels.INFO:
        whitelisting_factory.noisy = False

    service = StreamServerEndpointService(endpoint, whitelisting_factory)

    # Shut down, rather than simply logging an error, if we can't bind.
    service._raiseSynchronously = True

    return service
Example #10
0
def service(description, factory, default=_DEFAULT, reactor=None):
    """
    Return the service corresponding to a description.

    @param description: The description of the listening port, in the syntax
        described by L{twisted.internet.endpoints.server}.

    @type description: C{str}

    @param factory: The protocol factory which will build protocols for
        connections to this service.

    @type factory: L{twisted.internet.interfaces.IProtocolFactory}

    @type default: C{str} or C{None}

    @param default: Do not use this parameter.  It is deprecated since Twisted
        10.2.0.

    @rtype: C{twisted.application.service.IService}

    @return: the service corresponding to a description of a reliable
        stream server.

    @see: L{twisted.internet.endpoints.serverFromString}
    """
    if reactor is None:
        from twisted.internet import reactor
    if default is _DEFAULT:
        default = None
    else:
        message = "The 'default' parameter was deprecated in Twisted 10.2.0."
        if default is not None:
            message += ("  Use qualified endpoint descriptions; for example, "
                        "'tcp:%s'." % (description, ))
        warnings.warn(message=message,
                      category=DeprecationWarning,
                      stacklevel=2)
    svc = StreamServerEndpointService(
        endpoints._serverFromStringLegacy(reactor, description, default),
        factory)
    svc._raiseSynchronously = True
    return svc
Example #11
0
def makeReceiverService(endpoint, local_ivo, validators, handlers, whitelist):
    """Create a VOEvent receiver service.

    The receiver service accepts VOEvent messages submitted to the broker by
    authors.

    Parameters
    ----------
    endpoint : implements `twisted.internet.interfaces.IStreamServerEndpoint`
        The endpoint to which the service will listen.
    local_ivo : `str`
        IVOA identifier for the subscriber.
    validators : `list` of implementers of `~comet.icomet.IValidator`.
        Validators which will be applied to incoming events. Events which fail
        validation will be rejected.
    handlers : `list` of implementers of `~comet.icomet.IHandler`.
        Handlers to which events which pass validation will be passed.
    whitelist : `list` of `ipaddress.IPv4Network` or `ipaddress.IPv6Network`
        Submissions are only accepted from addresses which fall in a network
        included in the whitelist.

    Warnings
    --------
    Although a non-TCP endpoint can be specified (a Unix domain socket, for
    example), the whitelist won't be applied to it correctly (indeed, it will
    probably break horribly).
    """
    factory = VOEventReceiverFactory(local_ivo=local_ivo,
                                     validators=validators,
                                     handlers=handlers)
    if log.LEVEL >= log.Levels.INFO:
        factory.noisy = False

    whitelisting_factory = WhitelistingFactory(factory, whitelist, "submission")
    if log.LEVEL >= log.Levels.INFO:
        whitelisting_factory.noisy = False

    service = StreamServerEndpointService(endpoint, whitelisting_factory)

    # Shut down, rather than simply logging an error, if we can't bind.
    service._raiseSynchronously = True

    return service
Example #12
0
def service(description, factory, default=_DEFAULT, reactor=None):
    """
    Return the service corresponding to a description.

    @param description: The description of the listening port, in the syntax
        described by L{twisted.internet.endpoints.server}.

    @type description: C{str}

    @param factory: The protocol factory which will build protocols for
        connections to this service.

    @type factory: L{twisted.internet.interfaces.IProtocolFactory}

    @type default: C{str} or C{None}

    @param default: Do not use this parameter. It has been deprecated since
        Twisted 10.2.0.

    @rtype: C{twisted.application.service.IService}

    @return: the service corresponding to a description of a reliable
        stream server.

    @see: L{twisted.internet.endpoints.serverFromString}
    """
    if reactor is None:
        from twisted.internet import reactor
    if default is _DEFAULT:
        default = None
    else:
        message = "The 'default' parameter was deprecated in Twisted 10.2.0."
        if default is not None:
            message += (
                "  Use qualified endpoint descriptions; for example, "
                "'tcp:%s'." % (description,))
        warnings.warn(
            message=message, category=DeprecationWarning, stacklevel=2)
    svc = StreamServerEndpointService(
        endpoints._serverFromStringLegacy(reactor, description, default),
        factory)
    svc._raiseSynchronously = True
    return svc
Example #13
0
    def setup(self):
        storage.init(self.config['database'])

        cert = OpenPGPCertificate(open(self.config['pgp_cert']).read())
        key = OpenPGPPrivateKey(open(self.config['pgp_key']).read())

        cred = auth.OpenPGPKontalkCredentials(cert, key, str(self.config['pgp_keyring']))
        cred.verify_peer = True

        ring = keyring.Keyring(storage.MySQLNetworkStorage(), self.config['fingerprint'], self.network, self.servername)
        self.service = NetService(self.config, self, ring, cred)
        self.service.logTraffic = self.logTraffic
        self.sfactory = XMPPNetServerFactory(self.service)
        self.sfactory.logTraffic = self.logTraffic

        tls_svc = StreamServerEndpointService(
            tls.TLSServerEndpoint(reactor=reactor,
                port=int(self.config['bind'][1]),
                interface=str(self.config['bind'][0]),
                credentials=cred),
            self.sfactory)
        tls_svc._raiseSynchronously = True

        return tls_svc
Example #14
0
    def setup(self):
        # initialize storage
        # doing it here because it's needed by the c2s server factory
        storage.init(self.config['database'])
        self.presencedb = storage.MySQLPresenceStorage()

        try:
            stanza_expire = self.config['stanza_expire']
        except KeyError:
            stanza_expire = 0
        self.stanzadb = storage.MySQLStanzaStorage(stanza_expire)

        try:
            validation_expire = self.config['registration']['expire']
        except KeyError:
            validation_expire = 0
        self.validationdb = storage.MySQLUserValidationStorage(
            validation_expire)

        self.keyring = keyring.Keyring(storage.MySQLNetworkStorage(),
                                       self.config['fingerprint'],
                                       self.network, self.servername)
        authrealm = auth.SASLRealm("Kontalk")
        authportal = portal.Portal(authrealm, [
            auth.AuthKontalkChecker(self.config['fingerprint'], self.keyring,
                                    self._verify_fingerprint)
        ])

        self.sfactory = XMPPServerFactory(authportal, self, self.network,
                                          self.servername)
        self.sfactory.logTraffic = self.config['debug']
        if 'ssl_key' in self.config and 'ssl_cert' in self.config:
            self.sfactory.loadPEM(self.config['ssl_cert'],
                                  self.config['ssl_key'])

        services = []

        if 'plain' in self.config['bind']:
            plain_svc = strports.service(
                'tcp:' + str(self.config['bind']['plain'][1]) + ':interface=' +
                str(self.config['bind']['plain'][0]), self.sfactory)
            services.append(plain_svc)

        if 'ssl' in self.config['bind']:
            ssl_svc = internet.SSLServer(
                port=int(self.config['bind']['ssl'][1]),
                interface=str(self.config['bind']['ssl'][0]),
                factory=self.sfactory,
                contextFactory=self.sfactory.getSSLContext())

            services.append(ssl_svc)

        if 'tls' in self.config['bind']:
            cert = OpenPGPCertificate(open(self.config['pgp_cert']).read())
            key = OpenPGPPrivateKey(open(self.config['pgp_key']).read())

            cred = auth.OpenPGPKontalkCredentials(
                cert, key, str(self.config['pgp_keyring']))
            cred.verify_peer = True
            tls_svc = StreamServerEndpointService(
                tls.TLSServerEndpoint(reactor=reactor,
                                      port=int(self.config['bind']['tls'][1]),
                                      interface=str(
                                          self.config['bind']['tls'][0]),
                                      credentials=cred), self.sfactory)
            tls_svc._raiseSynchronously = True

            services.append(tls_svc)

        return services