connection.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. ackNoDelay bool
  61. writer io.WriteCloser
  62. since int64
  63. }
  64. // newUDPSession create a new udp session for client or server
  65. func newUDPSession(conv uint32, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *UDPSession {
  66. sess := new(UDPSession)
  67. sess.local = local
  68. sess.chReadEvent = make(chan struct{}, 1)
  69. sess.chWriteEvent = make(chan struct{}, 1)
  70. sess.remote = remote
  71. sess.block = block
  72. sess.writer = writerCloser
  73. sess.since = nowMillisec()
  74. mtu := uint32(effectiveConfig.Mtu - block.HeaderSize() - headerSize)
  75. sess.kcp = NewKCP(conv, mtu, func(buf []byte, size int) {
  76. log.Info(sess.local, " kcp output: ", buf[:size])
  77. if size >= IKCP_OVERHEAD {
  78. ext := alloc.NewBuffer().Clear().Append(buf[:size])
  79. cmd := cmdData
  80. opt := Option(0)
  81. if sess.state == ConnStateReadyToClose {
  82. opt = OptionClose
  83. }
  84. ext.Prepend([]byte{byte(cmd), byte(opt)})
  85. sess.output(ext)
  86. }
  87. })
  88. sess.kcp.WndSize(effectiveConfig.Sndwnd, effectiveConfig.Rcvwnd)
  89. sess.kcp.NoDelay(1, 20, 2, 1)
  90. sess.ackNoDelay = effectiveConfig.Acknodelay
  91. sess.kcp.current = sess.Elapsed()
  92. go sess.updateTask()
  93. log.Info("Created KCP conn to ", sess.RemoteAddr())
  94. return sess
  95. }
  96. func (this *UDPSession) Elapsed() uint32 {
  97. return uint32(nowMillisec() - this.since)
  98. }
  99. // Read implements the Conn Read method.
  100. func (s *UDPSession) Read(b []byte) (int, error) {
  101. if s.state == ConnStateReadyToClose || s.state == ConnStateClosed {
  102. return 0, io.EOF
  103. }
  104. for {
  105. s.Lock()
  106. if s.state == ConnStateReadyToClose || s.state == ConnStateClosed {
  107. s.Unlock()
  108. return 0, io.EOF
  109. }
  110. if !s.rd.IsZero() {
  111. if time.Now().After(s.rd) {
  112. s.Unlock()
  113. return 0, errTimeout
  114. }
  115. }
  116. nBytes := s.kcp.Recv(b)
  117. if nBytes > 0 {
  118. s.Unlock()
  119. return nBytes, nil
  120. }
  121. var timeout <-chan time.Time
  122. if !s.rd.IsZero() {
  123. delay := s.rd.Sub(time.Now())
  124. timeout = time.After(delay)
  125. }
  126. s.Unlock()
  127. select {
  128. case <-s.chReadEvent:
  129. case <-timeout:
  130. return 0, errTimeout
  131. }
  132. }
  133. }
  134. // Write implements the Conn Write method.
  135. func (s *UDPSession) Write(b []byte) (int, error) {
  136. log.Info("Trying to write ", len(b), " bytes. ", s.local)
  137. if s.state == ConnStateReadyToClose ||
  138. s.state == ConnStatePeerClosed ||
  139. s.state == ConnStateClosed {
  140. return 0, io.ErrClosedPipe
  141. }
  142. for {
  143. s.Lock()
  144. if s.state == ConnStateReadyToClose ||
  145. s.state == ConnStatePeerClosed ||
  146. s.state == ConnStateClosed {
  147. s.Unlock()
  148. return 0, io.ErrClosedPipe
  149. }
  150. if !s.wd.IsZero() {
  151. if time.Now().After(s.wd) { // timeout
  152. s.Unlock()
  153. return 0, errTimeout
  154. }
  155. }
  156. if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) {
  157. nBytes := len(b)
  158. log.Info("Writing ", nBytes, " bytes.", s.local)
  159. s.kcp.Send(b)
  160. s.kcp.current = s.Elapsed()
  161. s.kcp.flush()
  162. s.Unlock()
  163. return nBytes, nil
  164. }
  165. var timeout <-chan time.Time
  166. if !s.wd.IsZero() {
  167. delay := s.wd.Sub(time.Now())
  168. timeout = time.After(delay)
  169. }
  170. s.Unlock()
  171. // wait for write event or timeout
  172. select {
  173. case <-s.chWriteEvent:
  174. case <-timeout:
  175. return 0, errTimeout
  176. }
  177. }
  178. }
  179. func (this *UDPSession) Terminate() {
  180. if this.state == ConnStateClosed {
  181. return
  182. }
  183. this.Lock()
  184. defer this.Unlock()
  185. this.state = ConnStateClosed
  186. this.writer.Close()
  187. }
  188. func (this *UDPSession) NotifyTermination() {
  189. for i := 0; i < 16; i++ {
  190. this.Lock()
  191. if this.state == ConnStateClosed {
  192. this.Unlock()
  193. return
  194. }
  195. buffer := alloc.NewSmallBuffer().Clear()
  196. buffer.AppendBytes(byte(CommandTerminate), byte(OptionClose), byte(0), byte(0), byte(0), byte(0))
  197. this.output(buffer)
  198. time.Sleep(time.Second)
  199. this.Unlock()
  200. }
  201. this.Terminate()
  202. }
  203. // Close closes the connection.
  204. func (s *UDPSession) Close() error {
  205. log.Info("Closed ", s.local)
  206. s.Lock()
  207. defer s.Unlock()
  208. if s.state == ConnStateActive {
  209. s.state = ConnStateReadyToClose
  210. if s.kcp.WaitSnd() == 0 {
  211. go s.NotifyTermination()
  212. }
  213. }
  214. if s.state == ConnStatePeerClosed {
  215. go s.Terminate()
  216. }
  217. return nil
  218. }
  219. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  220. func (s *UDPSession) LocalAddr() net.Addr {
  221. return s.local
  222. }
  223. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  224. func (s *UDPSession) RemoteAddr() net.Addr { return s.remote }
  225. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  226. func (s *UDPSession) SetDeadline(t time.Time) error {
  227. s.Lock()
  228. defer s.Unlock()
  229. s.rd = t
  230. s.wd = t
  231. return nil
  232. }
  233. // SetReadDeadline implements the Conn SetReadDeadline method.
  234. func (s *UDPSession) SetReadDeadline(t time.Time) error {
  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. s.Lock()
  243. defer s.Unlock()
  244. s.wd = t
  245. return nil
  246. }
  247. func (s *UDPSession) output(payload *alloc.Buffer) {
  248. defer payload.Release()
  249. if s.state == ConnStatePeerClosed || s.state == ConnStateClosed {
  250. return
  251. }
  252. s.block.Seal(payload)
  253. s.writer.Write(payload.Value)
  254. }
  255. // kcp update, input loop
  256. func (s *UDPSession) updateTask() {
  257. ticker := time.NewTicker(20 * time.Millisecond)
  258. defer ticker.Stop()
  259. var nextupdate uint32 = 0
  260. for range ticker.C {
  261. s.Lock()
  262. if s.state == ConnStateClosed {
  263. s.Unlock()
  264. return
  265. }
  266. current := s.Elapsed()
  267. if !s.needUpdate && nextupdate == 0 {
  268. nextupdate = s.kcp.Check(current)
  269. }
  270. current = s.Elapsed()
  271. if s.needUpdate || current >= nextupdate {
  272. log.Info("Updating KCP: ", current, " addr ", s.LocalAddr())
  273. s.kcp.Update(current)
  274. nextupdate = s.kcp.Check(current)
  275. s.needUpdate = false
  276. }
  277. if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) {
  278. s.notifyWriteEvent()
  279. }
  280. s.Unlock()
  281. }
  282. }
  283. func (s *UDPSession) notifyReadEvent() {
  284. select {
  285. case s.chReadEvent <- struct{}{}:
  286. default:
  287. }
  288. }
  289. func (s *UDPSession) notifyWriteEvent() {
  290. select {
  291. case s.chWriteEvent <- struct{}{}:
  292. default:
  293. }
  294. }
  295. func (this *UDPSession) MarkPeerClose() {
  296. this.Lock()
  297. defer this.Unlock()
  298. if this.state == ConnStateReadyToClose {
  299. this.state = ConnStateClosed
  300. go this.Terminate()
  301. return
  302. }
  303. if this.state == ConnStateActive {
  304. this.state = ConnStatePeerClosed
  305. }
  306. }
  307. func (s *UDPSession) kcpInput(data []byte) {
  308. cmd := Command(data[0])
  309. opt := Option(data[1])
  310. if cmd == CommandTerminate {
  311. go s.Terminate()
  312. return
  313. }
  314. if opt == OptionClose {
  315. go s.MarkPeerClose()
  316. }
  317. s.kcpAccess.Lock()
  318. s.kcp.current = s.Elapsed()
  319. log.Info(s.local, " kcp input: ", data[2:])
  320. ret := s.kcp.Input(data[2:])
  321. log.Info("kcp input returns ", ret)
  322. if s.ackNoDelay {
  323. s.kcp.current = s.Elapsed()
  324. s.kcp.flush()
  325. } else {
  326. s.needUpdate = true
  327. }
  328. s.kcpAccess.Unlock()
  329. s.notifyReadEvent()
  330. }
  331. func (this *UDPSession) FetchInputFrom(conn net.Conn) {
  332. go func() {
  333. for {
  334. payload := alloc.NewBuffer()
  335. nBytes, err := conn.Read(payload.Value)
  336. if err != nil {
  337. return
  338. }
  339. payload.Slice(0, nBytes)
  340. if this.block.Open(payload) {
  341. log.Info("Client fetching ", payload.Len(), " bytes.")
  342. this.kcpInput(payload.Value)
  343. }
  344. payload.Release()
  345. }
  346. }()
  347. }
  348. func (this *UDPSession) Reusable() bool {
  349. return false
  350. }
  351. func (this *UDPSession) SetReusable(b bool) {}