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

237 lines
5.5 KiB

package kcp
import (
"errors"
"io"
"net"
"sync"
"time"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/log"
)
var (
9 years ago
errTimeout = errors.New("i/o timeout")
errBrokenPipe = errors.New("broken pipe")
errClosedListener = errors.New("Listener closed.")
errClosedConnection = errors.New("Connection closed.")
)
const (
headerSize uint32 = 2
)
func nowMillisec() int64 {
now := time.Now()
return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}
9 years ago
// Connection is a KCP connection over UDP.
type Connection struct {
9 years ago
sync.RWMutex
kcp *KCP // the core ARQ
kcpAccess sync.Mutex
block Authenticator
local, remote net.Addr
wd time.Time // write deadline
writer io.WriteCloser
since int64
}
9 years ago
// NewConnection create a new KCP connection between local and remote.
func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
9 years ago
conn := new(Connection)
conn.local = local
conn.remote = remote
conn.block = block
conn.writer = writerCloser
conn.since = nowMillisec()
authWriter := &AuthenticationWriter{
Authenticator: block,
Writer: writerCloser,
}
conn.kcp = NewKCP(conv, authWriter)
9 years ago
conn.kcp.current = conn.Elapsed()
9 years ago
go conn.updateTask()
9 years ago
return conn
}
9 years ago
func (this *Connection) Elapsed() uint32 {
return uint32(nowMillisec() - this.since)
}
// Read implements the Conn Read method.
9 years ago
func (this *Connection) Read(b []byte) (int, error) {
9 years ago
if this == nil || this.kcp.state == StateTerminating || this.kcp.state == StateTerminated {
return 0, io.EOF
}
9 years ago
return this.kcp.receivingWorker.Read(b)
}
// Write implements the Conn Write method.
9 years ago
func (this *Connection) Write(b []byte) (int, error) {
if this == nil || this.kcp.state != StateActive {
return 0, io.ErrClosedPipe
}
totalWritten := 0
for {
9 years ago
this.RLock()
if this == nil || this.kcp.state != StateActive {
9 years ago
this.RUnlock()
return totalWritten, io.ErrClosedPipe
}
9 years ago
this.RUnlock()
9 years ago
this.kcpAccess.Lock()
9 years ago
nBytes := this.kcp.sendingWorker.Push(b[totalWritten:])
if nBytes > 0 {
totalWritten += nBytes
if totalWritten == len(b) {
this.kcpAccess.Unlock()
return totalWritten, nil
}
}
9 years ago
this.kcpAccess.Unlock()
9 years ago
if !this.wd.IsZero() && this.wd.Before(time.Now()) {
return totalWritten, errTimeout
}
9 years ago
// Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
time.Sleep(time.Second)
}
}
// Close closes the connection.
9 years ago
func (this *Connection) Close() error {
if this == nil ||
this.kcp.state == StateReadyToClose ||
this.kcp.state == StateTerminating ||
this.kcp.state == StateTerminated {
9 years ago
return errClosedConnection
}
9 years ago
log.Debug("KCP|Connection: Closing connection to ", this.remote)
this.Lock()
defer this.Unlock()
this.kcpAccess.Lock()
this.kcp.OnClose()
this.kcpAccess.Unlock()
return nil
}
// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
9 years ago
func (this *Connection) LocalAddr() net.Addr {
if this == nil {
9 years ago
return nil
}
9 years ago
return this.local
}
// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
9 years ago
func (this *Connection) RemoteAddr() net.Addr {
if this == nil {
9 years ago
return nil
}
9 years ago
return this.remote
9 years ago
}
// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
9 years ago
func (this *Connection) SetDeadline(t time.Time) error {
9 years ago
if err := this.SetReadDeadline(t); err != nil {
return err
}
if err := this.SetWriteDeadline(t); err != nil {
return err
9 years ago
}
return nil
}
// SetReadDeadline implements the Conn SetReadDeadline method.
9 years ago
func (this *Connection) SetReadDeadline(t time.Time) error {
if this == nil || this.kcp.state != StateActive {
9 years ago
return errClosedConnection
}
9 years ago
this.kcpAccess.Lock()
defer this.kcpAccess.Unlock()
9 years ago
this.kcp.receivingWorker.SetReadDeadline(t)
return nil
}
// SetWriteDeadline implements the Conn SetWriteDeadline method.
9 years ago
func (this *Connection) SetWriteDeadline(t time.Time) error {
if this == nil || this.kcp.state != StateActive {
9 years ago
return errClosedConnection
}
9 years ago
this.Lock()
defer this.Unlock()
this.wd = t
return nil
}
// kcp update, input loop
9 years ago
func (this *Connection) updateTask() {
for this.kcp.state != StateTerminated {
9 years ago
current := this.Elapsed()
this.kcpAccess.Lock()
this.kcp.Update(current)
this.kcpAccess.Unlock()
interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
if this.kcp.state == StateTerminating {
interval = time.Second
}
time.Sleep(interval)
}
this.Terminate()
}
9 years ago
func (this *Connection) kcpInput(data []byte) {
this.kcpAccess.Lock()
this.kcp.current = this.Elapsed()
this.kcp.Input(data)
9 years ago
this.kcpAccess.Unlock()
}
9 years ago
func (this *Connection) FetchInputFrom(conn net.Conn) {
go func() {
for {
payload := alloc.NewBuffer()
nBytes, err := conn.Read(payload.Value)
if err != nil {
payload.Release()
return
}
payload.Slice(0, nBytes)
if this.block.Open(payload) {
this.kcpInput(payload.Value)
} else {
log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
}
payload.Release()
}
}()
}
9 years ago
func (this *Connection) Reusable() bool {
return false
}
9 years ago
func (this *Connection) SetReusable(b bool) {}
func (this *Connection) Terminate() {
if this == nil || this.writer == nil {
return
}
log.Info("Terminating connection to ", this.RemoteAddr())
this.writer.Close()
}