connection.go 6.0 KB

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