twisted.internet.main.CONNECTION_DONE

Here are the examples of the python api twisted.internet.main.CONNECTION_DONE taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

51 Examples 7

Example 1

Project: foolscap
Source File: client.py
View license
    def childConnectionLost(self, fd, reason):
        # the usual StandardIO class doesn't seem to handle half-closed stdio
        # well, specifically when our stdout is closed, then some data is
        # written to our stdin. The class responds to stdout's closure by
        # shutting down everything. I think this is related to
        # ProcessWriter.doRead returning CONNECTION_LOST instead of
        # CONNECTION_DONE (which ProcessWriter.connectionLost sends along to
        # StandardIO.childConnectionLost). There is code in
        # StandardIO.childConnectionLost to treat CONNECTION_DONE as a
        # half-close, but not CONNECTION_LOST.
        #
        # so this hack is to make it look more like a half-close
        #print >>sys.stderr, "my StandardIO.childConnectionLost", fd, reason.value
        from twisted.internet import error, main
        from twisted.python import failure
        if reason.check(error.ConnectionLost) and fd == "write":
            #print >>sys.stderr, " fixing"
            reason = failure.Failure(main.CONNECTION_DONE)
        return TwitchyStandardIO.childConnectionLost(self, fd, reason)

Example 2

Project: twisted-intro
Source File: get-poetry-broken.py
View license
    def doRead(self):
        poem = ''

        while True: # we're just reading everything (blocking) -- broken!
            bytes = self.sock.recv(1024)
            if not bytes:
                break
            poem += bytes

        msg = 'Task %d: got %d bytes of poetry from %s'
        print  msg % (self.task_num, len(poem), self.format_addr())

        self.poem = poem

        return main.CONNECTION_DONE

Example 3

Project: twisted-intro
Source File: get-poetry-broken.py
View license
    def doRead(self):
        poem = ''

        while True: # we're just reading everything (blocking) -- broken!
            bytes = self.sock.recv(1024)
            if not bytes:
                break
            poem += bytes

        msg = 'Task %d: got %d bytes of poetry from %s'
        print  msg % (self.task_num, len(poem), self.format_addr())

        self.poem = poem

        return main.CONNECTION_DONE

Example 4

Project: mythbox
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 5

Project: mythbox
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 6

Project: mythbox
Source File: tcp.py
View license
    def _closeWriteConnection(self):
        result = self._sendCloseAlert()

        if result is main.CONNECTION_DONE:
            return Connection._closeWriteConnection(self)

        return result

Example 7

Project: mythbox
Source File: tcp.py
View license
    def _closeWriteConnection(self):
        result = self._sendCloseAlert()

        if result is main.CONNECTION_DONE:
            return Connection._closeWriteConnection(self)

        return result

Example 8

Project: mythbox
Source File: _win32stdio.py
View license
    def checkConnLost(self):
        self.connsLost += 1
        if self.connsLost >= 2:
            self.disconnecting = True
            self.disconnected = True
            self.proto.connectionLost(Failure(main.CONNECTION_DONE))

Example 9

Project: mythbox
Source File: _win32stdio.py
View license
    def checkConnLost(self):
        self.connsLost += 1
        if self.connsLost >= 2:
            self.disconnecting = True
            self.disconnected = True
            self.proto.connectionLost(Failure(main.CONNECTION_DONE))

Example 10

Project: mythbox
Source File: loopback.py
View license
    def clearBuffer(self):
        if self.shouldLose == -1:
            return

        if self.producer:
            self.producer.resumeProducing()
        if self.buffer:
            if self.logFile:
                self.logFile.write("loopback receiving %s\n" % repr(self.buffer))
            buffer = self.buffer
            self.buffer = ''
            self.target.dataReceived(buffer)
        if self.shouldLose == 1:
            self.shouldLose = -1
            self.target.connectionLost(failure.Failure(main.CONNECTION_DONE))

Example 11

Project: mythbox
Source File: loopback.py
View license
    def clearBuffer(self):
        if self.shouldLose == -1:
            return

        if self.producer:
            self.producer.resumeProducing()
        if self.buffer:
            if self.logFile:
                self.logFile.write("loopback receiving %s\n" % repr(self.buffer))
            buffer = self.buffer
            self.buffer = ''
            self.target.dataReceived(buffer)
        if self.shouldLose == 1:
            self.shouldLose = -1
            self.target.connectionLost(failure.Failure(main.CONNECTION_DONE))

Example 12

Project: TwistedBot
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 13

Project: TwistedBot
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 14

Project: TwistedBot
Source File: tcp.py
View license
    def _dataReceived(self, data):
        if not data:
            return main.CONNECTION_DONE
        rval = self.protocol.dataReceived(data)
        if rval is not None:
            offender = self.protocol.dataReceived
            warningFormat = (
                'Returning a value other than None from %(fqpn)s is '
                'deprecated since %(version)s.')
            warningString = deprecate.getDeprecationWarningString(
                offender, versions.Version('Twisted', 11, 0, 0),
                format=warningFormat)
            deprecate.warnAboutFunction(offender, warningString)
        return rval

Example 15

Project: TwistedBot
Source File: tcp.py
View license
    def _dataReceived(self, data):
        if not data:
            return main.CONNECTION_DONE
        rval = self.protocol.dataReceived(data)
        if rval is not None:
            offender = self.protocol.dataReceived
            warningFormat = (
                'Returning a value other than None from %(fqpn)s is '
                'deprecated since %(version)s.')
            warningString = deprecate.getDeprecationWarningString(
                offender, versions.Version('Twisted', 11, 0, 0),
                format=warningFormat)
            deprecate.warnAboutFunction(offender, warningString)
        return rval

Example 16

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 17

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _postLoseConnection(self):
        """Called after a loseConnection(), when all data has been written.

        Whatever this returns is then returned by doWrite.
        """
        # default implementation, telling reactor we're finished
        return main.CONNECTION_DONE

Example 18

Project: SubliminalCollaborator
Source File: tcp.py
View license
    def _dataReceived(self, data):
        if not data:
            return main.CONNECTION_DONE
        rval = self.protocol.dataReceived(data)
        if rval is not None:
            offender = self.protocol.dataReceived
            warningFormat = (
                'Returning a value other than None from %(fqpn)s is '
                'deprecated since %(version)s.')
            warningString = deprecate.getDeprecationWarningString(
                offender, versions.Version('Twisted', 11, 0, 0),
                format=warningFormat)
            deprecate.warnAboutFunction(offender, warningString)
        return rval

Example 19

Project: SubliminalCollaborator
Source File: tcp.py
View license
    def _dataReceived(self, data):
        if not data:
            return main.CONNECTION_DONE
        rval = self.protocol.dataReceived(data)
        if rval is not None:
            offender = self.protocol.dataReceived
            warningFormat = (
                'Returning a value other than None from %(fqpn)s is '
                'deprecated since %(version)s.')
            warningString = deprecate.getDeprecationWarningString(
                offender, versions.Version('Twisted', 11, 0, 0),
                format=warningFormat)
            deprecate.warnAboutFunction(offender, warningString)
        return rval

Example 20

View license
    def checkConnLost(self):
        self.connsLost += 1
        if self.connsLost >= 2:
            self.disconnecting = True
            self.disconnected = True
            self.proto.connectionLost(Failure(main.CONNECTION_DONE))

Example 21

View license
    def checkConnLost(self):
        self.connsLost += 1
        if self.connsLost >= 2:
            self.disconnecting = True
            self.disconnected = True
            self.proto.connectionLost(Failure(main.CONNECTION_DONE))

Example 22

Project: SubliminalCollaborator
Source File: loopback.py
View license
    def clearBuffer(self):
        if self.shouldLose == -1:
            return

        if self.producer:
            self.producer.resumeProducing()
        if self.buffer:
            if self.logFile:
                self.logFile.write("loopback receiving %s\n" % repr(self.buffer))
            buffer = self.buffer
            self.buffer = ''
            self.target.dataReceived(buffer)
        if self.shouldLose == 1:
            self.shouldLose = -1
            self.target.connectionLost(failure.Failure(main.CONNECTION_DONE))

Example 23

Project: SubliminalCollaborator
Source File: loopback.py
View license
    def clearBuffer(self):
        if self.shouldLose == -1:
            return

        if self.producer:
            self.producer.resumeProducing()
        if self.buffer:
            if self.logFile:
                self.logFile.write("loopback receiving %s\n" % repr(self.buffer))
            buffer = self.buffer
            self.buffer = ''
            self.target.dataReceived(buffer)
        if self.shouldLose == 1:
            self.shouldLose = -1
            self.target.connectionLost(failure.Failure(main.CONNECTION_DONE))

Example 24

Project: flumotion
Source File: feed.py
View license
    def sendFeed(self, host, port, authenticator, fullFeedId):
        """Send a feed to a remote feed server.

        This helper method calls startConnecting() to make the
        connection and authenticate, and will return the feed file
        descriptor or an error. A pending connection attempt can be
        cancelled via stopConnecting().

        @param host:          the remote host name
        @type  host:          str
        @param port:          the tcp port on which to connect
        @type  port:          int
        @param authenticator: the authenticator, normally provided by
                              the worker
        @type  authenticator: L{flumotion.twisted.pb.Authenticator}
        @param fullFeedId:    the full feed id (/flow/component:eaterAlias)
                              to feed to on the remote size
        @type  fullFeedId:    str

        @returns: a deferred that, if successful, will fire with a pair
                  (feedId, fd). In an error case it will errback and close the
                  remote connection.
        """

        def connected(remote):
            assert isinstance(remote.broker.transport, _SocketMaybeCloser)
            self.setRemoteReference(remote)
            return remote.callRemote('receiveFeed', fullFeedId)

        def feedSent(res):
            t = self.remote.broker.transport
            self.debug('stop reading from transport')
            t.stopReading()

            self.debug('flushing PB write queue')
            t.doWrite()
            self.debug('stop writing to transport')
            t.stopWriting()

            t.keepSocketAlive = True
            fd = os.dup(t.fileno())

            # avoid refcount cycles
            self.setRemoteReference(None)

            d = defer.Deferred()

            def loseConnection():
                t.connectionLost(failure.Failure(main.CONNECTION_DONE))
                d.callback((fullFeedId, fd))

            reactor.callLater(0, loseConnection)
            return d

        def error(failure):
            self.warning('failed to retrieve %s from %s:%d', fullFeedId,
                         host, port)
            self.debug('failure: %s', log.getFailureMessage(failure))
            self.debug('closing connection')
            self.stopConnecting()
            return failure

        d = self.startConnecting(host, port, authenticator)
        d.addCallback(connected)
        d.addCallback(feedSent)
        d.addErrback(error)
        return d

Example 25

Project: flumotion
Source File: feed.py
View license
    def _doFeedTo(self, fullFeedId, t):
        self.debug('flushing PB write queue')
        t.doWrite()
        self.debug('stop writing to transport')
        t.stopWriting()

        # make sure shutdown() is not called on the socket
        t.keepSocketAlive = True

        fd = os.dup(t.fileno())
        # Similar to feedserver._sendFeedReplyCb, but since we are in a
        # callLater, not doReadOrWrite, we call connectionLost directly
        # on the transport.
        t.connectionLost(failure.Failure(main.CONNECTION_DONE))

        # This medium object is of no use any more; drop our reference
        # to the remote so we can avoid cycles.
        self.setRemoteReference(None)

        (flowName, componentName, feedName) = common.parseFullFeedId(
            fullFeedId)
        feedId = common.feedId(componentName, feedName)

        self.debug('firing deferred with feedId %s on fd %d', feedId,
                   fd)
        self._feedToDeferred.callback((feedId, fd))

Example 26

Project: flumotion
Source File: test_component_feed.py
View license
    def testConnectAndFeed(self):
        client = feed.FeedMedium(logName='test')

        def login():
            port = self.feedServer.getPortNum()
            self.assertAdditionalFDsOpen(1, 'connect (socket)')
            d = client.startConnecting('localhost', port,
                                       fpb.Authenticator(username='user',
                                                         password='test',
                                                         avatarId='test:src'))
            self.assertAdditionalFDsOpen(2, 'connect (socket, client)')
            return d

        def receiveFeed(remote):
            client.setRemoteReference(remote)
            self.assertAdditionalFDsOpen(3, 'feed (socket, client, server)')
            return remote.callRemote('receiveFeed', '/foo/bar:baz')

        def feedReceived(thisValueIsNone):
            return self.feedServer.waitForAvatarExit()

        def serverFdPassed(res):
            self.assertAdditionalFDsOpen(2, 'feedSent (socket, client)')

            t = client.remote.broker.transport
            self.info('stop reading from transport')
            t.stopReading()

            self.info('flushing PB write queue')
            t.doWrite()
            self.info('stop writing to transport')
            t.stopWriting()

            t.keepSocketAlive = True

            # avoid refcount cycles
            client.setRemoteReference(None)

            # Since we need to be able to know when the file descriptor
            # closes, and we currently could be within a doReadOrWrite
            # callstack, close the fd from within a callLater instead to
            # avoid corrupting the reactor's internal state.
            d = defer.Deferred()

            def loseConnection():
                t.connectionLost(failure.Failure(main.CONNECTION_DONE))
                d.callback(None)

            reactor.callLater(0, loseConnection)
            return d

        def checkfds(_):
            self.assertAdditionalFDsOpen(1, 'feedReadyOnServer (socket)')

        d = login()
        d.addCallback(receiveFeed)
        d.addCallback(feedReceived)
        d.addCallback(serverFdPassed)
        d.addCallback(checkfds)
        return d

Example 27

Project: txpostgres
Source File: txpostgres.py
View license
    def close(self):
        """
        Close the connection and disconnect from the database.

        :return: :class:`None`
        """
        # We'll be closing the underlying socket so stop watching it.
        self.reactor.removeReader(self)
        self.reactor.removeWriter(self)

        # make it safe to call Connection.close() multiple times, psycopg2
        # treats this as an error but we don't
        if not self._connection.closed:
            self._connection.close()

        # The above closed the connection socket from C code. Normally we would
        # get connectionLost called on all readers and writers of that socket,
        # but not if we're using the epoll reactor. According to the epoll(2)
        # man page, closing a file descriptor causes it to be removed from all
        # epoll sets automatically. In that case, the reactor might not have
        # the chance to notice that the connection has been closed. To cover
        # that, call connectionLost explicitly on the Connection and all
        # outstanding Cursors. It's OK if connectionLost ends up being called
        # twice, as the second call will not have any effects.

        for cursor in set(self._cursors):
            cursor.connectionLost(failure.Failure(main.CONNECTION_DONE))

        self.connectionLost(failure.Failure(main.CONNECTION_DONE))

Example 28

Project: mythbox
Source File: gtk2reactor.py
View license
    def _doReadOrWrite(self, source, condition, faildict={
        error.ConnectionDone: failure.Failure(error.ConnectionDone()),
        error.ConnectionLost: failure.Failure(error.ConnectionLost()),
        }):
        why = None
        inRead = False
        if condition & POLL_DISCONNECTED and not (condition & gobject.IO_IN):
            if source in self._reads:
                why = main.CONNECTION_DONE
                inRead = True
            else:
                why = main.CONNECTION_LOST
        else:
            try:
                if condition & gobject.IO_IN:
                    why = source.doRead()
                    inRead = True
                if not why and condition & gobject.IO_OUT:
                    # if doRead caused connectionLost, don't call doWrite
                    # if doRead is doWrite, don't call it again.
                    if not source.disconnected:
                        why = source.doWrite()
            except:
                why = sys.exc_info()[1]
                log.msg('Error In %s' % source)
                log.deferr()

        if why:
            self._disconnectSelectable(source, why, inRead)

Example 29

Project: mythbox
Source File: abstract.py
View license
    def _handleRead(self, rc, bytes, evt):
        """
        Returns False if we should stop reading for now
        """
        if self.disconnected:
            return False
        # graceful disconnection
        if (not (rc or bytes)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
            self.reactor.removeActiveHandle(self)
            self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        elif rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("read error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            assert self._readSize == 0
            assert self._readNextBuffer == 0
            self._readSize = bytes
            return self._dispatchData()

Example 30

Project: mythbox
Source File: abstract.py
View license
    def _handleWrite(self, rc, bytes, evt):
        """
        Returns false if we should stop writing for now
        """
        if self.disconnected or self._writeDisconnected:
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        if rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("write error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            self.offset += bytes
            # If there is nothing left to send,
            if self.offset == len(self.dataBuffer) and not self._tempDataLen:
                self.dataBuffer = ""
                self.offset = 0
                # stop writing
                self.stopWriting()
                # If I've got a producer who is supposed to supply me with data
                if self.producer is not None and ((not self.streamingProducer)
                                                  or self.producerPaused):
                    # tell them to supply some more.
                    self.producerPaused = True
                    self.producer.resumeProducing()
                elif self.disconnecting:
                    # But if I was previously asked to let the connection die,
                    # do so.
                    self.connectionLost(failure.Failure(main.CONNECTION_DONE))
                elif self._writeDisconnecting:
                    # I was previously asked to to half-close the connection.
                    self._closeWriteConnection()
                    self._writeDisconnected = True
                return False
            else:
                return True

Example 31

Project: mythbox
Source File: pollreactor.py
View license
    def _doReadOrWrite(self, selectable, fd, event):
        why = None
        inRead = False
        if event & POLL_DISCONNECTED and not (event & POLLIN):
            if fd in self._reads:
                why = main.CONNECTION_DONE
                inRead = True
            else:
                why = main.CONNECTION_LOST
        else:
            try:
                if event & POLLIN:
                    why = selectable.doRead()
                    inRead = True
                if not why and event & POLLOUT:
                    why = selectable.doWrite()
                    inRead = False
                if not selectable.fileno() == fd:
                    why = error.ConnectionFdescWentAway('Filedescriptor went away')
                    inRead = False
            except:
                log.deferr()
                why = sys.exc_info()[1]
        if why:
            self._disconnectSelectable(selectable, why, inRead)

Example 32

Project: mythbox
Source File: gtk2reactor.py
View license
    def _doReadOrWrite(self, source, condition, faildict={
        error.ConnectionDone: failure.Failure(error.ConnectionDone()),
        error.ConnectionLost: failure.Failure(error.ConnectionLost()),
        }):
        why = None
        inRead = False
        if condition & POLL_DISCONNECTED and not (condition & gobject.IO_IN):
            if source in self._reads:
                why = main.CONNECTION_DONE
                inRead = True
            else:
                why = main.CONNECTION_LOST
        else:
            try:
                if condition & gobject.IO_IN:
                    why = source.doRead()
                    inRead = True
                if not why and condition & gobject.IO_OUT:
                    # if doRead caused connectionLost, don't call doWrite
                    # if doRead is doWrite, don't call it again.
                    if not source.disconnected:
                        why = source.doWrite()
            except:
                why = sys.exc_info()[1]
                log.msg('Error In %s' % source)
                log.deferr()

        if why:
            self._disconnectSelectable(source, why, inRead)

Example 33

Project: mythbox
Source File: abstract.py
View license
    def _handleRead(self, rc, bytes, evt):
        """
        Returns False if we should stop reading for now
        """
        if self.disconnected:
            return False
        # graceful disconnection
        if (not (rc or bytes)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
            self.reactor.removeActiveHandle(self)
            self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        elif rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("read error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            assert self._readSize == 0
            assert self._readNextBuffer == 0
            self._readSize = bytes
            return self._dispatchData()

Example 34

Project: mythbox
Source File: abstract.py
View license
    def _handleWrite(self, rc, bytes, evt):
        """
        Returns false if we should stop writing for now
        """
        if self.disconnected or self._writeDisconnected:
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        if rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("write error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            self.offset += bytes
            # If there is nothing left to send,
            if self.offset == len(self.dataBuffer) and not self._tempDataLen:
                self.dataBuffer = ""
                self.offset = 0
                # stop writing
                self.stopWriting()
                # If I've got a producer who is supposed to supply me with data
                if self.producer is not None and ((not self.streamingProducer)
                                                  or self.producerPaused):
                    # tell them to supply some more.
                    self.producerPaused = True
                    self.producer.resumeProducing()
                elif self.disconnecting:
                    # But if I was previously asked to let the connection die,
                    # do so.
                    self.connectionLost(failure.Failure(main.CONNECTION_DONE))
                elif self._writeDisconnecting:
                    # I was previously asked to to half-close the connection.
                    self._closeWriteConnection()
                    self._writeDisconnected = True
                return False
            else:
                return True

Example 35

Project: mythbox
Source File: tcp.py
View license
    def doRead(self):
        if self.disconnected:
            # See the comment in the similar check in doWrite below.
            # Additionally, in order for anything other than returning
            # CONNECTION_DONE here to make sense, it will probably be necessary
            # to implement a way to switch back to TCP from TLS (actually, if
            # we did something other than return CONNECTION_DONE, that would be
            # a big part of implementing that feature).  In other words, the
            # expectation is that doRead will be called when self.disconnected
            # is True only when the connection has been lost.  It's possible
            # that the other end could stop speaking TLS and then send us some
            # non-TLS data.  We'll end up ignoring that data and dropping the
            # connection.  There's no unit tests for this check in the cases
            # where it makes a difference.  The test suite only hits this
            # codepath when it would have otherwise hit the SSL.ZeroReturnError
            # exception handler below, which has exactly the same behavior as
            # this conditional.  Maybe that's the only case that can ever be
            # triggered, I'm not sure.  -exarkun
            return main.CONNECTION_DONE
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST
        except SSL.Error, e:
            return e

Example 36

Project: mythbox
Source File: pollreactor.py
View license
    def _doReadOrWrite(self, selectable, fd, event):
        why = None
        inRead = False
        if event & POLL_DISCONNECTED and not (event & POLLIN):
            if fd in self._reads:
                why = main.CONNECTION_DONE
                inRead = True
            else:
                why = main.CONNECTION_LOST
        else:
            try:
                if event & POLLIN:
                    why = selectable.doRead()
                    inRead = True
                if not why and event & POLLOUT:
                    why = selectable.doWrite()
                    inRead = False
                if not selectable.fileno() == fd:
                    why = error.ConnectionFdescWentAway('Filedescriptor went away')
                    inRead = False
            except:
                log.deferr()
                why = sys.exc_info()[1]
        if why:
            self._disconnectSelectable(selectable, why, inRead)

Example 37

Project: mythbox
Source File: tcp.py
View license
    def doRead(self):
        if self.disconnected:
            # See the comment in the similar check in doWrite below.
            # Additionally, in order for anything other than returning
            # CONNECTION_DONE here to make sense, it will probably be necessary
            # to implement a way to switch back to TCP from TLS (actually, if
            # we did something other than return CONNECTION_DONE, that would be
            # a big part of implementing that feature).  In other words, the
            # expectation is that doRead will be called when self.disconnected
            # is True only when the connection has been lost.  It's possible
            # that the other end could stop speaking TLS and then send us some
            # non-TLS data.  We'll end up ignoring that data and dropping the
            # connection.  There's no unit tests for this check in the cases
            # where it makes a difference.  The test suite only hits this
            # codepath when it would have otherwise hit the SSL.ZeroReturnError
            # exception handler below, which has exactly the same behavior as
            # this conditional.  Maybe that's the only case that can ever be
            # triggered, I'm not sure.  -exarkun
            return main.CONNECTION_DONE
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST
        except SSL.Error, e:
            return e

Example 38

Project: mythbox
Source File: loopback.py
View license
def _loopbackAsyncBody(server, serverToClient, client, clientToServer,
                       pumpPolicy):
    """
    Transfer bytes from the output queue of each protocol to the input of the other.

    @param server: The protocol instance representing the server-side of this
    connection.

    @param serverToClient: The L{_LoopbackQueue} holding the server's output.

    @param client: The protocol instance representing the client-side of this
    connection.

    @param clientToServer: The L{_LoopbackQueue} holding the client's output.

    @param pumpPolicy: See L{loopbackAsync}.

    @return: A L{Deferred} which fires when the connection has been closed and
        both sides have received notification of this.
    """
    def pump(source, q, target):
        sent = False
        if q:
            pumpPolicy(q, target)
            sent = True
        if sent and not q:
            # A write buffer has now been emptied.  Give any producer on that
            # side an opportunity to produce more data.
            source.transport._pollProducer()

        return sent

    while 1:
        disconnect = clientSent = serverSent = False

        # Deliver the data which has been written.
        serverSent = pump(server, serverToClient, client)
        clientSent = pump(client, clientToServer, server)

        if not clientSent and not serverSent:
            # Neither side wrote any data.  Wait for some new data to be added
            # before trying to do anything further.
            d = defer.Deferred()
            clientToServer._notificationDeferred = d
            serverToClient._notificationDeferred = d
            d.addCallback(
                _loopbackAsyncContinue,
                server, serverToClient, client, clientToServer, pumpPolicy)
            return d
        if serverToClient.disconnect:
            # The server wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(server, serverToClient, client)
        elif clientToServer.disconnect:
            # The client wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(client, clientToServer, server)
        if disconnect:
            # Someone wanted to disconnect, so okay, the connection is gone.
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            return defer.succeed(None)

Example 39

Project: mythbox
Source File: loopback.py
View license
def loopback(server, client, logFile=None):
    """Run session between server and client.
    DEPRECATED in Twisted 2.5. Use loopbackAsync instead.
    """
    import warnings
    warnings.warn('loopback() is deprecated (since Twisted 2.5). '
                  'Use loopbackAsync() instead.',
                  stacklevel=2, category=DeprecationWarning)
    from twisted.internet import reactor
    serverToClient = LoopbackRelay(client, logFile)
    clientToServer = LoopbackRelay(server, logFile)
    server.makeConnection(serverToClient)
    client.makeConnection(clientToServer)
    while 1:
        reactor.iterate(0.01) # this is to clear any deferreds
        serverToClient.clearBuffer()
        clientToServer.clearBuffer()
        if serverToClient.shouldLose:
            serverToClient.clearBuffer()
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            break
        elif clientToServer.shouldLose:
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            break
    reactor.iterate() # last gasp before I go away

Example 40

Project: mythbox
Source File: loopback.py
View license
def _loopbackAsyncBody(server, serverToClient, client, clientToServer,
                       pumpPolicy):
    """
    Transfer bytes from the output queue of each protocol to the input of the other.

    @param server: The protocol instance representing the server-side of this
    connection.

    @param serverToClient: The L{_LoopbackQueue} holding the server's output.

    @param client: The protocol instance representing the client-side of this
    connection.

    @param clientToServer: The L{_LoopbackQueue} holding the client's output.

    @param pumpPolicy: See L{loopbackAsync}.

    @return: A L{Deferred} which fires when the connection has been closed and
        both sides have received notification of this.
    """
    def pump(source, q, target):
        sent = False
        if q:
            pumpPolicy(q, target)
            sent = True
        if sent and not q:
            # A write buffer has now been emptied.  Give any producer on that
            # side an opportunity to produce more data.
            source.transport._pollProducer()

        return sent

    while 1:
        disconnect = clientSent = serverSent = False

        # Deliver the data which has been written.
        serverSent = pump(server, serverToClient, client)
        clientSent = pump(client, clientToServer, server)

        if not clientSent and not serverSent:
            # Neither side wrote any data.  Wait for some new data to be added
            # before trying to do anything further.
            d = defer.Deferred()
            clientToServer._notificationDeferred = d
            serverToClient._notificationDeferred = d
            d.addCallback(
                _loopbackAsyncContinue,
                server, serverToClient, client, clientToServer, pumpPolicy)
            return d
        if serverToClient.disconnect:
            # The server wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(server, serverToClient, client)
        elif clientToServer.disconnect:
            # The client wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(client, clientToServer, server)
        if disconnect:
            # Someone wanted to disconnect, so okay, the connection is gone.
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            return defer.succeed(None)

Example 41

Project: mythbox
Source File: loopback.py
View license
def loopback(server, client, logFile=None):
    """Run session between server and client.
    DEPRECATED in Twisted 2.5. Use loopbackAsync instead.
    """
    import warnings
    warnings.warn('loopback() is deprecated (since Twisted 2.5). '
                  'Use loopbackAsync() instead.',
                  stacklevel=2, category=DeprecationWarning)
    from twisted.internet import reactor
    serverToClient = LoopbackRelay(client, logFile)
    clientToServer = LoopbackRelay(server, logFile)
    server.makeConnection(serverToClient)
    client.makeConnection(clientToServer)
    while 1:
        reactor.iterate(0.01) # this is to clear any deferreds
        serverToClient.clearBuffer()
        clientToServer.clearBuffer()
        if serverToClient.shouldLose:
            serverToClient.clearBuffer()
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            break
        elif clientToServer.shouldLose:
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            break
    reactor.iterate() # last gasp before I go away

Example 42

Project: mythbox
Source File: test_banana.py
View license
    def tearDown(self):
        self.enc.connectionLost(failure.Failure(main.CONNECTION_DONE))
        del self.enc

Example 43

Project: mythbox
Source File: test_banana.py
View license
    def tearDown(self):
        self.enc.connectionLost(failure.Failure(main.CONNECTION_DONE))
        del self.enc

Example 44

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _handleRead(self, rc, bytes, evt):
        """
        Returns False if we should stop reading for now
        """
        if self.disconnected:
            return False
        # graceful disconnection
        if (not (rc or bytes)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
            self.reactor.removeActiveHandle(self)
            self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        elif rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("read error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            assert self._readSize == 0
            assert self._readNextBuffer == 0
            self._readSize = bytes
            return self._dispatchData()

Example 45

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _handleWrite(self, rc, bytes, evt):
        """
        Returns false if we should stop writing for now
        """
        if self.disconnected or self._writeDisconnected:
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        if rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("write error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            self.offset += bytes
            # If there is nothing left to send,
            if self.offset == len(self.dataBuffer) and not self._tempDataLen:
                self.dataBuffer = ""
                self.offset = 0
                # stop writing
                self.stopWriting()
                # If I've got a producer who is supposed to supply me with data
                if self.producer is not None and ((not self.streamingProducer)
                                                  or self.producerPaused):
                    # tell them to supply some more.
                    self.producerPaused = True
                    self.producer.resumeProducing()
                elif self.disconnecting:
                    # But if I was previously asked to let the connection die,
                    # do so.
                    self.connectionLost(failure.Failure(main.CONNECTION_DONE))
                elif self._writeDisconnecting:
                    # I was previously asked to to half-close the connection.
                    self._writeDisconnected = True
                    self._closeWriteConnection()
                return False
            else:
                return True

Example 46

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _handleRead(self, rc, bytes, evt):
        """
        Returns False if we should stop reading for now
        """
        if self.disconnected:
            return False
        # graceful disconnection
        if (not (rc or bytes)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
            self.reactor.removeActiveHandle(self)
            self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        elif rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("read error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            assert self._readSize == 0
            assert self._readNextBuffer == 0
            self._readSize = bytes
            return self._dispatchData()

Example 47

Project: SubliminalCollaborator
Source File: abstract.py
View license
    def _handleWrite(self, rc, bytes, evt):
        """
        Returns false if we should stop writing for now
        """
        if self.disconnected or self._writeDisconnected:
            return False
        # XXX: not handling WSAEWOULDBLOCK
        # ("too many outstanding overlapped I/O requests")
        if rc:
            self.connectionLost(failure.Failure(
                                error.ConnectionLost("write error -- %s (%s)" %
                                    (errno.errorcode.get(rc, 'unknown'), rc))))
            return False
        else:
            self.offset += bytes
            # If there is nothing left to send,
            if self.offset == len(self.dataBuffer) and not self._tempDataLen:
                self.dataBuffer = ""
                self.offset = 0
                # stop writing
                self.stopWriting()
                # If I've got a producer who is supposed to supply me with data
                if self.producer is not None and ((not self.streamingProducer)
                                                  or self.producerPaused):
                    # tell them to supply some more.
                    self.producerPaused = True
                    self.producer.resumeProducing()
                elif self.disconnecting:
                    # But if I was previously asked to let the connection die,
                    # do so.
                    self.connectionLost(failure.Failure(main.CONNECTION_DONE))
                elif self._writeDisconnecting:
                    # I was previously asked to to half-close the connection.
                    self._writeDisconnected = True
                    self._closeWriteConnection()
                return False
            else:
                return True

Example 48

Project: SubliminalCollaborator
Source File: loopback.py
View license
def _loopbackAsyncBody(server, serverToClient, client, clientToServer,
                       pumpPolicy):
    """
    Transfer bytes from the output queue of each protocol to the input of the other.

    @param server: The protocol instance representing the server-side of this
    connection.

    @param serverToClient: The L{_LoopbackQueue} holding the server's output.

    @param client: The protocol instance representing the client-side of this
    connection.

    @param clientToServer: The L{_LoopbackQueue} holding the client's output.

    @param pumpPolicy: See L{loopbackAsync}.

    @return: A L{Deferred} which fires when the connection has been closed and
        both sides have received notification of this.
    """
    def pump(source, q, target):
        sent = False
        if q:
            pumpPolicy(q, target)
            sent = True
        if sent and not q:
            # A write buffer has now been emptied.  Give any producer on that
            # side an opportunity to produce more data.
            source.transport._pollProducer()

        return sent

    while 1:
        disconnect = clientSent = serverSent = False

        # Deliver the data which has been written.
        serverSent = pump(server, serverToClient, client)
        clientSent = pump(client, clientToServer, server)

        if not clientSent and not serverSent:
            # Neither side wrote any data.  Wait for some new data to be added
            # before trying to do anything further.
            d = defer.Deferred()
            clientToServer._notificationDeferred = d
            serverToClient._notificationDeferred = d
            d.addCallback(
                _loopbackAsyncContinue,
                server, serverToClient, client, clientToServer, pumpPolicy)
            return d
        if serverToClient.disconnect:
            # The server wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(server, serverToClient, client)
        elif clientToServer.disconnect:
            # The client wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(client, clientToServer, server)
        if disconnect:
            # Someone wanted to disconnect, so okay, the connection is gone.
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            return defer.succeed(None)

Example 49

Project: SubliminalCollaborator
Source File: loopback.py
View license
def _loopbackAsyncBody(server, serverToClient, client, clientToServer,
                       pumpPolicy):
    """
    Transfer bytes from the output queue of each protocol to the input of the other.

    @param server: The protocol instance representing the server-side of this
    connection.

    @param serverToClient: The L{_LoopbackQueue} holding the server's output.

    @param client: The protocol instance representing the client-side of this
    connection.

    @param clientToServer: The L{_LoopbackQueue} holding the client's output.

    @param pumpPolicy: See L{loopbackAsync}.

    @return: A L{Deferred} which fires when the connection has been closed and
        both sides have received notification of this.
    """
    def pump(source, q, target):
        sent = False
        if q:
            pumpPolicy(q, target)
            sent = True
        if sent and not q:
            # A write buffer has now been emptied.  Give any producer on that
            # side an opportunity to produce more data.
            source.transport._pollProducer()

        return sent

    while 1:
        disconnect = clientSent = serverSent = False

        # Deliver the data which has been written.
        serverSent = pump(server, serverToClient, client)
        clientSent = pump(client, clientToServer, server)

        if not clientSent and not serverSent:
            # Neither side wrote any data.  Wait for some new data to be added
            # before trying to do anything further.
            d = defer.Deferred()
            clientToServer._notificationDeferred = d
            serverToClient._notificationDeferred = d
            d.addCallback(
                _loopbackAsyncContinue,
                server, serverToClient, client, clientToServer, pumpPolicy)
            return d
        if serverToClient.disconnect:
            # The server wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(server, serverToClient, client)
        elif clientToServer.disconnect:
            # The client wants to drop the connection.  Flush any remaining
            # data it has.
            disconnect = True
            pump(client, clientToServer, server)
        if disconnect:
            # Someone wanted to disconnect, so okay, the connection is gone.
            server.connectionLost(failure.Failure(main.CONNECTION_DONE))
            client.connectionLost(failure.Failure(main.CONNECTION_DONE))
            return defer.succeed(None)

Example 50

View license
    def tearDown(self):
        self.enc.connectionLost(failure.Failure(main.CONNECTION_DONE))
        del self.enc