def _testFirewall( tcpListener, rpcSock, nodeAddrList, localIP, reactor, callback=None ) : def doCancel() : for checkOp in checkOps : checkOp.cancel() checkOps.clear() testServer.close() def onCheck( checkOp, err, payload ) : checkOps.remove( checkOp ) if err >= 0 : fwResult,fwToken = payload if (fwResult >= 0) and (fwToken == token) : successList.append( 1 ) if not checkOps : testServer.close() # n(success)/n(nodes) >= 1/2 op.notify( 2*len(successList) >= len(nodeAddrList) ) def doCheck( nodeAddr ) : checkOp = dhtClient.callFirewallCheck( localIP, nodeAddr, lambda e,p : onCheck(checkOp,e,p) ) checkOps.add( checkOp ) assert nodeAddrList successList = [] checkOps = set() token = rand_bytes( 20 ) dhtClient = DHTClient( rpcSock ) testServer = FirewallTestServer( tcpListener, token, reactor ) for nodeAddr in nodeAddrList : doCheck( nodeAddr ) op = AsyncOp( callback, doCancel ) return op
def addIncoming( self, sslConn, peerKey ) : while True : connectionId = hexEncode( rand_bytes(8) ) if connectionId not in self.connections : break def onTimeout() : self._onTimeout( connectionId ) timerOp = self.reactor.callLater( 30, onTimeout ) self.connections[connectionId] = (sslConn,peerKey,timerOp) return connectionId
def request( self, data, destaddr, callback=None ) : while 1 : id = rand_bytes( 20 ) if not self.pending.has_key(id) : break msg = (0, id, data) s = encode( msg ) def cancelRequest() : del self.pending[id] op = RPCOp( id, callback, cancelRequest ) self.pending[id] = op self._sendData( s, destaddr ) return op
def _doRegister( self, args, ctx ) : try : assert self.state == self.INITIAL assert len(args) == 0 except : ctx.response( (-1,'') ) return while True : routerId = rand_bytes( 20 ) if routerId not in self.routerState.registered : break self.routerId = routerId self.state = self.REGISTERED self.routerState.registered[routerId] = self ctx.response( (0,self.routerId) )
def _doConnect( self, args, ctx ) : try : assert self.state == self.INITIAL assert len(args) == 1 routerId = args[0] assert type(routerId) is str handler = self.routerState.registered.get( routerId ) assert handler is not None except : ctx.response( [-1] ) return while True : connectionId = rand_bytes( 20 ) if connectionId not in self.routerState.connecting : break self.connectionId = connectionId self.connectCtx = ctx self.state = self.CONNECTING self.routerState.connecting[connectionId] = self handler.sendIncoming( connectionId )