connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. package kcp
  2. import (
  3. "bytes"
  4. "io"
  5. "net"
  6. "runtime"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  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. reader := bytes.NewReader(b)
  312. if err := c.writeMultiBufferInternal(reader); err != nil {
  313. return 0, err
  314. }
  315. return len(b), nil
  316. }
  317. // WriteMultiBuffer implements buf.Writer.
  318. func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  319. reader := &buf.MultiBufferContainer{
  320. MultiBuffer: mb,
  321. }
  322. defer reader.Close()
  323. return c.writeMultiBufferInternal(reader)
  324. }
  325. func (c *Connection) writeMultiBufferInternal(reader io.Reader) error {
  326. updatePending := false
  327. defer func() {
  328. if updatePending {
  329. c.dataUpdater.WakeUp()
  330. }
  331. }()
  332. var b *buf.Buffer
  333. defer b.Release()
  334. for {
  335. for {
  336. if c == nil || c.State() != StateActive {
  337. return io.ErrClosedPipe
  338. }
  339. if b == nil {
  340. b = buf.New()
  341. _, err := b.ReadFrom(io.LimitReader(reader, int64(c.mss)))
  342. if err != nil {
  343. return nil
  344. }
  345. }
  346. if !c.sendingWorker.Push(b) {
  347. break
  348. }
  349. updatePending = true
  350. b = nil
  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. }