summaryrefslogtreecommitdiff
path: root/python_client.py
blob: 24c8a3e9702e838787f2e6b9c524b0b0915bc75c (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import socket, ssl, threading, struct

protocolVer = 1
sock = None
authed = False
sessionKey = b'\0'*16
nextID = 1
lastReceivedPacketID = 0
packetCache = []
packetLock = threading.Lock()

class Packet:
	def __init__(self, type, data):
		global nextID

		self.type = type
		self.data = data
		if (type & 0x8000) == 0:
			self.id = nextID
			nextID = nextID + 1

	def sendOverWire(self):
		header = struct.pack('<HHI', self.type, 0, len(self.data))
		if (self.type & 0x8000) == 0:
			extHeader = struct.pack('<II', self.id, lastReceivedPacketID)
		else:
			extHeader = b''

		sock.sendall(header)
		if extHeader:
			sock.sendall(extHeader)
		sock.sendall(self.data)


def clearCachedPackets(pid):
	for packet in packetCache[:]:
		if packet.id <= pid:
			packetCache.remove(packet)

def reader():
	global lastReceivedPacketID, authed, sessionKey
	readbuf = b''

	print('(Connected)')
	while True:
		data = sock.recv(1024)
		if not data:
			print('(Disconnected)')
			break

		readbuf += data

		pos = 0
		bufsize = len(readbuf)
		print('[bufsize: %d]' % bufsize)
		while True:
			if (pos + 8) > bufsize:
				break

			type, reserved, size = struct.unpack_from('<HHI', readbuf, pos)

			extHeaderSize = 8 if ((type & 0x8000) == 0) else 0
			if (pos + 8 + extHeaderSize + size) > bufsize:
				break

			pos += 8
			with packetLock:
				if ((type & 0x8000) == 0):
					pid, lastReceivedByServer = struct.unpack_from('<II', readbuf, pos)
					pos += 8

					lastReceivedPacketID = pid
					clearCachedPackets(lastReceivedByServer)

				packetdata = readbuf[pos:pos+size]
				print('0x%x : %d bytes : %s' % (type, size, packetdata))

				if type == 0x8001:
					sessionKey = packetdata
					authed = True
				elif type == 0x8003:
					authed = True
					pid = struct.unpack('<I', packetdata)[0]
					clearCachedPackets(pid)
					try:
						for packet in packetCache:
							packet.sendOverWire()
					except:
						pass
				elif type == 1:
					strlen = struct.unpack_from('<I', packetdata, 0)[0]
					print(packetdata[4:4+strlen].decode('utf-8'))

			pos += size

		print('[processed %d bytes]' % pos)
		readbuf = readbuf[pos:]

def writePacket(type, data, allowUnauthed=False):
	packet = Packet(type, data)
	if (type & 0x8000) == 0:
		packetCache.append(packet)
	try:
		if authed or allowUnauthed:
			packet.sendOverWire()
	except:
		pass



while True:
	bit = input()
	bits = bit.split(' ', 1)
	cmd = bits[0]

	with packetLock:
		print('{')
		if cmd == 'connect':
			try:
				basesock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
				basesock.connect(('localhost', 5454))
				#sock = ssl.wrap_socket(basesock)
				sock = basesock
				thd = threading.Thread(None, reader)
				thd.start()
			except Exception as e:
				print(e)
		elif cmd == 'disconnect':
			sock.shutdown(socket.SHUT_RDWR)
			sock.close()
			sock = None
			authed = False
		elif cmd == 'login':
			writePacket(0x8001, struct.pack('<II 16s', protocolVer, lastReceivedPacketID, sessionKey), True)
		elif cmd == 'cmd':
			data = bits[1].encode('utf-8')
			writePacket(1, struct.pack('<I', len(data)) + data)
		elif cmd == 'quit':
			break
		print('}')