connection.go 13 KB

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