connection.go 8.9 KB

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