def main(): P = OptionParser(usage="%prog [-C|-S] <-v> host:port") P.add_option('-v','--verbose', action='count', default=0, help='Print more information') P.add_option('-C','--client', action='store_true', default=True, dest='dir', help='Act as Client to PSC') P.add_option('-S','--server', action='store_false', dest='dir', help='Act as Server to IOC') vals, args = P.parse_args() if len(args)<1: P.usage() sys.exit(1) host, _, port = args[0].partition(':') port = int(port or '6') logging.basicConfig(level=_V.get(vals.verbose, 0)) if vals.dir: # Client log.info('Connect to %s:%u', host, port) fact = ClientFactory() fact.protocol = PSCClient ep = reactor.connectTCP(host, port, fact) else: # Server log.info('Serve from %s:%u', host, port) fact = Factory() fact.protocol = PSCServer ep = reactor.listenTCP(port, fact, interface=host or '') log.info('Run') reactor.run() log.info('Done')
def test_disconnectWhileProducing(self): """ If C{loseConnection} is called while a producer is registered with the transport, the connection is closed after the producer is unregistered. """ reactor = self.buildReactor() # For some reason, pyobject/pygtk will not deliver the close # notification that should happen after the unregisterProducer call in # this test. The selectable is in the write notification set, but no # notification ever arrives. Probably for the same reason #5233 led # win32eventreactor to be broken. skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest("A pygobject/pygtk bug disables this functionality " "on Windows.") class Producer: def resumeProducing(self): log.msg("Producer.resumeProducing") self.listen(reactor, ServerFactory.forProtocol(Protocol)) finished = Deferred() finished.addErrback(log.err) finished.addCallback(lambda ign: reactor.stop()) class ClientProtocol(Protocol): """ Protocol to connect, register a producer, try to lose the connection, unregister the producer, and wait for the connection to actually be lost. """ def connectionMade(self): log.msg("ClientProtocol.connectionMade") self.transport.registerProducer(Producer(), False) self.transport.loseConnection() # Let the reactor tick over, in case synchronously calling # loseConnection and then unregisterProducer is the same as # synchronously calling unregisterProducer and then # loseConnection (as it is in several reactors). reactor.callLater(0, reactor.callLater, 0, self.unregister) def unregister(self): log.msg("ClientProtocol unregister") self.transport.unregisterProducer() # This should all be pretty quick. Fail the test # if we don't get a connectionLost event really # soon. reactor.callLater(1.0, finished.errback, Failure(Exception("Connection was not lost"))) def connectionLost(self, reason): log.msg("ClientProtocol.connectionLost") finished.callback(None) clientFactory = ClientFactory() clientFactory.protocol = ClientProtocol self.connect(reactor, clientFactory) self.runReactor(reactor)
def dataReceived(self, data): _q_s.logs.info([ "servers", { 'server': 'http_proxy_server', 'action': 'connection', 'ip': self.transport.getPeer().host, 'port': self.transport.getPeer().port } ]) try: ip = self.resolve_domain(data) if ip: factory = ClientFactory() factory.CustomProtocolParent_ = self factory.protocol = CustomProtocolChild reactor.connectTCP(ip, 80, factory) else: self.transport.loseConnection() if self.client: self.client.write(data) else: self.buffer = data except: pass
def getOpenFlowClientFactory(self): f = ClientFactory() f.protocol = OpenFlowClientProtocol f.add_controllerConnection = self.add_controllerConnection f.handle_controller_openflow_msg = self.handle_controller_openflow_msg f.remove_controllerConnection = self.remove_controllerConnection return f
def testGetPolicyFile(self): class PolicyRequest(Protocol): def __init__(self, deffered): self.done = deffered def connectionMade(self): request = "<policy-file-request/>%c" % (0, ) self.transport.write(request) def dataReceived(self, data): self.transport.loseConnection() self.done.callback(data) d = defer.Deferred() factory = ClientFactory() factory.protocol = lambda : PolicyRequest(d) port = self.listener._realPortNumber reactor.connectTCP('127.0.0.1', port, factory) def asserts(received): policy = ( '<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM ' '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">' '<cross-domain-policy><allow-access-from domain="*" ' 'to-ports="*" /></cross-domain-policy>') self.assertEqual(policy, received) d.addCallback(asserts) return d
def test_getLogFiles(self): """ The reactor returned by L{loggedReactor} has a C{getLogFiles} method which returns a L{logstate} instance containing the active and completed log files tracked by the logging wrapper. """ wrapped = ClientFactory() wrapped.protocol = Discard reactor = MemoryReactor() logged = loggedReactor(reactor) logged.connectTCP('127.0.0.1', 1234, wrapped) factory = reactor.tcpClients[0][2] finished = factory.buildProtocol(None) finished.makeConnection(StringTransport()) finished.dataReceived('finished') finished.connectionLost(None) active = factory.buildProtocol(None) active.makeConnection(StringTransport()) active.dataReceived('active') logs = logged.getLogFiles() self.assertEqual(1, len(logs.finished)) self.assertIn('finished', logs.finished[0].getvalue()) self.assertEqual(1, len(logs.active)) self.assertIn('active', logs.active[0].getvalue())
def test_connectTCP(self): """ Called on the object returned by L{loggedReactor}, C{connectTCP} calls the wrapped reactor's C{connectTCP} method with the original factory wrapped in a L{_TrafficLoggingFactory}. """ class RecordDataProtocol(Protocol): def dataReceived(self, data): self.data = data proto = RecordDataProtocol() factory = ClientFactory() factory.protocol = lambda: proto reactor = MemoryReactor() logged = loggedReactor(reactor) logged.connectTCP('192.168.1.2', 1234, factory, 21, '127.0.0.2') [(host, port, factory, timeout, bindAddress)] = reactor.tcpClients self.assertEqual('192.168.1.2', host) self.assertEqual(1234, port) self.assertIsInstance(factory, _TrafficLoggingFactory) self.assertEqual(21, timeout) self.assertEqual('127.0.0.2', bindAddress) # Verify that the factory and protocol specified are really being used protocol = factory.buildProtocol(None) protocol.makeConnection(None) protocol.dataReceived("foo") self.assertEqual(proto.data, "foo")
def test_send_peh_upon_connection(self): '''To test client protocol we isloate it from the ClientFactory''' with patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime)) as patched: fixed_date = datetime.datetime(2014, 1, 1, 12, 0, 0) patched.now.return_value = fixed_date factory = ClientFactory() factory.comaster = self.comaster factory.protocol = MaraClientProtocol proto = factory.buildProtocol(('127.0.0.1', 0)) proto.construct = MaraFrame # Disable unnesesary behaviour def stop(): proto.stop() reactor.stop() proto.sendPoll = MagicMock(side_effect=stop) transport = proto_helpers.StringTransport() proto.makeConnection(transport) bytes_sent_to_device = transport.value() result = MaraFrame.parse(bytes_sent_to_device) self.assertEqual(result.dest, 0xFF) self.assertEqual(result.source, 2) # We don't need to check BCC since it's already coded into MaraFrame self.assertEqual(result.peh, fixed_date) reactor.run() # Shuld have stopped self.assertEqual(self.comaster.update_peh_timestamp.call_count, 1) self.assertEqual(self.comaster.update_peh_timestamp.call_args[0][0], fixed_date)
def test_disorderlyShutdown(self): """ If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is reported to the application. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol(clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) # Client speaks first, so the server can be dumb. serverProtocol = Protocol() connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol) # Now destroy the connection. serverProtocol.transport.loseConnection() # And when the connection completely dies, check the reason. def cbDisconnected(clientProtocol): clientProtocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbDisconnected) return clientConnectionLost
def writeBeforeHandshakeTest(self, sendingProtocol, bytes): """ Run test where client sends data before handshake, given the sending protocol and expected bytes. """ clientFactory = ClientFactory() clientFactory.protocol = sendingProtocol 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.assertEqual("".join(serverProtocol.received), bytes) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred
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
def test_disorderlyShutdown(self): """ If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is reported to the application. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) # Client speaks first, so the server can be dumb. serverProtocol = Protocol() connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol) # Now destroy the connection. serverProtocol.transport.loseConnection() # And when the connection completely dies, check the reason. def cbDisconnected(clientProtocol): clientProtocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbDisconnected) return clientConnectionLost
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
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
def new_protocol_tcp(self): """ Create a new client protocol connected to the server. :returns: a IRelayTestClient implementation """ server_factory = ServerFactory() server_factory.protocol = TransitConnection server_factory.transit = self._transit_server server_factory.log_requests = self.log_requests server_protocol = server_factory.buildProtocol(('127.0.0.1', 0)) @implementer(IRelayTestClient) class TransitClientProtocolTcp(Protocol): """ Speak the transit client protocol used by the tests over TCP """ _received = b"" connected = False # override Protocol callbacks def connectionMade(self): self.connected = True return Protocol.connectionMade(self) def connectionLost(self, reason): self.connected = False return Protocol.connectionLost(self, reason) def dataReceived(self, data): self._received = self._received + data # IRelayTestClient def send(self, data): self.transport.write(data) def disconnect(self): self.transport.loseConnection() def reset_received_data(self): self._received = b"" def get_received_data(self): return self._received client_factory = ClientFactory() client_factory.protocol = TransitClientProtocolTcp client_protocol = client_factory.buildProtocol(('127.0.0.1', 31337)) pump = iosim.connect( server_protocol, iosim.makeFakeServer(server_protocol), client_protocol, iosim.makeFakeClient(client_protocol), ) pump.flush() self._pumps.append(pump) return client_protocol
def getCachedConnection(self): """ Ask the L{conncache.ConnectionCache} for a connection to the endpoint created in L{setUp}. """ factory = ClientFactory() factory.protocol = lambda: self.protocol return self.cache.connectCached(self.endpoint, factory)
def main(): P = OptionParser(usage="%prog [-C|-S] <-v> host:port") P.add_option('-v', '--verbose', action='count', default=0, help='Print more information') P.add_option('-C', '--client', action='store_true', default=True, dest='dir', help='Act as Client to PSC') P.add_option('-S', '--server', action='store_false', dest='dir', help='Act as Server to IOC') vals, args = P.parse_args() if len(args) < 1: P.usage() sys.exit(1) host, _, port = args[0].partition(':') port = int(port or '6') logging.basicConfig(level=_V.get(vals.verbose, 0)) if vals.dir: # Client log.info('Connect to %s:%u', host, port) fact = ClientFactory() fact.protocol = PSCClient ep = reactor.connectTCP(host, port, fact) else: # Server log.info('Serve from %s:%u', host, port) fact = Factory() fact.protocol = PSCServer ep = reactor.listenTCP(port, fact, interface=host or '') log.info('Run') reactor.run() log.info('Done')
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.protocol = protoClass proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def getOpenFlowClientFactory(self, switchConn): f = ClientFactory() f.protocol = OpenFlowClientProtocol f.switchConn = switchConn f.add_controllerConnection = self.add_controllerConnection f.handle_controller_openflow_msg = self.handle_controller_openflow_msg f.remove_controllerConnection = self.remove_controllerConnection f.ofmsg_generator = self.ofmsg_generator return f
def _create_client_factory(self, target_id): factory = ClientFactory() factory.protocol = OutgoingProtocol factory.target_id = target_id factory.add_connection = self.outgoing_connections.add factory.remove_connection = self.outgoing_connections.remove self._init_factory(factory) return factory
def main(): inventory = Inventory(100, 1) def protocol(): return MakerTraderClient(inventory) factory = ClientFactory() factory.protocol = protocol reactor.connectTCP("localhost", 8000, factory) reactor.run()
def connect(self, host, port): self._connection_timeout = self.timeout self._stack_conn = _Connection() self._stack_conn.attach(self) self._stack_conn.connect_cb = Callback() factory = ClientFactory() factory.protocol = lambda: self._stack_conn factory.clientConnectionFailed = self.clientConnectionFailed self._connect_to_reactor(host, port, factory, self._connection_timeout) yield self._stack_conn.connect_cb
def connectionMade(self): self.buffer = [] self.client = None cli_factory = ClientFactory() cli_factory.protocol = SyncplayProxyClientProtocol cli_factory.server = self host_name, host_port = self._factory.host_name, self._factory.host_port reactor.connectTCP(host_name, host_port, cli_factory)
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
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.protocol = protoClass def raise_(ex): raise ex fac.bobConnectionFailed = lambda reason: raise_(reason) proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def connect(self, host, port): self._stack_conn = _Connection() self._stack_conn.attach(self) self._stack_conn.connect_cb = Callback() factory = ClientFactory() factory.protocol = lambda: self._stack_conn factory.clientConnectionFailed = self.clientConnectionFailed if self.ssl_options is not None: reactor.connectSSL(host, port, factory, SSLContextFactory(self.ssl_options)) else: reactor.connectTCP(host, port, factory) yield self._stack_conn.connect_cb
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.protocol = protoClass fac.options = {} def raise_(ex): raise ex fac.bobConnectionFailed = lambda reason: raise_(reason) proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def main(): serverFactory = ServerFactory() serverFactory.protocol = myHost() reactor.listenTCP(8000, serverFactory) reactor.run() host = raw_input("Enter chat screen name.\n") clientFactory = ClientFactory() clientFactory.protocol = myFactory() reactor.listenTCP(8000, serverFactory) reactor.run()
def _createClientFactory(self, tcpip=None, tcpport=None): import freetime.entity.config as ftconfig if ftconfig.global_config.get('is_h5', 0): # from autobahn.twisted.websocket import WebSocketClientFactory # factory = WebSocketClientFactory("ws://" + tcpip + ":" + str(tcpport), debug=True) factory = H5WebSocketClientFactory("ws://" + tcpip + ":" + str(tcpport), debug=True) factory.protocol = self._makeRoboProtocloWs return factory else: from twisted.internet.protocol import ClientFactory factory = ClientFactory() factory.protocol = self._makeRoboProtoclo return factory
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
def open(self): """open the connection to the lircd socket""" def gotProtocol(result): """now we have a connection""" self.protocol = result self.protocol.wrapper = self print 'got lirc protocol' def gotNoProtocol(result): """something went wrong""" print "got no connection to lirc: %s" % result point = UNIXClientEndpoint(reactor, self.irwSocket, timeout=2) factory = ClientFactory() factory.protocol = LircProtocol point.connect(factory).addCallback(gotProtocol).addErrback(gotNoProtocol)
def test_badContext(self): """ If the context factory passed to L{ITCPTransport.startTLS} raises an exception from its C{getContext} method, that exception is raised by L{ITCPTransport.startTLS}. """ reactor = self.buildReactor() brokenFactory = BrokenContextFactory() results = [] serverFactory = ServerFactory() serverFactory.protocol = Protocol port = reactor.listenTCP(0, serverFactory, interface=self.interface) endpoint = self.endpoints.client(reactor, port.getHost()) clientFactory = ClientFactory() clientFactory.protocol = Protocol connectDeferred = endpoint.connect(clientFactory) def connected(protocol): if not ITLSTransport.providedBy(protocol.transport): results.append("skip") else: results.append( self.assertRaises(ValueError, protocol.transport.startTLS, brokenFactory)) def connectFailed(failure): results.append(failure) def whenRun(): connectDeferred.addCallback(connected) connectDeferred.addErrback(connectFailed) connectDeferred.addBoth(lambda ign: reactor.stop()) needsRunningReactor(reactor, whenRun) self.runReactor(reactor) self.assertEqual(len(results), 1, "more than one callback result: %s" % (results, )) if isinstance(results[0], Failure): # self.fail(Failure) results[0].raiseException() if results[0] == "skip": raise SkipTest("Reactor does not support ITLSTransport") self.assertEqual(BrokenContextFactory.message, str(results[0]))
def main(): inventory = Inventory(100) def protocol(): RTC_instance = RandomTraderClient(inventory) # Read in file #RTC_instance.readCSVorder() # Return RTC instance after reading csv file return RTC_instance factory = ClientFactory() factory.protocol = protocol reactor.connectTCP("localhost", 8000, factory) reactor.run()
def test_badContext(self): """ If the context factory passed to L{ITCPTransport.startTLS} raises an exception from its C{getContext} method, that exception is raised by L{ITCPTransport.startTLS}. """ reactor = self.buildReactor() brokenFactory = BrokenContextFactory() results = [] serverFactory = ServerFactory() serverFactory.protocol = Protocol port = reactor.listenTCP(0, serverFactory, interface=self.interface) endpoint = self.endpoints.client(reactor, port.getHost()) clientFactory = ClientFactory() clientFactory.protocol = Protocol connectDeferred = endpoint.connect(clientFactory) def connected(protocol): if not ITLSTransport.providedBy(protocol.transport): results.append("skip") else: results.append(self.assertRaises(ValueError, protocol.transport.startTLS, brokenFactory)) def connectFailed(failure): results.append(failure) def whenRun(): connectDeferred.addCallback(connected) connectDeferred.addErrback(connectFailed) connectDeferred.addBoth(lambda ign: reactor.stop()) needsRunningReactor(reactor, whenRun) self.runReactor(reactor) self.assertEqual(len(results), 1, "more than one callback result: %s" % (results,)) if isinstance(results[0], Failure): # self.fail(Failure) results[0].raiseException() if results[0] == "skip": raise SkipTest("Reactor does not support ITLSTransport") self.assertEqual(BrokenContextFactory.message, str(results[0]))
def test_stopStartReading(self): """ This test verifies transport socket read state after multiple pause/resumeProducing calls. """ sf = ServerFactory() reactor = sf.reactor = self.buildReactor() skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest("This test is broken on gtk/glib under Windows.") sf.protocol = StopStartReadingProtocol sf.ready = Deferred() sf.stop = Deferred() p = reactor.listenTCP(0, sf) port = p.getHost().port def proceed(protos, port): """ Send several IOCPReactor's buffers' worth of data. """ self.assertTrue(protos[0]) self.assertTrue(protos[1]) protos = protos[0][1], protos[1][1] protos[0].transport.write('x' * (2 * 4096) + 'y' * (2 * 4096)) return (sf.stop.addCallback( cleanup, protos, port).addCallback(lambda ign: reactor.stop())) def cleanup(data, protos, port): """ Make sure IOCPReactor didn't start several WSARecv operations that clobbered each other's results. """ self.assertEquals(data, 'x' * (2 * 4096) + 'y' * (2 * 4096), 'did not get the right data') return DeferredList([ maybeDeferred(protos[0].transport.loseConnection), maybeDeferred(protos[1].transport.loseConnection), maybeDeferred(port.stopListening) ]) cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port) cf = ClientFactory() cf.protocol = Protocol d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p) self.runReactor(reactor) return d
def main(): import optparse parser = optparse.OptionParser(__doc__.strip()) parser.add_option('--host', action='store', default='localhost', help="Host to connect to.") parser.add_option('--port', action='store', type='int', default=5970, help="Port to connect to.") opts, args = parser.parse_args() factory = ClientFactory() factory.protocol = ClientProtocol reactor.connectTCP(opts.host, opts.port, factory) reactor.run()
def test_stopStartReading(self): """ This test verifies transport socket read state after multiple pause/resumeProducing calls. """ sf = ServerFactory() reactor = sf.reactor = self.buildReactor() skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest( "This test is broken on gtk/glib under Windows.") sf.protocol = StopStartReadingProtocol sf.ready = Deferred() sf.stop = Deferred() p = reactor.listenTCP(0, sf) port = p.getHost().port def proceed(protos, port): """ Send several IOCPReactor's buffers' worth of data. """ self.assertTrue(protos[0]) self.assertTrue(protos[1]) protos = protos[0][1], protos[1][1] protos[0].transport.write('x' * (2 * 4096) + 'y' * (2 * 4096)) return (sf.stop.addCallback(cleanup, protos, port) .addCallback(lambda ign: reactor.stop())) def cleanup(data, protos, port): """ Make sure IOCPReactor didn't start several WSARecv operations that clobbered each other's results. """ self.assertEqual(data, 'x'*(2*4096) + 'y'*(2*4096), 'did not get the right data') return DeferredList([ maybeDeferred(protos[0].transport.loseConnection), maybeDeferred(protos[1].transport.loseConnection), maybeDeferred(port.stopListening)]) cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port) cf = ClientFactory() cf.protocol = Protocol d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p) self.runReactor(reactor) return d
def test_handshakeFailure(self): """ L{TLSMemoryBIOProtocol} reports errors in the handshake process to the application-level protocol object using its C{connectionLost} method and disconnects the underlying transport. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverConnectionLost = Deferred() serverFactory = ServerFactory() serverFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( serverConnectionLost)) # This context factory rejects any clients which do not present a # certificate. certificateData = FilePath(certPath).getContent() certificate = PrivateCertificate.loadPEM(certificateData) serverContextFactory = certificate.options(certificate) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) def cbConnectionLost(protocol): # The connection should close on its own in response to the error # induced by the client not supplying the required certificate. # After that, check to make sure the protocol's connectionLost was # called with the right thing. protocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbConnectionLost) serverConnectionLost.addCallback(cbConnectionLost) # Additionally, the underlying transport should have been told to # go away. return gatherResults([ clientConnectionLost, serverConnectionLost, connectionDeferred])
def test_makeConnectionFiresDeferredWithProtocol(self): """ When L{ConnectionNotificationWrapper.makeConnection} is called, the Deferred previously registered should be fired with the protocol instance. """ realFactory = ClientFactory() realProtocol = Protocol() realFactory.protocol = lambda: realProtocol wrappedFactory = ConnectionNotificationFactory(realFactory) wrappedProtocol = wrappedFactory.buildProtocol(None) wrappedProtocol.makeConnection(StringTransport()) wrappedFactory.connectionNotification.addCallback( self.assertIdentical, realProtocol) return wrappedFactory.connectionNotification
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.nickname = 'foo' fac.privKey = None fac.options = {} fac.protocol = protoClass fac.resultNotOK = Mock() def raise_(ex): raise ex fac.connectionFailed = lambda reason: raise_(reason) proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def test_unregisterProducerAfterDisconnect(self): """ If a producer is unregistered from a L{ITCPTransport} provider after the transport has been disconnected (by the peer) and after L{ITCPTransport.loseConnection} has been called, the transport is not re-added to the reactor as a writer as would be necessary if the transport were still connected. """ reactor = self.buildReactor() port = reactor.listenTCP(0, serverFactoryFor(ClosingProtocol), interface=self.interface) finished = Deferred() finished.addErrback(log.err) finished.addCallback(lambda ign: reactor.stop()) writing = [] class ClientProtocol(Protocol): """ Protocol to connect, register a producer, try to lose the connection, wait for the server to disconnect from us, and then unregister the producer. """ def connectionMade(self): log.msg("ClientProtocol.connectionMade") self.transport.registerProducer( _SimplePullProducer(self.transport), False) self.transport.loseConnection() def connectionLost(self, reason): log.msg("ClientProtocol.connectionLost") self.unregister() writing.append(self.transport in _getWriters(reactor)) finished.callback(None) def unregister(self): log.msg("ClientProtocol unregister") self.transport.unregisterProducer() clientFactory = ClientFactory() clientFactory.protocol = ClientProtocol reactor.connectTCP(self.interface, port.getHost().port, clientFactory) self.runReactor(reactor) self.assertFalse(writing[0], "Transport was writing after unregisterProducer.")
def test_handshakeFailure(self): """ L{TLSMemoryBIOProtocol} reports errors in the handshake process to the application-level protocol object using its C{connectionLost} method and disconnects the underlying transport. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol(clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverConnectionLost = Deferred() serverFactory = ServerFactory() serverFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol(serverConnectionLost)) # This context factory rejects any clients which do not present a # certificate. certificateData = FilePath(certPath).getContent() certificate = PrivateCertificate.loadPEM(certificateData) serverContextFactory = certificate.options(certificate) wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) def cbConnectionLost(protocol): # The connection should close on its own in response to the error # induced by the client not supplying the required certificate. # After that, check to make sure the protocol's connectionLost was # called with the right thing. protocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbConnectionLost) serverConnectionLost.addCallback(cbConnectionLost) # Additionally, the underlying transport should have been told to # go away. return gatherResults( [clientConnectionLost, serverConnectionLost, connectionDeferred])
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
def gConnectTCP(host, port, reactor=None): """ Return a L{GreenletTransport} connected to the given host and port. This function must NOT be called from the reactor's greenlet. """ from corotwine.defer import blockOn current = greenlet.getcurrent() assert current is not MAIN, \ "Don't run gConnectTCP from the reactor greenlet." if reactor is None: from twisted.internet import reactor d = Deferred() f = ClientFactory() f.protocol = lambda: _GreenletClientProtocol(d, current) reactor.connectTCP(host, port, f) return blockOn(d)
def open(self): """open the connection to the lircd socket""" def gotProtocol(result): """now we have a connection""" self.protocol = result self.protocol.wrapper = self logDebug(self, None, 'got lirc protocol') def gotNoProtocol(result): """something went wrong""" print "got no connection to lirc: %s" % result point = UNIXClientEndpoint(reactor, self.irwSocket, timeout=2) factory = ClientFactory() factory.protocol = LircProtocol point.connect(factory).addCallback(gotProtocol).addErrback( gotNoProtocol)
def dataReceived(self, data): try: ip = self.resolve_domain(data) if ip: factory = ClientFactory() factory.CustomProtocolParent_ = self factory.protocol = CustomProtocolChild reactor.connectTCP(ip, 80, factory) else: self.transport.loseConnection() if self.client: self.client.write(data) else: self.buffer = data except: pass
def makeTCPClient(context, protocol, server, factory=None, when='connectionMade', close=disconnect): from twisted.internet import reactor hook(protocol, when) if factory is None: factory = ClientFactory() factory.protocol = protocol host = server.port.getHost() reactor.connectTCP(host.host, host.port, factory) return waitForClient(context, getattr(protocol, when), server.protocolClass.connectionMade, close)
def open(self): """open connection if not open""" def gotProtocol(result): """now we have a a connection, save it""" self.protocol = result self.protocol.wrapper = self self.ping() if not self.protocol: logDebug(self, None, 'opening Yamaha') point = TCP4ClientEndpoint(reactor, self.host, self.port) factory = ClientFactory() factory.protocol = YamahaProtocol result = point.connect(factory).addCallback(gotProtocol) else: result = succeed(None) reactor.callLater(self.closeTimeout, self.close) return result
def open(self): """open connection if not open""" def gotProtocol(result): """now we have a a connection, save it""" self.protocol = result self.protocol.wrapper = self def gotNoProtocol(result): """something went wrong""" msg = 'Pioneer: %s' % result.getErrorMessage() LOGGER.error(msg) raise Exception(msg) point = TCP4ClientEndpoint(reactor, self.host, self.port) factory = ClientFactory() factory.protocol = PioneerProtocol return point.connect(factory).addCallback(gotProtocol).addErrback( gotNoProtocol)
def open(self): """open connection if not open""" def gotProtocol(result): """now we have a a connection, save it""" self.protocol = result self.protocol.wrapper = self def gotNoProtocol(result): """something went wrong""" msg = "Pioneer: %s" % result.getErrorMessage() LOGGER.error(msg) raise Exception(msg) point = TCP4ClientEndpoint(reactor, self.host, self.port) factory = ClientFactory() factory.protocol = PioneerProtocol return point.connect(factory).addCallback(gotProtocol).addErrback(gotNoProtocol)