/
ClientConnection.java
304 lines (287 loc) · 13.9 KB
/
ClientConnection.java
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package com.denizenscript.depenizen.common.socket.server;
import com.denizenscript.depenizen.common.Depenizen;
import com.denizenscript.depenizen.common.socket.DataDeserializer;
import com.denizenscript.depenizen.common.socket.DataSerializer;
import com.denizenscript.depenizen.common.socket.Packet;
import com.denizenscript.depenizen.common.socket.server.packet.*;
import com.denizenscript.depenizen.common.util.Utilities;
import javax.crypto.BadPaddingException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ClientConnection implements Runnable {
private int clientId;
private String clientName;
private boolean bungeeScriptCompatible;
private SocketServer server;
private Socket client;
private Thread listenThread;
private DataOutputStream output;
private DataInputStream input;
private Set<String> eventSubscriptions;
private boolean isConnected;
public ClientConnection(int clientId, SocketServer server, Socket client) {
this.clientId = clientId;
this.server = server;
this.client = client;
this.eventSubscriptions = new HashSet<String>();
}
public void start() throws IOException {
if (!isConnected) {
output = new DataOutputStream(client.getOutputStream());
input = new DataInputStream(client.getInputStream());
listenThread = new Thread(this);
listenThread.start();
}
}
public void send(Packet packet) throws GeneralSecurityException, IOException {
DataSerializer data = new DataSerializer();
packet.serialize(data);
byte[] encryptedData = server.getEncryption().encrypt(data.toByteArray());
output.writeInt(encryptedData.length);
output.write(encryptedData);
output.flush();
}
public void trySend(Packet packet) {
try {
send(packet);
}
catch (IOException e) {
server.removeClient(clientId, "Client socket closed");
}
catch (Exception e) {
server.removeClient(clientId, "Failed to send data due to an exception");
Depenizen.getImplementation().debugException(e);
}
}
public void stop() {
if (isConnected) {
isConnected = false;
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
if (client != null) {
client.close();
}
}
catch (IOException e) {
Depenizen.getImplementation().debugException(e);
}
for (String event : eventSubscriptions) {
server.handleEventSubscription(this, event, false);
}
eventSubscriptions.clear();
if (listenThread != null) {
listenThread.interrupt();
listenThread = null;
}
}
}
public int getClientId() {
return clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public boolean isRegistered() {
return this.clientName != null;
}
public void setBungeeScriptCompatible(boolean bungeeScriptCompatible) {
this.bungeeScriptCompatible = bungeeScriptCompatible;
}
public boolean isBungeeScriptCompatible() {
return bungeeScriptCompatible;
}
private int lastPingBit;
@Override
public void run() {
if (client != null && client.isConnected()) {
isConnected = true;
byte[] buffer;
try {
output.write(server.getEncryption().getIV());
output.flush();
connectionLoop:
while (isConnected) {
long timePassed;
boolean pinged = false;
long start = System.currentTimeMillis();
int receivedEncryptedLength;
while ((receivedEncryptedLength = input.readInt()) == 0) {
if (!isConnected) {
break connectionLoop;
}
timePassed = System.currentTimeMillis() - start;
if (timePassed > 30 * 1000 && !pinged) {
lastPingBit = Utilities.getRandomUnsignedByte();
send(new ServerPacketOutPing(lastPingBit));
pinged = true;
}
if (timePassed > 60 * 1000) {
server.removeClient(clientId, "Ping timed out!");
break connectionLoop;
}
Thread.sleep(50);
}
if (receivedEncryptedLength < 0) {
server.removeClient(clientId, "Connection failed");
break;
}
if (receivedEncryptedLength > 1024 * 1024) {
server.removeClient(clientId, "Incoming data > 1MB. Was it encrypted incorrectly?");
break;
}
buffer = new byte[receivedEncryptedLength];
input.read(buffer);
byte[] encryptedBytes = new byte[receivedEncryptedLength];
System.arraycopy(buffer, 0, encryptedBytes, 0, encryptedBytes.length);
byte[] decryptedBytes = server.getEncryption().decrypt(encryptedBytes);
DataDeserializer data = new DataDeserializer(decryptedBytes);
int packetId = data.readUnsignedByte();
Packet.ServerBound packetType = Packet.ServerBound.getById(packetId);
if (packetType == null) {
server.removeClient(clientId, "Received invalid packet from client: " + packetId);
break;
}
if (!isRegistered() && packetType != Packet.ServerBound.REGISTER) {
server.removeClient(clientId, "Received packet before registration: " + packetType.name());
break;
}
switch (packetType) {
case REGISTER:
if (isRegistered()) {
server.removeClient(clientId, "Received a second registration packet");
break connectionLoop;
}
ServerPacketInRegister register = new ServerPacketInRegister();
register.deserialize(data);
String name = register.getName();
if (!server.registerClient(clientId, name, register.isBungeeScriptCompatible())) {
break connectionLoop;
}
break;
case PING:
ServerPacketInPing ping = new ServerPacketInPing();
ping.deserialize(data);
send(new ServerPacketOutPong(ping.getBit()));
break;
case PONG:
ServerPacketInPong pong = new ServerPacketInPong();
pong.deserialize(data);
if (pong.getBit() != lastPingBit) {
server.removeClient(clientId, "Invalid ping bit: Expected " + lastPingBit + ", got " + pong.getBit());
break connectionLoop;
}
break;
case SCRIPT:
ServerPacketInScript script = new ServerPacketInScript();
script.deserialize(data);
ServerPacketOutScript scriptOut = new ServerPacketOutScript(script.getScriptData());
Map<String, ClientConnection> scriptClients = server.getRegisteredClients();
for (String destination : script.getDestinations()) {
destination = destination.toLowerCase();
if (scriptClients.containsKey(destination)) {
ClientConnection destClient = scriptClients.get(destination);
if (destClient.isBungeeScriptCompatible()) {
destClient.trySend(scriptOut);
}
}
}
break;
case RUN_SCRIPT:
ServerPacketInRunScript runScript = new ServerPacketInRunScript();
runScript.deserialize(data);
ServerPacketOutRunScript runScriptOut = new ServerPacketOutRunScript(runScript.getScriptData());
Map<String, ClientConnection> runScriptClients = server.getRegisteredClients();
for (String destination : runScript.getDestinations()) {
destination = destination.toLowerCase();
if (runScriptClients.containsKey(destination)) {
runScriptClients.get(destination).trySend(runScriptOut);
}
}
break;
case TAG:
ServerPacketInTag tag = new ServerPacketInTag();
tag.deserialize(data);
Map<String, ClientConnection> tagClients = server.getRegisteredClients();
String tagDestination = tag.getDestination().toLowerCase();
if (tagClients.containsKey(tagDestination)) {
ServerPacketOutTag tagOut = new ServerPacketOutTag(clientName, tag.getTagData());
tagClients.get(tagDestination).send(tagOut);
}
break;
case PARSED_TAG:
ServerPacketInParsedTag parsedTag = new ServerPacketInParsedTag();
parsedTag.deserialize(data);
Map<String, ClientConnection> parsedTagClients = server.getRegisteredClients();
String parsedTagDestination = parsedTag.getDestination().toLowerCase();
if (parsedTagClients.containsKey(parsedTagDestination)) {
ServerPacketOutParsedTag parsedTagOut = new ServerPacketOutParsedTag(parsedTag.getResultData());
parsedTagClients.get(parsedTagDestination).send(parsedTagOut);
}
break;
case EVENT_SUBSCRIPTION:
ServerPacketInEventSubscription eventSubscription = new ServerPacketInEventSubscription();
eventSubscription.deserialize(data);
String event = eventSubscription.getEvent();
boolean subscribed = eventSubscription.isSubscribed();
if (subscribed) {
eventSubscriptions.add(event);
}
else {
eventSubscriptions.remove(event);
}
server.handleEventSubscription(this, event, subscribed);
break;
case EVENT_RESPONSE:
ServerPacketInEventResponse eventResponse = new ServerPacketInEventResponse();
eventResponse.deserialize(data);
server.handleEventResponse(this, eventResponse.getId(), eventResponse.getResponse());
break;
case SEND_PLAYER:
ServerPacketInSendPlayer sendPlayer = new ServerPacketInSendPlayer();
sendPlayer.deserialize(data);
server.handleSendPlayer(this, sendPlayer.getPlayer(), sendPlayer.getDestination());
break;
case EXECUTE:
ServerPacketInExecute execute = new ServerPacketInExecute();
execute.deserialize(data);
server.handleExecute(this, execute.getCommand());
break;
case SET_PRIORITY:
ServerPacketInSetPriority setpriority = new ServerPacketInSetPriority();
setpriority.deserialize(data);
server.handleSetPriority(this, setpriority.getPriorityList());
break;
}
}
}
catch (BadPaddingException e) {
server.removeClient(clientId, "Password is incorrect");
}
catch (IOException e) {
server.removeClient(clientId, "Client socket closed");
}
catch (InterruptedException e) {
// Assume this is intentional
}
catch (Exception e) {
server.removeClient(clientId, "Error receiving data from client: " + e.getMessage());
Depenizen.getImplementation().debugException(e);
}
}
listenThread = null;
}
}