connection.go 8.2 KB

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