2009-08-20 12:51:47 -06:00
|
|
|
#! /usr/bin/env python3
|
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
import asyncore
|
|
|
|
import socket
|
2009-08-20 12:51:47 -06:00
|
|
|
import struct
|
|
|
|
import points
|
|
|
|
import time
|
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
class MyHandler(asyncore.dispatcher):
|
|
|
|
def __init__(self, port):
|
|
|
|
asyncore.dispatcher.__init__(self)
|
|
|
|
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
self.bind(('', port))
|
|
|
|
self.acked = points.Storage('scores.dat')
|
|
|
|
self.outq = []
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def writable(self):
|
|
|
|
return bool(self.outq)
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def handle_write(self):
|
|
|
|
dgram, peer = self.outq.pop(0)
|
|
|
|
self.socket.sendto(dgram, peer)
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def handle_read(self):
|
|
|
|
dgram, peer = self.socket.recvfrom(4096)
|
2009-08-20 12:51:47 -06:00
|
|
|
now = int(time.time())
|
|
|
|
try:
|
2009-08-31 16:27:57 -06:00
|
|
|
req = points.decode_request(dgram)
|
2009-08-20 12:51:47 -06:00
|
|
|
except ValueError as e:
|
|
|
|
return self.respond(now, str(e))
|
|
|
|
when, cat, team, score = req
|
|
|
|
|
|
|
|
# Replays can happen legitimately.
|
2009-08-31 16:27:57 -06:00
|
|
|
if not req in self.acked:
|
2009-08-20 16:20:44 -06:00
|
|
|
if not (now - 2 < when <= now):
|
2009-08-20 12:51:47 -06:00
|
|
|
resp = points.encode_response(when, 'Your clock is off')
|
2009-08-31 16:27:57 -06:00
|
|
|
self.outq.append((resp, peer))
|
2009-08-20 12:51:47 -06:00
|
|
|
return
|
2009-08-31 16:27:57 -06:00
|
|
|
self.acked.add(req)
|
2009-08-20 12:51:47 -06:00
|
|
|
|
|
|
|
resp = points.encode_response(when, 'OK')
|
2009-08-31 16:27:57 -06:00
|
|
|
self.outq.append((resp, peer))
|
|
|
|
|
|
|
|
def respond(self, peer, when, txt):
|
|
|
|
resp = points.encode_response(when, txt)
|
|
|
|
self.outq.append((resp, peer))
|
2009-08-20 12:51:47 -06:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2009-08-31 16:27:57 -06:00
|
|
|
h = MyHandler(6667)
|
|
|
|
asyncore.loop()
|