connection.go 13 KB

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