connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. package kcp
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/predicate"
  10. "v2ray.com/core/common/signal"
  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 *signal.Semaphore
  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: signal.NewSemaphore(1),
  114. }
  115. return u
  116. }
  117. func (u *Updater) WakeUp() {
  118. select {
  119. case <-u.notifier.Wait():
  120. go u.run()
  121. default:
  122. }
  123. }
  124. func (u *Updater) run() {
  125. defer u.notifier.Signal()
  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. func (u *Updater) Interval() time.Duration {
  137. return time.Duration(atomic.LoadInt64(&u.interval))
  138. }
  139. func (u *Updater) SetInterval(d time.Duration) {
  140. atomic.StoreInt64(&u.interval, int64(d))
  141. }
  142. type ConnMetadata struct {
  143. LocalAddr net.Addr
  144. RemoteAddr net.Addr
  145. Conversation uint16
  146. }
  147. // Connection is a KCP connection over UDP.
  148. type Connection struct {
  149. meta ConnMetadata
  150. closer io.Closer
  151. rd time.Time
  152. wd time.Time // write deadline
  153. since int64
  154. dataInput *signal.Notifier
  155. dataOutput *signal.Notifier
  156. Config *Config
  157. state State
  158. stateBeginTime uint32
  159. lastIncomingTime uint32
  160. lastPingTime uint32
  161. mss uint32
  162. roundTrip *RoundTripInfo
  163. receivingWorker *ReceivingWorker
  164. sendingWorker *SendingWorker
  165. output SegmentWriter
  166. dataUpdater *Updater
  167. pingUpdater *Updater
  168. }
  169. // NewConnection create a new KCP connection between local and remote.
  170. func NewConnection(meta ConnMetadata, writer PacketWriter, closer io.Closer, config *Config) *Connection {
  171. newError("#", meta.Conversation, " creating connection to ", meta.RemoteAddr).WriteToLog()
  172. conn := &Connection{
  173. meta: meta,
  174. closer: closer,
  175. since: nowMillisec(),
  176. dataInput: signal.NewNotifier(),
  177. dataOutput: signal.NewNotifier(),
  178. Config: config,
  179. output: NewRetryableWriter(NewSegmentWriter(writer)),
  180. mss: config.GetMTUValue() - uint32(writer.Overhead()) - DataSegmentOverhead,
  181. roundTrip: &RoundTripInfo{
  182. rto: 100,
  183. minRtt: config.GetTTIValue(),
  184. },
  185. }
  186. conn.receivingWorker = NewReceivingWorker(conn)
  187. conn.sendingWorker = NewSendingWorker(conn)
  188. isTerminating := func() bool {
  189. return conn.State().Is(StateTerminating, StateTerminated)
  190. }
  191. isTerminated := func() bool {
  192. return conn.State() == StateTerminated
  193. }
  194. conn.dataUpdater = NewUpdater(
  195. config.GetTTIValue(),
  196. predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
  197. isTerminating,
  198. conn.updateTask)
  199. conn.pingUpdater = NewUpdater(
  200. 5000, // 5 seconds
  201. predicate.Not(isTerminated),
  202. isTerminated,
  203. conn.updateTask)
  204. conn.pingUpdater.WakeUp()
  205. return conn
  206. }
  207. func (c *Connection) Elapsed() uint32 {
  208. return uint32(nowMillisec() - c.since)
  209. }
  210. // ReadMultiBuffer implements buf.Reader.
  211. func (c *Connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
  212. if c == nil {
  213. return nil, io.EOF
  214. }
  215. for {
  216. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  217. return nil, io.EOF
  218. }
  219. mb := c.receivingWorker.ReadMultiBuffer()
  220. if !mb.IsEmpty() {
  221. c.dataUpdater.WakeUp()
  222. return mb, nil
  223. }
  224. if c.State() == StatePeerTerminating {
  225. return nil, io.EOF
  226. }
  227. if err := c.waitForDataInput(); err != nil {
  228. return nil, err
  229. }
  230. }
  231. }
  232. func (c *Connection) waitForDataInput() error {
  233. if c.State() == StatePeerTerminating {
  234. return io.EOF
  235. }
  236. duration := time.Minute
  237. if !c.rd.IsZero() {
  238. duration = time.Until(c.rd)
  239. if duration < 0 {
  240. return ErrIOTimeout
  241. }
  242. }
  243. select {
  244. case <-c.dataInput.Wait():
  245. case <-time.After(duration):
  246. if !c.rd.IsZero() && c.rd.Before(time.Now()) {
  247. return ErrIOTimeout
  248. }
  249. }
  250. return nil
  251. }
  252. // Read implements the Conn Read method.
  253. func (c *Connection) Read(b []byte) (int, error) {
  254. if c == nil {
  255. return 0, io.EOF
  256. }
  257. for {
  258. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  259. return 0, io.EOF
  260. }
  261. nBytes := c.receivingWorker.Read(b)
  262. if nBytes > 0 {
  263. c.dataUpdater.WakeUp()
  264. return nBytes, nil
  265. }
  266. if err := c.waitForDataInput(); err != nil {
  267. return 0, err
  268. }
  269. }
  270. }
  271. func (c *Connection) waitForDataOutput() error {
  272. duration := time.Minute
  273. if !c.wd.IsZero() {
  274. duration = time.Until(c.wd)
  275. if duration < 0 {
  276. return ErrIOTimeout
  277. }
  278. }
  279. select {
  280. case <-c.dataOutput.Wait():
  281. case <-time.After(duration):
  282. if !c.wd.IsZero() && c.wd.Before(time.Now()) {
  283. return ErrIOTimeout
  284. }
  285. }
  286. return nil
  287. }
  288. // Write implements io.Writer.
  289. func (c *Connection) Write(b []byte) (int, error) {
  290. updatePending := false
  291. defer func() {
  292. if updatePending {
  293. c.dataUpdater.WakeUp()
  294. }
  295. }()
  296. for {
  297. totalWritten := 0
  298. for {
  299. if c == nil || c.State() != StateActive {
  300. return totalWritten, io.ErrClosedPipe
  301. }
  302. if !c.sendingWorker.Push(func(bb []byte) (int, error) {
  303. n := copy(bb[:c.mss], b[totalWritten:])
  304. totalWritten += n
  305. return n, nil
  306. }) {
  307. break
  308. }
  309. updatePending = true
  310. if totalWritten == len(b) {
  311. return totalWritten, nil
  312. }
  313. }
  314. if updatePending {
  315. c.dataUpdater.WakeUp()
  316. updatePending = false
  317. }
  318. if err := c.waitForDataOutput(); err != nil {
  319. return totalWritten, err
  320. }
  321. }
  322. }
  323. // WriteMultiBuffer implements buf.Writer.
  324. func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  325. defer mb.Release()
  326. updatePending := false
  327. defer func() {
  328. if updatePending {
  329. c.dataUpdater.WakeUp()
  330. }
  331. }()
  332. for {
  333. for {
  334. if c == nil || c.State() != StateActive {
  335. return io.ErrClosedPipe
  336. }
  337. if !c.sendingWorker.Push(func(bb []byte) (int, error) {
  338. return mb.Read(bb[:c.mss])
  339. }) {
  340. break
  341. }
  342. updatePending = true
  343. if mb.IsEmpty() {
  344. return nil
  345. }
  346. }
  347. if updatePending {
  348. c.dataUpdater.WakeUp()
  349. updatePending = false
  350. }
  351. if err := c.waitForDataOutput(); err != nil {
  352. return err
  353. }
  354. }
  355. }
  356. func (c *Connection) SetState(state State) {
  357. current := c.Elapsed()
  358. atomic.StoreInt32((*int32)(&c.state), int32(state))
  359. atomic.StoreUint32(&c.stateBeginTime, current)
  360. newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
  361. switch state {
  362. case StateReadyToClose:
  363. c.receivingWorker.CloseRead()
  364. case StatePeerClosed:
  365. c.sendingWorker.CloseWrite()
  366. case StateTerminating:
  367. c.receivingWorker.CloseRead()
  368. c.sendingWorker.CloseWrite()
  369. c.pingUpdater.SetInterval(time.Second)
  370. case StatePeerTerminating:
  371. c.sendingWorker.CloseWrite()
  372. c.pingUpdater.SetInterval(time.Second)
  373. case StateTerminated:
  374. c.receivingWorker.CloseRead()
  375. c.sendingWorker.CloseWrite()
  376. c.pingUpdater.SetInterval(time.Second)
  377. c.dataUpdater.WakeUp()
  378. c.pingUpdater.WakeUp()
  379. go c.Terminate()
  380. }
  381. }
  382. // Close closes the connection.
  383. func (c *Connection) Close() error {
  384. if c == nil {
  385. return ErrClosedConnection
  386. }
  387. c.dataInput.Signal()
  388. c.dataOutput.Signal()
  389. switch c.State() {
  390. case StateReadyToClose, StateTerminating, StateTerminated:
  391. return ErrClosedConnection
  392. case StateActive:
  393. c.SetState(StateReadyToClose)
  394. case StatePeerClosed:
  395. c.SetState(StateTerminating)
  396. case StatePeerTerminating:
  397. c.SetState(StateTerminated)
  398. }
  399. newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog()
  400. return nil
  401. }
  402. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  403. func (c *Connection) LocalAddr() net.Addr {
  404. if c == nil {
  405. return nil
  406. }
  407. return c.meta.LocalAddr
  408. }
  409. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  410. func (c *Connection) RemoteAddr() net.Addr {
  411. if c == nil {
  412. return nil
  413. }
  414. return c.meta.RemoteAddr
  415. }
  416. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  417. func (c *Connection) SetDeadline(t time.Time) error {
  418. if err := c.SetReadDeadline(t); err != nil {
  419. return err
  420. }
  421. return c.SetWriteDeadline(t)
  422. }
  423. // SetReadDeadline implements the Conn SetReadDeadline method.
  424. func (c *Connection) SetReadDeadline(t time.Time) error {
  425. if c == nil || c.State() != StateActive {
  426. return ErrClosedConnection
  427. }
  428. c.rd = t
  429. return nil
  430. }
  431. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  432. func (c *Connection) SetWriteDeadline(t time.Time) error {
  433. if c == nil || c.State() != StateActive {
  434. return ErrClosedConnection
  435. }
  436. c.wd = t
  437. return nil
  438. }
  439. // kcp update, input loop
  440. func (c *Connection) updateTask() {
  441. c.flush()
  442. }
  443. func (c *Connection) Terminate() {
  444. if c == nil {
  445. return
  446. }
  447. newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog()
  448. //v.SetState(StateTerminated)
  449. c.dataInput.Signal()
  450. c.dataOutput.Signal()
  451. c.closer.Close()
  452. c.sendingWorker.Release()
  453. c.receivingWorker.Release()
  454. }
  455. func (c *Connection) HandleOption(opt SegmentOption) {
  456. if (opt & SegmentOptionClose) == SegmentOptionClose {
  457. c.OnPeerClosed()
  458. }
  459. }
  460. func (c *Connection) OnPeerClosed() {
  461. switch c.State() {
  462. case StateReadyToClose:
  463. c.SetState(StateTerminating)
  464. case StateActive:
  465. c.SetState(StatePeerClosed)
  466. }
  467. }
  468. // Input when you received a low level packet (eg. UDP packet), call it
  469. func (c *Connection) Input(segments []Segment) {
  470. current := c.Elapsed()
  471. atomic.StoreUint32(&c.lastIncomingTime, current)
  472. for _, seg := range segments {
  473. if seg.Conversation() != c.meta.Conversation {
  474. break
  475. }
  476. switch seg := seg.(type) {
  477. case *DataSegment:
  478. c.HandleOption(seg.Option)
  479. c.receivingWorker.ProcessSegment(seg)
  480. if c.receivingWorker.IsDataAvailable() {
  481. c.dataInput.Signal()
  482. }
  483. c.dataUpdater.WakeUp()
  484. case *AckSegment:
  485. c.HandleOption(seg.Option)
  486. c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
  487. c.dataOutput.Signal()
  488. c.dataUpdater.WakeUp()
  489. case *CmdOnlySegment:
  490. c.HandleOption(seg.Option)
  491. if seg.Command() == CommandTerminate {
  492. switch c.State() {
  493. case StateActive, StatePeerClosed:
  494. c.SetState(StatePeerTerminating)
  495. case StateReadyToClose:
  496. c.SetState(StateTerminating)
  497. case StateTerminating:
  498. c.SetState(StateTerminated)
  499. }
  500. }
  501. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  502. c.dataInput.Signal()
  503. c.dataOutput.Signal()
  504. }
  505. c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
  506. c.receivingWorker.ProcessSendingNext(seg.SendingNext)
  507. c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  508. seg.Release()
  509. default:
  510. }
  511. }
  512. }
  513. func (c *Connection) flush() {
  514. current := c.Elapsed()
  515. if c.State() == StateTerminated {
  516. return
  517. }
  518. if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
  519. c.Close()
  520. }
  521. if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
  522. c.SetState(StateTerminating)
  523. }
  524. if c.State() == StateTerminating {
  525. newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  526. c.Ping(current, CommandTerminate)
  527. if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
  528. c.SetState(StateTerminated)
  529. }
  530. return
  531. }
  532. if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
  533. c.SetState(StateTerminating)
  534. }
  535. if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
  536. c.SetState(StateTerminating)
  537. }
  538. // flush acknowledges
  539. c.receivingWorker.Flush(current)
  540. c.sendingWorker.Flush(current)
  541. if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
  542. c.Ping(current, CommandPing)
  543. }
  544. }
  545. func (c *Connection) State() State {
  546. return State(atomic.LoadInt32((*int32)(&c.state)))
  547. }
  548. func (c *Connection) Ping(current uint32, cmd Command) {
  549. seg := NewCmdOnlySegment()
  550. seg.Conv = c.meta.Conversation
  551. seg.Cmd = cmd
  552. seg.ReceivingNext = c.receivingWorker.NextNumber()
  553. seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
  554. seg.PeerRTO = c.roundTrip.Timeout()
  555. if c.State() == StateReadyToClose {
  556. seg.Option = SegmentOptionClose
  557. }
  558. c.output.Write(seg)
  559. atomic.StoreUint32(&c.lastPingTime, current)
  560. seg.Release()
  561. }