def test_interface(self): """ L{IReactorUNIX.connectUNIX} returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = reactor.connectUNIX(self.mktemp(), ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
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 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_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_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_interface(self): """ L{IReactorTCP.connectTCP} returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = reactor.connectTCP("127.0.0.1", 1234, ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
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_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 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 __init__(self, config, app=None): super().__init__(config, app) self.factory = ClientFactory() self.factory.config = config self.factory.protocol = TwistedHandler self.factory.protocol_factory = self.protocol_factory
def test_interface(self): """ The C{connect} method returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = self.connect(reactor, ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
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 __init__(self, conn_type, exp_conn, WSCLI): ClientFactory().__init__() self.exp_conn = exp_conn # self.q_obj = q_object self.dict_of_active = dict() self.dict_of_inactive = dict() self.wallet_servic_CLI_instance = WSCLI self.conn_type = conn_type
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 init_connection(self, url, byterange, level): if self.connection_list[level]: self.connection_list[level].stop() debug(DEBUG+1, '%s init_connection: %s', self, url) self.connection_list[level] = ClientFactory(url) self.connection_list[level].connect('connection-made', self.on_connection_made, url, byterange, level) self.connection_list[level].connect('connection-lost', self.on_connection_lost) self.connection_list[level].connect('data-received', self.on_data_received, level)
def test_doStart(self): """ L{_WrappingFactory.doStart} passes through to the wrapped factory's C{doStart} method, allowing application-specific setup and logging. """ factory = ClientFactory() wf = endpoints._WrappingFactory(factory) wf.doStart() self.assertEqual(1, factory.numPorts)
def connect_transport(protocol, factory=None): """ Connect a StringTransport to a client protocol. """ if factory is None: factory = ClientFactory() transport = StringTransportWithDisconnection() protocol.makeConnection(transport) transport.protocol = protocol protocol.factory = factory return transport
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 test_connectToLinuxAbstractNamespace(self): """ L{IReactorUNIX.connectUNIX} also accepts a Linux abstract namespace path. """ path = _abstractPath(self) reactor = self.buildReactor() connector = reactor.connectUNIX('\0' + path, ClientFactory()) self.assertEqual(connector.getDestination(), UNIXAddress('\0' + path))
def main(): inventory = Inventory(100, 1) def protocol(): return MakerTraderClient(inventory) factory = ClientFactory() factory.protocol = protocol reactor.connectTCP("localhost", 8000, factory) reactor.run()
class ClientBase(): factory = ClientFactory() def __init__(self, ip, port): self.__ip = ip self.__port = port task.react(self.Connect(), self) def connect(self, reactor): reactor.connectTCP(self.__ip, self.__port, self.factory)
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 __init__(self, basedir, configFileName="taskmaster.cfg"): Daemon.__init__(self, basedir, configFileName) self._clientFactory = ClientFactory( ) # Rename? # Later use: pb.PBServerFactory(p) self._clientFactory.protocol = JobClient self._serverFactory = ServerFactory() self._serverFactory.protocol = JobTracker self._serverFactory.master = self log.msg("creating TaskMaster")
def test_doStop(self): """ L{_WrappingFactory.doStop} passes through to the wrapped factory's C{doStop} method, allowing application-specific cleanup and logging. """ factory = ClientFactory() factory.numPorts = 3 wf = endpoints._WrappingFactory(factory, None) wf.doStop() self.assertEqual(2, factory.numPorts)
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 sbRequestAccepted((host, port, key)): LogEvent(INFO, self.ident) self.key = key self.reply = 0 factory = ClientFactory() factory.buildProtocol = lambda addr: self self.msncon.connectors.append( reactor.connectTCP(host, port, factory, bindAddress=(MSNConnection.BINDADDRESS, 0)))
def __init__(self, args): component.Component.__init__(self, "IPCInterface") ipc_dir = deluge.configmanager.get_config_dir("ipc") if not os.path.exists(ipc_dir): os.makedirs(ipc_dir) socket = os.path.join(ipc_dir, "deluge-gtk") if deluge.common.windows_check(): # If we're on windows we need to check the global mutex to see if deluge is # already running. import win32event import win32api import winerror self.mutex = win32event.CreateMutex(None, False, "deluge") if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS: # Create listen socket self.factory = Factory() self.factory.protocol = IPCProtocolServer import random port = random.randrange(20000, 65535) reactor.listenTCP(port, self.factory) # Store the port number in the socket file open(socket, "w").write(str(port)) # We need to process any args when starting this process process_args(args) else: # Send to existing deluge process port = int(open(socket, "r").readline()) self.factory = ClientFactory() self.factory.args = args self.factory.protocol = IPCProtocolClient reactor.connectTCP("127.0.0.1", port, self.factory) reactor.run() sys.exit(0) else: # Find and remove any restart tempfiles old_tempfile = glob(os.path.join(ipc_dir, 'tmp*deluge')) for f in old_tempfile: os.remove(f) lockfile = socket + ".lock" log.debug("Checking if lockfile exists: %s", lockfile) if os.path.lexists(lockfile) or os.path.lexists(socket): try: os.kill(int(os.readlink(lockfile)), 0) except OSError: log.debug("Removing lockfile since it's stale.") try: os.remove(lockfile) except OSError, ex: log.error("Failed to delete IPC lockfile file: %s", ex) try: os.remove(socket) except OSError, ex: log.error("Failed to delete IPC socket file: %s", ex)
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 connectReply(self, host, port, key, sessionID): LogEvent(INFO, self.ident) self.ready = False self.key = key self.sessionID = sessionID self.reply = 1 factory = ClientFactory() factory.buildProtocol = lambda addr: self self.msncon.connectors.append( reactor.connectTCP(host, port, factory, bindAddress=(MSNConnection.BINDADDRESS, 0)))
def test_connectDestination(self): """ L{MemoryReactor.connectTCP}, L{MemoryReactor.connectSSL}, and L{MemoryReactor.connectUNIX} will return an L{IConnector} whose C{getDestination} method returns an L{IAddress} with attributes which reflect the values passed. """ memoryReactor = MemoryReactor() for connector in [ memoryReactor.connectTCP("test.example.com", 8321, ClientFactory()), memoryReactor.connectSSL("test.example.com", 8321, ClientFactory(), None), ]: verifyObject(IConnector, connector) address = connector.getDestination() verifyObject(IAddress, address) self.assertEqual(address.host, "test.example.com") self.assertEqual(address.port, 8321) connector = memoryReactor.connectUNIX(b"/fake/path", ClientFactory()) verifyObject(IConnector, connector) address = connector.getDestination() verifyObject(IAddress, address) self.assertEqual(address.name, b"/fake/path")