connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. package kcp
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  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 func() bool
  104. shouldTerminate func() bool
  105. updateFunc func()
  106. notifier *semaphore.Instance
  107. }
  108. func NewUpdater(interval uint32, shouldContinue func() bool, shouldTerminate func() bool, 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. func() bool {
  198. return !isTerminating() && (conn.sendingWorker.UpdateNecessary() || conn.receivingWorker.UpdateNecessary())
  199. },
  200. isTerminating,
  201. conn.updateTask)
  202. conn.pingUpdater = NewUpdater(
  203. 5000, // 5 seconds
  204. func() bool { return !isTerminated() },
  205. isTerminated,
  206. conn.updateTask)
  207. conn.pingUpdater.WakeUp()
  208. return conn
  209. }
  210. func (c *Connection) Elapsed() uint32 {
  211. return uint32(nowMillisec() - c.since)
  212. }
  213. // ReadMultiBuffer implements buf.Reader.
  214. func (c *Connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
  215. if c == nil {
  216. return nil, io.EOF
  217. }
  218. for {
  219. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  220. return nil, io.EOF
  221. }
  222. mb := c.receivingWorker.ReadMultiBuffer()
  223. if !mb.IsEmpty() {
  224. c.dataUpdater.WakeUp()
  225. return mb, nil
  226. }
  227. if c.State() == StatePeerTerminating {
  228. return nil, io.EOF
  229. }
  230. if err := c.waitForDataInput(); err != nil {
  231. return nil, err
  232. }
  233. }
  234. }
  235. func (c *Connection) waitForDataInput() error {
  236. if c.State() == StatePeerTerminating {
  237. return io.EOF
  238. }
  239. duration := time.Minute
  240. if !c.rd.IsZero() {
  241. duration = time.Until(c.rd)
  242. if duration < 0 {
  243. return ErrIOTimeout
  244. }
  245. }
  246. select {
  247. case <-c.dataInput.Wait():
  248. case <-time.After(duration):
  249. if !c.rd.IsZero() && c.rd.Before(time.Now()) {
  250. return ErrIOTimeout
  251. }
  252. }
  253. return nil
  254. }
  255. // Read implements the Conn Read method.
  256. func (c *Connection) Read(b []byte) (int, error) {
  257. if c == nil {
  258. return 0, io.EOF
  259. }
  260. for {
  261. if c.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  262. return 0, io.EOF
  263. }
  264. nBytes := c.receivingWorker.Read(b)
  265. if nBytes > 0 {
  266. c.dataUpdater.WakeUp()
  267. return nBytes, nil
  268. }
  269. if err := c.waitForDataInput(); err != nil {
  270. return 0, err
  271. }
  272. }
  273. }
  274. func (c *Connection) waitForDataOutput() error {
  275. duration := time.Minute
  276. if !c.wd.IsZero() {
  277. duration = time.Until(c.wd)
  278. if duration < 0 {
  279. return ErrIOTimeout
  280. }
  281. }
  282. select {
  283. case <-c.dataOutput.Wait():
  284. case <-time.After(duration):
  285. if !c.wd.IsZero() && c.wd.Before(time.Now()) {
  286. return ErrIOTimeout
  287. }
  288. }
  289. return nil
  290. }
  291. // Write implements io.Writer.
  292. func (c *Connection) Write(b []byte) (int, error) {
  293. var mb buf.MultiBuffer
  294. common.Must2(mb.Write(b))
  295. if err := c.WriteMultiBuffer(mb); err != nil {
  296. return 0, err
  297. }
  298. return len(b), nil
  299. }
  300. // WriteMultiBuffer implements buf.Writer.
  301. func (c *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  302. defer mb.Release()
  303. updatePending := false
  304. defer func() {
  305. if updatePending {
  306. c.dataUpdater.WakeUp()
  307. }
  308. }()
  309. for {
  310. for {
  311. if c == nil || c.State() != StateActive {
  312. return io.ErrClosedPipe
  313. }
  314. if !c.sendingWorker.Push(&mb) {
  315. break
  316. }
  317. updatePending = true
  318. if mb.IsEmpty() {
  319. return nil
  320. }
  321. }
  322. if updatePending {
  323. c.dataUpdater.WakeUp()
  324. updatePending = false
  325. }
  326. if err := c.waitForDataOutput(); err != nil {
  327. return err
  328. }
  329. }
  330. }
  331. func (c *Connection) SetState(state State) {
  332. current := c.Elapsed()
  333. atomic.StoreInt32((*int32)(&c.state), int32(state))
  334. atomic.StoreUint32(&c.stateBeginTime, current)
  335. newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
  336. switch state {
  337. case StateReadyToClose:
  338. c.receivingWorker.CloseRead()
  339. case StatePeerClosed:
  340. c.sendingWorker.CloseWrite()
  341. case StateTerminating:
  342. c.receivingWorker.CloseRead()
  343. c.sendingWorker.CloseWrite()
  344. c.pingUpdater.SetInterval(time.Second)
  345. case StatePeerTerminating:
  346. c.sendingWorker.CloseWrite()
  347. c.pingUpdater.SetInterval(time.Second)
  348. case StateTerminated:
  349. c.receivingWorker.CloseRead()
  350. c.sendingWorker.CloseWrite()
  351. c.pingUpdater.SetInterval(time.Second)
  352. c.dataUpdater.WakeUp()
  353. c.pingUpdater.WakeUp()
  354. go c.Terminate()
  355. }
  356. }
  357. // Close closes the connection.
  358. func (c *Connection) Close() error {
  359. if c == nil {
  360. return ErrClosedConnection
  361. }
  362. c.dataInput.Signal()
  363. c.dataOutput.Signal()
  364. switch c.State() {
  365. case StateReadyToClose, StateTerminating, StateTerminated:
  366. return ErrClosedConnection
  367. case StateActive:
  368. c.SetState(StateReadyToClose)
  369. case StatePeerClosed:
  370. c.SetState(StateTerminating)
  371. case StatePeerTerminating:
  372. c.SetState(StateTerminated)
  373. }
  374. newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog()
  375. return nil
  376. }
  377. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  378. func (c *Connection) LocalAddr() net.Addr {
  379. if c == nil {
  380. return nil
  381. }
  382. return c.meta.LocalAddr
  383. }
  384. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  385. func (c *Connection) RemoteAddr() net.Addr {
  386. if c == nil {
  387. return nil
  388. }
  389. return c.meta.RemoteAddr
  390. }
  391. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  392. func (c *Connection) SetDeadline(t time.Time) error {
  393. if err := c.SetReadDeadline(t); err != nil {
  394. return err
  395. }
  396. return c.SetWriteDeadline(t)
  397. }
  398. // SetReadDeadline implements the Conn SetReadDeadline method.
  399. func (c *Connection) SetReadDeadline(t time.Time) error {
  400. if c == nil || c.State() != StateActive {
  401. return ErrClosedConnection
  402. }
  403. c.rd = t
  404. return nil
  405. }
  406. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  407. func (c *Connection) SetWriteDeadline(t time.Time) error {
  408. if c == nil || c.State() != StateActive {
  409. return ErrClosedConnection
  410. }
  411. c.wd = t
  412. return nil
  413. }
  414. // kcp update, input loop
  415. func (c *Connection) updateTask() {
  416. c.flush()
  417. }
  418. func (c *Connection) Terminate() {
  419. if c == nil {
  420. return
  421. }
  422. newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog()
  423. //v.SetState(StateTerminated)
  424. c.dataInput.Signal()
  425. c.dataOutput.Signal()
  426. c.closer.Close()
  427. c.sendingWorker.Release()
  428. c.receivingWorker.Release()
  429. }
  430. func (c *Connection) HandleOption(opt SegmentOption) {
  431. if (opt & SegmentOptionClose) == SegmentOptionClose {
  432. c.OnPeerClosed()
  433. }
  434. }
  435. func (c *Connection) OnPeerClosed() {
  436. switch c.State() {
  437. case StateReadyToClose:
  438. c.SetState(StateTerminating)
  439. case StateActive:
  440. c.SetState(StatePeerClosed)
  441. }
  442. }
  443. // Input when you received a low level packet (eg. UDP packet), call it
  444. func (c *Connection) Input(segments []Segment) {
  445. current := c.Elapsed()
  446. atomic.StoreUint32(&c.lastIncomingTime, current)
  447. for _, seg := range segments {
  448. if seg.Conversation() != c.meta.Conversation {
  449. break
  450. }
  451. switch seg := seg.(type) {
  452. case *DataSegment:
  453. c.HandleOption(seg.Option)
  454. c.receivingWorker.ProcessSegment(seg)
  455. if c.receivingWorker.IsDataAvailable() {
  456. c.dataInput.Signal()
  457. }
  458. c.dataUpdater.WakeUp()
  459. case *AckSegment:
  460. c.HandleOption(seg.Option)
  461. c.sendingWorker.ProcessSegment(current, seg, c.roundTrip.Timeout())
  462. c.dataOutput.Signal()
  463. c.dataUpdater.WakeUp()
  464. case *CmdOnlySegment:
  465. c.HandleOption(seg.Option)
  466. if seg.Command() == CommandTerminate {
  467. switch c.State() {
  468. case StateActive, StatePeerClosed:
  469. c.SetState(StatePeerTerminating)
  470. case StateReadyToClose:
  471. c.SetState(StateTerminating)
  472. case StateTerminating:
  473. c.SetState(StateTerminated)
  474. }
  475. }
  476. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  477. c.dataInput.Signal()
  478. c.dataOutput.Signal()
  479. }
  480. c.sendingWorker.ProcessReceivingNext(seg.ReceivingNext)
  481. c.receivingWorker.ProcessSendingNext(seg.SendingNext)
  482. c.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  483. seg.Release()
  484. default:
  485. }
  486. }
  487. }
  488. func (c *Connection) flush() {
  489. current := c.Elapsed()
  490. if c.State() == StateTerminated {
  491. return
  492. }
  493. if c.State() == StateActive && current-atomic.LoadUint32(&c.lastIncomingTime) >= 30000 {
  494. c.Close()
  495. }
  496. if c.State() == StateReadyToClose && c.sendingWorker.IsEmpty() {
  497. c.SetState(StateTerminating)
  498. }
  499. if c.State() == StateTerminating {
  500. newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  501. c.Ping(current, CommandTerminate)
  502. if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 {
  503. c.SetState(StateTerminated)
  504. }
  505. return
  506. }
  507. if c.State() == StatePeerTerminating && current-atomic.LoadUint32(&c.stateBeginTime) > 4000 {
  508. c.SetState(StateTerminating)
  509. }
  510. if c.State() == StateReadyToClose && current-atomic.LoadUint32(&c.stateBeginTime) > 15000 {
  511. c.SetState(StateTerminating)
  512. }
  513. // flush acknowledges
  514. c.receivingWorker.Flush(current)
  515. c.sendingWorker.Flush(current)
  516. if current-atomic.LoadUint32(&c.lastPingTime) >= 3000 {
  517. c.Ping(current, CommandPing)
  518. }
  519. }
  520. func (c *Connection) State() State {
  521. return State(atomic.LoadInt32((*int32)(&c.state)))
  522. }
  523. func (c *Connection) Ping(current uint32, cmd Command) {
  524. seg := NewCmdOnlySegment()
  525. seg.Conv = c.meta.Conversation
  526. seg.Cmd = cmd
  527. seg.ReceivingNext = c.receivingWorker.NextNumber()
  528. seg.SendingNext = c.sendingWorker.FirstUnacknowledged()
  529. seg.PeerRTO = c.roundTrip.Timeout()
  530. if c.State() == StateReadyToClose {
  531. seg.Option = SegmentOptionClose
  532. }
  533. c.output.Write(seg)
  534. atomic.StoreUint32(&c.lastPingTime, current)
  535. seg.Release()
  536. }