/
SubDataClient.java
580 lines (522 loc) · 26.3 KB
/
SubDataClient.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
package net.ME1312.SubData.Client;
import net.ME1312.Galaxi.Library.Callback.Callback;
import net.ME1312.Galaxi.Library.Callback.ReturnCallback;
import net.ME1312.Galaxi.Library.Container.Container;
import net.ME1312.Galaxi.Library.Container.PrimitiveContainer;
import net.ME1312.Galaxi.Library.Map.ObjectMap;
import net.ME1312.Galaxi.Library.Container.NamedContainer;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.SubData.Client.Encryption.NEH;
import net.ME1312.SubData.Client.Library.*;
import net.ME1312.SubData.Client.Library.Exception.*;
import net.ME1312.SubData.Client.Library.PingResponse;
import net.ME1312.SubData.Client.Protocol.*;
import net.ME1312.SubData.Client.Protocol.Initial.InitPacketDeclaration;
import net.ME1312.SubData.Client.Protocol.Initial.InitialPacket;
import net.ME1312.SubData.Client.Protocol.Initial.InitialProtocol;
import net.ME1312.SubData.Client.Protocol.Internal.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import java.util.logging.Logger;
import static net.ME1312.SubData.Client.Library.ConnectionState.*;
import static net.ME1312.SubData.Client.Library.DisconnectReason.*;
/**
* SubData Client Class
*/
public class SubDataClient extends DataClient implements SubDataSender {
private Socket socket;
private LinkedList<PacketOut> queue;
private HashMap<ConnectionState, LinkedList<PacketOut>> statequeue;
private BufferedInputStream in;
private OutputStreamL1 out;
private Container<Long> bs;
private SubDataProtocol protocol;
private Cipher cipher = NEH.get();
private int cipherlevel = 0;
private ObjectMap<?> login;
private ConnectionState state;
private DisconnectReason isdcr;
private Callback<Runnable> scheduler;
private Object[] constructor;
private SubDataClient next;
private Logger log;
SubDataClient(SubDataProtocol protocol, Callback<Runnable> scheduler, Logger log, InetAddress address, int port, ObjectMap<?> login) throws IOException {
if (Util.isNull(address, port)) throw new NullPointerException();
this.protocol = protocol;
this.bs = protocol.bs;
this.login = login;
this.scheduler = scheduler;
this.log = log;
this.state = PRE_INITIALIZATION;
this.isdcr = PROTOCOL_MISMATCH;
this.socket = new Socket(address, port);
this.in = new BufferedInputStream(socket.getInputStream(), (bs.get() > Integer.MAX_VALUE) ? Integer.MAX_VALUE : bs.get().intValue());
this.out = new OutputStreamL1(log, socket.getOutputStream(), bs.get());
this.queue = null;
this.statequeue = new HashMap<>();
this.constructor = new Object[]{
scheduler,
log,
address,
port,
login
};
log.info("Connected to " + socket.getRemoteSocketAddress());
read();
}
private void read(SubDataSender sender, PrimitiveContainer<Boolean> reset, InputStream stream) {
try {
BufferedInputStream data = new BufferedInputStream(stream, (bs.get() > Integer.MAX_VALUE) ? Integer.MAX_VALUE : bs.get().intValue());
ByteArrayOutputStream pending = new ByteArrayOutputStream();
int id = -1, version = -1;
int b, position = 0;
while (position < 4 && (b = data.read()) != -1) {
position++;
pending.write(b);
switch (position) {
case 2:
id = (int) UnsignedDataHandler.fromUnsigned(pending.toByteArray());
pending.reset();
break;
case 4:
version = (int) UnsignedDataHandler.fromUnsigned(pending.toByteArray());
pending.reset();
break;
}
}
// Step 4 // Create a detached data forwarding InputStream
if (state != CLOSED && id >= 0 && version >= 0) {
PrimitiveContainer<Boolean> open = new PrimitiveContainer<>(true);
InputStream forward = new InputStream() {
@Override
public int read() throws IOException {
if (open.value) {
int b = data.read();
if (b < 0) close();
return b;
} else return -1;
}
@Override
public void close() throws IOException {
open.value = false;
while (data.read() != -1);
}
};
if (state == PRE_INITIALIZATION && id != 0x0000) {
DebugUtil.logException(new IllegalStateException(getAddress().toString() + ": Only InitPacketDeclaration (0x0000) may be received during the PRE_INITIALIZATION stage: [" + DebugUtil.toHex(0xFFFF, id) + ", " + DebugUtil.toHex(0xFFFF, version) + "]"), log);
close(PROTOCOL_MISMATCH);
} else if (state == CLOSING && id != 0xFFFE) {
forward.close(); // Suppress other packets during the CLOSING stage
} else {
HashMap<Integer, PacketIn> pIn = (state.asInt() >= POST_INITIALIZATION.asInt())?protocol.pIn:Util.reflect(InitialProtocol.class.getDeclaredField("pIn"), null);
if (!pIn.keySet().contains(id)) throw new IllegalPacketException(getAddress().toString() + ": Could not find handler for packet: [" + DebugUtil.toHex(0xFFFF, id) + ", " + DebugUtil.toHex(0xFFFF, version) + "]");
PacketIn packet = pIn.get(id);
if (sender instanceof ForwardedDataSender && !(packet instanceof Forwardable)) throw new IllegalSenderException(getAddress().toString() + ": The handler does not support forwarded packets: [" + DebugUtil.toHex(0xFFFF, id) + ", " + DebugUtil.toHex(0xFFFF, version) + "]");
if (sender instanceof SubDataClient && packet instanceof ForwardOnly) throw new IllegalSenderException(getAddress().toString() + ": The handler does not support non-forwarded packets: [" + DebugUtil.toHex(0xFFFF, id) + ", " + DebugUtil.toHex(0xFFFF, version) + "]");
if (!packet.isCompatible(version)) throw new IllegalPacketException(getAddress().toString() + ": The handler does not support this packet version (" + DebugUtil.toHex(0xFFFF, packet.version()) + "): [" + DebugUtil.toHex(0xFFFF, id) + ", " + DebugUtil.toHex(0xFFFF, version) + "]");
// Step 5 // Invoke the Packet
if (state == PRE_INITIALIZATION && !(packet instanceof InitPacketDeclaration)) {
DebugUtil.logException(new IllegalStateException(getAddress().toString() + ": Only " + InitPacketDeclaration.class.getCanonicalName() + " may be received during the PRE_INITIALIZATION stage: " + packet.getClass().getCanonicalName()), log);
close(PROTOCOL_MISMATCH);
} else if (state == CLOSING && !(packet instanceof PacketDisconnectUnderstood)) {
forward.close(); // Suppress other packets during the CLOSING stage
} else {
scheduler.run(() -> {
try {
packet.receive(sender);
if (packet instanceof PacketStreamIn) {
((PacketStreamIn) packet).receive(sender, forward);
} else forward.close();
} catch (Throwable e) {
DebugUtil.logException(new InvocationTargetException(e, getAddress().toString() + ": Exception while running packet handler"), log);
Util.isException(forward::close);
if (state.asInt() <= INITIALIZATION.asInt())
Util.isException(() -> close(PROTOCOL_MISMATCH)); // Issues during the init stages are signs of a PROTOCOL_MISMATCH
}
});
if (sender == this) while (open.value) Thread.sleep(125);
}
}
}
} catch (Exception e) {
if (!reset.value) try {
if (!(e instanceof SocketException && !Boolean.getBoolean("subdata.debug"))) {
DebugUtil.logException(e, log);
} if (!(e instanceof SocketException)) {
close(UNHANDLED_EXCEPTION);
} else close(CONNECTION_INTERRUPTED);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
void read() {
if (!socket.isClosed()) new Thread(() -> {
PrimitiveContainer<Boolean> reset = new PrimitiveContainer<>(false);
try {
// Step 1 // Parse Escapes in the Encrypted Data
InputStream raw = new InputStreamL1(in, () -> {
if (state != PRE_INITIALIZATION) reset.value = true;
}, () -> {
if (!socket.isClosed()) {
SubDataClient.this.read();
} else Util.isException(() -> close(CONNECTION_INTERRUPTED));
});
PipedInputStream data = new PipedInputStream(1024);
PipedOutputStream forward = new PipedOutputStream(data);
// Step 3 // Parse the SubData Packet Formatting
new Thread(() -> read(this, reset, data), "SubDataClient::Packet_Listener(" + socket.getLocalSocketAddress().toString() + ')').start();
// Step 2 // Decrypt the Data
cipher.decrypt(this, raw, forward);
forward.close();
} catch (Exception e) {
if (!reset.value) try {
if (!(e instanceof SocketException && !Boolean.getBoolean("subdata.debug"))) {
DebugUtil.logException(e, log);
} if (!(e instanceof SocketException)) {
if (e instanceof EncryptionException)
close(ENCRYPTION_MISMATCH); // Classes that extend EncryptionException being thrown signify an ENCRYPTION_MISMATCH
else close(UNHANDLED_EXCEPTION);
} else close(CONNECTION_INTERRUPTED);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}, "SubDataClient::Data_Listener(" + socket.getLocalSocketAddress().toString() + ')').start();
}
private void write(SubDataSender sender, PacketOut next, OutputStream data) {
// Step 1 // Create a detached data forwarding OutputStream
try {
PrimitiveContainer<Boolean> open = new PrimitiveContainer<>(true);
OutputStream forward = new OutputStream() {
@Override
public void write(int b) throws IOException {
if (open.value) data.write(b);
}
@Override
public void close() throws IOException {
open.value = false;
Util.isException(data::close);
}
};
// Step 2 // Write the Packet Metadata
HashMap<Class<? extends PacketOut>, Integer> pOut = (state.asInt() >= POST_INITIALIZATION.asInt())?protocol.pOut:Util.reflect(InitialProtocol.class.getDeclaredField("pOut"), null);
if (!pOut.keySet().contains(next.getClass())) throw new IllegalMessageException(getAddress().toString() + ": Could not find ID for packet: " + next.getClass().getCanonicalName());
if (next.version() > 65535 || next.version() < 0) throw new IllegalMessageException(getAddress().toString() + ": Packet version is not in range (0x0000 to 0xFFFF): " + next.getClass().getCanonicalName());
data.write(UnsignedDataHandler.toUnsigned((long) pOut.get(next.getClass()), 2));
data.write(UnsignedDataHandler.toUnsigned((long) next.version(), 2));
data.flush();
// Step 3 // Invoke the Packet
scheduler.run(() -> {
try {
next.sending(sender);
if (next instanceof PacketStreamOut) {
((PacketStreamOut) next).send(sender, forward);
} else forward.close();
} catch (Throwable e) {
DebugUtil.logException(new InvocationTargetException(e, getAddress().toString() + ": Exception while running packet writer"), log);
Util.isException(forward::close);
}
});
if (sender == this) while (open.value) Thread.sleep(125);
} catch (Throwable e) {
DebugUtil.logException(e, log);
Util.isException(data::close);
}
}
void write() {
if (queue != null) new Thread(() -> {
if (queue.size() > 0) {
try {
PacketOut next = Util.getDespiteException(() -> queue.get(0), null);
Util.isException(() -> queue.remove(0));
if (next != null) {
if (!isClosed() || !(next instanceof PacketDisconnect || next instanceof PacketDisconnectUnderstood)) { // Disallows Disconnect packets during CLOSED
if (!isClosed() && (state != CLOSING || next instanceof PacketDisconnect || next instanceof PacketDisconnectUnderstood)) { // Allows only Disconnect packets during CLOSING
PipedOutputStream data = new PipedOutputStream();
PipedInputStream forward = new PipedInputStream(data, 1024);
new Thread(() -> write(this, next, data), "SubDataClient::Packet_Writer(" + socket.getLocalSocketAddress().toString() + ')').start();
// Step 5 // Add Escapes to the Encrypted Data
OutputStream raw = new OutputStream() {
boolean open = true;
@Override
public void write(int b) throws IOException {
if (open) {
try {
out.write(b);
} catch (Throwable e) {
close();
}
}
}
@Override
public void close() throws IOException {
if (open) {
open = false;
if (!socket.isClosed()) {
out.control('\u0017');
out.flush();
if (queue != null && queue.size() > 0) SubDataClient.this.write();
else queue = null;
}
}
}
};
// Step 4 // Encrypt the Data
cipher.encrypt(this, forward, raw);
raw.close();
forward.close();
} else {
// Re-queue any pending packets during the CLOSING state
sendPacket(next);
}
}
}
} catch (Throwable e) {
Util.isException(() -> queue.remove(0));
if (!(e instanceof SocketException)) { // Cut the write session short when socket issues occur
DebugUtil.logException(e, log);
if (queue != null && queue.size() > 0) SubDataClient.this.write();
else queue = null;
} else queue = null;
}
} else queue = null;
}, "SubDataClient::Data_Writer(" + socket.getLocalSocketAddress().toString() + ')').start();
}
/**
* Send a packet to Client
*
* @param packets Packets to send
* @see ForwardOnly Packets must <b><u>NOT</u></b> be tagged as Forward-Only
*/
public synchronized void sendPacket(PacketOut... packets) {
List<PacketOut> list = new ArrayList<>();
for (PacketOut packet : packets) {
if (Util.isNull(packet)) throw new NullPointerException();
if (packet instanceof ForwardOnly) throw new IllegalPacketException("Packet is Forward-Only");
if (isClosed() || (state == CLOSING && !(packet instanceof PacketDisconnect || packet instanceof PacketDisconnectUnderstood))) {
if (next == null) sendPacketLater(packet, CLOSED);
else next.sendPacket(packet);
} else if (state.asInt() < POST_INITIALIZATION.asInt() && !(packet instanceof InitialProtocol.Packet)) {
sendPacketLater(packet, (packet instanceof InitialPacket)?POST_INITIALIZATION:READY);
} else if (state == POST_INITIALIZATION && !(packet instanceof InitialPacket)) {
sendPacketLater(packet, READY);
} else {
list.add(packet);
}
}
if (list.size() > 0) {
boolean init = false;
if (queue == null) {
queue = new LinkedList<>();
init = true;
}
queue.addAll(list);
if (init) write();
}
}
private void sendPacketLater(PacketOut packet, ConnectionState state) {
LinkedList<PacketOut> prequeue = (this.statequeue.keySet().contains(state))?this.statequeue.get(state):new LinkedList<PacketOut>();
prequeue.add(packet);
this.statequeue.put(state, prequeue);
}
/**
* Forward a packet to another Client
*
* @param id Client ID
* @param packets Packets to send
* @see net.ME1312.SubData.Client.Protocol.Forwardable Packets must be tagged as Forwardable
*/
public void forwardPacket(UUID id, PacketOut... packets) {
List<PacketOut> list = new ArrayList<>();
for (PacketOut packet : packets) {
if (Util.isNull(id, packet)) throw new NullPointerException();
if (!(packet instanceof Forwardable)) throw new IllegalPacketException("Packet is not Forwardable");
sendPacket(new PacketForwardPacket(id, packet));
}
sendPacket(list.toArray(new PacketOut[0]));
}
public void sendMessage(MessageOut... messages) {
List<PacketOut> list = new ArrayList<>();
for (MessageOut message : messages) {
if (Util.isNull(message)) throw new NullPointerException();
if (message instanceof ForwardOnly) throw new IllegalMessageException("Message is Forward-Only");
list.add(new PacketSendMessage(message));
}
sendPacket(list.toArray(new PacketOut[0]));
}
public void forwardMessage(UUID id, MessageOut... messages) {
if (Util.isNull(id)) throw new NullPointerException();
List<PacketOut> list = new ArrayList<>();
for (MessageOut message : messages) {
if (Util.isNull(message)) throw new NullPointerException();
if (!(message instanceof Forwardable)) throw new IllegalMessageException("Message is not Forwardable");
list.add(new PacketForwardPacket(id, new PacketSendMessage(message)));
}
sendPacket(list.toArray(new PacketOut[0]));
}
@Override
public void getClient(UUID id, Callback<ObjectMap<String>> callback) {
if (Util.isNull(id, callback)) throw new NullPointerException();
StackTraceElement[] origin = new Exception().getStackTrace();
sendPacket(new PacketDownloadClientList(id, data -> {
ObjectMap<String> serialized = null;
if (data.contains(id.toString())) {
serialized = data.getMap(id.toString());
}
try {
callback.run(serialized);
} catch (Throwable e) {
Throwable ew = new InvocationTargetException(e);
ew.setStackTrace(origin);
ew.printStackTrace();
}
}));
}
@Override
public void getClients(Callback<Map<UUID, ObjectMap<String>>> callback) {
if (Util.isNull(callback)) throw new NullPointerException();
StackTraceElement[] origin = new Exception().getStackTrace();
sendPacket(new PacketDownloadClientList(data -> {
HashMap<UUID, ObjectMap<String>> serialized = new HashMap<UUID, ObjectMap<String>>();
for (String id : data.getKeys()) {
serialized.put(UUID.fromString(id), data.getMap(id));
}
try {
callback.run(serialized);
} catch (Throwable e) {
Throwable ew = new InvocationTargetException(e);
ew.setStackTrace(origin);
ew.printStackTrace();
}
}));
}
@Override
public void ping(Callback<PingResponse> response) {
if (Util.isNull(response)) throw new NullPointerException();
sendPacket(new PacketPing(response));
}
@Override
public void ping(UUID id, Callback<PingResponse> response) {
if (Util.isNull(response)) throw new NullPointerException();
forwardPacket(id, new PacketPing(response));
}
/**
* Get the underlying Client Socket
*
* @return Client Socket
*/
public Socket getSocket() {
return socket;
}
/**
* Get the Client that connects the Server to us
*
* @deprecated The Client connection to the Server is this
* @return This Client
*/
@Override
@Deprecated
public SubDataClient getConnection() {
return this;
}
public SubDataProtocol getProtocol() {
return protocol;
}
public InetSocketAddress getAddress() {
return new InetSocketAddress(socket.getInetAddress(), socket.getPort());
}
/**
* Get SubData's Block Size
*
* @return Block Size
*/
public long getBlockSize() {
return bs.get();
}
/**
* Set SubData's Block Size
*
* @param size Block Size (null for super)
*/
public void setBlockSize(Long size) {
if (size == null) {
bs = protocol.bs;
} else bs = new Container<>(size);
}
@SuppressWarnings("unchecked")
@Override
public SubDataClient openChannel() throws IOException {
return protocol.sub((Callback<Runnable>) constructor[0], (Logger) constructor[1], (InetAddress) constructor[2], (int) constructor[3], (ObjectMap<?>) constructor[4]);
}
/**
* Reconnect the data stream using another Client
*
* @param client Client
*/
public void reconnect(SubDataClient client) {
if (Util.isNull(client)) throw new NullPointerException();
if (client == this) throw new IllegalArgumentException("Cannot reconnect to 'this'");
if (state.asInt() < CLOSING.asInt() || next != null) throw new IllegalStateException("Cannot override existing data stream");
next = client;
if (statequeue.keySet().contains(CLOSED)) {
for (PacketOut packet : statequeue.get(CLOSED)) next.sendPacket(packet);
statequeue.remove(CLOSED);
}
}
public void close() throws IOException {
if (state.asInt() < CLOSING.asInt() && !socket.isClosed()) {
boolean result = true;
LinkedList<ReturnCallback<DataClient, Boolean>> events = new LinkedList<>(on.close);
for (ReturnCallback<DataClient, Boolean> next : events) try {
if (next != null) result = next.run(this) != Boolean.FALSE && result;
} catch (Throwable e) {
DebugUtil.logException(new InvocationTargetException(e, "Unhandled exception while running SubData Event"), log);
}
if (result) {
state = CLOSING;
if (!isClosed()) sendPacket(new PacketDisconnect());
Timer timeout = new Timer("SubDataClient::Disconnect_Timeout(" + socket.getLocalSocketAddress().toString() + ')');
timeout.schedule(new TimerTask() {
@Override
public void run() {
if (!socket.isClosed()) try {
close(CLOSE_REQUESTED);
} catch (IOException e) {
DebugUtil.logException(e, log);
}
}
}, 5000);
}
}
}
void close(DisconnectReason reason) throws IOException {
if (state != CLOSED && !socket.isClosed()) {
if (state == CLOSING && reason == CONNECTION_INTERRUPTED) reason = CLOSE_REQUESTED;
if (isdcr != null && reason == CONNECTION_INTERRUPTED) reason = isdcr;
state = CLOSED;
if (reason != CLOSE_REQUESTED) {
log.warning("Disconnected from " + socket.getRemoteSocketAddress() + ": " + reason);
} else log.info("Disconnected from " + socket.getRemoteSocketAddress());
socket.close();
cipher.retire(this);
final DisconnectReason freason = reason;
scheduler.run(() -> {
LinkedList<Callback<NamedContainer<DisconnectReason, DataClient>>> events = new LinkedList<>(on.closed);
for (Callback<NamedContainer<DisconnectReason, DataClient>> next : events) try {
if (next != null) next.run(new NamedContainer<>(freason, this));
} catch (Throwable e) {
DebugUtil.logException(new InvocationTargetException(e, "Unhandled exception while running SubData Event"), log);
}
});
}
}
public boolean isClosed() {
return socket.isClosed();
}
}