1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 09:17:55 -04:00
v2fly/transport/internet/kcp/connection.go

596 lines
14 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"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/alloc"
"v2ray.com/core/common/log"
"v2ray.com/core/common/predicate"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/transport/internet"
2016-06-17 10:51:41 -04:00
)
var (
2016-08-07 09:31:24 -04:00
ErrIOTimeout = errors.New("Read/Write timeout")
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
2016-07-26 15:34:00 -04:00
func (this State) Is(states ...State) bool {
for _, state := range states {
if this == state {
return true
}
}
return false
}
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-08-05 15:03:44 -04:00
type RoundTripInfo struct {
2016-07-05 17:53:46 -04:00
sync.RWMutex
variation uint32
srtt uint32
rto uint32
minRtt uint32
updatedTimestamp uint32
2016-07-05 17:53:46 -04:00
}
2016-08-05 15:03:44 -04:00
func (this *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
this.Lock()
defer this.Unlock()
2016-08-06 15:59:47 -04:00
if current-this.updatedTimestamp < 3000 {
return
}
this.updatedTimestamp = current
this.rto = rto
}
2016-08-05 15:03:44 -04:00
func (this *RoundTripInfo) Update(rtt uint32, current uint32) {
2016-07-05 17:53:46 -04:00
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
}
2016-10-11 07:17:57 -04:00
this.rto = rto * 5 / 4
this.updatedTimestamp = current
2016-07-05 17:53:46 -04:00
}
2016-08-05 15:03:44 -04:00
func (this *RoundTripInfo) Timeout() uint32 {
2016-07-05 17:53:46 -04:00
this.RLock()
defer this.RUnlock()
return this.rto
}
2016-08-05 15:03:44 -04:00
func (this *RoundTripInfo) SmoothedTime() uint32 {
2016-07-05 17:53:46 -04:00
this.RLock()
defer this.RUnlock()
return this.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
}
func (this *Updater) WakeUp() {
select {
case this.notifier <- true:
default:
}
}
func (this *Updater) Run() {
for <-this.notifier {
if this.shouldTerminate() {
return
}
for this.shouldContinue() {
this.updateFunc()
time.Sleep(this.interval)
}
}
}
2016-06-18 10:34:04 -04:00
// Connection is a KCP connection over UDP.
type Connection struct {
2016-08-06 15:59:22 -04:00
block internet.Authenticator
2016-07-14 11:39:12 -04:00
local, remote net.Addr
rd time.Time
wd time.Time // write deadline
writer io.WriteCloser
since int64
dataInputCond *sync.Cond
dataOutputCond *sync.Cond
2016-10-02 17:43:58 -04:00
Config *Config
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
2016-08-05 15:03:44 -04:00
roundTrip *RoundTripInfo
2016-07-05 17:53:46 -04:00
interval uint32
2016-07-05 17:02:52 -04:00
receivingWorker *ReceivingWorker
sendingWorker *SendingWorker
congestionControl bool
output *BufferedSegmentWriter
dataUpdater *Updater
pingUpdater *Updater
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-10-02 17:43:58 -04:00
func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block internet.Authenticator, config *Config) *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-10-02 17:43:58 -04:00
conn.Config = config
2016-06-17 10:51:41 -04:00
2016-06-29 04:34:34 -04:00
authWriter := &AuthenticationWriter{
Authenticator: block,
Writer: writerCloser,
2016-10-02 17:43:58 -04:00
Config: config,
2016-06-29 04:34:34 -04:00
}
2016-07-05 17:02:52 -04:00
conn.conv = conv
conn.output = NewSegmentWriter(authWriter)
conn.mss = authWriter.Mtu() - DataSegmentOverhead
2016-08-05 15:03:44 -04:00
conn.roundTrip = &RoundTripInfo{
2016-07-05 17:53:46 -04:00
rto: 100,
2016-10-02 17:43:58 -04:00
minRtt: config.Tti.GetValue(),
2016-07-05 17:53:46 -04:00
}
2016-10-02 17:43:58 -04:00
conn.interval = config.Tti.GetValue()
2016-07-05 17:02:52 -04:00
conn.receivingWorker = NewReceivingWorker(conn)
2016-10-02 17:43:58 -04:00
conn.congestionControl = config.Congestion
2016-07-05 17:02:52 -04:00
conn.sendingWorker = NewSendingWorker(conn)
2016-06-17 10:51:41 -04:00
2016-10-11 06:30:53 -04:00
isTerminating := func() bool {
return conn.State().Is(StateTerminating, StateTerminated)
}
isTerminated := func() bool {
return conn.State() == StateTerminated
}
conn.dataUpdater = NewUpdater(
conn.interval,
2016-10-11 06:44:17 -04:00
predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
2016-10-11 06:30:53 -04:00
isTerminating,
conn.updateTask)
conn.pingUpdater = NewUpdater(
2016-10-11 06:24:19 -04:00
5000, // 5 seconds
2016-10-11 06:30:53 -04:00
predicate.Not(isTerminated),
isTerminated,
conn.updateTask)
2016-10-11 06:24:19 -04:00
conn.pingUpdater.WakeUp()
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 {
2016-07-26 15:34:00 -04:00
if this.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
2016-07-06 11:34:38 -04:00
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 {
2016-08-07 09:31:24 -04:00
return 0, ErrIOTimeout
2016-07-12 06:54:09 -04:00
}
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()) {
2016-08-07 09:31:24 -04:00
return 0, ErrIOTimeout
2016-07-06 11:34:38 -04:00
}
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-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:])
this.dataUpdater.WakeUp()
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 {
2016-08-07 09:31:24 -04:00
return totalWritten, ErrIOTimeout
2016-07-14 11:39:12 -04:00
}
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-08-07 09:31:24 -04:00
return totalWritten, ErrIOTimeout
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()
2016-10-11 06:24:19 -04:00
this.pingUpdater.interval = time.Second
case StatePeerTerminating:
this.sendingWorker.CloseWrite()
2016-10-11 06:24:19 -04:00
this.pingUpdater.interval = time.Second
2016-07-05 17:02:52 -04:00
case StateTerminated:
this.receivingWorker.CloseRead()
this.sendingWorker.CloseWrite()
2016-10-11 06:24:19 -04:00
this.pingUpdater.interval = time.Second
this.dataUpdater.WakeUp()
2016-10-11 06:24:19 -04:00
this.pingUpdater.WakeUp()
go this.Terminate()
2016-07-05 17:02:52 -04:00
}
}
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 {
2016-08-07 09:31:24 -04:00
return ErrClosedConnection
2016-07-05 17:02:52 -04:00
}
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()
2016-07-26 15:34:00 -04:00
if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
2016-08-07 09:31:24 -04:00
return ErrClosedConnection
2016-06-17 17:50:08 -04:00
}
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-08-07 09:31:24 -04:00
return ErrClosedConnection
2016-06-17 17:50:08 -04:00
}
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-08-07 09:31:24 -04:00
return ErrClosedConnection
2016-06-17 17:50:08 -04:00
}
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() {
this.flush()
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-07-29 05:49:53 -04:00
for this.State() != StateTerminated {
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.SetState(StateTerminated)
2016-07-29 06:13:20 -04:00
this.dataInputCond.Broadcast()
this.dataOutputCond.Broadcast()
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-10-11 06:24:19 -04:00
this.dataUpdater.WakeUp()
2016-07-05 17:02:52 -04:00
case *AckSegment:
2016-07-14 16:52:00 -04:00
this.HandleOption(seg.Option)
2016-10-11 07:17:57 -04:00
this.sendingWorker.ProcessSegment(current, seg, this.roundTrip.Timeout())
2016-07-14 11:39:12 -04:00
this.dataOutputCond.Signal()
2016-10-11 06:24:19 -04:00
this.dataUpdater.WakeUp()
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)
this.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
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.")
2016-10-11 06:24:19 -04:00
this.Ping(current, CommandTerminate)
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-10-11 06:24:19 -04:00
if current-atomic.LoadUint32(&this.lastPingTime) >= 1000 {
this.Ping(current, CommandPing)
2016-07-05 17:02:52 -04:00
}
// 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
}
2016-10-11 06:24:19 -04:00
func (this *Connection) Ping(current uint32, cmd Command) {
seg := NewCmdOnlySegment()
seg.Conv = this.conv
seg.Command = cmd
seg.ReceivinNext = this.receivingWorker.nextNumber
seg.SendingNext = this.sendingWorker.firstUnacknowledged
seg.PeerRTO = this.roundTrip.Timeout()
if this.State() == StateReadyToClose {
seg.Option = SegmentOptionClose
}
this.output.Write(seg)
atomic.StoreUint32(&this.lastPingTime, current)
seg.Release()
}