connection.go 12 KB

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