connection.go 14 KB

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