connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. f := func(x *buf.MultiBuffer) buf.Supplier {
  335. return func(bb []byte) (int, error) {
  336. return x.Read(bb[:c.mss])
  337. }
  338. }(&mb)
  339. for {
  340. for {
  341. if c == nil || c.State() != StateActive {
  342. return io.ErrClosedPipe
  343. }
  344. if !c.sendingWorker.Push(f) {
  345. break
  346. }
  347. updatePending = true
  348. if mb.IsEmpty() {
  349. return nil
  350. }
  351. }
  352. if updatePending {
  353. c.dataUpdater.WakeUp()
  354. updatePending = false
  355. }
  356. if err := c.waitForDataOutput(); err != nil {
  357. return err
  358. }
  359. }
  360. }
  361. func (c *Connection) SetState(state State) {
  362. current := c.Elapsed()
  363. atomic.StoreInt32((*int32)(&c.state), int32(state))
  364. atomic.StoreUint32(&c.stateBeginTime, current)
  365. newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
  366. switch state {
  367. case StateReadyToClose:
  368. c.receivingWorker.CloseRead()
  369. case StatePeerClosed:
  370. c.sendingWorker.CloseWrite()
  371. case StateTerminating:
  372. c.receivingWorker.CloseRead()
  373. c.sendingWorker.CloseWrite()
  374. c.pingUpdater.SetInterval(time.Second)
  375. case StatePeerTerminating:
  376. c.sendingWorker.CloseWrite()
  377. c.pingUpdater.SetInterval(time.Second)
  378. case StateTerminated:
  379. c.receivingWorker.CloseRead()
  380. c.sendingWorker.CloseWrite()
  381. c.pingUpdater.SetInterval(time.Second)
  382. c.dataUpdater.WakeUp()
  383. c.pingUpdater.WakeUp()
  384. go c.Terminate()
  385. }
  386. }
  387. // Close closes the connection.
  388. func (c *Connection) Close() error {
  389. if c == nil {
  390. return ErrClosedConnection
  391. }
  392. c.dataInput.Signal()
  393. c.dataOutput.Signal()
  394. switch c.State() {
  395. case StateReadyToClose, StateTerminating, StateTerminated:
  396. return ErrClosedConnection
  397. case StateActive:
  398. c.SetState(StateReadyToClose)
  399. case StatePeerClosed:
  400. c.SetState(StateTerminating)
  401. case StatePeerTerminating:
  402. c.SetState(StateTerminated)
  403. }
  404. newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog()
  405. return nil
  406. }
  407. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  408. func (c *Connection) LocalAddr() net.Addr {
  409. if c == nil {
  410. return nil
  411. }
  412. return c.meta.LocalAddr
  413. }
  414. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  415. func (c *Connection) RemoteAddr() net.Addr {
  416. if c == nil {
  417. return nil
  418. }
  419. return c.meta.RemoteAddr
  420. }
  421. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  422. func (c *Connection) SetDeadline(t time.Time) error {
  423. if err := c.SetReadDeadline(t); err != nil {
  424. return err
  425. }
  426. return c.SetWriteDeadline(t)
  427. }
  428. // SetReadDeadline implements the Conn SetReadDeadline method.
  429. func (c *Connection) SetReadDeadline(t time.Time) error {
  430. if c == nil || c.State() != StateActive {
  431. return ErrClosedConnection
  432. }
  433. c.rd = t
  434. return nil
  435. }
  436. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  437. func (c *Connection) SetWriteDeadline(t time.Time) error {
  438. if c == nil || c.State() != StateActive {
  439. return ErrClosedConnection
  440. }
  441. c.wd = t
  442. return nil
  443. }
  444. // kcp update, input loop
  445. func (c *Connection) updateTask() {
  446. c.flush()
  447. }
  448. func (c *Connection) Terminate() {
  449. if c == nil {
  450. return
  451. }
  452. newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog()
  453. //v.SetState(StateTerminated)
  454. c.dataInput.Signal()
  455. c.dataOutput.Signal()
  456. c.closer.Close()
  457. c.sendingWorker.Release()
  458. c.receivingWorker.Release()
  459. }
  460. func (c *Connection) HandleOption(opt SegmentOption) {
  461. if (opt & SegmentOptionClose) == SegmentOptionClose {
  462. c.OnPeerClosed()
  463. }
  464. }
  465. func (c *Connection) OnPeerClosed() {
  466. switch c.State() {
  467. case StateReadyToClose:
  468. c.SetState(StateTerminating)
  469. case StateActive:
  470. c.SetState(StatePeerClosed)
  471. }
  472. }
  473. // Input when you received a low level packet (eg. UDP packet), call it
  474. func (c *Connection) Input(segments []Segment) {
  475. current := c.Elapsed()
  476. atomic.StoreUint32(&c.lastIncomingTime, current)
  477. for _, seg := range segments {
  478. if seg.Conversation() != c.meta.Conversation {
  479. break
  480. }
  481. switch seg := seg.(type) {
  482. case *DataSegment:
  483. c.HandleOption(seg.Option)
  484. c.receivingWorker.ProcessSegment(seg)
  485. if c.receivingWorker.IsDataAvailable() {
  486. c.dataInput.Signal()
  487. }
  488. c.dataUpdater.WakeUp()
  489. case *AckSegment:
  490. c.HandleOption(seg.Option)
  491. c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
  492. c.dataOutput.Signal()
  493. c.dataUpdater.WakeUp()
  494. case *CmdOnlySegment:
  495. c.HandleOption(seg.Option)
  496. if seg.Command() == CommandTerminate {
  497. switch c.State() {
  498. case StateActive, StatePeerClosed:
  499. c.SetState(StatePeerTerminating)
  500. case StateReadyToClose:
  501. c.SetState(StateTerminating)
  502. case StateTerminating:
  503. c.SetState(StateTerminated)
  504. }
  505. }
  506. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  507. c.dataInput.Signal()
  508. c.dataOutput.Signal()
  509. }
  510. c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
  511. c.receivingWorker.ProcessSendingNext(seg.SendingNext)
  512. c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  513. seg.Release()
  514. default:
  515. }
  516. }
  517. }
  518. func (c *Connection) flush() {
  519. current := c.Elapsed()
  520. if c.State() == StateTerminated {
  521. return
  522. }
  523. if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
  524. c.Close()
  525. }
  526. if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
  527. c.SetState(StateTerminating)
  528. }
  529. if c.State() == StateTerminating {
  530. newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  531. c.Ping(current, CommandTerminate)
  532. if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
  533. c.SetState(StateTerminated)
  534. }
  535. return
  536. }
  537. if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
  538. c.SetState(StateTerminating)
  539. }
  540. if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
  541. c.SetState(StateTerminating)
  542. }
  543. // flush acknowledges
  544. c.receivingWorker.Flush(current)
  545. c.sendingWorker.Flush(current)
  546. if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
  547. c.Ping(current, CommandPing)
  548. }
  549. }
  550. func (c *Connection) State() State {
  551. return State(atomic.LoadInt32((*int32)(&c.state)))
  552. }
  553. func (c *Connection) Ping(current uint32, cmd Command) {
  554. seg := NewCmdOnlySegment()
  555. seg.Conv = c.meta.Conversation
  556. seg.Cmd = cmd
  557. seg.ReceivingNext = c.receivingWorker.NextNumber()
  558. seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
  559. seg.PeerRTO = c.roundTrip.Timeout()
  560. if c.State() == StateReadyToClose {
  561. seg.Option = SegmentOptionClose
  562. }
  563. c.output.Write(seg)
  564. atomic.StoreUint32(&c.lastPingTime, current)
  565. seg.Release()
  566. }