Exemplo n.º 1
0
    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        tlsContext = self.factory._contextFactory.getContext()
        self._tlsConnection = Connection(tlsContext, None)
        if self.factory._isClient:
            self._tlsConnection.set_connect_state()
        else:
            self._tlsConnection.set_accept_state()
        self._appSendBuffer = []

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            # This is the expected case - there's no data in the connection's
            # input buffer yet, so it won't be able to complete the whole
            # handshake now.  If this is the speak-first side of the
            # connection, then some bytes will be in the send buffer now; flush
            # them.
            self._flushSendBIO()
Exemplo n.º 2
0
 def makeConnection(self, transport):
     if isinstance(self.factory, OutgoingConnectionFactory):
         self.factory.rawserver._remove_pending_connection(self.factory.addr)
     self.can_timeout = 1
     self.setTimeout(self.factory.rawserver.config['socket_timeout'])
     self.attachTransport(transport, self.factory.connection, *self.factory.connection_args)
     Protocol.makeConnection(self, transport)
Exemplo n.º 3
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     
     if not self.method in self.allowedMethods:
         self.sendHeaders({'status': '405 Method Not Supported','allow': ', '.join(self.allowedMethods)})
         self.transport.write("\r\n")
         self.transport.loseConnection()
         return
     elif self.method == 'OPTIONS':
         self.sendHeaders()
         self.transport.write("")
         self.transport.loseConnection()
         return
     
     if not self.writeOnly:
         if self.session in self.factory.sessions:
             self.wrappedProtocol = self.factory.sessions[self.session]
         else:
             self.wrappedProtocol = RelayProtocol(self.factory, self.factory.wrappedFactory.buildProtocol(self.transport.addr), self.session, self)
         
         if self.wrappedProtocol.attached:
             self.wrappedProtocol = None
             self.failConnect()
         else:
             if not self.prepConnection():
                 self.disconnecting = False
                 self.wrappedProtocol.makeConnection(self)
     else:
         if self.session in self.factory.sessions:
             self.wrappedProtocol = self.factory.sessions[self.session]
         else:
             self.sendHeaders({'status': '404 Not Found'})
             self.transport.write("\r\n")
             self.transport.loseConnection()
Exemplo n.º 4
0
 def request_shell(self, data):
     protocol = Protocol()
     transport = SSHSessionProcessProtocol(self)
     protocol.makeConnection(transport)
     transport.makeConnection(wrapProtocol(protocol))
     self.client = transport
     return True
Exemplo n.º 5
0
def build_protocol():
    """
    :return: ``Protocol`` hooked up to transport.
    """
    p = Protocol()
    p.makeConnection(StringTransport())
    return p
Exemplo n.º 6
0
    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        self._checkHandshakeStatus()
Exemplo n.º 7
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.transport.write(b"o")
     self.factory.registerProtocol(self)
     self.wrappedProtocol.makeConnection(self)
     self.heartbeat_timer = reactor.callLater(self.parent._options['heartbeat'], self.heartbeat)
Exemplo n.º 8
0
def build_protocol():
    """
    :return: ``Protocol`` hooked up to transport.
    """
    p = Protocol()
    p.makeConnection(StringTransport())
    return p
Exemplo n.º 9
0
    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        self._checkHandshakeStatus()
Exemplo n.º 10
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.transport.write("o")
     self.factory.registerProtocol(self)
     self.wrappedProtocol.makeConnection(self)
     self.heartbeat_timer = reactor.callLater(self.parent._options['heartbeat'], self.heartbeat)
Exemplo n.º 11
0
    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            # This is the expected case - there's no data in the connection's
            # input buffer yet, so it won't be able to complete the whole
            # handshake now.  If this is the speak-first side of the
            # connection, then some bytes will be in the send buffer now; flush
            # them.
            self._flushSendBIO()
Exemplo n.º 12
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     if self.wrappedProtocol:
         self.prepConnection()
         self.wrappedProtocol.makeConnection(self)
     else:
         self.failConnect()
 def makeConnection(self, transport):
     """
     overload Protocol.makeConnection in order to get a reference to the
     transport
     """
     log.msg("ResponseProducerProtocol makeConnection", 
             logLevel=logging.DEBUG)
     Protocol.makeConnection(self, transport)
Exemplo n.º 14
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     if self.wrappedProtocol:
         self.prepConnection()
         self.wrappedProtocol.makeConnection(self)
     else:
         self.failConnect()
Exemplo n.º 15
0
 def makeConnection(self, transport):
     if isinstance(self.factory, OutgoingConnectionFactory):
         self.factory.rawserver._remove_pending_connection(
             self.factory.addr)
     self.can_timeout = 1
     self.setTimeout(self.factory.rawserver.config['socket_timeout'])
     self.attachTransport(transport, self.factory.connection,
                          *self.factory.connection_args)
     Protocol.makeConnection(self, transport)
Exemplo n.º 16
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.attached = True
     self.peer = self.transport.getPeer()
     self.host = self.transport.getHost()
     if self.timeout.active():
         self.timeout.cancel()
     self.sendData()
Exemplo n.º 17
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.attached = True
     self.peer = self.transport.getPeer()
     self.host = self.transport.getHost()
     if self.timeout.active():
         self.timeout.cancel()
     self.sendData()
Exemplo n.º 18
0
 def makeConnection(self, transport):
     """
     When a connection is made, register this wrapper with its factory,
     save the real transport, and connect the wrapped protocol to this
     L{ProtocolWrapper} to intercept any transport calls it makes.
     """
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.factory.registerProtocol(self)
     self.wrappedProtocol.makeConnection(self)
Exemplo n.º 19
0
    def makeConnection(self, transport):
        self.host = transport.getHost()

        device_service = self.factory.service.parent.getServiceNamed('DeviceSlot')

        self.device_factory = device_service.factory

        if self.host.port in self.device_factory.device_list:
            self.device = self.device_factory.device_list[self.host.port]
            Protocol.makeConnection(self, transport)
        else:
            transport.loseConnection()
Exemplo n.º 20
0
    def makeConnection(self, transport):
        """
        Connects the factory to us and us to the underlying transport.

        L{CompressingProtocol.makeConnection}() can't be used because it calls
        makeConnection on the wrapped protocol, which causes a second full
        initialization, while the stream just needs a reset (done by
        L{CompressInitiatingInitializer}).
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        self.wrappedProtocol.transport = self
        transport.protocol = self
Exemplo n.º 21
0
    def makeConnection(self, transport):
        """
        Connects the factory to us and us to the underlying transport.

        L{CompressingProtocol.makeConnection}() can't be used because it calls
        makeConnection on the wrapped protocol, which causes a second full
        initialization, while the stream just needs a reset (done by
        L{CompressInitiatingInitializer}).
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        self.wrappedProtocol.transport = self
        transport.protocol = self
Exemplo n.º 22
0
    def makeConnection(self, transport):
        self.attachTransport(transport, self.wrapper)

        self.can_timeout = True
        self.setTimeout(self.factory.rawserver.config.get('socket_timeout', 30))
        
        return Protocol.makeConnection(self, transport)
Exemplo n.º 23
0
    def makeConnection(self, transport):
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)

        # We implement only Anonymous access
        self.transport.write(struct.pack("!BB", 5, len(b"\x00")) + b"\x00")

        self.transport.write(struct.pack("!BBBBB", 5, 1, 0, 3, len(self._host)) + self._host + struct.pack("!H", self._port))
        self.wrappedProtocol.makeConnection(self)

        try:
            self._connectedDeferred.callback(self.wrappedProtocol)
        except Exception:
            pass

        self.state = 1
Exemplo n.º 24
0
    def makeConnection(self, transport):
        self.attachTransport(transport, self.wrapper)

        self.can_timeout = True
        self.setTimeout(self.factory.rawserver.config.get(
            'socket_timeout', 30))

        return Protocol.makeConnection(self, transport)
Exemplo n.º 25
0
    def makeConnection(self, transport):
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)

        if not self.method in self.allowedMethods:
            self.sendHeaders({
                'status': '405 Method Not Supported',
                'allow': ', '.join(self.allowedMethods)
            })
            self.transport.write("\r\n")
            self.transport.loseConnection()
            return
        elif self.method == 'OPTIONS':
            self.sendHeaders()
            self.transport.write("")
            self.transport.loseConnection()
            return

        if not self.writeOnly:
            if self.session in self.factory.sessions:
                self.wrappedProtocol = self.factory.sessions[self.session]
            else:
                self.wrappedProtocol = RelayProtocol(
                    self.factory,
                    self.factory.wrappedFactory.buildProtocol(
                        self.transport.addr), self.session)

            if self.wrappedProtocol.attached:
                self.wrappedProtocol = None
                self.failConnect()
            else:
                if not self.prepConnection():
                    self.disconnecting = False
                    self.wrappedProtocol.makeConnection(self)
        else:
            if self.session in self.factory.sessions:
                self.wrappedProtocol = self.factory.sessions[self.session]
            else:
                self.sendHeaders({'status': '404 Not Found'})
                self.transport.write("\r\n")
                self.transport.loseConnection()
Exemplo n.º 26
0
    def makeConnection(self, transport):
        """
        When a connection is made, register this wrapper with its factory,
        save the real transport, and connect the wrapped protocol to this
        L{ProtocolWrapper} to intercept any transport calls it makes.
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)

        # We implement only Anonymous access
        self.transport.write(struct.pack("!BB", 5, len("\x00")) + "\x00")

        if self._optimistic:
            self.transport.write(struct.pack("!BBBBB", 5, 1, 0, 3, len(self._host)) + self._host + struct.pack("!H", self._port))
            self.wrappedProtocol.makeConnection(self)
            try:
                self._connectedDeferred.callback(self.wrappedProtocol)
            except Exception:
                pass

        self.state += 1
Exemplo n.º 27
0
    def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.

        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if not self._aborted:
            try:
                self._tlsConnection.do_handshake()
            except WantReadError:
                # This is the expected case - there's no data in the
                # connection's input buffer yet, so it won't be able to
                # complete the whole handshake now. If this is the speak-first
                # side of the connection, then some bytes will be in the send
                # buffer now; flush them.
                self._flushSendBIO()
Exemplo n.º 28
0
    def makeConnection(self, transport):
        """
        When a connection is made, register this wrapper with its factory,
        save the real transport, and connect the wrapped protocol to this
        L{ProtocolWrapper} to intercept any transport calls it makes.
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)

        # We implement only Anonymous access
        self.transport.write(struct.pack("!BB", 5, len("\x00")) + "\x00")

        if self._optimistic:
            self.transport.write(
                struct.pack("!BBBBB", 5, 1, 0, 3, len(self._host)) +
                self._host + struct.pack("!H", self._port))
            self.wrappedProtocol.makeConnection(self)
            try:
                self._connectedDeferred.callback(self.wrappedProtocol)
            except Exception:
                pass

        self.state = 1
Exemplo n.º 29
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self._buf = StringIO()
     self._buf_offset = 0
     self._resetReader()
     self._processData()
Exemplo n.º 30
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.send()
Exemplo n.º 31
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     from twisted.internet import reactor
     self.timeout = reactor.callLater(20, self.transport.loseConnection)
     print('Connection established for task %d' % self.task_num)
Exemplo n.º 32
0
 def makeConnection(self, transport):
     directlyProvides(self, *providedBy(self) + providedBy(transport))
     Protocol.makeConnection(self, transport)
Exemplo n.º 33
0
 def makeConnection(self, transport):
     self.history = TokenHistory()
     self.log.debug("ProviderProtocol makeConnection")
     Protocol.makeConnection(self, transport)
Exemplo n.º 34
0
 def makeConnection(self, transport):
     self.history = TokenHistory()
     self.log.debug("ProviderProtocol makeConnection")
     Protocol.makeConnection(self, transport)
Exemplo n.º 35
0
 def makeConnection(self, transport):
     directlyProvides(self, *providedBy(self) + providedBy(transport))
     Protocol.makeConnection(self, transport)
Exemplo n.º 36
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.onConnection.callback(transport)
Exemplo n.º 37
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     return self.protocol.makeConnection(transport)
Exemplo n.º 38
0
 def makeConnection(self, transport):
     return Protocol.makeConnection(self, transport)
Exemplo n.º 39
0
 def makeConnection(self, transport):
     self.can_timeout = 1
     self.setTimeout(self.factory.rawserver.config['socket_timeout'])
     self.attachTransport(transport, self.factory.connection, *self.factory.connection_args)
     Protocol.makeConnection(self, transport)
Exemplo n.º 40
0
 def makeConnection(self, transport):
     return Protocol.makeConnection(self, transport)
Exemplo n.º 41
0
Arquivo: ftp.py Projeto: fxia22/ASM_xf
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.connectedDeferred.callback(self)
Exemplo n.º 42
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.onConnection.callback(transport)
Exemplo n.º 43
0
class Client(_BaseBaseClient, _BaseTCPClient, Connection):
    """
    @ivar _tlsClientDefault: Always C{True}, indicating that this is a client
        connection, and by default when TLS is negotiated this class will act as
        a TLS client.
    """

    addressFamily = socket.AF_INET
    socketType = socket.SOCK_STREAM

    _tlsClientDefault = True
    _commonConnection = Connection

    def __init__(self, host, port, bindAddress, connector, reactor):
        # ConnectEx documentation says socket _has_ to be bound
        if bindAddress is None:
            bindAddress = ("", 0)
        self.reactor = reactor  # createInternetSocket needs this
        _BaseTCPClient.__init__(self, host, port, bindAddress, connector,
                                reactor)

    def createInternetSocket(self):
        """
        Create a socket registered with the IOCP reactor.

        @see: L{_BaseTCPClient}
        """
        return self.reactor.createSocket(self.addressFamily, self.socketType)

    def _collectSocketDetails(self):
        """
        Clean up potentially circular references to the socket and to its
        C{getFileHandle} method.

        @see: L{_BaseBaseClient}
        """
        del self.socket, self.getFileHandle

    def _stopReadingAndWriting(self):
        """
        Remove the active handle from the reactor.

        @see: L{_BaseBaseClient}
        """
        self.reactor.removeActiveHandle(self)

    def cbConnect(self, rc, data, evt):
        if rc:
            rc = connectExErrors.get(rc, rc)
            self.failIfNotConnected(
                error.getConnectError(
                    (rc, errno.errorcode.get(rc, "Unknown error"))))
        else:
            self.socket.setsockopt(
                socket.SOL_SOCKET,
                SO_UPDATE_CONNECT_CONTEXT,
                struct.pack("P", self.socket.fileno()),
            )
            self.protocol = self.connector.buildProtocol(self.getPeer())
            self.connected = True
            logPrefix = self._getLogPrefix(self.protocol)
            self.logstr = logPrefix + ",client"
            if self.protocol is None:
                # Factory.buildProtocol is allowed to return None.  In that
                # case, make up a protocol to satisfy the rest of the
                # implementation; connectionLost is going to be called on
                # something, for example.  This is easier than adding special
                # case support for a None protocol throughout the rest of the
                # transport implementation.
                self.protocol = Protocol()
                # But dispose of the connection quickly.
                self.loseConnection()
            else:
                self.protocol.makeConnection(self)
                self.startReading()

    def doConnect(self):
        if not hasattr(self, "connector"):
            # this happens if we connector.stopConnecting in
            # factory.startedConnecting
            return
        assert _iocp.have_connectex
        self.reactor.addActiveHandle(self)
        evt = _iocp.Event(self.cbConnect, self)

        rc = _iocp.connect(self.socket.fileno(), self.realAddress, evt)
        if rc and rc != ERROR_IO_PENDING:
            self.cbConnect(rc, 0, evt)
Exemplo n.º 44
0
 def makeConnection(self, transport):
     self.setTimeout(20)
     Protocol.makeConnection(self, transport)
Exemplo n.º 45
0
class BaseClient(_BaseBaseClient, _TLSClientMixin, Connection):
    """
    A base class for client TCP (and similar) sockets.

    @ivar realAddress: The address object that will be used for socket.connect;
        this address is an address tuple (the number of elements dependent upon
        the address family) which does not contain any names which need to be
        resolved.
    @type realAddress: C{tuple}

    @ivar _base: L{Connection}, which is the base class of this class which has
        all of the useful file descriptor methods.  This is used by
        L{_TLSServerMixin} to call the right methods to directly manipulate the
        transport, as is necessary for writing TLS-encrypted bytes (whereas
        those methods on L{Server} will go through another layer of TLS if it
        has been enabled).
    """

    _base = Connection
    _commonConnection = Connection

    def _stopReadingAndWriting(self):
        """
        Implement the POSIX-ish (i.e.
        L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this
        socket from the reactor for L{_BaseBaseClient}.
        """
        if hasattr(self, "reactor"):
            # this doesn't happen if we failed in __init__
            self.stopReading()
            self.stopWriting()


    def _collectSocketDetails(self):
        """
        Clean up references to the socket and its file descriptor.

        @see: L{_BaseBaseClient}
        """
        del self.socket, self.fileno


    def createInternetSocket(self):
        """(internal) Create a non-blocking socket using
        self.addressFamily, self.socketType.
        """
        s = socket.socket(self.addressFamily, self.socketType)
        s.setblocking(0)
        fdesc._setCloseOnExec(s.fileno())
        return s


    def doConnect(self):
        """
        Initiate the outgoing connection attempt.

        @note: Applications do not need to call this method; it will be invoked
            internally as part of L{IReactorTCP.connectTCP}.
        """
        self.doWrite = self.doConnect
        self.doRead = self.doConnect
        if not hasattr(self, "connector"):
            # this happens when connection failed but doConnect
            # was scheduled via a callLater in self._finishInit
            return

        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err:
            self.failIfNotConnected(error.getConnectError((err, strerror(err))))
            return

        # doConnect gets called twice.  The first time we actually need to
        # start the connection attempt.  The second time we don't really
        # want to (SO_ERROR above will have taken care of any errors, and if
        # it reported none, the mere fact that doConnect was called again is
        # sufficient to indicate that the connection has succeeded), but it
        # is not /particularly/ detrimental to do so.  This should get
        # cleaned up some day, though.
        try:
            connectResult = self.socket.connect_ex(self.realAddress)
        except socket.error as se:
            connectResult = se.args[0]
        if connectResult:
            if connectResult == EISCONN:
                pass
            # on Windows EINVAL means sometimes that we should keep trying:
            # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/connect_2.asp
            elif ((connectResult in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or
                  (connectResult == EINVAL and platformType == "win32")):
                self.startReading()
                self.startWriting()
                return
            else:
                self.failIfNotConnected(error.getConnectError((connectResult, strerror(connectResult))))
                return

        # If I have reached this point without raising or returning, that means
        # that the socket is connected.
        del self.doWrite
        del self.doRead
        # we first stop and then start, to reset any references to the old doRead
        self.stopReading()
        self.stopWriting()
        self._connectDone()


    def _connectDone(self):
        """
        This is a hook for when a connection attempt has succeeded.

        Here, we build the protocol from the
        L{twisted.internet.protocol.ClientFactory} that was passed in, compute
        a log string, begin reading so as to send traffic to the newly built
        protocol, and finally hook up the protocol itself.

        This hook is overridden by L{ssl.Client} to initiate the TLS protocol.
        """
        self.protocol = self.connector.buildProtocol(self.getPeer())
        self.connected = 1
        logPrefix = self._getLogPrefix(self.protocol)
        self.logstr = "%s,client" % logPrefix
        if self.protocol is None:
            # Factory.buildProtocol is allowed to return None.  In that case,
            # make up a protocol to satisfy the rest of the implementation;
            # connectionLost is going to be called on something, for example.
            # This is easier than adding special case support for a None
            # protocol throughout the rest of the transport implementation.
            self.protocol = Protocol()
            # But dispose of the connection quickly.
            self.loseConnection()
        else:
            self.startReading()
            self.protocol.makeConnection(self)
Exemplo n.º 46
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.ping()
Exemplo n.º 47
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self.send()
Exemplo n.º 48
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self._buffer = ProtocolBuffer()
Exemplo n.º 49
0
class Client(_BaseBaseClient, _BaseTCPClient, Connection):
    """
    @ivar _tlsClientDefault: Always C{True}, indicating that this is a client
        connection, and by default when TLS is negotiated this class will act as
        a TLS client.
    """
    addressFamily = socket.AF_INET
    socketType = socket.SOCK_STREAM

    _tlsClientDefault = True
    _commonConnection = Connection

    def __init__(self, host, port, bindAddress, connector, reactor):
        # ConnectEx documentation says socket _has_ to be bound
        if bindAddress is None:
            bindAddress = ('', 0)
        self.reactor = reactor # createInternetSocket needs this
        _BaseTCPClient.__init__(self, host, port, bindAddress, connector,
                                reactor)


    def createInternetSocket(self):
        """
        Create a socket registered with the IOCP reactor.

        @see: L{_BaseTCPClient}
        """
        return self.reactor.createSocket(self.addressFamily, self.socketType)


    def _collectSocketDetails(self):
        """
        Clean up potentially circular references to the socket and to its
        C{getFileHandle} method.

        @see: L{_BaseBaseClient}
        """
        del self.socket, self.getFileHandle


    def _stopReadingAndWriting(self):
        """
        Remove the active handle from the reactor.

        @see: L{_BaseBaseClient}
        """
        self.reactor.removeActiveHandle(self)


    def cbConnect(self, rc, bytes, evt):
        if rc:
            rc = connectExErrors.get(rc, rc)
            self.failIfNotConnected(error.getConnectError((rc,
                                    errno.errorcode.get(rc, 'Unknown error'))))
        else:
            self.socket.setsockopt(
                socket.SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT,
                struct.pack('P', self.socket.fileno()))
            self.protocol = self.connector.buildProtocol(self.getPeer())
            self.connected = True
            logPrefix = self._getLogPrefix(self.protocol)
            self.logstr = logPrefix + ",client"
            if self.protocol is None:
                # Factory.buildProtocol is allowed to return None.  In that
                # case, make up a protocol to satisfy the rest of the
                # implementation; connectionLost is going to be called on
                # something, for example.  This is easier than adding special
                # case support for a None protocol throughout the rest of the
                # transport implementation.
                self.protocol = Protocol()
                # But dispose of the connection quickly.
                self.loseConnection()
            else:
                self.protocol.makeConnection(self)
                self.startReading()


    def doConnect(self):
        if not hasattr(self, "connector"):
            # this happens if we connector.stopConnecting in
            # factory.startedConnecting
            return
        assert _iocp.have_connectex
        self.reactor.addActiveHandle(self)
        evt = _iocp.Event(self.cbConnect, self)

        rc = _iocp.connect(self.socket.fileno(), self.realAddress, evt)
        if rc and rc != ERROR_IO_PENDING:
            self.cbConnect(rc, 0, evt)
Exemplo n.º 50
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self._buffer = ProtocolBuffer()
Exemplo n.º 51
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.transport.write("o")
     self.factory.registerProtocol(self)
     self.wrappedProtocol.makeConnection(self)
Exemplo n.º 52
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     return self.protocol.makeConnection(transport)
Exemplo n.º 53
0
 def makeConnection(self, transport):
     self.setTimeout(20)
     Protocol.makeConnection(self, transport)
Exemplo n.º 54
0
 def makeConnection(self, transport):
     directlyProvides(self, providedBy(transport))
     Protocol.makeConnection(self, transport)
     self.transport.write("o")
     self.factory.registerProtocol(self)
     self.wrappedProtocol.makeConnection(self)
Exemplo n.º 55
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self._buf = StringIO()
     self._buf_offset = 0
     self._resetReader()
     self._processData()
Exemplo n.º 56
0
 def makeConnection(self, transport):
     Protocol.makeConnection(self, transport)
     self._buf = StringIO()
     self._buf_offset = 0