-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturnip.py
executable file
·82 lines (65 loc) · 2.23 KB
/
turnip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
import asyncio
import enum
import os
import socket
import struct
import time
# The address and port to run on.
BIND = os.getenv("BIND", "0.0.0.0:19555")
# Expire known servers after 60 seconds without a ping by default.
TIMEOUT = int(os.getenv("TIMEOUT", 60))
class Command(enum.IntEnum):
PING = 1
REQUEST = 2
PUNCH = 3
def packet(self, addr: tuple[str, int]) -> bytes:
return (
bytes([self.value])
+ socket.inet_aton(addr[0])
+ struct.pack("!H", addr[1])
)
def unpack_address(data: bytes) -> tuple[str, int] | None:
if len(data) != 6:
return None
return (socket.inet_ntoa(data[:4]), struct.unpack("!H", data[4:])[0])
class TurnipProtocol(asyncio.DatagramProtocol):
def __init__(self):
self.known = {}
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data: bytes, addr: tuple[str, int]):
if len(data) != 7:
return
cmd = Command(data[0])
connaddr = unpack_address(data[1:])
match cmd:
case Command.PING:
if addr not in self.known:
print("Registering {}".format(addr))
self.known[addr] = time.time()
case Command.REQUEST:
if connaddr in self.known:
print("Requesting {} to open {}".format(connaddr, addr))
self.transport.sendto(Command.PUNCH.packet(addr), connaddr)
else:
print("Unknown server: {}".format(connaddr))
def expire(self, timeout):
for addr in list(self.known.keys()):
if (time.time() - self.known[addr]) >= timeout:
print("Expiring {}".format(addr))
del self.known[addr]
async def main():
loop = asyncio.get_running_loop()
bind_host, bind_port = BIND.split(":")
transport, protocol = await loop.create_datagram_endpoint(
lambda: TurnipProtocol(), local_addr=(bind_host, int(bind_port))
)
try:
while True:
await asyncio.sleep(5.0)
protocol.expire(TIMEOUT)
finally:
transport.close()
if __name__ == "__main__":
asyncio.run(main())