connection.go 14 KB

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