def getChild(self, path, request): pre_check=[False, False] host, port = self.__get_host_info(request) if self.domain_level ==0 : ts = reactor.seconds() if self.domains_blocked_cache.has_key(host) and ( ts - self.domains_blocked_cache[host][0] ) <= 10 : print self.domains_blocked_cache[host][1] block_d = BlockingDeferred(self.domains_blocked_cache[host][1]) try: pre_check, categories = block_d.blockOn() print "Host %s , verified [cached] (pre_check=%s)" % (host, pre_check) except: print "Something wrong validating domain %s" % host pre_check = [False, False] else: query = self.filter_manager.check_domain_defer(self.uid, host) self.domains_blocked_cache[host]=[reactor.seconds(), query] block_d = BlockingDeferred(query) try: pre_check, categories = block_d.blockOn() print "Host %s , verified (pre_check=%s)" % (host, pre_check) except: print "Something wrong validating domain %s" % host pre_check = [False, False] return ReverseProxyResource(self.uid, self.filter_manager, reactor=reactor, domain_level=self.domain_level + 1, pre_check=pre_check) else: return ReverseProxyResource(self.uid, self.filter_manager, reactor=reactor, domain_level=self.domain_level + 1, pre_check=self.pre_check)
def on_chat(self, message): if self.time_last_chat < int(reactor.seconds() - constants.ANTISPAM_LIMIT_CHAT): self.chat_messages_burst = 0 else: if self.chat_messages_burst < constants.ANTISPAM_BURST_CHAT: self.chat_messages_burst += 1 else: self.time_last_chat = reactor.seconds() res = self.scripts.call('on_spamming_chat').result if not res: # As we do not want to spam back only do this when # burst limit is reached for the first time if self.chat_messages_burst == constants.ANTISPAM_BURST_CHAT: if self.server.config.base.auto_kick_spam: self.kick('Kicked for chat spamming') else: self.send_chat('[ANTISPAM] Please do not spam in chat!') return if message.startswith('/'): command, args = parse_command(message[1:]) self.on_command(command, args) return event = self.scripts.call('on_chat', message=message) if event.result is False: return return event.message
def with_lock(reactor, lock, func, log=None, acquire_timeout=None, release_timeout=None): """ Context manager for any lock object that contains acquire() and release() methods """ if log: log.msg('Starting lock acquisition') d = defer.maybeDeferred(lock.acquire) if acquire_timeout is not None: timeout_deferred(d, acquire_timeout, reactor, 'Lock acquisition') if log: d.addCallback(log_with_time, reactor, log, reactor.seconds(), 'Lock acquisition', 'acquire_time') d.addErrback(log_with_time, reactor, log, reactor.seconds(), 'Lock acquisition failed') def release_lock(result): if log: log.msg('Starting lock release') d = defer.maybeDeferred(lock.release) if release_timeout is not None: timeout_deferred(d, release_timeout, reactor, 'Lock release') if log: d.addCallback( log_with_time, reactor, log, reactor.seconds(), 'Lock release', 'release_time') return d.addCallback(lambda _: result) def lock_acquired(_): d = defer.maybeDeferred(func).addBoth(release_lock) return d d.addCallback(lock_acquired) return d
def on_team_join(self, team): if self.team is not None: if self.protocol.teamswitch_interval: teamswitch_interval = self.protocol.teamswitch_interval if teamswitch_interval == 'never': self.send_chat('Switching teams is not allowed') return False if (self.last_switch is not None and reactor.seconds() - self.last_switch < teamswitch_interval * 60): self.send_chat('You must wait before switching teams again') return False if team.locked: self.send_chat('Team is locked') if not team.spectator and not team.other.locked: return team.other return False balanced_teams = self.protocol.balanced_teams if balanced_teams and not team.spectator: other_team = team.other if other_team.count() < team.count() + 1 - balanced_teams: if other_team.locked: return False self.send_chat('Team is full, moved to %s' % other_team.name) return other_team self.last_switch = reactor.seconds()
def use_ability(self, mode): ability = ABILITIES[mode] if 'cooldown' in ability: min_cd = ability['cooldown'] last_used = 0 if mode in self.ability_cooldown: last_used = self.ability_cooldown[mode] current_cd = reactor.seconds() - last_used if current_cd < min_cd - self.cooldown_margin: self.cooldown_strikes += 1 if self.cooldown_strikes > self.max_cooldown_strikes: self.log(("ability used before cooldown was ready. " + "mode={mode}, min. cooldown={mincd}s, " + "current cooldown={currentcd}s") .format(mode=mode, mincd=min_cd, currentcd=current_cd), LOG_LEVEL_VERBOSE) return False else: self.cooldown_strikes = 0 # keep track of ability usage self.ability_cooldown[mode] = reactor.seconds() return True
def on_position_update(self): if self.protocol.running_man: if self.link is not None and self.link.hp > 0: dist = distance_3d_vector(self.world_object.position, self.link.world_object.position) if dist > LINK_DISTANCE: self.grenade_suicide() self.link_deaths += 1 self.link.grenade_suicide() self.link.link_deaths += 1 message = S_LINK_BREAK.format(player = self.link.name) self.send_chat(message) message = S_LINK_BREAK.format(player = self.name) self.link.send_chat(message) elif (dist > LINK_WARNING_DISTANCE and (self.last_warning is None or seconds() - self.last_warning > 2.0)): self.last_warning = seconds() self.link.last_warning = seconds() message = S_LINK_WARNING.format(player = self.link.name) self.send_chat(message) message = S_LINK_WARNING.format(player = self.name) self.link.send_chat(message) connection.on_position_update(self)
def on_shoot_set(self, fire): if self.tool == WEAPON_TOOL: self.pres_recoil_test_time = seconds() if self.prev_recoil_test_time is None: self.recoil_test_timer = .75 else: self.recoil_test_timer = self.pres_recoil_test_time - self.prev_recoil_test_time if self.recoil_test_timer >= .75: if fire: self.set_start_orientX, self.set_start_orientY, self.set_start_orientZ = round(self.world_object.orientation.x, 10), round(self.world_object.orientation.y, 10), round(self.world_object.orientation.z, 10) self.send_chat('Junction 1 confirmed') self.howmuchammoisinmyclip = self.weapon_object.current_ammo print self.howmuchammoisinmyclip self.junction2 = True if not fire and self.junction2: self.set_end_orientX, self.set_end_orientY, self.set_end_orientZ = round(self.world_object.orientation.x, 10), round(self.world_object.orientation.y, 10), round(self.world_object.orientation.z, 10) self.prev_recoil_test_time = seconds() self.send_chat('Junction 2 confirmed') self.junction2 = False if self.set_start_orientX == self.set_end_orientX and self.set_start_orientY == self.set_end_orientY and self.set_start_orientZ == self.set_end_orientZ: print self.weapon_object.current_ammo if self.howmuchammoisinmyclip != self.weapon_object.current_ammo and self.howmuchammoisinmyclip > 1: self.no_recoil_event_count += 1 self.send_chat('event +1') else: self.no_recoil_event_count = 0 if self.no_recoil_event_count >= 3: self.irc_say('Possible Hack Detected - No Recoil IGN: %s' % (self.name)) return connection.on_shoot_set(self, fire)
def on_hit(self, hit_amount, hit_player, type, grenade): body_damage_values = [49, 29, 27] limb_damage_values = [33, 18, 16] dist = int(distance_3d_vector(self.world_object.position, hit_player.world_object.position)) weap = self.weapon_object.name self.pres_time = seconds() if self.prev_time is None: dt = None else: dt = (self.pres_time - self.prev_time) * 1000 self.prev_time = seconds() if weap == "SMG" or weap == "Rifle": if dt is not None and dt < 5: self.illegal_dt_count = self.illegal_dt_count + 1 if weap == "Shotgun": if dist > 20: if dt < 8: if hit_amount == self.spread_hit_amount and hit_player.name == self.spread_hit_player: if type == HEADSHOT_KILL: self.spread_hs_count = self.spread_hs_count +1 elif hit_amount in body_damage_values: self.spread_hs_count = self.spread_bs_count +1 elif hit_amount in limb_damage_values: self.spread_ls_count = self.spread_ls_count +1 else: self.spread_hs_count, self.spread_bs_count, self.spread_ls_count = 0, 0, 0 self.spread_hit_amount, self.spread_hit_player = None, None else: self.spread_hs_count, self.spread_bs_count, self.spread_ls_count = 0, 0, 0 self.spread_hit_amount, self.spread_hit_player = hit_amount, hit_player.name else: self.spread_hs_count, self.spread_bs_count, self.spread_ls_count = 0, 0, 0 self.spread_hit_amount, self.spread_hit_player = None, None self.local_variable = self.shots_analyzed_by for names in self.local_variable: adminz = get_player(self.protocol, names) if type == HEADSHOT_KILL: adminz.hs = adminz.hs + 1 if dt is not None: adminz.send_chat('%s shot %s dist: %d blocks dT: %.0f ms %s HEADSHOT(%d)' % (self.name, hit_player.name, dist, dt, weap, adminz.hs)) else: adminz.send_chat('%s shot %s dist: %d blocks dT: NA %s HEADSHOT(%d)' % (self.name, hit_player.name, dist, weap, adminz.hs)) if hit_amount in body_damage_values: adminz.bs = adminz.bs + 1 if dt is not None: adminz.send_chat('%s shot %s dist: %d blocks dT: %.0f ms %s Body(%d)' % (self.name, hit_player.name, dist, dt, weap, adminz.bs)) else: adminz.send_chat('%s shot %s dist: %d blocks dT: NA %s Body(%d)' % (self.name, hit_player.name, dist, weap, adminz.bs)) if hit_amount in limb_damage_values: adminz.ls = adminz.ls + 1 if dt is not None: adminz.send_chat('%s shot %s dist: %d blocks dT: %.0f ms %s Limb(%d)' % (self.name, hit_player.name, dist, dt, weap, adminz.ls)) else: adminz.send_chat('%s shot %s dist: %d blocks dT: NA %s Limb(%d)' % (self.name, hit_player.name, dist, weap, adminz.ls)) if self.illegal_dt_count >= 5: self.ban('Hack Detected - Multiple Bullets', 10080) return False if self.spread_hs_count >= 7 or self.spread_bs_count >= 7 or self.spread_ls_count >=7: self.ban('Hack Detected - No Spread', 10080) return False return connection.on_hit(self, hit_amount, hit_player, type, grenade)
def html_grief_check(ignore, player, time): color = False minutes = float(time or 2) if minutes < 0.0: raise ValueError() time = reactor.seconds() - minutes * 60.0 blocks_removed = player.blocks_removed or [] blocks = [b[1] for b in blocks_removed if b[0] >= time] player_name = player.name if color: player_name = (('\x0303' if player.team.id else '\x0302') + player_name + '\x0f') message = '%s removed %s block%s in the last ' % (player_name, len(blocks) or 'no', '' if len(blocks) == 1 else 's') if minutes == 1.0: minutes_s = 'minute' else: minutes_s = '%s minutes' % ('%f' % minutes).rstrip('0').rstrip('.') message += minutes_s + '.' if len(blocks): infos = set(blocks) infos.discard(None) if color: names = [('\x0303' if team else '\x0302') + name for name, team in infos] else: names = set([name for name, team in infos]) if len(names) > 0: message += (' Some of them were placed by ' + ('\x0f, ' if color else ', ').join(names)) message += '\x0f.' if color else '.' else: message += ' All of them were map blocks.' last = blocks_removed[-1] time_s = prettify_timespan(reactor.seconds() - last[0], get_seconds = True) message += ' Last one was destroyed %s ago' % time_s whom = last[1] if whom is None and len(names) > 0: message += ', and was part of the map' elif whom is not None: name, team = whom if color: name = ('\x0303' if team else '\x0302') + name + '\x0f' message += ', and belonged to %s' % name message += '.' switch_sentence = False if player.last_switch is not None and player.last_switch >= time: time_s = prettify_timespan(reactor.seconds() - player.last_switch, get_seconds = True) message += ' %s joined %s team %s ago' % (player_name, player.team.name, time_s) switch_sentence = True teamkills = len([t for t in player.teamkill_times or [] if t >= time]) if teamkills > 0: s = ', and killed' if switch_sentence else ' %s killed' % player_name message += s + ' %s teammates in the last %s' % (teamkills, minutes_s) if switch_sentence or teamkills > 0: message += '.' return message
def on_position_update(self): # send jump action tip when you're near one if self.protocol.machineguns and not self.machinegun and self.hp > 0: last_message = self.last_machinegun_message available = last_message is None or seconds() - last_message > 10.0 if (available and any(mg.actionable(self) for mg in self.protocol.machineguns)): self.send_chat(S_JUMP_TO_USE) self.last_machinegun_message = seconds() connection.on_position_update(self)
def test_timeout(self): from time import sleep t0 = reactor.seconds() try: rsp = yield self.getPage("http://127.0.0.1:%d/" % self._port, timeout=self.requestTimeout) except netErr.TimeoutError: self.assertEquals(self.requestTimeout, int(reactor.seconds()-t0)) else: fail("Did not timeout")
def update_world(self): last_time = self.last_time current_time = reactor.seconds() if last_time is not None: dt = current_time - last_time if dt > 1.0: print '(warning: high CPU usage detected - %s)' % dt self.last_time = current_time ServerProtocol.update_world(self) time_taken = reactor.seconds() - current_time if time_taken > 1.0: print 'World update iteration took %s, objects: %s' % (time_taken, self.world.objects)
def pollDatabaseBuildRequests(self): # deal with cleaning up unclaimed requests, and (if necessary) # requests from a previous instance of this master timer = metrics.Timer("BuildMaster.pollDatabaseBuildRequests()") timer.start() # cleanup unclaimed builds since_last_cleanup = reactor.seconds() - self._last_claim_cleanup if since_last_cleanup < self.RECLAIM_BUILD_INTERVAL: unclaimed_age = (self.RECLAIM_BUILD_INTERVAL * self.UNCLAIMED_BUILD_FACTOR) wfd = defer.waitForDeferred( self.db.buildrequests.unclaimExpiredRequests(unclaimed_age)) yield wfd wfd.getResult() self._last_claim_cleanup = reactor.seconds() # _last_unclaimed_brids_set tracks the state of unclaimed build # requests; whenever it sees a build request which was not claimed on # the last poll, it notifies the subscribers. It only tracks that # state within the master instance, though; on startup, it notifies for # all unclaimed requests in the database. last_unclaimed = self._last_unclaimed_brids_set or set() if len(last_unclaimed) > self.WARNING_UNCLAIMED_COUNT: log.msg("WARNING: %d unclaimed buildrequests - is a scheduler " "producing builds for which no builder is running?" % len(last_unclaimed)) # get the current set of unclaimed buildrequests wfd = defer.waitForDeferred( self.db.buildrequests.getBuildRequests(claimed=False)) yield wfd now_unclaimed_brdicts = wfd.getResult() now_unclaimed = set([ brd['brid'] for brd in now_unclaimed_brdicts ]) # and store that for next time self._last_unclaimed_brids_set = now_unclaimed # see what's new, and notify if anything is new_unclaimed = now_unclaimed - last_unclaimed if new_unclaimed: brdicts = dict((brd['brid'], brd) for brd in now_unclaimed_brdicts) for brid in new_unclaimed: brd = brdicts[brid] self.buildRequestAdded(brd['buildsetid'], brd['brid'], brd['buildername']) timer.stop()
def on_shoot_set(self, fire): self.fire = fire if self.tool == WEAPON_TOOL: self.weap1 = self.weapon_object.name if self.fire and seconds() - self.start_set_time >= 1 and seconds() - self.end_set_time >= 1: self.start_ammo = self.weapon_object.current_ammo self.orient_count = 0 self.junction = True self.start_set_time = seconds() elif not self.fire and self.junction and seconds() - self.start_set_time >= .05 and self.world_object.orientation.z >= -0.95 and self.world_object.orientation.z <= 0.95: self.end_set_time = seconds() callLater(0.05, self.recoiltest) elif not self.fire and self.start_ammo != self.weapon_object.current_ammo: self.junction = False return connection.on_shoot_set(self, fire)
def data_received(self, peer, packet): ip = peer.address.host current_time = reactor.seconds() try: ServerProtocol.data_received(self, peer, packet) except (NoDataLeft, InvalidData): import traceback traceback.print_exc() print 'IP %s was hardbanned for invalid data or possibly DDoS.' % ip self.hard_bans.add(ip) return dt = reactor.seconds() - current_time if dt > 1.0: print '(warning: processing %r from %s took %s)' % ( packet.data, ip, dt)
def with_lock(reactor, lock, func, log=default_log, acquire_timeout=None, release_timeout=None, held_too_long=120): """ Context manager for any lock object that contains acquire() and release() methods """ held = [True] log = log.bind(lock_status="Acquiring", lock=lock, locked_func=func) log.msg('Starting lock acquisition') d = defer.maybeDeferred(lock.acquire) if acquire_timeout is not None: timeout_deferred(d, acquire_timeout, reactor, 'Lock acquisition') d.addCallback(log_with_time, reactor, log.bind(lock_status='Acquired'), reactor.seconds(), 'Lock acquisition', 'acquire_time') d.addErrback(log_with_time, reactor, log.bind(lock_status='Failed'), reactor.seconds(), 'Lock acquisition failed') def release_lock(result, log): log.msg('Starting lock release', lock_status="Releasing") d = defer.maybeDeferred(lock.release) if release_timeout is not None: timeout_deferred(d, release_timeout, reactor, 'Lock release') d.addCallback( log_with_time, reactor, log.bind(lock_status="Released"), reactor.seconds(), 'Lock release', 'release_time') def finished_release(_): held[0] = False return result return d.addCallback(finished_release) def check_still_acquired(log): if held[0]: log.msg("Lock held for more than %s seconds!" % (held_too_long,), isError=True) def lock_acquired(acquire_result, log): log = log.bind(lock_status="Acquired") reactor.callLater(held_too_long, check_still_acquired, log) d = defer.maybeDeferred(func).addBoth(release_lock, log) return d d.addCallback(lock_acquired, log) return d
def kick_afk(connection, minutes, amount = None): protocol = connection.protocol minutes = int(minutes) if minutes < 1: raise ValueError() to_kick = [] no_kick = False seconds = minutes * 60.0 minutes_s = prettify_timespan(seconds) lower_bound = reactor.seconds() - seconds for conn in protocol.connections.values(): for t in ('admin', 'moderator', 'guard', 'trusted'): if t in conn.user_types: no_kick = True if not no_kick and conn.last_activity < lower_bound: to_kick.append(conn) if not to_kick: return S_NO_PLAYERS_INACTIVE.format(time = minutes_s) to_kick.sort(key = attrgetter('last_activity')) to_kick.sort(key = lambda conn: conn.name is None) amount = amount or len(to_kick) kicks = 0 for conn in to_kick[:amount]: if conn.name: conn.afk_kick() kicks += 1 else: conn.disconnect() message = S_AFK_KICKED.format(num_players = kicks, num_connections = amount - kicks, time = minutes_s) protocol.irc_say('* ' + message) if connection in protocol.players: return message
def ratio(connection, user=None): msg = "You have" if user != None: connection = get_player(connection.protocol, user) msg = "%s has" if connection not in connection.protocol.players: raise KeyError() msg %= connection.name if connection not in connection.protocol.players: raise KeyError() kills = connection.ratio_kills deaths = float(max(1,connection.ratio_deaths)) headshotkills = connection.ratio_headshotkills meleekills = connection.ratio_meleekills grenadekills = connection.ratio_grenadekills msg += " a kill-death ratio of %.2f" % (kills/deaths) if HEADSHOT_RATIO: msg += ", headshot-death ratio of %.2f" % (headshotkills/deaths) msg += " (%s kills, %s deaths" % (kills, connection.ratio_deaths) if EXTENDED_RATIO: msg += ", %s headshot, %s melee, %s grenade" % (headshotkills, meleekills, grenadekills) if KILLS_PER_MINUTE: dt = (seconds() - connection.time_login) /60 msg += ", %.2f kills per minute" % (kills/dt) msg += ")." return msg
def buildFinished(self, build, sb): """This is called when the Build has finished (either success or failure). Any exceptions during the build are reported with results=FAILURE, not with an errback.""" # by the time we get here, the Build has already released the slave, # which will trigger a check for any now-possible build requests # (maybeStartBuilds) results = build.build_status.getResults() self.building.remove(build) if results == RETRY: d = self._resubmit_buildreqs(build) d.addErrback(log.err, 'while resubmitting a build request') else: complete_at_epoch = reactor.seconds() complete_at = epoch2datetime(complete_at_epoch) brids = [br.id for br in build.requests] d = self.master.data.updates.completeBuildRequests(brids, results, complete_at=complete_at) # nothing in particular to do with this deferred, so just log it if # it fails.. d.addErrback(log.err, 'while marking build requests as completed') if sb.slave: sb.slave.releaseLocks() self.updateBigStatus()
def set_time_limit(self, time_limit = None, additive = False): advance_call = self.advance_call add_time = 0.0 if advance_call is not None: add_time = ((advance_call.getTime() - reactor.seconds()) / 60.0) advance_call.cancel() self.advance_call = None time_limit = time_limit or self.default_time_limit if time_limit == False: for call in self.end_calls[:]: call.set(None) return if additive: time_limit = min(time_limit + add_time, self.default_time_limit) seconds = time_limit * 60.0 self.advance_call = reactor.callLater(seconds, self._time_up) for call in self.end_calls[:]: call.set(seconds) if self.time_announce_schedule is not None: self.time_announce_schedule.reset() self.time_announce_schedule = Scheduler(self) for seconds in self.time_announcements: self.time_announce_schedule.call_end(seconds, self._next_time_announce) return time_limit
def makeService(config): from twisted.internet import reactor, task multi = service.MultiService() domain = config['domain'] mutils.maybeWarnAboutDomain(reactor, domain) closureLibrary = FilePath(config['closure-library']) mutils.maybeWarnAboutClosureLibrary(reactor, closureLibrary) socketPorts = [] for minervaStrport in config['minerva']: _, _args, _ = strports.parse(minervaStrport, object()) socketPorts.append(_args[0]) doReloading = bool(int(os.environ.get('PYRELOADING', '0'))) fileCache = FileCache(lambda: reactor.seconds(), 0.1 if doReloading else -1) stf, httpSite = demosminerva_site.makeMinervaAndHttp( reactor, fileCache, socketPorts, domain, closureLibrary) httpSite.displayTracebacks = not config["no-tracebacks"] for httpStrport in config['http']: httpServer = strports.service(httpStrport, httpSite) httpServer.setServiceParent(multi) for minervaStrport in config['minerva']: minervaServer = strports.service(minervaStrport, stf) minervaServer.setServiceParent(multi) if doReloading: mutils.enablePyquitter(reactor) return multi
def __init__(self, config): self.config = config base = config.base # game-related self.update_packet = ServerUpdate() self.update_packet.reset() self.connections = MultikeyDict() self.chunk_items = collections.defaultdict(list) self.entities = {} self.entity_ids = IDPool(1) self.update_loop = LoopingCall(self.update) self.update_loop.start(1.0 / constants.UPDATE_FPS, False) # server-related self.git_rev = base.get('git_rev', None) self.passwords = {} for k, v in base.passwords.iteritems(): self.passwords[k.lower()] = v self.scripts = [] for script in base.scripts: self.load_script(script) # time self.extra_elapsed_time = 0.0 self.start_time = reactor.seconds() self.set_clock('12:00')
def aimbotcheck(connection, user, minutes): connection = commands.get_player(connection.protocol, user) if connection not in connection.protocol.players: raise KeyError() kills = connection.tally_kill_log(reactor.seconds() - int(minutes)*60) return ('Il giocatore %s ha fatto %s uccisioni negli ultimi %s minuti.' % (connection.name, kills, minutes))
def on_chat(self, value, global_message): if not self.mute: current_time = reactor.seconds() if self.last_chat is None: self.last_chat = current_time else: self.chat_time += current_time - self.last_chat if self.chat_count > CHAT_WINDOW_SIZE: if self.chat_count / self.chat_time > CHAT_PER_SECOND: self.mute = True self.protocol.send_chat( '%s has been muted for excessive spam' % (self.name), irc = True) self.chat_time = self.chat_count = 0 else: self.chat_count += 1 self.last_chat = current_time message = '<%s> %s' % (self.name, value) if self.mute: message = '(MUTED) %s' % message elif global_message and self.protocol.global_chat: self.protocol.irc_say('<%s> %s' % (self.name, value)) print message.encode('ascii', 'replace') if self.mute: self.send_chat('(Chat not sent - you are muted)') return False elif global_message and not self.protocol.global_chat: self.send_chat('(Chat not sent - global chat disabled)') return False return value
def start_timer(self, end): if self.timer_end is not None: return 'Timer is running already.' self.timer_end = reactor.seconds() + end self.send_chat('Timer started, ending in %s minutes' % (end / 60), irc = True) self.display_timer(True)
def griefalert(self): player = self time = seconds() - AUTO_GC_TIME * 60 blocks_removed = player.blocks_removed or [] blocks = [b[1] for b in blocks_removed if b[0] >= time] player_name = player.name infos = set(blocks) infos.discard(None) namecheck = [[name, team, 0] for name, team in infos] if len(namecheck) > 0: for f in range(len(namecheck)): for i in range(len(blocks_removed)): if blocks_removed[i][1] is not None: if namecheck[f][0] == blocks_removed[i][1][0] and namecheck[f][1] == blocks_removed[i][1][1] and blocks_removed[i][0] >= time: namecheck[f][2] += 1 teamblocks = 0 enemyblocks = 1 for i in range(len(namecheck)): if namecheck[i][1] == player.team.id: teamblocks += namecheck[i][2] else: enemyblocks += namecheck[i][2] if not self.griefcheck_delay and float(teamblocks)/float(len(blocks)) >= AUTO_GC_RATIO and len(blocks) >= AUTO_GC_BLOCKS: message = "Potential griefer detected: " + player_name message += " removed " + str(len(blocks)) + " blocks in the past " + str(AUTO_GC_TIME) + " minutes, " message += " " + str(int(float(teamblocks)/float(len(blocks))* 100)) + "% from their own team" irc_relay = self.protocol.irc_relay if irc_relay.factory.bot and irc_relay.factory.bot.colors: message = '\x0304* ' + message + '\x0f' self.griefcheck_delay = True reactor.callLater(10,griefcheckdelay,self) irc_relay.send(message)
def on_orientation_update(self, x, y, z): if not self.first_orientation and self.world_object is not None: orient = self.world_object.orientation old_orient_v = (orient.x, orient.y, orient.z) new_orient_v = (x, y, z) theta = dot3d(old_orient_v, new_orient_v) if theta <= HEADSHOT_SNAP_ANGLE_COS: self_pos = self.world_object.position for enemy in self.team.other.get_players(): enemy_pos = enemy.world_object.position position_v = (enemy_pos.x - self_pos.x, enemy_pos.y - self_pos.y, enemy_pos.z - self_pos.z) c = scale(new_orient_v, dot3d(new_orient_v, position_v)) h = magnitude(subtract(position_v, c)) if h <= HEAD_RADIUS: current_time = reactor.seconds() self.headshot_snap_times.append(current_time) if self.get_headshot_snap_count() >= HEADSHOT_SNAP_THRESHOLD: if HEADSHOT_SNAP == BAN: self.ban('Aimbot trovato - headshot colpo secco', HEADSHOT_SNAP_BAN_DURATION) return elif HEADSHOT_SNAP == KICK: self.kick('Aimbot trovato - headshot colpo secco') return elif HEADSHOT_SNAP == WARN_ADMIN: if (current_time - self.headshot_snap_warn_time) > WARN_INTERVAL_MINIMUM: self.headshot_snap_warn_time = current_time self.warn_admin() else: self.first_orientation = False return connection.on_orientation_update(self, x, y, z)
def create_group(self, **kwargs): """ :return: a tuple of the scaling group with (the helper's pool) and the server name prefix used for the scaling group. """ if self.clbs: # allow us to override the CLB setup kwargs.setdefault( 'use_lbs', [clb.scaling_group_spec() for clb in self.clbs]) kwargs.setdefault("flavor_ref", flavor_ref) kwargs.setdefault("min_entities", 0) server_name_prefix = "{}-{}".format( random_string(), reactor.seconds()) if "server_name_prefix" in kwargs: server_name_prefix = "{}-{}".format(kwargs['server_name_prefix'], server_name_prefix) kwargs['server_name_prefix'] = server_name_prefix return ( ScalingGroup( group_config=create_scaling_group_dict(**kwargs), treq=self.treq, pool=self.pool), server_name_prefix)
def check_hit_counter(self): entity_data = self.connection.entity_data if entity_data.hit_counter < 0: self.log("negative hit counter. hits={hits}" .format(hits=entity_data.hit_counter), LOG_LEVEL_VERBOSE) self.remove_cheater('illegal hit counter') return False if reactor.seconds() - self.last_hit_time > 4 + self.last_hit_margin: self.hit_counter = 0 hit_counter_diff = entity_data.hit_counter - self.hit_counter if hit_counter_diff > self.max_hit_counter_difference: self.hit_counter_strikes += 1 if self.hit_counter_strikes > self.max_hit_counter_strikes: self.log("hit counter mismatch, hits={hits}, expected={exp}" .format(hits=entity_data.hit_counter, exp=self.hit_counter), LOG_LEVEL_VERBOSE) self.remove_cheater('illegal hit counter') return False else: self.hit_counter_strikes = 0
def on_hit(self, hit_amount, hit_player, type, grenade): if self.team is not hit_player.team: if type == WEAPON_KILL or type == HEADSHOT_KILL: current_time = reactor.seconds() shotgun_use = False if current_time - self.shot_time > (0.5 * hit_player.weapon_object.delay): shotgun_use = True self.multiple_bullets_count = 0 self.shot_time = current_time if type == HEADSHOT_KILL: self.multiple_bullets_count += 1 if self.weapon == RIFLE_WEAPON: if (not (hit_amount in RIFLE_DAMAGE)) and DETECT_DAMAGE_HACK: return False else: self.rifle_hits += 1 if self.multiple_bullets_count >= RIFLE_MULTIPLE_BULLETS_MAX: self.multiple_bullets_eject() return False elif self.weapon == SMG_WEAPON: if (not (hit_amount in SMG_DAMAGE)) and DETECT_DAMAGE_HACK: return False else: self.smg_hits += 1 if self.multiple_bullets_count >= SMG_MULTIPLE_BULLETS_MAX: self.multiple_bullets_eject() return False elif self.weapon == SHOTGUN_WEAPON: if (not (hit_amount in SHOTGUN_DAMAGE)) and DETECT_DAMAGE_HACK: return False elif shotgun_use: self.shotgun_hits += 1 return connection.on_hit(self, hit_amount, hit_player, type, grenade)
def test_twisted_schedule_now(self): scheduler = TwistedScheduler(reactor) diff = scheduler.now - datetime.utcfromtimestamp(float(reactor.seconds())) assert abs(diff) < timedelta(milliseconds=1)
def __init__(self, timeout_callback, etime, *callback_arguments): etime -= reactor.seconds() if etime < 0: etime = 0 self._timeout_callback = timeout_callback self._task = reactor.callLater(etime, self._run_once, *callback_arguments)
def get_time_limit(connection): advance_call = connection.protocol.advance_call if advance_call is None: return 'No time limit set' left = int(math.ceil((advance_call.getTime() - reactor.seconds()) / 60.0)) return 'There are %s minutes left' % left
def _work(_): d = pp.callRemote(First, data=b"ciao", _deadline=reactor.seconds()) self.assertFailure(d, error.ProcessTerminated) return d
def afk(connection, player): player = get_player(connection.protocol, player) elapsed = prettify_timespan(reactor.seconds() - player.last_activity, True) return S_AFK_CHECK.format(player=player.name, time=elapsed)
def update(self): bans = [] for network, (name, reason, timestamp) in self.protocol.bans.iteritems(): if timestamp is None or reactor.seconds() < timestamp: bans.append({"username": name,"ip" : network, "reason" : reason}) self.json_bans = json.dumps(bans)
def _cb_doWork(self, command, _timeout=None, _deadline=None, **kwargs): """ Go and call the command. @param command: The L{amp.Command} to be executed in the child @type command: L{amp.Command} @param _d: The deferred for the calling code. @type _d: L{defer.Deferred} @param _timeout: The timeout for this call only @type _timeout: C{int} @param _deadline: The deadline for this call only @type _deadline: C{int} """ timeoutCall = None deadlineCall = None def _returned(result, child, is_error=False): def cancelCall(call): if call is not None and call.active(): call.cancel() cancelCall(timeoutCall) cancelCall(deadlineCall) self.busy.discard(child) if not die: # we are not marked to be removed, so add us back to # the ready set and let's see if there's some catching # up to do self.ready.add(child) self._catchUp() else: # We should die and we do, then we start a new worker # to pick up stuff from the queue otherwise we end up # without workers and the queue will remain there. self.stopAWorker(child).addCallback( lambda _: self.startAWorker()) self._lastUsage[child] = now() # we can't do recycling here because it's too late and # the process might have received tons of calls already # which would make it run more calls than what is # configured to do. return result die = False child = self.ready.pop() self.busy.add(child) self._calls[child] += 1 # Let's see if this call goes over the recycling barrier if self.recycleAfter and self._calls[child] >= self.recycleAfter: # it does so mark this child, using a closure, to be # removed at the end of the call. die = True # If the command doesn't require a response then callRemote # returns nothing, so we prepare for that too. # We also need to guard against timeout errors for child # and local timeout parameter overrides the global one if _timeout == 0: timeout = _timeout else: timeout = _timeout or self.timeout if timeout is not None: from twisted.internet import reactor timeoutCall = reactor.callLater(timeout, self._handleTimeout, child) if _deadline is not None: from twisted.internet import reactor delay = max(0, _deadline - reactor.seconds()) deadlineCall = reactor.callLater(delay, self._handleTimeout, child) return defer.maybeDeferred(child.callRemote, command, **kwargs).addCallback( _returned, child).addErrback(_returned, child, is_error=True)
def f(*args, **kwargs): now = reactor.seconds() num_pending = 0 # _newTimedCalls is one long list of *all* pending calls. Below loop # is based off of impl of reactor.runUntilCurrent for delayed_call in reactor._newTimedCalls: if delayed_call.time > now: break if delayed_call.delayed_time > 0: continue num_pending += 1 num_pending += len(reactor.threadCallQueue) start = time.time() ret = func(*args, **kwargs) end = time.time() # record the amount of wallclock time spent running pending calls. # This is a proxy for the actual amount of time between reactor polls, # since about 25% of time is actually spent running things triggered by # I/O events, but that is harder to capture without rewriting half the # reactor. tick_time.observe(end - start) pending_calls_metric.observe(num_pending) # Update the time we last ticked, for the metric to test whether # Synapse's reactor has frozen global last_ticked last_ticked = end if running_on_pypy: return ret # Check if we need to do a manual GC (since its been disabled), and do # one if necessary. Note we go in reverse order as e.g. a gen 1 GC may # promote an object into gen 2, and we don't want to handle the same # object multiple times. threshold = gc.get_threshold() counts = gc.get_count() for i in (2, 1, 0): # We check if we need to do one based on a straightforward # comparison between the threshold and count. We also do an extra # check to make sure that we don't a GC too often. if threshold[i] < counts[i] and MIN_TIME_BETWEEN_GCS[ i] < end - _last_gc[i]: if i == 0: logger.debug("Collecting gc %d", i) else: logger.info("Collecting gc %d", i) start = time.time() unreachable = gc.collect(i) end = time.time() _last_gc[i] = end gc_time.labels(i).observe(end - start) gc_unreachable.labels(i).set(unreachable) return ret
def update(fle, reactor): fle.setContent(time.ctime(reactor.seconds()))
def test_fuzz(self): # note that this will loop if do_fuzz doesn't take long enough endTime = reactor.seconds() + self.FUZZ_TIME while reactor.seconds() < endTime: yield self.do_fuzz(endTime)
def reset_afk_kick_call(self): self.last_activity = reactor.seconds() if self.afk_kick_call and self.afk_kick_call.active(): self.afk_kick_call.reset(time_limit)
def test_wall_sleep(self): t1 = reactor.seconds() yield util.wall_sleep(2.) t2 = reactor.seconds() assert 1 <= t2 - t1 <= 3
def score_grief(connection, player, time=None): # 302 = blue (0), #303 = green (1) print("start score grief") color = connection not in connection.protocol.players and connection.colors minutes = float(time or 2) if minutes < 0.0: raise ValueError() time = reactor.seconds() - minutes * 60.0 blocks_removed = player.blocks_removed or [] blocks = [b[1] for b in blocks_removed if b[0] >= time] player_name = player.name team_id = player.team.id # 0=blue, 1=green print("name/team set") gscore = 0 # griefscore map_blocks = 0 team_blocks = 0 enemy_blocks = 0 team_harmed = 0 enemy_harmed = 0 print("init values set") if len(blocks): print("len blocks = true, blocks found") total_blocks = len(blocks) info = blocks for info in blocks: if info: name, team = info if name != player_name and team == team_id: team_blocks += 1 elif team != team_id: enemy_blocks += 1 else: map_blocks += 1 print("second for done") infos = set(blocks) infos.discard(None) for name, team in infos: if name != player_name and team == team_id: team_harmed += 1 elif team != team_id: enemy_harmed += 1 print("third for done") else: print("len blocks = false, no blocks found") total_blocks = 0 # heuristic checks start here # if they didn't break any blocks at all, they probably aren't griefing. if total_blocks == 0: print("no blocks, ending") return 0 # checks on team blocks destroyed if team_blocks > 0 and team_blocks <= 5: gscore += 1 elif team_blocks > 5 and team_blocks <= 10: gscore += 2 elif team_blocks > 10 and team_blocks <= 25: gscore += 4 elif team_blocks > 25 and team_blocks <= 50: gscore += 6 elif team_blocks > 50: gscore += 10 print("team blocks set") # team / total ratio checks if total_blocks != 0: ttr = (float(team_blocks) / float(total_blocks)) * 100 if ttr > 5 and ttr <= 20: gscore += 1 elif ttr > 20 and ttr <= 50: gscore += 2 elif ttr > 50 and ttr <= 80: gscore += 3 elif ttr > 80: gscore += 4 print("ttr set") # teammates harmed check if team_harmed == 1: gscore += 1 elif team_harmed > 2 and team_harmed <= 4: gscore += 3 elif team_harmed > 4: gscore += 6 print("team harmed set") print("mb: %s, tb: %s, eb: %s, Tb: %s, th: %s, ttr: %s, eh: %s, gs: %s" % (map_blocks, team_blocks, enemy_blocks, total_blocks, team_harmed, ttr, enemy_harmed, gscore)) return gscore
def _work(_): d = pp.callRemote(Pid, _deadline=reactor.seconds() + 10) d.addCallback(lambda result: self.assertNotEqual(result['pid'], 0)) return d
def get_now(): return datetime.utcfromtimestamp(reactor.seconds())
def get_time_active(self): elapsed = self.seconds_active if self.last_usage: elapsed += seconds() - self.last_usage return timedelta(seconds=int(elapsed))
def test1(arguments, testnum): print testnum arguments['test'] = True reactor.crash() def test2(arguments, testnum): print testnum arguments['test'] = 'bar' reactor.crash() arguments = {'test': False} timeout_1 = Timeout(test1, 0, 1, arguments, 'test1') reactor.run() assert (arguments['test']) timeout_1 = Timeout(test1, 0.1, 1, arguments, 'test2') timeout_2 = Timeout(test2, 0.2, 1, arguments, 'test3') timeout_1.cancel() reactor.run() assert (arguments['test'] == 'bar') arguments = {'test': False} timeout_1 = TimeoutAbs(test1, reactor.seconds(), arguments, 'test4') reactor.run() assert (arguments['test']) timeout_1 = TimeoutAbs(test1, reactor.seconds() + 0.1, arguments, 'test5') timeout_2 = TimeoutAbs(test2, reactor.seconds() + 0.2, arguments, 'test6') timeout_1.cancel() reactor.run() assert (arguments['test'] == 'bar')
def update(application, reactor): stamp = time.ctime(reactor.seconds()) application.greeting = "hello world, it's {}".format(stamp)
def get_color(self): t = 1.0 - (self.final_time - seconds()) / self.duration t = min(1.0, self.interpolator(t)) return interpolate_rgb(self.begin(), self.end(), t)
def html_get_afk(ignore, player): return prettify_timespan(reactor.seconds() - player.last_activity, True)
def action(scheduler, state): nonlocal endtime endtime = reactor.seconds()
def action(scheduler, state): endtime[0] = reactor.seconds()
def start(self): if not self.loop.running: self.final_time = seconds() + self.duration self.loop.start(FOG_INTERVAL, now=True)
def send_zoomv_chat(self, message): last_message = self.last_zoomv_message if last_message is None or reactor.seconds() - last_message >= 1.0: self.send_chat(message) self.last_zoomv_message = reactor.seconds()
def on_kill(self, killer, type, grenade): if killer and killer.team is self.team: if killer.teamkill_times is None: killer.teamkill_times = [] killer.teamkill_times.append(seconds()) return connection.on_kill(self, killer, type, grenade)
def on_block_action_recieved(self, contained: loaders.BlockAction) -> None: world_object = self.world_object if not self.hp: return value = contained.value if value == BUILD_BLOCK: interval = TOOL_INTERVAL[BLOCK_TOOL] elif self.tool == WEAPON_TOOL: if self.weapon_object.is_empty(): return interval = WEAPON_INTERVAL[self.weapon] else: interval = TOOL_INTERVAL[self.tool] current_time = reactor.seconds() last_time = self.last_block self.last_block = current_time if (self.rapid_hack_detect and last_time is not None and current_time - last_time < interval): self.rapids.add(current_time) if self.rapids.check(): start, end = self.rapids.get() if end - start < MAX_RAPID_SPEED: log.info('RAPID HACK:', self.rapids.window) self.on_hack_attempt('Rapid hack detected') return map = self.protocol.map x = contained.x y = contained.y z = contained.z if z >= 62: return if value == BUILD_BLOCK: self.blocks -= 1 pos = world_object.position if self.blocks < -BUILD_TOLERANCE: return elif not collision_3d(pos.x, pos.y, pos.z, x, y, z, MAX_BLOCK_DISTANCE): return elif self.on_block_build_attempt(x, y, z) == False: return elif not map.build_point(x, y, z, self.color): return self.on_block_build(x, y, z) else: if not map.get_solid(x, y, z): return pos = world_object.position if self.tool == SPADE_TOOL and not collision_3d( pos.x, pos.y, pos.z, x, y, z, MAX_DIG_DISTANCE): return if self.on_block_destroy(x, y, z, value) == False: return elif value == DESTROY_BLOCK: count = map.destroy_point(x, y, z) if count: self.total_blocks_removed += count self.blocks = min(50, self.blocks + 1) self.on_block_removed(x, y, z) elif value == SPADE_DESTROY: for xyz in ((x, y, z), (x, y, z + 1), (x, y, z - 1)): count = map.destroy_point(*xyz) if count: self.total_blocks_removed += count self.on_block_removed(*xyz) self.last_block_destroy = reactor.seconds() block_action.x = x block_action.y = y block_action.z = z block_action.value = contained.value block_action.player_id = self.player_id self.protocol.send_contained(block_action, save=True) self.protocol.update_entities()
def grief_check(connection, player, minutes=2): player = get_player(connection.protocol, player) protocol = connection.protocol color = connection not in protocol.players.values() and connection.colors minutes = float(minutes) if minutes <= 0.0: raise ValueError('minutes must be number greater than 0') time = seconds() - minutes * 60.0 blocks_removed = player.blocks_removed or [] blocks = [b[1] for b in blocks_removed if b[0] >= time] player_name = player.name if color: player_name = (('\x0303' if player.team.id else '\x0302') + player_name + '\x0f') message = '%s removed %s block%s in the last ' % ( player_name, len(blocks) or 'no', '' if len(blocks) == 1 else 's') if minutes == 1.0: minutes_s = 'minute' else: minutes_s = '{:.1f} minutes'.format(minutes) message += minutes_s + '.' if len(blocks): infos = set(blocks) infos.discard(None) if color: names = [('\x0303' if team else '\x0302') + name for name, team in infos] else: names = set([name for name, team in infos]) if len(names) > 0: message += (' Some of them were placed by ' + ('\x0f, ' if color else ', ').join(names)) message += '\x0f.' if color else '.' else: message += ' All of them were map blocks.' last = blocks_removed[-1] time_s = prettify_timespan(seconds() - last[0], get_seconds=True) message += ' Last one was destroyed %s ago' % time_s whom = last[1] if whom is None and len(names) > 0: message += ', and was part of the map' elif whom is not None: name, team = whom if color: name = ('\x0303' if team else '\x0302') + name + '\x0f' message += ', and belonged to %s' % name message += '.' switch_sentence = False if player.last_switch is not None and player.last_switch >= time: time_s = prettify_timespan(seconds() - player.last_switch, get_seconds=True) message += ' %s joined %s team %s ago' % (player_name, player.team.name, time_s) switch_sentence = True teamkills = len([t for t in player.teamkill_times or [] if t >= time]) if teamkills > 0: s = ', and killed' if switch_sentence else ' %s killed' % player_name message += s + ' %s teammates in the last %s' % (teamkills, minutes_s) if switch_sentence or teamkills > 0: message += '.' votekick = getattr(protocol, 'votekick', None) if (votekick and votekick.victim is player and votekick.victim.world_object and votekick.instigator.world_object): instigator = votekick.instigator tiles = int( distance_3d_vector(player.world_object.position, instigator.world_object.position)) instigator_name = (('\x0303' if instigator.team.id else '\x0302') + instigator.name + '\x0f') message += (' %s is %d tiles away from %s, who started the votekick.' % (player_name, tiles, instigator_name)) return message
def do_ping(self): start = reactor.seconds() yield self.get_shares(hashes=[0], parents=0, stops=[]) end = reactor.seconds() defer.returnValue(end - start)
def on_connect(self): if time_limit: self.afk_kick_call = reactor.callLater(time_limit, self.afk_kick) self.last_activity = reactor.seconds() return connection.on_connect(self)
def _processChanges(self, page): result = json.loads(page, encoding=self.encoding) for pr in result['values']: branch = pr['source']['branch']['name'] nr = int(pr['id']) # Note that this is a short hash. The full length hash can be accessed via the # commit api resource but we want to avoid requesting multiple pages as long as # we are not sure that the pull request is new or updated. revision = pr['source']['commit']['hash'] # check branch if not self.branch or branch in self.branch: current = yield self._getCurrentRev(nr) # compare _short_ hashes to check if the PR has been updated if not current or current[0:12] != revision[0:12]: # parse pull request api page (required for the filter) page = yield client.getPage(str(pr['links']['self']['href'])) pr_json = json.loads(page, encoding=self.encoding) # filter pull requests by user function if not self.pullrequest_filter(pr_json): log.msg('pull request does not match filter') continue # access additional information author = pr['author']['display_name'] prlink = pr['links']['html']['href'] # Get time updated time. Note that the timezone offset is # ignored. if self.useTimestamps: updated = datetime.strptime( pr['updated_on'].split('.')[0], '%Y-%m-%dT%H:%M:%S') else: updated = epoch2datetime(reactor.seconds()) title = pr['title'] # parse commit api page page = yield client.getPage(str(pr['source']['commit']['links']['self']['href'])) commit_json = json.loads(page, encoding=self.encoding) # use the full-length hash from now on revision = commit_json['hash'] revlink = commit_json['links']['html']['href'] # parse repo api page page = yield client.getPage(str(pr['source']['repository']['links']['self']['href'])) repo_json = json.loads(page, encoding=self.encoding) repo = repo_json['links']['html']['href'] # update database yield self._setCurrentRev(nr, revision) # emit the change yield self.master.data.updates.addChange( author=ascii2unicode(author), revision=ascii2unicode(revision), revlink=ascii2unicode(revlink), comments=u'pull-request #%d: %s\n%s' % ( nr, title, prlink), when_timestamp=datetime2epoch(updated), branch=self.branch, category=self.category, project=self.project, repository=ascii2unicode(repo), src=u'bitbucket', )