Ejemplo n.º 1
0
    def _hostpeertest(self, get, testServer):
        """
        Test one of the permutations of client/server host/peer.
        """
        class TestProtocol(Protocol):
            def makeConnection(self, transport):
                Protocol.makeConnection(self, transport)
                self.onConnection.callback(transport)

        if testServer:
            server = TestProtocol()
            d = server.onConnection = Deferred()
            client = Protocol()
        else:
            server = Protocol()
            client = TestProtocol()
            d = client.onConnection = Deferred()

        loopback.loopbackAsync(server, client)

        def connected(transport):
            host = getattr(transport, get)()
            self.failUnless(IAddress.providedBy(host))

        return d.addCallback(connected)
Ejemplo n.º 2
0
    def _greetingtest(self, write, testServer):
        """
        Test one of the permutations of write/writeSequence client/server.
        """
        class GreeteeProtocol(Protocol):
            bytes = ""

            def dataReceived(self, bytes):
                self.bytes += bytes
                if self.bytes == "bytes":
                    self.received.callback(None)

        class GreeterProtocol(Protocol):
            def connectionMade(self):
                getattr(self.transport, write)("bytes")

        if testServer:
            server = GreeterProtocol()
            client = GreeteeProtocol()
            d = client.received = Deferred()
        else:
            server = GreeteeProtocol()
            d = server.received = Deferred()
            client = GreeterProtocol()

        loopback.loopbackAsync(server, client)
        return d
Ejemplo n.º 3
0
    def _greetingtest(self, write, testServer):
        """
        Test one of the permutations of write/writeSequence client/server.

        @param write: The name of the method to test, C{"write"} or
            C{"writeSequence"}.
        """
        class GreeteeProtocol(Protocol):
            bytes = b""
            def dataReceived(self, bytes):
                self.bytes += bytes
                if self.bytes == b"bytes":
                    self.received.callback(None)

        class GreeterProtocol(Protocol):
            def connectionMade(self):
                if write == "write":
                    self.transport.write(b"bytes")
                else:
                    self.transport.writeSequence([b"byt", b"es"])

        if testServer:
            server = GreeterProtocol()
            client = GreeteeProtocol()
            d = client.received = Deferred()
        else:
            server = GreeteeProtocol()
            d = server.received = Deferred()
            client = GreeterProtocol()

        loopback.loopbackAsync(server, client)
        return d
Ejemplo n.º 4
0
    def _hostpeertest(self, get, testServer):
        """
        Test one of the permutations of client/server host/peer.
        """
        class TestProtocol(Protocol):
            def makeConnection(self, transport):
                Protocol.makeConnection(self, transport)
                self.onConnection.callback(transport)

        if testServer:
            server = TestProtocol()
            d = server.onConnection = Deferred()
            client = Protocol()
        else:
            server = Protocol()
            client = TestProtocol()
            d = client.onConnection = Deferred()

        loopback.loopbackAsync(server, client)

        def connected(transport):
            host = getattr(transport, get)()
            self.assertTrue(IAddress.providedBy(host))

        return d.addCallback(connected)
Ejemplo n.º 5
0
    def _greetingtest(self, write, testServer):
        """
        Test one of the permutations of write/writeSequence client/server.

        @param write: The name of the method to test, C{"write"} or
            C{"writeSequence"}.
        """
        class GreeteeProtocol(Protocol):
            bytes = b""

            def dataReceived(self, bytes):
                self.bytes += bytes
                if self.bytes == b"bytes":
                    self.received.callback(None)

        class GreeterProtocol(Protocol):
            def connectionMade(self):
                if write == "write":
                    self.transport.write(b"bytes")
                else:
                    self.transport.writeSequence([b"byt", b"es"])

        if testServer:
            server = GreeterProtocol()
            client = GreeteeProtocol()
            d = client.received = Deferred()
        else:
            server = GreeteeProtocol()
            d = server.received = Deferred()
            client = GreeterProtocol()

        loopback.loopbackAsync(server, client)
        return d
Ejemplo n.º 6
0
    def _greetingtest(self, write, testServer):
        """
        Test one of the permutations of write/writeSequence client/server.
        """
        class GreeteeProtocol(Protocol):
            bytes = ""
            def dataReceived(self, bytes):
                self.bytes += bytes
                if self.bytes == "bytes":
                    self.received.callback(None)

        class GreeterProtocol(Protocol):
            def connectionMade(self):
                getattr(self.transport, write)("bytes")

        if testServer:
            server = GreeterProtocol()
            client = GreeteeProtocol()
            d = client.received = Deferred()
        else:
            server = GreeteeProtocol()
            d = server.received = Deferred()
            client = GreeterProtocol()

        loopback.loopbackAsync(server, client)
        return d
Ejemplo n.º 7
0
    def setUp(self):
        MorbidTestCase.setUp(self)
        self.serverProtocol2 = self.factory.buildProtocol(None)
        self.serverProtocol2.log = self.log
        self.client2 = StompClientProtocol('user2','user2')
        self.client2.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol2, 
                                                   self.client2)

        self.serverProtocol3 = self.factory.buildProtocol(None)
        self.serverProtocol3.log = self.log
        self.client3 = StompClientProtocol('user3','user3')
        self.client3.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol3, 
                                                   self.client3)
Ejemplo n.º 8
0
    def test_makeConnection(self):
        """
        Test that the client and server protocol both have makeConnection
        invoked on them by loopbackAsync.
        """
        class TestProtocol(Protocol):
            transport = None
            def makeConnection(self, transport):
                self.transport = transport

        server = TestProtocol()
        client = TestProtocol()
        loopback.loopbackAsync(server, client)
        self.assertIsNotNone(client.transport)
        self.assertIsNotNone(server.transport)
Ejemplo n.º 9
0
    def test_makeConnection(self):
        """
        Test that the client and server protocol both have makeConnection
        invoked on them by loopbackAsync.
        """
        class TestProtocol(Protocol):
            transport = None
            def makeConnection(self, transport):
                self.transport = transport

        server = TestProtocol()
        client = TestProtocol()
        loopback.loopbackAsync(server, client)
        self.failIfEqual(client.transport, None)
        self.failIfEqual(server.transport, None)
Ejemplo n.º 10
0
    def setUp(self):
        MorbidTestCase.setUp(self)
        self.serverProtocol2 = self.factory.buildProtocol(None)
        self.serverProtocol2.log = self.log
        self.client2 = StompClientProtocol('user2', 'user2')
        self.client2.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol2,
                                                   self.client2)

        self.serverProtocol3 = self.factory.buildProtocol(None)
        self.serverProtocol3.log = self.log
        self.client3 = StompClientProtocol('user3', 'user3')
        self.client3.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol3,
                                                   self.client3)
Ejemplo n.º 11
0
    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
Ejemplo n.º 12
0
    def test_List(self):
        """
        You can get a listing
        """
        server = Server(FakePlumber({
            'ls': [
                ('foo', 'bar', 12, True),
            ]
        }))
        client = SingleCommandClient(List)

        from twisted.protocols.loopback import loopbackAsync
        def check(response):
            self.assertEqual(server.plumber.called, ['ls'])
            self.assertEqual(client.response, {
                'pipes': [
                    {
                        'src': 'foo',
                        'dst': 'bar',
                        'conns': 12,
                        'active': True,
                    },
                ]
            })
        r = loopbackAsync(server, client)
        return r.addCallback(check)
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
    def test_pumpPolicy(self):
        """
        The callable passed as the value for the C{pumpPolicy} parameter to
        L{loopbackAsync} is called with a L{_LoopbackQueue} of pending bytes
        and a protocol to which they should be delivered.
        """
        pumpCalls = []
        def dummyPolicy(queue, target):
            bytes = []
            while queue:
                bytes.append(queue.get())
            pumpCalls.append((target, bytes))

        client = Protocol()
        server = Protocol()

        finished = loopback.loopbackAsync(server, client, dummyPolicy)
        self.assertEqual(pumpCalls, [])

        client.transport.write(b"foo")
        client.transport.write(b"bar")
        server.transport.write(b"baz")
        server.transport.write(b"quux")
        server.transport.loseConnection()

        def cbComplete(ignored):
            self.assertEqual(
                pumpCalls,
                # The order here is somewhat arbitrary.  The implementation
                # happens to always deliver data to the client first.
                [(client, [b"baz", b"quux", None]),
                 (server, [b"foo", b"bar"])])
        finished.addCallback(cbComplete)
        return finished
Ejemplo n.º 18
0
    def test_writeNotReentrant(self):
        """
        L{loopback.loopbackAsync} does not call a protocol's C{dataReceived}
        method while that protocol's transport's C{write} method is higher up
        on the stack.
        """
        class Server(Protocol):
            def dataReceived(self, bytes):
                self.transport.write(b"bytes")

        class Client(Protocol):
            ready = False

            def connectionMade(self):
                reactor.callLater(0, self.go)

            def go(self):
                self.transport.write(b"foo")
                self.ready = True

            def dataReceived(self, bytes):
                self.wasReady = self.ready
                self.transport.loseConnection()


        server = Server()
        client = Client()
        d = loopback.loopbackAsync(client, server)
        def cbFinished(ignored):
            self.assertTrue(client.wasReady)
        d.addCallback(cbFinished)
        return d
Ejemplo n.º 19
0
    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
Ejemplo n.º 20
0
    def test_pumpPolicy(self):
        """
        The callable passed as the value for the C{pumpPolicy} parameter to
        L{loopbackAsync} is called with a L{_LoopbackQueue} of pending bytes
        and a protocol to which they should be delivered.
        """
        pumpCalls = []

        def dummyPolicy(queue, target):
            bytes = []
            while queue:
                bytes.append(queue.get())
            pumpCalls.append((target, bytes))

        client = Protocol()
        server = Protocol()

        finished = loopback.loopbackAsync(server, client, dummyPolicy)
        self.assertEquals(pumpCalls, [])

        client.transport.write("foo")
        client.transport.write("bar")
        server.transport.write("baz")
        server.transport.write("quux")
        server.transport.loseConnection()

        def cbComplete(ignored):
            self.assertEquals(
                pumpCalls,
                # The order here is somewhat arbitrary.  The implementation
                # happens to always deliver data to the client first.
                [(client, ["baz", "quux", None]), (server, ["foo", "bar"])])

        finished.addCallback(cbComplete)
        return finished
Ejemplo n.º 21
0
    def test_writeNotReentrant(self):
        """
        L{loopback.loopbackAsync} does not call a protocol's C{dataReceived}
        method while that protocol's transport's C{write} method is higher up
        on the stack.
        """
        class Server(Protocol):
            def dataReceived(self, bytes):
                self.transport.write(b"bytes")

        class Client(Protocol):
            ready = False

            def connectionMade(self):
                reactor.callLater(0, self.go)

            def go(self):
                self.transport.write(b"foo")
                self.ready = True

            def dataReceived(self, bytes):
                self.wasReady = self.ready
                self.transport.loseConnection()

        server = Server()
        client = Client()
        d = loopback.loopbackAsync(client, server)

        def cbFinished(ignored):
            self.assertTrue(client.wasReady)

        d.addCallback(cbFinished)
        return d
Ejemplo n.º 22
0
 def testEmptyPASS(self):
     dummy = DummyPOP3()
     client = LineSendingProtocol([
         "PASS ",
         "QUIT"
     ])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbTestEmptyPASS, client, dummy)
Ejemplo n.º 23
0
 def setUp(self):
     MorbidTestCase.setUp(self)
     self.serverProtocol2 = self.factory.buildProtocol(None)
     self.serverProtocol2.log = self.log
     self.adminClient = StompClientProtocol('admin','admin')
     self.adminClient.log = self.log
     self.loopbackBody = loopback.loopbackAsync(self.serverProtocol2, 
                                                self.adminClient)
Ejemplo n.º 24
0
    def testAuthListing(self):
        p = DummyPOP3()
        p.factory = internet.protocol.Factory()
        p.factory.challengers = {"Auth1": None, "secondAuth": None, "authLast": None}
        client = LineSendingProtocol(["AUTH", "QUIT"])

        d = loopback.loopbackAsync(p, client)
        return d.addCallback(self._cbTestAuthListing, client)
Ejemplo n.º 25
0
 def setUp(self):
     MorbidTestCase.setUp(self)
     self.serverProtocol2 = self.factory.buildProtocol(None)
     self.serverProtocol2.log = self.log
     self.adminClient = StompClientProtocol('admin', 'admin')
     self.adminClient.log = self.log
     self.loopbackBody = loopback.loopbackAsync(self.serverProtocol2,
                                                self.adminClient)
Ejemplo n.º 26
0
 def testEmptyPASS(self):
     dummy = DummyPOP3()
     client = LineSendingProtocol([
         "PASS ",
         "QUIT"
     ])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbTestEmptyPASS, client, dummy)
Ejemplo n.º 27
0
 def test_emptyPASS(self):
     """
     L{pop3.POP3} handles a I{PASS} command with a password equal to C{""}
     as it would any other value.
     """
     dummy = DummyPOP3()
     client = LineSendingProtocol([b"PASS ", b"QUIT"])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbTestEmptyPASS, client, dummy)
Ejemplo n.º 28
0
 def test_illegalPASS(self):
     """
     L{pop3.POP3} handles a I{PASS} command before a I{USER} command with an
     error indicating the out-of-sequence operation.
     """
     dummy = DummyPOP3()
     client = LineSendingProtocol([b"PASS fooz", b"QUIT"])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbTestIllegalPASS, client, dummy)
Ejemplo n.º 29
0
 def testLoopback(self):
     protocol =  MyVirtualPOP3()
     protocol.service = self.factory
     clientProtocol = MyPOP3Downloader()
     def check(ignored):
         self.assertEqual(clientProtocol.message, self.message)
         protocol.connectionLost(
             failure.Failure(Exception("Test harness disconnect")))
     d = loopback.loopbackAsync(protocol, clientProtocol)
     return d.addCallback(check)
Ejemplo n.º 30
0
 def testLoopback(self):
     protocol =  MyVirtualPOP3()
     protocol.service = self.factory
     clientProtocol = MyPOP3Downloader()
     def check(ignored):
         self.assertEqual(clientProtocol.message, self.message)
         protocol.connectionLost(
             failure.Failure(Exception("Test harness disconnect")))
     d = loopback.loopbackAsync(protocol, clientProtocol)
     return d.addCallback(check)
Ejemplo n.º 31
0
 def testProtocol(self):
     from twisted.protocols import loopback
     server = flow.Protocol()
     server.controller = echoServer
     client = flow.makeProtocol(echoClient)()
     client.factory = protocol.ClientFactory()
     client.factory.d = defer.Deferred()
     d2 = loopback.loopbackAsync(server, client)
     client.factory.d.addCallback(self.assertEquals, 'testing')
     return defer.gatherResults([client.factory.d, d2])
Ejemplo n.º 32
0
 def testLoopback(self):
     server = http.HTTPChannel()
     server.requestFactory = DummyHTTPHandler
     client = LoopbackHTTPClient()
     client.handleResponse = self._handleResponse
     client.handleHeader = self._handleHeader
     client.handleEndHeaders = self._handleEndHeaders
     client.handleStatus = self._handleStatus
     d = loopback.loopbackAsync(server, client)
     d.addCallback(self._cbTestLoopback)
     return d
Ejemplo n.º 33
0
    def testAuthListing(self):
        p = DummyPOP3()
        p.factory = internet.protocol.Factory()
        p.factory.challengers = {'Auth1': None, 'secondAuth': None, 'authLast': None}
        client = LineSendingProtocol([
            "AUTH",
            "QUIT",
        ])

        d = loopback.loopbackAsync(p, client)
        return d.addCallback(self._cbTestAuthListing, client)
Ejemplo n.º 34
0
    def _producertest(self, producerClass):
        toProduce = list(map(intToBytes, range(0, 10)))

        class ProducingProtocol(Protocol):
            def connectionMade(self):
                self.producer = producerClass(list(toProduce))
                self.producer.start(self.transport)

        class ReceivingProtocol(Protocol):
            bytes = b""
            def dataReceived(self, data):
                self.bytes += data
                if self.bytes == b''.join(toProduce):
                    self.received.callback((client, server))

        server = ProducingProtocol()
        client = ReceivingProtocol()
        client.received = Deferred()

        loopback.loopbackAsync(server, client)
        return client.received
Ejemplo n.º 35
0
    def _producertest(self, producerClass):
        toProduce = list(map(intToBytes, range(0, 10)))

        class ProducingProtocol(Protocol):
            def connectionMade(self):
                self.producer = producerClass(list(toProduce))
                self.producer.start(self.transport)

        class ReceivingProtocol(Protocol):
            bytes = b""
            def dataReceived(self, data):
                self.bytes += data
                if self.bytes == b''.join(toProduce):
                    self.received.callback((client, server))

        server = ProducingProtocol()
        client = ReceivingProtocol()
        client.received = Deferred()

        loopback.loopbackAsync(server, client)
        return client.received
Ejemplo n.º 36
0
    def test_Stop(self):
        """
        You can stop the whole server.
        """
        server = Server(FakePlumber())
        client = SingleCommandClient(Stop)

        from twisted.protocols.loopback import loopbackAsync
        def check(response):
            self.assertEqual(server.plumber.called, ['stop'])
        r = loopbackAsync(server, client)
        return r.addCallback(check)
Ejemplo n.º 37
0
    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
Ejemplo n.º 38
0
    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
Ejemplo n.º 39
0
 def runTest(self, lines):
     dummy = DummyPOP3()
     client = LineSendingProtocol([
         "APOP moshez dummy",
         "LIST",
         "UIDL",
         "RETR 1",
         "RETR 2",
         "DELE 1",
         "RETR 1",
         "QUIT",
     ])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbRunTest, client, dummy)
Ejemplo n.º 40
0
    def setUp(self):
        self.timeout = 5
        self.log = logging.getLogger("sender")
        self.mqm = messagequeue.MessageQueueManager()
        self.mqs = mqsecurity.MQPortal(self.mqm, None)
        self.mqm.set_queue_rights(queue_rights)
 
        self.factory = StompFactory(mqm=self.mqm)
        self.factory.mq_portal = self.mqs
        self.serverProtocol = self.factory.buildProtocol(None)
        self.serverProtocol.log = self.log
        self.client = StompClientProtocol('users','users')
        self.client.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol, self.client)
Ejemplo n.º 41
0
    def test_RemovePipe(self):
        """
        You can remove a pipe.
        """
        server = Server(FakePlumber())
        client = SingleCommandClient(RemovePipe, src='foo')

        from twisted.protocols.loopback import loopbackAsync
        def check(response):
            self.assertEqual(server.plumber.called, [
                ('rmPipe', 'foo'),
            ])
        r = loopbackAsync(server, client)
        return r.addCallback(check)        
Ejemplo n.º 42
0
 def runTest(self, lines):
     dummy = DummyPOP3()
     client = LineSendingProtocol([
         "APOP moshez dummy",
         "LIST",
         "UIDL",
         "RETR 1",
         "RETR 2",
         "DELE 1",
         "RETR 1",
         "QUIT",
     ])
     d = loopback.loopbackAsync(dummy, client)
     return d.addCallback(self._cbRunTest, client, dummy)
Ejemplo n.º 43
0
    def test_Switch(self):
        """
        You can switch forwarding
        """
        server = Server(FakePlumber())
        client = SingleCommandClient(Switch, src='foo', dst='bar')

        from twisted.protocols.loopback import loopbackAsync
        def check(response):
            self.assertEqual(server.plumber.called, [
                ('pipeCommand', 'foo', 'switch', ('bar',), {}),
            ])
        r = loopbackAsync(server, client)
        return r.addCallback(check)
Ejemplo n.º 44
0
    def setUp(self):
        self.timeout = 5
        self.log = logging.getLogger("sender")
        self.mqm = messagequeue.MessageQueueManager()
        self.mqs = mqsecurity.MQPortal(self.mqm, None)
        self.mqm.set_queue_rights(queue_rights)

        self.factory = StompFactory(mqm=self.mqm)
        self.factory.mq_portal = self.mqs
        self.serverProtocol = self.factory.buildProtocol(None)
        self.serverProtocol.log = self.log
        self.client = StompClientProtocol('users', 'users')
        self.client.log = self.log
        self.loopbackBody = loopback.loopbackAsync(self.serverProtocol,
                                                   self.client)
Ejemplo n.º 45
0
 def testFileTransfer(self):
     auth = 1234
     sender = msn.FileSend(self.input)
     sender.auth = auth
     sender.fileSize = 7000
     client = msn.FileReceive(auth, "*****@*****.**", self.output)
     client.fileSize = 7000
     def check(ignored):
         self.failUnless((client.completed and sender.completed),
                         msg="send failed to complete")
         self.failUnless((self.input.getvalue() == self.output.getvalue()),
                         msg="saved file does not match original")
     d = loopback.loopbackAsync(sender, client)
     d.addCallback(check)
     return d
Ejemplo n.º 46
0
    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])
Ejemplo n.º 47
0
 def setUp(self):
     """
     Create a L{CredReceiver} hooked up to a fake L{IBoxSender} which
     records boxes sent through it.
     """
     self.username = '******'
     self.password = '******'
     self.checker = InMemoryUsernamePasswordDatabaseDontUse()
     self.checker.addUser(self.username, self.password)
     self.avatar = StubAvatar()
     self.realm = StubRealm(self.avatar)
     self.portal = Portal(self.realm, [self.checker])
     self.server = CredReceiver()
     self.server.portal = self.portal
     self.client = AMP()
     self.finished = loopbackAsync(self.server, self.client)
Ejemplo n.º 48
0
 def setUp(self):
     """
     Create a L{CredReceiver} hooked up to a fake L{IBoxSender} which
     records boxes sent through it.
     """
     self.username = '******'
     self.password = '******'
     self.checker = InMemoryUsernamePasswordDatabaseDontUse()
     self.checker.addUser(self.username, self.password)
     self.avatar = StubAvatar()
     self.realm = StubRealm(self.avatar)
     self.portal = Portal(self.realm, [self.checker])
     self.server = CredReceiver()
     self.server.portal = self.portal
     self.client = AMP()
     self.finished = loopbackAsync(self.server, self.client)
Ejemplo n.º 49
0
    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])
Ejemplo n.º 50
0
    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
Ejemplo n.º 51
0
    def testFileTransfer(self):
        auth = 1234
        sender = msn.FileSend(self.input)
        sender.auth = auth
        sender.fileSize = 7000
        client = msn.FileReceive(auth, "*****@*****.**", self.output)
        client.fileSize = 7000

        def check(ignored):
            self.failUnless((client.completed and sender.completed),
                            msg="send failed to complete")
            self.failUnless((self.input.getvalue() == self.output.getvalue()),
                            msg="saved file does not match original")

        d = loopback.loopbackAsync(sender, client)
        d.addCallback(check)
        return d
Ejemplo n.º 52
0
    def test_authListing(self):
        """
        L{pop3.POP3} responds to an I{AUTH} command with a list of supported
        authentication types based on its factory's C{challengers}.
        """
        p = DummyPOP3()
        p.factory = internet.protocol.Factory()
        p.factory.challengers = {b"Auth1": None, b"secondAuth": None, b"authLast": None}
        client = LineSendingProtocol(
            [
                b"AUTH",
                b"QUIT",
            ]
        )

        d = loopback.loopbackAsync(p, client)
        return d.addCallback(self._cbTestAuthListing, client)
Ejemplo n.º 53
0
    def runTest(self, lines, expectedOutput):
        """
        Assert that when C{lines} are delivered to L{pop3.POP3} it responds
        with C{expectedOutput}.

        @param lines: A sequence of L{bytes} representing lines to deliver to
            the server.

        @param expectedOutput: A sequence of L{bytes} representing the
            expected response from the server.

        @return: A L{Deferred} that fires when the lines have been delivered
            and the output checked.
        """
        dummy = DummyPOP3()
        client = LineSendingProtocol(lines)
        d = loopback.loopbackAsync(dummy, client)
        return d.addCallback(self._cbRunTest, client, dummy, expectedOutput)
Ejemplo n.º 54
0
    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
Ejemplo n.º 55
0
    def test_loopback(self):
        """
        Test that the userauth server and client play nicely with each other.
        """
        server = userauth.SSHUserAuthServer()
        client = ClientUserAuth('foo', self.Factory.Service())

        # set up transports
        server.transport = transport.SSHTransportBase()
        server.transport.service = server
        server.transport.isEncrypted = lambda x: True
        client.transport = transport.SSHTransportBase()
        client.transport.service = client
        server.transport.sessionID = client.transport.sessionID = ''
        # don't send key exchange packet
        server.transport.sendKexInit = client.transport.sendKexInit = \
                lambda: None

        # set up server authentication
        server.transport.factory = self.Factory()
        server.passwordDelay = 0  # remove bad password delay
        realm = Realm()
        portal = Portal(realm)
        checker = SSHProtocolChecker()
        checker.registerChecker(PasswordChecker())
        checker.registerChecker(PrivateKeyChecker())
        checker.registerChecker(PAMChecker())
        checker.areDone = lambda aId: (len(checker.successfulCredentials[aId])
                                       == 3)
        portal.registerChecker(checker)
        server.transport.factory.portal = portal

        d = loopback.loopbackAsync(server.transport, client.transport)
        server.transport.transport.logPrefix = lambda: '_ServerLoopback'
        client.transport.transport.logPrefix = lambda: '_ClientLoopback'

        server.serviceStarted()
        client.serviceStarted()

        def check(ignored):
            self.assertEquals(server.transport.service.name, 'TestService')

        return d.addCallback(check)
Ejemplo n.º 56
0
 def test_Wait(self):
     """
     You can wait for connections to settle.
     """
     wait_ret = defer.Deferred()
     server = Server(FakePlumber({
         'pipeCommand': wait_ret,
     }))
     client = SingleCommandClient(Wait, src='foo')
     
     from twisted.protocols.loopback import loopbackAsync
     def check(response):
         self.assertEqual(server.plumber.called, [
             ('pipeCommand', 'foo', 'wait', (), {}),
         ])
     r = loopbackAsync(server, client)
     self.assertFalse(r.called)
     wait_ret.callback(None)
     return r.addCallback(check)
Ejemplo n.º 57
0
 def test_fileTransfer(self):
     """
     Test L{FileSend} against L{FileReceive} using a loopback transport.
     """
     auth = 1234
     sender = msn.FileSend(StringIO.StringIO(self.input))
     sender.auth = auth
     sender.fileSize = 7000
     client = msn.FileReceive(auth, "*****@*****.**", self.output)
     client.fileSize = 7000
     def check(ignored):
         self.assertTrue(
             client.completed and sender.completed,
             msg="send failed to complete")
         self.assertEqual(
             self.input, self.output.getvalue(),
             msg="saved file does not match original")
     d = loopback.loopbackAsync(sender, client)
     d.addCallback(check)
     return d
Ejemplo n.º 58
0
    def test_multipleWrites(self):
        """
        If multiple separate TLS messages are received in a single chunk from
        the underlying transport, all of the application bytes from each
        message are delivered to the application-level protocol.
        """
        bytes = [str(i) for i in range(10)]

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

        clientFactory = ClientFactory()
        clientFactory.protocol = SimpleSendingProtocol

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

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

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

        connectionDeferred = loopbackAsync(sslServerProtocol,
                                           sslClientProtocol,
                                           collapsingPumpPolicy)

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

        connectionDeferred.addCallback(cbConnectionDone)
        return connectionDeferred