moth/ctf/pointsd.py

57 lines
1.5 KiB
Python
Raw Normal View History

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 time
2009-10-05 13:33:20 -06:00
from . import points
from . import config
2009-08-20 12:51:47 -06:00
2009-10-05 13:33:20 -06:00
house = config.get('global', 'house_team')
2009-09-01 09:34:15 -06:00
2009-08-31 16:27:57 -06:00
class MyHandler(asyncore.dispatcher):
2009-09-01 09:34:15 -06:00
def __init__(self, port=6667):
2009-08-31 16:27:57 -06:00
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
self.bind(('', port))
2009-09-25 13:27:37 -06:00
self.store = points.Storage()
2009-09-01 09:34:15 -06:00
self.acked = set()
2009-08-31 16:27:57 -06:00
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):
2009-08-20 12:51:47 -06:00
now = int(time.time())
2009-09-01 09:34:15 -06:00
dgram, peer = self.socket.recvfrom(4096)
2009-08-20 12:51:47 -06:00
try:
2009-09-01 09:34:15 -06:00
id, when, cat, team, score = points.decode_request(dgram)
2009-08-20 12:51:47 -06:00
except ValueError as e:
2009-09-01 09:34:15 -06:00
return self.respond(peer, now, str(e))
team = team or house
2009-08-20 12:51:47 -06:00
# Replays can happen legitimately.
if not ((peer, id) in self.acked):
2009-08-20 16:20:44 -06:00
if not (now - 2 < when <= now):
2009-09-01 09:34:15 -06:00
return self.respond(peer, id, 'Your clock is off')
self.store.add((when, cat, team, score))
self.acked.add((peer, id))
2009-08-20 12:51:47 -06:00
2009-09-01 09:34:15 -06:00
self.respond(peer, id, 'OK')
2009-08-31 16:27:57 -06:00
2009-09-01 09:34:15 -06:00
def respond(self, peer, id, txt):
resp = points.encode_response(id, txt)
2009-08-31 16:27:57 -06:00
self.outq.append((resp, peer))
2009-08-20 12:51:47 -06:00
2009-09-01 09:34:15 -06:00
def start():
return MyHandler()
2009-08-20 12:51:47 -06:00
if __name__ == "__main__":
2009-09-01 09:34:15 -06:00
h = start()
2009-08-31 16:27:57 -06:00
asyncore.loop()