connection.go 14 KB

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