connection.go 14 KB

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