1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-09 06:44:30 -04:00
v2fly/transport/internet/kcp/connection.go

402 lines
8.8 KiB
Go
Raw Normal View History

2016-06-17 10:51:41 -04:00
package kcp
import (
"errors"
"io"
"net"
"sync"
"time"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
2016-06-18 10:52:02 -04:00
"github.com/v2ray/v2ray-core/common/signal"
2016-06-17 10:51:41 -04:00
)
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
)
const (
2016-06-25 15:35:18 -04:00
headerSize uint32 = 2
2016-06-17 10:51:41 -04:00
)
type Command byte
var (
CommandData Command = 0
CommandTerminate Command = 1
)
type Option byte
var (
OptionClose Option = 1
)
type ConnState byte
var (
ConnStateActive ConnState = 0
ConnStateReadyToClose ConnState = 1
ConnStatePeerClosed ConnState = 2
ConnStateClosed ConnState = 4
)
func nowMillisec() int64 {
now := time.Now()
return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}
2016-06-18 10:34:04 -04:00
// Connection is a KCP connection over UDP.
type Connection struct {
2016-06-17 17:50:08 -04:00
sync.RWMutex
2016-06-23 16:37:48 -04:00
state ConnState
kcp *KCP // the core ARQ
kcpAccess sync.Mutex
block Authenticator
needUpdate bool
local, remote net.Addr
rd time.Time // read deadline
wd time.Time // write deadline
chReadEvent chan struct{}
writer io.WriteCloser
since int64
terminateOnce signal.Once
2016-06-25 15:35:18 -04:00
writeBufferSize uint32
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.
func NewConnection(conv uint32, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
conn := new(Connection)
conn.local = local
conn.chReadEvent = make(chan struct{}, 1)
conn.remote = remote
conn.block = block
conn.writer = writerCloser
conn.since = nowMillisec()
2016-06-17 10:51:41 -04:00
2016-06-25 15:35:18 -04:00
mtu := effectiveConfig.Mtu - uint32(block.HeaderSize()) - headerSize
conn.kcp = NewKCP(conv, mtu, effectiveConfig.GetSendingWindowSize(), effectiveConfig.GetReceivingWindowSize(), conn.output)
2016-06-25 11:32:09 -04:00
conn.kcp.NoDelay(effectiveConfig.Tti, 2, effectiveConfig.Congestion)
2016-06-18 10:34:04 -04:00
conn.kcp.current = conn.Elapsed()
2016-06-25 17:18:05 -04:00
conn.writeBufferSize = effectiveConfig.WriteBuffer / effectiveConfig.Mtu
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) {
if this == nil || this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
2016-06-17 10:51:41 -04:00
return 0, io.EOF
}
for {
2016-06-18 10:34:04 -04:00
this.RLock()
if this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
this.RUnlock()
2016-06-17 10:51:41 -04:00
return 0, io.EOF
}
2016-06-18 10:34:04 -04:00
if !this.rd.IsZero() && this.rd.Before(time.Now()) {
this.RUnlock()
2016-06-17 17:50:08 -04:00
return 0, errTimeout
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
this.RUnlock()
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
this.kcpAccess.Lock()
nBytes := this.kcp.Recv(b)
this.kcpAccess.Unlock()
2016-06-17 10:51:41 -04:00
if nBytes > 0 {
return nBytes, nil
}
select {
2016-06-18 10:34:04 -04:00
case <-this.chReadEvent:
2016-06-17 17:09:26 -04:00
case <-time.After(time.Second):
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) {
if this == nil ||
this.state == ConnStateReadyToClose ||
this.state == ConnStatePeerClosed ||
this.state == ConnStateClosed {
2016-06-17 10:51:41 -04:00
return 0, io.ErrClosedPipe
}
for {
2016-06-18 10:34:04 -04:00
this.RLock()
if this.state == ConnStateReadyToClose ||
this.state == ConnStatePeerClosed ||
this.state == ConnStateClosed {
this.RUnlock()
2016-06-17 10:51:41 -04:00
return 0, io.ErrClosedPipe
}
2016-06-18 10:34:04 -04:00
this.RUnlock()
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
this.kcpAccess.Lock()
2016-06-23 16:37:48 -04:00
if this.kcp.WaitSnd() < this.writeBufferSize {
2016-06-17 10:51:41 -04:00
nBytes := len(b)
2016-06-18 10:34:04 -04:00
this.kcp.Send(b)
this.kcp.current = this.Elapsed()
this.kcp.flush()
this.kcpAccess.Unlock()
2016-06-17 10:51:41 -04:00
return nBytes, nil
}
2016-06-18 10:34:04 -04:00
this.kcpAccess.Unlock()
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
if !this.wd.IsZero() && this.wd.Before(time.Now()) {
2016-06-17 10:51:41 -04:00
return 0, errTimeout
}
2016-06-17 11:38:42 -04:00
2016-06-17 17:09:26 -04:00
// Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
time.Sleep(time.Second)
2016-06-17 10:51:41 -04:00
}
}
2016-06-18 10:34:04 -04:00
func (this *Connection) Terminate() {
2016-06-17 17:50:08 -04:00
if this == nil || this.state == ConnStateClosed {
2016-06-17 10:51:41 -04:00
return
}
this.Lock()
defer this.Unlock()
2016-06-17 11:38:42 -04:00
if this.state == ConnStateClosed {
return
}
2016-06-17 10:51:41 -04:00
this.state = ConnStateClosed
this.writer.Close()
}
2016-06-18 10:34:04 -04:00
func (this *Connection) NotifyTermination() {
2016-06-17 10:51:41 -04:00
for i := 0; i < 16; i++ {
2016-06-17 17:50:08 -04:00
this.RLock()
2016-06-17 10:51:41 -04:00
if this.state == ConnStateClosed {
2016-06-17 17:50:08 -04:00
this.RUnlock()
2016-06-17 11:38:42 -04:00
break
2016-06-17 10:51:41 -04:00
}
2016-06-17 17:50:08 -04:00
this.RUnlock()
2016-06-17 10:51:41 -04:00
buffer := alloc.NewSmallBuffer().Clear()
buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
2016-06-18 10:52:02 -04:00
this.outputBuffer(buffer)
2016-06-17 17:09:26 -04:00
2016-06-17 10:51:41 -04:00
time.Sleep(time.Second)
2016-06-17 17:09:26 -04:00
2016-06-17 10:51:41 -04:00
}
this.Terminate()
}
2016-06-18 10:52:02 -04:00
func (this *Connection) ForceTimeout() {
if this == nil {
return
}
for i := 0; i < 5; i++ {
if this.state == ConnStateClosed {
return
}
time.Sleep(time.Minute)
}
go this.terminateOnce.Do(this.NotifyTermination)
}
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 {
if this == nil || this.state == ConnStateClosed || this.state == ConnStateReadyToClose {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-06-18 10:34:04 -04:00
log.Debug("KCP|Connection: Closing connection to ", this.remote)
this.Lock()
defer this.Unlock()
if this.state == ConnStateActive {
this.state = ConnStateReadyToClose
if this.kcp.WaitSnd() == 0 {
2016-06-18 10:52:02 -04:00
go this.terminateOnce.Do(this.NotifyTermination)
} else {
go this.ForceTimeout()
2016-06-17 10:51:41 -04:00
}
}
2016-06-18 10:34:04 -04:00
if this.state == ConnStatePeerClosed {
go this.Terminate()
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 {
if this == nil || this.state != ConnStateActive {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-06-18 10:34:04 -04:00
this.Lock()
defer this.Unlock()
this.rd = t
this.wd = t
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 {
if this == nil || this.state != ConnStateActive {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-06-18 10:34:04 -04:00
this.Lock()
defer this.Unlock()
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 {
if this == nil || this.state != ConnStateActive {
2016-06-17 17:50:08 -04:00
return errClosedConnection
}
2016-06-18 10:34:04 -04:00
this.Lock()
defer this.Unlock()
this.wd = t
2016-06-17 10:51:41 -04:00
return nil
}
2016-06-18 10:52:02 -04:00
func (this *Connection) outputBuffer(payload *alloc.Buffer) {
2016-06-17 10:51:41 -04:00
defer payload.Release()
2016-06-18 10:34:04 -04:00
if this == nil {
2016-06-17 17:50:08 -04:00
return
}
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
this.RLock()
defer this.RUnlock()
if this.state == ConnStatePeerClosed || this.state == ConnStateClosed {
2016-06-17 10:51:41 -04:00
return
}
2016-06-18 10:34:04 -04:00
this.block.Seal(payload)
2016-06-17 10:51:41 -04:00
2016-06-18 10:34:04 -04:00
this.writer.Write(payload.Value)
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:52:02 -04:00
func (this *Connection) output(payload []byte) {
if this == nil || this.state == ConnStateClosed {
return
}
if this.state == ConnStateReadyToClose && this.kcp.WaitSnd() == 0 {
go this.terminateOnce.Do(this.NotifyTermination)
}
if len(payload) < IKCP_OVERHEAD {
return
}
buffer := alloc.NewBuffer().Clear().Append(payload)
cmd := CommandData
opt := Option(0)
if this.state == ConnStateReadyToClose {
opt = OptionClose
}
buffer.Prepend([]byte{byte(cmd), byte(opt)})
this.outputBuffer(buffer)
}
2016-06-17 10:51:41 -04:00
// kcp update, input loop
2016-06-18 10:34:04 -04:00
func (this *Connection) updateTask() {
for this.state != ConnStateClosed {
current := this.Elapsed()
this.kcpAccess.Lock()
this.kcp.Update(current)
this.kcpAccess.Unlock()
2016-06-25 17:08:02 -04:00
time.Sleep(time.Duration(effectiveConfig.Tti) * time.Millisecond)
2016-06-17 10:51:41 -04:00
}
}
2016-06-18 10:34:04 -04:00
func (this *Connection) notifyReadEvent() {
2016-06-17 10:51:41 -04:00
select {
2016-06-18 10:34:04 -04:00
case this.chReadEvent <- struct{}{}:
2016-06-17 10:51:41 -04:00
default:
}
}
2016-06-18 10:34:04 -04:00
func (this *Connection) MarkPeerClose() {
2016-06-17 10:51:41 -04:00
this.Lock()
defer this.Unlock()
if this.state == ConnStateReadyToClose {
this.state = ConnStateClosed
go this.Terminate()
return
}
if this.state == ConnStateActive {
this.state = ConnStatePeerClosed
}
2016-06-23 17:17:17 -04:00
this.kcpAccess.Lock()
this.kcp.ClearSendQueue()
this.kcpAccess.Unlock()
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
func (this *Connection) kcpInput(data []byte) {
2016-06-17 10:51:41 -04:00
cmd := Command(data[0])
opt := Option(data[1])
if cmd == CommandTerminate {
2016-06-18 10:34:04 -04:00
go this.Terminate()
2016-06-17 10:51:41 -04:00
return
}
if opt == OptionClose {
2016-06-18 10:34:04 -04:00
go this.MarkPeerClose()
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
this.kcpAccess.Lock()
this.kcp.current = this.Elapsed()
this.kcp.Input(data[2:])
2016-06-17 11:38:42 -04:00
2016-06-18 10:34:04 -04:00
this.kcpAccess.Unlock()
this.notifyReadEvent()
2016-06-17 10:51:41 -04:00
}
2016-06-18 10:34:04 -04:00
func (this *Connection) FetchInputFrom(conn net.Conn) {
2016-06-17 10:51:41 -04:00
go func() {
for {
payload := alloc.NewBuffer()
nBytes, err := conn.Read(payload.Value)
if err != nil {
return
}
payload.Slice(0, nBytes)
if this.block.Open(payload) {
this.kcpInput(payload.Value)
2016-06-17 11:38:42 -04:00
} else {
log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
2016-06-17 10:51:41 -04:00
}
payload.Release()
}
}()
}
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) {}