connection.go 13 KB

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