connection.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. //go:build !confonly
  2. // +build !confonly
  3. package kcp
  4. import (
  5. "bytes"
  6. "io"
  7. "net"
  8. "runtime"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/v2fly/v2ray-core/v4/common/buf"
  13. "github.com/v2fly/v2ray-core/v4/common/signal"
  14. "github.com/v2fly/v2ray-core/v4/common/signal/semaphore"
  15. )
  16. var (
  17. ErrIOTimeout = newError("Read/Write timeout")
  18. ErrClosedListener = newError("Listener closed.")
  19. ErrClosedConnection = newError("Connection closed.")
  20. )
  21. // State of the connection
  22. type State int32
  23. // Is returns true if current State is one of the candidates.
  24. func (s State) Is(states ...State) bool {
  25. for _, state := range states {
  26. if s == state {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. const (
  33. StateActive State = 0 // Connection is active
  34. StateReadyToClose State = 1 // Connection is closed locally
  35. StatePeerClosed State = 2 // Connection is closed on remote
  36. StateTerminating State = 3 // Connection is ready to be destroyed locally
  37. StatePeerTerminating State = 4 // Connection is ready to be destroyed on remote
  38. StateTerminated State = 5 // Connection is destroyed.
  39. )
  40. func nowMillisec() int64 {
  41. now := time.Now()
  42. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  43. }
  44. type RoundTripInfo struct {
  45. sync.RWMutex
  46. variation uint32
  47. srtt uint32
  48. rto uint32
  49. minRtt uint32
  50. updatedTimestamp uint32
  51. }
  52. func (info *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
  53. info.Lock()
  54. defer info.Unlock()
  55. if current-info.updatedTimestamp < 3000 {
  56. return
  57. }
  58. info.updatedTimestamp = current
  59. info.rto = rto
  60. }
  61. func (info *RoundTripInfo) Update(rtt uint32, current uint32) {
  62. if rtt > 0x7FFFFFFF {
  63. return
  64. }
  65. info.Lock()
  66. defer info.Unlock()
  67. // https://tools.ietf.org/html/rfc6298
  68. if info.srtt == 0 {
  69. info.srtt = rtt
  70. info.variation = rtt / 2
  71. } else {
  72. delta := rtt - info.srtt
  73. if info.srtt > rtt {
  74. delta = info.srtt - rtt
  75. }
  76. info.variation = (3*info.variation + delta) / 4
  77. info.srtt = (7*info.srtt + rtt) / 8
  78. if info.srtt < info.minRtt {
  79. info.srtt = info.minRtt
  80. }
  81. }
  82. var rto uint32
  83. if info.minRtt < 4*info.variation {
  84. rto = info.srtt + 4*info.variation
  85. } else {
  86. rto = info.srtt + info.variation
  87. }
  88. if rto > 10000 {
  89. rto = 10000
  90. }
  91. info.rto = rto * 5 / 4
  92. info.updatedTimestamp = current
  93. }
  94. func (info *RoundTripInfo) Timeout() uint32 {
  95. info.RLock()
  96. defer info.RUnlock()
  97. return info.rto
  98. }
  99. func (info *RoundTripInfo) SmoothedTime() uint32 {
  100. info.RLock()
  101. defer info.RUnlock()
  102. return info.srtt
  103. }
  104. type Updater struct {
  105. interval int64
  106. shouldContinue func() bool
  107. shouldTerminate func() bool
  108. updateFunc func()
  109. notifier *semaphore.Instance
  110. }
  111. func NewUpdater(interval uint32, shouldContinue func() bool, shouldTerminate func() bool, updateFunc func()) *Updater {
  112. u := &Updater{
  113. interval: int64(time.Duration(interval) * time.Millisecond),
  114. shouldContinue: shouldContinue,
  115. shouldTerminate: shouldTerminate,
  116. updateFunc: updateFunc,
  117. notifier: semaphore.New(1),
  118. }
  119. return u
  120. }
  121. func (u *Updater) WakeUp() {
  122. select {
  123. case <-u.notifier.Wait():
  124. go u.run()
  125. default:
  126. }
  127. }
  128. func (u *Updater) run() {
  129. defer u.notifier.Signal()
  130. if u.shouldTerminate() {
  131. return
  132. }
  133. ticker := time.NewTicker(u.Interval())
  134. for u.shouldContinue() {
  135. u.updateFunc()
  136. <-ticker.C
  137. }
  138. ticker.Stop()
  139. }
  140. func (u *Updater) Interval() time.Duration {
  141. return time.Duration(atomic.LoadInt64(&u.interval))
  142. }
  143. func (u *Updater) SetInterval(d time.Duration) {
  144. atomic.StoreInt64(&u.interval, int64(d))
  145. }
  146. type ConnMetadata struct {
  147. LocalAddr net.Addr
  148. RemoteAddr net.Addr
  149. Conversation uint16
  150. }
  151. // Connection is a KCP connection over UDP.
  152. type Connection struct {
  153. meta ConnMetadata
  154. closer io.Closer
  155. rd time.Time
  156. wd time.Time // write deadline
  157. since int64
  158. dataInput *signal.Notifier
  159. dataOutput *signal.Notifier
  160. Config *Config
  161. state State
  162. stateBeginTime uint32
  163. lastIncomingTime uint32
  164. lastPingTime uint32
  165. mss uint32
  166. roundTrip *RoundTripInfo
  167. receivingWorker *ReceivingWorker
  168. sendingWorker *SendingWorker
  169. output SegmentWriter
  170. dataUpdater *Updater
  171. pingUpdater *Updater
  172. }
  173. // NewConnection create a new KCP connection between local and remote.
  174. func NewConnection(meta ConnMetadata, writer PacketWriter, closer io.Closer, config *Config) *Connection {
  175. newError("#", meta.Conversation, " creating connection to ", meta.RemoteAddr).WriteToLog()
  176. conn := &Connection{
  177. meta: meta,
  178. closer: closer,
  179. since: nowMillisec(),
  180. dataInput: signal.NewNotifier(),
  181. dataOutput: signal.NewNotifier(),
  182. Config: config,
  183. output: NewRetryableWriter(NewSegmentWriter(writer)),
  184. mss: config.GetMTUValue() - uint32(writer.Overhead()) - DataSegmentOverhead,
  185. roundTrip: &RoundTripInfo{
  186. rto: 100,
  187. minRtt: config.GetTTIValue(),
  188. },
  189. }
  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. func() bool {
  201. return !isTerminating() && (conn.sendingWorker.UpdateNecessary() || conn.receivingWorker.UpdateNecessary())
  202. },
  203. isTerminating,
  204. conn.updateTask)
  205. conn.pingUpdater = NewUpdater(
  206. 5000, // 5 seconds
  207. func() bool { return !isTerminated() },
  208. isTerminated,
  209. conn.updateTask)
  210. conn.pingUpdater.WakeUp()
  211. return conn
  212. }
  213. func (c *Connection) Elapsed() uint32 {
  214. return uint32(nowMillisec() - c.since)
  215. }
  216. // ReadMultiBuffer implements buf.Reader.
  217. func (c *Connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
  218. if c == nil {
  219. return nil, io.EOF
  220. }
  221. for {
  222. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  223. return nil, io.EOF
  224. }
  225. mb := c.receivingWorker.ReadMultiBuffer()
  226. if !mb.IsEmpty() {
  227. c.dataUpdater.WakeUp()
  228. return mb, nil
  229. }
  230. if c.State() == StatePeerTerminating {
  231. return nil, io.EOF
  232. }
  233. if err := c.waitForDataInput(); err != nil {
  234. return nil, err
  235. }
  236. }
  237. }
  238. func (c *Connection) waitForDataInput() error {
  239. for i := 0; i < 16; i++ {
  240. select {
  241. case <-c.dataInput.Wait():
  242. return nil
  243. default:
  244. runtime.Gosched()
  245. }
  246. }
  247. duration := time.Second * 16
  248. if !c.rd.IsZero() {
  249. duration = time.Until(c.rd)
  250. if duration < 0 {
  251. return ErrIOTimeout
  252. }
  253. }
  254. timeout := time.NewTimer(duration)
  255. defer timeout.Stop()
  256. select {
  257. case <-c.dataInput.Wait():
  258. case <-timeout.C:
  259. if !c.rd.IsZero() && c.rd.Before(time.Now()) {
  260. return ErrIOTimeout
  261. }
  262. }
  263. return nil
  264. }
  265. // Read implements the Conn Read method.
  266. func (c *Connection) Read(b []byte) (int, error) {
  267. if c == nil {
  268. return 0, io.EOF
  269. }
  270. for {
  271. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  272. return 0, io.EOF
  273. }
  274. nBytes := c.receivingWorker.Read(b)
  275. if nBytes > 0 {
  276. c.dataUpdater.WakeUp()
  277. return nBytes, nil
  278. }
  279. if err := c.waitForDataInput(); err != nil {
  280. return 0, err
  281. }
  282. }
  283. }
  284. func (c *Connection) waitForDataOutput() error {
  285. for i := 0; i < 16; i++ {
  286. select {
  287. case <-c.dataOutput.Wait():
  288. return nil
  289. default:
  290. runtime.Gosched()
  291. }
  292. }
  293. duration := time.Second * 16
  294. if !c.wd.IsZero() {
  295. duration = time.Until(c.wd)
  296. if duration < 0 {
  297. return ErrIOTimeout
  298. }
  299. }
  300. timeout := time.NewTimer(duration)
  301. defer timeout.Stop()
  302. select {
  303. case <-c.dataOutput.Wait():
  304. case <-timeout.C:
  305. if !c.wd.IsZero() && c.wd.Before(time.Now()) {
  306. return ErrIOTimeout
  307. }
  308. }
  309. return nil
  310. }
  311. // Write implements io.Writer.
  312. func (c *Connection) Write(b []byte) (int, error) {
  313. reader := bytes.NewReader(b)
  314. if err := c.writeMultiBufferInternal(reader); err != nil {
  315. return 0, err
  316. }
  317. return len(b), nil
  318. }
  319. // WriteMultiBuffer implements buf.Writer.
  320. func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  321. reader := &buf.MultiBufferContainer{
  322. MultiBuffer: mb,
  323. }
  324. defer reader.Close()
  325. return c.writeMultiBufferInternal(reader)
  326. }
  327. func (c *Connection) writeMultiBufferInternal(reader io.Reader) error {
  328. updatePending := false
  329. defer func() {
  330. if updatePending {
  331. c.dataUpdater.WakeUp()
  332. }
  333. }()
  334. var b *buf.Buffer
  335. defer b.Release()
  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. }
  462. func (c *Connection) HandleOption(opt SegmentOption) {
  463. if (opt & SegmentOptionClose) == SegmentOptionClose {
  464. c.OnPeerClosed()
  465. }
  466. }
  467. func (c *Connection) OnPeerClosed() {
  468. switch c.State() {
  469. case StateReadyToClose:
  470. c.SetState(StateTerminating)
  471. case StateActive:
  472. c.SetState(StatePeerClosed)
  473. }
  474. }
  475. // Input when you received a low level packet (eg. UDP packet), call it
  476. func (c *Connection) Input(segments []Segment) {
  477. current := c.Elapsed()
  478. atomic.StoreUint32(&c.lastIncomingTime, current)
  479. for _, seg := range segments {
  480. if seg.Conversation() != c.meta.Conversation {
  481. break
  482. }
  483. switch seg := seg.(type) {
  484. case *DataSegment:
  485. c.HandleOption(seg.Option)
  486. c.receivingWorker.ProcessSegment(seg)
  487. if c.receivingWorker.IsDataAvailable() {
  488. c.dataInput.Signal()
  489. }
  490. c.dataUpdater.WakeUp()
  491. case *AckSegment:
  492. c.HandleOption(seg.Option)
  493. c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
  494. c.dataOutput.Signal()
  495. c.dataUpdater.WakeUp()
  496. case *CmdOnlySegment:
  497. c.HandleOption(seg.Option)
  498. if seg.Command() == CommandTerminate {
  499. switch c.State() {
  500. case StateActive, StatePeerClosed:
  501. c.SetState(StatePeerTerminating)
  502. case StateReadyToClose:
  503. c.SetState(StateTerminating)
  504. case StateTerminating:
  505. c.SetState(StateTerminated)
  506. }
  507. }
  508. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  509. c.dataInput.Signal()
  510. c.dataOutput.Signal()
  511. }
  512. c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
  513. c.receivingWorker.ProcessSendingNext(seg.SendingNext)
  514. c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  515. seg.Release()
  516. default:
  517. }
  518. }
  519. }
  520. func (c *Connection) flush() {
  521. current := c.Elapsed()
  522. if c.State() == StateTerminated {
  523. return
  524. }
  525. if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
  526. c.Close()
  527. }
  528. if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
  529. c.SetState(StateTerminating)
  530. }
  531. if c.State() == StateTerminating {
  532. newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  533. c.Ping(current, CommandTerminate)
  534. if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
  535. c.SetState(StateTerminated)
  536. }
  537. return
  538. }
  539. if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
  540. c.SetState(StateTerminating)
  541. }
  542. if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
  543. c.SetState(StateTerminating)
  544. }
  545. // flush acknowledges
  546. c.receivingWorker.Flush(current)
  547. c.sendingWorker.Flush(current)
  548. if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
  549. c.Ping(current, CommandPing)
  550. }
  551. }
  552. func (c *Connection) State() State {
  553. return State(atomic.LoadInt32((*int32)(&c.state)))
  554. }
  555. func (c *Connection) Ping(current uint32, cmd Command) {
  556. seg := NewCmdOnlySegment()
  557. seg.Conv = c.meta.Conversation
  558. seg.Cmd = cmd
  559. seg.ReceivingNext = c.receivingWorker.NextNumber()
  560. seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
  561. seg.PeerRTO = c.roundTrip.Timeout()
  562. if c.State() == StateReadyToClose {
  563. seg.Option = SegmentOptionClose
  564. }
  565. c.output.Write(seg)
  566. atomic.StoreUint32(&c.lastPingTime, current)
  567. seg.Release()
  568. }