connection.go 14 KB

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