-
Notifications
You must be signed in to change notification settings - Fork 43
/
RakSessionCodec.java
857 lines (723 loc) · 31 KB
/
RakSessionCodec.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/*
* Copyright 2022 CloudburstMC
*
* CloudburstMC licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.cloudburstmc.netty.handler.codec.raknet.common;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import io.netty.util.concurrent.ScheduledFuture;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.cloudburstmc.netty.channel.raknet.*;
import org.cloudburstmc.netty.channel.raknet.config.RakChannelOption;
import org.cloudburstmc.netty.channel.raknet.config.RakChannelMetrics;
import org.cloudburstmc.netty.channel.raknet.packet.EncapsulatedPacket;
import org.cloudburstmc.netty.channel.raknet.packet.RakDatagramPacket;
import org.cloudburstmc.netty.channel.raknet.packet.RakMessage;
import org.cloudburstmc.netty.util.*;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import static org.cloudburstmc.netty.channel.raknet.RakConstants.*;
public class RakSessionCodec extends ChannelDuplexHandler {
private static final InternalLogger log = InternalLoggerFactory.getInstance(RakSessionCodec.class);
public static final String NAME = "rak-session-codec";
private final RakChannel channel;
private ScheduledFuture<?> tickFuture;
private volatile RakState state;
private volatile long lastTouched = System.currentTimeMillis();
private volatile long lastFlush;
// Reliability, Ordering, Sequencing and datagram indexes
private RakSlidingWindow slidingWindow;
private int splitIndex;
private int datagramReadIndex;
private int datagramWriteIndex;
private int reliabilityReadIndex;
private int reliabilityWriteIndex;
private int[] orderReadIndex;
private int[] orderWriteIndex;
private RoundRobinArray<SplitPacketHelper> splitPackets;
private BitQueue reliableDatagramQueue;
private FastBinaryMinHeap<EncapsulatedPacket> outgoingPackets;
private long[] outgoingPacketNextWeights;
private FastBinaryMinHeap<EncapsulatedPacket>[] orderingHeaps;
private long currentPingTime = -1;
private long lastPingTime = -1;
private long lastPongTime = -1;
private IntObjectMap<RakDatagramPacket> sentDatagrams;
private Queue<IntRange> incomingAcks;
private Queue<IntRange> incomingNaks;
private Queue<IntRange> outgoingAcks;
private Queue<IntRange> outgoingNaks;
private long lastMinWeight;
public RakSessionCodec(RakChannel channel) {
this.channel = channel;
this.setState(RakState.UNCONNECTED);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.setState(RakState.CONNECTED);
int mtu = this.getMtu();
this.slidingWindow = new RakSlidingWindow(mtu);
this.outgoingPacketNextWeights = new long[4];
this.initHeapWeights();
int maxChannels = this.channel.config().getOption(RakChannelOption.RAK_ORDERING_CHANNELS);
this.orderReadIndex = new int[maxChannels];
this.orderWriteIndex = new int[maxChannels];
// Noinspection unchecked
this.orderingHeaps = new FastBinaryMinHeap[maxChannels];
for (int i = 0; i < maxChannels; i++) {
orderingHeaps[i] = new FastBinaryMinHeap<>(64);
}
this.outgoingPackets = new FastBinaryMinHeap<>(8);
this.sentDatagrams = new IntObjectHashMap<>();
this.incomingAcks = new ArrayDeque<>();
this.incomingNaks = new ArrayDeque<>();
this.outgoingAcks = new ArrayDeque<>();
this.outgoingNaks = new ArrayDeque<>();
this.reliableDatagramQueue = new BitQueue(512);
this.splitPackets = new RoundRobinArray<>(256);
// After session is fully initialized, start ticking.
boolean autoFlush = this.channel.config().isAutoFlush();
// Make sure there happens at least one flush per 10ms to respect standard RakNet behavior
int flushInterval = autoFlush ? this.channel.config().getFlushInterval() : 10;
this.tickFuture = ctx.channel().eventLoop().scheduleAtFixedRate(this::tryTick, 0, flushInterval, TimeUnit.MILLISECONDS);
ctx.fireChannelActive(); // fire channel active on rakPipeline()
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
if (this.state == RakState.DISCONNECTED && this.tickFuture == null) {
// Already deinitialized
return;
}
this.setState(RakState.DISCONNECTED);
this.tickFuture.cancel(false);
this.tickFuture = null;
// Perform resource clean up.
for (SplitPacketHelper helper : this.splitPackets) {
if (helper != null) {
helper.release();
}
}
this.splitPackets = null;
for (RakDatagramPacket packet : this.sentDatagrams.values()) {
packet.release();
}
this.sentDatagrams = null;
FastBinaryMinHeap<EncapsulatedPacket>[] orderingHeaps = this.orderingHeaps;
this.orderingHeaps = null;
if (orderingHeaps != null) {
for (FastBinaryMinHeap<EncapsulatedPacket> orderingHeap : orderingHeaps) {
EncapsulatedPacket packet;
while ((packet = orderingHeap.poll()) != null) {
packet.release();
}
orderingHeap.release();
}
}
FastBinaryMinHeap<EncapsulatedPacket> outgoingPackets = this.outgoingPackets;
this.outgoingPackets = null;
if (outgoingPackets != null) {
EncapsulatedPacket packet;
while ((packet = outgoingPackets.poll()) != null) {
packet.release();
}
outgoingPackets.release();
}
if (log.isTraceEnabled()) {
log.trace("RakNet Session ({} => {}) closed!", this.channel.localAddress(), this.getRemoteAddress());
}
}
private void initHeapWeights() {
for (int priorityLevel = 0; priorityLevel < 4; priorityLevel++) {
this.outgoingPacketNextWeights[priorityLevel] = (1 << priorityLevel) * priorityLevel + priorityLevel;
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (msg instanceof ByteBuf) {
msg = new RakMessage((ByteBuf) msg);
} else if (!(msg instanceof RakMessage)) {
throw new IllegalArgumentException("Message must be a ByteBuf or RakMessage");
}
try {
this.send(ctx, (RakMessage) msg);
promise.setSuccess(null);
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void flush(ChannelHandlerContext ctx) throws Exception {
if (!this.channel.config().isAutoFlush()) {
this.internalFlush(ctx);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (!(msg instanceof RakDatagramPacket)) {
// We don't want to let anything through that isn't RakNet related.
return;
}
RakDatagramPacket packet = (RakDatagramPacket) msg;
if (this.state == RakState.UNCONNECTED) {
log.debug("{} received message from inactive channel: {}", this.getRemoteAddress(), packet);
} else {
this.handleDatagram(ctx, packet);
}
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
this.disconnect0(RakDisconnectReason.DISCONNECTED).addListener(future -> {
if (future.cause() == null) {
promise.trySuccess();
} else {
promise.tryFailure(future.cause());
}
});
}
private void send(ChannelHandlerContext ctx, RakMessage message) {
if (this.state == RakState.UNCONNECTED) {
throw new IllegalStateException("Can not send RakMessage to inactive channel");
}
if (message.content().getUnsignedByte(message.content().readerIndex()) == 0xc0) {
throw new IllegalArgumentException();
}
EncapsulatedPacket[] packets = this.createEncapsulated(message);
if (message.priority() == RakPriority.IMMEDIATE) {
this.sendImmediate(ctx, packets);
return;
}
long weight = this.getNextWeight(message.priority());
if (packets.length == 1) {
this.outgoingPackets.insert(weight, packets[0]);
} else {
this.outgoingPackets.insertSeries(weight, packets);
}
}
private void handleDatagram(ChannelHandlerContext ctx, RakDatagramPacket packet) {
this.touch();
RakChannelMetrics metrics = this.getMetrics();
if (metrics != null) {
metrics.rakDatagramsIn(1);
}
this.slidingWindow.onPacketReceived(packet.getSendTime());
int prevSequenceIndex = this.datagramReadIndex;
if (prevSequenceIndex <= packet.getSequenceIndex()) {
this.datagramReadIndex = packet.getSequenceIndex() + 1;
}
int missedDatagrams = packet.getSequenceIndex() - prevSequenceIndex;
if (missedDatagrams > 0) {
this.outgoingNaks.offer(new IntRange(packet.getSequenceIndex() - missedDatagrams, packet.getSequenceIndex() - 1));
}
this.outgoingAcks.offer(new IntRange(packet.getSequenceIndex(), packet.getSequenceIndex()));
for (final EncapsulatedPacket encapsulated : packet.getPackets()) {
if (encapsulated.getReliability().isReliable()) {
int missed = encapsulated.getReliabilityIndex() - this.reliabilityReadIndex;
if (missed > 0) {
if (missed < this.reliableDatagramQueue.size()) {
if (this.reliableDatagramQueue.get(missed)) {
this.reliableDatagramQueue.set(missed, false);
} else {
// Duplicate packet
continue;
}
} else {
int count = (missed - this.reliableDatagramQueue.size());
for (int i = 0; i < count; i++) {
this.reliableDatagramQueue.add(true);
}
this.reliableDatagramQueue.add(false);
}
} else if (missed == 0) {
this.reliabilityReadIndex++;
if (!this.reliableDatagramQueue.isEmpty()) {
this.reliableDatagramQueue.poll();
}
} else {
// Duplicate packet
continue;
}
while (!this.reliableDatagramQueue.isEmpty() && !this.reliableDatagramQueue.peek()) {
this.reliableDatagramQueue.poll();
++this.reliabilityReadIndex;
}
}
if (encapsulated.isSplit()) {
final EncapsulatedPacket reassembled = this.getReassembledPacket(encapsulated, ctx.alloc());
if (reassembled == null) {
// Not reassembled
continue;
}
try {
this.checkForOrdered(ctx, reassembled);
} finally {
reassembled.release();
}
} else {
this.checkForOrdered(ctx, encapsulated);
}
}
}
private void checkForOrdered(ChannelHandlerContext ctx, EncapsulatedPacket packet) {
if (packet.getReliability().isOrdered()) {
this.onOrderedReceived(ctx, packet);
} else {
ctx.fireChannelRead(packet.retain());
}
}
private void onOrderedReceived(ChannelHandlerContext ctx, EncapsulatedPacket packet) {
FastBinaryMinHeap<EncapsulatedPacket> binaryHeap = this.orderingHeaps[packet.getOrderingChannel()];
if (this.orderReadIndex[packet.getOrderingChannel()] < packet.getOrderingIndex()) {
// Not next in line so add to queue.
binaryHeap.insert(packet.getOrderingIndex(), packet.retain());
return;
} else if (this.orderReadIndex[packet.getOrderingChannel()] > packet.getOrderingIndex()) {
// We already have this
return;
}
this.orderReadIndex[packet.getOrderingChannel()]++;
// Can be handled
ctx.fireChannelRead(packet.retain());
EncapsulatedPacket queuedPacket;
while ((queuedPacket = binaryHeap.peek()) != null) {
if (queuedPacket.getOrderingIndex() == this.orderReadIndex[packet.getOrderingChannel()]) {
try {
// We got the expected packet
binaryHeap.remove();
this.orderReadIndex[packet.getOrderingChannel()]++;
ctx.fireChannelRead(queuedPacket.retain());
} finally {
queuedPacket.release();
}
} else {
// Found a gap. Wait till we start receive another ordered packet.
break;
}
}
}
private EncapsulatedPacket getReassembledPacket(EncapsulatedPacket splitPacket, ByteBufAllocator alloc) {
this.checkForClosed();
SplitPacketHelper helper = this.splitPackets.get(splitPacket.getPartId());
if (helper == null) {
this.splitPackets.set(splitPacket.getPartId(), helper = new SplitPacketHelper(splitPacket.getPartCount()));
}
// Try reassembling the packet.
EncapsulatedPacket result = helper.add(splitPacket, alloc);
if (result != null) {
// Packet reassembled. Remove the helper
this.splitPackets.remove(splitPacket.getPartId(), helper);
}
return result;
}
private void tryTick() {
try {
this.onTick();
} catch (Throwable t) {
log.error("[{}] Error while ticking RakSessionCodec state={} channelActive={}", this.getRemoteAddress(), this.state, this.channel.isActive(), t);
this.channel.close();
}
}
private void onTick() {
long curTime = System.currentTimeMillis();
if (this.state == RakState.UNCONNECTED) {
if (this.isTimedOut(curTime)) {
this.close(RakDisconnectReason.TIMED_OUT);
}
return;
}
if (this.isTimedOut(curTime)) {
this.disconnect(RakDisconnectReason.TIMED_OUT);
return;
}
ChannelHandlerContext ctx = ctx();
if (this.currentPingTime + 2000L < curTime) {
ByteBuf buffer = ctx.alloc().ioBuffer(9);
buffer.writeByte(ID_CONNECTED_PING);
buffer.writeLong(curTime);
this.currentPingTime = curTime;
this.write(ctx, new RakMessage(buffer, RakReliability.UNRELIABLE, RakPriority.IMMEDIATE), ctx.voidPromise());
}
this.internalFlush(ctx);
}
private void internalFlush(ChannelHandlerContext ctx) {
long curTime = System.currentTimeMillis();
if (this.lastFlush == curTime) {
return; // do not flush multiple times within one ms
}
this.lastFlush = curTime;
this.handleIncomingAcknowledge(ctx, curTime, this.incomingAcks, false);
this.handleIncomingAcknowledge(ctx, curTime, this.incomingNaks, true);
// Send our know outgoing acknowledge packets.
int mtuSize = this.getMtu();
int ackMtu = mtuSize - RAKNET_DATAGRAM_HEADER_SIZE;
int writtenAcks = 0;
int writtenNacks = 0;
// if (this.slidingWindow.shouldSendAcks(curTime)) {
while (!this.outgoingAcks.isEmpty()) {
ByteBuf buffer = ctx.alloc().ioBuffer(ackMtu);
buffer.writeByte(FLAG_VALID | FLAG_ACK);
writtenAcks += RakUtils.writeAckEntries(buffer, this.outgoingAcks, ackMtu - 1);
ctx.write(buffer);
this.slidingWindow.onSendAck();
}
// }
while (!this.outgoingNaks.isEmpty()) {
ByteBuf buffer = ctx.alloc().ioBuffer(ackMtu);
buffer.writeByte(FLAG_VALID | FLAG_NACK);
writtenNacks += RakUtils.writeAckEntries(buffer, this.outgoingNaks, ackMtu - 1);
ctx.write(buffer);
}
// Send packets that are stale first
int resendCount = this.sendStaleDatagrams(ctx, curTime);
// Now send usual packets
this.sendDatagrams(ctx, curTime, mtuSize);
// Finally flush channel
ctx.flush();
RakChannelMetrics metrics = this.getMetrics();
if (metrics != null) {
metrics.nackOut(writtenNacks);
metrics.ackOut(writtenAcks);
metrics.rakStaleDatagrams(resendCount);
}
}
private void handleIncomingAcknowledge(ChannelHandlerContext ctx, long curTime, Queue<IntRange> queue, boolean nack) {
if (queue.isEmpty()) {
return;
}
// if (nack) {
// this.slidingWindow.onNak();
// }
IntRange range;
while ((range = queue.poll()) != null) {
for (int i = range.start; i <= range.end; i++) {
RakDatagramPacket datagram = this.sentDatagrams.remove(i);
if (datagram != null) {
if (nack) {
this.onIncomingNack(ctx, datagram, curTime);
} else {
this.onIncomingAck(datagram, curTime);
}
}
}
}
}
private void onIncomingAck(RakDatagramPacket datagram, long curTime) {
try {
this.slidingWindow.onAck(curTime, datagram, this.datagramReadIndex);
} finally {
datagram.release();
}
}
private void onIncomingNack(ChannelHandlerContext ctx, RakDatagramPacket datagram, long curTime) {
if (log.isTraceEnabled()) {
log.trace("NAK'ed datagram {} from {}", datagram.getSequenceIndex(), this.getRemoteAddress());
}
this.slidingWindow.onNak(); // TODO: verify this
this.sendDatagram(ctx, datagram, curTime);
}
private int sendStaleDatagrams(ChannelHandlerContext ctx, long curTime) {
if (this.sentDatagrams.isEmpty()) {
return 0;
}
boolean hasResent = false;
int resendCount = 0;
int transmissionBandwidth = this.slidingWindow.getRetransmissionBandwidth();
for (RakDatagramPacket datagram : this.sentDatagrams.values()) {
if (datagram.getNextSend() <= curTime) {
int size = datagram.getSize();
if (transmissionBandwidth < size) {
break;
}
transmissionBandwidth -= size;
if (!hasResent) {
hasResent = true;
}
if (log.isTraceEnabled()) {
log.trace("Stale datagram {} from {}", datagram.getSequenceIndex(), this.getRemoteAddress());
}
resendCount++;
this.sendDatagram(ctx, datagram, curTime);
}
}
if (hasResent) {
this.slidingWindow.onResend(curTime);
}
return resendCount;
}
private void sendDatagrams(ChannelHandlerContext ctx, long curTime, int mtuSize) {
if (this.outgoingPackets.isEmpty()) {
return;
}
int transmissionBandwidth = this.slidingWindow.getTransmissionBandwidth();
RakDatagramPacket datagram = RakDatagramPacket.newInstance();
datagram.setSendTime(curTime);
EncapsulatedPacket packet;
while ((packet = this.outgoingPackets.peek()) != null) {
int size = packet.getSize();
if (transmissionBandwidth < size) {
break;
}
transmissionBandwidth -= size;
this.outgoingPackets.remove();
// Send full datagram
if (!datagram.tryAddPacket(packet, mtuSize)) {
this.sendDatagram(ctx, datagram, curTime);
datagram = RakDatagramPacket.newInstance();
datagram.setSendTime(curTime);
if (!datagram.tryAddPacket(packet, mtuSize)) {
throw new IllegalArgumentException("Packet too large to fit in MTU (size: " + packet.getSize() + ", MTU: " + mtuSize + ")");
}
}
}
if (!datagram.getPackets().isEmpty()) {
this.sendDatagram(ctx, datagram, curTime);
}
}
private void sendImmediate(ChannelHandlerContext ctx, EncapsulatedPacket[] packets) {
long curTime = System.currentTimeMillis();
for (EncapsulatedPacket packet : packets) {
RakDatagramPacket datagram = RakDatagramPacket.newInstance();
datagram.setSendTime(curTime);
if (!datagram.tryAddPacket(packet, this.getMtu())) {
throw new IllegalArgumentException("Packet too large to fit in MTU (size: " + packet.getSize() + ", MTU: " + this.getMtu() + ")");
}
this.sendDatagram(ctx, datagram, curTime);
}
ctx.flush();
}
private void sendDatagram(ChannelHandlerContext ctx, RakDatagramPacket datagram, long time) {
if (!this.channel.parent().eventLoop().inEventLoop()) {
// Make sure this runs on correct thread
log.error("Tried to send datagrams from wrong thread: {}", Thread.currentThread().getName(), new Throwable());
this.channel.parent().eventLoop().execute(() -> this.sendDatagram(ctx, datagram, time));
return;
}
if (datagram.getPackets().isEmpty()) {
throw new IllegalArgumentException("RakNetDatagram with no packets");
}
RakChannelMetrics metrics = this.getMetrics();
if (metrics != null) {
metrics.rakDatagramsOut(1);
}
int oldIndex = datagram.getSequenceIndex();
datagram.setSequenceIndex(this.datagramWriteIndex++);
for (EncapsulatedPacket packet : datagram.getPackets()) {
// Check if packet is reliable so it can be resent later if a NAK is received.
if (packet.getReliability().isReliable()) {
datagram.setNextSend(time + this.slidingWindow.getRtoForRetransmission());
if (oldIndex == -1) {
this.slidingWindow.onReliableSend(datagram);
} else {
this.sentDatagrams.remove(oldIndex, datagram);
}
this.sentDatagrams.put(datagram.getSequenceIndex(), datagram.retain()); // Keep for resending
break;
}
}
ctx.write(datagram);
}
private ChannelHandlerContext ctx() {
return this.channel.rakPipeline().context(RakSessionCodec.NAME);
}
private EncapsulatedPacket[] createEncapsulated(RakMessage rakMessage) {
int maxLength = this.getMtu() - MAXIMUM_ENCAPSULATED_HEADER_SIZE - RAKNET_DATAGRAM_HEADER_SIZE;
ByteBuf[] buffers;
int splitId = 0;
RakReliability reliability = rakMessage.reliability();
ByteBuf buffer = rakMessage.content();
int orderingChannel = rakMessage.channel();
if (buffer.readableBytes() > maxLength) {
// Packet requires splitting
// Adjust reliability
switch (reliability) {
case UNRELIABLE:
reliability = RakReliability.RELIABLE;
break;
case UNRELIABLE_SEQUENCED:
reliability = RakReliability.RELIABLE_SEQUENCED;
break;
case UNRELIABLE_WITH_ACK_RECEIPT:
reliability = RakReliability.RELIABLE_WITH_ACK_RECEIPT;
break;
}
int split = ((buffer.readableBytes() - 1) / maxLength) + 1;
buffer.retain(split);
buffers = new ByteBuf[split];
for (int i = 0; i < split; i++) {
buffers[i] = buffer.readSlice(Math.min(maxLength, buffer.readableBytes()));
}
if (buffer.isReadable()) {
throw new IllegalStateException("Buffer still has bytes to read!");
}
// Allocate split ID
splitId = this.splitIndex++;
} else {
buffers = new ByteBuf[]{buffer.readRetainedSlice(buffer.readableBytes())};
}
// Set meta
// TODO: sequencing
int orderingIndex = 0;
if (reliability.isOrdered()) {
orderingIndex = this.orderWriteIndex[orderingChannel]++;
}
// Now create the packets.
EncapsulatedPacket[] packets = new EncapsulatedPacket[buffers.length];
for (int i = 0, parts = buffers.length; i < parts; i++) {
EncapsulatedPacket packet = EncapsulatedPacket.newInstance();
packet.setBuffer(buffers[i]);
packet.setNeedsBAS(true);
packet.setOrderingChannel((short) orderingChannel);
packet.setOrderingIndex(orderingIndex);
// packet.setSequenceIndex(sequencingIndex);
packet.setReliability(reliability);
if (reliability.isReliable()) {
packet.setReliabilityIndex(this.reliabilityWriteIndex++);
}
if (parts > 1) {
packet.setSplit(true);
packet.setPartIndex(i);
packet.setPartCount(parts);
packet.setPartId(splitId);
}
packets[i] = packet;
}
return packets;
}
private long getNextWeight(RakPriority priority) {
int priorityLevel = priority.ordinal();
long next = this.outgoingPacketNextWeights[priorityLevel];
if (!this.outgoingPackets.isEmpty()) {
if (next >= this.lastMinWeight) {
next = this.lastMinWeight + (1L << priorityLevel) * priorityLevel + priorityLevel;
this.outgoingPacketNextWeights[priorityLevel] = next + (1L << priorityLevel) * (priorityLevel + 1) + priorityLevel;
}
} else {
this.initHeapWeights();
}
this.lastMinWeight = next - (1L << priorityLevel) * priorityLevel + priorityLevel;
return next;
}
public void disconnect() {
this.disconnect(RakDisconnectReason.DISCONNECTED);
}
public void disconnect(RakDisconnectReason reason) {
// Ensure we disconnect on the right thread
if (this.channel.parent().eventLoop().inEventLoop()) {
this.disconnect0(reason);
} else {
this.channel.parent().eventLoop().execute(() -> this.disconnect0(reason));
}
}
private ChannelPromise disconnect0(RakDisconnectReason reason) {
if (this.state == RakState.UNCONNECTED || this.state == RakState.DISCONNECTING) {
return this.channel.voidPromise();
}
this.setState(RakState.DISCONNECTING);
if (log.isDebugEnabled()) {
log.debug("Disconnecting RakNet Session ({} => {}) due to {}", this.channel.localAddress(), this.getRemoteAddress(), reason);
}
ChannelHandlerContext ctx = this.ctx();
ByteBuf buffer = ctx.alloc().ioBuffer(1);
buffer.writeByte(ID_DISCONNECTION_NOTIFICATION);
RakMessage rakMessage = new RakMessage(buffer, RakReliability.RELIABLE, RakPriority.IMMEDIATE);
ChannelPromise promise = ctx.newPromise();
promise.addListener((ChannelFuture future) -> // The channel provided in ChannelFuture is parent channel,
this.channel.pipeline().fireUserEventTriggered(reason).close()); // but we want RakChannel instead
this.write(ctx, rakMessage, promise);
return promise;
}
public void close(RakDisconnectReason reason) {
if (this.state == RakState.DISCONNECTING) {
return;
}
this.setState(RakState.DISCONNECTING);
if (log.isDebugEnabled()) {
log.debug("Closing RakNet Session ({} => {}) due to {}", this.channel.localAddress(), this.getRemoteAddress(), reason);
}
this.channel.pipeline().fireUserEventTriggered(reason).close();
}
public boolean isClosed() {
return this.state == RakState.UNCONNECTED;
}
private void checkForClosed() {
if (this.state == RakState.UNCONNECTED) {
throw new IllegalStateException("RakSession is closed!");
}
}
private void setState(RakState state) {
if (this.state == state) {
return;
}
this.state = state;
RakChannelMetrics metrics = this.getMetrics();
if (metrics != null) {
metrics.stateChange(state);
}
}
public void recalculatePongTime(long pingTime) {
if (this.currentPingTime == pingTime) {
this.lastPingTime = this.currentPingTime;
this.lastPongTime = System.currentTimeMillis();
}
}
private void touch() {
this.checkForClosed();
this.lastTouched = System.currentTimeMillis();
}
public boolean isStale(long curTime) {
return curTime - this.lastTouched >= SESSION_STALE_MS;
}
public boolean isStale() {
return this.isStale(System.currentTimeMillis());
}
public boolean isTimedOut(long curTime) {
return curTime - this.lastTouched >= this.channel.config().getOption(RakChannelOption.RAK_SESSION_TIMEOUT);
}
public boolean isTimedOut() {
return this.isTimedOut(System.currentTimeMillis());
}
public long getPing() {
return this.lastPongTime - this.lastPingTime;
}
public double getRTT() {
return this.slidingWindow.getRTT();
}
public int getMtu() {
return this.channel.config().getMtu() - UDP_HEADER_SIZE - (this.getRemoteAddress().getAddress() instanceof Inet6Address ? 40 : 20);
}
public RakChannelMetrics getMetrics() {
return this.channel.config().getMetrics();
}
public InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) this.channel.remoteAddress();
}
protected Queue<IntRange> getAcknowledgeQueue(boolean nack) {
return nack ? this.incomingNaks : this.incomingAcks;
}
public Channel getChannel() {
return channel;
}
}