connection.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 = 2
  19. )
  20. type Command byte
  21. var (
  22. CommandData Command = 0
  23. CommandTerminate Command = 1
  24. )
  25. type Option byte
  26. var (
  27. OptionClose Option = 1
  28. )
  29. type ConnState byte
  30. var (
  31. ConnStateActive ConnState = 0
  32. ConnStateReadyToClose ConnState = 1
  33. ConnStatePeerClosed ConnState = 2
  34. ConnStateClosed ConnState = 4
  35. )
  36. func nowMillisec() int64 {
  37. now := time.Now()
  38. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  39. }
  40. // Connection is a KCP connection over UDP.
  41. type Connection struct {
  42. sync.RWMutex
  43. state ConnState
  44. kcp *KCP // the core ARQ
  45. kcpAccess sync.Mutex
  46. block Authenticator
  47. needUpdate bool
  48. local, remote net.Addr
  49. rd time.Time // read deadline
  50. wd time.Time // write deadline
  51. chReadEvent chan struct{}
  52. writer io.WriteCloser
  53. since int64
  54. }
  55. // NewConnection create a new KCP connection between local and remote.
  56. func NewConnection(conv uint32, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  57. conn := new(Connection)
  58. conn.local = local
  59. conn.chReadEvent = make(chan struct{}, 1)
  60. conn.remote = remote
  61. conn.block = block
  62. conn.writer = writerCloser
  63. conn.since = nowMillisec()
  64. mtu := uint32(effectiveConfig.Mtu - block.HeaderSize() - headerSize)
  65. conn.kcp = NewKCP(conv, mtu, func(buf []byte, size int) {
  66. if size >= IKCP_OVERHEAD {
  67. ext := alloc.NewBuffer().Clear().Append(buf[:size])
  68. cmd := CommandData
  69. opt := Option(0)
  70. if conn.state == ConnStateReadyToClose {
  71. opt = OptionClose
  72. }
  73. ext.Prepend([]byte{byte(cmd), byte(opt)})
  74. go conn.output(ext)
  75. }
  76. if conn.state == ConnStateReadyToClose && conn.kcp.WaitSnd() == 0 {
  77. go conn.NotifyTermination()
  78. }
  79. })
  80. conn.kcp.WndSize(effectiveConfig.Sndwnd, effectiveConfig.Rcvwnd)
  81. conn.kcp.NoDelay(1, 20, 2, 1)
  82. conn.kcp.current = conn.Elapsed()
  83. go conn.updateTask()
  84. return conn
  85. }
  86. func (this *Connection) Elapsed() uint32 {
  87. return uint32(nowMillisec() - this.since)
  88. }
  89. // Read implements the Conn Read method.
  90. func (this *Connection) Read(b []byte) (int, error) {
  91. if this == nil || this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
  92. return 0, io.EOF
  93. }
  94. for {
  95. this.RLock()
  96. if this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
  97. this.RUnlock()
  98. return 0, io.EOF
  99. }
  100. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  101. this.RUnlock()
  102. return 0, errTimeout
  103. }
  104. this.RUnlock()
  105. this.kcpAccess.Lock()
  106. nBytes := this.kcp.Recv(b)
  107. this.kcpAccess.Unlock()
  108. if nBytes > 0 {
  109. return nBytes, nil
  110. }
  111. select {
  112. case <-this.chReadEvent:
  113. case <-time.After(time.Second):
  114. }
  115. }
  116. }
  117. // Write implements the Conn Write method.
  118. func (this *Connection) Write(b []byte) (int, error) {
  119. if this == nil ||
  120. this.state == ConnStateReadyToClose ||
  121. this.state == ConnStatePeerClosed ||
  122. this.state == ConnStateClosed {
  123. return 0, io.ErrClosedPipe
  124. }
  125. for {
  126. this.RLock()
  127. if this.state == ConnStateReadyToClose ||
  128. this.state == ConnStatePeerClosed ||
  129. this.state == ConnStateClosed {
  130. this.RUnlock()
  131. return 0, io.ErrClosedPipe
  132. }
  133. this.RUnlock()
  134. this.kcpAccess.Lock()
  135. if this.kcp.WaitSnd() < int(this.kcp.snd_wnd) {
  136. nBytes := len(b)
  137. this.kcp.Send(b)
  138. this.kcp.current = this.Elapsed()
  139. this.kcp.flush()
  140. this.kcpAccess.Unlock()
  141. return nBytes, nil
  142. }
  143. this.kcpAccess.Unlock()
  144. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  145. return 0, errTimeout
  146. }
  147. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  148. time.Sleep(time.Second)
  149. }
  150. }
  151. func (this *Connection) Terminate() {
  152. if this == nil || this.state == ConnStateClosed {
  153. return
  154. }
  155. this.Lock()
  156. defer this.Unlock()
  157. if this.state == ConnStateClosed {
  158. return
  159. }
  160. this.state = ConnStateClosed
  161. this.writer.Close()
  162. }
  163. func (this *Connection) NotifyTermination() {
  164. for i := 0; i < 16; i++ {
  165. this.RLock()
  166. if this.state == ConnStateClosed {
  167. this.RUnlock()
  168. break
  169. }
  170. this.RUnlock()
  171. buffer := alloc.NewSmallBuffer().Clear()
  172. buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
  173. this.output(buffer)
  174. time.Sleep(time.Second)
  175. }
  176. this.Terminate()
  177. }
  178. // Close closes the connection.
  179. func (this *Connection) Close() error {
  180. if this == nil || this.state == ConnStateClosed || this.state == ConnStateReadyToClose {
  181. return errClosedConnection
  182. }
  183. log.Debug("KCP|Connection: Closing connection to ", this.remote)
  184. this.Lock()
  185. defer this.Unlock()
  186. if this.state == ConnStateActive {
  187. this.state = ConnStateReadyToClose
  188. if this.kcp.WaitSnd() == 0 {
  189. go this.NotifyTermination()
  190. }
  191. }
  192. if this.state == ConnStatePeerClosed {
  193. go this.Terminate()
  194. }
  195. return nil
  196. }
  197. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  198. func (this *Connection) LocalAddr() net.Addr {
  199. if this == nil {
  200. return nil
  201. }
  202. return this.local
  203. }
  204. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  205. func (this *Connection) RemoteAddr() net.Addr {
  206. if this == nil {
  207. return nil
  208. }
  209. return this.remote
  210. }
  211. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  212. func (this *Connection) SetDeadline(t time.Time) error {
  213. if this == nil || this.state != ConnStateActive {
  214. return errClosedConnection
  215. }
  216. this.Lock()
  217. defer this.Unlock()
  218. this.rd = t
  219. this.wd = t
  220. return nil
  221. }
  222. // SetReadDeadline implements the Conn SetReadDeadline method.
  223. func (this *Connection) SetReadDeadline(t time.Time) error {
  224. if this == nil || this.state != ConnStateActive {
  225. return errClosedConnection
  226. }
  227. this.Lock()
  228. defer this.Unlock()
  229. this.rd = t
  230. return nil
  231. }
  232. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  233. func (this *Connection) SetWriteDeadline(t time.Time) error {
  234. if this == nil || this.state != ConnStateActive {
  235. return errClosedConnection
  236. }
  237. this.Lock()
  238. defer this.Unlock()
  239. this.wd = t
  240. return nil
  241. }
  242. func (this *Connection) output(payload *alloc.Buffer) {
  243. defer payload.Release()
  244. if this == nil {
  245. return
  246. }
  247. this.RLock()
  248. defer this.RUnlock()
  249. if this.state == ConnStatePeerClosed || this.state == ConnStateClosed {
  250. return
  251. }
  252. this.block.Seal(payload)
  253. this.writer.Write(payload.Value)
  254. }
  255. // kcp update, input loop
  256. func (this *Connection) updateTask() {
  257. for this.state != ConnStateClosed {
  258. current := this.Elapsed()
  259. this.kcpAccess.Lock()
  260. this.kcp.Update(current)
  261. interval := this.kcp.Check(this.Elapsed())
  262. this.kcpAccess.Unlock()
  263. sleep := interval - current
  264. if sleep < 10 {
  265. sleep = 10
  266. }
  267. time.Sleep(time.Duration(sleep) * time.Millisecond)
  268. }
  269. }
  270. func (this *Connection) notifyReadEvent() {
  271. select {
  272. case this.chReadEvent <- struct{}{}:
  273. default:
  274. }
  275. }
  276. func (this *Connection) MarkPeerClose() {
  277. this.Lock()
  278. defer this.Unlock()
  279. if this.state == ConnStateReadyToClose {
  280. this.state = ConnStateClosed
  281. go this.Terminate()
  282. return
  283. }
  284. if this.state == ConnStateActive {
  285. this.state = ConnStatePeerClosed
  286. }
  287. }
  288. func (this *Connection) kcpInput(data []byte) {
  289. cmd := Command(data[0])
  290. opt := Option(data[1])
  291. if cmd == CommandTerminate {
  292. go this.Terminate()
  293. return
  294. }
  295. if opt == OptionClose {
  296. go this.MarkPeerClose()
  297. }
  298. this.kcpAccess.Lock()
  299. this.kcp.current = this.Elapsed()
  300. this.kcp.Input(data[2:])
  301. this.kcpAccess.Unlock()
  302. this.notifyReadEvent()
  303. }
  304. func (this *Connection) FetchInputFrom(conn net.Conn) {
  305. go func() {
  306. for {
  307. payload := alloc.NewBuffer()
  308. nBytes, err := conn.Read(payload.Value)
  309. if err != nil {
  310. return
  311. }
  312. payload.Slice(0, nBytes)
  313. if this.block.Open(payload) {
  314. this.kcpInput(payload.Value)
  315. } else {
  316. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  317. }
  318. payload.Release()
  319. }
  320. }()
  321. }
  322. func (this *Connection) Reusable() bool {
  323. return false
  324. }
  325. func (this *Connection) SetReusable(b bool) {}