connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. )
  11. var (
  12. ErrIOTimeout = newError("Read/Write timeout")
  13. ErrClosedListener = newError("Listener closed.")
  14. ErrClosedConnection = newError("Connection closed.")
  15. )
  16. // State of the connection
  17. type State int32
  18. // Is returns true if current State is one of the candidates.
  19. func (s State) Is(states ...State) bool {
  20. for _, state := range states {
  21. if s == state {
  22. return true
  23. }
  24. }
  25. return false
  26. }
  27. const (
  28. StateActive State = 0 // Connection is active
  29. StateReadyToClose State = 1 // Connection is closed locally
  30. StatePeerClosed State = 2 // Connection is closed on remote
  31. StateTerminating State = 3 // Connection is ready to be destroyed locally
  32. StatePeerTerminating State = 4 // Connection is ready to be destroyed on remote
  33. StateTerminated State = 5 // Connection is destroyed.
  34. )
  35. func nowMillisec() int64 {
  36. now := time.Now()
  37. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  38. }
  39. type RoundTripInfo struct {
  40. sync.RWMutex
  41. variation uint32
  42. srtt uint32
  43. rto uint32
  44. minRtt uint32
  45. updatedTimestamp uint32
  46. }
  47. func (info *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
  48. info.Lock()
  49. defer info.Unlock()
  50. if current-info.updatedTimestamp < 3000 {
  51. return
  52. }
  53. info.updatedTimestamp = current
  54. info.rto = rto
  55. }
  56. func (info *RoundTripInfo) Update(rtt uint32, current uint32) {
  57. if rtt > 0x7FFFFFFF {
  58. return
  59. }
  60. info.Lock()
  61. defer info.Unlock()
  62. // https://tools.ietf.org/html/rfc6298
  63. if info.srtt == 0 {
  64. info.srtt = rtt
  65. info.variation = rtt / 2
  66. } else {
  67. delta := rtt - info.srtt
  68. if info.srtt > rtt {
  69. delta = info.srtt - rtt
  70. }
  71. info.variation = (3*info.variation + delta) / 4
  72. info.srtt = (7*info.srtt + rtt) / 8
  73. if info.srtt < info.minRtt {
  74. info.srtt = info.minRtt
  75. }
  76. }
  77. var rto uint32
  78. if info.minRtt < 4*info.variation {
  79. rto = info.srtt + 4*info.variation
  80. } else {
  81. rto = info.srtt + info.variation
  82. }
  83. if rto > 10000 {
  84. rto = 10000
  85. }
  86. info.rto = rto * 5 / 4
  87. info.updatedTimestamp = current
  88. }
  89. func (info *RoundTripInfo) Timeout() uint32 {
  90. info.RLock()
  91. defer info.RUnlock()
  92. return info.rto
  93. }
  94. func (info *RoundTripInfo) SmoothedTime() uint32 {
  95. info.RLock()
  96. defer info.RUnlock()
  97. return info.srtt
  98. }
  99. type Updater struct {
  100. interval int64
  101. shouldContinue predicate.Predicate
  102. shouldTerminate predicate.Predicate
  103. updateFunc func()
  104. notifier chan bool
  105. }
  106. func NewUpdater(interval uint32, shouldContinue predicate.Predicate, shouldTerminate predicate.Predicate, updateFunc func()) *Updater {
  107. u := &Updater{
  108. interval: int64(time.Duration(interval) * time.Millisecond),
  109. shouldContinue: shouldContinue,
  110. shouldTerminate: shouldTerminate,
  111. updateFunc: updateFunc,
  112. notifier: make(chan bool, 1),
  113. }
  114. go u.Run()
  115. return u
  116. }
  117. func (u *Updater) WakeUp() {
  118. select {
  119. case u.notifier <- true:
  120. default:
  121. }
  122. }
  123. func (u *Updater) Run() {
  124. for <-u.notifier {
  125. if u.shouldTerminate() {
  126. return
  127. }
  128. ticker := time.NewTicker(u.Interval())
  129. for u.shouldContinue() {
  130. u.updateFunc()
  131. <-ticker.C
  132. }
  133. ticker.Stop()
  134. }
  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 chan bool
  155. dataOutput chan bool
  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("creating connection ", meta.Conversation).WriteToLog()
  172. conn := &Connection{
  173. meta: meta,
  174. closer: closer,
  175. since: nowMillisec(),
  176. dataInput: make(chan bool, 1),
  177. dataOutput: make(chan bool, 1),
  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 (v *Connection) Elapsed() uint32 {
  208. return uint32(nowMillisec() - v.since)
  209. }
  210. func (v *Connection) OnDataInput() {
  211. select {
  212. case v.dataInput <- true:
  213. default:
  214. }
  215. }
  216. func (v *Connection) OnDataOutput() {
  217. select {
  218. case v.dataOutput <- true:
  219. default:
  220. }
  221. }
  222. // ReadMultiBuffer implements buf.Reader.
  223. func (v *Connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
  224. if v == nil {
  225. return nil, io.EOF
  226. }
  227. for {
  228. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  229. return nil, io.EOF
  230. }
  231. mb := v.receivingWorker.ReadMultiBuffer()
  232. if !mb.IsEmpty() {
  233. return mb, nil
  234. }
  235. if v.State() == StatePeerTerminating {
  236. return nil, io.EOF
  237. }
  238. if err := v.waitForDataInput(); err != nil {
  239. return nil, err
  240. }
  241. }
  242. }
  243. func (v *Connection) waitForDataInput() error {
  244. if v.State() == StatePeerTerminating {
  245. return io.EOF
  246. }
  247. duration := time.Minute
  248. if !v.rd.IsZero() {
  249. duration = time.Until(v.rd)
  250. if duration < 0 {
  251. return ErrIOTimeout
  252. }
  253. }
  254. select {
  255. case <-v.dataInput:
  256. case <-time.After(duration):
  257. if !v.rd.IsZero() && v.rd.Before(time.Now()) {
  258. return ErrIOTimeout
  259. }
  260. }
  261. return nil
  262. }
  263. // Read implements the Conn Read method.
  264. func (v *Connection) Read(b []byte) (int, error) {
  265. if v == nil {
  266. return 0, io.EOF
  267. }
  268. for {
  269. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  270. return 0, io.EOF
  271. }
  272. nBytes := v.receivingWorker.Read(b)
  273. if nBytes > 0 {
  274. return nBytes, nil
  275. }
  276. if err := v.waitForDataInput(); err != nil {
  277. return 0, err
  278. }
  279. }
  280. }
  281. func (v *Connection) waitForDataOutput() error {
  282. duration := time.Minute
  283. if !v.wd.IsZero() {
  284. duration = time.Until(v.wd)
  285. if duration < 0 {
  286. return ErrIOTimeout
  287. }
  288. }
  289. select {
  290. case <-v.dataOutput:
  291. case <-time.After(duration):
  292. if !v.wd.IsZero() && v.wd.Before(time.Now()) {
  293. return ErrIOTimeout
  294. }
  295. }
  296. return nil
  297. }
  298. // Write implements io.Writer.
  299. func (v *Connection) Write(b []byte) (int, error) {
  300. totalWritten := 0
  301. for {
  302. if v == nil || v.State() != StateActive {
  303. return totalWritten, io.ErrClosedPipe
  304. }
  305. for v.sendingWorker.Push(func(bb []byte) (int, error) {
  306. n := copy(bb[:v.mss], b[totalWritten:])
  307. totalWritten += n
  308. return n, nil
  309. }) {
  310. v.dataUpdater.WakeUp()
  311. if totalWritten == len(b) {
  312. return totalWritten, nil
  313. }
  314. }
  315. if err := v.waitForDataOutput(); err != nil {
  316. return totalWritten, err
  317. }
  318. }
  319. }
  320. // WriteMultiBuffer implements buf.Writer.
  321. func (v *Connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  322. defer mb.Release()
  323. for {
  324. if v == nil || v.State() != StateActive {
  325. return io.ErrClosedPipe
  326. }
  327. for v.sendingWorker.Push(func(bb []byte) (int, error) {
  328. return mb.Read(bb[:v.mss])
  329. }) {
  330. v.dataUpdater.WakeUp()
  331. if mb.IsEmpty() {
  332. return nil
  333. }
  334. }
  335. if err := v.waitForDataOutput(); err != nil {
  336. return err
  337. }
  338. }
  339. }
  340. func (v *Connection) SetState(state State) {
  341. current := v.Elapsed()
  342. atomic.StoreInt32((*int32)(&v.state), int32(state))
  343. atomic.StoreUint32(&v.stateBeginTime, current)
  344. newError("#", v.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog()
  345. switch state {
  346. case StateReadyToClose:
  347. v.receivingWorker.CloseRead()
  348. case StatePeerClosed:
  349. v.sendingWorker.CloseWrite()
  350. case StateTerminating:
  351. v.receivingWorker.CloseRead()
  352. v.sendingWorker.CloseWrite()
  353. v.pingUpdater.SetInterval(time.Second)
  354. case StatePeerTerminating:
  355. v.sendingWorker.CloseWrite()
  356. v.pingUpdater.SetInterval(time.Second)
  357. case StateTerminated:
  358. v.receivingWorker.CloseRead()
  359. v.sendingWorker.CloseWrite()
  360. v.pingUpdater.SetInterval(time.Second)
  361. v.dataUpdater.WakeUp()
  362. v.pingUpdater.WakeUp()
  363. go v.Terminate()
  364. }
  365. }
  366. // Close closes the connection.
  367. func (v *Connection) Close() error {
  368. if v == nil {
  369. return ErrClosedConnection
  370. }
  371. v.OnDataInput()
  372. v.OnDataOutput()
  373. state := v.State()
  374. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  375. return ErrClosedConnection
  376. }
  377. newError("closing connection to ", v.meta.RemoteAddr).WriteToLog()
  378. if state == StateActive {
  379. v.SetState(StateReadyToClose)
  380. }
  381. if state == StatePeerClosed {
  382. v.SetState(StateTerminating)
  383. }
  384. if state == StatePeerTerminating {
  385. v.SetState(StateTerminated)
  386. }
  387. return nil
  388. }
  389. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  390. func (v *Connection) LocalAddr() net.Addr {
  391. if v == nil {
  392. return nil
  393. }
  394. return v.meta.LocalAddr
  395. }
  396. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  397. func (v *Connection) RemoteAddr() net.Addr {
  398. if v == nil {
  399. return nil
  400. }
  401. return v.meta.RemoteAddr
  402. }
  403. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  404. func (v *Connection) SetDeadline(t time.Time) error {
  405. if err := v.SetReadDeadline(t); err != nil {
  406. return err
  407. }
  408. if err := v.SetWriteDeadline(t); err != nil {
  409. return err
  410. }
  411. return nil
  412. }
  413. // SetReadDeadline implements the Conn SetReadDeadline method.
  414. func (v *Connection) SetReadDeadline(t time.Time) error {
  415. if v == nil || v.State() != StateActive {
  416. return ErrClosedConnection
  417. }
  418. v.rd = t
  419. return nil
  420. }
  421. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  422. func (v *Connection) SetWriteDeadline(t time.Time) error {
  423. if v == nil || v.State() != StateActive {
  424. return ErrClosedConnection
  425. }
  426. v.wd = t
  427. return nil
  428. }
  429. // kcp update, input loop
  430. func (v *Connection) updateTask() {
  431. v.flush()
  432. }
  433. func (v *Connection) Terminate() {
  434. if v == nil {
  435. return
  436. }
  437. newError("terminating connection to ", v.RemoteAddr()).WriteToLog()
  438. //v.SetState(StateTerminated)
  439. v.OnDataInput()
  440. v.OnDataOutput()
  441. v.closer.Close()
  442. v.sendingWorker.Release()
  443. v.receivingWorker.Release()
  444. }
  445. func (v *Connection) HandleOption(opt SegmentOption) {
  446. if (opt & SegmentOptionClose) == SegmentOptionClose {
  447. v.OnPeerClosed()
  448. }
  449. }
  450. func (v *Connection) OnPeerClosed() {
  451. state := v.State()
  452. if state == StateReadyToClose {
  453. v.SetState(StateTerminating)
  454. }
  455. if state == StateActive {
  456. v.SetState(StatePeerClosed)
  457. }
  458. }
  459. // Input when you received a low level packet (eg. UDP packet), call it
  460. func (v *Connection) Input(segments []Segment) {
  461. current := v.Elapsed()
  462. atomic.StoreUint32(&v.lastIncomingTime, current)
  463. for _, seg := range segments {
  464. if seg.Conversation() != v.meta.Conversation {
  465. break
  466. }
  467. switch seg := seg.(type) {
  468. case *DataSegment:
  469. v.HandleOption(seg.Option)
  470. v.receivingWorker.ProcessSegment(seg)
  471. if v.receivingWorker.IsDataAvailable() {
  472. v.OnDataInput()
  473. }
  474. v.dataUpdater.WakeUp()
  475. case *AckSegment:
  476. v.HandleOption(seg.Option)
  477. v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
  478. v.OnDataOutput()
  479. v.dataUpdater.WakeUp()
  480. case *CmdOnlySegment:
  481. v.HandleOption(seg.Option)
  482. if seg.Command() == CommandTerminate {
  483. state := v.State()
  484. if state == StateActive ||
  485. state == StatePeerClosed {
  486. v.SetState(StatePeerTerminating)
  487. } else if state == StateReadyToClose {
  488. v.SetState(StateTerminating)
  489. } else if state == StateTerminating {
  490. v.SetState(StateTerminated)
  491. }
  492. }
  493. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  494. v.OnDataInput()
  495. v.OnDataOutput()
  496. }
  497. v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  498. v.receivingWorker.ProcessSendingNext(seg.SendingNext)
  499. v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  500. seg.Release()
  501. default:
  502. }
  503. }
  504. }
  505. func (v *Connection) flush() {
  506. current := v.Elapsed()
  507. if v.State() == StateTerminated {
  508. return
  509. }
  510. if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
  511. v.Close()
  512. }
  513. if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
  514. v.SetState(StateTerminating)
  515. }
  516. if v.State() == StateTerminating {
  517. newError("#", v.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog()
  518. v.Ping(current, CommandTerminate)
  519. if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
  520. v.SetState(StateTerminated)
  521. }
  522. return
  523. }
  524. if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
  525. v.SetState(StateTerminating)
  526. }
  527. if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
  528. v.SetState(StateTerminating)
  529. }
  530. // flush acknowledges
  531. v.receivingWorker.Flush(current)
  532. v.sendingWorker.Flush(current)
  533. if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
  534. v.Ping(current, CommandPing)
  535. }
  536. }
  537. func (v *Connection) State() State {
  538. return State(atomic.LoadInt32((*int32)(&v.state)))
  539. }
  540. func (v *Connection) Ping(current uint32, cmd Command) {
  541. seg := NewCmdOnlySegment()
  542. seg.Conv = v.meta.Conversation
  543. seg.Cmd = cmd
  544. seg.ReceivinNext = v.receivingWorker.NextNumber()
  545. seg.SendingNext = v.sendingWorker.FirstUnacknowledged()
  546. seg.PeerRTO = v.roundTrip.Timeout()
  547. if v.State() == StateReadyToClose {
  548. seg.Option = SegmentOptionClose
  549. }
  550. v.output.Write(seg)
  551. atomic.StoreUint32(&v.lastPingTime, current)
  552. seg.Release()
  553. }