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()
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()
def connectionLost(self, reason=twistedError.ConnectionDone): if self.role == Command.BaseCommand.PV_ROLE_HUMAN: InternalMessage.UnregistFilter(InternalMessage.TTYPE_HUMAN, self.client_id) InternalMessage.NotifyTerminalStatus(InternalMessage.TTYPE_HUMAN, self.client_id, id(self.transport), InternalMessage.OPER_OFFLINE, 'n') elif self.role == Command.BaseCommand.PV_ROLE_RELAYER: InternalMessage.UnregistFilter(InternalMessage.TTYPE_GATEWAY, self.relayer_id) InternalMessage.NotifyTerminalStatus(InternalMessage.TTYPE_GATEWAY, self.relayer_id, 0, InternalMessage.OPER_OFFLINE) try: self.timer.cancel() except Exception: pass #print ("connection lost:",id(self.transport),reason) self.releaseFromDict() with self.factory.lockPendingCmd: SBProtocol.connection_count = SBProtocol.connection_count - 1 Protocol.connectionLost(self, reason=reason)
def request_shell(self, data): protocol = Protocol() transport = SSHSessionProcessProtocol(self) protocol.makeConnection(transport) transport.makeConnection(wrapProtocol(protocol)) self.client = transport return True
def __init__(self): Protocol.__init__(self) self.packetBuffer = '' self.packetSize = 0 self.errorMsg = '' self.errorId = 0 self.msgMap = {}
def build_protocol(): """ :return: ``Protocol`` hooked up to transport. """ p = Protocol() p.makeConnection(StringTransport()) return p
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()
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)
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()
def __init__(self): try: Protocol.__init__(self) except AttributeError: pass self.buffer = "" self.drd = Deferred()
def _testStreamingProducer(self, mode): """ Connect a couple protocol/transport pairs to an L{IOPump} and then pump it. Verify that a streaming producer registered with one of the transports does not receive invalid L{IPushProducer} method calls and ends in the right state. @param mode: C{u"server"} to test a producer registered with the server transport. C{u"client"} to test a producer registered with the client transport. """ serverProto = Protocol() serverTransport = FakeTransport(serverProto, isServer=True) clientProto = Protocol() clientTransport = FakeTransport(clientProto, isServer=False) pump = connect( serverProto, serverTransport, clientProto, clientTransport, greet=False, ) producer = StrictPushProducer() victim = { u"server": serverTransport, u"client": clientTransport, }[mode] victim.registerProducer(producer, streaming=True) pump.pump() self.assertEqual(u"running", producer._state)
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 test_pumpPolicy(self): """ The callable passed as the value for the C{pumpPolicy} parameter to L{loopbackAsync} is called with a L{_LoopbackQueue} of pending bytes and a protocol to which they should be delivered. """ pumpCalls = [] def dummyPolicy(queue, target): bytes = [] while queue: bytes.append(queue.get()) pumpCalls.append((target, bytes)) client = Protocol() server = Protocol() finished = loopback.loopbackAsync(server, client, dummyPolicy) self.assertEquals(pumpCalls, []) client.transport.write("foo") client.transport.write("bar") server.transport.write("baz") server.transport.write("quux") server.transport.loseConnection() def cbComplete(ignored): self.assertEquals( pumpCalls, # The order here is somewhat arbitrary. The implementation # happens to always deliver data to the client first. [(client, ["baz", "quux", None]), (server, ["foo", "bar"])]) finished.addCallback(cbComplete) return finished
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)
def connectionLost( self, reason ): Protocol.connectionLost( self, reason ) self.log.warning("Disconnected: %s" % reason) #self.sessionState = JT808SessionStates.NONE if self.termPhone in self.factory.clients: self.factory.clients.pop(self.termPhone) self.disconnectedDeferred.callback(None)
def _hostpeertest(self, get, testServer): """ Test one of the permutations of client/server host/peer. """ class TestProtocol(Protocol): def makeConnection(self, transport): Protocol.makeConnection(self, transport) self.onConnection.callback(transport) if testServer: server = TestProtocol() d = server.onConnection = Deferred() client = Protocol() else: server = Protocol() client = TestProtocol() d = client.onConnection = Deferred() loopback.loopbackAsync(server, client) def connected(transport): host = getattr(transport, get)() self.assertTrue(IAddress.providedBy(host)) return d.addCallback(connected)
def connectionMade(self): """ overload Protocol.connectionMade to verify that we have a connection """ log.msg("ResponseProducerProtocol connectionMade", logLevel=logging.DEBUG) Protocol.connectionMade(self)
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)
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)
def connectionLost(self, reason): Protocol.connectionLost(self, reason) self.started = False self.factory.number_of_connections -= 1 self.player = None print "lost" print "Current number of connections:", self.factory.number_of_connections
def connectionMade(self): Protocol.connectionMade(self) self.transport.setTcpNoDelay(True) self.buffer = '' self.nbytes = 0 # XXX send version message self._handler = self._handle_version, 12
def connectionMade(self): AbstractWind.connectionMade(self) Protocol.connectionMade(self) _ = self.transport.getPeer() _ = (_.host, _.port) self.peer, self.port = _
def connectionLost(self, reason): print self.name self.factory.mzcall(self.name,False) Protocol.connectionLost(self, reason) self.stop() print "locst connection:",reason self.factory.number_of_connections -= 1 print "number_of_connections:",self.factory.number_of_connections
def __init__(self, conn_parameter, receiver): Protocol.__init__(self) self.buffer = None self.conn_parameter = conn_parameter self.last_receive_ts = 0.0 self.last_send_ts = 0.0 self.connected = False self.receiver = receiver
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)
def connectionLost(self, reason=None): g_logger.info( "Gate Callback connection lost. Disconnecting higher protocol") if self.higherProtocol(): self.higherProtocol().connectionLost(reason) self.setHigherProtocol(None) self.factory.unregisterCallbackProtocol(self) Protocol.connectionLost(self, reason)
def reconnector(self, onion): protocol = Protocol() protocol.onion = onion protocol.connectionLost = lambda failure: self.handleLostConnection(failure, onion) tor_endpoint = clientFromString(self.reactor, "tor:%s.onion:8060" % onion) self.onion_pending_map[onion] = connectProtocol(tor_endpoint, protocol) self.onion_pending_map[onion].addCallback(lambda protocol: self.connection_ready(onion, protocol)) self.onion_pending_map[onion].addErrback(lambda failure: self.connectFail(failure, onion))
def connectionMade(self): self.factory.num_connections += 1 Protocol.connectionMade(self) self._input = '' proto_version = ProtocolVersion().serialize() server_state = ServerState().serialize() # self.send(proto_version)
def connectionLost(self, reason = connectionDone): log.info('SyncAnyProtocol::connectionLost') self.started = False Protocol.connectionLost(self, reason) #self.factory.clients.remove(self) if not self.user is None: self.factory.clients.removeClient(self)
def connectionMade(self): Protocol.connectionMade(self) self.transport.write(struct.pack('>I', self.__seed)) self._input = '' self._decompress = None if self.__decompress: self._decompress = Decompress()
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()
def connectionLost(self, reason): # remove from channel and disconnect, reset state machine if self in self.factory.channels[self.channel]: self.factory.channels[self.channel].remove(self) if self.factory.channels[self.channel].count <= 0: del self.factory.channels[self.channel] self.curState=ProtocolState.CO_NO self.factory.notifyObservers("A dude left the channel", self.channel) Protocol.connectionLost(self, reason=reason)
def connectionMade(self): """When TCP connection is made """ Protocol.connectionMade(self) self.port = self.transport.getHost().port # Start the inactivity timer the connection is dropped if we receive no data self.activateInactivityTimer() self.sessionState = SMPPSessionStates.OPEN self.log.warning("SMPP connection established from %s to port %s", self.transport.getPeer().host, self.port)
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)
def dataReceived(self, p_data): """ This seems to be a line received function """ Protocol.dataReceived(self, p_data) self.setLineMode() l_data = p_data[:-2] # Drop the trailing CrLf if l_data == b'R': return LOG.info('Data Received.\n\tData:{}'.format(l_data))
def connectionLost(self, reason): #print "CONNECTIONLOST" #MultiBufferer.connectionLost(self, reason) # XXX When we call MultiBufferer.connectionLost, we get # unhandled errors (something isn't adding an Errback # to the deferred which eventually gets GC'd, but I'm # not *too* worried because it *does* get GC'd). # Do check that the things which yield on read() on # the multibufferer get correctly GC'd though. Protocol.connectionLost(self, reason)
def connectionMade(self): """ *3 Setup We have connected - now get the initial conditions. """ Protocol.connectionMade(self) self.setLineMode() LOG.info('Connection Made.') self.m_pioneer_device_obj._Transport = self.transport self._get_status()
def connectionLost(self, reason): Protocol.connectionLost(self, reason) self.log.warning("SMPP %s disconnected from port %s: %s", self.transport.getPeer().host, self.port, reason) self.sessionState = SMPPSessionStates.NONE self.cancelEnquireLinkTimer() self.cancelInactivityTimer() self.disconnectedDeferred.callback(None)
def connectionMade(self): self.log = util.getLogger("gamespy.login", self) self.loggedIn = False def sendKa(): self.sendMsg(MessageFactory.getMessage([("ka", "")])) self.kaService.alive() ## expects no reply self.kaService = KeepaliveService(sendKa, 90, self.transport.loseConnection) Protocol.connectionMade(self)
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)
def connectionLost(self, reason=ResponseDone): """ overload Protocol.connectionLost to handle disconnect """ Protocol.connectionLost(self, reason) if reason.check(ResponseDone): self._deferred.callback(True) else: log.err("ResponseProducerProtocol connection lost %s" % (reason, ), logLevel=logging.ERROR) self._deferred.errback(reason)
def connectionLost(self, *args, **kwargs): global _WebSocketTransports if _Debug: lg.args(_DebugLevel, key=self._key, ws_connections=len(_WebSocketTransports)) Protocol.connectionLost(self, *args, **kwargs) _WebSocketTransports.pop(self._key) peer = '%s://%s:%s' % (self._key[0], self._key[1], self._key[2]) self._key = None events.send('web-socket-disconnected', data=dict(peer=peer))
def test_protocolToConsumer(self): """ L{IProtocol} providers can be adapted to L{IConsumer} providers using L{ProtocolToConsumerAdapter}. """ result = [] p = Protocol() p.dataReceived = result.append consumer = IConsumer(p) consumer.write(b"hello") self.assertEqual(result, [b"hello"]) self.assertIsInstance(consumer, ProtocolToConsumerAdapter)
def connectionMade(self): global connection_count Protocol.connectionMade(self) connection_count += 1 print "connection made:", connection_count logging.info("connection made: %d", id(connection_count)) self.index = connection_count self.transport.write(str(self.index)) if self.index < 10000: oppo = self.transport.getPeer() reactor.callLater(0, reactor.connectTCP, oppo.host, oppo.port, self.factory)
def connectionLost(self, reason=connectionDone): """Abort any outstanding requests when we lose our connection.""" Protocol.connectionLost(self, reason) requests = self.requests.values() for request in requests: request.stopProducing() if request.started: request.cancel() try: # also removes from self.requests request.error(reason) except defer.AlreadyCalledError: # cancel may already have error-ed the request continue
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
def connectionMade(self): logger.debug("connectionMade(): %s port %s %s:%s %s", self.factory.name, self.factory.local_port, self.factory.host, self.factory.port, self.protocol_name) return Protocol.connectionMade(self)
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)