forked from urnetwork/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_remote_multi_client.go
More file actions
2692 lines (2372 loc) · 73.3 KB
/
ip_remote_multi_client.go
File metadata and controls
2692 lines (2372 loc) · 73.3 KB
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package connect
import (
"context"
"sync"
"time"
// "reflect"
"errors"
"fmt"
"math"
mathrand "math/rand"
"slices"
"strings"
"golang.org/x/exp/maps"
"google.golang.org/protobuf/proto"
"github.com/golang/glog"
"github.com/urnetwork/connect/protocol"
)
// multi client is a sender approach to mitigate bad destinations
// it maintains a window of compatible clients chosen using specs
// (e.g. from a desription of the intent of use)
// - the clients are rate limited by the number of outstanding acks (nacks)
// - the size of allowed outstanding nacks increases with each ack,
// scaling up successful destinations to use the full transfer buffer
// - the clients are chosen with probability weighted by their
// net frame count statistics (acks - nacks)
// TODO surface window stats to show to users
type clientReceivePacketFunction func(client *multiClientChannel, source TransferPath, provideMode protocol.ProvideMode, ipPath *IpPath, packet []byte)
type DestinationStats struct {
EstimatedBytesPerSecond ByteCount
Tier int
}
type WindowType int
func (self WindowType) RankMode() string {
switch self {
case WindowTypeQuality:
return "quality"
case WindowTypeSpeed:
return "speed"
default:
return ""
}
}
const (
WindowTypeQuality WindowType = 0
WindowTypeSpeed WindowType = 1
)
// for each `NewClientArgs`,
//
// `RemoveClientWithArgs` will be called if a client was created for the args,
// else `RemoveClientArgs`
type MultiClientGenerator interface {
// path -> estimated byte count per second
// the enumeration should typically
// 1. not repeat final destination ids from any path
// 2. not repeat intermediary elements from any path
NextDestinations(count int, excludeDestinations []MultiHopId, rankMode string) (map[MultiHopId]DestinationStats, error)
// client id, client auth
NewClientArgs() (*MultiClientGeneratorClientArgs, error)
RemoveClientArgs(args *MultiClientGeneratorClientArgs)
RemoveClientWithArgs(client *Client, args *MultiClientGeneratorClientArgs)
NewClientSettings() *ClientSettings
NewClient(ctx context.Context, args *MultiClientGeneratorClientArgs, clientSettings *ClientSettings) (*Client, error)
FixedDestinationSize() (int, bool)
}
func DefaultMultiClientSettings() *MultiClientSettings {
return &MultiClientSettings{
SequenceIdleTimeout: 30 * time.Second,
WindowSizes: map[WindowType]WindowSizeSettings{
WindowTypeQuality: WindowSizeSettings{
WindowSizeMin: 4,
// TODO increase this when p2p is deployed
WindowSizeMinP2pOnly: 0,
WindowSizeMax: 8,
// reconnects per source
WindowSizeReconnectScale: 1.0,
},
WindowTypeSpeed: WindowSizeSettings{
WindowSizeMin: 1,
// TODO increase this when p2p is deployed
WindowSizeMinP2pOnly: 0,
WindowSizeMax: 2,
WindowSizeUseMax: 1,
// reconnects per source
WindowSizeReconnectScale: 1.0,
},
},
SendRetryTimeout: 200 * time.Millisecond,
// this includes the time to establish the transport
PingWriteTimeout: 5 * time.Second,
PingTimeout: 10 * time.Second,
// a lower ack timeout helps cycle through bad providers faster
AckTimeout: 15 * time.Second,
BlackholeTimeout: 15 * time.Second,
WindowResizeTimeout: 5 * time.Second,
StatsWindowGraceperiod: 5 * time.Second,
StatsWindowEntropy: 0.25,
WindowExpandTimeout: 15 * time.Second,
WindowExpandBlockTimeout: 5 * time.Second,
// wait this time before enumerating potential clients again
WindowEnumerateEmptyTimeout: 60 * time.Second,
WindowEnumerateErrorTimeout: 1 * time.Second,
WindowExpandScale: 2.0,
WindowCollapseScale: 0.8,
WindowExpandMaxOvershotScale: 4.0,
WindowCollapseBeforeExpand: false,
WindowRevisitTimeout: 2 * time.Minute,
StatsWindowDuration: 10 * time.Second,
StatsWindowBucketDuration: 1 * time.Second,
StatsSampleWeightsCount: 8,
StatsSourceCountSelection: 0.95,
// ClientAffinityTimeout: 0 * time.Second,
MultiRaceSetOnNoResponseTimeout: 1000 * time.Millisecond,
MultiRaceSetOnResponseTimeout: 100 * time.Millisecond,
MultiRaceClientSentPacketMaxCount: 16,
MultiRaceClientPacketMaxCount: 4,
MultiRacePacketMaxCount: 16,
MultiRaceClientEarlyCompleteFraction: 0.25,
// TODO on platforms with more memory, increase this
MultiRaceClientCount: 4,
ProtocolVersion: DefaultProtocolVersion,
RemoteUserNatMultiClientMonitorSettings: *DefaultRemoteUserNatMultiClientMonitorSettings(),
}
}
type MultiClientSettings struct {
SequenceIdleTimeout time.Duration
WindowSizes map[WindowType]WindowSizeSettings
// ClientNackInitialLimit int
// ClientNackMaxLimit int
// ClientNackScale float64
// ClientWriteTimeout time.Duration
// SendTimeout time.Duration
// WriteTimeout time.Duration
SendRetryTimeout time.Duration
PingWriteTimeout time.Duration
PingTimeout time.Duration
AckTimeout time.Duration
BlackholeTimeout time.Duration
WindowResizeTimeout time.Duration
StatsWindowGraceperiod time.Duration
StatsWindowEntropy float32
WindowExpandTimeout time.Duration
WindowExpandBlockTimeout time.Duration
WindowEnumerateEmptyTimeout time.Duration
WindowEnumerateErrorTimeout time.Duration
WindowExpandScale float64
WindowCollapseScale float64
WindowExpandMaxOvershotScale float64
WindowCollapseBeforeExpand bool
WindowRevisitTimeout time.Duration
StatsWindowDuration time.Duration
StatsWindowBucketDuration time.Duration
StatsSampleWeightsCount int
StatsSourceCountSelection float64
// lower affinity is more private
// however, there may be some applications that assume the same ip across multiple connections
// in those cases, we would need some small affinity
// ClientAffinityTimeout time.Duration
// time since first send to end the race, if no response
MultiRaceSetOnNoResponseTimeout time.Duration
// time after the first response to end the race
MultiRaceSetOnResponseTimeout time.Duration
MultiRaceClientSentPacketMaxCount int
MultiRaceClientPacketMaxCount int
MultiRacePacketMaxCount int
MultiRaceClientEarlyCompleteFraction float32
MultiRaceClientCount int
ProtocolVersion int
RemoteUserNatMultiClientMonitorSettings
}
type WindowSizeSettings struct {
WindowSizeMin int
// the minimumum number of items in the windows that must be connected via p2p only
WindowSizeMinP2pOnly int
WindowSizeMax int
WindowSizeUseMax int
// reconnects per source
WindowSizeReconnectScale float64
}
type receivePacket struct {
Source TransferPath
ProvideMode protocol.ProvideMode
IpPath *IpPath
Packet []byte
Pooled bool
}
type RemoteUserNatMultiClient struct {
ctx context.Context
cancel context.CancelFunc
generator MultiClientGenerator
receivePacketCallback ReceivePacketFunction
settings *MultiClientSettings
windows map[WindowType]*multiClientWindow
monitor MultiClientMonitor
securityPolicyStats *securityPolicyStats
securityPolicy SecurityPolicy
ingressSecurityPolicy SecurityPolicy
// the provide mode of the source packets
// for locally generated packets this is `ProvideMode_Network`
provideMode protocol.ProvideMode
stateLock sync.Mutex
ip4PathUpdates map[Ip4Path]*multiClientChannelUpdate
ip6PathUpdates map[Ip6Path]*multiClientChannelUpdate
clientUpdates map[*multiClientChannel]map[*multiClientChannelUpdate]bool
}
func NewRemoteUserNatMultiClientWithDefaults(
ctx context.Context,
generator MultiClientGenerator,
receivePacketCallback ReceivePacketFunction,
provideMode protocol.ProvideMode,
) *RemoteUserNatMultiClient {
return NewRemoteUserNatMultiClient(
ctx,
generator,
receivePacketCallback,
provideMode,
DefaultMultiClientSettings(),
)
}
func NewRemoteUserNatMultiClient(
ctx context.Context,
generator MultiClientGenerator,
receivePacketCallback ReceivePacketFunction,
provideMode protocol.ProvideMode,
settings *MultiClientSettings,
) *RemoteUserNatMultiClient {
cancelCtx, cancel := context.WithCancel(ctx)
securityPolicyStats := DefaultSecurityPolicyStats()
multiClient := &RemoteUserNatMultiClient{
ctx: cancelCtx,
cancel: cancel,
generator: generator,
receivePacketCallback: receivePacketCallback,
settings: settings,
windows: map[WindowType]*multiClientWindow{},
securityPolicyStats: securityPolicyStats,
securityPolicy: DefaultEgressSecurityPolicyWithStats(securityPolicyStats),
ingressSecurityPolicy: DefaultIngressSecurityPolicyWithStats(securityPolicyStats),
provideMode: provideMode,
ip4PathUpdates: map[Ip4Path]*multiClientChannelUpdate{},
ip6PathUpdates: map[Ip6Path]*multiClientChannelUpdate{},
clientUpdates: map[*multiClientChannel]map[*multiClientChannelUpdate]bool{},
}
multiClient.windows[WindowTypeQuality] = newMultiClientWindow(
cancelCtx,
cancel,
generator,
multiClient.clientReceivePacket,
multiClient.ingressSecurityPolicy,
multiClient.removeClient,
WindowTypeQuality,
settings,
)
multiClient.windows[WindowTypeSpeed] = newMultiClientWindow(
cancelCtx,
cancel,
generator,
multiClient.clientReceivePacket,
multiClient.ingressSecurityPolicy,
multiClient.removeClient,
WindowTypeSpeed,
settings,
)
monitors := []MultiClientMonitor{}
for _, window := range multiClient.windows {
monitors = append(monitors, window.monitor)
}
multiClient.monitor = NewMergedMultiClientMonitor(monitors)
return multiClient
}
func (self *RemoteUserNatMultiClient) SecurityPolicyStats(reset bool) SecurityPolicyStats {
return self.securityPolicyStats.Stats(reset)
}
func (self *RemoteUserNatMultiClient) Monitor() MultiClientMonitor {
return self.monitor
}
func (self *RemoteUserNatMultiClient) AddContractStatusCallback(contractStatusCallback ContractStatusFunction) func() {
subs := []func(){}
for _, window := range self.windows {
sub := window.AddContractStatusCallback(contractStatusCallback)
subs = append(subs, sub)
}
return func() {
for _, sub := range subs {
sub()
}
}
}
func (self *RemoteUserNatMultiClient) updateClientPath(ipPath *IpPath, callback func(*multiClientChannelUpdate)) {
update, client := self.reserveUpdate(ipPath)
callback(update)
self.updateClient(update, client)
}
func (self *RemoteUserNatMultiClient) reserveUpdate(ipPath *IpPath) (*multiClientChannelUpdate, *multiClientChannel) {
self.stateLock.Lock()
defer self.stateLock.Unlock()
waitForIdle := func(update *multiClientChannelUpdate) {
for {
select {
case <-update.ctx.Done():
return
default:
}
var idleTimeout time.Duration
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
idleTimeout = update.activityTime.Add(self.settings.SequenceIdleTimeout).Sub(time.Now())
}()
if idleTimeout <= 0 {
return
} else {
select {
case <-update.ctx.Done():
return
case <-time.After(idleTimeout):
}
}
}
}
rst := func(client *multiClientChannel) {
if client != nil {
// rst to destination
if packet, ok := ipOosRst(ipPath); ok {
client.Send(&parsedPacket{
packet: packet,
ipPath: ipPath,
}, 0)
}
}
// rst to source
if packet, ok := ipOosRst(ipPath.Reverse()); ok {
self.receivePacketCallback(TransferPath{}, protocol.ProvideMode_Network, ipPath, packet)
}
}
switch ipPath.Version {
case 4:
ip4Path := ipPath.ToIp4Path()
update, ok := self.ip4PathUpdates[ip4Path]
if !ok || update.IsDone() {
update = newMultiClientChannelUpdate(self.ctx)
go HandleError(func() {
defer update.cancel()
waitForIdle(update)
var client *multiClientChannel
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
client = update.client
if self.ip4PathUpdates[ip4Path] == update {
delete(self.ip4PathUpdates, ip4Path)
}
if client != nil {
if updates, ok := self.clientUpdates[client]; ok {
delete(updates, update)
if len(updates) == 0 {
delete(self.clientUpdates, client)
}
}
}
}()
select {
case <-self.ctx.Done():
default:
rst(client)
}
}, update.cancel)
self.ip4PathUpdates[ip4Path] = update
}
return update, update.client
case 6:
ip6Path := ipPath.ToIp6Path()
update, ok := self.ip6PathUpdates[ip6Path]
if !ok || update.IsDone() {
update = newMultiClientChannelUpdate(self.ctx)
go HandleError(func() {
defer update.cancel()
waitForIdle(update)
var client *multiClientChannel
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
client = update.client
if self.ip6PathUpdates[ip6Path] == update {
delete(self.ip6PathUpdates, ip6Path)
}
if client != nil {
if updates, ok := self.clientUpdates[client]; ok {
delete(updates, update)
if len(updates) == 0 {
delete(self.clientUpdates, client)
}
}
}
}()
select {
case <-self.ctx.Done():
default:
rst(client)
}
}, update.cancel)
self.ip6PathUpdates[ip6Path] = update
}
return update, update.client
default:
panic(fmt.Errorf("Bad protocol version %d", ipPath.Version))
}
}
func (self *RemoteUserNatMultiClient) updateClient(update *multiClientChannelUpdate, previousClient *multiClientChannel) {
self.stateLock.Lock()
defer self.stateLock.Unlock()
client := update.client
update.activityTime = time.Now()
if previousClient != client {
if previousClient != nil {
if updates, ok := self.clientUpdates[previousClient]; ok {
delete(updates, update)
if len(updates) == 0 {
delete(self.clientUpdates, previousClient)
}
}
}
if client != nil && !client.IsDone() {
updates, ok := self.clientUpdates[client]
if !ok {
updates = map[*multiClientChannelUpdate]bool{}
self.clientUpdates[client] = updates
}
updates[update] = true
}
}
}
// remove a client from all updates
func (self *RemoteUserNatMultiClient) removeClient(client *multiClientChannel) {
self.stateLock.Lock()
defer self.stateLock.Unlock()
// note client must be marked as done, otherwise it may be re-added by updates in flight
if !client.IsDone() {
glog.Errorf("[multi]removed client that is not marked as done. This might lead to memory leak.")
}
if updates, ok := self.clientUpdates[client]; ok {
delete(self.clientUpdates, client)
for update, _ := range updates {
if update.client == client {
update.client = nil
} else {
glog.Errorf("[multi]update associated with incorrect client")
}
}
}
}
// `SendPacketFunction`
func (self *RemoteUserNatMultiClient) SendPacket(
source TransferPath,
provideMode protocol.ProvideMode,
packet []byte,
timeout time.Duration,
) bool {
minRelationship := max(provideMode, self.provideMode)
ipPath, r, err := self.securityPolicy.Inspect(minRelationship, packet)
if err != nil {
glog.Infof("[multi]send bad packet = %s\n", err)
return false
}
switch r {
case SecurityPolicyResultAllow:
parsedPacket := &parsedPacket{
packet: packet,
ipPath: ipPath,
}
return self.sendPacket(source, provideMode, parsedPacket, timeout)
default:
// TODO upgrade port 53 and port 80 here with protocol specific conversions
glog.Infof("[multi]drop packet ipv%d p%v -> %s:%d\n", ipPath.Version, ipPath.Protocol, ipPath.DestinationIp, ipPath.DestinationPort)
return false
}
}
// ordered by choice descending
func (self *RemoteUserNatMultiClient) selectWindowTypes(sendPacket *parsedPacket) []WindowType {
// - web traffic is routed to quality providers
// - all other traffic is routed to speed providers
if sendPacket.ipPath.DestinationPort == 443 {
return []WindowType{WindowTypeQuality, WindowTypeSpeed}
}
return []WindowType{WindowTypeSpeed, WindowTypeQuality}
}
func (self *RemoteUserNatMultiClient) sendPacket(
source TransferPath,
provideMode protocol.ProvideMode,
sendPacket *parsedPacket,
timeout time.Duration,
) (success bool) {
self.updateClientPath(sendPacket.ipPath, func(update *multiClientChannelUpdate) {
enterTime := time.Now()
currentClient := func() *multiClientChannel {
self.stateLock.Lock()
defer self.stateLock.Unlock()
return update.client
}
sendCurrent := func() bool {
for client := currentClient(); client != nil; {
p := &parsedPacket{
packet: sendPacket.packet,
ipPath: sendPacket.ipPath,
}
var err error
success, err = client.SendDetailed(p, timeout)
// note we do not check success also because it may be normal to drop packets under load
if err == nil {
return true
}
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
if client == update.client {
update.client = nil
client = nil
} else {
// a new client was set, try the new client
client = update.client
}
}()
}
return false
}
if sendCurrent() {
return
}
// find a new client
raceClients := func(orderedClients []*multiClientChannel, sendTimeout time.Duration) {
successCount := 0
for _, client := range orderedClients {
select {
case <-update.ctx.Done():
return
default:
}
done := false
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
if update.client != nil {
// another client already chosen, done
done = true
return
}
update.initRace()
race := update.race
state := race.clientStates[client]
if state == nil {
state = &multiClientChannelRaceClientState{
sendTime: time.Now(),
}
race.clientStates[client] = state
}
}()
if done {
return
}
p := &parsedPacket{
packet: MessagePoolShareReadOnly(sendPacket.packet),
ipPath: sendPacket.ipPath,
}
if client.Send(p, sendTimeout) {
successCount += 1
success = true
var abandonedClients []*multiClientChannel
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
if update.client != nil {
// another client already chosen, done
done = true
return
}
update.initRace()
race := update.race
state := race.clientStates[client]
race.sentPacketCount += 1
bufferExceeded := state != nil && self.settings.MultiRaceSetOnNoResponseTimeout <= time.Now().Sub(state.sendTime) || self.settings.MultiRaceClientSentPacketMaxCount < race.sentPacketCount
if race.packetCount == 0 && bufferExceeded {
// no client response in timeout, lock in this client
// this happens for example when the client only sends and does not receive (e.g. udp send)
for abandonedClient, _ := range race.clientStates {
if abandonedClient != client {
abandonedClients = append(abandonedClients, abandonedClient)
}
}
update.clearRace()
update.client = client
done = true
return
} else {
if self.settings.MultiRaceClientCount <= successCount {
done = true
return
}
// else continue sending to all clients
}
}()
if 0 < len(abandonedClients) {
if rstPacket, ok := ipOosRst(sendPacket.ipPath); ok {
for _, abandonedClient := range abandonedClients {
abandonedClient.Send(&parsedPacket{
packet: rstPacket,
ipPath: sendPacket.ipPath,
}, 0)
}
}
}
if done {
return
}
} else {
MessagePoolReturn(p.packet)
}
}
}
windowTypes := self.selectWindowTypes(sendPacket)
coalesceOrderedClients := func() []*multiClientChannel {
for _, windowType := range windowTypes {
if window, ok := self.windows[windowType]; ok {
orderedClients := window.OrderedClients()
if 0 < len(orderedClients) {
return orderedClients
}
}
}
return []*multiClientChannel{}
}
raceClients(coalesceOrderedClients(), 0)
if success {
MessagePoolReturn(sendPacket.packet)
return
}
for {
select {
case <-update.ctx.Done():
return
default:
}
if sendCurrent() {
return
}
var retryTimeout time.Duration
if 0 <= timeout {
remainingTimeout := enterTime.Add(timeout).Sub(time.Now())
if remainingTimeout <= 0 {
// drop
return
}
retryTimeout = min(remainingTimeout, self.settings.SendRetryTimeout)
} else {
retryTimeout = self.settings.SendRetryTimeout
}
if orderedClients := coalesceOrderedClients(); 0 < len(orderedClients) {
// distribute the timeout evenly via wait
retryTimeoutPerClient := retryTimeout / time.Duration(len(orderedClients))
raceClients(orderedClients, retryTimeoutPerClient)
if success {
MessagePoolReturn(sendPacket.packet)
return
}
} else {
select {
case <-update.ctx.Done():
// drop
return
case <-time.After(retryTimeout):
}
}
}
})
return
}
// clientReceivePacketFunction
func (self *RemoteUserNatMultiClient) clientReceivePacket(
sourceClient *multiClientChannel,
source TransferPath,
provideMode protocol.ProvideMode,
ipPath *IpPath,
packet []byte,
) {
// ipPath, err := ParseIpPath(packet)
// if err != nil {
// // bad ip packet, drop
// return
// }
ipPath = ipPath.Reverse()
var abandonedClients []*multiClientChannel
var receivePackets []*receivePacket
var returnPackets []*receivePacket
self.updateClientPath(ipPath, func(update *multiClientChannelUpdate) {
self.stateLock.Lock()
defer self.stateLock.Unlock()
client := update.client
if client == sourceClient {
p := &receivePacket{
Source: source,
ProvideMode: provideMode,
IpPath: ipPath,
Packet: packet,
}
receivePackets = []*receivePacket{p}
} else if client != nil {
// another client already chosen, drop
} else if race := update.race; race == nil {
// no race, no client, drop
glog.Infof("[multi]receive no race and no client")
} else if state, ok := race.clientStates[sourceClient]; !ok {
// this client is not part of the race, drop
glog.Infof("[multi]receive client not part of race")
} else if len(state.packets) < self.settings.MultiRaceClientPacketMaxCount && race.packetCount < self.settings.MultiRacePacketMaxCount {
// note that `MessagePoolShare*` will not work on the packet
// since the packet is typically a slice of the received transfer frame
ipPathCopy := ipPath.Copy()
packetCopy, pooled := MessagePoolCopyDetailed(packet)
receivePacket := &receivePacket{
Source: source,
ProvideMode: provideMode,
IpPath: ipPathCopy,
Packet: packetCopy,
Pooled: pooled,
}
state.packets = append(state.packets, receivePacket)
if 1 == len(state.packets) {
state.receiveTime = time.Now()
}
race.packetCount += 1
if race.packetCount == 1 {
// schedule the race evaluation on first packet
earlyComplete := race.completeMonitor.NotifyChannel()
// copy the ip path since the first packet may not be ultimately retained to the end of the race
self.scheduleCompleteRace(ipPathCopy, race, earlyComplete)
}
if len(state.packets) == 1 {
race.clientsWithPacketCount += 1
if int(float32(len(race.clientStates))*self.settings.MultiRaceClientEarlyCompleteFraction) <= race.clientsWithPacketCount {
race.completeMonitor.NotifyAll()
}
}
} else {
// race buffer limits exceeded, end the race immediately
glog.Infof("[multi]receive race buffer limit reached")
for abandonedClient, abandonedState := range race.clientStates {
if abandonedClient != client {
abandonedClients = append(abandonedClients, abandonedClient)
for _, p := range abandonedState.packets {
if p.Pooled {
p.Pooled = false
returnPackets = append(returnPackets, p)
}
}
}
}
update.clearRace()
update.client = client
receivePacket := &receivePacket{
Source: source,
ProvideMode: provideMode,
IpPath: ipPath,
Packet: packet,
}
receivePackets = append(state.packets, receivePacket)
for _, p := range receivePackets {
if p.Pooled {
p.Pooled = false
returnPackets = append(returnPackets, p)
}
}
}
})
if 0 < len(abandonedClients) {
if rstPacket, ok := ipOosRst(ipPath); ok {
for _, abandonedClient := range abandonedClients {
abandonedClient.Send(&parsedPacket{
packet: rstPacket,
ipPath: ipPath,
}, 0)
}
}
}
for _, p := range receivePackets {
self.receivePacketCallback(p.Source, p.ProvideMode, p.IpPath, p.Packet)
}
for _, p := range returnPackets {
MessagePoolReturn(p.Packet)
}
}
func (self *RemoteUserNatMultiClient) scheduleCompleteRace(
ipPath *IpPath,
race *multiClientChannelUpdateRace,
earlyComplete <-chan struct{},
) {
go HandleError(func() {
// wait for the race to finish, then choose
select {
case <-race.ctx.Done():
return
case <-earlyComplete:
case <-time.After(self.settings.MultiRaceSetOnResponseTimeout):
}
var abandonedClients []*multiClientChannel
var receivePackets []*receivePacket
var returnPackets []*receivePacket
self.updateClientPath(ipPath, func(update *multiClientChannelUpdate) {
self.stateLock.Lock()
defer self.stateLock.Unlock()
if update.client == nil && update.race == race {
// weighted shuffle clients by rtt
orderedClients := []*multiClientChannel{}
weights := map[*multiClientChannel]float32{}
for client, state := range race.clientStates {
if 0 < len(state.packets) {
orderedClients = append(orderedClients, client)
rtt := state.receiveTime.Sub(state.sendTime)
weights[client] = float32(rtt / time.Millisecond)
}
}
WeightedShuffleWithEntropy(orderedClients, weights, self.settings.StatsWindowEntropy)
// the last is the lowest rtt
client := orderedClients[len(orderedClients)-1]
for abandonedClient, abandonedState := range race.clientStates {
if abandonedClient != client {
abandonedClients = append(abandonedClients, abandonedClient)
for _, p := range abandonedState.packets {
if p.Pooled {
p.Pooled = false
returnPackets = append(returnPackets, p)
}
}
}
}
update.clearRace()
update.client = client
receivePackets = race.clientStates[update.client].packets
for _, p := range receivePackets {
if p.Pooled {
p.Pooled = false
returnPackets = append(returnPackets, p)
}
}
}
// else a client was already chosen, ignore
})
if 0 < len(abandonedClients) {
if rstPacket, ok := ipOosRst(ipPath); ok {
for _, abandonedClient := range abandonedClients {
abandonedClient.Send(&parsedPacket{
packet: rstPacket,
ipPath: ipPath,
}, 0)
}
}
}
for _, p := range receivePackets {
self.receivePacketCallback(p.Source, p.ProvideMode, p.IpPath, p.Packet)
}
for _, p := range returnPackets {
MessagePoolReturn(p.Packet)
}
})
}
func (self *RemoteUserNatMultiClient) Shuffle() {
for _, window := range self.windows {
window.shuffle()
}
}
func (self *RemoteUserNatMultiClient) Close() {
self.cancel()
for _, window := range self.windows {
window.Close()
}
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
for _, update := range self.ip4PathUpdates {
update.Close()
}
for _, update := range self.ip6PathUpdates {
update.Close()
}
clear(self.ip4PathUpdates)
clear(self.ip6PathUpdates)
// clear(self.updateIp4Paths)
// clear(self.updateIp6Paths)
// clear(clientUpdates)
}()
}