connection.go 14 KB

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