connection.go 13 KB

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