connection.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. chWriteEvent 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.chWriteEvent = make(chan struct{}, 1)
  69. sess.remote = remote
  70. sess.block = block
  71. sess.writer = writerCloser
  72. sess.since = nowMillisec()
  73. mtu := uint32(effectiveConfig.Mtu - block.HeaderSize() - headerSize)
  74. sess.kcp = NewKCP(conv, mtu, func(buf []byte, size int) {
  75. if size >= IKCP_OVERHEAD {
  76. ext := alloc.NewBuffer().Clear().Append(buf[:size])
  77. cmd := cmdData
  78. opt := Option(0)
  79. if sess.state == ConnStateReadyToClose {
  80. opt = OptionClose
  81. }
  82. ext.Prepend([]byte{byte(cmd), byte(opt)})
  83. sess.output(ext)
  84. }
  85. })
  86. sess.kcp.WndSize(effectiveConfig.Sndwnd, effectiveConfig.Rcvwnd)
  87. sess.kcp.NoDelay(1, 20, 2, 1)
  88. sess.kcp.current = sess.Elapsed()
  89. go sess.updateTask()
  90. return sess
  91. }
  92. func (this *UDPSession) Elapsed() uint32 {
  93. return uint32(nowMillisec() - this.since)
  94. }
  95. // Read implements the Conn Read method.
  96. func (s *UDPSession) Read(b []byte) (int, error) {
  97. if s.state == ConnStateReadyToClose || s.state == ConnStateClosed {
  98. return 0, io.EOF
  99. }
  100. for {
  101. s.Lock()
  102. if s.state == ConnStateReadyToClose || s.state == ConnStateClosed {
  103. s.Unlock()
  104. return 0, io.EOF
  105. }
  106. if !s.rd.IsZero() {
  107. if time.Now().After(s.rd) {
  108. s.Unlock()
  109. return 0, errTimeout
  110. }
  111. }
  112. nBytes := s.kcp.Recv(b)
  113. if nBytes > 0 {
  114. s.Unlock()
  115. return nBytes, nil
  116. }
  117. var timeout <-chan time.Time
  118. if !s.rd.IsZero() {
  119. delay := s.rd.Sub(time.Now())
  120. timeout = time.After(delay)
  121. }
  122. s.Unlock()
  123. select {
  124. case <-s.chReadEvent:
  125. case <-timeout:
  126. return 0, errTimeout
  127. }
  128. }
  129. }
  130. // Write implements the Conn Write method.
  131. func (s *UDPSession) Write(b []byte) (int, error) {
  132. if s.state == ConnStateReadyToClose ||
  133. s.state == ConnStatePeerClosed ||
  134. s.state == ConnStateClosed {
  135. return 0, io.ErrClosedPipe
  136. }
  137. for {
  138. if s.state == ConnStateReadyToClose ||
  139. s.state == ConnStatePeerClosed ||
  140. s.state == ConnStateClosed {
  141. return 0, io.ErrClosedPipe
  142. }
  143. s.kcpAccess.Lock()
  144. if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) {
  145. nBytes := len(b)
  146. s.kcp.Send(b)
  147. s.kcp.current = s.Elapsed()
  148. s.kcp.flush()
  149. s.kcpAccess.Unlock()
  150. return nBytes, nil
  151. }
  152. s.kcpAccess.Unlock()
  153. if !s.wd.IsZero() && s.wd.Before(time.Now()) {
  154. return 0, errTimeout
  155. }
  156. time.Sleep(time.Duration(s.kcp.WaitSnd()*5) * time.Millisecond)
  157. }
  158. }
  159. func (this *UDPSession) Terminate() {
  160. if 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.Lock()
  174. if this.state == ConnStateClosed {
  175. this.Unlock()
  176. break
  177. }
  178. buffer := alloc.NewSmallBuffer().Clear()
  179. buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
  180. this.output(buffer)
  181. time.Sleep(time.Second)
  182. this.Unlock()
  183. }
  184. this.Terminate()
  185. }
  186. // Close closes the connection.
  187. func (s *UDPSession) Close() error {
  188. log.Debug("KCP|Connection: Closing connection to ", s.remote)
  189. s.Lock()
  190. defer s.Unlock()
  191. if s.state == ConnStateActive {
  192. s.state = ConnStateReadyToClose
  193. if s.kcp.WaitSnd() == 0 {
  194. go s.NotifyTermination()
  195. }
  196. }
  197. if s.state == ConnStatePeerClosed {
  198. go s.Terminate()
  199. }
  200. return nil
  201. }
  202. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  203. func (s *UDPSession) LocalAddr() net.Addr {
  204. return s.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 (s *UDPSession) RemoteAddr() net.Addr { return s.remote }
  208. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  209. func (s *UDPSession) SetDeadline(t time.Time) error {
  210. s.Lock()
  211. defer s.Unlock()
  212. s.rd = t
  213. s.wd = t
  214. return nil
  215. }
  216. // SetReadDeadline implements the Conn SetReadDeadline method.
  217. func (s *UDPSession) SetReadDeadline(t time.Time) error {
  218. s.Lock()
  219. defer s.Unlock()
  220. s.rd = t
  221. return nil
  222. }
  223. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  224. func (s *UDPSession) SetWriteDeadline(t time.Time) error {
  225. s.Lock()
  226. defer s.Unlock()
  227. s.wd = t
  228. return nil
  229. }
  230. func (s *UDPSession) output(payload *alloc.Buffer) {
  231. defer payload.Release()
  232. if s.state == ConnStatePeerClosed || s.state == ConnStateClosed {
  233. return
  234. }
  235. s.block.Seal(payload)
  236. s.writer.Write(payload.Value)
  237. }
  238. // kcp update, input loop
  239. func (s *UDPSession) updateTask() {
  240. for s.state != ConnStateClosed {
  241. current := s.Elapsed()
  242. s.kcp.Update(current)
  243. interval := s.kcp.Check(s.Elapsed())
  244. time.Sleep(time.Duration(interval) * time.Millisecond)
  245. }
  246. }
  247. func (s *UDPSession) notifyReadEvent() {
  248. select {
  249. case s.chReadEvent <- struct{}{}:
  250. default:
  251. }
  252. }
  253. func (s *UDPSession) notifyWriteEvent() {
  254. select {
  255. case s.chWriteEvent <- struct{}{}:
  256. default:
  257. }
  258. }
  259. func (this *UDPSession) MarkPeerClose() {
  260. this.Lock()
  261. defer this.Unlock()
  262. if this.state == ConnStateReadyToClose {
  263. this.state = ConnStateClosed
  264. go this.Terminate()
  265. return
  266. }
  267. if this.state == ConnStateActive {
  268. this.state = ConnStatePeerClosed
  269. }
  270. }
  271. func (s *UDPSession) kcpInput(data []byte) {
  272. cmd := Command(data[0])
  273. opt := Option(data[1])
  274. if cmd == CommandTerminate {
  275. go s.Terminate()
  276. return
  277. }
  278. if opt == OptionClose {
  279. go s.MarkPeerClose()
  280. }
  281. s.kcpAccess.Lock()
  282. s.kcp.current = s.Elapsed()
  283. s.kcp.Input(data[2:])
  284. s.kcpAccess.Unlock()
  285. s.notifyReadEvent()
  286. }
  287. func (this *UDPSession) FetchInputFrom(conn net.Conn) {
  288. go func() {
  289. for {
  290. payload := alloc.NewBuffer()
  291. nBytes, err := conn.Read(payload.Value)
  292. if err != nil {
  293. return
  294. }
  295. payload.Slice(0, nBytes)
  296. if this.block.Open(payload) {
  297. this.kcpInput(payload.Value)
  298. } else {
  299. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  300. }
  301. payload.Release()
  302. }
  303. }()
  304. }
  305. func (this *UDPSession) Reusable() bool {
  306. return false
  307. }
  308. func (this *UDPSession) SetReusable(b bool) {}