connection.go 15 KB

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