-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
649 lines (557 loc) · 14.3 KB
/
connection.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
package kcp
import (
"io"
"net"
"runtime"
"sync"
"sync/atomic"
"time"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/signal"
"v2ray.com/core/common/signal/semaphore"
)
var (
ErrIOTimeout = newError("Read/Write timeout")
ErrClosedListener = newError("Listener closed.")
ErrClosedConnection = newError("Connection closed.")
)
// State of the connection
type State int32
// Is returns true if current State is one of the candidates.
func (s State) Is(states ...State) bool {
for _, state := range states {
if s == state {
return true
}
}
return false
}
const (
StateActive State = 0 // Connection is active
StateReadyToClose State = 1 // Connection is closed locally
StatePeerClosed State = 2 // Connection is closed on remote
StateTerminating State = 3 // Connection is ready to be destroyed locally
StatePeerTerminating State = 4 // Connection is ready to be destroyed on remote
StateTerminated State = 5 // Connection is destroyed.
)
func nowMillisec() int64 {
now := time.Now()
return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}
type RoundTripInfo struct {
sync.RWMutex
variation uint32
srtt uint32
rto uint32
minRtt uint32
updatedTimestamp uint32
}
func (info *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
info.Lock()
defer info.Unlock()
if current-info.updatedTimestamp < 3000 {
return
}
info.updatedTimestamp = current
info.rto = rto
}
func (info *RoundTripInfo) Update(rtt uint32, current uint32) {
if rtt > 0x7FFFFFFF {
return
}
info.Lock()
defer info.Unlock()
// https://tools.ietf.org/html/rfc6298
if info.srtt == 0 {
info.srtt = rtt
info.variation = rtt / 2
} else {
delta := rtt - info.srtt
if info.srtt > rtt {
delta = info.srtt - rtt
}
info.variation = (3*info.variation + delta) / 4
info.srtt = (7*info.srtt + rtt) / 8
if info.srtt < info.minRtt {
info.srtt = info.minRtt
}
}
var rto uint32
if info.minRtt < 4*info.variation {
rto = info.srtt + 4*info.variation
} else {
rto = info.srtt + info.variation
}
if rto > 10000 {
rto = 10000
}
info.rto = rto * 5 / 4
info.updatedTimestamp = current
}
func (info *RoundTripInfo) Timeout() uint32 {
info.RLock()
defer info.RUnlock()
return info.rto
}
func (info *RoundTripInfo) SmoothedTime() uint32 {
info.RLock()
defer info.RUnlock()
return info.srtt
}
type Updater struct {
interval int64
shouldContinue func() bool
shouldTerminate func() bool
updateFunc func()
notifier *semaphore.Instance
}
func NewUpdater(interval uint32, shouldContinue func() bool, shouldTerminate func() bool, updateFunc func()) *Updater {
u := &Updater{
interval: int64(time.Duration(interval) * time.Millisecond),
shouldContinue: shouldContinue,
shouldTerminate: shouldTerminate,
updateFunc: updateFunc,
notifier: semaphore.New(1),
}
return u
}
func (u *Updater) WakeUp() {
select {
case <-u.notifier.Wait():
go u.run()
default:
}
}
func (u *Updater) run() {
defer u.notifier.Signal()
if u.shouldTerminate() {
return
}
ticker := time.NewTicker(u.Interval())
for u.shouldContinue() {
u.updateFunc()
<-ticker.C
}
ticker.Stop()
}
func (u *Updater) Interval() time.Duration {
return time.Duration(atomic.LoadInt64(&u.interval))
}
func (u *Updater) SetInterval(d time.Duration) {
atomic.StoreInt64(&u.interval, int64(d))
}
type ConnMetadata struct {
LocalAddr net.Addr
RemoteAddr net.Addr
Conversation uint16
}
// Connection is a KCP connection over UDP.
type Connection struct {
meta ConnMetadata
closer io.Closer
rd time.Time
wd time.Time // write deadline
since int64
dataInput *signal.Notifier
dataOutput *signal.Notifier
Config *Config
state State
stateBeginTime uint32
lastIncomingTime uint32
lastPingTime uint32
mss uint32
roundTrip *RoundTripInfo
receivingWorker *ReceivingWorker
sendingWorker *SendingWorker
output SegmentWriter
dataUpdater *Updater
pingUpdater *Updater
}
// NewConnection create a new KCP connection between local and remote.
func NewConnection(meta ConnMetadata, writer PacketWriter, closer io.Closer, config *Config) *Connection {
newError("#", meta.Conversation, " creating connection to ", meta.RemoteAddr).WriteToLog()
conn := &Connection{
meta: meta,
closer: closer,
since: nowMillisec(),
dataInput: signal.NewNotifier(),
dataOutput: signal.NewNotifier(),
Config: config,
output: NewRetryableWriter(NewSegmentWriter(writer)),
mss: config.GetMTUValue() - uint32(writer.Overhead()) - DataSegmentOverhead,
roundTrip: &RoundTripInfo{
rto: 100,
minRtt: config.GetTTIValue(),
},
}
conn.receivingWorker = NewReceivingWorker(conn)
conn.sendingWorker = NewSendingWorker(conn)
isTerminating := func() bool {
return conn.State().Is(StateTerminating, StateTerminated)
}
isTerminated := func() bool {
return conn.State() == StateTerminated
}
conn.dataUpdater = NewUpdater(
config.GetTTIValue(),
func() bool {
return !isTerminating() && (conn.sendingWorker.UpdateNecessary() || conn.receivingWorker.UpdateNecessary())
},
isTerminating,
conn.updateTask)
conn.pingUpdater = NewUpdater(
5000, // 5 seconds
func() bool { return !isTerminated() },
isTerminated,
conn.updateTask)
conn.pingUpdater.WakeUp()
return conn
}
func (c *Connection) Elapsed() uint32 {
return uint32(nowMillisec() - c.since)
}
// ReadMultiBuffer implements buf.Reader.
func (c *Connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
if c == nil {
return nil, io.EOF
}
for {
if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
return nil, io.EOF
}
mb := c.receivingWorker.ReadMultiBuffer()
if !mb.IsEmpty() {
c.dataUpdater.WakeUp()
return mb, nil
}
if c.State() == StatePeerTerminating {
return nil, io.EOF
}
if err := c.waitForDataInput(); err != nil {
return nil, err
}
}
}
func (c *Connection) waitForDataInput() error {
for i := 0; i < 16; i++ {
select {
case <-c.dataInput.Wait():
return nil
default:
runtime.Gosched()
}
}
duration := time.Second * 16
if !c.rd.IsZero() {
duration = time.Until(c.rd)
if duration < 0 {
return ErrIOTimeout
}
}
timeout := time.NewTimer(duration)
defer timeout.Stop()
select {
case <-c.dataInput.Wait():
case <-timeout.C:
if !c.rd.IsZero() && c.rd.Before(time.Now()) {
return ErrIOTimeout
}
}
return nil
}
// Read implements the Conn Read method.
func (c *Connection) Read(b []byte) (int, error) {
if c == nil {
return 0, io.EOF
}
for {
if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
return 0, io.EOF
}
nBytes := c.receivingWorker.Read(b)
if nBytes > 0 {
c.dataUpdater.WakeUp()
return nBytes, nil
}
if err := c.waitForDataInput(); err != nil {
return 0, err
}
}
}
func (c *Connection) waitForDataOutput() error {
for i := 0; i < 16; i++ {
select {
case <-c.dataOutput.Wait():
return nil
default:
runtime.Gosched()
}
}
duration := time.Second * 16
if !c.wd.IsZero() {
duration = time.Until(c.wd)
if duration < 0 {
return ErrIOTimeout
}
}
timeout := time.NewTimer(duration)
defer timeout.Stop()
select {
case <-c.dataOutput.Wait():
case <-timeout.C:
if !c.wd.IsZero() && c.wd.Before(time.Now()) {
return ErrIOTimeout
}
}
return nil
}
// Write implements io.Writer.
func (c *Connection) Write(b []byte) (int, error) {
// This involves multiple copies of the buffer. But we don't expect this method to be used often.
// Only wrapped connections such as TLS and WebSocket will call into this.
// TODO: improve effeciency.
var mb buf.MultiBuffer
common.Must2(mb.Write(b))
if err := c.WriteMultiBuffer(mb); err != nil {
return 0, err
}
return len(b), nil
}
// WriteMultiBuffer implements buf.Writer.
func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
defer mb.Release()
updatePending := false
defer func() {
if updatePending {
c.dataUpdater.WakeUp()
}
}()
for {
for {
if c == nil || c.State() != StateActive {
return io.ErrClosedPipe
}
if !c.sendingWorker.Push(&mb) {
break
}
updatePending = true
if mb.IsEmpty() {
return nil
}
}
if updatePending {
c.dataUpdater.WakeUp()
updatePending = false
}
if err := c.waitForDataOutput(); err != nil {
return err
}
}
}
func (c *Connection) SetState(state State) {
current := c.Elapsed()
atomic.StoreInt32((*int32)(&c.state), int32(state))
atomic.StoreUint32(&c.stateBeginTime, current)
newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
switch state {
case StateReadyToClose:
c.receivingWorker.CloseRead()
case StatePeerClosed:
c.sendingWorker.CloseWrite()
case StateTerminating:
c.receivingWorker.CloseRead()
c.sendingWorker.CloseWrite()
c.pingUpdater.SetInterval(time.Second)
case StatePeerTerminating:
c.sendingWorker.CloseWrite()
c.pingUpdater.SetInterval(time.Second)
case StateTerminated:
c.receivingWorker.CloseRead()
c.sendingWorker.CloseWrite()
c.pingUpdater.SetInterval(time.Second)
c.dataUpdater.WakeUp()
c.pingUpdater.WakeUp()
go c.Terminate()
}
}
// Close closes the connection.
func (c *Connection) Close() error {
if c == nil {
return ErrClosedConnection
}
c.dataInput.Signal()
c.dataOutput.Signal()
switch c.State() {
case StateReadyToClose, StateTerminating, StateTerminated:
return ErrClosedConnection
case StateActive:
c.SetState(StateReadyToClose)
case StatePeerClosed:
c.SetState(StateTerminating)
case StatePeerTerminating:
c.SetState(StateTerminated)
}
newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog()
return nil
}
// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
func (c *Connection) LocalAddr() net.Addr {
if c == nil {
return nil
}
return c.meta.LocalAddr
}
// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
func (c *Connection) RemoteAddr() net.Addr {
if c == nil {
return nil
}
return c.meta.RemoteAddr
}
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (c *Connection) SetDeadline(t time.Time) error {
if err := c.SetReadDeadline(t); err != nil {
return err
}
return c.SetWriteDeadline(t)
}
// SetReadDeadline implements the Conn SetReadDeadline method.
func (c *Connection) SetReadDeadline(t time.Time) error {
if c == nil || c.State() != StateActive {
return ErrClosedConnection
}
c.rd = t
return nil
}
// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (c *Connection) SetWriteDeadline(t time.Time) error {
if c == nil || c.State() != StateActive {
return ErrClosedConnection
}
c.wd = t
return nil
}
// kcp update, input loop
func (c *Connection) updateTask() {
c.flush()
}
func (c *Connection) Terminate() {
if c == nil {
return
}
newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog()
//v.SetState(StateTerminated)
c.dataInput.Signal()
c.dataOutput.Signal()
c.closer.Close()
c.sendingWorker.Release()
c.receivingWorker.Release()
}
func (c *Connection) HandleOption(opt SegmentOption) {
if (opt & SegmentOptionClose) == SegmentOptionClose {
c.OnPeerClosed()
}
}
func (c *Connection) OnPeerClosed() {
switch c.State() {
case StateReadyToClose:
c.SetState(StateTerminating)
case StateActive:
c.SetState(StatePeerClosed)
}
}
// Input when you received a low level packet (eg. UDP packet), call it
func (c *Connection) Input(segments []Segment) {
current := c.Elapsed()
atomic.StoreUint32(&c.lastIncomingTime, current)
for _, seg := range segments {
if seg.Conversation() != c.meta.Conversation {
break
}
switch seg := seg.(type) {
case *DataSegment:
c.HandleOption(seg.Option)
c.receivingWorker.ProcessSegment(seg)
if c.receivingWorker.IsDataAvailable() {
c.dataInput.Signal()
}
c.dataUpdater.WakeUp()
case *AckSegment:
c.HandleOption(seg.Option)
c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
c.dataOutput.Signal()
c.dataUpdater.WakeUp()
case *CmdOnlySegment:
c.HandleOption(seg.Option)
if seg.Command() == CommandTerminate {
switch c.State() {
case StateActive, StatePeerClosed:
c.SetState(StatePeerTerminating)
case StateReadyToClose:
c.SetState(StateTerminating)
case StateTerminating:
c.SetState(StateTerminated)
}
}
if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
c.dataInput.Signal()
c.dataOutput.Signal()
}
c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
c.receivingWorker.ProcessSendingNext(seg.SendingNext)
c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
seg.Release()
default:
}
}
}
func (c *Connection) flush() {
current := c.Elapsed()
if c.State() == StateTerminated {
return
}
if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
c.Close()
}
if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
c.SetState(StateTerminating)
}
if c.State() == StateTerminating {
newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
c.Ping(current, CommandTerminate)
if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
c.SetState(StateTerminated)
}
return
}
if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
c.SetState(StateTerminating)
}
if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
c.SetState(StateTerminating)
}
// flush acknowledges
c.receivingWorker.Flush(current)
c.sendingWorker.Flush(current)
if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
c.Ping(current, CommandPing)
}
}
func (c *Connection) State() State {
return State(atomic.LoadInt32((*int32)(&c.state)))
}
func (c *Connection) Ping(current uint32, cmd Command) {
seg := NewCmdOnlySegment()
seg.Conv = c.meta.Conversation
seg.Cmd = cmd
seg.ReceivingNext = c.receivingWorker.NextNumber()
seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
seg.PeerRTO = c.roundTrip.Timeout()
if c.State() == StateReadyToClose {
seg.Option = SegmentOptionClose
}
c.output.Write(seg)
atomic.StoreUint32(&c.lastPingTime, current)
seg.Release()
}