connection.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. rd time.Time // read deadline
  42. wd time.Time // write deadline
  43. chReadEvent chan struct{}
  44. writer io.WriteCloser
  45. since int64
  46. terminateOnce signal.Once
  47. writeBufferSize uint32
  48. }
  49. // NewConnection create a new KCP connection between local and remote.
  50. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  51. conn := new(Connection)
  52. conn.local = local
  53. conn.chReadEvent = make(chan struct{}, 1)
  54. conn.remote = remote
  55. conn.block = block
  56. conn.writer = writerCloser
  57. conn.since = nowMillisec()
  58. conn.writeBufferSize = effectiveConfig.WriteBuffer / effectiveConfig.Mtu
  59. authWriter := &AuthenticationWriter{
  60. Authenticator: block,
  61. Writer: writerCloser,
  62. }
  63. mtu := effectiveConfig.Mtu - uint32(block.HeaderSize()) - headerSize
  64. conn.kcp = NewKCP(conv, mtu, effectiveConfig.GetSendingWindowSize(), effectiveConfig.GetReceivingWindowSize(), conn.writeBufferSize, authWriter)
  65. conn.kcp.NoDelay(effectiveConfig.Tti, 2, effectiveConfig.Congestion)
  66. conn.kcp.current = conn.Elapsed()
  67. go conn.updateTask()
  68. return conn
  69. }
  70. func (this *Connection) Elapsed() uint32 {
  71. return uint32(nowMillisec() - this.since)
  72. }
  73. // Read implements the Conn Read method.
  74. func (this *Connection) Read(b []byte) (int, error) {
  75. if this == nil ||
  76. this.kcp.state == StateReadyToClose ||
  77. this.kcp.state == StateTerminating ||
  78. this.kcp.state == StateTerminated {
  79. return 0, io.EOF
  80. }
  81. for {
  82. this.RLock()
  83. if this == nil ||
  84. this.kcp.state == StateReadyToClose ||
  85. this.kcp.state == StateTerminating ||
  86. this.kcp.state == StateTerminated {
  87. this.RUnlock()
  88. return 0, io.EOF
  89. }
  90. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  91. this.RUnlock()
  92. return 0, errTimeout
  93. }
  94. this.RUnlock()
  95. this.kcpAccess.Lock()
  96. nBytes := this.kcp.Recv(b)
  97. this.kcpAccess.Unlock()
  98. if nBytes > 0 {
  99. return nBytes, nil
  100. }
  101. select {
  102. case <-this.chReadEvent:
  103. case <-time.After(time.Second):
  104. }
  105. }
  106. }
  107. // Write implements the Conn Write method.
  108. func (this *Connection) Write(b []byte) (int, error) {
  109. if this == nil || this.kcp.state != StateActive {
  110. return 0, io.ErrClosedPipe
  111. }
  112. totalWritten := 0
  113. for {
  114. this.RLock()
  115. if this == nil || this.kcp.state != StateActive {
  116. this.RUnlock()
  117. return totalWritten, io.ErrClosedPipe
  118. }
  119. this.RUnlock()
  120. this.kcpAccess.Lock()
  121. nBytes := this.kcp.Send(b[totalWritten:])
  122. if nBytes > 0 {
  123. totalWritten += nBytes
  124. if totalWritten == len(b) {
  125. this.kcpAccess.Unlock()
  126. return totalWritten, nil
  127. }
  128. }
  129. this.kcpAccess.Unlock()
  130. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  131. return totalWritten, errTimeout
  132. }
  133. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  134. time.Sleep(time.Second)
  135. }
  136. }
  137. // Close closes the connection.
  138. func (this *Connection) Close() error {
  139. if this == nil ||
  140. this.kcp.state == StateReadyToClose ||
  141. this.kcp.state == StateTerminating ||
  142. this.kcp.state == StateTerminated {
  143. return errClosedConnection
  144. }
  145. log.Debug("KCP|Connection: Closing connection to ", this.remote)
  146. this.Lock()
  147. defer this.Unlock()
  148. this.kcpAccess.Lock()
  149. this.kcp.OnClose()
  150. this.kcpAccess.Unlock()
  151. return nil
  152. }
  153. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  154. func (this *Connection) LocalAddr() net.Addr {
  155. if this == nil {
  156. return nil
  157. }
  158. return this.local
  159. }
  160. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  161. func (this *Connection) RemoteAddr() net.Addr {
  162. if this == nil {
  163. return nil
  164. }
  165. return this.remote
  166. }
  167. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  168. func (this *Connection) SetDeadline(t time.Time) error {
  169. if this == nil || this.kcp.state != StateActive {
  170. return errClosedConnection
  171. }
  172. this.Lock()
  173. defer this.Unlock()
  174. this.rd = t
  175. this.wd = t
  176. return nil
  177. }
  178. // SetReadDeadline implements the Conn SetReadDeadline method.
  179. func (this *Connection) SetReadDeadline(t time.Time) error {
  180. if this == nil || this.kcp.state != StateActive {
  181. return errClosedConnection
  182. }
  183. this.Lock()
  184. defer this.Unlock()
  185. this.rd = t
  186. return nil
  187. }
  188. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  189. func (this *Connection) SetWriteDeadline(t time.Time) error {
  190. if this == nil || this.kcp.state != StateActive {
  191. return errClosedConnection
  192. }
  193. this.Lock()
  194. defer this.Unlock()
  195. this.wd = t
  196. return nil
  197. }
  198. // kcp update, input loop
  199. func (this *Connection) updateTask() {
  200. for this.kcp.state != StateTerminated {
  201. current := this.Elapsed()
  202. this.kcpAccess.Lock()
  203. this.kcp.Update(current)
  204. this.kcpAccess.Unlock()
  205. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  206. if this.kcp.state == StateTerminating {
  207. interval = time.Second
  208. }
  209. time.Sleep(interval)
  210. }
  211. this.Terminate()
  212. }
  213. func (this *Connection) notifyReadEvent() {
  214. select {
  215. case this.chReadEvent <- struct{}{}:
  216. default:
  217. }
  218. }
  219. func (this *Connection) kcpInput(data []byte) {
  220. this.kcpAccess.Lock()
  221. this.kcp.current = this.Elapsed()
  222. this.kcp.Input(data)
  223. this.kcpAccess.Unlock()
  224. this.notifyReadEvent()
  225. }
  226. func (this *Connection) FetchInputFrom(conn net.Conn) {
  227. go func() {
  228. for {
  229. payload := alloc.NewBuffer()
  230. nBytes, err := conn.Read(payload.Value)
  231. if err != nil {
  232. payload.Release()
  233. return
  234. }
  235. payload.Slice(0, nBytes)
  236. if this.block.Open(payload) {
  237. this.kcpInput(payload.Value)
  238. } else {
  239. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  240. }
  241. payload.Release()
  242. }
  243. }()
  244. }
  245. func (this *Connection) Reusable() bool {
  246. return false
  247. }
  248. func (this *Connection) SetReusable(b bool) {}
  249. func (this *Connection) Terminate() {
  250. if this == nil || this.writer == nil {
  251. return
  252. }
  253. log.Info("Terminating connection to ", this.RemoteAddr())
  254. this.writer.Close()
  255. }