connection.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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/errors"
  10. "v2ray.com/core/common/predicate"
  11. "v2ray.com/core/transport/internet/internal"
  12. )
  13. var (
  14. ErrIOTimeout = errors.New("Read/Write timeout")
  15. ErrClosedListener = errors.New("Listener closed.")
  16. ErrClosedConnection = errors.New("Connection closed.")
  17. )
  18. type State int32
  19. func (v State) Is(states ...State) bool {
  20. for _, state := range states {
  21. if v == state {
  22. return true
  23. }
  24. }
  25. return false
  26. }
  27. const (
  28. StateActive State = 0
  29. StateReadyToClose State = 1
  30. StatePeerClosed State = 2
  31. StateTerminating State = 3
  32. StatePeerTerminating State = 4
  33. StateTerminated State = 5
  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 (v *RoundTripInfo) UpdatePeerRTO(rto uint32, current uint32) {
  48. v.Lock()
  49. defer v.Unlock()
  50. if current-v.updatedTimestamp < 3000 {
  51. return
  52. }
  53. v.updatedTimestamp = current
  54. v.rto = rto
  55. }
  56. func (v *RoundTripInfo) Update(rtt uint32, current uint32) {
  57. if rtt > 0x7FFFFFFF {
  58. return
  59. }
  60. v.Lock()
  61. defer v.Unlock()
  62. // https://tools.ietf.org/html/rfc6298
  63. if v.srtt == 0 {
  64. v.srtt = rtt
  65. v.variation = rtt / 2
  66. } else {
  67. delta := rtt - v.srtt
  68. if v.srtt > rtt {
  69. delta = v.srtt - rtt
  70. }
  71. v.variation = (3*v.variation + delta) / 4
  72. v.srtt = (7*v.srtt + rtt) / 8
  73. if v.srtt < v.minRtt {
  74. v.srtt = v.minRtt
  75. }
  76. }
  77. var rto uint32
  78. if v.minRtt < 4*v.variation {
  79. rto = v.srtt + 4*v.variation
  80. } else {
  81. rto = v.srtt + v.variation
  82. }
  83. if rto > 10000 {
  84. rto = 10000
  85. }
  86. v.rto = rto * 5 / 4
  87. v.updatedTimestamp = current
  88. }
  89. func (v *RoundTripInfo) Timeout() uint32 {
  90. v.RLock()
  91. defer v.RUnlock()
  92. return v.rto
  93. }
  94. func (v *RoundTripInfo) SmoothedTime() uint32 {
  95. v.RLock()
  96. defer v.RUnlock()
  97. return v.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 (v *Updater) WakeUp() {
  118. select {
  119. case v.notifier <- true:
  120. default:
  121. }
  122. }
  123. func (v *Updater) Run() {
  124. for <-v.notifier {
  125. if v.shouldTerminate() {
  126. return
  127. }
  128. for v.shouldContinue() {
  129. v.updateFunc()
  130. time.Sleep(v.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. Id() internal.ConnectionID
  143. Reset(func([]Segment))
  144. Overhead() int
  145. }
  146. // Connection is a KCP connection over UDP.
  147. type Connection struct {
  148. conn SystemConnection
  149. connRecycler internal.ConnectionRecyler
  150. rd time.Time
  151. wd time.Time // write deadline
  152. since int64
  153. dataInput chan bool
  154. dataOutput chan bool
  155. Config *Config
  156. conv uint16
  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. reusable bool
  169. }
  170. // NewConnection create a new KCP connection between local and remote.
  171. func NewConnection(conv uint16, sysConn SystemConnection, recycler internal.ConnectionRecyler, config *Config) *Connection {
  172. log.Info("KCP|Connection: creating connection ", conv)
  173. conn := &Connection{
  174. conv: conv,
  175. conn: sysConn,
  176. connRecycler: recycler,
  177. since: nowMillisec(),
  178. dataInput: make(chan bool, 1),
  179. dataOutput: make(chan bool, 1),
  180. Config: config,
  181. output: 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. // Read implements the Conn Read method.
  226. func (v *Connection) Read(b []byte) (int, error) {
  227. if v == nil {
  228. return 0, io.EOF
  229. }
  230. for {
  231. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  232. return 0, io.EOF
  233. }
  234. nBytes := v.receivingWorker.Read(b)
  235. if nBytes > 0 {
  236. return nBytes, nil
  237. }
  238. if v.State() == StatePeerTerminating {
  239. return 0, 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 0, 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 0, ErrIOTimeout
  253. }
  254. }
  255. }
  256. }
  257. // Write implements the Conn Write method.
  258. func (v *Connection) Write(b []byte) (int, error) {
  259. totalWritten := 0
  260. for {
  261. if v == nil || v.State() != StateActive {
  262. return totalWritten, io.ErrClosedPipe
  263. }
  264. nBytes := v.sendingWorker.Push(b[totalWritten:])
  265. v.dataUpdater.WakeUp()
  266. if nBytes > 0 {
  267. totalWritten += nBytes
  268. if totalWritten == len(b) {
  269. return totalWritten, nil
  270. }
  271. }
  272. duration := time.Minute
  273. if !v.wd.IsZero() {
  274. duration = v.wd.Sub(time.Now())
  275. if duration < 0 {
  276. return totalWritten, ErrIOTimeout
  277. }
  278. }
  279. select {
  280. case <-v.dataOutput:
  281. case <-time.After(duration):
  282. if !v.wd.IsZero() && v.wd.Before(time.Now()) {
  283. return totalWritten, ErrIOTimeout
  284. }
  285. }
  286. }
  287. }
  288. func (v *Connection) SetState(state State) {
  289. current := v.Elapsed()
  290. atomic.StoreInt32((*int32)(&v.state), int32(state))
  291. atomic.StoreUint32(&v.stateBeginTime, current)
  292. log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current)
  293. switch state {
  294. case StateReadyToClose:
  295. v.receivingWorker.CloseRead()
  296. case StatePeerClosed:
  297. v.sendingWorker.CloseWrite()
  298. case StateTerminating:
  299. v.receivingWorker.CloseRead()
  300. v.sendingWorker.CloseWrite()
  301. v.pingUpdater.SetInterval(time.Second)
  302. case StatePeerTerminating:
  303. v.sendingWorker.CloseWrite()
  304. v.pingUpdater.SetInterval(time.Second)
  305. case StateTerminated:
  306. v.receivingWorker.CloseRead()
  307. v.sendingWorker.CloseWrite()
  308. v.pingUpdater.SetInterval(time.Second)
  309. v.dataUpdater.WakeUp()
  310. v.pingUpdater.WakeUp()
  311. go v.Terminate()
  312. }
  313. }
  314. // Close closes the connection.
  315. func (v *Connection) Close() error {
  316. if v == nil {
  317. return ErrClosedConnection
  318. }
  319. v.OnDataInput()
  320. v.OnDataOutput()
  321. state := v.State()
  322. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  323. return ErrClosedConnection
  324. }
  325. log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr())
  326. if state == StateActive {
  327. v.SetState(StateReadyToClose)
  328. }
  329. if state == StatePeerClosed {
  330. v.SetState(StateTerminating)
  331. }
  332. if state == StatePeerTerminating {
  333. v.SetState(StateTerminated)
  334. }
  335. return nil
  336. }
  337. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  338. func (v *Connection) LocalAddr() net.Addr {
  339. if v == nil {
  340. return nil
  341. }
  342. return v.conn.LocalAddr()
  343. }
  344. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  345. func (v *Connection) RemoteAddr() net.Addr {
  346. if v == nil {
  347. return nil
  348. }
  349. return v.conn.RemoteAddr()
  350. }
  351. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  352. func (v *Connection) SetDeadline(t time.Time) error {
  353. if err := v.SetReadDeadline(t); err != nil {
  354. return err
  355. }
  356. if err := v.SetWriteDeadline(t); err != nil {
  357. return err
  358. }
  359. return nil
  360. }
  361. // SetReadDeadline implements the Conn SetReadDeadline method.
  362. func (v *Connection) SetReadDeadline(t time.Time) error {
  363. if v == nil || v.State() != StateActive {
  364. return ErrClosedConnection
  365. }
  366. v.rd = t
  367. return nil
  368. }
  369. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  370. func (v *Connection) SetWriteDeadline(t time.Time) error {
  371. if v == nil || v.State() != StateActive {
  372. return ErrClosedConnection
  373. }
  374. v.wd = t
  375. return nil
  376. }
  377. // kcp update, input loop
  378. func (v *Connection) updateTask() {
  379. v.flush()
  380. }
  381. func (v *Connection) Reusable() bool {
  382. return v.Config.IsConnectionReuse() && v.reusable
  383. }
  384. func (v *Connection) SetReusable(b bool) {
  385. v.reusable = b
  386. }
  387. func (v *Connection) Terminate() {
  388. if v == nil {
  389. return
  390. }
  391. log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr())
  392. //v.SetState(StateTerminated)
  393. v.OnDataInput()
  394. v.OnDataOutput()
  395. if v.Config.IsConnectionReuse() && v.reusable {
  396. v.connRecycler.Put(v.conn.Id(), v.conn)
  397. } else {
  398. v.conn.Close()
  399. }
  400. v.sendingWorker.Release()
  401. v.receivingWorker.Release()
  402. }
  403. func (v *Connection) HandleOption(opt SegmentOption) {
  404. if (opt & SegmentOptionClose) == SegmentOptionClose {
  405. v.OnPeerClosed()
  406. }
  407. }
  408. func (v *Connection) OnPeerClosed() {
  409. state := v.State()
  410. if state == StateReadyToClose {
  411. v.SetState(StateTerminating)
  412. }
  413. if state == StateActive {
  414. v.SetState(StatePeerClosed)
  415. }
  416. }
  417. // Input when you received a low level packet (eg. UDP packet), call it
  418. func (v *Connection) Input(segments []Segment) {
  419. current := v.Elapsed()
  420. atomic.StoreUint32(&v.lastIncomingTime, current)
  421. for _, seg := range segments {
  422. if seg.Conversation() != v.conv {
  423. break
  424. }
  425. switch seg := seg.(type) {
  426. case *DataSegment:
  427. v.HandleOption(seg.Option)
  428. v.receivingWorker.ProcessSegment(seg)
  429. if v.receivingWorker.IsDataAvailable() {
  430. v.OnDataInput()
  431. }
  432. v.dataUpdater.WakeUp()
  433. case *AckSegment:
  434. v.HandleOption(seg.Option)
  435. v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
  436. v.OnDataOutput()
  437. v.dataUpdater.WakeUp()
  438. case *CmdOnlySegment:
  439. v.HandleOption(seg.Option)
  440. if seg.Command() == CommandTerminate {
  441. state := v.State()
  442. if state == StateActive ||
  443. state == StatePeerClosed {
  444. v.SetState(StatePeerTerminating)
  445. } else if state == StateReadyToClose {
  446. v.SetState(StateTerminating)
  447. } else if state == StateTerminating {
  448. v.SetState(StateTerminated)
  449. }
  450. }
  451. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  452. v.OnDataInput()
  453. v.OnDataOutput()
  454. }
  455. v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  456. v.receivingWorker.ProcessSendingNext(seg.SendingNext)
  457. v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  458. seg.Release()
  459. default:
  460. }
  461. }
  462. }
  463. func (v *Connection) flush() {
  464. current := v.Elapsed()
  465. if v.State() == StateTerminated {
  466. return
  467. }
  468. if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
  469. v.Close()
  470. }
  471. if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
  472. v.SetState(StateTerminating)
  473. }
  474. if v.State() == StateTerminating {
  475. log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.")
  476. v.Ping(current, CommandTerminate)
  477. if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
  478. v.SetState(StateTerminated)
  479. }
  480. return
  481. }
  482. if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
  483. v.SetState(StateTerminating)
  484. }
  485. if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
  486. v.SetState(StateTerminating)
  487. }
  488. // flush acknowledges
  489. v.receivingWorker.Flush(current)
  490. v.sendingWorker.Flush(current)
  491. if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
  492. v.Ping(current, CommandPing)
  493. }
  494. }
  495. func (v *Connection) State() State {
  496. return State(atomic.LoadInt32((*int32)(&v.state)))
  497. }
  498. func (v *Connection) Ping(current uint32, cmd Command) {
  499. seg := NewCmdOnlySegment()
  500. seg.Conv = v.conv
  501. seg.Cmd = cmd
  502. seg.ReceivinNext = v.receivingWorker.NextNumber()
  503. seg.SendingNext = v.sendingWorker.FirstUnacknowledged()
  504. seg.PeerRTO = v.roundTrip.Timeout()
  505. if v.State() == StateReadyToClose {
  506. seg.Option = SegmentOptionClose
  507. }
  508. v.output.Write(seg)
  509. atomic.StoreUint32(&v.lastPingTime, current)
  510. seg.Release()
  511. }