Python twisted.internet.reactor.connectTCP() Examples

The following are 30 code examples of twisted.internet.reactor.connectTCP(). 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.reactor , or try the search function .
Example #1
Source File: bar_daemon.py    From BAR with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def daemon_main(name, role, server):

    #parser = argparse.ArgumentParser(description='bar-daemon')
    #parser.add_argument('--name', default=False, help='Label of contact')
    #parser.add_argument('--role', default=False, help='Role of client')
    #args = parser.parse_args()
    
    #name = name or args.name
    #role = role or args.role    

    communicator_factory = CommunicatorFactory(reactor, name, role)
    if role == "hidden-client": 
        listener_factory = ListenerFactory(reactor, communicator_factory)
        communicator_factory.set_listener(listener_factory)
        port = reactor.listenTCP(4333, listener_factory,
                                 interface="127.0.0.1")
    else:
        port = reactor.listenTCP(4333, ProxyFactory())

    print "Starting reactor..."
    reactor.connectTCP(server, 231, communicator_factory)
    print 'Listening on %s.' % (port.getHost())
    reactor.run() 
Example #2
Source File: imapclient.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def main():
    hostname = raw_input('IMAP4 Server Hostname: ')
    port = raw_input('IMAP4 Server Port (the default is 143): ')
    username = raw_input('IMAP4 Username: ')
    password = util.getPassword('IMAP4 Password: ')

    onConn = defer.Deferred(
    ).addCallback(cbServerGreeting, username, password
                  ).addErrback(ebConnection
                               ).addBoth(cbClose)

    factory = SimpleIMAP4ClientFactory(username, onConn)

    from twisted.internet import reactor
    conn = reactor.connectTCP(hostname, int(port), factory)
    reactor.run() 
Example #3
Source File: network.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def buildProtocol(self, addr):
        log.debug("%s: New connection from %s:%d." % (self.name, log.safe_addr_str(addr.host), addr.port))

        circuit = Circuit(self.transport_class())

        # XXX instantiates a new factory for each client
        clientFactory = StaticDestinationClientFactory(circuit, self.mode)

        if self.pt_config.proxy:
            create_proxy_client(self.remote_host, self.remote_port,
                                self.pt_config.proxy,
                                clientFactory)
        else:
            reactor.connectTCP(self.remote_host, self.remote_port, clientFactory)

        return StaticDestinationProtocol(circuit, self.mode, addr) 
Example #4
Source File: distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET 
Example #5
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source File: protocol.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _connect(self, method, *args, **kwargs):
        """
        Initiate a connection attempt.

        @param method: A callable which will actually start the connection
            attempt.  For example, C{reactor.connectTCP}.

        @param *args: Positional arguments to pass to C{method}, excluding the
            factory.

        @param **kwargs: Keyword arguments to pass to C{method}.

        @return: A L{Deferred} which fires with an instance of the protocol
            class passed to this L{ClientCreator}'s initializer or fails if the
            connection cannot be set up for some reason.
        """
        def cancelConnect(deferred):
            connector.disconnect()
            if f.pending is not None:
                f.pending.cancel()
        d = defer.Deferred(cancelConnect)
        f = _InstanceFactory(
            self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
        connector = method(factory=f, *args, **kwargs)
        return d 
Example #7
Source File: test_pb.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Create a pb server using L{CachedReturner} protocol and connect a
        client to it.
        """
        self.orig = NewStyleCacheCopy()
        self.orig.s = "value"
        self.server = reactor.listenTCP(0,
            ConnectionNotifyServerFactory(CachedReturner(self.orig)))
        clientFactory = pb.PBClientFactory()
        reactor.connectTCP("localhost", self.server.getHost().port,
                           clientFactory)
        def gotRoot(ref):
            self.ref = ref
        d1 = clientFactory.getRootObject().addCallback(gotRoot)
        d2 = self.server.factory.connectionMade
        return gatherResults([d1, d2]) 
Example #8
Source File: test_pb.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_NSP(self):
        """
        An L{IPerspective} implementation which does not subclass
        L{Avatar} can expose remote methods for the client to call.
        """
        factory = pb.PBClientFactory()
        d = factory.login(credentials.UsernamePassword(b'user', b'pass'),
                          "BRAINS!")
        reactor.connectTCP('127.0.0.1', self.portno, factory)
        d.addCallback(lambda p: p.callRemote('ANYTHING', 'here', bar='baz'))
        d.addCallback(self.assertEqual,
                      ('ANYTHING', ('here',), {'bar': 'baz'}))
        def cleanup(ignored):
            factory.disconnect()
            for p in self.factory.protocols:
                p.transport.loseConnection()
        d.addCallback(cleanup)
        return d 
Example #9
Source File: bar_daemon.py    From BAR with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def received_broadcast(self, data):
            print "Received feed."
            message = Message(data)
            row = db.select_entries("contacts", {"label": message.label})
            if len(row) == 0:
                print "Can't find this label: " + message.label
                return
            row = row[0]
            message.decrypt(row["sharedkey"])
            if not message.validate():
                print "Received an invalid message."
                return
            print "Found label: " + message.label
            if self.factory.role == "hidden-client":
                if self.factory.listener_factory:
                    self.factory.listener_factory.send_message(message.cleartext_msg)
                    self.factory.listener_factory.client.transport.loseConnection()
                    db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]})
            else:
                if self.factory.role == "proxy":
                    message.cleartext_msg = re.sub(r'CONNECT (?P<value>.*?) HTTP/1.0\r\n', 'CONNECT localhost HTTP/1.0\r\n', message.cleartext_msg)
                socks_client_factory = HTTPClientFactory(reactor, message)
                socks_client_factory.set_communicator(self)
                reactor.connectTCP("localhost", 4333, socks_client_factory)
                db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]}) 
Example #10
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_tcpNoDelay(self):
        """
        The transport of a protocol connected with L{IReactorTCP.connectTCP} or
        L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
        and manipulated with L{ITCPTransport.getTcpNoDelay} and
        L{ITCPTransport.setTcpNoDelay}.
        """
        def check(serverProtocol, clientProtocol):
            for p in [serverProtocol, clientProtocol]:
                transport = p.transport
                self.assertEqual(transport.getTcpNoDelay(), 0)
                transport.setTcpNoDelay(1)
                self.assertEqual(transport.getTcpNoDelay(), 1)
                transport.setTcpNoDelay(0)
                self.assertEqual(transport.getTcpNoDelay(), 0)
        return self._connectedClientAndServerTest(check) 
Example #11
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _connectedClientAndServerTest(self, callback):
        """
        Invoke the given callback with a client protocol and a server protocol
        which have been connected to each other.
        """
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        portNumber = port.getHost().port
        clientF = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientF.protocolConnectionMade = clientConnMade
        reactor.connectTCP("127.0.0.1", portNumber, clientF)

        connsMade = defer.gatherResults([serverConnMade, clientConnMade])
        def connected(result):
            serverProtocol, clientProtocol = result
            callback(serverProtocol, clientProtocol)
            serverProtocol.transport.loseConnection()
            clientProtocol.transport.loseConnection()
        connsMade.addCallback(connected)
        return connsMade 
Example #12
Source File: relaymanager.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _cbExchange(self, address, port, factory):
        """
        Initiate a connection with a mail exchange server.

        This callback function runs after mail exchange server for the domain
        has been looked up.

        @type address: L{bytes}
        @param address: The hostname of a mail exchange server.

        @type port: L{int}
        @param port: A port number.

        @type factory: L{SMTPManagedRelayerFactory}
        @param factory: A factory which can create a relayer for the mail
            exchange server.
        """
        from twisted.internet import reactor
        reactor.connectTCP(address, port, factory) 
Example #13
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_closePortInProtocolFactory(self):
        """
        A port created with L{IReactorTCP.listenTCP} can be connected to with
        L{IReactorTCP.connectTCP}.
        """
        f = ClosingFactory()
        port = reactor.listenTCP(0, f, interface="127.0.0.1")
        f.port = port
        self.addCleanup(f.cleanUp)
        portNumber = port.getHost().port
        clientF = MyClientFactory()
        reactor.connectTCP("127.0.0.1", portNumber, clientF)
        def check(x):
            self.assertTrue(clientF.protocol.made)
            self.assertTrue(port.disconnected)
            clientF.lostReason.trap(error.ConnectionDone)
        return clientF.deferred.addCallback(check) 
Example #14
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_directConnectionLostCall(self):
        """
        If C{connectionLost} is called directly on a port object, it succeeds
        (and doesn't expect the presence of a C{deferred} attribute).

        C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
        """
        serverFactory = MyServerFactory()
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        portNumber = port.getHost().port
        port.connectionLost(None)

        client = MyClientFactory()
        serverFactory.protocolConnectionMade = defer.Deferred()
        client.protocolConnectionMade = defer.Deferred()
        reactor.connectTCP("127.0.0.1", portNumber, client)
        def check(ign):
            client.reason.trap(error.ConnectionRefusedError)
        return client.failDeferred.addCallback(check) 
Example #15
Source File: mail.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.mail.smtp import ESMTPSenderFactory
        msg = BytesIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
            to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
            requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d 
Example #16
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_serverRepr(self):
        """
        Check that the repr string of the server transport get the good port
        number if the server listens on 0.
        """
        server = MyServerFactory()
        serverConnMade = server.protocolConnectionMade = defer.Deferred()
        port = reactor.listenTCP(0, server)
        self.addCleanup(port.stopListening)

        client = MyClientFactory()
        clientConnMade = client.protocolConnectionMade = defer.Deferred()
        connector = reactor.connectTCP("127.0.0.1",
                                       port.getHost().port, client)
        self.addCleanup(connector.disconnect)
        def check(result):
            serverProto, clientProto = result
            portNumber = port.getHost().port
            self.assertEqual(
                repr(serverProto.transport),
                "<AccumulatingProtocol #0 on %s>" % (portNumber,))
            serverProto.transport.loseConnection()
            clientProto.transport.loseConnection()
        return defer.gatherResults([serverConnMade, clientConnMade]
            ).addCallback(check) 
Example #17
Source File: post_auth_handler.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_to_pot(self, returned_conn_details):
        if returned_conn_details:
            if returned_conn_details['success']:
                self.sensor_name = returned_conn_details['sensor_name']
                self.honey_ip = returned_conn_details['honey_ip']
                self.honey_port = returned_conn_details['honey_port']
                self.username = returned_conn_details['username']
                self.password = returned_conn_details['password']
                self.connection_timeout = returned_conn_details['connection_timeout']

                self.auth_packets = [[5, self.to_string('ssh-userauth')], [50, self.to_string(
                    self.username) + self.to_string('ssh-connection') + self.to_string('none')]]

                if self.sensor_name == self.server.sensor_name and self.honey_ip == self.server.honey_ip \
                        and self.honey_port == self.server.honey_port:
                    log.msg(log.LGREEN, '[POST_AUTH]', 'Details the same as pre-auth, not re-directing')
                    self.dont_post_auth()
                else:
                    self.server.client.loseConnection()
                    self.server.clientConnected = False
                    if not self.server.disconnected:
                        log.msg(log.LGREEN, '[POST_AUTH]', 'Connecting to Honeypot: %s (%s:%s)' %
                                (self.sensor_name, self.honey_ip, self.honey_port))
                        client_factory = client.HonsshClientFactory()
                        client_factory.server = self.server
                        bind_ip = self.server.net.setup_networking(self.server.peer_ip, self.honey_ip, self.honey_port)
                        self.networkingSetup = True
                        reactor.connectTCP(self.honey_ip, self.honey_port, client_factory,
                                           bindAddress=(bind_ip, self.server.peer_port + 1),
                                           timeout=self.connection_timeout)
                        pot_connect_defer = threads.deferToThread(self.is_pot_connected)
                        pot_connect_defer.addCallback(self.pot_connected)
            else:
                log.msg(log.LBLUE, '[POST_AUTH]', 'SUCCESS = FALSE, NOT POST-AUTHING')
                self.dont_post_auth()
        else:
            log.msg(log.LRED, '[POST_AUTH][ERROR]', 'PLUGIN ERROR - DISCONNECTING ATTACKER')
            self.server.loseConnection() 
Example #18
Source File: http10.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _connect(self, factory):
        host, port = to_unicode(factory.host), factory.port
        if factory.scheme == b'https':
            return reactor.connectSSL(host, port, factory,
                                      self.ClientContextFactory())
        else:
            return reactor.connectTCP(host, port, factory) 
Example #19
Source File: honsshInteraction.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_args(args):
    """Process the command line arguments."""
    if not args.cmd == 'list':
        if not args.uuid:
            print('UUID required for selected command')
            sys.exit(1)

    ifactory = HonSSHInteractFactory()
    ifactory.command = args.cmd
    ifactory.style = args.format
    if args.cmd in ['view', 'disconnect']:
        ifactory.uuid = args.uuid

    reactor.connectTCP(args.ip, args.port, ifactory)
    reactor.run() 
Example #20
Source File: pre_auth_handler.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_to_pot(self, returned_conn_details):
        if returned_conn_details:
            if returned_conn_details['success']:
                self.sensor_name = returned_conn_details['sensor_name']
                self.honey_ip = returned_conn_details['honey_ip']
                self.honey_port = returned_conn_details['honey_port']
                self.connection_timeout = returned_conn_details['connection_timeout']

                if not self.server.disconnected:
                    log.msg(log.LGREEN, '[PRE_AUTH]',
                            'Connecting to Honeypot: %s (%s:%s)' % (self.sensor_name, self.honey_ip, self.honey_port))
                    client_factory = client.HonsshClientFactory()
                    client_factory.server = self.server
                    bind_ip = self.server.net.setup_networking(self.server.peer_ip, self.honey_ip, self.honey_port)
                    self.networkingSetup = True
                    reactor.connectTCP(self.honey_ip, self.honey_port, client_factory,
                                       bindAddress=(bind_ip, self.server.peer_port + 2),
                                       timeout=self.connection_timeout)

                    pot_connect_defer = threads.deferToThread(self.is_pot_connected)
                    pot_connect_defer.addCallback(self.pot_connected)
            else:
                log.msg(log.LRED, '[PRE_AUTH][ERROR]', 'PLUGIN ERROR - DISCONNECTING ATTACKER')
                self.server.loseConnection()
        else:
            log.msg(log.LRED, '[PRE_AUTH][ERROR]', 'PLUGIN ERROR - DISCONNECTING ATTACKER')
            self.server.loseConnection() 
Example #21
Source File: server.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self.cfg = Config.getInstance()
        self.otherVersionString = ''
        self.connections = connections.Connections()
        self.plugin_servers = []
        self.ourVersionString = self.cfg.get(['honeypot', 'ssh_banner'])

        if len(self.ourVersionString) > 0:
            log.msg(log.LPURPLE, '[SERVER]', 'Using ssh_banner for SSH Version String: ' + self.ourVersionString)
        else:
            if self.cfg.getboolean(['honeypot-static', 'enabled']):
                log.msg(log.LPURPLE, '[SERVER]', 'Acquiring SSH Version String from honey_ip:honey_port')
                client_factory = client.HonsshSlimClientFactory()
                client_factory.server = self

                reactor.connectTCP(self.cfg.get(['honeypot-static', 'honey_ip']),
                                   int(self.cfg.get(['honeypot-static', 'honey_port'])), client_factory)
            elif self.cfg.getboolean(['honeypot-docker', 'enabled']):
                log.msg(log.LRED, '[SERVER][ERR]', 'You need to configure the ssh_banner for docker manually!')

        plugin_list = plugins.get_plugin_list()
        loaded_plugins = plugins.import_plugins(plugin_list)
        for plugin in loaded_plugins:
            plugin_server = plugins.run_plugins_function([plugin], 'start_server', False)
            plugin_name = plugins.get_plugin_name(plugin)
            self.plugin_servers.append({'name': plugin_name, 'server': plugin_server})

        if self.ourVersionString != '':
            log.msg(log.LGREEN, '[HONSSH]', 'HonSSH Boot Sequence Complete - Ready for attacks!') 
Example #22
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.f = f = MyServerFactory()
        self.f.protocolConnectionMade = defer.Deferred()
        self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")

        # XXX we don't test server side yet since we don't do it yet
        d = protocol.ClientCreator(reactor, AccumulatingProtocol).connectTCP(
            p.getHost().host, p.getHost().port)
        d.addCallback(self._gotClient)
        return d 
Example #23
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def connectClient(self, address, portNumber, clientCreator):
        """
        Create a TCP client using L{IReactorTCP.connectTCP}.
        """
        return clientCreator.connectTCP(address, portNumber) 
Example #24
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_hostAddress(self):
        """
        L{IListeningPort.getHost} returns the same address as a client
        connection's L{ITCPTransport.getPeer}.
        """
        serverFactory = MyServerFactory()
        serverFactory.protocolConnectionLost = defer.Deferred()
        serverConnectionLost = serverFactory.protocolConnectionLost
        port = reactor.listenTCP(0, serverFactory, interface='127.0.0.1')
        self.addCleanup(port.stopListening)
        n = port.getHost().port

        clientFactory = MyClientFactory()
        onConnection = clientFactory.protocolConnectionMade = defer.Deferred()
        connector = reactor.connectTCP('127.0.0.1', n, clientFactory)

        def check(ignored):
            self.assertEqual([port.getHost()], clientFactory.peerAddresses)
            self.assertEqual(
                port.getHost(), clientFactory.protocol.transport.getPeer())
        onConnection.addCallback(check)

        def cleanup(ignored):
            # Clean up the client explicitly here so that tear down of
            # the server side of the connection begins, then wait for
            # the server side to actually disconnect.
            connector.disconnect()
            return serverConnectionLost
        onConnection.addCallback(cleanup)

        return onConnection 
Example #25
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_clientStartStop(self):
        """
        The factory passed to L{IReactorTCP.connectTCP} should be started when
        the connection attempt starts and stopped when it is over.
        """
        f = ClosingFactory()
        p = reactor.listenTCP(0, f, interface="127.0.0.1")
        f.port = p
        self.addCleanup(f.cleanUp)
        portNumber = p.getHost().port

        factory = ClientStartStopFactory()
        reactor.connectTCP("127.0.0.1", portNumber, factory)
        self.assertTrue(factory.started)
        return loopUntil(lambda: factory.stopped) 
Example #26
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_connectByService(self):
        """
        L{IReactorTCP.connectTCP} accepts the name of a service instead of a
        port number and connects to the port number associated with that
        service, as defined by L{socket.getservbyname}.
        """
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)
        portNumber = port.getHost().port
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade

        def fakeGetServicePortByName(serviceName, protocolName):
            if serviceName == 'http' and protocolName == 'tcp':
                return portNumber
            return 10
        self.patch(socket, 'getservbyname', fakeGetServicePortByName)

        reactor.connectTCP('127.0.0.1', 'http', clientFactory)

        connMade = defer.gatherResults([serverConnMade, clientConnMade])
        def connected(result):
            serverProtocol, clientProtocol = result
            self.assertTrue(
                serverFactory.called,
                "Server factory was not called upon to build a protocol.")
            serverProtocol.transport.loseConnection()
            clientProtocol.transport.loseConnection()
        connMade.addCallback(connected)
        return connMade 
Example #27
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_connectByServiceFail(self):
        """
        Connecting to a named service which does not exist raises
        L{error.ServiceNameUnknownError}.
        """
        self.assertRaises(
            error.ServiceNameUnknownError,
            reactor.connectTCP,
            "127.0.0.1", "thisbetternotexist", MyClientFactory()) 
Example #28
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def testFailing(self):
        clientF = MyClientFactory()
        # XXX we assume no one is listening on TCP port 69
        reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5)
        def check(ignored):
            clientF.reason.trap(error.ConnectionRefusedError)
        return clientF.failDeferred.addCallback(check) 
Example #29
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_restartAfterExcept(self):
        """
        Even if the server factory raise an exception in C{stopFactory}, the
        corresponding C{tcp.Port} instance should be in a sane state and can
        be restarted.
        """
        serverFactory = MyServerFactory()
        def raiseException():
            raise RuntimeError("An error")
        serverFactory.stopFactory = raiseException
        port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
        self.addCleanup(port.stopListening)

        def cbStopListening(ignored):
            del serverFactory.stopFactory
            port.startListening()

            client = MyClientFactory()
            serverFactory.protocolConnectionMade = defer.Deferred()
            client.protocolConnectionMade = defer.Deferred()
            connector = reactor.connectTCP("127.0.0.1",
                                           port.getHost().port, client)
            self.addCleanup(connector.disconnect)
            return defer.gatherResults([serverFactory.protocolConnectionMade,
                                        client.protocolConnectionMade]
                ).addCallback(close)

        def close(result):
            serverProto, clientProto = result
            clientProto.transport.loseConnection()
            serverProto.transport.loseConnection()

        return self.assertFailure(port.stopListening(), RuntimeError
            ).addCallback(cbStopListening) 
Example #30
Source File: direct.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def connect(host, port, options, verifyHostKey, userAuthObject):
    d = defer.Deferred()
    factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
    reactor.connectTCP(host, port, factory)
    return d