You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/transport/internet/kcp/connection.go

590 lines
13 KiB

package kcp
import (
"io"
"net"
"sync"
"sync/atomic"
"time"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/log"
"v2ray.com/core/common/predicate"
"v2ray.com/core/transport/internet/internal"
)
var (
ErrIOTimeout = errors.New("Read/Write timeout")
ErrClosedListener = errors.New("Listener closed.")
ErrClosedConnection = errors.New("Connection closed.")
)
type State int32
8 years ago
func (v State) Is(states ...State) bool {
for _, state := range states {
8 years ago
if v == state {
return true
}
}
return false
}
const (
StateActive State = 0
StateReadyToClose State = 1
StatePeerClosed State = 2
StateTerminating State = 3
StatePeerTerminating State = 4
StateTerminated State = 5
)
const (
headerSize uint32 = 2
)
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
}
8 years ago
func (v *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
v.Lock()
defer v.Unlock()
8 years ago
if current-v.updatedTimestamp < 3000 {
return
}
8 years ago
v.updatedTimestamp = current
v.rto = rto
}
8 years ago
func (v *RoundTripInfo) Update(rtt uint32, current uint32) {
if rtt > 0x7FFFFFFF {
return
}
8 years ago
v.Lock()
defer v.Unlock()
// https://tools.ietf.org/html/rfc6298
8 years ago
if v.srtt == 0 {
v.srtt = rtt
v.variation = rtt / 2
} else {
8 years ago
delta := rtt - v.srtt
if v.srtt > rtt {
delta = v.srtt - rtt
}
8 years ago
v.variation = (3*v.variation + delta) / 4
v.srtt = (7*v.srtt + rtt) / 8
if v.srtt < v.minRtt {
v.srtt = v.minRtt
}
}
var rto uint32
8 years ago
if v.minRtt < 4*v.variation {
rto = v.srtt + 4*v.variation
} else {
8 years ago
rto = v.srtt + v.variation
}
if rto > 10000 {
rto = 10000
}
8 years ago
v.rto = rto * 5 / 4
v.updatedTimestamp = current
}
8 years ago
func (v *RoundTripInfo) Timeout() uint32 {
v.RLock()
defer v.RUnlock()
8 years ago
return v.rto
}
8 years ago
func (v *RoundTripInfo) SmoothedTime() uint32 {
v.RLock()
defer v.RUnlock()
8 years ago
return v.srtt
}
type Updater struct {
interval time.Duration
shouldContinue predicate.Predicate
shouldTerminate predicate.Predicate
updateFunc func()
notifier chan bool
}
func NewUpdater(interval uint32, shouldContinue predicate.Predicate, shouldTerminate predicate.Predicate, updateFunc func()) *Updater {
u := &Updater{
interval: time.Duration(interval) * time.Millisecond,
shouldContinue: shouldContinue,
shouldTerminate: shouldTerminate,
updateFunc: updateFunc,
notifier: make(chan bool, 1),
}
go u.Run()
return u
}
8 years ago
func (v *Updater) WakeUp() {
select {
8 years ago
case v.notifier <- true:
default:
}
}
8 years ago
func (v *Updater) Run() {
for <-v.notifier {
if v.shouldTerminate() {
return
}
8 years ago
for v.shouldContinue() {
v.updateFunc()
time.Sleep(v.interval)
}
}
}
type SystemConnection interface {
net.Conn
Id() internal.ConnectionId
Reset(func([]Segment))
Overhead() int
}
9 years ago
// Connection is a KCP connection over UDP.
type Connection struct {
conn SystemConnection
connRecycler internal.ConnectionRecyler
rd time.Time
wd time.Time // write deadline
since int64
dataInput chan bool
dataOutput chan bool
Config *Config
conv uint16
state State
stateBeginTime uint32
lastIncomingTime uint32
lastPingTime uint32
mss uint32
roundTrip *RoundTripInfo
receivingWorker *ReceivingWorker
sendingWorker *SendingWorker
output *BufferedSegmentWriter
dataUpdater *Updater
pingUpdater *Updater
reusable bool
}
9 years ago
// NewConnection create a new KCP connection between local and remote.
func NewConnection(conv uint16, sysConn SystemConnection, recycler internal.ConnectionRecyler, config *Config) *Connection {
log.Info("KCP|Connection: creating connection ", conv)
conn := &Connection{
conv: conv,
conn: sysConn,
connRecycler: recycler,
since: nowMillisec(),
dataInput: make(chan bool, 1),
dataOutput: make(chan bool, 1),
Config: config,
output: NewSegmentWriter(sysConn, config.GetMtu().GetValue()-uint32(sysConn.Overhead())),
mss: config.GetMtu().GetValue() - uint32(sysConn.Overhead()) - DataSegmentOverhead,
roundTrip: &RoundTripInfo{
rto: 100,
minRtt: config.Tti.GetValue(),
},
}
sysConn.Reset(conn.Input)
conn.receivingWorker = NewReceivingWorker(conn)
conn.sendingWorker = NewSendingWorker(conn)
8 years ago
isTerminating := func() bool {
return conn.State().Is(StateTerminating, StateTerminated)
}
isTerminated := func() bool {
return conn.State() == StateTerminated
}
conn.dataUpdater = NewUpdater(
config.Tti.GetValue(),
predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
8 years ago
isTerminating,
conn.updateTask)
conn.pingUpdater = NewUpdater(
5000, // 5 seconds
8 years ago
predicate.Not(isTerminated),
isTerminated,
conn.updateTask)
conn.pingUpdater.WakeUp()
9 years ago
return conn
}
8 years ago
func (v *Connection) Elapsed() uint32 {
return uint32(nowMillisec() - v.since)
}
func (v *Connection) OnDataInput() {
select {
case v.dataInput <- true:
default:
}
}
func (v *Connection) OnDataOutput() {
select {
case v.dataOutput <- true:
default:
}
}
// Read implements the Conn Read method.
8 years ago
func (v *Connection) Read(b []byte) (int, error) {
if v == nil {
return 0, io.EOF
}
for {
8 years ago
if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
return 0, io.EOF
}
8 years ago
nBytes := v.receivingWorker.Read(b)
if nBytes > 0 {
return nBytes, nil
}
8 years ago
if v.State() == StatePeerTerminating {
return 0, io.EOF
}
duration := time.Duration(time.Minute)
8 years ago
if !v.rd.IsZero() {
duration = v.rd.Sub(time.Now())
if duration < 0 {
return 0, ErrIOTimeout
}
}
select {
case <-v.dataInput:
case <-time.After(duration):
if !v.rd.IsZero() && v.rd.Before(time.Now()) {
return 0, ErrIOTimeout
}
}
}
}
// Write implements the Conn Write method.
8 years ago
func (v *Connection) Write(b []byte) (int, error) {
totalWritten := 0
for {
8 years ago
if v == nil || v.State() != StateActive {
return totalWritten, io.ErrClosedPipe
}
8 years ago
nBytes := v.sendingWorker.Push(b[totalWritten:])
v.dataUpdater.WakeUp()
if nBytes > 0 {
totalWritten += nBytes
if totalWritten == len(b) {
return totalWritten, nil
}
}
duration := time.Duration(time.Minute)
if !v.rd.IsZero() {
duration = v.wd.Sub(time.Now())
if duration < 0 {
return totalWritten, ErrIOTimeout
}
}
select {
case <-v.dataOutput:
case <-time.After(duration):
if !v.wd.IsZero() && v.wd.Before(time.Now()) {
return totalWritten, ErrIOTimeout
}
}
}
}
8 years ago
func (v *Connection) SetState(state State) {
current := v.Elapsed()
atomic.StoreInt32((*int32)(&v.state), int32(state))
atomic.StoreUint32(&v.stateBeginTime, current)
log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current)
switch state {
case StateReadyToClose:
8 years ago
v.receivingWorker.CloseRead()
case StatePeerClosed:
8 years ago
v.sendingWorker.CloseWrite()
case StateTerminating:
8 years ago
v.receivingWorker.CloseRead()
v.sendingWorker.CloseWrite()
v.pingUpdater.interval = time.Second
case StatePeerTerminating:
8 years ago
v.sendingWorker.CloseWrite()
v.pingUpdater.interval = time.Second
case StateTerminated:
8 years ago
v.receivingWorker.CloseRead()
v.sendingWorker.CloseWrite()
v.pingUpdater.interval = time.Second
v.dataUpdater.WakeUp()
v.pingUpdater.WakeUp()
go v.Terminate()
}
}
// Close closes the connection.
8 years ago
func (v *Connection) Close() error {
if v == nil {
return ErrClosedConnection
}
v.OnDataInput()
v.OnDataOutput()
8 years ago
state := v.State()
if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
return ErrClosedConnection
9 years ago
}
8 years ago
log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr())
9 years ago
if state == StateActive {
8 years ago
v.SetState(StateReadyToClose)
}
if state == StatePeerClosed {
8 years ago
v.SetState(StateTerminating)
}
if state == StatePeerTerminating {
8 years ago
v.SetState(StateTerminated)
}
return nil
}
// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
8 years ago
func (v *Connection) LocalAddr() net.Addr {
if v == nil {
9 years ago
return nil
}
8 years ago
return v.conn.LocalAddr()
}
// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
8 years ago
func (v *Connection) RemoteAddr() net.Addr {
if v == nil {
9 years ago
return nil
}
8 years ago
return v.conn.RemoteAddr()
9 years ago
}
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
8 years ago
func (v *Connection) SetDeadline(t time.Time) error {
if err := v.SetReadDeadline(t); err != nil {
9 years ago
return err
}
8 years ago
if err := v.SetWriteDeadline(t); err != nil {
9 years ago
return err
9 years ago
}
return nil
}
// SetReadDeadline implements the Conn SetReadDeadline method.
8 years ago
func (v *Connection) SetReadDeadline(t time.Time) error {
if v == nil || v.State() != StateActive {
return ErrClosedConnection
9 years ago
}
8 years ago
v.rd = t
return nil
}
// SetWriteDeadline implements the Conn SetWriteDeadline method.
8 years ago
func (v *Connection) SetWriteDeadline(t time.Time) error {
if v == nil || v.State() != StateActive {
return ErrClosedConnection
9 years ago
}
8 years ago
v.wd = t
return nil
}
// kcp update, input loop
8 years ago
func (v *Connection) updateTask() {
v.flush()
}
8 years ago
func (v *Connection) Reusable() bool {
return v.Config.ConnectionReuse.IsEnabled() && v.reusable
}
8 years ago
func (v *Connection) SetReusable(b bool) {
v.reusable = b
}
8 years ago
func (v *Connection) Terminate() {
if v == nil {
return
}
8 years ago
log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr())
8 years ago
//v.SetState(StateTerminated)
v.OnDataInput()
v.OnDataOutput()
8 years ago
if v.Config.ConnectionReuse.IsEnabled() && v.reusable {
v.connRecycler.Put(v.conn.Id(), v.conn)
} else {
8 years ago
v.conn.Close()
}
8 years ago
v.sendingWorker.Release()
v.receivingWorker.Release()
}
8 years ago
func (v *Connection) HandleOption(opt SegmentOption) {
if (opt & SegmentOptionClose) == SegmentOptionClose {
8 years ago
v.OnPeerClosed()
}
}
8 years ago
func (v *Connection) OnPeerClosed() {
state := v.State()
if state == StateReadyToClose {
8 years ago
v.SetState(StateTerminating)
}
if state == StateActive {
8 years ago
v.SetState(StatePeerClosed)
}
}
// Input when you received a low level packet (eg. UDP packet), call it
func (v *Connection) Input(segments []Segment) {
8 years ago
current := v.Elapsed()
atomic.StoreUint32(&v.lastIncomingTime, current)
for _, seg := range segments {
8 years ago
if seg.Conversation() != v.conv {
break
}
switch seg := seg.(type) {
case *DataSegment:
8 years ago
v.HandleOption(seg.Option)
v.receivingWorker.ProcessSegment(seg)
if seg.Number == v.receivingWorker.nextNumber {
v.OnDataInput()
}
8 years ago
v.dataUpdater.WakeUp()
case *AckSegment:
8 years ago
v.HandleOption(seg.Option)
v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
v.OnDataOutput()
8 years ago
v.dataUpdater.WakeUp()
case *CmdOnlySegment:
8 years ago
v.HandleOption(seg.Option)
if seg.Command() == CommandTerminate {
8 years ago
state := v.State()
if state == StateActive ||
state == StatePeerClosed {
8 years ago
v.SetState(StatePeerTerminating)
} else if state == StateReadyToClose {
8 years ago
v.SetState(StateTerminating)
} else if state == StateTerminating {
8 years ago
v.SetState(StateTerminated)
}
}
8 years ago
v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
v.receivingWorker.ProcessSendingNext(seg.SendingNext)
v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
seg.Release()
default:
}
}
}
8 years ago
func (v *Connection) flush() {
current := v.Elapsed()
8 years ago
if v.State() == StateTerminated {
return
}
8 years ago
if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
v.Close()
}
8 years ago
if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
v.SetState(StateTerminating)
}
8 years ago
if v.State() == StateTerminating {
log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.")
v.Ping(current, CommandTerminate)
v.output.Flush()
8 years ago
if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
v.SetState(StateTerminated)
}
return
}
8 years ago
if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
v.SetState(StateTerminating)
}
8 years ago
if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
v.SetState(StateTerminating)
}
// flush acknowledges
8 years ago
v.receivingWorker.Flush(current)
v.sendingWorker.Flush(current)
8 years ago
if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
v.Ping(current, CommandPing)
}
// flash remain segments
8 years ago
v.output.Flush()
}
8 years ago
func (v *Connection) State() State {
return State(atomic.LoadInt32((*int32)(&v.state)))
}
8 years ago
func (v *Connection) Ping(current uint32, cmd Command) {
seg := NewCmdOnlySegment()
8 years ago
seg.Conv = v.conv
seg.Cmd = cmd
8 years ago
seg.ReceivinNext = v.receivingWorker.nextNumber
seg.SendingNext = v.sendingWorker.firstUnacknowledged
seg.PeerRTO = v.roundTrip.Timeout()
if v.State() == StateReadyToClose {
seg.Option = SegmentOptionClose
}
8 years ago
v.output.Write(seg)
atomic.StoreUint32(&v.lastPingTime, current)
seg.Release()
}