connection.go 7.6 KB

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