connection.go 6.3 KB

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