connection.go 14 KB

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