twisted.internet.ssl.DefaultOpenSSLContextFactory

Here are the examples of the python api twisted.internet.ssl.DefaultOpenSSLContextFactory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

62 Examples 7

Example 1

Project: trigger
Source File: server.py
View license
def main():
    """To daemonize as a twistd plugin! Except this doesn't work and these"""
    from twisted.application.internet import TCPServer, SSLServer
    from twisted.application.service import Application
    from twisted.internet import ssl

    rpc = TriggerXMLRPCServer()
    xmlrpc.addIntrospection(rpc)

    server_factory = server.Site(rpc)
    application = Application('trigger_xmlrpc')

    #xmlrpc_service = TCPServer(8000, server_factory)
    ctx = ssl.DefaultOpenSSLContextFactory('server.key', 'cacert.pem')
    xmlrpc_service = SSLServer(8000, server_factory, ctx)
    xmlrpc_service.setServiceParent(application)

    return application

Example 2

Project: curio
Source File: twistsslecho.py
View license
def main():
    """This runs the protocol on port 25000"""
    factory = protocol.Factory()
    factory.protocol = Echo
    reactor.listenSSL(25000, factory,
                      ssl.DefaultOpenSSLContextFactory(KEYFILE, CERTFILE))
    reactor.run()

Example 3

Project: txloadbalancer
Source File: director.py
View license
def setupAdminWebUIServer(configuration, director):
    """
    Given the director, set up a potentially SSL-enabled admin web UI on the
    configured port.
    """
    if not configuration.admin.webEnable:
        return
    root = pages.AdminServer(configuration, director)
    site = server.Site(root)
    host, port = util.splitHostPort(configuration.admin.webListen)
    if configuration.admin.webSecure:
        util.setupServerCert()
        context = ssl.DefaultOpenSSLContextFactory(
            util.privKeyFile, util.certFile)
        admin = internet.SSLServer(port, site, context, interface=host)
    else:
        admin = internet.TCPServer(port, site, interface=host)
    admin.setName('adminWeb')
    return admin

Example 4

Project: txmsgpackrpc
Source File: tx_rpc_server_ssl.py
View license
def main():
    server = EchoRPC()

    sslContext = ssl.DefaultOpenSSLContextFactory(
                    'examples/cert/example.key',
                    'examples/cert/example.cert')

    reactor.listenSSL(8000, server.getStreamFactory(), sslContext)

Example 5

Project: mythbox
Source File: test_internet.py
View license
        def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

Example 6

Project: mythbox
Source File: test_internet.py
View license
        def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

Example 7

Project: mythbox
Source File: test_ssl.py
View license
    def makeContextFactory(self, org, orgUnit, *args, **kwArgs):
        base = self.mktemp()
        generateCertificateFiles(base, org, orgUnit)
        serverCtxFactory = ssl.DefaultOpenSSLContextFactory(
            os.extsep.join((base, 'key')),
            os.extsep.join((base, 'cert')),
            *args, **kwArgs)

        return base, serverCtxFactory

Example 8

Project: mythbox
Source File: test_ssl.py
View license
    def setUp(self):
        # pyOpenSSL Context objects aren't introspectable enough.  Pass in
        # an alternate context factory so we can inspect what is done to it.
        self.contextFactory = ssl.DefaultOpenSSLContextFactory(
            certPath, certPath, _contextFactory=FakeContext)
        self.context = self.contextFactory.getContext()

Example 9

Project: mythbox
Source File: test_ssl.py
View license
    def test_missingCertificateFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp())

Example 10

Project: mythbox
Source File: test_ssl.py
View license
    def test_missingPrivateKeyFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)

Example 11

Project: mythbox
Source File: test_ssl.py
View license
    def makeContextFactory(self, org, orgUnit, *args, **kwArgs):
        base = self.mktemp()
        generateCertificateFiles(base, org, orgUnit)
        serverCtxFactory = ssl.DefaultOpenSSLContextFactory(
            os.extsep.join((base, 'key')),
            os.extsep.join((base, 'cert')),
            *args, **kwArgs)

        return base, serverCtxFactory

Example 12

Project: mythbox
Source File: test_ssl.py
View license
    def setUp(self):
        # pyOpenSSL Context objects aren't introspectable enough.  Pass in
        # an alternate context factory so we can inspect what is done to it.
        self.contextFactory = ssl.DefaultOpenSSLContextFactory(
            certPath, certPath, _contextFactory=FakeContext)
        self.context = self.contextFactory.getContext()

Example 13

Project: mythbox
Source File: test_ssl.py
View license
    def test_missingCertificateFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp())

Example 14

Project: mythbox
Source File: test_ssl.py
View license
    def test_missingPrivateKeyFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)

Example 15

View license
        def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

Example 16

View license
        def testSSL(self, ssl=ssl):
            pem = util.sibpath(__file__, 'server.pem')
            p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
            portNo = p.getHost().port
            self.assertNotEqual(str(p).find(str(portNo)), -1,
                                "%d not found in %s" % (portNo, p))
            return p.stopListening()

Example 17

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def makeContextFactory(self, org, orgUnit, *args, **kwArgs):
        base = self.mktemp()
        generateCertificateFiles(base, org, orgUnit)
        serverCtxFactory = ssl.DefaultOpenSSLContextFactory(
            os.extsep.join((base, 'key')),
            os.extsep.join((base, 'cert')),
            *args, **kwArgs)

        return base, serverCtxFactory

Example 18

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def setUp(self):
        # pyOpenSSL Context objects aren't introspectable enough.  Pass in
        # an alternate context factory so we can inspect what is done to it.
        self.contextFactory = ssl.DefaultOpenSSLContextFactory(
            certPath, certPath, _contextFactory=FakeContext)
        self.context = self.contextFactory.getContext()

Example 19

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def test_missingCertificateFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp())

Example 20

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def test_missingPrivateKeyFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)

Example 21

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def makeContextFactory(self, org, orgUnit, *args, **kwArgs):
        base = self.mktemp()
        generateCertificateFiles(base, org, orgUnit)
        serverCtxFactory = ssl.DefaultOpenSSLContextFactory(
            os.extsep.join((base, 'key')),
            os.extsep.join((base, 'cert')),
            *args, **kwArgs)

        return base, serverCtxFactory

Example 22

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def setUp(self):
        # pyOpenSSL Context objects aren't introspectable enough.  Pass in
        # an alternate context factory so we can inspect what is done to it.
        self.contextFactory = ssl.DefaultOpenSSLContextFactory(
            certPath, certPath, _contextFactory=FakeContext)
        self.context = self.contextFactory.getContext()

Example 23

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def test_missingCertificateFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp())

Example 24

Project: SubliminalCollaborator
Source File: test_ssl.py
View license
    def test_missingPrivateKeyFile(self):
        """
        Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key
        filename which does not identify an existing file results in the
        initializer raising L{OpenSSL.SSL.Error}.
        """
        self.assertRaises(
            SSL.Error,
            ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath)

Example 25

Project: eth-proxy
Source File: server.py
View license
def setup_finalize(event, application):
       
    from twisted.application import service, internet
    from twisted.internet import reactor, ssl
    from twisted.web.server import Site
    from twisted.python import log
    #from twisted.enterprise import adbapi
    import OpenSSL.SSL
    
    from services import ServiceEventHandler
    
    import socket_transport
    import http_transport
    import websocket_transport
    
    from stratum import settings
    
    signing_key = None
        
    # Attach HTTPS Poll Transport service to application
    try:
        sslContext = ssl.DefaultOpenSSLContextFactory(settings.SSL_PRIVKEY, settings.SSL_CACERT)
    except OpenSSL.SSL.Error:
        sslContext = None
        print "Cannot initiate SSL context, are SSL_PRIVKEY or SSL_CACERT missing?"
        print "This will skip all SSL-based transports."
        
    # Set up thread pool size for service threads
    reactor.suggestThreadPoolSize(settings.THREAD_POOL_SIZE) 
    
    if settings.LISTEN_SOCKET_TRANSPORT:
        # Attach Socket Transport service to application
        socket = internet.TCPServer(settings.LISTEN_SOCKET_TRANSPORT,
                                socket_transport.SocketTransportFactory(debug=settings.DEBUG,
                                                                        signing_key=signing_key,
                                                                        signing_id=settings.SIGNING_ID,
                                                                        event_handler=ServiceEventHandler,
                                                                        tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL))
        socket.setServiceParent(application)

    # Build the HTTP interface
    httpsite = Site(http_transport.Root(debug=settings.DEBUG, signing_key=signing_key, signing_id=settings.SIGNING_ID,
                                        event_handler=ServiceEventHandler))
    httpsite.sessionFactory = http_transport.HttpSession

    if settings.LISTEN_HTTP_TRANSPORT:    
        # Attach HTTP Poll Transport service to application
        http = internet.TCPServer(settings.LISTEN_HTTP_TRANSPORT, httpsite)
        http.setServiceParent(application)

    if settings.LISTEN_HTTPS_TRANSPORT and sslContext:
            https = internet.SSLServer(settings.LISTEN_HTTPS_TRANSPORT, httpsite, contextFactory = sslContext)
            https.setServiceParent(application)
    
    if settings.LISTEN_WS_TRANSPORT:
        from autobahn.websocket import listenWS
        log.msg("Starting WS transport on %d" % settings.LISTEN_WS_TRANSPORT)
        ws = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WS_TRANSPORT,
                                                           debug=settings.DEBUG,
                                                           signing_key=signing_key,
                                                           signing_id=settings.SIGNING_ID,
                                                           event_handler=ServiceEventHandler,
                                                           tcp_proxy_protocol_enable=settings.TCP_PROXY_PROTOCOL)
        listenWS(ws)
    
    if settings.LISTEN_WSS_TRANSPORT and sslContext:  
        from autobahn.websocket import listenWS
        log.msg("Starting WSS transport on %d" % settings.LISTEN_WSS_TRANSPORT)
        wss = websocket_transport.WebsocketTransportFactory(settings.LISTEN_WSS_TRANSPORT, is_secure=True,
                                                            debug=settings.DEBUG,
                                                            signing_key=signing_key,
                                                            signing_id=settings.SIGNING_ID,
                                                            event_handler=ServiceEventHandler)
        listenWS(wss, contextFactory=sslContext)
    

    return event

Example 26

Project: splash
Source File: mockserver.py
View license
def ssl_factory():
    pem = cert_path()
    return ssl.DefaultOpenSSLContextFactory(pem, pem)

Example 27

Project: scrapy
Source File: mockserver.py
View license
def ssl_context_factory(keyfile='keys/cert.pem', certfile='keys/cert.pem'):
    return ssl.DefaultOpenSSLContextFactory(
         os.path.join(os.path.dirname(__file__), keyfile),
         os.path.join(os.path.dirname(__file__), certfile),
         )

Example 28

Project: trigger
Source File: trigger_xmlrpc.py
View license
    def makeService(self, options):
        rpc = TriggerXMLRPCServer(allowNone=True, useDateTime=True)
        xmlrpc.addIntrospection(rpc)
        site_factory = server.Site(rpc)

        # Try to setup SSL
        if ssl is not None:
            ctx = ssl.DefaultOpenSSLContextFactory(options['ssl-keyfile'],
                                                   options['ssl-certfile'])
            xmlrpc_service = SSLServer(int(options['port']), site_factory, ctx)
        # Or fallback to clear-text =(
        else:
            xmlrpc_service = TCPServer(int(options['port']), site_factory)

        # SSH Manhole service
        console_service = makeConsoleService(
            {
                'sshPort': 'tcp:%s' % options['ssh-port'],
                'sshKeyDir': options['ssh-keydir'],
                'sshKeyName': options['ssh-keyname'],
                'sshKeySize': options['ssh-keysize'],
                'telnetPort': None,
                'passwd': options['ssh-users'],
                'namespace': {
                    'service': rpc,
                    'rebuild': rebuild,
                    'factory': site_factory,
                }
            }
        )

        svc = MultiService()
        xmlrpc_service.setServiceParent(svc)
        console_service.setServiceParent(svc)
        return svc

Example 29

Project: txmongo
Source File: test_auth.py
View license
    @defer.inlineCallbacks
    def setUp(self):
        self.dbpath = tempfile.mkdtemp()

        self.server_keyfile = self.__create_keyfile(self.server_keycert)
        self.ca_certfile = self.__create_keyfile(self.ca_cert)
        self.client_keyfile = self.__create_keyfile(self.client_key)
        self.client_certfile = self.__create_keyfile(self.client_cert)

        self.ssl_factory = ssl.DefaultOpenSSLContextFactory(
            privateKeyFileName = self.client_keyfile,
            certificateFileName = self.client_certfile,
        )

        mongod_noauth = Mongod(port=mongo_port, auth=False, dbpath=self.dbpath)
        yield mongod_noauth.start()

        try:
            conn = connection.MongoConnection("localhost", mongo_port)

            yield conn["$external"].command("createUser", self.client_subject,
                                            roles=[{"role": "root", "db": "admin"}])
        finally:
            yield conn.disconnect()
            yield mongod_noauth.stop()

        self.mongod = Mongod(port=mongo_port, auth=True, dbpath=self.dbpath,
                             args=["--clusterAuthMode", "x509", "--sslMode", "requireSSL",
                                   "--sslPEMKeyFile", self.server_keyfile,
                                   "--sslCAFile", self.ca_certfile])
        try:
            yield self.mongod.start()
        except:
            print(self.mongod.output())
            raise

Example 30

Project: sedona
Source File: sedona.py
View license
def main():
    """the application entrypoint"""
    global config
    global users
    global logger
    global access_logger
    global debug

    #print the welcome message
    print_welcome_message()

    #handle command line arguments
    args = parse_cmdline()

    #specify verbosity
    if (args.verbose == True):
        log_level = logging.DEBUG
    else:
        log_level = logging.INFO

    ## Setup Logging (generic)
    logging.basicConfig(level=logging.CRITICAL, format='%(asctime)s %(levelname)s %(message)s')
    #logging.basicConfig(format='%(asctime)s %(clientip)s %(user)s %(levelname)s %(message)s')
    logger = logging.getLogger('sedona')
    logger.setLevel(logging.CRITICAL)

    #load the default config file
    config = load_config_file(args.config_path)

    ## Setup Debug Logging
    debug = logging.getLogger('sedona-debug')
    debug.setLevel(logging.DEBUG)
    debug.propagate = False
    fh = logging.FileHandler(config['debug-log'])
    fh.setLevel(logging.DEBUG)
    #ch = logging.StreamHandler()
    #ch.setLevel(logging.ERROR)

    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    fh.setFormatter(formatter)

    # add the handlers to logger
    debug.addHandler(fh)
    #debug.addHandler(ch)

    ## Setup Access logging (file-based)
    access_logger = logging.getLogger('sedona-access')
    access_logger.setLevel(logging.INFO)
    access_logger.propagate = False
    fh = logging.FileHandler(config['access-log'])
    fh.setLevel(logging.INFO)

    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s %(ip)s %(user)s %(command)s %(message)s')
    fh.setFormatter(formatter)

    # add the handlers to logger
    access_logger.addHandler(fh)
 
    #capture logs from Twisted
    observer = log.PythonLoggingObserver()
    observer.start()

    #check for authfile in config, or on commandline
    try:
        authfile = config['authfile']
    except KeyError:
        if (args.authfile == None):
            ThrowCritical("No authorization / rules file specified. Specify one in your config, or use -a")
        else:
            authfile = args.authfile

    #load the authorization file (ACLs)
    users = load_authfile(authfile)

    debug.debug("Found %s users" % len(users), extra={'clientip':'-', 'user':'-'})

    #perform some pre-flight checks
    #ssl or plaintext support must be enabled
    if (config['plaintext-support'] == False and config['ssl-support'] == False):
        ThrowCritical("You must enable plaintext support or SSL support.")

    #if require-auth is not enabled, must provide user
    if (config['require-authentication'] == False):
        if (config['default-user'] == None or config['default-user'] == ""):
            ThrowCritical("You must specify a default user account if you do not require authentication.")

    # Check for SSL support
    if (config['ssl-support'] == True):
        if os.path.exists(config['ssl-key-file']):
            if (os.path.exists(config['ssl-cert-file'])):
                ssl_factory = Factory()
                ssl_factory.protocol = Redis2
                reactor.listenSSL(config['ssl-port'], RedisFactory(config, users), ssl.DefaultOpenSSLContextFactory(config['ssl-key-file'], config['ssl-cert-file']))
            else:
                ThrowCritical("The SSL certificate file specified in the config does not exist")
        else:
            ThrowCritical("The SSL key file specified in the config does not exist")

    # Open an IPv4 TCP endpoint on 6370
    if (config['plaintext-support'] == True):
        endpoint = TCP4ServerEndpoint(reactor, config['plaintext-port'])
        endpoint.noisy = False
        endpoint.listen(RedisFactory(config, users))
        reactor.run()

Example 31

Project: PiIO.WS
Source File: server.py
View license
def main():
    if WS_USE_SSL or HTTP_USE_SSL:
        contextFactory = ssl.DefaultOpenSSLContextFactory('certs/server.key',
            'certs/server.crt')

    if WS_USE_SSL:
        uri_type = "wss"
    else:
        uri_type = "ws"

    server_url = "%s://%s:%d" % (uri_type, SERVER, WS_PORT)

    if DEBUG:
        log.startLogging(sys.stdout)

    factory = RPISocketServerFactory(server_url, debug=DEBUG, debugCodePaths=DEBUG)
    factory.protocol = RPIServerProtocol

    sitecomm = SiteComm(factory)
    factory.sitecomm = sitecomm
    site = server.Site(sitecomm)

    if WS_USE_SSL:
        listenWS(factory, contextFactory)
    else:
        listenWS(factory)

    if HTTP_USE_SSL:
        reactor.listenSSL(HTTP_PORT, site, contextFactory)
    else:
        reactor.listenTCP(HTTP_PORT, site)

    if PROVIDEFLASHSOCKETPOLICYFILE:
        socketfactory = twistedsockets.Factory()
        socketfactory.protocol = FlashSocketPolicyServerProtocol
        reactor.listenTCP(843, socketfactory)

    reactor.run()

Example 32

Project: autobahn-testsuite
Source File: util.py
View license
def _createWssContext(self, options, factory):
   """Create an SSL context factory for WSS connections.
   """

   if not factory.isSecure:
      return None

   # Check if an OpenSSL library can be imported; abort if it's missing.
   try:
      from twisted.internet import ssl
   except ImportError, e:
      print ("You need OpenSSL/pyOpenSSL installed for secure WebSockets"
             "(wss)!")
      sys.exit(1)

   # Make sure the necessary options ('key' and 'cert') are available
   if options['key'] is None or options['cert'] is None:
      print OPENSSL_HELP
      sys.exit(1)

   # Create the context factory based on the given key and certificate
   key = str(options['key'])
   cert = str(options['cert'])
   return ssl.DefaultOpenSSLContextFactory(key, cert)

Example 33

Project: sylkserver
Source File: web.py
View license
    def start(self):
        interface = WebServerConfig.local_ip
        port = WebServerConfig.local_port
        cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None
        cert_chain_path = WebServerConfig.certificate_chain.normalized if WebServerConfig.certificate_chain else None
        if cert_path is not None:
            if not os.path.isfile(cert_path):
                log.error('Certificate file %s could not be found' % cert_path)
                return
            try:
                ssl_ctx_factory = DefaultOpenSSLContextFactory(cert_path, cert_path)
            except Exception:
                log.exception('Creating TLS context')
                log.err()
                return
            if cert_chain_path is not None:
                if not os.path.isfile(cert_chain_path):
                    log.error('Certificate chain file %s could not be found' % cert_chain_path)
                    return
                ssl_ctx = ssl_ctx_factory.getContext()
                try:
                    ssl_ctx.use_certificate_chain_file(cert_chain_path)
                except Exception:
                    log.exception('Setting TLS certificate chain file')
                    log.err()
                    return
            self.listener = reactor.listenSSL(port, self.site, ssl_ctx_factory, backlog=511, interface=interface)
            scheme = 'https'
        else:
            self.listener = reactor.listenTCP(port, self.site, backlog=511, interface=interface)
            scheme = 'http'
        port = self.listener.getHost().port
        self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname or interface.normalized, port)
        log.msg('Web server listening for requests on: %s' % self.url)

Example 34

View license
def HttpdStart(session):
	if config.OpenWebif.enabled.value == True:
		global listener
		port = config.OpenWebif.port.value

		temproot = buildRootTree(session)
		root = temproot
		if config.OpenWebif.auth.value == True:
			root = AuthResource(session, root)
		site = server.Site(root)

		# start http webserver on configured port
		try:
			if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
				# use ipv6
				listener.append( reactor.listenTCP(port, site, interface='::') )
			else:
				# ipv4 only
				listener.append( reactor.listenTCP(port, site) )
			print "[OpenWebif] started on %i"% (port)
			BJregisterService('http',port)
		except CannotListenError:
			print "[OpenWebif] failed to listen on Port %i" % (port)

		if config.OpenWebif.https_clientcert.value == True and not os.path.exists(CA_FILE):
			# Disable https
			config.OpenWebif.https_enabled.value = False
			config.OpenWebif.https_enabled.save()
			# Inform the user
			session.open(MessageBox, "Cannot read CA certs for HTTPS access\nHTTPS access is disabled!", MessageBox.TYPE_ERROR)

		if config.OpenWebif.https_enabled.value == True:
			httpsPort = config.OpenWebif.https_port.value
			installCertificates(session)
			# start https webserver on port configured port
			try:
				try:
					context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE)
				except:
					# THIS EXCEPTION IS ONLY CATCHED WHEN CERT FILES ARE BAD (look below for error)
					print "[OpenWebif] failed to get valid cert files. (It could occure bad file save or format, removing...)"
					# removing bad files
					if os.path.exists(KEY_FILE):
						os.remove(KEY_FILE)
					if os.path.exists(CERT_FILE):
						os.remove(CERT_FILE)
					# regenerate new ones
					installCertificates(session)
					context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE)

				if config.OpenWebif.https_clientcert.value == True:
					ctx = context.getContext()
					ctx.set_verify(
						SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
						verifyCallback
						)
					ctx.load_verify_locations(CA_FILE)

				sslroot = temproot
				if config.OpenWebif.https_auth.value == True:
					sslroot = AuthResource(session, sslroot)
				sslsite = server.Site(sslroot)

				if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
					# use ipv6
					listener.append( reactor.listenSSL(httpsPort, sslsite, context, interface='::') )
				else:
					# ipv4 only
					listener.append( reactor.listenSSL(httpsPort, sslsite, context) )
				print "[OpenWebif] started on", httpsPort
				BJregisterService('https',httpsPort)
			except CannotListenError:
				print "[OpenWebif] failed to listen on Port", httpsPort
			except:
				print "[OpenWebif] failed to start https, disabling..."
				# Disable https
				config.OpenWebif.https_enabled.value = False
				config.OpenWebif.https_enabled.save()

		#Streaming requires listening on 127.0.0.1:80
		if port != 80:
			try:
				if has_ipv6 and fileExists('/proc/net/if_inet6') and version.major >= 12:
					# use ipv6
					# Dear Twisted devs: Learning English, lesson 1 - interface != address
					listener.append( reactor.listenTCP(80, site, interface='::1') )
					listener.append( reactor.listenTCP(80, site, interface='::ffff:127.0.0.1') )
				else:
					# ipv4 only
					listener.append( reactor.listenTCP(80, site, interface='127.0.0.1') )
				print "[OpenWebif] started stream listening on port 80"
			except CannotListenError:
				print "[OpenWebif] port 80 busy"

Example 35

Project: Piped
Source File: smtp_provider.py
View license
    def configure(self, runtime_environment):
        self.runtime_environment = runtime_environment

        dependency_manager = runtime_environment.dependency_manager
        self.processor_dependency = dependency_manager.add_dependency(self, self.processor_config)

        smtp_portal = None
        if self.checker:
            Checker = reflect.namedAny(self.checker['name'])
            checker = Checker(**self.checker.get('arguments', dict()))

            smtp_portal = portal.Portal(PipedSMTPRealm(server=self))
            smtp_portal.registerChecker(checker)

        if self.tls:
            from twisted.internet import ssl
            self.context_factory = ssl.DefaultOpenSSLContextFactory(
                privateKeyFileName=util.expand_filepath(self.tls['private_key']),
                certificateFileName=util.expand_filepath(self.tls['certificate'])
            )

        self.server_factory = PipedSMTPServerFactory(self, portal=smtp_portal)

        for listen in self.listen:
            server = strports.service(listen, self.server_factory)
            server.setServiceParent(self)

Example 36

Project: mythbox
Source File: test_tls.py
View license
    def test_handshake(self):
        """
        The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
        connected to a transport.
        """
        clientFactory = ClientFactory()
        clientFactory.protocol = Protocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Only wait for the handshake to complete.  Anything after that isn't
        # important here.
        return handshakeDeferred

Example 37

Project: mythbox
Source File: test_tls.py
View license
    def test_getPeerCertificate(self):
        """
        L{TLSMemoryBIOFactory.getPeerCertificate} returns the
        L{OpenSSL.crypto.X509Type} instance representing the peer's
        certificate.
        """
        # Set up a client and server so there's a certificate to grab.
        clientFactory = ClientFactory()
        clientFactory.protocol = Protocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(
            sslServerProtocol, sslClientProtocol)

        # Wait for the handshake
        def cbHandshook(ignored):
            # Grab the server's certificate and check it out
            cert = sslClientProtocol.getPeerCertificate()
            self.assertIsInstance(cert, X509Type)
            self.assertEquals(
                cert.digest('md5'),
                '9B:A4:AB:43:10:BE:82:AE:94:3E:6B:91:F2:F3:40:E8')
        handshakeDeferred.addCallback(cbHandshook)
        return handshakeDeferred

Example 38

Project: mythbox
Source File: test_tls.py
View license
    def test_writeAfterHandshake(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
        complete are received by the protocol on the other side of the
        connection once the handshake succeeds.
        """
        bytes = "some bytes"

        clientProtocol = Protocol()
        clientFactory = ClientFactory()
        clientFactory.protocol = lambda: clientProtocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the handshake to finish before writing anything.
        def cbHandshook(ignored):
            clientProtocol.transport.write(bytes)

            # The server will drop the connection once it gets the bytes.
            return connectionDeferred
        handshakeDeferred.addCallback(cbHandshook)

        # Once the connection is lost, make sure the server received the
        # expected bytes.
        def cbDisconnected(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        handshakeDeferred.addCallback(cbDisconnected)

        return handshakeDeferred

Example 39

Project: mythbox
Source File: test_tls.py
View license
    def test_writeBeforeHandshake(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
        complete are received by the protocol on the other side of the
        connection once the handshake succeeds.
        """
        bytes = "some bytes"

        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.write(bytes)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 40

Project: mythbox
Source File: test_tls.py
View license
    def test_writeSequence(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
        received by the protocol on the other side of the connection.
        """
        bytes = "some bytes"
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.writeSequence(list(bytes))

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 41

Project: mythbox
Source File: test_tls.py
View license
    def test_multipleWrites(self):
        """
        If multiple separate TLS messages are received in a single chunk from
        the underlying transport, all of the application bytes from each
        message are delivered to the application-level protocol.
        """
        bytes = [str(i) for i in range(10)]
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                for b in bytes:
                    self.transport.write(b)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(sum(map(len, bytes)))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol, collapsingPumpPolicy)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), ''.join(bytes))
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 42

Project: mythbox
Source File: test_tls.py
View license
    def test_hugeWrite(self):
        """
        If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any
        trailing part of it which cannot be send immediately is buffered and
        sent later.
        """
        bytes = "some bytes"
        factor = 8192
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.write(bytes * factor)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes) * factor)
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes * factor)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 43

Project: mythbox
Source File: test_tls.py
View license
    def test_loseConnectionAfterHandshake(self):
        """
        L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and
        shuts down the underlying connection.
        """
        clientConnectionLost = Deferred()
        clientFactory = ClientFactory()
        clientFactory.protocol = (
            lambda: ConnectionLostNotifyingProtocol(
                clientConnectionLost))

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = Protocol()
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the handshake before dropping the connection.
        def cbHandshake(ignored):
            serverProtocol.transport.loseConnection()

            # Now wait for the client to notice.
            return clientConnectionLost
        handshakeDeferred.addCallback(cbHandshake)

        # Wait for the connection to end, then make sure the client was
        # notified of a handshake failure.
        def cbConnectionDone(clientProtocol):
            clientProtocol.lostConnectionReason.trap(ConnectionDone)

            # The server should have closed its underlying transport, in
            # addition to whatever it did to shut down the TLS layer.
            self.assertTrue(serverProtocol.transport.q.disconnect)

            # The client should also have closed its underlying transport once
            # it saw the server shut down the TLS layer, so as to avoid relying
            # on the server to close the underlying connection.
            self.assertTrue(clientProtocol.transport.q.disconnect)
        handshakeDeferred.addCallback(cbConnectionDone)
        return handshakeDeferred

Example 44

Project: mythbox
Source File: test_tls.py
View license
    def test_handshake(self):
        """
        The TLS handshake is performed when L{TLSMemoryBIOProtocol} is
        connected to a transport.
        """
        clientFactory = ClientFactory()
        clientFactory.protocol = Protocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Only wait for the handshake to complete.  Anything after that isn't
        # important here.
        return handshakeDeferred

Example 45

Project: mythbox
Source File: test_tls.py
View license
    def test_getPeerCertificate(self):
        """
        L{TLSMemoryBIOFactory.getPeerCertificate} returns the
        L{OpenSSL.crypto.X509Type} instance representing the peer's
        certificate.
        """
        # Set up a client and server so there's a certificate to grab.
        clientFactory = ClientFactory()
        clientFactory.protocol = Protocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverFactory = ServerFactory()
        serverFactory.protocol = Protocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(
            sslServerProtocol, sslClientProtocol)

        # Wait for the handshake
        def cbHandshook(ignored):
            # Grab the server's certificate and check it out
            cert = sslClientProtocol.getPeerCertificate()
            self.assertIsInstance(cert, X509Type)
            self.assertEquals(
                cert.digest('md5'),
                '9B:A4:AB:43:10:BE:82:AE:94:3E:6B:91:F2:F3:40:E8')
        handshakeDeferred.addCallback(cbHandshook)
        return handshakeDeferred

Example 46

Project: mythbox
Source File: test_tls.py
View license
    def test_writeAfterHandshake(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
        complete are received by the protocol on the other side of the
        connection once the handshake succeeds.
        """
        bytes = "some bytes"

        clientProtocol = Protocol()
        clientFactory = ClientFactory()
        clientFactory.protocol = lambda: clientProtocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the handshake to finish before writing anything.
        def cbHandshook(ignored):
            clientProtocol.transport.write(bytes)

            # The server will drop the connection once it gets the bytes.
            return connectionDeferred
        handshakeDeferred.addCallback(cbHandshook)

        # Once the connection is lost, make sure the server received the
        # expected bytes.
        def cbDisconnected(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        handshakeDeferred.addCallback(cbDisconnected)

        return handshakeDeferred

Example 47

Project: mythbox
Source File: test_tls.py
View license
    def test_writeBeforeHandshake(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
        complete are received by the protocol on the other side of the
        connection once the handshake succeeds.
        """
        bytes = "some bytes"

        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.write(bytes)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory, handshakeDeferred = (
            HandshakeCallbackContextFactory.factoryAndDeferred())
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 48

Project: mythbox
Source File: test_tls.py
View license
    def test_writeSequence(self):
        """
        Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are
        received by the protocol on the other side of the connection.
        """
        bytes = "some bytes"
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.writeSequence(list(bytes))

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 49

Project: mythbox
Source File: test_tls.py
View license
    def test_multipleWrites(self):
        """
        If multiple separate TLS messages are received in a single chunk from
        the underlying transport, all of the application bytes from each
        message are delivered to the application-level protocol.
        """
        bytes = [str(i) for i in range(10)]
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                for b in bytes:
                    self.transport.write(b)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(sum(map(len, bytes)))
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol, collapsingPumpPolicy)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), ''.join(bytes))
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred

Example 50

Project: mythbox
Source File: test_tls.py
View license
    def test_hugeWrite(self):
        """
        If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any
        trailing part of it which cannot be send immediately is buffered and
        sent later.
        """
        bytes = "some bytes"
        factor = 8192
        class SimpleSendingProtocol(Protocol):
            def connectionMade(self):
                self.transport.write(bytes * factor)

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

        clientContextFactory = HandshakeCallbackContextFactory()
        wrapperFactory = TLSMemoryBIOFactory(
            clientContextFactory, True, clientFactory)
        sslClientProtocol = wrapperFactory.buildProtocol(None)

        serverProtocol = AccumulatingProtocol(len(bytes) * factor)
        serverFactory = ServerFactory()
        serverFactory.protocol = lambda: serverProtocol

        serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath)
        wrapperFactory = TLSMemoryBIOFactory(
            serverContextFactory, False, serverFactory)
        sslServerProtocol = wrapperFactory.buildProtocol(None)

        connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)

        # Wait for the connection to end, then make sure the server received
        # the bytes sent by the client.
        def cbConnectionDone(ignored):
            self.assertEquals("".join(serverProtocol.received), bytes * factor)
        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred