connection.go 15 KB

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