connection.go 14 KB

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