connection.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package kcp
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. "github.com/v2ray/v2ray-core/common/log"
  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. type State int32
  19. const (
  20. StateActive State = 0
  21. StateReadyToClose State = 1
  22. StatePeerClosed State = 2
  23. StateTerminating State = 3
  24. StateTerminated State = 4
  25. )
  26. const (
  27. headerSize uint32 = 2
  28. )
  29. func nowMillisec() int64 {
  30. now := time.Now()
  31. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  32. }
  33. type RountTripInfo struct {
  34. sync.RWMutex
  35. variation uint32
  36. srtt uint32
  37. rto uint32
  38. minRtt uint32
  39. }
  40. func (this *RountTripInfo) Update(rtt uint32) {
  41. if rtt > 0x7FFFFFFF {
  42. return
  43. }
  44. this.Lock()
  45. defer this.Unlock()
  46. // https://tools.ietf.org/html/rfc6298
  47. if this.srtt == 0 {
  48. this.srtt = rtt
  49. this.variation = rtt / 2
  50. } else {
  51. delta := rtt - this.srtt
  52. if this.srtt > rtt {
  53. delta = this.srtt - rtt
  54. }
  55. this.variation = (3*this.variation + delta) / 4
  56. this.srtt = (7*this.srtt + rtt) / 8
  57. if this.srtt < this.minRtt {
  58. this.srtt = this.minRtt
  59. }
  60. }
  61. var rto uint32
  62. if this.minRtt < 4*this.variation {
  63. rto = this.srtt + 4*this.variation
  64. } else {
  65. rto = this.srtt + this.variation
  66. }
  67. if rto > 10000 {
  68. rto = 10000
  69. }
  70. this.rto = rto * 3 / 2
  71. }
  72. func (this *RountTripInfo) Timeout() uint32 {
  73. this.RLock()
  74. defer this.RUnlock()
  75. return this.rto
  76. }
  77. func (this *RountTripInfo) SmoothedTime() uint32 {
  78. this.RLock()
  79. defer this.RUnlock()
  80. return this.srtt
  81. }
  82. // Connection is a KCP connection over UDP.
  83. type Connection struct {
  84. block Authenticator
  85. local, remote net.Addr
  86. rd time.Time
  87. wd time.Time // write deadline
  88. writer io.WriteCloser
  89. since int64
  90. dataInputCond *sync.Cond
  91. conv uint16
  92. state State
  93. stateBeginTime uint32
  94. lastIncomingTime uint32
  95. sendingUpdated bool
  96. lastPingTime uint32
  97. mss uint32
  98. roundTrip *RountTripInfo
  99. interval uint32
  100. receivingWorker *ReceivingWorker
  101. sendingWorker *SendingWorker
  102. fastresend uint32
  103. congestionControl bool
  104. output *BufferedSegmentWriter
  105. }
  106. // NewConnection create a new KCP connection between local and remote.
  107. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  108. log.Info("KCP|Connection: creating connection ", conv)
  109. conn := new(Connection)
  110. conn.local = local
  111. conn.remote = remote
  112. conn.block = block
  113. conn.writer = writerCloser
  114. conn.since = nowMillisec()
  115. conn.dataInputCond = sync.NewCond(new(sync.Mutex))
  116. authWriter := &AuthenticationWriter{
  117. Authenticator: block,
  118. Writer: writerCloser,
  119. }
  120. conn.conv = conv
  121. conn.output = NewSegmentWriter(authWriter)
  122. conn.mss = authWriter.Mtu() - DataSegmentOverhead
  123. conn.roundTrip = &RountTripInfo{
  124. rto: 100,
  125. minRtt: effectiveConfig.Tti,
  126. }
  127. conn.interval = effectiveConfig.Tti
  128. conn.receivingWorker = NewReceivingWorker(conn)
  129. conn.fastresend = 2
  130. conn.congestionControl = effectiveConfig.Congestion
  131. conn.sendingWorker = NewSendingWorker(conn)
  132. go conn.updateTask()
  133. return conn
  134. }
  135. func (this *Connection) Elapsed() uint32 {
  136. return uint32(nowMillisec() - this.since)
  137. }
  138. // Read implements the Conn Read method.
  139. func (this *Connection) Read(b []byte) (int, error) {
  140. if this == nil {
  141. return 0, io.EOF
  142. }
  143. for {
  144. if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
  145. return 0, io.EOF
  146. }
  147. nBytes := this.receivingWorker.Read(b)
  148. if nBytes > 0 {
  149. return nBytes, nil
  150. }
  151. var timer *time.Timer
  152. if !this.rd.IsZero() {
  153. duration := this.rd.Sub(time.Now())
  154. if duration <= 0 {
  155. return 0, errTimeout
  156. }
  157. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  158. }
  159. this.dataInputCond.L.Lock()
  160. this.dataInputCond.Wait()
  161. this.dataInputCond.L.Unlock()
  162. if timer != nil {
  163. timer.Stop()
  164. }
  165. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  166. return 0, errTimeout
  167. }
  168. }
  169. }
  170. // Write implements the Conn Write method.
  171. func (this *Connection) Write(b []byte) (int, error) {
  172. if this == nil || this.State() != StateActive {
  173. return 0, io.ErrClosedPipe
  174. }
  175. totalWritten := 0
  176. for {
  177. if this == nil || this.State() != StateActive {
  178. return totalWritten, io.ErrClosedPipe
  179. }
  180. nBytes := this.sendingWorker.Push(b[totalWritten:])
  181. if nBytes > 0 {
  182. totalWritten += nBytes
  183. if totalWritten == len(b) {
  184. return totalWritten, nil
  185. }
  186. }
  187. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  188. return totalWritten, errTimeout
  189. }
  190. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  191. time.Sleep(time.Second)
  192. }
  193. }
  194. func (this *Connection) SetState(state State) {
  195. current := this.Elapsed()
  196. atomic.StoreInt32((*int32)(&this.state), int32(state))
  197. atomic.StoreUint32(&this.stateBeginTime, current)
  198. log.Info("KCP|Connection: Entering state ", state, " at ", current)
  199. switch state {
  200. case StateReadyToClose:
  201. this.receivingWorker.CloseRead()
  202. case StatePeerClosed:
  203. this.sendingWorker.CloseWrite()
  204. case StateTerminating:
  205. this.receivingWorker.CloseRead()
  206. this.sendingWorker.CloseWrite()
  207. case StateTerminated:
  208. this.receivingWorker.CloseRead()
  209. this.sendingWorker.CloseWrite()
  210. }
  211. }
  212. // Close closes the connection.
  213. func (this *Connection) Close() error {
  214. if this == nil {
  215. return errClosedConnection
  216. }
  217. this.dataInputCond.Broadcast()
  218. state := this.State()
  219. if state == StateReadyToClose ||
  220. state == StateTerminating ||
  221. state == StateTerminated {
  222. return errClosedConnection
  223. }
  224. log.Info("KCP|Connection: Closing connection to ", this.remote)
  225. if state == StateActive {
  226. this.SetState(StateReadyToClose)
  227. }
  228. if state == StatePeerClosed {
  229. this.SetState(StateTerminating)
  230. }
  231. return nil
  232. }
  233. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  234. func (this *Connection) LocalAddr() net.Addr {
  235. if this == nil {
  236. return nil
  237. }
  238. return this.local
  239. }
  240. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  241. func (this *Connection) RemoteAddr() net.Addr {
  242. if this == nil {
  243. return nil
  244. }
  245. return this.remote
  246. }
  247. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  248. func (this *Connection) SetDeadline(t time.Time) error {
  249. if err := this.SetReadDeadline(t); err != nil {
  250. return err
  251. }
  252. if err := this.SetWriteDeadline(t); err != nil {
  253. return err
  254. }
  255. return nil
  256. }
  257. // SetReadDeadline implements the Conn SetReadDeadline method.
  258. func (this *Connection) SetReadDeadline(t time.Time) error {
  259. if this == nil || this.State() != StateActive {
  260. return errClosedConnection
  261. }
  262. this.rd = t
  263. return nil
  264. }
  265. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  266. func (this *Connection) SetWriteDeadline(t time.Time) error {
  267. if this == nil || this.State() != StateActive {
  268. return errClosedConnection
  269. }
  270. this.wd = t
  271. return nil
  272. }
  273. // kcp update, input loop
  274. func (this *Connection) updateTask() {
  275. for this.State() != StateTerminated {
  276. this.flush()
  277. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  278. if this.State() == StateTerminating {
  279. interval = time.Second
  280. }
  281. time.Sleep(interval)
  282. }
  283. this.Terminate()
  284. }
  285. func (this *Connection) FetchInputFrom(conn net.Conn) {
  286. go func() {
  287. payload := alloc.NewBuffer()
  288. defer payload.Release()
  289. for {
  290. payload.Reset()
  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.Input(payload.Value)
  298. } else {
  299. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  300. }
  301. }
  302. }()
  303. }
  304. func (this *Connection) Reusable() bool {
  305. return false
  306. }
  307. func (this *Connection) SetReusable(b bool) {}
  308. func (this *Connection) Terminate() {
  309. if this == nil || this.writer == nil {
  310. return
  311. }
  312. log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
  313. this.writer.Close()
  314. }
  315. func (this *Connection) HandleOption(opt SegmentOption) {
  316. if (opt & SegmentOptionClose) == SegmentOptionClose {
  317. this.OnPeerClosed()
  318. }
  319. }
  320. func (this *Connection) OnPeerClosed() {
  321. state := this.State()
  322. if state == StateReadyToClose {
  323. this.SetState(StateTerminating)
  324. }
  325. if state == StateActive {
  326. this.SetState(StatePeerClosed)
  327. }
  328. }
  329. // Input when you received a low level packet (eg. UDP packet), call it
  330. func (this *Connection) Input(data []byte) int {
  331. current := this.Elapsed()
  332. atomic.StoreUint32(&this.lastIncomingTime, current)
  333. var seg Segment
  334. for {
  335. seg, data = ReadSegment(data)
  336. if seg == nil {
  337. break
  338. }
  339. switch seg := seg.(type) {
  340. case *DataSegment:
  341. this.HandleOption(seg.Opt)
  342. this.receivingWorker.ProcessSegment(seg)
  343. this.dataInputCond.Signal()
  344. case *AckSegment:
  345. this.HandleOption(seg.Opt)
  346. this.sendingWorker.ProcessSegment(current, seg)
  347. case *CmdOnlySegment:
  348. this.HandleOption(seg.Opt)
  349. if seg.Cmd == SegmentCommandTerminated {
  350. state := this.State()
  351. if state == StateActive ||
  352. state == StateReadyToClose ||
  353. state == StatePeerClosed {
  354. this.SetState(StateTerminating)
  355. } else if state == StateTerminating {
  356. this.SetState(StateTerminated)
  357. }
  358. }
  359. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  360. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  361. default:
  362. }
  363. }
  364. return 0
  365. }
  366. func (this *Connection) flush() {
  367. current := this.Elapsed()
  368. if this.State() == StateTerminated {
  369. return
  370. }
  371. if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
  372. this.Close()
  373. }
  374. if this.State() == StateTerminating {
  375. this.output.Write(&CmdOnlySegment{
  376. Conv: this.conv,
  377. Cmd: SegmentCommandTerminated,
  378. })
  379. this.output.Flush()
  380. if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
  381. this.SetState(StateTerminated)
  382. }
  383. return
  384. }
  385. if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
  386. this.SetState(StateTerminating)
  387. }
  388. // flush acknowledges
  389. this.receivingWorker.Flush(current)
  390. this.sendingWorker.Flush(current)
  391. if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
  392. seg := NewCmdOnlySegment()
  393. seg.Conv = this.conv
  394. seg.Cmd = SegmentCommandPing
  395. seg.ReceivinNext = this.receivingWorker.nextNumber
  396. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  397. if this.State() == StateReadyToClose {
  398. seg.Opt = SegmentOptionClose
  399. }
  400. this.output.Write(seg)
  401. this.lastPingTime = current
  402. this.sendingUpdated = false
  403. seg.Release()
  404. }
  405. // flash remain segments
  406. this.output.Flush()
  407. }
  408. func (this *Connection) State() State {
  409. return State(atomic.LoadInt32((*int32)(&this.state)))
  410. }