connection.go 14 KB

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