connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. return mb, nil
  222. }
  223. if c.State() == StatePeerTerminating {
  224. return nil, io.EOF
  225. }
  226. if err := c.waitForDataInput(); err != nil {
  227. return nil, err
  228. }
  229. }
  230. }
  231. func (c *Connection) waitForDataInput() error {
  232. if c.State() == StatePeerTerminating {
  233. return io.EOF
  234. }
  235. duration := time.Minute
  236. if !c.rd.IsZero() {
  237. duration = time.Until(c.rd)
  238. if duration < 0 {
  239. return ErrIOTimeout
  240. }
  241. }
  242. select {
  243. case <-c.dataInput.Wait():
  244. case <-time.After(duration):
  245. if !c.rd.IsZero() && c.rd.Before(time.Now()) {
  246. return ErrIOTimeout
  247. }
  248. }
  249. return nil
  250. }
  251. // Read implements the Conn Read method.
  252. func (c *Connection) Read(b []byte) (int, error) {
  253. if c == nil {
  254. return 0, io.EOF
  255. }
  256. for {
  257. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  258. return 0, io.EOF
  259. }
  260. nBytes := c.receivingWorker.Read(b)
  261. if nBytes > 0 {
  262. return nBytes, nil
  263. }
  264. if err := c.waitForDataInput(); err != nil {
  265. return 0, err
  266. }
  267. }
  268. }
  269. func (c *Connection) waitForDataOutput() error {
  270. duration := time.Minute
  271. if !c.wd.IsZero() {
  272. duration = time.Until(c.wd)
  273. if duration < 0 {
  274. return ErrIOTimeout
  275. }
  276. }
  277. select {
  278. case <-c.dataOutput.Wait():
  279. case <-time.After(duration):
  280. if !c.wd.IsZero() && c.wd.Before(time.Now()) {
  281. return ErrIOTimeout
  282. }
  283. }
  284. return nil
  285. }
  286. // Write implements io.Writer.
  287. func (c *Connection) Write(b []byte) (int, error) {
  288. updatePending := false
  289. defer func() {
  290. if updatePending {
  291. c.dataUpdater.WakeUp()
  292. }
  293. }()
  294. for {
  295. totalWritten := 0
  296. for {
  297. if c == nil || c.State() != StateActive {
  298. return totalWritten, io.ErrClosedPipe
  299. }
  300. if !c.sendingWorker.Push(func(bb []byte) (int, error) {
  301. n := copy(bb[:c.mss], b[totalWritten:])
  302. totalWritten += n
  303. return n, nil
  304. }) {
  305. break
  306. }
  307. updatePending = true
  308. if totalWritten == len(b) {
  309. return totalWritten, nil
  310. }
  311. }
  312. if updatePending {
  313. c.dataUpdater.WakeUp()
  314. updatePending = false
  315. }
  316. if err := c.waitForDataOutput(); err != nil {
  317. return totalWritten, err
  318. }
  319. }
  320. }
  321. // WriteMultiBuffer implements buf.Writer.
  322. func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  323. defer mb.Release()
  324. updatePending := false
  325. defer func() {
  326. if updatePending {
  327. c.dataUpdater.WakeUp()
  328. }
  329. }()
  330. for {
  331. for {
  332. if c == nil || c.State() != StateActive {
  333. return io.ErrClosedPipe
  334. }
  335. if !c.sendingWorker.Push(func(bb []byte) (int, error) {
  336. return mb.Read(bb[:c.mss])
  337. }) {
  338. break
  339. }
  340. updatePending = true
  341. if mb.IsEmpty() {
  342. return nil
  343. }
  344. }
  345. if updatePending {
  346. c.dataUpdater.WakeUp()
  347. updatePending = false
  348. }
  349. if err := c.waitForDataOutput(); err != nil {
  350. return err
  351. }
  352. }
  353. }
  354. func (c *Connection) SetState(state State) {
  355. current := c.Elapsed()
  356. atomic.StoreInt32((*int32)(&c.state), int32(state))
  357. atomic.StoreUint32(&c.stateBeginTime, current)
  358. newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
  359. switch state {
  360. case StateReadyToClose:
  361. c.receivingWorker.CloseRead()
  362. case StatePeerClosed:
  363. c.sendingWorker.CloseWrite()
  364. case StateTerminating:
  365. c.receivingWorker.CloseRead()
  366. c.sendingWorker.CloseWrite()
  367. c.pingUpdater.SetInterval(time.Second)
  368. case StatePeerTerminating:
  369. c.sendingWorker.CloseWrite()
  370. c.pingUpdater.SetInterval(time.Second)
  371. case StateTerminated:
  372. c.receivingWorker.CloseRead()
  373. c.sendingWorker.CloseWrite()
  374. c.pingUpdater.SetInterval(time.Second)
  375. c.dataUpdater.WakeUp()
  376. c.pingUpdater.WakeUp()
  377. go c.Terminate()
  378. }
  379. }
  380. // Close closes the connection.
  381. func (c *Connection) Close() error {
  382. if c == nil {
  383. return ErrClosedConnection
  384. }
  385. c.dataInput.Signal()
  386. c.dataOutput.Signal()
  387. switch c.State() {
  388. case StateReadyToClose, StateTerminating, StateTerminated:
  389. return ErrClosedConnection
  390. case StateActive:
  391. c.SetState(StateReadyToClose)
  392. case StatePeerClosed:
  393. c.SetState(StateTerminating)
  394. case StatePeerTerminating:
  395. c.SetState(StateTerminated)
  396. }
  397. newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog()
  398. return nil
  399. }
  400. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  401. func (c *Connection) LocalAddr() net.Addr {
  402. if c == nil {
  403. return nil
  404. }
  405. return c.meta.LocalAddr
  406. }
  407. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  408. func (c *Connection) RemoteAddr() net.Addr {
  409. if c == nil {
  410. return nil
  411. }
  412. return c.meta.RemoteAddr
  413. }
  414. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  415. func (c *Connection) SetDeadline(t time.Time) error {
  416. if err := c.SetReadDeadline(t); err != nil {
  417. return err
  418. }
  419. return c.SetWriteDeadline(t)
  420. }
  421. // SetReadDeadline implements the Conn SetReadDeadline method.
  422. func (c *Connection) SetReadDeadline(t time.Time) error {
  423. if c == nil || c.State() != StateActive {
  424. return ErrClosedConnection
  425. }
  426. c.rd = t
  427. return nil
  428. }
  429. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  430. func (c *Connection) SetWriteDeadline(t time.Time) error {
  431. if c == nil || c.State() != StateActive {
  432. return ErrClosedConnection
  433. }
  434. c.wd = t
  435. return nil
  436. }
  437. // kcp update, input loop
  438. func (c *Connection) updateTask() {
  439. c.flush()
  440. }
  441. func (c *Connection) Terminate() {
  442. if c == nil {
  443. return
  444. }
  445. newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog()
  446. //v.SetState(StateTerminated)
  447. c.dataInput.Signal()
  448. c.dataOutput.Signal()
  449. c.closer.Close()
  450. c.sendingWorker.Release()
  451. c.receivingWorker.Release()
  452. }
  453. func (c *Connection) HandleOption(opt SegmentOption) {
  454. if (opt & SegmentOptionClose) == SegmentOptionClose {
  455. c.OnPeerClosed()
  456. }
  457. }
  458. func (c *Connection) OnPeerClosed() {
  459. switch c.State() {
  460. case StateReadyToClose:
  461. c.SetState(StateTerminating)
  462. case StateActive:
  463. c.SetState(StatePeerClosed)
  464. }
  465. }
  466. // Input when you received a low level packet (eg. UDP packet), call it
  467. func (c *Connection) Input(segments []Segment) {
  468. current := c.Elapsed()
  469. atomic.StoreUint32(&c.lastIncomingTime, current)
  470. for _, seg := range segments {
  471. if seg.Conversation() != c.meta.Conversation {
  472. break
  473. }
  474. switch seg := seg.(type) {
  475. case *DataSegment:
  476. c.HandleOption(seg.Option)
  477. c.receivingWorker.ProcessSegment(seg)
  478. if c.receivingWorker.IsDataAvailable() {
  479. c.dataInput.Signal()
  480. }
  481. c.dataUpdater.WakeUp()
  482. case *AckSegment:
  483. c.HandleOption(seg.Option)
  484. c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
  485. c.dataOutput.Signal()
  486. c.dataUpdater.WakeUp()
  487. case *CmdOnlySegment:
  488. c.HandleOption(seg.Option)
  489. if seg.Command() == CommandTerminate {
  490. switch c.State() {
  491. case StateActive, StatePeerClosed:
  492. c.SetState(StatePeerTerminating)
  493. case StateReadyToClose:
  494. c.SetState(StateTerminating)
  495. case StateTerminating:
  496. c.SetState(StateTerminated)
  497. }
  498. }
  499. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  500. c.dataInput.Signal()
  501. c.dataOutput.Signal()
  502. }
  503. c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
  504. c.receivingWorker.ProcessSendingNext(seg.SendingNext)
  505. c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  506. seg.Release()
  507. default:
  508. }
  509. }
  510. }
  511. func (c *Connection) flush() {
  512. current := c.Elapsed()
  513. if c.State() == StateTerminated {
  514. return
  515. }
  516. if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
  517. c.Close()
  518. }
  519. if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
  520. c.SetState(StateTerminating)
  521. }
  522. if c.State() == StateTerminating {
  523. newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  524. c.Ping(current, CommandTerminate)
  525. if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
  526. c.SetState(StateTerminated)
  527. }
  528. return
  529. }
  530. if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
  531. c.SetState(StateTerminating)
  532. }
  533. if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
  534. c.SetState(StateTerminating)
  535. }
  536. // flush acknowledges
  537. c.receivingWorker.Flush(current)
  538. c.sendingWorker.Flush(current)
  539. if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
  540. c.Ping(current, CommandPing)
  541. }
  542. }
  543. func (c *Connection) State() State {
  544. return State(atomic.LoadInt32((*int32)(&c.state)))
  545. }
  546. func (c *Connection) Ping(current uint32, cmd Command) {
  547. seg := NewCmdOnlySegment()
  548. seg.Conv = c.meta.Conversation
  549. seg.Cmd = cmd
  550. seg.ReceivingNext = c.receivingWorker.NextNumber()
  551. seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
  552. seg.PeerRTO = c.roundTrip.Timeout()
  553. if c.State() == StateReadyToClose {
  554. seg.Option = SegmentOptionClose
  555. }
  556. c.output.Write(seg)
  557. atomic.StoreUint32(&c.lastPingTime, current)
  558. seg.Release()
  559. }