connection.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 = 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. }
  57. // NewConnection create a new KCP connection between local and remote.
  58. func NewConnection(conv uint32, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  59. conn := new(Connection)
  60. conn.local = local
  61. conn.chReadEvent = make(chan struct{}, 1)
  62. conn.remote = remote
  63. conn.block = block
  64. conn.writer = writerCloser
  65. conn.since = nowMillisec()
  66. mtu := uint32(effectiveConfig.Mtu - block.HeaderSize() - headerSize)
  67. conn.kcp = NewKCP(conv, mtu, conn.output)
  68. conn.kcp.WndSize(effectiveConfig.GetSendingWindowSize(), effectiveConfig.GetReceivingWindowSize())
  69. conn.kcp.NoDelay(1, 20, 2, effectiveConfig.Congestion)
  70. conn.kcp.current = conn.Elapsed()
  71. go conn.updateTask()
  72. return conn
  73. }
  74. func (this *Connection) Elapsed() uint32 {
  75. return uint32(nowMillisec() - this.since)
  76. }
  77. // Read implements the Conn Read method.
  78. func (this *Connection) Read(b []byte) (int, error) {
  79. if this == nil || this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
  80. return 0, io.EOF
  81. }
  82. for {
  83. this.RLock()
  84. if this.state == ConnStateReadyToClose || this.state == ConnStateClosed {
  85. this.RUnlock()
  86. return 0, io.EOF
  87. }
  88. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  89. this.RUnlock()
  90. return 0, errTimeout
  91. }
  92. this.RUnlock()
  93. this.kcpAccess.Lock()
  94. nBytes := this.kcp.Recv(b)
  95. this.kcpAccess.Unlock()
  96. if nBytes > 0 {
  97. return nBytes, nil
  98. }
  99. select {
  100. case <-this.chReadEvent:
  101. case <-time.After(time.Second):
  102. }
  103. }
  104. }
  105. // Write implements the Conn Write method.
  106. func (this *Connection) Write(b []byte) (int, error) {
  107. if this == nil ||
  108. this.state == ConnStateReadyToClose ||
  109. this.state == ConnStatePeerClosed ||
  110. this.state == ConnStateClosed {
  111. return 0, io.ErrClosedPipe
  112. }
  113. for {
  114. this.RLock()
  115. if this.state == ConnStateReadyToClose ||
  116. this.state == ConnStatePeerClosed ||
  117. this.state == ConnStateClosed {
  118. this.RUnlock()
  119. return 0, io.ErrClosedPipe
  120. }
  121. this.RUnlock()
  122. this.kcpAccess.Lock()
  123. if this.kcp.WaitSnd() < int(this.kcp.snd_wnd) {
  124. nBytes := len(b)
  125. this.kcp.Send(b)
  126. this.kcp.current = this.Elapsed()
  127. this.kcp.flush()
  128. this.kcpAccess.Unlock()
  129. return nBytes, nil
  130. }
  131. this.kcpAccess.Unlock()
  132. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  133. return 0, errTimeout
  134. }
  135. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  136. time.Sleep(time.Second)
  137. }
  138. }
  139. func (this *Connection) Terminate() {
  140. if this == nil || this.state == ConnStateClosed {
  141. return
  142. }
  143. this.Lock()
  144. defer this.Unlock()
  145. if this.state == ConnStateClosed {
  146. return
  147. }
  148. this.state = ConnStateClosed
  149. this.writer.Close()
  150. }
  151. func (this *Connection) NotifyTermination() {
  152. for i := 0; i < 16; i++ {
  153. this.RLock()
  154. if this.state == ConnStateClosed {
  155. this.RUnlock()
  156. break
  157. }
  158. this.RUnlock()
  159. buffer := alloc.NewSmallBuffer().Clear()
  160. buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
  161. this.outputBuffer(buffer)
  162. time.Sleep(time.Second)
  163. }
  164. this.Terminate()
  165. }
  166. func (this *Connection) ForceTimeout() {
  167. if this == nil {
  168. return
  169. }
  170. for i := 0; i < 5; i++ {
  171. if this.state == ConnStateClosed {
  172. return
  173. }
  174. time.Sleep(time.Minute)
  175. }
  176. go this.terminateOnce.Do(this.NotifyTermination)
  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.terminateOnce.Do(this.NotifyTermination)
  190. } else {
  191. go this.ForceTimeout()
  192. }
  193. }
  194. if this.state == ConnStatePeerClosed {
  195. go this.Terminate()
  196. }
  197. return nil
  198. }
  199. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  200. func (this *Connection) LocalAddr() net.Addr {
  201. if this == nil {
  202. return nil
  203. }
  204. return this.local
  205. }
  206. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  207. func (this *Connection) RemoteAddr() net.Addr {
  208. if this == nil {
  209. return nil
  210. }
  211. return this.remote
  212. }
  213. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  214. func (this *Connection) SetDeadline(t time.Time) error {
  215. if this == nil || this.state != ConnStateActive {
  216. return errClosedConnection
  217. }
  218. this.Lock()
  219. defer this.Unlock()
  220. this.rd = t
  221. this.wd = t
  222. return nil
  223. }
  224. // SetReadDeadline implements the Conn SetReadDeadline method.
  225. func (this *Connection) SetReadDeadline(t time.Time) error {
  226. if this == nil || this.state != ConnStateActive {
  227. return errClosedConnection
  228. }
  229. this.Lock()
  230. defer this.Unlock()
  231. this.rd = t
  232. return nil
  233. }
  234. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  235. func (this *Connection) SetWriteDeadline(t time.Time) error {
  236. if this == nil || this.state != ConnStateActive {
  237. return errClosedConnection
  238. }
  239. this.Lock()
  240. defer this.Unlock()
  241. this.wd = t
  242. return nil
  243. }
  244. func (this *Connection) outputBuffer(payload *alloc.Buffer) {
  245. defer payload.Release()
  246. if this == nil {
  247. return
  248. }
  249. this.RLock()
  250. defer this.RUnlock()
  251. if this.state == ConnStatePeerClosed || this.state == ConnStateClosed {
  252. return
  253. }
  254. this.block.Seal(payload)
  255. this.writer.Write(payload.Value)
  256. }
  257. func (this *Connection) output(payload []byte) {
  258. if this == nil || this.state == ConnStateClosed {
  259. return
  260. }
  261. if this.state == ConnStateReadyToClose && this.kcp.WaitSnd() == 0 {
  262. go this.terminateOnce.Do(this.NotifyTermination)
  263. }
  264. if len(payload) < IKCP_OVERHEAD {
  265. return
  266. }
  267. buffer := alloc.NewBuffer().Clear().Append(payload)
  268. cmd := CommandData
  269. opt := Option(0)
  270. if this.state == ConnStateReadyToClose {
  271. opt = OptionClose
  272. }
  273. buffer.Prepend([]byte{byte(cmd), byte(opt)})
  274. this.outputBuffer(buffer)
  275. }
  276. // kcp update, input loop
  277. func (this *Connection) updateTask() {
  278. for this.state != ConnStateClosed {
  279. current := this.Elapsed()
  280. this.kcpAccess.Lock()
  281. this.kcp.Update(current)
  282. interval := this.kcp.Check(this.Elapsed())
  283. this.kcpAccess.Unlock()
  284. sleep := interval - current
  285. if sleep < 10 {
  286. sleep = 10
  287. }
  288. time.Sleep(time.Duration(sleep) * time.Millisecond)
  289. }
  290. }
  291. func (this *Connection) notifyReadEvent() {
  292. select {
  293. case this.chReadEvent <- struct{}{}:
  294. default:
  295. }
  296. }
  297. func (this *Connection) MarkPeerClose() {
  298. this.Lock()
  299. defer this.Unlock()
  300. if this.state == ConnStateReadyToClose {
  301. this.state = ConnStateClosed
  302. go this.Terminate()
  303. return
  304. }
  305. if this.state == ConnStateActive {
  306. this.state = ConnStatePeerClosed
  307. }
  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) {}