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,30 +406,47 @@ 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
while True:
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: if magic != FRODO_NETWORK_MAGIC:
raise Exception("Packet magic does not match: %4x vs %4x\n" % (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
pkts.append(out)
except KeyError, e: except KeyError, e:
raise Exception("Unknown packet type %d" % (type)) 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
for pkt in pkts:
# Log received packets (except ping ACKs to avoid filling the server) # Log received packets (except ping ACKs to avoid filling the server)
if pkt.get_type() != ACK: if pkt.get_type() != ACK:
t = pkt.get_type() t = pkt.get_type()
@ -447,7 +464,7 @@ class BrokerPacketHandler(SocketServer.DatagramRequestHandler):
peer.handle_packet(pkt) peer.handle_packet(pkt)
except Exception, e: except Exception, e:
# Sends crap, let's remove it # Sends crap, let's remove it
log_error("Handling packet failed, removing peer: %s" % e) log_error("Handling packets failed, removing peer: %s" % e)
srv.remove_peer(peer) srv.remove_peer(peer)
class Broker(SocketServer.UDPServer): class Broker(SocketServer.UDPServer):