connection.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. this.kcp.current = this.Elapsed()
  128. this.kcp.flush()
  129. totalWritten += nBytes
  130. if totalWritten == len(b) {
  131. this.kcpAccess.Unlock()
  132. return totalWritten, nil
  133. }
  134. }
  135. this.kcpAccess.Unlock()
  136. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  137. return totalWritten, errTimeout
  138. }
  139. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  140. time.Sleep(time.Second)
  141. }
  142. }
  143. func (this *Connection) Terminate() {
  144. if this == nil || this.state == ConnStateClosed {
  145. return
  146. }
  147. this.Lock()
  148. defer this.Unlock()
  149. if this.state == ConnStateClosed {
  150. return
  151. }
  152. this.state = ConnStateClosed
  153. this.writer.Close()
  154. }
  155. func (this *Connection) NotifyTermination() {
  156. for i := 0; i < 16; i++ {
  157. this.RLock()
  158. if this.state == ConnStateClosed {
  159. this.RUnlock()
  160. break
  161. }
  162. this.RUnlock()
  163. buffer := alloc.NewSmallBuffer().Clear()
  164. buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
  165. this.outputBuffer(buffer)
  166. time.Sleep(time.Second)
  167. }
  168. this.Terminate()
  169. }
  170. func (this *Connection) ForceTimeout() {
  171. if this == nil {
  172. return
  173. }
  174. for i := 0; i < 5; i++ {
  175. if this.state == ConnStateClosed {
  176. return
  177. }
  178. time.Sleep(time.Minute)
  179. }
  180. go this.terminateOnce.Do(this.NotifyTermination)
  181. }
  182. // Close closes the connection.
  183. func (this *Connection) Close() error {
  184. if this == nil || this.state == ConnStateClosed || this.state == ConnStateReadyToClose {
  185. return errClosedConnection
  186. }
  187. log.Debug("KCP|Connection: Closing connection to ", this.remote)
  188. this.Lock()
  189. defer this.Unlock()
  190. if this.state == ConnStateActive {
  191. this.state = ConnStateReadyToClose
  192. if this.kcp.WaitSnd() == 0 {
  193. go this.terminateOnce.Do(this.NotifyTermination)
  194. } else {
  195. go this.ForceTimeout()
  196. }
  197. }
  198. if this.state == ConnStatePeerClosed {
  199. go this.Terminate()
  200. }
  201. return nil
  202. }
  203. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  204. func (this *Connection) LocalAddr() net.Addr {
  205. if this == nil {
  206. return nil
  207. }
  208. return this.local
  209. }
  210. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  211. func (this *Connection) RemoteAddr() net.Addr {
  212. if this == nil {
  213. return nil
  214. }
  215. return this.remote
  216. }
  217. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  218. func (this *Connection) SetDeadline(t time.Time) error {
  219. if this == nil || this.state != ConnStateActive {
  220. return errClosedConnection
  221. }
  222. this.Lock()
  223. defer this.Unlock()
  224. this.rd = t
  225. this.wd = t
  226. return nil
  227. }
  228. // SetReadDeadline implements the Conn SetReadDeadline method.
  229. func (this *Connection) SetReadDeadline(t time.Time) error {
  230. if this == nil || this.state != ConnStateActive {
  231. return errClosedConnection
  232. }
  233. this.Lock()
  234. defer this.Unlock()
  235. this.rd = t
  236. return nil
  237. }
  238. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  239. func (this *Connection) SetWriteDeadline(t time.Time) error {
  240. if this == nil || this.state != ConnStateActive {
  241. return errClosedConnection
  242. }
  243. this.Lock()
  244. defer this.Unlock()
  245. this.wd = t
  246. return nil
  247. }
  248. func (this *Connection) outputBuffer(payload *alloc.Buffer) {
  249. defer payload.Release()
  250. if this == nil {
  251. return
  252. }
  253. this.RLock()
  254. defer this.RUnlock()
  255. if this.state == ConnStatePeerClosed || this.state == ConnStateClosed {
  256. return
  257. }
  258. this.block.Seal(payload)
  259. this.writer.Write(payload.Value)
  260. }
  261. func (this *Connection) output(payload []byte) {
  262. if this == nil || this.state == ConnStateClosed {
  263. return
  264. }
  265. if this.state == ConnStateReadyToClose && this.kcp.WaitSnd() == 0 {
  266. go this.terminateOnce.Do(this.NotifyTermination)
  267. }
  268. if len(payload) < IKCP_OVERHEAD {
  269. return
  270. }
  271. buffer := alloc.NewBuffer().Clear().Append(payload)
  272. cmd := CommandData
  273. opt := Option(0)
  274. if this.state == ConnStateReadyToClose {
  275. opt = OptionClose
  276. }
  277. buffer.Prepend([]byte{byte(cmd), byte(opt)})
  278. this.outputBuffer(buffer)
  279. }
  280. // kcp update, input loop
  281. func (this *Connection) updateTask() {
  282. for this.state != ConnStateClosed {
  283. current := this.Elapsed()
  284. this.kcpAccess.Lock()
  285. this.kcp.Update(current)
  286. this.kcpAccess.Unlock()
  287. time.Sleep(time.Duration(effectiveConfig.Tti) * time.Millisecond)
  288. }
  289. }
  290. func (this *Connection) notifyReadEvent() {
  291. select {
  292. case this.chReadEvent <- struct{}{}:
  293. default:
  294. }
  295. }
  296. func (this *Connection) MarkPeerClose() {
  297. this.Lock()
  298. defer this.Unlock()
  299. if this.state == ConnStateReadyToClose {
  300. this.state = ConnStateClosed
  301. go this.Terminate()
  302. return
  303. }
  304. if this.state == ConnStateActive {
  305. this.state = ConnStatePeerClosed
  306. }
  307. this.kcpAccess.Lock()
  308. this.kcp.ClearSendQueue()
  309. this.kcpAccess.Unlock()
  310. }
  311. func (this *Connection) kcpInput(data []byte) {
  312. cmd := Command(data[0])
  313. opt := Option(data[1])
  314. if cmd == CommandTerminate {
  315. go this.Terminate()
  316. return
  317. }
  318. if opt == OptionClose {
  319. go this.MarkPeerClose()
  320. }
  321. this.kcpAccess.Lock()
  322. this.kcp.current = this.Elapsed()
  323. this.kcp.Input(data[2:])
  324. this.kcpAccess.Unlock()
  325. this.notifyReadEvent()
  326. }
  327. func (this *Connection) FetchInputFrom(conn net.Conn) {
  328. go func() {
  329. for {
  330. payload := alloc.NewBuffer()
  331. nBytes, err := conn.Read(payload.Value)
  332. if err != nil {
  333. return
  334. }
  335. payload.Slice(0, nBytes)
  336. if this.block.Open(payload) {
  337. this.kcpInput(payload.Value)
  338. } else {
  339. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  340. }
  341. payload.Release()
  342. }
  343. }()
  344. }
  345. func (this *Connection) Reusable() bool {
  346. return false
  347. }
  348. func (this *Connection) SetReusable(b bool) {}