connection.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package kcp
  2. import (
  3. "io"
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "v2ray.com/core/common/errors"
  9. "v2ray.com/core/common/log"
  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 time.Duration
  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: 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. type SystemConnection interface {
  135. net.Conn
  136. Id() internal.ConnectionID
  137. Reset(func([]Segment))
  138. Overhead() int
  139. }
  140. // Connection is a KCP connection over UDP.
  141. type Connection struct {
  142. conn SystemConnection
  143. connRecycler internal.ConnectionRecyler
  144. rd time.Time
  145. wd time.Time // write deadline
  146. since int64
  147. dataInput chan bool
  148. dataOutput chan bool
  149. Config *Config
  150. conv uint16
  151. state State
  152. stateBeginTime uint32
  153. lastIncomingTime uint32
  154. lastPingTime uint32
  155. mss uint32
  156. roundTrip *RoundTripInfo
  157. receivingWorker *ReceivingWorker
  158. sendingWorker *SendingWorker
  159. output SegmentWriter
  160. dataUpdater *Updater
  161. pingUpdater *Updater
  162. reusable bool
  163. }
  164. // NewConnection create a new KCP connection between local and remote.
  165. func NewConnection(conv uint16, sysConn SystemConnection, recycler internal.ConnectionRecyler, config *Config) *Connection {
  166. log.Info("KCP|Connection: creating connection ", conv)
  167. conn := &Connection{
  168. conv: conv,
  169. conn: sysConn,
  170. connRecycler: recycler,
  171. since: nowMillisec(),
  172. dataInput: make(chan bool, 1),
  173. dataOutput: make(chan bool, 1),
  174. Config: config,
  175. output: NewSegmentWriter(sysConn),
  176. mss: config.GetMTUValue() - uint32(sysConn.Overhead()) - DataSegmentOverhead,
  177. roundTrip: &RoundTripInfo{
  178. rto: 100,
  179. minRtt: config.GetTTIValue(),
  180. },
  181. }
  182. sysConn.Reset(conn.Input)
  183. conn.receivingWorker = NewReceivingWorker(conn)
  184. conn.sendingWorker = NewSendingWorker(conn)
  185. isTerminating := func() bool {
  186. return conn.State().Is(StateTerminating, StateTerminated)
  187. }
  188. isTerminated := func() bool {
  189. return conn.State() == StateTerminated
  190. }
  191. conn.dataUpdater = NewUpdater(
  192. config.GetTTIValue(),
  193. predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
  194. isTerminating,
  195. conn.updateTask)
  196. conn.pingUpdater = NewUpdater(
  197. 5000, // 5 seconds
  198. predicate.Not(isTerminated),
  199. isTerminated,
  200. conn.updateTask)
  201. conn.pingUpdater.WakeUp()
  202. return conn
  203. }
  204. func (v *Connection) Elapsed() uint32 {
  205. return uint32(nowMillisec() - v.since)
  206. }
  207. func (v *Connection) OnDataInput() {
  208. select {
  209. case v.dataInput <- true:
  210. default:
  211. }
  212. }
  213. func (v *Connection) OnDataOutput() {
  214. select {
  215. case v.dataOutput <- true:
  216. default:
  217. }
  218. }
  219. // Read implements the Conn Read method.
  220. func (v *Connection) Read(b []byte) (int, error) {
  221. if v == nil {
  222. return 0, io.EOF
  223. }
  224. for {
  225. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  226. return 0, io.EOF
  227. }
  228. nBytes := v.receivingWorker.Read(b)
  229. if nBytes > 0 {
  230. return nBytes, nil
  231. }
  232. if v.State() == StatePeerTerminating {
  233. return 0, io.EOF
  234. }
  235. duration := time.Minute
  236. if !v.rd.IsZero() {
  237. duration = v.rd.Sub(time.Now())
  238. if duration < 0 {
  239. return 0, ErrIOTimeout
  240. }
  241. }
  242. select {
  243. case <-v.dataInput:
  244. case <-time.After(duration):
  245. if !v.rd.IsZero() && v.rd.Before(time.Now()) {
  246. return 0, ErrIOTimeout
  247. }
  248. }
  249. }
  250. }
  251. // Write implements the Conn Write method.
  252. func (v *Connection) Write(b []byte) (int, error) {
  253. totalWritten := 0
  254. for {
  255. if v == nil || v.State() != StateActive {
  256. return totalWritten, io.ErrClosedPipe
  257. }
  258. nBytes := v.sendingWorker.Push(b[totalWritten:])
  259. v.dataUpdater.WakeUp()
  260. if nBytes > 0 {
  261. totalWritten += nBytes
  262. if totalWritten == len(b) {
  263. return totalWritten, nil
  264. }
  265. }
  266. duration := time.Minute
  267. if !v.wd.IsZero() {
  268. duration = v.wd.Sub(time.Now())
  269. if duration < 0 {
  270. return totalWritten, ErrIOTimeout
  271. }
  272. }
  273. select {
  274. case <-v.dataOutput:
  275. case <-time.After(duration):
  276. if !v.wd.IsZero() && v.wd.Before(time.Now()) {
  277. return totalWritten, ErrIOTimeout
  278. }
  279. }
  280. }
  281. }
  282. func (v *Connection) SetState(state State) {
  283. current := v.Elapsed()
  284. atomic.StoreInt32((*int32)(&v.state), int32(state))
  285. atomic.StoreUint32(&v.stateBeginTime, current)
  286. log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current)
  287. switch state {
  288. case StateReadyToClose:
  289. v.receivingWorker.CloseRead()
  290. case StatePeerClosed:
  291. v.sendingWorker.CloseWrite()
  292. case StateTerminating:
  293. v.receivingWorker.CloseRead()
  294. v.sendingWorker.CloseWrite()
  295. v.pingUpdater.interval = time.Second
  296. case StatePeerTerminating:
  297. v.sendingWorker.CloseWrite()
  298. v.pingUpdater.interval = time.Second
  299. case StateTerminated:
  300. v.receivingWorker.CloseRead()
  301. v.sendingWorker.CloseWrite()
  302. v.pingUpdater.interval = time.Second
  303. v.dataUpdater.WakeUp()
  304. v.pingUpdater.WakeUp()
  305. go v.Terminate()
  306. }
  307. }
  308. // Close closes the connection.
  309. func (v *Connection) Close() error {
  310. if v == nil {
  311. return ErrClosedConnection
  312. }
  313. v.OnDataInput()
  314. v.OnDataOutput()
  315. state := v.State()
  316. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  317. return ErrClosedConnection
  318. }
  319. log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr())
  320. if state == StateActive {
  321. v.SetState(StateReadyToClose)
  322. }
  323. if state == StatePeerClosed {
  324. v.SetState(StateTerminating)
  325. }
  326. if state == StatePeerTerminating {
  327. v.SetState(StateTerminated)
  328. }
  329. return nil
  330. }
  331. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  332. func (v *Connection) LocalAddr() net.Addr {
  333. if v == nil {
  334. return nil
  335. }
  336. return v.conn.LocalAddr()
  337. }
  338. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  339. func (v *Connection) RemoteAddr() net.Addr {
  340. if v == nil {
  341. return nil
  342. }
  343. return v.conn.RemoteAddr()
  344. }
  345. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  346. func (v *Connection) SetDeadline(t time.Time) error {
  347. if err := v.SetReadDeadline(t); err != nil {
  348. return err
  349. }
  350. if err := v.SetWriteDeadline(t); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. // SetReadDeadline implements the Conn SetReadDeadline method.
  356. func (v *Connection) SetReadDeadline(t time.Time) error {
  357. if v == nil || v.State() != StateActive {
  358. return ErrClosedConnection
  359. }
  360. v.rd = t
  361. return nil
  362. }
  363. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  364. func (v *Connection) SetWriteDeadline(t time.Time) error {
  365. if v == nil || v.State() != StateActive {
  366. return ErrClosedConnection
  367. }
  368. v.wd = t
  369. return nil
  370. }
  371. // kcp update, input loop
  372. func (v *Connection) updateTask() {
  373. v.flush()
  374. }
  375. func (v *Connection) Reusable() bool {
  376. return v.Config.IsConnectionReuse() && v.reusable
  377. }
  378. func (v *Connection) SetReusable(b bool) {
  379. v.reusable = b
  380. }
  381. func (v *Connection) Terminate() {
  382. if v == nil {
  383. return
  384. }
  385. log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr())
  386. //v.SetState(StateTerminated)
  387. v.OnDataInput()
  388. v.OnDataOutput()
  389. if v.Config.IsConnectionReuse() && v.reusable {
  390. v.connRecycler.Put(v.conn.Id(), v.conn)
  391. } else {
  392. v.conn.Close()
  393. }
  394. v.sendingWorker.Release()
  395. v.receivingWorker.Release()
  396. }
  397. func (v *Connection) HandleOption(opt SegmentOption) {
  398. if (opt & SegmentOptionClose) == SegmentOptionClose {
  399. v.OnPeerClosed()
  400. }
  401. }
  402. func (v *Connection) OnPeerClosed() {
  403. state := v.State()
  404. if state == StateReadyToClose {
  405. v.SetState(StateTerminating)
  406. }
  407. if state == StateActive {
  408. v.SetState(StatePeerClosed)
  409. }
  410. }
  411. // Input when you received a low level packet (eg. UDP packet), call it
  412. func (v *Connection) Input(segments []Segment) {
  413. current := v.Elapsed()
  414. atomic.StoreUint32(&v.lastIncomingTime, current)
  415. for _, seg := range segments {
  416. if seg.Conversation() != v.conv {
  417. break
  418. }
  419. switch seg := seg.(type) {
  420. case *DataSegment:
  421. v.HandleOption(seg.Option)
  422. v.receivingWorker.ProcessSegment(seg)
  423. if seg.Number == v.receivingWorker.nextNumber {
  424. v.OnDataInput()
  425. }
  426. v.dataUpdater.WakeUp()
  427. case *AckSegment:
  428. v.HandleOption(seg.Option)
  429. v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
  430. v.OnDataOutput()
  431. v.dataUpdater.WakeUp()
  432. case *CmdOnlySegment:
  433. v.HandleOption(seg.Option)
  434. if seg.Command() == CommandTerminate {
  435. state := v.State()
  436. if state == StateActive ||
  437. state == StatePeerClosed {
  438. v.SetState(StatePeerTerminating)
  439. } else if state == StateReadyToClose {
  440. v.SetState(StateTerminating)
  441. } else if state == StateTerminating {
  442. v.SetState(StateTerminated)
  443. }
  444. }
  445. if seg.Option == SegmentOptionClose || seg.Command() == CommandTerminate {
  446. v.OnDataInput()
  447. v.OnDataOutput()
  448. }
  449. v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  450. v.receivingWorker.ProcessSendingNext(seg.SendingNext)
  451. v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  452. seg.Release()
  453. default:
  454. }
  455. }
  456. }
  457. func (v *Connection) flush() {
  458. current := v.Elapsed()
  459. if v.State() == StateTerminated {
  460. return
  461. }
  462. if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
  463. v.Close()
  464. }
  465. if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
  466. v.SetState(StateTerminating)
  467. }
  468. if v.State() == StateTerminating {
  469. log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.")
  470. v.Ping(current, CommandTerminate)
  471. if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
  472. v.SetState(StateTerminated)
  473. }
  474. return
  475. }
  476. if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
  477. v.SetState(StateTerminating)
  478. }
  479. if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
  480. v.SetState(StateTerminating)
  481. }
  482. // flush acknowledges
  483. v.receivingWorker.Flush(current)
  484. v.sendingWorker.Flush(current)
  485. if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
  486. v.Ping(current, CommandPing)
  487. }
  488. }
  489. func (v *Connection) State() State {
  490. return State(atomic.LoadInt32((*int32)(&v.state)))
  491. }
  492. func (v *Connection) Ping(current uint32, cmd Command) {
  493. seg := NewCmdOnlySegment()
  494. seg.Conv = v.conv
  495. seg.Cmd = cmd
  496. seg.ReceivinNext = v.receivingWorker.nextNumber
  497. seg.SendingNext = v.sendingWorker.firstUnacknowledged
  498. seg.PeerRTO = v.roundTrip.Timeout()
  499. if v.State() == StateReadyToClose {
  500. seg.Option = SegmentOptionClose
  501. }
  502. v.output.Write(seg)
  503. atomic.StoreUint32(&v.lastPingTime, current)
  504. seg.Release()
  505. }