connection.go 5.9 KB

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