connection.go 14 KB

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