Python twisted.internet.error.ConnectionClosed() Examples

The following are 23 code examples of twisted.internet.error.ConnectionClosed(). 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.error , or try the search function .
Example #1
Source File: amp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def connectionLost(self, reason):
        """
        The connection was lost; notify any nested protocol.
        """
        if self.innerProtocol is not None:
            self.innerProtocol.connectionLost(reason)
            if self.innerProtocolClientFactory is not None:
                self.innerProtocolClientFactory.clientConnectionLost(None, reason)
        if self._keyLengthLimitExceeded:
            failReason = Failure(TooLong(True, False, None, None))
        elif reason.check(ConnectionClosed) and self._justStartedTLS:
            # We just started TLS and haven't received any data.  This means
            # the other connection didn't like our cert (although they may not
            # have told us why - later Twisted should make 'reason' into a TLS
            # error.)
            failReason = PeerVerifyError(
                "Peer rejected our certificate for an unknown reason.")
        else:
            failReason = reason
        self.boxReceiver.stopReceivingBoxes(failReason)


    # The longest key allowed 
Example #2
Source File: test_unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_fileDescriptorOverrun(self):
        """
        If L{IUNIXTransport.sendFileDescriptor} is used to queue a greater
        number of file descriptors than the number of bytes sent using
        L{ITransport.write}, the connection is closed and the protocol connected
        to the transport has its C{connectionLost} method called with a failure
        wrapping L{FileDescriptorOverrun}.
        """
        cargo = socket()
        server = SendFileDescriptor(cargo.fileno(), None)

        client = ReceiveFileDescriptor()
        result = []
        d = client.waitForDescriptor()
        d.addBoth(result.append)
        d.addBoth(lambda ignored: server.transport.loseConnection())

        runProtocolsWithReactor(self, server, client, self.endpoints)

        self.assertIsInstance(result[0], Failure)
        result[0].trap(ConnectionClosed)
        self.assertIsInstance(server.reason.value, FileDescriptorOverrun) 
Example #3
Source File: regionservice.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def handshakeFailed(self, failure):
        """The authenticate handshake failed."""
        if failure.check(ConnectionClosed):
            # There has been a disconnection, clean or otherwise. There's
            # nothing we can do now, so do nothing. The reason will have been
            # logged elsewhere.
            return
        else:
            log.msg(
                "Rack controller '%s' could not be authenticated; dropping "
                "connection. Check that /var/lib/maas/secret on the "
                "controller contains the correct shared key." % self.ident
            )
            if self.transport is not None:
                return self.transport.loseConnection()
            else:
                return 
Example #4
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_surpriseFromInfoCallback(self):
        """
        pyOpenSSL isn't always so great about reporting errors.  If one occurs
        in the verification info callback, it should be logged and the
        connection should be shut down (if possible, anyway; the app_data could
        be clobbered but there's no point testing for that).
        """
        cProto, sProto, pump = self.serviceIdentitySetup(
            u"correct-host.example.com",
            u"correct-host.example.com",
            buggyInfoCallback=True,
        )
        self.assertEqual(cProto.wrappedProtocol.data, b'')
        self.assertEqual(sProto.wrappedProtocol.data, b'')

        cErr = cProto.wrappedProtocol.lostReason.value
        sErr = sProto.wrappedProtocol.lostReason.value

        self.assertIsInstance(cErr, ZeroDivisionError)
        self.assertIsInstance(sErr, (ConnectionClosed, SSL.Error))
        errors = self.flushLoggedErrors(ZeroDivisionError)
        self.assertTrue(errors) 
Example #5
Source File: amp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def connectionLost(self, reason):
        """
        The connection was lost; notify any nested protocol.
        """
        if self.innerProtocol is not None:
            self.innerProtocol.connectionLost(reason)
            if self.innerProtocolClientFactory is not None:
                self.innerProtocolClientFactory.clientConnectionLost(None, reason)
        if self._keyLengthLimitExceeded:
            failReason = Failure(TooLong(True, False, None, None))
        elif reason.check(ConnectionClosed) and self._justStartedTLS:
            # We just started TLS and haven't received any data.  This means
            # the other connection didn't like our cert (although they may not
            # have told us why - later Twisted should make 'reason' into a TLS
            # error.)
            failReason = PeerVerifyError(
                "Peer rejected our certificate for an unknown reason.")
        else:
            failReason = reason
        self.boxReceiver.stopReceivingBoxes(failReason)


    # The longest key allowed 
Example #6
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_invalidHostname(self):
        """
        When a certificate containing an invalid hostname is received from the
        server, the connection is immediately dropped.
        """
        cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
            u"wrong-host.example.com",
            u"correct-host.example.com",
        )
        self.assertEqual(cWrapped.data, b'')
        self.assertEqual(sWrapped.data, b'')

        cErr = cWrapped.lostReason.value
        sErr = sWrapped.lostReason.value

        self.assertIsInstance(cErr, VerificationError)
        self.assertIsInstance(sErr, ConnectionClosed) 
Example #7
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_surpriseFromInfoCallback(self):
        """
        pyOpenSSL isn't always so great about reporting errors.  If one occurs
        in the verification info callback, it should be logged and the
        connection should be shut down (if possible, anyway; the app_data could
        be clobbered but there's no point testing for that).
        """
        cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
            u"correct-host.example.com",
            u"correct-host.example.com",
            buggyInfoCallback=True,
        )

        self.assertEqual(cWrapped.data, b'')
        self.assertEqual(sWrapped.data, b'')

        cErr = cWrapped.lostReason.value
        sErr = sWrapped.lostReason.value

        self.assertIsInstance(cErr, ZeroDivisionError)
        self.assertIsInstance(sErr, (ConnectionClosed, SSL.Error))
        errors = self.flushLoggedErrors(ZeroDivisionError)
        self.assertTrue(errors) 
Example #8
Source File: amp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def connectionLost(self, reason):
        """
        The connection was lost; notify any nested protocol.
        """
        if self.innerProtocol is not None:
            self.innerProtocol.connectionLost(reason)
            if self.innerProtocolClientFactory is not None:
                self.innerProtocolClientFactory.clientConnectionLost(None, reason)
        if self._keyLengthLimitExceeded:
            failReason = Failure(TooLong(True, False, None, None))
        elif reason.check(ConnectionClosed) and self._justStartedTLS:
            # We just started TLS and haven't received any data.  This means
            # the other connection didn't like our cert (although they may not
            # have told us why - later Twisted should make 'reason' into a TLS
            # error.)
            failReason = PeerVerifyError(
                "Peer rejected our certificate for an unknown reason.")
        else:
            failReason = reason
        self.boxReceiver.stopReceivingBoxes(failReason)


    # The longest key allowed 
Example #9
Source File: test_adtran_rest.py    From voltha with Apache License 2.0 5 votes vote down vote up
def test_connection_closed(test_client, mock_treq):
    mock_treq.post.side_effect = ConnectionClosed()
    output = yield test_client.request("POST", "/test/uri", SOME_JSON)
    assert output == ConnectionClosed 
Example #10
Source File: test_regionservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handshakeFailed_does_not_log_when_connection_is_closed(self):
        server = RegionServer()
        with TwistedLoggerFixture() as logger:
            server.handshakeFailed(Failure(ConnectionClosed()))
        # Nothing was logged.
        self.assertEqual("", logger.output) 
Example #11
Source File: test_clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handshakeFailed_does_not_log_when_connection_is_closed(self):
        client = self.make_running_client()
        with TwistedLoggerFixture() as logger:
            client.handshakeFailed(Failure(ConnectionClosed()))
        # ready was set with ConnectionClosed.
        self.assertRaises(ConnectionClosed, extract_result, client.ready.get())
        # Nothing was logged.
        self.assertEqual("", logger.output) 
Example #12
Source File: clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def handshakeFailed(self, failure):
        """The handshake (identify and authenticate) failed."""
        if failure.check(ConnectionClosed):
            # There has been a disconnection, clean or otherwise. There's
            # nothing we can do now, so do nothing. The reason will have been
            # logged elsewhere.
            self.ready.fail(failure)
        else:
            log.err(
                failure,
                "Event-loop '%s' handshake failed; "
                "dropping connection." % self.ident,
            )
            self.transport.loseConnection()
            self.ready.fail(failure) 
Example #13
Source File: test_error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_connectionDoneSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionDone}.
        """
        self.assertTrue(issubclass(error.ConnectionDone,
                                   error.ConnectionClosed)) 
Example #14
Source File: test_error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_connectionLostSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionLost}.
        """
        self.assertTrue(issubclass(error.ConnectionLost,
                                   error.ConnectionClosed)) 
Example #15
Source File: test_transit.py    From magic-wormhole with MIT License 5 votes vote down vote up
def test_connectConsumer(self):
        # connectConsumer() takes an optional number of bytes to expect, and
        # fires a Deferred when that many have been written
        c = transit.Connection(None, None, None, "description")
        c._negotiation_d.addErrback(lambda err: None)  # eat it
        c.transport = proto_helpers.StringTransport()
        c.recordReceived(b"r1.")

        consumer = proto_helpers.StringTransport()
        d = c.connectConsumer(consumer, expected=10)
        self.assertEqual(consumer.value(), b"r1.")
        self.assertNoResult(d)

        c.recordReceived(b"r2.")
        self.assertEqual(consumer.value(), b"r1.r2.")
        self.assertNoResult(d)

        c.recordReceived(b"r3.")
        self.assertEqual(consumer.value(), b"r1.r2.r3.")
        self.assertNoResult(d)

        c.recordReceived(b"!")
        self.assertEqual(consumer.value(), b"r1.r2.r3.!")
        self.assertEqual(self.successResultOf(d), 10)

        # that should automatically disconnect the consumer, and subsequent
        # records should get queued, not delivered
        self.assertIs(c._consumer, None)
        c.recordReceived(b"overflow")
        self.assertEqual(consumer.value(), b"r1.r2.r3.!")

        # now test that the Deferred errbacks when the connection is lost
        d = c.connectConsumer(consumer, expected=10)

        c.connectionLost()
        self.failureResultOf(d, error.ConnectionClosed) 
Example #16
Source File: test_transit.py    From magic-wormhole with MIT License 5 votes vote down vote up
def test_receive_queue(self):
        c = transit.Connection(None, None, None, "description")
        c.transport = FakeTransport(c, None)
        c.transport.signalConnectionLost = False
        c.recordReceived(b"0")
        c.recordReceived(b"1")
        c.recordReceived(b"2")
        d0 = c.receive_record()
        self.assertEqual(self.successResultOf(d0), b"0")
        d1 = c.receive_record()
        d2 = c.receive_record()
        # they must fire in order of receipt, not order of addCallback
        self.assertEqual(self.successResultOf(d2), b"2")
        self.assertEqual(self.successResultOf(d1), b"1")

        d3 = c.receive_record()
        d4 = c.receive_record()
        self.assertNoResult(d3)
        self.assertNoResult(d4)

        c.recordReceived(b"3")
        self.assertEqual(self.successResultOf(d3), b"3")
        self.assertNoResult(d4)

        c.recordReceived(b"4")
        self.assertEqual(self.successResultOf(d4), b"4")

        d5 = c.receive_record()
        c.close()
        self.failureResultOf(d5, error.ConnectionClosed) 
Example #17
Source File: test_error.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_connectionDoneSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionDone}.
        """
        self.assertTrue(issubclass(error.ConnectionDone,
                                   error.ConnectionClosed)) 
Example #18
Source File: test_error.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_connectionLostSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionLost}.
        """
        self.assertTrue(issubclass(error.ConnectionLost,
                                   error.ConnectionClosed)) 
Example #19
Source File: test_error.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_connectionDoneSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionDone}.
        """
        self.assertTrue(issubclass(error.ConnectionDone,
                                   error.ConnectionClosed)) 
Example #20
Source File: test_error.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_connectionLostSubclassOfConnectionClosed(self):
        """
        L{error.ConnectionClosed} is a superclass of L{error.ConnectionLost}.
        """
        self.assertTrue(issubclass(error.ConnectionLost,
                                   error.ConnectionClosed)) 
Example #21
Source File: test_transit.py    From magic-wormhole with MIT License 4 votes vote down vote up
def test_writeToFile(self):
        c = transit.Connection(None, None, None, "description")
        c._negotiation_d.addErrback(lambda err: None)  # eat it
        c.transport = proto_helpers.StringTransport()
        c.recordReceived(b"r1.")

        f = io.BytesIO()
        progress = []
        d = c.writeToFile(f, 10, progress.append)
        self.assertEqual(f.getvalue(), b"r1.")
        self.assertEqual(progress, [3])
        self.assertNoResult(d)

        c.recordReceived(b"r2.")
        self.assertEqual(f.getvalue(), b"r1.r2.")
        self.assertEqual(progress, [3, 3])
        self.assertNoResult(d)

        c.recordReceived(b"r3.")
        self.assertEqual(f.getvalue(), b"r1.r2.r3.")
        self.assertEqual(progress, [3, 3, 3])
        self.assertNoResult(d)

        c.recordReceived(b"!")
        self.assertEqual(f.getvalue(), b"r1.r2.r3.!")
        self.assertEqual(progress, [3, 3, 3, 1])
        self.assertEqual(self.successResultOf(d), 10)

        # that should automatically disconnect the consumer, and subsequent
        # records should get queued, not delivered
        self.assertIs(c._consumer, None)
        c.recordReceived(b"overflow.")
        self.assertEqual(f.getvalue(), b"r1.r2.r3.!")
        self.assertEqual(progress, [3, 3, 3, 1])

        # test what happens when enough data is queued ahead of time
        c.recordReceived(b"second.")  # now "overflow.second."
        c.recordReceived(b"third.")  # now "overflow.second.third."
        f = io.BytesIO()
        d = c.writeToFile(f, 10)
        self.assertEqual(f.getvalue(), b"overflow.second.")  # whole records
        self.assertEqual(self.successResultOf(d), 16)
        self.assertEqual(list(c._inbound_records), [b"third."])

        # now test that the Deferred errbacks when the connection is lost
        d = c.writeToFile(f, 10)

        c.connectionLost()
        self.failureResultOf(d, error.ConnectionClosed) 
Example #22
Source File: test_tcp.py    From python-for-android with Apache License 2.0 4 votes vote down vote up
def test_properlyCloseFiles(self):
        """
        Test that lost connections properly have their underlying socket
        resources cleaned up.
        """
        onServerConnectionLost = defer.Deferred()
        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol(
            onServerConnectionLost)
        serverPort = self.createServer('127.0.0.1', 0, serverFactory)

        onClientConnectionLost = defer.Deferred()
        serverAddr = serverPort.getHost()
        clientCreator = protocol.ClientCreator(
            reactor, lambda: HandleSavingProtocol(onClientConnectionLost))
        clientDeferred = self.connectClient(
            serverAddr.host, serverAddr.port, clientCreator)

        def clientConnected(client):
            """
            Disconnect the client.  Return a Deferred which fires when both
            the client and the server have received disconnect notification.
            """
            client.transport.write(
                'some bytes to make sure the connection is set up')
            client.transport.loseConnection()
            return defer.gatherResults([
                onClientConnectionLost, onServerConnectionLost])
        clientDeferred.addCallback(clientConnected)

        def clientDisconnected((client, server)):
            """
            Verify that the underlying platform socket handle has been
            cleaned up.
            """
            client.lostConnectionReason.trap(error.ConnectionClosed)
            server.lostConnectionReason.trap(error.ConnectionClosed)
            expectedErrorCode = self.getHandleErrorCode()
            err = self.assertRaises(
                self.getHandleExceptionType(), client.handle.send, 'bytes')
            self.assertEqual(err.args[0], expectedErrorCode)
        clientDeferred.addCallback(clientDisconnected)

        def cleanup(passthrough):
            """
            Shut down the server port.  Return a Deferred which fires when
            this has completed.
            """
            result = defer.maybeDeferred(serverPort.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        clientDeferred.addBoth(cleanup)

        return clientDeferred 
Example #23
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def test_properlyCloseFiles(self):
        """
        Test that lost connections properly have their underlying socket
        resources cleaned up.
        """
        onServerConnectionLost = defer.Deferred()
        serverFactory = protocol.ServerFactory()
        serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol(
            onServerConnectionLost)
        serverPort = self.createServer('127.0.0.1', 0, serverFactory)

        onClientConnectionLost = defer.Deferred()
        serverAddr = serverPort.getHost()
        clientCreator = protocol.ClientCreator(
            reactor, lambda: HandleSavingProtocol(onClientConnectionLost))
        clientDeferred = self.connectClient(
            serverAddr.host, serverAddr.port, clientCreator)

        def clientConnected(client):
            """
            Disconnect the client.  Return a Deferred which fires when both
            the client and the server have received disconnect notification.
            """
            client.transport.write(
                b'some bytes to make sure the connection is set up')
            client.transport.loseConnection()
            return defer.gatherResults([
                onClientConnectionLost, onServerConnectionLost])
        clientDeferred.addCallback(clientConnected)

        def clientDisconnected(result):
            """
            Verify that the underlying platform socket handle has been
            cleaned up.
            """
            client, server = result
            if not client.lostConnectionReason.check(error.ConnectionClosed):
                err(client.lostConnectionReason,
                    "Client lost connection for unexpected reason")
            if not server.lostConnectionReason.check(error.ConnectionClosed):
                err(server.lostConnectionReason,
                    "Server lost connection for unexpected reason")
            expectedErrorCode = self.getHandleErrorCode()
            exception = self.assertRaises(
                self.getHandleExceptionType(), client.handle.send, b'bytes')
            self.assertEqual(exception.args[0], expectedErrorCode)
        clientDeferred.addCallback(clientDisconnected)

        def cleanup(passthrough):
            """
            Shut down the server port.  Return a Deferred which fires when
            this has completed.
            """
            result = defer.maybeDeferred(serverPort.stopListening)
            result.addCallback(lambda ign: passthrough)
            return result
        clientDeferred.addBoth(cleanup)

        return clientDeferred