connection.go 14 KB

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