-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathprudp_endpoint.go
816 lines (661 loc) · 27.7 KB
/
prudp_endpoint.go
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
package nex
import (
"encoding/binary"
"errors"
"fmt"
"slices"
"time"
"github.com/PretendoNetwork/nex-go/v2/constants"
"github.com/PretendoNetwork/nex-go/v2/types"
)
// PRUDPEndPoint is an implementation of rdv::PRUDPEndPoint.
// A PRUDPEndPoint represents a remote server location the client may connect to using a given remote stream ID.
// Each PRUDPEndPoint handles it's own set of PRUDPConnections, state, and events.
//
// In NEX there exists nn::nex::SecureEndPoint, which presumably is what differentiates between the authentication
// and secure servers. However the functionality of rdv::PRUDPEndPoint and nn::nex::SecureEndPoint is seemingly
// identical. Rather than duplicate the logic from PRUDPEndpoint, a IsSecureEndpoint flag has been added instead.
type PRUDPEndPoint struct {
Server *PRUDPServer
StreamID uint8
DefaultStreamSettings *StreamSettings
Connections *MutexMap[string, *PRUDPConnection]
packetHandlers map[uint16]func(packet PRUDPPacketInterface)
packetEventHandlers map[string][]func(packet PacketInterface)
connectionEndedEventHandlers []func(connection *PRUDPConnection)
errorEventHandlers []func(err *Error)
ConnectionIDCounter *Counter[uint32]
ServerAccount *Account
AccountDetailsByPID func(pid *types.PID) (*Account, *Error)
AccountDetailsByUsername func(username string) (*Account, *Error)
IsSecureEndPoint bool
CalcRetransmissionTimeoutCallback CalcRetransmissionTimeoutCallback
}
// CalcRetransmissionTimeoutCallback is an optional callback which can be used to override the RTO calculation
// for packets sent by this `PRUDPEndpoint`
type CalcRetransmissionTimeoutCallback func(rtt float64, sendCount uint32) time.Duration
// RegisterServiceProtocol registers a NEX service with the endpoint
func (pep *PRUDPEndPoint) RegisterServiceProtocol(protocol ServiceProtocol) {
protocol.SetEndpoint(pep)
pep.OnData(protocol.HandlePacket)
}
// RegisterCustomPacketHandler registers a custom handler for a given packet type. Used to override existing handlers or create new ones for custom packet types.
func (pep *PRUDPEndPoint) RegisterCustomPacketHandler(packetType uint16, handler func(packet PRUDPPacketInterface)) {
pep.packetHandlers[packetType] = handler
}
// OnData adds an event handler which is fired when a new DATA packet is received
func (pep *PRUDPEndPoint) OnData(handler func(packet PacketInterface)) {
pep.on("data", handler)
}
// OnError adds an event handler which is fired when an error occurs on the endpoint
func (pep *PRUDPEndPoint) OnError(handler func(err *Error)) {
// * "Ended" events are a special case, so handle them separately
pep.errorEventHandlers = append(pep.errorEventHandlers, handler)
}
// OnDisconnect adds an event handler which is fired when a new DISCONNECT packet is received
//
// To handle a connection being removed from the server, see OnConnectionEnded which fires on more cases
func (pep *PRUDPEndPoint) OnDisconnect(handler func(packet PacketInterface)) {
pep.on("disconnect", handler)
}
// OnConnectionEnded adds an event handler which is fired when a connection is removed from the server
//
// Fires both on a natural disconnect and from a timeout
func (pep *PRUDPEndPoint) OnConnectionEnded(handler func(connection *PRUDPConnection)) {
// * "Ended" events are a special case, so handle them separately
pep.connectionEndedEventHandlers = append(pep.connectionEndedEventHandlers, handler)
}
func (pep *PRUDPEndPoint) on(name string, handler func(packet PacketInterface)) {
if _, ok := pep.packetEventHandlers[name]; !ok {
pep.packetEventHandlers[name] = make([]func(packet PacketInterface), 0)
}
pep.packetEventHandlers[name] = append(pep.packetEventHandlers[name], handler)
}
func (pep *PRUDPEndPoint) emit(name string, packet PRUDPPacketInterface) {
if handlers, ok := pep.packetEventHandlers[name]; ok {
for _, handler := range handlers {
handler(packet)
}
}
}
func (pep *PRUDPEndPoint) emitConnectionEnded(connection *PRUDPConnection) {
for _, handler := range pep.connectionEndedEventHandlers {
handler(connection)
}
}
// EmitError calls all the endpoints error event handlers with the provided error
func (pep *PRUDPEndPoint) EmitError(err *Error) {
for _, handler := range pep.errorEventHandlers {
handler(err)
}
}
// cleanupConnection cleans up and deletes a connection from this endpoint. Will lock the Connections mutex - make sure
// you don't hold it during a call, or this will deadlock
func (pep *PRUDPEndPoint) cleanupConnection(connection *PRUDPConnection) {
discriminator := fmt.Sprintf("%s-%d-%d", connection.Socket.Address.String(), connection.StreamType, connection.StreamID)
found := false
pep.Connections.RunAndDelete(discriminator, func(key string, conn *PRUDPConnection) {
found = true
})
// * Probably this connection is on a different PRUDPEndPoint
if !found {
logger.Warningf("Tried to delete connection %v (ID %v) but it doesn't exist!", discriminator, connection.ID)
}
// * We can't do this during RunAndDelete, since we hold the Connections mutex then
// * This way we avoid any recursive locking
connection.cleanup()
}
func (pep *PRUDPEndPoint) processPacket(packet PRUDPPacketInterface, socket *SocketConnection) {
streamType := packet.SourceVirtualPortStreamType()
streamID := packet.SourceVirtualPortStreamID()
discriminator := fmt.Sprintf("%s-%d-%d", socket.Address.String(), streamType, streamID)
connection := pep.Connections.GetOrSetDefault(discriminator, func() *PRUDPConnection {
connection := NewPRUDPConnection(socket)
connection.endpoint = pep
connection.ID = pep.ConnectionIDCounter.Next()
connection.DefaultPRUDPVersion = packet.Version()
connection.StreamType = streamType
connection.StreamID = streamID
connection.StreamSettings = pep.DefaultStreamSettings.Copy()
return connection
})
connection.Lock()
defer connection.Unlock()
packet.SetSender(connection)
if packet.HasFlag(constants.PacketFlagAck) || packet.HasFlag(constants.PacketFlagMultiAck) {
pep.handleAcknowledgment(packet)
return
}
if packetHandler, ok := pep.packetHandlers[packet.Type()]; ok {
packetHandler(packet)
} else {
logger.Warningf("Unhandled packet type %d", packet.Type())
}
}
func (pep *PRUDPEndPoint) handleAcknowledgment(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
if connection.ConnectionState < StateConnected {
return
}
connection.resetHeartbeat()
if packet.HasFlag(constants.PacketFlagMultiAck) {
pep.handleMultiAcknowledgment(packet)
return
}
if packet.Type() == constants.PingPacket {
if packet.SequenceID() == connection.outgoingPingSequenceIDCounter.Value {
connection.rtt.Adjust(time.Since(connection.lastSentPingTime))
}
} else {
slidingWindow := connection.SlidingWindow(packet.SubstreamID())
slidingWindow.TimeoutManager.AcknowledgePacket(packet.SequenceID())
}
}
func (pep *PRUDPEndPoint) handleMultiAcknowledgment(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
stream := NewByteStreamIn(packet.Payload(), pep.Server.LibraryVersions, pep.ByteStreamSettings())
sequenceIDs := make([]uint16, 0)
var baseSequenceID uint16
var slidingWindow *SlidingWindow
if packet.SubstreamID() == 1 {
// * New aggregate acknowledgment packets set this to 1
// * and encode the real substream ID in in the payload
substreamID, _ := stream.ReadPrimitiveUInt8()
additionalIDsCount, _ := stream.ReadPrimitiveUInt8()
baseSequenceID, _ = stream.ReadPrimitiveUInt16LE()
slidingWindow = connection.SlidingWindow(substreamID)
for i := 0; i < int(additionalIDsCount); i++ {
additionalID, _ := stream.ReadPrimitiveUInt16LE()
sequenceIDs = append(sequenceIDs, additionalID)
}
} else {
// TODO - This is how Kinnay's client handles this, but it doesn't make sense for QRV? Since it can have multiple reliable substreams?
// * Old aggregate acknowledgment packets always use
// * substream 0
slidingWindow = connection.SlidingWindow(0)
baseSequenceID = packet.SequenceID()
for stream.Remaining() > 0 {
additionalID, _ := stream.ReadPrimitiveUInt16LE()
sequenceIDs = append(sequenceIDs, additionalID)
}
}
// * MutexMap.Each locks the mutex, can't remove while reading.
// * Have to just loop again
slidingWindow.TimeoutManager.packets.Each(func(sequenceID uint16, pending PRUDPPacketInterface) bool {
if sequenceID <= baseSequenceID && !slices.Contains(sequenceIDs, sequenceID) {
sequenceIDs = append(sequenceIDs, sequenceID)
}
return false
})
// * Actually remove the packets from the pool
for _, sequenceID := range sequenceIDs {
slidingWindow.TimeoutManager.AcknowledgePacket(sequenceID)
}
}
func (pep *PRUDPEndPoint) handleSyn(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
connection.resetHeartbeat()
var ack PRUDPPacketInterface
if packet.Version() == 2 {
ack, _ = NewPRUDPPacketLite(pep.Server, connection, nil)
} else if packet.Version() == 1 {
ack, _ = NewPRUDPPacketV1(pep.Server, connection, nil)
} else {
ack, _ = NewPRUDPPacketV0(pep.Server, connection, nil)
}
connectionSignature, err := packet.calculateConnectionSignature(connection.Socket.Address)
if err != nil {
logger.Error(err.Error())
}
connection.reset()
connection.Signature = connectionSignature
ack.SetType(constants.SynPacket)
ack.AddFlag(constants.PacketFlagAck)
ack.AddFlag(constants.PacketFlagHasSize)
ack.SetSourceVirtualPortStreamType(packet.DestinationVirtualPortStreamType())
ack.SetSourceVirtualPortStreamID(packet.DestinationVirtualPortStreamID())
ack.SetDestinationVirtualPortStreamType(packet.SourceVirtualPortStreamType())
ack.SetDestinationVirtualPortStreamID(packet.SourceVirtualPortStreamID())
ack.setConnectionSignature(connectionSignature)
ack.setSignature(ack.calculateSignature([]byte{}, []byte{}))
if ack, ok := ack.(*PRUDPPacketV1); ok {
// * Negotiate with the client what we support
ack.maximumSubstreamID = packet.(*PRUDPPacketV1).maximumSubstreamID // * No change needed, we can just support what the client wants
ack.minorVersion = packet.(*PRUDPPacketV1).minorVersion // * No change needed, we can just support what the client wants
ack.supportedFunctions = pep.Server.SupportedFunctions & packet.(*PRUDPPacketV1).supportedFunctions
}
connection.ConnectionState = StateConnecting
pep.emit("syn", ack)
pep.Server.sendRaw(connection.Socket, ack.Bytes())
}
func (pep *PRUDPEndPoint) handleConnect(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
if connection.ConnectionState < StateConnecting {
return
}
connection.resetHeartbeat()
var ack PRUDPPacketInterface
if packet.Version() == 2 {
ack, _ = NewPRUDPPacketLite(pep.Server, connection, nil)
} else if packet.Version() == 1 {
ack, _ = NewPRUDPPacketV1(pep.Server, connection, nil)
} else {
ack, _ = NewPRUDPPacketV0(pep.Server, connection, nil)
}
connection.ServerConnectionSignature = packet.getConnectionSignature()
connection.SessionID = packet.SessionID()
connectionSignature, err := packet.calculateConnectionSignature(connection.Socket.Address)
if err != nil {
logger.Error(err.Error())
}
connection.ServerSessionID = packet.SessionID()
ack.SetType(constants.ConnectPacket)
ack.AddFlag(constants.PacketFlagAck)
ack.AddFlag(constants.PacketFlagHasSize)
ack.SetSourceVirtualPortStreamType(packet.DestinationVirtualPortStreamType())
ack.SetSourceVirtualPortStreamID(packet.DestinationVirtualPortStreamID())
ack.SetDestinationVirtualPortStreamType(packet.SourceVirtualPortStreamType())
ack.SetDestinationVirtualPortStreamID(packet.SourceVirtualPortStreamID())
ack.setConnectionSignature(make([]byte, len(connectionSignature)))
ack.SetSessionID(connection.ServerSessionID)
ack.SetSequenceID(1)
if ack, ok := ack.(*PRUDPPacketV1); ok {
// * At this stage the client and server have already
// * negotiated what they each can support, so configure
// * the client now and just send the client back the
// * negotiated configuration
ack.maximumSubstreamID = packet.(*PRUDPPacketV1).maximumSubstreamID
ack.minorVersion = packet.(*PRUDPPacketV1).minorVersion
ack.supportedFunctions = packet.(*PRUDPPacketV1).supportedFunctions
connection.InitializeSlidingWindows(ack.maximumSubstreamID)
connection.InitializePacketDispatchQueues(ack.maximumSubstreamID)
connection.outgoingUnreliableSequenceIDCounter = NewCounter[uint16](packet.(*PRUDPPacketV1).initialUnreliableSequenceID)
} else {
connection.InitializeSlidingWindows(0)
connection.InitializePacketDispatchQueues(0)
}
payload := make([]byte, 0)
if pep.IsSecureEndPoint {
var decryptedPayload []byte
if pep.Server.PRUDPV0Settings.EncryptedConnect {
decryptedPayload, err = connection.StreamSettings.EncryptionAlgorithm.Decrypt(packet.Payload())
if err != nil {
logger.Error(err.Error())
return
}
} else {
decryptedPayload = packet.Payload()
}
decompressedPayload, err := connection.StreamSettings.CompressionAlgorithm.Decompress(decryptedPayload)
if err != nil {
logger.Error(err.Error())
return
}
sessionKey, pid, checkValue, err := pep.readKerberosTicket(decompressedPayload)
if err != nil {
logger.Error(err.Error())
return
}
connection.SetPID(pid)
connection.setSessionKey(sessionKey)
responseCheckValue := checkValue + 1
responseCheckValueBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(responseCheckValueBytes, responseCheckValue)
checkValueResponse := types.NewBuffer(responseCheckValueBytes)
stream := NewByteStreamOut(pep.Server.LibraryVersions, pep.ByteStreamSettings())
checkValueResponse.WriteTo(stream)
payload = stream.Bytes()
}
compressedPayload, err := connection.StreamSettings.CompressionAlgorithm.Compress(payload)
if err != nil {
logger.Error(err.Error())
return
}
var encryptedPayload []byte
if pep.Server.PRUDPV0Settings.EncryptedConnect {
encryptedPayload, err = connection.StreamSettings.EncryptionAlgorithm.Encrypt(compressedPayload)
if err != nil {
logger.Error(err.Error())
return
}
} else {
encryptedPayload = compressedPayload
}
ack.SetPayload(encryptedPayload)
ack.setSignature(ack.calculateSignature([]byte{}, packet.getConnectionSignature()))
connection.ConnectionState = StateConnected
connection.startHeartbeat()
pep.emit("connect", ack)
pep.Server.sendRaw(connection.Socket, ack.Bytes())
}
func (pep *PRUDPEndPoint) handleData(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
if connection.ConnectionState < StateConnected {
return
}
connection.resetHeartbeat()
if packet.HasFlag(constants.PacketFlagReliable) {
pep.handleReliable(packet)
} else {
pep.handleUnreliable(packet)
}
}
func (pep *PRUDPEndPoint) handleDisconnect(packet PRUDPPacketInterface) {
// TODO - Should we check the state here, or just let the connection disconnect at any time?
if packet.HasFlag(constants.PacketFlagNeedsAck) {
pep.acknowledgePacket(packet)
}
streamType := packet.SourceVirtualPortStreamType()
streamID := packet.SourceVirtualPortStreamID()
discriminator := fmt.Sprintf("%s-%d-%d", packet.Sender().Address().String(), streamType, streamID)
if connection, ok := pep.Connections.Get(discriminator); ok {
pep.cleanupConnection(connection)
}
pep.emit("disconnect", packet)
}
func (pep *PRUDPEndPoint) handlePing(packet PRUDPPacketInterface) {
connection := packet.Sender().(*PRUDPConnection)
if connection.ConnectionState < StateConnected {
return
}
connection.resetHeartbeat()
if packet.HasFlag(constants.PacketFlagNeedsAck) {
pep.acknowledgePacket(packet)
}
if packet.HasFlag(constants.PacketFlagReliable) {
substreamID := packet.SubstreamID()
packetDispatchQueue := connection.PacketDispatchQueue(substreamID)
packetDispatchQueue.Queue(packet)
}
}
func (pep *PRUDPEndPoint) readKerberosTicket(payload []byte) ([]byte, *types.PID, uint32, error) {
stream := NewByteStreamIn(payload, pep.Server.LibraryVersions, pep.ByteStreamSettings())
ticketData := types.NewBuffer(nil)
if err := ticketData.ExtractFrom(stream); err != nil {
return nil, nil, 0, err
}
requestData := types.NewBuffer(nil)
if err := requestData.ExtractFrom(stream); err != nil {
return nil, nil, 0, err
}
// * Sanity checks
serverAccount, _ := pep.AccountDetailsByUsername(pep.ServerAccount.Username)
if serverAccount == nil {
return nil, nil, 0, errors.New("Failed to find endpoint server account")
}
if serverAccount.Password != pep.ServerAccount.Password {
return nil, nil, 0, errors.New("Password for endpoint server account does not match the records from AccountDetailsByUsername")
}
serverKey := DeriveKerberosKey(serverAccount.PID, []byte(serverAccount.Password))
ticket := NewKerberosTicketInternalData(pep.Server)
if err := ticket.Decrypt(NewByteStreamIn(ticketData.Value, pep.Server.LibraryVersions, pep.ByteStreamSettings()), serverKey); err != nil {
return nil, nil, 0, err
}
ticketTime := ticket.Issued.Standard()
serverTime := time.Now().UTC()
timeLimit := ticketTime.Add(time.Minute * 2)
if serverTime.After(timeLimit) {
return nil, nil, 0, errors.New("Kerberos ticket expired")
}
sessionKey := ticket.SessionKey
kerberos := NewKerberosEncryption(sessionKey)
decryptedRequestData, err := kerberos.Decrypt(requestData.Value)
if err != nil {
return nil, nil, 0, err
}
checkDataStream := NewByteStreamIn(decryptedRequestData, pep.Server.LibraryVersions, pep.ByteStreamSettings())
userPID := types.NewPID(0)
if err := userPID.ExtractFrom(checkDataStream); err != nil {
return nil, nil, 0, err
}
_, err = checkDataStream.ReadPrimitiveUInt32LE() // * CID of secure server station url
if err != nil {
return nil, nil, 0, err
}
responseCheck, err := checkDataStream.ReadPrimitiveUInt32LE()
if err != nil {
return nil, nil, 0, err
}
return sessionKey, userPID, responseCheck, nil
}
func (pep *PRUDPEndPoint) acknowledgePacket(packet PRUDPPacketInterface) {
var ack PRUDPPacketInterface
if packet.Version() == 2 {
ack, _ = NewPRUDPPacketLite(pep.Server, packet.Sender().(*PRUDPConnection), nil)
} else if packet.Version() == 1 {
ack, _ = NewPRUDPPacketV1(pep.Server, packet.Sender().(*PRUDPConnection), nil)
} else {
ack, _ = NewPRUDPPacketV0(pep.Server, packet.Sender().(*PRUDPConnection), nil)
}
ack.SetType(packet.Type())
ack.AddFlag(constants.PacketFlagAck)
ack.SetSourceVirtualPortStreamType(packet.DestinationVirtualPortStreamType())
ack.SetSourceVirtualPortStreamID(packet.DestinationVirtualPortStreamID())
ack.SetDestinationVirtualPortStreamType(packet.SourceVirtualPortStreamType())
ack.SetDestinationVirtualPortStreamID(packet.SourceVirtualPortStreamID())
ack.SetSequenceID(packet.SequenceID())
ack.setFragmentID(packet.getFragmentID())
ack.SetSubstreamID(packet.SubstreamID())
pep.Server.sendPacket(ack)
// * Servers send the DISCONNECT ACK 3 times
if packet.Type() == constants.DisconnectPacket {
pep.Server.sendPacket(ack)
pep.Server.sendPacket(ack)
}
}
func (pep *PRUDPEndPoint) handleReliable(packet PRUDPPacketInterface) {
if packet.HasFlag(constants.PacketFlagNeedsAck) {
pep.acknowledgePacket(packet)
}
connection := packet.Sender().(*PRUDPConnection)
substreamID := packet.SubstreamID()
packetDispatchQueue := connection.PacketDispatchQueue(substreamID)
packetDispatchQueue.Queue(packet)
for nextPacket, ok := packetDispatchQueue.GetNextToDispatch(); ok; nextPacket, ok = packetDispatchQueue.GetNextToDispatch() {
if nextPacket.Type() == constants.DataPacket {
var decryptedPayload []byte
if nextPacket.Version() != 2 {
decryptedPayload = nextPacket.decryptPayload()
} else {
// * PRUDPLite does not encrypt payloads
decryptedPayload = nextPacket.Payload()
}
decompressedPayload, err := connection.StreamSettings.CompressionAlgorithm.Decompress(decryptedPayload)
if err != nil {
logger.Error(err.Error())
}
incomingFragmentBuffer := connection.GetIncomingFragmentBuffer(substreamID)
incomingFragmentBuffer = append(incomingFragmentBuffer, decompressedPayload...)
connection.SetIncomingFragmentBuffer(substreamID, incomingFragmentBuffer)
if nextPacket.getFragmentID() == 0 {
message := NewRMCMessage(pep)
err := message.FromBytes(incomingFragmentBuffer)
if err != nil {
// TODO - Should this return the error too?
logger.Error(err.Error())
}
nextPacket.SetRMCMessage(message)
connection.ClearOutgoingBuffer(substreamID)
pep.emit("data", nextPacket)
}
}
packetDispatchQueue.Dispatched(nextPacket)
}
}
func (pep *PRUDPEndPoint) handleUnreliable(packet PRUDPPacketInterface) {
if packet.HasFlag(constants.PacketFlagNeedsAck) {
pep.acknowledgePacket(packet)
}
// * Since unreliable DATA packets can in theory reach the
// * server in any order, and they lack a subsslidingWindowtream, it's
// * not actually possible to know what order they should
// * be processed in for each request. So assume all packets
// * MUST be fragment 0 (unreliable packets do not have frags)
// *
// * Example -
// *
// * Say there is 2 requests to the same protocol, methods 1
// * and 2. The starting unreliable sequence ID is 10. If both
// * method 1 and 2 are called at the same time, but method 1
// * has a fragmented payload, the packets could, in theory, reach
// * the server like so:
// *
// * - Method1 - Sequence 10, Fragment 1
// * - Method1 - Sequence 13, Fragment 3
// * - Method2 - Sequence 12, Fragment 0
// * - Method1 - Sequence 11, Fragment 2
// * - Method1 - Sequence 14, Fragment 0
// *
// * If we reorder these to the proper order, like so:
// *
// * - Method1 - Sequence 10, Fragment 1
// * - Method1 - Sequence 11, Fragment 2
// * - Method2 - Sequence 12, Fragment 0
// * - Method1 - Sequence 13, Fragment 3
// * - Method1 - Sequence 14, Fragment 0
// *
// * We still have a gap where Method2 was called. It's not
// * possible to know if the packet with sequence ID 12 belongs
// * to the Method1 calls or not. We don't even know which methods
// * the packets are for at this stage yet, since the RMC data
// * can't be checked until all the fragments are collected and
// * the payload decrypted. In this case, we would see fragment 0
// * and assume that's the end of fragments, losing the real last
// * fragments and resulting in a bad decryption
// TODO - Is this actually true? I'm just assuming, based on common sense, tbh. Kinnay also does not implement fragmented unreliable packets?
if packet.getFragmentID() != 0 {
logger.Warningf("Unexpected unreliable fragment ID. Expected 0, got %d", packet.getFragmentID())
return
}
payload := packet.processUnreliableCrypto()
message := NewRMCMessage(pep)
err := message.FromBytes(payload)
if err != nil {
// TODO - Should this return the error too?
logger.Error(err.Error())
}
packet.SetRMCMessage(message)
pep.emit("data", packet)
}
func (pep *PRUDPEndPoint) sendPing(connection *PRUDPConnection) {
var ping PRUDPPacketInterface
switch connection.DefaultPRUDPVersion {
case 0:
ping, _ = NewPRUDPPacketV0(pep.Server, connection, nil)
case 1:
ping, _ = NewPRUDPPacketV1(pep.Server, connection, nil)
case 2:
ping, _ = NewPRUDPPacketLite(pep.Server, connection, nil)
}
ping.SetType(constants.PingPacket)
ping.AddFlag(constants.PacketFlagNeedsAck)
ping.SetSourceVirtualPortStreamType(connection.StreamType)
ping.SetSourceVirtualPortStreamID(pep.StreamID)
ping.SetDestinationVirtualPortStreamType(connection.StreamType)
ping.SetDestinationVirtualPortStreamID(connection.StreamID)
ping.SetSubstreamID(0)
pep.Server.sendPacket(ping)
}
// FindConnectionByID returns the PRUDP client connected with the given connection ID
func (pep *PRUDPEndPoint) FindConnectionByID(connectedID uint32) *PRUDPConnection {
var connection *PRUDPConnection
pep.Connections.Each(func(discriminator string, pc *PRUDPConnection) bool {
if pc.ID == connectedID {
connection = pc
return true
}
return false
})
return connection
}
// FindConnectionByPID returns the PRUDP client connected with the given PID
func (pep *PRUDPEndPoint) FindConnectionByPID(pid uint64) *PRUDPConnection {
var connection *PRUDPConnection
pep.Connections.Each(func(discriminator string, pc *PRUDPConnection) bool {
if pc.pid.Value() == pid && pc.ConnectionState == StateConnected {
connection = pc
return true
}
return false
})
return connection
}
// ComputeRetransmitTimeout computes the RTO (Retransmit timeout) for a given packet
func (pep *PRUDPEndPoint) ComputeRetransmitTimeout(packet PRUDPPacketInterface) time.Duration {
connection := packet.Sender().(*PRUDPConnection)
rtt := connection.rtt
if callback := pep.CalcRetransmissionTimeoutCallback; callback != nil {
rttAverage := rtt.GetRTTSmoothedAvg()
rttDeviation := rtt.GetRTTSmoothedDev()
return callback(rttAverage+rttDeviation*4.0, packet.SendCount())
}
var retransmitTimeBase int64
if packet.Type() == constants.SynPacket {
retransmitTimeBase = int64(pep.DefaultStreamSettings.SynInitialRTT)
} else {
retransmitTimeBase = int64(pep.DefaultStreamSettings.InitialRTT)
if rtt.Initialized() {
retransmitTimeBase = int64(rtt.Average()/time.Millisecond) / 8
}
}
retransmitTimeBaseMultiplier := packet.SendCount()
var retransmitMultiplier float64
if packet.SendCount() < pep.DefaultStreamSettings.ExtraRetransmitTimeoutTrigger {
retransmitMultiplier = float64(pep.DefaultStreamSettings.RetransmitTimeoutMultiplier)
} else {
retransmitMultiplier = float64(pep.DefaultStreamSettings.ExtraRetransmitTimeoutMultiplier)
}
return time.Duration(float64(retransmitTimeBase*int64(retransmitTimeBaseMultiplier))*retransmitMultiplier) * time.Millisecond
}
// AccessKey returns the servers sandbox access key
func (pep *PRUDPEndPoint) AccessKey() string {
return pep.Server.AccessKey
}
// SetAccessKey sets the servers sandbox access key
func (pep *PRUDPEndPoint) SetAccessKey(accessKey string) {
pep.Server.AccessKey = accessKey
}
// Send sends the packet to the packets sender
func (pep *PRUDPEndPoint) Send(packet PacketInterface) {
pep.Server.Send(packet)
}
// LibraryVersions returns the versions that the server has
func (pep *PRUDPEndPoint) LibraryVersions() *LibraryVersions {
return pep.Server.LibraryVersions
}
// ByteStreamSettings returns the settings to be used for ByteStreams
func (pep *PRUDPEndPoint) ByteStreamSettings() *ByteStreamSettings {
return pep.Server.ByteStreamSettings
}
// SetByteStreamSettings sets the settings to be used for ByteStreams
func (pep *PRUDPEndPoint) SetByteStreamSettings(byteStreamSettings *ByteStreamSettings) {
pep.Server.ByteStreamSettings = byteStreamSettings
}
// UseVerboseRMC checks whether or not the endpoint uses verbose RMC
func (pep *PRUDPEndPoint) UseVerboseRMC() bool {
return pep.Server.UseVerboseRMC
}
// EnableVerboseRMC enable or disables the use of verbose RMC
func (pep *PRUDPEndPoint) EnableVerboseRMC(enable bool) {
pep.Server.UseVerboseRMC = enable
}
// NewPRUDPEndPoint returns a new PRUDPEndPoint for a server on the provided stream ID
func NewPRUDPEndPoint(streamID uint8) *PRUDPEndPoint {
pep := &PRUDPEndPoint{
StreamID: streamID,
DefaultStreamSettings: NewStreamSettings(),
Connections: NewMutexMap[string, *PRUDPConnection](),
packetHandlers: make(map[uint16]func(packet PRUDPPacketInterface)),
packetEventHandlers: make(map[string][]func(PacketInterface)),
connectionEndedEventHandlers: make([]func(connection *PRUDPConnection), 0),
errorEventHandlers: make([]func(err *Error), 0),
ConnectionIDCounter: NewCounter[uint32](0),
IsSecureEndPoint: false,
}
pep.packetHandlers[constants.SynPacket] = pep.handleSyn
pep.packetHandlers[constants.ConnectPacket] = pep.handleConnect
pep.packetHandlers[constants.DataPacket] = pep.handleData
pep.packetHandlers[constants.DisconnectPacket] = pep.handleDisconnect
pep.packetHandlers[constants.PingPacket] = pep.handlePing
return pep
}