connection.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package kcp
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "sync"
  7. "time"
  8. "github.com/v2ray/v2ray-core/common/alloc"
  9. "github.com/v2ray/v2ray-core/common/log"
  10. )
  11. var (
  12. errTimeout = errors.New("i/o timeout")
  13. errBrokenPipe = errors.New("broken pipe")
  14. errClosedListener = errors.New("Listener closed.")
  15. errClosedConnection = errors.New("Connection closed.")
  16. )
  17. const (
  18. headerSize uint32 = 2
  19. )
  20. func nowMillisec() int64 {
  21. now := time.Now()
  22. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  23. }
  24. // Connection is a KCP connection over UDP.
  25. type Connection struct {
  26. sync.RWMutex
  27. kcp *KCP // the core ARQ
  28. kcpAccess sync.Mutex
  29. block Authenticator
  30. local, remote net.Addr
  31. wd time.Time // write deadline
  32. writer io.WriteCloser
  33. since int64
  34. }
  35. // NewConnection create a new KCP connection between local and remote.
  36. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  37. conn := new(Connection)
  38. conn.local = local
  39. conn.remote = remote
  40. conn.block = block
  41. conn.writer = writerCloser
  42. conn.since = nowMillisec()
  43. authWriter := &AuthenticationWriter{
  44. Authenticator: block,
  45. Writer: writerCloser,
  46. }
  47. conn.kcp = NewKCP(conv, authWriter)
  48. conn.kcp.current = conn.Elapsed()
  49. go conn.updateTask()
  50. return conn
  51. }
  52. func (this *Connection) Elapsed() uint32 {
  53. return uint32(nowMillisec() - this.since)
  54. }
  55. // Read implements the Conn Read method.
  56. func (this *Connection) Read(b []byte) (int, error) {
  57. if this == nil || this.kcp.state == StateTerminating || this.kcp.state == StateTerminated {
  58. return 0, io.EOF
  59. }
  60. return this.kcp.receivingWorker.Read(b)
  61. }
  62. // Write implements the Conn Write method.
  63. func (this *Connection) Write(b []byte) (int, error) {
  64. if this == nil || this.kcp.state != StateActive {
  65. return 0, io.ErrClosedPipe
  66. }
  67. totalWritten := 0
  68. for {
  69. this.RLock()
  70. if this == nil || this.kcp.state != StateActive {
  71. this.RUnlock()
  72. return totalWritten, io.ErrClosedPipe
  73. }
  74. this.RUnlock()
  75. this.kcpAccess.Lock()
  76. nBytes := this.kcp.sendingWorker.Push(b[totalWritten:])
  77. if nBytes > 0 {
  78. totalWritten += nBytes
  79. if totalWritten == len(b) {
  80. this.kcpAccess.Unlock()
  81. return totalWritten, nil
  82. }
  83. }
  84. this.kcpAccess.Unlock()
  85. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  86. return totalWritten, errTimeout
  87. }
  88. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  89. time.Sleep(time.Second)
  90. }
  91. }
  92. // Close closes the connection.
  93. func (this *Connection) Close() error {
  94. if this == nil ||
  95. this.kcp.state == StateReadyToClose ||
  96. this.kcp.state == StateTerminating ||
  97. this.kcp.state == StateTerminated {
  98. return errClosedConnection
  99. }
  100. log.Debug("KCP|Connection: Closing connection to ", this.remote)
  101. this.Lock()
  102. defer this.Unlock()
  103. this.kcpAccess.Lock()
  104. this.kcp.OnClose()
  105. this.kcpAccess.Unlock()
  106. return nil
  107. }
  108. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  109. func (this *Connection) LocalAddr() net.Addr {
  110. if this == nil {
  111. return nil
  112. }
  113. return this.local
  114. }
  115. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  116. func (this *Connection) RemoteAddr() net.Addr {
  117. if this == nil {
  118. return nil
  119. }
  120. return this.remote
  121. }
  122. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  123. func (this *Connection) SetDeadline(t time.Time) error {
  124. if err := this.SetReadDeadline(t); err != nil {
  125. return err
  126. }
  127. if err := this.SetWriteDeadline(t); err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. // SetReadDeadline implements the Conn SetReadDeadline method.
  133. func (this *Connection) SetReadDeadline(t time.Time) error {
  134. if this == nil || this.kcp.state != StateActive {
  135. return errClosedConnection
  136. }
  137. this.kcpAccess.Lock()
  138. defer this.kcpAccess.Unlock()
  139. this.kcp.receivingWorker.SetReadDeadline(t)
  140. return nil
  141. }
  142. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  143. func (this *Connection) SetWriteDeadline(t time.Time) error {
  144. if this == nil || this.kcp.state != StateActive {
  145. return errClosedConnection
  146. }
  147. this.Lock()
  148. defer this.Unlock()
  149. this.wd = t
  150. return nil
  151. }
  152. // kcp update, input loop
  153. func (this *Connection) updateTask() {
  154. for this.kcp.state != StateTerminated {
  155. current := this.Elapsed()
  156. this.kcpAccess.Lock()
  157. this.kcp.Update(current)
  158. this.kcpAccess.Unlock()
  159. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  160. if this.kcp.state == StateTerminating {
  161. interval = time.Second
  162. }
  163. time.Sleep(interval)
  164. }
  165. this.Terminate()
  166. }
  167. func (this *Connection) kcpInput(data []byte) {
  168. this.kcpAccess.Lock()
  169. this.kcp.current = this.Elapsed()
  170. this.kcp.Input(data)
  171. this.kcpAccess.Unlock()
  172. }
  173. func (this *Connection) FetchInputFrom(conn net.Conn) {
  174. go func() {
  175. for {
  176. payload := alloc.NewBuffer()
  177. nBytes, err := conn.Read(payload.Value)
  178. if err != nil {
  179. payload.Release()
  180. return
  181. }
  182. payload.Slice(0, nBytes)
  183. if this.block.Open(payload) {
  184. this.kcpInput(payload.Value)
  185. } else {
  186. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  187. }
  188. payload.Release()
  189. }
  190. }()
  191. }
  192. func (this *Connection) Reusable() bool {
  193. return false
  194. }
  195. func (this *Connection) SetReusable(b bool) {}
  196. func (this *Connection) Terminate() {
  197. if this == nil || this.writer == nil {
  198. return
  199. }
  200. log.Info("Terminating connection to ", this.RemoteAddr())
  201. this.writer.Close()
  202. }