connection.go 8.8 KB

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