connection.go 14 KB

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