Handle multiple data packets in a packet for the broker

This commit is contained in:
simon.kagstrom 2010-02-15 06:22:11 +00:00
parent c97ab6801b
commit fae666980c

View File

@ -406,49 +406,66 @@ class Peer:
self.name, self.key, self.is_master) self.name, self.key, self.is_master)
class BrokerPacketHandler(SocketServer.DatagramRequestHandler): class BrokerPacketHandler(SocketServer.DatagramRequestHandler):
def get_packet_from_data(self, data): def get_packets_from_data(self, data):
magic = struct.unpack(">H", data[0:2])[0] pkts = []
type = struct.unpack(">H", data[2:4])[0] off = 0
if magic != FRODO_NETWORK_MAGIC: while True:
raise Exception("Packet magic does not match: %4x vs %4x\n" % (magic, if off >= len(data):
break
magic = struct.unpack(">H", data[off:off + 2])[0]
type = struct.unpack(">H", data[off + 2:off + 4])[0]
size = struct.unpack(">L", data[off + 4:off + 8])[0]
if type == STOP:
break
pkt_data = data[off:off + size]
off = off + size
if magic != FRODO_NETWORK_MAGIC:
raise Exception("Packet magic does not match: %4x vs %4x\n" % (magic,
FRODO_NETWORK_MAGIC) ) FRODO_NETWORK_MAGIC) )
try: try:
out = packet_class_by_type[type]() out = packet_class_by_type[type]()
out.demarshal_from_data(data) out.demarshal_from_data(pkt_data)
return out
except KeyError, e: pkts.append(out)
raise Exception("Unknown packet type %d" % (type)) except KeyError, e:
raise Exception("Unknown packet type %d" % (type))
return pkts
def handle(self): def handle(self):
srv = self.server srv = self.server
data = self.rfile.read() data = self.rfile.read()
try: try:
pkt = self.get_packet_from_data(data) pkts = self.get_packets_from_data(data)
except Exception, e: except Exception, e:
log_error("Broken packet: %s" % e) log_error("Broken packets: %s" % e)
return return
# Log received packets (except ping ACKs to avoid filling the server) for pkt in pkts:
if pkt.get_type() != ACK: # Log received packets (except ping ACKs to avoid filling the server)
t = pkt.get_type() if pkt.get_type() != ACK:
s = "%d" % (t) t = pkt.get_type()
s = "%d" % (t)
try:
s = pkt_type_to_str[t]
except KeyError, e:
pass
log_info("Received packet %s from %s:%d" % (s, self.client_address[0],
self.client_address[1]))
peer = srv.get_peer(self.client_address)
try: try:
s = pkt_type_to_str[t] peer.handle_packet(pkt)
except KeyError, e: except Exception, e:
pass # Sends crap, let's remove it
log_info("Received packet %s from %s:%d" % (s, self.client_address[0], log_error("Handling packets failed, removing peer: %s" % e)
self.client_address[1])) srv.remove_peer(peer)
peer = srv.get_peer(self.client_address)
try:
peer.handle_packet(pkt)
except Exception, e:
# Sends crap, let's remove it
log_error("Handling packet failed, removing peer: %s" % e)
srv.remove_peer(peer)
class Broker(SocketServer.UDPServer): class Broker(SocketServer.UDPServer):