connection.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package kcp
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "v2ray.com/core/common/errors"
  9. "v2ray.com/core/common/log"
  10. "v2ray.com/core/common/predicate"
  11. "v2ray.com/core/transport/internet/internal"
  12. )
  13. var (
  14. ErrIOTimeout = errors.New("Read/Write timeout")
  15. ErrClosedListener = errors.New("Listener closed.")
  16. ErrClosedConnection = errors.New("Connection closed.")
  17. )
  18. type State int32
  19. func (v State) Is(states ...State) bool {
  20. for _, state := range states {
  21. if v == state {
  22. return true
  23. }
  24. }
  25. return false
  26. }
  27. const (
  28. StateActive State = 0
  29. StateReadyToClose State = 1
  30. StatePeerClosed State = 2
  31. StateTerminating State = 3
  32. StatePeerTerminating State = 4
  33. StateTerminated State = 5
  34. )
  35. const (
  36. headerSize uint32 = 2
  37. )
  38. func nowMillisec() int64 {
  39. now := time.Now()
  40. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  41. }
  42. type RoundTripInfo struct {
  43. sync.RWMutex
  44. variation uint32
  45. srtt uint32
  46. rto uint32
  47. minRtt uint32
  48. updatedTimestamp uint32
  49. }
  50. func (v *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
  51. v.Lock()
  52. defer v.Unlock()
  53. if current-v.updatedTimestamp < 3000 {
  54. return
  55. }
  56. v.updatedTimestamp = current
  57. v.rto = rto
  58. }
  59. func (v *RoundTripInfo) Update(rtt uint32, current uint32) {
  60. if rtt > 0x7FFFFFFF {
  61. return
  62. }
  63. v.Lock()
  64. defer v.Unlock()
  65. // https://tools.ietf.org/html/rfc6298
  66. if v.srtt == 0 {
  67. v.srtt = rtt
  68. v.variation = rtt / 2
  69. } else {
  70. delta := rtt - v.srtt
  71. if v.srtt > rtt {
  72. delta = v.srtt - rtt
  73. }
  74. v.variation = (3*v.variation + delta) / 4
  75. v.srtt = (7*v.srtt + rtt) / 8
  76. if v.srtt < v.minRtt {
  77. v.srtt = v.minRtt
  78. }
  79. }
  80. var rto uint32
  81. if v.minRtt < 4*v.variation {
  82. rto = v.srtt + 4*v.variation
  83. } else {
  84. rto = v.srtt + v.variation
  85. }
  86. if rto > 10000 {
  87. rto = 10000
  88. }
  89. v.rto = rto * 5 / 4
  90. v.updatedTimestamp = current
  91. }
  92. func (v *RoundTripInfo) Timeout() uint32 {
  93. v.RLock()
  94. defer v.RUnlock()
  95. return v.rto
  96. }
  97. func (v *RoundTripInfo) SmoothedTime() uint32 {
  98. v.RLock()
  99. defer v.RUnlock()
  100. return v.srtt
  101. }
  102. type Updater struct {
  103. interval time.Duration
  104. shouldContinue predicate.Predicate
  105. shouldTerminate predicate.Predicate
  106. updateFunc func()
  107. notifier chan bool
  108. }
  109. func NewUpdater(interval uint32, shouldContinue predicate.Predicate, shouldTerminate predicate.Predicate, updateFunc func()) *Updater {
  110. u := &Updater{
  111. interval: time.Duration(interval) * time.Millisecond,
  112. shouldContinue: shouldContinue,
  113. shouldTerminate: shouldTerminate,
  114. updateFunc: updateFunc,
  115. notifier: make(chan bool, 1),
  116. }
  117. go u.Run()
  118. return u
  119. }
  120. func (v *Updater) WakeUp() {
  121. select {
  122. case v.notifier <- true:
  123. default:
  124. }
  125. }
  126. func (v *Updater) Run() {
  127. for <-v.notifier {
  128. if v.shouldTerminate() {
  129. return
  130. }
  131. for v.shouldContinue() {
  132. v.updateFunc()
  133. time.Sleep(v.interval)
  134. }
  135. }
  136. }
  137. type SystemConnection interface {
  138. net.Conn
  139. Id() internal.ConnectionId
  140. Reset(func([]Segment))
  141. Overhead() int
  142. }
  143. // Connection is a KCP connection over UDP.
  144. type Connection struct {
  145. conn SystemConnection
  146. connRecycler internal.ConnectionRecyler
  147. rd time.Time
  148. wd time.Time // write deadline
  149. since int64
  150. dataInput chan bool
  151. dataOutput chan bool
  152. Config *Config
  153. conv uint16
  154. state State
  155. stateBeginTime uint32
  156. lastIncomingTime uint32
  157. lastPingTime uint32
  158. mss uint32
  159. roundTrip *RoundTripInfo
  160. receivingWorker *ReceivingWorker
  161. sendingWorker *SendingWorker
  162. output SegmentWriter
  163. dataUpdater *Updater
  164. pingUpdater *Updater
  165. reusable bool
  166. }
  167. // NewConnection create a new KCP connection between local and remote.
  168. func NewConnection(conv uint16, sysConn SystemConnection, recycler internal.ConnectionRecyler, config *Config) *Connection {
  169. log.Info("KCP|Connection: creating connection ", conv)
  170. conn := &Connection{
  171. conv: conv,
  172. conn: sysConn,
  173. connRecycler: recycler,
  174. since: nowMillisec(),
  175. dataInput: make(chan bool, 1),
  176. dataOutput: make(chan bool, 1),
  177. Config: config,
  178. output: NewSegmentWriter(sysConn),
  179. mss: config.GetMTUValue() - uint32(sysConn.Overhead()) - DataSegmentOverhead,
  180. roundTrip: &RoundTripInfo{
  181. rto: 100,
  182. minRtt: config.GetTTIValue(),
  183. },
  184. }
  185. sysConn.Reset(conn.Input)
  186. conn.receivingWorker = NewReceivingWorker(conn)
  187. conn.sendingWorker = NewSendingWorker(conn)
  188. isTerminating := func() bool {
  189. return conn.State().Is(StateTerminating, StateTerminated)
  190. }
  191. isTerminated := func() bool {
  192. return conn.State() == StateTerminated
  193. }
  194. conn.dataUpdater = NewUpdater(
  195. config.GetTTIValue(),
  196. predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
  197. isTerminating,
  198. conn.updateTask)
  199. conn.pingUpdater = NewUpdater(
  200. 5000, // 5 seconds
  201. predicate.Not(isTerminated),
  202. isTerminated,
  203. conn.updateTask)
  204. conn.pingUpdater.WakeUp()
  205. return conn
  206. }
  207. func (v *Connection) Elapsed() uint32 {
  208. return uint32(nowMillisec() - v.since)
  209. }
  210. func (v *Connection) OnDataInput() {
  211. select {
  212. case v.dataInput <- true:
  213. default:
  214. }
  215. }
  216. func (v *Connection) OnDataOutput() {
  217. select {
  218. case v.dataOutput <- true:
  219. default:
  220. }
  221. }
  222. // Read implements the Conn Read method.
  223. func (v *Connection) Read(b []byte) (int, error) {
  224. if v == nil {
  225. return 0, io.EOF
  226. }
  227. for {
  228. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  229. return 0, io.EOF
  230. }
  231. nBytes := v.receivingWorker.Read(b)
  232. if nBytes > 0 {
  233. return nBytes, nil
  234. }
  235. if v.State() == StatePeerTerminating {
  236. return 0, io.EOF
  237. }
  238. duration := time.Duration(time.Minute)
  239. if !v.rd.IsZero() {
  240. duration = v.rd.Sub(time.Now())
  241. if duration < 0 {
  242. return 0, ErrIOTimeout
  243. }
  244. }
  245. select {
  246. case <-v.dataInput:
  247. case <-time.After(duration):
  248. if !v.rd.IsZero() && v.rd.Before(time.Now()) {
  249. return 0, ErrIOTimeout
  250. }
  251. }
  252. }
  253. }
  254. // Write implements the Conn Write method.
  255. func (v *Connection) Write(b []byte) (int, error) {
  256. totalWritten := 0
  257. for {
  258. if v == nil || v.State() != StateActive {
  259. return totalWritten, io.ErrClosedPipe
  260. }
  261. nBytes := v.sendingWorker.Push(b[totalWritten:])
  262. v.dataUpdater.WakeUp()
  263. if nBytes > 0 {
  264. totalWritten += nBytes
  265. if totalWritten == len(b) {
  266. return totalWritten, nil
  267. }
  268. }
  269. duration := time.Duration(time.Minute)
  270. if !v.rd.IsZero() {
  271. duration = v.wd.Sub(time.Now())
  272. if duration < 0 {
  273. return totalWritten, ErrIOTimeout
  274. }
  275. }
  276. select {
  277. case <-v.dataOutput:
  278. case <-time.After(duration):
  279. if !v.wd.IsZero() && v.wd.Before(time.Now()) {
  280. return totalWritten, ErrIOTimeout
  281. }
  282. }
  283. }
  284. }
  285. func (v *Connection) SetState(state State) {
  286. current := v.Elapsed()
  287. atomic.StoreInt32((*int32)(&v.state), int32(state))
  288. atomic.StoreUint32(&v.stateBeginTime, current)
  289. log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current)
  290. switch state {
  291. case StateReadyToClose:
  292. v.receivingWorker.CloseRead()
  293. case StatePeerClosed:
  294. v.sendingWorker.CloseWrite()
  295. case StateTerminating:
  296. v.receivingWorker.CloseRead()
  297. v.sendingWorker.CloseWrite()
  298. v.pingUpdater.interval = time.Second
  299. case StatePeerTerminating:
  300. v.sendingWorker.CloseWrite()
  301. v.pingUpdater.interval = time.Second
  302. case StateTerminated:
  303. v.receivingWorker.CloseRead()
  304. v.sendingWorker.CloseWrite()
  305. v.pingUpdater.interval = time.Second
  306. v.dataUpdater.WakeUp()
  307. v.pingUpdater.WakeUp()
  308. go v.Terminate()
  309. }
  310. }
  311. // Close closes the connection.
  312. func (v *Connection) Close() error {
  313. if v == nil {
  314. return ErrClosedConnection
  315. }
  316. v.OnDataInput()
  317. v.OnDataOutput()
  318. state := v.State()
  319. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  320. return ErrClosedConnection
  321. }
  322. log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr())
  323. if state == StateActive {
  324. v.SetState(StateReadyToClose)
  325. }
  326. if state == StatePeerClosed {
  327. v.SetState(StateTerminating)
  328. }
  329. if state == StatePeerTerminating {
  330. v.SetState(StateTerminated)
  331. }
  332. return nil
  333. }
  334. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  335. func (v *Connection) LocalAddr() net.Addr {
  336. if v == nil {
  337. return nil
  338. }
  339. return v.conn.LocalAddr()
  340. }
  341. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  342. func (v *Connection) RemoteAddr() net.Addr {
  343. if v == nil {
  344. return nil
  345. }
  346. return v.conn.RemoteAddr()
  347. }
  348. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  349. func (v *Connection) SetDeadline(t time.Time) error {
  350. if err := v.SetReadDeadline(t); err != nil {
  351. return err
  352. }
  353. if err := v.SetWriteDeadline(t); err != nil {
  354. return err
  355. }
  356. return nil
  357. }
  358. // SetReadDeadline implements the Conn SetReadDeadline method.
  359. func (v *Connection) SetReadDeadline(t time.Time) error {
  360. if v == nil || v.State() != StateActive {
  361. return ErrClosedConnection
  362. }
  363. v.rd = t
  364. return nil
  365. }
  366. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  367. func (v *Connection) SetWriteDeadline(t time.Time) error {
  368. if v == nil || v.State() != StateActive {
  369. return ErrClosedConnection
  370. }
  371. v.wd = t
  372. return nil
  373. }
  374. // kcp update, input loop
  375. func (v *Connection) updateTask() {
  376. v.flush()
  377. }
  378. func (v *Connection) Reusable() bool {
  379. return v.Config.IsConnectionReuse() && v.reusable
  380. }
  381. func (v *Connection) SetReusable(b bool) {
  382. v.reusable = b
  383. }
  384. func (v *Connection) Terminate() {
  385. if v == nil {
  386. return
  387. }
  388. log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr())
  389. //v.SetState(StateTerminated)
  390. v.OnDataInput()
  391. v.OnDataOutput()
  392. if v.Config.IsConnectionReuse() && v.reusable {
  393. v.connRecycler.Put(v.conn.Id(), v.conn)
  394. } else {
  395. v.conn.Close()
  396. }
  397. v.sendingWorker.Release()
  398. v.receivingWorker.Release()
  399. }
  400. func (v *Connection) HandleOption(opt SegmentOption) {
  401. if (opt & SegmentOptionClose) == SegmentOptionClose {
  402. v.OnPeerClosed()
  403. }
  404. }
  405. func (v *Connection) OnPeerClosed() {
  406. state := v.State()
  407. if state == StateReadyToClose {
  408. v.SetState(StateTerminating)
  409. }
  410. if state == StateActive {
  411. v.SetState(StatePeerClosed)
  412. }
  413. }
  414. // Input when you received a low level packet (eg. UDP packet), call it
  415. func (v *Connection) Input(segments []Segment) {
  416. current := v.Elapsed()
  417. atomic.StoreUint32(&v.lastIncomingTime, current)
  418. for _, seg := range segments {
  419. if seg.Conversation() != v.conv {
  420. break
  421. }
  422. switch seg := seg.(type) {
  423. case *DataSegment:
  424. v.HandleOption(seg.Option)
  425. v.receivingWorker.ProcessSegment(seg)
  426. if seg.Number == v.receivingWorker.nextNumber {
  427. v.OnDataInput()
  428. }
  429. v.dataUpdater.WakeUp()
  430. case *AckSegment:
  431. v.HandleOption(seg.Option)
  432. v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
  433. v.OnDataOutput()
  434. v.dataUpdater.WakeUp()
  435. case *CmdOnlySegment:
  436. v.HandleOption(seg.Option)
  437. if seg.Command() == CommandTerminate {
  438. state := v.State()
  439. if state == StateActive ||
  440. state == StatePeerClosed {
  441. v.SetState(StatePeerTerminating)
  442. } else if state == StateReadyToClose {
  443. v.SetState(StateTerminating)
  444. } else if state == StateTerminating {
  445. v.SetState(StateTerminated)
  446. }
  447. }
  448. v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  449. v.receivingWorker.ProcessSendingNext(seg.SendingNext)
  450. v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  451. seg.Release()
  452. default:
  453. }
  454. }
  455. }
  456. func (v *Connection) flush() {
  457. current := v.Elapsed()
  458. if v.State() == StateTerminated {
  459. return
  460. }
  461. if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
  462. v.Close()
  463. }
  464. if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
  465. v.SetState(StateTerminating)
  466. }
  467. if v.State() == StateTerminating {
  468. log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.")
  469. v.Ping(current, CommandTerminate)
  470. if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
  471. v.SetState(StateTerminated)
  472. }
  473. return
  474. }
  475. if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
  476. v.SetState(StateTerminating)
  477. }
  478. if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
  479. v.SetState(StateTerminating)
  480. }
  481. // flush acknowledges
  482. v.receivingWorker.Flush(current)
  483. v.sendingWorker.Flush(current)
  484. if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
  485. v.Ping(current, CommandPing)
  486. }
  487. }
  488. func (v *Connection) State() State {
  489. return State(atomic.LoadInt32((*int32)(&v.state)))
  490. }
  491. func (v *Connection) Ping(current uint32, cmd Command) {
  492. seg := NewCmdOnlySegment()
  493. seg.Conv = v.conv
  494. seg.Cmd = cmd
  495. seg.ReceivinNext = v.receivingWorker.nextNumber
  496. seg.SendingNext = v.sendingWorker.firstUnacknowledged
  497. seg.PeerRTO = v.roundTrip.Timeout()
  498. if v.State() == StateReadyToClose {
  499. seg.Option = SegmentOptionClose
  500. }
  501. v.output.Write(seg)
  502. atomic.StoreUint32(&v.lastPingTime, current)
  503. seg.Release()
  504. }