Python twisted.internet.protocol.Factory() Examples
The following are 30
code examples of twisted.internet.protocol.Factory().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
twisted.internet.protocol
, or try the search function
.
Example #1
Source File: test_stringtransport.py From python-for-android with Apache License 2.0 | 6 votes |
def test_listenDefaultHost(self): """ L{MemoryReactor.listenTCP}, L{MemoryReactor.listenSSL} and L{MemoryReactor.listenUNIX} will return an L{IListeningPort} whose C{getHost} method returns an L{IAddress}; C{listenTCP} and C{listenSSL} will have a default host of C{'0.0.0.0'}, and a port that reflects the value passed, and C{listenUNIX} will have a name that reflects the path passed. """ memoryReactor = MemoryReactor() for port in [memoryReactor.listenTCP(8242, Factory()), memoryReactor.listenSSL(8242, Factory(), None)]: verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEquals(address.host, '0.0.0.0') self.assertEquals(address.port, 8242) port = memoryReactor.listenUNIX("/path/to/socket", Factory()) verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEquals(address.name, "/path/to/socket")
Example #2
Source File: test_endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_deferBadEncodingToConnect(self): """ Since any client of L{IStreamClientEndpoint} needs to handle Deferred failures from C{connect}, L{HostnameEndpoint}'s constructor will not raise exceptions when given bad host names, instead deferring to returning a failing L{Deferred} from C{connect}. """ endpoint = endpoints.HostnameEndpoint( deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']), b'\xff-garbage-\xff', 80 ) deferred = endpoint.connect(Factory.forProtocol(Protocol)) err = self.failureResultOf(deferred, ValueError) self.assertIn("\\xff-garbage-\\xff", str(err)) endpoint = endpoints.HostnameEndpoint( deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']), u'\u2ff0-garbage-\u2ff0', 80 ) deferred = endpoint.connect(Factory()) err = self.failureResultOf(deferred, ValueError) self.assertIn("\\u2ff0-garbage-\\u2ff0", str(err))
Example #3
Source File: test_stringtransport.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_listenDefaultHost(self): """ L{MemoryReactor.listenTCP}, L{MemoryReactor.listenSSL} and L{MemoryReactor.listenUNIX} will return an L{IListeningPort} whose C{getHost} method returns an L{IAddress}; C{listenTCP} and C{listenSSL} will have a default host of C{'0.0.0.0'}, and a port that reflects the value passed, and C{listenUNIX} will have a name that reflects the path passed. """ memoryReactor = MemoryReactor() for port in [memoryReactor.listenTCP(8242, Factory()), memoryReactor.listenSSL(8242, Factory(), None)]: verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.host, '0.0.0.0') self.assertEqual(address.port, 8242) port = memoryReactor.listenUNIX(b"/path/to/socket", Factory()) verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.name, b"/path/to/socket")
Example #4
Source File: factory.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def buildProtocol(self, addr): """ Create an instance of the server side of the SSH protocol. @type addr: L{twisted.internet.interfaces.IAddress} provider @param addr: The address at which the server will listen. @rtype: L{twisted.conch.ssh.transport.SSHServerTransport} @return: The built transport. """ t = protocol.Factory.buildProtocol(self, addr) t.supportedPublicKeys = self.privateKeys.keys() if not self.primes: log.msg('disabling non-fixed-group key exchange algorithms ' 'because we cannot find moduli file') t.supportedKeyExchanges = [ kexAlgorithm for kexAlgorithm in t.supportedKeyExchanges if _kex.isFixedGroup(kexAlgorithm) or _kex.isEllipticCurve(kexAlgorithm)] return t
Example #5
Source File: endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def connect(self, protocolFactory): """ Set up an SSH connection, use a channel from that connection to launch a command, and hook the stdin and stdout of that command up as a transport for a protocol created by the given factory. @param protocolFactory: A L{Factory} to use to create the protocol which will be connected to the stdin and stdout of the command on the SSH server. @return: A L{Deferred} which will fire with an error if the connection cannot be set up for any reason or with the protocol instance created by C{protocolFactory} once it has been connected to the command. """ d = self._creator.secureConnection() d.addCallback(self._executeCommand, protocolFactory) return d
Example #6
Source File: endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def connectToAgent(self, endpoint): """ Set up a connection to the authentication agent and trigger its initialization. @param endpoint: An endpoint which can be used to connect to the authentication agent. @type endpoint: L{IStreamClientEndpoint} provider @return: A L{Deferred} which fires when the agent connection is ready for use. """ factory = Factory() factory.protocol = SSHAgentClient d = endpoint.connect(factory) def connected(agent): self.agent = agent return agent.getPublicKeys() d.addCallback(connected) return d
Example #7
Source File: endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def connectProtocol(endpoint, protocol): """ Connect a protocol instance to an endpoint. This allows using a client endpoint without having to create a factory. @param endpoint: A client endpoint to connect to. @param protocol: A protocol instance. @return: The result of calling C{connect} on the endpoint, i.e. a L{Deferred} that will fire with the protocol when connected, or an appropriate error. @since: 13.1 """ class OneShotFactory(Factory): def buildProtocol(self, addr): return protocol return endpoint.connect(OneShotFactory())
Example #8
Source File: test_endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_processAddress(self): """ The address passed to the factory's buildProtocol in the endpoint is a _ProcessAddress instance. """ class TestAddrFactory(protocol.Factory): protocol = StubApplicationProtocol address = None def buildProtocol(self, addr): self.address = addr p = self.protocol() p.factory = self return p myFactory = TestAddrFactory() d = self.ep.connect(myFactory) self.successResultOf(d) self.assertIsInstance(myFactory.address, _ProcessAddress)
Example #9
Source File: test_endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_connectProtocolCreatesFactory(self): """ C{endpoints.connectProtocol} calls the given endpoint's C{connect()} method with a factory that will build the given protocol. """ reactor = MemoryReactor() endpoint = endpoints.TCP4ClientEndpoint(reactor, "127.0.0.1", 0) theProtocol = object() endpoints.connectProtocol(endpoint, theProtocol) # A TCP connection was made via the given endpoint: self.assertEqual(len(reactor.tcpClients), 1) # TCP4ClientEndpoint uses a _WrapperFactory around the underlying # factory, so we need to unwrap it: factory = reactor.tcpClients[0][2]._wrappedFactory self.assertIsInstance(factory, protocol.Factory) self.assertIs(factory.buildProtocol(None), theProtocol)
Example #10
Source File: test_tcp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def testWriter(self): f = protocol.Factory() f.protocol = LargeBufferWriterProtocol f.done = 0 f.problem = 0 f.len = self.datalen wrappedF = FireOnCloseFactory(f) p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1") self.addCleanup(p.stopListening) n = p.getHost().port clientF = LargeBufferReaderClientFactory() wrappedClientF = FireOnCloseFactory(clientF) reactor.connectTCP("127.0.0.1", n, wrappedClientF) d = defer.gatherResults([wrappedF.deferred, wrappedClientF.deferred]) def check(ignored): self.assertTrue(f.done, "writer didn't finish, it probably died") self.assertTrue(clientF.len == self.datalen, "client didn't receive all the data it expected " "(%d != %d)" % (clientF.len, self.datalen)) self.assertTrue(clientF.done, "client didn't see connection dropped") return d.addCallback(check)
Example #11
Source File: test_ftp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_portRange(self): """ L{FTP.passivePortRange} should determine the ports which L{FTP.getDTPPort} attempts to bind. If no port from that iterator can be bound, L{error.CannotListenError} should be raised, otherwise the first successful result from L{FTP.listenFactory} should be returned. """ def listenFactory(portNumber, factory): if portNumber in (22032, 22033, 22034): raise error.CannotListenError('localhost', portNumber, 'error') return portNumber self.serverProtocol.listenFactory = listenFactory port = self.serverProtocol.getDTPPort(protocol.Factory()) self.assertEqual(port, 0) self.serverProtocol.passivePortRange = xrange(22032, 65536) port = self.serverProtocol.getDTPPort(protocol.Factory()) self.assertEqual(port, 22035) self.serverProtocol.passivePortRange = xrange(22032, 22035) self.assertRaises(error.CannotListenError, self.serverProtocol.getDTPPort, protocol.Factory())
Example #12
Source File: test_strports.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_service(self): """ L{strports.service} returns a L{StreamServerEndpointService} constructed with an endpoint produced from L{endpoint.serverFromString}, using the same syntax. """ reactor = object() # the cake is a lie aFactory = Factory() aGoodPort = 1337 svc = strports.service( 'tcp:' + str(aGoodPort), aFactory, reactor=reactor) self.assertIsInstance(svc, internet.StreamServerEndpointService) # See twisted.application.test.test_internet.EndpointServiceTests. # test_synchronousRaiseRaisesSynchronously self.assertTrue(svc._raiseSynchronously) self.assertIsInstance(svc.endpoint, TCP4ServerEndpoint) # Maybe we should implement equality for endpoints. self.assertEqual(svc.endpoint._port, aGoodPort) self.assertIs(svc.factory, aFactory) self.assertIs(svc.endpoint._reactor, reactor)
Example #13
Source File: test_gaiendpoint.py From ccs-twistedextensions with Apache License 2.0 | 6 votes |
def test_simpleSuccess(self): """ If C{getaddrinfo} gives one L{GAIEndpoint.connect}. """ gaiendpoint = self.makeEndpoint() protos = [] f = Factory() f.protocol = Protocol gaiendpoint.connect(f).addCallback(protos.append) WHO_CARES = 0 WHAT_EVER = "" self.gaiResult(AF_INET, SOCK_STREAM, WHO_CARES, WHAT_EVER, ("1.2.3.4", 4321)) self.clock.advance(1.0) attempt = self.fakeRealEndpoints[0]._attempt attempt.callback(self.fakeRealEndpoints[0]._factory.buildProtocol(None)) self.assertEqual(len(protos), 1)
Example #14
Source File: test_endpoint.py From txacme with MIT License | 6 votes |
def test_listen_starts_service(self): """ ``AutoTLSEndpoint.listen`` starts an ``AcmeIssuingService``. Stopping the port stops the service. """ factory = Factory() d = self.endpoint.listen(factory) self.assertThat( d, succeeded( MatchesPredicate( IListeningPort.providedBy, '%r does not provide IListeningPort'))) port = d.result self.assertThat( self.endpoint.service, MatchesStructure(running=Equals(True))) self.assertThat(port.stopListening(), succeeded(Always())) self.assertThat( self.endpoint.service, MatchesStructure(running=Equals(False)))
Example #15
Source File: endpoints.py From learn_python3_spider with MIT License | 6 votes |
def connectProtocol(endpoint, protocol): """ Connect a protocol instance to an endpoint. This allows using a client endpoint without having to create a factory. @param endpoint: A client endpoint to connect to. @param protocol: A protocol instance. @return: The result of calling C{connect} on the endpoint, i.e. a L{Deferred} that will fire with the protocol when connected, or an appropriate error. @since: 13.1 """ class OneShotFactory(Factory): def buildProtocol(self, addr): return protocol return endpoint.connect(OneShotFactory())
Example #16
Source File: Engine.py From Timeline with GNU General Public License v3.0 | 6 votes |
def __init__(self, protocol, _type, _id, name="World Server 1", _max=300, server_protocol = AS3_PROTOCOL): self.protocol = protocol self.server_protocol = server_protocol self.type = _type self.id = _id self.logger = logging.getLogger(TIMELINE_LOGGER) self.name = name self.users = deque() # Thread safe self.dbDetails = dict() self.maximum = _max - 1 self._listening = False self._portListener = None self.proxyReference = weakref.proxy(self) self.redis = Redis(self) self.log("info", "Timeline Factory Started!") self.log("info", "Running:", self.name) self.log("info", "Maximum users:", self.maximum) if self.type == WORLD_SERVER: self.initializeWorld() self.redis.redisConnectionDefer.addCallback(lambda *x: GeneralEvent('onEngine', self))
Example #17
Source File: test_endpoints.py From learn_python3_spider with MIT License | 6 votes |
def test_deferBadEncodingToConnect(self): """ Since any client of L{IStreamClientEndpoint} needs to handle Deferred failures from C{connect}, L{HostnameEndpoint}'s constructor will not raise exceptions when given bad host names, instead deferring to returning a failing L{Deferred} from C{connect}. """ endpoint = endpoints.HostnameEndpoint( deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']), b'\xff-garbage-\xff', 80 ) deferred = endpoint.connect(Factory.forProtocol(Protocol)) err = self.failureResultOf(deferred, ValueError) self.assertIn("\\xff-garbage-\\xff", str(err)) endpoint = endpoints.HostnameEndpoint( deterministicResolvingReactor(MemoryReactor(), ['127.0.0.1']), u'\u2ff0-garbage-\u2ff0', 80 ) deferred = endpoint.connect(Factory()) err = self.failureResultOf(deferred, ValueError) self.assertIn("\\u2ff0-garbage-\\u2ff0", str(err))
Example #18
Source File: test_endpoints.py From learn_python3_spider with MIT License | 6 votes |
def test_connectProtocolCreatesFactory(self): """ C{endpoints.connectProtocol} calls the given endpoint's C{connect()} method with a factory that will build the given protocol. """ reactor = MemoryReactor() endpoint = endpoints.TCP4ClientEndpoint(reactor, "127.0.0.1", 0) theProtocol = object() endpoints.connectProtocol(endpoint, theProtocol) # A TCP connection was made via the given endpoint: self.assertEqual(len(reactor.tcpClients), 1) # TCP4ClientEndpoint uses a _WrapperFactory around the underlying # factory, so we need to unwrap it: factory = reactor.tcpClients[0][2]._wrappedFactory self.assertIsInstance(factory, protocol.Factory) self.assertIs(factory.buildProtocol(None), theProtocol)
Example #19
Source File: test_testing.py From learn_python3_spider with MIT License | 6 votes |
def test_listenDefaultHost(self): """ L{MemoryReactor.listenTCP}, L{MemoryReactor.listenSSL} and L{MemoryReactor.listenUNIX} will return an L{IListeningPort} whose C{getHost} method returns an L{IAddress}; C{listenTCP} and C{listenSSL} will have a default host of C{'0.0.0.0'}, and a port that reflects the value passed, and C{listenUNIX} will have a name that reflects the path passed. """ memoryReactor = MemoryReactor() for port in [memoryReactor.listenTCP(8242, Factory()), memoryReactor.listenSSL(8242, Factory(), None)]: verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.host, '0.0.0.0') self.assertEqual(address.port, 8242) port = memoryReactor.listenUNIX(b"/path/to/socket", Factory()) verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.name, b"/path/to/socket")
Example #20
Source File: loopback.py From learn_python3_spider with MIT License | 6 votes |
def loopbackUNIX(server, client, noisy=True): """Run session between server and client protocol instances over UNIX socket.""" path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = lambda addr: serverWrapper serverPort = reactor.listenUNIX(path, f) clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectUNIX(path, clientF) d = clientF.deferred d.addCallback(lambda x: serverWrapper.deferred) d.addCallback(lambda x: serverPort.stopListening()) return d
Example #21
Source File: endpoints.py From learn_python3_spider with MIT License | 6 votes |
def connectToAgent(self, endpoint): """ Set up a connection to the authentication agent and trigger its initialization. @param endpoint: An endpoint which can be used to connect to the authentication agent. @type endpoint: L{IStreamClientEndpoint} provider @return: A L{Deferred} which fires when the agent connection is ready for use. """ factory = Factory() factory.protocol = SSHAgentClient d = endpoint.connect(factory) def connected(agent): self.agent = agent return agent.getPublicKeys() d.addCallback(connected) return d
Example #22
Source File: endpoints.py From learn_python3_spider with MIT License | 6 votes |
def connect(self, protocolFactory): """ Set up an SSH connection, use a channel from that connection to launch a command, and hook the stdin and stdout of that command up as a transport for a protocol created by the given factory. @param protocolFactory: A L{Factory} to use to create the protocol which will be connected to the stdin and stdout of the command on the SSH server. @return: A L{Deferred} which will fire with an error if the connection cannot be set up for any reason or with the protocol instance created by C{protocolFactory} once it has been connected to the command. """ d = self._creator.secureConnection() d.addCallback(self._executeCommand, protocolFactory) return d
Example #23
Source File: factory.py From learn_python3_spider with MIT License | 6 votes |
def buildProtocol(self, addr): """ Create an instance of the server side of the SSH protocol. @type addr: L{twisted.internet.interfaces.IAddress} provider @param addr: The address at which the server will listen. @rtype: L{twisted.conch.ssh.transport.SSHServerTransport} @return: The built transport. """ t = protocol.Factory.buildProtocol(self, addr) t.supportedPublicKeys = self.privateKeys.keys() if not self.primes: log.msg('disabling non-fixed-group key exchange algorithms ' 'because we cannot find moduli file') t.supportedKeyExchanges = [ kexAlgorithm for kexAlgorithm in t.supportedKeyExchanges if _kex.isFixedGroup(kexAlgorithm) or _kex.isEllipticCurve(kexAlgorithm)] return t
Example #24
Source File: test_ftp.py From learn_python3_spider with MIT License | 6 votes |
def test_PORTCannotConnect(self): """ Listen on a port, and immediately stop listening as a way to find a port number that is definitely closed. """ # Login d = self._anonymousLogin() def loggedIn(ignored): port = reactor.listenTCP(0, protocol.Factory(), interface='127.0.0.1') portNum = port.getHost().port d = port.stopListening() d.addCallback(lambda _: portNum) return d d.addCallback(loggedIn) # Tell the server to connect to that port with a PORT command, and # verify that it fails with the right error. def gotPortNum(portNum): return self.assertCommandFailed( 'PORT ' + ftp.encodeHostPort('127.0.0.1', portNum), ["425 Can't open data connection."]) return d.addCallback(gotPortNum)
Example #25
Source File: test_strports.py From learn_python3_spider with MIT License | 6 votes |
def test_service(self): """ L{strports.service} returns a L{StreamServerEndpointService} constructed with an endpoint produced from L{endpoint.serverFromString}, using the same syntax. """ reactor = object() # the cake is a lie aFactory = Factory() aGoodPort = 1337 svc = strports.service( 'tcp:' + str(aGoodPort), aFactory, reactor=reactor) self.assertIsInstance(svc, internet.StreamServerEndpointService) # See twisted.application.test.test_internet.EndpointServiceTests. # test_synchronousRaiseRaisesSynchronously self.assertTrue(svc._raiseSynchronously) self.assertIsInstance(svc.endpoint, TCP4ServerEndpoint) # Maybe we should implement equality for endpoints. self.assertEqual(svc.endpoint._port, aGoodPort) self.assertIs(svc.factory, aFactory) self.assertIs(svc.endpoint._reactor, reactor)
Example #26
Source File: __init__.py From opencanary with BSD 3-Clause "New" or "Revised" License | 6 votes |
def getService(self): """Return service to be run This handles the easy case where the CanaryService class is also the Factory/Datagram class. Subclasses should override this if more intricracy is needed. """ if isinstance(self, Factory): return internet.TCPServer(self.port, self) elif isinstance(self, DatagramProtocol): return internet.UDPServer(self.port, self) err = 'The class %s does not inherit from either Factory or DatagramProtocol.' % ( self.__class__.__name__ ) raise Exception(err)
Example #27
Source File: ssh.py From tensor with MIT License | 6 votes |
def connect(self): log.msg("Opening SSH connection to %s@%s:%s" % ( self.username, self.hostname, self.port)) self.endpoint = self._get_endpoint() factory = protocol.Factory() factory.protocol = protocol.Protocol def connected(protocol): log.msg("Established SSH connection to %s" % ( self.hostname,)) self.connection = protocol.transport.conn d = self.endpoint.connect(factory) d.addCallback(connected) return d
Example #28
Source File: loopback.py From python-for-android with Apache License 2.0 | 6 votes |
def loopbackUNIX(server, client, noisy=True): """Run session between server and client protocol instances over UNIX socket.""" path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = lambda addr: serverWrapper serverPort = reactor.listenUNIX(path, f) clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectUNIX(path, clientF) d = clientF.deferred d.addCallback(lambda x: serverWrapper.deferred) d.addCallback(lambda x: serverPort.stopListening()) return d
Example #29
Source File: test_endpoints.py From learn_python3_spider with MIT License | 6 votes |
def test_processAddress(self): """ The address passed to the factory's buildProtocol in the endpoint is a _ProcessAddress instance. """ class TestAddrFactory(protocol.Factory): protocol = StubApplicationProtocol address = None def buildProtocol(self, addr): self.address = addr p = self.protocol() p.factory = self return p myFactory = TestAddrFactory() d = self.ep.connect(myFactory) self.successResultOf(d) self.assertIsInstance(myFactory.address, _ProcessAddress)
Example #30
Source File: test_endpoints.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def setUp(self): self.reactor = MemoryProcessReactor() self.endpoint = endpoints.ProcessEndpoint(self.reactor, b'/bin/executable') protocol = self.successResultOf( self.endpoint.connect(Factory.forProtocol(Protocol)) ) self.process = self.reactor.processTransport self.endpointTransport = protocol.transport