def generate_ranking(self): # Also check end of the game for player in self.players.values(): # if player.dots > CST.SIZE ** 2 / (0.8 * self.active_players()): if player.dots > CST.WIN_DOTS: log("Game won by " + player.nick) mg.broadcast(struct.pack("!BB", CST.WIN, player.id)) self.task_game.stop() self.task_rank.stop() self.restart() break # WHY NOT CLIENT-SIDE ONLY ? ranking = {} for _id in mg.connections: count = sum(value == _id for value in mg.world.values()) if count: ranking[count] = _id ranking = sorted(ranking.items(), reverse=True) ranking = [_id for (count, _id) in ranking] rank_struct = "!BB" + str(len(ranking)) + "B" mg.broadcast( struct.pack(rank_struct, CST.RANKING, len(ranking), *ranking))
def irc_NICK(self, prefix, params): """ Called when an IRC user changes their nick. """ old_nick = prefix.split('!')[0] new_nick = params[0] log("%s is now known as %s" % (old_nick, new_nick))
def onionooParseSummaryBridge(bridge): try: h = bridge['h'] return h except: log("Error in onionooParseSummaryRelay(%s)" % bridge) return None
def __init__(self, port, newhost, newport): Thread.__init__(self) log("Redirecting:localhost:%s->%s:%s", port, newhost, newport) self.newhost = newhost self.newport = newport self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind(("", port)) self.sock.listen(5)
def run(self): while True: newsock, address = self.sock.accept() log("Creating new session for %s:%s", *address) fwd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) fwd.connect((self.newhost, self.newport)) PipeThread(newsock, fwd).start() PipeThread(fwd, newsock).start()
def __init__(self, port, newhost, newport): Thread.__init__(self) log('Redirecting:localhost:%s->%s:%s', port, newhost, newport) self.newhost = newhost self.newport = newport self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.bind(('', port)) self.sock.listen(5)
def run(self): while True: newsock, address = self.sock.accept() log('Creating new session for %s:%s', *address) fwd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) fwd.connect((self.newhost, self.newport)) PipeThread(newsock, fwd).start() PipeThread(fwd, newsock).start()
def connectionMade(self): global log irc.IRCClient.connectionMade(self) self.logger = MessageLogger(open(self.factory.filename, "a")) log = self.logger.log log("[connected at %s]" % time.asctime(time.localtime(time.time())))
def resumeProducing(self): """We can write to the transport again. Yay!.""" time_now = int(time.time()) log("Resumed TCP redirect. " "Dropped %s messages during %s seconds ", self.dropped, time_now - self.last_paused) self.paused = False self.dropped = 0 self.last_paused = None
def onionooParseSummaryRelay(relay): try: f = relay['f'] addrs = relay['a'] a = '' for addr in addrs: a = a + addr + ' ' return str(a), str(f) except: log("Error in onionooParseSummaryRelay(%s)" % relay) return None, None
def onionooParseSummaryGeneric(node): try: n = node['n'] if node['r'] == 'True': r = ' is running.' else: r = ' is not running.' return str(n), str(r) except: log("Error in onionooParseSummaryGeneric(%s)" % node) return None, None
def __init__(self, source, sink): Thread.__init__(self) self.source = source self.sink = sink log("Creating new pipe thread %s ( %s -> %s )", self, source.getpeername(), sink.getpeername()) self.pipeslock.acquire() try: self.pipes.append(self) finally: self.pipeslock.release() log("%s pipes now active", pipes_now)
def __init__(self, source, sink): Thread.__init__(self) self.source = source self.sink = sink log('Creating new pipe thread %s ( %s -> %s )', self, source.getpeername(), sink.getpeername()) self.pipeslock.acquire() try: self.pipes.append(self) finally: self.pipeslock.release() log('%s pipes now active', pipes_now)
def run(self): while True: try: data = self.source.recv(1024) if not data: break self.sink.send(data) except: break log('%s terminating', self) self.pipeslock.acquire() try: pipes_left = len(self.pipes) finally: self.pipeslock.release() log('%s pipes still active', pipes_left)
def __create_URL__(self, query): """ Turns an IRC query such as 'node details noise' into the correct URL for the Onionoo API. """ database = 'http://onionoo.torproject.org/' if query.startswith('details'): url = database + "details?search=" + str(query[8:]) elif query.startswith('bandwidth'): url = database + "bandwidth?search=" + str(query[10:]) elif query.startswith('summary'): url = database + "summary?search=" + str(query[8:]) else: log(err) return url
def run(self): while True: try: data = self.source.recv(1024) if not data: break self.sink.send(data) except: break log("%s terminating", self) self.pipeslock.acquire() try: pipes_left = len(self.pipes) finally: self.pipeslock.release() log("%s pipes still active", pipes_left)
def onionooParseSummary(self, leek, msg, channel): print type(leek) if type(leek) is dict: print "IS DICT" if leek.has_key(u'relays'): print "HAS KEY RELAYS" relays = leek[u'relays'] print "OH YEAH RELAYS" for relay in relays: n, r = self.onionooParseSummayGeneric(relay) print "DID THE GENERIC SUMMARY" a, f = self.onionooParseSummaryRelay(relay) print "DID THE RELAY SUMMARY" if a and f and n and r is not None: "A & F & N & R IS NOT NONE!" i = "Relay " + n + " with fingerprint " + f + \ " at " + a + r self.msg(channel, i) return finished else: i = "Unable to parse some relay info..." for x in (a, f, n, r): if x is not None: i = i + x + " " self.msg(channel, i) log("%s %s %s %s %s" % (i, a, f, n, r)) return finished else: i = "I didn't find any relays matching query " + str(msg) self.msg(channel, i) log("%s" % i) return finished if leek.has_key(u'bridges'): bridges = leek[u'bridges'] for bridge in bridges: n, r = self.onionooParseSummayGeneric(bridge) h = self.onionooParseSummaryBridge(bridge) if h and n and r is not None: i = "Bridge " + n + " with hashed fingerprint " + h + r self.msg(channel, i) return finished else: i = "Unable to parse some bridge info..." for x in (h, n, r): if x is not None: i = i + x + " " self.msg(channel, i) log("%s %s %s %s" % (i, h, n, r)) return finished else: i = "I didn't find any bridges matching query " + str(msg) self.msg(channel, i) log("%s" % i) return finished else: print "I'M NOT A F*****G DICT!"
def flush(self): """ Write logs in buffer to wherever the normal logging would go """ if not self._buffer: newbuffer = [] else: newbuffer = list(self._buffer) self._buffer = [] for msg in newbuffer: try: yield threads.deferToThread( super(self.__class__, self).log, *msg) except Exception as e: log('FILE LOGGING FAILED - log: %s excepton: %s' % (log, e)) self._buffer.append(msg)
def build(self, req): [builders, error] = self.getBuilders(req) if error is not None: return error reason = str(req.args.get("comments", [""])[0]) if len(reason) < 1: reason = "<no reason specified>" [properties, error] = self.getProperties(req) if error is not None: return error log.msg("web force build with properties for builders=[%s]" % ( " ".join(builders))) failed_builders = [] control = interfaces.IControl(self.getBuildmaster(req)) source_stamp = SourceStamp(branch=None, revision=None) for builder_name in builders: bc = control.getBuilder(builder_name) if not bc: failed_builders.append((builder_name, "Failed to get builder controller")) log("could not force build %s - failed to get build control" % ( builder_name)) continue try: bc.submitBuildRequest(source_stamp, reason, properties) except interfaces.NoSlaveError: failed_builders.append((builder_name, "No slave available")) if (len(failed_builders) > 0): reasons = ["<dt>%s</dt><dd>%s</dd>" % ( cgi.escape(x[0]), cgi.escape(x[1])) for x in failed_builders] return BuildError("The following builders failed to build: <dl>%s</dl>" % ( "\n".join(reasons)), req, False) # this isn't an error, but at this point I'm feeling lazy # it should realy be a templated html instead HTML = "<p>Build request submitted.</p>" return BuildError(HTML, req, False)
def get_next_host(): if not config.lb_file: return None try: hosts = [] f = open(config.lb_file, "r") for l in f.readlines(): hosts.append(l.strip()) f.close() my_host = "%s:%d" % (config.hostname, config.port) for i in range(0, 10): ndx = random.randint(0, len(hosts)-1) h = hosts[ndx] if h != my_host: return h return h except Exception, ex: log(logging.ERROR, "get next host error %s" % (str(ex))) return None
def privmsg(self, user, channel, msg): """ Try to discourage other nicks from querying the bot. """ self._channel = channel user = user.split('!', 1)[0] log("<%s> %s" % (user, msg)) heard_before = False if channel == self.nickname: if not heard_before: speak = "Why are you whispering?" self.msg(user, speak) heard_before = True return else: speak = self.makeQuote() self.msg(user, speak) return if msg.startswith(self.nickname + ":"): speak = "%s: %s" % (user, self.makeQuote()) self.msg(channel, speak) log("<%s> %s" % (self.nickname, speak)) if 'node details' or 'node bandwidth' or 'node summary' in msg: self.query = msg[5:] elif 'node details' or 'node bandwidth' or 'node summary' in msg: self.query = msg[5:] else: log("%s said '%s', which did not include a stats cmd." % (user, msg)) if self.query is not None: self.onionooQuery(self.query, msg, channel) self.query = None
def onMessage(self, data, isBinary): ## echo back message verbatim bs.put_data(data) while bs.working(): msg_type = bs.read_byte() if msg_type == CST.CONNECTION: # Here to prevent client receiving other clients datas before init mg.connections[self.id] = self print("Num connections", len(mg.connections.values())) self.tosend = b'' # NICKNAME self.nick = bs.read_UTF().decode("utf-8") log("Connection from " + str(self.nick)) # RANDOM COLOR color, = randomcolor.RandomColor().generate(luminosity="light") self.color = int("0x" + color[1:], 16) self.player = self.new_player() self.REALLY_connected = 1 # HOHO # BROADCAST CONNECTION for connection in mg.connections.values(): if connection.REALLY_connected: if connection != self: # Send players to me self.send(connection.get_datas_connection()) # Send me to players connection.send(self.get_datas_connection()) else: # Send me to me self.send(self.get_datas_connection(me=1)) # MAP flat_world = mg.game.get_world() self.send(get_map_struct(flat_world)) # SEND TOWERS for pillar in mg.game.pillars: print("send tower") self.send( struct.pack("!5B", CST.PILLAR, 1, pillar.owner.id, pillar.x, pillar.y)) if msg_type == CST.DOT_COLOR: posx, posy = int(bs.read_byte()), int(bs.read_byte()) if self.player.energy > CST.DOT_COST: pushed = self.push_dot(posx, posy) if pushed: self.player.energy -= CST.DOT_COST if msg_type == CST.TOWER: log("Tower create") x, y = int(bs.read_byte()), int(bs.read_byte()) if self.player.energy > 25: buildable = True for (dx, dy) in self.checklist: xt = x + dx yt = y + dy if Tool.valid_position(xt, yt): if mg.world[xt, yt] != self.id: buildable = False else: buildable = False if buildable: print("buildable") mg.broadcast(struct.pack("!4B", CST.TOWER, 1, x, y)) Tower(mg, x, y, self) self.player.energy -= 25 if msg_type == CST.PILLAR: log("Pillar create") x, y = int(bs.read_byte()), int(bs.read_byte()) # if self.player.energy > 50: if self.player.energy > 0: buildable = True if Tool.valid_position(x, y): if mg.world[x, y] != self.id: buildable = False else: buildable = False if buildable: print("buildable") mg.broadcast( struct.pack("!5B", CST.PILLAR, 1, self.id, x, y)) Pillar(mg, x, y, self) self.player.energy -= 50 if msg_type == CST.MESSAGE: chatmsg = bs.read_UTF() log(self.nick + " > " + self.dec(chatmsg)) chatstruct = "!BBH" + str(len(chatmsg)) + "s" mg.broadcast( struct.pack(chatstruct, CST.MESSAGE, self.id, len(chatmsg), chatmsg))
def joined(self, channel): """ Called when the bot joins the channel. """ log("[I have joined %s]" % channel)
def clientConnectionFailed(self, connector, reason): log("FATAL: connection failed: %s" % reason, level=LOG_ERROR) reactor.stop()
def describeFact(self, bot, room, user, args): try: return "{0}: Triggered by '{1}', authored by {2}, {3}".format(room["factSpouted"]["factoid"]["reply"], room["factSpouted"]["trigger"], room["factSpouted"]["factoid"]["author"], room["factSpouted"]["factoid"]["created"]) except KeyError: log("Exception getting last factoid, probably hasn't triggered here yet: " + str(e)) return "I haven't triggered anything here recently!"
from twisted.python import log import sys log.startLogging(sys.stdout) from twisted.internet import defer defer.Deferred.debug = True from octopus.runtime import * s = sequence( log("one"), sequence( log("two"), log("three"), ), wait("3s"), log("four"), ) run(s)
class TWDNSProxy(server.DNSServerFactory): def gotResolverResponse(self, (ans, auth, add), protocol, message, address): log(message.queries[0].name) args = (self, (ans, auth, add), protocol, message, address) return server.DNSServerFactory.gotResolverResponse(*args)
def action(self, user, channel, msg): """ When someone else does an action. """ user = user.split("!", 1)[0] log("* %s %s" % (user, msg))
def connectionMade(self): self.transport.write('dskdjsdksdjskdjsdks') print 'connection is build!' log('dskhddksdkj')
def openShell(self, transport): log('No interactive shell')
def connectionLost(self, reason): irc.IRCClient.connectionLost(self, reason) log("[disconnected at %s]" % time.asctime(time.localtime(time.time()))) self.logger.close()