connection.go 13 KB

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