connection.go 14 KB

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