connection.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. dataInput chan bool
  153. dataOutput chan bool
  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. dataInput: make(chan bool, 1),
  178. dataOutput: make(chan bool, 1),
  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. func (v *Connection) OnDataInput() {
  213. select {
  214. case v.dataInput <- true:
  215. default:
  216. }
  217. }
  218. func (v *Connection) OnDataOutput() {
  219. select {
  220. case v.dataOutput <- true:
  221. default:
  222. }
  223. }
  224. // Read implements the Conn Read method.
  225. func (v *Connection) Read(b []byte) (int, error) {
  226. if v == nil {
  227. return 0, io.EOF
  228. }
  229. for {
  230. if v.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  231. return 0, io.EOF
  232. }
  233. nBytes := v.receivingWorker.Read(b)
  234. if nBytes > 0 {
  235. return nBytes, nil
  236. }
  237. if v.State() == StatePeerTerminating {
  238. return 0, io.EOF
  239. }
  240. duration := time.Duration(time.Minute)
  241. if !v.rd.IsZero() {
  242. duration = v.rd.Sub(time.Now())
  243. if duration < 0 {
  244. return 0, ErrIOTimeout
  245. }
  246. }
  247. select {
  248. case <-v.dataInput:
  249. case <-time.After(duration):
  250. if !v.rd.IsZero() && v.rd.Before(time.Now()) {
  251. return 0, ErrIOTimeout
  252. }
  253. }
  254. }
  255. }
  256. // Write implements the Conn Write method.
  257. func (v *Connection) Write(b []byte) (int, error) {
  258. totalWritten := 0
  259. for {
  260. if v == nil || v.State() != StateActive {
  261. return totalWritten, io.ErrClosedPipe
  262. }
  263. nBytes := v.sendingWorker.Push(b[totalWritten:])
  264. v.dataUpdater.WakeUp()
  265. if nBytes > 0 {
  266. totalWritten += nBytes
  267. if totalWritten == len(b) {
  268. return totalWritten, nil
  269. }
  270. }
  271. duration := time.Duration(time.Minute)
  272. if !v.rd.IsZero() {
  273. duration = v.wd.Sub(time.Now())
  274. if duration < 0 {
  275. return totalWritten, ErrIOTimeout
  276. }
  277. }
  278. select {
  279. case <-v.dataOutput:
  280. case <-time.After(duration):
  281. if !v.wd.IsZero() && v.wd.Before(time.Now()) {
  282. return totalWritten, ErrIOTimeout
  283. }
  284. }
  285. }
  286. }
  287. func (v *Connection) SetState(state State) {
  288. current := v.Elapsed()
  289. atomic.StoreInt32((*int32)(&v.state), int32(state))
  290. atomic.StoreUint32(&v.stateBeginTime, current)
  291. log.Debug("KCP|Connection: #", v.conv, " entering state ", state, " at ", current)
  292. switch state {
  293. case StateReadyToClose:
  294. v.receivingWorker.CloseRead()
  295. case StatePeerClosed:
  296. v.sendingWorker.CloseWrite()
  297. case StateTerminating:
  298. v.receivingWorker.CloseRead()
  299. v.sendingWorker.CloseWrite()
  300. v.pingUpdater.interval = time.Second
  301. case StatePeerTerminating:
  302. v.sendingWorker.CloseWrite()
  303. v.pingUpdater.interval = time.Second
  304. case StateTerminated:
  305. v.receivingWorker.CloseRead()
  306. v.sendingWorker.CloseWrite()
  307. v.pingUpdater.interval = time.Second
  308. v.dataUpdater.WakeUp()
  309. v.pingUpdater.WakeUp()
  310. go v.Terminate()
  311. }
  312. }
  313. // Close closes the connection.
  314. func (v *Connection) Close() error {
  315. if v == nil {
  316. return ErrClosedConnection
  317. }
  318. v.OnDataInput()
  319. v.OnDataOutput()
  320. state := v.State()
  321. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  322. return ErrClosedConnection
  323. }
  324. log.Info("KCP|Connection: Closing connection to ", v.conn.RemoteAddr())
  325. if state == StateActive {
  326. v.SetState(StateReadyToClose)
  327. }
  328. if state == StatePeerClosed {
  329. v.SetState(StateTerminating)
  330. }
  331. if state == StatePeerTerminating {
  332. v.SetState(StateTerminated)
  333. }
  334. return nil
  335. }
  336. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  337. func (v *Connection) LocalAddr() net.Addr {
  338. if v == nil {
  339. return nil
  340. }
  341. return v.conn.LocalAddr()
  342. }
  343. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  344. func (v *Connection) RemoteAddr() net.Addr {
  345. if v == nil {
  346. return nil
  347. }
  348. return v.conn.RemoteAddr()
  349. }
  350. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  351. func (v *Connection) SetDeadline(t time.Time) error {
  352. if err := v.SetReadDeadline(t); err != nil {
  353. return err
  354. }
  355. if err := v.SetWriteDeadline(t); err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // SetReadDeadline implements the Conn SetReadDeadline method.
  361. func (v *Connection) SetReadDeadline(t time.Time) error {
  362. if v == nil || v.State() != StateActive {
  363. return ErrClosedConnection
  364. }
  365. v.rd = t
  366. return nil
  367. }
  368. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  369. func (v *Connection) SetWriteDeadline(t time.Time) error {
  370. if v == nil || v.State() != StateActive {
  371. return ErrClosedConnection
  372. }
  373. v.wd = t
  374. return nil
  375. }
  376. // kcp update, input loop
  377. func (v *Connection) updateTask() {
  378. v.flush()
  379. }
  380. func (v *Connection) Reusable() bool {
  381. return v.Config.ConnectionReuse.IsEnabled() && v.reusable
  382. }
  383. func (v *Connection) SetReusable(b bool) {
  384. v.reusable = b
  385. }
  386. func (v *Connection) Terminate() {
  387. if v == nil {
  388. return
  389. }
  390. log.Info("KCP|Connection: Terminating connection to ", v.RemoteAddr())
  391. //v.SetState(StateTerminated)
  392. v.OnDataInput()
  393. v.OnDataOutput()
  394. if v.Config.ConnectionReuse.IsEnabled() && v.reusable {
  395. v.connRecycler.Put(v.conn.Id(), v.conn)
  396. } else {
  397. v.conn.Close()
  398. }
  399. v.sendingWorker.Release()
  400. v.receivingWorker.Release()
  401. }
  402. func (v *Connection) HandleOption(opt SegmentOption) {
  403. if (opt & SegmentOptionClose) == SegmentOptionClose {
  404. v.OnPeerClosed()
  405. }
  406. }
  407. func (v *Connection) OnPeerClosed() {
  408. state := v.State()
  409. if state == StateReadyToClose {
  410. v.SetState(StateTerminating)
  411. }
  412. if state == StateActive {
  413. v.SetState(StatePeerClosed)
  414. }
  415. }
  416. // Input when you received a low level packet (eg. UDP packet), call it
  417. func (v *Connection) Input(segments []Segment) {
  418. current := v.Elapsed()
  419. atomic.StoreUint32(&v.lastIncomingTime, current)
  420. for _, seg := range segments {
  421. if seg.Conversation() != v.conv {
  422. break
  423. }
  424. switch seg := seg.(type) {
  425. case *DataSegment:
  426. v.HandleOption(seg.Option)
  427. v.receivingWorker.ProcessSegment(seg)
  428. if seg.Number == v.receivingWorker.nextNumber {
  429. v.OnDataInput()
  430. }
  431. v.dataUpdater.WakeUp()
  432. case *AckSegment:
  433. v.HandleOption(seg.Option)
  434. v.sendingWorker.ProcessSegment(current, seg, v.roundTrip.Timeout())
  435. v.OnDataOutput()
  436. v.dataUpdater.WakeUp()
  437. case *CmdOnlySegment:
  438. v.HandleOption(seg.Option)
  439. if seg.Command() == CommandTerminate {
  440. state := v.State()
  441. if state == StateActive ||
  442. state == StatePeerClosed {
  443. v.SetState(StatePeerTerminating)
  444. } else if state == StateReadyToClose {
  445. v.SetState(StateTerminating)
  446. } else if state == StateTerminating {
  447. v.SetState(StateTerminated)
  448. }
  449. }
  450. v.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  451. v.receivingWorker.ProcessSendingNext(seg.SendingNext)
  452. v.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  453. seg.Release()
  454. default:
  455. }
  456. }
  457. }
  458. func (v *Connection) flush() {
  459. current := v.Elapsed()
  460. if v.State() == StateTerminated {
  461. return
  462. }
  463. if v.State() == StateActive && current-atomic.LoadUint32(&v.lastIncomingTime) >= 30000 {
  464. v.Close()
  465. }
  466. if v.State() == StateReadyToClose && v.sendingWorker.IsEmpty() {
  467. v.SetState(StateTerminating)
  468. }
  469. if v.State() == StateTerminating {
  470. log.Debug("KCP|Connection: #", v.conv, " sending terminating cmd.")
  471. v.Ping(current, CommandTerminate)
  472. v.output.Flush()
  473. if current-atomic.LoadUint32(&v.stateBeginTime) > 8000 {
  474. v.SetState(StateTerminated)
  475. }
  476. return
  477. }
  478. if v.State() == StatePeerTerminating && current-atomic.LoadUint32(&v.stateBeginTime) > 4000 {
  479. v.SetState(StateTerminating)
  480. }
  481. if v.State() == StateReadyToClose && current-atomic.LoadUint32(&v.stateBeginTime) > 15000 {
  482. v.SetState(StateTerminating)
  483. }
  484. // flush acknowledges
  485. v.receivingWorker.Flush(current)
  486. v.sendingWorker.Flush(current)
  487. if current-atomic.LoadUint32(&v.lastPingTime) >= 3000 {
  488. v.Ping(current, CommandPing)
  489. }
  490. // flash remain segments
  491. v.output.Flush()
  492. }
  493. func (v *Connection) State() State {
  494. return State(atomic.LoadInt32((*int32)(&v.state)))
  495. }
  496. func (v *Connection) Ping(current uint32, cmd Command) {
  497. seg := NewCmdOnlySegment()
  498. seg.Conv = v.conv
  499. seg.Cmd = cmd
  500. seg.ReceivinNext = v.receivingWorker.nextNumber
  501. seg.SendingNext = v.sendingWorker.firstUnacknowledged
  502. seg.PeerRTO = v.roundTrip.Timeout()
  503. if v.State() == StateReadyToClose {
  504. seg.Option = SegmentOptionClose
  505. }
  506. v.output.Write(seg)
  507. atomic.StoreUint32(&v.lastPingTime, current)
  508. seg.Release()
  509. }