1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-06 10:20:44 -05:00
v2fly/transport/internet/kcp/connection.go

516 lines
12 KiB
Go
Raw Normal View History

2016-06-17 10:51:41 -04:00
package kcp
import (
"errors"
"io"
"net"
"sync"
2016-07-05 17:53:46 -04:00
"sync/atomic"
2016-06-17 10:51:41 -04:00
"time"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
)
var (
2016-06-17 17:50:08 -04:00
errTimeout = errors.New("i/o timeout")
errBrokenPipe = errors.New("broken pipe")
errClosedListener = errors.New("Listener closed.")
errClosedConnection = errors.New("Connection closed.")
2016-06-17 10:51:41 -04:00
)
2016-07-05 17:53:46 -04:00
type State int32
2016-07-05 17:02:52 -04:00
const (
StateActive State = 0
StateReadyToClose State = 1
StatePeerClosed State = 2
StateTerminating State = 3
StatePeerTerminating State = 4
StateTerminated State = 5
2016-07-05 17:02:52 -04:00
)
2016-06-17 10:51:41 -04:00
const (
2016-06-25 15:35:18 -04:00
headerSize uint32 = 2
2016-06-17 10:51:41 -04:00
)
func nowMillisec() int64 {
now := time.Now()
return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}
2016-07-05 17:53:46 -04:00
type RountTripInfo struct {
sync.RWMutex
variation uint32
srtt uint32
rto uint32
minRtt uint32
}
func (this *RountTripInfo) Update(rtt uint32) {
if rtt > 0x7FFFFFFF {
return
}
this.Lock()
defer this.Unlock()
// https://tools.ietf.org/html/rfc6298
if this.srtt == 0 {
this.srtt = rtt
this.variation = rtt / 2
} else {
delta := rtt - this.srtt
if this.srtt > rtt {
delta = this.srtt - rtt
}
this.variation = (3*this.variation + delta) / 4
this.srtt = (7*this.srtt + rtt) / 8
if this.srtt < this.minRtt {
this.srtt = this.minRtt
}
}
var rto uint32
if this.minRtt < 4*this.variation {
rto = this.srtt + 4*this.variation
} else {
rto = this.srtt + this.variation
}
if rto > 10000 {
rto = 10000
}
this.rto = rto * 3 / 2
}
func (this *RountTripInfo) Timeout() uint32 {
this.RLock()
defer this.RUnlock()
return this.rto
}
func (this *RountTripInfo) SmoothedTime() uint32 {
this.RLock()
defer this.RUnlock()
return this.srtt
}
2016-06-18 10:34:04 -04:00
// Connection is a KCP connection over UDP.
type Connection struct {
2016-07-14 11:39:12 -04:00
block Authenticator
local, remote net.Addr
rd time.Time
wd time.Time // write deadline
writer io.WriteCloser
since int64
dataInputCond *sync.Cond
dataOutputCond *sync.Cond
2016-07-05 17:02:52 -04:00
conv uint16
state State
stateBeginTime uint32
lastIncomingTime uint32
lastPingTime uint32
2016-07-05 17:53:46 -04:00
mss uint32
roundTrip *RountTripInfo
interval uint32
2016-07-05 17:02:52 -04:00
receivingWorker *ReceivingWorker
sendingWorker *SendingWorker
fastresend uint32
congestionControl bool
output *BufferedSegmentWriter
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
// NewConnection create a new KCP connection between local and remote.
2016-06-29 04:34:34 -04:00
func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
2016-07-11 11:24:35 -04:00
log.Info("KCP|Connection: creating connection ", conv)
2016-07-05 17:02:52 -04:00
2016-06-18 10:34:04 -04:00
conn := new(Connection)
conn.local = local
conn.remote = remote
conn.block = block
conn.writer = writerCloser
conn.since = nowMillisec()
2016-07-06 11:34:38 -04:00
conn.dataInputCond = sync.NewCond(new(sync.Mutex))
2016-07-14 11:39:12 -04:00
conn.dataOutputCond = sync.NewCond(new(sync.Mutex))
2016-06-17 10:51:41 -04:00
2016-06-29 04:34:34 -04:00
authWriter := &AuthenticationWriter{
Authenticator: block,
Writer: writerCloser,
}
2016-07-05 17:02:52 -04:00
conn.conv = conv
conn.output = NewSegmentWriter(authWriter)
conn.mss = authWriter.Mtu() - DataSegmentOverhead
2016-07-05 17:53:46 -04:00
conn.roundTrip = &RountTripInfo{
rto: 100,
minRtt: effectiveConfig.Tti,
}
2016-07-05 17:02:52 -04:00
conn.interval = effectiveConfig.Tti
conn.receivingWorker = NewReceivingWorker(conn)
conn.fastresend = 2
conn.congestionControl = effectiveConfig.Congestion
conn.sendingWorker = NewSendingWorker(conn)
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
go conn.updateTask()
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
return conn
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
func (this *Connection) Elapsed() uint32 {
2016-06-17 10:51:41 -04:00
return uint32(nowMillisec() - this.since)
}
// Read implements the Conn Read method.
2016-06-18 10:34:04 -04:00
func (this *Connection) Read(b []byte) (int, error) {
2016-07-05 17:02:52 -04:00
if this == nil {
2016-06-17 10:51:41 -04:00
return 0, io.EOF
}
2016-07-05 17:02:52 -04:00
2016-07-06 11:34:38 -04:00
for {
if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
return 0, io.EOF
}
nBytes := this.receivingWorker.Read(b)
if nBytes > 0 {
return nBytes, nil
}
2016-07-12 17:54:54 -04:00
if this.State() == StatePeerTerminating {
return 0, io.EOF
}
2016-07-06 11:34:38 -04:00
var timer *time.Timer
2016-07-12 06:54:09 -04:00
if !this.rd.IsZero() {
duration := this.rd.Sub(time.Now())
if duration <= 0 {
return 0, errTimeout
}
timer = time.AfterFunc(duration, this.dataInputCond.Signal)
2016-07-06 11:34:38 -04:00
}
this.dataInputCond.L.Lock()
this.dataInputCond.Wait()
this.dataInputCond.L.Unlock()
if timer != nil {
timer.Stop()
}
if !this.rd.IsZero() && this.rd.Before(time.Now()) {
return 0, errTimeout
}
2016-07-05 17:02:52 -04:00
}
2016-06-17 10:51:41 -04:00
}
// Write implements the Conn Write method.
2016-06-18 10:34:04 -04:00
func (this *Connection) Write(b []byte) (int, error) {
2016-07-05 17:02:52 -04:00
if this == nil || this.State() != StateActive {
2016-06-17 10:51:41 -04:00
return 0, io.ErrClosedPipe
}
2016-06-26 17:51:17 -04:00
totalWritten := 0
2016-06-17 10:51:41 -04:00
for {
2016-07-05 17:02:52 -04:00
if this == nil || this.State() != StateActive {
2016-06-26 17:51:17 -04:00
return totalWritten, io.ErrClosedPipe
2016-06-17 10:51:41 -04:00
}
2016-07-05 17:02:52 -04:00
nBytes := this.sendingWorker.Push(b[totalWritten:])
2016-06-26 17:51:17 -04:00
if nBytes > 0 {
totalWritten += nBytes
if totalWritten == len(b) {
return totalWritten, nil
}
2016-06-17 10:51:41 -04:00
}
2016-06-26 17:51:17 -04:00
2016-07-14 11:39:12 -04:00
var timer *time.Timer
if !this.wd.IsZero() {
duration := this.wd.Sub(time.Now())
if duration <= 0 {
return totalWritten, errTimeout
}
timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
}
this.dataOutputCond.L.Lock()
this.dataOutputCond.Wait()
this.dataOutputCond.L.Unlock()
if timer != nil {
timer.Stop()
}
2016-06-18 10:34:04 -04:00
if !this.wd.IsZero() && this.wd.Before(time.Now()) {
2016-06-26 17:51:17 -04:00
return totalWritten, errTimeout
2016-06-17 10:51:41 -04:00
}
}
}
2016-07-05 17:02:52 -04:00
func (this *Connection) SetState(state State) {
2016-07-11 11:24:35 -04:00
current := this.Elapsed()
2016-07-05 17:53:46 -04:00
atomic.StoreInt32((*int32)(&this.state), int32(state))
2016-07-11 11:24:35 -04:00
atomic.StoreUint32(&this.stateBeginTime, current)
2016-07-16 16:14:20 -04:00
log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)
2016-07-05 17:02:52 -04:00
switch state {
case StateReadyToClose:
this.receivingWorker.CloseRead()
case StatePeerClosed:
this.sendingWorker.CloseWrite()
case StateTerminating:
this.receivingWorker.CloseRead()
this.sendingWorker.CloseWrite()
case StatePeerTerminating:
this.sendingWorker.CloseWrite()
2016-07-05 17:02:52 -04:00
case StateTerminated:
this.receivingWorker.CloseRead()
this.sendingWorker.CloseWrite()
}
}
2016-06-17 10:51:41 -04:00
// Close closes the connection.
2016-06-18 10:34:04 -04:00
func (this *Connection) Close() error {
2016-07-05 17:02:52 -04:00
if this == nil {
return errClosedConnection
}
2016-07-06 11:34:38 -04:00
this.dataInputCond.Broadcast()
2016-07-14 11:39:12 -04:00
this.dataOutputCond.Broadcast()
2016-07-06 11:34:38 -04:00
2016-07-05 17:02:52 -04:00
state := this.State()
if state == StateReadyToClose ||
state == StateTerminating ||
state == StateTerminated {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-07-11 11:24:35 -04:00
log.Info("KCP|Connection: Closing connection to ", this.remote)
2016-06-18 10:34:04 -04:00
2016-07-05 17:02:52 -04:00
if state == StateActive {
this.SetState(StateReadyToClose)
}
if state == StatePeerClosed {
this.SetState(StateTerminating)
}
if state == StatePeerTerminating {
this.SetState(StateTerminated)
}
2016-06-17 10:51:41 -04:00
return nil
}
// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
2016-06-18 10:34:04 -04:00
func (this *Connection) LocalAddr() net.Addr {
if this == nil {
2016-06-17 17:50:08 -04:00
return nil
}
2016-06-18 10:34:04 -04:00
return this.local
2016-06-17 10:51:41 -04:00
}
// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
2016-06-18 10:34:04 -04:00
func (this *Connection) RemoteAddr() net.Addr {
if this == nil {
2016-06-17 17:50:08 -04:00
return nil
}
2016-06-18 10:34:04 -04:00
return this.remote
2016-06-17 17:50:08 -04:00
}
2016-06-17 10:51:41 -04:00
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
2016-06-18 10:34:04 -04:00
func (this *Connection) SetDeadline(t time.Time) error {
2016-06-30 08:51:49 -04:00
if err := this.SetReadDeadline(t); err != nil {
return err
}
if err := this.SetWriteDeadline(t); err != nil {
return err
2016-06-17 17:50:08 -04:00
}
2016-06-17 10:51:41 -04:00
return nil
}
// SetReadDeadline implements the Conn SetReadDeadline method.
2016-06-18 10:34:04 -04:00
func (this *Connection) SetReadDeadline(t time.Time) error {
2016-07-05 17:02:52 -04:00
if this == nil || this.State() != StateActive {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-07-06 11:34:38 -04:00
this.rd = t
2016-06-17 10:51:41 -04:00
return nil
}
// SetWriteDeadline implements the Conn SetWriteDeadline method.
2016-06-18 10:34:04 -04:00
func (this *Connection) SetWriteDeadline(t time.Time) error {
2016-07-05 17:02:52 -04:00
if this == nil || this.State() != StateActive {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-06-18 10:34:04 -04:00
this.wd = t
2016-06-17 10:51:41 -04:00
return nil
}
// kcp update, input loop
2016-06-18 10:34:04 -04:00
func (this *Connection) updateTask() {
2016-07-05 17:02:52 -04:00
for this.State() != StateTerminated {
this.flush()
2016-06-29 04:34:34 -04:00
interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
2016-07-05 17:02:52 -04:00
if this.State() == StateTerminating {
2016-06-29 04:34:34 -04:00
interval = time.Second
}
time.Sleep(interval)
2016-06-17 10:51:41 -04:00
}
2016-06-29 04:34:34 -04:00
this.Terminate()
2016-06-17 10:51:41 -04:00
}
2016-07-12 11:11:36 -04:00
func (this *Connection) FetchInputFrom(conn io.Reader) {
2016-06-17 10:51:41 -04:00
go func() {
2016-07-16 16:08:59 -04:00
payload := alloc.NewLocalBuffer(2048)
2016-07-12 08:32:17 -04:00
defer payload.Release()
2016-06-17 10:51:41 -04:00
for {
2016-07-12 08:32:17 -04:00
payload.Reset()
2016-06-17 10:51:41 -04:00
nBytes, err := conn.Read(payload.Value)
if err != nil {
return
}
payload.Slice(0, nBytes)
if this.block.Open(payload) {
2016-07-05 17:02:52 -04:00
this.Input(payload.Value)
2016-06-17 10:51:41 -04:00
}
}
}()
}
2016-06-18 10:34:04 -04:00
func (this *Connection) Reusable() bool {
2016-06-17 10:51:41 -04:00
return false
}
2016-06-18 10:34:04 -04:00
func (this *Connection) SetReusable(b bool) {}
2016-06-29 04:34:34 -04:00
func (this *Connection) Terminate() {
if this == nil || this.writer == nil {
return
}
2016-07-11 11:24:35 -04:00
log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
2016-06-29 04:34:34 -04:00
this.writer.Close()
}
2016-07-05 17:02:52 -04:00
func (this *Connection) HandleOption(opt SegmentOption) {
if (opt & SegmentOptionClose) == SegmentOptionClose {
this.OnPeerClosed()
}
}
func (this *Connection) OnPeerClosed() {
state := this.State()
if state == StateReadyToClose {
this.SetState(StateTerminating)
}
if state == StateActive {
this.SetState(StatePeerClosed)
}
}
// Input when you received a low level packet (eg. UDP packet), call it
2016-07-05 17:53:46 -04:00
func (this *Connection) Input(data []byte) int {
current := this.Elapsed()
atomic.StoreUint32(&this.lastIncomingTime, current)
2016-07-05 17:02:52 -04:00
var seg Segment
for {
seg, data = ReadSegment(data)
if seg == nil {
break
}
switch seg := seg.(type) {
case *DataSegment:
2016-07-14 16:52:00 -04:00
this.HandleOption(seg.Option)
2016-07-05 17:53:46 -04:00
this.receivingWorker.ProcessSegment(seg)
2016-07-06 11:34:38 -04:00
this.dataInputCond.Signal()
2016-07-05 17:02:52 -04:00
case *AckSegment:
2016-07-14 16:52:00 -04:00
this.HandleOption(seg.Option)
2016-07-05 17:53:46 -04:00
this.sendingWorker.ProcessSegment(current, seg)
2016-07-14 11:39:12 -04:00
this.dataOutputCond.Signal()
2016-07-05 17:02:52 -04:00
case *CmdOnlySegment:
2016-07-14 16:52:00 -04:00
this.HandleOption(seg.Option)
if seg.Command == CommandTerminate {
2016-07-05 17:53:46 -04:00
state := this.State()
if state == StateActive ||
state == StatePeerClosed {
this.SetState(StatePeerTerminating)
} else if state == StateReadyToClose {
2016-07-05 17:53:46 -04:00
this.SetState(StateTerminating)
} else if state == StateTerminating {
this.SetState(StateTerminated)
2016-07-05 17:02:52 -04:00
}
}
2016-07-05 17:53:46 -04:00
this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
this.receivingWorker.ProcessSendingNext(seg.SendingNext)
2016-07-13 17:15:40 -04:00
seg.Release()
2016-07-05 17:02:52 -04:00
default:
}
}
return 0
}
func (this *Connection) flush() {
current := this.Elapsed()
2016-07-05 17:53:46 -04:00
if this.State() == StateTerminated {
2016-07-05 17:02:52 -04:00
return
}
2016-07-12 08:23:42 -04:00
if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
2016-07-05 17:02:52 -04:00
this.Close()
}
2016-07-12 17:54:54 -04:00
if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
this.SetState(StateTerminating)
}
2016-07-05 17:02:52 -04:00
2016-07-05 17:53:46 -04:00
if this.State() == StateTerminating {
2016-07-12 17:54:54 -04:00
log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
seg := NewCmdOnlySegment()
defer seg.Release()
seg.Conv = this.conv
2016-07-14 16:52:00 -04:00
seg.Command = CommandTerminate
2016-07-12 17:54:54 -04:00
this.output.Write(seg)
2016-07-05 17:02:52 -04:00
this.output.Flush()
2016-07-12 08:23:42 -04:00
if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
2016-07-05 17:02:52 -04:00
this.SetState(StateTerminated)
}
return
}
if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 {
this.SetState(StateTerminating)
}
2016-07-05 17:02:52 -04:00
2016-07-12 08:23:42 -04:00
if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
2016-07-05 17:02:52 -04:00
this.SetState(StateTerminating)
}
// flush acknowledges
this.receivingWorker.Flush(current)
this.sendingWorker.Flush(current)
2016-07-12 08:23:42 -04:00
if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
2016-07-05 17:02:52 -04:00
seg := NewCmdOnlySegment()
seg.Conv = this.conv
2016-07-14 16:52:00 -04:00
seg.Command = CommandPing
2016-07-05 17:02:52 -04:00
seg.ReceivinNext = this.receivingWorker.nextNumber
seg.SendingNext = this.sendingWorker.firstUnacknowledged
2016-07-05 17:53:46 -04:00
if this.State() == StateReadyToClose {
2016-07-14 16:52:00 -04:00
seg.Option = SegmentOptionClose
2016-07-05 17:02:52 -04:00
}
this.output.Write(seg)
this.lastPingTime = current
2016-07-12 11:56:36 -04:00
this.sendingWorker.MarkPingNecessary(false)
this.receivingWorker.MarkPingNecessary(false)
2016-07-05 17:02:52 -04:00
seg.Release()
}
// flash remain segments
this.output.Flush()
}
func (this *Connection) State() State {
2016-07-05 17:53:46 -04:00
return State(atomic.LoadInt32((*int32)(&this.state)))
2016-07-05 17:02:52 -04:00
}